feat(apps): add connection grants and delegated identities (#12341)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - External tools need explicit identity and access boundaries.
> - Shared connection credentials cannot represent every user-scoped use
case.
> - Grants must stay company-scoped and support safe delegation.
> - This pull request adds connection grants, identity rules, and their
database contract.
> - The benefit is durable control over which identity an agent may use.

## Linked Issues or Issue Description

Refs #11965

This is stack 3 of 11. It depends on stack 2 and replaces another
reviewable part of #11965.

## What Changed

- Add company and user connection grants.
- Add delegated identity and membership rules.
- Synchronize database, shared, server, and UI contracts.
- Register the grant-member replacement route in the OpenAPI surface in
the same layer that mounts it.
- Add migration 0231 with replay-safe guards and coverage.

## Verification

- `pnpm -r typecheck`
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/tool-access-service.test.ts`
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/openapi-routes.test.ts` (5 passed)
- `pnpm --filter @paperclipai/db check:migrations`
- `pnpm build`

## Risks

- Incorrect grant selection could expose the wrong credential scope.
- The service enforces company and subject boundaries before credential
use.
- Migration 0231 is generated, ordered after 0230, and safe to replay.

> I checked `ROADMAP.md`. This stack continues the existing app
connection work from #11965 and does not duplicate another planned item.

## Model Used

OpenAI Codex, GPT-5. The runtime model ID and context window were not
exposed. The model used reasoning, tool use, and code execution.

## 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 linked a public issue or pull request with `Refs #`
- [x] I have not referenced internal or instance-local Paperclip issues
or links
- [x] My branch name describes the change 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:
DottaandPaperclip authored and GitHub committed 2026-08-29 12:08:33 -05:00
1 parent b51112798f
commit 20ccf3f476
82 files changed
+50274 -1331

No files matched your search

@@ -5,10 +5,15 @@ import { and, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
activityLog,
agents,
companies,
companyMemberships,
connectionGrantDelegations,
connectionGrants,
createDb,
principalPermissionGrants,
toolApplications,
toolConnections,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
@@ -90,8 +95,13 @@ describeEmbeddedPostgres("access routes permissions upgrade compatibility", () =
afterEach(async () => {
await db.delete(activityLog);
await db.delete(connectionGrantDelegations);
await db.delete(connectionGrants);
await db.delete(toolConnections);
await db.delete(toolApplications);
await db.delete(principalPermissionGrants);
await db.delete(companyMemberships);
await db.delete(agents);
await db.delete(companies);
});
@@ -164,4 +174,85 @@ describeEmbeddedPostgres("access routes permissions upgrade compatibility", () =
grantedByUserId: owner.principalId,
});
});
it("sweeps personal connection access when the member route suspends a user", async () => {
const { company, owner } = await createCompanyWithOwner(db);
const member = await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "user",
principalId: `member-${randomUUID()}`,
status: "active",
membershipRole: "member",
}).returning().then((rows) => rows[0]!);
const agent = await db.insert(agents).values({
companyId: company.id,
name: "Delegated route agent",
role: "worker",
adapterType: "process",
adapterConfig: {},
}).returning().then((rows) => rows[0]!);
const application = await db.insert(toolApplications).values({
companyId: company.id,
applicationKey: `route-app-${randomUUID()}`,
name: "Route personal app",
type: "mcp",
status: "active",
}).returning().then((rows) => rows[0]!);
const connection = await db.insert(toolConnections).values({
companyId: company.id,
applicationId: application.id,
name: "Route personal connection",
uid: `route-connection-${randomUUID()}`,
connectionKind: "managed",
ownership: "customer",
transport: "mcp_remote",
authKind: "oauth",
credentialPolicy: "per_user",
status: "active",
enabled: true,
}).returning().then((rows) => rows[0]!);
const grant = await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: connection.id,
kind: "user",
subjectUserId: member.principalId,
status: "active",
}).returning().then((rows) => rows[0]!);
await db.insert(connectionGrantDelegations).values({
companyId: company.id,
grantId: grant.id,
agentId: agent.id,
createdByUserId: member.principalId,
});
const res = await request(await createApp(db, company.id, owner.principalId))
.patch(`/api/companies/${company.id}/members/${member.id}`)
.send({ status: "suspended" });
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body.status).toBe("suspended");
expect(await db.select().from(connectionGrantDelegations)).toHaveLength(0);
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant.id)))
.toEqual([expect.objectContaining({ status: "revoked" })]);
await request(await createApp(db, company.id, owner.principalId))
.patch(`/api/companies/${company.id}/members/${member.id}/role-and-grants`)
.send({ status: "active", grants: [] })
.expect(200);
await db.update(connectionGrants).set({ status: "active" }).where(eq(connectionGrants.id, grant.id));
await db.insert(connectionGrantDelegations).values({
companyId: company.id,
grantId: grant.id,
agentId: agent.id,
createdByUserId: member.principalId,
});
const permissionsRoute = await request(await createApp(db, company.id, owner.principalId))
.patch(`/api/companies/${company.id}/members/${member.id}/role-and-grants`)
.send({ status: "suspended", grants: [] });
expect(permissionsRoute.status, JSON.stringify(permissionsRoute.body)).toBe(200);
expect(await db.select().from(connectionGrantDelegations)).toHaveLength(0);
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant.id)))
.toEqual([expect.objectContaining({ status: "revoked" })]);
});
});
+654 -1
View File
@@ -1,14 +1,24 @@
import { randomUUID } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
import { and, eq, inArray, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
agents,
companySecretBindings,
companySecrets,
companies,
companyMemberships,
createDb,
connectionGrantDelegations,
connectionGrantMembers,
connectionGrants,
instanceUserRoles,
issues,
principalPermissionGrants,
toolAccessAuditEvents,
toolApplications,
toolConnections,
userSecretDeclarations,
userSecretDefinitions,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
@@ -56,6 +66,16 @@ describeEmbeddedPostgres("access service", () => {
}, 20_000);
afterEach(async () => {
await db.delete(toolAccessAuditEvents);
await db.delete(userSecretDeclarations);
await db.delete(companySecretBindings);
await db.delete(connectionGrantDelegations);
await db.delete(connectionGrantMembers);
await db.delete(connectionGrants);
await db.delete(toolConnections);
await db.delete(toolApplications);
await db.delete(companySecrets);
await db.delete(userSecretDefinitions);
await db.delete(issues);
await db.delete(principalPermissionGrants);
await db.delete(instanceUserRoles);
@@ -226,6 +246,639 @@ describeEmbeddedPostgres("access service", () => {
).rejects.toThrow("Instance admins cannot be removed from company access");
});
it("sweeps personal grants when instance-level company access is removed", async () => {
const { company, owner } = await createCompanyWithOwner(db);
const member = await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "user",
principalId: `member-${randomUUID()}`,
status: "active",
membershipRole: "member",
}).returning().then((rows) => rows[0]!);
const agent = await db.insert(agents).values({
companyId: company.id,
name: "Instance access delegated agent",
role: "worker",
adapterType: "process",
adapterConfig: {},
}).returning().then((rows) => rows[0]!);
const application = await db.insert(toolApplications).values({
companyId: company.id,
applicationKey: `instance-access-${randomUUID()}`,
name: "Instance access app",
type: "mcp",
status: "active",
}).returning().then((rows) => rows[0]!);
const connection = await db.insert(toolConnections).values({
companyId: company.id,
applicationId: application.id,
name: "Instance access connection",
uid: `instance-access-${randomUUID()}`,
connectionKind: "managed",
ownership: "customer",
transport: "mcp_remote",
authKind: "oauth",
credentialPolicy: "per_user",
status: "active",
enabled: true,
}).returning().then((rows) => rows[0]!);
const grant = await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: connection.id,
kind: "user",
subjectUserId: member.principalId,
status: "active",
}).returning().then((rows) => rows[0]!);
await db.insert(connectionGrantDelegations).values({
companyId: company.id,
grantId: grant.id,
agentId: agent.id,
createdByUserId: member.principalId,
});
await accessService(db).setUserCompanyAccess(member.principalId, [], {
actorUserId: owner.principalId,
});
expect(await db.select().from(companyMemberships).where(eq(companyMemberships.id, member.id)))
.toEqual([expect.objectContaining({ status: "archived" })]);
expect(await db.select().from(connectionGrantDelegations)).toHaveLength(0);
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant.id)))
.toEqual([expect.objectContaining({ status: "revoked" })]);
});
it("revokes personal connection access and destroys user-scoped secrets when membership is archived", async () => {
const { company, owner } = await createCompanyWithOwner(db);
const member = await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "user",
principalId: `member-${randomUUID()}`,
status: "active",
membershipRole: "member",
}).returning().then((rows) => rows[0]!);
const agent = await db.insert(agents).values({
companyId: company.id,
name: "Delegated agent",
role: "worker",
adapterType: "process",
adapterConfig: {},
}).returning().then((rows) => rows[0]!);
const application = await db.insert(toolApplications).values({
companyId: company.id,
applicationKey: `app-${randomUUID()}`,
name: "Personal mail",
type: "mcp",
status: "active",
}).returning().then((rows) => rows[0]!);
const connection = await db.insert(toolConnections).values({
companyId: company.id,
applicationId: application.id,
name: "Mail",
uid: `mail-${randomUUID()}`,
connectionKind: "managed",
ownership: "customer",
transport: "mcp_remote",
authKind: "oauth",
credentialPolicy: "per_user",
status: "active",
enabled: true,
}).returning().then((rows) => rows[0]!);
const definition = await db.insert(userSecretDefinitions).values({
companyId: company.id,
key: `oauth-${randomUUID()}`,
name: "Personal OAuth token",
}).returning().then((rows) => rows[0]!);
const secret = await db.insert(companySecrets).values({
companyId: company.id,
scope: "user",
ownerUserId: member.principalId,
userSecretDefinitionId: definition.id,
key: `oauth-${randomUUID()}`,
name: `OAuth ${randomUUID()}`,
}).returning().then((rows) => rows[0]!);
await db.update(toolConnections).set({
credentialSecretRefs: [{ secretId: secret.id, configPath: "oauth.access_token" }],
}).where(eq(toolConnections.id, connection.id));
const grant = await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: connection.id,
kind: "user",
subjectUserId: member.principalId,
credentialSecretRefs: [{ secretId: secret.id, configPath: "oauth.access_token" }],
}).returning().then((rows) => rows[0]!);
await db.insert(connectionGrantDelegations).values({
companyId: company.id,
grantId: grant.id,
agentId: agent.id,
createdByUserId: member.principalId,
});
await accessService(db).archiveMember(company.id, member.id, {
reassignment: { assigneeUserId: owner.principalId },
});
expect(await db.select().from(connectionGrantDelegations)).toHaveLength(0);
expect(await db.select().from(connectionGrantMembers)).toHaveLength(0);
expect(await db.select().from(companySecrets).where(eq(companySecrets.id, secret.id))).toHaveLength(0);
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant.id)))
.toEqual([expect.objectContaining({ status: "revoked", credentialSecretRefs: [] })]);
expect(await db.select().from(toolConnections).where(eq(toolConnections.id, connection.id)))
.toEqual([expect.objectContaining({
status: "draft",
enabled: false,
healthStatus: "missing_secret",
lastError: "oauth_reauthorization_required",
credentialSecretRefs: [],
})]);
expect(await db.select().from(toolAccessAuditEvents).where(eq(toolAccessAuditEvents.reasonCode, "membership_removed")))
.toHaveLength(1);
});
it("retains a personal credential while another member grant still uses it", async () => {
const { company, owner } = await createCompanyWithOwner(db);
const [departing, surviving] = await db.insert(companyMemberships).values([
{
companyId: company.id,
principalType: "user" as const,
principalId: `departing-${randomUUID()}`,
status: "active" as const,
membershipRole: "member" as const,
},
{
companyId: company.id,
principalType: "user" as const,
principalId: `surviving-${randomUUID()}`,
status: "active" as const,
membershipRole: "member" as const,
},
]).returning();
const application = await db.insert(toolApplications).values({
companyId: company.id,
applicationKey: `shared-personal-${randomUUID()}`,
name: "Shared personal app",
type: "mcp",
status: "active",
}).returning().then((rows) => rows[0]!);
const connection = await db.insert(toolConnections).values({
companyId: company.id,
applicationId: application.id,
name: "Shared personal connection",
uid: `shared-personal-${randomUUID()}`,
connectionKind: "managed",
ownership: "customer",
transport: "mcp_remote",
authKind: "oauth",
credentialPolicy: "per_user",
status: "active",
enabled: true,
}).returning().then((rows) => rows[0]!);
const definition = await db.insert(userSecretDefinitions).values({
companyId: company.id,
key: `shared-personal-${randomUUID()}`,
name: "Shared personal token",
}).returning().then((rows) => rows[0]!);
const secret = await db.insert(companySecrets).values({
companyId: company.id,
scope: "user",
ownerUserId: departing!.principalId,
userSecretDefinitionId: definition.id,
key: `shared-personal-${randomUUID()}`,
name: "Shared personal token",
}).returning().then((rows) => rows[0]!);
const credentialSecretRefs = [{ secretId: secret.id, configPath: "oauth.access_token" }];
await db.update(toolConnections).set({ credentialSecretRefs }).where(eq(toolConnections.id, connection.id));
const [departingGrant, survivingGrant] = await db.insert(connectionGrants).values([
{
companyId: company.id,
connectionId: connection.id,
kind: "user" as const,
subjectUserId: departing!.principalId,
status: "active" as const,
credentialSecretRefs,
},
{
companyId: company.id,
connectionId: connection.id,
kind: "user" as const,
subjectUserId: surviving!.principalId,
status: "active" as const,
credentialSecretRefs,
},
]).returning();
await accessService(db).archiveMember(company.id, departing!.id, {
reassignment: { assigneeUserId: owner.principalId },
});
expect(await db.select().from(companySecrets).where(eq(companySecrets.id, secret.id)))
.toHaveLength(1);
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.id, departingGrant!.id)))
.toEqual([expect.objectContaining({ status: "revoked", credentialSecretRefs: [] })]);
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.id, survivingGrant!.id)))
.toEqual([expect.objectContaining({ status: "active", credentialSecretRefs })]);
expect(await db.select().from(toolConnections).where(eq(toolConnections.id, connection.id)))
.toEqual([expect.objectContaining({ status: "active", enabled: true, credentialSecretRefs })]);
});
it("keeps a mixed connection active when an unaffected organization credential survives", async () => {
const { company, owner } = await createCompanyWithOwner(db);
const departing = await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "user",
principalId: `departing-mixed-${randomUUID()}`,
status: "active",
membershipRole: "member",
}).returning().then((rows) => rows[0]!);
const application = await db.insert(toolApplications).values({
companyId: company.id,
applicationKey: `mixed-${randomUUID()}`,
name: "Mixed credential app",
type: "mcp",
status: "active",
}).returning().then((rows) => rows[0]!);
const definition = await db.insert(userSecretDefinitions).values({
companyId: company.id,
key: `mixed-personal-${randomUUID()}`,
name: "Mixed personal token",
}).returning().then((rows) => rows[0]!);
const personalSecret = await db.insert(companySecrets).values({
companyId: company.id,
scope: "user",
ownerUserId: departing.principalId,
userSecretDefinitionId: definition.id,
key: `mixed-personal-${randomUUID()}`,
name: "Mixed personal token",
}).returning().then((rows) => rows[0]!);
const organizationSecret = await db.insert(companySecrets).values({
companyId: company.id,
scope: "company",
key: `mixed-organization-${randomUUID()}`,
name: "Mixed organization token",
}).returning().then((rows) => rows[0]!);
const personalRef = { secretId: personalSecret.id, configPath: "credentials.personal" };
const organizationRef = { secretId: organizationSecret.id, configPath: "credentials.organization" };
const connection = await db.insert(toolConnections).values({
companyId: company.id,
applicationId: application.id,
name: "Mixed credential connection",
uid: `mixed-${randomUUID()}`,
connectionKind: "managed",
ownership: "customer",
transport: "mcp_remote",
authKind: "api_key",
credentialPolicy: "per_user_with_fallback",
status: "active",
enabled: true,
healthStatus: "healthy",
credentialSecretRefs: [personalRef, organizationRef],
}).returning().then((rows) => rows[0]!);
const personalGrant = await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: connection.id,
kind: "user",
subjectUserId: departing.principalId,
credentialSecretRefs: [personalRef],
}).returning().then((rows) => rows[0]!);
const organizationGrant = await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: connection.id,
kind: "organization",
status: "active",
isDefault: true,
credentialSecretRefs: [organizationRef],
}).returning().then((rows) => rows[0]!);
await accessService(db).archiveMember(company.id, departing.id, {
reassignment: { assigneeUserId: owner.principalId },
});
expect(await db.select().from(companySecrets).where(eq(companySecrets.id, personalSecret.id)))
.toHaveLength(0);
expect(await db.select().from(companySecrets).where(eq(companySecrets.id, organizationSecret.id)))
.toHaveLength(1);
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.id, personalGrant.id)))
.toEqual([expect.objectContaining({ status: "revoked", credentialSecretRefs: [] })]);
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.id, organizationGrant.id)))
.toEqual([expect.objectContaining({ status: "active", credentialSecretRefs: [organizationRef] })]);
expect(await db.select().from(toolConnections).where(eq(toolConnections.id, connection.id)))
.toEqual([expect.objectContaining({
status: "active",
enabled: true,
healthStatus: "healthy",
lastError: null,
credentialSecretRefs: [organizationRef],
})]);
});
it("keeps a sole organization audience dormant until its member is reactivated", async () => {
const { company, owner } = await createCompanyWithOwner(db);
const departing = await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "user",
principalId: `departing-org-${randomUUID()}`,
status: "active",
membershipRole: "member",
}).returning().then((rows) => rows[0]!);
const application = await db.insert(toolApplications).values({
companyId: company.id,
applicationKey: `shared-org-${randomUUID()}`,
name: "Shared organization app",
type: "mcp",
status: "active",
}).returning().then((rows) => rows[0]!);
const connection = await db.insert(toolConnections).values({
companyId: company.id,
applicationId: application.id,
name: "Shared organization connection",
uid: `shared-org-${randomUUID()}`,
connectionKind: "managed",
ownership: "customer",
transport: "mcp_remote",
authKind: "oauth",
credentialPolicy: "shared",
status: "active",
enabled: true,
}).returning().then((rows) => rows[0]!);
const definition = await db.insert(userSecretDefinitions).values({
companyId: company.id,
key: `shared-org-${randomUUID()}`,
name: "Shared organization token",
}).returning().then((rows) => rows[0]!);
const secret = await db.insert(companySecrets).values({
companyId: company.id,
scope: "user",
ownerUserId: departing.principalId,
userSecretDefinitionId: definition.id,
key: `shared-org-${randomUUID()}`,
name: "Shared organization token",
}).returning().then((rows) => rows[0]!);
const credentialSecretRefs = [{ secretId: secret.id, configPath: "oauth.access_token" }];
await db.update(toolConnections).set({ credentialSecretRefs }).where(eq(toolConnections.id, connection.id));
await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: connection.id,
kind: "user",
subjectUserId: departing.principalId,
status: "active",
credentialSecretRefs,
});
const organizationGrant = await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: connection.id,
kind: "organization",
status: "active",
isDefault: true,
credentialSecretRefs,
}).returning().then((rows) => rows[0]!);
await db.insert(connectionGrantMembers).values({
companyId: company.id,
grantId: organizationGrant.id,
subjectType: "user",
subjectId: departing.principalId,
});
await accessService(db).archiveMember(company.id, departing.id, {
reassignment: { assigneeUserId: owner.principalId },
});
expect(await db.select().from(companySecrets).where(eq(companySecrets.id, secret.id)))
.toHaveLength(1);
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.id, organizationGrant.id)))
.toEqual([expect.objectContaining({ status: "active", isDefault: true, credentialSecretRefs })]);
expect(await db.select().from(connectionGrantMembers).where(eq(connectionGrantMembers.grantId, organizationGrant.id)))
.toEqual([expect.objectContaining({ subjectId: departing.principalId })]);
expect(await db.select().from(toolConnections).where(eq(toolConnections.id, connection.id)))
.toEqual([expect.objectContaining({ status: "active", enabled: true, credentialSecretRefs })]);
await accessService(db).setUserCompanyAccess(departing.principalId, [company.id]);
expect(await db.select().from(companySecrets).where(eq(companySecrets.id, secret.id)))
.toHaveLength(1);
expect(await db.select().from(companyMemberships).where(eq(companyMemberships.id, departing.id)))
.toEqual([expect.objectContaining({ status: "active" })]);
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.id, organizationGrant.id)))
.toEqual([expect.objectContaining({ status: "active", credentialSecretRefs })]);
});
it("revokes delegated personal connection access when membership is suspended", async () => {
const { company } = await createCompanyWithOwner(db);
const member = await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "user",
principalId: `member-${randomUUID()}`,
status: "active",
membershipRole: "member",
}).returning().then((rows) => rows[0]!);
const agent = await db.insert(agents).values({
companyId: company.id,
name: "Delegated agent",
role: "worker",
adapterType: "process",
adapterConfig: {},
}).returning().then((rows) => rows[0]!);
const application = await db.insert(toolApplications).values({
companyId: company.id,
applicationKey: `app-${randomUUID()}`,
name: "Personal mail",
type: "mcp",
status: "active",
}).returning().then((rows) => rows[0]!);
const connection = await db.insert(toolConnections).values({
companyId: company.id,
applicationId: application.id,
name: "Mail",
uid: `mail-${randomUUID()}`,
connectionKind: "managed",
ownership: "customer",
transport: "mcp_remote",
authKind: "oauth",
credentialPolicy: "per_user",
}).returning().then((rows) => rows[0]!);
const definition = await db.insert(userSecretDefinitions).values({
companyId: company.id,
key: `oauth-${randomUUID()}`,
name: "Personal OAuth token",
}).returning().then((rows) => rows[0]!);
const secret = await db.insert(companySecrets).values({
companyId: company.id,
scope: "user",
ownerUserId: member.principalId,
userSecretDefinitionId: definition.id,
key: `oauth-${randomUUID()}`,
name: `OAuth ${randomUUID()}`,
}).returning().then((rows) => rows[0]!);
const grant = await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: connection.id,
kind: "user",
subjectUserId: member.principalId,
credentialSecretRefs: [{ secretId: secret.id, configPath: "oauth.access_token" }],
}).returning().then((rows) => rows[0]!);
await db.insert(connectionGrantDelegations).values({
companyId: company.id,
grantId: grant.id,
agentId: agent.id,
createdByUserId: member.principalId,
});
await accessService(db).updateMember(company.id, member.id, { status: "suspended" });
expect(await db.select().from(connectionGrantDelegations)).toHaveLength(0);
expect(await db.select().from(companySecrets).where(eq(companySecrets.id, secret.id))).toHaveLength(0);
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant.id)))
.toEqual([expect.objectContaining({ status: "revoked", credentialSecretRefs: [] })]);
});
it("preserves personal grant secrets used by surviving declarations and bindings", async () => {
const { company } = await createCompanyWithOwner(db);
const member = await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "user",
principalId: `member-${randomUUID()}`,
status: "active",
membershipRole: "member",
}).returning().then((rows) => rows[0]!);
const application = await db.insert(toolApplications).values({
companyId: company.id,
applicationKey: `app-${randomUUID()}`,
name: "Personal shared credentials",
type: "mcp",
status: "active",
}).returning().then((rows) => rows[0]!);
const definitions = await db.insert(userSecretDefinitions).values([
{ companyId: company.id, key: `agent-declared-${randomUUID()}`, name: "Agent-declared credential" },
{ companyId: company.id, key: `environment-declared-${randomUUID()}`, name: "Environment-declared credential" },
{ companyId: company.id, key: `bound-${randomUUID()}`, name: "Bound credential" },
]).returning();
const secrets = await db.insert(companySecrets).values(definitions.map((definition, index) => ({
companyId: company.id,
scope: "user",
ownerUserId: member.principalId,
userSecretDefinitionId: definition.id,
key: `shared-${index}-${randomUUID()}`,
name: `Shared credential ${index}`,
}))).returning();
const connection = await db.insert(toolConnections).values({
companyId: company.id,
applicationId: application.id,
name: "Shared personal connection",
uid: `shared-${randomUUID()}`,
connectionKind: "managed",
ownership: "customer",
transport: "mcp_remote",
authKind: "api_key",
credentialPolicy: "per_user",
status: "active",
enabled: true,
credentialSecretRefs: secrets.map((secret, index) => ({
secretId: secret.id,
configPath: `credentials.shared_${index}`,
})),
}).returning().then((rows) => rows[0]!);
const grant = await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: connection.id,
kind: "user",
subjectUserId: member.principalId,
credentialSecretRefs: secrets.map((secret, index) => ({
secretId: secret.id,
configPath: `credentials.shared_${index}`,
})),
}).returning().then((rows) => rows[0]!);
await db.insert(userSecretDeclarations).values([
{
companyId: company.id,
userSecretDefinitionId: definitions[0]!.id,
targetType: "agent",
targetId: `surviving-agent-${randomUUID()}`,
configPath: "env.AGENT_TOKEN",
envKey: "AGENT_TOKEN",
},
{
companyId: company.id,
userSecretDefinitionId: definitions[1]!.id,
targetType: "environment",
targetId: `surviving-environment-${randomUUID()}`,
configPath: "env.ENVIRONMENT_TOKEN",
envKey: "ENVIRONMENT_TOKEN",
},
]);
await db.insert(companySecretBindings).values([
...secrets.map((secret, index) => ({
companyId: company.id,
secretId: secret.id,
targetType: "tool_connection",
targetId: connection.id,
configPath: `credentials.shared_${index}`,
})),
{
companyId: company.id,
secretId: secrets[2]!.id,
targetType: "environment",
targetId: `surviving-environment-${randomUUID()}`,
configPath: "env.BOUND_TOKEN",
},
]);
await accessService(db).updateMember(company.id, member.id, { status: "suspended" });
expect(await db.select().from(companySecrets).where(inArray(companySecrets.id, secrets.map((secret) => secret.id))))
.toHaveLength(3);
expect(await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant.id)))
.toEqual([expect.objectContaining({ status: "revoked", credentialSecretRefs: [] })]);
expect(await db.select().from(toolConnections).where(eq(toolConnections.id, connection.id)))
.toEqual([expect.objectContaining({
status: "draft",
enabled: false,
credentialSecretRefs: [],
})]);
expect(await db.select().from(companySecretBindings)).toEqual([
expect.objectContaining({
secretId: secrets[2]!.id,
targetType: "environment",
}),
]);
expect(await db.select().from(userSecretDeclarations)).toHaveLength(2);
});
it("preserves unrelated user-scoped secrets when membership is suspended", async () => {
const { company } = await createCompanyWithOwner(db);
const member = await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "user",
principalId: `member-${randomUUID()}`,
status: "active",
membershipRole: "member",
}).returning().then((rows) => rows[0]!);
const definition = await db.insert(userSecretDefinitions).values({
companyId: company.id,
key: `oauth-${randomUUID()}`,
name: "Personal OAuth token",
}).returning().then((rows) => rows[0]!);
const unrelatedSecret = await db.insert(companySecrets).values({
companyId: company.id,
scope: "user",
ownerUserId: member.principalId,
userSecretDefinitionId: definition.id,
key: `oauth-${randomUUID()}`,
name: "Environment API key",
}).returning().then((rows) => rows[0]!);
const otherUserSecret = await db.insert(companySecrets).values({
companyId: company.id,
scope: "user",
ownerUserId: "another-user",
userSecretDefinitionId: definition.id,
key: `oauth-${randomUUID()}`,
name: "Another user's credential",
}).returning().then((rows) => rows[0]!);
await accessService(db).updateMember(company.id, member.id, { status: "suspended" });
expect(await db.select().from(companySecrets).where(eq(companySecrets.id, unrelatedSecret.id)))
.toHaveLength(1);
expect(await db.select().from(companySecrets).where(eq(companySecrets.id, otherUserSecret.id)))
.toHaveLength(1);
});
it("allows owner and admin role-default grants to manage environments", async () => {
const { company, owner } = await createCompanyWithOwner(db);
const access = accessService(db);
@@ -860,9 +860,23 @@ describeEmbeddedPostgres("attention service", () => {
addresseeAgentId: reviewerId,
payload: { version: 1, questions: [] },
});
await db.insert(issueThreadInteractions).values({
id: randomUUID(),
companyId,
issueId,
kind: "ask_user_questions",
status: "pending",
title: "User-addressed question",
createdByAgentId: workerId,
addresseeUserId: "board-user",
requestedResolverPolicy: "human_only",
effectiveResolverPolicy: "human_only",
payload: { version: 1, questions: [] },
});
await agentService(db).pause(reviewerId);
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
const otherUserFeed = await attentionService(db).list(companyId, { userId: "other-user" });
const audienceByTitle = new Map(feed.items
.filter((item) => item.sourceKind === "issue_thread_interaction")
.map((item) => [item.subject.title, item.resolverAudience]));
@@ -888,6 +902,11 @@ describeEmbeddedPostgres("attention service", () => {
addresseeAgentId: reviewerId,
addresseeName: "Reviewer",
});
expect(audienceByTitle.get("User-addressed question")).toMatchObject({
addresseeUserId: "board-user",
effectiveResolverPolicy: "human_only",
});
expect(otherUserFeed.items.some((item) => item.subject.title === "User-addressed question")).toBe(false);
// Non-interaction rows carry no resolver policy at all.
expect(feed.items.find((item) => item.sourceKind !== "issue_thread_interaction")?.resolverAudience)
.toBeNull();
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import {
isConnectionGrantAudienceAllowed,
resolveCredentialGrantKind,
} from "../services/tool-gateway.js";
describe("connection grant resolution", () => {
it("resolves every credential policy deterministically", () => {
expect(resolveCredentialGrantKind("shared", "alice", true)).toBe("organization");
expect(resolveCredentialGrantKind("per_user", "alice", true)).toBe("user");
expect(resolveCredentialGrantKind("per_user", "alice", false)).toBe("user_authorization_required");
expect(resolveCredentialGrantKind("per_user", null, false)).toBe("user_authorization_required");
expect(resolveCredentialGrantKind("per_user_with_fallback", "alice", true)).toBe("user");
expect(resolveCredentialGrantKind("per_user_with_fallback", "alice", false)).toBe("organization");
expect(resolveCredentialGrantKind("per_user_with_fallback", null, false)).toBe("organization");
});
it("allows an empty audience and rejects users outside a restricted audience", () => {
expect(isConnectionGrantAudienceAllowed([], "alice", true)).toBe(true);
expect(isConnectionGrantAudienceAllowed(["alice", "bob"], "alice", true)).toBe(true);
expect(isConnectionGrantAudienceAllowed(["alice", "bob"], "carol", true)).toBe(false);
expect(isConnectionGrantAudienceAllowed(["alice"], null, false)).toBe(false);
expect(isConnectionGrantAudienceAllowed([], "alice", false)).toBe(false);
expect(isConnectionGrantAudienceAllowed(["alice"], "alice", false)).toBe(false);
});
});
@@ -366,6 +366,9 @@ describeEmbeddedPostgres("generic remote MCP connections", () => {
// this connection cannot be depending on gallery metadata for anything.
expect(connection!.config).not.toHaveProperty("sourceTemplateKey");
expect(connection!.config).not.toHaveProperty("connectionMethodKey");
await expect(service.listConnectionGrants(result.connectionId, company.id)).resolves.toMatchObject({
grants: [expect.objectContaining({ kind: "organization", isDefault: true, credentialSecretRefs: [] })],
});
const profiles = await db.select().from(toolProfiles).where(eq(
toolProfiles.profileKey,
`app:${result.connectionId}`,
@@ -902,6 +905,7 @@ describeEmbeddedPostgres("generic remote MCP connections", () => {
});
it("redacts a hostile denial from the callback route and consumes the state", async () => {
vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL);
installMcpOAuthFixture({ auth: "oauth" });
const company = await createCompany(db);
const service = toolAccessService(db);
@@ -966,6 +970,7 @@ describeEmbeddedPostgres("generic remote MCP connections", () => {
});
it("returns browser denials to setup without reflecting provider-authored details", async () => {
vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL);
installMcpOAuthFixture({ auth: "oauth" });
const company = await createCompany(db);
const service = toolAccessService(db);
@@ -1218,7 +1218,7 @@ describe("plugin worker manager setup-token pty route gate", () => {
} finally {
await handle.stop().catch(() => undefined);
}
});
}, 15_000);
it("routes delayed input to the worker and back to the listener", async () => {
const handle = makeLoginPtyHandle();
+4
View File
@@ -6,6 +6,7 @@ import {
activityLog,
agents,
authUsers,
connectionGrants,
companies,
companyMemberships,
createDb,
@@ -354,10 +355,13 @@ describeEmbeddedPostgres("smoke lab service pack and results API", () => {
const applications = await db.select().from(toolApplications).where(eq(toolApplications.companyId, company.id));
const connections = await db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id));
const grants = await db.select().from(connectionGrants).where(eq(connectionGrants.companyId, company.id));
const catalog = await db.select().from(toolCatalogEntries).where(eq(toolCatalogEntries.companyId, company.id));
const profiles = await db.select().from(toolProfiles).where(eq(toolProfiles.companyId, company.id));
expect(applications).toHaveLength(2);
expect(connections).toHaveLength(2);
expect(grants).toHaveLength(2);
expect(grants.every((grant) => grant.kind === "organization" && grant.isDefault)).toBe(true);
expect(catalog.some((entry) => entry.toolName === "todo.add" && entry.riskLevel === "write")).toBe(true);
expect(catalog.some((entry) => entry.toolName === "time.now" && entry.riskLevel === "read")).toBe(true);
expect(profiles).toHaveLength(1);
@@ -1660,7 +1660,7 @@ describeEmbeddedPostgres("tool access policy service", () => {
await expect(svc.createConnection(company.id, {
name: "Wrong secret",
transport: "mcp_remote",
transportConfig: { url: "https://example.invalid/mcp" },
transportConfig: { url: "https://8.8.8.8/mcp" },
credentialSecretRefs: [{
secretId: otherSecret.id,
configPath: "headers.Authorization",
File diff suppressed because it is too large. Load diff
@@ -380,7 +380,8 @@ describeEmbeddedPostgres("tool connection removal", () => {
expect(removed.removal).toMatchObject({
secretsRevoked: headerSecretIds.length + 3,
secretsRetainedShared: 0,
grantsRevoked: 1,
// The default organization grant and the explicit user grant are both revoked.
grantsRevoked: 2,
oauthStatesDiscarded: 1,
tokenIssuanceHashesCleared: 1,
});
@@ -665,8 +666,9 @@ describeEmbeddedPostgres("tool connection removal", () => {
const reconnectedSecretIds = after!.credentialSecretRefs.map((ref) => ref.secretId);
// Not one of the revoked secrets came back.
for (const secretId of originalSecretIds) expect(reconnectedSecretIds).not.toContain(secretId);
// And the operator has to choose access again — the app profile is not back.
expect(await db.select().from(toolProfiles).where(eq(toolProfiles.profileKey, `app:${connectionId}`))).toEqual([]);
// A fresh connect recreates the deny-by-default profile, but does not restore installs.
await expect(db.select().from(toolProfiles).where(eq(toolProfiles.profileKey, `app:${connectionId}`)))
.resolves.toHaveLength(1);
expect(await service.listConnectionInstalls(connectionId, company.id)).toEqual([]);
});
});
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import { filterVisibleToolConnections } from "../routes/tool-access.js";
const connections = [
{ id: "other-draft", status: "draft", createdByUserId: "other-user" },
{ id: "own-draft", status: "draft", createdByUserId: "member-user" },
{ id: "active", status: "active", createdByUserId: "other-user" },
];
describe("tool connection visibility", () => {
it("keeps foreign drafts out of a regular member's reusable connection candidates", () => {
expect(filterVisibleToolConnections(connections, {
userId: "member-user",
canManageConnections: false,
})).toEqual([
connections[1],
connections[2],
]);
});
it("keeps every draft visible to a connection manager", () => {
expect(filterVisibleToolConnections(connections, {
userId: "owner-user",
canManageConnections: true,
})).toEqual(connections);
});
});
@@ -6,6 +6,7 @@ import {
agents,
approvals,
companies,
connectionGrants,
createDb,
heartbeatRuns,
issueApprovals,
@@ -41,6 +42,7 @@ function createTestToolGatewayService(db: ReturnType<typeof createDb>, options:
return createToolGatewayService(db, {
...options,
toolActionSigningSecret: options.toolActionSigningSecret ?? testToolActionSigningSecret,
remoteHttpRequest: options.remoteHttpRequest ?? (async (url, init) => fetch(url, init)),
});
}
@@ -93,8 +95,17 @@ async function createRemoteMcpToolFixture(db: ReturnType<typeof createDb>, compa
healthStatus: "ok",
// Use a public IP literal so protocol tests remain independent of DNS while
// still exercising the production egress guard and their global fetch stub.
credentialPolicy: "shared",
config: { url: "https://8.8.8.8/mcp" },
}).returning().then((rows) => rows[0]!);
await db.insert(connectionGrants).values({
companyId,
connectionId: connection.id,
kind: "organization",
credentialSecretRefs: [],
status: "active",
isDefault: true,
});
const catalogEntry = await db.insert(toolCatalogEntries).values({
companyId,
applicationId: application.id,
+351 -1
View File
@@ -12,6 +12,9 @@ import {
companySecretVersions,
companyMemberships,
companies,
connectionGrantMembers,
connectionGrantDelegations,
connectionGrants,
createDb,
heartbeatRuns,
issueThreadInteractions,
@@ -113,6 +116,16 @@ async function createIssueAndRun(db: Db, companyId: string, agentId: string) {
return { project, issue, run };
}
async function createActiveMember(db: Db, companyId: string, userId: string) {
await db.insert(companyMemberships).values({
companyId,
principalType: "user",
principalId: userId,
status: "active",
membershipRole: "member",
});
}
async function allowToolsForAgent(db: Db, companyId: string, agentId: string, toolNames: string[]) {
const profile = await db
.insert(toolProfiles)
@@ -214,6 +227,14 @@ async function createRemoteMcpTool(
credentialRefs: input.credentialRefs ?? [],
credentialSecretRefs: input.credentialSecretRefs ?? [],
}).returning();
await db.insert(connectionGrants).values({
companyId,
connectionId: connection.id,
kind: "organization",
credentialSecretRefs: connection.credentialSecretRefs,
status: "active",
isDefault: true,
});
if (input.credentialRefs?.length || input.credentialSecretRefs?.length) {
await db.insert(companySecretBindings).values([
...(input.credentialRefs ?? []).map((ref) => ({
@@ -276,6 +297,11 @@ async function createLocalStdioMcpTool(
healthStatus?: "unknown" | "healthy" | "degraded" | "failed" | "unchecked" | "ok" | "error" | "missing_secret";
catalogStatus?: "active" | "disabled" | "quarantined" | "removed";
riskLevel?: "read" | "write" | "destructive";
credentialPolicy?: "shared" | "per_user" | "per_user_with_fallback";
credentialSecretRefs?: typeof toolConnections.$inferInsert["credentialSecretRefs"];
stdioScript?: string;
envKeys?: string[];
connectionConfig?: Record<string, unknown>;
} = {},
) {
const applicationKey = input.applicationKey ?? `local-app-${randomUUID().slice(0, 8)}`;
@@ -333,9 +359,31 @@ rl.on("line", (line) => {
status: input.connectionStatus ?? "active",
enabled: input.connectionEnabled ?? true,
healthStatus: input.healthStatus ?? "ok",
credentialPolicy: input.credentialPolicy ?? "shared",
config: { templateId: templateKey, ...(input.connectionConfig ?? {}) },
transportConfig: { templateId: templateKey, ...(input.connectionConfig ?? {}) },
credentialSecretRefs: input.credentialSecretRefs ?? [],
}).returning();
await db.insert(connectionGrants).values({
companyId,
connectionId: connection.id,
kind: "organization",
credentialSecretRefs: connection.credentialSecretRefs,
status: "active",
isDefault: true,
});
if (input.credentialSecretRefs?.length) {
await db.insert(companySecretBindings).values(input.credentialSecretRefs.map((ref) => ({
companyId,
secretId: ref.secretId,
targetType: "tool_connection" as const,
targetId: connection.id,
configPath: ref.configPath,
versionSelector: String(ref.versionSelector ?? "latest"),
required: ref.required ?? true,
label: ref.label ?? null,
}))).onConflictDoNothing();
}
const [catalogEntry] = await db.insert(toolCatalogEntries).values({
companyId,
applicationId: application!.id,
@@ -1276,13 +1324,26 @@ describeEmbeddedPostgres("tool gateway acceptance", () => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
const { run } = await createIssueAndRun(db, company.id, agent.id);
const allowedToken = await secretService(db).create(company.id, {
name: `Local stdio token ${randomUUID()}`,
key: `local_stdio_token_${randomUUID().replace(/-/g, "")}`,
provider: "local_encrypted",
value: "allowed-token",
});
const localTool = await createLocalStdioMcpTool(db, company.id, {
applicationKey: "local-env-demo",
connectionName: "Local Env Demo",
toolName: "inspect_env",
title: "Inspect env",
envKeys: ["ALLOWED_TOKEN"],
connectionConfig: { env: { ALLOWED_TOKEN: "allowed-token", EXTRA_CONFIG: "extra-value", NODE_OPTIONS: "--trace-warnings" } },
credentialSecretRefs: [{
secretId: allowedToken.id,
versionSelector: "latest",
configPath: "env.ALLOWED_TOKEN",
required: true,
label: "Allowed token",
}],
connectionConfig: { env: { ALLOWED_TOKEN: "connection-level-token", EXTRA_CONFIG: "extra-value", NODE_OPTIONS: "--trace-warnings" } },
stdioScript: `
const readline = require("node:readline");
const rl = readline.createInterface({ input: process.stdin });
@@ -1352,6 +1413,149 @@ rl.on("line", (line) => {
}
});
it("passes only the selected grant identity to local stdio MCP processes", async () => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
const { run } = await createIssueAndRun(db, company.id, agent.id);
await createActiveMember(db, company.id, "alice");
await db.update(heartbeatRuns).set({ responsibleUserId: "alice" }).where(eq(heartbeatRuns.id, run.id));
const values = {
organization: `organization-${randomUUID()}`,
alice: `alice-${randomUUID()}`,
bob: `bob-${randomUUID()}`,
};
const organizationSecret = await secretService(db).create(company.id, {
name: `Organization stdio token ${randomUUID()}`,
key: `organization_stdio_${randomUUID().replace(/-/g, "")}`,
provider: "local_encrypted",
value: values.organization,
});
const aliceSecret = await secretService(db).create(company.id, {
name: `Alice stdio token ${randomUUID()}`,
key: `alice_stdio_${randomUUID().replace(/-/g, "")}`,
provider: "local_encrypted",
value: values.alice,
});
const bobSecret = await secretService(db).create(company.id, {
name: `Bob stdio token ${randomUUID()}`,
key: `bob_stdio_${randomUUID().replace(/-/g, "")}`,
provider: "local_encrypted",
value: values.bob,
});
const localTool = await createLocalStdioMcpTool(db, company.id, {
applicationKey: "local-grant-identity",
toolName: "identity",
title: "Grant identity",
envKeys: ["IDENTITY_TOKEN"],
credentialSecretRefs: [{
secretId: organizationSecret.id,
versionSelector: "latest",
configPath: "env.IDENTITY_TOKEN",
required: true,
label: "Organization identity",
}],
connectionConfig: { env: { IDENTITY_TOKEN: "legacy-connection-identity" } },
stdioScript: `
const readline = require("node:readline");
const identities = ${JSON.stringify(values)};
const rl = readline.createInterface({ input: process.stdin });
rl.on("line", (line) => {
const message = JSON.parse(line);
if (message.method === "initialize") {
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: "2024-11-05", capabilities: {}, serverInfo: { name: "identity-stdio", version: "0.0.0" } } }) + "\\n");
return;
}
if (message.method === "tools/call") {
const identity = Object.entries(identities).find(([, value]) => value === process.env.IDENTITY_TOKEN)?.[0] ?? "unknown";
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { content: [{ type: "text", text: identity }], structuredContent: { identity } } }) + "\\n");
}
});
`,
});
const grantRef = (secretId: string, label: string) => ({
secretId,
versionSelector: "latest" as const,
configPath: "env.IDENTITY_TOKEN",
required: true,
label,
});
const [aliceGrant] = await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: localTool.connection.id,
kind: "user",
subjectUserId: "alice",
credentialSecretRefs: [grantRef(aliceSecret.id, "Alice identity")],
status: "active",
isDefault: false,
}).returning();
await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: localTool.connection.id,
kind: "user",
subjectUserId: "bob",
credentialSecretRefs: [grantRef(bobSecret.id, "Bob identity")],
status: "active",
isDefault: false,
});
await allowAllToolsForAgent(db, company.id, agent.id);
const gateway = createTestToolGatewayService(db, { runtimeSupervisor: { idleTtlMs: 10_000 } });
const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });
const tool = (await gateway.listToolsForSession(session.token)).find((item) => item.connectionId === localTool.connection.id)!;
const executeIdentity = async () => {
const result = await gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: {} });
return (result.result as { data?: { structuredContent?: { identity?: string } } }).data?.structuredContent?.identity;
};
expect(await executeIdentity()).toBe("organization");
await db.update(toolConnections).set({ credentialPolicy: "per_user" }).where(eq(toolConnections.id, localTool.connection.id));
expect(await executeIdentity()).toBe("alice");
await db.update(toolConnections).set({ credentialPolicy: "per_user_with_fallback" }).where(eq(toolConnections.id, localTool.connection.id));
expect(await executeIdentity()).toBe("alice");
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, aliceGrant.id));
expect(await executeIdentity()).toBe("organization");
await db.delete(toolRuntimeSlots).where(eq(toolRuntimeSlots.connectionId, localTool.connection.id));
await db.update(toolConnections).set({ credentialPolicy: "per_user" }).where(eq(toolConnections.id, localTool.connection.id));
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: {} }))
.rejects.toMatchObject({ status: 409, reasonCode: "user_authorization_required" });
expect(await db.select().from(toolRuntimeSlots).where(eq(toolRuntimeSlots.connectionId, localTool.connection.id))).toHaveLength(0);
const [organizationGrant] = await db.select().from(connectionGrants).where(and(
eq(connectionGrants.connectionId, localTool.connection.id),
eq(connectionGrants.kind, "organization"),
));
await db.insert(connectionGrantMembers).values({
companyId: company.id,
grantId: organizationGrant.id,
subjectType: "user",
subjectId: "sales-user",
});
await db.update(toolConnections).set({ credentialPolicy: "shared" }).where(eq(toolConnections.id, localTool.connection.id));
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: {} }))
.rejects.toMatchObject({ status: 403, reasonCode: "grant_audience_denied" });
expect(await db.select().from(toolRuntimeSlots).where(eq(toolRuntimeSlots.connectionId, localTool.connection.id))).toHaveLength(0);
await db.insert(connectionGrantMembers).values({
companyId: company.id,
grantId: organizationGrant.id,
subjectType: "user",
subjectId: "alice",
});
expect(await executeIdentity()).toBe("organization");
await db.delete(toolRuntimeSlots).where(eq(toolRuntimeSlots.connectionId, localTool.connection.id));
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, organizationGrant.id));
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: {} }))
.rejects.toMatchObject({ status: 409, reasonCode: "organization_authorization_required" });
await db.delete(connectionGrantMembers).where(eq(connectionGrantMembers.grantId, organizationGrant.id));
await db.update(toolConnections).set({ credentialPolicy: "per_user" }).where(eq(toolConnections.id, localTool.connection.id));
await db.update(heartbeatRuns).set({ responsibleUserId: null }).where(eq(heartbeatRuns.id, run.id));
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: {} }))
.rejects.toMatchObject({ status: 409, reasonCode: "user_authorization_required" });
expect(await db.select().from(toolRuntimeSlots).where(eq(toolRuntimeSlots.connectionId, localTool.connection.id))).toHaveLength(0);
});
it("keeps connected remote MCP gateway names collision-safe and excludes inactive catalog sources", async () => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
@@ -1629,6 +1833,152 @@ rl.on("line", (line) => {
}
});
it("creates a personal authorization card and resumes after the user grant exists", async () => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
const { issue, run } = await createIssueAndRun(db, company.id, agent.id);
await createActiveMember(db, company.id, "carol");
await db.update(heartbeatRuns).set({ responsibleUserId: "carol" }).where(eq(heartbeatRuns.id, run.id));
const fake = await startFakeRemoteMcpServer((fakeRequest) => ({
body: {
jsonrpc: "2.0",
id: fakeRequest.body?.id,
result: { content: [{ type: "text", text: "connected" }] },
},
}));
try {
const { connection } = await createRemoteMcpTool(db, company.id, {
url: fake.url,
toolName: "whoami",
riskLevel: "read",
});
await db.update(toolConnections).set({ credentialPolicy: "per_user" }).where(eq(toolConnections.id, connection.id));
await allowAllToolsForAgent(db, company.id, agent.id);
const gateway = createTestToolGatewayService(db);
const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });
const tool = (await gateway.listToolsForSession(session.token)).find((item) => item.providerType === "mcp_remote_http")!;
await db.insert(issueThreadInteractions).values({
companyId: company.id,
issueId: issue.id,
kind: "request_confirmation",
status: "pending",
continuationPolicy: "none",
requestedResolverPolicy: "anyone",
effectiveResolverPolicy: "anyone",
idempotencyKey: `connection-authorization:${connection.id}:carol`,
title: "Connect your account",
summary: `Connect ${connection.name} to continue`,
payload: {
version: 1,
prompt: `Connect your account to ${connection.name}`,
acceptLabel: "Open authorization",
rejectLabel: "Not now",
},
});
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: {} }))
.rejects.toMatchObject({ status: 409, reasonCode: "user_authorization_required" });
const [interaction] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, issue.id));
expect(interaction).toMatchObject({
kind: "request_confirmation",
status: "pending",
continuationPolicy: "wake_assignee",
requestedResolverPolicy: "human_only",
effectiveResolverPolicy: "human_only",
addresseeUserId: "carol",
});
expect(interaction!.payload).toMatchObject({
prompt: `Connect your ${connection.name} account to continue`,
target: { key: `connection:${connection.uid}:user:carol` },
});
await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: connection.id,
kind: "user",
subjectUserId: "carol",
credentialSecretRefs: [],
status: "active",
isDefault: false,
});
const result = await gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: {} });
expect(result).toMatchObject({ status: "completed", result: { content: "connected" } });
expect(fake.requests).toHaveLength(1);
} finally {
await fake.close();
}
});
it("requires an explicit named-agent delegation for autonomous personal-identity runs", async () => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
const { issue, run } = await createIssueAndRun(db, company.id, agent.id);
await createActiveMember(db, company.id, "alice");
await db.update(heartbeatRuns).set({
responsibleUserId: "alice",
invocationSource: "automation",
}).where(eq(heartbeatRuns.id, run.id));
const fake = await startFakeRemoteMcpServer((fakeRequest) => ({
body: {
jsonrpc: "2.0",
id: fakeRequest.body?.id,
result: { content: [{ type: "text", text: "delegated" }] },
},
}));
try {
const { connection } = await createRemoteMcpTool(db, company.id, {
url: fake.url,
toolName: "whoami",
riskLevel: "read",
});
await db.update(toolConnections).set({ credentialPolicy: "per_user" }).where(eq(toolConnections.id, connection.id));
const grant = await db.insert(connectionGrants).values({
companyId: company.id,
connectionId: connection.id,
kind: "user",
subjectUserId: "alice",
credentialSecretRefs: [],
status: "active",
isDefault: false,
}).returning().then((rows) => rows[0]!);
await allowAllToolsForAgent(db, company.id, agent.id);
const gateway = createTestToolGatewayService(db);
const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });
const tool = (await gateway.listToolsForSession(session.token)).find((item) => item.providerType === "mcp_remote_http")!;
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: {} }))
.rejects.toMatchObject({ status: 409, reasonCode: "standing_delegation_required" });
expect(fake.requests).toHaveLength(0);
expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, issue.id)))
.toEqual([expect.objectContaining({
status: "pending",
addresseeUserId: "alice",
idempotencyKey: `connection-delegation:${connection.id}:alice:${agent.id}`,
})]);
await db.insert(connectionGrantDelegations).values({
companyId: company.id,
grantId: grant.id,
agentId: agent.id,
createdByUserId: "alice",
});
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: {} }))
.resolves.toMatchObject({ status: "completed", result: { content: "delegated" } });
expect(fake.requests).toHaveLength(1);
await db.update(companyMemberships).set({ status: "suspended" }).where(and(
eq(companyMemberships.companyId, company.id),
eq(companyMemberships.principalId, "alice"),
));
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: {} }))
.rejects.toMatchObject({ status: 403, reasonCode: "grant_owner_membership_inactive" });
expect(fake.requests).toHaveLength(1);
} finally {
await fake.close();
}
});
it("keeps managed credentials authoritative even when legacy override flags are set", async () => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
@@ -6806,6 +6806,7 @@ describeEmbeddedPostgres("workspace runtime service control persistence", () =>
services: [{
name: "paperclip-dev",
command,
env: { PAPERCLIP_PUBLIC_URL: "http://127.0.0.1:3100" },
port: { type: "fixed", value: 45_439, envKey: "PORT" },
readiness: {
type: "http",
@@ -7717,6 +7718,7 @@ describeEmbeddedPostgres("workspace runtime startup reconciliation", () => {
{
name: "paperclip-dev",
command,
env: { PAPERCLIP_PUBLIC_URL: "http://127.0.0.1:3100" },
port: legacyPort,
// The pre-feature block: backend URL only, no exposure declaration.
expose: { type: "url", urlTemplate: "http://127.0.0.1:{{port}}" },
+4
View File
@@ -101,11 +101,15 @@ export function errorHandler(
const workspaceRepairPreconditionFailure = details?.code === "workspace_repair_precondition_failed";
const structuredConnectionError = new Set([
"user_authorization_required",
"organization_authorization_required",
"grant_audience_denied",
"grant_revoked",
"needs_reauthorization",
"installation_required",
"connection_not_installed",
"subject_not_permitted",
"standing_delegation_required",
"grant_owner_membership_inactive",
]).has(typeof details?.code === "string" ? details.code : "");
recordResponsibleUserDenialFromHttpError(req, details);
if (err.status >= 500) {
+13 -162
View File
@@ -14,7 +14,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { Router } from "express";
import type { Request } from "express";
import { and, desc, eq, gt, inArray, isNotNull, isNull, lte, ne, sql } from "drizzle-orm";
import { and, desc, eq, gt, inArray, isNotNull, isNull, lte, ne } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
assets,
@@ -47,7 +47,7 @@ import {
PERMISSION_KEYS,
isUuidLike,
} from "@paperclipai/shared";
import type { DeploymentExposure, DeploymentMode, HumanCompanyMembershipRole, PermissionKey } from "@paperclipai/shared";
import type { DeploymentExposure, DeploymentMode, HumanCompanyMembershipRole } from "@paperclipai/shared";
import {
forbidden,
conflict,
@@ -121,11 +121,6 @@ const INVITE_TOKEN_MAX_RETRIES = 5;
const COMPANY_INVITE_TTL_MS = 72 * 60 * 60 * 1000;
const INVITE_RESOLUTION_DNS_TIMEOUT_MS = 3_000;
type MemberGrantPayload = {
permissionKey: PermissionKey;
scope?: Record<string, unknown> | null;
};
export function createInviteToken() {
const suffix = randomBytes(INVITE_TOKEN_ENTROPY_BYTES).toString("base64url");
return `${INVITE_TOKEN_PREFIX}${suffix}`;
@@ -4491,69 +4486,7 @@ export function accessRoutes(
if (!memberToUpdate) throw notFound("Member not found");
await assertCanManageCompanyMember(req, access, companyId, memberToUpdate);
const updated = await db.transaction(async (tx) => {
await tx.execute(sql`
select ${companyMemberships.id}
from ${companyMemberships}
where ${companyMemberships.companyId} = ${companyId}
and ${companyMemberships.principalType} = 'user'
and ${companyMemberships.status} = 'active'
and ${companyMemberships.membershipRole} = 'owner'
for update
`);
const existing = await tx
.select()
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.id, memberId),
),
)
.then((rows) => rows[0] ?? null);
if (!existing) return null;
const nextMembershipRole =
req.body.membershipRole !== undefined
? req.body.membershipRole
: existing.membershipRole;
const nextStatus = req.body.status ?? existing.status;
if (
existing.principalType === "user" &&
existing.status === "active" &&
existing.membershipRole === "owner" &&
(nextStatus !== "active" || nextMembershipRole !== "owner")
) {
const activeOwnerCount = await tx
.select({ id: companyMemberships.id })
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.status, "active"),
eq(companyMemberships.membershipRole, "owner"),
),
)
.then((rows) => rows.length);
if (activeOwnerCount <= 1) {
throw conflict("Cannot remove the last active owner");
}
}
return tx
.update(companyMemberships)
.set({
membershipRole: nextMembershipRole,
status: nextStatus,
updatedAt: new Date(),
})
.where(eq(companyMemberships.id, existing.id))
.returning()
.then((rows) => rows[0] ?? existing);
});
const updated = await access.updateMember(companyId, memberId, req.body);
if (!updated) throw notFound("Member not found");
await logActivity(db, {
@@ -4588,98 +4521,16 @@ export function accessRoutes(
if (!memberToUpdate) throw notFound("Member not found");
await assertCanManageCompanyMember(req, access, companyId, memberToUpdate);
const updated = await db.transaction(async (tx) => {
await tx.execute(sql`
select ${companyMemberships.id}
from ${companyMemberships}
where ${companyMemberships.companyId} = ${companyId}
and ${companyMemberships.principalType} = 'user'
and ${companyMemberships.status} = 'active'
and ${companyMemberships.membershipRole} = 'owner'
for update
`);
const existing = await tx
.select()
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.id, memberId),
),
)
.then((rows) => rows[0] ?? null);
if (!existing) return null;
const nextMembershipRole =
req.body.membershipRole !== undefined
? req.body.membershipRole
: existing.membershipRole;
const nextStatus = req.body.status ?? existing.status;
if (
existing.principalType === "user" &&
existing.status === "active" &&
existing.membershipRole === "owner" &&
(nextStatus !== "active" || nextMembershipRole !== "owner")
) {
const activeOwnerCount = await tx
.select({ id: companyMemberships.id })
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.status, "active"),
eq(companyMemberships.membershipRole, "owner"),
),
)
.then((rows) => rows.length);
if (activeOwnerCount <= 1) {
throw conflict("Cannot remove the last active owner");
}
}
const now = new Date();
const updatedMember = await tx
.update(companyMemberships)
.set({
membershipRole: nextMembershipRole,
status: nextStatus,
updatedAt: now,
})
.where(eq(companyMemberships.id, existing.id))
.returning()
.then((rows) => rows[0] ?? existing);
await tx
.delete(principalPermissionGrants)
.where(
and(
eq(principalPermissionGrants.companyId, companyId),
eq(principalPermissionGrants.principalType, existing.principalType),
eq(principalPermissionGrants.principalId, existing.principalId),
),
);
const grants = (req.body.grants ?? []) as MemberGrantPayload[];
if (grants.length > 0) {
await tx.insert(principalPermissionGrants).values(
grants.map((grant) => ({
companyId,
principalType: existing.principalType,
principalId: existing.principalId,
permissionKey: grant.permissionKey,
scope: grant.scope ?? null,
grantedByUserId: req.actor.userId ?? null,
createdAt: now,
updatedAt: now,
})),
);
}
return updatedMember;
});
const updated = await access.updateMemberAndPermissions(
companyId,
memberId,
{
membershipRole: req.body.membershipRole,
status: req.body.status,
grants: req.body.grants ?? [],
},
req.actor.userId ?? null,
);
if (!updated) throw notFound("Member not found");
await logActivity(db, {
+2
View File
@@ -4333,6 +4333,7 @@ export function issueRoutes(
effectiveResolverPolicy: string;
resolverPolicyProvenance?: string | null;
addresseeAgentId?: string | null;
addresseeUserId?: string | null;
kind: string;
status: string;
payload?: unknown;
@@ -11274,6 +11275,7 @@ export function issueRoutes(
interactionStatus: interaction.status,
continuationPolicy: interaction.continuationPolicy,
addresseeAgentId: interaction.addresseeAgentId ?? null,
addresseeUserId: interaction.addresseeUserId ?? null,
requestedResolverPolicy: interaction.requestedResolverPolicy,
effectiveResolverPolicy: interaction.effectiveResolverPolicy,
resolverPolicyProvenance: interaction.resolverPolicyProvenance,
+26
View File
@@ -199,6 +199,7 @@ import {
createToolApplicationSchema,
updateToolApplicationSchema,
createToolConnectionSchema,
createConnectionGrantDelegationSchema,
connectionTokenRequestSchema,
startConnectionAuthorizationSchema,
createToolStdioCommandTemplateSchema,
@@ -915,6 +916,8 @@ const BOARD_ONLY_OPERATIONS = new Set([
"GET /api/tool-connections/{connectionId}",
"GET /api/tool-connections/{connectionId}/grants",
"POST /api/tool-connections/{connectionId}/grants/installations",
"POST /api/tool-connections/{connectionId}/grants/{grantId}/delegations",
"DELETE /api/tool-connections/{connectionId}/grants/{grantId}/delegations/{delegationId}",
"DELETE /api/tool-connections/{connectionId}/grants/{grantId}",
"GET /api/tool-connections/{connectionId}/usage",
"PATCH /api/tool-connections/{connectionId}",
@@ -7289,6 +7292,22 @@ registerCurrentRoute({
responses: { 201: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
});
registerCurrentRoute({
method: "post",
path: "/api/tool-connections/{connectionId}/grants/{grantId}/delegations",
tags: ["tool-access"],
summary: "Delegate a personal tool connection grant to an agent",
body: createConnectionGrantDelegationSchema,
responses: { 201: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
});
registerCurrentRoute({
method: "delete",
path: "/api/tool-connections/{connectionId}/grants/{grantId}/delegations/{delegationId}",
tags: ["tool-access"],
summary: "Revoke a personal tool connection grant delegation",
});
registerCurrentRoute({
method: "delete",
path: "/api/tool-connections/{connectionId}/grants/{grantId}",
@@ -7303,6 +7322,13 @@ registerCurrentRoute({
summary: "Get tool connection usage",
});
registerCurrentRoute({
method: "put",
path: "/api/tool-connections/{connectionId}/grants/{grantId}/members",
tags: ["tool-access"],
summary: "Replace the member audience of a tool connection grant",
});
registerCurrentRoute({
method: "get",
path: "/api/tool-connections/{connectionId}/installs",
+265 -4
View File
@@ -9,7 +9,9 @@ import {
type DeploymentExposure,
type DeploymentMode,
type PermissionKey,
type ToolConnectionCreateCapabilities,
connectToolAppSchema,
createConnectionGrantDelegationSchema,
createToolStdioCommandTemplateSchema,
createToolApplicationSchema,
createToolConnectionSchema,
@@ -23,6 +25,7 @@ import {
duplicateToolProfileSchema,
finishToolAppSchema,
reconnectToolAppSchema,
replaceConnectionGrantMembersSchema,
reviewToolProfileNewToolsSchema,
createToolTrustRuleFromActionRequestSchema,
importMcpJsonSchema,
@@ -50,6 +53,9 @@ import {
oauthClientIdMetadataDocument,
} from "../services/tool-access.js";
const COMPANY_INSTALL_DENIAL_REASON =
"Only someone who can configure this connection can choose this.";
/** Allowlist (e.g. Google Sheets allowed spreadsheet ids) lives in connection config. */
function allowlistIds(config: Record<string, unknown> | null | undefined): string[] {
const raw = config?.allowedSpreadsheetIds;
@@ -104,6 +110,19 @@ function classifyConnectionUpdate(
return events;
}
export function filterVisibleToolConnections<T extends {
status?: string;
createdByUserId?: string | null;
}>(
connections: T[],
actor: { userId?: string | null; canManageConnections: boolean },
): T[] {
return connections.filter((connection) =>
connection.status !== "draft"
|| actor.canManageConnections
|| Boolean(actor.userId && connection.createdByUserId === actor.userId));
}
export function toolAccessRoutes(
db: Db,
options: {
@@ -227,10 +246,10 @@ export function toolAccessRoutes(
eq(connectionGrants.connectionId, connection.id),
eq(connectionGrants.status, "active"),
or(
eq(connectionGrants.kind, "workspace"),
eq(connectionGrants.kind, "organization"),
req.actor.userId
? and(eq(connectionGrants.kind, "user"), eq(connectionGrants.subjectUserId, req.actor.userId))
: eq(connectionGrants.kind, "workspace"),
: eq(connectionGrants.kind, "organization"),
),
))
.limit(1);
@@ -238,6 +257,118 @@ export function toolAccessRoutes(
throw forbidden("You need access to this connection before you can install it on an agent");
}
/**
* Non-throwing membership probe for capability reporting (PAP-17835).
*
* `activeToolMembership` throws for viewers because it guards mutations. The
* personal-connections UI still has to *render* for a viewer, so capability
* computation needs the role without the 403. Returns `null` for a principal
* with no scoped membership (local implicit / instance admin), matching
* `activeToolMembership`'s "unrestricted" sentinel.
*/
function toolMembershipRole(req: Request, companyId: string): {
unrestricted: boolean;
role: string | null;
isViewer: boolean;
isActive: boolean;
} {
if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) {
return { unrestricted: true, role: null, isViewer: false, isActive: true };
}
const membership = Array.isArray(req.actor.memberships)
? req.actor.memberships.find((item) => item.companyId === companyId)
: null;
const isActive = Boolean(membership && membership.status === "active");
const role = membership?.membershipRole ?? null;
return { unrestricted: false, role, isViewer: role === "viewer", isActive };
}
async function isToolConnectionManagerQuiet(req: Request, companyId: string) {
const membership = toolMembershipRole(req, companyId);
if (membership.unrestricted) return true;
if (!membership.isActive || membership.isViewer) return false;
if (membership.role === "owner" || membership.role === "admin") return true;
return Boolean(req.actor.userId && await access.hasPermission(
companyId,
"user",
req.actor.userId,
"tools:manage_connections",
));
}
async function describeConnectionCreateCapabilities(
req: Request,
companyId: string,
): Promise<ToolConnectionCreateCapabilities> {
const canSetCompanyInstall = await isToolConnectionManagerQuiet(req, companyId);
return {
canSetCompanyInstall,
companyInstallReason: canSetCompanyInstall ? null : COMPANY_INSTALL_DENIAL_REASON,
};
}
/**
* Server-computed capabilities for the connection identity/install surfaces.
* The UI renders the §3 matrix from these booleans instead of reconstructing
* policy from role strings, because creator identity and per-agent edit rights
* are not derivable client-side.
*/
async function describeConnectionCapabilities(
req: Request,
connection: { id: string; companyId: string; createdByUserId?: string | null },
) {
const membership = toolMembershipRole(req, connection.companyId);
const isManager = await isToolConnectionManagerQuiet(req, connection.companyId);
const mutationCapable = membership.unrestricted || (membership.isActive && !membership.isViewer);
const isCreator = Boolean(req.actor.userId && connection.createdByUserId === req.actor.userId);
const canConfigure = isManager || (mutationCapable && isCreator);
const editableAgentIds: string[] = [];
if (mutationCapable) {
const companyAgents = await db
.select({ id: agents.id })
.from(agents)
.where(eq(agents.companyId, connection.companyId));
for (const agent of companyAgents) {
const decision = await access.decide({
actor: req.actor,
action: "agent_config:update",
resource: { type: "agent", companyId: connection.companyId, agentId: agent.id },
});
if (decision.allowed) editableAgentIds.push(agent.id);
}
}
return {
canConfigure,
canCreateOrganizationGrant: canConfigure,
canSetCompanyInstall: canConfigure,
// Personal consent belongs to the person: it needs a named board user, and
// it is never available to a viewer or to an unauthenticated principal.
canConnectAsCurrentUser: Boolean(req.actor.userId) && mutationCapable,
canManageAgentInstalls: mutationCapable && editableAgentIds.length > 0,
canViewOtherPersonalIdentities: isManager,
editableAgentIds,
};
}
/**
* Per-grant authorization. Revoking your own identity is always allowed (the
* consent is yours to withdraw); revoking anyone else's is manager-only — that
* is the kill switch. Audience editing is creator-or-manager, and only for an
* organization grant.
*/
function describeGrantCapabilities(
grant: { kind: string; subjectUserId: string | null; createdByUserId: string | null },
context: { userId: string | null; isManager: boolean; mutationCapable: boolean },
) {
if (!context.mutationCapable) return { canRevoke: false, canEditAudience: false };
const isOwnGrant = Boolean(context.userId && grant.subjectUserId === context.userId);
const isGrantCreator = Boolean(context.userId && grant.createdByUserId === context.userId);
return {
canRevoke: isOwnGrant || isGrantCreator || context.isManager,
canEditAudience: grant.kind === "organization" && (isGrantCreator || context.isManager),
};
}
async function assertBoardAnyToolPermission(req: Request, companyId: string, permissionKeys: PermissionKey[]) {
assertBoard(req);
assertCompanyAccess(req, companyId);
@@ -341,6 +472,7 @@ export function toolAccessRoutes(
assertCompanyAccess(req, companyId);
const googleSheetsAvailability = googleSheetsRobotEmailFromEnv();
res.json({
capabilities: await describeConnectionCreateCapabilities(req, companyId),
apps: CONNECTABLE_APP_DEFINITIONS.map((app) =>
app.slug === "google-sheets"
? {
@@ -378,9 +510,16 @@ export function toolAccessRoutes(
const result = await svc.connectGalleryApp(companyId, req.body, getActorInfo(req));
if (result.auth?.kind === "oauth") {
try {
// "Just me" must consent as the caller, not as the workspace: passing
// `subjectUserId` is what makes the callback land the tokens on the
// caller's personal grant instead of an organization grant
// (PAP-17835). The service refuses any subject other than the actor,
// so this cannot start consent on someone else's behalf.
const personalSubjectUserId = req.body.grantKind === "user" ? req.actor.userId ?? null : null;
const start = await svc.startOAuth(companyId, result.connectionId, {
redirectUri: oauthRedirectUri(),
actor: getActorInfo(req),
...(personalSubjectUserId ? { subjectUserId: personalSubjectUserId } : {}),
});
result.auth.startUrl = start.authorizationUrl;
result.auth.issuer = start.issuer ?? result.auth.issuer ?? null;
@@ -692,7 +831,14 @@ export function toolAccessRoutes(
assertBoard(req);
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
res.json({ connections: await svc.listConnections(companyId) });
const connections = await svc.listConnections(companyId);
const canManageConnections = await isToolConnectionManagerQuiet(req, companyId);
res.json({
connections: filterVisibleToolConnections(connections, {
userId: req.actor.userId,
canManageConnections,
}),
});
});
router.post("/companies/:companyId/tools/connections", validate(createToolConnectionSchema), async (req, res) => {
@@ -731,9 +877,70 @@ export function toolAccessRoutes(
assertBoard(req);
const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
if (!connection) return;
res.json(await svc.listConnectionGrants(connection.id, connection.companyId));
const listed = await svc.listConnectionGrants(connection.id, connection.companyId);
const capabilities = await describeConnectionCapabilities(req, connection);
const membership = toolMembershipRole(req, connection.companyId);
const grantContext = {
userId: req.actor.userId ?? null,
isManager: await isToolConnectionManagerQuiet(req, connection.companyId),
mutationCapable: membership.unrestricted || (membership.isActive && !membership.isViewer),
};
// A regular member has no reason to browse coworkers' personal identities;
// the manager kill switch does. Filtering here rather than in the UI keeps
// the list itself — not just its controls — under server policy.
const visibleGrants = listed.grants.filter((grant) =>
grant.kind === "organization"
|| capabilities.canViewOtherPersonalIdentities
|| (grantContext.userId !== null && grant.subjectUserId === grantContext.userId));
res.json({
...listed,
grants: visibleGrants.map((grant) => ({
...grant,
capabilities: describeGrantCapabilities(grant, grantContext),
})),
capabilities,
currentUserId: grantContext.userId,
members: capabilities.canConfigure
? await svc.listConnectionAudienceMembers(connection.companyId)
: [],
});
});
router.put(
"/tool-connections/:connectionId/grants/:grantId/members",
validate(replaceConnectionGrantMembersSchema),
async (req, res) => {
assertBoard(req);
const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
if (!connection) return;
// Viewer/inactive principals are rejected before anything else, so a
// read-only member can never reach the audience writer.
activeToolMembership(req, connection.companyId);
const { grants } = await svc.listConnectionGrants(connection.id, connection.companyId);
const target = grants.find((grant) => grant.id === req.params.grantId);
if (!target) throw notFound("Connection grant not found");
const isGrantCreator = Boolean(req.actor.userId && target.createdByUserId === req.actor.userId);
if (!isGrantCreator) await assertToolConnectionConfigureAccess(req, connection);
const memberUserIds = req.body.memberUserIds as string[];
const grant = await svc.replaceConnectionGrantMembers(
connection.id,
target.id,
memberUserIds,
getActorInfo(req),
);
await logActivity(db, {
companyId: connection.companyId,
actorType: "user",
actorId: req.actor.userId ?? "board",
action: "tool_connection.grant_audience_replaced",
entityType: "connection_grant",
entityId: grant.id,
details: { connectionId: connection.id, memberCount: memberUserIds.length },
});
res.json(grant);
},
);
router.post("/tool-connections/:connectionId/grants/installations", async (req, res) => {
assertBoard(req);
const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
@@ -786,6 +993,60 @@ export function toolAccessRoutes(
res.json(grant);
});
router.post("/tool-connections/:connectionId/grants/:grantId/delegations", validate(createConnectionGrantDelegationSchema), async (req, res) => {
assertBoard(req);
const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
if (!connection) return;
const ownerUserId = req.actor.userId;
if (!ownerUserId) throw forbidden("A named user is required to delegate a personal grant");
const agentId = req.body.agentId;
const delegation = await svc.createConnectionGrantDelegation(
connection.id,
req.params.grantId as string,
agentId,
ownerUserId,
);
await logActivity(db, {
companyId: connection.companyId,
actorType: "user",
actorId: ownerUserId,
action: "tool_connection.grant_delegated",
entityType: "connection_grant",
entityId: req.params.grantId as string,
details: { connectionId: connection.id, delegationId: delegation.id, agentId },
});
res.status(201).json(delegation);
});
router.delete("/tool-connections/:connectionId/grants/:grantId/delegations/:delegationId", async (req, res) => {
assertBoard(req);
const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
if (!connection) return;
const { grants } = await svc.listConnectionGrants(connection.id, connection.companyId);
const grant = grants.find((candidate) => candidate.id === req.params.grantId);
if (!grant) throw notFound("Connection grant not found");
const canRevokeOwnDelegation = Boolean(req.actor.userId && grant.subjectUserId === req.actor.userId);
if (!canRevokeOwnDelegation && !await isToolConnectionManager(req, connection.companyId)) {
throw forbidden("Only the personal grant owner or a connection manager can revoke a delegation");
}
const delegation = await svc.revokeConnectionGrantDelegation(
connection.id,
grant.id,
req.params.delegationId as string,
getActorInfo(req),
);
await logActivity(db, {
companyId: connection.companyId,
actorType: "user",
actorId: req.actor.userId ?? "board",
action: "tool_connection.grant_delegation_revoked",
entityType: "connection_grant",
entityId: grant.id,
details: { connectionId: connection.id, delegationId: delegation.id, agentId: delegation.agentId },
});
res.json(delegation);
});
router.get("/tool-connections/:connectionId/usage", async (req, res) => {
assertBoard(req);
const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
+351 -5
View File
@@ -1,10 +1,18 @@
import { and, eq, inArray, ne, sql } from "drizzle-orm";
import { and, eq, inArray, ne, notInArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
companyMemberships,
companySecretBindings,
companySecrets,
connectionGrantDelegations,
connectionGrantMembers,
connectionGrants,
instanceUserRoles,
issues,
principalPermissionGrants,
toolAccessAuditEvents,
toolConnections,
userSecretDeclarations,
} from "@paperclipai/db";
import type { PermissionKey, PrincipalType } from "@paperclipai/shared";
import { conflict } from "../errors.js";
@@ -28,6 +36,318 @@ type MemberArchiveInput = {
export function accessService(db: Db) {
const authorization = authorizationService(db);
async function sweepMemberConnectionAccess(
tx: Parameters<Parameters<Db["transaction"]>[0]>[0],
companyId: string,
userId: string,
now: Date,
) {
const departingAudienceRows = await tx.select({
grantId: connectionGrantMembers.grantId,
}).from(connectionGrantMembers).where(and(
eq(connectionGrantMembers.companyId, companyId),
eq(connectionGrantMembers.subjectType, "user"),
eq(connectionGrantMembers.subjectId, userId),
));
const departingAudienceGrantIds = [...new Set(departingAudienceRows.map((row) => row.grantId))];
const affectedAudienceRows = departingAudienceGrantIds.length === 0 ? [] : await tx.select({
grantId: connectionGrantMembers.grantId,
subjectId: connectionGrantMembers.subjectId,
}).from(connectionGrantMembers).where(and(
eq(connectionGrantMembers.companyId, companyId),
eq(connectionGrantMembers.subjectType, "user"),
inArray(connectionGrantMembers.grantId, departingAudienceGrantIds),
));
const activeOrganizationAudienceGrants = departingAudienceGrantIds.length === 0 ? [] : await tx.select({
id: connectionGrants.id,
}).from(connectionGrants).where(and(
eq(connectionGrants.companyId, companyId),
eq(connectionGrants.kind, "organization"),
eq(connectionGrants.status, "active"),
inArray(connectionGrants.id, departingAudienceGrantIds),
));
const activeOrganizationAudienceGrantIds = new Set(activeOrganizationAudienceGrants.map((grant) => grant.id));
const soleAudienceGrantIds = new Set(departingAudienceGrantIds.filter((grantId) =>
activeOrganizationAudienceGrantIds.has(grantId)
&& affectedAudienceRows.filter((row) => row.grantId === grantId).length === 1,
));
const ownedGrants = await tx.select({
id: connectionGrants.id,
connectionId: connectionGrants.connectionId,
credentialSecretRefs: connectionGrants.credentialSecretRefs,
}).from(connectionGrants).where(and(
eq(connectionGrants.companyId, companyId),
eq(connectionGrants.kind, "user"),
eq(connectionGrants.subjectUserId, userId),
));
const grantIds = ownedGrants.map((grant) => grant.id);
const ownedGrantIds = new Set(grantIds);
const affectedConnectionIds = [...new Set(ownedGrants.map((grant) => grant.connectionId))];
const affectedConnections = new Set(affectedConnectionIds);
// Membership removal revokes personal connection identities. It must not
// erase unrelated user-scoped values used by agent or environment secret
// declarations or bindings. Start with only secrets the departing user's
// grants explicitly reference, then fail toward retention whenever another
// consumer still names the secret or its user-secret definition.
const referencedSecretIds = [...new Set(ownedGrants.flatMap((grant) =>
grant.credentialSecretRefs.map((ref) => ref.secretId),
))];
const ownedSecrets = referencedSecretIds.length === 0 ? [] : await tx.select({
id: companySecrets.id,
userSecretDefinitionId: companySecrets.userSecretDefinitionId,
}).from(companySecrets).where(and(
eq(companySecrets.companyId, companyId),
eq(companySecrets.scope, "user"),
eq(companySecrets.ownerUserId, userId),
inArray(companySecrets.id, referencedSecretIds),
));
const ownedSecretIds = ownedSecrets.map((secret) => secret.id);
const ownedSecretSet = new Set(ownedSecretIds);
const retainedSecretIds = new Set<string>();
const sharedConnectionSecretIds = new Set<string>();
let grantMemberRefs: Array<{ grantId: string; subjectId: string }> = [];
let existingMemberUserIds = new Set<string>();
let grantRefs: Array<{
id: string;
connectionId: string;
kind: typeof connectionGrants.$inferSelect.kind;
status: typeof connectionGrants.$inferSelect.status;
credentialSecretRefs: typeof connectionGrants.$inferSelect.credentialSecretRefs;
}> = [];
let connectionRefs: Array<{
id: string;
credentialRefs: typeof toolConnections.$inferSelect.credentialRefs;
credentialSecretRefs: typeof toolConnections.$inferSelect.credentialSecretRefs;
}> = [];
if (ownedSecretIds.length > 0) {
const definitionIds = ownedSecrets.flatMap((secret) =>
secret.userSecretDefinitionId ? [secret.userSecretDefinitionId] : [],
);
const [
bindingRefs,
declarationRefs,
allGrantRefs,
allConnectionRefs,
allGrantMemberRefs,
membershipRefs,
] = await Promise.all([
tx.select({
secretId: companySecretBindings.secretId,
targetType: companySecretBindings.targetType,
targetId: companySecretBindings.targetId,
}).from(companySecretBindings).where(and(
eq(companySecretBindings.companyId, companyId),
inArray(companySecretBindings.secretId, ownedSecretIds),
)),
definitionIds.length === 0 ? Promise.resolve([]) : tx.select({
userSecretDefinitionId: userSecretDeclarations.userSecretDefinitionId,
}).from(userSecretDeclarations).where(and(
eq(userSecretDeclarations.companyId, companyId),
inArray(userSecretDeclarations.userSecretDefinitionId, definitionIds),
)),
tx.select({
id: connectionGrants.id,
connectionId: connectionGrants.connectionId,
kind: connectionGrants.kind,
status: connectionGrants.status,
credentialSecretRefs: connectionGrants.credentialSecretRefs,
}).from(connectionGrants).where(eq(connectionGrants.companyId, companyId)),
tx.select({
id: toolConnections.id,
credentialRefs: toolConnections.credentialRefs,
credentialSecretRefs: toolConnections.credentialSecretRefs,
}).from(toolConnections).where(eq(toolConnections.companyId, companyId)),
tx.select({
grantId: connectionGrantMembers.grantId,
subjectId: connectionGrantMembers.subjectId,
}).from(connectionGrantMembers).where(and(
eq(connectionGrantMembers.companyId, companyId),
eq(connectionGrantMembers.subjectType, "user"),
)),
tx.select({ userId: companyMemberships.principalId }).from(companyMemberships).where(and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.principalType, "user"),
ne(companyMemberships.principalId, userId),
)),
]);
grantRefs = allGrantRefs;
connectionRefs = allConnectionRefs;
grantMemberRefs = allGrantMemberRefs;
existingMemberUserIds = new Set(membershipRefs.map((row) => row.userId));
for (const binding of bindingRefs) {
if (binding.targetType !== "tool_connection" || !affectedConnections.has(binding.targetId)) {
retainedSecretIds.add(binding.secretId);
}
}
const declaredDefinitions = new Set(declarationRefs.map((row) => row.userSecretDefinitionId));
for (const secret of ownedSecrets) {
if (secret.userSecretDefinitionId && declaredDefinitions.has(secret.userSecretDefinitionId)) {
retainedSecretIds.add(secret.id);
}
}
for (const grant of grantRefs) {
if (ownedGrantIds.has(grant.id)) continue;
const grantAudience = grantMemberRefs.filter((member) => member.grantId === grant.id);
const remainingGrantAudience = grantAudience.filter((member) => member.subjectId !== userId);
const hasSurvivingOrganizationAudience = grant.kind === "organization"
&& grant.status === "active"
&& (
soleAudienceGrantIds.has(grant.id)
? true
: remainingGrantAudience.length === 0
? existingMemberUserIds.size > 0
: remainingGrantAudience.some((member) => existingMemberUserIds.has(member.subjectId))
);
for (const ref of grant.credentialSecretRefs) {
if (!ownedSecretSet.has(ref.secretId)) continue;
if (!affectedConnections.has(grant.connectionId)) {
retainedSecretIds.add(ref.secretId);
} else if (grant.kind === "user" || hasSurvivingOrganizationAudience) {
// A connection may temporarily carry separate user grants that
// reference the same credential, or an organization grant may
// still have another persisted audience member. A sole named
// audience row stays persisted instead of being widened to company
// scope; both resolvers require current active membership, so the
// row remains dormant until company access is restored. Pending,
// suspended, and archived memberships are intentionally included
// because company access can reactivate each of them later.
retainedSecretIds.add(ref.secretId);
sharedConnectionSecretIds.add(ref.secretId);
}
}
}
for (const connection of connectionRefs) {
if (affectedConnections.has(connection.id)) continue;
for (const ref of [...connection.credentialRefs, ...connection.credentialSecretRefs]) {
if (ownedSecretSet.has(ref.secretId)) retainedSecretIds.add(ref.secretId);
}
}
}
const secretIdsToDelete = ownedSecretIds.filter((secretId) => !retainedSecretIds.has(secretId));
const connectionSecretIdsToRemove = new Set(
ownedSecretIds.filter((secretId) => !sharedConnectionSecretIds.has(secretId)),
);
const removedDelegations = grantIds.length === 0 ? [] : await tx
.delete(connectionGrantDelegations)
.where(and(
eq(connectionGrantDelegations.companyId, companyId),
inArray(connectionGrantDelegations.grantId, grantIds),
))
.returning();
if (grantIds.length > 0) {
await tx.update(connectionGrants).set({
status: "revoked",
isDefault: false,
revokedAt: now,
revokedByUserId: null,
revokedByAgentId: null,
updatedAt: now,
}).where(and(
eq(connectionGrants.companyId, companyId),
inArray(connectionGrants.id, grantIds),
));
}
if (ownedSecretIds.length > 0) {
for (const grant of grantRefs) {
if (!ownedGrantIds.has(grant.id) && !affectedConnections.has(grant.connectionId)) continue;
const refsToRemove = ownedGrantIds.has(grant.id) ? ownedSecretSet : connectionSecretIdsToRemove;
const credentialSecretRefs = grant.credentialSecretRefs.filter(
(ref) => !refsToRemove.has(ref.secretId),
);
if (credentialSecretRefs.length !== grant.credentialSecretRefs.length) {
await tx.update(connectionGrants).set({
credentialSecretRefs,
...(ownedGrantIds.has(grant.id) || grant.status === "revoked" ? {
status: "revoked" as const,
isDefault: false,
} : {
status: "needs_reauthorization" as const,
isDefault: false,
}),
updatedAt: now,
})
.where(eq(connectionGrants.id, grant.id));
}
}
for (const connection of connectionRefs) {
if (!affectedConnections.has(connection.id)) continue;
const credentialRefs = connection.credentialRefs.filter(
(ref) => !connectionSecretIdsToRemove.has(ref.secretId),
);
const credentialSecretRefs = connection.credentialSecretRefs.filter(
(ref) => !connectionSecretIdsToRemove.has(ref.secretId),
);
if (
credentialRefs.length !== connection.credentialRefs.length ||
credentialSecretRefs.length !== connection.credentialSecretRefs.length
) {
const hasUnaffectedActiveGrant = grantRefs.some((grant) =>
grant.connectionId === connection.id
&& !ownedGrantIds.has(grant.id)
&& grant.status === "active"
&& grant.credentialSecretRefs.length > 0
&& grant.credentialSecretRefs.every((ref) => !connectionSecretIdsToRemove.has(ref.secretId)),
);
await tx.update(toolConnections).set({
credentialRefs,
credentialSecretRefs,
...(!hasUnaffectedActiveGrant ? {
status: "draft" as const,
enabled: false,
healthStatus: "missing_secret" as const,
healthMessage: "Personal credential owner no longer has company access. Reauthorize this connection.",
lastError: "oauth_reauthorization_required",
} : {}),
updatedAt: now,
})
.where(eq(toolConnections.id, connection.id));
}
}
if (affectedConnectionIds.length > 0 && connectionSecretIdsToRemove.size > 0) {
await tx.delete(companySecretBindings).where(and(
eq(companySecretBindings.companyId, companyId),
eq(companySecretBindings.targetType, "tool_connection"),
inArray(companySecretBindings.targetId, affectedConnectionIds),
inArray(companySecretBindings.secretId, [...connectionSecretIdsToRemove]),
));
}
if (secretIdsToDelete.length > 0) {
await tx.delete(companySecrets).where(and(
eq(companySecrets.companyId, companyId),
inArray(companySecrets.id, secretIdsToDelete),
));
}
}
await tx.delete(connectionGrantMembers).where(and(
eq(connectionGrantMembers.companyId, companyId),
eq(connectionGrantMembers.subjectType, "user"),
eq(connectionGrantMembers.subjectId, userId),
soleAudienceGrantIds.size > 0
? notInArray(connectionGrantMembers.grantId, [...soleAudienceGrantIds])
: undefined,
));
if (removedDelegations.length > 0) {
const connectionByGrant = new Map(ownedGrants.map((grant) => [grant.id, grant.connectionId]));
await tx.insert(toolAccessAuditEvents).values(removedDelegations.map((delegation) => ({
companyId,
connectionId: connectionByGrant.get(delegation.grantId) ?? null,
actorType: "system",
actorId: null,
action: "connection_grant.delegation_revoked",
outcome: "success",
reasonCode: "membership_removed",
details: {
grantId: delegation.grantId,
delegationId: delegation.id,
agentId: delegation.agentId,
ownerUserId: userId,
},
})));
}
}
async function isInstanceAdmin(userId: string | null | undefined): Promise<boolean> {
if (!userId) return false;
const row = await db
@@ -185,6 +505,7 @@ export function accessService(db: Db) {
.select()
.from(companyMemberships)
.where(and(eq(companyMemberships.companyId, companyId), eq(companyMemberships.id, memberId)))
.for("update")
.then((rows) => rows[0] ?? null);
if (!existing) return null;
@@ -216,6 +537,9 @@ export function accessService(db: Db) {
}
const now = new Date();
if (existing.status === "active" && nextStatus !== "active" && existing.principalType === "user") {
await sweepMemberConnectionAccess(tx, companyId, existing.principalId, now);
}
const updated = await tx
.update(companyMemberships)
.set({
@@ -334,6 +658,7 @@ export function accessService(db: Db) {
.select()
.from(companyMemberships)
.where(and(eq(companyMemberships.companyId, companyId), eq(companyMemberships.id, memberId)))
.for("update")
.then((rows) => rows[0] ?? null);
if (!existing) return null;
if (existing.principalType !== "user") {
@@ -356,6 +681,7 @@ export function accessService(db: Db) {
await assertAssignableArchiveTarget(companyId, input.reassignment, tx);
const now = new Date();
await sweepMemberConnectionAccess(tx, companyId, existing.principalId, now);
const assignmentPatch = {
assigneeAgentId: input.reassignment?.assigneeAgentId ?? null,
assigneeUserId: input.reassignment?.assigneeUserId ?? null,
@@ -449,11 +775,17 @@ export function accessService(db: Db) {
companyIds: string[],
options: { actorUserId?: string | null } = {},
) {
const existing = await listUserCompanyAccess(userId);
const existingByCompany = new Map(existing.map((row) => [row.companyId, row]));
const target = new Set(companyIds);
await db.transaction(async (tx) => {
// Serialize every company-access removal/reactivation with personal OAuth
// completion, which locks the same membership row before writing secrets.
const existing = await tx
.select()
.from(companyMemberships)
.where(and(eq(companyMemberships.principalType, "user"), eq(companyMemberships.principalId, userId)))
.for("update");
const existingByCompany = new Map(existing.map((row) => [row.companyId, row]));
const toArchive = existing.filter((row) => !target.has(row.companyId) && row.status !== "archived");
if (toArchive.length > 0 && options.actorUserId && options.actorUserId === userId) {
throw conflict("You cannot remove yourself");
@@ -489,9 +821,13 @@ export function accessService(db: Db) {
}
}
if (toArchive.length > 0) {
const now = new Date();
for (const membership of toArchive) {
await sweepMemberConnectionAccess(tx, membership.companyId, membership.principalId, now);
}
await tx
.update(companyMemberships)
.set({ status: "archived", updatedAt: new Date() })
.set({ status: "archived", updatedAt: now })
.where(inArray(companyMemberships.id, toArchive.map((row) => row.id)));
await tx
.delete(principalPermissionGrants)
@@ -736,6 +1072,7 @@ export function accessService(db: Db) {
.select()
.from(companyMemberships)
.where(and(eq(companyMemberships.companyId, companyId), eq(companyMemberships.id, memberId)))
.for("update")
.then((rows) => rows[0] ?? null);
if (!existing) return null;
@@ -766,12 +1103,21 @@ export function accessService(db: Db) {
}
}
const now = new Date();
if (
existing.principalType === "user" &&
existing.status !== "suspended" &&
nextStatus === "suspended"
) {
await sweepMemberConnectionAccess(tx, companyId, existing.principalId, now);
}
return tx
.update(companyMemberships)
.set({
membershipRole: nextMembershipRole,
status: nextStatus,
updatedAt: new Date(),
updatedAt: now,
})
.where(eq(companyMemberships.id, existing.id))
.returning()
@@ -28,6 +28,7 @@ describe("attention feed resolver audience", () => {
effectiveResolverPolicySource: "requested",
resolverPolicyProvenance: "inherited",
addresseeAgentId: null,
addresseeUserId: null,
addresseeName: null,
createdByAgentId: "agent-watchdog",
createdByAgentName: "Watchdog",
+6 -2
View File
@@ -733,6 +733,7 @@ function interactionVerbs(kind: string, payload: Record<string, unknown>) {
export function interactionResolverAudience(
row: {
addresseeAgentId: string | null;
addresseeUserId?: string | null;
createdByAgentId: string | null;
requestedResolverPolicy: string;
effectiveResolverPolicy: string;
@@ -752,6 +753,7 @@ export function interactionResolverAudience(
(row.effectiveResolverPolicySource ?? "requested") as IssueThreadInteractionEffectiveResolverPolicySource,
resolverPolicyProvenance: provenance,
addresseeAgentId: row.addresseeAgentId,
addresseeUserId: row.addresseeUserId ?? null,
addresseeName: row.addresseeAgentId ? agentName(row.addresseeAgentId) : null,
createdByAgentId: row.createdByAgentId,
createdByAgentName: row.createdByAgentId ? agentName(row.createdByAgentId) : null,
@@ -1172,6 +1174,7 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
summary: issueThreadInteractions.summary,
payload: issueThreadInteractions.payload,
addresseeAgentId: issueThreadInteractions.addresseeAgentId,
addresseeUserId: issueThreadInteractions.addresseeUserId,
createdByAgentId: issueThreadInteractions.createdByAgentId,
requestedResolverPolicy: issueThreadInteractions.requestedResolverPolicy,
effectiveResolverPolicy: issueThreadInteractions.effectiveResolverPolicy,
@@ -1207,8 +1210,9 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
: [];
const companyAgentMap = new Map(companyAgentRows.map((agent) => [agent.id, agent]));
const boardInteractionRows = interactionRows.filter((row) =>
row.addresseeAgentId === null ||
!evaluateAgentInvokability(companyAgentMap.get(row.addresseeAgentId), companyAgentRows).invokable
(row.addresseeAgentId === null ||
!evaluateAgentInvokability(companyAgentMap.get(row.addresseeAgentId), companyAgentRows).invokable)
&& (row.addresseeUserId === null || row.addresseeUserId === options.userId)
);
const visibleInteractionRows = collapsePendingConfirmationsToNewest(boardInteractionRows);
const [interactionIssueMap, interactionImageMap, interactionPlanDocumentMap] = await Promise.all([
@@ -12,6 +12,7 @@ function interaction(overrides: Record<string, unknown> = {}) {
createdByUserId: null,
sourceRunId: "run-1",
addresseeAgentId: null,
addresseeUserId: null,
effectiveResolverPolicy: "anyone",
...overrides,
};
@@ -50,6 +51,18 @@ describe("issue-thread interaction resolver audience", () => {
expect(decision).toMatchObject({ allowed: false, code: "interaction_addressee_mismatch" });
});
it("allows only the addressed user to resolve a user-addressed interaction", () => {
expect(evaluateIssueThreadInteractionResolverAudience({
actor: { type: "user", userId: "alice" },
interaction: interaction({ addresseeUserId: "alice", effectiveResolverPolicy: "human_only" }),
})).toMatchObject({ allowed: true, reason: "allow_addressee" });
expect(evaluateIssueThreadInteractionResolverAudience({
actor: { type: "user", userId: "bob" },
interaction: interaction({ addresseeUserId: "alice", effectiveResolverPolicy: "human_only" }),
})).toMatchObject({ allowed: false, code: "interaction_addressee_mismatch" });
});
it("requires run attribution for agents", () => {
const decision = evaluateIssueThreadInteractionResolverAudience({
actor: { type: "agent", agentId: "agent-1", runId: null },
@@ -46,6 +46,7 @@ export type IssueThreadInteractionResolverAudienceInput = {
createdByUserId?: string | null;
sourceRunId?: string | null;
addresseeAgentId?: string | null;
addresseeUserId?: string | null;
effectiveResolverPolicy: IssueThreadInteractionResolverPolicy | string;
resolverPolicyProvenance?: string | null;
};
@@ -180,6 +181,18 @@ export function evaluateIssueThreadInteractionResolverAudience(
}
if (input.actor.type === "user") {
if (
input.interaction.addresseeUserId
&& input.interaction.addresseeUserId !== input.actor.userId
) {
return {
allowed: false,
effectiveResolverPolicy,
status: 403,
code: "interaction_addressee_mismatch",
message: "Only the addressed user may resolve this issue-thread interaction",
};
}
if (
creatorExcluded
&& input.interaction.createdByUserId === input.actor.userId
@@ -204,7 +217,11 @@ export function evaluateIssueThreadInteractionResolverAudience(
return {
allowed: true,
effectiveResolverPolicy,
reason: input.interaction.addresseeAgentId ? "allow_human_override" : "allow_human",
reason: input.interaction.addresseeUserId
? "allow_addressee"
: input.interaction.addresseeAgentId
? "allow_human_override"
: "allow_human",
};
}
@@ -421,6 +421,7 @@ function isEquivalentCreateRequest(
row.kind === input.kind
&& row.requestedResolverPolicy === input.resolverPolicy
&& (row.addresseeAgentId ?? null) === (input.addresseeAgentId ?? null)
&& (row.addresseeUserId ?? null) === (input.addresseeUserId ?? null)
&& row.continuationPolicy === input.continuationPolicy
&& (row.idempotencyKey ?? null) === (input.idempotencyKey ?? null)
&& (row.sourceCommentId ?? null) === (input.sourceCommentId ?? null)
@@ -478,6 +479,7 @@ function hydrateInteraction(
...row,
idempotencyKey: row.idempotencyKey ?? null,
addresseeAgentId: row.addresseeAgentId ?? null,
addresseeUserId: row.addresseeUserId ?? null,
status: row.status as IssueThreadInteraction["status"],
continuationPolicy: row.continuationPolicy as IssueThreadInteraction["continuationPolicy"],
resolverPolicy: requestedResolverPolicy,
@@ -2279,6 +2281,10 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti
});
const normalizedData = { ...data, resolverPolicy: policy.requestedResolverPolicy };
if (normalizedData.addresseeAgentId && normalizedData.addresseeUserId) {
throw unprocessable("An issue-thread interaction cannot address both an agent and a user");
}
if (normalizedData.addresseeAgentId) {
if (normalizedData.addresseeAgentId === actor.agentId) {
throw unprocessable("Agents cannot address issue-thread interactions to themselves");
@@ -2409,6 +2415,7 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti
summary: data.summary ?? null,
createdByAgentId: actor.agentId ?? null,
addresseeAgentId: data.addresseeAgentId ?? null,
addresseeUserId: data.addresseeUserId ?? null,
createdByUserId: actor.userId ?? null,
payload: data.payload,
})
+22
View File
@@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url";
import { and, desc, eq, inArray } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
connectionGrants,
smokeRuns,
smokeRunSteps,
toolApplications,
@@ -741,8 +742,28 @@ export function smokeLabService(db: Db, options: {
lastHealthAt: now,
updatedAt: now,
};
const ensureDefaultOrganizationGrant = async (connectionId: string) => {
const [existingGrant] = await db.select({ id: connectionGrants.id }).from(connectionGrants).where(and(
eq(connectionGrants.companyId, input.companyId),
eq(connectionGrants.connectionId, connectionId),
eq(connectionGrants.kind, "organization"),
eq(connectionGrants.isDefault, true),
));
if (existingGrant) return;
await db.insert(connectionGrants).values({
companyId: input.companyId,
connectionId,
kind: "organization",
status: "active",
isDefault: true,
credentialSecretRefs: [],
createdAt: now,
updatedAt: now,
});
};
if (existing) {
const [updated] = await db.update(toolConnections).set(values).where(eq(toolConnections.id, existing.id)).returning();
await ensureDefaultOrganizationGrant(existing.id);
return { row: updated ?? existing, created: false };
}
const [created] = await db.insert(toolConnections).values({
@@ -754,6 +775,7 @@ export function smokeLabService(db: Db, options: {
createdByUserId: input.actor?.actorType === "user" ? input.actor.actorId : null,
createdAt: now,
}).returning();
await ensureDefaultOrganizationGrant(created.id);
return { row: created, created: true };
}
File diff suppressed because it is too large. Load diff
+376 -25
View File
@@ -5,6 +5,11 @@ import type { Db } from "@paperclipai/db";
import {
agents,
approvals,
companies,
companyMemberships,
connectionGrantMembers,
connectionGrantDelegations,
connectionGrants,
documents,
heartbeatRuns,
issueApprovals,
@@ -80,6 +85,25 @@ import {
const DEFAULT_SESSION_TTL_MS = 15 * 60 * 1000;
const MAX_SESSION_TTL_MS = 60 * 60 * 1000;
const DEFAULT_TOOL_TIMEOUT_MS = 10_000;
export function resolveCredentialGrantKind(
policy: "shared" | "per_user" | "per_user_with_fallback",
actingUserId: string | null,
hasUserGrant: boolean,
): "organization" | "user" | "user_authorization_required" {
if (policy === "shared") return "organization";
if (actingUserId && hasUserGrant) return "user";
return policy === "per_user" ? "user_authorization_required" : "organization";
}
export function isConnectionGrantAudienceAllowed(
memberUserIds: string[],
actingUserId: string | null,
actingUserIsActiveMember: boolean,
): boolean {
if (actingUserId !== null && !actingUserIsActiveMember) return false;
return memberUserIds.length === 0 || (actingUserId !== null && memberUserIds.includes(actingUserId));
}
// When a human approves a parked write, the server carries it out on their
// behalf with no interactive caller left to raise `timeoutMs`. Remote write
// providers (e.g. Zapier Google Sheets `add_row`) routinely take longer than
@@ -2389,16 +2413,36 @@ export function createToolGatewayService(
.where(eq(toolConnections.id, connection.id));
}
async function resolveCredentialHeaders(connection: typeof toolConnections.$inferSelect): Promise<Record<string, string>> {
function grantRefForHeader(
grant: typeof connectionGrants.$inferSelect,
ref: McpConnectionCredentialRef,
): ToolCredentialSecretRef | undefined {
return grant.credentialSecretRefs.find((candidate) =>
candidate.configPath === ref.name || candidate.configPath === `credentials.${ref.name}`,
);
}
async function resolveCredentialHeaders(
session: ToolGatewaySession,
connection: typeof toolConnections.$inferSelect,
grant: typeof connectionGrants.$inferSelect,
): Promise<Record<string, string>> {
const headers: Record<string, string> = {};
for (const ref of connection.credentialRefs ?? []) {
if (ref.placement !== "header") continue;
const grantRef = grantRefForHeader(grant, ref);
if (!grantRef) continue;
try {
const value = await secrets.resolveSecretValue(connection.companyId, ref.secretId, ref.version ?? "latest", {
consumerType: "tool_connection",
consumerId: connection.id,
configPath: `credentials.${ref.name}`,
actorType: "system",
const value = await secrets.resolveSecretValue(connection.companyId, grantRef.secretId, grantRef.versionSelector ?? "latest", {
accessContext: {
consumerType: "tool_connection",
consumerId: connection.id,
configPath: `credentials.${ref.name}`,
actorType: "system",
actorId: session.agentId,
issueId: session.issueId,
heartbeatRunId: session.runId,
},
});
headers[ref.key] = `${ref.prefix ?? ""}${value}`;
} catch {
@@ -2411,6 +2455,34 @@ export function createToolGatewayService(
);
}
}
const oauthAccessRef = grant.credentialSecretRefs.find((ref) => ref.configPath === "oauth.access_token");
if (oauthAccessRef && headers.Authorization === undefined) {
try {
const value = await secrets.resolveSecretValue(
connection.companyId,
oauthAccessRef.secretId,
oauthAccessRef.versionSelector ?? "latest",
{
accessContext: {
consumerType: "tool_connection",
consumerId: connection.id,
configPath: oauthAccessRef.configPath,
actorType: "system",
actorId: session.agentId,
issueId: session.issueId,
heartbeatRunId: session.runId,
},
},
);
headers.Authorization = `Bearer ${value}`;
} catch {
await markRemoteConnectionHealth(connection, "missing_secret", "A configured credential secret could not be resolved.");
throw new ToolGatewayHttpError(422, "A configured credential secret could not be resolved.", "mcp_remote_missing_secret", {
connectionId: connection.id,
credential: oauthAccessRef.configPath,
});
}
}
return headers;
}
@@ -2430,12 +2502,7 @@ export function createToolGatewayService(
): Promise<ConnectedCredentialVersionSnapshot> {
const versionSelector = input.versionSelector ?? "latest";
try {
const resolvedVersion = await secrets.resolveSecretVersion(connection.companyId, input.secretId, versionSelector, {
consumerType: "tool_connection",
consumerId: connection.id,
configPath: input.configPath,
actorType: "system",
});
const resolvedVersion = await secrets.resolveSecretVersion(connection.companyId, input.secretId, versionSelector);
return {
refHash: input.refHash,
versionSelector: String(versionSelector),
@@ -2461,6 +2528,7 @@ export function createToolGatewayService(
async function connectedCredentialVersionSnapshots(
connection: typeof toolConnections.$inferSelect,
grant: typeof connectionGrants.$inferSelect,
options: { requireResolved: boolean },
): Promise<{
headerCredentialVersions: ConnectedCredentialVersionSnapshot[];
@@ -2472,15 +2540,17 @@ export function createToolGatewayService(
for (const ref of connection.credentialRefs ?? []) {
if (ref.placement !== "header") continue;
const typedRef = ref as McpConnectionCredentialRef;
const grantRef = grantRefForHeader(grant, typedRef);
if (!grantRef) continue;
const configPath = `credentials.${typedRef.name}`;
headerCredentialVersions.push(await resolveConnectedCredentialVersion(connection, {
secretId: typedRef.secretId,
versionSelector: typedRef.version,
secretId: grantRef.secretId,
versionSelector: grantRef.versionSelector,
configPath,
refHash: credentialVersionRefHash({
kind: "header",
name: typedRef.name,
secretId: typedRef.secretId,
secretId: grantRef.secretId,
placement: typedRef.placement,
key: typedRef.key,
prefix: typedRef.prefix ?? null,
@@ -2490,7 +2560,7 @@ export function createToolGatewayService(
}));
}
for (const ref of connection.credentialSecretRefs ?? []) {
for (const ref of grant.credentialSecretRefs ?? []) {
const typedRef = ref as ToolCredentialSecretRef;
credentialSecretVersions.push(await resolveConnectedCredentialVersion(connection, {
secretId: typedRef.secretId,
@@ -2510,6 +2580,252 @@ export function createToolGatewayService(
return { headerCredentialVersions, credentialSecretVersions };
}
async function createUserAuthorizationInteraction(
session: ToolGatewaySession,
connection: typeof toolConnections.$inferSelect,
userId: string,
) {
if (!session.issueId || !session.agentId || !session.runId) return;
const [company] = await db.select({ issuePrefix: companies.issuePrefix }).from(companies)
.where(eq(companies.id, session.companyId)).limit(1);
const href = `/${company?.issuePrefix ?? ""}/apps/${connection.id}/setup`;
const idempotencyKey = `connection-authorization:${connection.id}:${userId}`;
const payload = {
version: 1 as const,
prompt: `Connect your ${connection.name} account to continue`,
acceptLabel: "Connect account",
rejectLabel: "Not now",
detailsMarkdown: "This run needs your personal authorization. Paperclip will not use another user's identity.",
target: {
type: "custom" as const,
key: `connection:${connection.uid}:user:${userId}`,
revisionId: connection.updatedAt.toISOString(),
label: `Connect ${connection.name}`,
href,
},
};
const [existing] = await db.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and(
eq(issueThreadInteractions.companyId, session.companyId),
eq(issueThreadInteractions.issueId, session.issueId),
eq(issueThreadInteractions.idempotencyKey, idempotencyKey),
)).limit(1);
if (existing) {
await db.update(issueThreadInteractions).set({
status: "pending",
continuationPolicy: "wake_assignee",
requestedResolverPolicy: "human_only",
effectiveResolverPolicy: "human_only",
resolverPolicyProvenance: "explicit",
effectiveResolverPolicySource: "requested",
addresseeUserId: userId,
payload,
result: null,
resolvedAt: null,
updatedAt: new Date(),
}).where(eq(issueThreadInteractions.id, existing.id));
return;
}
await db.insert(issueThreadInteractions).values({
companyId: session.companyId,
issueId: session.issueId,
kind: "request_confirmation",
status: "pending",
continuationPolicy: "wake_assignee",
requestedResolverPolicy: "human_only",
effectiveResolverPolicy: "human_only",
resolverPolicyProvenance: "explicit",
effectiveResolverPolicySource: "requested",
idempotencyKey,
sourceRunId: session.runId,
title: `Connect your ${connection.name}`,
summary: "Personal authorization is required before this run can continue.",
createdByAgentId: session.agentId,
addresseeUserId: userId,
payload,
});
}
async function createStandingDelegationInteraction(
session: ToolGatewaySession,
connection: typeof toolConnections.$inferSelect,
userId: string,
) {
if (!session.issueId || !session.agentId || !session.runId) return;
const [company] = await db.select({ issuePrefix: companies.issuePrefix }).from(companies)
.where(eq(companies.id, session.companyId)).limit(1);
const href = `/${company?.issuePrefix ?? ""}/apps/${connection.id}/setup`;
const idempotencyKey = `connection-delegation:${connection.id}:${userId}:${session.agentId}`;
const payload = {
version: 1 as const,
prompt: `Allow this agent to use your ${connection.name} account for autonomous runs`,
acceptLabel: "Review delegation",
rejectLabel: "Not now",
detailsMarkdown: "This autonomous run is paused. Paperclip will not use your personal identity until you explicitly delegate it to this named agent.",
target: {
type: "custom" as const,
key: `connection:${connection.uid}:delegation:${userId}:${session.agentId}`,
revisionId: connection.updatedAt.toISOString(),
label: `Delegate ${connection.name}`,
href,
},
};
const [existing] = await db.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and(
eq(issueThreadInteractions.companyId, session.companyId),
eq(issueThreadInteractions.issueId, session.issueId),
eq(issueThreadInteractions.idempotencyKey, idempotencyKey),
)).limit(1);
if (existing) {
await db.update(issueThreadInteractions).set({
status: "pending",
continuationPolicy: "wake_assignee",
requestedResolverPolicy: "human_only",
effectiveResolverPolicy: "human_only",
resolverPolicyProvenance: "explicit",
effectiveResolverPolicySource: "requested",
addresseeUserId: userId,
payload,
result: null,
resolvedAt: null,
updatedAt: new Date(),
}).where(eq(issueThreadInteractions.id, existing.id));
return;
}
await db.insert(issueThreadInteractions).values({
companyId: session.companyId,
issueId: session.issueId,
kind: "request_confirmation",
status: "pending",
continuationPolicy: "wake_assignee",
requestedResolverPolicy: "human_only",
effectiveResolverPolicy: "human_only",
resolverPolicyProvenance: "explicit",
effectiveResolverPolicySource: "requested",
idempotencyKey,
sourceRunId: session.runId,
title: `Delegate your ${connection.name}`,
summary: "An explicit standing delegation is required for this autonomous run.",
createdByAgentId: session.agentId,
addresseeUserId: userId,
payload,
});
}
async function resolveConnectionGrant(
session: ToolGatewaySession,
connection: typeof toolConnections.$inferSelect,
): Promise<typeof connectionGrants.$inferSelect> {
const [run] = session.runId
? await db.select({
responsibleUserId: heartbeatRuns.responsibleUserId,
invocationSource: heartbeatRuns.invocationSource,
}).from(heartbeatRuns).where(and(
eq(heartbeatRuns.id, session.runId),
eq(heartbeatRuns.companyId, session.companyId),
)).limit(1)
: [];
const actingUserId = run?.responsibleUserId ?? null;
const autonomous = run?.invocationSource === "automation" || run?.invocationSource === "timer";
const findUserGrant = async () => {
if (!actingUserId) return undefined;
const [membership] = await db.select({ id: companyMemberships.id }).from(companyMemberships).where(and(
eq(companyMemberships.companyId, connection.companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, actingUserId),
eq(companyMemberships.status, "active"),
)).limit(1);
if (!membership) {
throw new ToolGatewayHttpError(403, "The personal grant owner is not an active company member", "grant_owner_membership_inactive", {
connectionId: connection.id,
actingUserId,
remediation: { action: "restore_membership_or_reconnect" },
});
}
const [grant] = await db.select().from(connectionGrants).where(and(
eq(connectionGrants.companyId, connection.companyId),
eq(connectionGrants.connectionId, connection.id),
eq(connectionGrants.kind, "user"),
eq(connectionGrants.subjectUserId, actingUserId),
eq(connectionGrants.status, "active"),
)).limit(1);
return grant;
};
const findOrganizationGrant = async () => {
const [grant] = await db.select().from(connectionGrants).where(and(
eq(connectionGrants.companyId, connection.companyId),
eq(connectionGrants.connectionId, connection.id),
eq(connectionGrants.kind, "organization"),
eq(connectionGrants.isDefault, true),
eq(connectionGrants.status, "active"),
)).limit(1);
if (!grant) {
throw new ToolGatewayHttpError(409, "Organization authorization is required", "organization_authorization_required", {
connectionId: connection.id,
});
}
const members = await db.select({ subjectId: connectionGrantMembers.subjectId }).from(connectionGrantMembers).where(and(
eq(connectionGrantMembers.companyId, connection.companyId),
eq(connectionGrantMembers.grantId, grant.id),
eq(connectionGrantMembers.subjectType, "user"),
));
const activeAudienceMember = actingUserId ? await db.select({ id: companyMemberships.id }).from(companyMemberships).where(and(
eq(companyMemberships.companyId, connection.companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, actingUserId),
eq(companyMemberships.status, "active"),
)).limit(1).then((rows) => rows[0] ?? null) : null;
if (!isConnectionGrantAudienceAllowed(
members.map((member) => member.subjectId),
actingUserId,
Boolean(activeAudienceMember),
)) {
throw new ToolGatewayHttpError(403, "The acting user is not in this grant's audience", "grant_audience_denied", {
connectionId: connection.id,
grantId: grant.id,
actingUserId,
});
}
return grant;
};
const userGrant = connection.credentialPolicy === "shared" ? undefined : await findUserGrant();
const resolution = resolveCredentialGrantKind(connection.credentialPolicy, actingUserId, Boolean(userGrant));
if (resolution === "user" && userGrant) {
if (autonomous) {
if (!session.agentId) {
throw new ToolGatewayHttpError(409, "Standing delegation requires a named agent", "standing_delegation_required", {
connectionId: connection.id,
grantId: userGrant.id,
actingUserId,
});
}
const [delegation] = await db.select({ id: connectionGrantDelegations.id }).from(connectionGrantDelegations).where(and(
eq(connectionGrantDelegations.companyId, connection.companyId),
eq(connectionGrantDelegations.grantId, userGrant.id),
eq(connectionGrantDelegations.agentId, session.agentId),
)).limit(1);
if (!delegation) {
await createStandingDelegationInteraction(session, connection, actingUserId!);
throw new ToolGatewayHttpError(409, "Standing delegation is required for this autonomous run", "standing_delegation_required", {
connectionId: connection.id,
grantId: userGrant.id,
actingUserId,
agentId: session.agentId,
remediation: { action: "delegate_personal_grant", grantId: userGrant.id, agentId: session.agentId },
});
}
}
return userGrant;
}
if (resolution === "user_authorization_required") {
if (actingUserId) await createUserAuthorizationInteraction(session, connection, actingUserId);
throw new ToolGatewayHttpError(409, "User authorization is required", "user_authorization_required", {
connectionId: connection.id,
actingUserId,
});
}
return findOrganizationGrant();
}
async function resolveConnectedRemoteTool(session: ToolGatewaySession, tool: ToolGatewayDescriptor) {
if (tool.providerType !== "mcp_remote_http" || !tool.connectionId || !tool.catalogEntryId) {
throw new ToolGatewayHttpError(404, `Tool "${tool.name}" not found`, "tool_not_found");
@@ -2615,9 +2931,12 @@ export function createToolGatewayService(
};
}
function localStdioEnvironment(connection: typeof toolConnections.$inferSelect, template: LocalStdioRuntimeTemplate): NodeJS.ProcessEnv {
const config = asRecord(connection.config) ?? {};
const configEnv = asRecord(config.env) ?? {};
async function localStdioEnvironment(
session: ToolGatewaySession,
connection: typeof toolConnections.$inferSelect,
template: LocalStdioRuntimeTemplate,
grant: typeof connectionGrants.$inferSelect,
): Promise<NodeJS.ProcessEnv> {
const env: NodeJS.ProcessEnv = {};
for (const key of ["PATH", "Path", "SystemRoot", "WINDIR", "COMSPEC", "PATHEXT"]) {
const value = process.env[key];
@@ -2626,9 +2945,33 @@ export function createToolGatewayService(
}
}
for (const key of template.envKeys) {
const configured = configEnv[key];
if (typeof configured === "string") {
env[key] = configured;
const grantRef = grant.credentialSecretRefs.find((ref) => ref.configPath === `env.${key}`);
if (!grantRef) continue;
try {
env[key] = await secrets.resolveSecretValue(
connection.companyId,
grantRef.secretId,
grantRef.versionSelector ?? "latest",
{
accessContext: {
consumerType: "tool_connection",
consumerId: connection.id,
configPath: grantRef.configPath,
actorType: "system",
actorId: session.agentId,
issueId: session.issueId,
heartbeatRunId: session.runId,
},
},
);
} catch {
await markRemoteConnectionHealth(connection, "missing_secret", "A configured local stdio credential could not be resolved.");
throw new ToolGatewayHttpError(
422,
"A configured local stdio credential could not be resolved.",
"local_stdio_missing_secret",
{ connectionId: connection.id, credential: grantRef.configPath },
);
}
}
return env;
@@ -2642,6 +2985,7 @@ export function createToolGatewayService(
connection: typeof toolConnections.$inferSelect;
entry: typeof toolCatalogEntries.$inferSelect;
template: LocalStdioRuntimeTemplate;
env: NodeJS.ProcessEnv;
parameters: unknown;
timeoutMs: number;
}): Promise<unknown> {
@@ -2654,7 +2998,7 @@ export function createToolGatewayService(
);
}
const child = spawn(input.template.command, input.template.args, {
env: localStdioEnvironment(input.connection, input.template),
env: input.env,
stdio: ["pipe", "pipe", "pipe"],
});
let stdout = "";
@@ -2801,7 +3145,8 @@ export function createToolGatewayService(
))
.limit(1);
if (!row) return null;
const credentialVersions = await connectedCredentialVersionSnapshots(row.connection, {
const grant = await resolveConnectionGrant(session, row.connection);
const credentialVersions = await connectedCredentialVersionSnapshots(row.connection, grant, {
requireResolved: options.requireResolvedCredentials === true,
});
return {
@@ -2817,6 +3162,8 @@ export function createToolGatewayService(
connectionTransportConfigHash: stableHash(row.connection.transportConfig ?? {}),
credentialRefsHash: stableHash(row.connection.credentialRefs ?? []),
credentialSecretRefsHash: stableHash(row.connection.credentialSecretRefs ?? []),
credentialGrantId: grant.id,
credentialGrantRefsHash: stableHash(grant.credentialSecretRefs ?? []),
headerCredentialVersions: credentialVersions.headerCredentialVersions,
credentialSecretVersions: credentialVersions.credentialSecretVersions,
catalogEntryId: row.entry.id,
@@ -3058,13 +3405,14 @@ export function createToolGatewayService(
callerHeaders?: ExecuteGatewayToolInput["callerHeaders"],
): Promise<RemoteHttpExecutionResult> {
const { entry, connection } = await resolveConnectedRemoteTool(session, tool);
const grant = await resolveConnectionGrant(session, connection);
const endpoint = remoteEndpoint(connection.config ?? {});
// Method-defined headers are trusted catalog configuration. Treat them as
// managed headers so callers cannot override the scope that was reviewed
// during tools/list. Credentials remain authoritative on collisions.
const credentialHeaders = {
...projectedConnectionHeaders(connection),
...await resolveCredentialHeaders(connection),
...await resolveCredentialHeaders(session, connection, grant),
};
const { headers, summary: headerSummary } = buildRemoteHeaders({
session,
@@ -3208,7 +3556,9 @@ export function createToolGatewayService(
ms: number,
): Promise<RemoteHttpExecutionResult> {
const { entry, connection } = await resolveConnectedLocalStdioTool(session, tool);
const grant = await resolveConnectionGrant(session, connection);
const template = await resolveLocalStdioRuntimeTemplate(connection);
const env = await localStdioEnvironment(session, connection, template, grant);
const result = await runtimeSupervisor.useConnectionSlot(
{
companyId: session.companyId,
@@ -3232,6 +3582,7 @@ export function createToolGatewayService(
connection,
entry,
template,
env,
parameters,
timeoutMs: ms,
});