知らない分野を、原文にたどりつくまで芋づる式に掘る Claude Code のスキル
Python
fix: watch.py で gzip で返すフィードを読む
MaryCachedc8ab904c66c
diff --git a/skills/imozuru/scripts/watch.py b/skills/imozuru/scripts/watch.pyindex f64a631..af7e366 100644--- a/skills/imozuru/scripts/watch.py+++ b/skills/imozuru/scripts/watch.py@@ -37,6 +37,7 @@ import urllib.parseimport urllib.requestimport xml.etree.ElementTree as ETfrom pathlib import Path+import zlibfrom xml.parsers import expatUA = {"User-Agent": "Mozilla/5.0 imozuru-watch"}@@ -116,6 +117,13 @@ def fetch_final(url: str) -> tuple[bytes, str, str]:body = res.read(MAX_BYTES + 1)if len(body) > MAX_BYTES:raise ValueError(f"本体が {MAX_BYTES:,} バイトを超える")+ # DeepMind のブログは頼まなくても gzip で返す。展開した後の大きさにも上限を置く+ # (小さな gzip が何 GB にも膨らむ爆弾で、メモリを使い切らないように)+ if res.headers.get("Content-Encoding", "").lower() == "gzip":+ inflater = zlib.decompressobj(16 + zlib.MAX_WBITS)+ body = inflater.decompress(body, MAX_BYTES + 1)+ if len(body) > MAX_BYTES:+ raise ValueError(f"展開した本体が {MAX_BYTES:,} バイトを超える")return body, res.headers.get("Content-Type", ""), res.geturl()diff --git a/tests/test_security.py b/tests/test_security.pyindex 42e9fc1..523cb42 100644--- a/tests/test_security.py+++ b/tests/test_security.py@@ -287,6 +287,29 @@ class FeedTests(unittest.TestCase):self.assertEqual(watch.cmd_add(Path(tmp), "https://a.example/", None), 1)self.assertFalse((Path(tmp) / "watch.tsv").exists())+ def gzip_response(self, body):+ res = MagicMock()+ res.read.return_value = body+ res.headers = {"Content-Encoding": "gzip"}+ res.geturl.return_value = "https://a.example/feed"+ res.__enter__.return_value = res+ return res++ def test_gzip_feed_is_inflated(self):+ import gzip+ feed = b'<?xml version="1.0"?><rss><channel><item><title>t</title></item></channel></rss>'+ with patch.object(watch, "resolve", lambda host: {PUBLIC_IP}), \+ patch.object(watch._OPENER, "open", return_value=self.gzip_response(gzip.compress(feed))):+ self.assertEqual(watch.fetch("https://a.example/feed")[0], feed)++ def test_gzip_bomb_is_refused(self):+ import gzip+ bomb = gzip.compress(b"\0" * (watch.MAX_BYTES * 10))+ with patch.object(watch, "resolve", lambda host: {PUBLIC_IP}), \+ patch.object(watch._OPENER, "open", return_value=self.gzip_response(bomb)):+ with self.assertRaises(ValueError):+ watch.fetch("https://a.example/feed")+def test_short_rows_are_skipped(self):with tempfile.TemporaryDirectory() as tmp:(Path(tmp) / "watch.tsv").write_text("site\tonly-two\nsite\tok\thttps://a.example/feed\n", encoding="utf-8")