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
17 changes: 15 additions & 2 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -1504,9 +1504,22 @@ agent-device session with an agent on a worker's own tokens. Through a gateway:
with status 200.
- A worker that is draining takes no new `open`, and keeps serving the leases
it holds.
- A request that names no lease, other than `/health`, is refused with
- Uploads, artifact downloads and diagnostics name their lease in the
`x-agent-device-lease-id: <lease id>` header, which agent-device sends once
it holds a lease. The request goes to the worker holding that lease. An
upload ticket works through the gateway: it carries your own `authorization`
and `x-agent-device-token`, so the `PUT` that follows reaches the gateway
with them, and the worker never sees your token. A header that is not 32
lower-case hex characters is refused with `refused: the
x-agent-device-lease-id header is not a lease id` (status 400). `/health`
does not read the header.
- A request that names no lease, or sends the header empty, other than
`/health`, is refused with
`refused: this agent-device is too old to use through a gateway; update it`.
That includes `devices`, uploads, artifact downloads and diagnostics.
That includes an upload, an artifact download or a diagnostics request with
no header, and the artifact list.
- `devices` lists your devices across every worker that holds one of your
leases, and answers an empty list when you hold none.
- A request that names a lease the token does not hold, or the gateway does not
know, is refused with `refused: lease <id> is not one of yours on this
gateway` (status 403). A lease `simlock release --all` ended stays known for
Expand Down
1 change: 1 addition & 0 deletions src/agent-device/dispose.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ describe("disposeAgentDeviceEdge", () => {
},
forward: () => Promise.reject(new Error("unused")),
leaseRequires: [],
readsLeaseHeader: false,
status: () => Promise.resolve({ reason: "unused", state: "unavailable" }),
};
const parts: AgentDeviceFrontParts = { link, map: new FrontMap(clock), renewals };
Expand Down
23 changes: 23 additions & 0 deletions src/agent-device/edge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1325,6 +1325,29 @@ describe("the agent-device front, through the whole worker daemon", () => {
expect(rig.fake.uploads).toEqual(["artifact bytes"]);
});

it("on a worker, an `x-agent-device-lease-id` header naming another token's lease, a malformed one and no header are each forwarded, as today", async () => {
const rig = await setUp();
await granted(rig, 1);
const other = { "x-agent-device-lease-id": hex(1) };
const malformed = { "x-agent-device-lease-id": "NOT-A-LEASE-ID".repeat(4) };
const preflights = () =>
rig.fake.requests.filter((request) => request.path === "/upload/preflight").length;

const answers: Response[] = [];
for (const headers of [other, malformed, {}]) {
const before = preflights();
const answer = await send(rig, "/upload/preflight", {
body: "{}",
headers,
token: secrets.two,
});
answers.push(answer);
expect(preflights()).toBe(before + 1);
}

expect(answers.map((answer) => answer.status)).toEqual([200, 200, 200]);
});

it("an `/rpc` body over 1 MiB, one that is not JSON, a JSON array, and an object with no `method` are each refused with their message and `id: null`, also while agent-device is unavailable, and neither simlock nor the agent-device daemon sees them", async () => {
const rig = await setUp();
expect((await command(rig, "snapshot", undefined)).status).toBe(200);
Expand Down
102 changes: 102 additions & 0 deletions src/agent-device/front/devices-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,105 @@ export async function filterDevices(
body.result.data["devices"] = kept;
return relay({ response, text: JSON.stringify(body) });
}

interface GatewayDevices {
readonly request: Request;
readonly identity: TokenIdentity;
readonly read: { readonly id: unknown; readonly text: string };
readonly forward: (request: Request, leaseId: string) => Promise<Response>;
}

type Piece =
| {
readonly kind: "list";
readonly response: Response;
readonly text: string;
readonly devices: unknown[];
}
| { readonly kind: "failed"; readonly response: Response };

function unreadable(leaseId: string, rpc: { readonly id: unknown }): Response {
return frontReply(
failure(`could not read the device list from the worker holding lease ${leaseId}`),
rpc,
);
}

async function readPiece(
response: Response,
address: string,
leaseId: string,
rpc: { readonly id: unknown },
): Promise<Piece> {
const text = await readBounded(response.body);
if (text === undefined) return { kind: "failed", response: unreadable(leaseId, rpc) };
const reading = readReply(text);
if (reading.kind === "error") return { kind: "failed", response: relay({ response, text }) };
const devices = asRecord(reading.kind === "success" ? reading.result["data"] : undefined)?.[
"devices"
];
if (
reading.kind !== "success" ||
!Array.isArray(devices) ||
!devices.every((device) => asRecord(device) !== undefined)
) {
return { kind: "failed", response: unreadable(leaseId, rpc) };
}
const own = devices.filter((device) => String(asRecord(device)?.["id"]) === address);
return { devices: own, kind: "list", response, text };
}

// why: each worker answers with everything its daemon sees; cutting each answer to its own lease's device before joining keeps two workers' equal ids apart and other tokens' devices out.
export async function devicesThroughGateway(
context: FrontContext,
{ forward, identity, read, request }: GatewayDevices,
): Promise<Response> {
let held: Awaited<ReturnType<typeof tokenDevices>>;
try {
held = await tokenDevices(context, identity);
} catch (error) {
if (!(error instanceof LeaseCheckFailed)) throw error;
return frontReply(failure(error.message), read);
}
if (held.length === 0) return emptyList(read);
const cancel = new AbortController();
const signal = AbortSignal.any([request.signal, cancel.signal]);
const pieces = await Promise.all(
held.map(async (lease) => {
const forwarded = new Request(request.url, {
body: read.text,
headers: withoutLength(request.headers),
method: request.method,
signal,
});
let piece: Piece;
try {
piece = await readPiece(
await forward(forwarded, lease.leaseId),
lease.address,
lease.leaseId,
read,
);
} catch {
piece = { kind: "failed", response: unreadable(lease.leaseId, read) };
}
const cancelledByUs = piece.kind === "failed" && cancel.signal.aborted;
if (piece.kind === "failed") cancel.abort();
return { cancelledByUs, piece };
}),
);
const failed = pieces.find((entry) => entry.piece.kind === "failed" && !entry.cancelledByUs);
if (failed !== undefined) return (failed.piece as { response: Response }).response;
const lists = pieces.flatMap((entry) => (entry.piece.kind === "list" ? [entry.piece] : []));
const [firstList] = lists;
if (firstList === undefined) return emptyList(read);
const body = JSON.parse(firstList.text) as { result: { data: Record<string, unknown> } };
body.result.data["devices"] = lists.flatMap((entry) => entry.devices);
return relay({ response: firstList.response, text: JSON.stringify(body) });
}

function withoutLength(source: Headers): Headers {
const headers = new Headers(source);
headers.delete("content-length");
return headers;
}
105 changes: 87 additions & 18 deletions src/agent-device/front/front.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { HttpMount } from "../../http/app.js";
import type { TokenIdentity } from "../../http/token-store.js";
import { FRONT_MOUNT, FRONT_PREFIX } from "../shared/paths.js";
import { FRONT_MOUNT, FRONT_PREFIX, LEASE_HEADER } from "../shared/paths.js";
import { failure, frontReply, notAvailable, refusal } from "../shared/replies.js";
import { isKnownRoute } from "../shared/routes.js";
import { commandName, asRecord } from "../shared/selectors.js";
Expand All @@ -15,8 +15,8 @@ import {
type RpcRead,
} from "../shared/rpc.js";
import { allocate } from "./allocate.js";
import type { FrontContext } from "./context.js";
import { filterDevices } from "./devices-filter.js";
import { relay, type FrontContext } from "./context.js";
import { devicesThroughGateway, filterDevices } from "./devices-filter.js";
import { heartbeat } from "./heartbeat.js";
import { release } from "./release.js";
import { checkRequest } from "./request-rules.js";
Expand Down Expand Up @@ -181,10 +181,18 @@ async function forwardCommand(
read: RpcRequest,
leaseId: string | undefined,
): Promise<Response> {
const response = await passThrough(context, request, identity, read, leaseId);
const isDevices =
methodName(read.method) === "command" &&
commandName(asRecord(read.params)?.["command"]) === "devices";
if (isDevices && context.link.readsLeaseHeader) {
return devicesThroughGateway(context, {
forward: (forwarded, held) => passThrough(context, forwarded, identity, read, held),
identity,
read,
request,
});
}
const response = await passThrough(context, request, identity, read, leaseId);
return isDevices ? filterDevices(context, identity, response, read) : response;
}

Expand Down Expand Up @@ -232,6 +240,80 @@ async function passThrough(
}
}

const TICKET_HEADERS = ["authorization", "x-agent-device-token"] as const;

// why: the relay drops the caller's credentials, so the worker's ticket has none; the CLI sends the ticket's headers with its PUT, which reaches the gateway.
async function withCallerCredentials(request: Request, response: Response): Promise<Response> {
const text = await response.text();
try {
const body: unknown = JSON.parse(text);
const upload = asRecord(asRecord(body)?.["upload"]);
if (upload === undefined) return relay({ response, text });
const headers = { ...asRecord(upload["headers"]) };
for (const name of TICKET_HEADERS) {
const value = request.headers.get(name);
if (value !== null) headers[name] = value;
}
upload["headers"] = headers;
return relay({ response, text: JSON.stringify(body) });
} catch {
return relay({ response, text });
}
}

type HeaderLease = { readonly leaseId: string | undefined } | { readonly refused: Response };

function readLeaseHeader(request: Request): HeaderLease {
const header = request.headers.get(LEASE_HEADER);
if (header === null || header === "") return { leaseId: undefined };
const leaseId = leaseIdOf(header);
if (leaseId !== undefined) return { leaseId };
return {
refused: frontReply(
refusal("refused: the x-agent-device-lease-id header is not a lease id"),
undefined,
),
};
}

async function routeByHeader(
context: FrontContext,
request: Request,
identity: TokenIdentity,
): Promise<Response> {
const read = readLeaseHeader(request);
if ("refused" in read) return read.refused;
const { leaseId } = read;
if (leaseId === undefined) return passThrough(context, request, identity, undefined);
const status = await context.link.status(leaseId, identity);
if (status.state === "unavailable") return frontReply(notAvailable(status.reason), undefined);
const response = await passThrough(context, request, identity, undefined, leaseId);
const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length);
const preflight = request.method === "POST" && path === "/upload/preflight";
return preflight && response.ok ? withCallerCredentials(request, response) : response;
}

async function handlePlain(
context: FrontContext,
request: Request,
identity: TokenIdentity,
): Promise<Response> {
const status = await context.link.status();
const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length);
const probe = request.method === "GET" && path === "/health";
if (status.state === "unavailable") {
const reply = notAvailable(status.reason);
return frontReply(probe ? { ...reply, status: HEALTH_STATUS } : reply, undefined);
}
if (!isKnownRoute(request.method, path)) {
return frontReply(refusal(`refused: unknown route ${request.method} ${path}`, 404), undefined);
}
if (probe || !context.link.readsLeaseHeader) {
return passThrough(context, request, identity, undefined, undefined, probe);
}
return routeByHeader(context, request, identity);
}

export function createFront(context: FrontContext): HttpMount {
return {
handle: async (request, identity) => {
Expand All @@ -241,20 +323,7 @@ export function createFront(context: FrontContext): HttpMount {
return frontReply(refusal(AGENT_TOKEN_ONLY, 403), isRpc ? { id: null } : undefined);
}
if (isRpc) return handleRpc(context, request, identity);
const status = await context.link.status();
const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length);
const probe = request.method === "GET" && path === "/health";
if (status.state === "unavailable") {
const reply = notAvailable(status.reason);
return frontReply(probe ? { ...reply, status: HEALTH_STATUS } : reply, undefined);
}
if (!isKnownRoute(request.method, path)) {
return frontReply(
refusal(`refused: unknown route ${request.method} ${path}`, 404),
undefined,
);
}
return passThrough(context, request, identity, undefined, undefined, probe);
return handlePlain(context, request, identity);
},
prefix: FRONT_MOUNT,
};
Expand Down
4 changes: 4 additions & 0 deletions src/agent-device/front/host-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export type LinkStatus =
| { readonly state: "unavailable"; readonly reason: string };

export interface HostLink {
// why: only a link that serves many hosts routes non-RPC requests by the lease header and fans out `devices`; a worker never reads the header.
readonly readsLeaseHeader: boolean;
// why: capabilities a lease request must require so it lands on a host that can serve agent-device; none means any worker.
readonly leaseRequires?: readonly string[];
status(leaseId?: string, identity?: TokenIdentity): Promise<LinkStatus>;
Expand All @@ -20,6 +22,8 @@ export interface HostLink {
}

export class InProcessHostLink implements HostLink {
readonly readsLeaseHeader = false;

constructor(private readonly host: AgentDeviceHost) {}

status(): ReturnType<HostLink["status"]> {
Expand Down
1 change: 1 addition & 0 deletions src/agent-device/front/relay-host-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ function refuseRequest(request: Request, message: string, status?: number): Prom

export class RelayHostLink implements HostLink {
readonly leaseRequires: readonly string[] = ["agent-device"];
readonly readsLeaseHeader = true;
readonly #kept = new Map<string, Kept>();
#sweep: TimerHandle | undefined;
#disposed = false;
Expand Down
Loading
Loading