From 830fcc5757bc958ee71882d7a96fc5beb1fd9c59 Mon Sep 17 00:00:00 2001 From: Leon Date: Sat, 19 Jul 2025 10:46:43 +0200 Subject: [PATCH] fix: don't require secret if auth disabled --- backend/app/core/auth.py | 10 ++++++++++ backend/app/core/config.py | 5 +++-- backend/app/routers/auth.py | 12 +++++++++--- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/backend/app/core/auth.py b/backend/app/core/auth.py index 92ea079..89a2c9b 100644 --- a/backend/app/core/auth.py +++ b/backend/app/core/auth.py @@ -46,6 +46,8 @@ def _get_auth_credentials(db: Session) -> dict: def create_access_token(data: dict, expires_delta: timedelta | None = None): """Create a new access token.""" + if not env_settings.secret_key: + raise ValueError("SECRET_KEY is not set, cannot create access tokens.") to_encode = data.copy() if expires_delta: expire = datetime.now(UTC) + expires_delta @@ -81,6 +83,14 @@ def protected_route( detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) + + if not env_settings.secret_key: + # This is an internal server error because auth is configured but the key is missing. + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="SECRET_KEY is not configured on the server.", + ) + try: payload = jwt.decode( token, env_settings.secret_key, algorithms=[env_settings.algorithm] diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 4ac49c3..f2437df 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -29,8 +29,9 @@ class Settings(BaseSettings): auto_add_new_senders: bool = False auth_username: str | None = None auth_password: str | None = None - secret_key: str = Field( - ..., validation_alias=AliasChoices("SECRET_KEY", "LETTERFEED_SECRET_KEY") + secret_key: str | None = Field( + default=None, + validation_alias=AliasChoices("SECRET_KEY", "LETTERFEED_SECRET_KEY"), ) algorithm: str = "HS256" access_token_expire_minutes: int = 30 diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py index 1195552..829e846 100644 --- a/backend/app/routers/auth.py +++ b/backend/app/routers/auth.py @@ -49,7 +49,13 @@ def login_for_access_token( ) access_token_expires = timedelta(minutes=settings.access_token_expire_minutes) - access_token = create_access_token( - data={"sub": form_data.username}, expires_delta=access_token_expires - ) + try: + access_token = create_access_token( + data={"sub": form_data.username}, expires_delta=access_token_expires + ) + except ValueError as e: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=str(e), + ) return {"access_token": access_token, "token_type": "bearer"}