import { execFile, execFileSync } from "node:child_process"; import { randomUUID } from "node:crypto"; import { mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { agents, companies, companyMemberships, connectionGrantMembers, connectionGrants, createDb, heartbeatRuns, issues, principalPermissionGrants, projects, projectWorkspaces, toolApplications, toolConnectionInstalls, toolConnections, } from "@paperclipai/db"; import { LOW_TRUST_REVIEW_PRESET } from "@paperclipai/shared"; import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, } from "./helpers/embedded-postgres.js"; import { authorizationService } from "../services/authorization.js"; import { writeConnectionCredential } from "../services/connection-credentials.js"; import { createGitRemoteAuthProvider } from "../services/git-credentials.js"; import { resolveGitHubOperationCredentials, resolveGitHubWorkspacePrepareCredentials, } from "../services/github-operation-credentials.js"; import { prepareRemoteWorkspaceDirectory } from "../services/remote-workspace-transport.js"; import { initializeRunIdentity } from "../services/run-identity.js"; import { secretService } from "../services/secrets.js"; const execFileAsync = promisify(execFile); const external = resolveExternalTestDatabaseUrl( "PAPERCLIP_GITHUB_WORKSPACE_PREPARE_TEST_DATABASE_URL", ); const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); (support.supported ? describe : describe.skip)( "low-trust workspace_prepare GitHub credential resolution", () => { let database: | Awaited> | undefined; let db: ReturnType; beforeAll(async () => { vi.stubEnv("PAPERCLIP_AGENT_JWT_SECRET", "test-workspace-prepare-signing-secret"); if (!external) { database = await startEmbeddedPostgresTestDatabase( "paperclip-github-ws-prepare-", ); } db = createDb(external ?? database!.connectionString); }, 30_000); afterAll(async () => { await db?.$client.end({ timeout: 1 }); await database?.cleanup(); vi.unstubAllEnvs(); }, 60_000); async function seedLowTrustFixture(opts?: { repoUrl?: string; extraProjects?: Array<{ repoUrl: string; inBoundary: boolean }>; allowedToolClasses?: string[]; quarantined?: boolean; responsibleUserId?: string; cause?: "instruction" | "company_default"; }) { const companyId = randomUUID(); const agentId = randomUUID(); const runId = randomUUID(); const issueId = randomUUID(); const responsibleUserId = opts?.responsibleUserId ?? "user-owner"; await db.insert(companies).values({ id: companyId, name: companyId, issuePrefix: companyId.slice(0, 8), }); await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: responsibleUserId, status: "active", membershipRole: "member", }); const [project] = await db .insert(projects) .values({ companyId, name: "Scoped Private Project", status: "in_progress", }) .returning(); const repoUrl = opts?.repoUrl ?? "https://github.com/acme/private-repo"; await db.insert(projectWorkspaces).values({ companyId, projectId: project!.id, name: "acme/private-repo", sourceType: "git_repo", repoUrl, isPrimary: true, }); const boundaryProjectIds = [project!.id]; const extraProjectIds: string[] = []; for (const extra of opts?.extraProjects ?? []) { const [extraProject] = await db .insert(projects) .values({ companyId, name: `Extra Project ${extraProjectIds.length + 1}`, status: "in_progress", }) .returning(); await db.insert(projectWorkspaces).values({ companyId, projectId: extraProject!.id, name: `extra-repo-${extraProjectIds.length + 1}`, sourceType: "git_repo", repoUrl: extra.repoUrl, isPrimary: true, }); extraProjectIds.push(extraProject!.id); if (extra.inBoundary) boundaryProjectIds.push(extraProject!.id); } const lowTrustBoundary = { mode: LOW_TRUST_REVIEW_PRESET, companyId, projectIds: boundaryProjectIds, allowedToolClasses: opts?.allowedToolClasses ?? ["git.read"], }; await db.insert(agents).values({ id: agentId, companyId, name: "Low-Trust Reviewer", role: "engineer", adapterType: "codex_local", permissions: { trustPreset: LOW_TRUST_REVIEW_PRESET, authorizationPolicy: { trustPreset: LOW_TRUST_REVIEW_PRESET, trustBoundary: lowTrustBoundary, }, }, }); await db.insert(issues).values({ id: issueId, companyId, projectId: project!.id, title: "Review private repo", ...(opts?.quarantined ? { sourceTrust: { preset: LOW_TRUST_REVIEW_PRESET, disposition: "quarantined" as const, }, } : {}), }); await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", contextSnapshot: { issueId }, }); await initializeRunIdentity(db, { companyId, runId, responsibleUserId: opts?.cause === "company_default" ? null : responsibleUserId, cause: opts?.cause ?? "instruction", }); return { companyId, agentId, runId, issueId, projectId: project!.id, extraProjectIds, repoUrl, responsibleUserId, }; } async function addManagedOAuthGrant( fixture: Awaited>, tokenValue: string, ) { const applicationId = randomUUID(); const connectionId = randomUUID(); const grantId = randomUUID(); await db.insert(toolApplications).values({ id: applicationId, companyId: fixture.companyId, name: `github-oauth-${applicationId}`, type: "mcp_http", }); const stored = await writeConnectionCredential(db, { companyId: fixture.companyId, connectionName: `github-oauth-${connectionId}`, configPath: "oauth.access_token", label: "GitHub OAuth token", value: tokenValue, ownerUserId: fixture.responsibleUserId, }); await db.insert(toolConnections).values({ id: connectionId, companyId: fixture.companyId, applicationId, name: `github-oauth-${connectionId}`, uid: `github-oauth-${connectionId}`, transport: "mcp_remote", authKind: "oauth", status: "active", enabled: true, credentialPolicy: "per_user", config: { sourceTemplateKey: "github" }, }); await db.insert(toolConnectionInstalls).values({ companyId: fixture.companyId, connectionId, targetType: "agent", targetId: fixture.agentId, }); await db.insert(connectionGrants).values({ id: grantId, companyId: fixture.companyId, connectionId, kind: "user", subjectUserId: fixture.responsibleUserId, status: "active", credentialSecretRefs: [ { configPath: "oauth.access_token", secretId: stored.secret.id, versionSelector: "latest", }, ], providerTenant: { github: { userId: `gh-${fixture.responsibleUserId}`, login: "owner-login", installationCount: 1, repositoryCount: 2, repositorySelection: "selected" as const, installationIds: ["1"], installationOwnerLogins: ["owner-login"], }, oauth: { accessTokenExpiresAt: "2099-01-01T00:00:00.000Z", refreshedAt: "2099-01-01T00:00:00.000Z", }, }, }); return { connectionId, grantId }; } async function addGitHubPatConnection( fixture: Awaited>, opts: { kind: "agent" | "user" | "organization"; tokenValue: string; grantStatus?: "active" | "revoked"; }, ) { const applicationId = randomUUID(); const connectionId = randomUUID(); const grantId = randomUUID(); const isPersonal = opts.kind === "user"; const isOrg = opts.kind === "organization"; await db.insert(toolApplications).values({ id: applicationId, companyId: fixture.companyId, name: `github-pat-${applicationId}`, type: "mcp_http", }); const stored = await writeConnectionCredential(db, { companyId: fixture.companyId, connectionName: `github-pat-${connectionId}`, configPath: "credentials.authorization", label: "GitHub PAT", value: `Bearer ${opts.tokenValue}`, ...(isPersonal ? { ownerUserId: fixture.responsibleUserId } : {}), }); await db.insert(toolConnections).values({ id: connectionId, companyId: fixture.companyId, applicationId, name: `github-pat-${connectionId}`, uid: `github-pat-${connectionId}`, transport: "mcp_remote", authKind: "api_key", status: "active", enabled: true, credentialPolicy: isPersonal ? "per_user" : isOrg ? "shared" : "per_agent", config: { sourceTemplateKey: "github" }, credentialRefs: [ { name: "authorization", placement: "header", key: "Authorization", secretId: stored.secret.id, version: "latest", }, ], }); await db.insert(toolConnectionInstalls).values({ companyId: fixture.companyId, connectionId, targetType: "agent", targetId: fixture.agentId, }); await db.insert(connectionGrants).values({ id: grantId, companyId: fixture.companyId, connectionId, kind: opts.kind, ...(isPersonal ? { subjectUserId: fixture.responsibleUserId } : isOrg ? { isDefault: true } : { subjectAgentId: fixture.agentId }), status: opts.grantStatus ?? "active", credentialSecretRefs: [ { configPath: "credentials.authorization", secretId: stored.secret.id, versionSelector: "latest", }, ], }); return { connectionId, grantId }; } it("grants transient workspace_prepare credentials for an in-boundary project repo while keeping runtime credentials denied", async () => { const fixture = await seedLowTrustFixture(); await addManagedOAuthGrant(fixture, "gho_managed_oauth_token"); const runtimeCreds = await resolveGitHubOperationCredentials(db, { companyId: fixture.companyId, agentId: fixture.agentId, runId: fixture.runId, }); expect(runtimeCreds.status).toBe("unavailable"); expect(runtimeCreds.env).toEqual({}); const prepareCreds = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: fixture.companyId, agentId: fixture.agentId, runId: fixture.runId, remoteUrl: `${fixture.repoUrl}.git`, }); expect(prepareCreds.status).toBe("available"); expect(prepareCreds.env.PAPERCLIP_GIT_TOKEN).toBe("gho_managed_oauth_token"); const prepareProvider = createGitRemoteAuthProvider(db, fixture.companyId, { agentId: fixture.agentId, heartbeatRunId: fixture.runId, issueId: fixture.issueId, purpose: "workspace_prepare", }); const invocation = await prepareProvider(`${fixture.repoUrl}.git`); expect(invocation?.env.PAPERCLIP_GIT_TOKEN).toBe("gho_managed_oauth_token"); const deniedOutOfBoundary = await prepareProvider( "https://github.com/acme/other-private-repo.git", ); expect(deniedOutOfBoundary?.env.PAPERCLIP_GIT_TOKEN).toBe(""); }); it("supports SSH and scp-style GitHub remotes for in-boundary project workspaces", async () => { const fixture = await seedLowTrustFixture({ repoUrl: "ssh://git@github.com/acme/ssh-private-repo.git", }); await addManagedOAuthGrant(fixture, "gho_ssh_repo_token"); const scpResult = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: fixture.companyId, agentId: fixture.agentId, runId: fixture.runId, remoteUrl: "git@github.com:acme/ssh-private-repo.git", }); expect(scpResult.status).toBe("available"); expect(scpResult.env.PAPERCLIP_GIT_TOKEN).toBe("gho_ssh_repo_token"); const sshProvider = createGitRemoteAuthProvider(db, fixture.companyId, { agentId: fixture.agentId, heartbeatRunId: fixture.runId, issueId: fixture.issueId, purpose: "workspace_prepare", }); const sshInvocation = await sshProvider( "ssh://git@github.com/acme/ssh-private-repo.git", ); expect(sshInvocation?.env.PAPERCLIP_GIT_TOKEN).toBe("gho_ssh_repo_token"); }); it("allows repos from any project inside trustBoundary.projectIds while denying out-of-boundary projects", async () => { const fixture = await seedLowTrustFixture({ extraProjects: [ { repoUrl: "https://github.com/acme/second-in-boundary", inBoundary: true }, { repoUrl: "https://github.com/acme/out-of-boundary", inBoundary: false }, ], }); await addManagedOAuthGrant(fixture, "gho_multi_project_token"); const allowedSecond = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: fixture.companyId, agentId: fixture.agentId, runId: fixture.runId, remoteUrl: "https://github.com/acme/second-in-boundary.git", }); expect(allowedSecond.status).toBe("available"); expect(allowedSecond.env.PAPERCLIP_GIT_TOKEN).toBe("gho_multi_project_token"); const deniedOutside = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: fixture.companyId, agentId: fixture.agentId, runId: fixture.runId, remoteUrl: "https://github.com/acme/out-of-boundary.git", }); expect(deniedOutside.status).toBe("unavailable"); expect(deniedOutside.env).toEqual({}); }); it("denies workspace_prepare credentials when git.read is not permitted or issue is quarantined", async () => { const noGitRead = await seedLowTrustFixture({ allowedToolClasses: [] }); await addManagedOAuthGrant(noGitRead, "gho_no_git_read"); const noGitReadResult = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: noGitRead.companyId, agentId: noGitRead.agentId, runId: noGitRead.runId, remoteUrl: noGitRead.repoUrl, }); expect(noGitReadResult.status).toBe("unavailable"); expect(noGitReadResult.env).toEqual({}); const quarantined = await seedLowTrustFixture({ quarantined: true }); await addManagedOAuthGrant(quarantined, "gho_quarantined"); const quarantinedResult = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: quarantined.companyId, agentId: quarantined.agentId, runId: quarantined.runId, remoteUrl: quarantined.repoUrl, }); expect(quarantinedResult.status).toBe("unavailable"); expect(quarantinedResult.env).toEqual({}); }); it("prefers an active dedicated agent PAT grant and rejects revoked PAT grants", async () => { const fixture = await seedLowTrustFixture(); const pat = await addGitHubPatConnection(fixture, { kind: "agent", tokenValue: "github_pat_dedicated_active_123", }); const activeResult = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: fixture.companyId, agentId: fixture.agentId, runId: fixture.runId, remoteUrl: fixture.repoUrl, }); expect(activeResult.status).toBe("available"); expect(activeResult.source).toBe("dedicated"); expect(activeResult.grantId).toBe(pat.grantId); expect(activeResult.env.PAPERCLIP_GIT_TOKEN).toBe("github_pat_dedicated_active_123"); // Revoking the grant immediately blocks checkout even while the connection and install remain active. await db .update(connectionGrants) .set({ status: "revoked" }) .where(eq(connectionGrants.id, pat.grantId)); const revokedResult = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: fixture.companyId, agentId: fixture.agentId, runId: fixture.runId, remoteUrl: fixture.repoUrl, }); expect(revokedResult.status).toBe("unavailable"); expect(revokedResult.env).toEqual({}); }); it("resolves a personal (per_user) GitHub PAT stored in a real user-scoped secret", async () => { const fixture = await seedLowTrustFixture(); const pat = await addGitHubPatConnection(fixture, { kind: "user", tokenValue: "github_pat_personal_user_scoped_456", }); const result = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: fixture.companyId, agentId: fixture.agentId, runId: fixture.runId, remoteUrl: fixture.repoUrl, }); expect(result.status).toBe("available"); expect(result.source).toBe("personal"); expect(result.grantId).toBe(pat.grantId); expect(result.env.PAPERCLIP_GIT_TOKEN).toBe("github_pat_personal_user_scoped_456"); // Runtime credentials remain denied even when the personal PAT is available for prepare. const runtimeCreds = await resolveGitHubOperationCredentials(db, { companyId: fixture.companyId, agentId: fixture.agentId, runId: fixture.runId, }); expect(runtimeCreds.status).toBe("unavailable"); expect(runtimeCreds.env).toEqual({}); }); it("supports shared (organization) PAT grants and blocks fallback to personal PAT when a dedicated PAT is revoked", async () => { const sharedFixture = await seedLowTrustFixture(); const orgPat = await addGitHubPatConnection(sharedFixture, { kind: "organization", tokenValue: "github_pat_shared_org_789", }); const orgResult = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: sharedFixture.companyId, agentId: sharedFixture.agentId, runId: sharedFixture.runId, remoteUrl: sharedFixture.repoUrl, }); expect(orgResult.status).toBe("available"); expect(orgResult.grantId).toBe(orgPat.grantId); expect(orgResult.env.PAPERCLIP_GIT_TOKEN).toBe("github_pat_shared_org_789"); await db .update(connectionGrants) .set({ status: "revoked" }) .where(eq(connectionGrants.id, orgPat.grantId)); const revokedOrgResult = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: sharedFixture.companyId, agentId: sharedFixture.agentId, runId: sharedFixture.runId, remoteUrl: sharedFixture.repoUrl, }); expect(revokedOrgResult.status).toBe("unavailable"); expect(revokedOrgResult.env).toEqual({}); // Revoking a dedicated PAT must fail closed rather than switching to an installed personal PAT. const mixedFixture = await seedLowTrustFixture(); await addGitHubPatConnection(mixedFixture, { kind: "agent", tokenValue: "github_pat_revoked_dedicated", grantStatus: "revoked", }); await addGitHubPatConnection(mixedFixture, { kind: "user", tokenValue: "github_pat_personal_should_not_be_used", grantStatus: "active", }); const mixedResult = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: mixedFixture.companyId, agentId: mixedFixture.agentId, runId: mixedFixture.runId, remoteUrl: mixedFixture.repoUrl, }); expect(mixedResult.status).toBe("unavailable"); expect(mixedResult.env).toEqual({}); // Shared organization PAT with a user-restricted audience denies users outside the audience. const restrictedFixture = await seedLowTrustFixture({ responsibleUserId: "user-outside-audience", }); const restrictedOrgPat = await addGitHubPatConnection(restrictedFixture, { kind: "organization", tokenValue: "github_pat_restricted_org_audience", }); await db.insert(connectionGrantMembers).values({ companyId: restrictedFixture.companyId, grantId: restrictedOrgPat.grantId, subjectType: "user", subjectId: "user-inside-audience", }); const deniedAudienceResult = await resolveGitHubWorkspacePrepareCredentials(db, { companyId: restrictedFixture.companyId, agentId: restrictedFixture.agentId, runId: restrictedFixture.runId, remoteUrl: restrictedFixture.repoUrl, }); expect(deniedAudienceResult.status).toBe("unavailable"); expect(deniedAudienceResult.env).toEqual({}); }); it("never falls back to company secrets or server-env GITHUB_TOKEN for low-trust workspace_prepare", async () => { const fixture = await seedLowTrustFixture(); await secretService(db).create( fixture.companyId, { name: "GITHUB_TOKEN", value: "ghp_company_secret_must_not_leak", provider: "local_encrypted", }, { userId: fixture.responsibleUserId, agentId: null }, ); const provider = createGitRemoteAuthProvider( db, fixture.companyId, { agentId: fixture.agentId, heartbeatRunId: fixture.runId, issueId: fixture.issueId, purpose: "workspace_prepare", }, { env: { GITHUB_TOKEN: "ghp_server_env_must_not_leak" }, }, ); const invocation = await provider(fixture.repoUrl); expect(invocation?.env.PAPERCLIP_GIT_TOKEN).toBe(""); }); it("denies project:write_workspace for low-trust agents even with tasks:assign on an in-boundary project", async () => { const fixture = await seedLowTrustFixture(); await db.insert(principalPermissionGrants).values({ companyId: fixture.companyId, principalType: "agent", principalId: fixture.agentId, permissionKey: "tasks:assign", }); const decision = await authorizationService(db).decide({ actor: { type: "agent", agentId: fixture.agentId, companyId: fixture.companyId, source: "agent_jwt", runId: fixture.runId, }, action: "project:write_workspace", resource: { type: "issue", companyId: fixture.companyId, projectId: fixture.projectId, issueId: fixture.issueId, assigneeAgentId: fixture.agentId, }, scope: { projectId: fixture.projectId, assigneeAgentId: fixture.agentId }, }); expect(decision.allowed).toBe(false); }); it("test-drives prepareRemoteWorkspaceDirectory end-to-end with transient low-trust auth and leaves zero credentials in the sandbox", async () => { const tmp = await realpath( await mkdtemp(path.join(os.tmpdir(), "paperclip-low-trust-e2e-")), ); try { const seedWork = path.join(tmp, "seed"); const bareRepo = path.join(tmp, "origin.git"); const remoteCwd = path.join(tmp, "sandbox-workspace"); execFileSync("git", ["init", "-b", "main", seedWork], { stdio: "ignore" }); await writeFile(path.join(seedWork, "README.md"), "private-repo-content\n", "utf8"); execFileSync("git", ["add", "README.md"], { cwd: seedWork, stdio: "ignore" }); execFileSync( "git", [ "-c", "user.name=Owner", "-c", "user.email=owner@example.test", "commit", "-m", "initial private commit", ], { cwd: seedWork, stdio: "ignore" }, ); execFileSync("git", ["clone", "--bare", seedWork, bareRepo], { stdio: "ignore" }); const fixture = await seedLowTrustFixture({ repoUrl: "https://github.com/acme/e2e-private-repo", }); await addManagedOAuthGrant(fixture, "gho_e2e_transient_token"); const prepareProvider = createGitRemoteAuthProvider(db, fixture.companyId, { agentId: fixture.agentId, heartbeatRunId: fixture.runId, issueId: fixture.issueId, purpose: "workspace_prepare", }); let observedTokenDuringPrepare: string | undefined; await prepareRemoteWorkspaceDirectory({ target: { kind: "remote", transport: "sandbox", remoteCwd: tmp, runner: { execute: async ({ command: cmd, args, env, }: { command: string; args: string[]; env?: Record; }) => { if (env?.PAPERCLIP_GIT_TOKEN) { observedTokenDuringPrepare = env.PAPERCLIP_GIT_TOKEN; } const { stdout, stderr } = await execFileAsync(cmd, args, { env: { ...process.env, ...(env ?? {}) }, }); return { exitCode: 0, signal: null, timedOut: false, stdout, stderr }; }, }, } as unknown as Parameters[0]["target"], remoteCwd, source: { kind: "git", repoUrl: bareRepo, ref: "main" }, resolveGitAuth: async () => prepareProvider(fixture.repoUrl), preparationIdentity: "a".repeat(64), }); expect(observedTokenDuringPrepare).toBe("gho_e2e_transient_token"); expect(await readFile(path.join(remoteCwd, "README.md"), "utf8")).toBe( "private-repo-content\n", ); const gitConfig = await readFile(path.join(remoteCwd, ".git", "config"), "utf8"); expect(gitConfig).not.toContain("gho_e2e_transient_token"); expect(gitConfig).not.toContain("PAPERCLIP_GIT_TOKEN"); expect(gitConfig).not.toContain("x-access-token"); const logOut = execFileSync("git", ["-C", remoteCwd, "log", "-1", "--format=%s"], { encoding: "utf8", env: { PATH: process.env.PATH ?? "" }, }).trim(); expect(logOut).toBe("initial private commit"); } finally { await rm(tmp, { recursive: true, force: true }); } }); }, );