Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(fleet): upload Image inputs safely through the SDK (#7759)
r33drichards141a6daa6e16
diff --git a/libs/fleet/Cargo.lock b/libs/fleet/Cargo.lockindex 352012ee84..e9bf84bdf0 100644--- a/libs/fleet/Cargo.lock+++ b/libs/fleet/Cargo.lock@@ -119,6 +119,15 @@ version = "2.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"+[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]+[[package]]name = "bumpalo"version = "3.20.3"@@ -192,7 +201,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"dependencies = ["cfg-if",- "cpufeatures",+ "cpufeatures 0.3.0","rand_core 0.10.1",]@@ -251,6 +260,15 @@ version = "0.8.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"+[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]+[[package]]name = "cpufeatures"version = "0.3.0"@@ -260,6 +278,16 @@ dependencies = ["libc",]+[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]+[[package]]name = "cyclops-sdk"version = "0.1.0"@@ -276,6 +304,7 @@ dependencies = ["reqwest","serde","serde_json",+ "sha2","thiserror","tokio","uniffi",@@ -399,6 +428,16 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]+[[package]]name = "displaydoc"version = "0.2.6"@@ -513,6 +552,16 @@ dependencies = ["slab",]+[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]+[[package]]name = "getrandom"version = "0.2.17"@@ -1560,6 +1609,17 @@ dependencies = ["unsafe-libyaml",]+[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "digest",+]+[[package]]name = "shlex"version = "2.0.1"@@ -1878,6 +1938,12 @@ version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"+[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"+[[package]]name = "unicode-ident"version = "1.0.24"@@ -2045,6 +2111,12 @@ version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"+[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"+[[package]]name = "want"version = "0.3.1"diff --git a/libs/fleet/scripts/generate-sdk-bindings.sh b/libs/fleet/scripts/generate-sdk-bindings.shindex 61944ae810..fa20300704 100755--- a/libs/fleet/scripts/generate-sdk-bindings.sh+++ b/libs/fleet/scripts/generate-sdk-bindings.sh@@ -901,8 +901,8 @@ def replace_buffer(match):f"{indent})")text, buffer_replacements = re.subn(buffer_pattern, replace_buffer, text)-if buffer_replacements != 29:- raise SystemExit(f"expected 29 Ruby Rust-buffer future wrappers, found {buffer_replacements}")+if buffer_replacements != 30:+ raise SystemExit(f"expected 30 Ruby Rust-buffer future wrappers, found {buffer_replacements}")if len(re.findall(r"result = FleetSdk\.rust_call_with_error\(SdkBuildError,:uniffi_[a-z0-9_]*builder_build,", text)) != 8:raise SystemExit("expected eight synchronous Ruby SDK builder build calls")diff --git a/libs/fleet/sdk-bindings/examples/python/IMAGE_BUILD.md b/libs/fleet/sdk-bindings/examples/python/IMAGE_BUILD.mdnew file mode 100644index 0000000000..71ce412d08--- /dev/null+++ b/libs/fleet/sdk-bindings/examples/python/IMAGE_BUILD.md@@ -0,0 +1,107 @@+# Submit an Image build from the Python SDK++This example uses the native SDK transport, hashes and uploads local files,+creates an Image only after all uploads succeed, and waits for that exact UID+and generation. It prints the OCI and VolumeSnapshot references when the+controller reports both artifacts Ready. It never deletes or resubmits an Image+automatically and does not run a full restore/boot test per build.++## Current delivery boundary++The SDK method is source functionality, not evidence that a released package or+production tenant controller is enabled. The deployment must provide tenant+Image authorization, an enabled upload bucket/signer, a pinned base catalog,+and an enabled Image controller. Missing upload configuration returns HTTP 503.+An Image with `BuildDisabled` stops the example immediately; it is not a+successful build. Snapshot-backed sandbox launch is a separate delivery gate.++## Local prerequisites++Use Python 3.11+ and the repository's pinned Rust toolchain. The repository+launcher builds the matching native library and stages generated Python bindings+in a temporary package; do not mix this branch's bindings with an older wheel.+Provide credentials authorized for the manifest's namespace through environment+variables, not command-line arguments or checked-in files. Use either an existing+Fleet bearer token in `CUA_ACCESS_TOKEN`, or the client-credentials configuration+below. A static access token is not refreshed automatically:++```bash+export REPO_ROOT=/absolute/path/to/cloud+export CUA_BASE_URL=https://your-fleet-api+export CUA_TOKEN_URL=https://your-identity-provider/token+export CUA_CLIENT_ID=your-client-id+# Supply CUA_CLIENT_SECRET from your normal local secret environment.+```++## Manifest and submission++Save a canonical Image JSON manifest as `image.json`. Use distro/version values+from the deployed, administrator-pinned base catalog. The Ubuntu values below+are illustrative, not a claim that this base is provisioned in your environment.+The current compiler requires a matching 40Gi base; it does not resize disks.++```json+{+ "apiVersion": "images.cua.ai/v1alpha1",+ "kind": "Image",+ "metadata": {"namespace": "your-namespace", "name": "local-build.v1"},+ "spec": {+ "recipe": {+ "osType": "linux",+ "distro": "ubuntu",+ "version": "24.04",+ "kind": "vm",+ "layers": [{"type": "run", "command": "cat /opt/build-input.txt"}]+ },+ "build": {"diskSize": "40Gi", "timeoutSeconds": 7200}+ }+}+```++Use only nonsensitive sample input: the sample command prints its contents to+build logs. Local files are read into memory by this small example. Repeat+`--file LOCAL_PATH GUEST_DESTINATION` to append multiple recipe files:++```bash+printf 'SDK upload example\n' > build-input.txt+"$REPO_ROOT/cyclops-cs/scripts/run-python-sdk-binding.sh" \+ "$REPO_ROOT/cyclops-cs/sdk-bindings/examples/python/image_build.py" \+ image.json --file build-input.txt /opt/build-input.txt --wait-seconds 120+```++The two-minute value is the **local polling budget**, not the server build+lifetime. `--wait-seconds 0` submits without waiting. Timeout leaves the Image+and remote build intact; it is not cancellation or proof of failure. A 409 on+create means you must inspect the existing Image instead of blindly retrying.+A changed UID or generation during polling aborts the wait rather than reporting+another build as the requested one.++## Inspect and clean up explicitly++With a client created using the same configuration:++```python+image = await client.get_image("your-namespace", "local-build.v1")+print(image.to_json())+# Only when you intend to request deletion:+# await client.delete_image("your-namespace", "local-build.v1")+```++Inspect `metadata.uid`, `metadata.generation`, `status.observedGeneration`,+conditions, `status.artifacts.oci` and `status.artifacts.volumeSnapshot`. Do not+publish the entire manifest: recipe environments or file details may be private.+Deletion acceptance is not evidence of backend storage cleanup; observe the+controller's lifecycle and retention behavior before assuming storage is gone.++## Fast local example checks++These checks use a fake SDK client and require no credentials or cluster:++```bash+python3 "$REPO_ROOT/cyclops-cs/sdk-bindings/examples/python/test_image_build.py"+```++They cover upload-before-create ordering, failed uploads, stale Ready status,+replacement/updates, BuildDisabled, bounded waits, and required same-namespace+artifacts. They do not prove S3 persistence, a real controller build, or sandbox+boot. The exact-digest release canary owns those end-to-end checks.diff --git a/libs/fleet/sdk-bindings/examples/python/image_build.py b/libs/fleet/sdk-bindings/examples/python/image_build.pynew file mode 100644index 0000000000..ce6f1f509d--- /dev/null+++ b/libs/fleet/sdk-bindings/examples/python/image_build.py@@ -0,0 +1,167 @@+#!/usr/bin/env python3+"""Upload local inputs and submit a generation-pinned Fleet Image build."""++import argparse+import asyncio+import copy+import json+import os+from pathlib import Path, PurePosixPath+import re+import sys+++class BuildError(RuntimeError):+ pass+++def image_identity(document):+ metadata = document.get("metadata", {})+ namespace, name = metadata.get("namespace", ""), metadata.get("name", "")+ label = r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"+ if (+ not isinstance(namespace, str)+ or not isinstance(name, str)+ or not 1 <= len(namespace) <= 63+ or not 1 <= len(name) <= 253+ or not re.fullmatch(label, namespace)+ or not all(re.fullmatch(label, part) for part in name.split("."))+ ):+ raise BuildError("The Image must have valid metadata.namespace and metadata.name.")+ return namespace, name+++def generation_identity(document):+ namespace, name = image_identity(document)+ metadata = document["metadata"]+ uid, generation = metadata.get("uid"), metadata.get("generation")+ if not isinstance(uid, str) or not uid or type(generation) is not int or generation < 1:+ raise BuildError("The API did not return an Image UID and generation.")+ return namespace, name, uid, generation+++async def wait_for_image(client, created, wait_seconds, *, poll_seconds=2):+ namespace, name, uid, generation = generation_identity(created)+ if wait_seconds <= 0 or poll_seconds <= 0:+ raise BuildError("Wait and poll durations must be positive.")+ try:+ async with asyncio.timeout(wait_seconds):+ while True:+ document = json.loads((await client.get_image(namespace, name)).to_json())+ if generation_identity(document) != (namespace, name, uid, generation):+ raise BuildError("The Image identity or generation changed while waiting.")+ if document["metadata"].get("deletionTimestamp"):+ raise BuildError("The Image is being deleted.")+ status = document.get("status") or {}+ if status.get("observedGeneration") == generation:+ conditions = status.get("conditions") or []+ ready = next((item for item in conditions if item.get("type") == "Ready" and item.get("observedGeneration") == generation), {})+ if ready.get("reason") == "BuildDisabled":+ raise BuildError("Remote Image builds are disabled; the Image and uploaded inputs are retained.")+ if status.get("phase") == "Failed":+ raise BuildError("Image build failed; inspect its generation-pinned conditions.")+ if status.get("phase") == "Ready" and ready.get("status") == "True":+ artifacts = status.get("artifacts") or {}+ oci = artifacts.get("oci") or {}+ snapshot = artifacts.get("volumeSnapshot") or {}+ digest, reference = oci.get("digest", ""), oci.get("reference", "")+ if (+ not isinstance(digest, str)+ or not re.fullmatch(r"sha256:[0-9a-f]{64}", digest)+ or not isinstance(reference, str)+ or not reference.endswith("@" + digest)+ or snapshot.get("namespace") != namespace+ or not snapshot.get("name")+ ):+ raise BuildError("Ready Image is missing matching OCI/snapshot artifacts.")+ return document+ await asyncio.sleep(poll_seconds)+ except TimeoutError as error:+ raise BuildError("Local wait timed out; the Image and build are retained. Inspect with get_image; do not resubmit blindly.") from error+++async def run_image_build(client, manifest, local_files, *, wait_seconds=120):+ if not isinstance(manifest, dict) or manifest.get("apiVersion") != "images.cua.ai/v1alpha1" or manifest.get("kind") != "Image":+ raise BuildError("Supply an images.cua.ai/v1alpha1 Image manifest.")+ namespace, name = image_identity(manifest)+ recipe = (manifest.get("spec") or {}).get("recipe")+ if not isinstance(recipe, dict) or not isinstance(recipe.get("files", []), list):+ raise BuildError("Supply an object spec.recipe with an optional files array.")+ if wait_seconds < 0:+ raise BuildError("Wait duration cannot be negative.")+ uploads = []+ for local_path, destination in local_files:+ destination_path = PurePosixPath(destination)+ if not destination_path.is_absolute() or destination_path == PurePosixPath("/") or ".." in destination_path.parts:+ raise BuildError("File destinations must be absolute guest paths without traversal.")+ uploads.append((Path(local_path), destination))+ document = copy.deepcopy(manifest)+ files = document["spec"]["recipe"].setdefault("files", [])+ for path, destination in uploads:+ uploaded = await client.upload_image_file(namespace, path.name, path.read_bytes())+ files.append({+ "source": {"reference": uploaded.reference, "digest": uploaded.digest, "sizeBytes": uploaded.size_bytes},+ "destination": destination,+ })+ from fleet_sdk import PreservedJson++ created = json.loads((await client.create_image(namespace, PreservedJson.from_json(json.dumps(document)))).to_json())+ returned_namespace, returned_name, _, _ = generation_identity(created)+ if (returned_namespace, returned_name) != (namespace, name):+ raise BuildError("Created Image identity did not match the submitted manifest.")+ if wait_seconds == 0:+ return created+ return await wait_for_image(client, created, wait_seconds)+++def connect_client():+ from fleet_sdk import CyclopsClient, CyclopsConfiguration, CyclopsCredentials, CyclopsTokenProviderConfiguration++ configuration = {+ "base_url": os.environ["CUA_BASE_URL"],+ "pool_poll_interval_ms": 2000, "pool_poll_limit": 60,+ "claim_poll_interval_ms": 2000, "claim_poll_limit": 60,+ }+ access_token = os.environ.get("CUA_ACCESS_TOKEN")+ if access_token:+ return CyclopsClient.connect_with_access_token_and_native_http_client(+ CyclopsTokenProviderConfiguration(**configuration), access_token,+ )+ return CyclopsClient.connect_with_native_http_client(CyclopsConfiguration(+ **configuration,+ token_url=os.environ["CUA_TOKEN_URL"],+ credentials=CyclopsCredentials(os.environ["CUA_CLIENT_ID"], os.environ["CUA_CLIENT_SECRET"]),+ ))+++async def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("manifest", type=Path, help="Canonical Image JSON manifest")+ parser.add_argument("--file", nargs=2, action="append", default=[], metavar=("LOCAL_PATH", "GUEST_DESTINATION"))+ parser.add_argument("--wait-seconds", type=int, default=120, help="Local wait budget; 0 submits without waiting (default: 120)")+ arguments = parser.parse_args()+ client = connect_client()+ manifest = json.loads(arguments.manifest.read_text())+ result = await run_image_build(client, manifest, arguments.file, wait_seconds=arguments.wait_seconds)+ metadata = result["metadata"]+ status = result.get("status") or {}+ print(json.dumps({+ "namespace": metadata["namespace"], "name": metadata["name"],+ "uid": metadata["uid"], "generation": metadata["generation"],+ "phase": status.get("phase", "Pending"),+ "observedGeneration": status.get("observedGeneration"),+ "artifacts": status.get("artifacts"),+ }, indent=2))+++if __name__ == "__main__":+ try:+ asyncio.run(main())+ except BuildError as error:+ print(str(error), file=sys.stderr)+ sys.exit(1)+ except Exception as error:+ status = getattr(error, "status", None)+ detail = f" (HTTP {status})" if isinstance(status, int) else ""+ print(f"Image submission failed: {type(error).__name__}{detail}. No automatic delete or resubmit was attempted.", file=sys.stderr)+ sys.exit(1)diff --git a/libs/fleet/sdk-bindings/examples/python/test_image_build.py b/libs/fleet/sdk-bindings/examples/python/test_image_build.pynew file mode 100644index 0000000000..973b492089--- /dev/null+++ b/libs/fleet/sdk-bindings/examples/python/test_image_build.py@@ -0,0 +1,146 @@+import copy+import json+from pathlib import Path+import sys+import tempfile+from types import SimpleNamespace+import unittest+from unittest.mock import AsyncMock, Mock, patch++import image_build+++class JsonDocument:+ def __init__(self, document):+ self.document = document++ @classmethod+ def from_json(cls, value):+ return cls(json.loads(value))++ def to_json(self):+ return json.dumps(self.document)+++def manifest():+ return {+ "apiVersion": "images.cua.ai/v1alpha1",+ "kind": "Image",+ "metadata": {"namespace": "workers", "name": "example.v1"},+ "spec": {"recipe": {"osType": "linux", "distro": "ubuntu", "version": "24.04", "kind": "vm", "layers": [{"type": "run", "command": "true"}]}},+ }+++def observation(phase="Ready", observed_generation=1):+ document = manifest()+ document["metadata"].update(uid="image-uid", generation=1)+ document["status"] = {+ "phase": phase,+ "observedGeneration": observed_generation,+ "conditions": [{"type": "Ready", "status": "True", "observedGeneration": observed_generation}],+ "artifacts": {+ "oci": {"reference": "registry.example/images@sha256:" + "a" * 64, "digest": "sha256:" + "a" * 64},+ "volumeSnapshot": {"namespace": "workers", "name": "snapshot"},+ },+ }+ return document+++class ImageBuildExampleTest(unittest.IsolatedAsyncioTestCase):+ def test_access_token_uses_native_transport_without_oauth_configuration(self):+ constructors = SimpleNamespace(connect_with_access_token_and_native_http_client=Mock(return_value="token-client"), connect_with_native_http_client=Mock())+ sdk = SimpleNamespace(CyclopsClient=constructors, CyclopsConfiguration=Mock(), CyclopsCredentials=Mock(), CyclopsTokenProviderConfiguration=lambda **values: values)+ with patch.dict("os.environ", {"CUA_BASE_URL": "https://fleet.example", "CUA_ACCESS_TOKEN": "test-token"}, clear=True), patch.dict(sys.modules, {"fleet_sdk": sdk}):+ self.assertEqual(image_build.connect_client(), "token-client")+ self.assertEqual(constructors.connect_with_access_token_and_native_http_client.call_args.args[1], "test-token")+ constructors.connect_with_native_http_client.assert_not_called()++ def test_client_credentials_use_native_transport(self):+ constructors = SimpleNamespace(connect_with_access_token_and_native_http_client=Mock(), connect_with_native_http_client=Mock(return_value="oauth-client"))+ sdk = SimpleNamespace(CyclopsClient=constructors, CyclopsConfiguration=lambda **values: values, CyclopsCredentials=Mock(return_value="credentials"), CyclopsTokenProviderConfiguration=Mock())+ environment = {"CUA_BASE_URL": "https://fleet.example", "CUA_TOKEN_URL": "https://identity.example/token", "CUA_CLIENT_ID": "client", "CUA_CLIENT_SECRET": "test-secret"}+ with patch.dict("os.environ", environment, clear=True), patch.dict(sys.modules, {"fleet_sdk": sdk}):+ self.assertEqual(image_build.connect_client(), "oauth-client")+ constructors.connect_with_access_token_and_native_http_client.assert_not_called()+ sdk.CyclopsCredentials.assert_called_once_with("client", "test-secret")++ async def test_upload_composes_source_then_creates_without_mutating_input(self):+ original = manifest()+ client = SimpleNamespace(+ upload_image_file=AsyncMock(return_value=SimpleNamespace(reference="uploads/tenant-x/hash", digest="sha256:" + "a" * 64, size_bytes=3)),+ create_image=AsyncMock(return_value=JsonDocument(observation("Pending"))),+ get_image=AsyncMock(),+ )+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "input.txt"+ path.write_bytes(b"abc")+ with patch.dict(sys.modules, {"fleet_sdk": SimpleNamespace(PreservedJson=JsonDocument)}):+ result = await image_build.run_image_build(client, original, [(path, "/opt/input.txt")], wait_seconds=0)+ client.upload_image_file.assert_awaited_once_with("workers", "input.txt", b"abc")+ created = client.create_image.await_args.args[1].document+ self.assertEqual(created["spec"]["recipe"]["files"][0]["source"]["sizeBytes"], 3)+ self.assertEqual(created["spec"]["recipe"]["files"][0]["destination"], "/opt/input.txt")+ self.assertNotIn("files", original["spec"]["recipe"])+ self.assertEqual(result["metadata"]["uid"], "image-uid")+ client.get_image.assert_not_awaited()++ async def test_upload_failure_never_creates_image(self):+ client = SimpleNamespace(upload_image_file=AsyncMock(side_effect=RuntimeError("upload failure")), create_image=AsyncMock())+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "input.txt"+ path.write_bytes(b"abc")+ with patch.dict(sys.modules, {"fleet_sdk": SimpleNamespace(PreservedJson=JsonDocument)}):+ with self.assertRaises(RuntimeError):+ await image_build.run_image_build(client, manifest(), [(path, "/opt/input.txt")], wait_seconds=0)+ client.create_image.assert_not_awaited()++ async def test_poll_ignores_stale_ready_generation(self):+ client = SimpleNamespace(get_image=AsyncMock(side_effect=[JsonDocument(observation(observed_generation=0)), JsonDocument(observation())]))+ result = await image_build.wait_for_image(client, observation("Pending"), 1, poll_seconds=0.001)+ self.assertEqual(result["status"]["observedGeneration"], 1)+ self.assertEqual(client.get_image.await_count, 2)++ async def test_poll_fails_on_replacement_or_update(self):+ for field, value in [("uid", "replacement"), ("generation", 2)]:+ with self.subTest(field=field):+ changed = observation()+ changed["metadata"][field] = value+ client = SimpleNamespace(get_image=AsyncMock(return_value=JsonDocument(changed)))+ with self.assertRaisesRegex(image_build.BuildError, "changed"):+ await image_build.wait_for_image(client, observation("Pending"), 1)++ async def test_build_disabled_does_not_wait_or_delete(self):+ disabled = observation("Pending")+ disabled["status"]["conditions"] = [{"type": "Ready", "status": "False", "reason": "BuildDisabled", "observedGeneration": 1}]+ client = SimpleNamespace(get_image=AsyncMock(return_value=JsonDocument(disabled)))+ with self.assertRaisesRegex(image_build.BuildError, "disabled"):+ await image_build.wait_for_image(client, observation("Pending"), 1)+ client.get_image.assert_awaited_once()++ async def test_timeout_retains_image(self):+ client = SimpleNamespace(get_image=AsyncMock(return_value=JsonDocument(observation("Building", 0))))+ with self.assertRaisesRegex(image_build.BuildError, "retained"):+ await image_build.wait_for_image(client, observation("Pending"), 0.01, poll_seconds=0.001)++ async def test_ready_requires_both_same_namespace_artifacts(self):+ for changed in [None, {"namespace": "other", "name": "snapshot"}]:+ document = observation()+ document["status"]["artifacts"]["volumeSnapshot"] = changed+ client = SimpleNamespace(get_image=AsyncMock(return_value=JsonDocument(document)))+ with self.assertRaisesRegex(image_build.BuildError, "artifacts"):+ await image_build.wait_for_image(client, observation("Pending"), 1)++ async def test_invalid_manifest_or_destination_does_not_upload(self):+ client = SimpleNamespace(upload_image_file=AsyncMock(), create_image=AsyncMock())+ invalid = copy.deepcopy(manifest())+ invalid["metadata"]["namespace"] = "../other"+ with self.assertRaises(image_build.BuildError):+ await image_build.run_image_build(client, invalid, [], wait_seconds=0)+ with self.assertRaises(image_build.BuildError):+ await image_build.run_image_build(client, manifest(), [(Path("missing"), "../outside")], wait_seconds=0)+ client.upload_image_file.assert_not_awaited()+ client.create_image.assert_not_awaited()+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.goindex d481a9059a..958c8d46cf 100644--- a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go+++ b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go@@ -484,6 +484,15 @@ func uniffiCheckChecksums() {panic("fleet_sdk: uniffi_cyclops_sdk_checksum_method_cyclopsclient_presign_image_uploads: UniFFI API checksum mismatch")}}+ {+ checksum := rustCall(func(_uniffiStatus *C.RustCallStatus) C.uint16_t {+ return C.uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file()+ })+ if checksum != 14212 {+ // If this happens try cleaning and rebuilding your project+ panic("fleet_sdk: uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file: UniFFI API checksum mismatch")+ }+ }{checksum := rustCall(func(_uniffiStatus *C.RustCallStatus) C.uint16_t {return C.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_image()@@ -740,7 +749,7 @@ func uniffiCheckChecksums() {checksum := rustCall(func(_uniffiStatus *C.RustCallStatus) C.uint16_t {return C.uniffi_cyclops_sdk_checksum_method_httpclient_execute()})- if checksum != 33213 {+ if checksum != 57947 {// If this happens try cleaning and rebuilding your projectpanic("fleet_sdk: uniffi_cyclops_sdk_checksum_method_httpclient_execute: UniFFI API checksum mismatch")}@@ -1357,6 +1366,10 @@ type CyclopsClientInterface interface {RenewClaim(claim Claim, shutdownTime string) (Claim, error)WaitClaim(claim Claim) (Sandbox, error)PresignImageUploads(request ImageUploadRequest) (ImageUploadResponse, error)+ // Hash and upload one file, or reuse a matching existing object.+ // Returns only the bound digest, size, and tenant reference, never a signed URL.+ // This does not create an Image or attest to object versioning/encryption.+ UploadImageFile(namespace string, name string, contents []byte) (ImageUploadInstruction, error)CreateImage(namespace string, manifest *cyclops_sdk_schema.PreservedJson) (*cyclops_sdk_schema.PreservedJson, error)DeleteImage(namespace string, name string) errorGetImage(namespace string, name string) (*cyclops_sdk_schema.PreservedJson, error)@@ -1720,6 +1733,44 @@ func (_self *CyclopsClient) PresignImageUploads(request ImageUploadRequest) (Imareturn res, err}+// Hash and upload one file, or reuse a matching existing object.+// Returns only the bound digest, size, and tenant reference, never a signed URL.+// This does not create an Image or attest to object versioning/encryption.+func (_self *CyclopsClient) UploadImageFile(namespace string, name string, contents []byte) (ImageUploadInstruction, error) {+ _pointer := _self.ffiObject.incrementPointer("*CyclopsClient")+ defer _self.ffiObject.decrementPointer()+ res, err := uniffiRustCallAsync[*SdkError](+ FfiConverterSdkErrorINSTANCE,+ // completeFn+ func(handle C.uint64_t, status *C.RustCallStatus) RustBufferI {+ res := C.ffi_cyclops_sdk_rust_future_complete_rust_buffer(handle, status)+ return GoRustBuffer{+ inner: res,+ }+ },+ // liftFn+ func(ffi RustBufferI) ImageUploadInstruction {+ return FfiConverterImageUploadInstructionINSTANCE.Lift(ffi)+ },+ C.uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(+ _pointer, FfiConverterStringINSTANCE.Lower(namespace), FfiConverterStringINSTANCE.Lower(name), FfiConverterBytesINSTANCE.Lower(contents)),+ // pollFn+ func(handle C.uint64_t, continuation C.UniffiRustFutureContinuationCallback, data C.uint64_t) {+ C.ffi_cyclops_sdk_rust_future_poll_rust_buffer(handle, continuation, data)+ },+ // freeFn+ func(handle C.uint64_t) {+ C.ffi_cyclops_sdk_rust_future_free_rust_buffer(handle)+ },+ )++ if err == nil {+ return res, nil+ }++ return res, err+}+func (_self *CyclopsClient) CreateImage(namespace string, manifest *cyclops_sdk_schema.PreservedJson) (*cyclops_sdk_schema.PreservedJson, error) {_pointer := _self.ffiObject.incrementPointer("*CyclopsClient")defer _self.ffiObject.decrementPointer()@@ -2769,6 +2820,9 @@ func (_ FfiDestroyerCyclopsCredentials) Destroy(value *CyclopsCredentials) {type HttpClient interface {// Executes an HTTP request. Foreign implementations must enforce// `request.max_response_bytes` while streaming the response body.+ // Implementations must not follow redirects, retry requests, or add ambient+ // authentication/cookies. Send only the supplied headers and body; signed+ // upload requests also use this interface and must not leak credentials.Execute(request HttpRequest) (HttpResponse, error)}type HttpClientImpl struct {@@ -2777,6 +2831,9 @@ type HttpClientImpl struct {// Executes an HTTP request. Foreign implementations must enforce// `request.max_response_bytes` while streaming the response body.+// Implementations must not follow redirects, retry requests, or add ambient+// authentication/cookies. Send only the supplied headers and body; signed+// upload requests also use this interface and must not leak credentials.func (_self *HttpClientImpl) Execute(request HttpRequest) (HttpResponse, error) {_pointer := _self.ffiObject.incrementPointer("HttpClient")defer _self.ffiObject.decrementPointer()diff --git a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.h b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.hindex 92d4d433f3..0463f0c595 100644--- a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.h+++ b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.h@@ -496,6 +496,11 @@ uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(uint64_t ptr, Rusuint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_presign_image_uploads(uint64_t ptr, RustBuffer request);#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_UPLOAD_IMAGE_FILE+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_UPLOAD_IMAGE_FILE+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(uint64_t ptr, RustBuffer namespace, RustBuffer name, RustBuffer contents+);+#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_IMAGE#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_IMAGEuint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_create_image(uint64_t ptr, RustBuffer namespace, uint64_t manifest@@ -1358,6 +1363,12 @@ uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim(void#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_PRESIGN_IMAGE_UPLOADSuint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_presign_image_uploads(void+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_UPLOAD_IMAGE_FILE+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_UPLOAD_IMAGE_FILE+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file(void+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_IMAGEdiff --git a/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt b/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.ktindex 966399614a..9840b2619e 100644--- a/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt+++ b/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt@@ -729,6 +729,8 @@ internal object IntegrityCheckingUniffiLib {): Shortexternal fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_presign_image_uploads(): Short+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file(+ ): Shortexternal fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_image(): Shortexternal fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_image(@@ -946,6 +948,8 @@ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(`ptr`: Long,`): Longexternal fun uniffi_cyclops_sdk_fn_method_cyclopsclient_presign_image_uploads(`ptr`: Long,`request`: RustBuffer.ByValue,): Long+external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(`ptr`: Long,`namespace`: RustBuffer.ByValue,`name`: RustBuffer.ByValue,`contents`: RustBuffer.ByValue,+): Longexternal fun uniffi_cyclops_sdk_fn_method_cyclopsclient_create_image(`ptr`: Long,`namespace`: RustBuffer.ByValue,`manifest`: Long,): Longexternal fun uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_image(`ptr`: Long,`namespace`: RustBuffer.ByValue,`name`: RustBuffer.ByValue,@@ -1309,6 +1313,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_presign_image_uploads() != 53280.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file() != 14212.toShort()) {+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ }if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_image() != 51053.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}@@ -1393,7 +1400,7 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cyclops_sdk_checksum_method_accesstokenprovider_get_access_token() != 1180.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}- if (lib.uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 33213.toShort()) {+ if (lib.uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 57947.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}if (lib.uniffi_cyclops_sdk_checksum_method_createclaimrequestbuilder_build() != 10518.toShort()) {@@ -4001,6 +4008,13 @@ public interface CyclopsClientInterface {suspend fun `presignImageUploads`(`request`: ImageUploadRequest): ImageUploadResponse+ /**+ * Hash and upload one file, or reuse a matching existing object.+ * Returns only the bound digest, size, and tenant reference, never a signed URL.+ * This does not create an Image or attest to object versioning/encryption.+ */+ suspend fun `uploadImageFile`(`namespace`: kotlin.String, `name`: kotlin.String, `contents`: kotlin.ByteArray): ImageUploadInstruction+suspend fun `createImage`(`namespace`: kotlin.String, `manifest`: PreservedJson): PreservedJsonsuspend fun `deleteImage`(`namespace`: kotlin.String, `name`: kotlin.String)@@ -4311,6 +4325,32 @@ open class CyclopsClient: Disposable, AutoCloseable, CyclopsClientInterface}+ /**+ * Hash and upload one file, or reuse a matching existing object.+ * Returns only the bound digest, size, and tenant reference, never a signed URL.+ * This does not create an Image or attest to object versioning/encryption.+ */+ @Throws(SdkException::class)+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")+ override suspend fun `uploadImageFile`(`namespace`: kotlin.String, `name`: kotlin.String, `contents`: kotlin.ByteArray) : ImageUploadInstruction {+ return uniffiRustCallAsync(+ callWithHandle { uniffiHandle ->+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(+ uniffiHandle,+ FfiConverterString.lower(`namespace`),FfiConverterString.lower(`name`),FfiConverterByteArray.lower(`contents`),+ )+ },+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },+ // lift function+ { FfiConverterTypeImageUploadInstruction.lift(it) },+ // Error FFI converter+ SdkException.ErrorHandler,+ )+ }++@Throws(SdkException::class)@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")override suspend fun `createImage`(`namespace`: kotlin.String, `manifest`: PreservedJson) : PreservedJson {@@ -5681,6 +5721,9 @@ public interface HttpClient {/*** Executes an HTTP request. Foreign implementations must enforce* `request.max_response_bytes` while streaming the response body.+ * Implementations must not follow redirects, retry requests, or add ambient+ * authentication/cookies. Send only the supplied headers and body; signed+ * upload requests also use this interface and must not leak credentials.*/suspend fun `execute`(`request`: HttpRequest): HttpResponse@@ -5787,6 +5830,9 @@ open class HttpClientImpl: Disposable, AutoCloseable, HttpClient/*** Executes an HTTP request. Foreign implementations must enforce* `request.max_response_bytes` while streaming the response body.+ * Implementations must not follow redirects, retry requests, or add ambient+ * authentication/cookies. Send only the supplied headers and body; signed+ * upload requests also use this interface and must not leak credentials.*/@Throws(HttpException::class)@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")diff --git a/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py b/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.pyindex e06899a7a9..4d5869bd05 100644--- a/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py+++ b/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py@@ -620,6 +620,8 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template() != 18704:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file() != 14212:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim() != 18984:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new() != 25746:@@ -638,7 +640,7 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cyclops_sdk_checksum_method_cyclopstokenproviderconfigurationbuilder_pool_poll_limit() != 6865:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")- if lib.uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 33213:+ if lib.uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 57947:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cyclops_sdk_checksum_constructor_httprequestbuilder_new() != 25892:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")@@ -1459,6 +1461,13 @@ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_update_template.argtypes =_UniffiRustBuffer,)_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_update_template.restype = ctypes.c_uint64+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file.argtypes = (+ ctypes.c_uint64,+ _UniffiRustBuffer,+ _UniffiRustBuffer,+ _UniffiRustBuffer,+)+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file.restype = ctypes.c_uint64_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim.argtypes = (ctypes.c_uint64,_UniffiRustBuffer,@@ -1805,6 +1814,9 @@ _UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_pool.restype_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template.argtypes = ()_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template.restype = ctypes.c_uint16+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file.argtypes = (+)+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file.restype = ctypes.c_uint16_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim.argtypes = ()_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim.restype = ctypes.c_uint16@@ -5311,6 +5323,13 @@ class CyclopsClientProtocol(typing.Protocol):raise NotImplementedErrorasync def update_template(self, template: Template) -> Template:raise NotImplementedError+ async def upload_image_file(self, namespace: str,name: str,contents: bytes) -> ImageUploadInstruction:+ """+ Hash and upload one file, or reuse a matching existing object.+ Returns only the bound digest, size, and tenant reference, never a signed URL.+ This does not create an Image or attest to object versioning/encryption.+"""+ raise NotImplementedErrorasync def wait_claim(self, claim: Claim) -> Sandbox:raise NotImplementedError@@ -6054,6 +6073,34 @@ class CyclopsClient(CyclopsClientProtocol):_uniffi_lift_return,_uniffi_error_converter,)+ async def upload_image_file(self, namespace: str,name: str,contents: bytes) -> ImageUploadInstruction:+ """+ Hash and upload one file, or reuse a matching existing object.+ Returns only the bound digest, size, and tenant reference, never a signed URL.+ This does not create an Image or attest to object versioning/encryption.+"""++ _UniffiFfiConverterString.check_lower(namespace)++ _UniffiFfiConverterString.check_lower(name)++ _UniffiFfiConverterBytes.check_lower(contents)+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ _UniffiFfiConverterString.lower(namespace),+ _UniffiFfiConverterString.lower(name),+ _UniffiFfiConverterBytes.lower(contents),+ )+ _uniffi_lift_return = _UniffiFfiConverterTypeImageUploadInstruction.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError+ return await _uniffi_rust_call_async(+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(*_uniffi_lowered_args),+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,+ _uniffi_lift_return,+ _uniffi_error_converter,+ )async def wait_claim(self, claim: Claim) -> Sandbox:_UniffiFfiConverterTypeClaim.check_lower(claim)@@ -6273,6 +6320,9 @@ class HttpClient():"""Executes an HTTP request. Foreign implementations must enforce`request.max_response_bytes` while streaming the response body.+ Implementations must not follow redirects, retry requests, or add ambient+ authentication/cookies. Send only the supplied headers and body; signed+ upload requests also use this interface and must not leak credentials."""raise NotImplementedError@@ -6304,6 +6354,9 @@ class HttpClientImpl(HttpClient):"""Executes an HTTP request. Foreign implementations must enforce`request.max_response_bytes` while streaming the response body.+ Implementations must not follow redirects, retry requests, or add ambient+ authentication/cookies. Send only the supplied headers and body; signed+ upload requests also use this interface and must not leak credentials."""_UniffiFfiConverterTypeHttpRequest.check_lower(request)diff --git a/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb b/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rbindex 440937f2a3..f270e690e2 100644--- a/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb+++ b/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb@@ -3214,6 +3214,9 @@ module UniFFILibattach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_presign_image_uploads,[:uint64, RustBuffer.by_value, RustCallStatus.by_ref],:uint64+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file,+ [:uint64, RustBuffer.by_value, RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref],+ :uint64attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_create_image,[:uint64, RustBuffer.by_value, :uint64, RustCallStatus.by_ref],:uint64@@ -3602,6 +3605,9 @@ module UniFFILibattach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_presign_image_uploads,[RustCallStatus.by_ref],:uint16+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file,+ [RustCallStatus.by_ref],+ :uint16attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_image,[RustCallStatus.by_ref],:uint16@@ -4832,6 +4838,22 @@ end)return result.consumeIntoTypeImageUploadResponseend+ def upload_image_file(namespace, name, contents)+ namespace = FleetSdk::uniffi_utf8(namespace)++ name = FleetSdk::uniffi_utf8(name)++ contents = FleetSdk::uniffi_bytes(contents)++ result = FleetSdk.uniffi_rust_future_rust_buffer(++ SdkError,++ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(uniffi_clone_handle(),RustBuffer.allocFromString(namespace),RustBuffer.allocFromString(name),RustBuffer.allocFromBytes(contents),RustCallStatus.new),++ )+ return result.consumeIntoTypeImageUploadInstruction+ enddef create_image(namespace, manifest)namespace = FleetSdk::uniffi_utf8(namespace)diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift b/libs/fleet/sdk-bindings/swift/CyclopsSdk.swiftindex 9a5ce4a7f0..ee3cd7b32a 100644--- a/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift@@ -1563,6 +1563,13 @@ public protocol CyclopsClientProtocol: AnyObject, Sendable {func presignImageUploads(request: ImageUploadRequest) async throws -> ImageUploadResponse+ /**+ * Hash and upload one file, or reuse a matching existing object.+ * Returns only the bound digest, size, and tenant reference, never a signed URL.+ * This does not create an Image or attest to object versioning/encryption.+ */+ func uploadImageFile(namespace: String, name: String, contents: Data) async throws -> ImageUploadInstruction+func createImage(namespace: String, manifest: PreservedJson) async throws -> PreservedJsonfunc deleteImage(namespace: String, name: String) async throws@@ -1862,6 +1869,28 @@ open func presignImageUploads(request: ImageUploadRequest)async throws -> Image)}+ /**+ * Hash and upload one file, or reuse a matching existing object.+ * Returns only the bound digest, size, and tenant reference, never a signed URL.+ * This does not create an Image or attest to object versioning/encryption.+ */+open func uploadImageFile(namespace: String, name: String, contents: Data)async throws -> ImageUploadInstruction {+ return+ try await uniffiRustCallAsync(+ rustFutureFunc: {+ uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(+ self.uniffiCloneHandle(),+ FfiConverterString.lower(namespace),FfiConverterString.lower(name),FfiConverterData.lower(contents)+ )+ },+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,+ liftFunc: FfiConverterTypeImageUploadInstruction_lift,+ errorHandler: FfiConverterTypeSdkError_lift+ )+}+open func createImage(namespace: String, manifest: PreservedJson)async throws -> PreservedJson {returntry await uniffiRustCallAsync(@@ -2669,6 +2698,9 @@ public protocol HttpClient: AnyObject, Sendable {/*** Executes an HTTP request. Foreign implementations must enforce* `request.max_response_bytes` while streaming the response body.+ * Implementations must not follow redirects, retry requests, or add ambient+ * authentication/cookies. Send only the supplied headers and body; signed+ * upload requests also use this interface and must not leak credentials.*/func execute(request: HttpRequest) async throws -> HttpResponse@@ -2729,6 +2761,9 @@ open class HttpClientImpl: HttpClient, @unchecked Sendable {/*** Executes an HTTP request. Foreign implementations must enforce* `request.max_response_bytes` while streaming the response body.+ * Implementations must not follow redirects, retry requests, or add ambient+ * authentication/cookies. Send only the supplied headers and body; signed+ * upload requests also use this interface and must not leak credentials.*/open func execute(request: HttpRequest)async throws -> HttpResponse {return@@ -6041,6 +6076,9 @@ private let initializationResult: InitializationResult = {if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_presign_image_uploads() != 53280) {return InitializationResult.apiChecksumMismatch}+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file() != 14212) {+ return InitializationResult.apiChecksumMismatch+ }if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_image() != 51053) {return InitializationResult.apiChecksumMismatch}@@ -6125,7 +6163,7 @@ private let initializationResult: InitializationResult = {if (uniffi_cyclops_sdk_checksum_method_accesstokenprovider_get_access_token() != 1180) {return InitializationResult.apiChecksumMismatch}- if (uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 33213) {+ if (uniffi_cyclops_sdk_checksum_method_httpclient_execute() != 57947) {return InitializationResult.apiChecksumMismatch}if (uniffi_cyclops_sdk_checksum_method_createclaimrequestbuilder_build() != 10518) {diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h b/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.hindex 87cd56ebce..580035b4a4 100644--- a/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h@@ -353,6 +353,11 @@ uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(uint64_t ptr, Rusuint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_presign_image_uploads(uint64_t ptr, RustBuffer request);#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_UPLOAD_IMAGE_FILE+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_UPLOAD_IMAGE_FILE+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(uint64_t ptr, RustBuffer namespace, RustBuffer name, RustBuffer contents+);+#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_IMAGE#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_IMAGEuint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_create_image(uint64_t ptr, RustBuffer namespace, uint64_t manifest@@ -1215,6 +1220,12 @@ uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim(void#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_PRESIGN_IMAGE_UPLOADSuint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_presign_image_uploads(void+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_UPLOAD_IMAGE_FILE+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_UPLOAD_IMAGE_FILE+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file(void+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_IMAGEdiff --git a/libs/fleet/sdk-bindings/ts-uniffi-browser/cpp/fleet_sdk_module.rs b/libs/fleet/sdk-bindings/ts-uniffi-browser/cpp/fleet_sdk_module.rsindex d8db0787f9..f71b52103b 100644--- a/libs/fleet/sdk-bindings/ts-uniffi-browser/cpp/fleet_sdk_module.rs+++ b/libs/fleet/sdk-bindings/ts-uniffi-browser/cpp/fleet_sdk_module.rs@@ -67,6 +67,12 @@ extern "C" {ptr: u64,request: u::RustBuffer,) -> u64;+ fn uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(+ ptr: u64,+ namespace: u::RustBuffer,+ name: u::RustBuffer,+ contents: u::RustBuffer,+ ) -> u64;fn uniffi_cyclops_sdk_fn_method_cyclopsclient_create_image(ptr: u64,namespace: u::RustBuffer,@@ -607,6 +613,7 @@ extern "C" {fn uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim() -> u16;fn uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim() -> u16;fn uniffi_cyclops_sdk_checksum_method_cyclopsclient_presign_image_uploads() -> u16;+ fn uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file() -> u16;fn uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_image() -> u16;fn uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_image() -> u16;fn uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_image() -> u16;@@ -914,6 +921,21 @@ pub unsafe fn ubrn_uniffi_cyclops_sdk_fn_method_cyclopsclient_presign_image_uplo.into_js()}#[wasm_bindgen]+pub unsafe fn ubrn_uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(+ ptr: js::Handle,+ namespace: js::ForeignBytes,+ name: js::ForeignBytes,+ contents: js::ForeignBytes,+) -> js::Handle {+ uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(+ u64::into_rust(ptr),+ u::RustBuffer::into_rust(namespace),+ u::RustBuffer::into_rust(name),+ u::RustBuffer::into_rust(contents),+ )+ .into_js()+}+#[wasm_bindgen]pub unsafe fn ubrn_uniffi_cyclops_sdk_fn_method_cyclopsclient_create_image(ptr: js::Handle,namespace: js::ForeignBytes,@@ -2710,6 +2732,11 @@ pub unsafe fn ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_presign_imaguniffi_cyclops_sdk_checksum_method_cyclopsclient_presign_image_uploads().into_js()}#[wasm_bindgen]+pub unsafe fn ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file() -> js::UInt16+{+ uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file().into_js()+}+#[wasm_bindgen]pub unsafe fn ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_image() -> js::UInt16 {uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_image().into_js()}diff --git a/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts b/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.tsindex c914f52e58..007662dc81 100644--- a/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts+++ b/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts@@ -3624,6 +3624,12 @@ export interface CyclopsClientLike {serviceRequest(sandbox: Sandbox, service: string, path: string, request: HttpRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<HttpResponse>;updatePool(pool: Pool, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Pool>;updateTemplate(template: Template, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Template>;+/**+ * Hash and upload one file, or reuse a matching existing object.+ * Returns only the bound digest, size, and tenant reference, never a signed URL.+ * This does not create an Image or attest to object versioning/encryption.+ */+ uploadImageFile(namespace: string, name: string, contents: ArrayBuffer, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ImageUploadInstruction>;waitClaim(claim: Claim, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Sandbox>;}/**@@ -4504,6 +4510,35 @@ private constructor(pointer: UniffiHandle) {);}+/**+ * Hash and upload one file, or reuse a matching existing object.+ * Returns only the bound digest, size, and tenant reference, never a signed URL.+ * This does not create an Image or attest to object versioning/encryption.+ */+ async uploadImageFile(namespace: string, name: string, contents: ArrayBuffer, asyncOpts_?: { signal: AbortSignal }): Promise<ImageUploadInstruction> /*throws*/ {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().ubrn_uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(+ uniffiTypeCyclopsClientObjectFactory.clonePointer(this),FfiConverterString.lower(namespace, nativeModule().rustbuffer_alloc),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc),FfiConverterArrayBuffer.lower(contents, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ubrn_ffi_cyclops_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ubrn_ffi_cyclops_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ubrn_ffi_cyclops_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ubrn_ffi_cyclops_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterTypeImageUploadInstruction.lift.bind(FfiConverterTypeImageUploadInstruction),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeSdkError.lift.bind(FfiConverterTypeSdkError)+ );+ }+async waitClaim(claim: Claim, asyncOpts_?: { signal: AbortSignal }): Promise<Sandbox> /*throws*/ {return await uniffiRustCallAsync(/*rustCaller:*/ uniffiCaller,@@ -4808,6 +4843,9 @@ export interface HttpClient {/*** Executes an HTTP request. Foreign implementations must enforce* `request.max_response_bytes` while streaming the response body.+ * Implementations must not follow redirects, retry requests, or add ambient+ * authentication/cookies. Send only the supplied headers and body; signed+ * upload requests also use this interface and must not leak credentials.*/execute(request: HttpRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<HttpResponse>;}@@ -4831,6 +4869,9 @@ private constructor(pointer: UniffiHandle) {/*** Executes an HTTP request. Foreign implementations must enforce* `request.max_response_bytes` while streaming the response body.+ * Implementations must not follow redirects, retry requests, or add ambient+ * authentication/cookies. Send only the supplied headers and body; signed+ * upload requests also use this interface and must not leak credentials.*/async execute(request: HttpRequest, asyncOpts_?: { signal: AbortSignal }): Promise<HttpResponse> /*throws*/ {return await uniffiRustCallAsync(@@ -5681,6 +5722,9 @@ function uniffiEnsureInitialized() {if (nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template() !== 18704) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template");}+ if (nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file() !== 14212) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file");+ }if (nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim() !== 18984) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim");}@@ -5708,7 +5752,7 @@ function uniffiEnsureInitialized() {if (nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopstokenproviderconfigurationbuilder_pool_poll_limit() !== 6865) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopstokenproviderconfigurationbuilder_pool_poll_limit");}- if (nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_httpclient_execute() !== 33213) {+ if (nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_httpclient_execute() !== 57947) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_httpclient_execute");}if (nativeModule().ubrn_uniffi_cyclops_sdk_checksum_constructor_httprequestbuilder_new() !== 25892) {diff --git a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk-ffi.ts b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk-ffi.tsindex 3fdc1a9325..2e8905caf4 100644--- a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk-ffi.ts+++ b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk-ffi.ts@@ -743,6 +743,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file": {+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim": {args: [FfiType.Handle, FfiType.RustBuffer],ret: FfiType.Handle,@@ -1218,6 +1223,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim": {args: [],ret: FfiType.UInt16,@@ -1555,6 +1565,7 @@ interface NativeModuleInterface {uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request(uniffiSelf: bigint, sandbox: Uint8Array, service: Uint8Array, path: Uint8Array, request: Uint8Array): bigint;uniffi_cyclops_sdk_fn_method_cyclopsclient_update_pool(uniffiSelf: bigint, pool: Uint8Array): bigint;uniffi_cyclops_sdk_fn_method_cyclopsclient_update_template(uniffiSelf: bigint, template: Uint8Array): bigint;+ uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(uniffiSelf: bigint, namespace: Uint8Array, name: Uint8Array, contents: Uint8Array): bigint;uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(uniffiSelf: bigint, claim: Uint8Array): bigint;uniffi_cyclops_sdk_fn_constructor_cyclopscredentials_new(clientId: Uint8Array, clientSecret: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;uniffi_cyclops_sdk_fn_constructor_cyclopstokenproviderconfigurationbuilder_new(uniffi_out_err: UniffiRustCallStatus): bigint;@@ -1650,6 +1661,7 @@ interface NativeModuleInterface {uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request(): number;uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_pool(): number;uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template(): number;+ uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file(): number;uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim(): number;uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new(): number;uniffi_cyclops_sdk_checksum_constructor_cyclopstokenproviderconfigurationbuilder_new(): number;diff --git a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.tsindex affaaf5040..44cd23d2cb 100644--- a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts+++ b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts@@ -2791,6 +2791,12 @@ export interface CyclopsClientLike {serviceRequest(sandbox: Sandbox, service: string, path: string, request: HttpRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<HttpResponse>;updatePool(pool: Pool, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Pool>;updateTemplate(template: Template, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Template>;+/**+ * Hash and upload one file, or reuse a matching existing object.+ * Returns only the bound digest, size, and tenant reference, never a signed URL.+ * This does not create an Image or attest to object versioning/encryption.+ */+ uploadImageFile(namespace: string, name: string, contents: ArrayBuffer, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ImageUploadInstruction>;waitClaim(claim: Claim, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Sandbox>;}/**@@ -3935,6 +3941,43 @@ private constructor(pointer: UniffiHandle) {}}+/**+ * Hash and upload one file, or reuse a matching existing object.+ * Returns only the bound digest, size, and tenant reference, never a signed URL.+ * This does not create an Image or attest to object versioning/encryption.+ */+ async uploadImageFile(namespace: string, name: string, contents: ArrayBuffer, asyncOpts_?: { signal: AbortSignal }): Promise<ImageUploadInstruction> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cyclops_sdk_fn_method_cyclopsclient_upload_image_file(+ uniffiTypeCyclopsClientObjectFactory.clonePointer(this),FfiConverterString.lower(namespace, nativeModule().rustbuffer_alloc),FfiConverterString.lower(name, nativeModule().rustbuffer_alloc),FfiConverterArrayBuffer.lower(contents, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterTypeImageUploadInstruction.lift.bind(FfiConverterTypeImageUploadInstruction),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeSdkError.lift.bind(FfiConverterTypeSdkError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+async waitClaim(claim: Claim, asyncOpts_?: { signal: AbortSignal }): Promise<Sandbox> /*throws*/ {const __stack = uniffiIsDebug ? new Error().stack : undefined;try {@@ -4052,6 +4095,9 @@ export interface HttpClient {/*** Executes an HTTP request. Foreign implementations must enforce* `request.max_response_bytes` while streaming the response body.+ * Implementations must not follow redirects, retry requests, or add ambient+ * authentication/cookies. Send only the supplied headers and body; signed+ * upload requests also use this interface and must not leak credentials.*/execute(request: HttpRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<HttpResponse>;}@@ -4075,6 +4121,9 @@ private constructor(pointer: UniffiHandle) {/*** Executes an HTTP request. Foreign implementations must enforce* `request.max_response_bytes` while streaming the response body.+ * Implementations must not follow redirects, retry requests, or add ambient+ * authentication/cookies. Send only the supplied headers and body; signed+ * upload requests also use this interface and must not leak credentials.*/async execute(request: HttpRequest, asyncOpts_?: { signal: AbortSignal }): Promise<HttpResponse> /*throws*/ {const __stack = uniffiIsDebug ? new Error().stack : undefined;@@ -4470,13 +4519,16 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template() !== 18704) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template");}+ if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file() !== 14212) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_upload_image_file");+ }if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim() !== 18984) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim");}if (nativeModule().uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new() !== 25746) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_constructor_cyclopscredentials_new");}- if (nativeModule().uniffi_cyclops_sdk_checksum_method_httpclient_execute() !== 33213) {+ if (nativeModule().uniffi_cyclops_sdk_checksum_method_httpclient_execute() !== 57947) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_httpclient_execute");}diff --git a/libs/fleet/sdk/Cargo.toml b/libs/fleet/sdk/Cargo.tomlindex 9b37850cd6..1fedf8bcf8 100644--- a/libs/fleet/sdk/Cargo.toml+++ b/libs/fleet/sdk/Cargo.toml@@ -19,6 +19,7 @@ petname = { version = "2", default-features = false, features = [] }serde.workspace = trueserde_json.workspace = true+sha2 = "0.10"thiserror.workspace = truetokio = { workspace = true, features = ["sync"] }uniffi.workspace = true@@ -36,7 +37,7 @@ js-sys = "0.3"wasm-bindgen = "0.2"wasm-bindgen-futures = "0.4"web-time = "1.1.0"-web-sys = { version = "0.3", features = ["Headers", "ReadableStream", "ReadableStreamDefaultReader", "Request", "RequestInit", "Response", "Window"] }+web-sys = { version = "0.3", features = ["AbortController", "AbortSignal", "Headers", "ReadableStream", "ReadableStreamDefaultReader", "Request", "RequestInit", "RequestRedirect", "RequestCredentials", "Response", "Window"] }[dev-dependencies]camino = "1.0"diff --git a/libs/fleet/sdk/README.md b/libs/fleet/sdk/README.mdnew file mode 100644index 0000000000..4195d2afee--- /dev/null+++ b/libs/fleet/sdk/README.md@@ -0,0 +1,51 @@+# Image file uploads++Use `CyclopsClient.upload_image_file(namespace, name, contents)` with a native+HTTP client (or the browser constructor). `name` is a basename; `contents` is the+complete file as bytes, so callers must budget memory for it.++See the [Python image-build example](../sdk-bindings/examples/python/IMAGE_BUILD.md)+for file mappings, Image creation, and generation-pinned status polling.+Initial infrastructure activation is **native-only**. Browser uploads require+explicitly configured S3 CORS for the application origin, PUT, and the returned+signed headers; browser transport support alone does not enable S3 access.++```rust,ignore+let uploaded = client.clone().upload_image_file(+ "workers".into(),+ "rootfs.tar".into(),+ std::fs::read("rootfs.tar")?,+).await?;+assert!(uploaded.upload.is_none());+// Use uploaded.reference, uploaded.digest, and uploaded.size_bytes in the recipe.+```++The SDK hashes the bytes, calls the authenticated presign endpoint, and checks+that exactly one result binds the digest, size, and canonical tenant reference.+It reuses a matching existing object or PUTs the bytes to the HTTPS signed URL.+Returned headers are preserved, with checksum and length checked when supplied.+Presign requests have a 30-second timeout and a 1 MiB response limit. The PUT+has a 300-second timeout and a 4 KiB response limit, never acquires or refreshes+a token, and accepts only 200/201/204 as completed uploads. Both built-in+transports enforce deadlines across sending and reading the response body,+enforce response limits, and reject redirects; the helper never retries.+Failures redact signed URLs and response bodies while retaining error classes+and HTTP statuses. Successful+results contain no upload instructions.++This method does not create an Image. Only submit the recipe after every upload+succeeds. It does not attest to storage encryption, object versions, readiness,+or controller resolution; those remain backend/controller responsibilities.++Custom `HttpClient` implementations must obey the transport contract: no+redirects, retries, ambient authentication, or cookies; preserve supplied headers+and enforce response limits while streaming. The built-in native transport is+the preferred path. Browser uploads additionally require configured S3 CORS;+the browser manages Host and Content-Length itself, omits cookies, and rejects+redirects. The existing Node `FetchHttpClient`, Go `netHTTPClient`, and Swift+`UrlSessionHttpClient` examples use default redirect behavior (Swift also uses+shared session state); they are **not upload-safe adapters**. The Kotlin and Ruby+examples likewise do not enforce streaming response limits. None of these+illustrative custom adapters is certified for uploads: use the native constructor+instead or explicitly implement the full contract. This helper cannot override a+foreign implementation's HTTP policy.diff --git a/libs/fleet/sdk/src/client.rs b/libs/fleet/sdk/src/client.rsindex fde94c9154..f92d691536 100644--- a/libs/fleet/sdk/src/client.rs+++ b/libs/fleet/sdk/src/client.rs@@ -198,6 +198,10 @@ impl CyclopsClient {}impl CyclopsClient {+ pub(crate) async fn send_image_upload(&self, request: HttpRequest) -> Result<(), SdkError> {+ self.transport.execute_upload(request).await+ }+pub(crate) fn base_url(&self) -> &Url {&self.base_url}diff --git a/libs/fleet/sdk/src/image_uploads.rs b/libs/fleet/sdk/src/image_uploads.rsindex ad4c6579fb..e01614e661 100644--- a/libs/fleet/sdk/src/image_uploads.rs+++ b/libs/fleet/sdk/src/image_uploads.rs@@ -1,5 +1,10 @@use crate::{CyclopsClient, HttpHeader, HttpRequest, SdkError, routes};+use base64::{+ Engine,+ engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},+};use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};use std::{collections::HashMap, sync::Arc};const JSON_CONTENT_TYPE: &str = "application/json";@@ -44,6 +49,65 @@ pub struct ImageUploadResponse {#[uniffi::export]impl CyclopsClient {+ /// Hash and upload one file, or reuse a matching existing object.+ /// Returns only the bound digest, size, and tenant reference, never a signed URL.+ /// This does not create an Image or attest to object versioning/encryption.+ pub async fn upload_image_file(+ self: Arc<Self>,+ namespace: String,+ name: String,+ contents: Vec<u8>,+ ) -> Result<ImageUploadInstruction, SdkError> {+ let checksum = Sha256::digest(&contents);+ let digest = format!("sha256:{checksum:x}");+ let size_bytes = contents.len() as u64;+ let tenant_hash = Sha256::digest(namespace.as_bytes());+ let tenant_hex = format!("{tenant_hash:x}");+ let reference = format!(+ "uploads/tenant-{}/{}",+ &tenant_hex[..32],+ URL_SAFE_NO_PAD.encode(Sha256::digest(digest.as_bytes()))+ );+ let mut response = Arc::clone(&self)+ .presign_image_uploads(ImageUploadRequest {+ namespace,+ files: vec![ImageUploadFileRequest {+ digest: digest.clone(),+ size_bytes,+ name,+ }],+ })+ .await+ .map_err(redact_presign_error)?;+ if response.files.len() != 1 {+ return Err(invalid_instruction());+ }+ let mut instruction = response.files.remove(0);+ if instruction.digest != digest+ || instruction.size_bytes != size_bytes+ || instruction.reference != reference+ {+ return Err(invalid_instruction());+ }+ if let Some(upload) = instruction.upload.take() {+ validate_upload(&upload, size_bytes, &STANDARD.encode(checksum))?;+ self.send_image_upload(HttpRequest {+ method: upload.method,+ url: upload.url,+ headers: upload+ .headers+ .into_iter()+ .map(|(name, value)| HttpHeader { name, value })+ .collect(),+ body: Some(contents),+ timeout_secs: Some(300),+ max_response_bytes: Some(4096),+ })+ .await?;+ }+ Ok(instruction)+ }+pub async fn presign_image_uploads(self: Arc<Self>,request: ImageUploadRequest,@@ -79,7 +143,126 @@ fn json_request(method: &str, url: url::Url, body: Option<Vec<u8>>) -> HttpReque},],body,- timeout_secs: None,- max_response_bytes: None,+ timeout_secs: Some(30),+ max_response_bytes: Some(1024 * 1024),+ }+}++fn invalid_instruction() -> SdkError {+ SdkError::Body {+ reason: "invalid image upload instruction".into(),+ }+}++fn validate_upload(upload: &PresignedPut, size_bytes: u64, checksum: &str) -> Result<(), SdkError> {+ let url = url::Url::parse(&upload.url).map_err(|_| invalid_instruction())?;+ let authority = upload+ .url+ .split_once("://")+ .map(|(_, rest)| rest.split(['/', '?', '#']).next().unwrap_or_default());+ if authority.is_none_or(|authority| authority.is_empty() || authority.contains('@'))+ || upload+ .url+ .bytes()+ .any(|byte| byte.is_ascii_whitespace() || byte == b'\\')+ || upload.method != "PUT"+ || url.scheme() != "https"+ || url.host_str().is_none()+ || !url.username().is_empty()+ || url.password().is_some()+ || url.fragment().is_some()+ {+ return Err(invalid_instruction());+ }+ let mut names = std::collections::HashSet::new();+ for (name, value) in &upload.headers {+ let lower = name.to_ascii_lowercase();+ if name.is_empty()+ || !name+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))+ || value+ .bytes()+ .any(|byte| (byte < 32 && byte != b'\t') || byte == 127)+ || !names.insert(lower.clone())+ || matches!(+ lower.as_str(),+ "authorization" | "proxy-authorization" | "cookie" | "transfer-encoding"+ )+ {+ return Err(invalid_instruction());+ }+ validate_signed_value(&lower, value, size_bytes, checksum)?;+ }+ for (name, value) in url.query_pairs() {+ validate_signed_value(&name.to_ascii_lowercase(), &value, size_bytes, checksum)?;+ }+ Ok(())+}++fn validate_signed_value(+ name: &str,+ value: &str,+ size_bytes: u64,+ checksum: &str,+) -> Result<(), SdkError> {+ if (name == "content-length"+ && (value.is_empty()+ || !value.bytes().all(|byte| byte.is_ascii_digit())+ || value.parse::<u64>().ok() != Some(size_bytes)))+ || (name == "x-amz-checksum-sha256" && value != checksum)+ {+ return Err(invalid_instruction());+ }+ Ok(())+}++fn redact_presign_error(mut error: SdkError) -> SdkError {+ match &mut error {+ SdkError::Status {+ operation, body, ..+ } => {+ *operation = "presign image uploads".into();+ body.clear();+ }+ SdkError::Configuration { reason }+ | SdkError::Transport { reason }+ | SdkError::Token { reason }+ | SdkError::Body { reason } => {+ *reason = "image upload presign failed".into();+ }+ SdkError::InvalidResourceName {+ field,+ value,+ reason,+ } => {+ field.clear();+ value.clear();+ *reason = "image upload presign failed".into();+ }+ SdkError::UnknownService {+ requested,+ available,+ } => {+ requested.clear();+ available.clear();+ }+ SdkError::InvalidServicePath { path } => path.clear(),+ SdkError::ClaimFailed { phase, status } => {+ phase.clear();+ status.clear();+ }+ SdkError::PoolAccessDenied {+ operation,+ namespace,+ body,+ ..+ } => {+ *operation = "presign image uploads".into();+ namespace.clear();+ body.clear();+ }+ SdkError::SignedServiceUrlsUnavailable | SdkError::ClaimTimeout => {}}+ error}diff --git a/libs/fleet/sdk/src/transport.rs b/libs/fleet/sdk/src/transport.rsindex 651680c417..225e0b7b88 100644--- a/libs/fleet/sdk/src/transport.rs+++ b/libs/fleet/sdk/src/transport.rs@@ -187,12 +187,67 @@ impl HttpClient for NativeHttpClient {pub trait HttpClient: Send + Sync {/// Executes an HTTP request. Foreign implementations must enforce/// `request.max_response_bytes` while streaming the response body.+ /// Implementations must not follow redirects, retry requests, or add ambient+ /// authentication/cookies. Send only the supplied headers and body; signed+ /// upload requests also use this interface and must not leak credentials.async fn execute(&self, request: HttpRequest) -> Result<HttpResponse, HttpError>;}#[cfg(target_arch = "wasm32")]pub(crate) struct BrowserHttpClient;+#[cfg(any(test, target_arch = "wasm32"))]+fn browser_timeout_millis(timeout_secs: Option<u64>) -> Result<Option<u32>, HttpError> {+ timeout_secs+ .map(|seconds| {+ seconds+ .checked_mul(1000)+ .filter(|millis| *millis <= i32::MAX as u64)+ .map(|millis| millis as u32)+ .ok_or_else(|| HttpError::Transport {+ reason: "HTTP timeout exceeds browser timer limit".into(),+ })+ })+ .transpose()+}++#[cfg(target_arch = "wasm32")]+struct BrowserRequestDeadline {+ controller: web_sys::AbortController,+ _timer: gloo_timers::callback::Timeout,+ completed: bool,+}++#[cfg(target_arch = "wasm32")]+impl BrowserRequestDeadline {+ fn new(+ timeout_secs: Option<u64>,+ init: &web_sys::RequestInit,+ ) -> Result<Option<Self>, HttpError> {+ let Some(millis) = browser_timeout_millis(timeout_secs)? else {+ return Ok(None);+ };+ let controller = web_sys::AbortController::new().map_err(browser_transport_error)?;+ init.set_signal(Some(&controller.signal()));+ let abort = controller.clone();+ let timer = gloo_timers::callback::Timeout::new(millis, move || abort.abort());+ Ok(Some(Self {+ controller,+ _timer: timer,+ completed: false,+ }))+ }+}++#[cfg(target_arch = "wasm32")]+impl Drop for BrowserRequestDeadline {+ fn drop(&mut self) {+ if !self.completed {+ self.controller.abort();+ }+ }+}+#[cfg(target_arch = "wasm32")]#[async_trait::async_trait(?Send)]impl HttpClient for BrowserHttpClient {@@ -203,11 +258,14 @@ impl HttpClient for BrowserHttpClient {let max_response_bytes = request.max_response_bytes;let init = web_sys::RequestInit::new();init.set_method(&request.method);+ init.set_redirect(web_sys::RequestRedirect::Error);+ init.set_credentials(web_sys::RequestCredentials::Omit);if let Some(body) = request.body {let body = js_sys::Uint8Array::from(body.as_slice());init.set_body(&body.into());}+ let mut deadline = BrowserRequestDeadline::new(request.timeout_secs, &init)?;let browser_request = web_sys::Request::new_with_str_and_init(&request.url, &init).map_err(browser_transport_error)?;let headers = browser_request.headers();@@ -226,6 +284,9 @@ impl HttpClient for BrowserHttpClient {.dyn_into::<web_sys::Response>().map_err(browser_transport_error)?;let body = read_browser_response_body(&response, max_response_bytes).await?;+ if let Some(deadline) = &mut deadline {+ deadline.completed = true;+ }Ok(HttpResponse {status: response.status(),@@ -421,6 +482,24 @@ impl Transport {.await}+ pub(crate) async fn execute_upload(&self, request: HttpRequest) -> Result<(), SdkError> {+ let response = self+ .http_client+ .execute(request)+ .await+ .map_err(|_| SdkError::Transport {+ reason: "image upload request failed".into(),+ })?;+ if !matches!(response.status, 200 | 201 | 204) {+ return Err(SdkError::Status {+ operation: "upload image file".into(),+ status: response.status,+ body: String::new(),+ });+ }+ Ok(())+ }+async fn execute_unchecked(&self, request: HttpRequest) -> Result<HttpResponse, SdkError> {self.http_client.execute(request)@@ -811,6 +890,48 @@ mod native_http_client_tests {assert!(matches!(redirected.accept(), Err(error) if error.kind() == ErrorKind::WouldBlock));}+ #[tokio::test]+ async fn native_transport_does_not_redirect_signed_puts() {+ let redirected = TcpListener::bind("127.0.0.1:0").unwrap();+ redirected.set_nonblocking(true).unwrap();+ let target = format!("http://{}/redirected", redirected.local_addr().unwrap());+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!(+ "http://{}/signed?signature=secret",+ listener.local_addr().unwrap()+ );+ let server = thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let request = read_request(&mut stream).to_ascii_lowercase();+ assert!(request.starts_with("put /signed?signature=secret "));+ assert!(request.contains("x-custom-signed: preserve exactly"));+ assert!(request.contains("content-length: 3"));+ assert!(!request.contains("authorization:"));+ let response = format!(+ "HTTP/1.1 307 Temporary Redirect\r\nlocation: {target}\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"+ );+ stream.write_all(response.as_bytes()).unwrap();+ });+ let response = NativeHttpClient::new()+ .unwrap()+ .execute(HttpRequest {+ method: "PUT".into(),+ url,+ headers: vec![HttpHeader {+ name: "x-custom-signed".into(),+ value: "preserve exactly".into(),+ }],+ body: Some(b"abc".to_vec()),+ timeout_secs: Some(5),+ max_response_bytes: Some(4096),+ })+ .await+ .unwrap();+ server.join().unwrap();+ assert_eq!(response.status, 307);+ assert!(matches!(redirected.accept(), Err(error) if error.kind() == ErrorKind::WouldBlock));+ }+#[tokio::test]async fn native_transport_enforces_limit_minus_one_exact_and_plus_one() {let below = execute_response("GET", fixed_response(b"abc"), Some(4))@@ -903,3 +1024,26 @@ mod native_tests {assert_eq!(overridden_request.timeout(), Some(&Duration::from_secs(75)));}}++#[cfg(test)]+mod browser_deadline_tests {+ use super::browser_timeout_millis;++ #[test]+ fn browser_deadline_preserves_none_and_converts_explicit_seconds() {+ assert_eq!(browser_timeout_millis(None).unwrap(), None);+ assert_eq!(browser_timeout_millis(Some(0)).unwrap(), Some(0));+ assert_eq!(browser_timeout_millis(Some(30)).unwrap(), Some(30_000));+ assert_eq!(browser_timeout_millis(Some(300)).unwrap(), Some(300_000));+ }++ #[test]+ fn browser_deadline_rejects_timer_overflow() {+ assert_eq!(+ browser_timeout_millis(Some(2_147_483)).unwrap(),+ Some(2_147_483_000)+ );+ assert!(browser_timeout_millis(Some(2_147_484)).is_err());+ assert!(browser_timeout_millis(Some(u64::MAX)).is_err());+ }+}diff --git a/libs/fleet/sdk/tests/image_upload_flow.rs b/libs/fleet/sdk/tests/image_upload_flow.rsindex a638f38c3f..d9a2e1e5ff 100644--- a/libs/fleet/sdk/tests/image_upload_flow.rs+++ b/libs/fleet/sdk/tests/image_upload_flow.rs@@ -46,6 +46,8 @@ async fn presign_image_uploads_posts_typed_request_and_returns_optional_upload()assert_eq!(requests.len(), 1);assert_eq!(requests[0].method, "POST");assert_eq!(requests[0].url.as_str(), UPLOAD_URL);+ assert_eq!(requests[0].timeout_secs, Some(30));+ assert_eq!(requests[0].max_response_bytes, Some(1024 * 1024));assert_eq!(serde_json::from_slice::<serde_json::Value>(requests[0].body.as_deref().unwrap()).unwrap(),serde_json::json!({@@ -100,3 +102,424 @@ fn response(status: u16, body: &[u8]) -> cyclops_sdk::HttpResponse {body: body.into(),}}++const FILE_DIGEST: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";+const REFERENCE: &str =+ "uploads/tenant-ed574aa71eb87d6cefff58373c93f1c2/kIt24leq5WBfxgNlqPjhOEGiFjnQtQGa0FkULIWw0Mo";+const SIGNED_URL: &str = "https://uploads.example.test/object?signature=secret";++fn instruction() -> serde_json::Value {+ serde_json::json!({"digest": FILE_DIGEST, "sizeBytes": 3, "reference": REFERENCE,+ "upload": {"method": "PUT", "url": SIGNED_URL, "headers": {+ "Content-Length": "3", "X-Amz-Checksum-Sha256": "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=",+ "x-custom-signed": "preserve exactly"}}})+}++fn presigned(files: serde_json::Value) -> cyclops_sdk::HttpResponse {+ response(+ 200,+ &serde_json::to_vec(&serde_json::json!({"files": files})).unwrap(),+ )+}++#[tokio::test]+async fn upload_hashes_bytes_and_isolates_auth_even_on_same_origin() {+ for url in [+ SIGNED_URL,+ "https://cyclops.example.test/signed?signature=secret",+ ] {+ let mut file = instruction();+ file["upload"]["url"] = url.into();+ let http = Arc::new(ScriptedHttpClient::new([+ Ok(token()),+ Ok(presigned(serde_json::json!([file]))),+ Ok(response(200, b"")),+ ]));+ let result = client(http.clone())+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap();+ assert_eq!(result.reference, REFERENCE);+ assert_eq!(result.digest, FILE_DIGEST);+ assert_eq!(result.size_bytes, 3);+ assert!(result.upload.is_none());+ let requests = http.requests().await;+ assert_eq!(requests.len(), 3);+ assert!(+ requests[1]+ .headers+ .iter()+ .any(|header| header.name.eq_ignore_ascii_case("authorization"))+ );+ assert_eq!(+ serde_json::from_slice::<serde_json::Value>(requests[1].body.as_ref().unwrap())+ .unwrap(),+ serde_json::json!({"namespace":"workers","files":[{"digest":FILE_DIGEST,"sizeBytes":3,"name":"rootfs"}]})+ );+ assert_eq!(requests[1].timeout_secs, Some(30));+ assert_eq!(requests[1].max_response_bytes, Some(1024 * 1024));+ assert_eq!(requests[2].timeout_secs, Some(300));+ assert_eq!(requests[2].max_response_bytes, Some(4096));+ assert_eq!(requests[2].method, "PUT");+ assert_eq!(requests[2].url, url);+ assert_eq!(requests[2].body.as_deref(), Some(b"abc".as_slice()));+ assert_eq!(requests[2].headers.len(), 3);+ for header in &requests[2].headers {+ assert_eq!(file["upload"]["headers"][&header.name], header.value);+ }+ }+}++#[tokio::test]+async fn matching_existing_object_skips_put() {+ let mut file = instruction();+ file["upload"] = serde_json::Value::Null;+ let http = Arc::new(ScriptedHttpClient::new([+ Ok(token()),+ Ok(presigned(serde_json::json!([file]))),+ ]));+ let result = client(http.clone())+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap();+ assert!(result.upload.is_none());+ assert_eq!(result.reference, REFERENCE);+ assert_eq!(http.request_count().await, 2);+}++#[tokio::test]+async fn malformed_instructions_never_upload() {+ let mut cases = vec![+ serde_json::json!([]),+ serde_json::json!([instruction(), instruction()]),+ ];+ for (pointer, value) in [+ ("/digest", serde_json::json!(DIGEST)),+ ("/sizeBytes", serde_json::json!(4)),+ (+ "/reference",+ serde_json::json!("uploads/tenant-other/token"),+ ),+ ("/upload/method", serde_json::json!("POST")),+ (+ "/upload/url",+ serde_json::json!("http://uploads.example.test/secret"),+ ),+ (+ "/upload/url",+ serde_json::json!("https://user:[email protected]/"),+ ),+ (+ "/upload/url",+ serde_json::json!("https://uploads.example.test/#secret"),+ ),+ ("/upload/url", serde_json::json!("not a URL secret")),+ ("/upload/headers/Content-Length", serde_json::json!("4")),+ (+ "/upload/headers/X-Amz-Checksum-Sha256",+ serde_json::json!("secret"),+ ),+ ] {+ let mut file = instruction();+ *file.pointer_mut(pointer).unwrap() = value;+ cases.push(serde_json::json!([file]));+ }+ for files in cases {+ let http = Arc::new(ScriptedHttpClient::new([Ok(token()), Ok(presigned(files))]));+ let error = client(http.clone())+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap_err();+ assert!(!format!("{error:?}").contains("secret"));+ assert_eq!(http.request_count().await, 2);+ }+}++#[tokio::test]+async fn put_errors_are_redacted_without_retry_refresh_or_image_creation() {+ let mut failures = vec![Err(cyclops_sdk::HttpError::Transport {+ reason: format!("timeout/network {SIGNED_URL} secret"),+ })];+ for status in [301, 307, 308, 400, 401, 403, 500] {+ failures.push(Ok(response(+ status,+ format!("{SIGNED_URL} secret").as_bytes(),+ )));+ }+ for failure in failures {+ let http = Arc::new(ScriptedHttpClient::new([+ Ok(token()),+ Ok(presigned(serde_json::json!([instruction()]))),+ failure,+ ]));+ let error = client(http.clone())+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap_err();+ assert!(!format!("{error:?}").contains("secret"));+ assert_eq!(http.request_count().await, 3);+ }+}++#[tokio::test]+async fn invalid_signed_headers_and_existing_object_bindings_are_rejected() {+ let mut cases = Vec::new();+ for (name, value) in [+ ("content-length", "3"),+ ("Authorization", "secret"),+ ("Cookie", "secret"),+ ("Transfer-Encoding", "chunked"),+ ("invalid header", "secret"),+ ("x-custom-signed", "secret\r\ninjected: yes"),+ ] {+ let mut file = instruction();+ file["upload"]["headers"][name] = value.into();+ cases.push(file);+ }+ for (field, value) in [+ ("digest", serde_json::json!(DIGEST)),+ ("sizeBytes", serde_json::json!(4)),+ ("reference", serde_json::json!("uploads/workers/secret")),+ ] {+ let mut file = instruction();+ file["upload"] = serde_json::Value::Null;+ file[field] = value;+ cases.push(file);+ }+ for url in [+ "https://uploads.example.test/?X-Amz-Checksum-Sha256=secret",+ "https://uploads.example.test/?content-length=4",+ "https://@uploads.example.test/secret",+ ] {+ let mut file = instruction();+ file["upload"]["url"] = url.into();+ cases.push(file);+ }+ for file in cases {+ let http = Arc::new(ScriptedHttpClient::new([+ Ok(token()),+ Ok(presigned(serde_json::json!([file]))),+ ]));+ let error = client(http.clone())+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap_err();+ assert!(!format!("{error:?}").contains("secret"));+ assert_eq!(http.request_count().await, 2);+ }+}++#[tokio::test]+async fn same_origin_put_401_does_not_refresh_token() {+ let mut file = instruction();+ file["upload"]["url"] = "https://cyclops.example.test/signed?signature=secret".into();+ let http = Arc::new(ScriptedHttpClient::new([+ Ok(token()),+ Ok(presigned(serde_json::json!([file]))),+ Ok(response(401, b"secret")),+ ]));+ let error = client(http.clone())+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap_err();+ assert!(matches!(+ error,+ cyclops_sdk::SdkError::Status { status: 401, .. }+ ));+ let requests = http.requests().await;+ assert_eq!(requests.len(), 3);+ assert!(+ !requests[2]+ .headers+ .iter()+ .any(|header| header.name.eq_ignore_ascii_case("authorization"))+ );+}++#[tokio::test]+async fn presign_errors_cannot_leak_signed_material() {+ for result in [+ Ok(response(403, SIGNED_URL.as_bytes())),+ Ok(response(200, br#"{"files":"secret"}"#)),+ Err(cyclops_sdk::HttpError::Transport {+ reason: SIGNED_URL.into(),+ }),+ ] {+ let http = Arc::new(ScriptedHttpClient::new([Ok(token()), result]));+ let error = client(http.clone())+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap_err();+ assert!(!format!("{error:?}").contains("secret"));+ assert_eq!(http.request_count().await, 2);+ }+}++#[tokio::test]+async fn upload_allows_absent_optional_signed_checksum_and_length() {+ let mut file = instruction();+ file["upload"]["headers"] = serde_json::json!({});+ let http = Arc::new(ScriptedHttpClient::new([+ Ok(token()),+ Ok(presigned(serde_json::json!([file]))),+ Ok(response(204, b"")),+ ]));+ assert!(+ client(http)+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap()+ .upload+ .is_none()+ );+}++#[tokio::test]+async fn presign_status_and_error_classification_survive_redaction() {+ for status in [403, 503] {+ let http = Arc::new(ScriptedHttpClient::new([+ Ok(token()),+ Ok(response(status, SIGNED_URL.as_bytes())),+ ]));+ let error = client(http.clone())+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap_err();+ match error {+ cyclops_sdk::SdkError::Status {+ status: actual,+ operation,+ body,+ } => {+ assert_eq!(actual, status);+ assert_eq!(operation, "presign image uploads");+ assert!(body.is_empty());+ }+ other => panic!("expected redacted status, got {other:?}"),+ }+ assert_eq!(http.request_count().await, 2);+ }+ let http = Arc::new(ScriptedHttpClient::new([+ Ok(token()),+ Ok(response(200, b"secret")),+ ]));+ let error = client(http)+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap_err();+ assert!(matches!(error, cyclops_sdk::SdkError::Body { .. }));+ let http = Arc::new(ScriptedHttpClient::new([Ok(response(200, b"secret"))]));+ let error = client(http.clone())+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap_err();+ assert!(matches!(error, cyclops_sdk::SdkError::Token { .. }));+ assert_eq!(http.request_count().await, 1);+}++#[tokio::test]+async fn presign_401_remains_authenticated_but_never_uploads_on_failure() {+ let http = Arc::new(ScriptedHttpClient::new([+ Ok(token()),+ Ok(response(401, b"secret")),+ Ok(token()),+ Ok(response(401, b"secret")),+ ]));+ let error = client(http.clone())+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap_err();+ assert!(matches!(+ error,+ cyclops_sdk::SdkError::Status { status: 401, .. }+ ));+ assert!(!format!("{error:?}").contains("secret"));+ assert_eq!(http.request_count().await, 4);+}++#[tokio::test]+async fn put_202_does_not_claim_upload_completion() {+ let http = Arc::new(ScriptedHttpClient::new([+ Ok(token()),+ Ok(presigned(serde_json::json!([instruction()]))),+ Ok(response(202, b"secret")),+ ]));+ let error = client(http.clone())+ .upload_image_file("workers".into(), "rootfs".into(), b"abc".to_vec())+ .await+ .unwrap_err();+ assert!(matches!(+ error,+ cyclops_sdk::SdkError::Status { status: 202, .. }+ ));+ assert!(!format!("{error:?}").contains("secret"));+ assert_eq!(http.request_count().await, 3);+}++#[tokio::test]+async fn native_presign_caps_success_and_error_bodies_before_parsing() {+ use std::io::{Read, Write};+ use std::net::TcpListener;++ for status in [200, 503] {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let base_url = format!("http://{}", listener.local_addr().unwrap());+ let server = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ stream+ .set_read_timeout(Some(std::time::Duration::from_secs(5)))+ .unwrap();+ let mut headers = Vec::new();+ while !headers.ends_with(b"\r\n\r\n") {+ let mut byte = [0];+ stream.read_exact(&mut byte).unwrap();+ headers.push(byte[0]);+ }+ let content_length = String::from_utf8(headers)+ .unwrap()+ .lines()+ .find_map(|line| {+ line.to_ascii_lowercase()+ .strip_prefix("content-length:")+ .map(|value| value.trim().parse::<usize>().unwrap())+ })+ .unwrap();+ stream.read_exact(&mut vec![0; content_length]).unwrap();+ let body = vec![b'x'; 1024 * 1024 + 1];+ write!(+ stream,+ "HTTP/1.1 {status} Response\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",+ body.len()+ )+ .unwrap();+ let _ = stream.write_all(&body);+ });+ let client = CyclopsClient::connect_with_access_token_and_native_http_client(+ cyclops_sdk::CyclopsTokenProviderConfiguration {+ base_url,+ pool_poll_interval_ms: 1,+ pool_poll_limit: 1,+ claim_poll_interval_ms: 1,+ claim_poll_limit: 1,+ },+ "token".into(),+ )+ .unwrap();+ let error = client+ .presign_image_uploads(ImageUploadRequest {+ namespace: "workers".into(),+ files: vec![ImageUploadFileRequest {+ digest: FILE_DIGEST.into(),+ size_bytes: 3,+ name: "rootfs".into(),+ }],+ })+ .await+ .unwrap_err();+ assert!(+ matches!(error, cyclops_sdk::SdkError::Transport { ref reason } if reason == "HTTP response exceeds configured size limit"),+ "{error:?}"+ );+ server.join().unwrap();+ }+}