|
| 1 | +# Copyright 2025 New Vector Ltd. |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial |
| 4 | +# Please see LICENSE files in the repository root for full details. |
| 5 | + |
| 6 | +from io import BytesIO |
| 7 | +from unittest.mock import MagicMock |
| 8 | + |
| 9 | +from twisted.internet import defer |
| 10 | +from twisted.python.failure import Failure |
| 11 | +from twisted.trial import unittest |
| 12 | +from twisted.web.client import ResponseDone |
| 13 | +from twisted.web.http import PotentialDataLoss |
| 14 | +from twisted.web.iweb import UNKNOWN_LENGTH |
| 15 | + |
| 16 | +from sydent.http.httpcommon import ( |
| 17 | + BodyExceededMaxSize, |
| 18 | + SizeLimitingRequest, |
| 19 | + _DiscardBodyWithMaxSizeProtocol, |
| 20 | + _ReadBodyWithMaxSizeProtocol, |
| 21 | + read_body_with_max_size, |
| 22 | +) |
| 23 | + |
| 24 | + |
| 25 | +class ReadBodyWithMaxSizeProtocolTest(unittest.TestCase): |
| 26 | + """Tests for _ReadBodyWithMaxSizeProtocol.""" |
| 27 | + |
| 28 | + def _make_protocol( |
| 29 | + self, max_size: int | None = None |
| 30 | + ) -> tuple[_ReadBodyWithMaxSizeProtocol, "defer.Deferred[bytes]"]: |
| 31 | + d: defer.Deferred[bytes] = defer.Deferred() |
| 32 | + protocol = _ReadBodyWithMaxSizeProtocol(d, max_size) |
| 33 | + protocol.transport = MagicMock() |
| 34 | + return protocol, d |
| 35 | + |
| 36 | + def test_reads_body_under_limit(self) -> None: |
| 37 | + """Body under the limit is read successfully.""" |
| 38 | + protocol, d = self._make_protocol(max_size=100) |
| 39 | + protocol.dataReceived(b"hello ") |
| 40 | + protocol.dataReceived(b"world") |
| 41 | + protocol.connectionLost(Failure(ResponseDone())) |
| 42 | + self.assertEqual(self.successResultOf(d), b"hello world") |
| 43 | + |
| 44 | + def test_exceeds_max_size(self) -> None: |
| 45 | + """Body exceeding max_size triggers BodyExceededMaxSize.""" |
| 46 | + protocol, d = self._make_protocol(max_size=5) |
| 47 | + protocol.dataReceived(b"too much data") |
| 48 | + self.failureResultOf(d, BodyExceededMaxSize) |
| 49 | + protocol.transport.abortConnection.assert_called_once() |
| 50 | + |
| 51 | + def test_exact_boundary(self) -> None: |
| 52 | + """Body exactly at max_size triggers the error (>= check).""" |
| 53 | + protocol, d = self._make_protocol(max_size=5) |
| 54 | + protocol.dataReceived(b"12345") |
| 55 | + self.failureResultOf(d, BodyExceededMaxSize) |
| 56 | + |
| 57 | + def test_no_max_size(self) -> None: |
| 58 | + """With max_size=None, any amount of data is accepted.""" |
| 59 | + protocol, d = self._make_protocol(max_size=None) |
| 60 | + protocol.dataReceived(b"x" * 10000) |
| 61 | + protocol.connectionLost(Failure(ResponseDone())) |
| 62 | + self.assertEqual(len(self.successResultOf(d)), 10000) |
| 63 | + |
| 64 | + def test_potential_data_loss_succeeds(self) -> None: |
| 65 | + """PotentialDataLoss is treated as success (same as ResponseDone).""" |
| 66 | + protocol, d = self._make_protocol(max_size=1000) |
| 67 | + protocol.dataReceived(b"partial data") |
| 68 | + protocol.connectionLost(Failure(PotentialDataLoss())) |
| 69 | + self.assertEqual(self.successResultOf(d), b"partial data") |
| 70 | + |
| 71 | + def test_connection_error_propagates(self) -> None: |
| 72 | + """An unexpected connection loss reason propagates the error.""" |
| 73 | + protocol, d = self._make_protocol(max_size=1000) |
| 74 | + protocol.dataReceived(b"some data") |
| 75 | + error = Failure(Exception("connection reset")) |
| 76 | + protocol.connectionLost(error) |
| 77 | + f = self.failureResultOf(d) |
| 78 | + self.assertIsInstance(f.value, Exception) |
| 79 | + |
| 80 | + |
| 81 | +class DiscardBodyWithMaxSizeProtocolTest(unittest.TestCase): |
| 82 | + """Tests for _DiscardBodyWithMaxSizeProtocol.""" |
| 83 | + |
| 84 | + def test_errors_on_data_received(self) -> None: |
| 85 | + """Fires errback and aborts connection on first data.""" |
| 86 | + d: defer.Deferred[bytes] = defer.Deferred() |
| 87 | + protocol = _DiscardBodyWithMaxSizeProtocol(d) |
| 88 | + protocol.transport = MagicMock() |
| 89 | + protocol.dataReceived(b"any data") |
| 90 | + self.failureResultOf(d, BodyExceededMaxSize) |
| 91 | + protocol.transport.abortConnection.assert_called_once() |
| 92 | + |
| 93 | + def test_errors_on_connection_lost(self) -> None: |
| 94 | + """Also fires errback if connectionLost fires first.""" |
| 95 | + d: defer.Deferred[bytes] = defer.Deferred() |
| 96 | + protocol = _DiscardBodyWithMaxSizeProtocol(d) |
| 97 | + protocol.transport = MagicMock() |
| 98 | + protocol.connectionLost(Failure(ResponseDone())) |
| 99 | + self.failureResultOf(d, BodyExceededMaxSize) |
| 100 | + |
| 101 | + def test_idempotent(self) -> None: |
| 102 | + """Multiple calls to _maybe_fail don't double-fire the deferred.""" |
| 103 | + d: defer.Deferred[bytes] = defer.Deferred() |
| 104 | + protocol = _DiscardBodyWithMaxSizeProtocol(d) |
| 105 | + protocol.transport = MagicMock() |
| 106 | + protocol.dataReceived(b"first") |
| 107 | + protocol.dataReceived(b"second") # should not raise |
| 108 | + protocol.connectionLost(Failure(ResponseDone())) |
| 109 | + self.failureResultOf(d, BodyExceededMaxSize) |
| 110 | + |
| 111 | + |
| 112 | +class ReadBodyWithMaxSizeFunctionTest(unittest.TestCase): |
| 113 | + """Tests for the read_body_with_max_size() top-level function.""" |
| 114 | + |
| 115 | + def _make_response(self, length: int | object = UNKNOWN_LENGTH) -> MagicMock: |
| 116 | + response = MagicMock() |
| 117 | + response.length = length |
| 118 | + return response |
| 119 | + |
| 120 | + def test_content_length_exceeds_limit_uses_discard(self) -> None: |
| 121 | + """When Content-Length > max_size, the Discard protocol is used.""" |
| 122 | + response = self._make_response(length=200) |
| 123 | + read_body_with_max_size(response, max_size=100) |
| 124 | + response.deliverBody.assert_called_once() |
| 125 | + protocol = response.deliverBody.call_args[0][0] |
| 126 | + self.assertIsInstance(protocol, _DiscardBodyWithMaxSizeProtocol) |
| 127 | + |
| 128 | + def test_content_length_under_limit_uses_reader(self) -> None: |
| 129 | + """When Content-Length <= max_size, the Read protocol is used.""" |
| 130 | + response = self._make_response(length=50) |
| 131 | + read_body_with_max_size(response, max_size=100) |
| 132 | + response.deliverBody.assert_called_once() |
| 133 | + protocol = response.deliverBody.call_args[0][0] |
| 134 | + self.assertIsInstance(protocol, _ReadBodyWithMaxSizeProtocol) |
| 135 | + |
| 136 | + def test_unknown_length_uses_reader(self) -> None: |
| 137 | + """When Content-Length is unknown, the Read protocol is used.""" |
| 138 | + response = self._make_response(length=UNKNOWN_LENGTH) |
| 139 | + read_body_with_max_size(response, max_size=100) |
| 140 | + response.deliverBody.assert_called_once() |
| 141 | + protocol = response.deliverBody.call_args[0][0] |
| 142 | + self.assertIsInstance(protocol, _ReadBodyWithMaxSizeProtocol) |
| 143 | + |
| 144 | + def test_no_max_size_uses_reader(self) -> None: |
| 145 | + """When max_size is None, always uses the Read protocol.""" |
| 146 | + response = self._make_response(length=999999) |
| 147 | + read_body_with_max_size(response, max_size=None) |
| 148 | + response.deliverBody.assert_called_once() |
| 149 | + protocol = response.deliverBody.call_args[0][0] |
| 150 | + self.assertIsInstance(protocol, _ReadBodyWithMaxSizeProtocol) |
| 151 | + |
| 152 | + |
| 153 | +class SizeLimitingRequestTest(unittest.TestCase): |
| 154 | + """Tests for SizeLimitingRequest.handleContentChunk().""" |
| 155 | + |
| 156 | + def _make_request(self) -> SizeLimitingRequest: |
| 157 | + """Create a minimal SizeLimitingRequest for testing.""" |
| 158 | + req = SizeLimitingRequest.__new__(SizeLimitingRequest) |
| 159 | + req.content = BytesIO() |
| 160 | + req.transport = MagicMock() |
| 161 | + # The client attribute is accessed for logging. |
| 162 | + req.client = MagicMock() |
| 163 | + return req |
| 164 | + |
| 165 | + def test_accepts_data_under_limit(self) -> None: |
| 166 | + """Chunks totalling under MAX_REQUEST_SIZE are accepted.""" |
| 167 | + req = self._make_request() |
| 168 | + data = b"x" * 1000 |
| 169 | + req.handleContentChunk(data) |
| 170 | + self.assertEqual(req.content.tell(), 1000) |
| 171 | + req.transport.abortConnection.assert_not_called() |
| 172 | + |
| 173 | + def test_aborts_on_oversize(self) -> None: |
| 174 | + """Connection is aborted when cumulative data exceeds MAX_REQUEST_SIZE.""" |
| 175 | + req = self._make_request() |
| 176 | + # Write data right up to the limit. |
| 177 | + req.content.write(b"x" * (512 * 1024)) |
| 178 | + req.content.seek(512 * 1024) |
| 179 | + # The next chunk pushes over. |
| 180 | + req.handleContentChunk(b"x") |
| 181 | + req.transport.abortConnection.assert_called_once() |
0 commit comments