From 0f52d90993cbbb50a5e061883264481a7e8dece7 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:33:31 -0600 Subject: [PATCH] fix(github): detect writes outside GitHub App installations and stop advising Refresh access (#22978) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents use managed GitHub App connections through the tool gateway to open issues, post comments, and perform approved writes on GitHub repositories. > - A GitHub App user-to-server token can write only to repositories inside accounts where the Paperclip GitHub App is installed; even on a public third-party repository, GitHub rejects writes with `403 Resource not accessible by integration`. > - Previously, Paperclip did not check the App's installed accounts before posting an approval card, mapped every `403 Resource not accessible by integration` to `github_access_denied`, and told both the user ("Manage GitHub access") and the agent ("select Refresh access") to repair access through a flow that cannot reach third-party organizations. > - This wastes human approvals on doomed writes and sends operators into a dead-end permission refresh loop. > - This pull request adds a pre-check before posting approval cards for managed GitHub App writes outside installed accounts, distinguishes `github_repo_outside_app_installations` and `github_app_installation_suspended` from `github_access_denied` across server classification, MCP routes, and continuation delivery, and renders accurate UI guidance without a misleading "Manage GitHub access" link for external repositories. > - The benefit is that unreachable external-org writes fail immediately with actionable alternatives (post directly on GitHub, use a PAT connection, or have an org admin install the App and refresh access), suspended installations get explicit unsuspend guidance, and missing repository grants on installed organizations keep the existing "Manage GitHub access" and "Refresh access" repair flow. ## Linked Issues or Issue Description No public issue exists. Refs #19315, #19655, #20141. **What happened?** When an agent requested an approval-gated GitHub write targeting a public repository owned by an external organization where the Paperclip GitHub App was not installed, Paperclip posted a normal approval card. After the user approved it, GitHub returned `403 Resource not accessible by integration`, and both the failed approval card and agent continuation instructions advised clicking "Manage GitHub access" and "Refresh access", which cannot grant write access to a third-party organization. **Expected behavior** Paperclip should check managed GitHub App write targets against the grant's installed accounts before posting an approval card, fail unreachable external-organization writes cleanly without wasting an approval, preserve suspended installations separately with unsuspend guidance, keep incomplete webhook-invalidated snapshots on `github_access_denied` until refreshed, and present accurate alternatives in both the UI card and agent continuation instructions. **Steps to reproduce** 1. Connect GitHub via the managed GitHub App installed on one organization (for example `acme`), with an approval policy on GitHub writes. 2. Ask an agent to run `create_issue` or `add_issue_comment` targeting a repository in an external organization where the App is not installed (for example `external-org/public-repo`). 3. Previously, Paperclip posted an approval card, executed it upon approval, received `403 Resource not accessible by integration`, and showed "GitHub access needed" / "Manage GitHub access" plus "Refresh access" instructions. **Paperclip version or commit** `2d065677959b` (`master`, merged cleanly with `331e1a9fd3`) **Deployment mode** Local / Paperclip Cloud managed GitHub App connection ## What Changed - `server/src/services/tool-access/github-access-discovery.ts`, `packages/db/src/schema/tool_access.ts`, `packages/shared/src/types/tool-access.ts`, `packages/shared/src/validators/tool-access.ts`: Preserved suspended installation owner logins separately in optional `suspendedInstallationOwnerLogins` so active `installationOwnerLogins` stays unchanged while suspended orgs are distinguishable from uninstalled orgs. Added `github_repo_outside_app_installations` to `ToolAccessReasonCode` and updated `tests/runner-e2e/source-sdk-public-inputs.json`. - `server/src/services/tool-access/github-access-errors.ts`: Added `github_repo_outside_app_installations`, `github_app_installation_suspended`, `isGitHubAccessErrorCode`, `extractGitHubTarget` (`owner`+`repo`, `repository: "owner/repo"`, `organization`/`org`, `fork_repository` destination-only handling, and GitHub API URL fallback), `suspendedManagedGitHubOwner`, `findUnreachableManagedGitHubTarget`, `githubOutsideAppInstallationsInstructions`, `githubSuspendedInstallationInstructions`, and `githubAccessErrorInstructions`. Webhook-invalidated/incomplete snapshots (`bindingSync` set or `installationIds` ahead of `installationOwnerLogins` with `repositories` cleared) skip pre-check blocking and stay on `github_access_denied` on runtime `403` until access is refreshed. - `server/src/services/tool-access-policy.ts` and `server/src/services/tool-gateway.ts`: Reused the already-resolved remote tool context from `resolveGovernedToolCall` (avoiding redundant connection/grant lookups for non-GitHub providers), routed unreachable approval-requiring managed GitHub writes through the canonical policy denial path with `{ claimIdempotencyKey: false }` (inserting `idempotencyKey: null` atomically in the single `INSERT` so retries after installing the App are never falsely replayed), and propagated `github_repo_outside_app_installations` / `github_app_installation_suspended` (HTTP 403) without echoing raw provider text into trusted instructions. - `server/src/routes/tool-gateway.ts`, `server/src/services/tool-action-delivery.ts`, `server/src/services/continuation-cause.ts`, `server/src/services/agent-task-run-telemetry.ts`: Treated all GitHub access error codes as MCP `tools/call` `isError: true` results, routed continuation wakes through `githubAccessErrorInstructions`, and registered `github_repo_outside_app_installations` and `github_app_installation_suspended` as person-owned `missing_access` failure codes. - `ui/src/components/IssueThreadInteractionCard.tsx` and `ui/storybook/stories/questions-and-approvals/connection-reviews.stories.tsx`: Added dedicated alert states for `github_repo_outside_app_installations` ("Repository outside GitHub App access", omitting dead-end "Manage GitHub access") and `github_app_installation_suspended` ("GitHub App installation suspended", with unsuspend guidance and "Manage GitHub access"), using existing design tokens only, while keeping "GitHub access needed" for `github_access_denied`. - `doc/connections/GITHUB.md`: Documented pre-check, suspended installation, incomplete webhook snapshot, and error classification behavior. - Added unit, UI component, and embedded-Postgres integration tests in `server/src/services/tool-access/github-access-errors.test.ts`, `server/src/__tests__/github-grant-metadata.test.ts`, `server/src/__tests__/tool-gateway.test.ts`, `server/src/__tests__/tool-gateway-action-approvals.test.ts`, and `ui/src/components/IssueThreadInteractionCard.test.tsx`. ## Verification - `pnpm vitest run server/src/services/tool-access/github-access-errors.test.ts server/src/services/tool-access/github-default-owner.test.ts server/src/__tests__/github-grant-metadata.test.ts ui/src/components/IssueThreadInteractionCard.test.tsx`: 4 files, 140/140 passed. - `pnpm vitest run server/src/__tests__/tool-gateway.test.ts -t "GitHub"`: 13/13 passed (covers pre-check blocking with atomic `idempotencyKey: null`, installed-org missing-repo `github_access_denied`, direct + MCP HTTP route `isError: true`, approved-card runtime 403 URL classification, post-install retry, suspended installation `github_app_installation_suspended`, and webhook-invalidated `bindingSync` snapshot pass-through). - `pnpm vitest run server/src/__tests__/tool-gateway-action-approvals.test.ts -t "tells the agent how to recover from"`: 9/9 passed (including `github_repo_outside_app_installations` and `github_app_installation_suspended` continuation wakes). - `pnpm --filter @paperclipai/shared typecheck && pnpm --filter @paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck && pnpm --filter @paperclipai/ui typecheck`: passed (0 errors across all 7 server layers, shared, db migration safety/compatibility, and UI + Storybook catalog). - `pnpm check:token-gates`: all 4 gates clean. - `node tests/runner-e2e/source-sdk-public-inputs.mjs 6714ad6b6854bdcc695eaca4ad083f36f11abba2 --check`: passed (`changed: false`, 578 inputs). - `node scripts/check-test-budget.mjs --files server/src/services/tool-access/github-access-errors.test.ts server/src/__tests__/github-grant-metadata.test.ts server/src/__tests__/tool-gateway.test.ts server/src/__tests__/tool-gateway-action-approvals.test.ts ui/src/components/IssueThreadInteractionCard.test.tsx`: PASS (`113 nightly suites validated, 5 test file(s) checked`). - PR CI on `6714ad6b68`: 81/81 executed checks passed (`0 failing, 0 pending, 0 cancelled, 6 skipped`), including `ci / verify`, `ci / e2e` + all 16 E2E shards, all General tests, all 9 Serialized server shards, all Verify Paperclip Runner lanes, `Build`, `Typecheck + Release Registry`, `Superagent Security Scan`, `Socket Security`, `Contributor trust`, `commitperclip`, `Snyk`, and `Greptile Review` (5/5, 0 unresolved threads). - Not tested against a live GitHub App installation. ## Risks - Low risk. No SQL database migration is required (`suspendedInstallationOwnerLogins` is an optional property inside the existing `connection_grants.provider_tenant` JSONB column, and `errorCode` is already an open string field). - Pre-check blocking only activates for approval-requiring non-read writes on managed GitHub connections that have a complete, populated grant snapshot (`login` and non-empty `installationOwnerLogins`, without `bindingSync` invalidation). PAT connections, legacy/empty/incomplete snapshots, installed organizations, suspended installations, the user's own personal account, read tools, and upstream `fork_repository` source repos retain their existing behavior. - Pre-check denials insert `idempotencyKey: null` atomically so retrying the same write after an org admin installs the App and access is refreshed never hits a stale denial replay. ## Model Used - Google Gemini (Antigravity agent) 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 - [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 --- doc/connections/GITHUB.md | 21 +- packages/db/src/schema/tool_access.ts | 1 + packages/shared/src/types/tool-access.ts | 2 + packages/shared/src/validators/tool-access.ts | 1 + .../__tests__/github-grant-metadata.test.ts | 1 + .../tool-gateway-action-approvals.test.ts | 44 ++- server/src/__tests__/tool-gateway.test.ts | 238 ++++++++++++++ server/src/routes/tool-gateway.ts | 3 +- .../src/services/agent-task-run-telemetry.ts | 2 + server/src/services/continuation-cause.ts | 2 +- server/src/services/tool-access-policy.ts | 8 +- .../tool-access/github-access-discovery.ts | 11 + .../tool-access/github-access-errors.test.ts | 265 +++++++++++++++- .../tool-access/github-access-errors.ts | 291 +++++++++++++++++- server/src/services/tool-action-delivery.ts | 11 +- server/src/services/tool-gateway.ts | 151 +++++++-- .../runner-e2e/source-sdk-public-inputs.json | 4 +- .../IssueThreadInteractionCard.test.tsx | 45 +++ .../components/IssueThreadInteractionCard.tsx | 16 + .../connection-reviews.stories.tsx | 14 + 20 files changed, 1080 insertions(+), 51 deletions(-) diff --git a/doc/connections/GITHUB.md b/doc/connections/GITHUB.md index 90f206b0a17..e660b1b036e 100644 --- a/doc/connections/GITHUB.md +++ b/doc/connections/GITHUB.md @@ -131,10 +131,27 @@ installation-health failure, not as token expiry. ## Repository access GitHub can return `403 Resource not accessible by integration` inside an MCP tool -error even when the connection itself is healthy. A failed tool approval shows +error even when the connection itself is healthy. When the target repository belongs +to an account or organization where the Paperclip GitHub App is installed (or the +connected user's own personal account), a failed tool approval shows **GitHub access needed** and **Manage GitHub access**, which opens that connection's Permissions page. Check the connected account and the App's access to the intended -account and repository there. The original provider error remains in the action's +account and repository there. When a managed GitHub App write targets an external +organization or account outside the App's installations, Paperclip blocks approval +cards before asking the user to approve a doomed write and classifies runtime +integration `403` denials as `github_repo_outside_app_installations` instead of +`github_access_denied`. Suspended installations are preserved separately in the +snapshot (`suspendedInstallationOwnerLogins`) so writes targeting a suspended +organization classify as `github_app_installation_suspended` with explicit +unsuspend + Refresh access guidance instead of advising a fresh install. When an +installation webhook marks the owner snapshot incomplete (`bindingSync`), both +the pre-check and runtime `403` classification fall back to `github_access_denied` +until access is refreshed. Failed cards and agent continuation instructions explain +that refreshing access alone cannot grant write permission before the App is +installed on that organization, and advise posting directly on GitHub, using a +personal access token connection, or having an organization administrator install +the App and refresh access on the Permissions page before retrying. +The original provider error remains in the action's error details and diagnostic record. Paperclip does not replay the write or hide other working tools. Saved GitHub approval errors receive the same presentation. The agent's continuation wake carries server-written next steps and tells it diff --git a/packages/db/src/schema/tool_access.ts b/packages/db/src/schema/tool_access.ts index 90b91f17ccd..5a19e578fc3 100644 --- a/packages/db/src/schema/tool_access.ts +++ b/packages/db/src/schema/tool_access.ts @@ -228,6 +228,7 @@ export const connectionGrants = pgTable( repositorySelection: "all" | "selected" | "mixed" | "none"; installationIds: string[]; installationOwnerLogins: string[]; + suspendedInstallationOwnerLogins?: string[]; /** Repository metadata visible to this credential; refreshed from GitHub. */ repositories?: Array<{ id: string; fullName: string; installationId: string; private?: boolean }>; installationUrl?: string; diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index e517c0282ce..203dc803d73 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -256,6 +256,7 @@ export interface ConnectionGrant { repositorySelection: "all" | "selected" | "mixed" | "none"; installationIds: string[]; installationOwnerLogins: string[]; + suspendedInstallationOwnerLogins?: string[]; /** Repository metadata visible to this credential; refreshed from GitHub. */ repositories?: Array<{ id: string; @@ -1592,6 +1593,7 @@ export type ToolAccessReasonCode = | "deny_policy_block" | "deny_run_context_mismatch" | "deny_missing_agent" + | "github_repo_outside_app_installations" | "rate_limited"; export interface ToolAccessSelector { diff --git a/packages/shared/src/validators/tool-access.ts b/packages/shared/src/validators/tool-access.ts index 0336b4b582f..23d0b8959ef 100644 --- a/packages/shared/src/validators/tool-access.ts +++ b/packages/shared/src/validators/tool-access.ts @@ -245,6 +245,7 @@ export const connectionGrantSchema = z.object({ repositorySelection: z.enum(["all", "selected", "mixed", "none"]), installationIds: z.array(z.string().regex(/^[1-9][0-9]{0,30}$/)).max(100), installationOwnerLogins: z.array(z.string().trim().min(1).max(100)).max(100), + suspendedInstallationOwnerLogins: z.array(z.string().trim().min(1).max(100)).max(100).optional(), installationUrl: z.string().url().max(2000).optional(), managementUrl: z.string().url().max(2000).optional(), appSlug: z.string().regex(/^[a-z0-9-]{1,100}$/).optional(), diff --git a/server/src/__tests__/github-grant-metadata.test.ts b/server/src/__tests__/github-grant-metadata.test.ts index 58ccb7080de..916a1a5c673 100644 --- a/server/src/__tests__/github-grant-metadata.test.ts +++ b/server/src/__tests__/github-grant-metadata.test.ts @@ -108,6 +108,7 @@ describe("GitHub grant metadata", () => { repositorySelection: "selected", installationIds: ["102"], installationOwnerLogins: ["octocat"], + suspendedInstallationOwnerLogins: ["paperclipai"], repositories: [{ id: "2", fullName: "octocat/b", installationId: "102" }], }); }); diff --git a/server/src/__tests__/tool-gateway-action-approvals.test.ts b/server/src/__tests__/tool-gateway-action-approvals.test.ts index 1bc7e54a533..ad81276e4b2 100644 --- a/server/src/__tests__/tool-gateway-action-approvals.test.ts +++ b/server/src/__tests__/tool-gateway-action-approvals.test.ts @@ -240,6 +240,8 @@ describeToolGatewayEmbeddedPostgres("tool gateway service: action approvals", () it.each([ { method: "managed", errorCode: "github_access_denied", sourceKey: "github" }, + { method: "managed", errorCode: "github_app_installation_suspended", sourceKey: "github" }, + { method: "managed", errorCode: "github_repo_outside_app_installations", sourceKey: "github" }, { method: "mcp-key", errorCode: "github_access_denied", sourceKey: "github" }, { method: "foreign", errorCode: "github_access_denied", sourceKey: "github" }, { method: "managed", errorCode: "tool_error", sourceKey: "github" }, @@ -283,21 +285,35 @@ describeToolGatewayEmbeddedPostgres("tool gateway service: action approvals", () const payload = wakeup.mock.calls[0][1].payload; const instructions: string = payload.toolAction.instructions; // Retrying or re-approving hits the same GitHub refusal. - const trustedGitHubDenial = errorCode === "github_access_denied" || (sourceKey === "github" && method !== "foreign"); - expect(instructions).toMatch(trustedGitHubDenial ? /do not retry.*until GitHub access is repaired/i : /did not complete successfully/); - // Concrete next step the agent can relay to the user. - if (!trustedGitHubDenial) { - expect(instructions).not.toMatch(/GitHub App|Refresh access|replace.*token/); - } else if (method === "managed") { - expect(instructions).toContain("github.com/new"); - expect(instructions).toMatch(/Refresh access/); - } else if (method === "mcp-key") { - expect(instructions).toMatch(/token.*permissions/i); - expect(instructions).toMatch(/replace.*token/i); - expect(instructions).not.toMatch(/GitHub App|Refresh access/); + const outsideApp = errorCode === "github_repo_outside_app_installations"; + const suspendedApp = errorCode === "github_app_installation_suspended"; + const trustedGitHubDenial = outsideApp || suspendedApp || errorCode === "github_access_denied" || (sourceKey === "github" && method !== "foreign"); + if (outsideApp) { + expect(instructions).toMatch(/do not retry/i); + expect(instructions).toMatch(/not installed/i); + expect(instructions).toMatch(/install the Paperclip GitHub App.*refresh access.*retry/i); + expect(instructions).not.toMatch(/select Refresh access|Add More Repos on GitHub/i); + } else if (suspendedApp) { + expect(instructions).toMatch(/do not retry/i); + expect(instructions).toMatch(/suspended/i); + expect(instructions).toMatch(/unsuspend/i); + expect(instructions).toContain("Refresh access"); } else { - expect(instructions).toMatch(/authentication method/); - expect(instructions).not.toMatch(/GitHub App|Refresh access/); + expect(instructions).toMatch(trustedGitHubDenial ? /do not retry.*until GitHub access is repaired/i : /did not complete successfully/); + // Concrete next step the agent can relay to the user. + if (!trustedGitHubDenial) { + expect(instructions).not.toMatch(/GitHub App|Refresh access|replace.*token/); + } else if (method === "managed") { + expect(instructions).toContain("github.com/new"); + expect(instructions).toMatch(/Refresh access/); + } else if (method === "mcp-key") { + expect(instructions).toMatch(/token.*permissions/i); + expect(instructions).toMatch(/replace.*token/i); + expect(instructions).not.toMatch(/GitHub App|Refresh access/); + } else { + expect(instructions).toMatch(/authentication method/); + expect(instructions).not.toMatch(/GitHub App|Refresh access/); + } } expect(payload.paperclipAgentMessage.text).toContain(instructions); // Provider text stays in the untrusted result, not in trusted instructions. diff --git a/server/src/__tests__/tool-gateway.test.ts b/server/src/__tests__/tool-gateway.test.ts index f5a4342cf3b..ea2caad8d9c 100644 --- a/server/src/__tests__/tool-gateway.test.ts +++ b/server/src/__tests__/tool-gateway.test.ts @@ -898,6 +898,244 @@ describeEmbeddedPostgres("tool gateway acceptance", () => { } finally { await remote.close(); } }); + it("blocks approval cards for managed GitHub writes outside installed orgs and distinguishes external-org vs installed-org 403s", async () => { + const company = await createCompany(db); + const agent = await createAgent(db, company.id); + const { run } = await createIssueAndRun(db, company.id, agent.id); + const remote = await startFakeRemoteMcpServer(({ body }) => { + const args = (body?.params as { arguments?: { owner?: string; repo?: string; issueRef?: string } } | undefined)?.arguments; + const owner = args?.owner ?? (args?.issueRef === "external-org-issue-42" ? "external-org" : "unknown"); + const repo = args?.repo ?? (args?.issueRef === "external-org-issue-42" ? "public-repo" : "unknown"); + const url = `https://api.github.com/repos/${owner}/${repo}/issues`; + return { body: { + jsonrpc: "2.0", id: body?.id, result: { + content: [{ type: "text", text: `failed to create issue: POST ${url}: 403 Resource not accessible by integration []` }], + isError: true, + }, + } }; + }); + try { + const { application, connection, catalogEntry } = await createRemoteMcpTool(db, company.id, { + url: remote.url, applicationKey: "github", toolName: "create_issue", riskLevel: "write", + connectionConfig: { sourceTemplateKey: "github", connectionMethodKey: "managed" }, + }); + await db.update(toolCatalogEntries).set({ inputSchema: { + type: "object", + properties: { owner: { type: "string" }, repo: { type: "string" }, title: { type: "string" }, issueRef: { type: "string" } }, + required: ["title"], + additionalProperties: false, + } }).where(eq(toolCatalogEntries.id, catalogEntry.id)); + await db.update(connectionGrants).set({ + providerTenant: { + github: { + userId: "1", + login: "octocat", + installationCount: 1, + repositoryCount: 1, + repositorySelection: "selected", + installationIds: ["9"], + installationOwnerLogins: ["acme"], + repositories: [{ id: "10", fullName: "acme/site", installationId: "9" }], + }, + }, + }).where(eq(connectionGrants.connectionId, connection.id)); + const toolName = expectedConnectedToolName({ + applicationKey: application.applicationKey, + connectionId: connection.id, + toolName: catalogEntry.toolName, + }); + await allowToolsForAgent(db, company.id, agent.id, [toolName]); + await db.insert(toolPolicies).values({ + companyId: company.id, + name: "Review GitHub writes", + policyType: "require_approval", + selectors: { connectionId: connection.id }, + priority: 10, + }); + const gateway = createTestToolGatewayService(db); + const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id }); + + // 1. Pre-check before posting an approval card: external org fails cleanly without wasting an approval. + const precheckError = await gateway.executeTool({ + sessionToken: session.token, + tool: toolName, + parameters: { owner: "external-org", repo: "public-repo", title: "Bug report" }, + }).catch((err) => err); + expect(precheckError).toMatchObject({ reasonCode: "github_repo_outside_app_installations" }); + expect(precheckError.message).toMatch(/not installed/i); + expect(precheckError.message).not.toMatch(/select Refresh access|Add More Repos on GitHub/i); + expect(remote.requests).toHaveLength(0); + expect(await db.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, company.id))).toHaveLength(0); + expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.companyId, company.id))).toHaveLength(0); + const [deniedInvocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.companyId, company.id)); + expect(deniedInvocation).toMatchObject({ + status: "denied", + errorCode: "github_repo_outside_app_installations", + idempotencyKey: null, + }); + + // 2. Installed org missing a repo grant STILL creates an approval card and classifies 403 as github_access_denied. + const installedOrgParams = { owner: "acme", repo: "unselected-repo", title: "Internal issue" }; + await expect(gateway.executeTool({ + sessionToken: session.token, + tool: toolName, + parameters: installedOrgParams, + })).rejects.toMatchObject({ reasonCode: "approval_required" }); + const [installedAction] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, company.id)); + expect(installedAction).toBeDefined(); + await db.update(issueThreadInteractions).set({ status: "accepted", resolvedAt: new Date() }) + .where(eq(issueThreadInteractions.id, installedAction!.interactionId!)); + await db.update(toolActionRequests).set({ status: "approved", resolvedAt: new Date() }) + .where(eq(toolActionRequests.id, installedAction!.id)); + const installedFailure = await gateway.executeTool({ + sessionToken: session.token, + tool: toolName, + parameters: installedOrgParams, + approvedActionRequestId: installedAction!.id, + }).catch((err) => err); + expect(installedFailure).toMatchObject({ reasonCode: "github_access_denied" }); + expect(installedFailure.message).toContain("Refresh access"); + const [installedCard] = await db.select().from(issueThreadInteractions) + .where(eq(issueThreadInteractions.id, installedAction!.interactionId!)); + expect(installedCard!.result).toMatchObject({ toolAction: { status: "failed", errorCode: "github_access_denied" } }); + + // 3. Direct runtime 403 on an external org (e.g. without require_approval policy) classifies as github_repo_outside_app_installations + // for both direct gateway execution and MCP HTTP protocol callers. + await db.delete(toolPolicies).where(eq(toolPolicies.companyId, company.id)); + const directExternalFailure = await gateway.executeTool({ + sessionToken: session.token, + tool: toolName, + parameters: { owner: "external-org", repo: "public-repo", title: "Direct bug" }, + }).catch((err) => err); + expect(directExternalFailure).toMatchObject({ reasonCode: "github_repo_outside_app_installations" }); + expect(directExternalFailure.message).toMatch(/not installed/i); + expect(directExternalFailure.message).not.toMatch(/select Refresh access|Add More Repos on GitHub/i); + + const profile = await allowToolsForAgent(db, company.id, agent.id, [toolName]); + const named = await gateway.createNamedGateway({ companyId: company.id, + body: { name: "GitHub external org", profileId: profile.id } }); + const token = await gateway.createNamedGatewayToken({ companyId: company.id, gatewayId: named.id, + body: { name: "Test", clientLabel: "Test", ownerNote: "" } }); + const mcpResponse = await request(createGatewayRouteApp(db, gateway)).post(named.endpointPath) + .set("authorization", `Bearer ${token.token}`) + .send({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: toolName, arguments: { owner: "external-org", repo: "public-repo", title: "MCP bug" } } }) + .expect(200); + expect(mcpResponse.body.result.isError).toBe(true); + expect(mcpResponse.body.result.content[0].text).toMatch(/not installed/i); + expect(mcpResponse.body.result.content[0].text).not.toMatch(/select Refresh access|Add More Repos on GitHub/i); + + // 4. If an approval card executes when the target owner only becomes visible in GitHub's 403 URL, + // approveActionRequest classifies and persists github_repo_outside_app_installations onto the card. + await db.insert(toolPolicies).values({ + companyId: company.id, + name: "Review GitHub writes again", + policyType: "require_approval", + selectors: { connectionId: connection.id }, + priority: 10, + }); + await expect(gateway.executeTool({ + sessionToken: session.token, + tool: toolName, + parameters: { title: "Opaque ref bug", issueRef: "external-org-issue-42" }, + })).rejects.toMatchObject({ reasonCode: "approval_required" }); + const actionsBeforeRefresh = await db.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, company.id)); + const externalAction = actionsBeforeRefresh.find((row) => row.id !== installedAction!.id); + expect(externalAction).toBeDefined(); + await expect(gateway.approveActionRequest({ + companyId: company.id, + actionRequestId: externalAction!.id, + actor: { userId: "reviewer" }, + })).resolves.toMatchObject({ status: "failed" }); + const [externalCard] = await db.select().from(issueThreadInteractions) + .where(eq(issueThreadInteractions.id, externalAction!.interactionId!)); + expect(externalCard!.result).toMatchObject({ + toolAction: { status: "failed", errorCode: "github_repo_outside_app_installations" }, + }); + + // 5. After an org admin installs the App on external-org and access refreshes, retrying the previously + // pre-checked write posts an approval card cleanly (no stale idempotency replay from step 1). + await db.update(connectionGrants).set({ + providerTenant: { + github: { + userId: "1", + login: "octocat", + installationCount: 2, + repositoryCount: 2, + repositorySelection: "selected", + installationIds: ["9", "11"], + installationOwnerLogins: ["acme", "external-org"], + repositories: [ + { id: "10", fullName: "acme/site", installationId: "9" }, + { id: "12", fullName: "external-org/public-repo", installationId: "11" }, + ], + }, + }, + }).where(eq(connectionGrants.connectionId, connection.id)); + await expect(gateway.executeTool({ + sessionToken: session.token, + tool: toolName, + parameters: { owner: "external-org", repo: "public-repo", title: "Bug report" }, + })).rejects.toMatchObject({ reasonCode: "approval_required" }); + + // 6. A suspended installation owner (one active + one suspended) is NOT treated as outside installations + // and delivers unsuspend guidance on runtime 403. + await db.delete(toolPolicies).where(eq(toolPolicies.companyId, company.id)); + await db.update(connectionGrants).set({ + providerTenant: { + github: { + userId: "1", + login: "octocat", + installationCount: 1, + repositoryCount: 1, + repositorySelection: "selected", + installationIds: ["9"], + installationOwnerLogins: ["acme"], + suspendedInstallationOwnerLogins: ["suspended-org"], + repositories: [{ id: "10", fullName: "acme/site", installationId: "9" }], + }, + }, + }).where(eq(connectionGrants.connectionId, connection.id)); + const suspendedFailure = await gateway.executeTool({ + sessionToken: session.token, + tool: toolName, + parameters: { owner: "suspended-org", repo: "app", title: "Suspended write" }, + }).catch((err) => err); + expect(suspendedFailure).toMatchObject({ reasonCode: "github_app_installation_suspended" }); + expect(suspendedFailure.message).toMatch(/unsuspend/i); + expect(suspendedFailure.message).toContain("suspended-org"); + expect(suspendedFailure.message).toContain("Refresh access"); + + // 7. A webhook-invalidated snapshot (bindingSync present) skips the stale pre-check so a newly + // installed org is not blocked before Refresh access. + await db.insert(toolPolicies).values({ + companyId: company.id, + name: "Review GitHub writes after webhook", + policyType: "require_approval", + selectors: { connectionId: connection.id }, + priority: 10, + }); + await db.update(connectionGrants).set({ + providerTenant: { + github: { + userId: "1", + login: "octocat", + installationCount: 2, + repositoryCount: 1, + repositorySelection: "selected", + installationIds: ["9", "11"], + installationOwnerLogins: ["acme"], + bindingSync: { id: "00000000-0000-4000-8000-000000000001", removeInstallationIds: [] }, + }, + }, + }).where(eq(connectionGrants.connectionId, connection.id)); + await expect(gateway.executeTool({ + sessionToken: session.token, + tool: toolName, + parameters: { owner: "newly-installed-org", repo: "public-repo", title: "Post-install bug" }, + })).rejects.toMatchObject({ reasonCode: "approval_required" }); + } finally { await remote.close(); } + }); + it("returns a JSON-RPC reconciliation error instead of repeating an unverifiable legacy write", async () => { const company = await createCompany(db); const remote = await startFakeRemoteMcpServer(({ body }) => ({ diff --git a/server/src/routes/tool-gateway.ts b/server/src/routes/tool-gateway.ts index f4853ed5254..51a5adad273 100644 --- a/server/src/routes/tool-gateway.ts +++ b/server/src/routes/tool-gateway.ts @@ -15,6 +15,7 @@ import { } from "@paperclipai/shared/validators/tool-access"; import { assertBoard, assertBoardOrAgent, assertCompanyAccess, getActorInfo } from "./authz.js"; import { ToolGatewayHttpError, type ToolGatewayService } from "../services/tool-gateway.js"; +import { isGitHubAccessErrorCode } from "../services/tool-access/github-access-errors.js"; import { forbidden, HttpError } from "../errors.js"; import { accessService } from "../services/index.js"; import { authorizationDeniedDetails } from "../services/authorization.js"; @@ -246,7 +247,7 @@ async function handleMcpGatewayProtocol( // Provider tool failures are MCP tool results, not successful calls or // protocol errors. The service has already recorded the failed invocation. if (req.body?.method === "tools/call" && - (err.reasonCode === "tool_error" || err.reasonCode === "github_access_denied")) { + (err.reasonCode === "tool_error" || isGitHubAccessErrorCode(err.reasonCode))) { res.json({ jsonrpc: "2.0", id, diff --git a/server/src/services/agent-task-run-telemetry.ts b/server/src/services/agent-task-run-telemetry.ts index eb75de4fec0..57e001e4a79 100644 --- a/server/src/services/agent-task-run-telemetry.ts +++ b/server/src/services/agent-task-run-telemetry.ts @@ -53,6 +53,8 @@ const FAILURE_CAUSE_BY_ERROR_CODE: Record = { user_secret_definition_missing: "missing_access", user_secret_definition_inactive: "missing_access", github_access_denied: "missing_access", + github_app_installation_suspended: "missing_access", + github_repo_outside_app_installations: "missing_access", github_repo_not_accessible: "missing_access", github_auth_required: "missing_access", project_access_denied: "missing_access", diff --git a/server/src/services/continuation-cause.ts b/server/src/services/continuation-cause.ts index f9ffd23c748..bbca767a384 100644 --- a/server/src/services/continuation-cause.ts +++ b/server/src/services/continuation-cause.ts @@ -16,7 +16,7 @@ export const PERSON_OWNED_FAILURE_CODES = [ // A credential, secret or access the person must share. "configuration_incomplete", "slack_configuration_incomplete", "signing_secret_unconfigured", "user_secret_missing", "user_secret_definition_missing", "user_secret_definition_inactive", - "github_access_denied", "github_repo_not_accessible", "github_auth_required", "project_access_denied", + "github_access_denied", "github_app_installation_suspended", "github_repo_outside_app_installations", "github_repo_not_accessible", "github_auth_required", "project_access_denied", "permission_denied", "responsible_user_unauthorized", "oauth_access_projection_disabled", "acpx_auth_required", "codex_auth_required", "claude_auth_required", "provider_auth_failed", "hermes_gateway_auth_failed", // A configuration choice the person must change. diff --git a/server/src/services/tool-access-policy.ts b/server/src/services/tool-access-policy.ts index 18a0a34fb96..f00a0a84c01 100644 --- a/server/src/services/tool-access-policy.ts +++ b/server/src/services/tool-access-policy.ts @@ -1902,7 +1902,11 @@ export function toolAccessPolicyService(db: Pick(); + const suspendedOwners = new Set(); const selections = new Set<"all" | "selected">(); const managementUrls = new Set(); const suspendedManagementUrls = new Set(); @@ -191,6 +193,12 @@ export async function loadGitHubGrantMetadata( if (installation.suspended_at) { const suspendedUrl = githubInstallationManagementUrl(installation.html_url); if (suspendedUrl) suspendedManagementUrls.add(suspendedUrl); + const suspendedAccount = recordValue(installation.account) + ? installation.account + : null; + if (typeof suspendedAccount?.login === "string") { + suspendedOwners.add(suspendedAccount.login); + } suspendedCount += 1; continue; } @@ -281,6 +289,9 @@ export async function loadGitHubGrantMetadata( : (selections.values().next().value ?? "none"), installationIds, installationOwnerLogins: [...owners], + ...(suspendedOwners.size > 0 + ? { suspendedInstallationOwnerLogins: [...suspendedOwners] } + : {}), repositories: [...repositories.values()].sort((a, b) => a.fullName.localeCompare(b.fullName), ), diff --git a/server/src/services/tool-access/github-access-errors.test.ts b/server/src/services/tool-access/github-access-errors.test.ts index 60bf7b42f58..526330fbccd 100644 --- a/server/src/services/tool-access/github-access-errors.test.ts +++ b/server/src/services/tool-access/github-access-errors.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from "vitest"; -import { githubAccessDeniedInstructions, githubAccessError, projectGitHubActionResult } from "./github-access-errors.js"; +import { + findUnreachableManagedGitHubTarget, + githubAccessDeniedInstructions, + githubAccessError, + githubAccessErrorInstructions, + projectGitHubActionResult, +} from "./github-access-errors.js"; describe("GitHub tool access failures", () => { it.each(["integration", "personal access token"])("classifies GitHub's %s permission denial", kind => { @@ -59,4 +65,261 @@ describe("GitHub tool access failures", () => { expect(unknown).toMatch(/authentication method/); expect(unknown).not.toMatch(/GitHub App|Refresh access/); }); + + it("classifies 403 denials on external orgs outside managed GitHub App installations separately from installed-org denials", () => { + const githubGrant = { + login: "octocat", + installationOwnerLogins: ["acme"], + repositories: [{ id: "10", fullName: "acme/app", installationId: "9" }], + }; + expect(githubAccessError( + "github", + "POST https://api.github.com/repos/external-org/public-repo/issues: 403 Resource not accessible by integration []", + { + connectionMethodKey: "managed", + githubGrant, + toolName: "mcp.github:create_issue", + parameters: { owner: "external-org", repo: "public-repo", title: "Bug" }, + }, + )).toEqual({ errorCode: "github_repo_outside_app_installations" }); + + // Accessible org missing a specific repo selection remains github_access_denied. + expect(githubAccessError( + "github", + "POST https://api.github.com/repos/acme/unselected-repo/issues: 403 Resource not accessible by integration []", + { + connectionMethodKey: "managed", + githubGrant, + toolName: "mcp.github:create_issue", + parameters: { owner: "acme", repo: "unselected-repo", title: "Bug" }, + }, + )).toEqual({ errorCode: "github_access_denied" }); + + // User's own personal account remains repairable via Manage GitHub access. + expect(githubAccessError( + "github", + "POST https://api.github.com/repos/octocat/personal-repo/issues: 403 Resource not accessible by integration []", + { + connectionMethodKey: "managed", + githubGrant, + toolName: "mcp.github:create_issue", + parameters: { owner: "octocat", repo: "personal-repo", title: "Bug" }, + }, + )).toEqual({ errorCode: "github_access_denied" }); + + // PAT connections and missing snapshots keep github_access_denied. + expect(githubAccessError( + "github", + "POST https://api.github.com/repos/external-org/public-repo/issues: 403 Resource not accessible by personal access token []", + { + connectionMethodKey: "mcp-key", + githubGrant, + toolName: "mcp.github:create_issue", + parameters: { owner: "external-org", repo: "public-repo", title: "Bug" }, + }, + )).toEqual({ errorCode: "github_access_denied" }); + expect(githubAccessError( + "github", + "POST https://api.github.com/repos/external-org/public-repo/issues: 403 Resource not accessible by integration []", + { + connectionMethodKey: "managed", + githubGrant: null, + toolName: "mcp.github:create_issue", + parameters: { owner: "external-org", repo: "public-repo", title: "Bug" }, + }, + )).toEqual({ errorCode: "github_access_denied" }); + }); + + it("pre-checks managed GitHub writes against installed accounts without blocking installed orgs, personal accounts, or upstream fork sources", () => { + const githubGrant = { + login: "octocat", + installationOwnerLogins: ["Acme"], + }; + const unreachable = findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "managed", + githubGrant, + toolName: "mcp.github:add_issue_comment", + parameters: { owner: "vercel", repo: "next.js", issue_number: 1, body: "hi" }, + }); + expect(unreachable).toMatchObject({ owner: "vercel", repo: "next.js" }); + expect(unreachable?.message).toContain("vercel/next.js"); + expect(unreachable?.message).toMatch(/not installed/i); + expect(unreachable?.message).not.toMatch(/select Refresh access|Add More Repos on GitHub/i); + + // repository: "owner/repo" format is also detected. + expect(findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "managed", + githubGrant, + toolName: "mcp.github:create_issue", + parameters: { repository: "external-org/public-repo", title: "Bug" }, + })).toMatchObject({ owner: "external-org", repo: "public-repo" }); + + // Installed org (case-insensitive) and user's own personal account are allowed. + expect(findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "managed", + githubGrant, + toolName: "mcp.github:create_issue", + parameters: { owner: "acme", repo: "other-repo", title: "Bug" }, + })).toBeNull(); + expect(findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "managed", + githubGrant, + toolName: "mcp.github:create_issue", + parameters: { owner: "OctoCat", repo: "my-repo", title: "Bug" }, + })).toBeNull(); + + // fork_repository reads from owner/repo and writes to organization (or personal account). + expect(findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "managed", + githubGrant, + toolName: "mcp.github:fork_repository", + parameters: { owner: "vercel", repo: "next.js", organization: "acme" }, + })).toBeNull(); + expect(findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "managed", + githubGrant, + toolName: "mcp.github:fork_repository", + parameters: { owner: "vercel", repo: "next.js", organization: "other-org" }, + })).toMatchObject({ owner: "other-org" }); + + // PAT connections and missing snapshots are not pre-blocked. + expect(findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "mcp-key", + githubGrant, + toolName: "mcp.github:create_issue", + parameters: { owner: "vercel", repo: "next.js" }, + })).toBeNull(); + expect(findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "managed", + githubGrant: { login: "octocat", installationOwnerLogins: [] }, + toolName: "mcp.github:create_issue", + parameters: { owner: "vercel", repo: "next.js" }, + })).toBeNull(); + }); + + it("gives accurate non-refresh instructions for github_repo_outside_app_installations", () => { + const text = githubAccessErrorInstructions( + "github_repo_outside_app_installations", + "mcp.github:create_issue", + "managed", + { owner: "external-org", repo: "public-repo" }, + ); + expect(text).toMatch(/Do not retry/); + expect(text).toMatch(/not installed/i); + expect(text).toMatch(/directly on GitHub|personal access token/i); + expect(text).toMatch(/install the Paperclip GitHub App.*refresh access.*retry/i); + expect(text).not.toMatch(/select Refresh access|Add More Repos on GitHub/i); + }); + + it("preserves suspended installations as repairable access with unsuspend guidance instead of install advice", () => { + const githubGrant = { + login: "octocat", + installationIds: ["102"], + installationOwnerLogins: ["octocat"], + suspendedInstallationOwnerLogins: ["paperclipai"], + repositories: [{ id: "2", fullName: "octocat/b", installationId: "102" }], + }; + // Pre-check must NOT classify a suspended owner as outside installations. + expect(findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "managed", + githubGrant, + toolName: "mcp.github:create_issue", + parameters: { owner: "paperclipai", repo: "a", title: "Bug" }, + })).toBeNull(); + // Runtime 403 on suspended owner classifies as github_app_installation_suspended (not outside installations). + expect(githubAccessError( + "github", + "POST https://api.github.com/repos/paperclipai/a/issues: 403 Resource not accessible by integration []", + { + connectionMethodKey: "managed", + githubGrant, + toolName: "mcp.github:create_issue", + parameters: { owner: "paperclipai", repo: "a", title: "Bug" }, + }, + )).toEqual({ errorCode: "github_app_installation_suspended" }); + // Unsuspend guidance points operators to unsuspend and then Refresh access (with or without explicit owner). + const guidance = githubAccessErrorInstructions( + "github_app_installation_suspended", + "mcp.github:create_issue", + "managed", + null, + undefined, + { suspendedOwner: "paperclipai" }, + ); + expect(guidance).toMatch(/suspended/i); + expect(guidance).toMatch(/unsuspend/i); + expect(guidance).toContain("paperclipai"); + expect(guidance).toContain("Refresh access"); + const genericSuspendedGuidance = githubAccessErrorInstructions( + "github_app_installation_suspended", + "mcp.github:create_issue", + "managed", + ); + expect(genericSuspendedGuidance).toMatch(/suspended/i); + expect(genericSuspendedGuidance).toMatch(/unsuspend/i); + expect(genericSuspendedGuidance).toContain("Refresh access"); + }); + + it("handles create_repository omitted organization and falls back to github_access_denied on webhook-invalidated snapshots", () => { + const singleOrg = { login: "octocat", installationOwnerLogins: ["acme"] }; + const multiOrg = { login: "octocat", installationOwnerLogins: ["acme", "globex"] }; + // Omitted organization (personal fallback) and injected single-org default both stay reachable. + expect(findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "managed", + githubGrant: singleOrg, + toolName: "mcp.github:create_repository", + parameters: { name: "site", organization: "acme" }, + })).toBeNull(); + expect(findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "managed", + githubGrant: multiOrg, + toolName: "mcp.github:create_repository", + parameters: { name: "site" }, + })).toBeNull(); + expect(findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "managed", + githubGrant: singleOrg, + toolName: "mcp.github:create_repository", + parameters: { name: "site", organization: "external-org" }, + })).toMatchObject({ owner: "external-org" }); + + // Webhook-invalidated snapshot (bindingSync present / repositories cleared) skips pre-check + // AND keeps runtime 403 as github_access_denied so newly installed orgs get Refresh access guidance. + const webhookSnapshot = { + login: "octocat", + installationIds: ["9", "11"], + installationOwnerLogins: ["acme"], + repositories: undefined, + bindingSync: { id: "sync-1", removeInstallationIds: [] }, + }; + expect(findUnreachableManagedGitHubTarget({ + sourceTemplateKey: "github", + connectionMethodKey: "managed", + githubGrant: webhookSnapshot, + toolName: "mcp.github:create_issue", + parameters: { owner: "newly-installed-org", repo: "public-repo" }, + })).toBeNull(); + expect(githubAccessError( + "github", + "POST https://api.github.com/repos/newly-installed-org/public-repo/issues: 403 Resource not accessible by integration []", + { + connectionMethodKey: "managed", + githubGrant: webhookSnapshot, + toolName: "mcp.github:create_issue", + parameters: { owner: "newly-installed-org", repo: "public-repo" }, + }, + )).toEqual({ errorCode: "github_access_denied" }); + }); }); diff --git a/server/src/services/tool-access/github-access-errors.ts b/server/src/services/tool-access/github-access-errors.ts index 191c1495d89..f0a2da16ca1 100644 --- a/server/src/services/tool-access/github-access-errors.ts +++ b/server/src/services/tool-access/github-access-errors.ts @@ -1,12 +1,247 @@ import type { RequestConfirmationResult } from "@paperclipai/shared"; +export const GITHUB_ACCESS_DENIED_ERROR_CODE = "github_access_denied" as const; +export const GITHUB_APP_INSTALLATION_SUSPENDED_ERROR_CODE = "github_app_installation_suspended" as const; +export const GITHUB_REPO_OUTSIDE_APP_INSTALLATIONS_ERROR_CODE = "github_repo_outside_app_installations" as const; + +export type GitHubAccessErrorCode = + | typeof GITHUB_ACCESS_DENIED_ERROR_CODE + | typeof GITHUB_APP_INSTALLATION_SUSPENDED_ERROR_CODE + | typeof GITHUB_REPO_OUTSIDE_APP_INSTALLATIONS_ERROR_CODE; + +export function isGitHubAccessErrorCode(code: unknown): code is GitHubAccessErrorCode { + return code === GITHUB_ACCESS_DENIED_ERROR_CODE + || code === GITHUB_APP_INSTALLATION_SUSPENDED_ERROR_CODE + || code === GITHUB_REPO_OUTSIDE_APP_INSTALLATIONS_ERROR_CODE; +} + +export interface GitHubAccessSnapshot { + login?: unknown; + installationIds?: unknown; + installationOwnerLogins?: unknown; + suspendedInstallationOwnerLogins?: unknown; + repositories?: unknown; + bindingSync?: unknown; +} + +export interface GitHubTarget { + owner: string; + repo?: string; +} + +const GITHUB_OWNER_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/; +const GITHUB_REPO_RE = /^(?!\.{1,2}$)[A-Za-z0-9_.-]{1,100}$/; +const GITHUB_API_REPO_URL_RE = /\bhttps:\/\/api\.github\.com\/repos\/([A-Za-z0-9][A-Za-z0-9-]{0,38})\/([A-Za-z0-9_.-]{1,100})(?=[/:?\s]|$)/i; +const GITHUB_API_ORG_URL_RE = /\bhttps:\/\/api\.github\.com\/orgs\/([A-Za-z0-9][A-Za-z0-9-]{0,38})(?=[/:?\s]|$)/i; + +function asRecord(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? value as Record + : {}; +} + +function githubOperation(toolName: string): string { + return (toolName.split(/[.:/]/).pop() ?? "").trim().toLowerCase().replace(/-/g, "_"); +} + +function validOwner(value: unknown): string | null { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return GITHUB_OWNER_RE.test(trimmed) ? trimmed : null; +} + +function validRepo(value: unknown): string | null { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return GITHUB_REPO_RE.test(trimmed) ? trimmed : null; +} + +function parseFullName(value: unknown): GitHubTarget | null { + if (typeof value !== "string") return null; + const parts = value.trim().split("/"); + if (parts.length !== 2) return null; + const owner = validOwner(parts[0]); + const repo = validRepo(parts[1]); + return owner && repo ? { owner, repo } : null; +} + +function collectValidOwners(values: unknown): { list: string[]; set: Set } { + const list: string[] = []; + const set = new Set(); + if (!Array.isArray(values)) return { list, set }; + for (const entry of values) { + const owner = validOwner(entry); + if (!owner) continue; + const key = owner.toLowerCase(); + if (set.has(key)) continue; + set.add(key); + list.push(owner); + } + return { list, set }; +} + +/** Extract the write target owner (and repository when known) from structured + * GitHub tool parameters, or as a fallback from a GitHub REST API URL in a 403 + * error message. For `fork_repository`, `owner`/`repo` is the upstream source + * repo rather than the write destination, so only `organization`/`org` counts. */ +export function extractGitHubTarget( + toolName: string, + parameters: unknown, + providerMessage?: unknown, +): GitHubTarget | null { + const op = githubOperation(toolName); + const params = asRecord(parameters); + if (op === "create_repository" || op === "fork_repository") { + const org = validOwner(params.organization ?? params.org); + if (org) return { owner: org }; + if (typeof providerMessage === "string") { + const orgMatch = GITHUB_API_ORG_URL_RE.exec(providerMessage.slice(0, 4000)); + const matchedOrg = validOwner(orgMatch?.[1]); + if (matchedOrg) return { owner: matchedOrg }; + } + return null; + } + + const owner = validOwner(params.owner); + if (owner) { + const repo = validRepo(params.repo ?? params.repository_name ?? params.repositoryName); + return repo ? { owner, repo } : { owner }; + } + + for (const key of ["repository", "repo", "repoFullName", "fullName"] as const) { + const parsed = parseFullName(params[key]); + if (parsed) return parsed; + } + + const org = validOwner(params.organization ?? params.org); + if (org) return { owner: org }; + + if (typeof providerMessage === "string") { + const snippet = providerMessage.slice(0, 4000); + const repoMatch = GITHUB_API_REPO_URL_RE.exec(snippet); + if (repoMatch) { + const matchedOwner = validOwner(repoMatch[1]); + const matchedRepo = validRepo(repoMatch[2]); + if (matchedOwner && matchedRepo) return { owner: matchedOwner, repo: matchedRepo }; + } + const orgMatch = GITHUB_API_ORG_URL_RE.exec(snippet); + const matchedOrg = validOwner(orgMatch?.[1]); + if (matchedOrg) return { owner: matchedOrg }; + } + + return null; +} + +function normalizedInstalledOwners(githubGrant: GitHubAccessSnapshot | null | undefined): { + login: string; + installedOwners: string[]; + installedOwnerSet: Set; + suspendedOwnerSet: Set; + incomplete: boolean; +} | null { + if (!githubGrant) return null; + const login = validOwner(githubGrant.login); + if (!login) return null; + const active = collectValidOwners(githubGrant.installationOwnerLogins); + if (active.list.length === 0) return null; + const suspended = collectValidOwners(githubGrant.suspendedInstallationOwnerLogins); + // Installation webhooks add installationIds and clear repositories without + // refreshing installationOwnerLogins. Mark such snapshots incomplete so + // pre-checks do not block newly installed organizations before Refresh access. + const incomplete = Boolean(githubGrant.bindingSync) + || (Array.isArray(githubGrant.installationIds) + && githubGrant.installationIds.length > active.list.length + && githubGrant.repositories === undefined); + return { + login, + installedOwners: active.list, + installedOwnerSet: active.set, + suspendedOwnerSet: suspended.set, + incomplete, + }; +} + +/** Return the canonical suspended installation owner login when the target + * owner has a suspended Paperclip GitHub App installation (and no active + * installation), so repair requires unsuspending rather than installing the App. */ +export function suspendedManagedGitHubOwner( + githubGrant: GitHubAccessSnapshot | null | undefined, + target: GitHubTarget | null | undefined, +): string | null { + if (!githubGrant || !target) return null; + const owner = validOwner(target.owner); + if (!owner) return null; + const key = owner.toLowerCase(); + const active = collectValidOwners(githubGrant.installationOwnerLogins); + if (active.set.has(key)) return null; + const suspended = collectValidOwners(githubGrant.suspendedInstallationOwnerLogins); + return suspended.list.find((entry) => entry.toLowerCase() === key) ?? null; +} + +/** Check whether a managed GitHub App call targets an account/organization + * outside the Paperclip GitHub App's installed accounts (and not the user's + * own personal account or a suspended installation). Refreshing access alone + * cannot grant write access before the App is installed on that organization. */ +export function findUnreachableManagedGitHubTarget(input: { + sourceTemplateKey: unknown; + connectionMethodKey: unknown; + githubGrant: GitHubAccessSnapshot | null | undefined; + toolName: string; + parameters?: unknown; + providerMessage?: unknown; +}): { owner: string; repo?: string; installedOwners: string[]; message: string } | null { + if (input.sourceTemplateKey !== "github" || input.connectionMethodKey !== "managed") return null; + const snapshot = normalizedInstalledOwners(input.githubGrant); + if (!snapshot || snapshot.incomplete) return null; + const target = extractGitHubTarget(input.toolName, input.parameters, input.providerMessage); + if (!target) return null; + const targetOwnerLower = target.owner.toLowerCase(); + if ( + targetOwnerLower === snapshot.login.toLowerCase() + || snapshot.installedOwnerSet.has(targetOwnerLower) + || snapshot.suspendedOwnerSet.has(targetOwnerLower) + ) { + return null; + } + return { + ...target, + installedOwners: snapshot.installedOwners, + message: githubOutsideAppInstallationsInstructions(target, snapshot.installedOwners), + }; +} + /** GitHub reports repository permission failures inside successful MCP HTTP * responses. Do not infer that every 403 is an access problem (rate limits also * use 403), or echo provider response text into the repair instructions. */ -export function githubAccessError(sourceTemplateKey: unknown, message: unknown) { +export function githubAccessError( + sourceTemplateKey: unknown, + message: unknown, + context?: { + connectionMethodKey?: unknown; + githubGrant?: GitHubAccessSnapshot | null; + toolName?: string; + parameters?: unknown; + }, +): { errorCode: GitHubAccessErrorCode } | null { if (sourceTemplateKey !== "github" || typeof message !== "string" || !/\b403\s+Resource not accessible by (?:integration|personal access token)\b/i.test(message.slice(0, 4000))) return null; - return { errorCode: "github_access_denied" as const }; + if (context && context.connectionMethodKey === "managed" && context.githubGrant) { + const target = extractGitHubTarget(context.toolName ?? "", context.parameters, message); + if (suspendedManagedGitHubOwner(context.githubGrant, target)) { + return { errorCode: GITHUB_APP_INSTALLATION_SUSPENDED_ERROR_CODE }; + } + if (findUnreachableManagedGitHubTarget({ + sourceTemplateKey, + connectionMethodKey: context.connectionMethodKey, + githubGrant: context.githubGrant, + toolName: context.toolName ?? "", + parameters: context.parameters, + providerMessage: message, + })) { + return { errorCode: GITHUB_REPO_OUTSIDE_APP_INSTALLATIONS_ERROR_CODE }; + } + } + return { errorCode: GITHUB_ACCESS_DENIED_ERROR_CODE }; } /** Upgrade already saved tool errors using verified connection identity. Retain @@ -19,10 +254,32 @@ export function projectGitHubActionResult(sourceTemplateKey: unknown, result: Re return failure ? { ...result, toolAction: { ...action, ...failure } } : result; } +/** Trusted, server-authored next steps when a managed GitHub App connection + * targets an organization or repository outside the App's installations. + * Never echoes raw provider text. */ +export function githubOutsideAppInstallationsInstructions( + target?: GitHubTarget | null, + installedOwners?: string[], +): string { + const safeTarget = target && validOwner(target.owner) + ? (target.repo && validRepo(target.repo) ? `${target.owner}/${target.repo}` : target.owner) + : null; + const safeInstalled = (installedOwners ?? []).filter((owner) => validOwner(owner) !== null); + const targetPhrase = safeTarget ? ` for ${safeTarget}` : ""; + const installedPhrase = safeInstalled.length > 0 + ? ` (currently installed on: ${safeInstalled.join(", ")})` + : ""; + return `GitHub cannot run this action${targetPhrase} because the Paperclip GitHub App is not installed on that organization or account${installedPhrase}. Do not retry or request approval for the same call on this managed GitHub App connection unless an administrator installs the Paperclip GitHub App on that organization and access is refreshed. Never automatically replay an approved write. Refreshing access alone cannot grant write permission before the Paperclip GitHub App is installed on that organization. Explain this to the user and offer the drafted content so they can post directly on GitHub, note that a personal access token (PAT) GitHub connection is required to write to external repositories where the App cannot be installed, or—only if they administer that organization—ask an organization admin to install the Paperclip GitHub App there, open the GitHub connection's Permissions page to refresh access, and then retry the same call.`; +} + /** Trusted, server-authored next steps for the agent after GitHub denied an * approved action. Access must be repaired before another attempt. The * provider text stays in the untrusted result, never in these instructions. */ -export function githubAccessDeniedInstructions(toolName: string, connectionMethodKey: unknown = null): string { +export function githubAccessDeniedInstructions( + toolName: string, + connectionMethodKey: unknown = null, + options?: { suspendedOwner?: string | null }, +): string { const operation = (toolName.split(":").pop() ?? "").trim().toLowerCase().replace(/-/g, "_"); const base = "GitHub denied this action because the Paperclip GitHub connection cannot access the requested account or repository. Do not retry or request approval for the same call until GitHub access is repaired. Never automatically replay an approved write."; if (connectionMethodKey === "mcp-key") { @@ -31,8 +288,36 @@ export function githubAccessDeniedInstructions(toolName: string, connectionMetho if (connectionMethodKey !== "managed") { return `${base} Ask the user to open the GitHub connection's Permissions page and check its connected account, authentication method and requested repository access. Continue after they repair that connection.`; } + const suspendedOwner = validOwner(options?.suspendedOwner); + if (suspendedOwner) { + return `${base} The Paperclip GitHub App installation for ${suspendedOwner} is currently suspended. Ask an owner or administrator of ${suspendedOwner} to unsuspend the Paperclip GitHub App on GitHub, then open the GitHub connection's Permissions page and select Refresh access. Continue after they confirm.`; + } if (operation === "create_repository") { return `${base} Check the repository owner. Connecting a GitHub user does not by itself grant App access to their personal account. For a personal repository, the Paperclip GitHub App needs access to that personal account. For an organization repository, it needs access to that organization; use the tool's organization argument only for an owner the user requested. Open the GitHub connection's Permissions page, select Add More Repos on GitHub, choose the intended account, then Refresh access. If creation remains unavailable, ask the user to create it at https://github.com/new and grant the App access before continuing.`; } return `${base} Tell the user which account or repository you need. Ask them to give the Paperclip GitHub App access from the GitHub connection's Permissions page and select Refresh access. Continue after they confirm.`; } + +export function githubSuspendedInstallationInstructions(suspendedOwner?: string | null): string { + const safeOwner = validOwner(suspendedOwner); + const ownerPhrase = safeOwner ? ` for ${safeOwner}` : " for this account or organization"; + const adminPhrase = safeOwner ? `an owner or administrator of ${safeOwner}` : "an owner or administrator of that account or organization"; + return `GitHub denied this action because the Paperclip GitHub App installation${ownerPhrase} is currently suspended. Do not retry or request approval for the same call until the installation is unsuspended. Never automatically replay an approved write. Ask ${adminPhrase} to unsuspend the Paperclip GitHub App on GitHub, then open the GitHub connection's Permissions page and select Refresh access. Continue after they confirm.`; +} + +export function githubAccessErrorInstructions( + errorCode: GitHubAccessErrorCode, + toolName: string, + connectionMethodKey: unknown = null, + target?: GitHubTarget | null, + installedOwners?: string[], + options?: { suspendedOwner?: string | null }, +): string { + if (errorCode === GITHUB_REPO_OUTSIDE_APP_INSTALLATIONS_ERROR_CODE) { + return githubOutsideAppInstallationsInstructions(target, installedOwners); + } + if (errorCode === GITHUB_APP_INSTALLATION_SUSPENDED_ERROR_CODE) { + return githubSuspendedInstallationInstructions(options?.suspendedOwner); + } + return githubAccessDeniedInstructions(toolName, connectionMethodKey, options); +} diff --git a/server/src/services/tool-action-delivery.ts b/server/src/services/tool-action-delivery.ts index 62365177ae3..8f7d15f1310 100644 --- a/server/src/services/tool-action-delivery.ts +++ b/server/src/services/tool-action-delivery.ts @@ -25,7 +25,11 @@ import { } from "@paperclipai/db"; import type { heartbeatService } from "./heartbeat.js"; import type { RequestConfirmationResult } from "@paperclipai/shared"; -import { githubAccessDeniedInstructions, projectGitHubActionResult } from "./tool-access/github-access-errors.js"; +import { + githubAccessErrorInstructions, + isGitHubAccessErrorCode, + projectGitHubActionResult, +} from "./tool-access/github-access-errors.js"; import { toolSourceTemplateKeySql } from "./tool-access/source-template-key.js"; const terminalStatuses: Array = [ @@ -237,6 +241,7 @@ export function toolActionDeliveryService( reason?: string; toolAction?: { resultSummary?: string; errorMessage?: string; errorCode?: string | null }; } | null; + const effectiveErrorCode = result?.toolAction?.errorCode ?? invocation.errorCode; const instructions = request.status === "executed" ? "The approved action already ran. Do not call it again; continue with the recorded result. Process the result and answer the user in your own words. Do not paste the raw tool or transport JSON unless the user asks for it." @@ -245,8 +250,8 @@ export function toolActionDeliveryService( : request.status === "expired" || request.status === "cancelled" ? "The review is no longer available. Do not execute the stored request. Explain the recorded outcome before requesting another review." - : (result?.toolAction?.errorCode ?? invocation.errorCode) === "github_access_denied" - ? githubAccessDeniedInstructions(invocation.toolName, connectionMethodKey) + : isGitHubAccessErrorCode(effectiveErrorCode) + ? githubAccessErrorInstructions(effectiveErrorCode, invocation.toolName, connectionMethodKey) : "The approved action did not complete successfully. Do not automatically replay it; inspect the recorded outcome first."; return { toolName: invocation.toolName.slice(0, 256), diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 06fe6295ea3..dd929277a72 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -40,7 +40,15 @@ import { currentConnectionToolDefinition } from "./connectors/paperclip-defined- import { composeConnectionInstructions } from "./connection-instructions.js"; import { googleWorkspaceToolTarget, googleWorkspaceGrantedScopes, isGoogleWorkspaceToolGranted } from "@paperclipai/shared"; import { isInsufficientConnectionScope, INSUFFICIENT_CONNECTION_SCOPE_MESSAGE } from "./connection-permission-errors.js"; -import { githubAccessDeniedInstructions, githubAccessError } from "./tool-access/github-access-errors.js"; +import { + extractGitHubTarget, + findUnreachableManagedGitHubTarget, + githubAccessError, + githubAccessErrorInstructions, + isGitHubAccessErrorCode, + suspendedManagedGitHubOwner, + type GitHubAccessSnapshot, +} from "./tool-access/github-access-errors.js"; import { githubDefaultOwnerApplies, githubDefaultOwnerArguments } from "./tool-access/github-default-owner.js"; import { toolSourceTemplateKeySql } from "./tool-access/source-template-key.js"; import { usesClientCredentials } from "./tool-access/oauth/client-credentials.js"; @@ -1704,9 +1712,13 @@ export function createToolGatewayService( await connectionManagementService(database).authorize(actor, "connections:gateway", resource, { mutation: false }); await connectionManagementService(database).authorize(actor, "connections:test", resource, { mutation: false }); } - async function recordToolInvocation(input: ToolAccessDecisionInput, decision: ToolAccessDecision) { + async function recordToolInvocation( + input: ToolAccessDecisionInput, + decision: ToolAccessDecision, + recordOptions?: { claimIdempotencyKey?: boolean }, + ) { try { - return await policyService.recordInvocation(input, decision); + return await policyService.recordInvocation(input, decision, recordOptions); } catch (error) { const details = error instanceof HttpError ? asRecord(error.details) : null; if (error instanceof HttpError && error.status === 409 && details?.reasonCode === "legacy_tool_idempotency_unverifiable") { @@ -5783,19 +5795,61 @@ export function createToolGatewayService( return { entry, connection, sourceTemplateKey: connected?.sourceTemplateKey ?? null }; } + type GovernedRemoteToolContext = { + connection: Awaited>["connection"]; + entry: Awaited>["entry"]; + sourceTemplateKey: string | null; + grant?: Awaited> | null; + }; + + async function resolveGovernedToolCall( + session: ToolGatewaySession, + tool: ToolGatewayDescriptor, + parameters: unknown, + ): Promise<{ parameters: unknown; remote: GovernedRemoteToolContext | null }> { + if (tool.providerType !== "mcp_remote_http" && tool.providerType !== "provider_rest") { + return { parameters, remote: null }; + } + const { connection, entry, sourceTemplateKey } = await resolveConnectedRemoteTool(session, tool); + const projected = projectedConnectionToolArguments(connection, parameters, entry.toolName, entry.inputSchema ?? {}); + if (!githubDefaultOwnerApplies(connection, entry.toolName, entry.inputSchema, projected)) { + return { parameters: projected, remote: { connection, entry, sourceTemplateKey } }; + } + // An unavailable credential keeps the call unchanged and fails with its own + // error at dispatch. + const grant = await resolveConnectionGrant(session, connection, false).catch(() => null); + return { + parameters: githubDefaultOwnerArguments(entry.toolName, projected, grant?.providerTenant?.github), + remote: { connection, entry, sourceTemplateKey, grant }, + }; + } + async function governedToolArguments( session: ToolGatewaySession, tool: ToolGatewayDescriptor, parameters: unknown, ): Promise { - if (tool.providerType !== "mcp_remote_http" && tool.providerType !== "provider_rest") return parameters; - const { connection, entry } = await resolveConnectedRemoteTool(session, tool); - const projected = projectedConnectionToolArguments(connection, parameters, entry.toolName, entry.inputSchema ?? {}); - if (!githubDefaultOwnerApplies(connection, entry.toolName, entry.inputSchema, projected)) return projected; - // An unavailable credential keeps the call unchanged and fails with its own - // error at dispatch. - const grant = await resolveConnectionGrant(session, connection, false).catch(() => null); - return githubDefaultOwnerArguments(entry.toolName, projected, grant?.providerTenant?.github); + return (await resolveGovernedToolCall(session, tool, parameters)).parameters; + } + + async function checkManagedGitHubWriteReachability( + session: ToolGatewaySession, + remote: GovernedRemoteToolContext | null, + parameters: unknown, + ) { + if (!remote || remote.sourceTemplateKey !== "github") return null; + const connectionMethodKey = remote.connection.config.connectionMethodKey ?? remote.connection.transportConfig.connectionMethodKey; + if (connectionMethodKey !== "managed") return null; + const grant = remote.grant !== undefined + ? remote.grant + : await resolveConnectionGrant(session, remote.connection, false).catch(() => null); + return findUnreachableManagedGitHubTarget({ + sourceTemplateKey: remote.sourceTemplateKey, + connectionMethodKey, + githubGrant: grant?.providerTenant?.github, + toolName: remote.entry.toolName, + parameters, + }); } async function approvedManagedArgumentsRemainCurrent( @@ -7534,12 +7588,18 @@ export function createToolGatewayService( transport: "mcp_http" | "local_stdio" | "cognee_cloud" = "mcp_http", spawnedLocalProcess = false, sourceTemplateKey?: string | null, + githubContext?: { + connectionMethodKey?: unknown; + githubGrant?: GitHubAccessSnapshot | null; + toolName?: string; + parameters?: unknown; + }, ) { const record = asRecord(result); if (!record) throw malformedRemoteMcpResponse(); const providerContent = normalizeMcpContent(record.content); const githubFailure = record.isError === true - ? githubAccessError(sourceTemplateKey, providerContent) : null; + ? githubAccessError(sourceTemplateKey, providerContent, githubContext) : null; const googleWorkspacePermissionDenied = record.isError === true && (sourceTemplateKey === "gmail" || @@ -9116,14 +9176,39 @@ export function createToolGatewayService( request: resultElicitation, }); } + const connectionMethodKey = connection.config.connectionMethodKey ?? connection.transportConfig.connectionMethodKey; const result = normalizeMcpToolResult( callResult, "mcp_http", false, sourceTemplateKey, + sourceTemplateKey === "github" + ? { connectionMethodKey, githubGrant: grant.providerTenant?.github, toolName: entry.toolName, parameters } + : undefined, ); - const failureInstructions = result.errorCode === "github_access_denied" - ? githubAccessDeniedInstructions(entry.toolName, connection.config.connectionMethodKey ?? connection.transportConfig.connectionMethodKey) + const githubTarget = isGitHubAccessErrorCode(result.errorCode) + ? extractGitHubTarget(entry.toolName, parameters) + : null; + const suspendedOwner = result.errorCode === "github_app_installation_suspended" + && connectionMethodKey === "managed" + ? suspendedManagedGitHubOwner( + grant.providerTenant?.github, + githubTarget ?? extractGitHubTarget(entry.toolName, parameters, result.content), + ) + : null; + const failureInstructions = isGitHubAccessErrorCode(result.errorCode) + ? githubAccessErrorInstructions( + result.errorCode, + entry.toolName, + connectionMethodKey, + result.errorCode === "github_repo_outside_app_installations" + ? githubTarget + : null, + result.errorCode === "github_repo_outside_app_installations" + ? grant.providerTenant?.github?.installationOwnerLogins + : undefined, + suspendedOwner ? { suspendedOwner } : undefined, + ) : undefined; await markCallHealth( "ok", @@ -10319,9 +10404,10 @@ export function createToolGatewayService( }); const providerResult = asRecord(resultValidation.value); if (providerResult?.error) { - throw new ToolGatewayHttpError(providerResult.errorCode === "github_access_denied" ? 403 : 502, + const githubCode = isGitHubAccessErrorCode(providerResult.errorCode) ? providerResult.errorCode : null; + throw new ToolGatewayHttpError(githubCode ? 403 : 502, toolResultErrorMessage(providerResult, connectedMcpExecution.failureInstructions), - providerResult.errorCode === "github_access_denied" ? "github_access_denied" : "tool_error", + githubCode ?? "tool_error", { execution: connectedMcpExecution.execution, ...connectedToolErrorDetails(connectedMcpExecution, providerResult) }); } } catch (err) { @@ -11205,13 +11291,15 @@ export function createToolGatewayService( promptInjectionMode: "block", classifier: resultClassifier(session, tool, invocation.id, { approvedAction: true }), }); const resultRecord = asRecord(resultValidation.value); - if (resultRecord?.error) + if (resultRecord?.error) { + const githubCode = isGitHubAccessErrorCode(resultRecord.errorCode) ? resultRecord.errorCode : null; throw new ToolGatewayHttpError( - resultRecord.errorCode === "github_access_denied" ? 403 : 502, + githubCode ? 403 : 502, toolResultErrorMessage(resultRecord, connectedMcpExecution?.failureInstructions), - resultRecord.errorCode === "github_access_denied" ? "github_access_denied" : "tool_execution_failed", + githubCode ?? "tool_execution_failed", connectedToolErrorDetails(connectedMcpExecution, resultRecord), ); + } const now = new Date(); await db .update(toolInvocations) @@ -13515,12 +13603,15 @@ export function createToolGatewayService( // approval signing, previews, and audit summaries. Approved retries // re-project only for a compatibility comparison and dispatch the // already-reviewed signed payload unchanged. + let governedRemote: GovernedRemoteToolContext | null = null; if (!input.approvedActionRequestId) { - requestedParameters = await governedToolArguments( + const governed = await resolveGovernedToolCall( session, tool, requestedParameters, ); + requestedParameters = governed.parameters; + governedRemote = governed.remote; } const argumentValidation = await validateToolContent({ @@ -13975,9 +14066,24 @@ export function createToolGatewayService( if (accessDecision.allowed && tool.providerType === "paperclip_slack_chat" && SLACK_TOOLS.some(t => t.name === tool.upstreamToolName && t.risk === "approval")) { accessDecision = { ...accessDecision, allowed: false, decision: "require_approval", reasonCode: "requires_approval_policy", explanation: "Slack destructive actions, channel creation and invitations require approval." }; } + const unreachableGitHubTarget = accessDecision.decision === "require_approval" && tool.risk !== "read" + ? await checkManagedGitHubWriteReachability(session, governedRemote, effectiveParameters) + : null; + if (unreachableGitHubTarget) { + accessDecision = { + ...accessDecision, + allowed: false, + decision: "deny", + reasonCode: "github_repo_outside_app_installations", + explanation: unreachableGitHubTarget.message, + }; + } const recorded = await recordToolInvocation( decisionInput, accessDecision, + accessDecision.reasonCode === "github_repo_outside_app_installations" + ? { claimIdempotencyKey: false } + : undefined, ); await policyService.writeAudit(decisionInput, accessDecision); invocationId = recorded.invocation.id; @@ -14223,10 +14329,11 @@ export function createToolGatewayService( ? asRecord(resultValidation.value) : null; if (validatedMcpResult?.error) { + const githubCode = isGitHubAccessErrorCode(validatedMcpResult.errorCode) ? validatedMcpResult.errorCode : null; throw new ToolGatewayHttpError( - validatedMcpResult.errorCode === "github_access_denied" ? 403 : 502, + githubCode ? 403 : 502, toolResultErrorMessage(validatedMcpResult, connectedMcpExecution?.failureInstructions), - validatedMcpResult.errorCode === "github_access_denied" ? "github_access_denied" : "tool_error", + githubCode ?? "tool_error", { execution: connectedMcpExecution?.execution, ...connectedToolErrorDetails(connectedMcpExecution, validatedMcpResult) }, ); } diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 79d666146e4..fd921e599ce 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -463,7 +463,7 @@ "packages/shared/src/types/tailscale.ts": "d02a917945d7779009a2dea4c4b535e9478e0680", "packages/shared/src/types/task-workspace.ts": "a23afa13d2cb58dc2eb72692ed28c16ed6fb84fb", "packages/shared/src/types/teams-catalog.ts": "632fe75f8e5a4cfc455843c2a1a2daff28a022be", - "packages/shared/src/types/tool-access.ts": "e517c0282ce65664eb281eafa8534c642a5943a8", + "packages/shared/src/types/tool-access.ts": "203dc803d733c0fda990cbd8d5fc0dabb457730b", "packages/shared/src/types/user-profile.ts": "1ac26e033a79fab21dc267fd983959814c8b680f", "packages/shared/src/types/voice-sessions.ts": "95e3b62cdd51f62290e68536728ddd7297bc0459", "packages/shared/src/types/work-product.ts": "26f9129f606a207ce7a218ccef40f96747283086", @@ -554,7 +554,7 @@ "packages/shared/src/validators/teams-catalog.ts": "7bddf40c091a52aaa54e79de784bea5ae496f9aa", "packages/shared/src/validators/text.ts": "74c430fe17cdcfd4b56dd08a4c57cd3d567670a8", "packages/shared/src/validators/tool-access.test.ts": "b5838320115946a936b256919a5bd3a2294c6070", - "packages/shared/src/validators/tool-access.ts": "0336b4b582f351c6beec350fc167fa829c44bb28", + "packages/shared/src/validators/tool-access.ts": "23d0b8959efdabd0fdb15e4309ea56ebdc321056", "packages/shared/src/validators/trust-policy.test.ts": "1fc4818984eb0e14f034d56ad147600224496d4e", "packages/shared/src/validators/trust-policy.ts": "f16b002db940b06bd882d51df8b5712c576e1d7b", "packages/shared/src/validators/voice-sessions.ts": "018a71f9ac544645041ac3cc9919e59c95fbe998", diff --git a/ui/src/components/IssueThreadInteractionCard.test.tsx b/ui/src/components/IssueThreadInteractionCard.test.tsx index e30ba777a2e..f809a4d03f5 100644 --- a/ui/src/components/IssueThreadInteractionCard.test.tsx +++ b/ui/src/components/IssueThreadInteractionCard.test.tsx @@ -1538,6 +1538,51 @@ describe("IssueThreadInteractionCard tool-action card", () => { expect(host.textContent).not.toContain("Approve & run"); }); + it("explains an unreachable external repository without offering misleading Manage GitHub access advice", () => { + const interaction = { ...failedToolActionInteraction, + payload: { ...failedToolActionInteraction.payload, toolAction: { + ...failedToolActionInteraction.payload.toolAction!, appDisplayName: "GitHub", + toolName: "mcp.github:create_issue", toolDisplayName: "Create issue", + } }, + result: { ...failedToolActionInteraction.result!, toolAction: { + ...failedToolActionInteraction.result!.toolAction!, errorCode: "github_repo_outside_app_installations", + errorMessage: "failed to create issue: POST https://api.github.com/repos/external-org/public-repo/issues: 403 Resource not accessible by integration []", + } }, + }; + const host = renderCard({ interaction }); + const alert = host.querySelector('[role="alert"]'); + expect(alert?.textContent).toContain("Repository outside GitHub App access"); + expect(alert?.textContent).toMatch(/not installed/i); + expect(alert?.textContent).toMatch(/post on GitHub directly|personal access token/i); + expect(host.textContent).not.toContain("GitHub access needed"); + expect(host.textContent).not.toContain("Manage GitHub access"); + expect(host.textContent).not.toContain("Retry"); + expect(host.textContent).not.toContain("Approve & run"); + expect(host.textContent).toContain(interaction.result.toolAction.errorMessage); + expect(host.querySelector("details")?.hasAttribute("open")).toBe(false); + }); + + it("offers unsuspend guidance and Manage GitHub access when the GitHub App installation is suspended", () => { + const interaction = { ...failedToolActionInteraction, + payload: { ...failedToolActionInteraction.payload, toolAction: { + ...failedToolActionInteraction.payload.toolAction!, appDisplayName: "GitHub", + toolName: "mcp.github:create_issue", toolDisplayName: "Create issue", + } }, + result: { ...failedToolActionInteraction.result!, toolAction: { + ...failedToolActionInteraction.result!.toolAction!, errorCode: "github_app_installation_suspended", + errorMessage: "failed to create issue: POST https://api.github.com/repos/suspended-org/app/issues: 403 Resource not accessible by integration []", + } }, + }; + const host = renderCard({ interaction }); + const alert = host.querySelector('[role="alert"]'); + expect(alert?.textContent).toContain("GitHub App installation suspended"); + expect(alert?.textContent).toMatch(/unsuspend/i); + const manage = Array.from(host.querySelectorAll("a")).find(link => link.textContent === "Manage GitHub access"); + expect(manage?.getAttribute("href")).toBe(`/apps/${interaction.payload.toolAction.connectionId}/permissions`); + expect(host.textContent).not.toContain("Repository outside GitHub App access"); + expect(host.querySelector("details")?.hasAttribute("open")).toBe(false); + }); + it("renders the expired state without decision controls", () => { const host = renderCard({ interaction: expiredToolActionInteraction }); diff --git a/ui/src/components/IssueThreadInteractionCard.tsx b/ui/src/components/IssueThreadInteractionCard.tsx index cc3e09be9f2..05d63a5111d 100644 --- a/ui/src/components/IssueThreadInteractionCard.tsx +++ b/ui/src/components/IssueThreadInteractionCard.tsx @@ -1974,6 +1974,22 @@ function ToolActionResolution({ {detail ?
Error details

{detail}

: null} ; } + if (state === "failed" && result?.errorCode === "github_app_installation_suspended") { + const connectionId = interaction.payload.toolAction?.connectionId; + return
+

+

The Paperclip GitHub App installation for this account or organization is suspended. Ask an administrator to unsuspend it on GitHub, refresh access on the Permissions page, then ask the agent to continue.

+ {connectionId ? : null} + {detail ?
Error details

{detail}

: null} +
; + } + if (state === "failed" && result?.errorCode === "github_repo_outside_app_installations") { + return
+

+

The Paperclip GitHub App is not installed on this repository’s organization or account, so refreshing access cannot grant write permission here. Post on GitHub directly, use a personal access token connection, or have an administrator of that organization install the Paperclip GitHub App.

+ {detail ?
Error details

{detail}

: null} +
; + } const status = <> {labels[state]} diff --git a/ui/storybook/stories/questions-and-approvals/connection-reviews.stories.tsx b/ui/storybook/stories/questions-and-approvals/connection-reviews.stories.tsx index bfd4c03df43..5034af75519 100644 --- a/ui/storybook/stories/questions-and-approvals/connection-reviews.stories.tsx +++ b/ui/storybook/stories/questions-and-approvals/connection-reviews.stories.tsx @@ -356,6 +356,20 @@ export const GitHubAccessNeeded: Story = { } }, }]} />, }; +export const GitHubRepoOutsideAppAccess: Story = { + render: () => , +}; export const Declined: Story = { render: () => , };