mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 04:29:01 +01:00
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
This commit is contained in:
1 parent
23ca89e376
commit
1fb8ddb740
6 files changed
+1303
-33
No files matched your search
@@ -0,0 +1,750 @@
|
||||
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 });
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1520,7 +1520,11 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
|
||||
return lowTrustDeny("Issue is outside this low-trust boundary.");
|
||||
}
|
||||
|
||||
if (input.action === "tasks:assign" || input.action === "project:write_workspace") {
|
||||
if (input.action === "project:write_workspace") {
|
||||
return lowTrustDeny("Low-trust agents cannot modify project workspaces.");
|
||||
}
|
||||
|
||||
if (input.action === "tasks:assign") {
|
||||
if (input.resource.type !== "issue") {
|
||||
return lowTrustDeny("Low-trust task assignment is missing an issue resource.");
|
||||
}
|
||||
|
||||
@@ -278,6 +278,7 @@ export function createGitRemoteAuthProvider(
|
||||
heartbeatRunId?: string | null;
|
||||
responsibleUserId?: string | null;
|
||||
agentId?: string | null;
|
||||
purpose?: "workspace_prepare";
|
||||
},
|
||||
deps?: {
|
||||
secrets?: GitCredentialSecretsDeps;
|
||||
@@ -333,10 +334,23 @@ export function createGitRemoteAuthProvider(
|
||||
eq(heartbeatRuns.id, context.heartbeatRunId), eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.agentId, context.agentId),
|
||||
));
|
||||
if (run?.contextId) {
|
||||
const { resolveGitHubOperationCredentials } = await import("./github-operation-credentials.js");
|
||||
const result = await resolveGitHubOperationCredentials(db, {
|
||||
companyId, runId: context.heartbeatRunId, agentId: context.agentId,
|
||||
});
|
||||
const {
|
||||
resolveGitHubOperationCredentials,
|
||||
resolveGitHubWorkspacePrepareCredentials,
|
||||
} = await import("./github-operation-credentials.js");
|
||||
const result =
|
||||
context.purpose === "workspace_prepare"
|
||||
? await resolveGitHubWorkspacePrepareCredentials(db, {
|
||||
companyId,
|
||||
runId: context.heartbeatRunId,
|
||||
agentId: context.agentId,
|
||||
remoteUrl,
|
||||
})
|
||||
: await resolveGitHubOperationCredentials(db, {
|
||||
companyId,
|
||||
runId: context.heartbeatRunId,
|
||||
agentId: context.agentId,
|
||||
});
|
||||
if (result.status === "absent") {
|
||||
const credential = await resolveCredential();
|
||||
return credential ? buildGitAuthInvocation(credential) : null;
|
||||
|
||||
@@ -1,21 +1,32 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { and, eq, inArray, or, sql } from "drizzle-orm";
|
||||
import { isUuidLike } from "@paperclipai/shared";
|
||||
import {
|
||||
agents,
|
||||
companyMemberships,
|
||||
companySecrets,
|
||||
connectionGrantMembers,
|
||||
connectionGrants,
|
||||
heartbeatRuns,
|
||||
issues,
|
||||
projects,
|
||||
projectWorkspaces,
|
||||
runIdentityContexts,
|
||||
toolConnectionInstalls,
|
||||
toolConnections,
|
||||
type Db,
|
||||
} from "@paperclipai/db";
|
||||
import { forbidden } from "../errors.js";
|
||||
import { connectionGrantCredentialRef } from "./connection-credentials.js";
|
||||
import { isGitHubDotCom } from "./github-fetch.js";
|
||||
import { captureRunCompletionIdentity, captureRunIdentity, type RunIdentityContext } from "./run-identity.js";
|
||||
import {
|
||||
buildGitAuthInvocation,
|
||||
resolveManagedGitHubCredential,
|
||||
} from "./git-credentials.js";
|
||||
import { normalizeProjectRepositoryUrl } from "./project-repositories.js";
|
||||
import { secretService } from "./secrets.js";
|
||||
import { sharedAgentGrantIds } from "./tool-access/connections/agent-grant.js";
|
||||
import { resolveCoreTrustPreset } from "./trust-preset-resolver.js";
|
||||
import { isLowTrustQuarantined } from "./source-trust.js";
|
||||
|
||||
@@ -32,11 +43,20 @@ export type GitHubCredentialSummary = {
|
||||
type GitHubCredentialRun = Pick<typeof heartbeatRuns.$inferSelect,
|
||||
"id" | "companyId" | "agentId" | "nativeIssueId" | "contextSnapshot">;
|
||||
|
||||
/** A raw GitHub token cannot enforce the low-trust read-only tool boundary. */
|
||||
async function allowsGitHubCredentialExport(
|
||||
type LoadedRunTrustContext = {
|
||||
projectId: string | null;
|
||||
trust: ReturnType<typeof resolveCoreTrustPreset>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Shared fail-closed trust loader for both runtime credential export and
|
||||
* controller-only workspace-prepare checkout. Quarantined issues are denied
|
||||
* in both paths so security gates cannot drift.
|
||||
*/
|
||||
async function loadRunTrustContext(
|
||||
db: Db,
|
||||
run: GitHubCredentialRun,
|
||||
) {
|
||||
): Promise<LoadedRunTrustContext | null> {
|
||||
const issueId =
|
||||
run.contextSnapshot?.issueId ??
|
||||
run.contextSnapshot?.taskId ??
|
||||
@@ -45,15 +65,16 @@ async function allowsGitHubCredentialExport(
|
||||
issueId !== undefined &&
|
||||
issueId !== null &&
|
||||
(typeof issueId !== "string" || !isUuidLike(issueId))
|
||||
)
|
||||
return false;
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const [agent] = await db
|
||||
.select({ companyId: agents.companyId, permissions: agents.permissions })
|
||||
.from(agents)
|
||||
.where(
|
||||
and(eq(agents.id, run.agentId), eq(agents.companyId, run.companyId)),
|
||||
);
|
||||
if (!agent) return false;
|
||||
if (!agent) return null;
|
||||
const [issue] =
|
||||
typeof issueId === "string"
|
||||
? await db
|
||||
@@ -68,15 +89,16 @@ async function allowsGitHubCredentialExport(
|
||||
and(eq(issues.id, issueId), eq(issues.companyId, run.companyId)),
|
||||
)
|
||||
: [];
|
||||
if (issueId !== undefined && issueId !== null && !issue) return false;
|
||||
if (isLowTrustQuarantined(issue?.sourceTrust)) return false;
|
||||
if (issueId !== undefined && issueId !== null && !issue) return null;
|
||||
if (isLowTrustQuarantined(issue?.sourceTrust)) return null;
|
||||
const projectId = issue?.projectId ?? run.contextSnapshot?.projectId;
|
||||
if (
|
||||
projectId !== undefined &&
|
||||
projectId !== null &&
|
||||
(typeof projectId !== "string" || !isUuidLike(projectId))
|
||||
)
|
||||
return false;
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const [project] =
|
||||
typeof projectId === "string"
|
||||
? await db
|
||||
@@ -92,19 +114,57 @@ async function allowsGitHubCredentialExport(
|
||||
),
|
||||
)
|
||||
: [];
|
||||
if (projectId !== undefined && projectId !== null && !project) return false;
|
||||
return (
|
||||
resolveCoreTrustPreset({
|
||||
if (projectId !== undefined && projectId !== null && !project) return null;
|
||||
const trust = resolveCoreTrustPreset({
|
||||
companyId: run.companyId,
|
||||
agent,
|
||||
project,
|
||||
issue,
|
||||
run: {
|
||||
companyId: run.companyId,
|
||||
agent,
|
||||
project,
|
||||
issue,
|
||||
run: {
|
||||
companyId: run.companyId,
|
||||
executionPolicy: run.contextSnapshot?.executionPolicy,
|
||||
},
|
||||
}).kind === "standard"
|
||||
);
|
||||
executionPolicy: run.contextSnapshot?.executionPolicy,
|
||||
},
|
||||
});
|
||||
return {
|
||||
projectId: typeof projectId === "string" ? projectId : null,
|
||||
trust,
|
||||
};
|
||||
}
|
||||
|
||||
/** A raw GitHub token cannot enforce the low-trust read-only tool boundary. */
|
||||
async function allowsGitHubCredentialExport(
|
||||
db: Db,
|
||||
run: GitHubCredentialRun,
|
||||
) {
|
||||
return (await loadRunTrustContext(db, run))?.trust.kind === "standard";
|
||||
}
|
||||
|
||||
function normalizeGitHubRepositoryIdentity(remoteUrl: string): string | null {
|
||||
const trimmed = remoteUrl.trim();
|
||||
const scpMatch = /^git@(?:www\.)?github\.com:([^\s]+)$/i.exec(trimmed);
|
||||
let candidate = trimmed;
|
||||
if (scpMatch) {
|
||||
candidate = `https://github.com/${scpMatch[1]!.replace(/^\/+/, "")}`;
|
||||
} else {
|
||||
try {
|
||||
const parsed = new URL(trimmed);
|
||||
if (
|
||||
parsed.protocol === "ssh:" &&
|
||||
parsed.username === "git" &&
|
||||
!parsed.password &&
|
||||
isGitHubDotCom(parsed.hostname)
|
||||
) {
|
||||
candidate = `https://github.com/${parsed.pathname.replace(/^\/+/, "")}`;
|
||||
}
|
||||
} catch {
|
||||
// Fall through to normalizeProjectRepositoryUrl below.
|
||||
}
|
||||
}
|
||||
try {
|
||||
return normalizeProjectRepositoryUrl(candidate).url.toLowerCase();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveGitHubSummary(
|
||||
@@ -133,6 +193,432 @@ export async function resolveGitHubOperationCredentials(
|
||||
return resolveCapturedGitHubCredentials(db, run, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Controller-only workspace-prepare credentials. For low-trust runs, this allows
|
||||
* a transient clone of a repository explicitly configured on a project inside
|
||||
* the run's trust boundary when `git.read` is permitted. Runtime agent shells
|
||||
* still use `resolveGitHubOperationCredentials`, which remains denied.
|
||||
*/
|
||||
export async function resolveGitHubWorkspacePrepareCredentials(
|
||||
db: Db,
|
||||
input: {
|
||||
companyId: string;
|
||||
agentId: string;
|
||||
runId: string;
|
||||
remoteUrl: string;
|
||||
},
|
||||
) {
|
||||
const { run, context } = await captureRunIdentity(db, input, { readScope: "github_credentials" });
|
||||
if (!context) throw forbidden("This run predates managed GitHub credentials");
|
||||
const trustContext = await loadRunTrustContext(db, run);
|
||||
if (trustContext?.trust.kind === "standard") {
|
||||
return resolveCapturedGitHubCredentials(db, run, context, {
|
||||
authorized: true,
|
||||
saveSummary: true,
|
||||
allowAbsentFallback: true,
|
||||
});
|
||||
}
|
||||
const prepareAllowed = trustContext
|
||||
? await allowsLowTrustWorkspacePrepareCheckout(db, run, input.remoteUrl, trustContext)
|
||||
: false;
|
||||
if (!prepareAllowed) {
|
||||
return {
|
||||
identityContextId: context.id,
|
||||
revision: context.revision,
|
||||
status: "unavailable" as const,
|
||||
reason:
|
||||
"GitHub credentials are not available to low-trust or unverified executions; use authorized read-only tools.",
|
||||
env: {} as Record<string, string>,
|
||||
};
|
||||
}
|
||||
const pat = await resolveAuthorizedGitHubPat(db, run, context);
|
||||
if (pat) {
|
||||
if (pat.status === "unavailable") {
|
||||
return {
|
||||
identityContextId: context.id,
|
||||
revision: context.revision,
|
||||
status: "unavailable" as const,
|
||||
source: pat.source,
|
||||
reason: pat.reason,
|
||||
env: {} as Record<string, string>,
|
||||
};
|
||||
}
|
||||
return {
|
||||
identityContextId: context.id,
|
||||
revision: context.revision,
|
||||
status: "available" as const,
|
||||
source: pat.source,
|
||||
connectionId: pat.connectionId,
|
||||
grantId: pat.grantId,
|
||||
authenticationMode: "managed" as const,
|
||||
env: buildGitAuthInvocation({ token: pat.token, source: "managed_connection", secretName: null }).env,
|
||||
};
|
||||
}
|
||||
// Low-trust workspace prepare must never overwrite the runtime credential
|
||||
// summary or fall through to company secrets / process-wide GITHUB_TOKEN.
|
||||
return resolveCapturedGitHubCredentials(db, run, context, {
|
||||
authorized: true,
|
||||
saveSummary: false,
|
||||
allowAbsentFallback: false,
|
||||
});
|
||||
}
|
||||
|
||||
async function allowsLowTrustWorkspacePrepareCheckout(
|
||||
db: Db,
|
||||
run: GitHubCredentialRun,
|
||||
remoteUrl: string,
|
||||
trustContext: LoadedRunTrustContext,
|
||||
): Promise<boolean> {
|
||||
const normalizedRemote = normalizeGitHubRepositoryIdentity(remoteUrl);
|
||||
if (!normalizedRemote) return false;
|
||||
const { trust, projectId } = trustContext;
|
||||
if (trust.kind !== "low_trust_review") return false;
|
||||
if (!(trust.boundary.allowedToolClasses ?? []).includes("git.read")) return false;
|
||||
const boundaryProjectIds = (trust.boundary.projectIds ?? []).filter(
|
||||
(id): id is string => typeof id === "string" && isUuidLike(id),
|
||||
);
|
||||
if (boundaryProjectIds.length === 0) return false;
|
||||
if (projectId && !boundaryProjectIds.includes(projectId)) return false;
|
||||
|
||||
const workspaces = await db
|
||||
.select({ repoUrl: projectWorkspaces.repoUrl })
|
||||
.from(projectWorkspaces)
|
||||
.where(
|
||||
and(
|
||||
eq(projectWorkspaces.companyId, run.companyId),
|
||||
inArray(projectWorkspaces.projectId, boundaryProjectIds),
|
||||
),
|
||||
);
|
||||
return workspaces.some((ws) => {
|
||||
if (!ws.repoUrl) return false;
|
||||
return normalizeGitHubRepositoryIdentity(ws.repoUrl) === normalizedRemote;
|
||||
});
|
||||
}
|
||||
|
||||
type AuthorizedGitHubPatResult =
|
||||
| {
|
||||
status: "available";
|
||||
connectionId: string;
|
||||
grantId: string;
|
||||
source: "dedicated" | "personal";
|
||||
token: string;
|
||||
}
|
||||
| {
|
||||
status: "unavailable";
|
||||
source: "dedicated" | "personal";
|
||||
reason: string;
|
||||
};
|
||||
|
||||
async function resolveAuthorizedGitHubPat(
|
||||
db: Db,
|
||||
run: GitHubCredentialRun,
|
||||
context: RunIdentityContext,
|
||||
): Promise<AuthorizedGitHubPatResult | null> {
|
||||
const connections = await db
|
||||
.select({
|
||||
id: toolConnections.id,
|
||||
credentialPolicy: toolConnections.credentialPolicy,
|
||||
credentialRefs: toolConnections.credentialRefs,
|
||||
})
|
||||
.from(toolConnections)
|
||||
.where(
|
||||
and(
|
||||
eq(toolConnections.companyId, run.companyId),
|
||||
eq(toolConnections.authKind, "api_key"),
|
||||
eq(toolConnections.enabled, true),
|
||||
eq(toolConnections.status, "active"),
|
||||
or(
|
||||
sql`${toolConnections.config}->'sourceTemplateKey' = '"github"'::jsonb`,
|
||||
sql`${toolConnections.transportConfig}->'sourceTemplateKey' = '"github"'::jsonb`,
|
||||
),
|
||||
),
|
||||
);
|
||||
const authConnections = connections.filter((connection) =>
|
||||
connection.credentialRefs.some(
|
||||
(ref) => ref.placement === "header" && ref.key.toLowerCase() === "authorization",
|
||||
),
|
||||
);
|
||||
if (authConnections.length === 0) return null;
|
||||
const authConnectionIds = authConnections.map((connection) => connection.id);
|
||||
const installs = await db
|
||||
.select({
|
||||
connectionId: toolConnectionInstalls.connectionId,
|
||||
targetType: toolConnectionInstalls.targetType,
|
||||
targetId: toolConnectionInstalls.targetId,
|
||||
})
|
||||
.from(toolConnectionInstalls)
|
||||
.where(
|
||||
and(
|
||||
eq(toolConnectionInstalls.companyId, run.companyId),
|
||||
inArray(toolConnectionInstalls.connectionId, authConnectionIds),
|
||||
),
|
||||
);
|
||||
const sharedGrants = await sharedAgentGrantIds(
|
||||
db,
|
||||
run.companyId,
|
||||
run.agentId,
|
||||
authConnections
|
||||
.filter((connection) => connection.credentialPolicy === "per_agent")
|
||||
.map((connection) => connection.id),
|
||||
);
|
||||
const sharedConnectionIds = new Set(sharedGrants.values());
|
||||
const eligibleConnections = authConnections.filter(
|
||||
(connection) =>
|
||||
sharedConnectionIds.has(connection.id) ||
|
||||
installs.some(
|
||||
(install) =>
|
||||
install.connectionId === connection.id &&
|
||||
((install.targetType === "company" && install.targetId === run.companyId) ||
|
||||
(install.targetType === "agent" && install.targetId === run.agentId)),
|
||||
),
|
||||
);
|
||||
if (eligibleConnections.length === 0) return null;
|
||||
|
||||
// Query all matching grants before checking status so revoking a higher-priority
|
||||
// dedicated grant fails closed instead of silently switching to a personal or
|
||||
// organization credential.
|
||||
const grants = await db
|
||||
.select()
|
||||
.from(connectionGrants)
|
||||
.where(
|
||||
and(
|
||||
eq(connectionGrants.companyId, run.companyId),
|
||||
inArray(
|
||||
connectionGrants.connectionId,
|
||||
eligibleConnections.map((connection) => connection.id),
|
||||
),
|
||||
or(
|
||||
eq(connectionGrants.kind, "agent"),
|
||||
eq(connectionGrants.kind, "user"),
|
||||
eq(connectionGrants.kind, "organization"),
|
||||
),
|
||||
),
|
||||
);
|
||||
const ownDedicated = grants.filter(
|
||||
(grant) => grant.kind === "agent" && grant.subjectAgentId === run.agentId,
|
||||
);
|
||||
const sharedDedicated =
|
||||
ownDedicated.length > 0
|
||||
? []
|
||||
: grants.filter((grant) => grant.kind === "agent" && sharedGrants.has(grant.id));
|
||||
const liveSharedDedicated = sharedDedicated.filter((grant) => grant.status === "active");
|
||||
const dedicated =
|
||||
ownDedicated.length > 0
|
||||
? ownDedicated
|
||||
: liveSharedDedicated.length > 0
|
||||
? liveSharedDedicated
|
||||
: sharedDedicated;
|
||||
const responsibleUserId =
|
||||
context.cause === "company_default" ? null : (context.responsibleUserId ?? null);
|
||||
const personal = responsibleUserId
|
||||
? grants.filter(
|
||||
(grant) => grant.kind === "user" && grant.subjectUserId === responsibleUserId,
|
||||
)
|
||||
: [];
|
||||
const sharedPolicyConnectionIds = new Set(
|
||||
eligibleConnections
|
||||
.filter((connection) => connection.credentialPolicy === "shared")
|
||||
.map((connection) => connection.id),
|
||||
);
|
||||
const organization = grants.filter(
|
||||
(grant) =>
|
||||
grant.kind === "organization" &&
|
||||
grant.isDefault === true &&
|
||||
sharedPolicyConnectionIds.has(grant.connectionId),
|
||||
);
|
||||
const candidates =
|
||||
dedicated.length > 0
|
||||
? dedicated
|
||||
: personal.length > 0
|
||||
? personal
|
||||
: organization;
|
||||
if (candidates.length === 0) return null;
|
||||
const identitySource: "dedicated" | "personal" =
|
||||
dedicated.length > 0 || (personal.length === 0 && organization.length > 0)
|
||||
? "dedicated"
|
||||
: "personal";
|
||||
if (candidates.length !== 1) {
|
||||
return {
|
||||
status: "unavailable",
|
||||
source: identitySource,
|
||||
reason: "More than one GitHub PAT authorization matches this run",
|
||||
};
|
||||
}
|
||||
|
||||
const grant = candidates[0]!;
|
||||
if (grant.status !== "active") {
|
||||
return {
|
||||
status: "unavailable",
|
||||
source: identitySource,
|
||||
reason: "The configured GitHub PAT authorization must be reconnected",
|
||||
};
|
||||
}
|
||||
const connection = eligibleConnections.find((item) => item.id === grant.connectionId);
|
||||
if (!connection) {
|
||||
return {
|
||||
status: "unavailable",
|
||||
source: identitySource,
|
||||
reason: "The configured GitHub PAT connection is unavailable",
|
||||
};
|
||||
}
|
||||
const authRef = connection.credentialRefs.find(
|
||||
(ref) => ref.placement === "header" && ref.key.toLowerCase() === "authorization",
|
||||
);
|
||||
if (!authRef) {
|
||||
return {
|
||||
status: "unavailable",
|
||||
source: identitySource,
|
||||
reason: "The configured GitHub PAT credential is incomplete",
|
||||
};
|
||||
}
|
||||
|
||||
const grantRef = connectionGrantCredentialRef(grant, authRef);
|
||||
const accessContext = {
|
||||
consumerType: "system" as const,
|
||||
consumerId: "workspace-git-credential",
|
||||
actorType: "system" as const,
|
||||
actorId: run.agentId,
|
||||
issueId: typeof run.contextSnapshot?.issueId === "string" ? run.contextSnapshot.issueId : null,
|
||||
heartbeatRunId: run.id,
|
||||
responsibleUserId,
|
||||
};
|
||||
const secrets = secretService(db);
|
||||
try {
|
||||
let raw: string;
|
||||
if (grant.kind === "user") {
|
||||
if (!grant.subjectUserId || !grantRef) {
|
||||
return {
|
||||
status: "unavailable",
|
||||
source: "personal",
|
||||
reason: "The personal GitHub PAT credential is invalid",
|
||||
};
|
||||
}
|
||||
const [membership] = await db
|
||||
.select({ id: companyMemberships.id, role: companyMemberships.membershipRole })
|
||||
.from(companyMemberships)
|
||||
.where(
|
||||
and(
|
||||
eq(companyMemberships.companyId, run.companyId),
|
||||
eq(companyMemberships.principalType, "user"),
|
||||
eq(companyMemberships.principalId, grant.subjectUserId),
|
||||
eq(companyMemberships.status, "active"),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (!membership || membership.role === "viewer") {
|
||||
return {
|
||||
status: "unavailable",
|
||||
source: "personal",
|
||||
reason: "The personal GitHub PAT owner is not an authorized company member",
|
||||
};
|
||||
}
|
||||
const [secret] = await db
|
||||
.select({ userSecretDefinitionId: companySecrets.userSecretDefinitionId })
|
||||
.from(companySecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(companySecrets.companyId, run.companyId),
|
||||
eq(companySecrets.id, grantRef.secretId),
|
||||
eq(companySecrets.ownerUserId, grant.subjectUserId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (!secret?.userSecretDefinitionId) {
|
||||
return {
|
||||
status: "unavailable",
|
||||
source: "personal",
|
||||
reason: "The personal GitHub PAT credential is invalid",
|
||||
};
|
||||
}
|
||||
const resolved = await secrets.resolveUserSecretValue(
|
||||
run.companyId,
|
||||
{
|
||||
definitionId: secret.userSecretDefinitionId,
|
||||
responsibleUserId: grant.subjectUserId,
|
||||
version: grantRef.versionSelector ?? "latest",
|
||||
required: true,
|
||||
},
|
||||
accessContext,
|
||||
);
|
||||
if (!resolved) {
|
||||
return {
|
||||
status: "unavailable",
|
||||
source: "personal",
|
||||
reason: "The personal GitHub PAT credential is missing",
|
||||
};
|
||||
}
|
||||
raw = resolved.value;
|
||||
} else {
|
||||
if (grant.kind === "organization") {
|
||||
const activeAudienceMember = responsibleUserId
|
||||
? await db
|
||||
.select({ id: companyMemberships.id, role: companyMemberships.membershipRole })
|
||||
.from(companyMemberships)
|
||||
.where(
|
||||
and(
|
||||
eq(companyMemberships.companyId, run.companyId),
|
||||
eq(companyMemberships.principalType, "user"),
|
||||
eq(companyMemberships.principalId, responsibleUserId),
|
||||
eq(companyMemberships.status, "active"),
|
||||
),
|
||||
)
|
||||
.limit(1)
|
||||
.then((rows) => rows[0] ?? null)
|
||||
: null;
|
||||
const audience = await db
|
||||
.select({ subjectId: connectionGrantMembers.subjectId })
|
||||
.from(connectionGrantMembers)
|
||||
.where(
|
||||
and(
|
||||
eq(connectionGrantMembers.companyId, run.companyId),
|
||||
eq(connectionGrantMembers.grantId, grant.id),
|
||||
eq(connectionGrantMembers.subjectType, "user"),
|
||||
),
|
||||
);
|
||||
if (
|
||||
(responsibleUserId !== null &&
|
||||
(!activeAudienceMember || activeAudienceMember.role === "viewer")) ||
|
||||
(audience.length > 0 &&
|
||||
(!responsibleUserId ||
|
||||
!audience.some((member) => member.subjectId === responsibleUserId)))
|
||||
) {
|
||||
return {
|
||||
status: "unavailable",
|
||||
source: "dedicated",
|
||||
reason: "The responsible user is not in this GitHub PAT grant's audience",
|
||||
};
|
||||
}
|
||||
}
|
||||
const secretId = grantRef?.secretId ?? authRef.secretId;
|
||||
const version = grantRef?.versionSelector ?? authRef.version ?? "latest";
|
||||
raw = await secrets.resolveSecretValue(run.companyId, secretId, version, {
|
||||
accessContext,
|
||||
});
|
||||
}
|
||||
const token = raw.trim().replace(/^(?:Bearer|token)\s+/i, "").trim();
|
||||
if (!token) {
|
||||
return {
|
||||
status: "unavailable",
|
||||
source: identitySource,
|
||||
reason: "The configured GitHub PAT credential is empty",
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: "available",
|
||||
connectionId: connection.id,
|
||||
grantId: grant.id,
|
||||
source: identitySource,
|
||||
token,
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
status: "unavailable",
|
||||
source: identitySource,
|
||||
reason: "GitHub PAT credentials are temporarily unavailable",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveGitHubCompletionCredentials(
|
||||
db: Db,
|
||||
input: { companyId: string; issueId: string; runId: string },
|
||||
@@ -149,20 +635,32 @@ export async function resolveGitHubCompletionCredentials(
|
||||
return resolveCapturedGitHubCredentials(db, run, context);
|
||||
}
|
||||
|
||||
async function resolveCapturedGitHubCredentials(db: Db, run: GitHubCredentialRun, context: RunIdentityContext) {
|
||||
async function resolveCapturedGitHubCredentials(
|
||||
db: Db,
|
||||
run: GitHubCredentialRun,
|
||||
context: RunIdentityContext,
|
||||
options?: {
|
||||
authorized?: boolean;
|
||||
saveSummary?: boolean;
|
||||
allowAbsentFallback?: boolean;
|
||||
},
|
||||
) {
|
||||
const saveSummary = options?.saveSummary !== false;
|
||||
const allowAbsentFallback = options?.allowAbsentFallback !== false;
|
||||
let summary: GitHubCredentialSummary;
|
||||
let env: Record<string, string> = {};
|
||||
// A sponsored guest's responsible person is an internal accountability field,
|
||||
// not authorization to export that person's (or a dedicated bot's) token.
|
||||
// Re-read every policy source for each operation, including a run's retained
|
||||
// boundary after task policy edits. Deny before touching the credential store.
|
||||
if (!(await allowsGitHubCredentialExport(db, run))) {
|
||||
const authorized = options?.authorized ?? (await allowsGitHubCredentialExport(db, run));
|
||||
if (!authorized) {
|
||||
summary = {
|
||||
status: "unavailable",
|
||||
reason:
|
||||
"GitHub credentials are not available to low-trust or unverified executions; use authorized read-only tools.",
|
||||
};
|
||||
await saveGitHubSummary(db, context, summary);
|
||||
if (saveSummary) await saveGitHubSummary(db, context, summary);
|
||||
return {
|
||||
identityContextId: context.id,
|
||||
revision: context.revision,
|
||||
@@ -201,7 +699,7 @@ async function resolveCapturedGitHubCredentials(db: Db, run: GitHubCredentialRun
|
||||
env = buildGitAuthInvocation(resolved.credential).env;
|
||||
} else {
|
||||
summary = {
|
||||
status: resolved.configured ? "unavailable" : "absent",
|
||||
status: resolved.configured || !allowAbsentFallback ? "unavailable" : "absent",
|
||||
source: resolved.identitySource ?? "personal",
|
||||
reason: resolved.error ?? "No GitHub identity connected",
|
||||
};
|
||||
@@ -213,7 +711,7 @@ async function resolveCapturedGitHubCredentials(db: Db, run: GitHubCredentialRun
|
||||
reason: "GitHub credentials are temporarily unavailable",
|
||||
};
|
||||
}
|
||||
if (context) await saveGitHubSummary(db, context, summary);
|
||||
if (context && saveSummary) await saveGitHubSummary(db, context, summary);
|
||||
return {
|
||||
identityContextId: context?.id ?? null,
|
||||
revision: context?.revision ?? null,
|
||||
|
||||
@@ -1015,6 +1015,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
|
||||
heartbeatRunId: run.id,
|
||||
responsibleUserId: run.responsibleUserId,
|
||||
agentId: agent.id,
|
||||
purpose: "workspace_prepare",
|
||||
},
|
||||
);
|
||||
if (freshNeedsSeed && issueId && !pluginPrepared && !pluginTaskWorkspace && !remoteAuthority) {
|
||||
|
||||
@@ -3439,6 +3439,7 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
|
||||
resolveGitAuth: createGitRemoteAuthProvider(db, agent.companyId, {
|
||||
issueId: input.issueId, heartbeatRunId: input.runId, agentId: agent.id,
|
||||
responsibleUserId: input.responsibleUserId,
|
||||
purpose: "workspace_prepare",
|
||||
}),
|
||||
});
|
||||
return original.cwd;
|
||||
@@ -3481,6 +3482,7 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
|
||||
readNonEmptyString(context.responsibleUserId) ??
|
||||
readNonEmptyString(context.responsible_user_id),
|
||||
agentId: agent.id,
|
||||
purpose: "workspace_prepare",
|
||||
});
|
||||
const contextProjectId = readNonEmptyString(context.projectId);
|
||||
const contextProjectWorkspaceId = readNonEmptyString(
|
||||
@@ -3793,6 +3795,7 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
|
||||
heartbeatRunId: readNonEmptyString(context.executionIdentityRunId),
|
||||
responsibleUserId,
|
||||
agentId: agent.id,
|
||||
purpose: "workspace_prepare",
|
||||
});
|
||||
const { additionalWorkspaces, warnings, failures } =
|
||||
await resolveAdditionalRunWorkspaces(issueId, anchor.projectId, {
|
||||
|
||||
Reference in new issue
Block a user