# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause """Ensure broker-controlled data is never deserialized using pickle.""" import pickle import uuid from datetime import UTC, datetime, timedelta import pytest from flask import Flask from huey.utils import SKIPPED, Error from webmentions_ssg.tasks.extension import FlaskHuey from webmentions_ssg.tasks.json_serializer import TaggedJSONSerializer def test_json_is_default_even_for_production_style_broker(app: Flask) -> None: app.config["HUEY"] = {"immediate": False} huey = FlaskHuey(app) assert isinstance(huey.huey.serializer, TaggedJSONSerializer) assert huey.huey.serializer.serialize("hello") == b'"hello"' def test_uuid_and_retry_message_survive_enqueue_dequeue(app: Flask) -> None: app.config["HUEY"] = {"immediate": False} huey = FlaskHuey(app) identifier = uuid.uuid4() @huey.task(retries=2, retry_delay=50) def check(webmention_uuid: uuid.UUID) -> str: return str(webmention_uuid) task = check.s(identifier) task.eta = datetime.now(UTC) + timedelta(minutes=5) raw = huey.huey.serialize_task(task) assert raw.startswith(b'{"type":"message"') assert b"pickle" not in raw restored = huey.huey.deserialize_task(raw) assert restored.args == (identifier,) assert restored.eta == task.eta assert restored.retries == 2 assert restored.retry_delay == 50 huey.huey.enqueue(task) from_queue = huey.huey.dequeue() assert from_queue is not None assert from_queue.args == (identifier,) def test_result_and_error_data_roundtrip() -> None: serializer = TaggedJSONSerializer() identifier = uuid.uuid4() payload = { "ids": [identifier], "nested": ("str", None, 3), "error": Error({"error": "failed", "retries": 0}), "skipped": SKIPPED, "tag_collision": {"type": "uuid", "value": "not a UUID"}, } assert serializer.deserialize(serializer.serialize(payload)) == payload def test_rejects_pickle_payload() -> None: serializer = TaggedJSONSerializer() with pytest.raises((ValueError, UnicodeDecodeError)): serializer.deserialize(pickle.dumps({"untrusted": True})) def test_rejects_unknown_and_malformed_types() -> None: serializer = TaggedJSONSerializer() with pytest.raises(ValueError, match="Unsupported Huey JSON type"): serializer.deserialize(b'{"type":"arbitrary.class","value":{}}') with pytest.raises(ValueError, match="Invalid Huey JSON data"): serializer.deserialize(b'{"type":"uuid","value":"x","extra":1}') with pytest.raises(ValueError, match="Invalid Huey JSON message field count"): serializer.deserialize(b'{"type":"message","value":[]}') with pytest.raises(ValueError, match="Invalid non-finite JSON value"): serializer.deserialize(b"NaN") with pytest.raises(TypeError, match="Unsupported Huey JSON value"): serializer.serialize(object()) def test_refuses_unsafe_serializer_configuration(app: Flask) -> None: app.config["HUEY"] = {"serializer": None} with pytest.raises(RuntimeError, match="JSON is required"): FlaskHuey(app) def test_compression_with_json(app: Flask) -> None: app.config["HUEY"] = {"compression": True, "immediate": False} huey = FlaskHuey(app) payload = {"id": uuid.uuid4()} raw = huey.huey.serializer.serialize(payload) assert raw.startswith(b"\x1f\x8b") assert huey.huey.serializer.deserialize(raw) == payload @pytest.mark.parametrize( ("encoded", "expected_error", "message"), [ ( b'{"type":"error","value":"not metadata"}', TypeError, "Invalid Huey JSON error metadata", ), ( b'{"type":"dict","value":[["key",1],["key",2]]}', ValueError, "Duplicate Huey JSON dictionary key", ), ( b'{"type":"dict","value":[["key",1],[42,2]]}', ValueError, "Invalid Huey JSON dictionary entry", ), ], ) def test_rejects_invalid_huey_json_structure( encoded: bytes, expected_error: type[Exception], message: str ) -> None: with pytest.raises(expected_error, match=message): TaggedJSONSerializer().deserialize(encoded)