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

[fix] Fix overlapping shared/non-shared subnet validation #88 #89

Merged
merged 1 commit into from
Apr 5, 2021
Merged
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: 8 additions & 3 deletions openwisp_ipam/base/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import xlrd
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from openwisp_users.mixins import ShareableOrgMixin
from openwisp_utils.base import TimeStampedEditableModel
Expand Down Expand Up @@ -92,9 +93,13 @@ def _validate_multitenant_master_subnet(self):
)

def _validate_overlapping_subnets(self):
qs = self._meta.model.objects.filter(organization=self.organization).only(
'subnet'
)
qs = self._meta.model.objects.only('subnet', 'master_subnet')
# if the subnet is not shared, include shared subnets in the overlap check
if self.organization:
conditions = Q(organization__isnull=True) | Q(
organization=self.organization
)
qs = qs.filter(conditions)
# exclude parent subnets
exclude = [self.pk]
parent_subnet = self.master_subnet
Expand Down
16 changes: 16 additions & 0 deletions openwisp_ipam/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,22 @@ def test_overlapping_subnet(self):
org2 = self._create_org(name='org2', slug='org2')
self._create_subnet(subnet='10.0.0.0/24', organization=org2)

with self.subTest('shared orgs overlaps with non shared'):
with self.assertRaises(ValidationError) as context_manager:
self._create_subnet(subnet='10.0.0.0/8', organization=None)
message_dict = context_manager.exception.message_dict
self.assertIn('subnet', message_dict)
self.assertIn('Subnet overlaps with 10.0.0.0/16.', message_dict['subnet'])

with self.subTest('non shared subnet overlaps with shared'):
Subnet.objects.all().delete()
self._create_subnet(subnet='10.0.0.0/8', organization=None)
with self.assertRaises(ValidationError) as context_manager:
self._create_subnet(subnet='10.0.0.0/16')
message_dict = context_manager.exception.message_dict
self.assertIn('subnet', message_dict)
self.assertIn('Subnet overlaps with 10.0.0.0/8.', message_dict['subnet'])

def test_master_subnet_validation(self):
master = self._create_subnet(subnet='10.0.0.0/23')
org2 = self._create_org(name='org2', slug='org2')
Expand Down