Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
2e72bb7
test: a lease holder PUTs a file and gets 201 with its name and size;…
V3RON Nov 6, 2026
f88b6c9
feat(lease-files): a PUT stores a file in the lease's folder and a GE…
V3RON Nov 6, 2026
22ed642
docs(lease-files): the lease files section and the five new error cod…
V3RON Nov 6, 2026
a618e4d
test: a lease holder PUTs a bad file name and gets 400 BAD_REQUEST wi…
V3RON Nov 6, 2026
bda0429
feat(lease-files): a file name outside the name rule is refused 400 B…
V3RON Nov 6, 2026
ed51196
test: a lease holder PUTs past a limit and gets the limit's code, wit…
V3RON Nov 6, 2026
6306cfa
feat(lease-files): an upload past 2 GiB is refused 413 FILE_TOO_LARGE…
V3RON Nov 6, 2026
2923cb7
test: a lease holder PUTs past a limit and gets the limit's code, wit…
V3RON Nov 6, 2026
d86cf0a
feat(lease-files): a lease's folder holds at most 4 GiB and a worker …
V3RON Nov 6, 2026
35aa36e
feat(lease-files): a cut upload keeps the previous file, silence ends…
V3RON Nov 6, 2026
26a171f
test: a lease holder lists the lease's files and deletes one (#1356)
V3RON Nov 6, 2026
cd248d1
feat(lease-files): list the files of a lease, delete one, and answer …
V3RON Nov 6, 2026
800f8ae
test: a lease holder's file names match ignoring case (#1356)
V3RON Nov 6, 2026
823c278
feat(lease-files): file names match ignoring case on every disk (#1356)
V3RON Nov 6, 2026
3b47da1
test: a lease holder GETs a file and gets it whole or the range it as…
V3RON Nov 6, 2026
a67de15
feat(lease-files): a GET answers the whole file or one byte range, 41…
V3RON Nov 6, 2026
48a51cb
test: a lease holder PUTs a file and gets 201 with its name and size;…
V3RON Nov 6, 2026
ca55b67
test: a caller that does not hold the lease gets 404 UNKNOWN_LEASE on…
V3RON Nov 6, 2026
18570b3
test: on a gateway, before the gateway relays them, the file routes a…
V3RON Nov 6, 2026
7570f3b
test: a module named files is refused when the module host loads (#1356)
V3RON Nov 6, 2026
9ae674c
feat(modules): files is a core lease sub-route no module may take (#1…
V3RON Nov 6, 2026
a57a19a
test: the HTTP listener of a worker and of a gateway has no total req…
V3RON Nov 6, 2026
5f05862
feat(http): the listener has no total request time limit (#1356)
V3RON Nov 6, 2026
08d4a4a
test: a lease's files are gone once it ends, and startup removes the …
V3RON Nov 6, 2026
c8dfe5e
fix(leasing): the lease-end participant test expects the lease's gran…
V3RON Nov 6, 2026
c126093
refactor(lease-files): GET serving is its own function and the index …
V3RON Nov 6, 2026
84e964a
test(lease-files): the lease-end, sweep and limit tests go red when t…
V3RON Nov 6, 2026
07b1d71
test(lease-files): a DELETE removes every spelling a command left (#1…
V3RON Nov 6, 2026
72ff0b9
fix(lease-files): an upload is not counted twice, a HEAD closes its f…
V3RON Nov 6, 2026
c0e8b00
test(lease-files): the mute upload test shows no answer one ms before…
V3RON Nov 6, 2026
c6ae71f
Merge remote-tracking branch 'origin/feature/1351-adr' into HEAD
V3RON Nov 6, 2026
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
12 changes: 12 additions & 0 deletions .dependency-cruiser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,18 @@ export default {
"^src/input/",
{ path: "^src/(http|gateway|drivers|daemon|cli|mcp|leasing)/" },
),
direction(
"not-lease-files",
"core, leasing, the drivers, the gateway and the contract import nothing from lease-files: the daemon builds it and the HTTP frontend serves it",
"^src/(core|leasing|drivers|gateway|contract)/",
{ path: "^src/lease-files/" },
),
direction(
"lease-files-imports-little",
"lease-files reads and writes through the Filesystem port and knows leases only by the types it takes from leasing; it imports no frontend, gateway, driver or core",
"^src/lease-files/",
{ path: "^src/(http|gateway|drivers|daemon|cli|mcp|core)/" },
),
direction(
"host-load-imports-ports-only",
"host-load reads the machine through the HostLoadProbe port and imports no other component",
Expand Down
1 change: 1 addition & 0 deletions docs/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘
| stream | Optional edge: a running device's live screen over HTTP, relayed by a gateway | [stream](../../src/stream/AGENTS.md) |
| input | Optional edge: a lease holder's taps and keys over a WebSocket, relayed by a gateway | [input](../../src/input/AGENTS.md) |
| tunnel | Optional edge: a lease holder's reverse tunnels (device to caller) and forward tunnels (caller to device) on its Android device or iOS simulator over a WebSocket, on a lone worker or through a gateway | [tunnel](../../src/tunnel/AGENTS.md) |
| lease-files | Core worker feature: a lease's files uploaded over HTTP to a folder under the data directory, served back with ranges, and removed when the lease ends | [lease-files](../../src/lease-files/AGENTS.md) |
| auth | Credential → identity: tokens, admin secret, `hello`, uplink join token, HTTP strategies | [auth](../../src/auth/AGENTS.md) |
| http | HTTP frontend: routes, SSE | [http](../../src/http/AGENTS.md) |
| cli | Operator command surface | [cli](../../src/cli/AGENTS.md) |
Expand Down
1 change: 1 addition & 0 deletions src/agent-device/host/lease-end.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const tenant = "tok_one";
function ended(n: number): EndedLease {
return {
deviceId: "dev_1",
grantedAt: 1_000,
leaseId: hex(n),
ownerId: tenant,
platform: "ios",
Expand Down
12 changes: 12 additions & 0 deletions src/auth/admin-secret.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ describe("AdminSecretManager", () => {
copyFile: () => {
throw new Error("verify() must not touch the filesystem");
},
writeFileStream: () => {
throw new Error("verify() must not touch the filesystem");
},
openFile: () => {
throw new Error("verify() must not touch the filesystem");
},
copyTree: () => {
throw new Error("verify() must not touch the filesystem");
},
Expand Down Expand Up @@ -150,6 +156,12 @@ describe("AdminSecretManager", () => {
copyFile: () => {
throw new Error("verify() must not touch the filesystem");
},
writeFileStream: () => {
throw new Error("verify() must not touch the filesystem");
},
openFile: () => {
throw new Error("verify() must not touch the filesystem");
},
copyTree: () => {
throw new Error("verify() must not touch the filesystem");
},
Expand Down
20 changes: 20 additions & 0 deletions src/contract/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,15 @@ export interface ErrorDetailsMap {
};
/** why: `device.rotate` could not reach the lease's input helper; `reason` is the driver's text, cut to 200 characters. */
INPUT_UNAVAILABLE: { readonly leaseId: string; readonly reason: string };
/** why: ADR 0067 §4: a lease's file upload passed 2 GiB. */
FILE_TOO_LARGE: { readonly name: string };
/** why: ADR 0067 §4: an upload would take a lease's folder past 4 GiB. */
LEASE_FILES_FULL: { readonly leaseId: string; readonly usedBytes: number };
UNKNOWN_FILE: { readonly name: string };
/** why: ADR 0067 §6: no byte of an upload's body arrived for 330 s. */
UPLOAD_STALLED: { readonly name: string };
/** why: ADR 0067 §2: another request is uploading the same file name. */
FILE_BUSY: { readonly name: string };
DOCTOR_UNAVAILABLE: Record<string, never>;
HISTORY_NOT_KEPT: { readonly oldestTs: number };
HISTORY_UNAVAILABLE: Record<string, never>;
Expand Down Expand Up @@ -217,6 +226,11 @@ const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record<CodeWithDeclaredDetails, true>
UNKNOWN_MODEL: true,
HISTORY_NOT_KEPT: true,
INSUFFICIENT_DISK_SPACE: true,
FILE_TOO_LARGE: true,
LEASE_FILES_FULL: true,
UNKNOWN_FILE: true,
UPLOAD_STALLED: true,
FILE_BUSY: true,
LICENSE_NOT_ACCEPTED: true,
DOWNLOAD_TIMEOUT: true,
DOWNLOADS_DISABLED: true,
Expand Down Expand Up @@ -350,6 +364,12 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry
httpStatus: 422,
},
UNKNOWN_LEASE: { code: "UNKNOWN_LEASE", kind: "domain", cliExitCode: 1, httpStatus: 404 },
// why: a lease's file routes (ADR 0067): a refused upload or a missing file is a fact about the request, not a state of the host.
FILE_TOO_LARGE: { code: "FILE_TOO_LARGE", kind: "domain", cliExitCode: 1, httpStatus: 413 },
LEASE_FILES_FULL: { code: "LEASE_FILES_FULL", kind: "domain", cliExitCode: 1, httpStatus: 413 },
UNKNOWN_FILE: { code: "UNKNOWN_FILE", kind: "domain", cliExitCode: 1, httpStatus: 404 },
UPLOAD_STALLED: { code: "UPLOAD_STALLED", kind: "domain", cliExitCode: 1, httpStatus: 408 },
FILE_BUSY: { code: "FILE_BUSY", kind: "domain", cliExitCode: 1, httpStatus: 409 },
// why: a lease's tunnel socket refuses with these (ADR 0054 section 7), so every surface reports them alike.
TUNNEL_UNSUPPORTED: {
code: "TUNNEL_UNSUPPORTED",
Expand Down
2 changes: 1 addition & 1 deletion src/contract/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export interface ProtocolRange {
const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() });

/** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 80, max: 80 };
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 81, max: 81 };

const LEGACY_DAEMON_PROTOCOL_VERSION = 2;

Expand Down
259 changes: 259 additions & 0 deletions src/daemon/lease-files.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,259 @@
import { mkdir, readdir, writeFile } from "node:fs/promises";
import { join } from "node:path";

import { afterEach, describe, expect, it, vi } from "vitest";

import { FakeDriver } from "../core/testing.js";
import { createLeaseFiles } from "../lease-files/index.js";
import {
CryptoIdGenerator,
FakeClock,
MemoryFilesystem,
NodeFilesystem,
NoopLogger,
} from "../ports/index.js";
import { freeLoopbackPort } from "./test-relay-support.js";
import { start, runningDaemons } from "./test-main.js";

afterEach(async () => {
await Promise.all(runningDaemons.splice(0).map((daemon) => daemon.stop("test").catch(() => {})));
});

const admin = {
manageEventSubscription: () => undefined,
via: "socket",
principal: "test-operator",
role: "admin",
} as const;
const ios = { model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const;

// why: a real daemon with HTTP on, a real data folder, and a lease its token holds, so lease end reaches the lease-files participant through the same path production uses.
async function rig() {
const clock = new FakeClock(1_000);
const port = await freeLoopbackPort();
const drivers = [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })];
const started = await start({
clock,
configOverrides: { http: { enabled: true, host: "127.0.0.1", port } },
drivers,
filesystem: new NodeFilesystem(),
});
const { secret, token } = await started.daemon.dispatch(
"token.create",
{ label: "holder", role: "agent" },
admin,
);
const origin = `http://127.0.0.1:${String(port)}`;
const headers = { authorization: `Bearer ${secret}` };
const holder = {
manageEventSubscription: () => undefined,
via: "socket",
principal: token.id,
role: "agent",
} as const;
const lease = async (): Promise<string> => {
const grant = (await started.daemon.dispatch(
"lease.request",
{ ...ios, requesterId: "agent-1" },
holder,
)) as { lease: { id: string } };
return grant.lease.id;
};
const put = (id: string, name: string, body: BodyInit) =>
fetch(`${origin}/v1/leases/${id}/files/${name}`, { body, headers, method: "PUT" });
const list = (id: string) => fetch(`${origin}/v1/leases/${id}/files`, { headers });
const release = (id: string) => started.daemon.dispatch("lease.release", { leaseId: id }, holder);
const root = join(started.directory, "lease-files");
const folders = () => readdir(root).catch(() => []);
return { ...started, clock, drivers, folders, headers, lease, list, origin, put, release, root };
}

describe("a lease's files at lease end", () => {
it("are gone once the lease is released, expires or is killed, and a new lease starts empty", async () => {
const r = await rig();
const ends: Record<string, (id: string) => Promise<unknown>> = {
expired: () => {
r.clock.advance(24 * 3_600_000);
return new Promise((done) => setTimeout(done, 50));
},
killed: () => r.daemon.dispatch("nuke.run", { deleteDevices: true }, admin),
released: (id) => r.release(id),
};
for (const [reason, end] of Object.entries(ends)) {
const id = await r.lease();
expect((await r.put(id, `${reason}.bin`, "bytes")).status, reason).toBe(201);
expect(await r.folders(), reason).toHaveLength(1);

await end(id);
await new Promise((done) => setTimeout(done, 200));

expect(await r.folders(), reason).toEqual([]);
expect((await r.list(id)).status, reason).toBe(404);
}
const fresh = await r.lease();
expect(await (await r.list(fresh)).json()).toEqual({ files: [] });
});

it("an upload still running when its lease ends answers 404 UNKNOWN_LEASE and leaves nothing behind", async () => {
const r = await rig();
const id = await r.lease();
let feed!: ReadableStreamDefaultController<Uint8Array>;
const body = new ReadableStream<Uint8Array>({
start(controller) {
feed = controller;
controller.enqueue(new TextEncoder().encode("first half"));
},
});
const running = fetch(`${r.origin}/v1/leases/${id}/files/big.bin`, {
body,
duplex: "half",
headers: r.headers,
method: "PUT",
} as RequestInit);
await vi.waitFor(async () =>
expect(await readdir(join(r.root, (await r.folders())[0] ?? ""))).toHaveLength(1),
);

await r.release(id);
// why: the lease end stops the upload itself; it does not wait for the caller to finish sending.
await vi.waitFor(async () => expect(await r.folders()).toEqual([]));
feed.enqueue(new TextEncoder().encode("second half"));
feed.close();
const answer = await running;

expect(answer.status).toBe(404);
expect(await answer.json()).toMatchObject({ error: { code: "UNKNOWN_LEASE" } });
});

it("startup removes the folders of leases that are no longer live, an upload's temporary file included", async () => {
const r = await rig();
const live = await r.lease();
await r.put(live, "kept.bin", "bytes");
const [liveFolder = ""] = await r.folders();
await writeFile(join(r.root, liveFolder, ".upload-left"), "half");
const gone = join(r.root, `${Buffer.from("lse_gone").toString("hex")}-500`);
await mkdir(gone, { recursive: true });
await writeFile(join(gone, ".upload-x"), "half");
await writeFile(join(gone, "old.bin"), "old");
expect(await r.folders()).toHaveLength(2);

await r.daemon.stop("test");
runningDaemons.length = 0;
const port = await freeLoopbackPort();
const again = await start({
clock: r.clock,
configOverrides: { http: { enabled: true, host: "127.0.0.1", port } },
dataDirectory: r.directory,
drivers: r.drivers,
filesystem: new NodeFilesystem(),
});

expect(again.daemon).toBeDefined();
expect(await r.folders()).toEqual([liveFolder]);
expect(await readdir(join(r.root, liveFolder))).toEqual(["kept.bin"]);
});
});

// why: the folder-level rules of `createLeaseFiles` that the worker's HTTP routes cannot reach yet (`folderOf` is for exec) or only by luck of timing: a held mkdir or listing, and grants whose lease ids differ only in case or in grant time.
class GatedFilesystem extends MemoryFilesystem {
release: (() => void) | undefined;
#gate: "mkdirp" | "readdir" | undefined;

hold(call: "mkdirp" | "readdir"): void {
this.#gate = call;
}

async #gated(call: "mkdirp" | "readdir"): Promise<void> {
if (this.#gate !== call) return;
this.#gate = undefined;
await new Promise<void>((resolve) => (this.release = resolve));
}

override async mkdirp(path: string, options?: Parameters<MemoryFilesystem["mkdirp"]>[1]) {
await this.#gated("mkdirp");
return super.mkdirp(path, options);
}

// why: the first listing that shows a finished upload's temporary file is the one before the upload is renamed into place.
override async readdir(path: string) {
const names = await super.readdir(path);
if (names.some((name) => name.startsWith(".upload-"))) await this.#gated("readdir");
return names;
}
}

function leaseFilesOver(filesystem: GatedFilesystem) {
return createLeaseFiles({
clock: new FakeClock(1_000),
dataDirectory: "/data",
diskPressureThreshold: 0,
filesystem,
findGrant: (id) => ({ grantedAt: 1, id, platform: "ios" }),
idGenerator: new CryptoIdGenerator(),
logger: new NoopLogger(),
});
}

const grant = (id: string, grantedAt: number) => ({ grantedAt, id, platform: "ios" }) as const;
const ended = (id: string, grantedAt: number) =>
({
deviceId: "dev-1",
grantedAt,
leaseId: id,
ownerId: "agent-1",
platform: "ios",
reason: "explicit",
}) as const;

describe("a lease's folder", () => {
it("is removed with its own grant only: not a later grant of the same id, not an id that differs in case", async () => {
const filesystem = new GatedFilesystem();
const files = leaseFilesOver(filesystem);

expect(await files.folderOf(grant("CI", 1))).toBe("/data/lease-files/4349-1");
expect(await files.folderOf(grant("ci", 1))).toBe("/data/lease-files/6369-1");
expect(await files.folderOf(grant("ci", 2))).toBe("/data/lease-files/6369-2");

await files.leaseEnd.leaseEnded(ended("ci", 1), new AbortController().signal);

expect(await filesystem.readdir("/data/lease-files")).toEqual(["4349-1", "6369-2"]);
});

it("a folderOf whose mkdir is still running when the lease ends leaves no folder, and a later folderOf is refused", async () => {
const filesystem = new GatedFilesystem();
const files = leaseFilesOver(filesystem);
filesystem.hold("mkdirp");

const making = files.folderOf(grant("ci", 1));
await vi.waitFor(() => expect(filesystem.release).toBeDefined());
const ending = files.leaseEnd.leaseEnded(ended("ci", 1), new AbortController().signal);
filesystem.release?.();
await ending;

await making;
expect(await filesystem.readdir("/data/lease-files")).toEqual([]);
await expect(files.folderOf(grant("ci", 1))).rejects.toMatchObject({ code: "UNKNOWN_LEASE" });
});

it("an upload whose body is in but whose name is not yet taken when the lease ends answers 404 UNKNOWN_LEASE and leaves no folder", async () => {
const filesystem = new GatedFilesystem();
const files = leaseFilesOver(filesystem);
filesystem.hold("readdir");

const uploading = files.handle(
new Request("http://worker/v1/leases/ci/files/a.bin", { body: "bytes", method: "PUT" }),
{ ambient: false, name: "agent", principal: "agent-1", role: "agent", via: "token" },
{ deviceId: "dev-1", id: "ci" },
"a.bin",
);
await vi.waitFor(() => expect(filesystem.release).toBeDefined());
const ending = files.leaseEnd.leaseEnded(ended("ci", 1), new AbortController().signal);
filesystem.release?.();
await ending;

const answer = await uploading;
expect(answer.status).toBe(404);
expect(await answer.json()).toMatchObject({ error: { code: "UNKNOWN_LEASE" } });
expect(await filesystem.readdir("/data/lease-files")).toEqual([]);
});
});
1 change: 1 addition & 0 deletions src/daemon/lease-inputs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { createLeaseInputs } from "./lease-inputs.js";
const device = { id: "device-1", platform: "ios" } as never;
const ended = {
deviceId: "device-1",
grantedAt: 1_000,
leaseId: "lease-1",
ownerId: "owner-1",
platform: "ios",
Expand Down
7 changes: 5 additions & 2 deletions src/daemon/optional-modules.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,8 +280,8 @@ describe("optional modules: HTTP routes", () => {
);
});

it("a module named like a core lease sub-route (renew, exec, rotate) fails the start, and POST /v1/leases/{id}/renew still renews", async () => {
for (const name of ["renew", "exec", "rotate"]) {
it("a module named like a core lease sub-route (renew, exec, rotate, files) fails the start, and POST /v1/leases/{id}/renew still renews", async () => {
for (const name of ["renew", "exec", "rotate", "files"]) {
await expect(start({ modules: definitions(fakeModule({ name })) })).rejects.toThrow(name);
}

Expand All @@ -290,6 +290,9 @@ describe("optional modules: HTTP routes", () => {
modules: definitions(fakeModule({ name: "alpha" })),
on: ["alpha"],
});
expect(
(await start({ modules: definitions(fakeModule({ name: "stream" })) })).daemon,
).toBeDefined();
const { secret } = await daemon.dispatch(
"token.create",
{ label: "o", role: "operator" },
Expand Down
Loading
Loading