11"""Configuration settings for the FastAPI application."""
22
3- from functools import lru_cache
4- from typing import Any , Dict
3+ import os
4+ from typing import Any , Dict , Optional
55
66from pydantic import Field , field_validator
77from pydantic_settings import BaseSettings , SettingsConfigDict
@@ -16,6 +16,11 @@ class Settings(BaseSettings):
1616 default = 3000 ,
1717 description = "Port for the frontend service" ,
1818 )
19+ api_write_token : str | None = Field (
20+ default = None ,
21+ description = "Bearer token required for write-protected API routes." ,
22+ repr = False ,
23+ )
1924
2025 # Database and integration settings
2126 database_url : str = Field (
@@ -34,6 +39,11 @@ class Settings(BaseSettings):
3439 default = "" ,
3540 description = "Hygraph access token" ,
3641 )
42+ api_write_token : str = Field (
43+ default = "" ,
44+ description = "Bearer token required for privileged write routes" ,
45+ repr = False ,
46+ )
3747 hygraph_webhook_secret : str = Field (
3848 description = (
3949 "Shared secret used to verify Hygraph webhook signatures."
@@ -42,6 +52,14 @@ class Settings(BaseSettings):
4252 min_length = 1 ,
4353 repr = False ,
4454 )
55+ api_write_token : str | None = Field (
56+ default = None ,
57+ description = (
58+ "Bearer token required for privileged API write operations."
59+ " Provide via the API_WRITE_TOKEN environment variable."
60+ ),
61+ repr = False ,
62+ )
4563
4664 model_config = SettingsConfigDict (
4765 env_file = ".env.development" ,
@@ -61,12 +79,31 @@ def _validate_hygraph_webhook_secret(cls, value: str) -> str:
6179 )
6280 return value .strip ()
6381
82+ @field_validator ("api_write_token" )
83+ @classmethod
84+ def _normalize_api_write_token (cls , value : str | None ) -> str | None :
85+ """Normalize optional API write tokens."""
86+
87+ if value is None :
88+ return None
89+ value = value .strip ()
90+ return value or None
91+
92+
93+ _SETTINGS_CACHE : Optional [Settings ] = None
94+ _LAST_SECRET : Optional [str ] = None
95+
6496
65- @lru_cache ()
6697def get_settings () -> Settings :
67- """Return a cached instance of :class:`Settings`."""
98+ """Return a cached instance of :class:`Settings`, refreshing on secret changes ."""
6899
69- return Settings ()
100+ global _SETTINGS_CACHE , _LAST_SECRET
101+ current_secret = os .getenv ("HYGRAPH_WEBHOOK_SECRET" )
102+ if _SETTINGS_CACHE is None or _LAST_SECRET != current_secret :
103+ settings = Settings ()
104+ _SETTINGS_CACHE = settings
105+ _LAST_SECRET = settings .hygraph_webhook_secret
106+ return _SETTINGS_CACHE
70107
71108
72109def get_fastapi_settings () -> Dict [str , Any ]:
0 commit comments