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 <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-11-25 14:16:39 -06:00
1 parent 621cbeada8
commit 6714ad6b68
11 files changed
+131 -46

No files matched your search

+5 -4
View File
@@ -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
@@ -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.
+7 -1
View File
@@ -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");
@@ -53,6 +53,7 @@ const FAILURE_CAUSE_BY_ERROR_CODE: Record<string, AgentRunFailureCause> = {
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",
+1 -1
View File
@@ -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.
+6 -2
View File
@@ -1866,7 +1866,11 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
}
}
async function recordInvocation(input: ToolAccessDecisionInput, accessDecision: ToolAccessDecision) {
async function recordInvocation(
input: ToolAccessDecisionInput,
accessDecision: ToolAccessDecision,
recordOptions?: { claimIdempotencyKey?: boolean },
) {
const loaded = await loadContext(input);
if (!loaded.ok) throw new Error("Cannot record invocation for invalid tool access context");
const { ctx, redaction } = loaded;
@@ -1955,7 +1959,7 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
: "denied";
const [invocation] = await db.insert(toolInvocations).values({
companyId: ctx.companyId,
idempotencyKey,
idempotencyKey: recordOptions?.claimIdempotencyKey === false ? null : idempotencyKey,
actorType: ctx.actorType,
actorId: ctx.actorId,
agentId: ctx.agentId,
@@ -235,7 +235,7 @@ describe("GitHub tool access failures", () => {
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" });
});
});
@@ -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);
}
+10 -9
View File
@@ -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;
@@ -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 });
@@ -1974,6 +1974,15 @@ function ToolActionResolution({
{detail ? <details className="text-xs text-muted-foreground"><summary className="cursor-pointer">Error details</summary><p className="mt-2 break-words">{detail}</p></details> : null}
</div>;
}
if (state === "failed" && result?.errorCode === "github_app_installation_suspended") {
const connectionId = interaction.payload.toolAction?.connectionId;
return <div role="alert" className="space-y-2 rounded-lg bg-destructive/10 p-3 text-sm text-foreground">
<p className="flex items-center gap-2 font-medium"><AlertTriangle className="size-4 shrink-0 text-destructive" aria-hidden="true" />GitHub App installation suspended</p>
<p>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.</p>
{connectionId ? <Button asChild size="sm" variant="outline"><Link to={appTabHref(connectionId, "permissions")}>Manage GitHub access</Link></Button> : null}
{detail ? <details className="text-xs text-muted-foreground"><summary className="cursor-pointer">Error details</summary><p className="mt-2 break-words">{detail}</p></details> : null}
</div>;
}
if (state === "failed" && result?.errorCode === "github_repo_outside_app_installations") {
return <div role="alert" className="space-y-2 rounded-lg bg-destructive/10 p-3 text-sm text-foreground">
<p className="flex items-center gap-2 font-medium"><AlertTriangle className="size-4 shrink-0 text-destructive" aria-hidden="true" />Repository outside GitHub App access</p>