Skip to content

Commit fe3bd0a

Browse files
authored
fix: stop reading the filesystem from ordinary string parameters (#3)
1 parent fbd7887 commit fe3bd0a

6 files changed

Lines changed: 118 additions & 125 deletions

File tree

‎README.md‎

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -639,26 +639,20 @@ The per-model methods (`get_model`, `get_model_examples`, `get_model_pricing`) a
639639

640640
## File helpers
641641

642-
`file_to_data_uri` encodes a local file as a `data:` URI for passing as input:
642+
**The SDK never reads the filesystem on its own.** A string you pass as a parameter is sent as that string, prompts and media parameters alike. When you want a file's contents on the wire, you say so:
643643

644644
```python
645-
from pathlib import Path
646-
from runware import file_to_data_uri
645+
from runware import file_to_base64, file_to_data_uri
647646

648-
data_uri = file_to_data_uri(Path("photo.jpg"))
649-
await client.media_storage({"operation": "upload", "media": data_uri})
647+
await client.run({"model": "...", "seedImage": file_to_base64("photo.jpg")})
648+
await client.media_storage({"operation": "upload", "media": file_to_data_uri("photo.jpg")})
650649
```
651650

652-
Accepts both `Path` and `bytes` — `bytes` is useful when the file lives in memory (e.g. a freshly downloaded blob).
651+
`file_to_base64` returns raw base64, with no `data:` prefix and no MIME type, which is what a media parameter takes most directly: the server reads the real format from the bytes. `file_to_data_uri` returns a `data:<mime>;base64,...` URI, taking the MIME from the file's extension.
653652

654-
`file_to_base64` does the same read but returns raw base64 with no `data:` prefix or MIME type (the server sniffs the real format from the bytes).
653+
Both accept a `str`, a `Path`, `bytes`, or a file-like object, so a blob you already hold in memory needs no round trip through disk.
655654

656-
You usually don't need either helper for inputs: `run()` and `media_storage` auto-encode local file paths. Any string value (recursively, including nested dicts and lists) that points to an existing file on disk is read and replaced with its base64 before the request is sent. URLs, UUIDs, data URIs, existing base64, and prompts pass through untouched.
657-
658-
```python
659-
await client.run({"model": "...", "seedImage": "./photo.jpg"})
660-
await client.run({"model": "...", "referenceImages": ["./a.jpg", "./b.jpg"]})
661-
```
655+
> Before 1.7.1 the SDK replaced any string that happened to name a readable file with that file's contents, in every parameter. Passing a path straight to `seedImage` no longer works: wrap it in `file_to_base64`.
662656
663657
## Custom dependencies
664658

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "runware-sdk"
3-
version = "1.7.0"
3+
version = "1.7.1"
44
description = "Async Python SDK for the Runware platform — image, video, audio, text, and 3D generation, plus upscaling, background removal, and more, over REST or WebSocket with typed parameters and runtime validation."
55
readme = "README.md"
66
requires-python = ">=3.11"

‎runware/client.py‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,6 @@
8282
operation_task_types as _bundled_operation_task_types,
8383
)
8484
from .types.transport import RequestOptions, WireFrame
85-
from .utils.file import encode_local_files
8685
from .validate import validate_tasks
8786

8887

@@ -264,7 +263,6 @@ async def run( # pyright: ignore[reportInconsistentOverload]
264263
options: RunOptions | None = None,
265264
) -> list[dict[str, Any]]: # pyright: ignore[reportExplicitAny]
266265
"""Run an inference task."""
267-
params = cast("dict[str, Any]", encode_local_files(params)) # pyright: ignore[reportExplicitAny]
268266
params = await self._normalize_model_param(params)
269267
task_type = await self._resolve_task_type(params)
270268
task_uuid = str(params.get("taskUUID") or uuid.uuid4())
@@ -379,19 +377,17 @@ async def image_upload(
379377
self, params: ImageUploadParams, options: RunOptions | None = None,
380378
) -> list[ImageUploadResult]:
381379
"""Deprecated: use :meth:`media_storage`, which handles any media type and supports deletion."""
382-
encoded = cast("dict[str, Any]", encode_local_files(dict(params))) # pyright: ignore[reportExplicitAny]
383380
return cast(
384381
list[ImageUploadResult],
385-
await self._utility("imageUpload", encoded, options),
382+
await self._utility("imageUpload", dict(params), options),
386383
)
387384

388385
async def media_storage(
389386
self, params: MediaStorageParams, options: RunOptions | None = None,
390387
) -> list[MediaStorageResult]:
391-
encoded = cast("dict[str, Any]", encode_local_files(dict(params))) # pyright: ignore[reportExplicitAny]
392388
return cast(
393389
list[MediaStorageResult],
394-
await self._utility("mediaStorage", encoded, options),
390+
await self._utility("mediaStorage", dict(params), options),
395391
)
396392

397393
async def account_management(

‎runware/utils/file.py‎

Lines changed: 2 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,12 @@
55
import base64
66
import io
77
import mimetypes
8-
import os
98
from pathlib import Path
10-
from typing import BinaryIO, cast
9+
from typing import BinaryIO
10+
1111

1212
# Strings longer than this can't plausibly be a filesystem path — a base64 blob
1313
# or data URI is far longer. Skipping them avoids hitting the disk for them.
14-
_MAX_PATH_LEN = 4096
15-
_REMOTE_PREFIXES = ("http://", "https://", "data:")
16-
17-
1814
def _read_bytes(source: str | Path | bytes | BinaryIO) -> bytes:
1915
if isinstance(source, (str, Path)):
2016
return Path(source).read_bytes()
@@ -44,40 +40,6 @@ def file_to_base64(source: str | Path | bytes | BinaryIO) -> str:
4440
return base64.b64encode(_read_bytes(source)).decode("ascii")
4541

4642

47-
def _looks_like_local_file(value: str) -> bool:
48-
if value.startswith(_REMOTE_PREFIXES):
49-
return False
50-
if len(value) > _MAX_PATH_LEN:
51-
return False
52-
try:
53-
return os.path.isfile(value)
54-
except (OSError, ValueError):
55-
return False
56-
57-
58-
def encode_local_files(value: object) -> object:
59-
"""
60-
Recursively walk a params object (dicts, lists, strings) and replace any
61-
string that points to an existing local file with its base64 contents.
62-
63-
URLs, data URIs, UUIDs, prompts, existing base64, numbers, and bools pass
64-
through untouched — only strings that resolve to a real file on disk are
65-
converted. A string that merely looks like a path but doesn't exist is left
66-
as-is (no error raised).
67-
"""
68-
if isinstance(value, str):
69-
if _looks_like_local_file(value):
70-
return file_to_base64(value)
71-
return value
72-
if isinstance(value, dict):
73-
items = cast("dict[object, object]", value)
74-
return {k: encode_local_files(v) for k, v in items.items()}
75-
if isinstance(value, list):
76-
items_list = cast("list[object]", value)
77-
return [encode_local_files(item) for item in items_list]
78-
return value
79-
80-
8143
def file_to_data_uri(source: str | Path | bytes | BinaryIO) -> str:
8244
"""
8345
Encode a file, bytes blob, or file-like into a `data:<mime>;base64,...` URI.

‎tests/test_file_encoding.py‎

Lines changed: 105 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
"""
2-
Tests for runware/utils/file.py — auto-encoding of local file paths to base64
3-
when passed as inputs to client.run().
2+
Tests for the rule that the SDK never reads the filesystem on its own.
3+
4+
Until 1.7.0 every string in the params was checked against the filesystem and
5+
replaced with the file's base64 if it happened to name one, which made any caller
6+
that forwarded user text into ``run()`` read local files on request. A local
7+
file now travels only through ``file_to_base64`` or ``file_to_data_uri``, which
8+
the caller has to reach for.
9+
10+
The case that matters is the one that used to leak: a prompt that is exactly a
11+
path to a real file has to arrive at the transport as that path.
412
"""
513

614
from __future__ import annotations
@@ -12,9 +20,8 @@
1220

1321
import pytest
1422

15-
from runware import Runware, file_to_base64
23+
from runware import Runware, file_to_base64, file_to_data_uri
1624
from runware.transport.rest import RestTransport
17-
from runware.utils.file import encode_local_files
1825

1926

2027
def _patch_rest(client: Runware, response: Any) -> AsyncMock:
@@ -25,81 +32,115 @@ def _patch_rest(client: Runware, response: Any) -> AsyncMock:
2532
return mock
2633

2734

28-
class TestEncodeLocalFiles:
29-
def test_file_to_base64_has_no_prefix(self, tmp_path: Path) -> None:
30-
f = tmp_path / "photo.jpg"
31-
f.write_bytes(b"\xff\xd8\xff\xe0binary")
32-
expected = base64.b64encode(b"\xff\xd8\xff\xe0binary").decode("ascii")
33-
assert file_to_base64(f) == expected
34-
assert not file_to_base64(f).startswith("data:")
35-
36-
def test_existing_file_converted(self, tmp_path: Path) -> None:
37-
f = tmp_path / "a.png"
38-
f.write_bytes(b"pixels")
39-
out = encode_local_files(str(f))
40-
assert out == base64.b64encode(b"pixels").decode("ascii")
41-
42-
def test_nonexistent_path_passes_through(self) -> None:
43-
assert encode_local_files("./not-a-real-file.jpg") == "./not-a-real-file.jpg"
44-
45-
def test_url_uuid_data_uri_prompt_pass_through(self) -> None:
46-
assert encode_local_files("https://x.com/a.jpg") == "https://x.com/a.jpg"
47-
assert encode_local_files("http://x.com/a.jpg") == "http://x.com/a.jpg"
48-
assert encode_local_files("data:image/png;base64,AAAA") == "data:image/png;base64,AAAA"
49-
assert encode_local_files("a paragraph that describes a cat") == "a paragraph that describes a cat"
50-
assert encode_local_files("9f3c-uuid-like-1234") == "9f3c-uuid-like-1234"
51-
52-
def test_recurses_into_dicts_and_lists(self, tmp_path: Path) -> None:
53-
a = tmp_path / "a.jpg"
54-
b = tmp_path / "b.jpg"
55-
a.write_bytes(b"AAA")
56-
b.write_bytes(b"BBB")
57-
from typing import cast
58-
59-
out = cast(
60-
"dict[str, Any]",
61-
encode_local_files(
62-
{
63-
"inputs": {"image": str(a)},
64-
"referenceImages": [str(b), "https://x.com/c.jpg"],
65-
"positivePrompt": "a cat",
66-
"width": 1024,
67-
"flag": True,
68-
}
69-
),
35+
async def _sent_for(params: dict[str, Any]) -> dict[str, Any]:
36+
client = Runware(api_key="sk-test", transport="rest")
37+
mock = _patch_rest(
38+
client,
39+
{"data": [{"taskUUID": "u1", "imageURL": "https://x.jpg", "imageUUID": "i1"}]},
40+
)
41+
await client.run(params)
42+
return mock.send_request.call_args_list[0].args[0]
43+
44+
45+
class TestTheSdkDoesNotReadTheFilesystem:
46+
@pytest.mark.asyncio
47+
async def test_a_prompt_that_is_a_real_path_is_sent_as_that_path(
48+
self, tmp_path: Path
49+
) -> None:
50+
secret = tmp_path / "secrets.env"
51+
secret.write_bytes(b"API_KEY=leaked")
52+
53+
sent = await _sent_for(
54+
{
55+
"taskType": "imageInference",
56+
"taskUUID": "u1",
57+
"model": "runware:101@1",
58+
"positivePrompt": str(secret),
59+
"width": 1024,
60+
"height": 1024,
61+
"deliveryMethod": "sync",
62+
}
7063
)
71-
assert out["inputs"]["image"] == base64.b64encode(b"AAA").decode("ascii")
72-
assert out["referenceImages"][0] == base64.b64encode(b"BBB").decode("ascii")
73-
assert out["referenceImages"][1] == "https://x.com/c.jpg"
74-
assert out["positivePrompt"] == "a cat"
75-
assert out["width"] == 1024
76-
assert out["flag"] is True
7764

65+
assert sent["positivePrompt"] == str(secret)
66+
assert base64.b64encode(b"API_KEY=leaked").decode("ascii") not in str(sent)
7867

79-
class TestRunAutoEncodes:
8068
@pytest.mark.asyncio
81-
async def test_run_encodes_local_seed_image(self, tmp_path: Path) -> None:
69+
async def test_a_media_param_that_is_a_real_path_is_sent_as_that_path(
70+
self, tmp_path: Path
71+
) -> None:
8272
f = tmp_path / "seed.jpg"
8373
f.write_bytes(b"\x89PNG seed bytes")
84-
client = Runware(api_key="sk-test", transport="rest")
85-
mock = _patch_rest(
86-
client,
87-
{"data": [{"taskUUID": "u1", "imageURL": "https://x.jpg", "imageUUID": "i1"}]},
88-
)
89-
await client.run(
74+
75+
sent = await _sent_for(
9076
{
9177
"taskType": "imageInference",
9278
"taskUUID": "u1",
9379
"model": "runware:101@1",
9480
"seedImage": str(f),
95-
"referenceImages": ["https://x.com/keep.jpg"],
9681
"positivePrompt": "x",
9782
"width": 1024,
9883
"height": 1024,
9984
"deliveryMethod": "sync",
10085
}
10186
)
102-
sent = mock.send_request.call_args_list[0].args[0]
87+
88+
assert sent["seedImage"] == str(f)
89+
90+
@pytest.mark.asyncio
91+
async def test_a_nested_path_is_left_alone(self, tmp_path: Path) -> None:
92+
f = tmp_path / "nested.txt"
93+
f.write_bytes(b"nested bytes")
94+
95+
sent = await _sent_for(
96+
{
97+
"taskType": "imageInference",
98+
"taskUUID": "u1",
99+
"model": "runware:101@1",
100+
"positivePrompt": "x",
101+
"referenceImages": [str(f)],
102+
"width": 1024,
103+
"height": 1024,
104+
"deliveryMethod": "sync",
105+
}
106+
)
107+
108+
assert sent["referenceImages"] == [str(f)]
109+
110+
111+
class TestALocalFileTravelsWhenTheCallerAsks:
112+
def test_file_to_base64_has_no_prefix(self, tmp_path: Path) -> None:
113+
f = tmp_path / "photo.jpg"
114+
f.write_bytes(b"\x89PNG photo bytes")
115+
116+
assert file_to_base64(str(f)) == base64.b64encode(b"\x89PNG photo bytes").decode("ascii")
117+
118+
def test_file_to_data_uri_carries_the_mime(self, tmp_path: Path) -> None:
119+
f = tmp_path / "photo.jpg"
120+
f.write_bytes(b"bytes")
121+
122+
encoded = base64.b64encode(b"bytes").decode("ascii")
123+
assert file_to_data_uri(str(f)) == f"data:image/jpeg;base64,{encoded}"
124+
125+
def test_bytes_the_caller_already_holds(self) -> None:
126+
assert file_to_base64(b"\x01\x02\x03") == base64.b64encode(b"\x01\x02\x03").decode("ascii")
127+
128+
@pytest.mark.asyncio
129+
async def test_it_reaches_the_transport_when_encoded_first(self, tmp_path: Path) -> None:
130+
f = tmp_path / "seed.jpg"
131+
f.write_bytes(b"\x89PNG seed bytes")
132+
133+
sent = await _sent_for(
134+
{
135+
"taskType": "imageInference",
136+
"taskUUID": "u1",
137+
"model": "runware:101@1",
138+
"seedImage": file_to_base64(str(f)),
139+
"positivePrompt": "x",
140+
"width": 1024,
141+
"height": 1024,
142+
"deliveryMethod": "sync",
143+
}
144+
)
145+
103146
assert sent["seedImage"] == base64.b64encode(b"\x89PNG seed bytes").decode("ascii")
104-
assert sent["referenceImages"] == ["https://x.com/keep.jpg"]
105-
assert sent["positivePrompt"] == "x"

‎uv.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)