Files
planet/backend/app/core/config.py
T
linkong e53c3af355
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release / images (push) Canceled after 0s
release / client_release (push) Canceled after 0s
release: bump version to 0.79.0
2026-11-24 15:40:10 +08:00

186 lines
5.9 KiB
Python

from functools import lru_cache
import os
from pathlib import Path
from typing import List, Optional
from urllib.parse import quote, urlsplit, urlunsplit
from pydantic_settings import BaseSettings
ROOT_DIR = Path(__file__).parent.parent.parent.parent
VERSION_FILE = ROOT_DIR / "VERSION"
WEAK_SECRET_PLACEHOLDERS = frozenset(
{
"",
"change-me",
"change_me",
"change_me_to_a_random_secret",
"change_me_to_a_random_32_plus_char_secret",
"your-secret-key-change-in-production",
"replace-with-strong-32-char-random-secret",
}
)
WEAK_SERVICE_TOKEN_PLACEHOLDERS = frozenset(
{
"",
"change-me",
"change_me",
"replace-with-internal-token",
}
)
VALID_PLANET_ROLES = frozenset({"all", "api", "worker"})
class Settings(BaseSettings):
PROJECT_NAME: str = "Intelligent Planet Plan"
VERSION: str = (
os.getenv("APP_VERSION")
or (VERSION_FILE.read_text(encoding="utf-8").strip() if VERSION_FILE.exists() else "0.19.0")
)
APP_ENV: str = "development"
PLANET_ROLE: str = "all"
ENABLE_SCHEDULER: Optional[bool] = None
API_V1_STR: str = "/api/v1"
SECRET_KEY: str = "your-secret-key-change-in-production"
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
SEED_DEFAULT_DEV_USERS: Optional[bool] = None
INITIAL_ADMIN_USERNAME: str = ""
INITIAL_ADMIN_EMAIL: str = ""
INITIAL_ADMIN_PASSWORD: str = ""
SETTINGS_ENCRYPTION_KEY: str = ""
LOGIN_RATE_LIMIT_MAX_ATTEMPTS: int = 10
LOGIN_RATE_LIMIT_WINDOW_SECONDS: int = 300
POSTGRES_SERVER: str = "localhost"
POSTGRES_USER: str = "postgres"
POSTGRES_PASSWORD: str = "postgres"
POSTGRES_DB: str = "planet_db"
DATABASE_URL: str = "postgresql+asyncpg://postgres:postgres@localhost:5432/planet_db"
REDIS_SERVER: str = "localhost"
REDIS_PORT: int = 6379
REDIS_DB: int = 0
REDIS_PASSWORD: str = ""
CORS_ORIGINS: List[str] = [
"http://localhost:3000",
"http://127.0.0.1:3000",
"http://localhost:8000",
"http://127.0.0.1:8000",
"planet://earth",
]
COLLECTOR_MAX_CONCURRENCY: int = 2
COLLECTOR_HEAVY_CONCURRENCY: int = 1
SPACETRACK_USERNAME: str = ""
SPACETRACK_PASSWORD: str = ""
AI_PROVIDER_SERVICE_URL: str = "http://localhost:8010"
AI_PROVIDER_SERVICE_TOKEN: str = ""
AI_PROVIDER_TIMEOUT_SECONDS: int = 60
AI_PROVIDER_RETRY_ATTEMPTS: int = 2
OBSERVABILITY_INGEST_TOKEN: str = ""
CLIENT_UPDATES_DIR: str = ""
CLIENT_UPDATE_PUBLISH_TOKEN: str = ""
CLIENT_MIN_SHELL_VERSION: str = "0.78.0"
CLIENT_RELEASE_PAGE_URL: str = "https://gitea.rclaw.top/linkong/planet/releases"
@property
def is_production(self) -> bool:
return str(self.APP_ENV or "").strip().lower() == "production"
@property
def normalized_role(self) -> str:
role = str(self.PLANET_ROLE or "all").strip().lower()
return role if role in VALID_PLANET_ROLES else "all"
@property
def should_run_scheduler(self) -> bool:
if self.ENABLE_SCHEDULER is not None:
return bool(self.ENABLE_SCHEDULER)
return self.normalized_role in {"all", "worker"}
@property
def should_run_workers(self) -> bool:
return self.normalized_role in {"all", "worker"}
@property
def should_seed_default_dev_users(self) -> bool:
if self.SEED_DEFAULT_DEV_USERS is not None:
return bool(self.SEED_DEFAULT_DEV_USERS)
return not self.is_production
@property
def REDIS_URL(self) -> str:
raw = os.getenv(
"REDIS_URL",
f"redis://{self.REDIS_SERVER}:{self.REDIS_PORT}/{self.REDIS_DB}",
)
password = str(self.REDIS_PASSWORD or "")
if password:
parsed = urlsplit(raw)
if parsed.scheme in {"redis", "rediss"} and parsed.password is None and parsed.hostname:
user_part = parsed.username or ""
encoded_pw = quote(password, safe="")
netloc = f"{user_part}:{encoded_pw}@{parsed.hostname}"
if parsed.port:
netloc = f"{netloc}:{parsed.port}"
return urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment))
return raw
class Config:
env_file = Path(__file__).parent.parent.parent / ".env"
case_sensitive = True
extra = "ignore"
def validate_production_security(cfg: Settings) -> None:
"""Fail fast on insecure defaults when APP_ENV=production."""
raw_role = str(cfg.PLANET_ROLE or "all").strip().lower()
if raw_role not in VALID_PLANET_ROLES:
raise RuntimeError(
f"Invalid PLANET_ROLE={cfg.PLANET_ROLE!r}; expected one of {sorted(VALID_PLANET_ROLES)}"
)
if not cfg.is_production:
return
errors: list[str] = []
secret_key = str(cfg.SECRET_KEY or "").strip()
if secret_key in WEAK_SECRET_PLACEHOLDERS or len(secret_key) < 32:
errors.append("SECRET_KEY must be set to a random string of at least 32 characters")
if int(cfg.ACCESS_TOKEN_EXPIRE_MINUTES) <= 0:
errors.append("ACCESS_TOKEN_EXPIRE_MINUTES must be > 0 in production")
if int(cfg.REFRESH_TOKEN_EXPIRE_DAYS) <= 0:
errors.append("REFRESH_TOKEN_EXPIRE_DAYS must be > 0 in production")
if "*" in (cfg.CORS_ORIGINS or []):
errors.append("CORS_ORIGINS must not contain '*' in production")
ai_url = str(cfg.AI_PROVIDER_SERVICE_URL or "").strip()
ai_token = str(cfg.AI_PROVIDER_SERVICE_TOKEN or "").strip()
if ai_url and ai_token in WEAK_SERVICE_TOKEN_PLACEHOLDERS:
errors.append(
"AI_PROVIDER_SERVICE_TOKEN must be configured (not empty or placeholder) in production"
)
if errors:
raise RuntimeError("Production security validation failed: " + "; ".join(errors))
@lru_cache()
def get_settings() -> Settings:
return Settings()
settings = get_settings()