Files
PaperClipAI/server/src/__tests__/headless-identity-auth.test.ts
T
DottaandPaperclip ea56320e10 feat(board): add headless channels, fenced task queues, paperclipai/sdk, and pc CLI (#23330)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Multi-agent workflows and terminal scripts often need lightweight
shared channels, structured task queues, and scriptable CLI/SDK
primitives without building a full project UI first.
> - Today, Paperclip issues require board-oriented setup, lack lazy
hierarchical channels, lack fenced task claim leases, and lack a
zero-dependency TypeScript SDK and short CLI alias for fast script
coordination.
> - Without fenced leases, blocking queue claims, CAS key-value labels,
and race-free event streaming, multiple headless workers collide on
shared work or fall back to wasteful polling loops.
> - This pull request adds headless channels, versioned JSON schemas,
topological `plan.json` batch creation, fenced task queues with `FOR
UPDATE SKIP LOCKED` claims, CAS key-value labels, one-line ask/confirm
interactions, SSE event streaming, `paperclipai/sdk`, and the `pc` CLI
with `paperclipai up`.
> - The benefit is zero-ceremony, machine-readable, race-safe
coordination across terminal agents, CI scripts, and local Paperclip
servers while staying compatible with existing Web UI issue threads.

## Linked Issues or Issue Description

**Subsystem affected**

Cross-cutting (`packages/db`, `packages/shared`, `server/`, `cli/`,
`doc/`, `skills/`)

**Problem or motivation**

Agents and terminal workflows need a fast way to post updates, queue DAG
tasks, claim work without double-execution, ask humans for approval, and
wait on board events without browser setup or polling loops. Existing
Paperclip routes assume UI-driven projects, lack fenced claim leases for
pools of workers, and lack a minimal `pc` CLI and `paperclipai/sdk`
client.

**Proposed solution**

Build a headless coordination layer directly on top of Paperclip
`issues` and `issue_comments` using `issues.scope = 'channel'`:

- **Database & Contracts (`packages/db`, `packages/shared`)**: Add
`0511_pale_kronos.sql` (`issues.scope`) and `0512_stormy_the_hood.sql`
for lazy hierarchical `channels`, `channel_access_members`, immutable
`company_schemas`, monotonic `board_events`, `scheduled_board_posts`,
`issue_batch_idempotency_keys`, scoped `board_api_keys`,
`agent_identity_policy`, `kv_labels`, `schema_blocks`, and fenced claim
leases. Export Zod contracts, DAG sorting, KV CAS helpers, and the
zero-dependency `paperclip()` SDK (`packages/shared/src/sdk/`),
including an in-memory test backend.
- **Server APIs & Workers (`server/`)**: Add routes and services for
progressive `--as` actor resolution (`open_local_profiles`,
`delegated_profiles`, `strict_agent_keys`), `pc agent connect` auth
challenges, lazy channels, CAS `kv-labels`, versioned schemas,
topological batch creation, `FOR UPDATE SKIP LOCKED` pool claims with
fenced TTL renewal/release/complete/fail, one-line
`ask`/`confirm`/`approve`/`reject` interactions, SSE cursor streaming
(`events/wait`, `events/stream`), and sleep-aware lease expiry and
scheduled post workers.
- **CLI, Launcher & Docs (`cli/`, `doc/`, `skills/`)**: Expose the `pc`
binary alias and `paperclipai/sdk` export, add the zero-prompt
`paperclipai up` / `pc up` local launcher, add `pc` commands (`post`,
`reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`,
`approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent
connect/login`), add documentation (`doc/CHANNELS-AND-QUEUES.md`,
`doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`), and add
`skills/paperclip-lite/SKILL.md`.

**Alternatives considered**

- **Separate message and queue tables outside `issues`**: Rejected
because channel posts and queued tasks would lose Paperclip identifiers
(`PC-1`), comments, attachments, privacy ACLs, and direct Web UI issue
URLs (`/<prefix>/issues/PC-1`).
- **Advisory locks or polling loops for task workers**: Rejected because
advisory locks drop on reconnect across laptop sleep, and polling wastes
tokens and prevents database sleep. Fenced `(claimToken, claimEpoch)`
TTL leases with `events/wait` and `waitSec` solve both safely.

**Roadmap alignment**

Extends core Paperclip agent orchestration and CLI workflows with a
headless board, SDK, and queue primitive without altering existing Web
UI board behavior.

**Additional context**

This PR builds on the `issues.scope` surface visibility foundation from
#23329 (included as the base commit in this stacked branch so CI and
reviewers can test the full integration against `master`).

## What Changed

- **Schema & Migrations (`packages/db`)**: Added online-compatible
migrations `0511_pale_kronos.sql` and `0512_stormy_the_hood.sql`, schema
definitions (`channels.ts`, `company_schemas.ts`, `headless_board.ts`),
and column extensions on `issues`, `issue_comments`, `companies`,
`board_api_keys`, and `cli_auth_challenges`.
- **Shared Contracts & SDK (`packages/shared`)**: Added
`packages/shared/src/headless/*` (channels, events, identity, labels,
leases, DAG plans, schemas) and `packages/shared/src/sdk/*`
(`paperclip()` client, env loader, SSE parser, and in-memory backend).
- **Server Routes & Services (`server/`)**: Added
`headless-channels-schemas.ts`, `headless-queues-events.ts`,
`headless-identity.ts` routes and supporting services
(`headless-channels.ts`, `headless-common.ts`,
`headless-events-schedules-interactions.ts`, `headless-identity.ts`,
`headless-labels-batch.ts`, `headless-schemas.ts`,
`headless-task-queue.ts`), plus `issues.scope` visibility isolation and
`board-auth.ts` extensions.
- **CLI & SDK Export (`cli/`, `scripts/`)**: Exposed `pc` bin alias and
`paperclipai/sdk` entrypoint, added `up.ts` zero-prompt launcher and
`cli/src/commands/board/*` commands (`post`, `reply`, `read`,
`channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`,
`schemas`, `schedule`, `tail`, `wait`, `agent`).
- **Docs, Skill & Runner Registry (`doc/`, `skills/`,
`tests/runner-e2e/`)**: Added `doc/CHANNELS-AND-QUEUES.md`,
`doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`, plan docs,
`skills/paperclip-lite/SKILL.md`, and synchronized
`tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `pnpm --filter @paperclipai/shared build` — passed.
- `pnpm --filter @paperclipai/db check:migrations` — passed
(`0511_pale_kronos.sql` and `0512_stormy_the_hood.sql` verified
online-compatible, 2 new migrations since `630cf0423024`, none blocked).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed (`598` inputs, `changed: false`).
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs` — 13/13 tests
passed.
- `node scripts/check-maps.mjs` — passed (`35` areas, `192` capability
IDs aligned).
- `pnpm exec vitest run packages/shared/src/headless/headless.test.ts
packages/shared/src/sdk/sdk.test.ts
cli/src/__tests__/headless-board-cli.test.ts` — 3 files, 22/22 tests
passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-scope-visibility.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-identity-auth.test.ts
src/__tests__/headless-queues-leases-events.test.ts
src/__tests__/headless-e2e-sdk-cli.test.ts` — 5 files, 25/25 tests
passed.
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck
&& pnpm --filter paperclipai typecheck` — all passed.
- `pnpm --filter paperclipai build` — passed.

## Risks

- **Two new migrations (`0511`, `0512`)**: Both migrations are marked
online-compatible (`NOT VALID` constraints validated afterwards,
`CONCURRENTLY` index creation, idempotent statements for
non-transactional execution) and checked by `check:migrations`. If
#23329 lands separately with `0511` modified or renumbered, this branch
will rebase on top cleanly.
- **Large surface area (91 files)**: Changes are primarily additive new
modules (`headless-*`, `cli/src/commands/board/*`,
`packages/shared/src/headless/*`, `packages/shared/src/sdk/*`); existing
Web UI board behavior remains isolated via `issues.scope`.
- **Full repository Vitest suite**: Only the targeted headless, SDK,
CLI, server, and runner-e2e pin suites ran locally after rebasing; full
cross-package CI checks will validate the remaining suite.

## Model Used

- Google DeepMind Antigravity (Gemini coding agent) with 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 (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 08:12:19 -06:00

1291 lines
48 KiB
TypeScript

import { createHash, randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { eq } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import {
activityLog,
agentApiKeys,
agents,
authUsers,
boardApiKeys,
channels,
cliAuthChallenges,
companies,
companyMemberships,
createDb,
getEmbeddedPostgresTestSupport,
instanceUserRoles,
issues,
principalPermissionGrants,
projects,
startEmbeddedPostgresTestDatabase,
} from "@paperclipai/db";
import { findServerAdapter, listEnabledServerAdapters } from "../adapters/registry.js";
import { actorMiddleware } from "../middleware/auth.js";
import { errorHandler } from "../middleware/error-handler.js";
import { accessRoutes } from "../routes/access.js";
import { assertCompanyAccess } from "../routes/authz.js";
import { agentRoutes } from "../routes/agents.js";
import { headlessChannelsSchemasRoutes } from "../routes/headless-channels-schemas.js";
import { headlessIdentityRoutes } from "../routes/headless-identity.js";
import { headlessQueuesEventsRoutes } from "../routes/headless-queues-events.js";
import { issueRoutes } from "../routes/issues.js";
import { authorizationService, issueReadSqlCondition } from "../services/authorization.js";
import { enforceHeadlessScopes, resolveHeadlessActor } from "../services/headless-common.js";
const external = process.env.PAPERCLIP_TEST_DATABASE_URL;
const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport();
const databaseSuite = support.supported ? describe : describe.skip;
databaseSuite("Headless identity, auth & default company (real PostgreSQL)", () => {
let db: ReturnType<typeof createDb>;
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
beforeAll(async () => {
if (external) {
db = createDb(external);
} else {
temporary = await startEmbeddedPostgresTestDatabase("headless-identity-");
db = createDb(temporary.connectionString);
}
}, 60_000);
afterAll(async () => {
await db?.$client.end();
await temporary?.cleanup();
});
beforeEach(async () => {
await db.delete(activityLog);
await db.delete(cliAuthChallenges);
await db.delete(boardApiKeys);
await db.delete(agentApiKeys);
await db.delete(issues);
await db.delete(channels);
await db.delete(projects);
await db.delete(agents);
await db.delete(principalPermissionGrants);
await db.delete(companyMemberships);
await db.delete(companies);
await db.delete(instanceUserRoles);
await db.delete(authUsers);
});
function buildLocalTrustedApp() {
const app = express();
app.use(express.json());
app.use(
actorMiddleware(db, {
deploymentMode: "local_trusted",
localAgentProcessBoundary: {
classify: async () => "operator",
grantsImplicitBoard: async () => true,
},
}),
);
app.use("/api", headlessIdentityRoutes(db, { deploymentMode: "local_trusted" }));
app.use(
"/api",
accessRoutes(db, {
deploymentMode: "local_trusted",
deploymentExposure: "private",
bindHost: "127.0.0.1",
allowedHostnames: [],
}),
);
app.use(errorHandler);
return app;
}
function buildAuthenticatedApp(
validUserIds: Set<string>,
extraRoutes: express.Router[] = [],
) {
const app = express();
app.use(express.json());
app.use(
actorMiddleware(db, {
deploymentMode: "authenticated",
resolveSession: async (req) => {
const userId = req.header("X-Test-Session");
if (!userId || !validUserIds.has(userId)) return null;
return {
session: { id: `session-${userId}` },
user: {
id: userId,
name: "Test User",
email: `${userId}@example.invalid`,
},
} as never;
},
}),
);
app.use("/api", headlessIdentityRoutes(db, { deploymentMode: "authenticated" }));
for (const router of extraRoutes) {
app.use("/api", router);
}
app.use(
"/api",
accessRoutes(db, {
deploymentMode: "authenticated",
deploymentExposure: "private",
bindHost: "127.0.0.1",
allowedHostnames: [],
}),
);
app.get("/api/test-scoped-read", async (req, res) => {
const companyId = req.header("x-test-company-id") ?? "";
const channelPath =
typeof req.query.channel === "string" ? req.query.channel : undefined;
const action =
typeof req.query.action === "string" ? req.query.action : undefined;
const ctx = await resolveHeadlessActor(db, req, companyId, {
deploymentMode: "authenticated",
requiredAction: action,
requiredChannel: channelPath,
});
enforceHeadlessScopes(ctx, { action, channelPath });
res.json({ ok: true, actorProfile: ctx.actorProfile, scopes: ctx.scopes });
});
app.post("/api/test-scoped-write", async (req, res) => {
const companyId = req.header("x-test-company-id") ?? "";
const action =
typeof req.query.action === "string" ? req.query.action : "issue.create";
const ctx = await resolveHeadlessActor(db, req, companyId, {
deploymentMode: "authenticated",
requiredAction: action,
});
res.json({ ok: true, actorProfile: ctx.actorProfile });
});
app.get("/api/test-canonical/:companyId", (req, res) => {
assertCompanyAccess(req, req.params.companyId);
res.json({ ok: true });
});
app.use(errorHandler);
return app;
}
it("registers the pull-only headless adapter while excluding it from listEnabledServerAdapters", () => {
const headless = findServerAdapter("headless");
expect(headless).not.toBeNull();
expect(headless?.type).toBe("headless");
expect(headless?.models).toEqual([]);
expect(listEnabledServerAdapters([]).some((a) => a.type === "headless")).toBe(false);
});
it("auto-creates a single default company in local_trusted mode idempotently across concurrent calls", async () => {
const app = buildLocalTrustedApp();
const results = await Promise.all([
request(app).get("/api/companies/resolve-default"),
request(app).get("/api/companies/resolve-default"),
request(app).get("/api/companies/resolve-default"),
request(app).get("/api/companies/resolve-default"),
]);
for (const res of results) {
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
name: "Workspace",
issuePrefix: "PC",
agentIdentityPolicy: "open_local_profiles",
});
}
const uniqueIds = new Set(results.map((r) => r.body.id));
expect(uniqueIds.size).toBe(1);
const allCompanies = await db.select().from(companies);
expect(allCompanies).toHaveLength(1);
expect(allCompanies[0]?.defaultResponsibleUserId).toBe("local-board");
// Prefix / name lookup also resolves cleanly
const byPrefix = await request(app).get("/api/companies/resolve-default?company=pc");
expect(byPrefix.status).toBe(200);
expect(byPrefix.body.id).toBe(allCompanies[0]!.id);
const missing = await request(app).get("/api/companies/resolve-default?company=NOPE");
expect(missing.status).toBe(404);
});
it("enforces agentIdentityPolicy on ephemeral profiles across open_local_profiles, delegated_profiles, and strict_agent_keys", async () => {
const app = buildLocalTrustedApp();
const resolved = await request(app).get("/api/companies/resolve-default");
expect(resolved.status).toBe(200);
const companyId = resolved.body.id as string;
const openRes = await request(app)
.get("/api/whoami")
.set("X-Paperclip-Actor-Profile", "unregistered-bot");
expect(openRes.status).toBe(200);
expect(openRes.body).toMatchObject({
companyId,
principalType: "local_trusted",
actorProfile: "unregistered-bot",
agentIdentityPolicy: "open_local_profiles",
agentId: null,
agentName: null,
});
const patchDelegated = await request(app)
.patch(`/api/companies/${companyId}/agent-identity-policy`)
.send({ agentIdentityPolicy: "delegated_profiles" });
expect(patchDelegated.status).toBe(200);
expect(patchDelegated.body.agentIdentityPolicy).toBe("delegated_profiles");
const delegatedRes = await request(app)
.get(`/api/whoami?companyId=${companyId}`)
.set("X-Paperclip-Actor-Profile", "unregistered-bot");
expect(delegatedRes.status).toBe(200);
expect(delegatedRes.body).toMatchObject({
companyId,
actorProfile: "unregistered-bot",
agentIdentityPolicy: "delegated_profiles",
});
const patchStrict = await request(app)
.patch(`/api/companies/${companyId}/agent-identity-policy`)
.send({ agentIdentityPolicy: "strict_agent_keys" });
expect(patchStrict.status).toBe(200);
const strictRes = await request(app)
.get(`/api/whoami?companyId=${companyId}`)
.set("X-Paperclip-Actor-Profile", "unregistered-bot");
expect(strictRes.status).toBe(403);
expect(strictRes.body.code).toBe("agent_key_required");
});
it("connects @scanner, blocks unauthenticated profile impersonation with 409, and authenticates Bearer agent key", async () => {
const app = buildLocalTrustedApp();
const resolved = await request(app).get("/api/companies/resolve-default");
const companyId = resolved.body.id as string;
const connectRes = await request(app)
.post(`/api/companies/${companyId}/agents/connect`)
.send({ name: "scanner", role: "security" });
expect(connectRes.status).toBe(201);
expect(connectRes.body.agentName).toBe("scanner");
expect(connectRes.body.companyId).toBe(companyId);
expect(connectRes.body.apiKey).toMatch(/^pcp_/);
expect(connectRes.body.agent).toMatchObject({
name: "scanner",
role: "security",
adapterType: "headless",
status: "active",
});
const scannerToken = connectRes.body.apiKey as string;
// Attempting to impersonate @scanner without its API key fails closed with 409
const impersonateRes = await request(app)
.get(`/api/whoami?companyId=${companyId}`)
.set("X-Paperclip-Actor-Profile", "scanner");
expect(impersonateRes.status).toBe(409);
expect(impersonateRes.body.code).toBe("profile_matches_registered_agent");
// Authenticating with @scanner's Bearer key succeeds as principalType: "agent"
const agentWhoami = await request(app)
.get(`/api/whoami?companyId=${companyId}`)
.set("Authorization", `Bearer ${scannerToken}`);
expect(agentWhoami.status).toBe(200);
expect(agentWhoami.body).toMatchObject({
companyId,
principalType: "agent",
agentId: connectRes.body.agentId,
agentName: "scanner",
actorProfile: "scanner",
});
// An agent key cannot connect/mint keys for other agents
const agentMintAttempt = await request(app)
.post(`/api/companies/${companyId}/agents/connect`)
.set("Authorization", `Bearer ${scannerToken}`)
.send({ name: "rogue-bot" });
expect(agentMintAttempt.status).toBe(403);
});
it("enforces scoped board_api_keys (lockedProfile, companyId, scopes) and mints agent_api_key on agent_key CLI auth approval", async () => {
const userId = randomUUID();
const companyAId = randomUUID();
const companyBId = randomUUID();
const now = new Date();
await db.insert(authUsers).values({
id: userId,
name: "Board Owner",
email: `${userId}@example.invalid`,
createdAt: now,
updatedAt: now,
});
await db.insert(companies).values([
{ id: companyAId, name: "Company Alpha", issuePrefix: "ALF", agentIdentityPolicy: "delegated_profiles" },
{ id: companyBId, name: "Company Beta", issuePrefix: "BET", agentIdentityPolicy: "delegated_profiles" },
]);
await db.insert(companyMemberships).values([
{ companyId: companyAId, principalType: "user", principalId: userId, status: "active", membershipRole: "owner" },
{ companyId: companyBId, principalType: "user", principalId: userId, status: "active", membershipRole: "owner" },
]);
await db.insert(principalPermissionGrants).values([
{ companyId: companyAId, principalType: "user", principalId: userId, permissionKey: "agents:create", grantedByUserId: userId },
{ companyId: companyAId, principalType: "user", principalId: userId, permissionKey: "agents:configure", grantedByUserId: userId },
{ companyId: companyBId, principalType: "user", principalId: userId, permissionKey: "agents:create", grantedByUserId: userId },
{ companyId: companyBId, principalType: "user", principalId: userId, permissionKey: "agents:configure", grantedByUserId: userId },
]);
const app = buildAuthenticatedApp(new Set([userId]));
// 1. Create a scoped board API key locked to companyAId, profile "ci-triage", and restricted scopes
const keyRes = await request(app)
.post("/api/board-api-keys")
.set("X-Test-Session", userId)
.send({
name: "Scoped CI Key",
companyId: companyAId,
lockedProfile: "ci-triage",
scopes: {
channels: ["eng/*"],
actions: ["issue.read", "issue.comment"],
},
expiresAt: "2099-01-01T00:00:00.000Z",
});
expect(keyRes.status).toBe(201);
const scopedBoardToken = keyRes.body.token as string;
expect(scopedBoardToken).toMatch(/^pcp_board_/);
expect(keyRes.body.companyId).toBe(companyAId);
expect(keyRes.body.lockedProfile).toBe("ci-triage");
// resolve-default restricts to companyAId
const resolvedDefault = await request(app)
.get("/api/companies/resolve-default")
.set("Authorization", `Bearer ${scopedBoardToken}`);
expect(resolvedDefault.status).toBe(200);
expect(resolvedDefault.body.id).toBe(companyAId);
const otherCompanyResolve = await request(app)
.get(`/api/companies/resolve-default?company=${companyBId}`)
.set("Authorization", `Bearer ${scopedBoardToken}`);
expect(otherCompanyResolve.status).toBe(404);
// Passing a mismatched profile header fails with 403 profile_locked
const wrongProfile = await request(app)
.get(`/api/whoami?companyId=${companyAId}`)
.set("Authorization", `Bearer ${scopedBoardToken}`)
.set("X-Paperclip-Actor-Profile", "impostor");
expect(wrongProfile.status).toBe(403);
expect(wrongProfile.body.code).toBe("profile_locked");
// Passing the matching profile (or no header) succeeds and reports the locked profile + scopes
const rightProfile = await request(app)
.get(`/api/whoami?companyId=${companyAId}`)
.set("Authorization", `Bearer ${scopedBoardToken}`);
expect(rightProfile.status).toBe(200);
expect(rightProfile.body).toMatchObject({
companyId: companyAId,
principalType: "user",
userId,
actorProfile: "ci-triage",
scopes: {
channels: ["eng/*"],
actions: ["issue.read", "issue.comment"],
},
});
// Scoped enforcement: allowed channel + action succeeds
const allowedAction = await request(app)
.get("/api/test-scoped-read?channel=eng/backend&action=issue.read")
.set("Authorization", `Bearer ${scopedBoardToken}`)
.set("x-test-company-id", companyAId);
expect(allowedAction.status).toBe(200);
// Disallowed action fails with 403 scope_denied
const deniedAction = await request(app)
.get("/api/test-scoped-read?channel=eng/backend&action=issue.delete")
.set("Authorization", `Bearer ${scopedBoardToken}`)
.set("x-test-company-id", companyAId);
expect(deniedAction.status).toBe(403);
expect(deniedAction.body.code).toBe("scope_denied");
// Disallowed channel fails with 403 scope_denied
const deniedChannel = await request(app)
.get("/api/test-scoped-read?channel=ops/alerts&action=issue.read")
.set("Authorization", `Bearer ${scopedBoardToken}`)
.set("x-test-company-id", companyAId);
expect(deniedChannel.status).toBe(403);
expect(deniedChannel.body.code).toBe("scope_denied");
// 2. agent_key CLI auth challenge mints an agent_api_key without creating a board_api_keys row
const boardKeysBefore = await db.select().from(boardApiKeys);
const challengeCreate = await request(app)
.post("/api/cli-auth/challenges")
.send({
command: "paperclipai agent login --name triage-bot",
clientName: "paperclipai cli",
requestedAccess: "board",
requestedCompanyId: companyAId,
challengeKind: "agent_key",
agentName: "triage-bot",
agentRole: "qa",
});
expect(challengeCreate.status).toBe(201);
const { id: challengeId, token: challengeSecret, boardApiToken: issuedAgentToken } =
challengeCreate.body as {
id: string;
token: string;
boardApiToken: string;
};
expect(issuedAgentToken).toMatch(/^pcp_/);
// Pending token cannot authenticate yet
const preApproveWhoami = await request(app)
.get(`/api/whoami?companyId=${companyAId}`)
.set("Authorization", `Bearer ${issuedAgentToken}`);
expect(preApproveWhoami.status).toBe(401);
// Approve challenge as user
const approveRes = await request(app)
.post(`/api/cli-auth/challenges/${challengeId}/approve`)
.set("X-Test-Session", userId)
.send({ token: challengeSecret });
expect(approveRes.status).toBe(200);
expect(approveRes.body).toMatchObject({
approved: true,
status: "approved",
keyId: null,
companyId: companyAId,
});
expect(approveRes.body.agentId).toBeTruthy();
// No new board_api_keys row was created
const boardKeysAfter = await db.select().from(boardApiKeys);
expect(boardKeysAfter).toHaveLength(boardKeysBefore.length);
// Polling returns approved + agentId + companyId
const pollRes = await request(app).get(
`/api/cli-auth/challenges/${challengeId}?token=${encodeURIComponent(challengeSecret)}`,
);
expect(pollRes.status).toBe(200);
expect(pollRes.body).toMatchObject({
status: "approved",
challengeKind: "agent_key",
agentId: approveRes.body.agentId,
companyId: companyAId,
});
// The issued token now authenticates directly as agent @triage-bot
const postApproveWhoami = await request(app)
.get(`/api/whoami?companyId=${companyAId}`)
.set("Authorization", `Bearer ${issuedAgentToken}`);
expect(postApproveWhoami.status).toBe(200);
expect(postApproveWhoami.body).toMatchObject({
companyId: companyAId,
principalType: "agent",
agentId: approveRes.body.agentId,
agentName: "triage-bot",
});
const [createdAgent] = await db
.select()
.from(agents)
.where(eq(agents.id, approveRes.body.agentId));
expect(createdAgent).toMatchObject({
companyId: companyAId,
name: "triage-bot",
role: "qa",
adapterType: "headless",
status: "active",
});
});
it("enforces viewer read-only limits, prevents scope/key privilege escalation, and expires ttlSec agent keys", async () => {
const ownerId = randomUUID();
const viewerId = randomUUID();
const companyId = randomUUID();
const now = new Date();
await db.insert(authUsers).values([
{ id: ownerId, name: "Owner", email: `${ownerId}@example.invalid`, createdAt: now, updatedAt: now },
{ id: viewerId, name: "Viewer", email: `${viewerId}@example.invalid`, createdAt: now, updatedAt: now },
]);
await db.insert(companies).values({
id: companyId,
name: "Security Co",
issuePrefix: "SEC",
agentIdentityPolicy: "delegated_profiles",
});
await db.insert(companyMemberships).values([
{ companyId, principalType: "user", principalId: ownerId, status: "active", membershipRole: "owner" },
{ companyId, principalType: "user", principalId: viewerId, status: "active", membershipRole: "viewer" },
]);
await db.insert(principalPermissionGrants).values([
{ companyId, principalType: "user", principalId: ownerId, permissionKey: "agents:create", grantedByUserId: ownerId },
{ companyId, principalType: "user", principalId: ownerId, permissionKey: "agents:configure", grantedByUserId: ownerId },
]);
const app = buildAuthenticatedApp(new Set([ownerId, viewerId]));
// 1. Viewer can read headless routes but is blocked from headless writes (403)
await request(app)
.get("/api/test-scoped-read?action=issue.read")
.set("X-Test-Session", viewerId)
.set("x-test-company-id", companyId)
.expect(200);
await request(app)
.post("/api/test-scoped-write?action=issue.create")
.set("X-Test-Session", viewerId)
.set("x-test-company-id", companyId)
.expect(403);
// 2. Scoped board_key cannot call canonical company routes, connect agents, mint unrestricted child keys, or widen scopes via header
const scopedKeyRes = await request(app)
.post("/api/board-api-keys")
.set("X-Test-Session", ownerId)
.send({
name: "Narrow Channel Key",
companyId,
lockedProfile: "narrow-bot",
scopes: {
channels: ["eng/backend"],
actions: ["issue.read", "issue.comment", "board_keys.create"],
},
expiresAt: "2099-01-01T00:00:00.000Z",
})
.expect(201);
const scopedToken = scopedKeyRes.body.token as string;
// Canonical route rejects restricted board_key
await request(app)
.get(`/api/test-canonical/${companyId}`)
.set("Authorization", `Bearer ${scopedToken}`)
.expect(403);
// Profile-locked / channel-scoped key cannot connect agent
await request(app)
.post(`/api/companies/${companyId}/agents/connect`)
.set("Authorization", `Bearer ${scopedToken}`)
.send({ name: "escalated-agent" })
.expect(403);
// Scoped key cannot mint unrestricted or wider-scoped board API key
await request(app)
.post("/api/board-api-keys")
.set("Authorization", `Bearer ${scopedToken}`)
.send({ name: "Wildcard Key", companyId })
.expect(403);
// Header attempting to widen ['eng/backend'] to ['eng/*'] is rejected for out-of-scope channel 'eng/frontend'
await request(app)
.get("/api/test-scoped-read?channel=eng/frontend&action=issue.read")
.set("Authorization", `Bearer ${scopedToken}`)
.set("x-test-company-id", companyId)
.set("X-Paperclip-Actor-Scopes", JSON.stringify({ channels: ["eng/*"] }))
.expect(403);
// 3. connectAgent ttlSec sets expiresAt and expired agent API keys are rejected with 401
const connectRes = await request(app)
.post(`/api/companies/${companyId}/agents/connect`)
.set("X-Test-Session", ownerId)
.send({ name: "ephemeral-bot", role: "qa", ttlSec: 60 })
.expect(201);
const ephemeralToken = connectRes.body.apiKey as string;
const [keyRow] = await db
.select()
.from(agentApiKeys)
.where(eq(agentApiKeys.agentId, connectRes.body.agentId as string));
expect(keyRow?.expiresAt).toBeInstanceOf(Date);
await db
.update(agentApiKeys)
.set({ expiresAt: new Date(Date.now() - 5_000) })
.where(eq(agentApiKeys.id, keyRow!.id));
await request(app)
.get(`/api/whoami?companyId=${companyId}`)
.set("Authorization", `Bearer ${ephemeralToken}`)
.expect(401);
});
it("requires agents:create + manage rights on connectAgent & agent_key CLI approval and denies instance_admin bypass on restricted board_keys", async () => {
const adminId = randomUUID();
const memberId = randomUUID();
const creatorId = randomUUID();
const companyAId = randomUUID();
const companyBId = randomUUID();
const now = new Date();
await db.insert(authUsers).values([
{ id: adminId, name: "Inst Admin", email: `${adminId}@example.invalid`, createdAt: now, updatedAt: now },
{ id: memberId, name: "Plain Member", email: `${memberId}@example.invalid`, createdAt: now, updatedAt: now },
{ id: creatorId, name: "Creator", email: `${creatorId}@example.invalid`, createdAt: now, updatedAt: now },
]);
await db.insert(instanceUserRoles).values({
userId: adminId,
role: "instance_admin",
});
await db.insert(companies).values([
{ id: companyAId, name: "Authz Alpha", issuePrefix: "AA", agentIdentityPolicy: "delegated_profiles" },
{ id: companyBId, name: "Authz Beta", issuePrefix: "AB", agentIdentityPolicy: "delegated_profiles" },
]);
await db.insert(companyMemberships).values([
{ companyId: companyAId, principalType: "user", principalId: adminId, status: "active", membershipRole: "operator" },
{ companyId: companyAId, principalType: "user", principalId: memberId, status: "active", membershipRole: "member" },
{ companyId: companyAId, principalType: "user", principalId: creatorId, status: "active", membershipRole: "owner" },
{ companyId: companyBId, principalType: "user", principalId: creatorId, status: "active", membershipRole: "owner" },
]);
await db.insert(principalPermissionGrants).values([
{ companyId: companyAId, principalType: "user", principalId: creatorId, permissionKey: "agents:create", grantedByUserId: creatorId },
{ companyId: companyAId, principalType: "user", principalId: creatorId, permissionKey: "agents:configure", grantedByUserId: creatorId },
]);
const [ceoAgent] = await db
.insert(agents)
.values({
companyId: companyAId,
name: "ceo",
role: "ceo",
adapterType: "headless",
status: "idle",
})
.returning();
const app = buildAuthenticatedApp(new Set([adminId, memberId, creatorId]));
app.use("/api", issueRoutes(db, { deploymentMode: "authenticated" } as any));
app.get("/api/test-decide-issue", async (req, res) => {
const targetCompany = req.header("x-test-company-id")!;
const targetIssueId = req.header("x-test-issue-id")!;
const decision = await authorizationService(db).decide({
actor: req.actor,
action: "issue:read",
resource: { type: "issue", companyId: targetCompany, issueId: targetIssueId },
});
const cond = await issueReadSqlCondition(db, req.actor);
const rows = await db
.select({ id: issues.id })
.from(issues)
.where(eq(issues.id, targetIssueId));
const readableRows = await db
.select({ id: issues.id })
.from(issues)
.where(cond);
res.json({
allowed: decision.allowed,
reason: decision.reason,
ignoreInstanceAdmin: Boolean(req.actor.ignoreInstanceAdmin),
total: rows.length,
readable: readableRows.some((r) => r.id === targetIssueId),
});
});
// 1. Plain member without agents:create cannot connect existing 'ceo' or new agent
await request(app)
.post(`/api/companies/${companyAId}/agents/connect`)
.set("X-Test-Session", memberId)
.send({ name: ceoAgent!.name })
.expect(403);
await request(app)
.post(`/api/companies/${companyAId}/agents/connect`)
.set("X-Test-Session", memberId)
.send({ name: "rogue-member-bot" })
.expect(403);
// 2. Plain member without agents:create cannot approve an agent_key CLI challenge for 'ceo' or new agent
const challengeRes = await request(app)
.post("/api/cli-auth/challenges")
.send({
command: "paperclipai agent login --name ceo",
clientName: "paperclipai cli",
requestedAccess: "board",
requestedCompanyId: companyAId,
challengeKind: "agent_key",
agentName: "ceo",
})
.expect(201);
await request(app)
.post(`/api/cli-auth/challenges/${challengeRes.body.id}/approve`)
.set("X-Test-Session", memberId)
.send({ token: challengeRes.body.token })
.expect(403);
// 3. Restricted board_key owned by instance_admin cannot elevate via instance_user_roles DB fallback
const [privProjB] = await db
.insert(projects)
.values({ companyId: companyBId, name: "Private Beta", visibility: "private" })
.returning();
const [privIssueB] = await db
.insert(issues)
.values({
companyId: companyBId,
projectId: privProjB!.id,
visibility: "private",
title: "Secret in Beta",
status: "todo",
scope: "board",
issueNumber: 1,
identifier: "AB-1",
createdByUserId: creatorId,
responsibleUserId: creatorId,
})
.returning();
await db.update(issues).set({ privacyRootIssueId: privIssueB!.id }).where(eq(issues.id, privIssueB!.id));
const restrictedKey = await request(app)
.post("/api/board-api-keys")
.set("X-Test-Session", adminId)
.send({
name: "Scopes-Only Key",
scopes: { actions: ["*"] },
expiresAt: "2099-01-01T00:00:00.000Z",
})
.expect(201);
const probe = await request(app)
.get("/api/test-decide-issue")
.set("Authorization", `Bearer ${restrictedKey.body.token}`)
.set("x-test-company-id", companyBId)
.set("x-test-issue-id", privIssueB!.id)
.expect(200);
expect(probe.body).toMatchObject({
allowed: false,
ignoreInstanceAdmin: true,
readable: false,
});
});
it("blocks channel-scoped board_api_key (scopes.channels=['build/*']) from reading or mutating unchanneled board issues", async () => {
const ownerId = randomUUID();
const companyId = randomUUID();
const now = new Date();
await db.insert(authUsers).values({
id: ownerId,
name: "Scope Owner",
email: `${ownerId}@example.invalid`,
createdAt: now,
updatedAt: now,
});
await db.insert(companies).values({
id: companyId,
name: "Scoped Key Org",
issuePrefix: "SKO",
agentIdentityPolicy: "delegated_profiles",
});
await db.insert(companyMemberships).values({
companyId,
principalType: "user",
principalId: ownerId,
status: "active",
membershipRole: "owner",
});
const [unchanneledIssue] = await db
.insert(issues)
.values({
companyId,
channelId: null,
title: "Board-level confidential task",
status: "todo",
scope: "board",
priority: "medium",
issueNumber: 1,
identifier: "SKO-1",
createdByUserId: ownerId,
responsibleUserId: ownerId,
})
.returning();
const app = buildAuthenticatedApp(new Set([ownerId]), [
headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }),
headlessQueuesEventsRoutes(db, { deploymentMode: "authenticated" }),
issueRoutes(db, { deploymentMode: "authenticated" } as any),
]);
const scopedKeyRes = await request(app)
.post("/api/board-api-keys")
.set("X-Test-Session", ownerId)
.send({
name: "Build Channel Only",
companyId,
scopes: { channels: ["build/*"] },
expiresAt: "2099-01-01T00:00:00.000Z",
})
.expect(201);
const scopedToken = scopedKeyRes.body.token as string;
// Seed one issue in #build/ci and verify matching channel succeeds while unchanneled SKO-1 is denied across every headless handler
await request(app)
.post(`/api/companies/${companyId}/channels/posts`)
.set("Authorization", `Bearer ${scopedToken}`)
.send({ channel: "build/ci", text: "In-scope post" })
.expect(201);
await request(app)
.get(`/api/issues/${unchanneledIssue!.identifier}?view=thread`)
.set("Authorization", `Bearer ${scopedToken}`)
.expect(403);
await request(app)
.post(`/api/issues/${unchanneledIssue!.identifier}/comments`)
.set("Authorization", `Bearer ${scopedToken}`)
.send({ body: "Out of scope comment" })
.expect(403);
await request(app)
.patch(`/api/issues/${unchanneledIssue!.identifier}/kv-labels`)
.set("Authorization", `Bearer ${scopedToken}`)
.send({ set: { hijacked: "1" } })
.expect(403);
await request(app)
.patch(`/api/issues/${unchanneledIssue!.identifier}`)
.set("Authorization", `Bearer ${scopedToken}`)
.send({ status: "done" })
.expect(403);
await request(app)
.patch(`/api/issues/${unchanneledIssue!.identifier}`)
.set("Authorization", `Bearer ${scopedToken}`)
.send({ status: "done", labels: { hijacked: "1" } })
.expect(403);
await request(app)
.post(`/api/issues/${unchanneledIssue!.identifier}/claim/complete`)
.set("Authorization", `Bearer ${scopedToken}`)
.send({ text: "Hijacked completion" })
.expect(403);
await request(app)
.post(`/api/issues/${unchanneledIssue!.identifier}/ask`)
.set("Authorization", `Bearer ${scopedToken}`)
.send({ question: "Block?", choices: ["yes", "no"] })
.expect(403);
await request(app)
.post(`/api/issues/${unchanneledIssue!.identifier}/approve`)
.set("Authorization", `Bearer ${scopedToken}`)
.send({ note: "Hijacked approval" })
.expect(403);
await request(app)
.post(`/api/companies/${companyId}/schedules`)
.set("Authorization", `Bearer ${scopedToken}`)
.send({ target: unchanneledIssue!.identifier, message: "Ping", in: "5m" })
.expect(403);
// Disjoint X-Paperclip-Actor-Scopes header narrows to empty [] (deny-all), NEVER widens to unrestricted
const disjointList = await request(app)
.get(`/api/companies/${companyId}/issues?headless=1`)
.set("Authorization", `Bearer ${scopedToken}`)
.set("X-Paperclip-Actor-Scopes", JSON.stringify({ channels: ["other"] }))
.expect(200);
expect(disjointList.body.items).toEqual([]);
await request(app)
.get(`/api/issues/${unchanneledIssue!.identifier}?view=thread`)
.set("Authorization", `Bearer ${scopedToken}`)
.set("X-Paperclip-Actor-Scopes", JSON.stringify({ channels: ["other"] }))
.expect(403);
});
it("blocks board_api_keys from approving CLI challenges and restricts key-management and /cli-auth/me metadata", async () => {
const adminId = randomUUID();
const companyAId = randomUUID();
const companyBId = randomUUID();
const now = new Date();
await db.insert(authUsers).values({
id: adminId,
name: "Key Admin",
email: `${adminId}@example.invalid`,
createdAt: now,
updatedAt: now,
});
await db.insert(instanceUserRoles).values({
userId: adminId,
role: "instance_admin",
});
await db.insert(companies).values([
{ id: companyAId, name: "Scoped Co A", issuePrefix: "SCA", agentIdentityPolicy: "delegated_profiles" },
{ id: companyBId, name: "Scoped Co B", issuePrefix: "SCB", agentIdentityPolicy: "delegated_profiles" },
]);
await db.insert(companyMemberships).values([
{ companyId: companyAId, principalType: "user", principalId: adminId, status: "active", membershipRole: "owner" },
{ companyId: companyBId, principalType: "user", principalId: adminId, status: "active", membershipRole: "owner" },
]);
const [agentA] = await db
.insert(agents)
.values({
companyId: companyAId,
name: "key-agent-a",
role: "engineer",
adapterType: "headless",
status: "idle",
})
.returning();
const app = buildAuthenticatedApp(new Set([adminId]), [
agentRoutes(db),
]);
// Seed an unrestricted board key plus three restricted variants (company-scoped, profile-locked, channel-scoped)
const targetKeyRes = await request(app)
.post("/api/board-api-keys")
.set("X-Test-Session", adminId)
.send({ name: "Target Unrestricted", expiresAt: "2099-01-01T00:00:00.000Z" })
.expect(201);
const companyKeyRes = await request(app)
.post("/api/board-api-keys")
.set("X-Test-Session", adminId)
.send({ name: "Company A Only", companyId: companyAId, expiresAt: "2099-01-01T00:00:00.000Z" })
.expect(201);
const profileKeyRes = await request(app)
.post("/api/board-api-keys")
.set("X-Test-Session", adminId)
.send({ name: "Profile Locked", lockedProfile: "scanner", expiresAt: "2099-01-01T00:00:00.000Z" })
.expect(201);
const channelKeyRes = await request(app)
.post("/api/board-api-keys")
.set("X-Test-Session", adminId)
.send({ name: "Channel Scoped", scopes: { channels: ["build/*"] }, expiresAt: "2099-01-01T00:00:00.000Z" })
.expect(201);
const challenge = await request(app)
.post("/api/cli-auth/challenges")
.send({ command: "paperclipai auth login", clientName: "cli", requestedAccess: "board" })
.expect(201);
for (const restricted of [companyKeyRes.body, profileKeyRes.body, channelKeyRes.body]) {
const tok = restricted.token as string;
// 1. Cannot approve CLI auth challenges to mint an unrestricted key
await request(app)
.post(`/api/cli-auth/challenges/${challenge.body.id}/approve`)
.set("Authorization", `Bearer ${tok}`)
.send({ token: challenge.body.token })
.expect(403);
// 2. Cannot list or revoke other board API keys
await request(app)
.get("/api/board-api-keys")
.set("Authorization", `Bearer ${tok}`)
.expect(403);
await request(app)
.delete(`/api/board-api-keys/${targetKeyRes.body.id}`)
.set("Authorization", `Bearer ${tok}`)
.expect(403);
}
// 3. Company-scoped key /cli-auth/me hides other companies and instance-admin status
const meRes = await request(app)
.get("/api/cli-auth/me")
.set("Authorization", `Bearer ${companyKeyRes.body.token}`)
.expect(200);
expect(meRes.body.isInstanceAdmin).toBe(false);
expect(meRes.body.companyIds).toEqual([companyAId]);
expect(meRes.body.memberships.map((m: { companyId: string }) => m.companyId)).toEqual([companyAId]);
// 4. Scoped & profile-locked board keys cannot list or revoke agent API keys
for (const restricted of [profileKeyRes.body, channelKeyRes.body]) {
const tok = restricted.token as string;
await request(app)
.get(`/api/agents/${agentA!.id}/keys`)
.set("Authorization", `Bearer ${tok}`)
.expect(403);
await request(app)
.delete(`/api/agents/${agentA!.id}/keys/${randomUUID()}`)
.set("Authorization", `Bearer ${tok}`)
.expect(403);
}
// 5. Self-revocation via /cli-auth/revoke-current remains permitted
await request(app)
.post("/api/cli-auth/revoke-current")
.set("Authorization", `Bearer ${companyKeyRes.body.token}`)
.expect(200);
});
it("blocks skill_test and task_bridge agent API keys across headless channel, queue, and identity endpoints", async () => {
const companyId = randomUUID();
const adminId = randomUUID();
await db.insert(authUsers).values({
id: adminId,
name: "Admin",
email: "admin-scope@example.invalid",
emailVerified: true,
createdAt: new Date(),
updatedAt: new Date(),
});
await db.insert(companies).values({
id: companyId,
name: "Scoped Agent Key Corp",
issuePrefix: "SAK",
});
await db.insert(companyMemberships).values({
companyId,
principalType: "user",
principalId: adminId,
membershipRole: "owner",
status: "active",
});
await db.insert(channels).values({
companyId,
path: "general",
visibility: "open",
});
const [agent] = await db
.insert(agents)
.values({
companyId,
name: "scoped-runner",
role: "engineer",
adapterType: "headless",
status: "idle",
})
.returning();
const allowedIssueId = randomUUID();
await db.insert(issues).values({
id: allowedIssueId,
companyId,
title: "Scoped harness issue",
status: "in_progress",
issueNumber: 1,
identifier: "SAK-1",
});
const skillToken = "pcp_skill_test_token_12345";
const bridgeToken = "pcp_task_bridge_token_67890";
await db.insert(agentApiKeys).values([
{
agentId: agent!.id,
companyId,
name: "skill-test-key",
keyHash: createHash("sha256").update(skillToken).digest("hex"),
responsibleUserId: adminId,
scopeConfig: {
kind: "skill_test",
issueId: allowedIssueId,
},
},
{
agentId: agent!.id,
companyId,
name: "task-bridge-key",
keyHash: createHash("sha256").update(bridgeToken).digest("hex"),
responsibleUserId: adminId,
scopeConfig: {
kind: "task_bridge",
parentIssueId: allowedIssueId,
projectIds: [],
allowedAssigneeAgentIds: [],
},
},
]);
expect(() =>
enforceHeadlessScopes(
{ scopes: null, keyScope: { kind: "skill_test", issueId: allowedIssueId } },
{ action: "read" },
),
).toThrow(/cannot access headless/);
expect(() =>
enforceHeadlessScopes(
{
scopes: null,
keyScope: {
kind: "task_bridge",
parentIssueId: allowedIssueId,
projectIds: [],
allowedAssigneeAgentIds: [],
},
},
{ action: "tasks.claim" },
),
).toThrow(/cannot access headless/);
const app = buildAuthenticatedApp(new Set([adminId]), [
headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }),
headlessQueuesEventsRoutes(db, { deploymentMode: "authenticated" }),
]);
for (const token of [skillToken, bridgeToken]) {
const resolveRes = await request(app)
.get("/api/companies/resolve-default")
.set("Authorization", `Bearer ${token}`)
.expect(403);
expect(resolveRes.body.code).toBe("scope_denied");
const chRes = await request(app)
.get(`/api/companies/${companyId}/channels`)
.set("Authorization", `Bearer ${token}`)
.expect(403);
expect(chRes.body.code).toBe("scope_denied");
const threadsRes = await request(app)
.get(`/api/companies/${companyId}/channels/threads?channel=general`)
.set("Authorization", `Bearer ${token}`)
.expect(403);
expect(threadsRes.body.code).toBe("scope_denied");
const postRes = await request(app)
.post(`/api/companies/${companyId}/channels/posts`)
.set("Authorization", `Bearer ${token}`)
.send({ channel: "general", message: "Bypass attempt" })
.expect(403);
expect(postRes.body.code).toBe("scope_denied");
const schemasRes = await request(app)
.get(`/api/companies/${companyId}/schemas`)
.set("Authorization", `Bearer ${token}`)
.expect(403);
expect(schemasRes.body.code).toBe("scope_denied");
const issuesRes = await request(app)
.get(`/api/companies/${companyId}/issues?ready=true`)
.set("Authorization", `Bearer ${token}`)
.expect(403);
expect(issuesRes.body.code).toBe("scope_denied");
const waitRes = await request(app)
.get(`/api/companies/${companyId}/events/wait?timeoutMs=0`)
.set("Authorization", `Bearer ${token}`)
.expect(403);
expect(waitRes.body.code).toBe("scope_denied");
const scheduleRes = await request(app)
.post(`/api/companies/${companyId}/schedules`)
.set("Authorization", `Bearer ${token}`)
.send({ target: "general", message: "Bypass ping", in: "1m" })
.expect(403);
expect(scheduleRes.body.code).toBe("scope_denied");
const claimRes = await request(app)
.post(`/api/companies/${companyId}/tasks/claim`)
.set("Authorization", `Bearer ${token}`)
.send({ channel: "general", wait: 0 })
.expect(403);
expect(claimRes.body.code).toBe("scope_denied");
const askRes = await request(app)
.post(`/api/issues/${allowedIssueId}/ask`)
.set("Authorization", `Bearer ${token}`)
.send({ question: "Bypass ask?" })
.expect(403);
expect(askRes.body.code).toBe("scope_denied");
const whoRes = await request(app)
.get(`/api/whoami?companyId=${companyId}`)
.set("Authorization", `Bearer ${token}`)
.expect(403);
expect(whoRes.body.code).toBe("scope_denied");
}
});
it("enforces requireBoardApprovalForNewAgents on connectAgent and agent_key CLI approval", async () => {
const ownerId = randomUUID();
const companyId = randomUUID();
const now = new Date();
await db.insert(authUsers).values({
id: ownerId,
name: "Approval Owner",
email: `${ownerId}@example.invalid`,
createdAt: now,
updatedAt: now,
});
await db.insert(companies).values({
id: companyId,
name: "Approval Gate Org",
issuePrefix: "AGO",
agentIdentityPolicy: "strict_agent_keys",
requireBoardApprovalForNewAgents: true,
});
await db.insert(companyMemberships).values({
companyId,
principalType: "user",
principalId: ownerId,
status: "active",
membershipRole: "owner",
});
await db.insert(principalPermissionGrants).values([
{ companyId, principalType: "user", principalId: ownerId, permissionKey: "agents:create", grantedByUserId: ownerId },
{ companyId, principalType: "user", principalId: ownerId, permissionKey: "agents:configure", grantedByUserId: ownerId },
]);
const [approvedAgent, pendingAgent] = await db
.insert(agents)
.values([
{
companyId,
name: "approved-worker",
role: "engineer",
adapterType: "headless",
status: "idle",
},
{
companyId,
name: "pending-worker",
role: "engineer",
adapterType: "headless",
status: "pending_approval",
},
])
.returning();
const app = buildAuthenticatedApp(new Set([ownerId]));
// 1. Direct new-agent creation via connectAgent returns 409 when requireBoardApprovalForNewAgents=true
const newConnectRes = await request(app)
.post(`/api/companies/${companyId}/agents/connect`)
.set("X-Test-Session", ownerId)
.send({ name: "unapproved-connect-bot", role: "engineer" })
.expect(409);
expect(newConnectRes.body.code).toBe("board_approval_required");
// 2. Direct new-agent creation via agent_key CLI challenge approval returns 409
const challengeRes = await request(app)
.post("/api/cli-auth/challenges")
.send({
command: "paperclipai agent login --name unapproved-cli-bot",
clientName: "paperclipai cli",
requestedAccess: "board",
requestedCompanyId: companyId,
challengeKind: "agent_key",
agentName: "unapproved-cli-bot",
})
.expect(201);
const approveNewRes = await request(app)
.post(`/api/cli-auth/challenges/${challengeRes.body.id}/approve`)
.set("X-Test-Session", ownerId)
.send({ token: challengeRes.body.token })
.expect(409);
expect(approveNewRes.body.code).toBe("board_approval_required");
// 3. Pending-approval agents cannot be issued keys before approval
await request(app)
.post(`/api/companies/${companyId}/agents/connect`)
.set("X-Test-Session", ownerId)
.send({ name: pendingAgent!.name })
.expect(409);
// 4. Existing approved agents can still mint keys via both connectAgent and agent_key approval
const existingConnectRes = await request(app)
.post(`/api/companies/${companyId}/agents/connect`)
.set("X-Test-Session", ownerId)
.send({ name: approvedAgent!.name })
.expect(201);
expect(existingConnectRes.body.agentId).toBe(approvedAgent!.id);
const existingChallengeRes = await request(app)
.post("/api/cli-auth/challenges")
.send({
command: `paperclipai agent login --name ${approvedAgent!.name}`,
clientName: "paperclipai cli",
requestedAccess: "board",
requestedCompanyId: companyId,
challengeKind: "agent_key",
agentName: approvedAgent!.name,
})
.expect(201);
const approveExistingRes = await request(app)
.post(`/api/cli-auth/challenges/${existingChallengeRes.body.id}/approve`)
.set("X-Test-Session", ownerId)
.send({ token: existingChallengeRes.body.token })
.expect(200);
expect(approveExistingRes.body.agentId).toBe(approvedAgent!.id);
const companyAgents = await db
.select({ name: agents.name })
.from(agents)
.where(eq(agents.companyId, companyId));
expect(companyAgents.map((a) => a.name).sort()).toEqual([
"approved-worker",
"pending-worker",
]);
});
});