Repository navigation
Studio: reject binary web_search fetches instead of decoding them into replacement chars #7130
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 13 commits
2e21aed
e392343
75dfba2
9fcbc1a
71fbfd2
ef43072
c4404dd
c5902a6
1059285
1bfd582
14dca24
76de937
4eb1283
c7fbec2
3b7bebe
29e6ffe
f8296d3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,6 +5,7 @@ | |
| (DuckDuckGo), Python code execution, and terminal commands.""" | ||
|
|
||
| import ast | ||
| import codecs | ||
| import fnmatch | ||
| import http.client | ||
| import os | ||
|
|
@@ -3581,6 +3582,64 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di | |
| # sections stripped during conversion; 512 KB reaches article content even | ||
| # where <head> alone is ~200 KB. | ||
| _MAX_FETCH_BYTES = 512 * 1024 | ||
| # Undecodable bytes and controls, excluding text whitespace and ESC for ANSI logs. | ||
| # More than 12.5% is binary after allowing 16 minor encoding glitches. | ||
| _BINARY_CHAR_RE = re.compile("[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1a\\x1c-\\x1f\\x7f-\\x9f\\ufffd]") | ||
| _MIN_BINARY_CHARS = 16 | ||
| _BINARY_CHAR_DIVISOR = 8 | ||
| # Common binary signatures that can otherwise look text-heavy when mislabeled. | ||
| _BINARY_MAGIC = ( | ||
| b"%PDF-", # PDF | ||
| b"PK\x03\x04", # zip / docx / xlsx / pptx / epub / jar | ||
| b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1", # OLE / legacy Office | ||
| b"\x89PNG\r\n\x1a\n", # PNG | ||
| b"\xff\xd8\xff", # JPEG | ||
| b"GIF87a", | ||
| b"GIF89a", | ||
| b"\x1f\x8b", # gzip | ||
| b"BZh", # bzip2 | ||
| b"\xfd7zXZ\x00", # xz | ||
| b"\x28\xb5\x2f\xfd", # zstd | ||
| ) | ||
|
|
||
| # Check UTF-32 first because its little-endian BOM starts with the UTF-16 BOM. | ||
| _UNICODE_BOM_CODECS = ( | ||
| (codecs.BOM_UTF32_LE, "utf-32"), | ||
| (codecs.BOM_UTF32_BE, "utf-32"), | ||
| (codecs.BOM_UTF16_LE, "utf-16"), | ||
| (codecs.BOM_UTF16_BE, "utf-16"), | ||
| (codecs.BOM_UTF8, "utf-8-sig"), | ||
| ) | ||
|
|
||
| # A cp1252 retry needs 75% ASCII structure so it cannot rescue high-byte binary. | ||
| _MIN_SINGLE_BYTE_ASCII_RATIO = 3 / 4 | ||
| _ASCII_TEXT_BYTES = frozenset((*range(0x20, 0x7F), 0x09, 0x0A, 0x0D, 0x1B)) | ||
|
|
||
|
|
||
| def _looks_binary(text: str) -> bool: | ||
| """Whether control or undecodable characters exceed the binary threshold.""" | ||
| return len(_BINARY_CHAR_RE.findall(text)) > max( | ||
| _MIN_BINARY_CHARS, len(text) // _BINARY_CHAR_DIVISOR | ||
| ) | ||
|
|
||
|
|
||
| def _has_binary_magic(data: bytes) -> bool: | ||
| """Whether a common binary signature follows optional BOM or whitespace.""" | ||
| head = data[:1024].lstrip() | ||
| for bom, _codec in _UNICODE_BOM_CODECS: | ||
| if head.startswith(bom): | ||
| head = head.removeprefix(bom).lstrip() | ||
| break | ||
| return head.startswith(_BINARY_MAGIC) | ||
|
|
||
|
|
||
| def _has_single_byte_text_evidence(data: bytes) -> bool: | ||
| """True when *data* has enough ASCII structure for a cp1252 text retry.""" | ||
| if not data: | ||
| return True | ||
| ascii_text_bytes = sum(byte in _ASCII_TEXT_BYTES for byte in data) | ||
| return ascii_text_bytes / len(data) >= _MIN_SINGLE_BYTE_ASCII_RATIO | ||
|
|
||
|
|
||
| _USER_AGENTS = ( | ||
| "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", | ||
|
|
@@ -3682,6 +3741,42 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, str | |
| return True, "", first_ip | ||
|
|
||
|
|
||
| # Known binary application subtypes are rejected by MIME type. Unknown | ||
| # application types are sniffed so textual artifacts such as SQL remain usable. | ||
| _BINARY_APPLICATION_SUBTYPES = frozenset( | ||
| { | ||
| "epub+zip", | ||
| "gzip", | ||
| "java-archive", | ||
| "pdf", | ||
| "vnd.apple.installer+xml", | ||
| "wasm", | ||
| "x-7z-compressed", | ||
| "x-bzip2", | ||
| "x-gzip", | ||
| "x-rar-compressed", | ||
| "x-tar", | ||
| "x-xz", | ||
| "zip", | ||
| "zstd", | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| def _is_text_candidate_content_type(content_type: str | None) -> bool: | ||
| """Whether a MIME type is textual or ambiguous enough for byte sniffing.""" | ||
| match = re.match(r"[\w.+-]+/[\w.+-]+", content_type or "") | ||
| if not match: | ||
| return True | ||
| ct = match.group(0).lower() | ||
| if ct.startswith("text/"): | ||
| return True | ||
| if ct.startswith("application/"): | ||
| subtype = ct[len("application/") :] | ||
| return subtype not in _BINARY_APPLICATION_SUBTYPES | ||
| return False | ||
|
|
||
|
|
||
| def _fetch_page_text( | ||
| url: str, | ||
| max_chars: int = _MAX_PAGE_CHARS, | ||
|
|
@@ -3762,8 +3857,39 @@ def _fetch_page_text( | |
| else: | ||
| return "Failed to fetch URL: too many redirects." | ||
|
|
||
| charset = resp.headers.get_content_charset() or "utf-8" | ||
| raw_html = raw_bytes.decode(charset, errors = "replace") | ||
| # Reject MIME types known to be binary before decoding. | ||
| content_type = resp.headers.get_content_type() | ||
| if not _is_text_candidate_content_type(content_type): | ||
| # Only echo a clean MIME token back to the model. | ||
| m = re.match(r"[\w.+-]+/[\w.+-]+", content_type or "") | ||
| safe_type = m.group(0) if m else "unknown type" | ||
| return f"(non-text content: {safe_type}, {len(raw_bytes)} bytes; not readable as text)" | ||
|
|
||
| # Catch text-labeled binary whose header and first chunk look textual. | ||
| if _has_binary_magic(raw_bytes): | ||
| return f"(binary content, {len(raw_bytes)} bytes; not readable as text)" | ||
|
|
||
| declared = resp.headers.get_content_charset() | ||
| declared_codec = codecs.lookup(declared).name if declared else None | ||
| bom_codec = next( | ||
| (codec for bom, codec in _UNICODE_BOM_CODECS if raw_bytes.startswith(bom)), | ||
| None, | ||
| ) | ||
| raw_html = raw_bytes.decode(declared or bom_codec or "utf-8", errors = "replace") | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a response declares Useful? React with 👍 / 👎.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Declining this: it is the direct inverse of the earlier review that (correctly) flagged the same gate for dropping legitimate dense-accented Latin-1 text. The ASCII-ratio signal cannot separate dense Latin-1 text from high-byte Latin-1 binary (byte-identical), so gating declared Latin-1/cp1252 regresses real text. This path requires a server mislabeling binary as iso-8859-1 text, matches pre-PR behavior (not a regression), and any true binary is already bounded by the MIME, magic-byte, and control-density guards. Leaving declared single-byte responses to decode and keep. |
||
|
|
||
| # Catch mislabeled or unlabeled binary, including valid UTF-8 controls. | ||
| if _looks_binary(raw_html): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
For responses declared as Useful? React with 👍 / 👎.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in c7fbec2: the ASCII-structure gate now also applies to declared iso-8859-1/windows-1252 decodes, so high-byte binary mislabeled as Latin-1 is rejected. Scoped to the Latin family so legitimate non-Latin single-byte pages (Cyrillic, Greek) with dense high bytes are not dropped. Verified against a full declared-encoding matrix.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. On reflection this is reverted (3b7bebe). The only available signal (ASCII ratio) cannot separate dense-accented Latin-1 text from high-byte binary, so gating declared Latin-1/cp1252 regressed legitimate text (see the follow-up review). The mislabeled-binary-as-Latin-1 case matches pre-PR behavior and is already bounded by the MIME, magic-byte, and control-density guards, so the declared single-byte path is left to decode and keep. |
||
| # Rescue undeclared cp1252 only when the bytes have text structure. | ||
| alt = ( | ||
| raw_bytes.decode("cp1252", "replace") | ||
| if declared_codec in (None, "iso8859-1") | ||
| and _has_single_byte_text_evidence(raw_bytes) | ||
| else None | ||
|
oobabooga marked this conversation as resolved.
Resolved
|
||
| ) | ||
| if alt is not None and not _looks_binary(alt): | ||
| raw_html = alt | ||
|
oobabooga marked this conversation as resolved.
Resolved
|
||
| else: | ||
| return f"(binary content, {len(raw_bytes)} bytes; not readable as text)" | ||
| except _HTTPError as e: | ||
| return f"Failed to fetch URL: HTTP {e.code} {getattr(e, 'reason', '')}" | ||
| except Exception as e: | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.