fix: preserve gateway approval admission without pool stalls

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-27 15:59:42 -05:00
1 parent 8dfe3958db
commit 4161939032
6 files changed
+121 -28

No files matched your search

+46
View File
@@ -333,3 +333,49 @@ case because its reused HTTP database still held the previous run's bot identity
The existing ownership guard correctly rejected the duplicate connection. A fresh
dedicated fixture resolved that environment collision; no product behavior or
assertion changed for the rerun. That failed run remains part of the evidence.
## Gateway admission uses its transaction connection
Review of the master-targeted branch exposed a delegated gateway deadlock: the
admission transaction held the sole pool connection while issuer/token authority
reads used the root client. Foreground approval and approved recovery each failed
the real one-connection regression; a revoked-issuer control already passed.
The admission callback now receives its transaction and passes it through the
existing issuer authority checks. Both connection authorization checks and the
token read use that connection. Ordinary checks retain their root client, and
current authority, claim, company and rate enforcement remain in place.
The three constrained-pool cases pass, as do all 81 HTTP integration cases and
190 gateway, policy, startup and deadline consumer cases. The initial consumer
command selected an incorrect policy filename and omitted the gateway database
override; it was interrupted and is not counted as passing evidence.
## Pending historical approvals retain their original admission
A second review finding concerned the normal foreground approval gate, before
execution has claimed and rebound historical arguments. A real PostgreSQL
regression with signed sensitive arguments and an already-consumed limit of one
failed with `rate_limited`; the Test-tab and invalid-signature controls passed.
The gateway now supplies the preview digest only after verifying the signed
payload and matching either supported form of the review's canonical digest. Policy may match that digest
only in a read-only preflight, with every other invocation-context field and
stored rate-rule receipt still checked. The consuming admission continues to
require the complete keyed identity, rebound under the exact execution claim.
New or changed rate rules still apply. Historical recovery, invalid signatures,
foreign invocation hashes, stale claims, and provider argument preservation stay
covered. This adds no schema, recurring query or additional connection.
The preceding CI head also failed E2E shard 3/8. Its failure is retained in the
validation record; local gateway checks do not erase it. Fresh-head CI and both
required automated reviews remain merge gates.
The five full gateway/policy/startup/deadline suites passed 329 cases before the
additional mixed historical identity control. The first combined attempt is
retained: a Test-tab failure-result assertion incorrectly expected a thrown
error, and reusing the earlier HTTP database left formal-approval foreign keys
that prevented gateway acceptance setup. The assertion now checks the existing
failed-result contract, with unchanged no-provider, hash and counter checks;
the complete acceptance rerun used an independently migrated gateway database.
Server production typechecking and build passed. The earlier E2E failure was a
500 during the agent-chat project-plan fixture restoration, with a PostgreSQL
deadlock in cancellation; it remains a fresh-head CI gate.
@@ -1,10 +1,12 @@
import { createToolGatewayService } from "../services/tool-gateway.js";
import { commitToolActionReview } from "../services/tool-action-review.js";
import { googleWorkspaceSelectedScopes, defaultGitHubReviewPolicy, SLACK_CHAT_BOT_SCOPES, SLACK_BOT_TOOL_SCOPES } from "@paperclipai/shared";
import { randomUUID, generateKeyPairSync } from "node:crypto";
import { join } from "node:path";
import { createServer } from "node:http";
import { and, eq } from "drizzle-orm";
import { and, eq, sql } from "drizzle-orm";
import { beforeAll, afterAll, describe, expect, it, vi } from "vitest";
import { activityLog, agentApiKeys, companies, companySecrets, companySecretVersions, chatConversations, chatDeliveries, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, toolPolicies, toolRateLimitCounters, connectionGrants, connectionGrantDelegations, toolAccessAuditEvents, toolOauthStates, issueThreadInteractions, connectionIntentDeliveries, agents, companyMemberships, heartbeatRuns, issues, principalPermissionGrants, projects, toolConnections, toolMcpGateways, toolMcpGatewayTokens, toolActionRequests, toolCatalogEntries, toolInvocations, toolCallEvents, toolProfileBindings, plugins, adapterAuthSessions, environments, routines, chatGitHubReviews } from "@paperclipai/db";
import { createDb, activityLog, agentApiKeys, companies, companySecrets, companySecretVersions, chatConversations, chatDeliveries, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, toolPolicies, toolRateLimitCounters, connectionGrants, connectionGrantDelegations, toolAccessAuditEvents, toolOauthStates, issueThreadInteractions, connectionIntentDeliveries, agents, companyMemberships, heartbeatRuns, issues, principalPermissionGrants, projects, toolConnections, toolMcpGateways, toolMcpGatewayTokens, toolActionRequests, toolCatalogEntries, toolInvocations, toolCallEvents, toolProfileBindings, plugins, adapterAuthSessions, environments, routines, chatGitHubReviews } from "@paperclipai/db";
import { findSatisfiedToolConnection, satisfiedConnectionIntentService } from "../services/satisfied-connection-intents.js";
import { connectionManagementService, continuingConnectionManagement } from "../services/connection-management.js";
import { redactRunnerApiPayloads } from "../services/native-runtime/runner-api-log-redaction.js";
@@ -1253,7 +1255,7 @@ describe("connection management with production default agents", () => {
expect((await use()).status).toBeGreaterThanOrEqual(400);
});
it.each(["block", "ask", "ask-board", "ask-revoked", "ask-rate", "ask-new-rate", "ask-new-shared-rate", "ask-new-rate-target-block", "ask-token-revoked", "ask-token-deleted", "ask-token-scope", "ask-grant-revoked", "rate", "shared-rate", "target-block", "credential"] as const)("intersects gateway issuer and target rules (%s)", async mode => {
it.each(["block", "ask", "ask-board", "ask-revoked", "ask-rate", "ask-new-rate", "ask-new-shared-rate", "ask-new-rate-target-block", "ask-token-revoked", "ask-token-deleted", "ask-token-scope", "ask-grant-revoked", "ask-one-connection", "ask-one-connection-recovery", "ask-one-connection-revoked", "rate", "shared-rate", "target-block", "credential"] as const)("intersects gateway issuer and target rules (%s)", async mode => {
const f = await fixture();
const cookie = await server.humanSession(f.userId);
const createdTarget = await fetch(`${server.apiUrl}/api/companies/${f.companyId}/agents`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" },
@@ -1340,10 +1342,33 @@ describe("connection management with production default agents", () => {
if (mode === "ask-token-revoked") await server.db.update(toolMcpGatewayTokens).set({ revokedAt: new Date() }).where(eq(toolMcpGatewayTokens.id, token.body.id));
if (mode === "ask-token-deleted") await server.db.delete(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.id, token.body.id));
if (mode === "ask-token-scope") await server.db.update(toolMcpGatewayTokens).set({ allowedActions: ["tools/list"] }).where(eq(toolMcpGatewayTokens.id, token.body.id));
if (mode === "ask-grant-revoked") await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
const approvalDenied = ["ask-revoked", "ask-new-rate-target-block", "ask-token-revoked", "ask-token-deleted", "ask-token-scope", "ask-grant-revoked"].includes(mode);
const response = await fetch(`${server.apiUrl}/api/tool-gateway/action-requests/${action.id}/approve`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) });
expect(response.status, JSON.stringify(await response.json())).toBe(approvalDenied ? 403 : 200);
if (mode === "ask-grant-revoked" || mode === "ask-one-connection-revoked") await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections")));
const approvalDenied = ["ask-revoked", "ask-new-rate-target-block", "ask-token-revoked", "ask-token-deleted", "ask-token-scope", "ask-grant-revoked", "ask-one-connection-revoked"].includes(mode);
if (mode.startsWith("ask-one-connection")) {
const limited = createDb(server.databaseUrl, { maxConnections: 1, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
const service = createToolGatewayService(limited);
let timer: ReturnType<typeof setTimeout> | undefined;
let attempt: Promise<unknown> | undefined;
try {
if (mode === "ask-one-connection-recovery") await commitToolActionReview(server.db, {
companyId: f.companyId, actionRequestId: action.id, decision: "approved", actor: { userId: f.userId },
});
attempt = mode === "ask-one-connection-recovery" ? service.recoverApprovedActionReviews(f.companyId)
: service.approveActionRequest({ companyId: f.companyId, actionRequestId: action.id, actor: { userId: f.userId } });
void attempt.catch(() => undefined);
const completed = Promise.race([attempt, new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error("Single-connection gateway approval did not settle")), 5000);
})]);
if (approvalDenied) await expect(completed).rejects.toMatchObject({ status: 403 });
else await completed;
expect((await limited.execute(sql`select 1 as available`))[0].available).toBe(1);
} finally {
clearTimeout(timer); await limited.$client.end({ timeout: 1 }); await attempt?.catch(() => undefined);
}
} else {
const response = await fetch(`${server.apiUrl}/api/tool-gateway/action-requests/${action.id}/approve`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) });
expect(response.status, JSON.stringify(await response.json())).toBe(approvalDenied ? 403 : 200);
}
expect(calls).toBe(approvalDenied ? 0 : 1);
if (mode.startsWith("ask-new-")) {
const counters = await server.db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.companyId, f.companyId));
@@ -60,6 +60,7 @@ export async function startRunnerApiTestServer(options: {
const apiUrl = `http://127.0.0.1:${address.port}`;
setupRunnerPrpWebSocketServer(http, { apiUrl });
return {
databaseUrl: temporary.connectionString,
db, root, apiUrl, storage,
async humanSession(userId: string) {
if (!auth) throw new Error("Enable humanSessions for this fixture");
@@ -418,11 +418,15 @@ describeEmbeddedPostgres("tool gateway service", () => {
});
it.each([
...["agent", "test-tab"].flatMap(origin => ["valid", "new-rate", "invalid-signature", "foreign-hash"]
...["agent", "test-tab"].flatMap(origin => ["valid", "new-rate", "invalid-signature", "foreign-hash", "foreground-rate", "foreground-invalid-signature", "foreground-foreign-hash", "foreground-modern-review-hash"]
.map(state => ({ origin, state }))),
])("recovers historical preview-hash approval ($origin, $state)", async ({ origin, state }) => {
const remoteCall = providerFixture(); remoteCall.release();
const parameters = { value: "reviewed", apiKey: "synthetic-historical-approval-key" };
const foreground = state.startsWith("foreground-");
if (foreground) await db.insert(toolPolicies).values({ companyId: fixture.company.id,
name: "Already admitted historical action", policyType: "rate_limit", priority: 1,
selectors: {}, config: { limit: 1, windowSeconds: 3600, keyBy: ["company", "tool"] } });
const pending = origin === "agent" ? await agentRequest(remoteCall.provider, parameters)
: (await testRequest(remoteCall.provider, false, parameters)).pending;
const [originalInvocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId));
@@ -432,16 +436,25 @@ describeEmbeddedPostgres("tool gateway service", () => {
const legacyHash = summarizeToolValue(payload.arguments).sha256!;
const completeHash = toolRequestIdentityHash(payload.arguments, testToolActionSigningSecret);
expect(legacyHash).not.toBe(completeHash);
const storedHash = state === "foreign-hash" ? "e".repeat(64) : legacyHash;
const storedHash = state.endsWith("foreign-hash") ? "e".repeat(64) : legacyHash;
await db.update(toolInvocations).set({ argumentsHash: storedHash }).where(eq(toolInvocations.id, pending.invocationId));
await db.update(toolActionRequests).set({ canonicalArgumentsHash: legacyHash,
...(state === "invalid-signature" ? { signedArguments: "unreadable-old-signature" } : {}),
await db.update(toolActionRequests).set({ canonicalArgumentsHash: state === "foreground-modern-review-hash" ? completeHash : legacyHash,
...(["invalid-signature", "foreground-invalid-signature"].includes(state) ? { signedArguments: "unreadable-old-signature" } : {}),
}).where(eq(toolActionRequests.id, pending.id));
if (state === "new-rate") await db.insert(toolPolicies).values({ companyId: fixture.company.id,
name: "New admission for historical approval", policyType: "rate_limit", priority: 1,
selectors: {}, config: { limit: 1, windowSeconds: 3600, keyBy: ["company", "tool"] } });
await approve(pending); await startRecovery(); await settle();
if (state === "valid" || state === "new-rate") {
const counters = foreground ? await db.select().from(toolRateLimitCounters) : [];
if (foreground) {
expect(counters).toEqual([expect.objectContaining({ remaining: 0 })]);
const approval = gateway.approveActionRequest({ companyId: fixture.company.id,
actionRequestId: pending.id, actor: { userId: "board" } });
if (state === "foreground-invalid-signature") await expect(approval).rejects.toMatchObject({ reasonCode: "action_request_invalidated" });
else if (state === "foreground-foreign-hash" && origin === "agent") await expect(approval).rejects.toMatchObject({ reasonCode: "rate_limited" });
else await approval;
} else await approve(pending);
await startRecovery(); await settle();
if (state === "valid" || state === "new-rate" || state === "foreground-rate" || state === "foreground-modern-review-hash") {
await executed(pending);
expect((await db.select().from(toolInvocations))[0].argumentsHash).toBe(completeHash);
expect(remoteCall.provider).toHaveBeenCalledOnce();
@@ -450,10 +463,12 @@ describeEmbeddedPostgres("tool gateway service", () => {
.toEqual([expect.objectContaining({ limit: 1, remaining: 0 })]);
} else {
expect((await db.select().from(toolActionRequests))[0].status)
.toBe(state === "invalid-signature" ? "cancelled" : "failed");
.toBe(["invalid-signature", "foreground-invalid-signature"].includes(state) ? "cancelled"
: state === "foreground-foreign-hash" && origin === "agent" ? "pending" : "failed");
expect((await db.select().from(toolInvocations))[0].argumentsHash).toBe(storedHash);
expect(remoteCall.provider).not.toHaveBeenCalled();
}
if (foreground) expect(await db.select().from(toolRateLimitCounters)).toEqual(counters);
await quiet();
});
+7 -6
View File
@@ -1384,7 +1384,7 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
});
}
async function admittedRateLimitAdmissions(ctx: ToolAccessContext, invocationId: string): Promise<ConsumedRateAdmission[] | null> {
async function admittedRateLimitAdmissions(ctx: ToolAccessContext, invocationId: string, previewHash?: string): Promise<ConsumedRateAdmission[] | null> {
const [invocation] = await db.select({
actorType: toolInvocations.actorType, actorId: toolInvocations.actorId, agentId: toolInvocations.agentId,
runId: toolInvocations.runId, issueId: toolInvocations.issueId, gatewayId: toolInvocations.gatewayId,
@@ -1412,7 +1412,7 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
&& invocation.catalogEntryId === ctx.catalogEntryId && invocation.toolName === ctx.toolName
&& invocation.providerType === ctx.providerType && invocation.applicationKey === ctx.applicationKey
&& invocation.upstreamToolName === ctx.upstreamToolName
&& invocation.argumentsHash === ctx.argumentsHash;
&& (invocation.argumentsHash === ctx.argumentsHash || invocation.argumentsHash === previewHash);
if (!authorized) return null;
const stored = invocation.policyExplanation?.[isDelegatedCaller ? "delegatedCallerConsumedRateAdmissions" : "consumedRateAdmissions"];
return Array.isArray(stored) ? stored.filter((item): item is ConsumedRateAdmission => isRecord(item)
@@ -1428,6 +1428,7 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
evaluate?: (
policy: Pick<ReturnType<typeof toolAccessPolicyService>, "decide" | "writeAudit">,
input: ToolAccessDecisionInput,
transaction: Db,
) => Promise<ToolAccessDecision>,
): Promise<ToolAccessDecision> {
try {
@@ -1460,7 +1461,7 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
// Composed caller/target policy must share this claim transaction so
// either all new charges and receipts commit or all roll back.
const result = evaluate
? await evaluate(admissionPolicy, admissionInput)
? await evaluate(admissionPolicy, admissionInput, tx as unknown as Db)
: await admissionPolicy.decide(admissionInput, { admittedInvocationId: invocationId });
if (!result.allowed && result.decision !== "require_approval") {
// A later policy can reject after an earlier rate rule spent a slot.
@@ -1493,7 +1494,7 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
*/
async function decide(
input: ToolAccessDecisionInput,
options: { cache?: ToolAccessDecisionCache; admittedInvocationId?: string; sharedRateDecision?: ToolAccessDecision } = {},
options: { cache?: ToolAccessDecisionCache; admittedInvocationId?: string; admittedPreviewHash?: string; sharedRateDecision?: ToolAccessDecision } = {},
): Promise<ToolAccessDecision> {
const consumedRateAdmissions: ConsumedRateAdmission[] = [];
const result = await decideInternal(input, options, consumedRateAdmissions);
@@ -1504,7 +1505,7 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
async function decideInternal(
input: ToolAccessDecisionInput,
options: { cache?: ToolAccessDecisionCache; admittedInvocationId?: string; sharedRateDecision?: ToolAccessDecision },
options: { cache?: ToolAccessDecisionCache; admittedInvocationId?: string; admittedPreviewHash?: string; sharedRateDecision?: ToolAccessDecision },
consumedRateAdmissions: ConsumedRateAdmission[],
): Promise<ToolAccessDecision> {
// A decision that consumes a rate limit can also record a trust-rule hit
@@ -1519,7 +1520,7 @@ export function toolAccessPolicyService(db: Pick<Db, "select" | "insert" | "upda
// edited rules still apply. admitInvocation owns atomic consuming rechecks;
// ordinary preflight and browser handoff callers remain read-only.
const admittedRates = options.admittedInvocationId
? await admittedRateLimitAdmissions(ctx, options.admittedInvocationId) : [];
? await admittedRateLimitAdmissions(ctx, options.admittedInvocationId, input.consumeRateLimit === true ? undefined : options.admittedPreviewHash) : [];
if (options.admittedInvocationId && input.consumeRateLimit === true && admittedRates === null) {
return decision("deny", "deny_policy_block", "Tool invocation no longer matches this admission.", [], []);
}
+13 -8
View File
@@ -1251,6 +1251,7 @@ export function createToolGatewayService(
input: ToolAccessDecisionInput,
decisionOptions: NonNullable<Parameters<typeof basePolicyService.decide>[1]> & { requiredGatewayAction?: ToolMcpGatewayTokenAction } = {},
policy: Pick<typeof basePolicyService, "decide" | "writeAudit"> = basePolicyService,
database: Db = db,
): Promise<ToolAccessDecision> {
const issuerId = input.runContext?.originatingAgentId;
if (!issuerId || !input.runContext?.gatewayId || input.actor.actorType !== "agent") return policy.decide(input, decisionOptions);
@@ -1264,7 +1265,7 @@ export function createToolGatewayService(
const authorityKey = `gateway-issuer:${input.companyId}:${input.runContext.gatewayTokenId}:${issuerId}:${requiredAction ?? "inspect"}`;
let authority = issuerCache?.get(authorityKey);
if (!authority) {
authority = assertGatewayIssuerAuthority(input, requiredAction);
authority = assertGatewayIssuerAuthority(input, requiredAction, database);
issuerCache?.set(authorityKey, authority);
}
await authority;
@@ -1289,13 +1290,13 @@ export function createToolGatewayService(
...basePolicyService,
decide: decideGatewayPolicy,
admitInvocation(input: ToolAccessDecisionInput, invocationId: string, claim?: ToolApprovalClaim) {
return basePolicyService.admitInvocation(input, invocationId, claim, (policy, admissionInput) =>
decideGatewayPolicy(admissionInput, { admittedInvocationId: invocationId, requiredGatewayAction: "tools/call" }, policy));
return basePolicyService.admitInvocation(input, invocationId, claim, (policy, admissionInput, transaction) =>
decideGatewayPolicy(admissionInput, { admittedInvocationId: invocationId, requiredGatewayAction: "tools/call" }, policy, transaction));
},
};
async function assertGatewayIssuerAuthority(input: ToolAccessDecisionInput, requiredAction?: ToolMcpGatewayTokenAction) {
const [row] = await db.select({ token: toolMcpGatewayTokens, gateway: toolMcpGateways }).from(toolMcpGatewayTokens)
async function assertGatewayIssuerAuthority(input: ToolAccessDecisionInput, requiredAction?: ToolMcpGatewayTokenAction, database: Db = db) {
const [row] = await database.select({ token: toolMcpGatewayTokens, gateway: toolMcpGateways }).from(toolMcpGatewayTokens)
.innerJoin(toolMcpGateways, eq(toolMcpGateways.id, toolMcpGatewayTokens.gatewayId))
.where(and(eq(toolMcpGatewayTokens.id, input.runContext!.gatewayTokenId!), eq(toolMcpGatewayTokens.companyId, input.companyId)));
const issuerId = input.runContext!.originatingAgentId!;
@@ -1310,8 +1311,8 @@ export function createToolGatewayService(
const resource = { type: "connection_management" as const, companyId: input.companyId, gatewayId: row.gateway.id,
profileId: row.gateway.profileId, purpose: "tool" as const, operation: "gateway_token.use", targetAgentId: row.gateway.agentId,
projectId: row.gateway.projectId, issueId: row.gateway.issueId };
await connectionManagementService(db).authorize(actor, "connections:gateway", resource, { mutation: false });
await connectionManagementService(db).authorize(actor, "connections:test", resource, { mutation: false });
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) {
try {
@@ -10266,6 +10267,7 @@ export function createToolGatewayService(
"Tool definition or connection changed; request a new review",
"approved_tool_target_changed",
);
const previewHash = summarizeToolValue(signedPayload.arguments).sha256;
const access = await policyService.decide(
policyInputForTool({
session,
@@ -10273,7 +10275,10 @@ export function createToolGatewayService(
parameters: signedPayload.arguments,
consumeRateLimit: false,
}),
{ admittedInvocationId: invocation.id, requiredGatewayAction: "tools/call" },
{ admittedInvocationId: invocation.id, requiredGatewayAction: "tools/call",
admittedPreviewHash: [previewHash, toolRequestIdentityHash(signedPayload.arguments, options.toolActionSigningSecret)]
.includes(actionRequest.canonicalArgumentsHash) ? previewHash : undefined,
},
);
if (!access.allowed && access.decision !== "require_approval")
throw new ToolGatewayHttpError(