"""
Middleware that throttles unauthenticated clients that generate excessive HTTP 404 responses.
This middleware detects repeated invalid URL requests from unauthenticated
clients and temporarily blocks abusive request patterns commonly associated
with automated scanners, vulnerability probes, and broken crawlers.
Key Features
============
- ASGI and WSGI compatible
- Supports sync and async middleware execution
- Per-IP throttling of repeated 404 responses
- Temporary automatic client blocking
- Low-noise sampled logging
- Feature-flag enablement via Django Waffle
- Exemption for authenticated users
Threat Mitigation
=================
This middleware helps mitigate several classes of abusive traffic:
- automated vulnerability scanners
- brute-force endpoint discovery
- malicious URL enumeration
- broken or misconfigured crawlers
- excessive invalid resource probing
Behavior
========
For each response, the middleware:
#. Detects HTTP 404 responses
#. Exempts authenticated users
#. Resolves the client IP address
#. Tracks repeated 404 activity in cache storage
#. Logs sampled probe activity
#. Temporarily blocks abusive clients after threshold exhaustion
When a client exceeds the configured threshold, the middleware returns
``HTTP 403 Forbidden`` responses for the duration of the throttle window.
Throttle Configuration
======================
The middleware uses the following default limits:
- ``THROTTLE_LIMIT`` = 25 requests
- ``THROTTLE_TIMEOUT`` = 600 seconds
- ``LOG_SAMPLE_RATE`` = every 10th event
These values may be overridden at the class level if needed.
Caching
=======
Throttle counters are stored using the application's configured cache
backend.
Each client is tracked independently using cache keys in the format:
.. code-block:: text
excessive_404_throttle:<client_ip>
Authenticated Requests
======================
Authenticated requests are intentionally excluded from throttling to
avoid disrupting legitimate application usage or administrative activity.
Async Compatibility
===================
The middleware supports both synchronous and asynchronous Django
execution models.
Async deployments use ``async_process_response()``, while synchronous
deployments use ``process_response()``.
The middleware automatically detects coroutine-based request handlers
during initialization.
Feature Flags
=============
Middleware activation is controlled using Django Waffle:
- ``ENABLE_MIDDLEWARE_EXCESSIVE_404``
When disabled, the middleware becomes a transparent pass-through.
Logging
=======
The middleware emits structured logs for:
- middleware initialization
- client throttling events
- sampled 404 probe activity
- client IP resolution failures
To reduce log noise during large scanning events, 404 activity is logged
using configurable sampling intervals.
Classes
=======
.. autosummary::
:toctree: generated/
SmarterBlockExcessive404Middleware
Dependencies
============
- Django
- Django Waffle
- asgiref
- application cache backend
Warnings
========
This middleware uses IP-based throttling and may affect multiple users
sharing the same public IP address.
Care should be taken when deploying behind proxies or load balancers to
ensure accurate client IP extraction.
Notes
=====
The middleware depends on helper functionality provided by
:class:`smarter.common.mixins.SmarterMiddlewareMixin`.
Blocking state is temporary and automatically expires after the throttle
timeout period.
"""
from __future__ import annotations
from collections.abc import Awaitable
from functools import cached_property
from http import HTTPStatus
from cache_results import lazy_cache as cache
from django.http import HttpRequest, HttpResponseBase, HttpResponseForbidden
from smarter.common.conf import smarter_settings
from smarter.common.mixins import SmarterHelperMixin, SmarterMiddlewareMixin
from smarter.common.utils import is_authenticated_request
from smarter.lib import logging
from smarter.lib.cache.exceptions import CACHE_EXCEPTIONS
from smarter.lib.django import waffle
from smarter.lib.django.waffle import SmarterWaffleSwitches
logger = logging.getSmarterLogger(__name__, any_switches=[SmarterWaffleSwitches.MIDDLEWARE_LOGGING])
if waffle.switch_is_active(SmarterWaffleSwitches.ENABLE_MIDDLEWARE_EXCESSIVE_404):
logger.debug(
"is %s",
SmarterHelperMixin().formatted_state_ready,
)
else:
logger.debug(
"is %s. Enable with Django waffle in the admin console.",
SmarterHelperMixin().formatted_state_not_ready,
)
[docs]
class SmarterBlockExcessive404Middleware(SmarterMiddlewareMixin):
"""
Middleware that throttles unauthenticated clients producing excessive 404s.
This mitigates:
- automated scanners
- brute-force URL probing
- broken crawlers
- vulnerability enumeration attempts
"""
THROTTLE_LIMIT = 25
THROTTLE_TIMEOUT = 600
LOG_SAMPLE_RATE = 10
# JSON schema lookups, which editors (e.g. smarter-vscode-yaml) send in
# bursts for every manifest kind they encounter, including obsolete ones.
IGNORED_PATH_PREFIXES = (
"/api/v1/cli/schema/",
"/api/v1/cli/json-schema/",
)
def __call__(self, request: HttpRequest) -> HttpResponseBase | Awaitable[HttpResponseBase]:
"""
Count a sync response's 404, or hand the request to :meth:`__acall__` in async mode.
:param request: The incoming request.
:returns: The response, or a ``403`` when the client has exceeded the throttle limit (a
coroutine in async mode).
"""
if self.async_mode:
return self.__acall__(request)
response = super().__call__(request)
# process_response() returns a 403 for a client that has exceeded the limit.
return self.process_response(request, response) # type: ignore
async def __acall__(self, request: HttpRequest) -> HttpResponseBase:
"""
Count an async response's 404, unless ``ENABLE_MIDDLEWARE_EXCESSIVE_404`` is off.
:param request: The incoming request.
:returns: The response, or a ``403`` when the client has exceeded the throttle limit.
"""
if not await waffle.async_switch_is_active(SmarterWaffleSwitches.ENABLE_MIDDLEWARE_EXCESSIVE_404):
return await super().__acall__(request)
response = await super().__acall__(request)
return await self.async_process_response(request, response)
[docs]
async def async_process_response(self, request: HttpRequest, response: HttpResponseBase) -> HttpResponseBase:
"""
Async entry point for ASGI deployments: count anonymous 404s per client ip, and block excessive ones.
Unlike :meth:`process_response`, it does not check the ``ENABLE_MIDDLEWARE_EXCESSIVE_404`` switch.
:param request: The request.
:param response: The response from the view.
:returns: The response, or a 403 response when the client has exceeded the throttle limit.
"""
return self._process_response(request, response)
[docs]
def process_response(self, request: HttpRequest, response: HttpResponseBase) -> HttpResponseBase:
"""
Sync entry point: count anonymous 404s per client ip, and block excessive ones.
It does nothing unless the ``ENABLE_MIDDLEWARE_EXCESSIVE_404`` waffle switch is active.
:param request: The request.
:param response: The response from the view.
:returns: The response, or a 403 response when the client has exceeded the throttle limit.
"""
if not waffle.switch_is_active(SmarterWaffleSwitches.ENABLE_MIDDLEWARE_EXCESSIVE_404):
return response
return self._process_response(request, response)
def _process_response(self, request: HttpRequest, response: HttpResponseBase) -> HttpResponseBase:
"""
Count an anonymous client's 404, and block the client once it reaches ``THROTTLE_LIMIT``.
This is the implementation that the sync and async entry points share. Responses other
than 404, ignored paths, authenticated requests and requests without a client ip are left
alone. Side effect: the client's counter in the cache is incremented.
:param request: The request.
:param response: The response from the view.
:returns: The response, or a ``403`` when the client has exceeded the throttle limit.
"""
if response.status_code != HTTPStatus.NOT_FOUND:
return response
if self.is_ignored_path(request.path):
return response
# Authenticated users are exempt
if is_authenticated_request(request):
return response
client_ip = self.get_client_ip(request)
if not client_ip:
return response
throttle_key = self.get_throttle_key(client_ip)
try:
blocked_count = cache.get(throttle_key, 0)
except CACHE_EXCEPTIONS as e:
# one line, no traceback: Redis being away is an outage to report, not a bug to debug.
# The 404 isn't counted, and no client is blocked, until Redis is back (issue #1091).
logger.warning("the cache failed, not counting the 404 of %s: %s", request.path, e)
return response
self.log_404_event(
request=request,
client_ip=client_ip,
blocked_count=blocked_count,
)
if blocked_count >= self.THROTTLE_LIMIT:
logger.warning(
"blocked client=%s count=%d",
client_ip,
blocked_count,
)
return HttpResponseForbidden(
"Too many invalid requests detected from your IP address. "
f"Contact {smarter_settings.platform_branding_support_email} for assistance."
)
self.increment_throttle(throttle_key)
return response
[docs]
def is_ignored_path(self, path: str) -> bool:
"""
Determine whether 404s on this path should never count toward the throttle.
:param path: The request path.
:returns: True for amnesty urls and JSON schema lookups.
"""
return self.deserves_amnesty(path) or path.startswith(self.IGNORED_PATH_PREFIXES)
[docs]
@classmethod
def get_throttle_key(cls, client_ip: str) -> str:
"""
Return the cache key of a client's 404 counter.
:param client_ip: The client's ip address.
:returns: The cache key.
"""
return f"excessive_404_throttle:{client_ip}"
[docs]
def increment_throttle(self, throttle_key: str) -> None:
"""
Add one to a client's 404 counter in the cache, and reset its ``THROTTLE_TIMEOUT``.
While the cache can't be written, e.g. during a Redis outage, the 404 isn't counted.
:param throttle_key: The cache key of the client's counter, from :meth:`get_throttle_key`.
"""
try:
try:
blocked_count = cache.incr(throttle_key)
except ValueError:
cache.set(
throttle_key,
1,
timeout=self.THROTTLE_TIMEOUT,
)
else:
cache.set(
throttle_key,
blocked_count,
timeout=self.THROTTLE_TIMEOUT,
)
except CACHE_EXCEPTIONS as e:
# one line, no traceback: Redis being away is an outage to report, not a bug to debug.
logger.warning("the cache failed, not counting the 404: %s", e)
[docs]
def log_404_event(
self,
request: HttpRequest,
client_ip: str,
blocked_count: int,
) -> None:
"""
Log a 404 probe at DEBUG, sampled every ``LOG_SAMPLE_RATE`` counts to reduce spam during bot scans.
:param request: The request.
:param client_ip: The client's ip address.
:param blocked_count: The client's 404 count before this one.
"""
if blocked_count % self.LOG_SAMPLE_RATE != 0:
return
logger.debug(
"404 probe detected client=%s count=%d path=%s",
client_ip,
blocked_count,
request.path,
)