Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(gen): a refusal line ends with the provider's error body, keys and signatures masked
Soohong Kimf2b5bf5b49cb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 42f9536..ba492d0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,10 +4,11 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased (v2.12.0) - A refusal names the provider's code, and says when it was the content policy-- A provider refusal line now carries the provider's own code after the status: `openai-gen: image request failed (HTTP 400) code=invalid_value; no retry or provider fallback`. The code is `error.code` (or, for xAI's synchronous errors, a top-level `code`) and is printed only when it matches `^[A-Za-z0-9_.:-]{1,64}$`; the rest of the error body is still never printed on the image paths, since it can echo the prompt, a key or a signed URL. The video verbs read the code out of a failed poll's `error` object too.+- A provider refusal line now carries the provider's own code after the status: `openai-gen: image request failed (HTTP 400) code=invalid_value; no retry or provider fallback`. The code is `error.code` (or, for xAI's synchronous errors, a top-level `code`) and is printed only when it matches `^[A-Za-z0-9_.:-]{1,64}$`. The video verbs read the code out of a failed poll's `error` object too.+- The image paths now print the provider's error body too, as received, at the end of the line: `openai-gen: image request failed (HTTP 400) code=invalid_value; no retry or provider fallback: {"error": {...}}` (JSON on one line, other text with its line breaks as `\n`, nothing for an empty body; this includes 401/403). Before, the body was dropped and a failure was hard to diagnose. Two things are masked with `[redacted]`: strings shaped like an API key (`sk-…`, `xai-…`, a `Bearer` value, the credential the request carried; a key the provider already masked is left alone) and URL query strings, where signatures live. The video verbs, which already printed what xAI said, now go through the same mask. The body can repeat the prompt: a product that shows sprite-gen's stderr to its own users decides what to keep. Everything in front of the body is unchanged.- A code the provider documents as a content-policy block turns the line into `<verb>: refused by the provider's content policy (HTTP <n>) code=<code>; no retry or provider fallback`, so a caller can tell "change the request" from an auth, quota or parameter error by one fixed phrase. OpenAI's `moderation_blocked` is the only such code (the image guide calls `error.code` the stable discriminator); its `moderation_details.moderation_stage` follows as `moderation_stage=input|output|unknown`. xAI's `invalid_argument` is not one: it covers moderation and parameter errors alike.- An xAI clip that finishes with `video.respect_moderation: false` is now `<verb>: generation <id> refused by the provider's content policy (HTTP 200) respect_moderation=false; nothing was written` instead of "done but reported no video url". The xAI REST image answer has no moderation field, so a grok image refusal carries its code only.-- `(HTTP <n>)` is unchanged, so anything that finds the status with `\(HTTP (\d{3})\)` reads these lines as before. The policy table is `sprite_gen/gen/refusal.py` `POLICY_CODES`. Line shape: [docs/gen.md](docs/gen.md).+- `(HTTP <n>)` is unchanged, and the body comes after it and everything else, so anything that finds the status with `\(HTTP (\d{3})\)` reads these lines as before, whatever the body says. The policy table is `sprite_gen/gen/refusal.py` `POLICY_CODES`. Line shape: [docs/gen.md](docs/gen.md).## v2.11.0 - An attack is one strike, and its whole clip is the loopdiff --git a/docs/gen.md b/docs/gen.mdindex 1b9936d..aa3309f 100644--- a/docs/gen.md+++ b/docs/gen.md@@ -128,10 +128,9 @@ gpt-image models always answer with inline base64 (the API does not acceptforward. The payload is decoded, verified as a PNG and published atomically withoutresizing; a missing, malformed or multi-image response fails without replacing anexisting raw output. HTTP 401/403 names the credential; any other non-200 fails-with the status and the provider's code only — an error body can echo the prompt or-a key, so it is not printed.+with the status, the provider's code and the error body the provider sent.-A refusal line is `<verb>: <reason> (HTTP <n>)[ code=<code>][ key=value ...]; …`:+A refusal line is `<verb>: <reason> (HTTP <n>)[ code=<code>][ key=value ...]; …: <body>`:`code=` is the provider's `error.code` when it matches `^[A-Za-z0-9_.:-]{1,64}$`,and `<reason>` is `refused by the provider's content policy` when that code is adocumented policy block (`sprite_gen/gen/refusal.py` `POLICY_CODES`: openai@@ -140,6 +139,17 @@ documented policy block (`sprite_gen/gen/refusal.py` `POLICY_CODES`: openaireason, and a clip xAI reports with `respect_moderation: false` is that refusalwith `respect_moderation=false` in place of a code (docs/video.md).+`<body>` is the provider's error body as received, last on the line: JSON on one+line, anything else as its text (line breaks written as `\n`), nothing when the body+was empty. Two things in it are masked with `[redacted]` (`refusal.redact`): strings+shaped like an API key (`sk-…`, `xai-…`, a `Bearer` value, and the credential the+request carried; a key the provider already masked stays as it came) and the query+string of any URL, where a signature lives. The body can repeat the prompt, so a+product that shows sprite-gen's stderr to its own users decides what to cut there.+The video verbs print what xAI said the same way, through the same mask. Because the+body comes after everything else, nothing it says moves the status, reason or code+a caller reads off the front.+`--aspect-ratio` picks the `size`. gpt-image has no long-edge preset, so the ratiomaps to one concrete size out of a table that satisfies the documented constraints(both sides divisible by 16, ratio within 1:3..3:1, 655,360–8,294,400 pixels) and isdiff --git a/sprite_gen/gen/grok_provider.py b/sprite_gen/gen/grok_provider.pyindex 08857ab..bf95b74 100644--- a/sprite_gen/gen/grok_provider.py+++ b/sprite_gen/gen/grok_provider.py@@ -143,21 +143,23 @@ class GrokProvider:started = time.monotonic()status, reply = xai.http_json("POST", xai.API_BASE + endpoint, credential.token,body, timeout=GEN_TIMEOUT_SECONDS)- # Error bodies can include prompts, credentials or URLs; do not echo them.- # Only the provider's code leaves, format-checked. The REST image answer- # has no moderation field (docs.x.ai reference; a 2026-09-30 probe's items- # carried `b64_json` and `mime_type` only), so a code is all there is.+ # The provider's code goes in front, format-checked; the body it sent goes+ # last, as received, with keys and URL query strings masked (refusal.said).+ # The REST image answer has no moderation field (docs.x.ai reference; a+ # 2026-09-30 probe's items carried `b64_json` and `mime_type` only), so a+ # code is all there is to say why.refused = refusal.read(self.name, reply) if status != 200 else Noneif status in (401, 403):remedy = (f"run `{xai.GROK_LOGIN_COMMAND}` to renew the login" if credential.source == xai.AUTH_SOURCE_GROK_LOGINelse f"check {xai.AUTH_ENV}")- raise SystemExit(f"grok-gen: credential {credential.source} rejected (HTTP {status}){refused.suffix()}; {remedy}")+ raise SystemExit(f"grok-gen: credential {credential.source} rejected (HTTP {status}){refused.suffix()}; {remedy}"+ f"{refusal.said(reply, credential.token)}")# The one other thing worth naming is the combination the docs scope to# grok-imagine-image-2.0, which another model is entitled to reject.if refused is not None:scoped = f" (sent with {priced}, documented for {DEFAULT_MODEL})" if priced and body["model"] != DEFAULT_MODEL else ""raise SystemExit(f"grok-gen: {refused.reason('image request failed')} (HTTP {status}){refused.suffix()}; "- f"no retry or provider fallback{scoped}")+ f"no retry or provider fallback{scoped}{refusal.said(reply, credential.token)}")items = reply.get("data") if isinstance(reply, dict) else Noneif not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):raise SystemExit("grok-gen: expected exactly one image in the response; nothing published")diff --git a/sprite_gen/gen/openai_provider.py b/sprite_gen/gen/openai_provider.pyindex 1f23e3e..3152821 100644--- a/sprite_gen/gen/openai_provider.py+++ b/sprite_gen/gen/openai_provider.py@@ -228,7 +228,7 @@ def http_image(url: str, token: str, data: bytes, content_type: str, *, timeout:try:return exc.code, json.loads(raw)except json.JSONDecodeError:- return exc.code, {"raw": raw[:400]}+ return exc.code, refusal.RawBody(raw)except (urllib.error.URLError, TimeoutError, OSError) as exc:raise SystemExit("openai-gen: request failed or timed out; no automatic retry (the server may have accepted it)"@@ -288,18 +288,19 @@ class OpenAIProvider:)started = time.monotonic()status, reply = http_image(API_BASE + endpoint, token, data, content_type, timeout=GEN_TIMEOUT_SECONDS)- # Error bodies can echo the prompt, a key or a signed URL; do not print them.- # Only the provider's code (and the moderation stage) leave, format-checked.+ # The provider's code (and the moderation stage) go in front, format-checked;+ # the body the provider sent goes last, as received, with keys and URL+ # query strings masked (refusal.said).refused = _refusal(reply) if status != 200 else Noneif status in (401, 403):raise SystemExit(f"openai-gen: credential {AUTH_SOURCE_API_KEY} rejected (HTTP {status}){refused.suffix()}; "- f"check the key's value and that its project may call {fields['model']}"+ f"check the key's value and that its project may call {fields['model']}{refusal.said(reply, token)}")if refused is not None:raise SystemExit(f"openai-gen: {refused.reason('image request failed')} (HTTP {status}){refused.suffix()}; "- "no retry or provider fallback"+ f"no retry or provider fallback{refusal.said(reply, token)}")items = reply.get("data") if isinstance(reply, dict) else Noneif not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):diff --git a/sprite_gen/gen/refusal.py b/sprite_gen/gen/refusal.pyindex c895c5c..eb47d2a 100644--- a/sprite_gen/gen/refusal.py+++ b/sprite_gen/gen/refusal.py@@ -1,23 +1,28 @@# SPDX-License-Identifier: Apache-2.0-"""What a provider refusal line may say about why the provider refused.--Error bodies stay unprinted on the image paths: they can echo the prompt, a key or-a signed URL. The one field worth carrying out is the provider's own machine code-(`error.code`, which OpenAI's image guide calls the stable discriminator), and only-when it looks like an identifier — anything else could be prose from the body.+"""What a provider refusal line says about why the provider refused.The line shape is a contract other programs read:- <verb>: <reason> (HTTP <n>) code=<code>[ key=value ...]<tail>+ <verb>: <reason> (HTTP <n>)[ code=<code>][ key=value ...]<tail>: <body>`(HTTP <n>)` stays exactly that — callers find the provider status with-`\\(HTTP (\\d{3})\\)` — and `code=` follows it after one space. When the code is-one the provider documents as a content-policy block, `<reason>` is the fixed+`\\(HTTP (\\d{3})\\)` — and `code=` follows it after one space. The code is the+provider's own machine code (`error.code`, which OpenAI's image guide calls the+stable discriminator), and only when it looks like an identifier. When the code+is one the provider documents as a content-policy block, `<reason>` is the fixedmarker `CONTENT_POLICY`, so a caller can tell "change the request" from auth,quota or parameter errors without knowing any provider's vocabulary.++`<body>` is the provider's error body as received — JSON on one line, anything+else as its text — so an open-source tool shows the whole error and the product+that wraps it decides what its own users see. Only two things are masked+(`redact`): strings shaped like an API key (the credential the request carried+among them) and the query string of a URL, where a signature lives. The body comes last, so nothing in it can move what a caller+reads off the front of the line."""from __future__ import annotations+import jsonimport refrom dataclasses import dataclassfrom typing import Any@@ -26,6 +31,14 @@ CODE_PATTERN = re.compile(r"[A-Za-z0-9_.:-]{1,64}")CONTENT_POLICY = "refused by the provider's content policy"+# A key is a known prefix and a long run of key characters. One the provider+# already masked (`sk-proj-****…abcd`) carries `*` and is left as it came.+_KEY = re.compile(r"(?<![A-Za-z0-9_-])(sk|xai)-([A-Za-z0-9_*-]+)")+_KEY_MIN_LENGTH = 16+_BEARER = re.compile(r"(?i)\b(bearer\s+)[A-Za-z0-9._~+/=-]{16,}")+_URL_QUERY = re.compile(r"(?i)\b(https?://[^\s?#\"'<>\\]+)\?[^\s#\"'<>\\]*")+REDACTED = "[redacted]"+# Which provider codes are a content-policy block, per provider; the one table.# OpenAI images: `moderation_blocked` (developers.openai.com image-generation# guide, "Handling blocked requests", 2026-09-30). xAI has none: its documented@@ -39,6 +52,47 @@ POLICY_CODES: dict[str, frozenset[str]] = {}+class RawBody(dict):+ """An error body that was not JSON: `{"raw": text}` to the callers that read+ keys, and the text itself to `said`."""++ def __init__(self, text: str) -> None:+ super().__init__(raw=text)+ self.text = text+++def _key(match: re.Match[str]) -> str:+ rest = match.group(2)+ if "*" in rest or len(rest) < _KEY_MIN_LENGTH:+ return match.group(0)+ return f"{match.group(1)}-{REDACTED}"+++def redact(text: str, secret: str | None = None) -> str:+ """`text` with key-shaped strings and URL query strings masked; nothing else.++ `secret` is the credential the request was sent with: an echo of it is a key+ whatever its shape (a login token need not start with `sk-` or `xai-`).+ """+ if secret and len(secret) >= 8:+ text = text.replace(secret, REDACTED)+ text = _KEY.sub(_key, text)+ text = _BEARER.sub(lambda m: m.group(1) + REDACTED, text)+ return _URL_QUERY.sub(lambda m: f"{m.group(1)}?{REDACTED}", text)+++def said(body: Any, secret: str | None = None) -> str:+ """`: <body>` for the end of a refusal line — the body as received, on one+ line and redacted — or "" when the provider sent nothing."""+ if isinstance(body, RawBody):+ text = body.text.strip().replace("\r\n", "\n").replace("\r", "\n").replace("\n", "\\n")+ elif body in (None, {}, ""):+ text = ""+ else:+ text = json.dumps(body, ensure_ascii=False)+ return f": {redact(text, secret)}" if text else ""++def identifier(value: Any) -> str | None:"""`value` when it is a string shaped like a code, else None."""return value if isinstance(value, str) and CODE_PATTERN.fullmatch(value) else Nonediff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.pyindex f937a0d..feec578 100644--- a/sprite_gen/gen/video.py+++ b/sprite_gen/gen/video.py@@ -123,11 +123,13 @@ def _data_url(path: Path) -> str:return f"data:{mime};base64," + base64.b64encode(path.read_bytes()).decode("ascii")-def _error_detail(body: Any) -> str:+def _error_detail(body: Any, secret: str | None = None) -> str:+ # What the provider said, with keys and URL query strings masked — the same+ # mask the image lines use (refusal.redact).if not isinstance(body, dict):- return str(body)[:300]+ return refusal.redact(str(body)[:300], secret)parts = [f"{key}={body[key]!r}" for key in ("code", "error", "message", "status", "raw") if body.get(key)]- return ", ".join(parts) if parts else json.dumps(body)[:300]+ return refusal.redact(", ".join(parts) if parts else json.dumps(body)[:300], secret)def _redact_host(url: str) -> str | None:@@ -402,7 +404,7 @@ def _submit_poll_publish(status, reply = call("POST", f"{API_BASE}/videos/{endpoint}", credential.token, body)if status in (401, 403):raise SystemExit(- f"{verb}: xAI rejected the credential ({credential.source}) with HTTP {status}: {_error_detail(reply)}\n"+ f"{verb}: xAI rejected the credential ({credential.source}) with HTTP {status}: {_error_detail(reply, credential.token)}\n"+ (f" the grok login token may have been revoked or rotated — run `{GROK_REFRESH_COMMAND}` {GROK_REFRESH_WHERE} or `{GROK_LOGIN_COMMAND}`."if credential.source == AUTH_SOURCE_GROK_LOGIN@@ -413,7 +415,7 @@ def _submit_poll_publish(if status not in (200, 202) or not request_id:refused = refusal.read("grok", reply)raise SystemExit(- f"{verb}: {refused.reason('generation request refused')} (HTTP {status}){refused.suffix()}: {_error_detail(reply)}"+ f"{verb}: {refused.reason('generation request refused')} (HTTP {status}){refused.suffix()}: {_error_detail(reply, credential.token)}")deadline = time.monotonic() + (POLL_TIMEOUT_SECONDS if poll_timeout is None else poll_timeout)@@ -446,7 +448,7 @@ def _submit_poll_publish(refused = refusal.read("grok", poll)raise SystemExit(f"{verb}: generation {request_id} {refused.reason(f'ended with status={poll_status!r}')} "- f"(HTTP {http}){refused.suffix()}: {_error_detail(poll)}"+ f"(HTTP {http}){refused.suffix()}: {_error_detail(poll, credential.token)}")if time.monotonic() >= deadline:raise SystemExit(diff --git a/sprite_gen/gen/xai.py b/sprite_gen/gen/xai.pyindex a857a56..564bc28 100644--- a/sprite_gen/gen/xai.py+++ b/sprite_gen/gen/xai.py@@ -16,6 +16,8 @@ from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Callable+from . import refusal+API_BASE = "https://api.x.ai/v1"AUTH_ENV = "XAI_API_KEY"AUTH_SOURCE_API_KEY = "XAI_API_KEY"@@ -147,6 +149,6 @@ def http_json(method: str, url: str, token: str, body: dict | None = None, *, titry:return exc.code, json.loads(raw)except json.JSONDecodeError:- return exc.code, {"raw": raw[:400]}+ return exc.code, refusal.RawBody(raw)except (urllib.error.URLError, TimeoutError, OSError) as exc:raise SystemExit("xai: request failed or timed out; no automatic retry (the server may have accepted it)") from excdiff --git a/tests/gen/test_grok_provider.py b/tests/gen/test_grok_provider.pyindex f777112..8a4744e 100644--- a/tests/gen/test_grok_provider.py+++ b/tests/gen/test_grok_provider.py@@ -103,12 +103,14 @@ def test_direct_output_keeps_chroma_pipeline(tmp_path, api):@pytest.mark.parametrize("status", [400, 401, 403, 429, 500])def test_api_failure_keeps_existing_output_and_does_not_retry(tmp_path, api, status):- api.update(status=status, body={"error": "synthetic-secret https://signed.invalid/private"})+ api.update(status=status, body={"error": "synthetic-secret https://signed.invalid/private?sig=abc"})out = tmp_path / "existing.png"out.write_bytes(b"existing")with pytest.raises(SystemExit, match=f"HTTP {status}") as error:gen.generate_image("grok", "x", out)- assert "synthetic-secret" not in str(error.value)+ # The body is shown; the key the request carried and the URL's signature are not.+ assert "synthetic-secret" not in str(error.value) and "sig=abc" not in str(error.value)+ assert '"error": "[redacted] https://signed.invalid/private?[redacted]"' in str(error.value)assert out.read_bytes() == b"existing"assert len(api["calls"]) == 1@@ -313,7 +315,7 @@ def test_the_declared_subsets_are_the_servers_own_enums():assert set(grok.SUPPORTED_RESOLUTIONS) <= set(gen_base.RESOLUTIONS)-# --- refusal lines: the provider code, never the body -----------------------------+# --- refusal lines: the provider code in front, the body as received last ---------@pytest.mark.parametrize("body, suffix", [({"error": {"code": "invalid_argument", "message": "synthetic-secret"}}, " code=invalid_argument"),@@ -327,11 +329,26 @@ def test_a_refused_image_names_the_provider_code_only(tmp_path, api, body, suffiapi.update(status=400, body=body)with pytest.raises(SystemExit) as error:gen.generate_image("grok", "x", tmp_path / "out.png")- assert str(error.value) == f"grok-gen: image request failed (HTTP 400){suffix}; no retry or provider fallback"+ assert str(error.value) == (f"grok-gen: image request failed (HTTP 400){suffix}; no retry or provider fallback: "+ + json.dumps(body).replace("synthetic-secret", "[redacted]"))def test_a_rejected_credential_names_the_code_too(tmp_path, api):api.update(status=401, body={"code": "unauthenticated:bad-credentials", "error": "synthetic-secret"})with pytest.raises(SystemExit) as error:gen.generate_image("grok", "x", tmp_path / "out.png")- assert str(error.value) == "grok-gen: credential XAI_API_KEY rejected (HTTP 401) code=unauthenticated:bad-credentials; check XAI_API_KEY"+ assert str(error.value) == ("grok-gen: credential XAI_API_KEY rejected (HTTP 401) code=unauthenticated:bad-credentials; "+ 'check XAI_API_KEY: {"code": "unauthenticated:bad-credentials", "error": "[redacted]"}')+++def test_an_xai_key_and_a_signed_url_in_the_body_are_masked(tmp_path, api):+ xai_key = "xai-" + "Synthetic0Key1For2Tests3Only4" * 3+ api.update(status=400, body={"code": "invalid-argument",+ "error": f"bad key {xai_key} at https://x.invalid/v?token=abc and (HTTP 999) code=decoy"})+ with pytest.raises(SystemExit) as error:+ gen.generate_image("grok", "x", tmp_path / "out.png")+ assert str(error.value) == (+ "grok-gen: image request failed (HTTP 400) code=invalid-argument; no retry or provider fallback: "+ '{"code": "invalid-argument", "error": "bad key xai-[redacted] at https://x.invalid/v?[redacted] '+ 'and (HTTP 999) code=decoy"}'+ )diff --git a/tests/gen/test_openai_provider.py b/tests/gen/test_openai_provider.pyindex b50810d..d918890 100644--- a/tests/gen/test_openai_provider.py+++ b/tests/gen/test_openai_provider.py@@ -176,13 +176,14 @@ def test_reference_edit_posts_multipart_images_in_order(tmp_path, api):@pytest.mark.parametrize("status", [400, 401, 403, 429, 500])def test_api_failure_keeps_existing_output_and_does_not_retry(tmp_path, api, status):- api.update(status=status, body={"error": {"message": f"{KEY} https://signed.invalid/private"}})+ api.update(status=status, body={"error": {"message": f"{KEY} https://signed.invalid/private?sig=abc"}})out = tmp_path / "existing.png"out.write_bytes(b"existing")with pytest.raises(SystemExit, match=f"HTTP {status}") as error:gen.generate_image("openai", "x", out)- assert KEY not in str(error.value)- assert "signed.invalid" not in str(error.value)+ # The body is shown; the key the request carried and the URL's signature are not.+ assert KEY not in str(error.value) and "sig=abc" not in str(error.value)+ assert "https://signed.invalid/private?[redacted]" in str(error.value)assert out.read_bytes() == b"existing"assert len(api["calls"]) == 1@@ -360,14 +361,16 @@ HTTP_STATUS = re.compile(r"\(HTTP (\d{3})\)") # what a caller reads the statusdef _refused(tmp_path, api, status, error):- api.update(status=status, body={"error": {"message": f"{KEY} synthetic prompt echo", **error}})+ """The line in front of the body; the body itself must follow it as sent."""+ api.update(status=status, body={"error": {"message": "synthetic prompt echo", **error}})with pytest.raises(SystemExit) as refused:gen.generate_image("openai", "x", tmp_path / "out.png")message = str(refused.value)- assert KEY not in message and "prompt echo" not in message+ body = ": " + json.dumps(api["body"], ensure_ascii=False)+ assert message.endswith(body) and "\n" not in messageassert HTTP_STATUS.search(message).group(1) == str(status)assert len(api["calls"]) == 1- return message+ return message[: -len(body)]@pytest.mark.parametrize("details, stage", [@@ -404,10 +407,89 @@ def test_a_top_level_code_is_not_the_openai_error_code(tmp_path, api):api.update(status=400, body={"code": "moderation_blocked", "error": {"message": "x"}})with pytest.raises(SystemExit) as refused:gen.generate_image("openai", "x", tmp_path / "out.png")- assert str(refused.value) == "openai-gen: image request failed (HTTP 400); no retry or provider fallback"+ assert str(refused.value) == ("openai-gen: image request failed (HTTP 400); no retry or provider fallback: "+ '{"code": "moderation_blocked", "error": {"message": "x"}}')def test_a_rejected_key_names_the_code_too(tmp_path, api):assert _refused(tmp_path, api, 401, {"code": "invalid_api_key"}).startswith("openai-gen: credential OPENAI_API_KEY rejected (HTTP 401) code=invalid_api_key; check the key's value")+++# --- the body the provider sent: shown as received, keys and signatures masked ----++# Synthetic, shaped like the real thing: a project key, an xAI key, a key the+# provider already masked, a bearer header and a signed URL.+PROJECT_KEY = "sk-proj-" + "Synthetic0Key1For2Tests3Only4" * 2+XAI_KEY = "xai-" + "Synthetic0Key1For2Tests3Only4" * 3+MASKED_KEY = "sk-proj-" + "*" * 20 + "ab12"+BEARER = "Bearer " + "synthetic.token.value-0123456789"+SIGNED = "https://files.example.invalid/img/out.png?X-Signature=0a1b2c&Expires=1"+++def _line(tmp_path, api, status, body):+ api.update(status=status, body=body)+ with pytest.raises(SystemExit) as refused:+ gen.generate_image("openai", "x", tmp_path / "out.png")+ return str(refused.value)+++def test_the_body_follows_the_line_as_received_on_one_line(tmp_path, api):+ body = {"error": {"message": "Your request was rejected by the safety system.\n요청이 거절됐어요.",+ "type": "image_generation_user_error", "param": None, "code": "moderation_blocked",+ "moderation_details": {"moderation_stage": "output", "categories": ["other"]}}}+ assert _line(tmp_path, api, 400, body) == (+ "openai-gen: refused by the provider's content policy (HTTP 400) code=moderation_blocked "+ "moderation_stage=output; no retry or provider fallback: " + json.dumps(body, ensure_ascii=False)+ )+++def test_keys_and_url_query_strings_are_masked_and_nothing_else(tmp_path, api):+ said = (f"key {PROJECT_KEY} or {XAI_KEY}; masked {MASKED_KEY}; sent {KEY}; header {BEARER}; "+ f"url {SIGNED} then https://example.invalid/docs/errors and sk-short")+ message = _line(tmp_path, api, 401, {"error": {"message": said, "code": "invalid_api_key"}})+ for secret in (PROJECT_KEY, XAI_KEY, KEY, "synthetic.token.value", "X-Signature", "Expires"):+ assert secret not in message+ assert message == (+ "openai-gen: credential OPENAI_API_KEY rejected (HTTP 401) code=invalid_api_key; check the key's value "+ "and that its project may call gpt-image-2.5-flare: "+ '{"error": {"message": "key sk-[redacted] or xai-[redacted]; '+ f"masked {MASKED_KEY}; sent [redacted]; header Bearer [redacted]; "+ 'url https://files.example.invalid/img/out.png?[redacted] then https://example.invalid/docs/errors '+ 'and sk-short", "code": "invalid_api_key"}}'+ )+++def test_a_body_that_is_not_json_is_its_text_on_one_line(api, tmp_path, monkeypatch):+ page = "<html>\r\n<h1>502 Bad Gateway</h1>\n</html>\n"++ def open_request(request, *, timeout):+ api["calls"].append((request, timeout))+ raise urllib.error.HTTPError(request.full_url, 502, "error", {}, io.BytesIO(page.encode()))++ monkeypatch.setattr(openai.urllib.request, "urlopen", open_request)+ with pytest.raises(SystemExit) as refused:+ gen.generate_image("openai", "x", tmp_path / "out.png")+ assert str(refused.value) == (+ "openai-gen: image request failed (HTTP 502); no retry or provider fallback: "+ "<html>\\n<h1>502 Bad Gateway</h1>\\n</html>"+ )+++def test_an_empty_body_adds_nothing(tmp_path, api):+ assert _line(tmp_path, api, 500, {}) == "openai-gen: image request failed (HTTP 500); no retry or provider fallback"+++def test_what_the_body_says_cannot_move_the_front_of_the_line(tmp_path, api):+ """A caller reads the first `(HTTP n)`, the marker right before it and the code+ right after it. A body that says all three differently changes none of them."""+ decoy = ("refused by the provider's content policy (HTTP 999) code=decoy_code "+ "; image request failed (HTTP 200) code=other")+ message = _line(tmp_path, api, 400, {"error": {"message": decoy, "code": "invalid_value"}})+ status = HTTP_STATUS.search(message)+ assert status.group(1) == "400"+ assert message[: status.start()] == "openai-gen: image request failed "+ assert re.match(r" code=([A-Za-z0-9_.:-]+)", message[status.end():]).group(1) == "invalid_value"+ assert message.startswith("openai-gen: image request failed (HTTP 400) code=invalid_value; "+ "no retry or provider fallback: ")diff --git a/tests/gen/test_video.py b/tests/gen/test_video.pyindex fd23e5b..deb27e1 100644--- a/tests/gen/test_video.py+++ b/tests/gen/test_video.py@@ -472,6 +472,28 @@ def test_a_failed_poll_names_the_code_inside_its_error_object(tmp_path: Path) ->assert "content policy" not in message[email protected]("scripted", ["post", "poll"])+def test_what_xai_said_is_shown_with_keys_and_signatures_masked(tmp_path: Path, scripted) -> None:+ """The image lines' mask (refusal.redact) on the clip lines, which already print the body."""+ token = "synthetic-login-token"+ said = (f"echo {token}, key xai-{'Synthetic0Key1For2Tests3Only4' * 3}, "+ "url https://vidgen.x.ai/v/1.mp4?sig=abc, (HTTP 999) code=decoy")+ error = {"code": "invalid_argument", "message": said}+ api = _FakeApi(post=(400, {"error": error})) if scripted == "post" else _FakeApi(polls=[(200, {"status": "failed", "error": error})])+ request = _request(tmp_path)+ with pytest.raises(SystemExit) as refused:+ video.generate_video(request, credential=video.Credential(token, video.AUTH_SOURCE_GROK_LOGIN),+ call=api.call, download=api.download, sleep=lambda s: None)+ message = str(refused.value)+ front = ("video: generation request refused (HTTP 400) code=invalid_argument: " if scripted == "post"+ else "video: generation req-1 ended with status='failed' (HTTP 200) code=invalid_argument: ")+ # A query runs to the next space or quote, so the comma after it goes too.+ assert message == front + ("error={'code': 'invalid_argument', 'message': 'echo [redacted], key xai-[redacted], "+ "url https://vidgen.x.ai/v/1.mp4?[redacted] (HTTP 999) code=decoy'}"+ + ("" if scripted == "post" else ", status='failed'"))+ assert HTTP_STATUS.search(message).group(1) == ("400" if scripted == "post" else "200")++@pytest.mark.parametrize(("post", "prefix"), [((400, {"code": "invalid-argument", "error": "synthetic"}), "video: generation request refused (HTTP 400) code=invalid-argument: "),((400, {"error": {"code": "invalid_argument", "message": "synthetic"}}), "video: generation request refused (HTTP 400) code=invalid_argument: "),