Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent logging of requests that are blocked by middlewares #3135

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions blt/middleware/ip_restrict.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import ipaddress
import threading

from django.core.cache import cache
from django.db import models, transaction
Expand All @@ -8,6 +9,12 @@

MAX_COUNT = 2147483647

_thread_locals = threading.local()


def get_current_request():
return getattr(_thread_locals, "request", None)


class IPRestrictMiddleware:
"""
Expand Down Expand Up @@ -111,6 +118,7 @@ def increment_block_count(self, ip=None, network=None, user_agent=None):
blocked_entry.save(update_fields=["count"])

def __call__(self, request):
_thread_locals.request = request
ip = request.META.get("HTTP_X_FORWARDED_FOR", "").split(",")[0].strip() or request.META.get(
"REMOTE_ADDR", ""
)
Expand All @@ -122,18 +130,21 @@ def __call__(self, request):

if self.ip_in_ips(ip, blocked_ips):
self.increment_block_count(ip=ip)
request.blocked = True # Indicate that the request was blocked
return HttpResponseForbidden()

if self.ip_in_range(ip, blocked_ip_network):
# Find the specific network that caused the block and increment its count
for network in blocked_ip_network:
if ipaddress.ip_address(ip) in network:
self.increment_block_count(network=str(network))
request.blocked = True
break
return HttpResponseForbidden()

if self.is_user_agent_blocked(agent, blocked_agents):
self.increment_block_count(user_agent=agent)
request.blocked = True
return HttpResponseForbidden()

if ip:
Expand Down
16 changes: 16 additions & 0 deletions blt/middleware/logging_filters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import logging
import threading

_thread_locals = threading.local()


def get_current_request():
return getattr(_thread_locals, "request", None)


class ExcludeBlockedRequestsFilter(logging.Filter):
def filter(self, record):
request = get_current_request()
if request:
return not getattr(request, "blocked", False)
return True
14 changes: 13 additions & 1 deletion blt/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,11 @@
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"allauth.account.middleware.AccountMiddleware",
"blt.middleware.ip_restrict.IPRestrictMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
"tz_detect.middleware.TimezoneMiddleware",
"blt.middleware.ip_restrict.IPRestrictMiddleware",
)
BLUESKY_USERNAME = env("BLUESKY_USERNAME", default="default_username")
BLUESKY_PASSWORD = env("BLUESKY_PASSWORD", default="default_password")
Expand Down Expand Up @@ -340,19 +340,31 @@
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"filters": {
"exclude_blocked_requests": {
"()": "blt.middleware.logging_filters.ExcludeBlockedRequestsFilter",
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"filters": ["exclude_blocked_requests"],
},
"mail_admins": {
"class": "django.utils.log.AdminEmailHandler",
"filters": ["exclude_blocked_requests"],
},
},
"loggers": {
"": {
"handlers": ["console"],
"level": "DEBUG",
},
"django.request": {
"handlers": ["console", "mail_admins"],
"level": "ERROR",
"propagate": True,
},
},
}
# disable logging unless critical
Expand Down
2 changes: 1 addition & 1 deletion website/migrations/0165_merge_20241203_0320.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 5.1.3 on 2024-12-03 03:20
# Generated by Django 5.1.3 on 2024-12-03 20:36

from django.db import migrations

Expand Down
Loading