Files
PaperClipAI/server/src/__tests__/github-workspace-prepare-credentials.test.ts
T
Dotta 1fb8ddb740 feat(trust): allow transient workspace_prepare checkout for low-trust in-boundary projects (#23656)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The low-trust review preset isolates untrusted review agents inside
sandboxes with no runtime GitHub tokens and no sandbox network access
> - When a low-trust agent is explicitly assigned to a
private-repository project with `git.read` enabled, workspace
preparation routed the setup-time clone through
`resolveGitHubOperationCredentials`, which blocks all low-trust
credential export and caused `stage=clone git=auth_failed exit=128`
before the agent could start
> - Setup-time `prepareRemoteWorkspaceDirectory` runs on the trusted
controller path before the agent starts, uses transient `GIT_CONFIG_*` /
`PAPERCLIP_GIT_TOKEN` environment variables with `-c
core.hooksPath=/dev/null`, and writes zero credentials into
`.git/config`
> - This pull request adds `resolveGitHubWorkspacePrepareCredentials`
for controller-only `workspace_prepare` call sites, allowing transient
clone credentials strictly for a repository configured on a project
inside `trustBoundary.projectIds` when `git.read` is permitted
(preferring an agent-installed GitHub PAT connection when present),
while keeping runtime shell credentials
(`resolveGitHubOperationCredentials`) strictly denied
> - The benefit is that assigning a low-trust agent to a private-repo
project works out of the box for local read-only code review without
exposing any live GitHub token to the agent runtime

## Linked Issues or Issue Description

**What happened?**
When an agent configured with `trustPreset: "low_trust_review"` and
`allowedToolClasses: ["git.read"]` was assigned a task in a project with
a private GitHub repository workspace, workspace preparation failed
before the agent started with `remote_workspace_prepare_failed:
stage=clone git=auth_failed exit=128 program=git`.

**Expected behavior**
When a `low_trust_review` run has `git.read` enabled and targets a
project explicitly listed in `trustBoundary.projectIds`, the trusted
controller should clone that project's configured repository during
`workspace_prepare` using transient credentials (preferring an
agent-installed GitHub PAT connection if configured, otherwise the run's
managed GitHub identity), while leaving zero credentials in
`.git/config` and keeping runtime GitHub credential export strictly
denied.

**Steps to reproduce**
1. Create a project with a private GitHub repository workspace.
2. Configure an agent with `trustPreset: "low_trust_review"`,
`projectIds: [projectId]`, and `allowedToolClasses: ["git.read"]`.
3. Run a task in that project on a cloud sandbox environment.
4. Before this fix, `createGitRemoteAuthProvider` falls back to
anonymous clone and fails at `stage=clone git=auth_failed exit=128`.

**Paperclip version or commit**
`master` (`23ca89e376`)

## What Changed

- **`server/src/services/github-operation-credentials.ts`**: Added
`resolveGitHubWorkspacePrepareCredentials`,
`allowsLowTrustWorkspacePrepareCheckout`, and
`resolveAgentInstalledGitHubPat`. For `low_trust_review` runs, transient
prepare-time clone auth is permitted only when `trust.kind ===
"low_trust_review"`, `git.read` is in `allowedToolClasses`, the task's
project is explicitly in `trustBoundary.projectIds`, and `remoteUrl`
matches a configured `project_workspaces.repo_url` on that project.
Prefers an active agent-installed GitHub `api_key` (PAT) connection when
present and otherwise falls back to `resolveManagedGitHubCredential`.
Runtime `resolveGitHubOperationCredentials` remains unchanged and
strictly denied for low-trust runs.
- **`server/src/services/git-credentials.ts`**: Added optional
`purpose?: "workspace_prepare"` to `createGitRemoteAuthProvider` so only
controller workspace-preparation call sites invoke
`resolveGitHubWorkspacePrepareCredentials`.
- **`server/src/services/heartbeat/workspace-preparation.ts`** and
**`server/src/services/heartbeat/workspaces.ts`**: Passed `purpose:
"workspace_prepare"` at the four controller workspace-preparation call
sites.
- **`server/src/__tests__/github-operation-credentials.test.ts`**: Added
unit, security-boundary, and end-to-end
`prepareRemoteWorkspaceDirectory` tests covering managed identity
prepare checkout, agent-installed GitHub PAT preference, runtime
credential denial, unrelated repo denial, missing `git.read` denial, and
zero credentials persisted in `.git/config`.

## Verification

- `pnpm --filter @paperclipai/server typecheck` — passed with 0 errors.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/github-operation-credentials.test.ts` — 30/30 passed
(including the 3 new low-trust `workspace_prepare` and local E2E
`prepareRemoteWorkspaceDirectory` tests).

## Risks

- Low risk. Runtime agent credential endpoints
(`/runtime-tools/github/credentials`, native GitHub broker, skill-source
fetch) continue calling `resolveGitHubOperationCredentials` and stay
strictly denied for `low_trust_review`.
- Prepare-time credentials are scoped strictly to repositories already
configured in `project_workspaces` for a project explicitly inside
`trustBoundary.projectIds` and only when `git.read` is enabled.

## Model Used

- Google Gemini (Antigravity agentic coding assistant) with tool use and
local code/test execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge
2026-12-03 15:41:55 -06:00

751 lines
27 KiB
TypeScript

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<ReturnType<typeof startEmbeddedPostgresTestDatabase>>
| undefined;
let db: ReturnType<typeof createDb>;
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<ReturnType<typeof seedLowTrustFixture>>,
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<ReturnType<typeof seedLowTrustFixture>>,
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<string, string>;
}) => {
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<typeof prepareRemoteWorkspaceDirectory>[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 });
}
});
},
);