Files
PaperClipAI/server/src/services/github-operation-credentials.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

722 lines
24 KiB
TypeScript

import { isDeepStrictEqual } from "node:util";
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";
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">;
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 ??
run.nativeIssueId;
if (
issueId !== undefined &&
issueId !== null &&
(typeof issueId !== "string" || !isUuidLike(issueId))
) {
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 null;
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 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 null;
}
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 null;
const trust = resolveCoreTrustPreset({
companyId: run.companyId,
agent,
project,
issue,
run: {
companyId: run.companyId,
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(
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);
}
/**
* 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 },
) {
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,
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.
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.",
};
if (saveSummary) 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 || !allowAbsentFallback ? "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 && saveSummary) await saveGitHubSummary(db, context, summary);
return {
identityContextId: context?.id ?? null,
revision: context?.revision ?? null,
...summary,
env,
};
}