mirror of
https://github.com/eduardogsilva/wireguard_webadmin.git
synced 2026-11-27 07:06:03 +01:00
Fix speed limits of peers inside a limited network and require profile values
This commit is contained in:
+12
-14
@@ -1,5 +1,3 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from crispy_forms.helper import FormHelper
|
||||
from crispy_forms.layout import Button, Div, Layout, Submit
|
||||
from django import forms
|
||||
@@ -7,8 +5,6 @@ from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from speed_profiles.models import SpeedProfile
|
||||
|
||||
MIN_LIMIT = Decimal('0.001')
|
||||
|
||||
|
||||
class SpeedProfileForm(forms.ModelForm):
|
||||
class Meta:
|
||||
@@ -22,16 +18,16 @@ class SpeedProfileForm(forms.ModelForm):
|
||||
'upload_burst': _('Upload burst (MB)'),
|
||||
}
|
||||
help_texts = {
|
||||
'download_limit': _('Traffic that reaches the peer. Leave empty for no download limit.'),
|
||||
'upload_limit': _('Traffic that the peer sends. Leave empty for no upload limit.'),
|
||||
'download_burst': _('Optional. Data that may pass at full speed before the limit applies.'),
|
||||
'upload_burst': _('Optional. Data that may pass at full speed before the limit applies.'),
|
||||
'download_limit': _('Traffic that reaches the peer. 0 disables the download limit.'),
|
||||
'upload_limit': _('Traffic that the peer sends. 0 disables the upload limit.'),
|
||||
'download_burst': _('Data that may pass at full speed before the limit applies. 0 disables the burst.'),
|
||||
'upload_burst': _('Data that may pass at full speed before the limit applies. 0 disables the burst.'),
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
for field_name in ('download_limit', 'download_burst', 'upload_limit', 'upload_burst'):
|
||||
self.fields[field_name].widget.attrs.update({'min': str(MIN_LIMIT), 'step': 'any'})
|
||||
self.fields[field_name].widget.attrs.update({'min': '0', 'step': 'any'})
|
||||
self.helper = FormHelper()
|
||||
self.helper.form_method = 'post'
|
||||
self.helper.layout = Layout(
|
||||
@@ -57,13 +53,15 @@ class SpeedProfileForm(forms.ModelForm):
|
||||
cleaned_data = super().clean()
|
||||
for field_name in ('download_limit', 'download_burst', 'upload_limit', 'upload_burst'):
|
||||
value = cleaned_data.get(field_name)
|
||||
if value is not None and value < MIN_LIMIT:
|
||||
self.add_error(field_name, _('Enter a value greater than zero.'))
|
||||
if value is not None and value < 0:
|
||||
self.add_error(field_name, _('Enter a value greater than or equal to zero.'))
|
||||
if self.errors:
|
||||
return cleaned_data
|
||||
|
||||
if cleaned_data.get('download_limit') is None and cleaned_data.get('upload_limit') is None:
|
||||
if not cleaned_data.get('download_limit') and not cleaned_data.get('upload_limit'):
|
||||
raise forms.ValidationError(_('Set at least a download or an upload limit.'))
|
||||
if cleaned_data.get('download_burst') and cleaned_data.get('download_limit') is None:
|
||||
if cleaned_data.get('download_burst') and not cleaned_data.get('download_limit'):
|
||||
self.add_error('download_burst', _('The burst requires a download limit.'))
|
||||
if cleaned_data.get('upload_burst') and cleaned_data.get('upload_limit') is None:
|
||||
if cleaned_data.get('upload_burst') and not cleaned_data.get('upload_limit'):
|
||||
self.add_error('upload_burst', _('The burst requires an upload limit.'))
|
||||
return cleaned_data
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-24 15:57
|
||||
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
@@ -18,10 +19,10 @@ class Migration(migrations.Migration):
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=64, unique=True)),
|
||||
('download_limit', models.DecimalField(blank=True, decimal_places=3, max_digits=9, null=True)),
|
||||
('upload_limit', models.DecimalField(blank=True, decimal_places=3, max_digits=9, null=True)),
|
||||
('download_burst', models.DecimalField(blank=True, decimal_places=3, max_digits=9, null=True)),
|
||||
('upload_burst', models.DecimalField(blank=True, decimal_places=3, max_digits=9, null=True)),
|
||||
('download_limit', models.DecimalField(decimal_places=3, default=Decimal('0'), max_digits=9)),
|
||||
('upload_limit', models.DecimalField(decimal_places=3, default=Decimal('0'), max_digits=9)),
|
||||
('download_burst', models.DecimalField(decimal_places=3, default=Decimal('0'), max_digits=9)),
|
||||
('upload_burst', models.DecimalField(decimal_places=3, default=Decimal('0'), max_digits=9)),
|
||||
('created', models.DateTimeField(auto_now_add=True)),
|
||||
('updated', models.DateTimeField(auto_now=True)),
|
||||
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
|
||||
@@ -13,14 +13,14 @@ def megabytes_to_bytes(value):
|
||||
|
||||
|
||||
class SpeedProfile(models.Model):
|
||||
"""Bandwidth limit applied to each peer that uses the profile. Empty limits mean no limit in that direction."""
|
||||
"""Bandwidth limit applied to each peer that uses the profile. Zero disables a limit or a burst."""
|
||||
name = models.CharField(max_length=64, unique=True)
|
||||
# Mbit/s. Download is the traffic that reaches the peer, upload the traffic the peer sends.
|
||||
download_limit = models.DecimalField(max_digits=9, decimal_places=3, blank=True, null=True)
|
||||
upload_limit = models.DecimalField(max_digits=9, decimal_places=3, blank=True, null=True)
|
||||
# MB that may pass at full speed before the limit applies. Empty means the automatic minimum.
|
||||
download_burst = models.DecimalField(max_digits=9, decimal_places=3, blank=True, null=True)
|
||||
upload_burst = models.DecimalField(max_digits=9, decimal_places=3, blank=True, null=True)
|
||||
download_limit = models.DecimalField(max_digits=9, decimal_places=3, default=Decimal('0'))
|
||||
upload_limit = models.DecimalField(max_digits=9, decimal_places=3, default=Decimal('0'))
|
||||
# MB that may pass at full speed before the limit applies. Zero means the automatic minimum.
|
||||
download_burst = models.DecimalField(max_digits=9, decimal_places=3, default=Decimal('0'))
|
||||
upload_burst = models.DecimalField(max_digits=9, decimal_places=3, default=Decimal('0'))
|
||||
|
||||
created = models.DateTimeField(auto_now_add=True)
|
||||
updated = models.DateTimeField(auto_now=True)
|
||||
|
||||
+48
-10
@@ -20,7 +20,7 @@ from user_manager.models import UserAcl
|
||||
from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
|
||||
from wireguard_peer.functions import func_create_new_peer
|
||||
from wireguard_tools import functions
|
||||
from wireguard_tools.speed_limits import apply_speed_limits, build_tc_commands, parse_speed_limits
|
||||
from wireguard_tools.speed_limits import apply_speed_limits, build_tc_commands, parse_peers, parse_speed_limits
|
||||
from wireguard_tools.tests import FakeNetwork, load_cluster_worker
|
||||
from wireguard_tools.views import export_wireguard_configuration
|
||||
|
||||
@@ -43,22 +43,24 @@ def create_peer(instance, number, speed_profile=None, networks=(), endpoint=''):
|
||||
|
||||
class SpeedProfileFormTests(TestCase):
|
||||
def form(self, **data):
|
||||
return SpeedProfileForm(data={'name': 'Basic', **data})
|
||||
values = {'download_limit': '0', 'download_burst': '0', 'upload_limit': '0', 'upload_burst': '0'}
|
||||
return SpeedProfileForm(data={'name': 'Basic', **values, **data})
|
||||
|
||||
def test_accepts_optional_and_decimal_limits(self):
|
||||
def test_accepts_decimal_limits_and_zero_disables_a_limit_or_burst(self):
|
||||
self.assertTrue(self.form(download_limit='0.5').is_valid())
|
||||
self.assertTrue(self.form(upload_limit='10').is_valid())
|
||||
form = self.form(download_limit='10', download_burst='5', upload_limit='2.5', upload_burst='0.25')
|
||||
self.assertTrue(form.is_valid(), form.errors)
|
||||
profile = self.form(download_limit='10').save()
|
||||
self.assertEqual(profile.config_comment(), 'download_kbit=10000')
|
||||
self.assertEqual(profile.summary, '↓ 10 Mbit/s')
|
||||
|
||||
def test_refuses_zero_and_negative_values(self):
|
||||
for field_name in ('download_limit', 'upload_limit'):
|
||||
for value in ('0', '-1'):
|
||||
form = self.form(**{field_name: value})
|
||||
def test_refuses_empty_and_negative_values(self):
|
||||
for field_name in ('download_limit', 'download_burst', 'upload_limit', 'upload_burst'):
|
||||
for value in ('', '-1'):
|
||||
form = self.form(**{'download_limit': '10', 'upload_limit': '5', field_name: value})
|
||||
self.assertFalse(form.is_valid())
|
||||
self.assertIn(field_name, form.errors)
|
||||
form = self.form(download_limit='10', download_burst='0')
|
||||
self.assertIn('download_burst', form.errors)
|
||||
|
||||
def test_refuses_repeated_name(self):
|
||||
SpeedProfile.objects.create(name='Basic', download_limit=10)
|
||||
@@ -127,7 +129,8 @@ class SpeedProfileDeleteTests(SpeedProfileViewMixin, TestCase):
|
||||
class SpeedProfileEditTests(SpeedProfileViewMixin, TestCase):
|
||||
def edit(self):
|
||||
return self.client.post(
|
||||
f'/speed_profiles/manage/?uuid={self.profile.uuid}', {'name': 'Basic', 'download_limit': '20', 'upload_limit': '5'}
|
||||
f'/speed_profiles/manage/?uuid={self.profile.uuid}',
|
||||
{'name': 'Basic', 'download_limit': '20', 'download_burst': '0', 'upload_limit': '5', 'upload_burst': '0'},
|
||||
)
|
||||
|
||||
@patch('speed_profiles.views._auto_apply', return_value=True)
|
||||
@@ -209,6 +212,11 @@ class ExportedConfigMixin:
|
||||
with open(os.path.join(self.wireguard_dir, f'wg{instance_id}.conf')) as config_file:
|
||||
return parse_speed_limits(config_file.read())
|
||||
|
||||
def exported_peers(self, instance_id=0):
|
||||
export_wireguard_configuration()
|
||||
with open(os.path.join(self.wireguard_dir, f'wg{instance_id}.conf')) as config_file:
|
||||
return parse_peers(config_file.read())
|
||||
|
||||
|
||||
class SpeedLimitRuleTests(ExportedConfigMixin, TestCase):
|
||||
def setUp(self):
|
||||
@@ -262,6 +270,36 @@ class SpeedLimitRuleTests(ExportedConfigMixin, TestCase):
|
||||
self.assertNotIn('burst', download_classes[1])
|
||||
self.assertNotIn('burst', upload_classes[1])
|
||||
|
||||
def test_peers_inside_the_network_of_a_limited_peer_are_not_limited_with_it(self):
|
||||
create_peer(self.instance, 10, SpeedProfile.objects.create(name='Full', download_limit=10, upload_limit=5),
|
||||
networks=['0.0.0.0/0'], endpoint='remote.example.test:51820')
|
||||
create_peer(self.instance, 11)
|
||||
create_peer(self.instance, 12, SpeedProfile.objects.create(name='Down', download_limit=20))
|
||||
commands = build_tc_commands('wg0', self.exported_peers())
|
||||
|
||||
download_pass = [command for command in commands if command.endswith('flowid 1:')]
|
||||
upload_pass = [command for command in commands if command.endswith('action ok')]
|
||||
# Peer 11 has no limit in both directions; peer 12 has its own download class and no upload limit
|
||||
self.assertEqual([command.split('ip dst ')[1].split()[0] for command in download_pass], ['10.188.0.11/32'])
|
||||
self.assertEqual(
|
||||
sorted(command.split('ip src ')[1].split()[0] for command in upload_pass),
|
||||
['10.188.0.11/32', '10.188.0.12/32'],
|
||||
)
|
||||
# The pass filters are checked before the filters of the broader network
|
||||
broad_priority = int(next(
|
||||
command for command in commands if 'match ip dst 0.0.0.0/0' in command
|
||||
).split(' prio ')[1].split()[0])
|
||||
self.assertTrue(all(int(command.split(' prio ')[1].split()[0]) < broad_priority for command in download_pass))
|
||||
self.assertEqual(len([command for command in commands if command.startswith('class add dev wg0 ')]), 2)
|
||||
|
||||
def test_peers_outside_the_networks_of_limited_peers_get_no_extra_filters(self):
|
||||
create_peer(self.instance, 10, SpeedProfile.objects.create(name='Basic', download_limit=10, upload_limit=5),
|
||||
networks=['192.168.50.0/24'])
|
||||
create_peer(self.instance, 11, networks=['192.168.60.0/24'])
|
||||
commands = build_tc_commands('wg0', self.exported_peers())
|
||||
self.assertEqual(commands, build_tc_commands('wg0', self.exported_limits()))
|
||||
self.assertTrue(all('10.188.0.11' not in command and '192.168.60.0' not in command for command in commands))
|
||||
|
||||
def test_peer_with_endpoint_gets_the_same_rules(self):
|
||||
profile = SpeedProfile.objects.create(name='Basic', download_limit=10, upload_limit=5)
|
||||
create_peer(self.instance, 10, profile, networks=['192.168.70.0/24'], endpoint='remote.example.test:51820')
|
||||
|
||||
@@ -56,19 +56,18 @@ def view_manage_speed_profile(request):
|
||||
form_description = {
|
||||
'size': 'col-lg-6',
|
||||
'content': _('''
|
||||
<h5>Speed profile</h5>
|
||||
<p>Each peer that uses this profile gets its own limit: a profile of 10 Mbit/s does not share 10 Mbit/s among
|
||||
its peers. Peers without a profile have no limit.</p>
|
||||
|
||||
<h5>Download and upload</h5>
|
||||
<p><strong>Download</strong> is the traffic that reaches the peer and <strong>upload</strong> the traffic that
|
||||
it sends. Each limit is optional, so a profile may limit only one direction. The limit covers all the
|
||||
addresses and networks of the peer.</p>
|
||||
it sends. The limit covers all the addresses and networks of the peer. Use 0 to leave a direction without
|
||||
limit. Peers without a profile have no limit.</p>
|
||||
|
||||
<h5>Burst</h5>
|
||||
<p>The amount of data that may pass at full speed before the limit applies, refilled while the peer uses less
|
||||
than its limit. A burst of a few MB keeps browsing fast without allowing large downloads at full speed. For
|
||||
reference, 10 Mbit/s is about 1.25 MB per second. Leave it empty for the automatic minimum.</p>
|
||||
<p>The amount of data that may pass at full speed before the limit applies. It refills while the peer uses
|
||||
less than its limit.</p>
|
||||
<p>Web pages and most apps transfer a few MB at a time, so, depending on the case, a burst of 5 or 10 MB may
|
||||
improve browsing considerably: pages load at full speed, while long downloads and streams still run at the
|
||||
configured limit. For reference, 10 Mbit/s is about 1.25 MB per second.</p>
|
||||
<p>Use 0 to disable the burst.</p>
|
||||
'''),
|
||||
}
|
||||
return render(request, 'generic_form.html', {
|
||||
|
||||
Reference in New Issue
Block a user