Buckets:

download
raw
15.1 kB
"""Nexus Preset System - Pre-configured middleware stacks.
Provides ready-to-use middleware presets that encode best practices into
one-line configurations. Eliminates boilerplate for common patterns.
Usage:
app = Nexus(preset="lightweight") # CORS only
app = Nexus(preset="standard") # CORS + rate limiting + error handling
app = Nexus(preset="saas") # Full SaaS stack
app = Nexus(preset="enterprise") # Enterprise features
"""
import logging
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional
logger = logging.getLogger(__name__)
_SENSITIVE_PATTERNS = {
"secret",
"key",
"token",
"password",
"credential",
"private",
"certificate",
}
@dataclass
class NexusConfig:
"""Unified configuration object passed to preset factories.
SECURITY NOTE: Secrets (jwt_secret, sso_config client_secret, etc.) should
be read from environment variables in plugin factories, NOT stored in this
config in production. This config may be logged or serialized.
"""
# CORS
# SECURITY: credentials=False by default; wildcard origins + credentials=True
# is rejected by browsers and is a misconfiguration. Set explicit origins when
# enabling credentials.
cors_origins: List[str] = field(default_factory=lambda: ["*"])
cors_allow_methods: List[str] = field(default_factory=lambda: ["*"])
cors_allow_headers: List[str] = field(default_factory=lambda: ["*"])
cors_allow_credentials: bool = False
# JWT
jwt_secret: Optional[str] = None
jwt_algorithm: str = "HS256"
jwt_audience: Optional[str] = None
jwt_issuer: Optional[str] = None
# RBAC
rbac_config: Optional[Dict[str, Any]] = None
# Tenant
tenant_header: str = "X-Tenant-ID"
tenant_required: bool = True
# Rate Limiting
rate_limit: Optional[int] = 100
rate_limit_config: Optional[Dict[str, Any]] = None
# Per-request HTTP metrics
# Opt-in per-request HTTP metrics middleware (RequestMetricsMiddleware:
# nexus_http_requests_total + nexus_http_request_duration_seconds, labelled
# by method/route-template/status). Requires prometheus_client AND a
# registered /metrics endpoint (register_metrics_endpoint). Default False
# because prometheus_client is an optional dependency.
metrics_enabled: bool = False
# Security Headers (threaded into the security-headers preset middleware)
# csp: custom Content-Security-Policy string; None keeps SecurityHeadersConfig's
# secure default. security_header_overrides: per-field overrides
# (hsts_max_age, frame_options, referrer_policy, etc.) merged into the
# SecurityHeadersConfig the preset constructs.
csp: Optional[str] = None
security_header_overrides: Optional[Dict[str, Any]] = None
# Audit
audit_enabled: bool = True
audit_log_bodies: bool = False
# SSO
sso_provider: Optional[str] = None
sso_config: Optional[Dict[str, Any]] = None
# Feature Flags
feature_flags_provider: Optional[str] = None
feature_flags_config: Optional[Dict[str, Any]] = None
# Environment
environment: str = "development"
def __repr__(self) -> str:
"""Return string representation with secrets redacted."""
safe_jwt = "[REDACTED]" if self.jwt_secret else None
safe_sso = None
if self.sso_config:
safe_sso = {
k: (
"[REDACTED]"
if any(p in k.lower() for p in _SENSITIVE_PATTERNS)
else v
)
for k, v in self.sso_config.items()
}
return (
f"NexusConfig("
f"cors_origins={self.cors_origins}, "
f"jwt_secret={safe_jwt}, "
f"jwt_algorithm={self.jwt_algorithm!r}, "
f"rate_limit={self.rate_limit}, "
f"sso_provider={self.sso_provider!r}, "
f"sso_config={safe_sso}, "
f"environment={self.environment!r})"
)
@dataclass
class PresetConfig:
"""Configuration for a middleware preset."""
name: str
description: str
middleware_factories: List[Callable[["NexusConfig"], Optional[tuple]]] = field(
default_factory=list
)
plugin_factories: List[Callable[["NexusConfig"], Optional[Any]]] = field(
default_factory=list
)
# =============================================================================
# Middleware Factory Functions
# =============================================================================
def _cors_middleware_factory(config: NexusConfig) -> tuple:
"""Create CORS middleware configuration."""
from starlette.middleware.cors import CORSMiddleware
return (
CORSMiddleware,
{
"allow_origins": config.cors_origins,
"allow_methods": config.cors_allow_methods,
"allow_headers": config.cors_allow_headers,
"allow_credentials": config.cors_allow_credentials,
},
)
def _security_headers_middleware_factory(config: NexusConfig) -> Optional[tuple]:
"""Create security headers middleware configuration.
Threads a consumer-supplied CSP string (``config.csp``) and any per-field
security-header overrides (``config.security_header_overrides``) into the
``SecurityHeadersConfig`` the preset constructs. When neither is set, the
SecurityHeadersConfig secure defaults apply unchanged.
"""
from nexus.middleware.security_headers import (
SecurityHeadersConfig,
SecurityHeadersMiddleware,
)
sec_kwargs: Dict[str, Any] = {
"exclude_paths": ("/healthz", "/readyz", "/startup"),
}
if config.csp is not None:
sec_kwargs["csp"] = config.csp
if config.security_header_overrides:
sec_kwargs.update(config.security_header_overrides)
sec_config = SecurityHeadersConfig(**sec_kwargs)
return (SecurityHeadersMiddleware, {"config": sec_config})
def _csrf_middleware_factory(config: NexusConfig) -> Optional[tuple]:
"""Create CSRF middleware configuration.
Uses the CORS origins as allowed origins for CSRF validation.
Non-browser API clients that omit Origin/Referer are allowed
when cors_origins includes the wildcard "*".
"""
from nexus.middleware.csrf import CSRFMiddleware
# If wildcard origins, allow missing Origin (non-browser clients)
allow_missing = "*" in config.cors_origins
# Use non-wildcard origins for CSRF validation
allowed = [o for o in config.cors_origins if o != "*"]
return (
CSRFMiddleware,
{
"allowed_origins": allowed,
"allow_missing_origin": allow_missing,
"exempt_paths": ["/healthz", "/readyz", "/startup", "/openapi.json"],
},
)
def _rate_limit_middleware_factory(config: NexusConfig) -> Optional[tuple]:
"""Create the token-bucket rate-limit middleware from NexusConfig.
Auto-attaches the built ``RateLimitMiddleware`` (token-bucket + 429 body +
``X-RateLimit-*`` / ``Retry-After`` headers) using ``config.rate_limit`` as
the per-minute limit. ``config.rate_limit_config`` (a dict) supplies any
further ``RateLimitConfig`` fields (burst_size, backend, route_limits, …).
Returns None when rate limiting is disabled (``config.rate_limit is None``).
"""
if config.rate_limit is None:
return None
from nexus.auth import RateLimitConfig, RateLimitMiddleware
rl_kwargs: Dict[str, Any] = {"requests_per_minute": config.rate_limit}
if config.rate_limit_config:
rl_kwargs.update(config.rate_limit_config)
rl_config = RateLimitConfig(**rl_kwargs)
return (RateLimitMiddleware, {"config": rl_config})
def _request_metrics_middleware_factory(config: NexusConfig) -> Optional[tuple]:
"""Create the per-request HTTP metrics middleware when opted-in.
Returns None unless ``config.metrics_enabled`` is True. When enabled,
attaches ``RequestMetricsMiddleware`` (which records
``nexus_http_requests_total`` + ``nexus_http_request_duration_seconds``).
Appended LAST in the standard/saas/enterprise chains so it is the OUTERMOST
middleware (LIFO) and measures total request latency including all others.
"""
if not config.metrics_enabled:
return None
from nexus.middleware.request_metrics import RequestMetricsMiddleware
return (RequestMetricsMiddleware, {})
# NOTE: The exception → canonical-error-envelope contract (the WS02
# "error handler middleware" placeholder formerly stubbed here) ships via the
# HTTP transport's NexusError handler — see
# nexus/transports/http.py::_install_exception_handlers (installs
# app.add_exception_handler(NexusError, ...) producing the canonical
# {"error", "detail"} body). No preset middleware is required for it.
# =============================================================================
# Plugin Factory Functions
# =============================================================================
def _jwt_auth_plugin_factory(config: NexusConfig) -> Optional[Any]:
"""Placeholder: Create JWT auth plugin if configured."""
if not config.jwt_secret:
return None
logger.warning(
"JWT auth plugin not yet implemented. "
"Install with: pip install kailash-nexus[auth] (coming in WS02)"
)
return None
def _rbac_plugin_factory(config: NexusConfig) -> Optional[Any]:
"""Placeholder: Create RBAC plugin if configured."""
if not config.rbac_config:
return None
logger.warning(
"RBAC plugin not yet implemented. "
"Install with: pip install kailash-nexus[auth] (coming in WS02)"
)
return None
def _tenant_isolation_plugin_factory(config: NexusConfig) -> Optional[Any]:
"""Placeholder: Create tenant isolation plugin."""
logger.warning(
"Tenant isolation plugin not yet implemented. "
"Install with: pip install kailash-nexus[auth] (coming in WS02)"
)
return None
def _audit_plugin_factory(config: NexusConfig) -> Optional[Any]:
"""Placeholder: Create audit plugin if enabled."""
if not config.audit_enabled:
return None
logger.warning(
"Audit plugin not yet implemented. "
"Install with: pip install kailash-nexus[auth] (coming in WS02)"
)
return None
def _sso_plugin_factory(config: NexusConfig) -> Optional[Any]:
"""Placeholder: Create SSO plugin if configured."""
if not config.sso_provider:
return None
logger.warning(
"SSO plugin not yet implemented. "
"Install with: pip install kailash-nexus[auth] (coming in WS02)"
)
return None
def _feature_flags_plugin_factory(config: NexusConfig) -> Optional[Any]:
"""Placeholder: Create feature flags plugin if configured."""
if not config.feature_flags_provider:
return None
logger.warning(
"Feature flags plugin not yet implemented. "
"Install with: pip install kailash-nexus[auth] (coming in WS02)"
)
return None
# =============================================================================
# Preset Registry
# =============================================================================
PRESETS: Dict[str, PresetConfig] = {
"none": PresetConfig(
name="none",
description="No middleware - bare Nexus instance",
middleware_factories=[],
plugin_factories=[],
),
"lightweight": PresetConfig(
name="lightweight",
description="CORS + Security Headers - for development and internal tools",
middleware_factories=[
_cors_middleware_factory,
_security_headers_middleware_factory,
],
plugin_factories=[],
),
"standard": PresetConfig(
name="standard",
description="CORS + Security Headers + CSRF + Rate Limiting - for public APIs without auth",
middleware_factories=[
_cors_middleware_factory,
_security_headers_middleware_factory,
_csrf_middleware_factory,
_rate_limit_middleware_factory,
_request_metrics_middleware_factory,
],
plugin_factories=[],
),
"saas": PresetConfig(
name="saas",
description="Full SaaS stack - CORS, Security Headers, CSRF, JWT, RBAC, Rate Limiting, Tenant Isolation, Audit",
middleware_factories=[
_cors_middleware_factory,
_security_headers_middleware_factory,
_csrf_middleware_factory,
_rate_limit_middleware_factory,
_request_metrics_middleware_factory,
],
plugin_factories=[
_jwt_auth_plugin_factory,
_rbac_plugin_factory,
_tenant_isolation_plugin_factory,
_audit_plugin_factory,
],
),
"enterprise": PresetConfig(
name="enterprise",
description="Enterprise stack - Everything in SaaS + SSO + ABAC + Feature Gates",
middleware_factories=[
_cors_middleware_factory,
_security_headers_middleware_factory,
_csrf_middleware_factory,
_rate_limit_middleware_factory,
_request_metrics_middleware_factory,
],
plugin_factories=[
_jwt_auth_plugin_factory,
_rbac_plugin_factory,
_tenant_isolation_plugin_factory,
_audit_plugin_factory,
_sso_plugin_factory,
_feature_flags_plugin_factory,
],
),
}
def get_preset(name: str) -> PresetConfig:
"""Get a preset configuration by name.
Args:
name: Preset name (none, lightweight, standard, saas, enterprise).
Returns:
PresetConfig for the named preset.
Raises:
ValueError: If the preset name is unknown.
"""
if name not in PRESETS:
available = ", ".join(PRESETS.keys())
raise ValueError(f"Unknown preset '{name}'. Available: {available}")
return PRESETS[name]
def apply_preset(app: Any, preset_name: str, config: NexusConfig) -> None:
"""Apply a preset to a Nexus instance.
Args:
app: The Nexus application instance.
preset_name: Name of the preset to apply.
config: NexusConfig with configuration values.
"""
preset = get_preset(preset_name)
logger.info(f"Applying preset '{preset_name}': {preset.description}")
# Apply middleware
for factory in preset.middleware_factories:
result = factory(config)
if result is not None:
middleware_class, kwargs = result
app.add_middleware(middleware_class, **kwargs)
logger.debug(f" Added middleware: {middleware_class.__name__}")
# Apply plugins
for factory in preset.plugin_factories:
plugin = factory(config)
if plugin is not None:
app.add_plugin(plugin)
logger.debug(f" Added plugin: {plugin.name}")
logger.info(f"Preset '{preset_name}' applied successfully")

Xet Storage Details

Size:
15.1 kB
·
Xet hash:
0daa6f3a189be0246b7f1d32f93bc71ce7da4da3f7fa7ace4d14e99d5cdc6bbd

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.