Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-13100 Bound gzip decompression in browser recording processing (#7985)
Aaron Perez1ab4455d23d2
diff --git a/skyvern/services/browser_recording/service.py b/skyvern/services/browser_recording/service.pyindex a605b9f56..4f32b0756 100644--- a/skyvern/services/browser_recording/service.py+++ b/skyvern/services/browser_recording/service.py@@ -71,9 +71,41 @@ LOG = structlog.get_logger(__name__)# avoid decompression bombsMAX_BASE64_SIZE = 14 * 1024 * 1024 # ~10MB compressed + base64 overhead+# Cap decompressed output per chunk. The compressed input is already bounded to ~10MB, so this+# allows a generous ~10x expansion for legitimate recordings while rejecting bombs that would+# otherwise inflate to gigabytes and exhaust process memory on a shared host.+MAX_DECOMPRESSED_SIZE = 100 * 1024 * 1024 # 100MBDEFAULT_DRAFT_ACTION_TITLE = "Browser Action"+def _gunzip_bounded(compressed_data: bytes, max_output_size: int) -> bytes | None:+ """Gzip-decompress `compressed_data`, returning None once the output would exceed+ `max_output_size`.++ The bound is enforced incrementally via zlib's ``max_length`` so a decompression bomb+ aborts mid-stream and never materializes its full output in memory. Raises ``zlib.error``+ on malformed input, matching a raw ``zlib.decompress`` call.+ """+ decompressor = zlib.decompressobj(wbits=16 + zlib.MAX_WBITS)+ output = bytearray()+ pending = compressed_data++ while pending:+ # +1 so an output that exactly fills the budget stays distinguishable from an overflow.+ output.extend(decompressor.decompress(pending, max_output_size - len(output) + 1))+ if len(output) > max_output_size:+ return None+ pending = decompressor.unconsumed_tail++ # unconsumed_tail is empty, so all input was consumed within the budget; flush only drains+ # zlib's small internal buffer and cannot reintroduce an unbounded amount of output.+ output.extend(decompressor.flush())+ if len(output) > max_output_size:+ return None++ return bytes(output)++@functools.lru_cache(maxsize=None)def _resolve_enrichment_handler(key: str) -> LLMAPIHandler | None:"""Resolve the dedicated enrichment handler for `key`, or None if it isn't registered.@@ -224,19 +256,24 @@ class Processor:return Nonetry:- # gzip decompression -> bytes+ # gzip decompression -> bytes, bounded to MAX_DECOMPRESSED_SIZE.#- # NOTE(llm): We use zlib.decompress with wbits=16 + zlib.MAX_WBITS (31).- # This tells zlib to automatically detect and handle Gzip headers,- # which is essential since the browser used CompressionStream('gzip').- # Using zlib is often faster than the higher-level gzip module for this- # purpose.- decompressed_bytes: bytes = zlib.decompress(compressed_data, wbits=16 + zlib.MAX_WBITS)+ # NOTE(llm): wbits=16 + zlib.MAX_WBITS (31) tells zlib to detect and handle Gzip+ # headers, which is essential since the browser used CompressionStream('gzip').+ decompressed_bytes = _gunzip_bounded(compressed_data, MAX_DECOMPRESSED_SIZE)except zlib.error as e:LOG.warning(f"{self.class_name} decompression error: {e}", **self.identity)# Log the error, maybe log the first few characters of the payload for debuggingreturn None+ if decompressed_bytes is None:+ LOG.warning(+ f"{self.class_name}: decompressed payload exceeded {MAX_DECOMPRESSED_SIZE} bytes; "+ "rejecting suspected decompression bomb",+ **self.identity,+ )+ return None+return decompressed_bytesdef serialize(self, decompressed_bytes: bytes | None) -> list[dict[str, t.Any]]:diff --git a/tests/unit/services/test_browser_recording.py b/tests/unit/services/test_browser_recording.pyindex bd6c99b7a..b83ae356b 100644--- a/tests/unit/services/test_browser_recording.py+++ b/tests/unit/services/test_browser_recording.py@@ -3,8 +3,11 @@ Just an example unit test for now. Will expand later."""import asyncio+import base64+import gzipimport timeimport typing as t+import zlibimport pytest@@ -20,6 +23,7 @@ from skyvern.services.browser_recording.interpretation import RecordingInterpretfrom skyvern.services.browser_recording.service import (DUPLICATE_ACTION_WINDOW_MS,Processor,+ _gunzip_bounded,_is_duplicate_action,_recording_enrichment_llm_handler,_resolve_enrichment_handler,@@ -827,3 +831,56 @@ def test_summarize_exfiltrated_recording_events_mixed() -> None:assert summary["recording_exfil_cdp_event_name_counts"] == {"nav:frame_navigated": 2}assert summary["recording_exfil_console_dom_type_counts"] == {"click": 1, "keypress": 1}assert summary["recording_exfil_console_exfil_event_name_counts"] == {"user_interaction": 2}+++def test_gunzip_bounded_returns_full_payload_under_limit() -> None:+ payload = b"hello world" * 500+ compressed = gzip.compress(payload)++ assert _gunzip_bounded(compressed, len(payload)) == payload+++def test_gunzip_bounded_allows_output_exactly_at_limit() -> None:+ payload = b"A" * 4096+ compressed = gzip.compress(payload)++ assert _gunzip_bounded(compressed, len(payload)) == payload+++def test_gunzip_bounded_rejects_output_over_limit() -> None:+ payload = b"A" * 4096+ compressed = gzip.compress(payload)++ assert _gunzip_bounded(compressed, len(payload) - 1) is None+++def test_gunzip_bounded_rejects_decompression_bomb() -> None:+ # ~32 MiB of zeros compresses to a few KiB; the bound must reject it long before+ # the full output would be materialized in memory.+ bomb = gzip.compress(b"\x00" * (32 * 1024 * 1024))+ assert len(bomb) < 1 * 1024 * 1024++ assert _gunzip_bounded(bomb, 1024) is None+++def test_gunzip_bounded_raises_on_corrupt_input() -> None:+ with pytest.raises(zlib.error):+ _gunzip_bounded(b"not a valid gzip stream", 1024)+++def test_decompress_rejects_bomb(monkeypatch: pytest.MonkeyPatch) -> None:+ import skyvern.services.browser_recording.service as svc++ monkeypatch.setattr(svc, "MAX_DECOMPRESSED_SIZE", 1024)+ processor = Processor(PBS_ID, ORG_ID, WP_ID)+ bomb = base64.b64encode(gzip.compress(b"\x00" * (10 * 1024 * 1024))).decode("ascii")++ assert processor.decompress(bomb) is None+++def test_decompress_returns_bytes_for_valid_payload() -> None:+ processor = Processor(PBS_ID, ORG_ID, WP_ID)+ raw = b'[{"source": "cdp", "event_name": "nav:frame_navigated"}]'+ payload = base64.b64encode(gzip.compress(raw)).decode("ascii")++ assert processor.decompress(payload) == raw