fix(runner): restore legacy Git access and independent networking (#13094)

## Thinking Path

> - Paperclip runs agents for people with different GitHub accounts.
> - Managed operations must use the intended person's eligible
connection.
> - A failed duplicate connection must not hide a healthy grant for the
same account.
> - Legacy hosts also need their existing Git configuration when managed
access is not configured.
> - Runner networking and local Git operations must not depend on GitHub
broker availability.
> - This pull request separates those policies and improves failure
diagnostics.

## Linked Issues or Issue Description

**What happened?** New runs always cleared host Git credentials and
installed managed launchers. Network permission depended on GitHub
environment variables. A launcher failure could stop even local `git
status`. A newer unhealthy duplicate could take precedence over a
healthy connection, and generic health errors were shown as reconnect
requirements.

**Expected behavior:** Use a healthy eligible managed connection for the
intended account. Preserve host authentication only for unconfigured
standard-trust local or SSH execution. Permit local Git during broker
failures and keep network permission independent of GitHub credentials.

**Steps to reproduce:** Configure healthy and unhealthy grants for one
GitHub account, dispatch an agent, and execute Git commands. Separately
run an unconfigured legacy host with existing GitHub CLI authentication.
Stop the broker and run local `git status`.

**Paperclip version or commit:** Master at 668110469. **Deployment
mode:** Self-hosted. **Installation method:** Git checkout. **Agent
adapters involved:** Native Codex runner and shared adapter execution
setup. **Database mode:** Existing instance database; no migration.
**Access context:** Responsible person's managed grant, or explicitly
unconfigured legacy host. **Node.js version:** 26.4.0 locally.
**Operating system:** macOS development and Linux execution hosts.

**Relevant logs or output:** Previously `GitHub credential context
unavailable` hid configuration, transport, and capability errors. New
diagnostics identify these categories without credential values.

**Additional context:** Refs #13005 and #13022. Dependency provisioning
is addressed separately in #13093.

## What Changed

- Prefer healthy eligible grants and retry credential acquisition once
for the same principal and account before starting an operation.
- Preserve host Git configuration only when managed access is
unconfigured on a standard-trust local or SSH target.
- Project authentication mode and validated Git metadata into native
runner boundaries; refresh resumed provider settings when modes change.
- Enable network access through an explicit standard-trust controller
decision, independently of GitHub. Omitted or restricted decisions stay
disabled; replace warm providers when that decision changes.
- Run local Git with cleared credentials when the managed broker fails,
with specific redacted diagnostics.
- Retry access-refresh conflicts once without treating concurrency as
expired authorization.
- Show retry instead of reconnect for transient GitHub health failures.
Add optional authorization and run-diagnostic fields without a database
migration.

## Verification

- All latest-head CI gates are green, including typecheck, general and
serialized suites, browser tests, canary, native runner verification,
and build. Greptile is 5/5 with no remaining findings; the security scan
passed.
- Full recursive typecheck and build passed. UI token gates passed.
- Full general server run: 7,110 passed, one transient socket hangup;
that file passed on retry. All remaining workspace groups passed,
including 5,552 UI and 478 CLI tests. The complete serialized rerun
passed all 144 suites / 2,179 tests after the initial isolated timeout
passed on retry.
- 195 final launcher and native session tests passed, including
host/managed transitions, local/remote warm network-policy changes,
broker rotation, and attempts to override validated controller
filesystem roots.
- GitHub gateway fallback, duplicate connection selection, refresh
conflicts, per-user reauthorization, and native transport/security
suites passed.
- Additional live native fixtures passed SSH public-key authentication
and a Git credential helper in fresh and resumed host-mode sessions. An
unwritable managed configuration directory preserved local Git (exit 0)
while GitHub CLI failed with `configuration_directory_unavailable` (exit
4). The temporary SSH listener and keys were removed.
- Applicable Rust suites passed except two timing failures under load;
each failed case passed in isolation. The final environment contract
test passed.
- Linux native runner acceptance passed in both managed and legacy host
modes: DNS, HTTPS, npm package download, fresh-worktree Git status,
authenticated GitHub user lookup, repository read, and a new run
continuing the same provider conversation. Managed broker outage
preserved local Git and rejected authenticated access without host
fallback.
- Matching Linux server/runner artifacts and the separate provisioning
repair are deployed to the development instance. A fresh UI-dispatched
task and a new run after a server restart both passed all six shell
checks through the live controller and credential broker. Both runs
selected the expected healthy connection/grant and retained the same
provider conversation. Neither connection was repaired or reconnected.

The sandbox roots are assigned from the validated execution-target probe
**after** ordinary bindings are merged. Regression coverage supplies
forged roots and verifies they cannot override the controller paths.
Networking is enabled only for an explicit
`PAPERCLIP_RUNNER_NETWORK_ACCESS=enabled` controller decision; omitted
values remain disabled.

## Risks

Unconfigured standard-trust local and SSH runs regain access to host Git
authentication resources. Managed, sandbox, plugin, and low-trust runs
do not gain this fallback. Revoked managed access never falls back to
another account. Deploy server and runner artifacts together;
already-started operations retain their captured identity. An
unauthenticated command can still fail when it requires GitHub access.

## Model Used

OpenAI GPT-6 through Codex, with code editing, shell execution, tests,
and browser inspection. The exact model variant and context-window size
are not exposed in this session.

## 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>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-09 10:15:10 -05:00
1 parent 2ceb630b6c
commit 82f662656a
29 files changed
+870 -169

No files matched your search

@@ -73,6 +73,29 @@ const support = await getEmbeddedPostgresTestSupport();
expect((await resolveGitHubOperationCredentials(db,input)).reason).toMatch(/More than one/);
await expect(resolveGitHubOperationCredentials(db,{...input,companyId:randomUUID()})).rejects.toThrow();
});
it.each([true, false])("prefers the healthy duplicate regardless of grant age (%s)", async (healthyNewer) => {
const input = await seed();
const healthy = await grant(input, "A");
const broken = await grant(input, "A");
await db.update(toolConnections).set({ healthStatus: "ok" }).where(eq(toolConnections.id, healthy.connectionId));
await db.update(toolConnections).set({ healthStatus: "error", healthMessage: "GitHub access changed during refresh. Try again." }).where(eq(toolConnections.id, broken.connectionId));
await db.update(connectionGrants).set({ createdAt: new Date(healthyNewer ? "2026-02-01" : "2026-01-01") }).where(eq(connectionGrants.id, healthy.id));
await db.update(connectionGrants).set({ createdAt: new Date(healthyNewer ? "2026-01-01" : "2026-02-01") }).where(eq(connectionGrants.id, broken.id));
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({
status: "available", connectionId: healthy.connectionId, grantId: healthy.id, authenticationMode: "managed",
});
});
it("retries credential acquisition once using another grant for the same account", async () => {
const input = await seed();
const older = await grant(input, "A");
const newer = await grant(input, "A");
await db.update(connectionGrants).set({ createdAt: new Date("2026-01-01") }).where(eq(connectionGrants.id, older.id));
await db.update(connectionGrants).set({ createdAt: new Date("2026-02-01") }).where(eq(connectionGrants.id, newer.id));
vault.resolveUserSecretValue.mockRejectedValueOnce(new Error("secret provider failed"));
expect(await resolveGitHubOperationCredentials(db, input)).toMatchObject({ status: "available", grantId: older.id });
});
it("uses one stable grant when the same person connects the same GitHub account twice", async () => {
const input = await seed();
const first = await grant(input, "A");
@@ -194,6 +194,7 @@ describe("resolveExecutionRunAdapterConfig", () => {
environmentId: "environment-1",
environmentEnv: {
PAPERCLIP_API_KEY: "environment-api-key",
PAPERCLIP_RUNNER_NETWORK_ACCESS: "enabled",
PAPERCLIP_CLOUD_PROVIDER_TOKEN_ENV: "environment-cloud",
ENV_ONLY: "environment-only",
},
@@ -250,6 +251,7 @@ describe("resolveExecutionRunAdapterConfig", () => {
ROUTINE_ONLY: "routine-only",
});
expect(JSON.stringify(result.resolvedConfig.env)).not.toContain("PAPERCLIP_API_KEY");
expect(JSON.stringify(result.resolvedConfig.env)).not.toContain("PAPERCLIP_RUNNER_NETWORK_ACCESS");
});
it("skips project env resolution when the project has no bindings", async () => {
@@ -5156,7 +5156,27 @@ describeEmbeddedPostgres("tool access service", () => {
}
}, 15_000);
it.each(["none", "event", "same-time-refresh"])("binds a managed GitHub identity and protects refresh from concurrent access changes (%s)", async (concurrentChange) => {
it("reports GitHub reauthorization for the viewer without borrowing another user's grant", async () => {
const company = await createCompany(db);
const [application] = await db.insert(toolApplications).values({ companyId: company.id,
name: "GitHub authorization fixture", type: "mcp_http", status: "active" }).returning();
const [connection] = await db.insert(toolConnections).values({ companyId: company.id,
applicationId: application!.id, name: "GitHub authorization fixture", uid: randomUUID(),
transport: "mcp_remote", status: "active", enabled: true, credentialPolicy: "per_user",
createdByUserId: "A", config: { sourceTemplateKey: "github" },
}).returning();
await db.insert(connectionGrants).values(["A", "B"].map(user => ({ companyId: company.id,
connectionId: connection!.id, kind: "user" as const, subjectUserId: user,
status: user === "A" ? "revoked" as const : "active" as const, credentialSecretRefs: [],
})));
const service = createTestToolAccessService(db);
expect((await service.getConnection(connection!.id, company.id, "A")).requiresReauthorization).toBe(true);
expect((await service.getConnection(connection!.id, company.id, "B")).requiresReauthorization).toBe(false);
expect((await service.listConnections(company.id, "A"))[0]?.requiresReauthorization).toBe(true);
expect((await service.listConnections(company.id, "B"))[0]?.requiresReauthorization).toBe(false);
});
it.each(["none", "event", "same-time-refresh", "one-conflict"])("binds a managed GitHub identity and protects refresh from concurrent access changes (%s)", async (concurrentChange) => {
const company = await createCompany(db);
const userId = `github-manager-${randomUUID()}`;
await grantBoardUser(db, company.id, userId, [], "owner");
@@ -5284,6 +5304,7 @@ describeEmbeddedPostgres("tool access service", () => {
vi.mocked(connector.setWebhookBinding).mockClear();
if (concurrentChange !== "none") {
beforeRepositoryResponse = async () => {
if (concurrentChange === "one-conflict") beforeRepositoryResponse = async () => {};
const [latest] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant!.id));
await db.update(connectionGrants).set({ providerTenant: {
...latest!.providerTenant,
@@ -5298,6 +5319,15 @@ describeEmbeddedPostgres("tool access service", () => {
},
} }).where(eq(connectionGrants.id, grant!.id));
};
if (concurrentChange === "one-conflict") {
await expect(service.checkHealth(connected.connectionId, actor))
.resolves.toMatchObject({ connection: { healthStatus: "ok" } });
expect(connector.setWebhookBinding).toHaveBeenCalled();
const [latest] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant!.id));
expect(latest?.status).toBe("active");
expect(latest?.providerTenant?.github?.repositoryCount).toBe(3);
return;
}
await expect(service.checkHealth(connected.connectionId, actor))
.rejects.toThrow("GitHub access changed during refresh. Try again.");
const [latest] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant!.id));
@@ -1487,6 +1487,62 @@ describeEmbeddedPostgres("tool gateway service", () => {
expect(resolvedGrants).toHaveLength(3);
});
it.each([false, true])("reselects a duplicate only before GitHub dispatch (upstream failure: %s)", async (upstreamFailure) => {
const { company, agent, issue, run } = await createRunFixture(db);
const first = await createRemoteMcpToolFixture(db, company.id);
await db.update(toolApplications).set({ name: "Older GitHub" }).where(eq(toolApplications.id, first.application.id));
const fixtures = [first, await createRemoteMcpToolFixture(db, company.id)];
const grants = [];
for (const [index, { connection }] of fixtures.entries()) {
const secret = await secretService(db).create(company.id, {
provider: "local_encrypted", name: `GitHub ${index}`, key: `github.${randomUUID()}`, value: `token-${index}`,
});
await db.insert(companySecretBindings).values({ companyId: company.id, secretId: secret.id,
targetType: "tool_connection", targetId: connection.id, configPath: "oauth.access_token" });
await db.update(toolConnections).set({ authKind: "oauth", credentialSource: "paperclip_vault",
config: { ...connection.config, sourceTemplateKey: "github" },
}).where(eq(toolConnections.id, connection.id));
await db.insert(toolConnectionInstalls).values({ companyId: company.id,
connectionId: connection.id, targetType: "agent", targetId: agent.id });
const [grant] = await db.insert(connectionGrants).values({ companyId: company.id,
connectionId: connection.id, kind: "agent", subjectAgentId: agent.id, status: "active",
createdAt: new Date(index === 0 ? "2026-01-01" : "2026-02-01"),
credentialSecretRefs: [{ secretId: secret.id, configPath: "oauth.access_token", versionSelector: "latest" }],
providerTenant: { github: { userId: "42", login: "octocat", installationCount: 1,
repositoryCount: 1, repositorySelection: "all", installationIds: ["101"] } },
}).returning();
grants.push(grant!);
}
await initializeRunIdentity(db, { companyId: company.id, runId: run.id, issueId: issue.id,
responsibleUserId: "A", cause: "instruction" });
await db.insert(toolPolicies).values({ companyId: company.id, name: "Allow reads",
policyType: "allow", selectors: { riskLevel: "read" } });
const refreshed: string[] = [];
const dispatched = vi.fn(async (_url: string, init: RequestInit) => {
expect(new Headers(init.headers).get("authorization")).toBe(`Bearer token-${upstreamFailure ? 1 : 0}`);
return new Response(JSON.stringify({ jsonrpc: "2.0", id: JSON.parse(String(init.body)).id,
result: { content: [{ type: "text", text: "ok" }] } }),
{ status: upstreamFailure ? 500 : 200, headers: { "content-type": "application/json" } });
});
const gateway = createTestToolGatewayService(db, {
oauthGrantRefresher: async ({ grantId }) => {
refreshed.push(grantId);
if (!upstreamFailure && grantId === grants[1]!.id) {
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, grantId));
throw new Error("refresh invalidated the selected authorization");
}
return grants.find(grant => grant.id === grantId)!;
}, remoteHttpRequest: dispatched,
});
const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });
const tool = (await gateway.listToolsForSession(session.token)).find(t => t.providerType === "mcp_remote_http")!;
const execution = gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: {} });
if (upstreamFailure) await expect(execution).rejects.toMatchObject({ status: 502 });
else expect((await execution).status).toBe("completed");
expect(dispatched).toHaveBeenCalledTimes(1);
expect(refreshed).toEqual(upstreamFailure ? [grants[1]!.id] : [grants[1]!.id, grants[0]!.id]);
});
it("refreshes a customer OAuth grant once and retries after an upstream 401", async () => {
const { company, agent, run } = await createRunFixture(db);
const { connection } = await createRemoteMcpToolFixture(db, company.id);
+2 -2
View File
@@ -1598,7 +1598,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
assertBoard(req);
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
const connections = await svc.listConnections(companyId);
const connections = await svc.listConnections(companyId, req.actor.userId);
const canManageConnections = await isToolConnectionManagerQuiet(req, companyId);
res.json({
connections: filterVisibleToolConnections(connections, {
@@ -1638,7 +1638,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
const connection = await getAccessibleResource(
req,
res,
svc.getConnection(req.params.connectionId as string),
svc.getConnection(req.params.connectionId as string, undefined, req.actor.userId),
"Tool connection not found",
);
if (!connection) return;
+113 -77
View File
@@ -51,6 +51,8 @@ export type GitCredential = {
secretName: string | null;
githubIdentity?: { userId: string; login: string };
identitySource?: "personal" | "dedicated";
connectionId?: string;
grantId?: string;
};
/** A prepared, credential-bearing git invocation: config args plus the env that carries the token. */
@@ -272,6 +274,10 @@ export function createGitRemoteAuthProvider(
const result = await resolveGitHubOperationCredentials(db, {
companyId, runId: context.heartbeatRunId, agentId: context.agentId,
});
if (result.status === "absent") {
const credential = await resolveCredential();
return credential ? buildGitAuthInvocation(credential) : null;
}
const anonymous = buildGitAuthInvocation({ token: "", source: "managed_connection", secretName: null });
return { ...anonymous, env: {
...anonymous.env, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_SYSTEM: "/dev/null",
@@ -294,6 +300,7 @@ export async function resolveManagedGitHubIdentitySelection(
responsibleUserId?: string | null;
agentId?: string | null;
allowStandingDelegation?: boolean;
excludeGrantId?: string;
},
): Promise<{
configured: boolean;
@@ -400,14 +407,20 @@ export async function resolveManagedGitHubIdentitySelection(
grant.status === "active" && hasCredentialRecord(grant) && githubConnections.some((connection) =>
connection.id === grant.connectionId && connection.enabled && connection.status === "active",
);
// Prefer an available authorization for this same account, then the newest
// Prefer an available, healthy authorization for this account, then the newest
// connection grant. Do not rank by updatedAt: refreshes/webhooks change it.
// Select one grant, preserving its credential and connection policy intact.
const grant = [...candidates].sort((a, b) =>
const healthRank = (candidate: typeof connectionGrants.$inferSelect) => {
const health = githubConnections.find((connection) => connection.id === candidate.connectionId)?.healthStatus;
return health === "ok" || health === "healthy" ? 2 : health === "unknown" ? 1 : 0;
};
const grant = candidates.filter((candidate) => candidate.id !== context.excludeGrantId).sort((a, b) =>
Number(isAvailable(b)) - Number(isAvailable(a))
|| healthRank(b) - healthRank(a)
|| b.createdAt.getTime() - a.createdAt.getTime()
|| a.id.localeCompare(b.id),
)[0]!;
if (!grant) return { configured: true, identitySource, error: "No alternative managed GitHub authorization is available" };
const connection = githubConnections.find((candidate) => candidate.id === grant.connectionId);
if (!connection?.enabled || connection.status !== "active") {
return { configured: true, identitySource, error: "The managed GitHub connection is unavailable" };
@@ -463,81 +476,104 @@ export async function resolveManagedGitHubCredential(
const selection = await resolveManagedGitHubIdentitySelection(db, companyId, context);
if (!selection.configured) return { configured: false };
if (!selection.grant) return { configured: true, identitySource: selection.identitySource, error: selection.error };
let grant = selection.grant;
if (grant.kind === "user" && grant.subjectUserId) {
const [membership] = await db.select({ id: companyMemberships.id, role: companyMemberships.membershipRole }).from(companyMemberships).where(and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, grant.subjectUserId),
eq(companyMemberships.status, "active"),
)).limit(1);
if (!membership || membership.role === "viewer") return { configured: true, identitySource: selection.identitySource, error: "The managed GitHub identity owner is not an authorized company member" };
}
const expiresAt = grant.providerTenant?.oauth?.accessTokenExpiresAt;
const refreshedAt = grant.providerTenant?.oauth?.refreshedAt;
const expiryMs = typeof expiresAt === "string" ? Date.parse(expiresAt) : Number.NaN;
const refreshedMs = typeof refreshedAt === "string" ? Date.parse(refreshedAt) : Number.NaN;
if (Number.isFinite(expiryMs) && (
expiryMs <= Date.now() + 60 * 60_000
|| !Number.isFinite(refreshedMs)
|| refreshedMs <= Date.now() - 30 * 24 * 60 * 60_000
)) {
grant = await toolAccessService(db).refreshOAuthGrantCredentials({
companyId,
connectionId: grant.connectionId,
grantId: grant.id,
actor: { actorType: "system", actorId: "workspace-git-credential" },
issueId: context.issueId,
heartbeatRunId: context.heartbeatRunId,
});
}
const accessRef = grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.access_token");
const github = grant.providerTenant?.github;
if (!accessRef || !github) return { configured: true, identitySource: selection.identitySource, error: "The managed GitHub identity is incomplete" };
if (github.installationCount < 1 || github.repositoryCount < 1) {
return { configured: true, identitySource: selection.identitySource, error: "The managed GitHub identity no longer has repository access" };
}
const accessContext = {
consumerType: "system" as const,
consumerId: "workspace-git-credential",
actorType: "system" as const,
actorId: context.agentId ?? undefined,
issueId: context.issueId ?? null,
heartbeatRunId: context.heartbeatRunId ?? null,
responsibleUserId: context.responsibleUserId ?? null,
};
let token: string;
if (grant.kind === "user") {
if (!grant.subjectUserId || !secrets.resolveUserSecretValue) {
return { configured: true, identitySource: selection.identitySource, error: "The personal GitHub credential cannot be resolved" };
const acquire = async (selection: Awaited<ReturnType<typeof resolveManagedGitHubIdentitySelection>>) => {
let grant = selection.grant!;
if (grant.kind === "user" && grant.subjectUserId) {
const [membership] = await db.select({ id: companyMemberships.id, role: companyMemberships.membershipRole }).from(companyMemberships).where(and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, grant.subjectUserId),
eq(companyMemberships.status, "active"),
)).limit(1);
if (!membership || membership.role === "viewer") return { configured: true, identitySource: selection.identitySource, error: "The managed GitHub identity owner is not an authorized company member" };
}
const [secret] = await db.select({
userSecretDefinitionId: companySecrets.userSecretDefinitionId,
}).from(companySecrets).where(and(
eq(companySecrets.companyId, companyId),
eq(companySecrets.id, accessRef.secretId),
eq(companySecrets.ownerUserId, grant.subjectUserId),
)).limit(1);
if (!secret?.userSecretDefinitionId) return { configured: true, identitySource: selection.identitySource, error: "The personal GitHub credential is invalid" };
const resolved = await secrets.resolveUserSecretValue(companyId, {
definitionId: secret.userSecretDefinitionId,
responsibleUserId: grant.subjectUserId,
version: accessRef.versionSelector ?? "latest",
required: true,
}, accessContext);
if (!resolved) return { configured: true, identitySource: selection.identitySource, error: "The personal GitHub credential is missing" };
token = resolved.value;
} else {
token = await secrets.resolveSecretValue(companyId, accessRef.secretId, accessRef.versionSelector ?? "latest", { accessContext });
}
return {
configured: true, identitySource: selection.identitySource,
credential: {
token,
source: "managed_connection",
secretName: null,
githubIdentity: { userId: github.userId, login: github.login },
identitySource: grant.kind === "agent" ? "dedicated" : "personal",
},
const expiresAt = grant.providerTenant?.oauth?.accessTokenExpiresAt;
const refreshedAt = grant.providerTenant?.oauth?.refreshedAt;
const expiryMs = typeof expiresAt === "string" ? Date.parse(expiresAt) : Number.NaN;
const refreshedMs = typeof refreshedAt === "string" ? Date.parse(refreshedAt) : Number.NaN;
if (Number.isFinite(expiryMs) && (
expiryMs <= Date.now() + 60 * 60_000
|| !Number.isFinite(refreshedMs)
|| refreshedMs <= Date.now() - 30 * 24 * 60 * 60_000
)) {
grant = await toolAccessService(db).refreshOAuthGrantCredentials({
companyId,
connectionId: grant.connectionId,
grantId: grant.id,
actor: { actorType: "system", actorId: "workspace-git-credential" },
issueId: context.issueId,
heartbeatRunId: context.heartbeatRunId,
});
}
const accessRef = grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.access_token");
const github = grant.providerTenant?.github;
if (!accessRef || !github) return { configured: true, identitySource: selection.identitySource, error: "The managed GitHub identity is incomplete" };
if (github.installationCount < 1 || github.repositoryCount < 1) {
return { configured: true, identitySource: selection.identitySource, error: "The managed GitHub identity no longer has repository access" };
}
const accessContext = {
consumerType: "system" as const,
consumerId: "workspace-git-credential",
actorType: "system" as const,
actorId: context.agentId ?? undefined,
issueId: context.issueId ?? null,
heartbeatRunId: context.heartbeatRunId ?? null,
responsibleUserId: context.responsibleUserId ?? null,
};
let token: string;
if (grant.kind === "user") {
if (!grant.subjectUserId || !secrets.resolveUserSecretValue) {
return { configured: true, identitySource: selection.identitySource, error: "The personal GitHub credential cannot be resolved" };
}
const [secret] = await db.select({
userSecretDefinitionId: companySecrets.userSecretDefinitionId,
}).from(companySecrets).where(and(
eq(companySecrets.companyId, companyId),
eq(companySecrets.id, accessRef.secretId),
eq(companySecrets.ownerUserId, grant.subjectUserId),
)).limit(1);
if (!secret?.userSecretDefinitionId) return { configured: true, identitySource: selection.identitySource, error: "The personal GitHub credential is invalid" };
const resolved = await secrets.resolveUserSecretValue(companyId, {
definitionId: secret.userSecretDefinitionId,
responsibleUserId: grant.subjectUserId,
version: accessRef.versionSelector ?? "latest",
required: true,
}, accessContext);
if (!resolved) return { configured: true, identitySource: selection.identitySource, error: "The personal GitHub credential is missing" };
token = resolved.value;
} else {
token = await secrets.resolveSecretValue(companyId, accessRef.secretId, accessRef.versionSelector ?? "latest", { accessContext });
}
return {
configured: true, identitySource: selection.identitySource,
credential: {
token,
source: "managed_connection" as const,
secretName: null,
githubIdentity: { userId: github.userId, login: github.login },
identitySource: grant.kind === "agent" ? "dedicated" as const : "personal" as const,
connectionId: grant.connectionId,
grantId: grant.id,
},
};
};
let failure: { configured: boolean; identitySource?: "personal" | "dedicated"; error?: string };
try {
const result = await acquire(selection);
if (result.credential) return result;
failure = result;
} catch {
failure = { configured: true, identitySource: selection.identitySource, error: "GitHub credentials are temporarily unavailable" };
}
// Retry credential acquisition, never the GitHub operation. An alternate
// authorization must still belong to this exact principal and account.
const alternate = await resolveManagedGitHubIdentitySelection(db, companyId, {
...context, excludeGrantId: selection.grant.id,
});
const accountId = selection.grant.providerTenant?.github?.userId;
if (!accountId || !alternate.grant || alternate.identitySource !== selection.identitySource
|| alternate.grant.providerTenant?.github?.userId !== accountId
|| alternate.grant.subjectUserId !== selection.grant.subjectUserId
|| alternate.grant.subjectAgentId !== selection.grant.subjectAgentId) return failure;
try { return await acquire(alternate); } catch { return failure; }
}
@@ -10,6 +10,9 @@ export type GitHubCredentialSummary = {
source?: "personal" | "dedicated";
login?: string;
reason?: string;
connectionId?: string;
grantId?: string;
authenticationMode?: "managed" | "host" | "anonymous";
};
/** No company secrets or ambient credentials are consulted by this path. */
@@ -28,7 +31,7 @@ export async function resolveGitHubOperationCredentials(db: Db, input: {
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 };
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" };
+40 -15
View File
@@ -8,7 +8,7 @@ import { buildExecutionContinuation } from "./execution-continuation.js";
import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils";
import { initializeRunIdentity } from "./run-identity.js";
import { githubBrokerEnvironment } from "@paperclipai/adapter-utils/github-launcher";
import { cleanupGitHubOperationLaunchers, prepareGitHubOperationLaunchers, startAdapterExecutionTargetPaperclipBridge } from "@paperclipai/adapter-utils/execution-target";
import { cleanupGitHubOperationLaunchers, prepareGitHubOperationLaunchers, prepareGitHubExecutionEnvironment, startAdapterExecutionTargetPaperclipBridge } from "@paperclipai/adapter-utils/execution-target";
import { agentService } from "./agents.js";
import { normalizeLegacyRunnerProvider } from "@paperclipai/adapter-utils";
import fs from "node:fs/promises";
@@ -115,6 +115,7 @@ import { incrementToolRuntimeMetricCounter } from "./tool-runtime-metrics.js";
import { logger } from "../middleware/logger.js";
import {
createGitRemoteAuthProvider,
resolveManagedGitHubIdentitySelection,
describeGitAuthFailure,
filterResolvedGitHubConnectionsForRun,
scrubGitCredentialText,
@@ -1261,7 +1262,12 @@ const LOW_TRUST_SENSITIVE_ENV_KEY_RE =
// binding; adapters enforce this at env-merge time.
// 3. Any other PAPERCLIP_*-named binding is user data and flows through to
// the run env like any non-prefixed binding.
const FORBIDDEN_ENV_BINDING_KEYS = new Set(["PAPERCLIP_API_KEY"]);
const FORBIDDEN_ENV_BINDING_KEYS = new Set([
"PAPERCLIP_RUNNER_NETWORK_ACCESS", "PAPERCLIP_RUNNER_NETWORK_ROOTS",
"PAPERCLIP_API_KEY", "PAPERCLIP_GITHUB_AUTH_MODE", "PAPERCLIP_GITHUB_HOST_HOME",
"PAPERCLIP_GIT_METADATA_ROOTS", "PAPERCLIP_GITHUB_BROKER_TOKEN", "PAPERCLIP_GITHUB_BROKER_URL",
"PAPERCLIP_GITHUB_BRIDGE_TOKEN", "PAPERCLIP_GITHUB_LAUNCHER_DIR",
]);
const MANAGED_GITHUB_TOKEN_KEYS = new Set([
"GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN", "PAPERCLIP_GIT_TOKEN",
]);
@@ -18299,9 +18305,14 @@ export function heartbeatService(
!acceptedPlanWakeRoutingDecision?.suppressAcceptedContinuation
? [...runScopedMentionedSkillKeys, ACCEPTED_PLAN_CONVERSION_SKILL_KEY]
: runScopedMentionedSkillKeys;
const githubSelection = await resolveManagedGitHubIdentitySelection(db, agent.companyId, {
agentId: agent.id, responsibleUserId, allowStandingDelegation: false,
});
const useHostGitHub = !githubSelection.configured && trustPreset.kind === "standard"
&& ["local", "ssh"].includes(selectedEnvironmentForConfig?.driver ?? "local");
const { resolvedConfig, secretKeys, secretManifest } =
await resolveExecutionRunAdapterConfig({
managedGitHubCredentials: true,
managedGitHubCredentials: !useHostGitHub,
companyId: agent.companyId,
agentId: agent.id,
adapterType: agent.adapterType,
@@ -19264,19 +19275,33 @@ export function heartbeatService(
} else {
delete context.paperclipScratch;
}
const githubBrokerToken = createRuntimeToolsToken({
agentId: agent.id, companyId: agent.companyId, runId: run.id,
responsibleUserId: responsibleUserId ?? "", scope: "github_credentials",
const gitExecutionEnv = await prepareGitHubExecutionEnvironment({
target: executionTarget, cwd: executionWorkspace.cwd,
env: Object.fromEntries(Object.entries(parseObject(runtimeConfig.env)).filter((entry): entry is [string, string] => typeof entry[1] === "string")),
hostCredentials: useHostGitHub,
// Networking is a controller-owned trust decision, independent of
// whether GitHub is configured or a credential can be acquired.
networkAccess: trustPreset.kind === "standard"
&& process.env.PAPERCLIP_RUNNER_NETWORK_ACCESS !== "disabled",
});
const githubBrokerEnv = githubBrokerEnvironment(parseObject(runtimeConfig.env), {
url: configuredPaperclipApiBaseUrl() ?? "", token: githubBrokerToken?.token ?? "",
});
githubLauncherLocation = { runId: run.id, target: executionTarget };
runtimeConfig = { ...runtimeConfig, env: await prepareGitHubOperationLaunchers({
runId: run.id, target: executionTarget, cwd: executionWorkspace.cwd,
env: githubBrokerEnv,
}) };
secretKeys.add("PAPERCLIP_GITHUB_BROKER_TOKEN");
runtimeConfig = { ...runtimeConfig, env: gitExecutionEnv };
for (const key of MANAGED_GITHUB_TOKEN_KEYS) secretKeys.add(key);
context.githubAuthenticationMode = useHostGitHub ? "host" : "managed";
if (!useHostGitHub) {
const githubBrokerToken = createRuntimeToolsToken({
agentId: agent.id, companyId: agent.companyId, runId: run.id,
responsibleUserId: responsibleUserId ?? "", scope: "github_credentials",
});
const githubBrokerEnv = githubBrokerEnvironment(gitExecutionEnv, {
url: configuredPaperclipApiBaseUrl() ?? "", token: githubBrokerToken?.token ?? "",
});
githubLauncherLocation = { runId: run.id, target: executionTarget };
runtimeConfig = { ...runtimeConfig, env: await prepareGitHubOperationLaunchers({
runId: run.id, target: executionTarget, cwd: executionWorkspace.cwd,
env: githubBrokerEnv,
}) };
secretKeys.add("PAPERCLIP_GITHUB_BROKER_TOKEN");
}
context.paperclipEnvironment = {
id: selectedEnvironment.id,
name: selectedEnvironment.name,
@@ -3404,11 +3404,18 @@ describe("native warm session supervision", () => {
expect(close).not.toHaveBeenCalled();
});
it.each([false, true].flatMap((useBroker) =>
it.each([...[false, true].flatMap((useBroker) =>
[false, true].flatMap((projectless) =>
[false, true].map((local) => ({ useBroker, projectless, local })),
[false, true].map((local) => ({ useBroker, projectless, local, firstMode: "host", secondMode: "host" })),
),
))("verifies a live warm owner before refreshing run authority (broker: $useBroker, projectless: $projectless, local: $local)", async ({ useBroker, projectless, local }) => {
), ...["host", "managed"].flatMap((firstMode) => [false, true].map((local) => ({
useBroker: false, projectless: false, local, firstMode,
secondMode: firstMode === "host" ? "managed" : "host",
}))), ...[false, true].flatMap((local) => [
{ useBroker: false, projectless: false, local, firstMode: "host", secondMode: "host", firstNetwork: "enabled", secondNetwork: "disabled" },
{ useBroker: false, projectless: false, local, firstMode: "managed", secondMode: "managed", firstNetwork: "disabled", secondNetwork: "enabled" },
])].map((scenario) => ({ firstNetwork: "disabled", secondNetwork: "disabled", ...scenario })))("verifies a live warm owner before refreshing run authority (broker: $useBroker, projectless: $projectless, local: $local, auth: $firstMode -> $secondMode, network: $firstNetwork -> $secondNetwork)", async ({ useBroker, projectless, local, firstMode, secondMode, firstNetwork, secondNetwork }) => {
const replacesProvider = useBroker || firstMode !== secondMode || firstNetwork !== secondNetwork;
const stateBase = await mkdtemp(
join(tmpdir(), "paperclip-runnerd-warm-authority-"),
);
@@ -3489,7 +3496,7 @@ describe("native warm session supervision", () => {
return result;
})
.mockImplementationOnce(async (options) => {
if (useBroker) {
if (replacesProvider) {
expect(options.existingSession).toBeUndefined();
expect(options.persistedSession?.providerSessionId).toBe("provider-runnerd-warm");
expect(options.persistedSession?.semanticResult).toBeNull();
@@ -3506,7 +3513,7 @@ describe("native warm session supervision", () => {
await executePaperclipNativeSession({
db: leaseDb(first),
execution: first,
runnerEnvironment: useBroker ? { PAPERCLIP_GITHUB_BROKER_TOKEN: "first-run-capability" } : undefined,
runnerEnvironment: { PAPERCLIP_GITHUB_AUTH_MODE: firstMode, PAPERCLIP_RUNNER_NETWORK_ACCESS: firstNetwork, ...(useBroker ? { PAPERCLIP_GITHUB_BROKER_TOKEN: "first-run-capability" } : {}) },
runnerInstanceId: "runner-runnerd-warm",
useRunnerd: true,
runnerExecutionTarget: remoteTarget,
@@ -3577,12 +3584,12 @@ describe("native warm session supervision", () => {
await executePaperclipNativeSession({
db: continuationDb,
execution: second,
runnerEnvironment: useBroker ? { PAPERCLIP_GITHUB_BROKER_TOKEN: "second-run-capability" } : undefined,
runnerEnvironment: { PAPERCLIP_GITHUB_AUTH_MODE: secondMode, PAPERCLIP_RUNNER_NETWORK_ACCESS: secondNetwork, ...(useBroker ? { PAPERCLIP_GITHUB_BROKER_TOKEN: "second-run-capability" } : {}) },
runnerInstanceId: "runner-runnerd-warm",
useRunnerd: true,
runnerExecutionTarget: remoteTarget,
});
if (useBroker) {
if (replacesProvider) {
expect(firstClose).toHaveBeenCalledOnce();
expect(firstClose).toHaveBeenCalledWith({ reason: "warm native session configuration changed" });
} else {
@@ -273,6 +273,8 @@ function clearNativeRuntimeRequestResolutions(runId: string): void {
type WarmNativeSession = {
credentialRunId?: string;
githubAuthenticationMode?: string;
networkAccess: boolean;
session: NativeSession;
ownerToken: symbol;
configDigest: string;
@@ -4727,7 +4729,9 @@ async function executePaperclipNativeSessionWithinScope(
// settled provider checkpoint retains the conversation across runs.
const credentialRunChanged = Boolean(input.runnerEnvironment?.PAPERCLIP_GITHUB_BROKER_TOKEN)
&& entry.credentialRunId !== input.execution.binding.runId;
if (entry.configDigest !== warmConfigDigest || credentialRunChanged) {
if (entry.configDigest !== warmConfigDigest || credentialRunChanged
|| entry.githubAuthenticationMode !== input.runnerEnvironment?.PAPERCLIP_GITHUB_AUTH_MODE
|| entry.networkAccess !== (input.runnerEnvironment?.PAPERCLIP_RUNNER_NETWORK_ACCESS === "enabled")) {
if (entry.busy) throw new Error("native_session_supervisor_busy");
if (entry.idleTimer !== null) clearTimeout(entry.idleTimer);
warmNativeSessions.delete(warmSessionId);
@@ -4982,6 +4986,8 @@ async function executePaperclipNativeSessionWithinScope(
existing.session = session;
} else
warmNativeSessions.set(warmSessionId, {
githubAuthenticationMode: input.runnerEnvironment?.PAPERCLIP_GITHUB_AUTH_MODE,
networkAccess: input.runnerEnvironment?.PAPERCLIP_RUNNER_NETWORK_ACCESS === "enabled",
credentialRunId: input.runnerEnvironment?.PAPERCLIP_GITHUB_BROKER_TOKEN
? input.execution.binding.runId : undefined,
session,
+40 -2
View File
@@ -5435,6 +5435,22 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
return localTools(connection);
}
async function annotateGitHubAuthorization(connections: ToolConnection[], viewerUserId?: string) {
const github = connections.filter((connection) => asRecord(connection.config).sourceTemplateKey === "github");
if (!github.length) return;
const grants = await db.select({ connectionId: connectionGrants.connectionId, status: connectionGrants.status, kind: connectionGrants.kind, subjectUserId: connectionGrants.subjectUserId })
.from(connectionGrants).where(and(
eq(connectionGrants.companyId, github[0].companyId),
inArray(connectionGrants.connectionId, github.map((connection) => connection.id)),
));
for (const connection of github) {
const userId = viewerUserId ?? connection.createdByUserId;
const eligible = grants.filter((grant) => grant.connectionId === connection.id
&& (connection.credentialPolicy !== "per_user" || (grant.kind === "user" && grant.subjectUserId === userId)));
connection.requiresReauthorization = !eligible.some((grant) => grant.status === "active");
}
}
async function updateConnectionHealth(
connection: typeof toolConnections.$inferSelect,
status: ToolConnectionHealthStatus,
@@ -5517,6 +5533,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
});
return { connection: toConnection(updated), runtimeSlot };
} catch (error) {
if (error instanceof HttpError && asRecord(error.details).code === "github_access_changed") throw error;
const failure = sanitizeHttpFailure(error);
const updated = await updateConnectionHealth(connection, failure.status, failure.message);
const runtimeSlot = connection.transport === "local_stdio" ? await ensureRuntimeSlot(updated) : null;
@@ -5557,6 +5574,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
try {
descriptors = await discoverTools(connection, refreshOptions.credentialHeaders, actor);
} catch (error) {
if (error instanceof HttpError && asRecord(error.details).code === "github_access_changed") throw error;
const failure = sanitizeHttpFailure(error);
const updated = await updateConnectionHealth(connection, failure.status, failure.message);
await audit({
@@ -8594,6 +8612,24 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
connection: typeof toolConnections.$inferSelect,
initialGrant: typeof connectionGrants.$inferSelect,
actor?: ActorInfo,
) {
try {
return await refreshManagedGitHubGrantAccessOnce(connection, initialGrant, actor);
} catch (error) {
if (!(error instanceof HttpError) || asRecord(error.details).code !== "github_access_changed") throw error;
const [current] = await db.select().from(connectionGrants).where(and(
eq(connectionGrants.id, initialGrant.id), eq(connectionGrants.companyId, connection.companyId),
eq(connectionGrants.connectionId, connection.id),
));
if (!current || current.status !== "active") throw error;
return refreshManagedGitHubGrantAccessOnce(connection, current, actor);
}
}
async function refreshManagedGitHubGrantAccessOnce(
connection: typeof toolConnections.$inferSelect,
initialGrant: typeof connectionGrants.$inferSelect,
actor?: ActorInfo,
) {
let grant = await refreshOAuthGrantCredentials({
companyId: connection.companyId,
@@ -12495,7 +12531,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
return { repositories: [...repositories.values()].sort((a, b) => a.fullName.localeCompare(b.fullName)), connectionCount, failedConnectionCount };
},
listConnections: async (companyId: string): Promise<ToolConnection[]> => {
listConnections: async (companyId: string, viewerUserId?: string): Promise<ToolConnection[]> => {
const rows = await db
.select()
.from(toolConnections)
@@ -12539,6 +12575,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
for (const connection of connections) {
connection.lastUsedAt = lastUsedByConnection.get(connection.id) ?? null;
}
await annotateGitHubAuthorization(connections, viewerUserId);
return connections;
},
@@ -12616,9 +12653,10 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
return toConnection(row);
},
getConnection: async (connectionId: string, companyId?: string): Promise<ToolConnection> => {
getConnection: async (connectionId: string, companyId?: string, viewerUserId?: string): Promise<ToolConnection> => {
const connection = toConnection(await getConnectionRow(connectionId, companyId));
connection.installs = await listConnectionInstalls(connection.id, connection.companyId);
await annotateGitHubAuthorization([connection], viewerUserId);
return connection;
},
+50 -9
View File
@@ -894,6 +894,12 @@ export function createToolGatewayService(
const interactions = issueThreadInteractionService(db);
const policyService = toolAccessPolicyService(db);
const secrets = secretService(db);
// Authentication produces a new session object for every operation. Keep
// credential acquisition scoped to that object and out of persisted inputs.
const githubOperationCredentials = new WeakMap<ToolGatewaySession, {
grant: typeof connectionGrants.$inferSelect;
headers: Record<string, string>;
}>();
const configuredCloudConnector = options.paperclipCloudConnector ?? options.paperclipIdGmailConnector;
const connectorWasProvided = options.paperclipCloudConnector !== undefined || options.paperclipIdGmailConnector !== undefined;
let cachedCloudConnector = configuredCloudConnector ?? null;
@@ -2066,14 +2072,42 @@ export function createToolGatewayService(
eq(toolConnections.id, tool.connectionId), eq(toolConnections.companyId, session.companyId),
));
if (connection?.config.sourceTemplateKey === "github" || connection?.transportConfig?.sourceTemplateKey === "github") {
const selected = await resolveManagedGitHubIdentitySelection(db, session.companyId, {
let selected = await resolveManagedGitHubIdentitySelection(db, session.companyId, {
agentId: session.agentId, responsibleUserId: session.responsibleUserId, allowStandingDelegation: false,
});
if (!selected.grant) throw new ToolGatewayHttpError(409, selected.error ?? "No GitHub identity connected", "github_identity_unavailable");
const target = connectedTools.find((candidate) => candidate.connectionId === selected.grant!.connectionId
&& candidate.upstreamToolName === tool.upstreamToolName && candidate.providerType === tool.providerType);
if (!target) throw new ToolGatewayHttpError(404, "This GitHub tool is unavailable for the responsible person", "github_tool_unavailable");
return target;
const original = selected.grant;
// Acquire before policy evaluation or dispatch. An alternate connection
// gets its own catalog descriptor and policy checks; never replay a call.
for (let attempt = 0; attempt < 2; attempt += 1) {
const grant = selected.grant!;
const target = connectedTools.find((candidate) => candidate.connectionId === grant.connectionId
&& candidate.upstreamToolName === tool.upstreamToolName && candidate.providerType === tool.providerType);
if (!target) throw new ToolGatewayHttpError(404, "This GitHub tool is unavailable for the responsible person", "github_tool_unavailable");
const [selectedConnection] = await db.select().from(toolConnections).where(and(
eq(toolConnections.id, grant.connectionId), eq(toolConnections.companyId, session.companyId),
));
if (!selectedConnection) throw new ToolGatewayHttpError(409, "GitHub connection is unavailable", "github_identity_unavailable");
if (attempt === 0) await resolveConnectionGrant(session, selectedConnection);
try {
const headers = await resolveCredentialHeaders(session, selectedConnection, grant);
githubOperationCredentials.set(session, { grant, headers });
return target;
} catch (error) {
if (attempt !== 0) throw error;
const alternate = await resolveManagedGitHubIdentitySelection(db, session.companyId, {
agentId: session.agentId, responsibleUserId: session.responsibleUserId,
allowStandingDelegation: false, excludeGrantId: original.id,
});
const accountId = original.providerTenant?.github?.userId;
if (!accountId || !alternate.grant
|| alternate.grant.providerTenant?.github?.userId !== accountId
|| alternate.grant.subjectUserId !== original.subjectUserId
|| alternate.grant.subjectAgentId !== original.subjectAgentId) throw error;
selected = alternate;
}
}
throw new ToolGatewayHttpError(409, "GitHub credentials are unavailable", "github_identity_unavailable");
}
}
return tool;
@@ -2838,10 +2872,14 @@ export function createToolGatewayService(
const tracked = session.identityContextId && (connection.config.sourceTemplateKey === "github"
|| connection.transportConfig?.sourceTemplateKey === "github");
try {
const headers = await resolveCredentialHeadersUnrecorded(session, connection, grant, resolveOptions);
const captured = githubOperationCredentials.get(session);
const headers = !resolveOptions.forceRefresh && captured?.grant.id === grant.id
? captured.headers
: await resolveCredentialHeadersUnrecorded(session, connection, grant, resolveOptions);
if (tracked) await db.update(runIdentityContexts).set({ github: {
status: "available", login: grant.providerTenant?.github?.login,
source: grant.kind === "agent" ? "dedicated" : "personal",
connectionId: connection.id, grantId: grant.id, authenticationMode: "managed",
} }).where(and(eq(runIdentityContexts.id, session.identityContextId!), eq(runIdentityContexts.companyId, session.companyId)));
return headers;
} catch (error) {
@@ -3211,9 +3249,12 @@ export function createToolGatewayService(
if (session.identityContextId && session.agentId && (
connection.config.sourceTemplateKey === "github" || connection.transportConfig?.sourceTemplateKey === "github"
)) {
const selected = await resolveManagedGitHubIdentitySelection(db, session.companyId, {
agentId: session.agentId, responsibleUserId: session.responsibleUserId, allowStandingDelegation: false,
});
const captured = githubOperationCredentials.get(session);
const selected = captured
? { grant: captured.grant, error: undefined }
: await resolveManagedGitHubIdentitySelection(db, session.companyId, {
agentId: session.agentId, responsibleUserId: session.responsibleUserId, allowStandingDelegation: false,
});
if (!selected.grant || selected.grant.connectionId !== connection.id) {
throw new ToolGatewayHttpError(409, selected.error ?? "GitHub identity changed; retry through the managed tool", "github_identity_unavailable");
}