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; type LoadedRunTrustContext = { projectId: string | null; trust: ReturnType; }; /** * 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 { 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, }; } 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, }; } 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 { 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 { 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 }; 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 = {}; // 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, }; }