606e74d11f
## Thinking Path > - Paperclip orchestrates AI agents for zero-human companies, and a single server instance can host many companies. > - The auth middleware (`server/src/middleware/auth.ts`) supports a `cloud_tenant` mode where a trusted hosting proxy injects per-request identity headers, designed originally for one-deployment-per-tenant setups. > - In that original setup, granting every cloud tenant the `instance_admin` role was harmless; on a **shared, multi-tenant pool** it means any paying tenant is admin of the whole instance and can reach every other tenant's data. > - A tenant only needs to own its own company — which it already gets via the company membership the same code path upserts — so instance-level admin is never appropriate for `cloud_tenant` actors. > - This PR removes the `instance_admin` grant from the cloud-tenant path and pins `isInstanceAdmin: false` on the resolved actor. > - Greptile review then surfaced a follow-up gap: deployments that ran the pre-hardening build still have stale `instance_admin` rows in `instance_user_roles`, which other lookups (BetterAuth session path, board API keys, and the authorization service's own DB re-check) would still honor. > - The follow-up commit closes that gap by purging stale rows at the cloud-tenant auth boundary and by teaching the authorization service that `cloud_tenant` actors are never instance admins. > - The benefit is that shared-pool hosting becomes structurally safe: tenants are company-scoped owners, never instance admins — including on deployments upgrading from the older behavior. ## Linked Issues - Refs #966 — managed SaaS multi-tenant hosting is the deployment shape this hardening protects. - Refs #5015 — same problem space: instance-admin-scoped credentials are too broad for multi-company instances; tenants need company-scoped access. Neither issue is fully closed by this PR; it removes the instance-admin grant from the `cloud_tenant` trusted-header path specifically. ## What Changed - `server/src/middleware/auth.ts` - Removed the `instanceUserRoles` insert that granted every cloud tenant `instance_admin`; `resolveCloudTenantActor` now returns `isInstanceAdmin: false` (was `true`). - `resolveCloudTenantActor` now **deletes** any stale `instance_admin` row for the authenticated tenant user on every trusted-header request, so grants left behind by pre-hardening deployments are purged at the source (closes the Greptile P2: stale rows could otherwise re-elevate the user via the BetterAuth session path, board API keys, or the authorization service). - The function is `export`ed so it can be unit-tested directly. - `server/src/services/authorization.ts` - `authorizationService` previously re-checked `instanceUserRoles` from the DB regardless of the actor flag, which would have elevated even hardened `cloud_tenant` actors while a stale row lingered. Actors with `source === "cloud_tenant"` are now never elevated to instance admin; other board actors keep the existing lookup. - `server/src/services/authorization.ts` + `server/src/middleware/auth.ts` (follow-up commit `dc57a71c7`) - CI on the merge ref surfaced that elevation removal alone strands real cloud tenant users: board actors only ever reached `issue:read` / `issue:mutate` through instance-admin elevation (`permissionForAction` maps both to no grant key). `decide()` now grants `cloud_tenant` actors with an **active membership in the resource company** the same read surface as a same-company agent (`agent:read`, `company_scope:read`, `issue:read`, `project:read`) plus `issue:mutate` for non-viewer members — cross-company access stays denied (new `allow_company_member` reason). - `resolveCloudTenantActor` seeds the standard role-default permission grants (`ensureHumanRoleDefaultGrants`) so granted actions (e.g. `tasks:assign`, `agents:create` for owners) work without elevation. - Master-side route tests that stubbed cloud tenant actors with `isInstanceAdmin: true` now seed a real membership and assert under the hardened contract (`issue-identifier-routes`, `multilingual-issues-routes`, `issue-comment-redaction`). - Tests - `server/src/middleware/cloud-tenant-actor.test.ts` (new): cloud tenant is never instance-admin, is scoped to exactly the one company from its stack, still upserts user/company/membership, purges stale `instance_admin` rows, returns null without the server token, and maps non-owner stack roles without elevating. - `server/src/__tests__/auth-session-route.test.ts`: end-to-end middleware regression — a user with a stale `instance_admin` row stops being elevated via the session path once they authenticate through the cloud-tenant path (with a control assertion showing the pre-purge elevation). - `server/src/__tests__/authorization-service.test.ts` (embedded Postgres): a `cloud_tenant` actor with a stale `instance_admin` row in the real DB cannot cross company boundaries, while a `session` actor with the same row still resolves `allow_instance_admin`. ## Verification Run from the repo root after `pnpm install --frozen-lockfile`: ```bash cd server npx vitest run src/middleware/cloud-tenant-actor.test.ts src/__tests__/auth-session-route.test.ts # 9 tests passed npx vitest run src/__tests__/authorization-service.test.ts # 16 tests passed (embedded Postgres) pnpm typecheck # clean ``` Also ran the broader auth-related suites locally (`auth-routes`, `authz-company-access`, `better-auth`, `adapter-routes-authz`, `express5-auth-wildcard`): 8 files, 58 tests, all passing. ## Risks - **This touches authentication and authorization paths directly.** Mistakes here are security bugs in both directions; review accordingly. - **Behavioral change for existing `cloud_tenant` deployments:** tenants that previously (incorrectly) had instance-admin lose it — including the ability to see/manage other companies on the instance. This is the intended hardening, but any single-tenant deployment that relied on the cloud-tenant identity for instance administration must provision a separate admin identity. - **The purge is destructive by design:** if an operator's instance-admin identity is *also* provisioned through the cloud-tenant headers (same user id), its `instance_admin` row will be deleted on the next trusted-header request. Operators should hold admin through a non-cloud-tenant identity. - **Residual gap (documented, not fixed here):** a deployment that ran the old cloud_tenant build and then *disabled* cloud-tenant mode keeps stale rows until the affected user re-authenticates through the cloud path. A data migration was considered and deliberately avoided: there is no reliable SQL predicate for "cloud-tenant-provisioned user" (no source column), so a migration risks deleting legitimate admins. - No schema or migration changes; no UI changes. ## Model Used - Claude Fable 5 (claude-fable-5, 1M context), extended thinking + tool use, via Claude Code — this revision; original PR authored in an earlier Claude Code session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above (none duplicate this; related issues Refs #966 / #5015 are linked in the issue section) - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] If this change affects the UI, I have included before/after screenshots (no UI changes) - [x] I have updated relevant documentation to reflect my changes (no existing docs reference `cloud_tenant` mode) - [x] I have considered and documented any risks above - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
916 lines
33 KiB
TypeScript
916 lines
33 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
|
import {
|
|
agents,
|
|
companies,
|
|
companyMemberships,
|
|
createDb,
|
|
instanceUserRoles,
|
|
issues,
|
|
principalPermissionGrants,
|
|
projects,
|
|
} from "@paperclipai/db";
|
|
import { LOW_TRUST_REVIEW_PRESET } from "@paperclipai/shared";
|
|
import {
|
|
getEmbeddedPostgresTestSupport,
|
|
startEmbeddedPostgresTestDatabase,
|
|
} from "./helpers/embedded-postgres.js";
|
|
import { authorizationService } from "../services/authorization.js";
|
|
|
|
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
|
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
|
|
|
async function createCompany(db: ReturnType<typeof createDb>, label: string) {
|
|
return db
|
|
.insert(companies)
|
|
.values({
|
|
name: `Authorization ${label} ${randomUUID()}`,
|
|
issuePrefix: `AZ${randomUUID().slice(0, 6).toUpperCase()}`,
|
|
})
|
|
.returning()
|
|
.then((rows) => rows[0]!);
|
|
}
|
|
|
|
async function createAgent(
|
|
db: ReturnType<typeof createDb>,
|
|
companyId: string,
|
|
input: { role?: string; reportsTo?: string | null; permissions?: Record<string, unknown> } = {},
|
|
) {
|
|
return db
|
|
.insert(agents)
|
|
.values({
|
|
companyId,
|
|
name: `Agent ${randomUUID()}`,
|
|
role: input.role ?? "engineer",
|
|
reportsTo: input.reportsTo ?? null,
|
|
permissions: input.permissions ?? {},
|
|
adapterType: "process",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
})
|
|
.returning()
|
|
.then((rows) => rows[0]!);
|
|
}
|
|
|
|
async function createProject(db: ReturnType<typeof createDb>, companyId: string, label: string) {
|
|
return db
|
|
.insert(projects)
|
|
.values({
|
|
companyId,
|
|
name: `Project ${label} ${randomUUID()}`,
|
|
})
|
|
.returning()
|
|
.then((rows) => rows[0]!);
|
|
}
|
|
|
|
async function createIssue(
|
|
db: ReturnType<typeof createDb>,
|
|
companyId: string,
|
|
input: {
|
|
id?: string;
|
|
title?: string;
|
|
projectId?: string | null;
|
|
parentId?: string | null;
|
|
assigneeAgentId?: string | null;
|
|
} = {},
|
|
) {
|
|
return db
|
|
.insert(issues)
|
|
.values({
|
|
id: input.id ?? randomUUID(),
|
|
companyId,
|
|
title: input.title ?? `Issue ${randomUUID()}`,
|
|
status: "todo",
|
|
priority: "medium",
|
|
projectId: input.projectId ?? null,
|
|
parentId: input.parentId ?? null,
|
|
assigneeAgentId: input.assigneeAgentId ?? null,
|
|
})
|
|
.returning()
|
|
.then((rows) => rows[0]!);
|
|
}
|
|
|
|
async function grantAgentPermission(
|
|
db: ReturnType<typeof createDb>,
|
|
companyId: string,
|
|
agentId: string,
|
|
permissionKey: "tasks:assign" | "tasks:assign_scope",
|
|
scope: Record<string, unknown> | null = null,
|
|
) {
|
|
await db.insert(companyMemberships).values({
|
|
companyId,
|
|
principalType: "agent",
|
|
principalId: agentId,
|
|
status: "active",
|
|
membershipRole: "member",
|
|
});
|
|
await db.insert(principalPermissionGrants).values({
|
|
companyId,
|
|
principalType: "agent",
|
|
principalId: agentId,
|
|
permissionKey,
|
|
scope,
|
|
grantedByUserId: null,
|
|
});
|
|
}
|
|
|
|
describeEmbeddedPostgres("authorization service", () => {
|
|
let db!: ReturnType<typeof createDb>;
|
|
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
|
|
|
beforeAll(async () => {
|
|
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-authorization-service-");
|
|
db = createDb(tempDb.connectionString);
|
|
}, 20_000);
|
|
|
|
afterEach(async () => {
|
|
await db.delete(principalPermissionGrants);
|
|
await db.delete(companyMemberships);
|
|
await db.delete(instanceUserRoles);
|
|
await db.delete(issues);
|
|
await db.delete(agents);
|
|
await db.delete(projects);
|
|
await db.delete(companies);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await tempDb?.cleanup();
|
|
});
|
|
|
|
it("allows active user role grants and explains the grant source", async () => {
|
|
const company = await createCompany(db, "UserGrant");
|
|
const userId = `user-${randomUUID()}`;
|
|
await db.insert(companyMemberships).values({
|
|
companyId: company.id,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
status: "active",
|
|
membershipRole: "operator",
|
|
});
|
|
await db.insert(principalPermissionGrants).values({
|
|
companyId: company.id,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
permissionKey: "tasks:assign",
|
|
grantedByUserId: "owner",
|
|
});
|
|
|
|
const decision = await authorizationService(db).decidePrincipalGrant({
|
|
companyId: company.id,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
action: "tasks:assign",
|
|
permissionKey: "tasks:assign",
|
|
});
|
|
|
|
expect(decision).toMatchObject({
|
|
allowed: true,
|
|
reason: "allow_explicit_grant",
|
|
grant: {
|
|
principalType: "user",
|
|
principalId: userId,
|
|
permissionKey: "tasks:assign",
|
|
},
|
|
});
|
|
expect(decision.explanation).toContain("Allowed by explicit grant tasks:assign");
|
|
});
|
|
|
|
it("allows agent grants for agent configuration decisions", async () => {
|
|
const company = await createCompany(db, "AgentGrant");
|
|
const actorAgent = await createAgent(db, company.id);
|
|
const targetAgent = await createAgent(db, company.id);
|
|
await db.insert(companyMemberships).values({
|
|
companyId: company.id,
|
|
principalType: "agent",
|
|
principalId: actorAgent.id,
|
|
status: "active",
|
|
membershipRole: "member",
|
|
});
|
|
await db.insert(principalPermissionGrants).values({
|
|
companyId: company.id,
|
|
principalType: "agent",
|
|
principalId: actorAgent.id,
|
|
permissionKey: "agents:create",
|
|
grantedByUserId: null,
|
|
});
|
|
|
|
const decision = await authorizationService(db).decide({
|
|
actor: { type: "agent", agentId: actorAgent.id, companyId: company.id, source: "agent_key" },
|
|
action: "agent_config:read",
|
|
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
|
|
});
|
|
|
|
expect(decision.allowed).toBe(true);
|
|
expect(decision.grant?.permissionKey).toBe("agents:create");
|
|
});
|
|
|
|
it("denies cross-company agent decisions before grant evaluation", async () => {
|
|
const sourceCompany = await createCompany(db, "Source");
|
|
const targetCompany = await createCompany(db, "Target");
|
|
const actorAgent = await createAgent(db, sourceCompany.id);
|
|
|
|
const decision = await authorizationService(db).decide({
|
|
actor: { type: "agent", agentId: actorAgent.id, companyId: sourceCompany.id, source: "agent_jwt" },
|
|
action: "tasks:assign",
|
|
resource: { type: "company", companyId: targetCompany.id },
|
|
});
|
|
|
|
expect(decision).toMatchObject({
|
|
allowed: false,
|
|
reason: "deny_company_boundary",
|
|
});
|
|
expect(decision.explanation).toContain("Agent key cannot access another company");
|
|
});
|
|
|
|
it("allows simple-mode task assignment between same-company agents without explicit grants", async () => {
|
|
const company = await createCompany(db, "AssignmentDefault");
|
|
const actorAgent = await createAgent(db, company.id, { role: "engineer" });
|
|
const targetAgent = await createAgent(db, company.id, { role: "engineer" });
|
|
await db.insert(companyMemberships).values({
|
|
companyId: company.id,
|
|
principalType: "agent",
|
|
principalId: actorAgent.id,
|
|
status: "active",
|
|
membershipRole: "member",
|
|
});
|
|
|
|
const decision = await authorizationService(db).decide({
|
|
actor: { type: "agent", agentId: actorAgent.id, companyId: company.id, source: "agent_key" },
|
|
action: "tasks:assign",
|
|
resource: { type: "issue", companyId: company.id, assigneeAgentId: targetAgent.id },
|
|
scope: { assigneeAgentId: targetAgent.id },
|
|
});
|
|
|
|
expect(decision).toMatchObject({
|
|
allowed: true,
|
|
reason: "allow_simple_company_member",
|
|
});
|
|
expect(decision.explanation).toContain("simple mode");
|
|
});
|
|
|
|
it("limits low-trust issue reads to the configured project and root issue boundary", async () => {
|
|
const company = await createCompany(db, "LowTrustIssueReads");
|
|
const project = await createProject(db, company.id, "Allowed");
|
|
const otherProject = await createProject(db, company.id, "Denied");
|
|
const rootIssueId = randomUUID();
|
|
const actorAgent = await createAgent(db, company.id, {
|
|
permissions: {
|
|
trustPreset: LOW_TRUST_REVIEW_PRESET,
|
|
authorizationPolicy: {
|
|
trustBoundary: {
|
|
mode: LOW_TRUST_REVIEW_PRESET,
|
|
projectIds: [project.id],
|
|
rootIssueId,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
const rootIssue = await createIssue(db, company.id, {
|
|
id: rootIssueId,
|
|
projectId: project.id,
|
|
assigneeAgentId: actorAgent.id,
|
|
});
|
|
const childIssue = await createIssue(db, company.id, {
|
|
projectId: project.id,
|
|
parentId: rootIssue.id,
|
|
});
|
|
const unrelatedIssue = await createIssue(db, company.id, {
|
|
projectId: otherProject.id,
|
|
});
|
|
|
|
const authorization = authorizationService(db);
|
|
const actor = { type: "agent" as const, agentId: actorAgent.id, companyId: company.id, source: "agent_key" as const };
|
|
const rootDecision = await authorization.decide({
|
|
actor,
|
|
action: "issue:read",
|
|
resource: {
|
|
type: "issue",
|
|
companyId: company.id,
|
|
issueId: rootIssue.id,
|
|
projectId: rootIssue.projectId,
|
|
parentIssueId: rootIssue.parentId,
|
|
assigneeAgentId: rootIssue.assigneeAgentId,
|
|
status: rootIssue.status,
|
|
},
|
|
});
|
|
const childDecision = await authorization.decide({
|
|
actor,
|
|
action: "issue:read",
|
|
resource: {
|
|
type: "issue",
|
|
companyId: company.id,
|
|
issueId: childIssue.id,
|
|
projectId: childIssue.projectId,
|
|
parentIssueId: childIssue.parentId,
|
|
status: childIssue.status,
|
|
},
|
|
});
|
|
const unrelatedDecision = await authorization.decide({
|
|
actor,
|
|
action: "issue:read",
|
|
resource: {
|
|
type: "issue",
|
|
companyId: company.id,
|
|
issueId: unrelatedIssue.id,
|
|
projectId: unrelatedIssue.projectId,
|
|
parentIssueId: unrelatedIssue.parentId,
|
|
status: unrelatedIssue.status,
|
|
},
|
|
});
|
|
|
|
expect(rootDecision).toMatchObject({ allowed: true, reason: "allow_low_trust_boundary" });
|
|
expect(childDecision).toMatchObject({ allowed: true, reason: "allow_low_trust_boundary" });
|
|
expect(unrelatedDecision).toMatchObject({ allowed: false, reason: "deny_low_trust_boundary" });
|
|
});
|
|
|
|
it("blocks low-trust project, agent, company-wide, and outside-boundary assignment access", async () => {
|
|
const company = await createCompany(db, "LowTrustOtherResources");
|
|
const project = await createProject(db, company.id, "Allowed");
|
|
const otherProject = await createProject(db, company.id, "Denied");
|
|
const collaborator = await createAgent(db, company.id);
|
|
const higherTrustAgent = await createAgent(db, company.id, { role: "cto" });
|
|
const actorAgent = await createAgent(db, company.id, {
|
|
permissions: {
|
|
trustPreset: LOW_TRUST_REVIEW_PRESET,
|
|
authorizationPolicy: {
|
|
trustBoundary: {
|
|
mode: LOW_TRUST_REVIEW_PRESET,
|
|
projectIds: [project.id],
|
|
allowedAgentIds: [collaborator.id],
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
const authorization = authorizationService(db);
|
|
const actor = { type: "agent" as const, agentId: actorAgent.id, companyId: company.id, source: "agent_key" as const };
|
|
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "project:read",
|
|
resource: { type: "project", companyId: company.id, projectId: project.id },
|
|
})).resolves.toMatchObject({ allowed: true, reason: "allow_low_trust_boundary" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "project:read",
|
|
resource: { type: "project", companyId: company.id, projectId: otherProject.id },
|
|
})).resolves.toMatchObject({ allowed: false, reason: "deny_low_trust_boundary" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "agent:read",
|
|
resource: { type: "agent", companyId: company.id, agentId: collaborator.id },
|
|
})).resolves.toMatchObject({ allowed: true, reason: "allow_low_trust_boundary" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "agent:read",
|
|
resource: { type: "agent", companyId: company.id, agentId: higherTrustAgent.id },
|
|
})).resolves.toMatchObject({ allowed: false, reason: "deny_low_trust_boundary" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "company_scope:read",
|
|
resource: { type: "company", companyId: company.id },
|
|
})).resolves.toMatchObject({ allowed: false, reason: "deny_low_trust_boundary" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "tasks:assign",
|
|
resource: {
|
|
type: "issue",
|
|
companyId: company.id,
|
|
projectId: project.id,
|
|
assigneeAgentId: higherTrustAgent.id,
|
|
},
|
|
scope: { projectId: project.id, assigneeAgentId: higherTrustAgent.id },
|
|
})).resolves.toMatchObject({ allowed: false, reason: "deny_low_trust_boundary" });
|
|
});
|
|
|
|
it("denies simple-mode assignment when the target agent requires protected-assignment approval", async () => {
|
|
const company = await createCompany(db, "ProtectedAssignment");
|
|
const actorAgent = await createAgent(db, company.id, { role: "engineer" });
|
|
const targetAgent = await createAgent(db, company.id, {
|
|
role: "engineer",
|
|
permissions: {
|
|
authorizationPolicy: {
|
|
assignmentPolicy: {
|
|
mode: "protected",
|
|
protectedAgentRequiresApproval: true,
|
|
},
|
|
protectedAgent: {
|
|
requiresApproval: true,
|
|
approvalReason: "Production deployment authority",
|
|
},
|
|
managedBy: "permissions-extension",
|
|
},
|
|
},
|
|
});
|
|
|
|
const decision = await authorizationService(db).decide({
|
|
actor: { type: "agent", agentId: actorAgent.id, companyId: company.id, source: "agent_key" },
|
|
action: "tasks:assign",
|
|
resource: { type: "issue", companyId: company.id, assigneeAgentId: targetAgent.id },
|
|
scope: { assigneeAgentId: targetAgent.id },
|
|
});
|
|
|
|
expect(decision).toMatchObject({
|
|
allowed: false,
|
|
reason: "deny_policy_restricted",
|
|
});
|
|
expect(decision.explanation).toContain("requires approval");
|
|
});
|
|
|
|
it("requires an explicit grant before assigning to a private target agent", async () => {
|
|
const company = await createCompany(db, "PrivateAssignment");
|
|
const actorAgent = await createAgent(db, company.id, { role: "engineer" });
|
|
const targetAgent = await createAgent(db, company.id, {
|
|
role: "engineer",
|
|
permissions: {
|
|
authorizationPolicy: {
|
|
agentVisibility: {
|
|
mode: "private",
|
|
hiddenFromDefaultDirectory: true,
|
|
},
|
|
assignmentPolicy: {
|
|
mode: "company_default",
|
|
protectedAgentRequiresApproval: false,
|
|
},
|
|
protectedAgent: {
|
|
requiresApproval: false,
|
|
},
|
|
managedBy: "permissions-extension",
|
|
},
|
|
},
|
|
});
|
|
|
|
const denied = await authorizationService(db).decide({
|
|
actor: { type: "agent", agentId: actorAgent.id, companyId: company.id, source: "agent_key" },
|
|
action: "tasks:assign",
|
|
resource: { type: "issue", companyId: company.id, assigneeAgentId: targetAgent.id },
|
|
scope: { assigneeAgentId: targetAgent.id },
|
|
});
|
|
|
|
await grantAgentPermission(db, company.id, actorAgent.id, "tasks:assign_scope", {
|
|
assigneeAgentId: targetAgent.id,
|
|
});
|
|
|
|
const allowed = await authorizationService(db).decide({
|
|
actor: { type: "agent", agentId: actorAgent.id, companyId: company.id, source: "agent_key" },
|
|
action: "tasks:assign",
|
|
resource: { type: "issue", companyId: company.id, assigneeAgentId: targetAgent.id },
|
|
scope: { assigneeAgentId: targetAgent.id },
|
|
});
|
|
|
|
expect(denied).toMatchObject({
|
|
allowed: false,
|
|
reason: "deny_policy_restricted",
|
|
});
|
|
expect(denied.explanation).toContain("private");
|
|
expect(allowed).toMatchObject({
|
|
allowed: true,
|
|
reason: "allow_explicit_grant",
|
|
grant: { permissionKey: "tasks:assign_scope" },
|
|
});
|
|
});
|
|
|
|
it("allows simple-mode task assignment for active same-company board operators without explicit grants", async () => {
|
|
const company = await createCompany(db, "BoardAssignmentDefault");
|
|
const userId = `user-${randomUUID()}`;
|
|
const targetAgent = await createAgent(db, company.id, { role: "engineer" });
|
|
await db.insert(companyMemberships).values({
|
|
companyId: company.id,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
status: "active",
|
|
membershipRole: "operator",
|
|
});
|
|
|
|
const decision = await authorizationService(db).decide({
|
|
actor: { type: "board", userId, source: "session" },
|
|
action: "tasks:assign",
|
|
resource: { type: "issue", companyId: company.id, assigneeAgentId: targetAgent.id },
|
|
scope: { assigneeAgentId: targetAgent.id },
|
|
});
|
|
|
|
expect(decision).toMatchObject({
|
|
allowed: true,
|
|
reason: "allow_simple_company_member",
|
|
});
|
|
});
|
|
|
|
it("allows null-mapped visibility actions for active same-company board members", async () => {
|
|
const company = await createCompany(db, "BoardVisibility");
|
|
const userId = `user-${randomUUID()}`;
|
|
const project = await createProject(db, company.id, "Visible");
|
|
const targetAgent = await createAgent(db, company.id, { role: "engineer" });
|
|
const issue = await createIssue(db, company.id, { projectId: project.id });
|
|
await db.insert(companyMemberships).values({
|
|
companyId: company.id,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
status: "active",
|
|
membershipRole: "member",
|
|
});
|
|
|
|
const authorization = authorizationService(db);
|
|
const actor = { type: "board" as const, userId, source: "session" as const };
|
|
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "agent:read",
|
|
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
|
|
})).resolves.toMatchObject({ allowed: true, reason: "allow_simple_company_member" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "company_scope:read",
|
|
resource: { type: "company", companyId: company.id },
|
|
})).resolves.toMatchObject({ allowed: true, reason: "allow_simple_company_member" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "project:read",
|
|
resource: { type: "project", companyId: company.id, projectId: project.id },
|
|
})).resolves.toMatchObject({ allowed: true, reason: "allow_simple_company_member" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "issue:read",
|
|
resource: {
|
|
type: "issue",
|
|
companyId: company.id,
|
|
issueId: issue.id,
|
|
projectId: issue.projectId,
|
|
parentIssueId: issue.parentId,
|
|
status: issue.status,
|
|
},
|
|
})).resolves.toMatchObject({ allowed: true, reason: "allow_simple_company_member" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "runtime:manage",
|
|
resource: { type: "company", companyId: company.id },
|
|
})).resolves.toMatchObject({ allowed: true, reason: "allow_simple_company_member" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "secrets:read",
|
|
resource: { type: "company", companyId: company.id },
|
|
})).resolves.toMatchObject({ allowed: true, reason: "allow_simple_company_member" });
|
|
});
|
|
|
|
it("denies null-mapped visibility actions for board users without an active membership", async () => {
|
|
const memberCompany = await createCompany(db, "BoardVisibilityMember");
|
|
const otherCompany = await createCompany(db, "BoardVisibilityOther");
|
|
const userId = `user-${randomUUID()}`;
|
|
const targetAgent = await createAgent(db, otherCompany.id, { role: "engineer" });
|
|
const inactiveUserId = `user-${randomUUID()}`;
|
|
await db.insert(companyMemberships).values({
|
|
companyId: memberCompany.id,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
status: "active",
|
|
membershipRole: "member",
|
|
});
|
|
await db.insert(companyMemberships).values({
|
|
companyId: otherCompany.id,
|
|
principalType: "user",
|
|
principalId: inactiveUserId,
|
|
status: "removed",
|
|
membershipRole: "member",
|
|
});
|
|
|
|
const authorization = authorizationService(db);
|
|
|
|
await expect(authorization.decide({
|
|
actor: { type: "board", userId, source: "session" },
|
|
action: "agent:read",
|
|
resource: { type: "agent", companyId: otherCompany.id, agentId: targetAgent.id },
|
|
})).resolves.toMatchObject({ allowed: false, reason: "deny_missing_membership" });
|
|
await expect(authorization.decide({
|
|
actor: { type: "board", userId: inactiveUserId, source: "session" },
|
|
action: "company_scope:read",
|
|
resource: { type: "company", companyId: otherCompany.id },
|
|
})).resolves.toMatchObject({ allowed: false, reason: "deny_missing_membership" });
|
|
});
|
|
|
|
it("keeps denying self-gated null-mapped actions for board members", async () => {
|
|
const company = await createCompany(db, "BoardWakeDenied");
|
|
const userId = `user-${randomUUID()}`;
|
|
const targetAgent = await createAgent(db, company.id, { role: "engineer" });
|
|
await db.insert(companyMemberships).values({
|
|
companyId: company.id,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
status: "active",
|
|
membershipRole: "member",
|
|
});
|
|
|
|
const authorization = authorizationService(db);
|
|
|
|
await expect(authorization.decide({
|
|
actor: { type: "board", userId, source: "session" },
|
|
action: "agent:wake",
|
|
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
|
|
})).resolves.toMatchObject({
|
|
allowed: false,
|
|
reason: "deny_unsupported_action",
|
|
});
|
|
const issue = await createIssue(db, company.id, { title: "Wake denied issue" });
|
|
await expect(authorization.decide({
|
|
actor: { type: "board", userId, source: "session" },
|
|
action: "issue:mutate",
|
|
resource: { type: "issue", companyId: company.id, issueId: issue.id },
|
|
})).resolves.toMatchObject({
|
|
allowed: false,
|
|
reason: "deny_unsupported_action",
|
|
});
|
|
});
|
|
|
|
it("limits viewer members to read-only visibility actions", async () => {
|
|
const company = await createCompany(db, "BoardViewerVisibility");
|
|
const userId = `user-${randomUUID()}`;
|
|
const targetAgent = await createAgent(db, company.id, { role: "engineer" });
|
|
await db.insert(companyMemberships).values({
|
|
companyId: company.id,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
status: "active",
|
|
membershipRole: "viewer",
|
|
});
|
|
|
|
const authorization = authorizationService(db);
|
|
const actor = { type: "board", userId, source: "session" } as const;
|
|
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "agent:read",
|
|
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
|
|
})).resolves.toMatchObject({ allowed: true, reason: "allow_simple_company_member" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "company_scope:read",
|
|
resource: { type: "company", companyId: company.id },
|
|
})).resolves.toMatchObject({ allowed: true, reason: "allow_simple_company_member" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "runtime:manage",
|
|
resource: { type: "company", companyId: company.id },
|
|
})).resolves.toMatchObject({ allowed: false, reason: "deny_missing_grant" });
|
|
await expect(authorization.decide({
|
|
actor,
|
|
action: "secrets:read",
|
|
resource: { type: "company", companyId: company.id },
|
|
})).resolves.toMatchObject({ allowed: false, reason: "deny_missing_grant" });
|
|
});
|
|
|
|
it("denies legacy board assignment context for viewers", async () => {
|
|
const company = await createCompany(db, "BoardViewerAssignment");
|
|
const userId = `user-${randomUUID()}`;
|
|
const targetAgent = await createAgent(db, company.id, { role: "engineer" });
|
|
await db.insert(companyMemberships).values({
|
|
companyId: company.id,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
status: "active",
|
|
membershipRole: "viewer",
|
|
});
|
|
|
|
const decision = await authorizationService(db).decide({
|
|
actor: { type: "board", userId, companyIds: [company.id], source: "session" },
|
|
action: "tasks:assign",
|
|
resource: { type: "issue", companyId: company.id, assigneeAgentId: targetAgent.id },
|
|
scope: { assigneeAgentId: targetAgent.id },
|
|
});
|
|
|
|
expect(decision).toMatchObject({
|
|
allowed: false,
|
|
reason: "deny_missing_grant",
|
|
});
|
|
});
|
|
|
|
it("never elevates cloud_tenant actors through stale instance_admin rows", async () => {
|
|
const tenantCompany = await createCompany(db, "CloudTenantStale");
|
|
const otherCompany = await createCompany(db, "CloudTenantOther");
|
|
const userId = `user-${randomUUID()}`;
|
|
const targetAgent = await createAgent(db, otherCompany.id, { role: "engineer" });
|
|
await db.insert(companyMemberships).values({
|
|
companyId: tenantCompany.id,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
status: "active",
|
|
membershipRole: "owner",
|
|
});
|
|
// Stale grant left behind by a pre-hardening cloud_tenant deployment.
|
|
await db.insert(instanceUserRoles).values({ userId, role: "instance_admin" });
|
|
|
|
const decision = await authorizationService(db).decide({
|
|
actor: {
|
|
type: "board",
|
|
userId,
|
|
companyIds: [tenantCompany.id],
|
|
isInstanceAdmin: false,
|
|
source: "cloud_tenant",
|
|
},
|
|
action: "tasks:assign",
|
|
resource: { type: "issue", companyId: otherCompany.id, assigneeAgentId: targetAgent.id },
|
|
scope: { assigneeAgentId: targetAgent.id },
|
|
});
|
|
|
|
expect(decision.allowed).toBe(false);
|
|
expect(decision.reason).not.toBe("allow_instance_admin");
|
|
|
|
// Control: the instanceUserRoles lookup still elevates non-cloud_tenant
|
|
// board actors, so the carve-out is scoped to the tenant contract only.
|
|
const sessionDecision = await authorizationService(db).decide({
|
|
actor: { type: "board", userId, companyIds: [tenantCompany.id], source: "session" },
|
|
action: "tasks:assign",
|
|
resource: { type: "issue", companyId: otherCompany.id, assigneeAgentId: targetAgent.id },
|
|
scope: { assigneeAgentId: targetAgent.id },
|
|
});
|
|
expect(sessionDecision).toMatchObject({ allowed: true, reason: "allow_instance_admin" });
|
|
});
|
|
|
|
it("denies simple-mode assignment to a target agent from another company", async () => {
|
|
const sourceCompany = await createCompany(db, "AssignmentSource");
|
|
const targetCompany = await createCompany(db, "AssignmentTarget");
|
|
const actorAgent = await createAgent(db, sourceCompany.id, { role: "engineer" });
|
|
const targetAgent = await createAgent(db, targetCompany.id, { role: "engineer" });
|
|
await db.insert(companyMemberships).values({
|
|
companyId: sourceCompany.id,
|
|
principalType: "agent",
|
|
principalId: actorAgent.id,
|
|
status: "active",
|
|
membershipRole: "member",
|
|
});
|
|
|
|
const decision = await authorizationService(db).decide({
|
|
actor: { type: "agent", agentId: actorAgent.id, companyId: sourceCompany.id, source: "agent_key" },
|
|
action: "tasks:assign",
|
|
resource: { type: "issue", companyId: sourceCompany.id, assigneeAgentId: targetAgent.id },
|
|
scope: { assigneeAgentId: targetAgent.id },
|
|
});
|
|
|
|
expect(decision).toMatchObject({
|
|
allowed: false,
|
|
reason: "deny_company_boundary",
|
|
});
|
|
});
|
|
|
|
it("preserves legacy CEO agent creator authority", async () => {
|
|
const company = await createCompany(db, "Legacy");
|
|
const actorAgent = await createAgent(db, company.id, { role: "ceo" });
|
|
|
|
const decision = await authorizationService(db).decide({
|
|
actor: { type: "agent", agentId: actorAgent.id, companyId: company.id, source: "agent_jwt" },
|
|
action: "agents:create",
|
|
resource: { type: "company", companyId: company.id },
|
|
});
|
|
|
|
expect(decision).toMatchObject({
|
|
allowed: true,
|
|
reason: "allow_legacy_agent_creator",
|
|
});
|
|
});
|
|
|
|
it("allows scoped assignment inside a granted project and denies other projects", async () => {
|
|
const company = await createCompany(db, "ProjectScope");
|
|
const project = await createProject(db, company.id, "Allowed");
|
|
const otherProject = await createProject(db, company.id, "Denied");
|
|
const actorAgent = await createAgent(db, company.id);
|
|
const targetAgent = await createAgent(db, company.id);
|
|
await grantAgentPermission(db, company.id, actorAgent.id, "tasks:assign_scope", {
|
|
projectIds: [project.id],
|
|
});
|
|
|
|
const allowed = await authorizationService(db).decidePrincipalGrant({
|
|
companyId: company.id,
|
|
principalType: "agent",
|
|
principalId: actorAgent.id,
|
|
action: "tasks:assign",
|
|
permissionKey: "tasks:assign_scope",
|
|
scope: { projectId: project.id, assigneeAgentId: targetAgent.id },
|
|
});
|
|
const denied = await authorizationService(db).decidePrincipalGrant({
|
|
companyId: company.id,
|
|
principalType: "agent",
|
|
principalId: actorAgent.id,
|
|
action: "tasks:assign",
|
|
permissionKey: "tasks:assign_scope",
|
|
scope: { projectId: otherProject.id, assigneeAgentId: targetAgent.id },
|
|
});
|
|
|
|
expect(allowed).toMatchObject({
|
|
allowed: true,
|
|
grant: { permissionKey: "tasks:assign_scope" },
|
|
});
|
|
expect(denied).toMatchObject({
|
|
allowed: false,
|
|
reason: "deny_scope",
|
|
});
|
|
expect(denied.explanation).toContain("does not cover the requested scope");
|
|
});
|
|
|
|
it("treats unknown grant scope metadata as unconstrained", async () => {
|
|
const company = await createCompany(db, "UnknownScopeMetadata");
|
|
const actorAgent = await createAgent(db, company.id);
|
|
const targetAgent = await createAgent(db, company.id);
|
|
await grantAgentPermission(db, company.id, actorAgent.id, "tasks:assign_scope", {
|
|
note: "CEO-approved",
|
|
});
|
|
|
|
const decision = await authorizationService(db).decidePrincipalGrant({
|
|
companyId: company.id,
|
|
principalType: "agent",
|
|
principalId: actorAgent.id,
|
|
action: "tasks:assign",
|
|
permissionKey: "tasks:assign_scope",
|
|
scope: { assigneeAgentId: targetAgent.id },
|
|
});
|
|
|
|
expect(decision).toMatchObject({
|
|
allowed: true,
|
|
grant: { permissionKey: "tasks:assign_scope" },
|
|
});
|
|
});
|
|
|
|
it("allows scoped assignment to agents inside a managed subtree only", async () => {
|
|
const company = await createCompany(db, "SubtreeScope");
|
|
const actorAgent = await createAgent(db, company.id);
|
|
const managerAgent = await createAgent(db, company.id);
|
|
const childAgent = await createAgent(db, company.id, { reportsTo: managerAgent.id });
|
|
const grandchildAgent = await createAgent(db, company.id, { reportsTo: childAgent.id });
|
|
const outsideAgent = await createAgent(db, company.id);
|
|
await grantAgentPermission(db, company.id, actorAgent.id, "tasks:assign_scope", {
|
|
managedSubtreeAgentIds: [managerAgent.id],
|
|
});
|
|
|
|
const allowed = await authorizationService(db).decidePrincipalGrant({
|
|
companyId: company.id,
|
|
principalType: "agent",
|
|
principalId: actorAgent.id,
|
|
action: "tasks:assign",
|
|
permissionKey: "tasks:assign_scope",
|
|
scope: { assigneeAgentId: grandchildAgent.id },
|
|
});
|
|
const denied = await authorizationService(db).decidePrincipalGrant({
|
|
companyId: company.id,
|
|
principalType: "agent",
|
|
principalId: actorAgent.id,
|
|
action: "tasks:assign",
|
|
permissionKey: "tasks:assign_scope",
|
|
scope: { assigneeAgentId: outsideAgent.id },
|
|
});
|
|
|
|
expect(allowed.allowed).toBe(true);
|
|
expect(allowed.grant?.permissionKey).toBe("tasks:assign_scope");
|
|
expect(denied).toMatchObject({
|
|
allowed: false,
|
|
reason: "deny_scope",
|
|
});
|
|
});
|
|
|
|
it("allows scoped assignment to an explicit target-agent allowlist only", async () => {
|
|
const company = await createCompany(db, "AllowlistScope");
|
|
const actorAgent = await createAgent(db, company.id);
|
|
const allowedTarget = await createAgent(db, company.id);
|
|
const deniedTarget = await createAgent(db, company.id);
|
|
await grantAgentPermission(db, company.id, actorAgent.id, "tasks:assign_scope", {
|
|
assigneeAgentIds: [allowedTarget.id],
|
|
});
|
|
|
|
const allowed = await authorizationService(db).decidePrincipalGrant({
|
|
companyId: company.id,
|
|
principalType: "agent",
|
|
principalId: actorAgent.id,
|
|
action: "tasks:assign",
|
|
permissionKey: "tasks:assign_scope",
|
|
scope: { assigneeAgentId: allowedTarget.id },
|
|
});
|
|
const denied = await authorizationService(db).decidePrincipalGrant({
|
|
companyId: company.id,
|
|
principalType: "agent",
|
|
principalId: actorAgent.id,
|
|
action: "tasks:assign",
|
|
permissionKey: "tasks:assign_scope",
|
|
scope: { assigneeAgentId: deniedTarget.id },
|
|
});
|
|
|
|
expect(allowed.allowed).toBe(true);
|
|
expect(denied.allowed).toBe(false);
|
|
});
|
|
|
|
it("preserves unscoped tasks:assign compatibility for assignment decisions", async () => {
|
|
const company = await createCompany(db, "BroadAssign");
|
|
const actorAgent = await createAgent(db, company.id);
|
|
const targetAgent = await createAgent(db, company.id);
|
|
await grantAgentPermission(db, company.id, actorAgent.id, "tasks:assign");
|
|
|
|
const decision = await authorizationService(db).decidePrincipalGrant({
|
|
companyId: company.id,
|
|
principalType: "agent",
|
|
principalId: actorAgent.id,
|
|
action: "tasks:assign",
|
|
permissionKey: "tasks:assign",
|
|
scope: { assigneeAgentId: targetAgent.id },
|
|
});
|
|
|
|
expect(decision).toMatchObject({
|
|
allowed: true,
|
|
grant: { permissionKey: "tasks:assign" },
|
|
});
|
|
});
|
|
});
|