From ded2f0c46da653b062f6f43fc6eb8521b1c77370 Mon Sep 17 00:00:00 2001 From: Blaine Jester Date: Sat, 31 Oct 2026 14:13:45 -0700 Subject: [PATCH 1/5] Fall back to localhost when the client IP probe is denied _get_client_ip_for_server opens a UDP socket to learn which local address routes to the server. AppArmor or a sandbox can refuse to create that socket, which raised outside the existing try block. It now logs a warning and returns 127.0.0.1, as it already did when the connect failed. The bare except is narrowed to OSError. Co-Authored-By: Claude Opus 5.5 (1M context) --- morango/sync/syncsession.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/morango/sync/syncsession.py b/morango/sync/syncsession.py index 777004ec..dbc74101 100644 --- a/morango/sync/syncsession.py +++ b/morango/sync/syncsession.py @@ -69,15 +69,25 @@ def _get_server_ip(hostname): def _get_client_ip_for_server(server_host, server_port): - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + default_ip = "127.0.0.1" + + # strict apparmor rules or sandboxing could prevent this + try: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + except OSError: + logger.warning( + f"Could not create socket to determine external IP address to reach {server_host}" + ) + return default_ip + try: s.connect((server_host, server_port)) - IP = s.getsockname()[0] - except: # noqa: E722 - IP = "127.0.0.1" + return s.getsockname()[0] + except (OSError, ValueError, OverflowError): # ValueError covers UnicodeError + logger.warning(f"Could not determine external IP address to reach {server_host}") + return default_ip finally: s.close() - return IP def ignore_404(target): From eee95825d64dd607e0fdd022692bb422baef5e57 Mon Sep 17 00:00:00 2001 From: Blaine Jester Date: Sat, 31 Oct 2026 14:13:45 -0700 Subject: [PATCH 2/5] Clear MORANGO_NODE_ID in the 0.5 instance ID test A MORANGO_NODE_ID set in the environment overrides the node ID, so test_consistent_0_5_instance_id got a different instance ID than the one it expects. Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/testapp/tests/test_uuid_utilities.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/testapp/tests/test_uuid_utilities.py b/tests/testapp/tests/test_uuid_utilities.py index 17c30963..335f9323 100644 --- a/tests/testapp/tests/test_uuid_utilities.py +++ b/tests/testapp/tests/test_uuid_utilities.py @@ -146,6 +146,7 @@ def test_consistent_0_5_instance_id(self, *args): with EnvironmentVarGuard() as env: env["MORANGO_SYSTEM_ID"] = "magicsysid" + env["MORANGO_NODE_ID"] = "" # ensure envvar override does not kick in DatabaseIDModel.objects.all().update(current=False) DatabaseIDModel.objects.create(id="7fe445b75cea11858c00fb97bdee8878", current=True) From d8647a49434c8b7dd4d6422ebc0ae6e7d106e039 Mon Sep 17 00:00:00 2001 From: Blaine Jester Date: Sat, 31 Oct 2026 14:13:45 -0700 Subject: [PATCH 3/5] Use explicit ports for test live servers A sandbox can deny binding to port 0, which LiveServerTestCase uses by default and get_free_tcp_port used to find a free port. get_free_tcp_port moves to the test helpers and falls back to a fixed list of ports when port 0 is denied. A new FreePortLiveServerTestCase picks its port with it in setUpClass, so each class gets a port that is free when its server starts. The client test cases now extend it. Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/testapp/tests/helpers.py | 32 ++++++++++++++++++- .../tests/integration/test_syncsession.py | 10 +----- tests/testapp/tests/sync/test_syncsession.py | 4 +-- 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/tests/testapp/tests/helpers.py b/tests/testapp/tests/helpers.py index 7d7a06eb..5e2459f7 100644 --- a/tests/testapp/tests/helpers.py +++ b/tests/testapp/tests/helpers.py @@ -4,6 +4,7 @@ import functools import json +import socket import uuid import factory @@ -81,6 +82,35 @@ def setUp(self): return cls +def get_free_tcp_port(): + # sandboxing can cause 0 to fail (which is to try for any open port), so fallback to a hardcoded + # list afterward + ports = [0, 3000, 8000, 8001, 8080, 8081, 8888, 10001, 10002, 10003] + for p in ports: + try: + tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + tcp.bind(("127.0.0.1", p)) + _, port = tcp.getsockname() + tcp.close() + return port + except OSError: + pass + + raise RuntimeError("Could not find open port") + + +class FreePortLiveServerTestCase(LiveServerTestCase): + """ + LiveServerTestCase defaults to port 0, which sandboxing can deny, so pick an explicit port + for each test class instead + """ + + @classmethod + def setUpClass(cls): + cls.port = get_free_tcp_port() + super(FreePortLiveServerTestCase, cls).setUpClass() + + class FacilityModelFactory(factory.django.DjangoModelFactory): class Meta: model = Facility @@ -371,7 +401,7 @@ def create_buffer_and_store_dummy_data(transfer_session_id): return data -class BaseClientTestCase(LiveServerTestCase): +class BaseClientTestCase(FreePortLiveServerTestCase): profile = "facilitydata" def setUp(self): diff --git a/tests/testapp/tests/integration/test_syncsession.py b/tests/testapp/tests/integration/test_syncsession.py index cc019328..40f33a37 100644 --- a/tests/testapp/tests/integration/test_syncsession.py +++ b/tests/testapp/tests/integration/test_syncsession.py @@ -1,7 +1,6 @@ import contextlib import json import os -import socket import subprocess import sys import time @@ -29,6 +28,7 @@ from morango.sync.controller import MorangoProfileController from ..compat import EnvironmentVarGuard +from ..helpers import get_free_tcp_port SECOND_TEST_DATABASE = "default2" SECOND_SYSTEM_ID = "default2" @@ -45,14 +45,6 @@ def second_environment(): assert instance1.id != instance2.id -def get_free_tcp_port(): - tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - tcp.bind(("", 0)) - addr, port = tcp.getsockname() - tcp.close() - return port - - class LiveServer: def __init__(self): self.env = os.environ.copy() diff --git a/tests/testapp/tests/sync/test_syncsession.py b/tests/testapp/tests/sync/test_syncsession.py index e715329b..dbe27ce3 100644 --- a/tests/testapp/tests/sync/test_syncsession.py +++ b/tests/testapp/tests/sync/test_syncsession.py @@ -2,7 +2,6 @@ import uuid import mock -from django.test.testcases import LiveServerTestCase from django.test.utils import override_settings from requests.exceptions import ChunkedEncodingError from requests.exceptions import HTTPError @@ -35,6 +34,7 @@ from ..helpers import BaseClientTestCase from ..helpers import BaseTransferClientTestCase +from ..helpers import FreePortLiveServerTestCase def mock_patch_decorator(func): @@ -52,7 +52,7 @@ def wrapper(*args, **kwargs): return wrapper -class NetworkSyncConnectionTestCase(LiveServerTestCase): +class NetworkSyncConnectionTestCase(FreePortLiveServerTestCase): def setUp(self): super(NetworkSyncConnectionTestCase, self).setUp() self.profile = "facilitydata" From 1f69aba94d21d9aefcfe56838cb64ce1b4649d49 Mon Sep 17 00:00:00 2001 From: Blaine Jester Date: Thu, 5 Nov 2026 16:15:53 -0800 Subject: [PATCH 4/5] Close sockets that fail to bind in get_free_tcp_port The socket was only closed after a successful bind, so each port the sandbox refused left a socket open until garbage collection. Co-Authored-By: Claude Opus 5.5 --- tests/testapp/tests/helpers.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tests/testapp/tests/helpers.py b/tests/testapp/tests/helpers.py index 5e2459f7..95a1a658 100644 --- a/tests/testapp/tests/helpers.py +++ b/tests/testapp/tests/helpers.py @@ -88,10 +88,9 @@ def get_free_tcp_port(): ports = [0, 3000, 8000, 8001, 8080, 8081, 8888, 10001, 10002, 10003] for p in ports: try: - tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - tcp.bind(("127.0.0.1", p)) - _, port = tcp.getsockname() - tcp.close() + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as tcp: + tcp.bind(("127.0.0.1", p)) + _, port = tcp.getsockname() return port except OSError: pass From 8ec3958876fb511f1c39f759034e262b2de0d7e8 Mon Sep 17 00:00:00 2001 From: Blaine Jester Date: Thu, 5 Nov 2026 16:15:53 -0800 Subject: [PATCH 5/5] Test the fallbacks in _get_client_ip_for_server Covers both paths that return 127.0.0.1: when the UDP socket can't be created, and when connect raises OSError, UnicodeError or OverflowError. The second also checks that the socket is closed. Co-Authored-By: Claude Opus 5.5 --- tests/testapp/tests/sync/test_syncsession.py | 26 ++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/testapp/tests/sync/test_syncsession.py b/tests/testapp/tests/sync/test_syncsession.py index dbe27ce3..5e63612e 100644 --- a/tests/testapp/tests/sync/test_syncsession.py +++ b/tests/testapp/tests/sync/test_syncsession.py @@ -2,6 +2,7 @@ import uuid import mock +from django.test import SimpleTestCase from django.test.utils import override_settings from requests.exceptions import ChunkedEncodingError from requests.exceptions import HTTPError @@ -26,6 +27,7 @@ from morango.sync.context import NetworkSessionContext from morango.sync.controller import MorangoProfileController from morango.sync.session import SessionWrapper +from morango.sync.syncsession import _get_client_ip_for_server from morango.sync.syncsession import NetworkSyncConnection from morango.sync.syncsession import PullClient from morango.sync.syncsession import PushClient @@ -52,6 +54,30 @@ def wrapper(*args, **kwargs): return wrapper +class GetClientIPForServerTestCase(SimpleTestCase): + logger_name = "morango.sync.syncsession" + + @mock.patch("morango.sync.syncsession.socket.socket") + def test_socket_creation_fails(self, mock_socket): + mock_socket.side_effect = OSError("Too many open files") + with self.assertLogs(self.logger_name, "WARNING") as logs: + ip = _get_client_ip_for_server("example.com", 80) + self.assertEqual(ip, "127.0.0.1") + self.assertIn("Could not create socket", logs.output[0]) + + @mock.patch("morango.sync.syncsession.socket.socket") + def test_connect_fails(self, mock_socket): + for error in (OSError("unreachable"), UnicodeError("label too long"), OverflowError()): + with self.subTest(error=type(error).__name__): + mock_socket.reset_mock() + mock_socket.return_value.connect.side_effect = error + with self.assertLogs(self.logger_name, "WARNING") as logs: + ip = _get_client_ip_for_server("example.com", 80) + self.assertEqual(ip, "127.0.0.1") + self.assertIn("Could not determine external IP address", logs.output[0]) + mock_socket.return_value.close.assert_called_once_with() + + class NetworkSyncConnectionTestCase(FreePortLiveServerTestCase): def setUp(self): super(NetworkSyncConnectionTestCase, self).setUp()