Skip to content

The agent that grows with you

fix(image_gen): run the credential guard before probing a local Krea style reference

kshitijk4poor68655270c77e
diff --git a/plugins/image_gen/krea/__init__.py b/plugins/image_gen/krea/__init__.py
index 3049e026a73..2155022c9b8 100644
--- a/plugins/image_gen/krea/__init__.py
+++ b/plugins/image_gen/krea/__init__.py
@@ -317,30 +317,33 @@ def _collect_style_refs(
def _inline_local_style_refs(
- style_refs: List[Any], fail: ErrorFn
-) -> Tuple[List[Any], Optional[Dict[str, Any]]]:
+ style_refs: List[Dict[str, Any]], fail: ErrorFn
+) -> Tuple[List[Dict[str, Any]], Optional[Dict[str, Any]]]:
"""Embed local image files as data URIs; URLs and data URIs pass through unchanged."""
from agent.file_safety import raise_if_read_blocked
- inlined: List[Any] = []
+ inlined: List[Dict[str, Any]] = []
total_bytes = 0
for ref in style_refs:
- source = ref.get("url") if isinstance(ref, dict) else ref
+ source = ref.get("url")
if not isinstance(source, str) or source.lower().startswith(_REMOTE_REFERENCE_PREFIXES):
inlined.append(ref)
continue
path = Path(os.path.expanduser(source))
+ # Guard first: a denied path must not reveal whether it exists or how large it is.
+ try:
+ raise_if_read_blocked(str(path))
+ except ValueError as exc:
+ return [], fail(str(exc), "invalid_image_url")
if not path.is_file():
return [], fail(f"Style reference image not found: {source}", "invalid_image_url")
total_bytes += path.stat().st_size
if total_bytes > _MAX_LOCAL_REFERENCE_BYTES:
return [], fail(
- "Local style reference images total over 3 MB; resize them or pass public URLs",
- "source_too_large")
- raise_if_read_blocked(str(path))
+ f"Local style reference images total over {_MAX_LOCAL_REFERENCE_BYTES / 2**20:g} MB; "
+ "resize them or pass public URLs", "source_too_large")
mime = mimetypes.guess_type(path.name)[0] or "image/png"
- data_uri = f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode('ascii')}"
- inlined.append({**ref, "url": data_uri} if isinstance(ref, dict) else data_uri)
+ inlined.append({**ref, "url": f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode('ascii')}"})
return inlined, None
@@ -488,9 +491,6 @@ class KreaImageGenProvider(StaticImageGenProvider):
model_id, meta = _resolve_model(kwargs.get("model"))
creativity = _resolve_creativity(kwargs.get("creativity"))
fail = error_factory("krea", aspect, model=model_id, prompt=prompt)
- style_refs, err = _inline_local_style_refs(style_refs, fail)
- if err is not None:
- return err
payload = _build_payload(prompt, krea_ar, creativity, style_refs, kwargs)
# LoRAs/moodboards are rejected by the managed gateway: fail fast with guidance, not a raw 400.
@@ -501,6 +501,11 @@ class KreaImageGenProvider(StaticImageGenProvider):
f"Managed Krea (Nous Subscription) does not support {what}. "
f"Set KREA_API_KEY to use Krea directly, or omit `{arg}`.",
"unsupported_argument")
+ # After the fail-fast above, so a request about to be refused never reads local files.
+ if payload.get("image_style_references"):
+ payload["image_style_references"], err = _inline_local_style_refs(payload["image_style_references"], fail)
+ if err is not None:
+ return err
# 1. Submit job.
job_id, err = _submit_job(
diff --git a/tests/plugins/image_gen/test_krea_provider.py b/tests/plugins/image_gen/test_krea_provider.py
index a29b18c8ba6..eac2e0f0391 100644
--- a/tests/plugins/image_gen/test_krea_provider.py
+++ b/tests/plugins/image_gen/test_krea_provider.py
@@ -299,43 +299,28 @@ class TestGenerate:
expected = "data:image/png;base64," + base64.b64encode(image.read_bytes()).decode("ascii")
assert ref == {"url": expected, "strength": 0.6}
- def test_oversized_local_style_reference_is_refused_before_submit(self, tmp_path, monkeypatch):
- from plugins.image_gen import krea
-
- monkeypatch.setattr(krea, "_MAX_LOCAL_REFERENCE_BYTES", 4)
- image = tmp_path / "big.png"
- image.write_bytes(b"\x89PNG\r\n\x1a\n")
-
- with patch("plugins.image_gen.krea.requests.post") as mock_post:
- result = krea.KreaImageGenProvider().generate(prompt="test", image_url=str(image))
-
- assert result["error_type"] == "source_too_large"
- mock_post.assert_not_called()
-
- def test_local_style_references_are_limited_in_total_not_per_file(self, tmp_path, monkeypatch):
+ @pytest.mark.parametrize("case", ["missing", "total_over_limit", "credential_file"])
+ def test_unusable_local_style_references_are_refused_before_submit(self, case, tmp_path, monkeypatch):
+ """Refused with no request sent: a missing file, local files whose TOTAL (not each) exceeds the
+ cap, and a path the credential-read guard denies (refused before its existence is probed)."""
from plugins.image_gen import krea
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
monkeypatch.setattr(krea, "_MAX_LOCAL_REFERENCE_BYTES", 10)
- first = tmp_path / "a.png"
- second = tmp_path / "b.png"
- first.write_bytes(b"\x89PNG\r\n")
- second.write_bytes(b"\x89PNG\r\n")
+ for name in ("a.png", "b.png"):
+ (tmp_path / name).write_bytes(b"\x89PNG\r\n") # 6 bytes each: fits alone, not together
+ refs = {
+ "missing": [str(tmp_path / "nowhere.png")],
+ "total_over_limit": [str(tmp_path / "a.png"), str(tmp_path / "b.png")],
+ "credential_file": [str(tmp_path / ".env")], # absent on disk: the guard must answer first
+ }[case]
with patch("plugins.image_gen.krea.requests.post") as mock_post:
- result = krea.KreaImageGenProvider().generate(
- prompt="test", reference_image_urls=[str(first), str(second)])
+ result = krea.KreaImageGenProvider().generate(prompt="test", reference_image_urls=refs)
- assert result["error_type"] == "source_too_large"
- mock_post.assert_not_called()
-
- def test_missing_local_style_reference_is_refused_before_submit(self):
- from plugins.image_gen.krea import KreaImageGenProvider
-
- with patch("plugins.image_gen.krea.requests.post") as mock_post:
- result = KreaImageGenProvider().generate(
- prompt="test", reference_image_urls=["/nowhere/ref.png"])
-
- assert result["error_type"] == "invalid_image_url"
+ assert result["success"] is False
+ assert (result["error_type"] == "source_too_large") is (case == "total_over_limit")
+ assert ("not found" in result["error"]) is (case == "missing")
mock_post.assert_not_called()
def test_unknown_kwargs_ignored(self):