Skip to content
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
18 changes: 14 additions & 4 deletions openwisp_ipam/base/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,12 +294,22 @@ def get_next_available_ip(self):
"""Return the next assignable, unallocated IP address in this subnet.

Usability is checked against this subnet and its ancestors. Existing
IP address records directly assigned to this subnet are skipped.
IP address records in this subnet, its ancestors and descendants are
skipped, matching duplicate validation when the address is saved.
"""
ipaddress_set = set(self.ipaddress_set.values_list("ip_address", flat=True))
related_ips = (
load_model("openwisp_ipam", "IpAddress")
.objects.filter(subnet_id__in=self.get_related_subnet_pks())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 · Prevent private allocations from becoming a shared-subnet oracle

The next-available-IP endpoint calls this method for shared subnets accessible to organization managers. Since this query includes every descendant, a manager can see the returned address change when another organization allocates the first address in its private child subnet. The hosts and allocation endpoints already filter those private descendants. Keep the global check for actual allocation, but prevent this endpoint from revealing another organization's allocation state, for example by restricting the response when it cannot be disclosed safely.

I ran the following regression in TestMultitenantApi with ./runtests openwisp_ipam.tests.test_multitenant.TestMultitenantApi.test_shared_next_ip_hides_other_org_allocation. It fails because the responses change from 10.0.0.1 to 10.0.0.2. If access is restricted instead, adapt the assertions to verify the restricted response.

def test_shared_next_ip_hides_other_org_allocation(self):
    parent = self._create_subnet(subnet="10.0.0.0/29", organization=None)
    child = self._create_subnet(
        subnet="10.0.0.1/32",
        organization=self._get_org(org_name="org_b"),
        master_subnet=parent,
    )
    self._login(username="user_a", password="tester")
    url = reverse("ipam:get_next_available_ip", args=(parent.id,))
    before = self.client.get(url)
    self._create_ipaddress(ip_address="10.0.0.1", subnet=child)
    after = self.client.get(url)
    self.assertEqual(before.status_code, 200)
    self.assertEqual(after.status_code, 200)
    self.assertEqual(before.data, after.data)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on 2de40c9: an organization manager receives a 404 for another organization’s private child, but the shared parent next-IP response changes from 10.0.0.1 to 10.0.0.2 after that child allocates the first address. At base 7ffe5d5 the GET response does not change. The shared-parent request-IP endpoint also returns the globally selected address, so restricting only the preview would leave another way to infer allocation state. Filtering the preview alone would instead advertise an address that actual allocation cannot use. Restricting both operations for non-superusers on shared parents would prevent this path but would also remove a workflow described in issue #275. Under openwisp-iterate-review, "Scope and Complexity", this API and access-policy tradeoff needs a maintainer decision before changing behavior. I am pausing this review stage while seeking that decision; no code has been changed.

.values_list("ip_address", flat=True)
.iterator()
)
# Filter as addresses are read so unrelated ancestor IPs are not retained.
# Python membership also works with SQLite text and PostgreSQL inet fields.
ipaddress_set = set(
address for address in related_ips if ip_address(address) in self.subnet
)
containing_networks = self._get_containing_networks()
subnet_hosts = self.subnet.hosts()
for host in subnet_hosts:
for host in self.subnet.hosts():
if (
self._is_ip_usable(host, containing_networks)
and str(host) not in ipaddress_set
Expand Down
68 changes: 68 additions & 0 deletions openwisp_ipam/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
from unittest.mock import patch

from django.core.exceptions import ValidationError
from django.db import connection
from django.test import TestCase
from django.test.utils import CaptureQueriesContext
from swapper import load_model

from openwisp_ipam.base.models import CsvImportException
Expand Down Expand Up @@ -816,3 +818,69 @@ def test_get_or_create_org(self):
"“new-org”",
str(context_manager.exception),
)

def test_request_ip_skips_related_subnet_allocations(self):
parent = self._create_subnet(subnet="10.0.0.0/29")
child = self._create_subnet(subnet="10.0.0.0/30", master_subnet=parent)
grandchild = self._create_subnet(subnet="10.0.0.1/32", master_subnet=child)
self._create_ipaddress(subnet=grandchild, ip_address="10.0.0.1")

with self.subTest("parent skips descendant allocation"):
self.assertEqual(parent.get_next_available_ip(), "10.0.0.2")
self.assertEqual(parent.request_ip().ip_address, "10.0.0.2")

with self.subTest("child exhausted by ancestor and descendant allocations"):
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
parent = self._create_subnet(subnet="10.0.1.0/29")
child = self._create_subnet(subnet="10.0.1.0/30", master_subnet=parent)
grandchild = self._create_subnet(subnet="10.0.1.1/32", master_subnet=child)
self._create_ipaddress(subnet=grandchild, ip_address="10.0.1.1")
self._create_ipaddress(subnet=parent, ip_address="10.0.1.2")
self.assertEqual(child.get_next_available_ip(), None)
self.assertEqual(child.request_ip(), None)

def test_child_allocation_retains_only_addresses_in_subnet(self):
retained_addresses = []

def capture_set(values):
result = set(values)
retained_addresses.append(result)
return result

# Observe the set because the result alone cannot show retained memory.
with self.subTest("IPv4 ancestor allocations outside the child"):
parent = self._create_subnet(subnet="10.0.0.0/24")
child = self._create_subnet(subnet="10.0.0.0/30", master_subnet=parent)
self._create_ipaddress(subnet=parent, ip_address="10.0.0.1")
self._create_ipaddress(subnet=parent, ip_address="10.0.0.10")
with patch("openwisp_ipam.base.models.set", capture_set, create=True):
self.assertEqual(child.get_next_available_ip(), "10.0.0.2")
self.assertEqual(retained_addresses, [{"10.0.0.1"}])

with self.subTest("IPv6 ancestor allocations outside the child"):
retained_addresses.clear()
parent = self._create_subnet(subnet="2001:db8::/120")
child = self._create_subnet(subnet="2001:db8::/126", master_subnet=parent)
self._create_ipaddress(subnet=parent, ip_address="2001:db8::1")
self._create_ipaddress(subnet=parent, ip_address="2001:db8::10")
with patch("openwisp_ipam.base.models.set", capture_set, create=True):
self.assertEqual(child.get_next_available_ip(), "2001:db8::2")
self.assertEqual(retained_addresses, [{"2001:db8::1"}])

def test_request_ip_after_many_related_allocations(self):
parent = self._create_subnet(subnet="10.0.0.0/22")
child = self._create_subnet(subnet="10.0.0.0/23", master_subnet=parent)
# Bulk insertion keeps the allocation regression independent of validation.
IpAddress.objects.bulk_create(
[
IpAddress(subnet=parent, ip_address=str(address))
for address in islice(child.subnet.hosts(), 256)
]
)
with CaptureQueriesContext(connection) as queries:
self.assertEqual(child.get_next_available_ip(), "10.0.1.1")
ip_table = connection.ops.quote_name(IpAddress._meta.db_table)
allocation_queries = [
query for query in queries if f"FROM {ip_table}" in query["sql"]
]
self.assertEqual(len(allocation_queries), 1)
self.assertEqual(child.request_ip().ip_address, "10.0.1.1")
Loading