HKUDS/Vibe-Trading · error · ValueError
invalid base64 payload
Error message
invalid base64 payload
What it means
save_base64_data_url decodes the payload with base64.b64decode(payload, validate=True), which rejects any non-alphabet characters. binascii.Error (or ValueError) from the decoder is re-raised as ValueError('invalid base64 payload'), preserving the original as __cause__.
Source
Thrown at agent/src/utils/media_decode.py:57
The path of the decoded file.
Raises:
FileSizeExceeded: If decoded data exceeds ``max_bytes``.
ValueError: If the URL is malformed or uses an unsupported MIME type.
"""
match = _DATA_URL_RE.match(data_url)
if not match:
raise ValueError("expected data:<mime>;base64,<payload>")
mime = match.group(1).strip().lower()
ext = _EXT_BY_MIME.get(mime)
if not ext:
raise ValueError(f"unsupported data URL MIME type: {mime}")
payload = match.group(3).strip()
try:
decoded = base64.b64decode(payload, validate=True)
except (binascii.Error, ValueError) as exc:
raise ValueError("invalid base64 payload") from exc
if max_bytes and len(decoded) > max_bytes:
raise FileSizeExceeded(f"decoded media exceeds {max_bytes} bytes")
output_dir.mkdir(parents=True, exist_ok=True)
path = output_dir / f"{uuid.uuid4().hex}{ext}"
path.write_bytes(decoded)
return path
View on GitHub (pinned to 80ffdda44c)
Solutions
- Validate/normalize the payload: strip whitespace, restore padding with '=' to a multiple of 4
- If the source uses URL-safe alphabet, translate '-_' to '+/' before passing
- Send base64 in the request body (not query params) so '+' survives transport
- Check payload length % 4 == 0 before calling
Example fix
# before
path = save_base64_data_url(data_url, out_dir) # URL-safe base64 payload
# after
import re
header, _, payload = data_url.partition(',')
payload = payload.strip().replace('-', '+').replace('_', '/')
payload += '=' * (-len(payload) % 4)
path = save_base64_data_url(f"{header},{payload}", out_dir) Defensive patterns
Strategy: validation
Validate before calling
import base64
def is_valid_base64_payload(data_url: str) -> bool:
payload = data_url.split(",", 1)[1].strip() if "," in data_url else ""
if not payload or len(payload) % 4 != 0:
return False
try:
base64.b64decode(payload, validate=True)
return True
except Exception:
return False Type guard
def is_standard_base64(payload: str) -> bool:
import re
p = payload.strip()
return bool(re.fullmatch(r"[A-Za-z0-9+/]+={0,2}", p)) and len(p) % 4 == 0 Try / catch
try:
path = save_base64_data_url(data_url, out_dir)
except ValueError as e:
if str(e) == "invalid base64 payload":
return reject_attachment("attachment data corrupted in transit")
raise Prevention
- Transport base64 in JSON bodies, never in URL query strings
- Normalize URL-safe base64 ('-_' -> '+/') and restore '=' padding before sending
- Add a checksum (e.g. SHA-256) alongside large payloads to detect truncation
When it happens
Trigger: Payloads containing URL-safe characters ('-','_') instead of standard base64, missing '=' padding, embedded newlines/whitespace in the middle, corrupted transfer truncating the string, or '+' or '/' mangled to spaces by URL form encoding.
Common situations: Base64 passed through a query string unescaped ( '+' becomes ' '), URL-safe base64 from another library, JSON truncation of very large payloads, or copy-paste artifacts (smart quotes, ellipses).
Related errors
- expected data:<mime>;base64,<payload>
- invalid alpha_id
- alpha_id not found
- invalid period: {exc}
- too many running benches; wait for one to finish
AI-assisted analysis of HKUDS/Vibe-Trading@80ffdda44c (2026-08-28).
Data as JSON: /api/errors/5f37299fa8c87a8a.
Report an issue: GitHub.