Security Middleware

class smarter.apps.llmclient.middleware.security.SmarterSecurityMiddleware(get_response)[source]

Bases: SecurityMiddleware, SmarterHelperMixin

This middleware overrides Django’s built-in SecurityMiddleware to 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 introduces smarter_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 DisallowedHost exception. Instead, it returns a HttpResponseBadRequest (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 llmclient logging. Urls are logged with mask_url_query(), because a chat’s session key can be in the query string.

Request Validation Steps:

  1. Internal IPs: Requests from internal IP addresses (e.g., load balancer health checks) are allowed.

  2. Local Hosts: Requests from local hosts (e.g., localhost, 127.0.0.1) are allowed.

  3. Health/Readiness URLs: Requests to health or readiness endpoints are allowed.

  4. Allowed Hosts: Requests matching any pattern in smarter_settings.allowed_hosts are allowed.

  5. LLMClient Domains: Requests where the host matches a deployed LLMClient’s domain are allowed.

  6. Fallback: All other requests are rejected with a 400 Bad Request response.

Example Usage:

MIDDLEWARE = [
    ...
    'smarter.apps.llmclient.middleware.security.SmarterSecurityMiddleware',
    ...
]
property formatted_class_name: str

The module and class name, with the instance id, formatted for log messages.

process_request(request)[source]

Allow the request, or reject it with a 400 response if its host is not one Smarter serves.

When the ENABLE_MIDDLEWARE_SECURITY switch is on, a request passes if its path is a health check, its host is an internal IP address or a local host, it is an ACME challenge, its host matches smarter_settings.allowed_hosts, or it resolves to an LLMClient.

Parameters:

request (HttpRequest) – The HTTP request.

Returns:

None to let the request continue, a 400 response for a rejected host, or a 500 response if the request has no host.