The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(tools): batch profile selector validation (#16521)
Dotta90924d61b378
diff --git a/maps/agent-access-map/gateways-profiles.md b/maps/agent-access-map/gateways-profiles.mdindex 034ddeced1..44a8d08bb6 100644--- a/maps/agent-access-map/gateways-profiles.md+++ b/maps/agent-access-map/gateways-profiles.md@@ -58,6 +58,11 @@ own policy and access review.Gaps: Agent access to tools does not permit profile editing.+Backend evidence: [profile entry validation](../../server/src/__tests__/tool-profile-entry-validation.test.ts)+covers company-scoped selector references and bounded reads for a large immutable+runtime assignment. Batched validation retains the checks before profile and+entry writes. It grants no profile-management authority to agents.+## `client-connect`Review: `baseline`.diff --git a/maps/feature-map/gateways-profiles.md b/maps/feature-map/gateways-profiles.mdindex 2fc7eae877..2d6128ec97 100644--- a/maps/feature-map/gateways-profiles.md+++ b/maps/feature-map/gateways-profiles.md@@ -47,6 +47,12 @@ Manual: Create a disposable gateway with one harmless tool, connect a client usiAutomated: [profile wizard](../../ui/src/pages/tools/profiles/ProfileWizard.test.tsx) and [profile detail](../../ui/src/pages/tools/profiles/ProfileDetail.test.tsx) cover component behavior with mocks.+Backend: [profile entry validation](../../server/src/__tests__/tool-profile-entry-validation.test.ts)+uses isolated PostgreSQL to create and replace a 518-selector assignment with+bounded reference reads. It checks exact selector retention, company boundaries,+invalid input order, and fresh validation after deletion. This does not establish+live client latency.+Manual: Create a bounded profile, choose its offered tools and options, save or resume its draft, and reload the detail. Apply/connect it through the offered flow and inspect the actual client-visible tool set. Verify cancellation and invalid selections retain an understandable draft.## Gotchasdiff --git a/server/src/__tests__/tool-profile-entry-validation.test.ts b/server/src/__tests__/tool-profile-entry-validation.test.tsnew file mode 100644index 0000000000..158f0ad776--- /dev/null+++ b/server/src/__tests__/tool-profile-entry-validation.test.ts@@ -0,0 +1,185 @@+import { randomUUID } from "node:crypto";+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";+import { companies, createDb, toolApplications, toolCatalogEntries, toolConnections, toolProfileEntries, toolProfiles } from "@paperclipai/db";+import type { CreateToolProfileEntryForProfile } from "@paperclipai/shared";+import { eq } from "drizzle-orm";+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";+import { toolAccessService } from "../services/tool-access.js";++const support = await getEmbeddedPostgresTestSupport();+const describeDatabase = support.supported ? describe : describe.skip;++describeDatabase("tool profile entry validation", () => {+ let db: ReturnType<typeof createDb>;+ let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;+ const companyIds: string[] = [];++ beforeAll(async () => {+ database = await startEmbeddedPostgresTestDatabase("paperclip-profile-entry-validation-");+ db = createDb(database.connectionString);+ }, 20_000);++ afterEach(async () => {+ for (const id of companyIds.splice(0)) await db.delete(companies).where(eq(companies.id, id));+ });++ afterAll(async () => { await database?.cleanup(); });++ async function fixture(count = 1) {+ const [company] = await db.insert(companies).values({+ name: `Profile fixture ${randomUUID()}`, issuePrefix: `PV${randomUUID().slice(0, 6).toUpperCase()}`,+ }).returning();+ companyIds.push(company.id);+ const [application] = await db.insert(toolApplications).values({+ companyId: company.id, name: `Application ${randomUUID()}`, type: "mcp_http", status: "active",+ }).returning();+ const [connection] = await db.insert(toolConnections).values({+ companyId: company.id, applicationId: application.id, name: "Fixture connection", uid: `fixture/${randomUUID()}`,+ transport: "mcp_remote", status: "active", enabled: true, config: {}, transportConfig: {}, healthStatus: "ok",+ }).returning();+ const catalog = await db.insert(toolCatalogEntries).values(Array.from({ length: count }, (_, index) => ({+ companyId: company.id, applicationId: application.id, connectionId: connection.id,+ name: `tool_${index}`, toolName: `tool_${index}`, riskLevel: "read" as const, status: "active" as const,+ versionHash: randomUUID(), schemaHash: randomUUID(),+ }))).returning();+ const entries: CreateToolProfileEntryForProfile[] = catalog.map(entry => ({+ selectorType: "catalog_entry", effect: "include", applicationId: application.id,+ connectionId: connection.id, catalogEntryId: entry.id,+ }));+ return { company, application, connection, catalog, entries };+ }++ function countedService() {+ let selects = 0;+ const counted = new Proxy(db, { get(target, key) {+ if (key === "select") return (...args: unknown[]) => {+ selects++;+ return Reflect.apply(target.select, target, args);+ };+ const value = Reflect.get(target, key);+ return typeof value === "function" ? value.bind(target) : value;+ } });+ return { service: toolAccessService(counted), reads: () => selects };+ }++ it("creates all 518 exact selectors without per-entry database reads", async () => {+ const { company, entries } = await fixture(518);+ const { service, reads } = countedService();+ const started = performance.now();+ const profile = await service.createProfile(company.id, {+ profileKey: `cold-${randomUUID()}`, name: "Cold runtime assignment", defaultAction: "deny", entries,+ });+ const elapsedMs = performance.now() - started;+ const saved = await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.profileId, profile.id));+ expect(saved).toHaveLength(518);+ expect(new Set(saved.map(entry => entry.catalogEntryId))).toEqual(new Set(entries.map(entry => entry.catalogEntryId)));+ console.info(JSON.stringify({ operation: "create", entries: 518, selects: reads(), elapsedMs }));+ expect(reads()).toBeLessThanOrEqual(24);+ });++ it("replaces 518 selectors without repeating per-entry reads", async () => {+ const { company, entries } = await fixture(518);+ const existing = await toolAccessService(db).createProfile(company.id, {+ profileKey: `replace-${randomUUID()}`, name: "Before replacement", entries: [entries[0]],+ });+ const { service, reads } = countedService();+ const started = performance.now();+ await service.updateProfile(existing.id, { name: "After replacement", entries });+ const elapsedMs = performance.now() - started;+ expect(await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.profileId, existing.id))).toHaveLength(518);+ console.info(JSON.stringify({ operation: "replace", entries: 518, selects: reads(), elapsedMs }));+ expect(reads()).toBeLessThanOrEqual(32);+ });++ it.each(["application", "connection", "catalog"] as const)("rejects a foreign %s before creating or replacing a profile", async kind => {+ const own = await fixture();+ const foreign = await fixture();+ const service = toolAccessService(db);+ const profile = await service.createProfile(own.company.id, {+ profileKey: `preserve-${randomUUID()}`, name: "Preserved profile", entries: own.entries,+ });+ const invalid = { ...own.entries[0], ...({+ application: { applicationId: foreign.application.id },+ connection: { connectionId: foreign.connection.id },+ catalog: { catalogEntryId: foreign.catalog[0].id },+ }[kind]) };+ const status = kind === "catalog" ? 422 : 404;+ const key = `rejected-${randomUUID()}`;+ await expect(service.createProfile(own.company.id, { profileKey: key, name: "Rejected", entries: [invalid] }))+ .rejects.toMatchObject({ status });+ expect(await db.select().from(toolProfiles).where(eq(toolProfiles.profileKey, key))).toEqual([]);+ await expect(service.updateProfile(profile.id, { name: "Must not change", entries: [invalid] }))+ .rejects.toMatchObject({ status });+ expect((await service.getProfile(profile.id)).name).toBe("Preserved profile");+ const saved = await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.profileId, profile.id));+ expect(saved).toHaveLength(1);+ expect(saved[0].catalogEntryId).toBe(own.catalog[0].id);+ });++ it.each([+ ["application", "Application profile entries require applicationId"],+ ["connection", "Connection profile entries require connectionId"],+ ["catalog_entry", "Catalog-entry profile entries require catalogEntryId"],+ ["tool_name", "Tool-name profile entries require toolName"],+ ["risk_level", "Risk-level profile entries require riskLevel"],+ ] as const)("preserves the required %s selector check", async (selectorType, message) => {+ const { company } = await fixture();+ await expect(toolAccessService(db).createProfile(company.id, {+ profileKey: `missing-${randomUUID()}`, name: "Missing selector", entries: [{ selectorType, effect: "include" }],+ })).rejects.toMatchObject({ status: 400, message });+ });++ it("preserves input-order errors when a later selector has a missing field", async () => {+ const own = await fixture();+ const foreign = await fixture();+ await expect(toolAccessService(db).createProfile(own.company.id, {+ profileKey: `ordered-${randomUUID()}`, name: "Ordered errors", entries: [+ { ...own.entries[0], applicationId: foreign.application.id },+ { selectorType: "tool_name", effect: "include" },+ ],+ })).rejects.toMatchObject({ status: 404, message: "Tool application not found" });+ });++ it("does not reuse validation after a catalog entry is removed", async () => {+ const { company, catalog, entries } = await fixture();+ const service = toolAccessService(db);+ await service.createProfile(company.id, { profileKey: `valid-${randomUUID()}`, name: "Before removal", entries });+ await db.delete(toolCatalogEntries).where(eq(toolCatalogEntries.id, catalog[0].id));+ await expect(service.createProfile(company.id, { profileKey: `after-${randomUUID()}`, name: "After removal", entries }))+ .rejects.toMatchObject({ status: 422 });+ });++ it("does not authorize a foreign UUID through another connection's matching UID", async () => {+ const own = await fixture();+ const foreign = await fixture();+ await db.update(toolConnections).set({ uid: foreign.connection.id }).where(eq(toolConnections.id, own.connection.id));+ await expect(toolAccessService(db).createProfile(own.company.id, {+ profileKey: `uid-collision-${randomUUID()}`, name: "UID collision", entries: [+ own.entries[0], { ...own.entries[0], connectionId: foreign.connection.id },+ ],+ })).rejects.toMatchObject({ status: 404, message: "Tool connection not found" });+ });++ it("rejects a foreign catalog selector in the second lookup batch", async () => {+ const own = await fixture(518);+ const foreign = await fixture();+ own.entries[517] = { ...own.entries[517], catalogEntryId: foreign.catalog[0].id };+ const profileKey = `last-batch-${randomUUID()}`;+ await expect(toolAccessService(db).createProfile(own.company.id, {+ profileKey, name: "Last batch", entries: own.entries,+ })).rejects.toMatchObject({ status: 422 });+ expect(await db.select().from(toolProfiles).where(eq(toolProfiles.profileKey, profileKey))).toEqual([]);+ });++ it("preserves PostgreSQL UUID case matching", async () => {+ const own = await fixture();+ const profile = await toolAccessService(db).createProfile(own.company.id, {+ profileKey: `upper-${randomUUID()}`, name: "Uppercase identifiers", entries: [{+ ...own.entries[0], applicationId: own.application.id.toUpperCase(),+ connectionId: own.connection.id.toUpperCase(), catalogEntryId: own.catalog[0].id.toUpperCase(),+ }],+ });+ const [saved] = await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.profileId, profile.id));+ expect(saved).toMatchObject({ applicationId: own.application.id, connectionId: own.connection.id, catalogEntryId: own.catalog[0].id });+ });+});diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.tsindex cc068babbd..516aa8fba6 100644--- a/server/src/services/tool-access.ts+++ b/server/src/services/tool-access.ts@@ -1,4 +1,5 @@import { stableHash, descriptorHash } from "./tool-catalog-hash.js";+import { assertProfileEntryInputs, assertProfileEntryShape } from "./tool-profile-entry-validation.js";import { DAYTONA_TOOLS, daytonaClient, daytonaRisk, isDaytonaConnection, isDaytonaToolName } from "./daytona.js";import { chatCredentialMutationLease } from "./chat-credential-mutation-lease.js";import { notifyChatEndpointWork } from "./chat-work-notifications.js";@@ -5869,21 +5870,7 @@ export function toolAccessService(companyId: string,input: CreateToolProfileEntryForProfile,) {- if (input.selectorType === "application" && !input.applicationId) {- throw badRequest("Application profile entries require applicationId");- }- if (input.selectorType === "connection" && !input.connectionId) {- throw badRequest("Connection profile entries require connectionId");- }- if (input.selectorType === "catalog_entry" && !input.catalogEntryId) {- throw badRequest("Catalog-entry profile entries require catalogEntryId");- }- if (input.selectorType === "tool_name" && !input.toolName) {- throw badRequest("Tool-name profile entries require toolName");- }- if (input.selectorType === "risk_level" && !input.riskLevel) {- throw badRequest("Risk-level profile entries require riskLevel");- }+ assertProfileEntryShape(input);if (input.applicationId)await assertApplication(companyId, input.applicationId);if (input.connectionId)@@ -6237,9 +6224,7 @@ export function toolAccessService(profileId: string,entries: CreateToolProfileEntryForProfile[],) {- for (const entry of entries) {- await assertProfileEntryInput(companyId, entry);- }+ await assertProfileEntryInputs(db, companyId, entries);if (entries.length === 0) return;await db.insert(toolProfileEntries).values(entries.map((entry) => ({@@ -6262,9 +6247,7 @@ export function toolAccessService(profileId: string,entries: CreateToolProfileEntryForProfile[],) {- for (const entry of entries) {- await assertProfileEntryInput(companyId, entry);- }+ await assertProfileEntryInputs(db, companyId, entries);await db.delete(toolProfileEntries).where(@@ -19613,9 +19596,7 @@ export function toolAccessService(companyId: string,input: CreateToolProfileWithEntries,): Promise<ToolProfileWithDetails> => {- for (const entry of input.entries ?? []) {- await assertProfileEntryInput(companyId, entry);- }+ await assertProfileEntryInputs(db, companyId, input.entries ?? []);const [row] = await db.insert(toolProfiles).values({@@ -19644,9 +19625,7 @@ export function toolAccessService(): Promise<ToolProfileWithDetails> => {const existing = await getProfileRow(profileId);if (input.entries) {- for (const entry of input.entries) {- await assertProfileEntryInput(existing.companyId, entry);- }+ await assertProfileEntryInputs(db, existing.companyId, input.entries);}await db.update(toolProfiles)diff --git a/server/src/services/tool-profile-entry-validation.ts b/server/src/services/tool-profile-entry-validation.tsnew file mode 100644index 0000000000..356342c28e--- /dev/null+++ b/server/src/services/tool-profile-entry-validation.ts@@ -0,0 +1,82 @@+import { toolApplications, toolCatalogEntries, toolConnections, type Db } from "@paperclipai/db";+import type { CreateToolProfileEntryForProfile } from "@paperclipai/shared";+import { and, eq, inArray, or } from "drizzle-orm";+import { badRequest, notFound, unprocessable } from "../errors.js";++const UUID_IDENTIFIER = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;+const REFERENCE_BATCH_SIZE = 500;++function* referenceBatches(values: string[]) {+ for (let index = 0; index < values.length; index += REFERENCE_BATCH_SIZE) {+ yield values.slice(index, index + REFERENCE_BATCH_SIZE);+ }+}++export function assertProfileEntryShape(input: CreateToolProfileEntryForProfile) {+ if (input.selectorType === "application" && !input.applicationId) {+ throw badRequest("Application profile entries require applicationId");+ }+ if (input.selectorType === "connection" && !input.connectionId) {+ throw badRequest("Connection profile entries require connectionId");+ }+ if (input.selectorType === "catalog_entry" && !input.catalogEntryId) {+ throw badRequest("Catalog-entry profile entries require catalogEntryId");+ }+ if (input.selectorType === "tool_name" && !input.toolName) {+ throw badRequest("Tool-name profile entries require toolName");+ }+ if (input.selectorType === "risk_level" && !input.riskLevel) {+ throw badRequest("Risk-level profile entries require riskLevel");+ }+}++export async function assertProfileEntryInputs(+ db: Pick<Db, "select">,+ companyId: string,+ entries: CreateToolProfileEntryForProfile[],+) {+ const applications = new Set<string>();+ const connectionIds = new Set<string>();+ const connectionUids = new Set<string>();+ const catalogEntries = new Set<string>();+ const references = (key: "applicationId" | "connectionId" | "catalogEntryId") =>+ [...new Set(entries.flatMap(entry => entry[key] ? [entry[key]!] : []))];++ for (const ids of referenceBatches(references("applicationId"))) {+ const rows = await db.select({ id: toolApplications.id }).from(toolApplications)+ .where(and(eq(toolApplications.companyId, companyId), inArray(toolApplications.id, ids)));+ for (const row of rows) applications.add(row.id.toLowerCase());+ }+ for (const refs of referenceBatches(references("connectionId"))) {+ const ids = refs.filter(value => UUID_IDENTIFIER.test(value));+ const uids = refs.filter(value => !UUID_IDENTIFIER.test(value));+ const rows = await db.select({ id: toolConnections.id, uid: toolConnections.uid }).from(toolConnections)+ .where(and(eq(toolConnections.companyId, companyId), or(+ ids.length ? inArray(toolConnections.id, ids) : undefined,+ uids.length ? inArray(toolConnections.uid, uids) : undefined,+ )));+ for (const row of rows) {+ connectionIds.add(row.id.toLowerCase());+ connectionUids.add(row.uid);+ }+ }+ for (const ids of referenceBatches(references("catalogEntryId"))) {+ const rows = await db.select({ id: toolCatalogEntries.id }).from(toolCatalogEntries)+ .where(and(eq(toolCatalogEntries.companyId, companyId), inArray(toolCatalogEntries.id, ids)));+ for (const row of rows) catalogEntries.add(row.id.toLowerCase());+ }++ for (const entry of entries) {+ assertProfileEntryShape(entry);+ if (entry.applicationId && !applications.has(entry.applicationId.toLowerCase())) {+ throw notFound("Tool application not found");+ }+ if (entry.connectionId && !(UUID_IDENTIFIER.test(entry.connectionId)+ ? connectionIds.has(entry.connectionId.toLowerCase()) : connectionUids.has(entry.connectionId))) {+ throw notFound("Tool connection not found");+ }+ if (entry.catalogEntryId && !catalogEntries.has(entry.catalogEntryId.toLowerCase())) {+ throw unprocessable("Tool profile catalog entry selector must belong to the same company");+ }+ }+}