Skip to content

Give your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.

fix(v2ex): constrain TLS fallback boundary

Pnantc6808270046b
diff --git a/agent_reach/channels/v2ex.py b/agent_reach/channels/v2ex.py
index 6e7884fe..0b4c6967 100644
--- a/agent_reach/channels/v2ex.py
+++ b/agent_reach/channels/v2ex.py
@@ -7,6 +7,7 @@ import ssl
import subprocess
import urllib.request
from typing import Any
+from urllib.parse import urlsplit
from agent_reach.utils.process import utf8_subprocess_env
from agent_reach.utils.text import scrub_url_credentials
@@ -18,8 +19,27 @@ _TIMEOUT = 10
_MAX_RESPONSE_BYTES = 1024 * 1024
+def _validate_api_url(url: str) -> None:
+ """Allow only the public V2EX HTTPS JSON API."""
+ try:
+ parsed = urlsplit(url)
+ port = parsed.port
+ except ValueError as exc:
+ raise ValueError("invalid V2EX API URL") from exc
+ if (
+ parsed.scheme.lower() != "https"
+ or (parsed.hostname or "").lower() not in {"v2ex.com", "www.v2ex.com"}
+ or port not in {None, 443}
+ or parsed.username is not None
+ or parsed.password is not None
+ or not parsed.path.startswith("/api/")
+ ):
+ raise ValueError("only the V2EX HTTPS API is allowed")
+
+
def _get_json_with_urllib(url: str) -> Any:
"""Fetch JSON with Python's standard HTTP stack."""
+ _validate_api_url(url)
req = urllib.request.Request(url, headers={"User-Agent": _UA})
with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp:
raw = resp.read(_MAX_RESPONSE_BYTES + 1)
@@ -37,12 +57,15 @@ def _is_unexpected_tls_eof(error: BaseException) -> bool:
if id(current) in seen:
continue
seen.add(id(current))
- text = str(current).casefold()
- if (
- "unexpected_eof_while_reading" in text
- or "eof occurred in violation of protocol" in text
+ if isinstance(current, ssl.SSLError) and not isinstance(
+ current, ssl.SSLCertVerificationError
):
- return True
+ text = str(current).casefold()
+ if (
+ "unexpected_eof_while_reading" in text
+ or "eof occurred in violation of protocol" in text
+ ):
+ return True
for nested in (
getattr(current, "reason", None),
current.__cause__,
@@ -55,6 +78,7 @@ def _is_unexpected_tls_eof(error: BaseException) -> bool:
def _get_json_with_curl(url: str) -> Any:
"""Fetch bounded JSON with the OS curl TLS stack."""
+ _validate_api_url(url)
curl = shutil.which("curl")
if not curl:
raise RuntimeError("curl is unavailable for the V2EX TLS fallback")
@@ -64,7 +88,8 @@ def _get_json_with_curl(url: str) -> Any:
"--fail",
"--silent",
"--show-error",
- "--location",
+ "--proto",
+ "=https",
"--connect-timeout",
"5",
"--max-time",
diff --git a/tests/test_v2ex_channel.py b/tests/test_v2ex_channel.py
index cdf76b8f..7964fa81 100644
--- a/tests/test_v2ex_channel.py
+++ b/tests/test_v2ex_channel.py
@@ -74,6 +74,8 @@ def test_get_json_retries_unexpected_tls_eof_with_bounded_curl():
command = run.call_args.args[0]
assert command[0] == "C:/Windows/System32/curl.exe"
assert "--fail" in command
+ assert command[command.index("--proto") + 1] == "=https"
+ assert "--location" not in command
assert "--max-time" in command
assert "--max-filesize" in command
assert command[-2:] == [
@@ -97,6 +99,41 @@ def test_get_json_does_not_hide_certificate_verification_failures():
run.assert_not_called()
+def test_get_json_does_not_fallback_for_plain_error_text():
+ fake_error = RuntimeError(
+ "UNEXPECTED_EOF_WHILE_READING appeared in an unrelated message"
+ )
+
+ with patch.object(
+ v2, "_get_json_with_urllib", side_effect=fake_error
+ ), patch.object(v2.subprocess, "run") as run:
+ with pytest.raises(RuntimeError, match="unrelated"):
+ v2._get_json("https://www.v2ex.com/api/topics/hot.json")
+
+ run.assert_not_called()
+
+
+ "url",
+ [
+ "http://www.v2ex.com/api/topics/hot.json",
+ "https://v2ex.com.evil.test/api/topics/hot.json",
+ "https://user:[email protected]/api/topics/hot.json",
+ "https://www.v2ex.com:8443/api/topics/hot.json",
+ "https://www.v2ex.com/about",
+ ],
+)
+def test_get_json_rejects_non_api_targets_before_network(url):
+ with patch.object(v2.urllib.request, "urlopen") as urlopen, patch.object(
+ v2.subprocess, "run"
+ ) as run:
+ with pytest.raises(ValueError, match="V2EX HTTPS API"):
+ v2._get_json(url)
+
+ urlopen.assert_not_called()
+ run.assert_not_called()
+
+
def test_check_is_healthy_when_native_curl_recovers_tls_eof():
ch = V2EXChannel()
tls_error = ssl.SSLError(