Add ip address exclusion support (closes #22)
Co-authored-by: Anthony Abeo <anthonyabeo@gmail.com>
This commit is contained in:
@@ -6,13 +6,13 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('analytics', '0002_auto_20200415_1742'),
|
||||
("analytics", "0002_auto_20200415_1742"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='session',
|
||||
name='ip',
|
||||
model_name="session",
|
||||
name="ip",
|
||||
field=models.GenericIPAddressField(db_index=True, null=True),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import ipaddress
|
||||
import json
|
||||
import logging
|
||||
from hashlib import sha1
|
||||
|
||||
import geoip2.database
|
||||
import user_agents
|
||||
from hashlib import sha1
|
||||
from celery import shared_task
|
||||
from django.conf import settings
|
||||
from django.core.cache import cache
|
||||
@@ -60,6 +61,14 @@ def ingress_request(
|
||||
if dnt and service.respect_dnt:
|
||||
return
|
||||
|
||||
try:
|
||||
remote_ip = ipaddress.ip_network(ip)
|
||||
for ignored_network in service.get_ignored_networks():
|
||||
if ignored_network.supernet_of(remote_ip):
|
||||
return
|
||||
except ValueError as e:
|
||||
log.exception(e)
|
||||
|
||||
# Validate payload
|
||||
if payload.get("loadTime", 1) <= 0:
|
||||
payload["loadTime"] = None
|
||||
|
||||
@@ -4,7 +4,7 @@ import json
|
||||
from django.conf import settings
|
||||
from django.core.cache import cache
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.http import HttpResponse, Http404, HttpResponseBadRequest
|
||||
from django.http import Http404, HttpResponse, HttpResponseBadRequest
|
||||
from django.shortcuts import render, reverse
|
||||
from django.utils import timezone
|
||||
from django.utils.decorators import method_decorator
|
||||
@@ -36,6 +36,7 @@ def ingress(request, service_uuid, identifier, tracker, payload):
|
||||
identifier=identifier,
|
||||
)
|
||||
|
||||
|
||||
class ValidateServiceOriginsMixin:
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
try:
|
||||
|
||||
@@ -3,12 +3,11 @@ import uuid
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.sites.models import Site
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.utils.crypto import get_random_string
|
||||
|
||||
from django.db import DEFAULT_DB_ALIAS, connections
|
||||
from django.db.utils import OperationalError, ConnectionHandler
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.db import DEFAULT_DB_ALIAS, connections
|
||||
from django.db.utils import ConnectionHandler, OperationalError
|
||||
from django.utils.crypto import get_random_string
|
||||
|
||||
from core.models import User
|
||||
|
||||
@@ -18,6 +17,7 @@ class Command(BaseCommand):
|
||||
|
||||
def check_migrations(self):
|
||||
from django.db.migrations.executor import MigrationExecutor
|
||||
|
||||
try:
|
||||
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
|
||||
except OperationalError:
|
||||
@@ -26,24 +26,31 @@ class Command(BaseCommand):
|
||||
except ImproperlyConfigured:
|
||||
# No databases are configured (or the dummy one)
|
||||
return True
|
||||
|
||||
|
||||
if executor.migration_plan(executor.loader.graph.leaf_nodes()):
|
||||
return True
|
||||
|
||||
|
||||
return False
|
||||
|
||||
|
||||
|
||||
def handle(self, *args, **options):
|
||||
migration = self.check_migrations()
|
||||
|
||||
admin, hostname, whitelabel = [True] * 3
|
||||
if not migration:
|
||||
admin = not User.objects.all().exists()
|
||||
hostname = not Site.objects.filter(domain__isnull=False).exclude(domain__exact="").exclude(domain__exact="example.com").exists()
|
||||
whitelabel = not Site.objects.filter(name__isnull=False).exclude(name__exact="").exclude(name__exact="example.com").exists()
|
||||
hostname = (
|
||||
not Site.objects.filter(domain__isnull=False)
|
||||
.exclude(domain__exact="")
|
||||
.exclude(domain__exact="example.com")
|
||||
.exists()
|
||||
)
|
||||
whitelabel = (
|
||||
not Site.objects.filter(name__isnull=False)
|
||||
.exclude(name__exact="")
|
||||
.exclude(name__exact="example.com")
|
||||
.exists()
|
||||
)
|
||||
|
||||
self.stdout.write(
|
||||
self.style.SUCCESS(
|
||||
f"{migration} {admin} {hostname} {whitelabel}"
|
||||
)
|
||||
self.style.SUCCESS(f"{migration} {admin} {hostname} {whitelabel}")
|
||||
)
|
||||
|
||||
@@ -6,13 +6,13 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('core', '0003_service_respect_dnt'),
|
||||
("core", "0003_service_respect_dnt"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='service',
|
||||
name='collect_ips',
|
||||
model_name="service",
|
||||
name="collect_ips",
|
||||
field=models.BooleanField(default=True),
|
||||
),
|
||||
]
|
||||
|
||||
22
shynet/core/migrations/0005_service_ignored_ips.py
Normal file
22
shynet/core/migrations/0005_service_ignored_ips.py
Normal file
@@ -0,0 +1,22 @@
|
||||
# Generated by Django 3.0.6 on 2020-05-07 20:28
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
import core.models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("core", "0004_service_collect_ips"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="service",
|
||||
name="ignored_ips",
|
||||
field=models.TextField(
|
||||
blank=True, default="", validators=[core.models._validate_network_list]
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -1,8 +1,10 @@
|
||||
import ipaddress
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from django.apps import apps
|
||||
from django.contrib.auth.models import AbstractUser
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import models
|
||||
from django.db.models.functions import TruncDate
|
||||
from django.db.utils import NotSupportedError
|
||||
@@ -14,6 +16,19 @@ def _default_uuid():
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def _validate_network_list(networks: str):
|
||||
try:
|
||||
_parse_network_list(networks)
|
||||
except ValueError as e:
|
||||
raise ValidationError(str(e))
|
||||
|
||||
|
||||
def _parse_network_list(networks: str):
|
||||
if len(networks.strip()) == 0:
|
||||
return []
|
||||
return [ipaddress.ip_network(network.strip()) for network in networks.split(",")]
|
||||
|
||||
|
||||
class User(AbstractUser):
|
||||
username = models.TextField(default=_default_uuid, unique=True)
|
||||
email = models.EmailField(unique=True)
|
||||
@@ -43,6 +58,9 @@ class Service(models.Model):
|
||||
)
|
||||
respect_dnt = models.BooleanField(default=True)
|
||||
collect_ips = models.BooleanField(default=True)
|
||||
ignored_ips = models.TextField(
|
||||
default="", blank=True, validators=[_validate_network_list]
|
||||
)
|
||||
|
||||
class Meta:
|
||||
ordering = ["name", "uuid"]
|
||||
@@ -50,6 +68,9 @@ class Service(models.Model):
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
def get_ignored_networks(self):
|
||||
return _parse_network_list(self.ignored_ips)
|
||||
|
||||
def get_daily_stats(self):
|
||||
return self.get_core_stats(
|
||||
start_time=timezone.now() - timezone.timedelta(days=1)
|
||||
|
||||
@@ -8,17 +8,27 @@ from core.models import Service, User
|
||||
class ServiceForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = Service
|
||||
fields = ["name", "link", "respect_dnt", "collect_ips", "origins", "collaborators"]
|
||||
fields = [
|
||||
"name",
|
||||
"link",
|
||||
"respect_dnt",
|
||||
"collect_ips",
|
||||
"ignored_ips",
|
||||
"origins",
|
||||
"collaborators",
|
||||
]
|
||||
widgets = {
|
||||
"name": forms.TextInput(),
|
||||
"origins": forms.TextInput(),
|
||||
"ignored_ips": forms.TextInput(),
|
||||
"respect_dnt": forms.RadioSelect(choices=[(True, "Yes"), (False, "No")]),
|
||||
"collect_ips": forms.RadioSelect(choices=[(True, "Yes"), (False, "No")]),
|
||||
}
|
||||
labels = {
|
||||
"origins": "Allowed Hostnames",
|
||||
"respect_dnt": "Respect DNT",
|
||||
"collect_ips": "Collect IP addresses"
|
||||
"collect_ips": "Collect IP addresses",
|
||||
"ignored_ips": "Ignored IP addresses",
|
||||
}
|
||||
help_texts = {
|
||||
"name": _("What should the service be called?"),
|
||||
@@ -27,7 +37,8 @@ class ServiceForm(forms.ModelForm):
|
||||
"At what hostnames does the service operate? This sets CORS headers, so use '*' if you're not sure (or don't care)."
|
||||
),
|
||||
"respect_dnt": "Should visitors who have enabled <a href='https://en.wikipedia.org/wiki/Do_Not_Track'>Do Not Track</a> be excluded from all data?",
|
||||
"collect_ips": "Should individual IP addresses be collected? IP metadata (location, host, etc) will still be collected."
|
||||
"collect_ips": "Should individual IP addresses be collected? IP metadata (location, host, etc) will still be collected.",
|
||||
"ignored_ips": "A comma-separated list of IP addresses or IP ranges (IPv4 and IPv6) to exclude from tracking (e.g., '192.168.0.2, 127.0.0.1/32').",
|
||||
}
|
||||
|
||||
collaborators = forms.CharField(
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
{{form.link|a17t}}
|
||||
{{form.collaborators|a17t}}
|
||||
|
||||
<details class="p-4 border rounded">
|
||||
<details class="p-4 border rounded" {% if form.errors %}open{% endif %}>
|
||||
<summary class="cursor-pointer text-sm">Advanced settings</summary>
|
||||
<hr class="sep h-4">
|
||||
{{form.respect_dnt|a17t}}
|
||||
{{form.collect_ips|a17t}}
|
||||
{{form.ignored_ips|a17t}}
|
||||
{{form.origins|a17t}}
|
||||
</details>
|
||||
@@ -81,11 +81,11 @@ def percent_change_display(start, end):
|
||||
|
||||
return SafeString(direction + pct_change)
|
||||
|
||||
|
||||
@register.inclusion_tag("dashboard/includes/sidebar_footer.html")
|
||||
def sidebar_footer():
|
||||
return {
|
||||
"version": settings.VERSION
|
||||
}
|
||||
return {"version": settings.VERSION}
|
||||
|
||||
|
||||
@register.inclusion_tag("dashboard/includes/stat_comparison.html")
|
||||
def compare(
|
||||
|
||||
Reference in New Issue
Block a user