Retire orphan computer owners and verify HTTP authorization

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-10 08:31:36 -05:00
1 parent 80377989b0
commit 6b0bf2f791
10 files changed
+745 -75

No files matched your search

@@ -0,0 +1,316 @@
import express from "express";
import request from "supertest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { ZodError } from "zod";
import {
agents,
environmentLeases,
environments,
issues,
type Db,
} from "@paperclipai/db";
import {
ComputerError,
type ComputerService,
} from "../modules/computers/index.js";
import { computerRoutes } from "../routes/computers.js";
const mocks = vi.hoisted(() => ({
experimental: vi.fn(),
settings: vi.fn(),
getLease: vi.fn(),
audit: vi.fn(),
owner: vi.fn(),
}));
vi.mock("../modules/computers/index.js", async () => {
const { ComputerError } =
await import("../modules/computers/domain/ledger.js");
return {
ComputerError,
computerService: () => {
throw new Error("Inject the computer service");
},
};
});
vi.mock("@paperclipai/adapter-utils", () => ({
resolvePaperclipRunnerIdleTimeoutMs: (value: number | undefined) =>
value ?? 60_000,
}));
vi.mock("../services/instance-settings.js", () => ({
instanceSettingsService: () => ({
getExperimental: mocks.experimental,
get: mocks.settings,
}),
}));
vi.mock("../services/environments.js", () => ({
environmentService: () => ({ getLeaseById: mocks.getLease }),
}));
vi.mock("../services/computer-environment-driver.js", () => ({
computerOwnerFromLease: mocks.owner,
}));
vi.mock("../services/activity-log.js", () => ({ logActivity: mocks.audit }));
vi.mock("../services/authorization.js", () => ({
responsibleUserAuthzShadowMode: () => false,
}));
const companyId = "11111111-1111-4111-8111-111111111111";
const otherCompanyId = "22222222-2222-4222-8222-222222222222";
const issueId = "33333333-3333-4333-8333-333333333333";
const environmentId = "44444444-4444-4444-8444-444444444444";
const owner = {
computerId: "55555555-5555-4555-8555-555555555555",
ownerId: "66666666-6666-4666-8666-666666666666",
generation: 2,
};
const endpoint = `/api/issues/${issueId}/computer`;
function fixture(
options: {
actor?: "board" | "agent";
issueCompanyId?: string;
attachedCompanyId?: string;
issueMissing?: boolean;
} = {},
) {
const issue = options.issueMissing
? null
: {
id: issueId,
companyId: options.issueCompanyId ?? companyId,
assigneeAgentId: null,
};
const environment = {
id: environmentId,
name: "Boat",
driver: "computer",
status: "active",
config: { runnerIdleTimeoutMs: 30_000 },
metadata: { computerCompanyId: options.attachedCompanyId ?? companyId },
};
const lease = {
id: "lease",
environmentId,
companyId,
issueId,
provider: "boat",
metadata: { computerOwner: owner },
};
const rows = new Map<unknown, unknown[]>([
[issues, issue ? [issue] : []],
[environmentLeases, [lease]],
[environments, [environment]],
[agents, []],
]);
const select = vi.fn(() => ({
from: (table: unknown) => {
const query = {
where: vi.fn(() => query),
orderBy: vi.fn(() => query),
limit: vi.fn(async () => rows.get(table) ?? []),
};
return query;
},
}));
const computers = {
connect: vi.fn(async () => ({
viewerUrl: "https://computer.on.boat.dev/#private",
expiresAt: "2026-10-10T13:00:00Z",
owner,
})),
renewViewer: vi.fn(),
disconnectViewer: vi.fn(),
preview: vi.fn(async () => ({
url: "https://preview.on.boat.dev/?_token=private",
})),
};
mocks.getLease.mockResolvedValue(lease);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor =
options.actor === "agent"
? ({ type: "agent", agentId: "agent", companyId } as typeof req.actor)
: ({
type: "board",
source: "session",
userId: "alice",
companyIds: [companyId],
memberships: [
{ companyId, status: "active", membershipRole: "member" },
],
} as typeof req.actor);
next();
});
app.use(
"/api",
computerRoutes(
{ select } as unknown as Db,
computers as unknown as ComputerService,
),
);
app.use(
(
error: unknown,
_req: express.Request,
res: express.Response,
_next: express.NextFunction,
) => {
res
.status(
error instanceof ZodError
? 400
: ((error as { status?: number }).status ?? 500),
)
.json({ error: error instanceof Error ? error.message : "error" });
},
);
return { app, computers, select, rows, environment, lease };
}
beforeEach(() => {
vi.clearAllMocks();
mocks.experimental.mockResolvedValue({ enableBoatEnvironments: true });
mocks.settings.mockResolvedValue({ defaultEnvironmentId: null });
mocks.owner.mockReturnValue(owner);
});
describe("Computer routes", () => {
it("rejects agents and invalid task IDs before looking up a computer", async () => {
const agent = fixture({ actor: "agent" });
expect((await request(agent.app).get(endpoint)).status).toBe(403);
expect(agent.select).not.toHaveBeenCalled();
const board = fixture();
expect(
(await request(board.app).get("/api/issues/not-a-uuid/computer")).status,
).toBe(404);
expect(board.select).not.toHaveBeenCalled();
});
it("hides cross-company tasks exactly like missing tasks", async () => {
const foreign = fixture({ issueCompanyId: otherCompanyId });
const missing = fixture({ issueMissing: true });
const a = await request(foreign.app)
.post(`${endpoint}/connect`)
.send({ environmentId });
const b = await request(missing.app)
.post(`${endpoint}/connect`)
.send({ environmentId });
expect(a.status).toBe(404);
expect(a.body).toEqual(b.body);
expect(foreign.computers.connect).not.toHaveBeenCalled();
});
it("requires a company-bound environment and rejects a posted environment override", async () => {
const foreign = fixture({ attachedCompanyId: otherCompanyId });
expect((await request(foreign.app).get(endpoint)).body).toBeNull();
expect(
(
await request(foreign.app)
.post(`${endpoint}/connect`)
.send({ environmentId })
).status,
).toBe(404);
const f = fixture();
expect(
(
await request(f.app)
.post(`${endpoint}/connect`)
.send({ environmentId: otherCompanyId })
).status,
).toBe(404);
expect(f.computers.connect).not.toHaveBeenCalled();
});
it("returns ephemeral viewer credentials with no-store and no-referrer and audits only IDs", async () => {
const f = fixture();
const result = await request(f.app)
.post(`${endpoint}/connect`)
.send({ environmentId });
expect(result.status).toBe(200);
expect(result.headers["cache-control"]).toBe("no-store");
expect(result.headers["referrer-policy"]).toBe("no-referrer");
expect(f.computers.connect).toHaveBeenCalledWith({
companyId,
environmentId,
userId: "alice",
idleTimeoutMs: 30_000,
});
expect(JSON.stringify(mocks.audit.mock.calls)).not.toContain("private");
expect(mocks.audit).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
action: "computer.connected",
details: { issueId },
}),
);
});
it("rejects forged preview owners and derives the owner from the scoped stored lease", async () => {
const f = fixture();
expect(
(
await request(f.app)
.post(`${endpoint}/preview`)
.send({
environmentId,
port: 5173,
owner: { ...owner, generation: 9 },
})
).status,
).toBe(400);
expect(f.computers.preview).not.toHaveBeenCalled();
const result = await request(f.app)
.post(`${endpoint}/preview`)
.send({ environmentId, port: 5173 });
expect(result.status).toBe(200);
expect(result.headers["cache-control"]).toBe("no-store");
expect(f.computers.preview).toHaveBeenCalledWith({
companyId,
environmentId,
owner,
port: 5173,
});
});
it("disables new connections and previews while preserving authenticated disconnect", async () => {
mocks.experimental.mockResolvedValue({ enableBoatEnvironments: false });
const f = fixture();
expect((await request(f.app).get(endpoint)).body).toBeNull();
expect(
(await request(f.app).post(`${endpoint}/connect`).send({ environmentId }))
.status,
).toBe(422);
expect(
(
await request(f.app)
.post(`${endpoint}/preview`)
.send({ environmentId, port: 5173 })
).status,
).toBe(422);
expect(
(
await request(f.app)
.post(`${endpoint}/disconnect`)
.send({ environmentId, owner })
).status,
).toBe(204);
expect(f.computers.disconnectViewer).toHaveBeenCalledWith({
companyId,
environmentId,
owner,
userId: "alice",
});
});
it("passes viewer identity to the module and maps ownership errors without exposing credentials", async () => {
const f = fixture();
f.computers.renewViewer.mockRejectedValue(
new ComputerError("forbidden", "Computer viewer belongs to another user"),
);
const result = await request(f.app)
.post(`${endpoint}/presence`)
.send({ environmentId, owner });
expect(result.status).toBe(403);
expect(result.headers["cache-control"]).toBe("no-store");
expect(f.computers.renewViewer).toHaveBeenCalledWith({
companyId,
environmentId,
owner,
userId: "alice",
});
});
});
@@ -1,11 +1,96 @@
import {describe,it,expect,vi} from 'vitest';
import {boatBackend} from './boat.js';
import type {ComputerRecord} from '../domain/ledger.js';
const record:ComputerRecord={id:'computer',companyId:'company',environmentId:'environment',providerId:'bx_test',ledger:{controllerId:'controller',status:'attached',secretRef:{type:'secret_ref',secretId:'secret'},owners:[],placements:{},action:null}};
const json=(value:unknown,status=200,headers?:Record<string,string>)=>new Response(JSON.stringify(value),{status,headers:{'content-type':'application/json',...headers}});
describe('Boat transport validation',()=>{
it('recognizes idle as an already running computer',async()=>{const fetcher=vi.fn(async()=>json({sandbox:{id:'bx_test',state:'idle',snapshots:true,stop:null}}));await boatBackend(async()=>'secret',fetcher).ready(record);expect(fetcher).toHaveBeenCalledTimes(1);});
it('rejects another physical ID and snapshot-disabled computers',async()=>{await expect(boatBackend(async()=>'secret',vi.fn(async()=>json({sandbox:{id:'bx_wrong',state:'idle',snapshots:true}}))).inspect(record)).rejects.toMatchObject({code:'provider_error'});await expect(boatBackend(async()=>'secret',vi.fn(async()=>json({sandbox:{id:'bx_test',state:'idle',snapshots:false}}))).ready(record)).rejects.toMatchObject({code:'invalid'});});
it('keeps port credentials out of the WSS URL and does not forward API authorization to the hosting origin',async()=>{const fetcher=vi.fn(async(url:any,options?:any)=>String(url).startsWith('https://boat.dev/')?json({url:'https://test.on.boat.dev/?_token=private-token',access:'private'}):new Response(null,{status:302,headers:{'set-cookie':'_port_auth=private-cookie; Secure; HttpOnly'}}));const endpoint=await boatBackend(async()=>'api-secret',fetcher).ingress(record,43127,'/runner/ws');expect(endpoint).toEqual({url:'wss://test.on.boat.dev/runner/ws',secretHeaders:{Cookie:'_port_auth=private-cookie'}});expect(fetcher.mock.calls[1]![1].headers).toBeUndefined();expect(fetcher.mock.calls[1]![1].redirect).toBe('manual');});
it('refuses public ports and arbitrary hosting origins',async()=>{for(const url of ['http://test.on.boat.dev/?_token=x','https://evil.example/?_token=x'])await expect(boatBackend(async()=>'secret',vi.fn(async()=>json({url,access:'private'}))).preview(record,5173)).rejects.toMatchObject({code:'provider_error'});await expect(boatBackend(async()=>'secret',vi.fn(async()=>json({url:'https://test.on.boat.dev/',access:'public'}))).preview(record,5173)).rejects.toMatchObject({code:'provider_error'});});
import { describe, it, expect, vi } from "vitest";
import { boatBackend } from "./boat.js";
import type { ComputerRecord } from "../domain/ledger.js";
const record: ComputerRecord = {
id: "computer",
companyId: "company",
environmentId: "environment",
providerId: "bx_test",
ledger: {
controllerId: "controller",
status: "attached",
secretRef: { type: "secret_ref", secretId: "secret" },
owners: [],
placements: {},
action: null,
},
};
const json = (value: unknown, status = 200, headers?: Record<string, string>) =>
new Response(JSON.stringify(value), {
status,
headers: { "content-type": "application/json", ...headers },
});
describe("Boat transport validation", () => {
it("recognizes idle as an already running computer", async () => {
const fetcher = vi.fn(async () =>
json({
sandbox: { id: "bx_test", state: "idle", snapshots: true, stop: null },
}),
);
await boatBackend(async () => "secret", fetcher).ready(record);
expect(fetcher).toHaveBeenCalledTimes(1);
});
it("rejects another physical ID and snapshot-disabled computers", async () => {
await expect(
boatBackend(
async () => "secret",
vi.fn(async () =>
json({ sandbox: { id: "bx_wrong", state: "idle", snapshots: true } }),
),
).inspect(record),
).rejects.toMatchObject({ code: "provider_error" });
await expect(
boatBackend(
async () => "secret",
vi.fn(async () =>
json({ sandbox: { id: "bx_test", state: "idle", snapshots: false } }),
),
).ready(record),
).rejects.toMatchObject({ code: "invalid" });
});
it("keeps port credentials out of the WSS URL and does not forward API authorization to the hosting origin", async () => {
const fetcher = vi.fn(async (url: any, options?: any) =>
String(url).startsWith("https://boat.dev/")
? json({
url: "https://test.on.boat.dev/?_token=private-token",
access: "private",
})
: new Response(null, {
status: 302,
headers: {
"set-cookie": "_port_auth=private-cookie; Secure; HttpOnly",
},
}),
);
const endpoint = await boatBackend(
async () => "api-secret",
fetcher,
).ingress(record, 43127, "/runner/ws");
expect(endpoint).toEqual({
url: "wss://test.on.boat.dev/runner/ws",
secretHeaders: { Cookie: "_port_auth=private-cookie" },
});
expect(fetcher.mock.calls[1]![1].headers).toBeUndefined();
expect(fetcher.mock.calls[1]![1].redirect).toBe("manual");
});
it("refuses public ports and arbitrary hosting origins", async () => {
for (const url of [
"http://test.on.boat.dev/?_token=x",
"https://evil.example/?_token=x",
])
await expect(
boatBackend(
async () => "secret",
vi.fn(async () => json({ url, access: "private" })),
).preview(record, 5173),
).rejects.toMatchObject({ code: "provider_error" });
await expect(
boatBackend(
async () => "secret",
vi.fn(async () =>
json({ url: "https://test.on.boat.dev/", access: "public" }),
),
).preview(record, 5173),
).rejects.toMatchObject({ code: "provider_error" });
});
});
+16 -5
View File
@@ -261,12 +261,23 @@ with open(os.path.join(root,'lock'),'a') as lock:
);
return url;
}
function stopReceipt(value: any, expectedId?: string): {id:string;status:string} {
if (!value || typeof value.id !== "string" || !/^stop_[a-zA-Z0-9]+$/.test(value.id) ||
(expectedId && value.id !== expectedId) || !["pending", "failing", "completed", "superseded"].includes(value.status)) {
throw new ComputerError("provider_error", "Boat returned an invalid stop receipt");
function stopReceipt(
value: any,
expectedId?: string,
): { id: string; status: string } {
if (
!value ||
typeof value.id !== "string" ||
!/^stop_[a-zA-Z0-9]+$/.test(value.id) ||
(expectedId && value.id !== expectedId) ||
!["pending", "failing", "completed", "superseded"].includes(value.status)
) {
throw new ComputerError(
"provider_error",
"Boat returned an invalid stop receipt",
);
}
return {id:value.id,status:value.status};
return { id: value.id, status: value.status };
}
return {
inspect,
@@ -5,11 +5,22 @@ import { ComputerError, liveOwners, type Ledger } from "../domain/ledger.js";
export const computerCompanyDeletion: CompanyDeletionParticipant = {
async deleteCompanyData(tx, companyId) {
const records = await tx.select().from(computers).where(eq(computers.companyId, companyId)).for("update");
const records = await tx
.select()
.from(computers)
.where(eq(computers.companyId, companyId))
.for("update");
for (const record of records) {
const ledger = record.ledger as unknown as Ledger;
if (ledger.status !== "detached" || ledger.action || liveOwners(ledger).length) {
throw new ComputerError("conflict", "Detach company computers and wait for their snapshots before deleting the company");
if (
ledger.status !== "detached" ||
ledger.action ||
liveOwners(ledger).length
) {
throw new ComputerError(
"conflict",
"Detach company computers and wait for their snapshots before deleting the company",
);
}
}
await tx.delete(computers).where(eq(computers.companyId, companyId));
@@ -1,15 +1,121 @@
import {afterEach,describe,expect,it} from 'vitest';
import {mkdtempSync,realpathSync,rmSync,symlinkSync,writeFileSync,mkdirSync} from 'node:fs';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import {spawnSync} from 'node:child_process';
import {remoteProgram} from './remote-program.js';
const roots:string[]=[];
function fixture(){const temp=realpathSync(mkdtempSync(join(tmpdir(),'computer-files-')));roots.push(temp);const root=join(temp,'home');const call=(input:Record<string,unknown>)=>{const result=spawnSync('python3',['-c',remoteProgram.replaceAll('/home/user/paperclip/',`${temp}/`)],{input:JSON.stringify({...input,root}),encoding:'utf8'});if(result.status!==0)throw new Error(result.stderr);return JSON.parse(result.stdout);};return {root,temp,call};}
afterEach(()=>{for(const root of roots.splice(0))rmSync(root,{recursive:true,force:true});});
describe('confined computer files',()=>{
it('seeds absent home only and preserves existing content',()=>{const f=fixture();expect(f.call({action:'seed',files:{'nested/one':Buffer.from('first').toString('base64')}})).toEqual({seeded:true});expect(f.call({action:'seed',files:{'nested/one':Buffer.from('overwrite').toString('base64')}})).toEqual({seeded:false});expect(Buffer.from(f.call({action:'read',path:'nested/one'}).base64,'base64').toString()).toBe('first');});
it('rejects traversal, symlink escapes, and oversized reads',()=>{const f=fixture();f.call({action:'seed',files:{'ok':Buffer.from('12345').toString('base64')}});mkdirSync(join(f.temp,'outside'));writeFileSync(join(f.temp,'outside','secret'),'private');symlinkSync(join(f.temp,'outside'),join(f.root,'escape'));expect(f.call({action:'read',path:'../outside/secret'})).toEqual({error:'invalid'});expect(f.call({action:'read',path:'escape/secret'})).toEqual({error:'invalid'});expect(f.call({action:'read',path:'ok',maxBytes:4})).toEqual({error:'invalid'});});
it('rejects stale edits and uses no-clobber move semantics',()=>{const f=fixture();f.call({action:'seed',files:{}});const first=f.call({action:'write',path:'file',expectedSha256:null,base64:Buffer.from('one').toString('base64')});const second=f.call({action:'write',path:'file',expectedSha256:first.sha256,base64:Buffer.from('two').toString('base64')});expect(f.call({action:'write',path:'file',expectedSha256:first.sha256,base64:''})).toEqual({error:'conflict'});expect(f.call({action:'move',path:'file',to:'other',expectedSha256:second.sha256})).toEqual({sha256:second.sha256});expect(f.call({action:'list'}).map((e:any)=>e.name)).toEqual(['other']);expect(f.call({action:'remove',path:'other',expectedSha256:first.sha256})).toEqual({error:'conflict'});});
it('roundtrips binary bytes without interpreting text',()=>{const f=fixture();const bytes=Buffer.from([0,255,254,13,10,128]);f.call({action:'seed',files:{binary:bytes.toString('base64')}});expect(Buffer.from(f.call({action:'read',path:'binary'}).base64,'base64')).toEqual(bytes);});
import { afterEach, describe, expect, it } from "vitest";
import {
mkdtempSync,
realpathSync,
rmSync,
symlinkSync,
writeFileSync,
mkdirSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawnSync } from "node:child_process";
import { remoteProgram } from "./remote-program.js";
const roots: string[] = [];
function fixture() {
const temp = realpathSync(mkdtempSync(join(tmpdir(), "computer-files-")));
roots.push(temp);
const root = join(temp, "home");
const call = (input: Record<string, unknown>) => {
const result = spawnSync(
"python3",
["-c", remoteProgram.replaceAll("/home/user/paperclip/", `${temp}/`)],
{ input: JSON.stringify({ ...input, root }), encoding: "utf8" },
);
if (result.status !== 0) throw new Error(result.stderr);
return JSON.parse(result.stdout);
};
return { root, temp, call };
}
afterEach(() => {
for (const root of roots.splice(0))
rmSync(root, { recursive: true, force: true });
});
describe("confined computer files", () => {
it("seeds absent home only and preserves existing content", () => {
const f = fixture();
expect(
f.call({
action: "seed",
files: { "nested/one": Buffer.from("first").toString("base64") },
}),
).toEqual({ seeded: true });
expect(
f.call({
action: "seed",
files: { "nested/one": Buffer.from("overwrite").toString("base64") },
}),
).toEqual({ seeded: false });
expect(
Buffer.from(
f.call({ action: "read", path: "nested/one" }).base64,
"base64",
).toString(),
).toBe("first");
});
it("rejects traversal, symlink escapes, and oversized reads", () => {
const f = fixture();
f.call({
action: "seed",
files: { ok: Buffer.from("12345").toString("base64") },
});
mkdirSync(join(f.temp, "outside"));
writeFileSync(join(f.temp, "outside", "secret"), "private");
symlinkSync(join(f.temp, "outside"), join(f.root, "escape"));
expect(f.call({ action: "read", path: "../outside/secret" })).toEqual({
error: "invalid",
});
expect(f.call({ action: "read", path: "escape/secret" })).toEqual({
error: "invalid",
});
expect(f.call({ action: "read", path: "ok", maxBytes: 4 })).toEqual({
error: "invalid",
});
});
it("rejects stale edits and uses no-clobber move semantics", () => {
const f = fixture();
f.call({ action: "seed", files: {} });
const first = f.call({
action: "write",
path: "file",
expectedSha256: null,
base64: Buffer.from("one").toString("base64"),
});
const second = f.call({
action: "write",
path: "file",
expectedSha256: first.sha256,
base64: Buffer.from("two").toString("base64"),
});
expect(
f.call({
action: "write",
path: "file",
expectedSha256: first.sha256,
base64: "",
}),
).toEqual({ error: "conflict" });
expect(
f.call({
action: "move",
path: "file",
to: "other",
expectedSha256: second.sha256,
}),
).toEqual({ sha256: second.sha256 });
expect(f.call({ action: "list" }).map((e: any) => e.name)).toEqual([
"other",
]);
expect(
f.call({ action: "remove", path: "other", expectedSha256: first.sha256 }),
).toEqual({ error: "conflict" });
});
it("roundtrips binary bytes without interpreting text", () => {
const f = fixture();
const bytes = Buffer.from([0, 255, 254, 13, 10, 128]);
f.call({ action: "seed", files: { binary: bytes.toString("base64") } });
expect(
Buffer.from(f.call({ action: "read", path: "binary" }).base64, "base64"),
).toEqual(bytes);
});
});
@@ -1,5 +1,5 @@
import { and, eq } from "drizzle-orm";
import { computers, companies, type Db } from "@paperclipai/db";
import { computers, companies, heartbeatRuns, type Db } from "@paperclipai/db";
import {
ComputerError,
type ComputerRecord,
@@ -18,10 +18,19 @@ export function computerRepository(db: Db): ComputerRepository {
);
return {
async create(record) {
await db.transaction(async tx => {
const [company] = await tx.select({id:companies.id}).from(companies).where(eq(companies.id,record.companyId)).for("update");
await db.transaction(async (tx) => {
const [company] = await tx
.select({ id: companies.id })
.from(companies)
.where(eq(companies.id, record.companyId))
.for("update");
if (!company) throw new ComputerError("not_found", "Company not found");
await tx.insert(computers).values({...record,ledger:record.ledger as unknown as Record<string,unknown>});
await tx
.insert(computers)
.values({
...record,
ledger: record.ledger as unknown as Record<string, unknown>,
});
});
},
async get(scope) {
@@ -57,6 +66,28 @@ export function computerRepository(db: Db): ComputerRepository {
return result;
});
},
async runState(scope, runId, agentId) {
const [run] = await db
.select({ status: heartbeatRuns.status })
.from(heartbeatRuns)
.where(
and(
eq(heartbeatRuns.companyId, scope.companyId),
eq(heartbeatRuns.id, runId),
eq(heartbeatRuns.agentId, agentId),
),
);
if (!run) return "missing";
return [
"succeeded",
"interrupted",
"failed",
"cancelled",
"timed_out",
].includes(run.status)
? "terminal"
: "active";
},
async all() {
return (await db.select().from(computers)).map(decode);
},
@@ -16,11 +16,14 @@ export interface ComputerRepository {
fn: (record: ComputerRecord) => T,
): Promise<T>;
all(): Promise<ComputerRecord[]>;
runState(
scope: { companyId: string },
runId: string,
agentId: string,
): Promise<"active" | "terminal" | "missing">;
}
export interface ComputerBackend {
inspect(
record: ComputerRecord,
): Promise<{
inspect(record: ComputerRecord): Promise<{
state: string;
snapshots: boolean;
stop: null | { id: string; status: string };
@@ -28,6 +28,7 @@ function fixture() {
return result;
},
all: async () => (record ? [structuredClone(record)] : []),
runState: vi.fn(async () => "active" as const),
};
const backend: ComputerBackend = {
inspect: vi.fn(async () => ({ state, snapshots: true, stop: null })),
@@ -215,12 +216,59 @@ describe("computer ownership", () => {
expect(f.backend.inspect).not.toHaveBeenCalled();
});
it("keeps process capabilities across attempt generations only for the exact same process", async () => {
const f=fixture();await f.attach();const first=await f.admit();await first.launch({command:"runnerd"});
await f.service.retainWarm({...f.scope,owner:first.owner,idleTimeoutMs:60_000});await f.admit();
await expect(first.ingress()).rejects.toMatchObject({code:"conflict"});
const f = fixture();
await f.attach();
const first = await f.admit();
await first.launch({ command: "runnerd" });
await f.service.retainWarm({
...f.scope,
owner: first.owner,
idleTimeoutMs: 60_000,
});
await f.admit();
await expect(first.ingress()).rejects.toMatchObject({ code: "conflict" });
await expect(first.process.ingress()).resolves.toHaveProperty("url");
await f.repository.update(f.scope,record=>{record.ledger.owners[0]!.process!.nonce="replacement-process";});
await expect(first.process.ingress()).rejects.toMatchObject({code:"conflict"});
await f.repository.update(f.scope, (record) => {
record.ledger.owners[0]!.process!.nonce = "replacement-process";
});
await expect(first.process.ingress()).rejects.toMatchObject({
code: "conflict",
});
});
it.each(["terminal", "missing"] as const)(
"retires an orphan active owner with a %s run after admission grace",
async (state) => {
const f = fixture();
await f.attach();
await f.admit();
vi.mocked(f.repository.runState).mockResolvedValue(state);
f.advance(119_000);
await f.service.reconcile();
expect(f.backend.retire).not.toHaveBeenCalled();
f.advance(1_001);
await f.service.reconcile();
expect(f.backend.retire).toHaveBeenCalledOnce();
expect(f.backend.stop).toHaveBeenCalledOnce();
},
);
it("preserves recoverable running owners and gives completed warm owners their idle interval", async () => {
const f = fixture();
await f.attach();
const binding = await f.admit();
f.advance(180_000);
await f.service.reconcile();
expect(f.backend.retire).not.toHaveBeenCalled();
await f.service.retainWarm({
...f.scope,
owner: binding.owner,
idleTimeoutMs: 60_000,
});
vi.mocked(f.repository.runState).mockResolvedValue("terminal");
await f.service.reconcile();
expect(f.backend.retire).not.toHaveBeenCalled();
f.advance(60_001);
await f.service.reconcile();
expect(f.backend.retire).toHaveBeenCalledOnce();
});
});
@@ -59,9 +59,7 @@ export function createComputerService(
let record: ComputerRecord;
try {
record = await repository.get(input);
if (
record.providerId !== input.sandboxId
)
if (record.providerId !== input.sandboxId)
throw new ComputerError(
"conflict",
"Environment already attaches another computer",
@@ -85,12 +83,21 @@ export function createComputerService(
};
await repository.create(record);
}
if (JSON.stringify(record.ledger.secretRef) !== JSON.stringify(input.apiKeySecretRef)) {
if (
JSON.stringify(record.ledger.secretRef) !==
JSON.stringify(input.apiKeySecretRef)
) {
const candidate = structuredClone(record);
candidate.ledger.secretRef = input.apiKeySecretRef;
const status = await backend.inspect(candidate);
if (!status.snapshots) throw new ComputerError("invalid", "Boat snapshots must remain enabled");
await repository.update(input, current => { current.ledger.secretRef = input.apiKeySecretRef; });
if (!status.snapshots)
throw new ComputerError(
"invalid",
"Boat snapshots must remain enabled",
);
await repository.update(input, (current) => {
current.ledger.secretRef = input.apiKeySecretRef;
});
record = candidate;
}
if (record.ledger.status === "detaching" || record.ledger.action)
@@ -118,17 +125,31 @@ export function createComputerService(
async function processScope() {
if (!pinnedProcess) return scoped({ ...record, owner: ownerRef });
const latest = await repository.get(record);
const candidate = latest.ledger.owners.find(value => value.id === owner.id);
if (!candidate?.process || !["active", "starting", "warm"].includes(candidate.phase) ||
candidate.process.nonce !== pinnedProcess.nonce || candidate.process.unitName !== pinnedProcess.unitName ||
candidate.process.bootId !== pinnedProcess.bootId || candidate.process.launchGeneration !== pinnedProcess.launchGeneration) {
throw new ComputerError("conflict", "Computer process capability has expired");
const candidate = latest.ledger.owners.find(
(value) => value.id === owner.id,
);
if (
!candidate?.process ||
!["active", "starting", "warm"].includes(candidate.phase) ||
candidate.process.nonce !== pinnedProcess.nonce ||
candidate.process.unitName !== pinnedProcess.unitName ||
candidate.process.bootId !== pinnedProcess.bootId ||
candidate.process.launchGeneration !== pinnedProcess.launchGeneration
) {
throw new ComputerError(
"conflict",
"Computer process capability has expired",
);
}
return {record:latest,owner:candidate};
return { record: latest, owner: candidate };
}
const runnerFor = (processScoped: boolean): CommandManagedRuntimeRunner => ({
const runnerFor = (
processScoped: boolean,
): CommandManagedRuntimeRunner => ({
execute: async (input) => {
const current = await (processScoped ? processScope() : scoped({ ...record, owner: ownerRef }));
const current = await (processScoped
? processScope()
: scoped({ ...record, owner: ownerRef }));
if (!["active", "starting", "warm"].includes(current.owner.phase))
throw new ComputerError("conflict", "Computer owner is retired");
// Start a command unit under the same owner slice while holding the remote tombstone lock.
@@ -185,9 +206,13 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
runner: runnerFor(false),
process: {
runner: runnerFor(true),
async ingress(input?: {port?:number;path?:string}) {
async ingress(input?: { port?: number; path?: string }) {
const current = await processScope();
return backend.ingress(current.record,input?.port??current.owner.port,input?.path??"/");
return backend.ingress(
current.record,
input?.port ?? current.owner.port,
input?.path ?? "/",
);
},
},
listenerPort: owner.port,
@@ -200,8 +225,10 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
cwd?: string;
env?: Record<string, string>;
}) {
const before = await scoped({...record,owner:ownerRef});
const existing = before.owner.process ? await backend.inspectProcess(before.record,before.owner) : null;
const before = await scoped({ ...record, owner: ownerRef });
const existing = before.owner.process
? await backend.inspectProcess(before.record, before.owner)
: null;
const claimed = await repository.update(record, (current) => {
const o = exactOwner(current, ownerRef);
if (o.phase !== "active" && o.phase !== "starting")
@@ -252,7 +279,8 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
},
) {
segment(input.agentId);
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(input.sessionKey)) throw new ComputerError("invalid", "Invalid computer session key");
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(input.sessionKey))
throw new ComputerError("invalid", "Invalid computer session key");
timeout(input.idleTimeoutMs);
const result = await repository.update(input, (record) => {
assertAdmission(record.ledger);
@@ -277,6 +305,7 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
owner.generation++;
owner.phase = "starting";
owner.runId = input.runId;
owner.admittedAt = now().toISOString();
owner.deadline = new Date(now().getTime() + 120_000).toISOString();
} else {
owner = {
@@ -286,6 +315,7 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
phase: "starting",
agentId: input.agentId,
runId: input.runId,
admittedAt: now().toISOString(),
sessionKey: input.sessionKey,
port: nextPort(record.ledger.owners),
deadline: new Date(now().getTime() + 120_000).toISOString(),
@@ -349,18 +379,17 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
});
}
async function retire(input: Scope & { owner: OwnerRef }) {
const before = await repository.get(input);
const previous = before.ledger.owners.find(
(o) => o.id === input.owner.ownerId,
);
if (before.id !== input.owner.computerId || !previous)
throw new ComputerError("not_found", "Computer owner not found");
if (previous.generation !== input.owner.generation) return { retired: false };
const state = await repository.update(input, (record) => {
const owner = exactOwner(record, input.owner);
const owner = record.ledger.owners.find(
(value) => value.id === input.owner.ownerId,
);
if (record.id !== input.owner.computerId || !owner)
throw new ComputerError("not_found", "Computer owner not found");
if (owner.generation !== input.owner.generation) return null;
if (owner.phase !== "retired") owner.phase = "retiring";
return { record: structuredClone(record), owner: structuredClone(owner) };
});
if (!state) return { retired: false };
if (state.owner.phase === "retired") return { retired: true };
if (state.owner.kind === "runner") {
const status = await backend.inspect(state.record);
@@ -542,9 +571,7 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
) {
return writeBytes(path, Buffer.from(content), expectedSha256);
},
async list(
path = "",
): Promise<
async list(path = ""): Promise<
Array<{
name: string;
kind: "file" | "directory";
@@ -671,6 +698,28 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
}
async function reconcileRecord(record: ComputerRecord) {
if (record.ledger.status === "attaching") return;
// A crash can happen after admission but before an environment lease exists.
// Run identity, rather than lease presence, decides whether that active owner
// still has work to recover. Warm owners keep their own idle deadline.
for (const owner of liveOwners(record.ledger)) {
const admittedAt = owner.admittedAt ? Date.parse(owner.admittedAt) : 0;
if (
owner.kind === "runner" &&
owner.phase === "active" &&
owner.runId &&
owner.agentId &&
now().getTime() - admittedAt >= 120_000
) {
const runState = await repository.runState(
record,
owner.runId,
owner.agentId,
);
if (runState !== "active")
await retire({ ...record, owner: ref(record, owner) });
}
}
record = await repository.get(record);
for (const owner of liveOwners(record.ledger))
if (owner.phase === "retiring" || expired(owner, now()))
await retire({ ...record, owner: ref(record, owner) });
@@ -738,7 +787,16 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
);
}
return {
async list(companyId: string) { return (await repository.all()).filter(record => record.companyId === companyId).map(record => ({ computerId: record.id, environmentId: record.environmentId, sandboxId: record.providerId, status: record.ledger.status })); },
async list(companyId: string) {
return (await repository.all())
.filter((record) => record.companyId === companyId)
.map((record) => ({
computerId: record.id,
environmentId: record.environmentId,
sandboxId: record.providerId,
status: record.ledger.status,
}));
},
attach,
admit,
recover,
@@ -16,6 +16,7 @@ export interface Owner {
phase: "starting" | "active" | "warm" | "retiring" | "retired";
agentId?: string;
runId?: string;
admittedAt?: string;
sessionKey?: string;
userId?: string;
port: number;