From 6714ad6b6854bdcc695eaca4ad083f36f11abba2 Mon Sep 17 00:00:00 2001 From: Dotta Date: Wed, 25 Nov 2026 14:16:39 -0600 Subject: [PATCH] fix(github): insert pre-check denials without idempotency key, keep incomplete snapshots on github_access_denied, and persist suspended error code Addresses review findings cleanly: - Passes { claimIdempotencyKey: false } to policyService.recordInvocation so github_repo_outside_app_installations pre-check denials insert with idempotencyKey: null atomically in the single INSERT (removing the compensating follow-up UPDATE). - Drops allowIncompleteSnapshot so webhook-invalidated snapshots (bindingSync set or installationIds ahead of installationOwnerLogins with repositories cleared) fall back to github_access_denied on both pre-check and runtime 403 until access is refreshed. - Introduces github_app_installation_suspended for suspended managed GitHub App installations so immediate dispatch, continuation wakes (tool-action-delivery), and IssueThreadInteractionCard all render consistent unsuspend + Refresh access guidance. Co-Authored-By: Paperclip --- doc/connections/GITHUB.md | 9 ++-- .../tool-gateway-action-approvals.test.ts | 9 +++- server/src/__tests__/tool-gateway.test.ts | 8 +++- .../src/services/agent-task-run-telemetry.ts | 1 + server/src/services/continuation-cause.ts | 2 +- server/src/services/tool-access-policy.ts | 8 +++- .../tool-access/github-access-errors.test.ts | 48 +++++++++++++------ .../tool-access/github-access-errors.ts | 43 +++++++++++------ server/src/services/tool-gateway.ts | 19 ++++---- .../IssueThreadInteractionCard.test.tsx | 21 ++++++++ .../components/IssueThreadInteractionCard.tsx | 9 ++++ 11 files changed, 131 insertions(+), 46 deletions(-) diff --git a/doc/connections/GITHUB.md b/doc/connections/GITHUB.md index 9b37676ea8b..e660b1b036e 100644 --- a/doc/connections/GITHUB.md +++ b/doc/connections/GITHUB.md @@ -142,10 +142,11 @@ 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 still classify as `github_access_denied` with unsuspend guidance -instead of advising a fresh install. When an installation webhook marks the -owner snapshot incomplete (`bindingSync`), the pre-check defers to GitHub until -access is refreshed. Failed cards and agent continuation instructions explain +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 diff --git a/server/src/__tests__/tool-gateway-action-approvals.test.ts b/server/src/__tests__/tool-gateway-action-approvals.test.ts index 31ba6fdeff4..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,7 @@ 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" }, @@ -285,12 +286,18 @@ describeToolGatewayEmbeddedPostgres("tool gateway service: action approvals", () const instructions: string = payload.toolAction.instructions; // Retrying or re-approving hits the same GitHub refusal. const outsideApp = errorCode === "github_repo_outside_app_installations"; - const trustedGitHubDenial = outsideApp || errorCode === "github_access_denied" || (sourceKey === "github" && method !== "foreign"); + 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(trustedGitHubDenial ? /do not retry.*until GitHub access is repaired/i : /did not complete successfully/); // Concrete next step the agent can relay to the user. diff --git a/server/src/__tests__/tool-gateway.test.ts b/server/src/__tests__/tool-gateway.test.ts index 22dceac17b2..ea2caad8d9c 100644 --- a/server/src/__tests__/tool-gateway.test.ts +++ b/server/src/__tests__/tool-gateway.test.ts @@ -967,6 +967,12 @@ describeEmbeddedPostgres("tool gateway acceptance", () => { 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" }; @@ -1094,7 +1100,7 @@ describeEmbeddedPostgres("tool gateway acceptance", () => { tool: toolName, parameters: { owner: "suspended-org", repo: "app", title: "Suspended write" }, }).catch((err) => err); - expect(suspendedFailure).toMatchObject({ reasonCode: "github_access_denied" }); + 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"); diff --git a/server/src/services/agent-task-run-telemetry.ts b/server/src/services/agent-task-run-telemetry.ts index c4d97cd283e..57e001e4a79 100644 --- a/server/src/services/agent-task-run-telemetry.ts +++ b/server/src/services/agent-task-run-telemetry.ts @@ -53,6 +53,7 @@ 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", diff --git a/server/src/services/continuation-cause.ts b/server/src/services/continuation-cause.ts index 8a87a06dbb3..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_outside_app_installations", "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 6b0944c38ad..c4dcf0b1d4e 100644 --- a/server/src/services/tool-access-policy.ts +++ b/server/src/services/tool-access-policy.ts @@ -1866,7 +1866,11 @@ export function toolAccessPolicyService(db: Pick { toolName: "mcp.github:create_issue", parameters: { owner: "paperclipai", repo: "a", title: "Bug" }, })).toBeNull(); - // Runtime 403 on suspended owner classifies as github_access_denied (not outside installations). + // 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 []", @@ -245,10 +245,10 @@ describe("GitHub tool access failures", () => { toolName: "mcp.github:create_issue", parameters: { owner: "paperclipai", repo: "a", title: "Bug" }, }, - )).toEqual({ errorCode: "github_access_denied" }); - // Unsuspend guidance points operators to unsuspend and then Refresh access. + )).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_access_denied", + "github_app_installation_suspended", "mcp.github:create_issue", "managed", null, @@ -259,9 +259,17 @@ describe("GitHub tool access failures", () => { 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 skips pre-check on webhook-invalidated snapshots", () => { + 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. @@ -287,19 +295,31 @@ describe("GitHub tool access failures", () => { parameters: { name: "site", organization: "external-org" }, })).toMatchObject({ owner: "external-org" }); - // Webhook-invalidated snapshot (bindingSync present / repositories cleared) skips pre-check. + // 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: { - login: "octocat", - installationIds: ["9", "11"], - installationOwnerLogins: ["acme"], - repositories: undefined, - bindingSync: { id: "sync-1", removeInstallationIds: [] }, - }, + githubGrant: webhookSnapshot, toolName: "mcp.github:create_issue", - parameters: { owner: "external-org", repo: "public-repo" }, + 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 d955b0fad8a..f0a2da16ca1 100644 --- a/server/src/services/tool-access/github-access-errors.ts +++ b/server/src/services/tool-access/github-access-errors.ts @@ -1,14 +1,17 @@ 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; } @@ -186,13 +189,10 @@ export function findUnreachableManagedGitHubTarget(input: { toolName: string; parameters?: unknown; providerMessage?: unknown; - /** Skip pre-check when webhooks have invalidated the owner snapshot. */ - allowIncompleteSnapshot?: boolean; }): { 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) return null; - if (snapshot.incomplete && !input.allowIncompleteSnapshot) return null; + if (!snapshot || snapshot.incomplete) return null; const target = extractGitHubTarget(input.toolName, input.parameters, input.providerMessage); if (!target) return null; const targetOwnerLower = target.owner.toLowerCase(); @@ -225,16 +225,21 @@ export function githubAccessError( ): { 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; - if (context && findUnreachableManagedGitHubTarget({ - sourceTemplateKey, - connectionMethodKey: context.connectionMethodKey, - githubGrant: context.githubGrant, - toolName: context.toolName ?? "", - parameters: context.parameters, - providerMessage: message, - allowIncompleteSnapshot: true, - })) { - return { errorCode: GITHUB_REPO_OUTSIDE_APP_INSTALLATIONS_ERROR_CODE }; + 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 }; } @@ -293,6 +298,13 @@ export function githubAccessDeniedInstructions( 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, @@ -304,5 +316,8 @@ export function githubAccessErrorInstructions( 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-gateway.ts b/server/src/services/tool-gateway.ts index 53e406b4382..dd929277a72 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -1712,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") { @@ -9185,7 +9189,7 @@ export function createToolGatewayService( const githubTarget = isGitHubAccessErrorCode(result.errorCode) ? extractGitHubTarget(entry.toolName, parameters) : null; - const suspendedOwner = result.errorCode === "github_access_denied" + const suspendedOwner = result.errorCode === "github_app_installation_suspended" && connectionMethodKey === "managed" ? suspendedManagedGitHubOwner( grant.providerTenant?.github, @@ -14077,15 +14081,12 @@ export function createToolGatewayService( 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; - if (!recorded.replayed && accessDecision.reasonCode === "github_repo_outside_app_installations") { - await db - .update(toolInvocations) - .set({ idempotencyKey: null, updatedAt: new Date() }) - .where(eq(toolInvocations.id, invocationId)); - } const retryingSlackRateLimit = recorded.replayed && accessDecision.allowed && tool.providerType === "paperclip_slack_chat" && session.agentId && session.runId && session.issueId ? await claimSlackRateLimitRetry(db, { companyId: session.companyId, agentId: session.agentId, runId: session.runId, issueId: session.issueId, endpointId: String(asRecord(tool.providerMetadata)?.endpointId ?? ""), identityContextId: session.identityContextId }, invocationId) : false; diff --git a/ui/src/components/IssueThreadInteractionCard.test.tsx b/ui/src/components/IssueThreadInteractionCard.test.tsx index 6830f6bd2fe..f809a4d03f5 100644 --- a/ui/src/components/IssueThreadInteractionCard.test.tsx +++ b/ui/src/components/IssueThreadInteractionCard.test.tsx @@ -1562,6 +1562,27 @@ describe("IssueThreadInteractionCard tool-action card", () => { 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 061c8681362..05d63a5111d 100644 --- a/ui/src/components/IssueThreadInteractionCard.tsx +++ b/ui/src/components/IssueThreadInteractionCard.tsx @@ -1974,6 +1974,15 @@ 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