feat(apps): consolidate connector management (#12684)

Completes the post-managed-OAuth connector lifecycle, Paperclip Cloud provisioning defaults, governed test flows, and consolidated Apps UI.\n\nCo-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Dotta authored and GitHub committed 2026-09-01 14:55:35 -05:00
1 parent 141f202e40
commit 1ab159d3a7
67 files changed
+1738 -1855

No files matched your search

@@ -2310,7 +2310,7 @@ describeEmbeddedPostgres("tool access service", () => {
});
});
it("lists testable agents with per-connection effective access summaries", async () => {
it("lists testable agents without calculating every agent's access summary", async () => {
const company = await createCompany(db);
const userId = `tool-tester-${randomUUID()}`;
await grantBoardUser(db, company.id, userId, ["tools:use"]);
@@ -2335,13 +2335,18 @@ describeEmbeddedPostgres("tool access service", () => {
expect(res.body.agents[0]).toMatchObject({
id: agent.id,
orgDepth: 0,
effectiveAccess: {
connectionId: connection.id,
toolCount: 1,
allowedCount: 1,
askFirstCount: 0,
offCount: 0,
},
});
expect(res.body.agents[0]).not.toHaveProperty("effectiveAccess");
const accessRes = await request(app)
.get(`/api/tool-connections/${connection.id}/test-agents/${agent.id}/access`)
.expect(200);
expect(accessRes.body.access).toMatchObject({
connectionId: connection.id,
toolCount: 1,
allowedCount: 1,
askFirstCount: 0,
offCount: 0,
});
});
@@ -2412,10 +2417,10 @@ describeEmbeddedPostgres("tool access service", () => {
const app = createRouteApp(db, actor, createToolGatewayService(db, { toolActionSigningSecret: "test-secret" }));
const res = await request(app)
.get(`/api/tool-connections/${connection.id}/test-agents`)
.get(`/api/tool-connections/${connection.id}/test-agents/${agent.id}/access`)
.expect(200);
const summary = res.body.agents[0].effectiveAccess;
const summary = res.body.access;
expect(typeof summary.lastChangedAt).toBe("string");
expect(summary.lastChangedByAgentId).toBe(agent.id);
expect(summary.lastChangedByName).toBe(agent.name);
@@ -2523,6 +2528,44 @@ describeEmbeddedPostgres("tool access service", () => {
]));
});
it("cancels an ask-first test request when approval signing is unavailable", async () => {
vi.stubEnv("PAPERCLIP_TOOL_ACTION_SIGNING_SECRET", "");
const company = await createCompany(db);
const userId = `tool-tester-${randomUUID()}`;
await grantBoardUser(db, company.id, userId, ["tools:use"]);
const agent = await createAgent(db, company.id);
const { connection } = await createRemoteToolFixture(db, company.id);
await db.insert(toolPolicies).values({
companyId: company.id,
name: `Ask first without signing ${randomUUID()}`,
policyType: "require_approval",
priority: 100,
selectors: { connectionId: connection.id },
});
const app = createRouteApp(
db,
boardSessionActor(company.id, "operator", userId),
createToolGatewayService(db, { toolActionSigningSecret: " " }),
);
const res = await request(app)
.post(`/api/tool-connections/${connection.id}/test-calls`)
.send({ agentId: agent.id, toolName: "send_email", parameters: { to: "a@example.com" } })
.expect(500);
expect(res.body).toMatchObject({
reasonCode: "signing_secret_unconfigured",
error: expect.stringContaining("PAPERCLIP_TOOL_ACTION_SIGNING_SECRET"),
});
const [actionRequest] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, company.id));
expect(actionRequest).toMatchObject({ status: "cancelled", signedArguments: null });
const [invocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.companyId, company.id));
expect(invocation).toMatchObject({
status: "failed",
errorCode: "signing_secret_unconfigured",
});
});
it("audits ask-first test calls with the real board actor and selected agent", async () => {
const company = await createCompany(db);
const userId = `tool-tester-${randomUUID()}`;
@@ -3418,6 +3461,7 @@ describeEmbeddedPostgres("tool access service", () => {
.put(`/api/tool-connections/${connection.id}/installs`)
.send({ installs: [] }),
await request(app).get(`/api/tool-connections/${connection.id}/test-agents`),
await request(app).get(`/api/tool-connections/${connection.id}/test-agents/${randomUUID()}/access`),
await request(app)
.post(`/api/tool-connections/${connection.id}/test-calls`)
.send({ agentId: randomUUID(), toolName: "read_notes", parameters: {} }),
@@ -3620,7 +3664,7 @@ describeEmbeddedPostgres("tool access service", () => {
it("serves the app gallery manifest through the board route", async () => {
const company = await createCompany(db);
const app = createRouteApp(db);
const app = createRouteApp(db, undefined, undefined, { paperclipCloudConnector: null });
const res = await request(app).get(`/api/companies/${company.id}/tools/gallery`);
@@ -8097,6 +8141,12 @@ describeEmbeddedPostgres("tool access service", () => {
status: "pending",
canonicalArgumentsHash: "args-hash",
canonicalArgumentsSummary: { summary: "redacted", redactedFields: [] },
signedArguments: signToolArguments({
invocationId: invocation.id,
toolName: invocation.toolName,
canonicalArguments: canonicalToolArguments({ redacted: true }),
signingSecret: "attention-test-secret",
}),
});
const res = await request(app).get(`/api/companies/${company.id}/tools/apps/attention`);
@@ -8152,7 +8202,7 @@ describeEmbeddedPostgres("tool access service", () => {
schemaHash: "s1",
}).returning();
const canonicalArguments = canonicalToolArguments({ key: "alpha", value: "one" });
const invocationValues = [1, 2, 3].map(() => ({
const invocationValues = [1, 2, 3, 4].map(() => ({
companyId: company.id,
applicationId: application.id,
connectionId: connection.id,
@@ -8164,7 +8214,7 @@ describeEmbeddedPostgres("tool access service", () => {
approvalState: "pending" as const,
status: "awaiting_approval" as const,
}));
const [validInvocation, missingSignatureInvocation, oldSecretInvocation] =
const [validInvocation, missingSignatureInvocation, staleMissingSignatureInvocation, oldSecretInvocation] =
await db.insert(toolInvocations).values(invocationValues).returning();
const validSignedArguments = signToolArguments({
invocationId: validInvocation.id,
@@ -8178,7 +8228,7 @@ describeEmbeddedPostgres("tool access service", () => {
canonicalArguments,
signingSecret: "old-secret",
});
const [validRequest, missingSignatureRequest, oldSecretRequest] = await db.insert(toolActionRequests).values([
const [validRequest, missingSignatureRequest, staleMissingSignatureRequest, oldSecretRequest] = await db.insert(toolActionRequests).values([
{
companyId: company.id,
invocationId: validInvocation.id,
@@ -8195,6 +8245,19 @@ describeEmbeddedPostgres("tool access service", () => {
canonicalArgumentsSummary: { summary: canonicalArguments, sha256: "args-hash", sizeBytes: canonicalArguments.length },
signedArguments: null,
},
{
companyId: company.id,
invocationId: staleMissingSignatureInvocation.id,
status: "pending",
canonicalArgumentsHash: "args-hash",
canonicalArgumentsSummary: {
summary: canonicalArguments,
sha256: "args-hash",
sizeBytes: canonicalArguments.length,
},
signedArguments: null,
createdAt: new Date(Date.now() - 3 * 60 * 1000),
},
{
companyId: company.id,
invocationId: oldSecretInvocation.id,
@@ -8214,6 +8277,9 @@ describeEmbeddedPostgres("tool access service", () => {
// An unsigned request is still being created; the read hides it but keeps it
// pending, so the creator can finish signing and the later approve succeeds.
expect(statusById.get(missingSignatureRequest.id)).toBe("pending");
// If the creator never finishes signing, Review retires the stale orphan
// instead of leaving a permanent badge for a request no human can approve.
expect(statusById.get(staleMissingSignatureRequest.id)).toBe("cancelled");
// A request signed with a rotated/old secret is unverifiable and is cancelled.
expect(statusById.get(oldSecretRequest.id)).toBe("cancelled");
});
@@ -171,10 +171,12 @@ describe("worktree config repair", () => {
expect(repairedEnv).toContain(`PAPERCLIP_CONTEXT=${JSON.stringify(path.join(isolatedHome, "context.json"))}`);
expect(repairedEnv).toContain('PAPERCLIP_DB_BACKUP_ENABLED="false"');
expect(repairedEnv).toContain("PAPERCLIP_AGENT_JWT_SECRET=shared-secret");
expect(repairedEnv).toContain("PAPERCLIP_TOOL_ACTION_SIGNING_SECRET=");
expect(process.env.PAPERCLIP_HOME).toBe(isolatedHome);
expect(process.env.PORT).toBe("3101");
expect(process.env.PAPERCLIP_INSTANCE_ID).toBe("pap-884-ai-commits-component");
expect(process.env.PAPERCLIP_DB_BACKUP_ENABLED).toBe("false");
expect(process.env.PAPERCLIP_TOOL_ACTION_SIGNING_SECRET).toHaveLength(64);
});
it("disables backups in an otherwise isolated existing worktree config", async () => {
+8
View File
@@ -950,6 +950,7 @@ const BOARD_ONLY_OPERATIONS = new Set([
"GET /api/tool-connections/{connectionId}/catalog",
"GET /api/tool-connections/{connectionId}/activity",
"GET /api/tool-connections/{connectionId}/test-agents",
"GET /api/tool-connections/{connectionId}/test-agents/{agentId}/access",
"POST /api/tool-connections/{connectionId}/test-calls",
"GET /api/tool-connections/{connectionId}/test-calls/{actionRequestId}",
"POST /api/agents/me/connections/{connectionId}/start-authorization",
@@ -7681,6 +7682,13 @@ registerCurrentRoute({
summary: "List agents available for tool connection test calls",
});
registerCurrentRoute({
method: "get",
path: "/api/tool-connections/{connectionId}/test-agents/{agentId}/access",
tags: ["tool-access"],
summary: "Summarize one agent's effective access to a tool connection",
});
registerCurrentRoute({
method: "post",
path: "/api/tool-connections/{connectionId}/test-calls",
+25 -6
View File
@@ -1485,7 +1485,12 @@ function connectorEnrollmentPrincipal(req: Request): string {
router.get("/tool-connections/:connectionId", async (req, res) => {
assertBoard(req);
const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
const connection = await getAccessibleResource(
req,
res,
svc.getConnection(req.params.connectionId as string),
"Tool connection not found",
);
if (!connection) return;
res.json(connection);
});
@@ -1831,17 +1836,31 @@ function connectorEnrollmentPrincipal(req: Request): string {
title: agent.title,
status: agent.status,
orgDepth: orgDepthByAgentId.get(agent.id) ?? 0,
effectiveAccess: await options.toolGateway.summarizeConnectionAccessForAgent({
companyId: connection.companyId,
connectionId: connection.id,
agentId: agent.id,
}),
});
}
candidates.sort((a, b) => a.orgDepth - b.orgDepth || a.name.localeCompare(b.name));
res.json({ agents: candidates });
});
router.get("/tool-connections/:connectionId/test-agents/:agentId/access", async (req, res) => {
assertBoard(req);
if (!options.toolGateway) {
res.status(501).json({ error: "Tool gateway service is not configured" });
return;
}
const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
if (!connection) return;
await assertBoardAnyToolPermission(req, connection.companyId, ["tools:use", "tools:manage_connections"]);
const agentId = req.params.agentId as string;
await assertCanTestAsAgent(req, connection.companyId, agentId);
const accessSummary = await options.toolGateway.summarizeConnectionAccessForAgent({
companyId: connection.companyId,
connectionId: connection.id,
agentId,
});
res.json({ access: accessSummary });
});
router.post("/tool-connections/:connectionId/test-calls", validate(toolConnectionTestCallSchema), async (req, res) => {
assertBoard(req);
if (!options.toolGateway) {
@@ -12,6 +12,7 @@ import {
createPaperclipCloudConnector,
GMAIL_CONNECTOR_SCOPES,
GOOGLE_WORKSPACE_CONNECTOR_PROFILES,
paperclipCloudConnectorCapabilitiesFromEnv,
paperclipCloudConnectorConfigFromEnv,
PaperclipCloudConnectorError,
type PaperclipCloudConnectorConfig,
@@ -271,6 +272,13 @@ describe("Paperclip Cloud connector", () => {
expect(legacyError).toMatchObject({ code: "CONNECTOR_MIGRATION_REQUIRED" });
expect(String(legacyError)).toContain("incompatible legacy protocol");
});
it("keeps gallery capability discovery available during incomplete enrollment", async () => {
await expect(paperclipCloudConnectorCapabilitiesFromEnv({
PAPERCLIP_CLOUD_CONNECTOR_BASE_URL: "https://my-staging.paperclip.app",
PAPERCLIP_CLOUD_CONNECTOR_ENVIRONMENT: "staging",
})).resolves.toEqual([]);
});
});
function seal(
@@ -357,7 +357,11 @@ export async function paperclipCloudConnectorCapabilitiesFromEnv(
try {
config = paperclipCloudConnectorConfigFromEnv(env);
} catch (error) {
if (error instanceof PaperclipCloudConnectorError && error.code === "CONNECTOR_MIGRATION_REQUIRED") return [];
// Gallery discovery is useful even while connector enrollment is pending or
// local connector settings are incomplete. Treat every connector-config
// error as "no managed profiles" here; enrollment/status surfaces still
// report the actionable configuration problem.
if (error instanceof PaperclipCloudConnectorError) return [];
throw error;
}
if (!config) return [];
+14 -5
View File
@@ -1,6 +1,6 @@
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { readFileSync } from "node:fs";
import { and, asc, desc, eq, gte, inArray, isNull, lt, max, ne, sql } from "drizzle-orm";
import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lt, max, ne, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
@@ -157,7 +157,7 @@ import {
} from "./remote-url-credentials.js";
import { secretService } from "./secrets.js";
import { toolAccessPolicyService } from "./tool-access-policy.js";
import { readSignedToolArgumentsPayload } from "./tool-content-guards.js";
import { readSignedToolArgumentsPayload, TOOL_ACTION_REQUEST_SIGNING_GRACE_MS } from "./tool-content-guards.js";
import {
effectiveToolProfileBindings,
narrowestScopeBindings,
@@ -5575,7 +5575,11 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
db
.select()
.from(toolActionRequests)
.where(and(eq(toolActionRequests.companyId, companyId), eq(toolActionRequests.status, "pending"))),
.where(and(
eq(toolActionRequests.companyId, companyId),
eq(toolActionRequests.status, "pending"),
isNotNull(toolActionRequests.signedArguments),
)),
db
.select()
.from(toolInvocations)
@@ -12434,7 +12438,8 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
// that window. Hide such a request from the queue, but do not cancel it —
// cancelling here races the two-step create and makes the later approve
// fail with action_not_pending. Only cancel a request that carries a
// signature we cannot verify (secret rotation or tampering).
// signature we cannot verify (secret rotation or tampering), or an
// unsigned row whose creator has exceeded the signing grace period.
const unsignedRequestIds = new Set<string>();
const invalidRequestIds: string[] = [];
for (const request of requests) {
@@ -12444,7 +12449,11 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
continue;
}
if (request.signedArguments === null) {
unsignedRequestIds.add(request.id);
if (Date.now() - request.createdAt.getTime() >= TOOL_ACTION_REQUEST_SIGNING_GRACE_MS) {
invalidRequestIds.push(request.id);
} else {
unsignedRequestIds.add(request.id);
}
continue;
}
let readable = false;
@@ -54,6 +54,11 @@ export class ToolActionSigningSecretMissingError extends Error {
}
}
// Creating an approval is a two-step insert/sign operation. Readers must allow
// a short window for the creator to attach the signature before treating a null
// signature as an abandoned, unapprovable request.
export const TOOL_ACTION_REQUEST_SIGNING_GRACE_MS = 2 * 60 * 1000;
export function resolveToolActionSigningSecret(env: ToolActionSigningSecretEnv = process.env as ToolActionSigningSecretEnv) {
const secret = env.PAPERCLIP_TOOL_ACTION_SIGNING_SECRET?.trim();
if (!secret) {
+35 -10
View File
@@ -109,6 +109,7 @@ import {
readSignedToolArgumentsPayload,
signToolArguments,
summarizeToolValue,
TOOL_ACTION_REQUEST_SIGNING_GRACE_MS,
ToolActionSigningSecretMissingError,
ToolContentValidationError,
validateToolContent,
@@ -162,7 +163,6 @@ const ACTION_REQUEST_EXECUTION_WAIT_MS = APPROVED_EXECUTION_TIMEOUT_MS + 5_000;
// treat an unsigned row as abandoned after this grace time from createdAt. This
// grace must exceed the normal sign path (approval-snapshot fetch + interaction
// create) so a live create keeps its own row.
const UNSIGNED_ACTION_REQUEST_ABANDON_MS = 2 * 60 * 1000;
const MAX_REMOTE_MCP_RESPONSE_BYTES = 1_000_000;
const ACTIVE_GATEWAY_RUN_STATUSES = new Set(["running"]);
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -5692,7 +5692,7 @@ export function createToolGatewayService(
const pendingUnsigned =
pendingRequest.status === "pending"
&& pendingRequest.signedArguments === null
&& Date.now() - pendingRequest.createdAt.getTime() >= UNSIGNED_ACTION_REQUEST_ABANDON_MS;
&& Date.now() - pendingRequest.createdAt.getTime() >= TOOL_ACTION_REQUEST_SIGNING_GRACE_MS;
const pendingExpired =
pendingRequest.status === "pending"
&& pendingRequest.expiresAt !== null
@@ -6365,14 +6365,39 @@ export function createToolGatewayService(
const approvalSnapshot = await connectedRemoteApprovalSnapshot(session, tool, {
requireResolvedCredentials: true,
});
const signedArguments = signToolArguments({
invocationId,
toolName: tool.name,
canonicalArguments,
approvalSnapshot: approvalSnapshot ?? undefined,
executionOnApprove: true,
signingSecret: options.toolActionSigningSecret,
});
let signedArguments: ReturnType<typeof signToolArguments>;
try {
signedArguments = signToolArguments({
invocationId,
toolName: tool.name,
canonicalArguments,
approvalSnapshot: approvalSnapshot ?? undefined,
executionOnApprove: true,
signingSecret: options.toolActionSigningSecret,
});
} catch (error) {
await db
.update(toolActionRequests)
.set({ status: "cancelled", resolvedAt: new Date(), updatedAt: new Date() })
.where(and(eq(toolActionRequests.id, recorded.actionRequest.id), eq(toolActionRequests.status, "pending")));
if (error instanceof ToolActionSigningSecretMissingError) {
await db
.update(toolInvocations)
.set({
status: "failed",
errorCode: "signing_secret_unconfigured",
errorMessage: error.message,
completedAt: new Date(),
updatedAt: new Date(),
})
.where(eq(toolInvocations.id, invocationId));
throw new ToolGatewayHttpError(500, error.message, "signing_secret_unconfigured", {
invocationId,
tool: tool.name,
});
}
throw error;
}
const previewMarkdown = buildHumanizedActionPreview({ tool, argumentsSummary: argumentValidation.summary });
await db
.update(toolActionRequests)
+12 -4
View File
@@ -1,6 +1,7 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { randomBytes } from "node:crypto";
import { isDeepStrictEqual } from "node:util";
import {
mergePaperclipConfig,
@@ -530,6 +531,15 @@ export function maybeRepairLegacyWorktreeConfigAndEnvFiles(): {
}
}
const existingContents = fs.existsSync(context.envPath)
? fs.readFileSync(context.envPath, "utf8")
: null;
const existingEnvEntries = parseEnvFile(existingContents ?? "");
const toolActionSigningSecret =
nonEmpty(process.env.PAPERCLIP_TOOL_ACTION_SIGNING_SECRET) ??
nonEmpty(existingEnvEntries.PAPERCLIP_TOOL_ACTION_SIGNING_SECRET) ??
randomBytes(32).toString("hex");
const managedEnvEntries: Record<string, string> = {
PAPERCLIP_HOME: context.homeDir,
PAPERCLIP_INSTANCE_ID: context.instanceId,
@@ -538,13 +548,11 @@ export function maybeRepairLegacyWorktreeConfigAndEnvFiles(): {
PAPERCLIP_IN_WORKTREE: "true",
PAPERCLIP_DB_BACKUP_ENABLED: "false",
PAPERCLIP_WORKTREE_NAME: context.worktreeName,
PAPERCLIP_TOOL_ACTION_SIGNING_SECRET: toolActionSigningSecret,
};
process.env.PAPERCLIP_DB_BACKUP_ENABLED = "false";
const existingContents = fs.existsSync(context.envPath)
? fs.readFileSync(context.envPath, "utf8")
: null;
process.env.PAPERCLIP_TOOL_ACTION_SIGNING_SECRET = toolActionSigningSecret;
const repairedContents = updateEnvFileContents(
existingContents ?? emptyWorktreeEnvFileContents(),
managedEnvEntries,