mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
Fence repository acquisition by durable physical root
Preserve empty-inventory admission and immutable recovery. Reserve managed or anonymous roots before acquisition and fence legacy recovery using its verified host binding. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
0e0557f123
commit
d66a2de539
14 files changed
+2444
-42
No files matched your search
@@ -13,6 +13,7 @@ import {
|
||||
classifyNativeWorkspaceInbound,
|
||||
nativeWorkspaceSyncInternals,
|
||||
readNativeWorkspaceSyncReference,
|
||||
readNativeWorkspaceSyncLocalCwd,
|
||||
resumeNativeWorkspaceSync,
|
||||
prepareNativeWorkspaceSync,
|
||||
cleanupNativeWorkspaceSync,
|
||||
@@ -185,6 +186,9 @@ describe("native workspace sync durable metadata", () => {
|
||||
const recovered = await nativeWorkspaceSyncInternals.readDescriptor({ runId, reference });
|
||||
expect(recovered.baseline.entries.get("private-filename-雪")).toMatchObject({ kind: "file" });
|
||||
await disposeDirectorySnapshot(recovered.baseline);
|
||||
await expect(readNativeWorkspaceSyncLocalCwd({ runId, companyId: "company", workspaceId: "workspace", reference })).resolves.toBe(workspace);
|
||||
await expect(readNativeWorkspaceSyncLocalCwd({ runId, companyId: "other-company", workspaceId: "workspace", reference })).rejects.toThrow(/binding_mismatch/);
|
||||
await expect(readNativeWorkspaceSyncLocalCwd({ runId, companyId: "company", workspaceId: "other-workspace", reference })).rejects.toThrow(/binding_mismatch/);
|
||||
if (tamper === "corrupt") {
|
||||
await appendFile(serialized.entries.filePath, "corrupt");
|
||||
} else if (tamper === "symlink") {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";
|
||||
import { mkdtemp, mkdir, writeFile, readFile, realpath, rm, symlink } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { agents, authUsers, companies, companyMemberships, createDb, executionWorkspaceRepositories, executionWorkspaces,
|
||||
import { agents, authUsers, companies, companyMemberships, createDb, executionWorkspaceRepositoryRoots, executionWorkspaceRepositories, executionWorkspaces,
|
||||
heartbeatRuns, issues, projects, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
|
||||
import { executionWorkspaceRepositoryService } from "../services/execution-workspace-repositories.js";
|
||||
import { buildGitAuthInvocation } from "../services/git-credentials.js";
|
||||
@@ -68,6 +68,19 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
return { companyId, agentId, issueId, runId, userId, workspace, policy, service, actor, request, admission };
|
||||
}
|
||||
|
||||
async function lowTrustPeer(f: Awaited<ReturnType<typeof fixture>>, cwd = f.admission.cwd) {
|
||||
const [workspace] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, name: "Low-trust alias",
|
||||
cwd, mode: "isolated_workspace", strategyType: "task_directory" }).returning();
|
||||
const issueId = randomUUID(), runId = randomUUID();
|
||||
await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Low-trust peer",
|
||||
assigneeAgentId: f.agentId, executionWorkspaceId: workspace.id });
|
||||
const policy = { ...f.policy, authorizationPolicy: { ...f.policy.authorizationPolicy,
|
||||
trustBoundary: { ...f.policy.authorizationPolicy.trustBoundary, rootIssueId: issueId } } };
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "running",
|
||||
responsibleUserId: f.userId, contextSnapshot: { issueId, executionPolicy: policy } });
|
||||
return { workspace, admission: { ...f.admission, cwd, issueId, runId, workspaceId: workspace.id }, actor: { ...f.actor, runId } };
|
||||
}
|
||||
|
||||
it.each(["agent", "issue", "project", "workspace_source_project", "run"] as const)(
|
||||
"rejects catalog acquisition from raw %s low-trust policy", async source => {
|
||||
const f = await fixture();
|
||||
@@ -148,14 +161,19 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
expect(acquisition.managedAuth).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["same_repository", "different_repository", "empty_inventory", "unpinned_publication"] as const)(
|
||||
it.each(["same_repository", "different_repository", "empty_inventory", "unpinned_publication", "pending_intent"] as const)(
|
||||
"rejects managed peer bytes in the same physical root with %s", async scenario => {
|
||||
const f = await fixture();
|
||||
const managed = await f.request({ kind: "catalog", id: "private-repo" });
|
||||
const checkout = path.join(f.admission.cwd, managed.repository.relativePath);
|
||||
await mkdir(path.join(checkout, ".git"), { recursive: true });
|
||||
await writeFile(path.join(checkout, "private.txt"), "Private peer bytes");
|
||||
if (scenario !== "unpinned_publication") await db.update(executionWorkspaceRepositories)
|
||||
if (scenario !== "pending_intent") {
|
||||
await mkdir(path.join(checkout, ".git"), { recursive: true });
|
||||
await writeFile(path.join(checkout, "private.txt"), "Private peer bytes");
|
||||
} else {
|
||||
// A legacy pending intent has neither a root-policy row nor published bytes.
|
||||
await db.delete(executionWorkspaceRepositoryRoots).where(eq(executionWorkspaceRepositoryRoots.companyId, f.companyId));
|
||||
}
|
||||
if (scenario !== "unpinned_publication" && scenario !== "pending_intent") await db.update(executionWorkspaceRepositories)
|
||||
.set({ state: "ready", pinnedCommit: "b".repeat(40) }).where(eq(executionWorkspaceRepositories.id, managed.operationId));
|
||||
const [peer] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, name: "Same physical folder",
|
||||
cwd: f.admission.cwd, mode: "isolated_workspace", strategyType: "task_directory" }).returning();
|
||||
@@ -167,15 +185,123 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "running",
|
||||
responsibleUserId: f.userId, contextSnapshot: { issueId, executionPolicy: policy } });
|
||||
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
|
||||
if (scenario !== "empty_inventory") await 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" } } });
|
||||
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/);
|
||||
expect(acquisition.materialize).not.toHaveBeenCalled();
|
||||
expect(acquisition.managedAuth).not.toHaveBeenCalled();
|
||||
expect(await readFile(path.join(checkout, "private.txt"), "utf8")).toBe("Private peer bytes");
|
||||
if (scenario !== "pending_intent") expect(await readFile(path.join(checkout, "private.txt"), "utf8")).toBe("Private peer bytes");
|
||||
},
|
||||
);
|
||||
|
||||
it("reserves a legacy low-trust recovery folder after its task binding moves", async () => {
|
||||
const f = await fixture();
|
||||
const peer = await lowTrustPeer(f);
|
||||
await db.update(issues).set({ executionWorkspaceId: null }).where(eq(issues.id, peer.admission.issueId));
|
||||
await db.update(executionWorkspaces).set({ cwd: path.join(root, "moved-recovery"), metadata: {}, status: "archived" })
|
||||
.where(eq(executionWorkspaces.id, peer.workspace.id));
|
||||
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/);
|
||||
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();
|
||||
expect(acquisition.managedAuth).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reserves a legacy managed recovery folder before a low-trust peer resumes", async () => {
|
||||
const f = await fixture();
|
||||
await f.request({ kind: "catalog", id: "private-repo" });
|
||||
await db.delete(executionWorkspaceRepositoryRoots).where(eq(executionWorkspaceRepositoryRoots.companyId, f.companyId));
|
||||
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/);
|
||||
expect(acquisition.materialize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("serializes a managed request against anonymous admission through physical aliases", async () => {
|
||||
const f = await fixture();
|
||||
const alias = path.join(root, `${f.issueId}-alias`);
|
||||
await symlink(f.admission.cwd, alias);
|
||||
const peer = await lowTrustPeer(f, alias);
|
||||
const outcomes = await Promise.allSettled([
|
||||
f.service.prepareForAdmission(peer.admission),
|
||||
f.request({ kind: "catalog", id: "private-repo" }),
|
||||
]);
|
||||
expect(outcomes.filter(result => result.status === "fulfilled")).toHaveLength(1);
|
||||
expect(outcomes.filter(result => result.status === "rejected")).toHaveLength(1);
|
||||
const [reservation] = await db.select().from(executionWorkspaceRepositoryRoots).where(eq(executionWorkspaceRepositoryRoots.companyId, f.companyId));
|
||||
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(restarted.prepareForAdmission(peer.admission)).resolves.toEqual([]);
|
||||
} else await expect(restarted.prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only/);
|
||||
expect(acquisition.materialize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps anonymous root ownership across workspace moves and blocks future catalog promotion", async () => {
|
||||
const f = await fixture();
|
||||
// A standard task's initially anonymous intent may later appear in its catalog.
|
||||
const pending = await f.request({ kind: "url", url: "https://github.com/public/later-catalog" });
|
||||
const peer = await lowTrustPeer(f);
|
||||
await f.service.prepareForAdmission(peer.admission);
|
||||
await db.update(executionWorkspaces).set({ cwd: path.join(root, "moved-anonymous-workspace"), metadata: {}, status: "archived" })
|
||||
.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/);
|
||||
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/);
|
||||
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();
|
||||
});
|
||||
|
||||
it("rejects anonymous admission while a managed clone is waiting to publish", async () => {
|
||||
const f = await fixture();
|
||||
const receipt = await f.request({ kind: "catalog", id: "private-repo" });
|
||||
const peer = await lowTrustPeer(f);
|
||||
const source = path.join(root, `${f.issueId}-private-source`);
|
||||
await mkdir(source);
|
||||
const exec = promisify(execFileCallback);
|
||||
await exec("git", ["init", "--initial-branch=main", source]);
|
||||
await writeFile(path.join(source, "private.txt"), "Private fixture bytes\n");
|
||||
await exec("git", ["-C", source, "add", "."]);
|
||||
await exec("git", ["-C", source, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "private source"]);
|
||||
let release!: () => void, started!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
const staged = new Promise<void>(resolve => { started = resolve; });
|
||||
const actual = await vi.importActual<typeof import("../services/managed-repository-checkout.js")>("../services/managed-repository-checkout.js");
|
||||
acquisition.materialize.mockImplementationOnce(async (cwd, input) => {
|
||||
const result = await actual.materializeManagedProjectWorkspace(cwd, { ...input, localSource: source,
|
||||
beforePublish: async cloneCwd => {
|
||||
await input.beforePublish(cloneCwd);
|
||||
started();
|
||||
await gate;
|
||||
} });
|
||||
await exec("git", ["-C", cwd, "remote", "set-url", "origin", input.repoUrl]);
|
||||
return result;
|
||||
});
|
||||
const preparation = f.service.prepareForAdmission(f.admission);
|
||||
try {
|
||||
await Promise.race([staged, preparation.then(() => { throw new Error("Managed preparation finished before publication barrier"); })]);
|
||||
const [pending] = await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.id, receipt.operationId));
|
||||
expect(pending).toMatchObject({ state: "preparing", pinnedCommit: null });
|
||||
// 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/);
|
||||
} 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/);
|
||||
});
|
||||
|
||||
it("retains previous run trust without confusing a board request's reassigned agent", async () => {
|
||||
const f = await fixture();
|
||||
const [replacement] = await db.insert(agents).values({ companyId: f.companyId, name: "Replacement", adapterType: "process" }).returning();
|
||||
@@ -189,6 +315,29 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
await expect(request()).rejects.toThrow(/anonymous public URLs only/);
|
||||
});
|
||||
|
||||
it("preserves standard empty-inventory admission without repository mutation authority", async () => {
|
||||
const f = await fixture();
|
||||
await db.delete(companyMemberships).where(eq(companyMemberships.companyId, f.companyId));
|
||||
await expect(f.service.prepareForAdmission(f.admission)).resolves.toEqual([]);
|
||||
expect(acquisition.catalog).not.toHaveBeenCalled();
|
||||
expect(acquisition.materialize).not.toHaveBeenCalled();
|
||||
// Adding an acquisition still requires the full authorization intersection.
|
||||
await db.insert(executionWorkspaceRepositories).values({ companyId: f.companyId, executionWorkspaceId: f.workspace.id,
|
||||
requestedByIssueId: f.issueId, repositoryIdentity: "https://github.com/public/example", repoUrl: "https://github.com/public/example",
|
||||
relativePath: ".paperclip-repositories/unused", requestedRef: "HEAD", requestKey: "requires-authority", requestKeys: ["requires-authority"] });
|
||||
await expect(f.service.prepareForAdmission(f.admission)).rejects.toThrow();
|
||||
expect(acquisition.materialize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps low-trust empty-inventory admission free of acquisition-only filesystem and membership requirements", async () => {
|
||||
const f = await fixture();
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, executionPolicy: f.policy } }).where(eq(heartbeatRuns.id, f.runId));
|
||||
await db.delete(companyMemberships).where(eq(companyMemberships.companyId, f.companyId));
|
||||
await expect(f.service.prepareForAdmission({ ...f.admission, cwd: path.join(root, "not-materialized") })).resolves.toEqual([]);
|
||||
expect(acquisition.catalog).not.toHaveBeenCalled();
|
||||
expect(acquisition.materialize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects admission without the persisted task run before materialization", async () => {
|
||||
const f = await fixture();
|
||||
await f.request({ kind: "catalog", id: "private-repo" });
|
||||
|
||||
@@ -5,7 +5,7 @@ import fs from "node:fs/promises";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { and, eq, isNotNull, or, sql } from "drizzle-orm";
|
||||
import { activityLog, agents, heartbeatRuns, projects, executionWorkspaceRepositories, executionWorkspaces, issues, type Db } from "@paperclipai/db";
|
||||
import { activityLog, agents, heartbeatRuns, projects, executionWorkspaceRepositoryRoots, executionWorkspaceRepositories, executionWorkspaces, issues, type Db } from "@paperclipai/db";
|
||||
import { prepareWorkspaceRepositorySchema, type PrepareWorkspaceRepository, type ProjectRepository } from "@paperclipai/shared";
|
||||
import { withDirectoryPublicationLock } from "@paperclipai/adapter-utils/workspace-restore-merge";
|
||||
import { conflict, forbidden, notFound } from "../errors.js";
|
||||
@@ -22,6 +22,18 @@ const execFile = promisify(execFileCallback);
|
||||
type RepositoryRow = typeof executionWorkspaceRepositories.$inferSelect;
|
||||
type DbTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
|
||||
/** Match physical aliases, including task directories not materialized yet. */
|
||||
async function canonicalRepositoryRoot(cwd: string): Promise<string> {
|
||||
const absolute = path.resolve(cwd);
|
||||
try { return await fs.realpath(absolute); }
|
||||
catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||
const parent = path.dirname(absolute);
|
||||
if (parent === absolute) throw error;
|
||||
return path.join(await canonicalRepositoryRoot(parent), path.basename(absolute));
|
||||
}
|
||||
}
|
||||
|
||||
const lowTrustRepositoryMessage = "Low-trust tasks may prepare anonymous public URLs only. Use an authorized configured source for private repositories.";
|
||||
|
||||
function resolveAcquisitionSource(request: PrepareWorkspaceRepository["repository"], available: ProjectRepository[], anonymousOnly: boolean) {
|
||||
@@ -78,6 +90,37 @@ export function executionWorkspaceRepositoryService(db: Db) {
|
||||
if (trust.kind === "denied") throw forbidden(trust.detail);
|
||||
return trust.kind === "low_trust_review";
|
||||
}
|
||||
async function lockRootPolicies(tx: DbTransaction, companyId: string) {
|
||||
// Acquire before task/workspace row locks. Hold only for policy and receipt
|
||||
// transactions, never Git, provider execution, or snapshot capture.
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`task-repository-roots:${companyId}`}, 0))`);
|
||||
}
|
||||
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");
|
||||
const [existing] = await tx.select().from(executionWorkspaceRepositoryRoots).where(and(
|
||||
eq(executionWorkspaceRepositoryRoots.companyId, companyId), eq(executionWorkspaceRepositoryRoots.rootKey, rootKey)));
|
||||
if (existing && (existing.canonicalCwd !== canonicalCwd || existing.mode !== mode)) throw forbidden(lowTrustRepositoryMessage);
|
||||
if (mode === "anonymous_only") {
|
||||
// Legacy receipts predate root reservations. Even pending/staging work
|
||||
// can publish after admission, so no managed intent in this root is safe.
|
||||
const managed = await tx.select({ cwd: executionWorkspaces.cwd }).from(executionWorkspaceRepositories)
|
||||
.innerJoin(executionWorkspaces, eq(executionWorkspaces.id, executionWorkspaceRepositories.executionWorkspaceId))
|
||||
.where(and(eq(executionWorkspaceRepositories.companyId, companyId), eq(executionWorkspaces.companyId, companyId),
|
||||
isNotNull(executionWorkspaceRepositories.catalogRepositoryId)));
|
||||
for (const peer of managed) {
|
||||
if (peer.cwd && await canonicalRepositoryRoot(peer.cwd) === canonicalCwd) throw forbidden(lowTrustRepositoryMessage);
|
||||
}
|
||||
}
|
||||
if (!existing) await tx.insert(executionWorkspaceRepositoryRoots).values({ companyId, canonicalCwd, rootKey, mode });
|
||||
return canonicalCwd;
|
||||
}
|
||||
async function reserveAdmissionRoot(companyId: string, cwd: string, mode: "anonymous_only" | "managed") {
|
||||
return db.transaction(async tx => {
|
||||
await lockRootPolicies(tx, companyId);
|
||||
return reserveRootPolicy(tx, companyId, cwd, mode);
|
||||
});
|
||||
}
|
||||
async function request(input: { companyId: string; issueId: string; actor: AuthorizationActor; request: PrepareWorkspaceRepository }) {
|
||||
const parsed = prepareWorkspaceRepositorySchema.parse(input.request);
|
||||
const [requestedIssue] = await db.select().from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId), await issueReadSqlCondition(db, input.actor)));
|
||||
@@ -100,6 +143,7 @@ export function executionWorkspaceRepositoryService(db: Db) {
|
||||
const available = await catalog(input.companyId, userId, localTrusted);
|
||||
const requestedRef = parsed.ref ?? "HEAD";
|
||||
const receipt = await db.transaction(async tx => {
|
||||
await lockRootPolicies(tx, input.companyId);
|
||||
const [issue] = await tx.select().from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId), await issueReadSqlCondition(tx, input.actor))).for("no key update");
|
||||
if (!issue) throw notFound("Task not found");
|
||||
const currentDecision = await authorizationService(tx).decide({ actor: input.actor, action: "issue:mutate", resource: issueResource(issue) });
|
||||
@@ -114,6 +158,10 @@ export function executionWorkspaceRepositoryService(db: Db) {
|
||||
const anonymousOnly = await requiresAnonymousAcquisition(tx, { issue, workspace,
|
||||
agentId: input.actor.agentId, runId: input.actor.runId });
|
||||
const source = resolveAcquisitionSource(parsed.repository, available, anonymousOnly);
|
||||
if (anonymousOnly || source.catalogRepositoryId) {
|
||||
if (!workspace.cwd) throw conflict("The task workspace has no directory for repository preparation");
|
||||
await reserveRootPolicy(tx, input.companyId, workspace.cwd, anonymousOnly ? "anonymous_only" : "managed");
|
||||
}
|
||||
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);
|
||||
@@ -137,6 +185,17 @@ export function executionWorkspaceRepositoryService(db: Db) {
|
||||
async function list(companyId: string, workspaceId: string) {
|
||||
return db.select().from(executionWorkspaceRepositories).where(and(eq(executionWorkspaceRepositories.companyId, companyId), eq(executionWorkspaceRepositories.executionWorkspaceId, workspaceId)));
|
||||
}
|
||||
/** Recovery keeps its admitted identity and folder; only fence future publication. */
|
||||
async function reserveForRecovery(input: { companyId: string; issueId: string; workspaceId: string; cwd: 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) throw forbidden("Task repository recovery identity is unavailable");
|
||||
const anonymousOnly = await requiresAnonymousAcquisition(db, { issue, workspace, agentId: input.agentId, runId: input.runId });
|
||||
if (anonymousOnly) await reserveAdmissionRoot(input.companyId, input.cwd, "anonymous_only");
|
||||
else if ((await list(input.companyId, input.workspaceId)).some(row => row.catalogRepositoryId)) {
|
||||
await reserveAdmissionRoot(input.companyId, input.cwd, "managed");
|
||||
}
|
||||
}
|
||||
/** Logical rows may deliberately name one physical folder. Reuse bytes only
|
||||
* after validating every published owner's retained privacy and source intent. */
|
||||
async function sharedPublicationPin(input: { issueId: string; row: RepositoryRow; root: string; actor: AuthorizationActor; anonymousOnly: boolean; ownership: { repositoryId?: string; pinnedCommit?: string } | null }) {
|
||||
@@ -160,21 +219,6 @@ export function executionWorkspaceRepositoryService(db: Db) {
|
||||
}
|
||||
return pin;
|
||||
}
|
||||
async function assertAnonymousPhysicalRoot(companyId: string, root: string) {
|
||||
const publications = await db.select({ repository: executionWorkspaceRepositories, cwd: executionWorkspaces.cwd })
|
||||
.from(executionWorkspaceRepositories).innerJoin(executionWorkspaces, eq(executionWorkspaces.id, executionWorkspaceRepositories.executionWorkspaceId))
|
||||
.where(and(eq(executionWorkspaceRepositories.companyId, companyId), eq(executionWorkspaces.companyId, companyId),
|
||||
isNotNull(executionWorkspaceRepositories.catalogRepositoryId)));
|
||||
for (const { repository, cwd } of publications) {
|
||||
if (!cwd || await fs.realpath(cwd).catch(() => null) !== root) continue;
|
||||
if (repository.relativePath !== taskRepositoryRelativePath(repository.repositoryIdentity)) throw conflict("Repository preparation receipt does not match its source");
|
||||
// Include an interrupted publication whose database pin was not saved yet.
|
||||
// Even another repository's files would be included in the root snapshot.
|
||||
if (repository.pinnedCommit || await fs.lstat(path.join(root, repository.relativePath)).catch(() => null)) {
|
||||
throw forbidden(lowTrustRepositoryMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
async function prepareForAdmission(input: { companyId: string; issueId: string; workspaceId: string; cwd: string; agentId: string; runId: string; responsibleUserId: string | null }) {
|
||||
const rows = await list(input.companyId, input.workspaceId);
|
||||
const actor: AuthorizationActor = { type: "agent", source: "agent_jwt", companyId: input.companyId,
|
||||
@@ -182,14 +226,17 @@ export function executionWorkspaceRepositoryService(db: Db) {
|
||||
// local-board is a server identity, not a membership record. Preserve the
|
||||
// agent's own authority rather than promoting it to a board actor.
|
||||
onBehalfOfUserId: input.responsibleUserId === "local-board" ? null : input.responsibleUserId };
|
||||
await assertTaskWorkspaceAccess(db, actor, input.companyId, input.workspaceId, { write: true, issueId: input.issueId });
|
||||
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");
|
||||
const anonymousOnly = await requiresAnonymousAcquisition(db, { issue, workspace, agentId: input.agentId, runId: input.runId });
|
||||
// Ordinary admission without acquisitions is owned by heartbeat, not this mutation service.
|
||||
if (!rows.length) {
|
||||
if (anonymousOnly) await reserveAdmissionRoot(input.companyId, input.cwd, "anonymous_only");
|
||||
return [];
|
||||
}
|
||||
await assertTaskWorkspaceAccess(db, actor, input.companyId, input.workspaceId, { write: true, issueId: input.issueId });
|
||||
const root = await fs.realpath(input.cwd);
|
||||
if (anonymousOnly) await assertAnonymousPhysicalRoot(input.companyId, root);
|
||||
if (!rows.length) return [];
|
||||
const available = anonymousOnly ? [] : 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.
|
||||
@@ -197,6 +244,10 @@ export function executionWorkspaceRepositoryService(db: Db) {
|
||||
assertAcquisitionReceipt(row, anonymousOnly);
|
||||
return resolveAcquisitionSource(row.catalogRepositoryId ? { kind: "catalog", id: row.catalogRepositoryId } : { kind: "url", url: row.repoUrl }, available, anonymousOnly);
|
||||
});
|
||||
if (anonymousOnly || sources.some(source => source.catalogRepositoryId)) {
|
||||
const reservedRoot = await reserveAdmissionRoot(input.companyId, root, anonymousOnly ? "anonymous_only" : "managed");
|
||||
if (reservedRoot !== root) throw conflict("Repository workspace root changed during admission");
|
||||
}
|
||||
const repositoryRoot = path.join(root, ".paperclip-repositories");
|
||||
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");
|
||||
@@ -293,5 +344,5 @@ export function executionWorkspaceRepositoryService(db: Db) {
|
||||
}
|
||||
return prepared;
|
||||
}
|
||||
return { request, list, prepareForAdmission };
|
||||
return { request, list, prepareForAdmission, reserveForRecovery };
|
||||
}
|
||||
@@ -2153,6 +2153,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
|
||||
requestTaskRepository: executionWorkspaceRepositoryService(db).request,
|
||||
listTaskRepositories: executionWorkspaceRepositoryService(db).list,
|
||||
prepareTaskRepositoriesForAdmission: executionWorkspaceRepositoryService(db).prepareForAdmission,
|
||||
reserveTaskRepositoryRootForRecovery: executionWorkspaceRepositoryService(db).reserveForRecovery,
|
||||
resolveSourceWorkspaceStrategy, validateSelection, inspectTaskWorkspace, selectTaskWorkspace, applyPendingTaskWorkspaceSelection, bindTaskWorkspace, prepareTaskWorkspaceUpdate, assertTaskWorkspaceUpdateAccess,
|
||||
listOverview: async (
|
||||
companyId: string,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { mkdtemp, mkdir, readFile, rm, writeFile, access } from "node:fs/promise
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { captureDirectorySnapshot, directorySnapshotSha256, serializeDirectorySnapshot } from "@paperclipai/adapter-utils/workspace-restore-merge";
|
||||
import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, environmentLeases, heartbeatRuns, issues, projects, projectWorkspaces, type Db } from "@paperclipai/db";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
@@ -12,6 +13,7 @@ import { environmentService } from "../environments.js";
|
||||
import { executionWorkspaceService } from "../execution-workspaces.js";
|
||||
import { instanceSettingsService } from "../instance-settings.js";
|
||||
import { workspaceOperationService } from "../workspace-operations.js";
|
||||
import { nativeWorkspaceSyncInternals } from "../native-runtime/native-workspace-sync.js";
|
||||
import { createHeartbeatWorkspaceResolver, resolveExecutionWorkspaceReuseRequestForIssue } from "./workspaces.js";
|
||||
import { prepareHeartbeatWorkspace, type HeartbeatWorkspacePreparationInput } from "./workspace-preparation.js";
|
||||
|
||||
@@ -156,12 +158,60 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary",
|
||||
input.task.issueRef = { ...input.task.issueRef!, executionWorkspaceId: null, projectWorkspaceId: null };
|
||||
input.reuse.nativeRecoveryExecutionWorkspaceId = first.persistedExecutionWorkspace!.id;
|
||||
const anchor = vi.spyOn(input.services, "resolveReusedGitWorkspaceAnchor");
|
||||
const prepareRepositories = vi.spyOn(input.services.executionWorkspacesSvc, "prepareTaskRepositoriesForAdmission");
|
||||
const reserveRoot = vi.spyOn(input.services.executionWorkspacesSvc, "reserveTaskRepositoryRootForRecovery");
|
||||
const acquire = input.services.envOrchestrator.acquireForRun;
|
||||
vi.spyOn(input.services.envOrchestrator, "acquireForRun").mockImplementation(async args => {
|
||||
expect(reserveRoot).toHaveBeenCalledWith({ companyId: issue.companyId, issueId: issue.id,
|
||||
workspaceId: first.persistedExecutionWorkspace!.id, cwd: first.executionWorkspace.cwd,
|
||||
agentId: input.agent.id, runId: input.run.id });
|
||||
return acquire(args);
|
||||
});
|
||||
const next = await prepareHeartbeatWorkspace(db, input);
|
||||
expect(prepareRepositories).not.toHaveBeenCalled();
|
||||
expect(next.persistedExecutionWorkspace!.id).toBe(first.persistedExecutionWorkspace!.id);
|
||||
expect(anchor).toHaveBeenCalledWith(expect.objectContaining({ immutableNativeBinding: true, explicitProjectWorkspaceId: first.persistedExecutionWorkspace!.projectWorkspaceId }));
|
||||
expect(await readIssue(issue.id)).toMatchObject({ executionWorkspaceId: null, projectWorkspaceId: null });
|
||||
});
|
||||
|
||||
it.each([false, true])("requires the immutable host descriptor for remote recovery (present=%s)", async present => {
|
||||
const { input, issue } = await fixture(true);
|
||||
const first = await prepareHeartbeatWorkspace(db, input);
|
||||
await reuse(input, first.persistedExecutionWorkspace!);
|
||||
await db.update(issues).set({ executionWorkspaceId: null, projectWorkspaceId: null }).where(eq(issues.id, issue.id));
|
||||
input.task.issueRef = { ...input.task.issueRef!, executionWorkspaceId: null, projectWorkspaceId: null };
|
||||
input.reuse.nativeRecoveryExecutionWorkspaceId = first.persistedExecutionWorkspace!.id;
|
||||
input.environment.selectedEnvironmentForConfig = { ...input.environment.localEnvironment, driver: "ssh" };
|
||||
const admittedRoot = join(home, `admitted-${input.run.id}`);
|
||||
await mkdir(admittedRoot);
|
||||
if (present) {
|
||||
const baseline = await captureDirectorySnapshot(admittedRoot);
|
||||
const reference = await nativeWorkspaceSyncInternals.writeDescriptor({
|
||||
schema: "paperclip.native-workspace-sync/v1", state: "prepared",
|
||||
binding: { companyId: issue.companyId, runId: input.run.id, workspaceId: first.persistedExecutionWorkspace!.id,
|
||||
leaseId: "admitted-lease", providerLeaseId: "admitted-provider", localCwd: admittedRoot, remoteCwd: "/workspace" },
|
||||
baseline: serializeDirectorySnapshot(baseline), baselineSha256: directorySnapshotSha256(baseline),
|
||||
gitSnapshot: null, seed: null, createdAt: new Date().toISOString(), finalizedAt: null, finalHostSha256: null, resourceDisposition: null,
|
||||
});
|
||||
input.run.runnerProfileJson = { nativeWorkspaceSync: reference };
|
||||
}
|
||||
const reserve = vi.spyOn(input.services.executionWorkspacesSvc, "reserveTaskRepositoryRootForRecovery");
|
||||
const prepare = vi.spyOn(input.services.executionWorkspacesSvc, "prepareTaskRepositoriesForAdmission");
|
||||
const acquire = vi.spyOn(input.services.envOrchestrator, "acquireForRun");
|
||||
if (present) {
|
||||
await prepareHeartbeatWorkspace(db, input);
|
||||
expect(reserve).toHaveBeenCalledWith({ companyId: issue.companyId, issueId: issue.id,
|
||||
workspaceId: first.persistedExecutionWorkspace!.id, cwd: admittedRoot, agentId: input.agent.id, runId: input.run.id });
|
||||
expect(admittedRoot).not.toBe(first.executionWorkspace.cwd);
|
||||
} else {
|
||||
await expect(prepareHeartbeatWorkspace(db, input)).rejects.toThrow("native_workspace_sync_descriptor_binding_missing");
|
||||
expect(reserve).not.toHaveBeenCalled();
|
||||
expect(acquire).not.toHaveBeenCalled();
|
||||
}
|
||||
expect(prepare).not.toHaveBeenCalled();
|
||||
expect((await readIssue(issue.id)).executionWorkspaceId).toBeNull();
|
||||
});
|
||||
|
||||
it("removes a newly created worktree when persistence fails and preserves the original error", async () => {
|
||||
const { input, source } = await fixture(true);
|
||||
const error = new Error("workspace persistence unavailable");
|
||||
|
||||
@@ -24,7 +24,7 @@ import { createHostDuplexObservabilityRecorder } from "../duplex-observability-r
|
||||
import { incrementToolRuntimeMetricCounter } from "../tool-runtime-metrics.js";
|
||||
import { logger } from "../../middleware/logger.js";
|
||||
import { createGitRemoteAuthProvider } from "../git-credentials.js";
|
||||
import { readNativeWorkspaceSyncReference } from "../native-runtime/index.js";
|
||||
import { readNativeWorkspaceSyncReference, readNativeWorkspaceSyncLocalCwd } from "../native-runtime/index.js";
|
||||
import { parseObject } from "../../adapters/utils.js";
|
||||
import { materializeNativeChatTaskRoot } from "../native-runtime/native-chat-workspace.js";
|
||||
import { materializeIsolatedTaskDirectory } from "../isolated-task-directory.js";
|
||||
@@ -126,7 +126,7 @@ export interface HeartbeatWorkspacePreparationInput {
|
||||
};
|
||||
services: {
|
||||
envOrchestrator: Pick<ReturnType<typeof environmentRunOrchestrator>, "resolveEnvironment" | "acquireForRun" | "realizeForRun">;
|
||||
executionWorkspacesSvc: Pick<ReturnType<typeof executionWorkspaceService>, "create" | "update" | "bindTaskWorkspace" | "prepareTaskRepositoriesForAdmission">;
|
||||
executionWorkspacesSvc: Pick<ReturnType<typeof executionWorkspaceService>, "create" | "update" | "bindTaskWorkspace" | "prepareTaskRepositoriesForAdmission" | "reserveTaskRepositoryRootForRecovery">;
|
||||
workspaceOperationsSvc: Pick<ReturnType<typeof workspaceOperationService>, "createRecorder">;
|
||||
resolveWorkspaceForRun: WorkspaceResolver["resolveWorkspaceForRun"];
|
||||
resolveReusedGitWorkspaceAnchor: WorkspaceResolver["resolveReusedGitWorkspaceAnchor"];
|
||||
@@ -885,12 +885,29 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspac
|
||||
repoRef: readNonEmptyString(source.repoRef),
|
||||
}));
|
||||
}
|
||||
if (persistedExecutionWorkspace && issueId && !persistedNativeExecutionInput) {
|
||||
if (persistedExecutionWorkspace && issueId && !persistedNativeExecutionInput && !nativeRecoveryExecutionWorkspaceId) {
|
||||
const taskRepositories = await executionWorkspacesSvc.prepareTaskRepositoriesForAdmission({ companyId: agent.companyId,
|
||||
issueId, workspaceId: persistedExecutionWorkspace.id, cwd: executionWorkspace.cwd,
|
||||
agentId: agent.id, runId: run.id, responsibleUserId });
|
||||
projectRepositoryPaths.push(...taskRepositories.map(repository => repository.relativePath));
|
||||
}
|
||||
if (!isDotRun && issueId && (persistedNativeExecutionInput || nativeRecoveryExecutionWorkspaceId)) {
|
||||
const workspaceId = persistedNativeExecutionInput?.binding.executionWorkspaceId ?? nativeRecoveryExecutionWorkspaceId!;
|
||||
const reference = readNativeWorkspaceSyncReference(parseObject(run.runnerProfileJson).nativeWorkspaceSync);
|
||||
if (!reference && selectedEnvironmentForConfig?.driver !== "local") {
|
||||
throw new Error("native_workspace_sync_descriptor_binding_missing");
|
||||
}
|
||||
// Recovery keeps admitted files and trust even when the task now selects
|
||||
// another workspace. Reserve only; never acquire newly requested repositories.
|
||||
const cwd = reference
|
||||
? await readNativeWorkspaceSyncLocalCwd({ companyId: agent.companyId, runId: run.id, workspaceId, reference })
|
||||
: persistedNativeExecutionInput && persistedNativeExecutionInput.schema !== "paperclip.native-execution-input.v6"
|
||||
&& selectedEnvironmentForConfig?.driver === "local"
|
||||
? persistedNativeExecutionInput.workspace.cwd
|
||||
: executionWorkspace.cwd;
|
||||
await executionWorkspacesSvc.reserveTaskRepositoryRootForRecovery({ companyId: agent.companyId,
|
||||
issueId, workspaceId, cwd, agentId: agent.id, runId: run.id });
|
||||
}
|
||||
if (persistedExecutionWorkspace) {
|
||||
context.executionWorkspaceId = persistedExecutionWorkspace.id;
|
||||
await db
|
||||
|
||||
@@ -1091,6 +1091,29 @@ export async function prepareNativeWorkspaceSync(input: {
|
||||
}
|
||||
}
|
||||
|
||||
/** Read the admitted host root without reacquiring or transferring workspace files. */
|
||||
export async function readNativeWorkspaceSyncLocalCwd(input: {
|
||||
companyId: string;
|
||||
runId: string;
|
||||
workspaceId: string;
|
||||
reference: NativeWorkspaceSyncReference;
|
||||
}): Promise<string> {
|
||||
const existing = await readDescriptor(input);
|
||||
try {
|
||||
if (existing.descriptor.binding.companyId !== input.companyId ||
|
||||
existing.descriptor.binding.workspaceId !== input.workspaceId) {
|
||||
throw new Error("native_workspace_sync_descriptor_binding_mismatch");
|
||||
}
|
||||
return existing.descriptor.binding.localCwd;
|
||||
} finally {
|
||||
await disposeDirectorySnapshot(existing.baseline);
|
||||
await disposeGitWorkspaceSnapshot(existing.descriptor.gitSnapshot);
|
||||
for (const repository of existing.descriptor.repositories ?? []) {
|
||||
await disposeGitWorkspaceSnapshot(repository.snapshot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function resumeNativeWorkspaceSync(input: {
|
||||
db: Db;
|
||||
runId: string;
|
||||
|
||||
Reference in new issue
Block a user