Close low-trust repository acquisition and preserve workspace lifecycle defaults

Reject new controller clones for low-trust tasks, reuse only verified existing public checkouts, accept eligible idle repository requests, and carry Telegram destination defaults through migration.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-12 12:27:58 -05:00
1 parent 29c37bb1fe
commit 680431b5c1
8 files changed
+245 -84

No files matched your search

@@ -64644,7 +64644,10 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
}
});
it("migrates Telegram basic-group reach and topic tasks to the replacement supergroup", async () => {
it.each([
...["unset", "inherit", "clear", "configured"].flatMap((defaultsMode) =>
[false, true].map((existingDestination) => ({ defaultsMode, existingDestination }))),
])("migrates Telegram basic-group reach, topic tasks and $defaultsMode defaults (existing destination: $existingDestination)", async ({ defaultsMode, existingDestination }) => {
const fixture = await seedCompany();
const { callbacks, endpoint, service, wakeup } =
await configuredTelegramEndpoint(fixture);
@@ -64652,6 +64655,17 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
.update(chatEndpoints)
.set({ status: "active" })
.where(eq(chatEndpoints.id, endpoint.id));
const [defaultProject, selectedProject] = await db.insert(projects).values([
{ companyId: fixture.companyId, name: "Endpoint default project" },
{ companyId: fixture.companyId, name: "Migrated resource project" },
]).returning();
await service.update(endpoint.id, { executionDefaults: {
projectId: defaultProject.id, workspace: { kind: "task_directory" },
} }, "owner-user");
const executionDefaults = defaultsMode === "unset" ? null
: defaultsMode === "inherit" ? {}
: defaultsMode === "clear" ? { projectId: null, workspace: null }
: { projectId: selectedProject.id, workspace: { kind: "task_directory" as const } };
const previousChatId = "-5546433913";
const migratedChatId = "-1004415501660";
const topicId = 77;
@@ -64665,8 +64679,14 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
label: "Telegram migration group",
availability: "available",
enabled: true,
executionDefaults,
})
.returning();
if (existingDestination) await db.insert(chatEndpointResources).values({
companyId: fixture.companyId, endpointId: endpoint.id, type: "chat",
providerResourceId: migratedChatId, label: "Existing destination", availability: "available",
executionDefaults: { projectId: selectedProject.id, workspace: null },
});
const previousTopic = makeThread({
channelId: `telegram:${previousChatId}`,
id: `telegram:${previousChatId}:${topicId}`,
@@ -64725,6 +64745,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
}),
expect.objectContaining({
providerResourceId: migratedChatId,
executionDefaults,
label: "Telegram migration group",
availability: "available",
enabled: true,
@@ -64779,6 +64800,22 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
{ body: "Continue by replying after the group migration" },
]);
expect(wakeup).toHaveBeenCalledTimes(2);
// A new topic must snapshot the migrated destination's defaults, while the
// existing topic above keeps its original task and workspace selection.
const newTopic = makeThread({ channelId: `telegram:${migratedChatId}`,
id: `telegram:${migratedChatId}:${topicId + 1}`, name: "New migrated topic" });
await deliverMessage({ callbacks, endpointId: endpoint.id, provider: "telegram", thread: newTopic.thread,
message: makeMessage({ id: `${migratedChatId}:43`, raw: { message_id: 43, message_thread_id: topicId + 1 },
text: "Start a new topic after migration", mentioned: true, userId: "telegram-migration-user" }), trigger: "mention" });
const newConversation = (await service.listConversations(endpoint.id)).find(row => row.id !== beforeMigration.id);
expect(newConversation).toBeDefined();
const [newTask] = await readIssuesById(newConversation!.issueId);
expect(newTask.projectId).toBe(defaultsMode === "clear" ? null
: defaultsMode === "configured" ? selectedProject.id : defaultProject.id);
expect(newTask.workspaceSelection).toEqual(defaultsMode === "clear" ? null
: { version: 1, selection: { kind: "task_directory" }, source: "channel" });
expect(wakeup).toHaveBeenCalledTimes(3);
});
it("enforces Telegram group reach and privacy-mode addressing before retaining message content", async () => {
@@ -14,9 +14,9 @@ const support = await getEmbeddedPostgresTestSupport();
const originalSecret = process.env.PAPERCLIP_AGENT_JWT_SECRET;
beforeAll(async () => { process.env.PAPERCLIP_AGENT_JWT_SECRET = randomUUID(); server = await startRunnerApiTestServer(); }, 60_000);
afterAll(async () => { await server?.close(); if (originalSecret === undefined) delete process.env.PAPERCLIP_AGENT_JWT_SECRET; else process.env.PAPERCLIP_AGENT_JWT_SECRET = originalSecret; });
it("inspects admitted files, durably requests a repository, and stages root selection without interrupting", async () => {
it("inspects an idle admitted workspace, requests a repository, and stages root selection without interrupting", async () => {
const f = await server.fixture({ conversation: true, disableWakeOnDemand: true });
const [workspace] = await server.db.insert(executionWorkspaces).values({ companyId: f.companyId, projectId: null, sourceIssueId: f.issueId, name: "Task files", cwd: f.workspace, mode: "shared_workspace", strategyType: "task_directory" }).returning();
const [workspace] = await server.db.insert(executionWorkspaces).values({ companyId: f.companyId, projectId: null, sourceIssueId: f.issueId, name: "Task files", cwd: f.workspace, mode: "shared_workspace", strategyType: "task_directory", status: "idle" }).returning();
await server.db.update(issues).set({ projectId: null, projectWorkspaceId: null, executionWorkspaceId: workspace.id }).where(eq(issues.id, f.issueId));
const authority = new PaperclipRunnerToolAuthority(server.db, { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, runId: f.runId, apiUrl: server.apiUrl, workspaceRoot: "/admitted/task" });
const call = (tool: string, args: Record<string, unknown>) => authority.execute({ tool, arguments: args, callId: randomUUID() });
@@ -57,6 +57,24 @@ const support = await getEmbeddedPostgresTestSupport();
await expect(call("prepare_repository", repository)).resolves.toMatchObject({ kind: "requires_next_admission" });
});
it("denies new public clones for unlinked full-auto chat while keeping workspace discovery readable", async () => {
const f = await server.fixture({ conversation: true, disableWakeOnDemand: true });
const cwd = await mkdtemp(join(dirname(f.workspace), "unlinked-task-"));
const [workspace] = await server.db.insert(executionWorkspaces).values({ companyId: f.companyId, sourceIssueId: f.issueId,
name: "Unlinked chat files", cwd, mode: "isolated_workspace", strategyType: "task_directory" }).returning();
const policy = { trustPreset: "low_trust_review", authorizationPolicy: { trustPreset: "low_trust_review",
trustBoundary: { mode: "low_trust_review", companyId: f.companyId, rootIssueId: f.issueId } } };
await server.db.update(agents).set({ adapterConfig: { provider: "codex", codexPermissionMode: "never" } }).where(eq(agents.id, f.agentId));
await server.db.update(issues).set({ projectId: null, projectWorkspaceId: null, executionWorkspaceId: workspace.id,
executionPolicy: {} }).where(eq(issues.id, f.issueId));
await server.db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, executionPolicy: policy } }).where(eq(heartbeatRuns.id, f.runId));
const call = (tool: string, args: Record<string, unknown>) => f.authority.execute({ tool, arguments: args, callId: randomUUID() });
await expect(call("get_workspace", {})).resolves.toMatchObject({ workspace: { id: workspace.id } });
await expect(call("prepare_repository", { repository: { kind: "url", url: "https://github.com/public/example" }, requestKey: "unlinked-full-auto" }))
.rejects.toThrow(/trusted task/);
expect(await server.db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.companyId, f.companyId))).toHaveLength(0);
});
it("does not expose repository preparation or workspace selection to Ask mode", async () => {
const f = await server.fixture({ mode: "ask", conversation: true, disableWakeOnDemand: true });
await expect(f.authority.execute({ tool: "prepare_repository", callId: randomUUID(), arguments: { repository: { kind: "url", url: "https://github.com/public/example" }, requestKey: "denied" } })).rejects.toThrow();
@@ -121,7 +139,7 @@ const support = await getEmbeddedPostgresTestSupport();
const unrelatedCwd = await mkdtemp(join(dirname(f.workspace), "unrelated-workspace-"));
await server.db.update(executionWorkspaces).set({ cwd: unrelatedCwd }).where(eq(executionWorkspaces.id, unrelated.id));
await expect(call("select_workspace", { selection: { kind: "existing", workspaceId: source.id }, expectedBindingRevision: 0, requestKey: "source-allowed" })).resolves.toMatchObject({ kind: "scheduled" });
await expect(call("prepare_repository", repository)).resolves.toMatchObject({ kind: "requires_next_admission" });
await expect(call("prepare_repository", repository)).rejects.toThrow(/trusted task/);
expect((await server.db.select().from(issues).where(eq(issues.id, f.issueId)))[0]?.projectId).toBeNull();
});
});
@@ -425,7 +425,7 @@ const support = await getEmbeddedPostgresTestSupport();
await expect(f.service.prepareForAdmission(f.admission)).resolves.toEqual([]);
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, executionPolicy: f.policy } }).where(eq(heartbeatRuns.id, f.runId));
await expect(f.service.request({ companyId: f.companyId, issueId: peer.issueId, actor: peer.actor,
request: { repository: { kind: "catalog", id: "private-repo" }, requestKey: randomUUID() } })).rejects.toThrow(/anonymous public URLs only/);
request: { repository: { kind: "catalog", id: "private-repo" }, requestKey: randomUUID() } })).rejects.toThrow(/anonymous public URLs only|trusted task/);
expect(await f.service.list(f.companyId, peer.workspace.id)).toEqual([]);
expect(acquisition.materialize).not.toHaveBeenCalled();
});
@@ -504,28 +504,57 @@ const support = await getEmbeddedPostgresTestSupport();
await db.update(executionWorkspaces).set({ projectId: project.id, strategyType: "git_worktree" }).where(eq(executionWorkspaces.id, f.workspace.id));
}
}
await expect(f.request({ kind: "catalog", id: "private-repo" })).rejects.toThrow(/anonymous public URLs only/);
await expect(f.request({ kind: "catalog", id: "private-repo" })).rejects.toThrow(/anonymous public URLs only|trusted task/);
expect(await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.companyId, f.companyId))).toHaveLength(0);
expect(acquisition.managedAuth).not.toHaveBeenCalled();
},
);
it("keeps a URL matching the sponsor's private catalog anonymous under retained run trust", async () => {
const f = await fixture();
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, executionPolicy: f.policy } }).where(eq(heartbeatRuns.id, f.runId));
const receipt = await f.request({ kind: "url", url: "https://github.com/sponsor/private" });
expect(receipt.repository.catalogRepositoryId).toBeNull();
acquisition.materialize.mockImplementationOnce(async (_cwd, input) => {
const auth = await input.resolveGitAuth(input.repoUrl);
expect(auth).toEqual({ ...buildGitAuthInvocation({ token: "", source: "managed_connection", secretName: null }),
env: expect.objectContaining({ GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_SYSTEM: "/dev/null" }) });
throw new Error("Anonymous remote rejects private repository");
it.each(["agent", "issue", "project", "workspace_source_project", "run"] as const)(
"rejects public acquisition from raw %s policy even with full-auto provider permissions", async source => {
const f = await fixture();
await db.update(agents).set({ adapterConfig: { provider: "codex", codexPermissionMode: "never" },
...(source === "agent" ? { permissions: f.policy } : {}) }).where(eq(agents.id, f.agentId));
if (source === "issue") await db.update(issues).set({ executionPolicy: f.policy }).where(eq(issues.id, f.issueId));
if (source === "run") {
await db.update(issues).set({ executionPolicy: {} }).where(eq(issues.id, f.issueId));
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, executionPolicy: f.policy } }).where(eq(heartbeatRuns.id, f.runId));
}
if (source === "project" || source === "workspace_source_project") {
const [project] = await db.insert(projects).values({ companyId: f.companyId, name: "Restricted", executionWorkspacePolicy: f.policy }).returning();
if (source === "project") await db.update(issues).set({ projectId: project.id }).where(eq(issues.id, f.issueId));
else {
await db.update(projects).set({ executionWorkspacePolicy: { ...f.policy, authorizationPolicy: { ...f.policy.authorizationPolicy,
trustBoundary: { ...f.policy.authorizationPolicy.trustBoundary, projectIds: [project.id] } } } }).where(eq(projects.id, project.id));
await db.update(executionWorkspaces).set({ projectId: project.id, strategyType: "git_worktree" }).where(eq(executionWorkspaces.id, f.workspace.id));
}
}
for (const url of ["https://github.com/public/example", "https://github.com/sponsor/private"]) {
await expect(f.request({ kind: "url", url })).rejects.toThrow(/trusted task/);
}
expect(await f.service.list(f.companyId, f.workspace.id)).toEqual([]);
expect(acquisition.materialize).not.toHaveBeenCalled();
expect(acquisition.managedAuth).not.toHaveBeenCalled();
});
await expect(f.service.prepareForAdmission(f.admission)).rejects.toThrow("Anonymous remote rejects private repository");
expect(acquisition.materialize).toHaveBeenCalledOnce();
it.each(["pending", "preparing"] as const)("blocks %s public acquisition after trust is downgraded", async state => {
const f = await fixture();
const receipt = await f.request({ kind: "url", url: "https://github.com/public/example" });
await db.update(executionWorkspaceRepositories).set({ state }).where(eq(executionWorkspaceRepositories.id, receipt.operationId));
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, executionPolicy: f.policy } }).where(eq(heartbeatRuns.id, f.runId));
await expect(f.service.prepareForAdmission(f.admission)).rejects.toThrow(/trusted task/);
expect((await f.service.list(f.companyId, f.workspace.id))[0].state).toBe(state);
expect(acquisition.materialize).not.toHaveBeenCalled();
expect(acquisition.managedAuth).not.toHaveBeenCalled();
const [stored] = await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.id, receipt.operationId));
expect(stored).toMatchObject({ catalogRepositoryId: null, state: "needs_repair" });
});
it("rejects an unsponsored request even when the caller supplies a sponsor actor", async () => {
const f = await fixture();
await db.update(heartbeatRuns).set({ responsibleUserId: null }).where(eq(heartbeatRuns.id, f.runId));
await expect(f.request({ kind: "url", url: "https://github.com/public/example" })).rejects.toThrow(/responsible user/);
expect(await f.service.list(f.companyId, f.workspace.id)).toEqual([]);
await expect(f.service.prepareForAdmission({ ...f.admission, responsibleUserId: null })).resolves.toEqual([]);
expect(acquisition.materialize).not.toHaveBeenCalled();
});
it.each(["pending", "ready"] as const)("blocks a %s managed receipt after the run becomes low trust", async state => {
@@ -536,17 +565,34 @@ const support = await getEmbeddedPostgresTestSupport();
const checkout = path.join(f.admission.cwd, receipt.repository.relativePath);
if (state === "ready") { await mkdir(checkout, { recursive: true }); await writeFile(path.join(checkout, "private.txt"), "retained private bytes"); }
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, executionPolicy: f.policy } }).where(eq(heartbeatRuns.id, f.runId));
await expect(f.request({ kind: "url", url: receipt.repository.repoUrl })).rejects.toThrow(/anonymous public URLs only/);
await expect(f.service.prepareForAdmission(f.admission)).rejects.toThrow(/anonymous public URLs only/);
await expect(f.request({ kind: "url", url: receipt.repository.repoUrl })).rejects.toThrow(/anonymous public URLs only|trusted task/);
await expect(f.service.prepareForAdmission(f.admission)).rejects.toThrow(/anonymous public URLs only|trusted task/);
expect(acquisition.materialize).not.toHaveBeenCalled();
expect(acquisition.managedAuth).not.toHaveBeenCalled();
if (state === "ready") expect(await readFile(path.join(checkout, "private.txt"), "utf8")).toBe("retained private bytes");
});
it("prepares an anonymous public URL through actual local Git materialization", async () => {
it.each([
{ status: "active", closedAt: new Date() },
{ status: "idle", closedAt: new Date() },
{ status: "archived", closedAt: null },
{ status: "in_review", closedAt: null },
])("rejects repository requests for unavailable $status workspaces (closed=$closedAt)", async lifecycle => {
const f = await fixture();
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, executionPolicy: f.policy } }).where(eq(heartbeatRuns.id, f.runId));
await db.update(executionWorkspaces).set(lifecycle).where(eq(executionWorkspaces.id, f.workspace.id));
await expect(f.request({ kind: "url", url: "https://github.com/public/example" })).rejects.toThrow("Execution workspace is unavailable");
expect(await f.service.list(f.companyId, f.workspace.id)).toEqual([]);
expect(acquisition.materialize).not.toHaveBeenCalled();
});
it.each(["sponsored", "local_board", "routine"] as const)("prepares public Git from an idle workspace for a trusted %s task and reuses verified bytes after trust downgrade", async principal => {
const f = await fixture();
await db.update(executionWorkspaces).set({ status: "idle" }).where(eq(executionWorkspaces.id, f.workspace.id));
if (principal === "local_board") await db.update(heartbeatRuns).set({ responsibleUserId: "local-board" }).where(eq(heartbeatRuns.id, f.runId));
const receipt = await f.request({ kind: "url", url: "https://github.com/public/example" });
const responsibleUserId = principal === "local_board" ? "local-board" : principal === "routine" ? null : f.userId;
await db.update(heartbeatRuns).set({ responsibleUserId }).where(eq(heartbeatRuns.id, f.runId));
const admission = { ...f.admission, responsibleUserId };
const source = path.join(root, `${f.issueId}-public-source`);
await mkdir(source);
const exec = promisify(execFileCallback);
@@ -563,10 +609,40 @@ const support = await getEmbeddedPostgresTestSupport();
await exec("git", ["-C", cwd, "remote", "set-url", "origin", input.repoUrl]);
return result;
});
const [prepared] = await f.service.prepareForAdmission(f.admission);
const [prepared] = await f.service.prepareForAdmission(admission);
expect(prepared.id).toBe(receipt.operationId);
expect(await readFile(path.join(prepared.cwd, "public.txt"), "utf8")).toBe("Public fixture bytes\n");
expect(acquisition.managedAuth).not.toHaveBeenCalled();
await writeFile(path.join(prepared.cwd, "committed.txt"), "Later task commit\n");
await exec("git", ["-C", prepared.cwd, "add", "committed.txt"]);
await exec("git", ["-C", prepared.cwd, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "task changes"]);
const editedHead = (await exec("git", ["-C", prepared.cwd, "rev-parse", "HEAD"])).stdout.trim();
expect(editedHead).not.toBe(prepared.pinnedCommit);
await writeFile(path.join(prepared.cwd, "dirty.txt"), "Uncommitted task bytes\n");
acquisition.materialize.mockClear();
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, executionPolicy: f.policy } }).where(eq(heartbeatRuns.id, f.runId));
await expect(f.service.prepareForAdmission(admission)).resolves.toEqual([prepared]);
await expect(f.service.reserveForRecovery(admission)).resolves.toBeUndefined();
expect(acquisition.materialize).not.toHaveBeenCalled();
expect(await readFile(path.join(prepared.cwd, "public.txt"), "utf8")).toBe("Public fixture bytes\n");
expect((await exec("git", ["-C", prepared.cwd, "rev-parse", "HEAD"])).stdout.trim()).toBe(editedHead);
expect(await readFile(path.join(prepared.cwd, "dirty.txt"), "utf8")).toBe("Uncommitted task bytes\n");
await rm(prepared.cwd, { recursive: true });
await expect(f.service.prepareForAdmission(admission)).rejects.toThrow(/trusted task/);
expect(acquisition.materialize).not.toHaveBeenCalled();
});
it("reauthorizes a public clone before publication after trust changes during Git", async () => {
const f = await fixture();
const receipt = await f.request({ kind: "url", url: "https://github.com/public/example" });
await localPrivateClone(f, async () => {
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, executionPolicy: f.policy } }).where(eq(heartbeatRuns.id, f.runId));
});
await expect(f.service.prepareForAdmission(f.admission)).rejects.toThrow(/trusted task/);
await expect(fs.lstat(path.join(f.admission.cwd, receipt.repository.relativePath))).rejects.toMatchObject({ code: "ENOENT" });
expect((await f.service.list(f.companyId, f.workspace.id))[0]).toMatchObject({ pinnedCommit: null, state: "needs_repair" });
expect(acquisition.materialize).toHaveBeenCalledOnce();
expect(acquisition.managedAuth).not.toHaveBeenCalled();
});
it.each(["same_repository", "different_repository", "empty_inventory", "unpinned_publication", "pending_intent"] as const)(
@@ -595,8 +671,8 @@ const support = await getEmbeddedPostgresTestSupport();
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
if (scenario !== "empty_inventory") await expect(f.service.request({ companyId: f.companyId, issueId, actor: { ...f.actor, runId },
request: { requestKey: randomUUID(), repository: { kind: "url", url: scenario === "same_repository" ? managed.repository.repoUrl : "https://github.com/public/other" } } }))
.rejects.toThrow(/anonymous public URLs only/);
await expect(f.service.prepareForAdmission({ ...f.admission, issueId, runId, workspaceId: peer.id })).rejects.toThrow(/anonymous public URLs only/);
.rejects.toThrow(/anonymous public URLs only|trusted task/);
await expect(f.service.prepareForAdmission({ ...f.admission, issueId, runId, workspaceId: peer.id })).rejects.toThrow(/anonymous public URLs only|trusted task/);
expect(acquisition.materialize).not.toHaveBeenCalled();
expect(acquisition.managedAuth).not.toHaveBeenCalled();
if (scenario !== "pending_intent") expect(await readFile(path.join(checkout, "private.txt"), "utf8")).toBe("Private peer bytes");
@@ -642,10 +718,10 @@ const support = await getEmbeddedPostgresTestSupport();
if (String(pathname).startsWith(aliasParent)) throw Object.assign(new Error("Unreadable legacy alias"), { code: "EACCES" });
return actual(pathname);
});
await expect(f.service.prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only/);
await expect(f.service.prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only|trusted task/);
await expect(f.service.request({ companyId: f.companyId, issueId: peer.admission.issueId, actor: peer.actor,
request: { repository: { kind: "url", url: "https://github.com/public/unrelated" }, requestKey: randomUUID() } }))
.rejects.toThrow(/anonymous public URLs only/);
.rejects.toThrow(/anonymous public URLs only|trusted task/);
expect(await f.service.list(f.companyId, peer.workspace.id)).toEqual([]);
expect(acquisition.materialize).not.toHaveBeenCalled();
expect(acquisition.managedAuth).not.toHaveBeenCalled();
@@ -713,7 +789,7 @@ const support = await getEmbeddedPostgresTestSupport();
await symlink(f.admission.cwd, alias);
await db.update(executionWorkspaces).set({ cwd: alias }).where(eq(executionWorkspaces.id, f.workspace.id));
const peer = await lowTrustPeer(f);
await expect(f.service.prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only/);
await expect(f.service.prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only|trusted task/);
});
it("reserves a legacy low-trust recovery folder after its task binding moves", async () => {
@@ -726,7 +802,7 @@ const support = await getEmbeddedPostgresTestSupport();
await f.service.reserveForRecovery(peer.admission);
await expect(executionWorkspaceRepositoryService(db).request({ companyId: f.companyId, issueId: f.issueId, actor: f.actor,
request: { repository: { kind: "catalog", id: "private-repo" }, requestKey: randomUUID() } }))
.rejects.toThrow(/anonymous public URLs only/);
.rejects.toThrow(/anonymous public URLs only|trusted task/);
const [reservation] = await db.select().from(executionWorkspaceRepositoryRoots).where(eq(executionWorkspaceRepositoryRoots.companyId, f.companyId));
expect(reservation).toMatchObject({ canonicalCwd: await realpath(f.admission.cwd), mode: "anonymous_only" });
expect(acquisition.materialize).not.toHaveBeenCalled();
@@ -740,7 +816,7 @@ const support = await getEmbeddedPostgresTestSupport();
const peer = await lowTrustPeer(f);
await f.service.reserveForRecovery(f.admission);
await db.update(executionWorkspaces).set({ cwd: path.join(root, "moved-managed-recovery") }).where(eq(executionWorkspaces.id, f.workspace.id));
await expect(executionWorkspaceRepositoryService(db).reserveForRecovery(peer.admission)).rejects.toThrow(/anonymous public URLs only/);
await expect(executionWorkspaceRepositoryService(db).reserveForRecovery(peer.admission)).rejects.toThrow(/anonymous public URLs only|trusted task/);
expect(acquisition.materialize).not.toHaveBeenCalled();
});
@@ -760,9 +836,9 @@ const support = await getEmbeddedPostgresTestSupport();
expect(reservation.mode).toBe(outcomes[0].status === "fulfilled" ? "anonymous_only" : "managed");
const restarted = executionWorkspaceRepositoryService(db);
if (reservation.mode === "anonymous_only") {
await expect(f.request({ kind: "catalog", id: "private-repo" })).rejects.toThrow(/anonymous public URLs only/);
await expect(f.request({ kind: "catalog", id: "private-repo" })).rejects.toThrow(/anonymous public URLs only|trusted task/);
await expect(restarted.prepareForAdmission(peer.admission)).resolves.toEqual([]);
} else await expect(restarted.prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only/);
} else await expect(restarted.prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only|trusted task/);
expect(acquisition.materialize).not.toHaveBeenCalled();
});
@@ -778,10 +854,10 @@ const support = await getEmbeddedPostgresTestSupport();
.where(eq(executionWorkspaces.id, peer.workspace.id));
const restarted = executionWorkspaceRepositoryService(db);
await expect(restarted.request({ companyId: f.companyId, issueId: f.issueId, actor: f.actor,
request: { repository: { kind: "catalog", id: "private-repo" }, requestKey: randomUUID() } })).rejects.toThrow(/anonymous public URLs only/);
request: { repository: { kind: "catalog", id: "private-repo" }, requestKey: randomUUID() } })).rejects.toThrow(/anonymous public URLs only|trusted task/);
acquisition.catalog.mockResolvedValue({ repositories: [{ id: "later", fullName: "public/later-catalog", private: true,
url: pending.repository.repoUrl, connections: ["sponsor-github"] }] });
await expect(restarted.prepareForAdmission(f.admission)).rejects.toThrow(/anonymous public URLs only/);
await expect(restarted.prepareForAdmission(f.admission)).rejects.toThrow(/anonymous public URLs only|trusted task/);
expect(acquisition.managedAuth).not.toHaveBeenCalled();
expect(acquisition.materialize).not.toHaveBeenCalled();
expect((await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.id, pending.operationId)))[0].catalogRepositoryId).toBeNull();
@@ -820,11 +896,11 @@ const support = await getEmbeddedPostgresTestSupport();
// The reservation remains anchored to the physical root even if ordinary
// metadata/placement maintenance changes the originating workspace row.
await db.update(executionWorkspaces).set({ cwd: path.join(root, "moved-managed-workspace"), metadata: {} }).where(eq(executionWorkspaces.id, f.workspace.id));
await expect(executionWorkspaceRepositoryService(db).prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only/);
await expect(executionWorkspaceRepositoryService(db).prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only|trusted task/);
} finally { release(); }
const [prepared] = await preparation;
expect(await readFile(path.join(prepared.cwd, "private.txt"), "utf8")).toBe("Private fixture bytes\n");
await expect(executionWorkspaceRepositoryService(db).prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only/);
await expect(executionWorkspaceRepositoryService(db).prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only|trusted task/);
});
it("retains previous run trust without confusing a board request's reassigned agent", async () => {
@@ -837,7 +913,7 @@ const support = await getEmbeddedPostgresTestSupport();
request: { requestKey: randomUUID(), repository: { kind: "catalog", id: "private-repo" } } });
await expect(request()).resolves.toMatchObject({ kind: "requires_next_admission" });
await db.update(heartbeatRuns).set({ contextSnapshot: { taskId: f.issueId, executionPolicy: f.policy } }).where(eq(heartbeatRuns.id, f.runId));
await expect(request()).rejects.toThrow(/anonymous public URLs only/);
await expect(request()).rejects.toThrow(/anonymous public URLs only|trusted task/);
});
it("preserves standard empty-inventory admission without repository mutation authority", async () => {
@@ -434,6 +434,7 @@ export function createChatResourceReconciliation(db: Db, options: ResourceReconc
(currentEndpoint.provider === "slack" &&
effect.resourceType === "channel" &&
effect.availability === "available"),
...(previousResource ? { executionDefaults: previousResource.executionDefaults } : {}),
metadata: effect.metadata ?? {},
})
.onConflictDoUpdate({
@@ -453,6 +454,7 @@ export function createChatResourceReconciliation(db: Db, options: ResourceReconc
enabled: sql<boolean>`${chatEndpointResources.enabled} or ${migratedEnabled}`,
}
: {}),
...(previousResource ? { executionDefaults: previousResource.executionDefaults } : {}),
metadata: effect.metadata ?? {},
updatedAt: now,
},
@@ -13,6 +13,7 @@ import { parseNativeExecutionInput } from "../vendor/paperclip-runner/index.js";
import { assertTaskWorkspaceAccess, assertTaskWorkspaceSourceProjectAccess } from "./task-workspace-source-access.js";
import { authorizationService, canActorReadExecutionWorkspace, executionWorkspaceReadSqlCondition, issueReadSqlCondition, projectReadSqlCondition, type AuthorizationActor } from "./authorization.js";
import { resolveCoreTrustPreset } from "./trust-preset-resolver.js";
import { taskWorkspaceSelectableCondition } from "./task-workspace-selection.js";
import { captureRunIdentity } from "./run-identity.js";
import { toolAccessService } from "./tool-access.js";
import { normalizeProjectRepositoryUrl } from "./project-repositories.js";
@@ -63,7 +64,8 @@ async function legacyRepositoryRootMayMatch(cwd: string, candidate: string): Pro
}
}
const lowTrustRepositoryMessage = "Low-trust tasks may prepare anonymous public URLs only. Use an authorized configured source for private repositories.";
const controllerAcquisitionMessage = "New controller repository acquisition requires a trusted task. Existing verified public checkouts remain available.";
const lowTrustRepositoryMessage = "Low-trust repository reuse permits anonymous public URLs only; new acquisition is unavailable. Use an authorized configured source for private repositories.";
function resolveAcquisitionSource(request: PrepareWorkspaceRepository["repository"], available: ProjectRepository[], anonymousOnly: boolean) {
if (anonymousOnly && request.kind === "catalog") throw forbidden(lowTrustRepositoryMessage);
@@ -286,6 +288,12 @@ export function executionWorkspaceRepositoryService(db: Db) {
if (trust.kind === "denied") throw forbidden(trust.detail);
return trust.kind === "low_trust_review";
}
async function assertCurrentControllerAcquisition(input: { companyId: string; issueId: string; workspaceId: string; agentId: string; runId: string }) {
const [issue] = await db.select().from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId)));
const [workspace] = await db.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.id, input.workspaceId), eq(executionWorkspaces.companyId, input.companyId)));
if (!issue || !workspace || issue.executionWorkspaceId !== workspace.id) throw forbidden("Task repository workspace binding is unavailable");
if (await requiresAnonymousAcquisition(db, { issue, workspace, agentId: input.agentId, runId: input.runId })) throw forbidden(controllerAcquisitionMessage);
}
async function reserveRootPolicy(tx: DbTransaction, companyId: string, cwd: string, mode: "anonymous_only" | "managed") {
const canonicalCwd = await canonicalRepositoryRoot(cwd);
const rootKey = createHash("sha256").update(canonicalCwd).digest("hex");
@@ -447,8 +455,8 @@ export function executionWorkspaceRepositoryService(db: Db) {
if (!issue.executionWorkspaceId) throw conflict("The task has no admitted workspace yet. Start it once before preparing a repository.");
if (!(await canActorReadExecutionWorkspace(db, input.actor, issue.executionWorkspaceId))) throw notFound("Execution workspace not found");
// Serialize receipts across tasks without blocking unchanged-ID foreign-key reads.
const [workspace] = await tx.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.id, issue.executionWorkspaceId), eq(executionWorkspaces.companyId, input.companyId))).for("no key update");
if (!workspace || workspace.status !== "active") throw conflict("Execution workspace is unavailable");
const [workspace] = await tx.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.id, issue.executionWorkspaceId), eq(executionWorkspaces.companyId, input.companyId), taskWorkspaceSelectableCondition())).for("no key update");
if (!workspace) throw conflict("Execution workspace is unavailable");
await assertTaskWorkspaceAccess(tx, input.actor, input.companyId, workspace.id, { write: true, issueId: input.issueId });
const anonymousOnly = await requiresAnonymousAcquisition(tx, { issue, workspace,
agentId: input.actor.agentId, runId: input.actor.runId });
@@ -459,6 +467,7 @@ export function executionWorkspaceRepositoryService(db: Db) {
}
if (!workspace.cwd) throw conflict("The task workspace has no directory for repository preparation");
await authorizeRootAccess(tx, { companyId: input.companyId, cwd: workspace.cwd, sourceWorkspaceId: workspace.id, actor: input.actor, issueId: input.issueId });
if (anonymousOnly) throw forbidden(controllerAcquisitionMessage);
const existing = await tx.select().from(executionWorkspaceRepositories).where(and(eq(executionWorkspaceRepositories.executionWorkspaceId, workspace.id), or(eq(executionWorkspaceRepositories.repositoryIdentity, source.repositoryIdentity), sql`${executionWorkspaceRepositories.requestKeys} ? ${parsed.requestKey}`)));
for (const row of existing) {
assertAcquisitionReceipt(row, anonymousOnly);
@@ -568,9 +577,13 @@ export function executionWorkspaceRepositoryService(db: Db) {
sourceWorkspaceId: workspace.id, preserveOwnAdmission: true });
return [];
}
const acquisitionRestricted = anonymousOnly;
if (acquisitionRestricted && rows.some(row => row.state !== "ready" || !row.pinnedCommit || !/^[a-f0-9]{40,64}$/.test(row.pinnedCommit))) {
throw forbidden(controllerAcquisitionMessage);
}
await assertTaskWorkspaceAccess(db, actor, input.companyId, input.workspaceId, { write: true, issueId: input.issueId });
const root = await fs.realpath(input.cwd);
const available = anonymousOnly ? [] : await catalog(input.companyId, input.responsibleUserId, input.responsibleUserId === "local-board");
const available = acquisitionRestricted ? [] : await catalog(input.companyId, input.responsibleUserId, input.responsibleUserId === "local-board");
const resolveAuth = createGitRemoteAuthProvider(db, input.companyId, { issueId: input.issueId, heartbeatRunId: input.runId, agentId: input.agentId, responsibleUserId: input.responsibleUserId });
// Validate every receipt before reading or transferring any prepared bytes.
const sources = rows.map(row => {
@@ -583,37 +596,39 @@ export function executionWorkspaceRepositoryService(db: Db) {
}
await reserveRootAccess({ companyId: input.companyId, cwd: root, sourceWorkspaceId: input.workspaceId, reader: input });
const repositoryRoot = path.join(root, ".paperclip-repositories");
await fs.mkdir(repositoryRoot, { recursive: true });
if (!acquisitionRestricted) await fs.mkdir(repositoryRoot, { recursive: true });
if ((await fs.lstat(repositoryRoot)).isSymbolicLink() || await fs.realpath(repositoryRoot) !== repositoryRoot) throw conflict("Repository directory escapes the task workspace");
// Incomplete clones belong to the runtime tree, which is excluded from
// transfer and recovery. The published namespace contains checkouts only.
let stagingParent = root;
for (const name of [".paperclip-runtime", "repository-staging"]) {
stagingParent = path.join(stagingParent, name);
await fs.mkdir(stagingParent, { mode: 0o700 }).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "EEXIST") throw error;
});
const entry = await fs.lstat(stagingParent);
if (!entry.isDirectory() || entry.isSymbolicLink() || await fs.realpath(stagingParent) !== stagingParent) {
throw conflict("Repository staging directory escapes the task workspace");
if (!acquisitionRestricted) {
for (const name of [".paperclip-runtime", "repository-staging"]) {
stagingParent = path.join(stagingParent, name);
await fs.mkdir(stagingParent, { mode: 0o700 }).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "EEXIST") throw error;
});
const entry = await fs.lstat(stagingParent);
if (!entry.isDirectory() || entry.isSymbolicLink() || await fs.realpath(stagingParent) !== stagingParent) {
throw conflict("Repository staging directory escapes the task workspace");
}
}
// Self-ignore before any clone writes, including when the task directory
// is a subfolder of another checkout. Never follow a supplied ignore file.
const ignorePath = path.join(stagingParent, ".gitignore");
const ignoreEntry = await fs.lstat(ignorePath).catch((error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT") return null;
throw error;
});
if (ignoreEntry && (!ignoreEntry.isFile() || ignoreEntry.isSymbolicLink())) {
throw conflict("Repository staging ignore file is not a regular file");
}
const ignoreTemporary = path.join(stagingParent, `.ignore-${randomUUID()}.tmp`);
try {
await fs.writeFile(ignoreTemporary, "*\n", { flag: "wx", mode: 0o600 });
await fs.rename(ignoreTemporary, ignorePath);
} finally { await fs.rm(ignoreTemporary, { force: true }); }
await ensureManagedRepositoriesIgnored(root);
}
// Self-ignore before any clone writes, including when the task directory
// is a subfolder of another checkout. Never follow a supplied ignore file.
const ignorePath = path.join(stagingParent, ".gitignore");
const ignoreEntry = await fs.lstat(ignorePath).catch((error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT") return null;
throw error;
});
if (ignoreEntry && (!ignoreEntry.isFile() || ignoreEntry.isSymbolicLink())) {
throw conflict("Repository staging ignore file is not a regular file");
}
const ignoreTemporary = path.join(stagingParent, `.ignore-${randomUUID()}.tmp`);
try {
await fs.writeFile(ignoreTemporary, "*\n", { flag: "wx", mode: 0o600 });
await fs.rename(ignoreTemporary, ignorePath);
} finally { await fs.rm(ignoreTemporary, { force: true }); }
await ensureManagedRepositoriesIgnored(root);
const prepared: Array<{ id: string; cwd: string; repoUrl: string; relativePath: string; pinnedCommit: string; branchName: string | null }> = [];
for (const [index, row] of rows.entries()) {
const source = sources[index];
@@ -627,10 +642,11 @@ export function executionWorkspaceRepositoryService(db: Db) {
const metadata = await fs.lstat(gitDir).catch(() => null);
if (!metadata?.isDirectory() || metadata.isSymbolicLink() || await fs.realpath(gitDir) !== gitDir) throw conflict("Repository Git metadata escapes the managed checkout");
}
if (acquisitionRestricted && !existing) throw forbidden(controllerAcquisitionMessage);
// Uncataloged URLs may use anonymous public Git only. Never borrow a user's/company's credential for an arbitrary URL.
const anonymous = buildGitAuthInvocation({ token: "", source: "managed_connection", secretName: null });
anonymous.env = { ...anonymous.env, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_SYSTEM: "/dev/null" };
await db.update(executionWorkspaceRepositories).set({ state: "preparing", catalogRepositoryId: source.catalogRepositoryId, failureCode: null, updatedAt: new Date() }).where(eq(executionWorkspaceRepositories.id, row.id));
if (!acquisitionRestricted) await db.update(executionWorkspaceRepositories).set({ state: "preparing", catalogRepositoryId: source.catalogRepositoryId, failureCode: null, updatedAt: new Date() }).where(eq(executionWorkspaceRepositories.id, row.id));
try {
const ownershipPath = path.join(cwd, ".git", "paperclip-workspace-owner.json");
const readOwnership = async () => {
@@ -649,25 +665,30 @@ export function executionWorkspaceRepositoryService(db: Db) {
if (existing && !authorizedPin && initialOwnership?.repositoryId !== row.id) {
throw conflict("Repository directory has no matching preparation receipt; repair it before retrying");
}
const result = await materializeManagedProjectWorkspace(cwd, {
repoUrl: row.repoUrl,
stagingParent,
repoRef: authorizedPin ?? (row.requestedRef === "HEAD" ? null : row.requestedRef),
resolveGitAuth: source.catalogRepositoryId ? resolveAuth : async () => anonymous,
beforePublish: async cloneCwd => {
await reserveRootAccess({ companyId: input.companyId, cwd: root, sourceWorkspaceId: input.workspaceId, reader: input });
const pinnedCommit = (await execFile("git", ["-C", cloneCwd, "rev-parse", "HEAD"], { timeout: 30_000 })).stdout.trim();
await fs.writeFile(path.join(cloneCwd, ".git", "paperclip-workspace-owner.json"), JSON.stringify({ version: 1, repositoryId: row.id, pinnedCommit }), { flag: "wx", mode: 0o600 });
},
});
if (result.warning) throw conflict(result.warning);
const git = async (...args: string[]) => (await execFile("git", ["-C", cwd, ...args], { timeout: 30_000 })).stdout.trim();
if (!acquisitionRestricted) {
await assertCurrentControllerAcquisition(input);
const result = await materializeManagedProjectWorkspace(cwd, {
repoUrl: row.repoUrl,
stagingParent,
repoRef: authorizedPin ?? (row.requestedRef === "HEAD" ? null : row.requestedRef),
resolveGitAuth: source.catalogRepositoryId ? resolveAuth : async () => anonymous,
beforePublish: async cloneCwd => {
await assertCurrentControllerAcquisition(input);
await reserveRootAccess({ companyId: input.companyId, cwd: root, sourceWorkspaceId: input.workspaceId, reader: input });
const pinnedCommit = (await execFile("git", ["-C", cloneCwd, "rev-parse", "HEAD"], { timeout: 30_000 })).stdout.trim();
await fs.writeFile(path.join(cloneCwd, ".git", "paperclip-workspace-owner.json"), JSON.stringify({ version: 1, repositoryId: row.id, pinnedCommit }), { flag: "wx", mode: 0o600 });
},
});
if (result.warning) throw conflict(result.warning);
}
const git = async (...args: string[]) => (await execFile("git", ["-C", cwd, ...args], { timeout: 30_000, env: { ...process.env, GIT_NO_LAZY_FETCH: "1" } })).stdout.trim();
const origin = normalizeProjectRepositoryUrl(await git("remote", "get-url", "origin"));
if (origin.url.toLowerCase() !== row.repositoryIdentity) throw conflict("Repository checkout belongs to a different origin");
const ownership = await readOwnership();
if (!authorizedPin && (ownership?.repositoryId !== row.id || !/^[a-f0-9]{40,64}$/.test(ownership.pinnedCommit))) throw conflict("Repository publication has no valid preparation receipt");
// The pre-publication commit survives a crash before the database update.
const pinnedCommit: string = authorizedPin ?? ownership.pinnedCommit;
if (acquisitionRestricted) await git("cat-file", "-e", `${pinnedCommit}^{commit}`);
const branchName = await git("symbolic-ref", "--quiet", "--short", "HEAD").catch(() => null);
await db.update(executionWorkspaceRepositories).set({ state: "ready", pinnedCommit, branchName, failureCode: null, updatedAt: new Date() }).where(eq(executionWorkspaceRepositories.id, row.id));
prepared.push({ id: row.id, cwd, repoUrl: row.repoUrl, relativePath: row.relativePath, pinnedCommit, branchName });
@@ -1,7 +1,7 @@
import { and, inArray, isNull } from "drizzle-orm";
import { executionWorkspaces } from "@paperclipai/db";
/** Lifecycle eligibility shared by discovery and selection; callers add scope and privacy. */
/** Lifecycle eligibility shared by discovery, selection and repository requests; callers add scope and privacy. */
export function taskWorkspaceSelectableCondition() {
return and(
inArray(executionWorkspaces.status, ["active", "idle"]),