mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
fix(apps): reduce Google Chat scopes and block unread filters (#13820)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Apps give agents controlled access to external services. > - Google Chat uses OAuth profiles and reviewed MCP tools. > - Those profiles request membership and read-state access that the supported feature set does not need. > - Removing read-state access also requires us to block unread search filters, including on existing connections. > - This pull request reduces both OAuth methods and enforces the reduced search contract before dispatch. > - Users retain conversation lookup, message history, ordinary search, and approved message sending. ## Linked Issues or Issue Description **What happened?** Both Google Chat profiles request membership and read-state scopes. The supported tool set does not include membership listing or read-state updates. Message search still advertises an unread filter. Related work: Refs #12619. **Expected behavior** Managed and customer-owned OAuth request only the scopes needed for supported features. Unsupported unread filters fail clearly before any provider call. Existing cached catalogs and broader grants must not bypass that policy. **Steps to reproduce** Start Google Chat OAuth from either connection method and inspect the requested scopes. Inspect the message-search tool schema, then submit a search with `searchParameters.isUnread` set to true or false. **Paperclip version or commit** The scope change is based on master at `110d176fc`. **Deployment mode** Managed Cloud and self-hosted instances with Google Chat Apps enabled. ## What Changed - Remove `chat.memberships.readonly` and `chat.users.readstate.readonly` from shared profiles and all four Chat connection methods. - Hide unsupported read-state fields and instructions in agent and board Test tool schemas. - Reject explicit unread filters, including false, null, snake-case fields, and encoded filter objects, before provider dispatch. - Recheck previously approved calls and support existing profile-bound and URL-only Chat connections. - Add scope, signed broker request, OAuth URL, allowlist, schema, and dispatch regression tests. - Document coordinated app/broker rollout, existing-grant reconnects, and the remaining deployment checks. ## Verification - All seven focused OAuth and Chat gateway test files pass: 498 tests on the rebased branch. - `pnpm -r typecheck` and `pnpm build` pass, using pinned pnpm 9.15.4. - The complete sharded CI test matrix passes, including general server, Chat, workspace, serialized server, Runner, and all eight browser e2e shards. The duplicate unsharded local `pnpm test:run` was stopped after CI passed; it did not complete locally. - `git diff --check` passes. - `node scripts/ingest-app-definitions.mjs` succeeds and leaves the branch unchanged. Google Workspace JSON is the durable reviewed input used by the generator. - All current-head CI checks pass at `7ee755371714dc036fff1c7da844776fee3f2ec1`, including typecheck, build, and canary dry run. Greptile is 5/5 with zero unresolved threads. The generator concern was withdrawn after review of the source and regeneration evidence. - No production deployment or live Google consent test was performed. After coordinated deployment, verify reduced consent scopes, normal search/history, message sending, and rejection of unread filters. ## Risks - Coordinate deployment with the companion Cloud broker scope change. Mixed versions can reject exact-scope requests. - Existing tokens are not narrowed or revoked. Grants with old scopes need new consent. Do not revoke a shared Google client to migrate one profile. - Explicit unread filters now return an error instead of being sent to Google. Ordinary search and the approved send tool remain available. - No database, UI, lockfile, or workflow changes. ## Model Used OpenAI Codex, a GPT-5-based coding agent, with tool use and code execution. The exact runtime model ID and context window were not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
9a76390cfa
commit
a959e47508
12 files changed
+352
-23
No files matched your search
@@ -2410,6 +2410,36 @@ describeEmbeddedPostgres("tool access service", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["read", "write"])("requests only reduced Chat scopes for customer-owned %s OAuth, including reconnect", async (capability) => {
|
||||
const company = await createCompany(db);
|
||||
const service = createTestToolAccessService(db);
|
||||
const actor = { actorType: "user" as const, actorId: "board" };
|
||||
const connected = await service.connectGalleryApp(company.id, {
|
||||
galleryKey: "google-chat",
|
||||
connectionMethodKey: `customer-${capability}-oauth`,
|
||||
name: "Chat scope fixture",
|
||||
grantKind: "user",
|
||||
oauthClient: { clientId: "google-chat-client", clientSecret: "google-chat-secret" },
|
||||
}, actor);
|
||||
const scopes = ["chat.spaces.readonly", "chat.messages.readonly", ...(capability === "write" ? ["chat.messages.create"] : [])]
|
||||
.map((scope) => `https://www.googleapis.com/auth/${scope}`);
|
||||
const removed = ["chat.memberships.readonly", "chat.users.readstate.readonly"]
|
||||
.map((scope) => `https://www.googleapis.com/auth/${scope}`);
|
||||
const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId));
|
||||
// A saved broad scope hint must not leak back into the next consent URL.
|
||||
await db.update(toolConnections).set({ config: {
|
||||
...connection.config,
|
||||
oauth: { ...(connection.config.oauth as Record<string, unknown>), scopes: [...scopes, ...removed] },
|
||||
} }).where(eq(toolConnections.id, connection.id));
|
||||
const input = { redirectUri: "https://paperclip.example.test/api/tools/oauth/callback", actor };
|
||||
const started = await service.startOAuth(company.id, connection.id, input);
|
||||
expect(new URL(started.authorizationUrl).searchParams.get("scope")?.split(" ")).toEqual(scopes);
|
||||
for (const removedScope of removed) {
|
||||
await expect(service.startOAuth(company.id, connection.id, { ...input, scopes: [...scopes, removedScope] }))
|
||||
.rejects.toMatchObject({ status: 400, details: { code: "oauth_scope_widening_rejected", scopes: [removedScope] } });
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps tools outside a Google Workspace capability profile disabled", async () => {
|
||||
const company = await createCompany(db);
|
||||
const service = createTestToolAccessService(db);
|
||||
|
||||
@@ -38,6 +38,7 @@ import { commitToolActionReview } from "../services/tool-action-review.js";
|
||||
import { materializeNativeInteractionResponses } from "../services/native-runtime/native-interaction-bridge.js";
|
||||
import { toolActionDeliveryService } from "../services/tool-action-delivery.js";
|
||||
import { secretService } from "../services/secrets.js";
|
||||
import { toolAccessService } from "../services/tool-access.js";
|
||||
import {
|
||||
createToolGatewayService,
|
||||
ToolGatewayHttpError,
|
||||
@@ -1314,6 +1315,68 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("hides cached Chat unread filters and blocks agent and board requests before provider dispatch", async () => {
|
||||
const { company, agent, run } = await createRunFixture(db);
|
||||
const { connection, catalogEntry } = await createRemoteMcpToolFixture(db, company.id);
|
||||
await db.update(toolConnections).set({
|
||||
lastCatalogRefreshAt: new Date(),
|
||||
config: {
|
||||
url: "https://8.8.8.8/mcp",
|
||||
sourceTemplateKey: "google-chat",
|
||||
connectionMethodKey: "customer-read-oauth",
|
||||
oauth: { scopes: ["https://www.googleapis.com/auth/chat.users.readstate.readonly"] },
|
||||
},
|
||||
}).where(eq(toolConnections.id, connection.id));
|
||||
await db.update(toolCatalogEntries).set({
|
||||
name: "search_messages", toolName: "search_messages", description: "Search unread messages.",
|
||||
inputSchema: { type: "object", properties: {
|
||||
searchParameters: { type: "object", properties: {
|
||||
isUnread: { type: "boolean" }, keywords: { type: "array", items: { type: "string" } },
|
||||
} },
|
||||
} },
|
||||
}).where(eq(toolCatalogEntries.id, catalogEntry.id));
|
||||
await db.insert(toolPolicies).values({
|
||||
companyId: company.id, name: "Allow Chat reads", policyType: "allow", selectors: { riskLevel: "read" },
|
||||
});
|
||||
const provider = vi.fn(async (_url, init) => {
|
||||
const payload = JSON.parse(String(init.body));
|
||||
if (payload.method === "notifications/initialized") return new Response(null, { status: 202 });
|
||||
return Response.json({ jsonrpc: "2.0", id: payload.id, result: payload.method === "initialize"
|
||||
? { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "chat-fixture", version: "1" } }
|
||||
: { content: [{ type: "text", text: "Found matching messages." }] } });
|
||||
});
|
||||
const gateway = createTestToolGatewayService(db, { remoteHttpRequest: provider });
|
||||
const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });
|
||||
const tool = (await gateway.listToolsForSession(session.token))
|
||||
.find((candidate) => candidate.upstreamToolName === "search_messages")!;
|
||||
expect(tool).toBeTruthy();
|
||||
expect(JSON.stringify(tool.parametersSchema)).not.toContain("isUnread");
|
||||
expect(tool.description).toContain("Read/unread filtering is not supported.");
|
||||
const catalog = await toolAccessService(db).listCatalog(connection.id, company.id);
|
||||
expect(JSON.stringify(catalog[0].inputSchema)).not.toContain("isUnread");
|
||||
expect(catalog[0].description).toContain("Read/unread filtering is not supported.");
|
||||
|
||||
for (const isUnread of [true, false]) {
|
||||
const parameters = { searchParameters: { isUnread, keywords: ["release"] } };
|
||||
const error = { status: 400, details: { code: "google_chat_unread_filter_unsupported" } };
|
||||
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters }))
|
||||
.rejects.toMatchObject(error);
|
||||
await expect(gateway.executeTestCall({
|
||||
companyId: company.id, connectionId: connection.id, agentId: agent.id,
|
||||
userId: "board", toolName: "search_messages", parameters,
|
||||
})).rejects.toMatchObject(error);
|
||||
}
|
||||
expect(provider).not.toHaveBeenCalled();
|
||||
|
||||
const parameters = { searchParameters: { keywords: ["release"], startTime: "2026-09-22T00:00:00Z" }, pageSize: 10 };
|
||||
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters }))
|
||||
.resolves.toMatchObject({ status: "completed" });
|
||||
const calls = provider.mock.calls.map(([, init]) => JSON.parse(String(init.body)))
|
||||
.filter((payload) => payload.method === "tools/call");
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0].params).toEqual({ name: "search_messages", arguments: parameters });
|
||||
});
|
||||
|
||||
it("explains Google Workspace preview enrollment when a tool call is denied", async () => {
|
||||
const { company, agent, run } = await createRunFixture(db);
|
||||
const { connection } = await createRemoteMcpToolFixture(db, company.id);
|
||||
|
||||
Reference in new issue
Block a user