Security Middleware
- class smarter.apps.llm_client.middleware.security.SmarterSecurityMiddleware(get_response)[source]
Bases:
SecurityMiddleware,SmarterHelperMixinThis middleware overrides Django’s built-in
SecurityMiddlewareto provide custom host validation logic for the Smarter platform.Key Features:
Custom Host Validation: Instead of relying solely on Django’s
ALLOWED_HOSTS, this middleware introducessmarter_settings.allowed_hosts. It checks incoming requests against both the traditional allowed hosts and a dynamic list of domains associated with deployed LLMClients.LLMClient Domain Support: If the request’s host matches a domain for a deployed LLMClient, the request is allowed to pass through. This enables flexible multi-tenant deployments where each LLMClient can have its own domain.
Friendly Error Handling: The middleware suppresses Django’s default
DisallowedHostexception. Instead, it returns aHttpResponseBadRequest(400) response, which is not logged and is more user-friendly for clients.Health Check Short-Circuiting: Requests from internal IP addresses or for health/readiness endpoints are allowed to pass through without further validation. This ensures that infrastructure health checks do not get blocked by host validation.
Logging: Uses a custom logger that respects feature flags (waffle switches) for granular control over middleware and llm_client logging.
Request Validation Steps:
Internal IPs: Requests from internal IP addresses (e.g., load balancer health checks) are allowed.
Local Hosts: Requests from local hosts (e.g.,
localhost,127.0.0.1) are allowed.Health/Readiness URLs: Requests to health or readiness endpoints are allowed.
Allowed Hosts: Requests matching any pattern in
smarter_settings.allowed_hostsare allowed.LLMClient Domains: Requests where the host matches a deployed LLMClient’s domain are allowed.
Fallback: All other requests are rejected with a
400 Bad Requestresponse.
Example Usage:
MIDDLEWARE = [ ... 'smarter.apps.llm_client.middleware.security.SmarterSecurityMiddleware', ... ]