Fence warm process capabilities and confine remote file operations

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-10 08:31:36 -05:00
1 parent 0cf2ea86e8
commit 40b453fc85
5 files changed
+156 -60

No files matched your search

@@ -0,0 +1,11 @@
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 -7
View File
@@ -217,15 +217,19 @@ with open(os.path.join(root,'lock'),'a') as lock:
if state not in ('inactive','failed',''):raise RuntimeError('process retirement unconfirmed')
print('{}')
elif p['action']=='inspect':
claim=owner.get('process');state=subprocess.run(['systemctl','--user','is-active',unit],capture_output=True,text=True).stdout.strip()
print(json.dumps({'running':bool(claim and claim['bootId']==boot and state=='active' and not os.path.exists(tombstone)),'claim':claim}))
claim=owner.get('process');marker=os.path.join(root,'claim.json');actual=json.load(open(marker)) if os.path.exists(marker) else None
valid=claim and actual and claim['nonce']==actual['nonce'] and claim['launchGeneration']==actual['launchGeneration'] and actual['bootId']==boot
state=subprocess.run(['systemctl','--user','is-active',unit],capture_output=True,text=True).stdout.strip()
print(json.dumps({'running':bool(valid and state=='active' and not os.path.exists(tombstone)),'claim':actual if valid else claim}))
else:
if os.path.exists(tombstone):print(json.dumps({'error':'conflict'}));sys.exit(0)
claim=owner['process'];claim['bootId']=boot
marker=os.path.join(root,'claim.json')
if os.path.exists(marker):
old=json.load(open(marker))
if old['nonce']!=claim['nonce']:print(json.dumps({'error':'conflict'}));sys.exit(0)
if old['launchGeneration']>claim['launchGeneration'] or (old['launchGeneration']==claim['launchGeneration'] and old['nonce']!=claim['nonce']):print(json.dumps({'error':'conflict'}));sys.exit(0)
active=subprocess.run(['systemctl','--user','is-active',unit],capture_output=True,text=True).stdout.strip()=='active'
if active and old['nonce']!=claim['nonce']:print(json.dumps({'error':'conflict'}));sys.exit(0)
with open(marker,'w') as f:json.dump(claim,f)
payload=p['input'];args=['systemd-run','--user','--unit='+unit,'--slice='+slice,'--collect','--property=KillMode=control-group','--working-directory='+payload.get('cwd','/home/user')]
for key,value in payload.get('env',{}).items():args.append('--setenv='+key+'='+value)
@@ -257,6 +261,13 @@ 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");
}
return {id:value.id,status:value.status};
}
return {
inspect,
runner,
@@ -321,13 +332,11 @@ print('{}')
async stop(record) {
const value = await api(record, "POST", "/stop", {});
const stop = value.stop ?? value.sandbox?.stop;
if (!stop?.id)
throw new ComputerError("provider_error", "Boat stop receipt missing");
return stop;
return stopReceipt(stop);
},
async stopStatus(record, id) {
const value = await api(record, "GET", `/stops/${segment(id)}`);
return value.stop ?? value;
return stopReceipt(value.stop ?? value, id);
},
async renew(record) {
await api(record, "PATCH", "", { ttlSeconds: 300 });
@@ -82,20 +82,50 @@ if act=='workspace':
target=checkout
if branch:run(['git','checkout',branch],checkout)
print(json.dumps({'remoteCwd':target}));sys.exit(0)
if not os.path.isdir(root):fail('not_found')
path=safe(p.get('path',''))
lock=os.open(os.path.join(root,'.paperclip-editor.lock'),os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600)
# Hold directory descriptors throughout each operation. Ancestor symlink swaps cannot
# redirect a checked pathname outside the selected placement.
def directory(parts,create=False,start=None):
fd=os.dup(start) if start is not None else os.open('/',os.O_RDONLY|os.O_DIRECTORY)
try:
for part in parts:
if not part or part=='.':continue
if part=='..':fail('invalid')
try:nxt=os.open(part,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=fd)
except FileNotFoundError:
if not create:raise
try:os.mkdir(part,0o700,dir_fd=fd)
except FileExistsError:pass
nxt=os.open(part,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=fd)
os.close(fd);fd=nxt
return fd
except BaseException:os.close(fd);raise
try:rootfd=directory(root.split('/'))
except FileNotFoundError:fail('not_found')
except OSError:fail('invalid')
def parent(relative,create=False):
safe(relative)
parts=[part for part in relative.split('/') if part not in ('','.')]
if not parts:fail('invalid')
return directory(parts[:-1],create,rootfd),parts[-1]
path=p.get('path','');safe(path)
lock=os.open('.paperclip-editor.lock',os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600,dir_fd=rootfd)
fcntl.flock(lock,fcntl.LOCK_EX)
try:
if act=='list':
out=[]
for entry in os.scandir(path):
if entry.name=='.paperclip-editor.lock' or entry.is_symlink():continue
if not entry.is_dir(follow_symlinks=False) and not entry.is_file(follow_symlinks=False):continue
out.append({'name':entry.name,'kind':'directory' if entry.is_dir(follow_symlinks=False) else 'file','size':entry.stat(follow_symlinks=False).st_size,'mtimeMs':entry.stat(follow_symlinks=False).st_mtime*1000})
print(json.dumps(out))
fd=directory(path.split('/'),start=rootfd)
try:
out=[]
for entry in os.scandir(fd):
if entry.name=='.paperclip-editor.lock' or entry.is_symlink():continue
info=entry.stat(follow_symlinks=False)
if not stat.S_ISDIR(info.st_mode) and not stat.S_ISREG(info.st_mode):continue
out.append({'name':entry.name,'kind':'directory' if stat.S_ISDIR(info.st_mode) else 'file','size':info.st_size,'mtimeMs':info.st_mtime*1000})
print(json.dumps(out))
finally:os.close(fd)
elif act=='read':
fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW)
parentfd,name=parent(path)
try:fd=os.open(name,os.O_RDONLY|os.O_NOFOLLOW,dir_fd=parentfd)
finally:os.close(parentfd)
with os.fdopen(fd,'rb') as f:
st=os.fstat(f.fileno())
if not stat.S_ISREG(st.st_mode) or st.st_size>p.get('maxBytes',16*1024*1024):fail('invalid')
@@ -103,40 +133,49 @@ try:
if len(data)>p.get('maxBytes',16*1024*1024):fail('invalid')
print(json.dumps({'base64':base64.b64encode(data).decode(),'sha256':digest(data)}))
elif act in ('write','remove','move'):
if path==root:fail('invalid')
exists=os.path.exists(path)
old=None
if exists:
fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW)
with os.fdopen(fd,'rb') as f:
if not stat.S_ISREG(os.fstat(f.fileno()).st_mode):fail('invalid')
h=hashlib.sha256()
while True:
block=f.read(65536)
if not block:break
h.update(block)
old=h.hexdigest()
if old!=p.get('expectedSha256'):fail('conflict')
if act=='write':
data=base64.b64decode(p['base64'],validate=True)
if len(data)>p.get('maxBytes',16*1024*1024):fail('invalid')
os.makedirs(os.path.dirname(path),exist_ok=True)
fd,temp=tempfile.mkstemp(prefix='.paperclip-write-',dir=os.path.dirname(path))
try:
with os.fdopen(fd,'wb') as f:f.write(data);f.flush();os.fsync(f.fileno())
os.replace(temp,path)
finally:
if os.path.exists(temp):os.unlink(temp)
print(json.dumps({'sha256':digest(data)}))
elif act=='remove':
if not exists:fail('not_found')
os.unlink(path);print('{}')
else:
target=safe(p['to'])
if os.path.exists(target):fail('conflict')
os.makedirs(os.path.dirname(target),exist_ok=True)
os.link(path,target,follow_symlinks=False);os.unlink(path);print(json.dumps({'sha256':old}))
parentfd,name=parent(path,create=act=='write')
try:
old=None
try:fd=os.open(name,os.O_RDONLY|os.O_NOFOLLOW,dir_fd=parentfd)
except FileNotFoundError:fd=None
if fd is not None:
with os.fdopen(fd,'rb') as f:
if not stat.S_ISREG(os.fstat(f.fileno()).st_mode):fail('invalid')
h=hashlib.sha256()
while True:
block=f.read(65536)
if not block:break
h.update(block)
old=h.hexdigest()
if old!=p.get('expectedSha256'):fail('conflict')
if act=='write':
data=base64.b64decode(p['base64'],validate=True)
if len(data)>16*1024*1024:fail('invalid')
import secrets
temp='.paperclip-write-'+secrets.token_hex(16)
fd=os.open(temp,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600,dir_fd=parentfd)
try:
with os.fdopen(fd,'wb') as f:f.write(data);f.flush();os.fsync(f.fileno())
os.replace(temp,name,src_dir_fd=parentfd,dst_dir_fd=parentfd)
finally:
try:os.unlink(temp,dir_fd=parentfd)
except FileNotFoundError:pass
print(json.dumps({'sha256':digest(data)}))
elif act=='remove':
if old is None:fail('not_found')
os.unlink(name,dir_fd=parentfd);print('{}')
else:
if old is None:fail('not_found')
targetfd,target=parent(p['to'],create=True)
try:
try:os.link(name,target,src_dir_fd=parentfd,dst_dir_fd=targetfd,follow_symlinks=False)
except FileExistsError:fail('conflict')
os.unlink(name,dir_fd=parentfd)
finally:os.close(targetfd)
print(json.dumps({'sha256':old}))
finally:os.close(parentfd)
else:fail('invalid')
except FileNotFoundError:fail('not_found')
finally:os.close(lock)
except OSError:fail('invalid')
finally:os.close(lock);os.close(rootfd)
`;
@@ -214,4 +214,13 @@ describe("computer ownership", () => {
).rejects.toMatchObject({ code: "not_found" });
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"});
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"});
});
});
@@ -114,9 +114,21 @@ export function createComputerService(
if (!placement)
throw new ComputerError("conflict", "Computer placement is missing");
const raw = await backend.runner(record);
const runner: CommandManagedRuntimeRunner = {
let pinnedProcess = owner.process ? structuredClone(owner.process) : null;
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");
}
return {record:latest,owner:candidate};
}
const runnerFor = (processScoped: boolean): CommandManagedRuntimeRunner => ({
execute: async (input) => {
const current = await 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.
@@ -131,7 +143,10 @@ p=json.load(sys.stdin);root='/home/user/.paperclip-owners/'+p['owner'];os.makedi
with open(root+'/lock','a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX)
if os.path.exists(root+'/retired'):raise RuntimeError('computer owner retired')
if not os.path.exists(root+'/generation') or int(open(root+'/generation').read())!=p['generation']:raise RuntimeError('computer owner superseded')
if p.get('processClaim'):
claim=json.load(open(root+'/claim.json'))
if any(claim[k]!=p['processClaim'][k] for k in ['nonce','unitName','bootId','launchGeneration']) or claim['bootId']!=open('/proc/sys/kernel/random/boot_id').read().strip():raise RuntimeError('computer process superseded')
elif not os.path.exists(root+'/generation') or int(open(root+'/generation').read())!=p['generation']:raise RuntimeError('computer owner superseded')
i=p['input'];args=['systemd-run','--user','--pipe','--wait','--collect','--unit='+p['unit'],'--slice=paperclip-'+p['owner']+'.slice','--property=KillMode=control-group','--working-directory='+i.get('cwd',p['cwd'])]
for k,v in i.get('env',{}).items():args.append('--setenv='+k+'='+v)
child=subprocess.Popen(args+['--',i['command']]+i.get('args',[]),stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
@@ -147,7 +162,8 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
],
stdin: JSON.stringify({
owner: owner.id,
generation: owner.generation,
generation: current.owner.generation,
processClaim: processScoped ? pinnedProcess : null,
unit: `paperclip-command-${randomUUID()}.service`,
cwd: placement.cwd,
input: {
@@ -163,10 +179,17 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
onSpawn: input.onSpawn,
});
},
};
});
return {
owner: ownerRef,
runner,
runner: runnerFor(false),
process: {
runner: runnerFor(true),
async ingress(input?: {port?:number;path?:string}) {
const current = await processScope();
return backend.ingress(current.record,input?.port??current.owner.port,input?.path??"/");
},
},
listenerPort: owner.port,
remoteCwd: placement.cwd,
agentHome: placement.root,
@@ -177,16 +200,19 @@ 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 claimed = await repository.update(record, (current) => {
const o = exactOwner(current, ownerRef);
if (o.phase !== "active" && o.phase !== "starting")
throw new ComputerError("conflict", "Computer owner cannot launch");
if (!o.process)
if (existing?.running && existing.claim) o.process = existing.claim;
else if (!o.process || !existing?.running)
o.process = {
bootId: "",
unitName: `paperclip-${o.id}.service`,
nonce: randomUUID(),
launchGeneration: o.generation,
launchGeneration: (o.process?.launchGeneration ?? 0) + 1,
};
return structuredClone(current);
});
@@ -198,6 +224,7 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
await repository.update(record, (current) => {
exactOwner(current, ownerRef).process = claim;
});
pinnedProcess = structuredClone(claim);
return claim;
},
async inspectProcess() {
@@ -225,6 +252,7 @@ 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");
timeout(input.idleTimeoutMs);
const result = await repository.update(input, (record) => {
assertAdmission(record.ledger);
@@ -616,7 +644,7 @@ sys.stdout.write(output);sys.stderr.write(error);sys.exit(child.returncode)
});
await repository.update(input, (current) => {
exactOwner(current, input.owner);
const placementKey = `workspace:${input.projectId}:${input.mode}:${input.taskId ?? "shared"}:${result.remoteCwd}`;
const placementKey = `workspace:${owner.agentId}:${input.projectId}:${input.mode}:${input.taskId ?? "shared"}:${result.remoteCwd}`;
current.ledger.placements[placementKey] ??= {
id: randomUUID(),
root: placement.root,