diff --git a/flow-agent/flow_agent/api.py b/flow-agent/flow_agent/api.py
index cc5bad3..cd37de2 100644
--- a/flow-agent/flow_agent/api.py
+++ b/flow-agent/flow_agent/api.py
@@ -10,16 +10,18 @@
import base64
import json
+import mimetypes
import time
from pathlib import Path
from typing import Any, Optional
+from urllib.parse import urlsplit
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
-from fastapi.responses import FileResponse, StreamingResponse
-from pydantic import BaseModel, ConfigDict, Field
+from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
+from pydantic import BaseModel, ConfigDict, Field, field_validator
-from .engine import EngineError, FlowEngine
+from .engine import EngineError, FlowEngine, clean_model
app = FastAPI(
title="flow-agent",
@@ -39,7 +41,6 @@
# OpenAI's image sizes, and the aspect each one means.
-#
# The pairs are not invented here: OpenAI's three sizes are 1:1, 3:2 and 2:3, and
# the Flow ratios that match are square, landscape and portrait. The two extra
# entries are Flow's own 4:3 and 3:4, which have no OpenAI size and are reachable
@@ -50,6 +51,8 @@
"1024x1792": "9:16",
"1365x1024": "4:3",
"1024x1365": "3:4",
+ "512x512": "1:1",
+ "256x256": "1:1",
# The aliases a caller may use instead of pixels.
"square": "1:1",
"landscape": "16:9",
@@ -75,23 +78,43 @@ class ImageGenerationRequest(BaseModel):
model_config = ConfigDict(extra="allow")
prompt: str
- model: str = "narwhal"
+ model: str = "beluga"
n: int = Field(default=1, ge=1, le=4)
size: str = "1024x1024"
- response_format: str = "url"
+ response_format: str = Field(
+ default="url",
+ description=(
+ "Response format. 'url' is the OpenAI default and what an unmodified "
+ "SDK expects: JSON carrying a fetchable link. 'image' streams the raw "
+ "bytes back for inline preview or download in a browser; 'b64_json' "
+ "inlines the bytes in JSON."
+ ),
+ )
# Flow-specific, ignored by OpenAI clients.
all_accounts: bool = False
cookies: Optional[str] = None
+ @field_validator("model", mode="before")
+ @classmethod
+ def sanitize_model(cls, v: Any) -> str:
+ # Swagger UI fills an untouched field with the literal text `string`.
+ return clean_model(v)
+
class FlowImageRequest(BaseModel):
prompt: str
aspect: str = "1:1"
count: int = Field(default=1, ge=1, le=4)
- model: str = "narwhal"
+ model: str = "beluga"
all_accounts: bool = False
cookies: Optional[str] = None
+ @field_validator("model", mode="before")
+ @classmethod
+ def sanitize_model(cls, v: Any) -> str:
+ # Swagger UI fills an untouched field with the literal text `string`.
+ return clean_model(v)
+
class FlowVideoRequest(BaseModel):
prompt: str
@@ -128,14 +151,58 @@ class ChatCompletionRequest(BaseModel):
# --------------------------------------------------------------------------- #
-def _media_url(request: Request, path: str) -> str:
- """The URL a client can fetch one generated file from.
+#: The characters a `host[:port]` may be built from: a DNS name, an IPv4 literal,
+#: a bracketed IPv6 literal, or an underscore in an internal hostname. `@`, `\`
+#: and `%` are absent on purpose - a userinfo `@` makes the host read as a
+#: credential, and a browser normalises `\` to `/`.
+_AUTHORITY_CHARS = frozenset(
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-:[]_"
+)
- Built from the request's own base URL rather than a hardcoded host, so the
- response is correct whether this is reached on localhost, a LAN address or
- behind a proxy.
+
+def _base_url(request: Request) -> str:
+ """The scheme and authority to build a URL for this request from.
+
+ Taken from the request's own base URL rather than a hardcoded host, so the
+ answer is right whether this is reached on localhost, a LAN address or behind
+ a proxy. `X-Forwarded-Proto` and `X-Forwarded-Host` are what a reverse proxy
+ rewrites, so they are honoured - but they are also caller-supplied strings on
+ their way into a response body, and a URL in a response is followed by
+ whoever asked for it. A forwarded pair is therefore used only when it
+ assembles into a bare `scheme://host[:port]`: no path, no query, no
+ credentials. Anything else falls back to this framework's own base URL.
"""
- return f"{str(request.base_url).rstrip('/')}/api/v1/media/{Path(path).name}"
+ proto = request.headers.get("x-forwarded-proto", "").strip().lower()
+ if proto not in ("http", "https"):
+ # A proxy that forwards the host but not the scheme is the ordinary
+ # case rather than an error, so the scheme falls back on its own instead
+ # of discarding a host that is perfectly usable.
+ proto = request.url.scheme
+
+ host = (request.headers.get("x-forwarded-host") or request.headers.get("host") or "").strip()
+ forwarded = f"{proto}://{host}" if host else ""
+
+ try:
+ parts = urlsplit(forwarded)
+ except ValueError:
+ # A malformed authority (an unclosed IPv6 bracket, say) is not usable.
+ return str(request.base_url).rstrip("/")
+
+ if (
+ parts.scheme in ("http", "https")
+ and parts.netloc
+ and set(parts.netloc) <= _AUTHORITY_CHARS
+ and not parts.path
+ and not parts.query
+ and not parts.fragment
+ ):
+ return f"{parts.scheme}://{parts.netloc}"
+ return str(request.base_url).rstrip("/")
+
+
+def _media_url(request: Request, path: str) -> str:
+ """The URL a client can fetch one generated file from."""
+ return f"{_base_url(request)}/api/v1/media/{Path(path).name}"
def _no_image_detail(result: dict) -> str:
@@ -260,9 +327,47 @@ async def frames():
# --------------------------------------------------------------------------- #
-@app.post("/v1/images/generations")
+@app.post(
+ "/v1/images/generations",
+ responses={
+ 200: {
+ "content": {
+ "application/json": {},
+ "image/png": {},
+ "image/jpeg": {},
+ },
+ "description": "OpenAI-shaped JSON, or the image file itself for inline preview",
+ }
+ },
+)
+@app.post(
+ "/api/v1/images/generations",
+ responses={
+ 200: {
+ "content": {
+ "application/json": {},
+ "image/png": {},
+ "image/jpeg": {},
+ },
+ "description": "OpenAI-shaped JSON, or the image file itself for inline preview",
+ }
+ },
+)
async def openai_images(payload: ImageGenerationRequest, request: Request):
- """Generate an image from an OpenAI images payload."""
+ """Generate an image from an OpenAI images payload.
+
+ `response_format` decides how the bytes come back:
+
+ - `image` (also `file`, `binary`, `raw`, `preview`): the image file itself,
+ streamed, so Swagger UI or a plain browser can show or save it at once.
+ - `url` (the default): OpenAI's own shape, JSON carrying a download URL a
+ client on another machine can fetch.
+ - `b64_json`: the bytes inlined as a base64 string.
+
+ The declared types list PNG as well as JPEG because the type of a streamed
+ file is read from the file itself, so whichever one the engine wrote is the
+ one the client is told.
+ """
aspect = SIZE_TO_ASPECT.get(payload.size.strip().lower())
if aspect is None:
raise HTTPException(
@@ -285,6 +390,30 @@ async def openai_images(payload: ImageGenerationRequest, request: Request):
except EngineError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
+ files = result.get("files") or []
+ if not files:
+ raise HTTPException(status_code=502, detail=_no_image_detail(result))
+
+ fmt = (payload.response_format or "").strip().lower()
+
+ # Hand the bytes back untouched: this is the branch a browser and Swagger UI
+ # use to show the image and its download button.
+ if fmt in ("image", "file", "binary", "raw", "preview"):
+ first_file = files[0].get("path")
+ if first_file:
+ img_path = Path(first_file)
+ if img_path.is_file():
+ # Read the type off the file, the same rule the media route
+ # above uses. A hardcoded `image/jpeg` mislabels a PNG, and a
+ # client that trusts the label saves the file instead of
+ # showing it - the one thing this branch exists to do.
+ media_type = mimetypes.guess_type(img_path.name)[0] or "application/octet-stream"
+ return FileResponse(
+ img_path,
+ media_type=media_type,
+ filename=img_path.name,
+ )
+
payload_out = _image_payload(request, result, payload.response_format)
# A run that produced nothing is not a success. Returning 200 with an empty
# `data` would tell an OpenAI client the request worked and there simply
@@ -335,10 +464,15 @@ async def openai_chat(payload: ChatCompletionRequest, request: Request):
@app.post("/v1/generate/image")
@app.post("/v1/image")
@app.post("/api/v1/image")
-async def flow_image(payload: FlowImageRequest):
- """Generate an image, speaking the engine's own vocabulary."""
+async def flow_image(payload: FlowImageRequest, request: Request):
+ """Generate an image, speaking the engine's own vocabulary.
+
+ Each entry in `files` is also given a `url` a client can fetch directly, so
+ a caller on a different machine from this process does not have to be told
+ where the file was written.
+ """
try:
- return await engine.generate_image(
+ result = await engine.generate_image(
prompt=payload.prompt,
aspect=payload.aspect,
count=payload.count,
@@ -346,6 +480,12 @@ async def flow_image(payload: FlowImageRequest):
all_accounts=payload.all_accounts,
cookies=payload.cookies,
)
+ # A caller that is not this process needs a URL, not a path.
+ if isinstance(result, dict) and "files" in result and isinstance(result["files"], list):
+ for f in result["files"]:
+ if isinstance(f, dict) and "path" in f:
+ f["url"] = _media_url(request, f["path"])
+ return result
except EngineError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
@@ -353,10 +493,10 @@ async def flow_image(payload: FlowImageRequest):
@app.post("/v1/generate/video")
@app.post("/v1/video")
@app.post("/api/v1/video")
-async def flow_video(payload: FlowVideoRequest):
+async def flow_video(payload: FlowVideoRequest, request: Request):
"""Generate a video, speaking the engine's own vocabulary."""
try:
- return await engine.generate_video(
+ result = await engine.generate_video(
prompt=payload.prompt,
aspect=payload.aspect,
duration=payload.duration,
@@ -366,6 +506,11 @@ async def flow_video(payload: FlowVideoRequest):
all_accounts=payload.all_accounts,
cookies=payload.cookies,
)
+ if isinstance(result, dict) and "files" in result and isinstance(result["files"], list):
+ for f in result["files"]:
+ if isinstance(f, dict) and "path" in f:
+ f["url"] = _media_url(request, f["path"])
+ return result
except EngineError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
@@ -402,17 +547,392 @@ async def flow_projects(cookies: Optional[str] = None):
@app.get("/v1/media/{filename:path}")
@app.get("/api/v1/media/{filename:path}")
async def flow_media(filename: str):
- """Serve one generated file.
+ """Serve a generated media file, confined to a known output directory.
+
+ Candidates are tried in order and each must resolve *inside* the directory
+ it was found in. A string prefix is not that test: `/out` is a prefix of
+ `/out-evil`, so a sibling directory that merely shares a prefix would be
+ served. `Path.is_relative_to` compares path parts, so it cannot be fooled.
+
+ `engine.root` is read defensively. It is optional on the engine contract,
+ and a missing attribute must be a 404 here, not a 500.
- The name is resolved against the output directory and rejected if it escapes
- it: this route takes a path from a URL, and `..` in one is the whole attack.
+ There is deliberately no `__file__`-relative guess at an output directory:
+ the package's install layout has nothing to do with where the engine writes,
+ so such a candidate either duplicates a directory already in the list or
+ serves files from somewhere the engine never put them.
+
+ The content type comes from `mimetypes` rather than a hand-kept extension
+ table, because the preview page exists to render images inline - serving a
+ PNG as `application/octet-stream` makes the browser download it instead.
"""
- candidate = (MEDIA_DIR / filename).resolve()
- if candidate.parent != MEDIA_DIR.resolve() or not candidate.is_file():
- raise HTTPException(status_code=404, detail="no such media file")
- return FileResponse(candidate)
+ search_dirs: list[Path] = [MEDIA_DIR]
+ engine_root = getattr(engine, "root", None)
+ if engine_root is not None:
+ search_dirs.append(Path(engine_root) / "output")
+
+ for sdir in search_dirs:
+ base = Path(sdir).resolve()
+ try:
+ cand = (base / filename).resolve()
+ except (OSError, ValueError):
+ continue
+ if not cand.is_file() or not cand.is_relative_to(base):
+ continue
+ media_type = mimetypes.guess_type(cand.name)[0] or "application/octet-stream"
+ return FileResponse(cand, media_type=media_type, filename=cand.name)
+ raise HTTPException(status_code=404, detail="no such media file")
@app.get("/health")
async def health():
return {"status": "ok", "engine": engine.available(), "binary": str(engine.binary)}
+
+
+# --------------------------------------------------------------------------- #
+# web preview dashboard
+# --------------------------------------------------------------------------- #
+
+PREVIEW_HTML = """
+
+
+
+
+ Flow Agent - OpenAI image generation preview
+
+
+
+
+
+
+
+
+
+
Generating...
+
+
![Generated image]()
+
+
+
+
+
+
+
+
+
+
+"""
+
+
+@app.get("/", response_class=HTMLResponse)
+@app.get("/preview", response_class=HTMLResponse)
+async def preview_dashboard():
+ """Generate over the OpenAI route from a browser and show the result at once."""
+ return HTMLResponse(content=PREVIEW_HTML)
diff --git a/flow-agent/flow_agent/engine.py b/flow-agent/flow_agent/engine.py
index 98c0636..a9411a1 100644
--- a/flow-agent/flow_agent/engine.py
+++ b/flow-agent/flow_agent/engine.py
@@ -21,6 +21,46 @@
#: minutes, so this is generous by design rather than a hang guard.
DEFAULT_TIMEOUT = 900
+#: The image model to run when a request names none.
+DEFAULT_IMAGE_MODEL = "beluga"
+
+#: Values that mean "the field was left blank" rather than naming a model.
+#: Swagger UI fills an untouched field with the literal text `string`.
+_MODEL_PLACEHOLDERS = frozenset({"", "string", "default", "none", "null", "undefined"})
+
+#: The same for cookies, plus the two spellings of an empty string that arrive
+#: already quoted from a form field or a shell.
+_DUMMY_COOKIES = frozenset({"", "string", "null", "none", "undefined", '""', "''"})
+
+
+def clean_model(value: Any) -> str:
+ """The image model to run for `value`.
+
+ A placeholder is "not given" and becomes the default. A name the caller did
+ supply is passed through untouched: rewriting one - `narwhal` to `beluga`,
+ say - runs something other than what was asked for while reporting success,
+ and `main.py` passes its own `narwhal` default straight through, so the two
+ surfaces would disagree about the same word.
+ """
+ if value is None:
+ return DEFAULT_IMAGE_MODEL
+ name = str(value).strip()
+ return DEFAULT_IMAGE_MODEL if name.lower() in _MODEL_PLACEHOLDERS else name
+
+
+def clean_cookies(value: Optional[str]) -> Optional[str]:
+ """The `--cookies` argument for `value`, or None when there is not one.
+
+ Swagger UI sends the literal text `string` for a field left alone and some
+ clients send `null`. Those would hand the engine a session cookie already
+ known to be wrong, which reads as an auth failure rather than as an option
+ nobody set. What survives is stripped, because it becomes one argv token.
+ """
+ if value is None:
+ return None
+ text = str(value).strip()
+ return None if text.lower() in _DUMMY_COOKIES else text
+
class EngineError(RuntimeError):
"""A Flow engine invocation that did not succeed.
@@ -112,15 +152,25 @@ def _find_binary(root: Path, explicit: Optional[str | Path] = None) -> Path:
import platform
system = platform.system().lower()
+ machine = platform.machine().lower()
bin_dir = root / "bin"
+ is_arm = machine in ("aarch64", "arm64", "armv8l", "armv8")
+
# Platform priority candidates
if "windows" in system:
candidates = ["flow-windows.exe", "flow.exe", "flow"]
elif "darwin" in system:
- candidates = ["flow-macos", "flow", "flow-darwin"]
+ candidates = (
+ ["flow-macos-arm64", "flow-macos", "flow", "flow-darwin"]
+ if is_arm
+ else ["flow-macos", "flow", "flow-darwin"]
+ )
else: # Linux / Unix
- candidates = ["flow-linux", "flow", "flow-x86_64"]
+ if is_arm:
+ candidates = ["flow-linux-arm64", "flow-arm64", "flow-linux", "flow"]
+ else:
+ candidates = ["flow-linux-amd64", "flow-linux", "flow", "flow-x86_64"]
for name in candidates:
candidate_path = bin_dir / name
@@ -218,7 +268,7 @@ async def generate_image(
prompt: str,
aspect: str = "1:1",
count: int = 1,
- model: str = "narwhal",
+ model: str = "beluga",
all_accounts: bool = False,
cookies: Optional[str] = None,
download: bool = True,
@@ -238,12 +288,12 @@ async def generate_image(
args: list[Any] = ["image", prompt, aspect]
if count and count > 1:
args.append(f"x{count}")
- if model:
- args += ["--model", model]
+ args += ["--model", clean_model(model)]
if all_accounts:
args.append("--all")
- if cookies:
- args += ["--cookies", cookies]
+ cookie_arg = clean_cookies(cookies)
+ if cookie_arg:
+ args += ["--cookies", cookie_arg]
if not download:
args.append("--no-download")
@@ -275,8 +325,9 @@ async def generate_video(
args += ["--start-image", start_image]
if all_accounts:
args.append("--all")
- if cookies:
- args += ["--cookies", cookies]
+ cookie_arg = clean_cookies(cookies)
+ if cookie_arg:
+ args += ["--cookies", cookie_arg]
if not download:
args.append("--no-download")
@@ -298,8 +349,9 @@ async def upload_video(
args: list[Any] = ["upload-video", file_path]
if force:
args.append("--force-upload")
- if cookies:
- args += ["--cookies", cookies]
+ cookie_arg = clean_cookies(cookies)
+ if cookie_arg:
+ args += ["--cookies", cookie_arg]
return await self._run_json(*args, timeout=timeout)
@@ -328,8 +380,9 @@ async def get_projects(self, cookies: Optional[str] = None) -> list[dict]:
not an object wrapping one.
"""
args: list[Any] = ["projects", "--json"]
- if cookies:
- args += ["--cookies", cookies]
+ cookie_arg = clean_cookies(cookies)
+ if cookie_arg:
+ args += ["--cookies", cookie_arg]
out, _ = await self._run(*args)
try:
parsed = extract_json(out)
diff --git a/flow-agent/tests/test_api.py b/flow-agent/tests/test_api.py
index 7440dd1..758b320 100644
--- a/flow-agent/tests/test_api.py
+++ b/flow-agent/tests/test_api.py
@@ -142,6 +142,72 @@ def test_openai_images_returns_a_fetchable_url(client):
assert body["flow"]["job_id"] == "j1"
+def test_openai_images_requires_a_prompt(client):
+ """A missing prompt is refused rather than filled in.
+
+ `prompt` is the one field OpenAI marks required, and every generation here
+ spends a credit: a server-side default would charge an account for a
+ sentence the caller never wrote and hand back an image nobody asked for.
+ """
+ response = client.post("/v1/images/generations", json={})
+ assert response.status_code == 422
+ # Refused at the schema, so the engine is never reached and nothing is spent.
+ assert client.fake.calls == []
+
+
+def test_openai_images_uses_a_forwarded_proxy_authority(client):
+ """Honouring the forwarded pair is the point - a proxy rewrites it."""
+ body = client.post(
+ "/v1/images/generations",
+ json={"prompt": "x"},
+ headers={"x-forwarded-host": "proxy.example:8443", "x-forwarded-proto": "https"},
+ ).json()
+ assert body["data"][0]["url"] == "https://proxy.example:8443/api/v1/media/one.png"
+
+
+def test_openai_images_keeps_the_request_scheme_for_a_bogus_forwarded_proto(client):
+ """The scheme and the host fall back independently.
+
+ A proxy that forwards the host but not the scheme must still get its host
+ used, and a scheme that is not http(s) must not be able to reach the URL.
+ """
+ body = client.post(
+ "/v1/images/generations",
+ json={"prompt": "x"},
+ headers={"x-forwarded-host": "proxy.example", "x-forwarded-proto": "javascript:"},
+ ).json()
+ assert body["data"][0]["url"] == "http://proxy.example/api/v1/media/one.png"
+
+
+@pytest.mark.parametrize(
+ "forwarded_host",
+ [
+ "evil.example/steal", # a path leaves the authority position
+ "evil.example?x=1", # so does a query
+ "evil.example#f", # and a fragment
+ "user@evil.example", # read as credentials, not as a host
+ "good\\evil.example", # a browser normalises the backslash to a slash
+ "evil%2f.example", # percent-encoded, and not decoded here
+ "[::1", # an unclosed IPv6 bracket is not a URL
+ "", # absent
+ ],
+)
+def test_openai_images_ignores_a_forwarded_host_that_is_not_an_authority(
+ client, forwarded_host
+):
+ """The header is caller input and the URL it builds lands in a response.
+
+ A value that is not a bare `host[:port]` is not an error - the request's own
+ host is used instead, so the link a client is handed still points here.
+ """
+ body = client.post(
+ "/v1/images/generations",
+ json={"prompt": "x"},
+ headers={"x-forwarded-host": forwarded_host},
+ ).json()
+ assert body["data"][0]["url"] == "http://testserver/api/v1/media/one.png"
+
+
def test_openai_images_refuses_an_unknown_size(client):
response = client.post(
"/v1/images/generations", json={"prompt": "x", "size": "640x480"}
@@ -162,6 +228,24 @@ def test_openai_images_passes_the_count_through(client):
assert client.fake.calls[-1][1]["count"] == 3
+def test_openai_images_passes_an_explicit_model_through(client):
+ """A model that was named is the model that runs.
+
+ `narwhal` used to be rewritten to `beluga` without saying so, which is the
+ failure that is hard to notice: the request looks like it did what was
+ asked. The CLI passes its own `narwhal` default straight through, so the
+ two surfaces would also disagree about the same word.
+ """
+ client.post("/v1/images/generations", json={"prompt": "x", "model": "narwhal"})
+ assert client.fake.calls[-1][1]["model"] == "narwhal"
+
+
+def test_openai_images_replaces_a_placeholder_model_with_the_default(client):
+ """Swagger UI sends the literal text `string` for a field left alone."""
+ client.post("/v1/images/generations", json={"prompt": "x", "model": "string"})
+ assert client.fake.calls[-1][1]["model"] == "beluga"
+
+
def test_openai_images_ignores_fields_it_does_not_model(client):
"""An OpenAI client sends keys this does not know; failing on them would
make the endpoint unusable from the SDKs it exists to serve."""
@@ -225,6 +309,48 @@ def test_openai_images_reports_an_unreadable_file_as_a_failure(client):
assert response.status_code == 502
+def test_openai_images_streams_the_file_it_was_asked_for(client):
+ """`response_format: "image"` hands back the bytes, not a description.
+
+ This is the branch Swagger UI's Execute button and the dashboard use, so it
+ has to answer with the file itself and name its real type.
+ """
+ target = client.media_dir / "one.jpg"
+ target.write_bytes(b"\xff\xd8\xff\xe0jpeg-bytes")
+ client.fake.image = {"status": "succeeded", "files": [{"path": str(target)}]}
+
+ response = client.post(
+ "/v1/images/generations",
+ json={"prompt": "x", "response_format": "image"},
+ )
+
+ assert response.status_code == 200
+ assert response.content == b"\xff\xd8\xff\xe0jpeg-bytes"
+ assert response.headers["content-type"] == "image/jpeg"
+
+
+def test_openai_images_streams_a_png_as_a_png(client):
+ """The streamed type comes from the file, so a PNG is not called a JPEG.
+
+ A label that disagrees with the bytes makes the browser download the file
+ instead of rendering it, which is the outcome the preview branch exists to
+ avoid. PNG is reachable: `response_format: "image"` serves whichever file
+ the engine produced.
+ """
+ target = client.media_dir / "one.png"
+ target.write_bytes(b"\x89PNG\r\n\x1a\npng-bytes")
+ client.fake.image = {"status": "succeeded", "files": [{"path": str(target)}]}
+
+ response = client.post(
+ "/api/v1/images/generations",
+ json={"prompt": "x", "response_format": "image"},
+ )
+
+ assert response.status_code == 200
+ assert response.content == b"\x89PNG\r\n\x1a\npng-bytes"
+ assert response.headers["content-type"] == "image/png"
+
+
# --------------------------------------------------------------------------- #
# OpenAI-compatible chat
# --------------------------------------------------------------------------- #
@@ -368,6 +494,32 @@ def test_media_serves_a_real_file(client):
assert v1_response.content == b"png-bytes"
+def test_media_serves_a_png_as_a_png(client):
+ """The preview page renders these inline, so the type has to be right.
+
+ `application/octet-stream` makes the browser download the file instead,
+ which is the one thing the preview page exists to avoid.
+ """
+ (client.media_dir / "ok.png").write_bytes(b"png-bytes")
+ response = client.get("/api/v1/media/ok.png")
+ assert response.headers["content-type"] == "image/png"
+
+
+def test_media_refuses_a_sibling_directory_sharing_a_prefix(client):
+ """A prefix is not containment: `/out` starts `/out-evil`.
+
+ Encoded on purpose - a literal `..` may be collapsed by the HTTP client
+ before the request reaches the route, which would make this pass for the
+ wrong reason.
+ """
+ sibling = client.media_dir.parent / f"{client.media_dir.name}-evil"
+ sibling.mkdir()
+ (sibling / "leak.txt").write_text("do not serve me")
+
+ name = f"%2e%2e%2f{client.media_dir.name}-evil%2fleak.txt"
+ assert client.get(f"/api/v1/media/{name}").status_code == 404
+
+
def test_media_refuses_a_traversal(client):
"""The route takes a name out of a URL, and `..` in one is the whole attack."""
secret = client.media_dir.parent / "secret.txt"
diff --git a/flow-agent/tests/test_engine.py b/flow-agent/tests/test_engine.py
index 1e91dcf..261e38b 100644
--- a/flow-agent/tests/test_engine.py
+++ b/flow-agent/tests/test_engine.py
@@ -4,7 +4,7 @@
import pytest
-from flow_agent.engine import FlowEngine, extract_json
+from flow_agent.engine import FlowEngine, clean_cookies, clean_model, extract_json
# --------------------------------------------------------------------------- #
# extract_json
@@ -95,6 +95,69 @@ def test_command_keeps_falsy_values_that_are_not_absent():
assert engine._command("image", "p", 0) == ["/bin/echo", "image", "p", "0"]
+# --------------------------------------------------------------------------- #
+# what reaches the command line
+# --------------------------------------------------------------------------- #
+
+
+def test_clean_model_keeps_a_name_it_was_given():
+ """`narwhal` is a model the caller asked for, not a typo to be corrected.
+
+ Rewriting it to `beluga` runs something other than what was asked for, and
+ `main.py` passes its own `narwhal` default through untouched, so the CLI and
+ the API would disagree about the same word.
+ """
+ assert clean_model("narwhal") == "narwhal"
+
+
+def test_clean_model_falls_back_for_a_placeholder():
+ """Swagger UI sends `string` for a field left alone."""
+ for placeholder in ("", " ", "string", "default", "none", "null", None):
+ assert clean_model(placeholder) == "beluga"
+
+
+def test_clean_cookies_drops_the_placeholders_a_form_sends():
+ """A known-dummy cookie reads as an auth failure, not as an unset option."""
+ for placeholder in ("", " ", "string", "null", "none", "undefined", '""', "''", None):
+ assert clean_cookies(placeholder) is None
+
+
+def test_clean_cookies_strips_the_value_it_keeps():
+ """The value becomes one argv token, so padding around it is not cosmetic."""
+ assert clean_cookies(" sid=abc ") == "sid=abc"
+
+
+async def test_a_placeholder_cookie_never_reaches_the_command(monkeypatch, tmp_path):
+ engine = FlowEngine(root=str(tmp_path), binary=str(tmp_path / "flow"))
+ seen: dict = {}
+
+ async def capture(*args, **kwargs):
+ seen["args"] = args
+ return {}
+
+ monkeypatch.setattr(engine, "_run_json", capture)
+
+ await engine.generate_image("a boat", cookies="string")
+ assert "--cookies" not in seen["args"]
+
+ await engine.generate_image("a boat", cookies=" sid=abc ")
+ assert seen["args"][-2:] == ("--cookies", "sid=abc")
+
+
+async def test_a_named_model_reaches_the_command_unchanged(monkeypatch, tmp_path):
+ engine = FlowEngine(root=str(tmp_path), binary=str(tmp_path / "flow"))
+ seen: dict = {}
+
+ async def capture(*args, **kwargs):
+ seen["args"] = args
+ return {}
+
+ monkeypatch.setattr(engine, "_run_json", capture)
+
+ await engine.generate_image("a boat", model="narwhal")
+ assert seen["args"][seen["args"].index("--model") + 1] == "narwhal"
+
+
# --------------------------------------------------------------------------- #
# database reads
# --------------------------------------------------------------------------- #