fix(github): preserve suspended installations, handle stale webhooks, and reuse canonical denial path

Addresses review feedback on managed GitHub App reachability:
- Preserves suspended installation owner logins separately in
  suspendedInstallationOwnerLogins (github-access-discovery.ts, shared types/
  validators, and connection_grants JSONB type) so writes targeting suspended
  installations remain github_access_denied with explicit unsuspend guidance
  instead of github_repo_outside_app_installations install advice.
- Skips the pre-check when an installation webhook marks the owner snapshot
  incomplete (bindingSync present / repositories cleared) and clarifies in
  trusted instructions that after an org admin installs the App, the user
  should refresh access on the Permissions page and retry.
- Reuses the canonical policy denial path in tool-gateway.ts (adding
  github_repo_outside_app_installations to ToolAccessReasonCode and clearing
  idempotencyKey on non-replayed denials) and reuses the already-resolved
  remote tool context from resolveGovernedToolCall to avoid redundant lookups
  for non-GitHub providers.
- Adds unit and gateway integration tests for suspended installations,
  webhook-invalidated snapshots, and create_repository omitted-organization
  behavior.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-11-25 14:02:44 -06:00
1 parent 7c699213f3
commit 41044ca814
11 files changed
+319 -120

No files matched your search

+10 -4
View File
@@ -140,10 +140,16 @@ account and repository there. When a managed GitHub App write targets an externa
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`. Failed cards and agent continuation instructions explain
that refreshing access cannot grant write permission to external repositories where
the App is not installed, and advise posting directly on GitHub, using a personal
access token connection, or having an organization administrator install the App.
`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
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.
+1
View File
@@ -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;
+2
View File
@@ -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 {
@@ -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(),
@@ -108,6 +108,7 @@ describe("GitHub grant metadata", () => {
repositorySelection: "selected",
installationIds: ["102"],
installationOwnerLogins: ["octocat"],
suspendedInstallationOwnerLogins: ["paperclipai"],
repositories: [{ id: "2", fullName: "octocat/b", installationId: "102" }],
});
});
+57
View File
@@ -1070,6 +1070,63 @@ describeEmbeddedPostgres("tool gateway acceptance", () => {
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_access_denied" });
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(); }
});
@@ -79,6 +79,7 @@ export async function loadGitHubGrantMetadata(
repositorySelection: "all" | "selected" | "mixed" | "none";
installationIds: string[];
installationOwnerLogins: string[];
suspendedInstallationOwnerLogins?: string[];
repositories: Array<{
id: string;
fullName: string;
@@ -165,6 +166,7 @@ export async function loadGitHubGrantMetadata(
const installations = await list("/user/installations", "installations");
const installationIds: string[] = [];
const owners = new Set<string>();
const suspendedOwners = new Set<string>();
const selections = new Set<"all" | "selected">();
const managementUrls = new Set<string>();
const suspendedManagementUrls = new Set<string>();
@@ -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),
),
@@ -215,6 +215,91 @@ describe("GitHub tool access failures", () => {
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_access_denied (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_access_denied" });
// Unsuspend guidance points operators to unsuspend and then Refresh access.
const guidance = githubAccessErrorInstructions(
"github_access_denied",
"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");
});
it("handles create_repository omitted organization and skips pre-check 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.
expect(findUnreachableManagedGitHubTarget({
sourceTemplateKey: "github",
connectionMethodKey: "managed",
githubGrant: {
login: "octocat",
installationIds: ["9", "11"],
installationOwnerLogins: ["acme"],
repositories: undefined,
bindingSync: { id: "sync-1", removeInstallationIds: [] },
},
toolName: "mcp.github:create_issue",
parameters: { owner: "external-org", repo: "public-repo" },
})).toBeNull();
});
});
@@ -14,7 +14,11 @@ export function isGitHubAccessErrorCode(code: unknown): code is GitHubAccessErro
export interface GitHubAccessSnapshot {
login?: unknown;
installationIds?: unknown;
installationOwnerLogins?: unknown;
suspendedInstallationOwnerLogins?: unknown;
repositories?: unknown;
bindingSync?: unknown;
}
export interface GitHubTarget {
@@ -58,6 +62,21 @@ function parseFullName(value: unknown): GitHubTarget | null {
return owner && repo ? { owner, repo } : null;
}
function collectValidOwners(values: unknown): { list: string[]; set: Set<string> } {
const list: string[] = [];
const set = new Set<string>();
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
@@ -114,28 +133,52 @@ function normalizedInstalledOwners(githubGrant: GitHubAccessSnapshot | null | un
login: string;
installedOwners: string[];
installedOwnerSet: Set<string>;
suspendedOwnerSet: Set<string>;
incomplete: boolean;
} | null {
if (!githubGrant) return null;
const login = validOwner(githubGrant.login);
if (!login || !Array.isArray(githubGrant.installationOwnerLogins)) return null;
const seen = new Set<string>();
const installedOwners: string[] = [];
for (const entry of githubGrant.installationOwnerLogins) {
const owner = validOwner(entry);
if (!owner) continue;
const key = owner.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
installedOwners.push(owner);
}
if (installedOwners.length === 0) return null;
return { login, installedOwners, installedOwnerSet: seen };
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). Refreshing access cannot grant write access to
* third-party orgs where the App is not installed. */
* 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;
@@ -143,14 +186,21 @@ 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;
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)) {
if (
targetOwnerLower === snapshot.login.toLowerCase()
|| snapshot.installedOwnerSet.has(targetOwnerLower)
|| snapshot.suspendedOwnerSet.has(targetOwnerLower)
) {
return null;
}
return {
@@ -182,6 +232,7 @@ export function githubAccessError(
toolName: context.toolName ?? "",
parameters: context.parameters,
providerMessage: message,
allowIncompleteSnapshot: true,
})) {
return { errorCode: GITHUB_REPO_OUTSIDE_APP_INSTALLATIONS_ERROR_CODE };
}
@@ -213,13 +264,17 @@ export function githubOutsideAppInstallationsInstructions(
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. Never automatically replay an approved write. Refreshing access cannot grant write permission to repositories outside the Paperclip GitHub App's installations. 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 first.`;
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") {
@@ -228,6 +283,10 @@ 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.`;
}
@@ -240,9 +299,10 @@ export function githubAccessErrorInstructions(
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);
}
return githubAccessDeniedInstructions(toolName, connectionMethodKey);
return githubAccessDeniedInstructions(toolName, connectionMethodKey, options);
}
+70 -95
View File
@@ -46,6 +46,8 @@ import {
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";
@@ -5789,37 +5791,59 @@ export function createToolGatewayService(
return { entry, connection, sourceTemplateKey: connected?.sourceTemplateKey ?? null };
}
type GovernedRemoteToolContext = {
connection: Awaited<ReturnType<typeof resolveConnectedRemoteTool>>["connection"];
entry: Awaited<ReturnType<typeof resolveConnectedRemoteTool>>["entry"];
sourceTemplateKey: string | null;
grant?: Awaited<ReturnType<typeof resolveConnectionGrant>> | 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<unknown> {
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,
tool: ToolGatewayDescriptor,
remote: GovernedRemoteToolContext | null,
parameters: unknown,
) {
if (tool.providerType !== "mcp_remote_http" && tool.providerType !== "provider_rest") return null;
const resolved = await resolveConnectedRemoteTool(session, tool).catch(() => null);
if (!resolved || resolved.sourceTemplateKey !== "github") return null;
const connectionMethodKey = resolved.connection.config.connectionMethodKey ?? resolved.connection.transportConfig.connectionMethodKey;
if (!remote || remote.sourceTemplateKey !== "github") return null;
const connectionMethodKey = remote.connection.config.connectionMethodKey ?? remote.connection.transportConfig.connectionMethodKey;
if (connectionMethodKey !== "managed") return null;
const grant = await resolveConnectionGrant(session, resolved.connection, false).catch(() => null);
const grant = remote.grant !== undefined
? remote.grant
: await resolveConnectionGrant(session, remote.connection, false).catch(() => null);
return findUnreachableManagedGitHubTarget({
sourceTemplateKey: resolved.sourceTemplateKey,
sourceTemplateKey: remote.sourceTemplateKey,
connectionMethodKey,
githubGrant: grant?.providerTenant?.github,
toolName: resolved.entry.toolName,
toolName: remote.entry.toolName,
parameters,
});
}
@@ -7562,7 +7586,7 @@ export function createToolGatewayService(
sourceTemplateKey?: string | null,
githubContext?: {
connectionMethodKey?: unknown;
githubGrant?: { login?: unknown; installationOwnerLogins?: unknown } | null;
githubGrant?: GitHubAccessSnapshot | null;
toolName?: string;
parameters?: unknown;
},
@@ -9158,17 +9182,28 @@ export function createToolGatewayService(
? { connectionMethodKey, githubGrant: grant.providerTenant?.github, toolName: entry.toolName, parameters }
: undefined,
);
const githubTarget = isGitHubAccessErrorCode(result.errorCode)
? extractGitHubTarget(entry.toolName, parameters)
: null;
const suspendedOwner = result.errorCode === "github_access_denied"
&& 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"
? extractGitHubTarget(entry.toolName, parameters)
? githubTarget
: null,
result.errorCode === "github_repo_outside_app_installations"
? grant.providerTenant?.github?.installationOwnerLogins
: undefined,
suspendedOwner ? { suspendedOwner } : undefined,
)
: undefined;
await markCallHealth(
@@ -13564,12 +13599,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({
@@ -14025,85 +14063,16 @@ export function createToolGatewayService(
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, tool, effectiveParameters)
? await checkManagedGitHubWriteReachability(session, governedRemote, effectiveParameters)
: null;
if (unreachableGitHubTarget) {
const deniedAt = new Date();
const [deniedInvocation] = await db
.insert(toolInvocations)
.values({
companyId: session.companyId,
idempotencyKey: null,
actorType: decisionInput.actor.actorType,
actorId: decisionInput.actor.actorId,
agentId: session.agentId,
issueId: session.issueId,
runId: session.runId,
gatewayId: session.gatewayId ?? null,
applicationId: tool.applicationId ?? null,
connectionId: tool.connectionId ?? null,
catalogEntryId: tool.catalogEntryId ?? null,
providerType: tool.providerType,
applicationKey: tool.applicationKey ?? null,
upstreamToolName: tool.upstreamToolName ?? null,
riskLevel: tool.risk,
toolName: tool.name,
argumentsHash: toolRequestIdentityHash(effectiveParameters, options.toolActionSigningSecret),
argumentsSummary: effectiveArgumentsSummary,
policyDecision: "deny",
policyExplanation: accessDecision.policyExplanation ?? null,
matchedPolicyIds: accessDecision.matchedPolicyIds,
approvalState: "not_required",
status: "denied",
errorCode: "github_repo_outside_app_installations",
errorMessage: unreachableGitHubTarget.message,
completedAt: deniedAt,
})
.returning({ id: toolInvocations.id });
invocationId = deniedInvocation.id;
void emitConnectionInvoked(db, invocationId);
await writeToolCallEvent({
invocationId,
session,
eventType: "call_denied",
outcome: "denied",
toolName: tool.name,
policyDecision: "deny",
accessDecision = {
...accessDecision,
allowed: false,
decision: "deny",
reasonCode: "github_repo_outside_app_installations",
errorMessage: unreachableGitHubTarget.message,
argumentsSummary: effectiveArgumentsSummary,
tool,
});
await writeAudit({
session,
companyId: session.companyId,
agentId: session.agentId,
runId: session.runId,
issueId: session.issueId,
action: "tool_gateway.call_denied",
details: {
invocationId,
decision: "deny",
reasonCode: "github_repo_outside_app_installations",
matchedPolicyIds: accessDecision.matchedPolicyIds,
tool: tool.name,
virtualToolName,
targetToolName: virtualToolName ? tool.name : undefined,
...toolAuditMetadata(tool),
argumentsSummary: effectiveArgumentsSummary,
},
});
throw new ToolGatewayHttpError(
403,
unreachableGitHubTarget.message,
"github_repo_outside_app_installations",
{
invocationId,
tool: tool.name,
decision: "deny",
matchedPolicyIds: accessDecision.matchedPolicyIds,
},
);
explanation: unreachableGitHubTarget.message,
};
}
const recorded = await recordToolInvocation(
decisionInput,
@@ -14111,6 +14080,12 @@ export function createToolGatewayService(
);
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;
@@ -462,7 +462,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",
@@ -553,7 +553,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",