diff --git a/CHANGELOG.md b/CHANGELOG.md index 72736ef..1bf56fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `ZeroBounceWarmup` errors reported on a 200 carry `status_code` 200: an HTML page (such as a proxy's "Access denied" page), a body that is not valid JSON, and a JSON body or empty body from `download_seeds` or `download_statistics`. Up to 3.0.1 their `status_code` was `None`. - `ZeroBounceWarmup.add_sending_account` parses `ignore_conflict` strictly, as `ZeroBounce` parses its boolean options: `True`/`False`, `"true"`/`"false"` (any case) and `1`/`0` are accepted, and anything else raises `ZBClientException("Invalid parameter: ignore_conflict must be true or false")` before a request is sent. Up to 3.0.1 the value went through `bool()`, so `ignore_conflict="false"` sent `true`. +### Security + +- `validate_batch` redacts the API key in its account-level error (an `"email_address": "all"` entry such as "Invalid API key "), as every other error is redacted. 3.0.1 raised that text unchanged. +- A body that is not valid JSON no longer keeps the JSON parser's error, which quotes the body (and any key in it), as the `__context__` of the `ZBApiException` raised for it, on `ZeroBounce` and `ZeroBounceWarmup`. Up to 3.0.1 the error was raised with `from None`, which hides the original from tracebacks but leaves it on `__context__`. + ## [3.0.1] - 2026-11-11 ### Fixed diff --git a/src/zerobouncesdk/zb_warmup.py b/src/zerobouncesdk/zb_warmup.py index 54bb4d0..1bd1111 100644 --- a/src/zerobouncesdk/zb_warmup.py +++ b/src/zerobouncesdk/zb_warmup.py @@ -119,9 +119,11 @@ def _json(self, method: str, path: str, *, params=None, json=None, secrets=()): try: return response.json() except ValueError: - raise ZBApiException( - self._redact(_message_from_body(body, response.status_code), secrets), status_code=response.status_code - ) from None + pass + # Raised outside the except block: the parser's error quotes the body, so it must not be the __context__. + raise ZBApiException( + self._redact(_message_from_body(body, response.status_code), secrets), status_code=response.status_code + ) def _csv(self, path: str, params=None, download_path: Optional[str] = None) -> str: response = self._send("GET", path, params=params) diff --git a/src/zerobouncesdk/zerobouncesdk.py b/src/zerobouncesdk/zerobouncesdk.py index ac4ad81..6d466f5 100644 --- a/src/zerobouncesdk/zerobouncesdk.py +++ b/src/zerobouncesdk/zerobouncesdk.py @@ -194,6 +194,9 @@ def _wire_bool(value, name: str) -> str: return "true" if _strict_bool(value, name) else "false" +# What a body that does not parse as JSON reads as, so the error is raised outside the except block. +_NOT_JSON = object() + # The keys a message-only body is made of. _MESSAGE_KEYS = ("error", "message", "error_message", "Message", "Error", "detail") @@ -360,7 +363,11 @@ def _read_json_payload(self, response, message_only_is_error: bool = False): try: payload = response.json() except ValueError: - raise ZBApiException(self._redact(_message_from_body(body, status)), status_code=status) from None + payload = _NOT_JSON + if payload is _NOT_JSON: + # Raised outside the except block: the parser's error quotes the body, so it must not be the + # __context__ (``from None`` only hides it from tracebacks). + raise ZBApiException(self._redact(_message_from_body(body, status)), status_code=status) if isinstance(payload, dict): title = payload.get("title") if isinstance(title, str) and payload.get("cloudflare_error") is True: @@ -943,8 +950,9 @@ def validate_batch( text = batch_error.error or "Invalid API Key or your account ran out of credits" if isinstance(text, str): text = _strip_error_prefix(text) - # Reported on an HTTP 200, like a dead key on the other calls. - raise ZBApiException(text, status_code=200) + # Reported on an HTTP 200, like a dead key on the other calls. The text comes from the body, + # which can quote the key. + raise ZBApiException(self._redact(text), status_code=200) return result def _send_file( @@ -1658,7 +1666,7 @@ def list_s3files( params=params, ) if isinstance(payload, dict) and payload.get("error"): - raise ZBApiException(payload["error"]) + raise ZBApiException(self._redact(payload["error"])) # Documented as {"success": true, "files": [{"Name", "Size", "LastModified"}]}. if isinstance(payload, dict) and isinstance(payload.get("files"), list): return payload["files"] diff --git a/tests/test_standard_parity_offline.py b/tests/test_standard_parity_offline.py index 828189b..ab0eeaf 100644 --- a/tests/test_standard_parity_offline.py +++ b/tests/test_standard_parity_offline.py @@ -1,9 +1,13 @@ """Behaviour every ZeroBounce SDK shares for the same API response (sdk-docs standard, section 3).""" +import inspect import io import json import os +import re import tempfile +import types +import typing from datetime import date from unittest import TestCase from unittest.mock import patch @@ -17,6 +21,7 @@ ZBGetFileOptions, ZBValidateBatchElement, ZeroBounce, + ZeroBounceWarmup, ) KEY = "parity-key" @@ -204,6 +209,122 @@ def test_anything_else_is_rejected_before_sending(self): self.assertEqual(self.server.requests, []) + +def _is_bool(annotation) -> bool: + if annotation is bool: + return True + if typing.get_origin(annotation) in (typing.Union, types.UnionType): + return set(typing.get_args(annotation)) == {bool, type(None)} + return False + + +class StrictBooleanSweepTest(ParityTestCase): + """Every boolean parameter of every public method is parsed strictly: ``"false"`` is never sent as true and + ``"junk"`` is rejected before a request. The parameters are found from the signatures, so a new boolean + parameter fails the completeness check until it is in the sweep.""" + + # Client-side switches that choose how a request is made, not API fields. + CLIENT_SWITCHES = {"use_post", "stream"} + D = "https://example.com/d" + + @staticmethod + def _stream(): + return io.BytesIO(b"email\na@example.com\n") + + def _calls(self): + """Each method with a boolean parameter: (positional args, keyword args) builders.""" + file_job = lambda: (("f.csv",), {"has_header_row": True, "return_url": self.D}) # noqa: E731 + calls = { + "validate": lambda: (("a@example.com",), {}), + "validate_batch": lambda: (([ZBValidateBatchElement("a@example.com")],), {}), + "send_file": lambda: ((__file__, 1), {}), + "send_file_stream": lambda: ((self._stream(), "f.csv", 1), {}), + "scoring_send_file": lambda: ((__file__, 1), {}), + "scoring_send_file_stream": lambda: ((self._stream(), "f.csv", 1), {}), + "send_email_finder_file": lambda: ((__file__, 1), {"first_name_column": 2}), + "send_email_finder_file_stream": lambda: ((self._stream(), "f.csv", 1), {"first_name_column": 2}), + "send_domain_search_file": lambda: ((__file__, 1), {}), + "send_domain_search_file_stream": lambda: ((self._stream(), "f.csv", 1), {}), + "Warmup.add_sending_account": lambda: (("a@example.com", "self_managed"), {"engagement_rule_id": 0}), + "Warmup.update_sending_account": lambda: (("a@example.com", 1, 1), {"auto_enable": False}), + } + for job in ("validate_s3file", "score_s3file", "email_finder_s3file", "domain_search_s3file", + "validate_sftpfile", "score_sftpfile", "email_finder_sftpfile", "domain_search_sftpfile"): + calls[job] = file_job + return calls + + def _booleans(self): + """{method: [boolean parameter names]} for every public method of both clients, from the signatures.""" + found = {} + for cls, prefix in ((ZeroBounce, ""), (ZeroBounceWarmup, "Warmup.")): + for name in dir(cls): + member = getattr(cls, name) + if name.startswith("_") or not callable(member) or inspect.isclass(member): + continue + names = [ + p.name for p in inspect.signature(member).parameters.values() + if _is_bool(p.annotation) and p.name not in self.CLIENT_SWITCHES + ] + if names: + found[prefix + name] = names + return found + + @staticmethod + def _sent(request, name): + """What a request sent for ``name`` (query, JSON body, form or multipart field), as a string.""" + fields = {k: v[0] for k, v in parse_qs(urlsplit(request.url).query).items()} + if name in fields: + return fields[name] + body = request.body or b"" + if isinstance(body, bytes): + body = body.decode("utf-8", "replace") + if body.startswith("{"): + value = json.loads(body).get(name) + return None if value is None else str(value).lower() + match = re.search(r'name="%s"\r\n(?:[^\r\n]+\r\n)*\r\n([^\r\n]*)' % re.escape(name), body) + if match: + return match.group(1) + return {k: v[0] for k, v in parse_qs(body).items()}.get(name) + + def test_the_sweep_covers_every_boolean_parameter(self): + self.assertEqual(set(self._booleans()), set(self._calls())) + + def test_the_library_parses_no_boolean_the_sweep_does_not_know(self): + source = "".join( + open(os.path.join(os.path.dirname(inspect.getfile(ZeroBounce)), f), encoding="utf-8").read() + for f in ("zerobouncesdk.py", "zb_warmup.py") + ) + parsed = set(re.findall(r"_(?:strict|wire)_bool\([^,]+,\s*\"(\w+)\"\)", source)) + known = {name for names in self._booleans().values() for name in names} + # activity_data on a download is a ZBGetFileOptions field, with its own test above. + self.assertTrue(parsed) + self.assertEqual(parsed - known, set()) + + def test_junk_is_rejected_and_false_is_never_sent_as_true(self): + client = ZeroBounce(KEY) + warmup = ZeroBounceWarmup(KEY) + server = self.serve('{"success":true,"address":"a@example.com","status":"valid","email_batch":[]}') + for method, names in self._booleans().items(): + target = getattr(warmup, method[len("Warmup."):]) if method.startswith("Warmup.") else getattr(client, method) + for name in names: + args, kwargs = self._calls()[method]() + before = len(server.requests) + with self.assertRaises(ZBClientException, msg=f"{method} took {name}='junk'") as caught: + target(*args, **{**kwargs, name: "junk"}) + self.assertIn(name, str(caught.exception)) + self.assertEqual(len(server.requests), before, f"{method} sent {name}='junk'") + + args, kwargs = self._calls()[method]() + try: + target(*args, **{**kwargs, name: "false"}) + except ZBClientException as error: + # A parameter that takes only True/False may reject the string. + self.assertIn(name, str(error)) + continue + self.assertGreater(len(server.requests), before, f"{method} sent nothing") + self.assertEqual(self._sent(server.requests[-1], name), "false", f"{method} {name}='false'") + + class PerApiBaseUrlTest(ParityTestCase): def test_trailing_slashes_on_per_api_base_urls_are_dropped(self): server = self.serve('{"success":true,"file_status":"Complete","file_id":"f1"}') diff --git a/tests/test_transport_guards_offline.py b/tests/test_transport_guards_offline.py index 6aef6e9..d4e7cbb 100644 --- a/tests/test_transport_guards_offline.py +++ b/tests/test_transport_guards_offline.py @@ -10,6 +10,7 @@ import socket import tempfile import threading +import traceback import warnings from datetime import timedelta from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -421,6 +422,29 @@ def refuse(path, mode="r", *args, **kwargs): self.client.get_file("f1", str(path)) self.assertEqual(path.read_bytes(), b"keep me\n") + def test_a_json_error_under_a_csv_content_type_is_not_saved(self): + # The content type says CSV, but the body is the API's JSON error: only the body tells them apart. + # Every download, streamed and not, found from the public methods. + downloads = sorted(name for name in _public(ZeroBounce) if name.endswith("get_file")) + self.assertEqual(set(downloads), set(self.downloads)) + bodies = ( + b'{"success": false, "message": "File cannot be found."}', + b' \n{"error": "File cannot be found."}', + ) + for body in bodies: + with patch("requests.sessions.Session.send", _file_reply(200, body, "text/csv")): + for name in downloads: + for stream in (False, True): + path = self.folder / f"{name}-{stream}.csv" + with self.assertRaises(ZBApiException, msg=f"{name} stream={stream} {body!r}") as caught: + getattr(self.client, name)("f1", str(path), stream=stream) + self.assertEqual(caught.exception.status_code, 200) + self.assertFalse(path.exists(), f"{name} saved a JSON error (stream={stream})") + self.assertEqual( + [p for p in self.folder.iterdir() if p.name.startswith(".zb-download-")], [], + f"{name} left a partial file", + ) + class WarmupCsvWriteTest(TestCase): """A Warmup CSV saved to download_path: a failed write must not leave a truncated file behind.""" @@ -496,3 +520,81 @@ def test_errors_and_other_calls_are_unchanged(self): with patch("requests.sessions.Session.send", _file_reply(204, b"", "text/plain")): with self.assertRaises(ZBApiException): ZeroBounce(KEY).get_inbox_placement_test(7) + + +class KeyEchoSweepTest(TestCase): + """A response body that quotes the key (an API message naming it, a proxy echoing the request URL, an HTML + title) never hands it to the caller: no error from any public method of either client carries it, in its + raw or URL-encoded form, in its message, repr, attributes, or its cause or context.""" + + ECHO_KEY = "echo+key/42" + ENCODED = "echo%2Bkey%2F42" + JSON = "application/json" + BODIES = { + '200 {"error"}': (200, JSON, '{"error":"Invalid API key %s"}' % ECHO_KEY), + '200 {"success":false}': (200, JSON, '{"success":false,"message":"Invalid API key %s"}' % ECHO_KEY), + '200 batch "all" error': ( + 200, JSON, '{"email_batch":[],"errors":[{"email_address":"all","error":"Invalid API key %s"}]}' % ECHO_KEY + ), + "200 HTML title": (200, "text/html", "Denied %s" % ECHO_KEY), + "200 JSON cut off": (200, JSON, '{"error":"Invalid API key %s"' % ECHO_KEY), + "400 text quoting the URL": (400, "text/plain", "Bad request: https://x.example/v2/x?api_key=" + ENCODED), + '400 {"error"}': (400, JSON, '{"error":"Invalid API key %s"}' % ECHO_KEY), + } + + def setUp(self): + self.answer = self.BODIES['200 {"error"}'] + self.server = LocalServer(lambda h: (self.answer[0], {"Content-Type": self.answer[1]}, self.answer[2].encode())) + self.addCleanup(self.server.close) + # Plain http to the loopback server; https is enforced by its own sweep. + patcher = patch("zerobouncesdk.zerobouncesdk._https_url", lambda url: url) + patcher.start() + self.addCleanup(patcher.stop) + self.folder = Path(tempfile.mkdtemp()) + self.out = str(self.folder / "out.csv") + + def _visible(self, error): + """Everything a caller or a traceback printer can read off the error, its cause and context included.""" + parts = ["".join(traceback.format_exception(type(error), error, error.__traceback__))] + seen = error + while seen is not None: + parts += [repr(seen), repr(seen.args), repr(vars(seen))] + seen = seen.__cause__ or seen.__context__ + return "\n".join(parts) + + def _sweep(self, calls, must_raise): + for label, answer in self.BODIES.items(): + self.answer = answer + for name, variants in calls.items(): + for call in variants: + try: + _quiet(call) + except Exception as error: # noqa: BLE001 - every error is checked + text = self._visible(error) + self.assertNotIn(self.ECHO_KEY, text, f"{name}: {label}") + self.assertNotIn(self.ENCODED, text, f"{name}: {label}") + else: + self.assertNotIn(label, must_raise, f"{name} returned for {label}") + self.assertEqual(list(self.folder.iterdir()), [], f"a file was saved for {label}") + + def test_every_client_request(self): + client = ZeroBounce(self.ECHO_KEY, timeout=timedelta(seconds=5)) + client._base_url = self.server.url + "/v2" + for attribute, path in _BASE_URL_ATTRIBUTES.items(): + setattr(client, attribute, self.server.url + path) + calls = client_calls(client, self.out) + self.assertEqual(_public(ZeroBounce, parity.HttpsSweepTest.NOT_REQUESTS) - set(calls), set()) + for name in [name for name in calls if name.endswith("get_file")]: + calls[name] = [ + lambda m=getattr(client, name): m("f1", self.out), + lambda m=getattr(client, name): m("f1", self.out, stream=True), + ] + # Each of these bodies is an error on every call of the client. + self._sweep(calls, must_raise=set(self.BODIES) - {'200 batch "all" error'}) + + def test_every_warmup_request(self): + warmup = ZeroBounceWarmup(self.ECHO_KEY, timeout=timedelta(seconds=5)) + warmup._root = self.server.url + ZeroBounceWarmup.BASE_PATH + calls = {name: [lambda c=call: c(warmup)] for name, call in warmup_calls(self.out).items()} + # A 200 JSON body is a Warmup result, whatever it says. + self._sweep(calls, must_raise={"200 HTML title", "200 JSON cut off", "400 text quoting the URL", '400 {"error"}'})