Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /TrueSelph_jvspatial /jvspatial /api /config_groups.py
| """Configuration groups for jvspatial Server. | |
| This module provides logical configuration groups that compose into ServerConfig, | |
| improving organization and maintainability. | |
| """ | |
| from typing import Dict, List, Optional | |
| from pydantic import BaseModel, ConfigDict, Field, model_validator | |
| from jvspatial.env import resolve_file_storage_root | |
| from jvspatial.runtime.serverless import is_serverless_mode | |
| _DEFAULT_ROLE_MAPPING: Dict[str, List[str]] = {"admin": ["*"], "user": []} | |
| class DatabaseConfig(BaseModel): | |
| """Database configuration group.""" | |
| # Aliased fields below are settable only by their alias unless the model | |
| # opts in here, so callers passing them by field name -- including | |
| # ``server_config_overrides_from_env`` -- were silently ignored. | |
| model_config = ConfigDict(populate_by_name=True) | |
| db_type: Optional[str] = None | |
| db_path: Optional[str] = None | |
| db_path_resolve: Optional[str] = Field( | |
| default=None, | |
| description="When set to 'app', resolve relative db_path against the directory " | |
| "of the module that instantiated Server. Use when cwd varies (e.g. running from " | |
| "project root vs backend dir).", | |
| ) | |
| db_connection_string: Optional[str] = None | |
| db_database_name: Optional[str] = None | |
| # DynamoDB Configuration (only used if db_type is "dynamodb") | |
| dynamodb_table_name: Optional[str] = Field( | |
| default=None, validation_alias="JVSPATIAL_DYNAMODB_TABLE_NAME" | |
| ) | |
| dynamodb_region: Optional[str] = Field( | |
| default=None, validation_alias="JVSPATIAL_DYNAMODB_REGION" | |
| ) | |
| dynamodb_endpoint_url: Optional[str] = Field( | |
| default=None, validation_alias="JVSPATIAL_DYNAMODB_ENDPOINT_URL" | |
| ) | |
| dynamodb_access_key_id: Optional[str] = Field( | |
| default=None, validation_alias="AWS_ACCESS_KEY_ID" | |
| ) | |
| dynamodb_secret_access_key: Optional[str] = Field( | |
| default=None, validation_alias="AWS_SECRET_ACCESS_KEY" | |
| ) | |
| # PostgreSQL Configuration (only used if db_type is "postgres"/"postgresql"). | |
| # Unset values fall through to PostgresDB's own env defaults. | |
| postgres_dsn: Optional[str] = Field( | |
| default=None, validation_alias="JVSPATIAL_POSTGRES_DSN" | |
| ) | |
| postgres_min_pool_size: Optional[int] = Field( | |
| default=None, validation_alias="JVSPATIAL_POSTGRES_MIN_POOL_SIZE" | |
| ) | |
| postgres_max_pool_size: Optional[int] = Field( | |
| default=None, validation_alias="JVSPATIAL_POSTGRES_MAX_POOL_SIZE" | |
| ) | |
| postgres_pooler_mode: Optional[str] = Field( | |
| default=None, | |
| validation_alias="JVSPATIAL_POSTGRES_POOLER_MODE", | |
| description="'session' (default) or 'transaction' for PgBouncer / RDS Proxy.", | |
| ) | |
| class SecurityConfig(BaseModel): | |
| """Security configuration group.""" | |
| security_headers_enabled: bool = Field( | |
| default=True, | |
| description="Add security headers (X-Content-Type-Options, X-Frame-Options, CSP, etc.) to responses", | |
| ) | |
| hsts_enabled: bool = Field( | |
| default=False, | |
| description="Add Strict-Transport-Security header (enable in production behind TLS)", | |
| ) | |
| class CORSConfig(BaseModel): | |
| """CORS configuration group.""" | |
| cors_enabled: bool = True | |
| cors_origins: List[str] = Field( | |
| default_factory=lambda: [ | |
| "http://localhost:5173", | |
| "http://127.0.0.1:5173", | |
| "http://localhost:3000", | |
| "http://127.0.0.1:3000", | |
| "http://localhost:8000", | |
| "http://127.0.0.1:8000", | |
| ] | |
| ) | |
| cors_methods: List[str] = Field( | |
| default_factory=lambda: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] | |
| ) | |
| cors_headers: List[str] = Field( | |
| default_factory=lambda: ["Content-Type", "Authorization", "X-API-Key"] | |
| ) | |
| # Set to ``True`` to silence the startup warning that fires when | |
| # ``cors_origins`` contains a wildcard. Default opt-in is loud so | |
| # accidental wildcards in production surface as logs (audit §4.12 / | |
| # SPEC §15.4). | |
| cors_allow_wildcard: bool = False | |
| def _warn_on_wildcard_origin(self) -> "CORSConfig": | |
| """Emit a startup warning when CORS origins include a wildcard. | |
| SPEC §15.4: "Wildcard origins must be set explicitly and trigger | |
| a startup warning." Browsers reject ``allow_origins=["*"]`` when | |
| ``allow_credentials=True`` at runtime, but the surprise factor | |
| of a permissive wildcard left in by mistake warrants a loud | |
| warning here too (audit §4.12). | |
| """ | |
| import logging | |
| if not self.cors_enabled: | |
| return self | |
| wildcards = [o for o in self.cors_origins if o.strip() == "*" or "*" in o] | |
| if wildcards and not self.cors_allow_wildcard: | |
| logging.getLogger(__name__).warning( | |
| "CORSConfig: wildcard origins detected: %s. This permits " | |
| "any origin and is rarely correct in production. Set " | |
| "cors_allow_wildcard=True on CORSConfig to silence this " | |
| "warning.", | |
| wildcards, | |
| ) | |
| return self | |
| class AuthConfig(BaseModel): | |
| """Authentication configuration group. | |
| Authentication behavior: | |
| - enabled/auth_enabled: Master switch for authentication middleware. When True: | |
| """ | |
| model_config = ConfigDict(populate_by_name=True) | |
| # Master switch (accept auth_enabled for backward compat) | |
| enabled: bool = Field( | |
| default=False, | |
| description="Enable authentication middleware (JWT + API key)", | |
| validation_alias="auth_enabled", | |
| ) | |
| # Test mode: when True, honors request.state.user set by test fixtures for | |
| # in-process ASGI testing (e.g. TestClient with ASGITransport) | |
| test_mode: bool = Field( | |
| default=False, | |
| description="When True, use request.state.user if set (for testing). " | |
| "See docs Request State Contract.", | |
| ) | |
| # API key management endpoint control | |
| api_key_management_enabled: bool = Field( | |
| default=True, | |
| description="Enable API key management endpoints (/auth/api-keys). " | |
| "Does not affect API key authentication availability.", | |
| ) | |
| # JWT Configuration (use empty default; must be set explicitly when auth enabled) | |
| jwt_secret: str = Field( | |
| default="", | |
| description="JWT secret key. MUST be set via JVSPATIAL_JWT_SECRET_KEY when auth is enabled.", | |
| ) | |
| jwt_algorithm: str = Field(default="HS256", description="JWT algorithm") | |
| jwt_expire_minutes: int = Field( | |
| default=30, description="JWT expiration time in minutes" | |
| ) | |
| refresh_expire_days: int = Field( | |
| default=7, description="Refresh token expiration time in days" | |
| ) | |
| refresh_token_rotation: bool = Field( | |
| default=False, description="Enable refresh token rotation on refresh" | |
| ) | |
| blacklist_cache_ttl_seconds: int = Field( | |
| default=3600, description="Cache TTL for blacklist checks in seconds" | |
| ) | |
| password_reset_token_expiry_minutes: int = Field( | |
| default=60, | |
| description="Password reset token expiry in minutes", | |
| ) | |
| password_change_enabled: bool = Field( | |
| default=True, | |
| description="Enable /auth/change-password endpoint", | |
| ) | |
| password_reset_enabled: bool = Field( | |
| default=True, | |
| description="Enable /auth/forgot-password and /auth/reset-password endpoints", | |
| ) | |
| password_reset_base_url: Optional[str] = Field( | |
| default=None, | |
| description="Base URL for reset links, e.g. https://app.example.com", | |
| ) | |
| # API Key Configuration | |
| api_key_header: str = Field( | |
| default="x-api-key", description="Header name for API key" | |
| ) | |
| api_key_min_length: int = Field(default=32, description="Minimum API key length") | |
| api_key_prefix: str = Field( | |
| default="sk_", description="Key prefix (e.g., sk_live_, sk_test_)" | |
| ) | |
| # Session Configuration (cookie names; session auth not implemented) | |
| session_cookie_name: str = Field( | |
| default="session", description="Session cookie name" | |
| ) | |
| session_expire_minutes: int = Field( | |
| default=60, description="Session expiration time in minutes" | |
| ) | |
| # RBAC Configuration | |
| rbac_enabled: bool = Field( | |
| default=True, | |
| description="Enable role and permission enforcement", | |
| ) | |
| default_role: str = Field( | |
| default="user", | |
| description="Role for new users (non-bootstrap)", | |
| ) | |
| admin_role: str = Field( | |
| default="admin", | |
| description="Role name for bootstrap and admin-only checks", | |
| ) | |
| registration_open: bool = Field( | |
| default=True, | |
| description="When False, disable public register even when no users", | |
| ) | |
| role_permission_mapping: Dict[str, List[str]] = Field( | |
| default_factory=lambda: dict(_DEFAULT_ROLE_MAPPING), | |
| description="Maps each role to its permissions. Use '*' for admin-all.", | |
| ) | |
| # Bootstrap admin (create first admin from env on startup when set) | |
| bootstrap_admin_email: Optional[str] = Field( | |
| default=None, | |
| description="Admin email for bootstrap. When set with bootstrap_admin_password, " | |
| "creates an admin user on startup if none exists. Typically from ADMIN_EMAIL env.", | |
| ) | |
| bootstrap_admin_password: Optional[str] = Field( | |
| default=None, | |
| description="Admin password for bootstrap. Min 6 chars. Typically from ADMIN_PASSWORD env.", | |
| ) | |
| bootstrap_admin_name: Optional[str] = Field( | |
| default=None, | |
| description="Admin display name for bootstrap. Defaults to email. Typically from ADMIN_NAME env.", | |
| ) | |
| # Authentication Exempt Paths (accept auth_exempt_paths for backward compat) | |
| # Use prefix-relative paths only; PathMatcher expands to {APIRoutes.PREFIX}/auth/... | |
| # at runtime so any prefix (e.g. /api, /v1) works without hardcoding. | |
| exempt_paths: List[str] = Field( | |
| default_factory=lambda: [ | |
| "/", | |
| "/health", | |
| "/docs", | |
| "/redoc", | |
| "/openapi.json", | |
| "/favicon.ico", | |
| "/auth/register", | |
| "/auth/login", | |
| "/auth/logout", | |
| "/auth/refresh", | |
| "/auth/forgot-password", | |
| "/auth/reset-password", | |
| "/_internal/deferred", | |
| "/_internal/retention", | |
| ], | |
| validation_alias="auth_exempt_paths", | |
| ) | |
| # --- OAuth 2.1 service (opt-in; see api/auth/oauth/). All off/empty by | |
| # default so existing apps are unaffected. --- | |
| oauth_enabled: bool = Field( | |
| default=False, description="Enable the OAuth 2.1 authorization server" | |
| ) | |
| oauth_issuer_url: str = Field( | |
| default="", | |
| description="OAuth issuer URL (https origin) for token iss + metadata", | |
| ) | |
| oauth_prefix: str = Field( | |
| default="/oauth", description="Route prefix for OAuth endpoints" | |
| ) | |
| oauth_supported_scopes: List[str] = Field( | |
| default_factory=list, | |
| description="Advertised OAuth scopes (RBAC permission strings)", | |
| ) | |
| oauth_dcr_enabled: bool = Field( | |
| default=True, description="Enable Dynamic Client Registration (RFC 7591)" | |
| ) | |
| oauth_access_token_ttl_minutes: int = Field( | |
| default=60, description="OAuth access token lifetime (minutes)" | |
| ) | |
| oauth_code_ttl_seconds: int = Field( | |
| default=300, description="Authorization code lifetime (seconds)" | |
| ) | |
| accept_oauth_bearer: bool = Field( | |
| default=False, | |
| description="Resource-server: accept OAuth access tokens on auth=True endpoints", | |
| ) | |
| oauth_dcr_rate_limit_per_minute: int = Field( | |
| default=12, | |
| description=( | |
| "Maximum DCR (/oauth/register) requests per minute per client IP when " | |
| "oauth_enabled. Protects against open-registration DB-fill / resource-" | |
| "exhaustion DoS (security review I-1). Set to 0 to disable the override " | |
| "(leaves the endpoint subject to the server-wide rate limit, if any)." | |
| ), | |
| ) | |
| oauth_authorize_login_redirect: str = Field( | |
| default="", | |
| description=( | |
| "When set and an unauthenticated browser hits GET /oauth/authorize, " | |
| "302-redirect to this SPA URL with the original OAuth query string appended " | |
| "(e.g. https://app.example.com/oauth/authorize). Empty = legacy 401." | |
| ), | |
| ) | |
| # Backward compatibility: allow access via auth_enabled/auth_exempt_paths | |
| def auth_enabled(self) -> bool: | |
| """Return whether authentication is enabled (alias for enabled).""" | |
| return self.enabled | |
| def auth_exempt_paths(self) -> List[str]: | |
| """Return paths exempt from authentication (alias for exempt_paths).""" | |
| return self.exempt_paths | |
| class RateLimitConfig(BaseModel): | |
| """Rate limiting configuration group.""" | |
| rate_limit_enabled: bool = Field( | |
| default=False, description="Enable rate limiting middleware" | |
| ) | |
| rate_limit_default_requests: int = Field( | |
| default=60, description="Default requests per window" | |
| ) | |
| rate_limit_default_window: int = Field( | |
| default=60, description="Default time window in seconds" | |
| ) | |
| rate_limit_overrides: Dict[str, Dict[str, int]] = Field( | |
| default_factory=dict, | |
| description="Per-endpoint rate limit overrides: {path: {requests: N, window: M}}", | |
| ) | |
| class FileStorageConfig(BaseModel): | |
| """File storage configuration group.""" | |
| file_storage_enabled: bool = Field(default=False) | |
| file_storage_provider: str = Field(default="local") # "local" or "s3" | |
| file_storage_root: str = Field( | |
| default_factory=lambda: "/tmp/.files" if is_serverless_mode() else "./.files", | |
| ) | |
| file_storage_base_url: str = Field(default="http://localhost:8000") | |
| file_storage_max_size: int = Field(default=100 * 1024 * 1024) # 100MB default | |
| # S3 Configuration (only used if provider is "s3") | |
| s3_bucket_name: Optional[str] = Field(default=None) | |
| s3_region: Optional[str] = Field(default=None) | |
| s3_access_key: Optional[str] = Field(default=None) | |
| s3_secret_key: Optional[str] = Field(default=None) | |
| s3_endpoint_url: Optional[str] = Field(default=None) | |
| def _unify_file_storage_root_with_jvagent(self) -> "FileStorageConfig": | |
| """Apply :func:`jvspatial.env.resolve_file_storage_root` (env + merged fallback).""" | |
| object.__setattr__( | |
| self, | |
| "file_storage_root", | |
| resolve_file_storage_root(self.file_storage_root), | |
| ) | |
| return self | |
| class WebhookConfig(BaseModel): | |
| """Webhook configuration group.""" | |
| webhook_api_key_header: str = Field( | |
| default="x-api-key", | |
| description="Header name for webhook API key authentication", | |
| ) | |
| webhook_api_key_query_param: str = Field( | |
| default="api_key", | |
| description="Query parameter name for webhook API key authentication", | |
| ) | |
| webhook_api_key_require_https: bool = Field( | |
| default=True, description="Require HTTPS for query parameter authentication" | |
| ) | |
| webhook_https_required: bool = Field( | |
| default=True, | |
| description="Require HTTPS for webhook endpoints (general requirement)", | |
| ) | |
| class ProxyConfig(BaseModel): | |
| """URL proxy configuration group.""" | |
| proxy_enabled: bool = Field(default=False) | |
| proxy_default_expiration: int = Field(default=3600) # 1 hour | |
| proxy_max_expiration: int = Field(default=86400) # 24 hours | |
| class RetentionConfig(BaseModel): | |
| """Garbage-collection settings for framework transient Objects.""" | |
| retention_enabled: bool = Field( | |
| default=True, | |
| description="Enable scheduled and manual retention runs", | |
| ) | |
| retention_schedule: str = Field( | |
| default="daily at 02:00", | |
| description="Scheduler spec for periodic retention when scheduler is enabled", | |
| ) | |
| max_deletes_per_entity: int = Field( | |
| default=1000, | |
| ge=1, | |
| description="Maximum rows deleted per entity rule per run", | |
| ) | |
| max_runtime_seconds: int = Field( | |
| default=300, | |
| ge=1, | |
| description="Stop the janitor after this many seconds", | |
| ) | |
| batch_size: int = Field( | |
| default=100, | |
| ge=1, | |
| description="Records fetched per database round trip", | |
| ) | |
| password_reset_used_grace_hours: int = Field( | |
| default=24, | |
| ge=0, | |
| description="Hours to keep used password-reset tokens before deletion", | |
| ) | |
| log_retention_days: Optional[int] = Field( | |
| default=None, | |
| description="Reserved: DBLog retention (not implemented in v1)", | |
| ) | |
| retention_invoke_disabled: bool = Field( | |
| default=False, | |
| description="When True, do not register POST /_internal/retention", | |
| ) | |
| __all__ = [ | |
| "DatabaseConfig", | |
| "SecurityConfig", | |
| "CORSConfig", | |
| "AuthConfig", | |
| "RateLimitConfig", | |
| "FileStorageConfig", | |
| "WebhookConfig", | |
| "ProxyConfig", | |
| "RetentionConfig", | |
| ] | |
Xet Storage Details
- Size:
- 17.1 kB
- Xet hash:
- f550305a88a8e5d94d2081cc2551067c2850880078ca231bde6dccc7671c6068
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.