Skip to content

Commit 47282f3

Browse files
authored
Merge pull request #411 from learningequality/sandboxing-defense
Add defensive behavior for strict environments like sandboxes
2 parents 32ced7b + b8e632d commit 47282f3

5 files changed

Lines changed: 75 additions & 17 deletions

File tree

‎morango/sync/syncsession.py‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,15 +69,25 @@ def _get_server_ip(hostname):
6969

7070

7171
def _get_client_ip_for_server(server_host, server_port):
72-
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
72+
default_ip = "127.0.0.1"
73+
74+
# strict apparmor rules or sandboxing could prevent this
75+
try:
76+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
77+
except OSError:
78+
logger.warning(
79+
f"Could not create socket to determine external IP address to reach {server_host}"
80+
)
81+
return default_ip
82+
7383
try:
7484
s.connect((server_host, server_port))
75-
IP = s.getsockname()[0]
76-
except: # noqa: E722
77-
IP = "127.0.0.1"
85+
return s.getsockname()[0]
86+
except (OSError, ValueError, OverflowError): # ValueError covers UnicodeError
87+
logger.warning(f"Could not determine external IP address to reach {server_host}")
88+
return default_ip
7889
finally:
7990
s.close()
80-
return IP
8191

8292

8393
def ignore_404(target):

‎tests/testapp/tests/helpers.py‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import functools
66
import json
7+
import socket
78
import uuid
89

910
import factory
@@ -81,6 +82,34 @@ def setUp(self):
8182
return cls
8283

8384

85+
def get_free_tcp_port():
86+
# sandboxing can cause 0 to fail (which is to try for any open port), so fallback to a hardcoded
87+
# list afterward
88+
ports = [0, 3000, 8000, 8001, 8080, 8081, 8888, 10001, 10002, 10003]
89+
for p in ports:
90+
try:
91+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as tcp:
92+
tcp.bind(("127.0.0.1", p))
93+
_, port = tcp.getsockname()
94+
return port
95+
except OSError:
96+
pass
97+
98+
raise RuntimeError("Could not find open port")
99+
100+
101+
class FreePortLiveServerTestCase(LiveServerTestCase):
102+
"""
103+
LiveServerTestCase defaults to port 0, which sandboxing can deny, so pick an explicit port
104+
for each test class instead
105+
"""
106+
107+
@classmethod
108+
def setUpClass(cls):
109+
cls.port = get_free_tcp_port()
110+
super(FreePortLiveServerTestCase, cls).setUpClass()
111+
112+
84113
class FacilityModelFactory(factory.django.DjangoModelFactory):
85114
class Meta:
86115
model = Facility
@@ -371,7 +400,7 @@ def create_buffer_and_store_dummy_data(transfer_session_id):
371400
return data
372401

373402

374-
class BaseClientTestCase(LiveServerTestCase):
403+
class BaseClientTestCase(FreePortLiveServerTestCase):
375404
profile = "facilitydata"
376405

377406
def setUp(self):

‎tests/testapp/tests/integration/test_syncsession.py‎

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import contextlib
22
import json
33
import os
4-
import socket
54
import subprocess
65
import sys
76
import time
@@ -29,6 +28,7 @@
2928
from morango.sync.controller import MorangoProfileController
3029

3130
from ..compat import EnvironmentVarGuard
31+
from ..helpers import get_free_tcp_port
3232

3333
SECOND_TEST_DATABASE = "default2"
3434
SECOND_SYSTEM_ID = "default2"
@@ -45,14 +45,6 @@ def second_environment():
4545
assert instance1.id != instance2.id
4646

4747

48-
def get_free_tcp_port():
49-
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
50-
tcp.bind(("", 0))
51-
addr, port = tcp.getsockname()
52-
tcp.close()
53-
return port
54-
55-
5648
class LiveServer:
5749
def __init__(self):
5850
self.env = os.environ.copy()

‎tests/testapp/tests/sync/test_syncsession.py‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import uuid
33

44
import mock
5-
from django.test.testcases import LiveServerTestCase
5+
from django.test import SimpleTestCase
66
from django.test.utils import override_settings
77
from requests.exceptions import ChunkedEncodingError
88
from requests.exceptions import HTTPError
@@ -27,6 +27,7 @@
2727
from morango.sync.context import NetworkSessionContext
2828
from morango.sync.controller import MorangoProfileController
2929
from morango.sync.session import SessionWrapper
30+
from morango.sync.syncsession import _get_client_ip_for_server
3031
from morango.sync.syncsession import NetworkSyncConnection
3132
from morango.sync.syncsession import PullClient
3233
from morango.sync.syncsession import PushClient
@@ -35,6 +36,7 @@
3536

3637
from ..helpers import BaseClientTestCase
3738
from ..helpers import BaseTransferClientTestCase
39+
from ..helpers import FreePortLiveServerTestCase
3840

3941

4042
def mock_patch_decorator(func):
@@ -52,7 +54,31 @@ def wrapper(*args, **kwargs):
5254
return wrapper
5355

5456

55-
class NetworkSyncConnectionTestCase(LiveServerTestCase):
57+
class GetClientIPForServerTestCase(SimpleTestCase):
58+
logger_name = "morango.sync.syncsession"
59+
60+
@mock.patch("morango.sync.syncsession.socket.socket")
61+
def test_socket_creation_fails(self, mock_socket):
62+
mock_socket.side_effect = OSError("Too many open files")
63+
with self.assertLogs(self.logger_name, "WARNING") as logs:
64+
ip = _get_client_ip_for_server("example.com", 80)
65+
self.assertEqual(ip, "127.0.0.1")
66+
self.assertIn("Could not create socket", logs.output[0])
67+
68+
@mock.patch("morango.sync.syncsession.socket.socket")
69+
def test_connect_fails(self, mock_socket):
70+
for error in (OSError("unreachable"), UnicodeError("label too long"), OverflowError()):
71+
with self.subTest(error=type(error).__name__):
72+
mock_socket.reset_mock()
73+
mock_socket.return_value.connect.side_effect = error
74+
with self.assertLogs(self.logger_name, "WARNING") as logs:
75+
ip = _get_client_ip_for_server("example.com", 80)
76+
self.assertEqual(ip, "127.0.0.1")
77+
self.assertIn("Could not determine external IP address", logs.output[0])
78+
mock_socket.return_value.close.assert_called_once_with()
79+
80+
81+
class NetworkSyncConnectionTestCase(FreePortLiveServerTestCase):
5682
def setUp(self):
5783
super(NetworkSyncConnectionTestCase, self).setUp()
5884
self.profile = "facilitydata"

‎tests/testapp/tests/test_uuid_utilities.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ def test_consistent_0_5_instance_id(self, *args):
146146

147147
with EnvironmentVarGuard() as env:
148148
env["MORANGO_SYSTEM_ID"] = "magicsysid"
149+
env["MORANGO_NODE_ID"] = "" # ensure envvar override does not kick in
149150

150151
DatabaseIDModel.objects.all().update(current=False)
151152
DatabaseIDModel.objects.create(id="7fe445b75cea11858c00fb97bdee8878", current=True)

0 commit comments

Comments
 (0)