|
| 1 | +"""Tests for the full-scan upload retry on transient gateway/connection failures. |
| 2 | +
|
| 3 | +A `POST /orgs/<org>/full-scans` upload can fail transiently (an HTTP 502/503/504/408, a |
| 4 | +dropped or reset connection, or a timeout) without the server having created the scan. |
| 5 | +`Core.create_full_scan` retries the failures the SDK classifies as transient |
| 6 | +(`APIFailure.is_transient_error()`, socketdev>=3.3.0); these tests cover the retry |
| 7 | +decision, the loop bounds, and that the temporary brotli-compressed facts files survive |
| 8 | +until every attempt has finished. |
| 9 | +""" |
| 10 | + |
| 11 | +import logging |
| 12 | +from unittest.mock import MagicMock |
| 13 | + |
| 14 | +import pytest |
| 15 | +from socketdev.exceptions import ( |
| 16 | + APIAccessDenied, |
| 17 | + APIBadGateway, |
| 18 | + APIConnectionError, |
| 19 | + APIFailure, |
| 20 | + APIResourceNotFound, |
| 21 | + APITimeout, |
| 22 | +) |
| 23 | +from socketdev.fullscans import FullScanMetadata |
| 24 | + |
| 25 | +from socketsecurity.core import ( |
| 26 | + FULL_SCAN_UPLOAD_MAX_ATTEMPTS, |
| 27 | + SOCKET_FACTS_BROTLI_FILENAME, |
| 28 | + SOCKET_FACTS_FILENAME, |
| 29 | + Core, |
| 30 | +) |
| 31 | + |
| 32 | + |
| 33 | +def _success_response(): |
| 34 | + metadata = FullScanMetadata( |
| 35 | + id="scan-1", |
| 36 | + created_at="2026-01-01T00:00:00Z", |
| 37 | + updated_at="2026-01-01T00:00:00Z", |
| 38 | + organization_id="org-1", |
| 39 | + repository_id="repo-1", |
| 40 | + branch="main", |
| 41 | + html_report_url="https://socket.dev/report", |
| 42 | + ) |
| 43 | + response = MagicMock() |
| 44 | + response.success = True |
| 45 | + response.data = metadata |
| 46 | + return response |
| 47 | + |
| 48 | + |
| 49 | +# Catch-all APIFailure as the SDK raises it for statuses without a dedicated class |
| 50 | +# (socketdev/core/api.py); the recorded status_code drives is_transient_error(). |
| 51 | +def _catch_all_failure(status_code: int) -> APIFailure: |
| 52 | + return APIFailure( |
| 53 | + f"Bad Request: HTTP original_status_code:{status_code}\n" |
| 54 | + f"Path: https://api.socket.dev/v0/orgs/org/full-scans\n\n" |
| 55 | + f"Headers:\ncf-ray: abc123", |
| 56 | + status_code=status_code, |
| 57 | + ) |
| 58 | + |
| 59 | + |
| 60 | +@pytest.fixture |
| 61 | +def core_with_mock_sdk(): |
| 62 | + # Build a Core without running org setup; we only exercise create_full_scan. |
| 63 | + core = Core.__new__(Core) |
| 64 | + core.sdk = MagicMock() |
| 65 | + core.cli_config = None # skip the tier1 finalize branch |
| 66 | + return core |
| 67 | + |
| 68 | + |
| 69 | +@pytest.fixture(autouse=True) |
| 70 | +def no_sleep(mocker): |
| 71 | + return mocker.patch("socketsecurity.core.time.sleep") |
| 72 | + |
| 73 | + |
| 74 | +def test_upload_succeeds_first_try(core_with_mock_sdk, tmp_path, no_sleep): |
| 75 | + manifest = tmp_path / "package.json" |
| 76 | + manifest.write_text("{}") |
| 77 | + core_with_mock_sdk.sdk.fullscans.post.return_value = _success_response() |
| 78 | + |
| 79 | + full_scan = core_with_mock_sdk.create_full_scan([str(manifest)], MagicMock()) |
| 80 | + |
| 81 | + assert full_scan.id == "scan-1" |
| 82 | + assert core_with_mock_sdk.sdk.fullscans.post.call_count == 1 |
| 83 | + no_sleep.assert_not_called() |
| 84 | + |
| 85 | + |
| 86 | +def test_upload_retries_on_502_then_succeeds( |
| 87 | + core_with_mock_sdk, tmp_path, no_sleep, caplog |
| 88 | +): |
| 89 | + manifest = tmp_path / "package.json" |
| 90 | + manifest.write_text("{}") |
| 91 | + core_with_mock_sdk.sdk.fullscans.post.side_effect = [ |
| 92 | + APIBadGateway(), |
| 93 | + APIBadGateway(), |
| 94 | + _success_response(), |
| 95 | + ] |
| 96 | + |
| 97 | + with caplog.at_level(logging.WARNING, logger="socketdev"): |
| 98 | + full_scan = core_with_mock_sdk.create_full_scan([str(manifest)], MagicMock()) |
| 99 | + |
| 100 | + assert full_scan.id == "scan-1" |
| 101 | + assert core_with_mock_sdk.sdk.fullscans.post.call_count == 3 |
| 102 | + assert no_sleep.call_count == 2 # waits before attempts 2 and 3 |
| 103 | + retry_warnings = [r for r in caplog.records if "retrying in" in r.message] |
| 104 | + assert len(retry_warnings) == 2 |
| 105 | + assert "APIBadGateway" in retry_warnings[0].message |
| 106 | + assert f"(attempt 2/{FULL_SCAN_UPLOAD_MAX_ATTEMPTS})" in retry_warnings[0].message |
| 107 | + |
| 108 | + |
| 109 | +def test_upload_raises_after_exhausting_attempts( |
| 110 | + core_with_mock_sdk, tmp_path, no_sleep |
| 111 | +): |
| 112 | + manifest = tmp_path / "package.json" |
| 113 | + manifest.write_text("{}") |
| 114 | + core_with_mock_sdk.sdk.fullscans.post.side_effect = APIBadGateway() |
| 115 | + |
| 116 | + with pytest.raises(APIBadGateway): |
| 117 | + core_with_mock_sdk.create_full_scan([str(manifest)], MagicMock()) |
| 118 | + |
| 119 | + assert ( |
| 120 | + core_with_mock_sdk.sdk.fullscans.post.call_count |
| 121 | + == FULL_SCAN_UPLOAD_MAX_ATTEMPTS |
| 122 | + ) |
| 123 | + |
| 124 | + |
| 125 | +@pytest.mark.parametrize("status_code", [408, 503, 504]) |
| 126 | +def test_upload_retries_on_catch_all_transient_statuses( |
| 127 | + core_with_mock_sdk, tmp_path, no_sleep, status_code |
| 128 | +): |
| 129 | + manifest = tmp_path / "package.json" |
| 130 | + manifest.write_text("{}") |
| 131 | + core_with_mock_sdk.sdk.fullscans.post.side_effect = [ |
| 132 | + _catch_all_failure(status_code), |
| 133 | + _success_response(), |
| 134 | + ] |
| 135 | + |
| 136 | + full_scan = core_with_mock_sdk.create_full_scan([str(manifest)], MagicMock()) |
| 137 | + |
| 138 | + assert full_scan.id == "scan-1" |
| 139 | + assert core_with_mock_sdk.sdk.fullscans.post.call_count == 2 |
| 140 | + |
| 141 | + |
| 142 | +@pytest.mark.parametrize("error_class", [APIConnectionError, APITimeout]) |
| 143 | +def test_upload_retries_on_connection_level_errors( |
| 144 | + core_with_mock_sdk, tmp_path, no_sleep, error_class |
| 145 | +): |
| 146 | + manifest = tmp_path / "package.json" |
| 147 | + manifest.write_text("{}") |
| 148 | + core_with_mock_sdk.sdk.fullscans.post.side_effect = [ |
| 149 | + error_class(), |
| 150 | + _success_response(), |
| 151 | + ] |
| 152 | + |
| 153 | + full_scan = core_with_mock_sdk.create_full_scan([str(manifest)], MagicMock()) |
| 154 | + |
| 155 | + assert full_scan.id == "scan-1" |
| 156 | + assert core_with_mock_sdk.sdk.fullscans.post.call_count == 2 |
| 157 | + |
| 158 | + |
| 159 | +def test_upload_does_not_retry_on_400(core_with_mock_sdk, tmp_path, no_sleep): |
| 160 | + manifest = tmp_path / "package.json" |
| 161 | + manifest.write_text("{}") |
| 162 | + core_with_mock_sdk.sdk.fullscans.post.side_effect = _catch_all_failure(400) |
| 163 | + |
| 164 | + with pytest.raises(APIFailure): |
| 165 | + core_with_mock_sdk.create_full_scan([str(manifest)], MagicMock()) |
| 166 | + |
| 167 | + assert core_with_mock_sdk.sdk.fullscans.post.call_count == 1 |
| 168 | + no_sleep.assert_not_called() |
| 169 | + |
| 170 | + |
| 171 | +@pytest.mark.parametrize( |
| 172 | + "error_class,status_code", [(APIAccessDenied, 401), (APIResourceNotFound, 404)] |
| 173 | +) |
| 174 | +def test_upload_does_not_retry_on_dedicated_4xx_classes( |
| 175 | + core_with_mock_sdk, tmp_path, no_sleep, error_class, status_code |
| 176 | +): |
| 177 | + manifest = tmp_path / "package.json" |
| 178 | + manifest.write_text("{}") |
| 179 | + core_with_mock_sdk.sdk.fullscans.post.side_effect = error_class( |
| 180 | + status_code=status_code |
| 181 | + ) |
| 182 | + |
| 183 | + with pytest.raises(error_class): |
| 184 | + core_with_mock_sdk.create_full_scan([str(manifest)], MagicMock()) |
| 185 | + |
| 186 | + assert core_with_mock_sdk.sdk.fullscans.post.call_count == 1 |
| 187 | + no_sleep.assert_not_called() |
| 188 | + |
| 189 | + |
| 190 | +def test_upload_does_not_retry_on_error_payload(core_with_mock_sdk, tmp_path, no_sleep): |
| 191 | + # A response that came back but reports failure (res.success False) is not transient. |
| 192 | + manifest = tmp_path / "package.json" |
| 193 | + manifest.write_text("{}") |
| 194 | + failed = MagicMock() |
| 195 | + failed.success = False |
| 196 | + failed.message = "tarball too large" |
| 197 | + failed.status = 200 |
| 198 | + core_with_mock_sdk.sdk.fullscans.post.return_value = failed |
| 199 | + |
| 200 | + with pytest.raises(Exception, match="tarball too large"): |
| 201 | + core_with_mock_sdk.create_full_scan([str(manifest)], MagicMock()) |
| 202 | + |
| 203 | + assert core_with_mock_sdk.sdk.fullscans.post.call_count == 1 |
| 204 | + no_sleep.assert_not_called() |
| 205 | + |
| 206 | + |
| 207 | +def test_temp_br_file_survives_retries_and_is_cleaned_after( |
| 208 | + core_with_mock_sdk, tmp_path, no_sleep |
| 209 | +): |
| 210 | + # The brotli-compressed facts sibling must stay on disk across every retry attempt |
| 211 | + # (the SDK re-reads it per call) and only be deleted once all attempts finished. |
| 212 | + facts = tmp_path / SOCKET_FACTS_FILENAME |
| 213 | + facts.write_text('{"components": []}') |
| 214 | + compressed = tmp_path / SOCKET_FACTS_BROTLI_FILENAME |
| 215 | + br_present_per_attempt = [] |
| 216 | + |
| 217 | + def post_side_effect(upload_files, *args, **kwargs): |
| 218 | + br_present_per_attempt.append(compressed.is_file()) |
| 219 | + assert str(compressed) in upload_files |
| 220 | + if len(br_present_per_attempt) < 3: |
| 221 | + raise APIBadGateway() |
| 222 | + return _success_response() |
| 223 | + |
| 224 | + core_with_mock_sdk.sdk.fullscans.post.side_effect = post_side_effect |
| 225 | + |
| 226 | + full_scan = core_with_mock_sdk.create_full_scan([str(facts)], MagicMock()) |
| 227 | + |
| 228 | + assert full_scan.id == "scan-1" |
| 229 | + assert br_present_per_attempt == [True, True, True] |
| 230 | + assert not compressed.exists() # cleaned up after the attempts finished |
| 231 | + assert facts.is_file() # the original facts file is never touched |
| 232 | + |
| 233 | + |
| 234 | +def test_temp_br_file_cleaned_after_exhausted_retries( |
| 235 | + core_with_mock_sdk, tmp_path, no_sleep |
| 236 | +): |
| 237 | + facts = tmp_path / SOCKET_FACTS_FILENAME |
| 238 | + facts.write_text('{"components": []}') |
| 239 | + compressed = tmp_path / SOCKET_FACTS_BROTLI_FILENAME |
| 240 | + core_with_mock_sdk.sdk.fullscans.post.side_effect = APIBadGateway() |
| 241 | + |
| 242 | + with pytest.raises(APIBadGateway): |
| 243 | + core_with_mock_sdk.create_full_scan([str(facts)], MagicMock()) |
| 244 | + |
| 245 | + assert ( |
| 246 | + core_with_mock_sdk.sdk.fullscans.post.call_count |
| 247 | + == FULL_SCAN_UPLOAD_MAX_ATTEMPTS |
| 248 | + ) |
| 249 | + assert not compressed.exists() |
| 250 | + |
| 251 | + |
| 252 | +class _StubFailure(APIFailure): |
| 253 | + """An APIFailure whose transience is fixed, regardless of class or status code.""" |
| 254 | + |
| 255 | + def __init__(self, transient: bool): |
| 256 | + super().__init__("stub failure") |
| 257 | + self._transient = transient |
| 258 | + |
| 259 | + def is_transient_error(self) -> bool: |
| 260 | + return self._transient |
| 261 | + |
| 262 | + |
| 263 | +@pytest.mark.parametrize("transient,expected_calls", [(True, 2), (False, 1)]) |
| 264 | +def test_retry_decision_delegates_to_sdk_classification( |
| 265 | + core_with_mock_sdk, tmp_path, no_sleep, transient, expected_calls |
| 266 | +): |
| 267 | + # The CLI encodes no knowledge of the SDK's exception hierarchy or status codes: |
| 268 | + # the retry decision is exactly APIFailure.is_transient_error(). (The transient / |
| 269 | + # non-transient truth table itself is tested in the SDK, next to the code that |
| 270 | + # raises the exceptions.) |
| 271 | + manifest = tmp_path / "package.json" |
| 272 | + manifest.write_text("{}") |
| 273 | + core_with_mock_sdk.sdk.fullscans.post.side_effect = [ |
| 274 | + _StubFailure(transient), |
| 275 | + _success_response(), |
| 276 | + ] |
| 277 | + |
| 278 | + if transient: |
| 279 | + full_scan = core_with_mock_sdk.create_full_scan([str(manifest)], MagicMock()) |
| 280 | + assert full_scan.id == "scan-1" |
| 281 | + else: |
| 282 | + with pytest.raises(_StubFailure): |
| 283 | + core_with_mock_sdk.create_full_scan([str(manifest)], MagicMock()) |
| 284 | + |
| 285 | + assert core_with_mock_sdk.sdk.fullscans.post.call_count == expected_calls |
0 commit comments