Skip to content

Commit 0014715

Browse files
Broaden header JSON parsing error hardening
Co-authored-by: Shri Sukhani <shrisukhani@users.noreply.github.com>
1 parent 6fa5065 commit 0014715

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

hyperbrowser/header_utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,9 @@ def parse_headers_env_json(raw_headers: Optional[str]) -> Optional[Dict[str, str
125125
return None
126126
try:
127127
parsed_headers = json.loads(raw_headers)
128-
except (json.JSONDecodeError, ValueError, RecursionError, TypeError) as exc:
128+
except HyperbrowserError:
129+
raise
130+
except Exception as exc:
129131
raise HyperbrowserError(
130132
"HYPERBROWSER_HEADERS must be valid JSON object",
131133
original_error=exc,

tests/test_header_utils.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,36 @@ def _raise_recursion_error(_raw_headers: str):
149149
assert exc_info.value.original_error is not None
150150

151151

152+
def test_parse_headers_env_json_wraps_unexpected_json_errors(
153+
monkeypatch: pytest.MonkeyPatch,
154+
):
155+
def _raise_runtime_error(_raw_headers: str):
156+
raise RuntimeError("unexpected json parser failure")
157+
158+
monkeypatch.setattr("hyperbrowser.header_utils.json.loads", _raise_runtime_error)
159+
160+
with pytest.raises(
161+
HyperbrowserError, match="HYPERBROWSER_HEADERS must be valid JSON object"
162+
) as exc_info:
163+
parse_headers_env_json('{"X-Trace-Id":"abc123"}')
164+
165+
assert exc_info.value.original_error is not None
166+
167+
168+
def test_parse_headers_env_json_preserves_hyperbrowser_json_errors(
169+
monkeypatch: pytest.MonkeyPatch,
170+
):
171+
def _raise_hyperbrowser_error(_raw_headers: str):
172+
raise HyperbrowserError("custom header json failure")
173+
174+
monkeypatch.setattr("hyperbrowser.header_utils.json.loads", _raise_hyperbrowser_error)
175+
176+
with pytest.raises(HyperbrowserError, match="custom header json failure") as exc_info:
177+
parse_headers_env_json('{"X-Trace-Id":"abc123"}')
178+
179+
assert exc_info.value.original_error is None
180+
181+
152182
def test_parse_headers_env_json_rejects_non_mapping_payload():
153183
with pytest.raises(
154184
HyperbrowserError,

0 commit comments

Comments
 (0)