Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
44 changes: 40 additions & 4 deletions core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
})
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved


class AppSettings(BaseModel):
"""Validated, immutable service configuration.
Expand Down Expand Up @@ -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:
Expand Down
19 changes: 15 additions & 4 deletions core/lifespan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))\"."
)

Expand Down
7 changes: 5 additions & 2 deletions pages/admin.html
Original file line number Diff line number Diff line change
Expand Up @@ -480,9 +480,12 @@ <h3 class="card-title" style="font-size:1.15rem;">System status</h3>
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',
Expand Down
1 change: 1 addition & 0 deletions schemas/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion services/admin_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
30 changes: 30 additions & 0 deletions tests/test_backend_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
40 changes: 40 additions & 0 deletions tests/test_backend_foundation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading