Files
PaperClipAI/server/src/services/github-operation-credentials.ts
T
Devin FoleyandPaperclip 24132dac16 fix(tasks): verify PR merges with the managed run identity (#22357)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Native task completion independently verifies that declared PR
deliverables are merged.
> - Runs can already use an authorized managed GitHub connection to
merge private PRs.
> - Completion used the background credential resolver, which cannot
select that run's managed identity.
> - This pull request reuses operation-time identity and grant checks
for completion verification.
> - Agents can finish delivered work while unavailable grants and
unverified merges remain blocked.

## Linked Issues or Issue Description

Related: #22244 introduced the native PR merge gate. No duplicate fix
was found in the open PR search. The roadmap's personal GitHub identity
capability already covers the intended identity model.

**What happened?**

A native agent with a managed GitHub connection merges a private PR,
then completion rejects it as not verified merged. The independent
server-side check only tries legacy company token names or an instance
token; it does not use the agent run's managed connection.

**Expected behavior**

Verify the merge with the run's current accepted GitHub identity,
retaining current grant, membership, trust and company boundaries.
GitHub must confirm the merge regardless of saved work-product metadata.

**Steps to reproduce**

1. Configure a managed GitHub identity with access to a private
repository and no legacy company GitHub token.
2. Use a native task run to merge and register a PR deliverable.
3. Finish the task. Before this change, the merge verifier cannot
authenticate with the managed identity and rejects completion.

## What Changed

- Bind completion credential lookup to the persisted company, native
task and run.
- Add a server-side completion credential path that shares managed
grant, membership and trust checks with command credentials. Both active
and succeeded runs capture identity under the existing task/run locks
and reconcile pending steering acknowledgements before credential
lookup. The command credential API still requires a running run.
- Resolve credentials once for all PRs in a verification attempt; do no
credential work for tasks without PR deliverables.
- Preserve legacy fallback only for runs without a managed identity, and
preserve the public-only restriction on server-environment credentials.
- Add 23 PostgreSQL-backed authorization regression cases and document
completion's identity behavior.

## Verification

- Local checks cover revision
`da2a3608b0375ead646bbbad35af853191488f07`. [Greptile
review](https://github.com/paperclipai/paperclip/pull/22357#issuecomment-7023243798)
is 5/5 on that revision with both prior threads resolved. [Required
CI](https://github.com/paperclipai/paperclip/actions/runs/44625662403)
passed on attempt 2 for the same revision, including typecheck, build,
canary, server/runner suites and all eight e2e shards.
- Red/green: the private-PR and identity-selection cases failed before
the initial fix. Review exposed a succeeded-run reassessment failure and
then an unsettled-steering gap in that path; each has a regression that
failed on the reviewed commit and passes after its correction.
Unresolved steering performs no token lookup, and durable
acknowledgement selects the new person. The full worker test completes
the task after automatic-review withdrawal while command credentials
remain unavailable to the finished run.
- `pnpm exec vitest run
server/src/services/native-runtime/native-pull-request-completion.test.ts
server/src/services/native-runtime/native-completion-feedback.test.ts
server/src/__tests__/github-operation-credentials.test.ts
server/src/__tests__/native-status-reassessment-work.test.ts
server/src/__tests__/run-identity.test.ts
server/src/__tests__/run-identity-projections.test.ts` — 222 tests pass
across six files, on macOS arm64 with Node 25.6.1 and embedded
PostgreSQL.
- `pnpm --filter @paperclipai/server typecheck` — passes.
- `pnpm verify --explain` — exits 2 because the subsystem documentation
selects broad CI coverage. Required CI supplies the broader test/build
coverage; this exit is not a full-suite pass.
- The credential selection, steering, grant and company checks use real
PostgreSQL state. Only the secret vault and GitHub HTTP transport are
mocked; test requests never reach GitHub.
- `git diff --check` and the staged secret/PII scan pass. No runtime
artifacts are committed.
- Earlier CI revision `4e42f64`: the [Build
job](https://github.com/paperclipai/paperclip/actions/runs/44624163145/job/135914203042)
ended after the runner received a shutdown signal and the workflow was
cancelled. Its log does not show a compiler error before interruption;
this interrupted attempt is not build verification. The current revision
subsequently passed its own CI build on attempt 2.
- Current revision canary: the [Canary Dry Run
job](https://github.com/paperclipai/paperclip/actions/runs/44625662403/job/135919504493)
was interrupted by runner shutdown before completion. The repository
runner-loss classifier returns `lost: true` for its actual annotation
and log. A targeted retry was refused while the workflow remained
active. The same revision subsequently passed Canary Dry Run and the
full workflow on attempt 2; the earlier interrupted attempt remains
recorded here separately.
- Live acceptance remains pending deployment; the change has not been
deployed.

## Risks

Completion now reads managed credentials through a server-side path
shared with the existing authorization checks. Successful finished runs
can be reassessed without granting them command execution credentials.
Denied or unavailable identities must remain blocked without falling
through to a different identity; regression tests cover revocation and
company/task isolation. Credential lookup is shared within one bounded
PR verification attempt, not cached across attempts. The existing HTTP
deadline and merge proof requirements remain in place. No migrations or
API contract changes.

## Model Used

OpenAI Codex, `gpt-6.1-sol`, xhigh reasoning, with repository
inspection, code editing and test execution. Context-window size is not
exposed by the harness.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-19 14:44:03 -08:00

224 lines
7.4 KiB
TypeScript

import { isDeepStrictEqual } from "node:util";
import { and, eq } from "drizzle-orm";
import { isUuidLike } from "@paperclipai/shared";
import {
agents,
heartbeatRuns,
issues,
projects,
runIdentityContexts,
type Db,
} from "@paperclipai/db";
import { forbidden } from "../errors.js";
import { captureRunCompletionIdentity, captureRunIdentity, type RunIdentityContext } from "./run-identity.js";
import {
buildGitAuthInvocation,
resolveManagedGitHubCredential,
} from "./git-credentials.js";
import { secretService } from "./secrets.js";
import { resolveCoreTrustPreset } from "./trust-preset-resolver.js";
import { isLowTrustQuarantined } from "./source-trust.js";
export type GitHubCredentialSummary = {
status: "available" | "absent" | "unavailable";
source?: "personal" | "dedicated";
login?: string;
reason?: string;
connectionId?: string;
grantId?: string;
authenticationMode?: "managed" | "host" | "anonymous";
};
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(
db: Db,
run: GitHubCredentialRun,
) {
const issueId =
run.contextSnapshot?.issueId ??
run.contextSnapshot?.taskId ??
run.nativeIssueId;
if (
issueId !== undefined &&
issueId !== null &&
(typeof issueId !== "string" || !isUuidLike(issueId))
)
return false;
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;
const [issue] =
typeof issueId === "string"
? await db
.select({
companyId: issues.companyId,
projectId: issues.projectId,
executionPolicy: issues.executionPolicy,
sourceTrust: issues.sourceTrust,
})
.from(issues)
.where(
and(eq(issues.id, issueId), eq(issues.companyId, run.companyId)),
)
: [];
if (issueId !== undefined && issueId !== null && !issue) return false;
if (isLowTrustQuarantined(issue?.sourceTrust)) return false;
const projectId = issue?.projectId ?? run.contextSnapshot?.projectId;
if (
projectId !== undefined &&
projectId !== null &&
(typeof projectId !== "string" || !isUuidLike(projectId))
)
return false;
const [project] =
typeof projectId === "string"
? await db
.select({
companyId: projects.companyId,
executionWorkspacePolicy: projects.executionWorkspacePolicy,
})
.from(projects)
.where(
and(
eq(projects.id, projectId),
eq(projects.companyId, run.companyId),
),
)
: [];
if (projectId !== undefined && projectId !== null && !project) return false;
return (
resolveCoreTrustPreset({
companyId: run.companyId,
agent,
project,
issue,
run: {
companyId: run.companyId,
executionPolicy: run.contextSnapshot?.executionPolicy,
},
}).kind === "standard"
);
}
async function saveGitHubSummary(
db: Db,
context: RunIdentityContext,
summary: GitHubCredentialSummary,
) {
if (isDeepStrictEqual(context.github, JSON.parse(JSON.stringify(summary)))) return;
await db
.update(runIdentityContexts)
.set({ github: summary })
.where(eq(runIdentityContexts.id, context.id));
}
/** No company secrets or ambient credentials are consulted by this path. */
export async function resolveGitHubOperationCredentials(
db: Db,
input: {
companyId: string;
agentId: string;
runId: string;
},
) {
const { run, context } = await captureRunIdentity(db, input, { readScope: "github_credentials" });
if (!context) throw forbidden("This run predates managed GitHub credentials");
return resolveCapturedGitHubCredentials(db, run, context);
}
export async function resolveGitHubCompletionCredentials(
db: Db,
input: { companyId: string; issueId: string; runId: string },
) {
const [source] = await db.select({ agentId: heartbeatRuns.agentId })
.from(heartbeatRuns).where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId),
eq(heartbeatRuns.nativeIssueId, input.issueId))).limit(1);
if (!source) throw forbidden("GitHub completion requires the bound task run");
const { run, context } = await captureRunCompletionIdentity(db, { ...input, agentId: source.agentId });
if (!run.activeIdentityContextId && !context) return { status: "absent" as const, env: {} as Record<string, string> };
if (!context || context.companyId !== run.companyId || context.status !== "accepted") {
throw forbidden("GitHub completion requires the run's accepted identity");
}
return resolveCapturedGitHubCredentials(db, run, context);
}
async function resolveCapturedGitHubCredentials(db: Db, run: GitHubCredentialRun, context: RunIdentityContext) {
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))) {
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);
return {
identityContextId: context.id,
revision: context.revision,
...summary,
env,
};
}
try {
const resolved = await resolveManagedGitHubCredential(
db,
secretService(db),
run.companyId,
{
agentId: run.agentId,
heartbeatRunId: run.id,
allowStandingDelegation: false,
responsibleUserId:
context?.cause === "company_default"
? null
: (context?.responsibleUserId ?? null),
issueId:
typeof run.contextSnapshot?.issueId === "string"
? run.contextSnapshot.issueId
: null,
},
);
if (resolved.credential) {
summary = {
status: "available",
source: resolved.credential.identitySource,
login: resolved.credential.githubIdentity?.login,
connectionId: resolved.credential.connectionId,
grantId: resolved.credential.grantId,
authenticationMode: "managed",
};
env = buildGitAuthInvocation(resolved.credential).env;
} else {
summary = {
status: resolved.configured ? "unavailable" : "absent",
source: resolved.identitySource ?? "personal",
reason: resolved.error ?? "No GitHub identity connected",
};
}
} catch {
// Provider/secret errors can contain sensitive response bodies. Never persist them.
summary = {
status: "unavailable",
reason: "GitHub credentials are temporarily unavailable",
};
}
if (context) await saveGitHubSummary(db, context, summary);
return {
identityContextId: context?.id ?? null,
revision: context?.revision ?? null,
...summary,
env,
};
}