Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -1492,6 +1492,12 @@ agent-device close
With `agentDevice.enabled` `false` or unset, on a worker or a gateway, every
`/v1/agent-device` URL answers `404`.

Downloads (artifacts) up to 2 GB (2147483648 bytes) are carried. A download
whose `content-length` is over that is answered `413` with
`{"ok": false, "code": "INVALID_ARGS", "error": "..."}` before any byte is
read. A download with no usable `content-length` that passes 2 GB is cut with
a failed response, never one that ends as if it were whole.

A **gateway** with `agentDevice.enabled` serves the same URL, and the CLI is
pointed at the gateway the same way. `open` lands only on a worker whose
agent-device is available, and the commands, heartbeats and `close` of that
Expand Down
158 changes: 158 additions & 0 deletions src/agent-device/edge.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
Expand Down Expand Up @@ -3701,3 +3702,160 @@ describe("a worker's capabilities in status.get, through the whole worker daemon
expect(workers[0]?.capabilities).toEqual([{ name: "agent-device", state: "available" }]);
});
});

const downloadLimit = 2_147_483_648;
const tooLargeReply = (size: number) => ({
code: "INVALID_ARGS",
error: `the download is ${String(size)} bytes; simlock carries downloads up to 2 GB (2147483648 bytes)`,
ok: false,
});

async function drainDownload(response: Response): Promise<{
readonly bytes: number;
readonly digest: string;
readonly ended: boolean;
}> {
const hash = createHash("sha256");
let bytes = 0;
const reader = (response.body as ReadableStream<Uint8Array>).getReader();
try {
for (;;) {
const next = await reader.read();
if (next.done) return { bytes, digest: hash.digest("hex"), ended: true };
hash.update(next.value);
bytes += next.value.length;
}
} catch {
return { bytes, digest: "", ended: false };
}
}

describe(
"the agent-device front, through the whole worker daemon: downloads over 2 GiB",
{
timeout: 120_000,
},
() => {
it("an artifact download whose `content-length` is 2147483649 is answered 413 with simlock's reply; the fake produced 0 bytes and its body was cancelled", async () => {
const rig = await setUp();
rig.fake.serveArtifact({ contentLength: "size", size: downloadLimit + 1 });

const response = await send(rig, "/artifacts/a1");

expect(response.status).toBe(413);
expect(await response.json()).toEqual(tooLargeReply(downloadLimit + 1));
expect(rig.fake.artifactBytesProduced).toBe(0);
await expect.poll(() => rig.fake.artifactBodyCancelled).toBe(true);
});

it("an artifact download of exactly 2147483648 bytes with `content-length` arrives byte for byte", async () => {
const rig = await setUp();
rig.fake.serveArtifact({ contentLength: "size", size: downloadLimit });

const response = await send(rig, "/artifacts/a1");
const received = await drainDownload(response);

expect(response.status).toBe(200);
expect(received.ended).toBe(true);
expect(received.bytes).toBe(downloadLimit);
expect(received.digest).toBe(rig.fake.producedDigest());
});

it("a download with no `content-length` of exactly 2147483648 bytes arrives byte for byte", async () => {
const rig = await setUp();
rig.fake.serveArtifact({ contentLength: "none", size: downloadLimit });

const response = await send(rig, "/artifacts/a1");
const received = await drainDownload(response);

expect(response.status).toBe(200);
expect(received.ended).toBe(true);
expect(received.bytes).toBe(downloadLimit);
expect(received.digest).toBe(rig.fake.producedDigest());
});

it("a download with no `content-length` that passes 2147483648 bytes errors the agent's response, which never ends cleanly, and the fake's body is cancelled", async () => {
const rig = await setUp();
rig.fake.serveArtifact({ contentLength: "none", size: downloadLimit + 1 });

const response = await send(rig, "/artifacts/a1");
const received = await drainDownload(response);

expect(received.ended).toBe(false);
await expect.poll(() => rig.fake.artifactBodyCancelled).toBe(true);
});

it("an agent that cancels a 1 GiB download halfway cancels the fake's body", async () => {
const rig = await setUp();
rig.fake.serveArtifact({ contentLength: "none", size: 1_073_741_824 });

const response = await send(rig, "/artifacts/a1");
const reader = (response.body as ReadableStream<Uint8Array>).getReader();
let bytes = 0;
while (bytes < 536_870_912) {
const next = await reader.read();
if (next.done) break;
bytes += next.value.length;
}
await reader.cancel();

expect(bytes).toBeGreaterThanOrEqual(536_870_912);
await expect.poll(() => rig.fake.artifactBodyCancelled).toBe(true);
expect(rig.fake.artifactBytesProduced).toBeLessThan(1_073_741_824);
});

it("an RPC reply and a preflight reply pass unchanged", async () => {
const rig = await setUp();
await granted(rig, 1);

const reply = await command(rig, "snapshot", 1);
const preflight = await send(rig, "/upload/preflight", { body: "{}" });

expect(reply.status).toBe(200);
expect((await envelopeOf(reply)).result).toMatchObject({ ok: true });
expect(preflight.status).toBe(200);
expect(
((await preflight.json()) as { upload: { url: string } }).upload.url.startsWith(
`${rig.origin}/v1/agent-device/upload/direct/`,
),
).toBe(true);
});

it("a 2147483648-byte upload reaches the fake byte for byte", async () => {
const rig = await setUp();
const preflight = await send(rig, "/upload/preflight", { body: "{}" });
const ticket = (
(await preflight.json()) as { upload: { url: string; headers: Record<string, string> } }
).upload;
const hash = createHash("sha256");
let sent = 0;
const piece = new Uint8Array(65_536).fill(7);
const body = new ReadableStream<Uint8Array>(
{
pull: (controller) => {
if (sent >= downloadLimit) {
controller.close();
return;
}
sent += piece.length;
hash.update(piece);
controller.enqueue(piece);
},
},
{ highWaterMark: 0 },
);

const put = await fetch(ticket.url, {
body,
duplex: "half",
headers: { ...ticket.headers, "content-length": String(downloadLimit) },
method: "PUT",
} as RequestInit);

expect(put.status).toBe(200);
expect(rig.fake.uploadSummaries).toEqual([
{ bytes: downloadLimit, sha256: hash.copy().digest("hex") },
]);
});
},
);
53 changes: 53 additions & 0 deletions src/agent-device/gateway-front.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { createHash } from "node:crypto";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
Expand Down Expand Up @@ -2185,3 +2186,55 @@ describe(
});
},
);

describe(
"the agent-device front, through a gateway: downloads over 2 GiB",
{ timeout: 120_000 },
() => {
const limit = 2_147_483_648;

it("an artifact download whose `content-length` is 2147483649 gets the 413 reply; the worker's fake produced 0 bytes and its body was cancelled", async () => {
const rig = await setUp();
await granted(rig, 1);
const worker = holderOf(rig, 1);
worker.fake.serveArtifact({ contentLength: "size", size: limit + 1 });

const response = await send(rig, "/artifacts/a1", { headers: leased(1) });

expect(response.status).toBe(413);
expect(await response.json()).toEqual({
code: "INVALID_ARGS",
error: `the download is ${String(limit + 1)} bytes; simlock carries downloads up to 2 GB (2147483648 bytes)`,
ok: false,
});
expect(worker.fake.artifactBytesProduced).toBe(0);
await expect.poll(() => worker.fake.artifactBodyCancelled).toBe(true);
});

it("a download with no `content-length` that passes 2147483648 bytes errors the agent's response, which never ends cleanly", async () => {
const rig = await setUp();
await granted(rig, 1);
const worker = holderOf(rig, 1);
worker.fake.serveArtifact({ contentLength: "none", size: limit + 1 });

const response = await send(rig, "/artifacts/a1", { headers: leased(1) });
const reader = (response.body as ReadableStream<Uint8Array>).getReader();
const hash = createHash("sha256");
let ended = false;
try {
for (;;) {
const next = await reader.read();
if (next.done) {
ended = true;
break;
}
hash.update(next.value);
}
} catch {
ended = false;
}

expect(ended).toBe(false);
});
},
);
69 changes: 69 additions & 0 deletions src/agent-device/host/download-cap.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";

import { FakeAgentDevice } from "../testing.js";
import { AgentDeviceHost } from "./host.js";

const LIMIT = 2_147_483_648;
const identity = { requesterId: "tok_a", role: "agent" } as const;

function download(): Request {
return new Request("http://simlock.test/v1/agent-device/artifacts/a1", {
headers: { authorization: "Bearer slk_test_agent" },
});
}

async function drain(response: Response): Promise<{
readonly bytes: number;
readonly digest: string;
readonly error: unknown;
readonly ended: boolean;
}> {
const hash = createHash("sha256");
let bytes = 0;
const reader = (response.body as ReadableStream<Uint8Array>).getReader();
try {
for (;;) {
const next = await reader.read();
if (next.done) return { bytes, digest: hash.digest("hex"), error: undefined, ended: true };
hash.update(next.value);
bytes += next.value.length;
}
} catch (error) {
return { bytes, digest: "", error, ended: false };
}
}

function hostFor(fake: FakeAgentDevice): AgentDeviceHost {
return new AgentDeviceHost(fake, ["ios"]);
}

describe("the agent-device host's download cap, called directly", { timeout: 120_000 }, () => {
it.each(["3e9", "2147483649, 2147483649", "9007199254740993"])(
"a content-length of %s is counted as absent: the body is counted, and one passing 2147483648 bytes under it errors",
async (contentLength) => {
const fake = new FakeAgentDevice();
fake.serveArtifact({ contentLength, size: LIMIT + 1 });

const response = await hostFor(fake).forward(download(), identity);
expect(response.status).toBe(200);
const result = await drain(response);

expect(result.ended).toBe(false);
expect(result.error).toBeDefined();
expect(fake.artifactBodyCancelled).toBe(true);
},
);

it("a 2 GiB download whose body nobody reads leaves the fake having produced at most 128 KiB after 1 s", async () => {
const fake = new FakeAgentDevice();
fake.serveArtifact({ contentLength: "none", size: LIMIT });

const response = await hostFor(fake).forward(download(), identity);
expect(response.status).toBe(200);
await new Promise<void>((resolve) => setTimeout(resolve, 1_000));

expect(fake.artifactBytesProduced).toBeLessThanOrEqual(128 * 1024);
await response.body?.cancel();
});
});
62 changes: 59 additions & 3 deletions src/agent-device/host/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
import type { TokenIdentity } from "../../http/token-store.js";
import type { AgentDevicePlatform } from "./agent-device-supervisor.js";
import { FRONT_PREFIX, PROXY_BASE_PATH } from "../shared/paths.js";
import { frontReply, refusal } from "../shared/replies.js";
import { recordingFetch, ReleaseScopeRecord } from "./lease-end.js";
import type { AgentDeviceUpstream } from "./upstream.js";

Expand All @@ -28,6 +29,60 @@ function stripBodyHeaders(headers: Headers): Headers {
return copy;
}

const DOWNLOAD_LIMIT = 2_147_483_648;

function tooLarge(size: number): Response {
return frontReply(
refusal(
`the download is ${String(size)} bytes; simlock carries downloads up to 2 GB (${String(DOWNLOAD_LIMIT)} bytes)`,
413,
),
undefined,
);
}

// why: only a plain decimal is trusted as a size; anything else is counted as absent and the body is counted instead.
function declaredLength(response: Response): number | undefined {
const value = response.headers.get("content-length");
if (value === null || !/^\d+$/.test(value)) return undefined;
const size = Number(value);
return Number.isSafeInteger(size) ? size : undefined;
}

function capped(response: Response): Response {
const body = response.body;
if (body === null) return response;
const declared = declaredLength(response);
if (declared !== undefined && declared > DOWNLOAD_LIMIT) {
void body.cancel().catch(() => undefined);
return tooLarge(declared);
}
const reader = body.getReader();
let seen = 0;
// why: highWaterMark 0 pulls from the worker only as fast as the agent reads, so nothing is buffered past the cap.
const counted = new ReadableStream<Uint8Array>(
{
cancel: (reason) => reader.cancel(reason),
pull: async (controller) => {
const next = await reader.read();
if (next.done) {
controller.close();
return;
}
seen += next.value.length;
if (seen > DOWNLOAD_LIMIT) {
void reader.cancel().catch(() => undefined);
controller.error(new Error("the download passed 2 GB (2147483648 bytes)"));
return;
}
controller.enqueue(next.value);
},
},
{ highWaterMark: 0 },
);
return new Response(counted, { headers: response.headers, status: response.status });
}

export class AgentDeviceHost {
readonly #identities = new Map<string, TokenIdentity>();
#loading: Promise<ProxyModule | undefined> | undefined;
Expand Down Expand Up @@ -94,9 +149,10 @@ export class AgentDeviceHost {
const tag = this.tag(proxied, identity);
try {
const response = await this.#proxy.proxy.handle(proxied);
return new URL(proxied.url).pathname === PREFLIGHT_PATH
? await this.#withTicketPrefix(response)
: response;
if (new URL(proxied.url).pathname === PREFLIGHT_PATH) {
return await this.#withTicketPrefix(response);
}
return capped(response);
} finally {
this.#identities.delete(tag);
}
Expand Down
Loading
Loading