perf(auth): authenticate a run's agent JWT in three statements (#21434)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Each running agent calls the Paperclip API with a signed run token
(an agent JWT)
> - The server authenticates each of these requests before the route
handler starts
> - This authentication sent 13 statements to the database for each
request, and none of them were cached
> - One server process starts to struggle at about 50 concurrent agents,
and the target is 1,000
> - This pull request cuts the work before the route handler to 3
statements, with no transaction and no row locks in the usual case
> - The benefit is less database work and less event-loop work for each
agent request, with the same security checks on each request

## Linked Issues or Issue Description

Refs #16577 (trimmed saved run JSON from agent authentication)
Refs #17931 (scoped run identity reads to the needs of each operation)

**What existing behavior does this improve?**
The authentication of an API request that an agent makes with its run
JWT. Before the route handler starts, `actorMiddleware` did 13 database
statements in sequence: a board key lookup, an agent key lookup, a
`select *` of the agent, the run read, a 7-statement locked identity
capture (BEGIN, run task read, task row lock, run row lock and wide row
read, pending steering read, context read, COMMIT), and two reads for
the responsible user.

**Subsystem affected**
Server: `server/src/middleware/auth.ts`,
`server/src/middleware/agent-run-authentication.ts` and
`server/src/services/run-identity.ts`.

**Current behavior**
Each agent request costs 13 statements. The identity capture is a
transaction that holds a pooled connection and takes `FOR NO KEY UPDATE`
locks on the task row and the run row. These are the same rows that
event appends and steering lock, so agent requests wait behind them.

**Proposed behavior**
Each agent request costs 3 statements and no transaction: the agent
status columns, one run statement, and one membership statement. A run
with a pending steering context still uses the locked capture, so
steering acceptance does not change.

**Reason and benefit**
Item 1c of the thousand-concurrent-agents plan. The load model at 50
agents (API requests only) shows the database statements for this path
go from 165.7/s to 30.1/s, transactions from 15.1/s to 0, and event-loop
utilization from 0.74 to 0.25.

**Breaking changes**
None. The actor shape that routes get does not change. No route handler
changes. No schema change.

## What Changed

- **Skip key lookups for a verified run JWT.** The middleware verifies
the JWT first (HMAC only, no database). Every stored board key and agent
key is `pcp_` followed by letters, `_` and hex (`createBoardApiToken`,
`createToken`). A verified JWT has three parts with dots. So its SHA-256
cannot equal a stored key hash, and both lookups always returned no row
for it. A token that does not verify still tries the board key, then the
agent key, in the same order as before.
- **Read only the agent columns that authentication checks.**
`companyId`, `status` and `lifecycleHolds` replace `select *`. The agent
configuration JSON stays in the database. The agent-key path uses the
same columns.
- **Read revocation and identity in one statement.**
`loadAgentRunAuthentication` now also returns the run task ids, a
`pendingIdentityContext` flag (`exists` on a pending context of this
run), and the active context `id` and `responsibleUserId` (only when
that context belongs to this run). The new `resolveRequestRunIdentity`
in `run-identity.ts` uses these columns:
- The run is not running, or it has no active context: it keeps the run
row values, as before.
- A pending context exists: it calls `captureRunIdentity(...,
"request_authentication")`, as before. This keeps the locked
accept-or-refuse step and the 409 for an unacknowledged steer.
- Otherwise: it checks the run task ids with the same rule as
`lockIdentityTask` (now `assertRunTaskIdentity`), and returns the
context from the statement.
- **Reuse the run row for the legacy responsible user.** The legacy
lookup had the same filter as the run read. The middleware now uses the
`responsibleUserId` from that read, with the same non-UUID guard.
- **One statement for memberships.** The user existence check is an
`exists` condition in the membership statement, in place of a second
parallel statement.
- No in-process memo and no time-based cache. Every request reads the
current run row.

### Why the request-authentication read does not need the locks or the
transaction

The capture locks are released at COMMIT, before the route handler
starts. So they do not protect anything that the route does. Inside
authentication, they have two effects:

1. **They protect the acceptance write when a pending context exists.**
This PR keeps this case on the locked capture.
2. **They make the read wait for a steering transaction that is in
progress.** In PostgreSQL READ COMMITTED, one statement reads one
snapshot. So the run status, the cancellation fields, the active
context, its responsible user and the pending flag are all from the same
committed state. Each interleaving with a steering writer gives a result
that a serial order also gives:

| Writer state when the statement runs | What the statement sees |
Result | Same as a serial order? |
| --- | --- | --- | --- |
| Reservation (`reserveSteeredIdentity`) not committed | Old active
context, no pending | Old identity, 200 | Yes: request before the
reservation. The old identity stays active until the steer is accepted.
|
| Reservation committed | Pending flag | Locked capture: 409, or accept
if acknowledged | Same code path as before |
| Acceptance in progress (pending committed) | Pending flag | Locked
capture waits for the acceptance, then returns the new identity | Same
code path as before |
| Acceptance committed | New active context, no pending | New identity |
Yes: request after the acceptance |
| Cancel or supersede committed | `cancelled`,
`executionCancellation.state = requested`, or
`freshContinuationSupersededAt` | 403 on a write | Yes, on the very next
request |

`activate()` writes `activeIdentityContextId` and `responsibleUserId` in
one update, and the statement joins the context by id and run id. So a
mix of an old context with a new user is not possible. The tests show
the first and third rows on real PostgreSQL.

### Notes for reviewers (moved from code comments)

- The two correlated subqueries in `requestRunIdentityFields` name
`"heartbeat_runs"` and an alias for `run_identity_contexts` in raw SQL.
Drizzle writes the columns of a one-table select without the table name,
so a `${heartbeatRuns.id}` inside the subquery would resolve to the
inner table. The first test run showed this (the identity came back
empty), and the statement-count test catches it.
- The `exists` condition in `loadResponsibleUserMemberships` keeps the
old rule: a membership counts only while its user exists.
- The legacy responsible-user value comes from the run read, because
that read has the same filter (`id`, `company_id`, `agent_id`) as the
removed legacy lookup.

## Verification

- New `server/src/__tests__/agent-jwt-request-authentication.test.ts`
(embedded PostgreSQL, real `actorMiddleware`,
`meterDatabaseStatements`):
- Statement count: 3 statements, 0 transactions, 3 waits for a running
agent with an active identity and a responsible user. Before: 13
statements. The test also checks that fewer than 8 KiB come back, with a
120 KB agent configuration.
- Revocation: a write that passes is refused on the very next request
after `status = cancelled`, after a Stop request
(`executionCancellation.state = requested`), and after a
fresh-continuation supersede (`agent_run_superseded`).
- Identity change between two requests: the next request uses the new
context and the new responsible user.
- Uncommitted steering reservation: the request does not wait, and keeps
the committed identity. After commit, the next request gets 409. After
the acknowledgement, the next request gets the new identity.
- Acceptance in progress: the request waits for it (locked capture),
then returns the new identity.
- Wrong claims: an agent token signed for another company gets 401. A
token that names another agent's run gets no identity from that run. An
active context id of another run is not used.
  - Pending steering without an acknowledgement still gets 409.
- Red/green: on `origin/master` code, the statement-count test failed
with 13 statements, and the uncommitted-reservation test failed because
the request was blocked on the row lock. Both pass with this change.
- `agent-auth-identity-transfer.test.ts`: the heartbeat_runs read count
is now exactly 1 (it was a lower bound of 3).
- These pass: `agent-auth-middleware.test.ts`,
`agent-auth-identity-transfer.test.ts`,
`agent-run-authentication.test.ts`, `run-identity.test.ts`.
- `pnpm verify`: it selected 2,639 of 3,459 Vitest files, because
`auth.ts` is imported by most route tests. That is close to the full
suite, so I stopped it at 30 minutes on this busy machine (exit 124, no
failures before the stop). CI supplies the broad coverage. The focused
checks above pass on the final revision (41 tests).
- `pnpm check:module-boundaries`: passed. Server `tsc --noEmit`: passed.
- Load model (`scripts/benchmark-agent-scaling-load.ts` from the plan
branch, not committed), `AGENTS=50 SECONDS=20`, one run at a time. The
machine had a load average of 25 to 33 from other work, so the timings
are noisy. The statement and transaction counts are not affected by the
noise.

| `SOURCES=api` | Before | After |
| --- | --- | --- |
| Statements/s (15 requests/s) | 165.7 | 30.1 |
| Statements per request (this model has no responsible user) | 11 | 2 |
| Transactions/s | 15.1 | 0 |
| Event-loop utilization | 0.741 | 0.252 |
| Event-loop delay p99 | 267.8 ms | 19.0 ms |
| API lateness p50 / p99 | 1104 / 5631 ms | 6.7 / 79 ms |

| All sources | Before | After |
| --- | --- | --- |
| API requests done | 300/300 | 300/300 |
| API lateness p50 / p99 | 291 / 1130 ms | 230 / 2681 ms |
| Delta appends done | 14977/20000 | 8260/20000 |

The all-sources run is limited by delta appends, which this PR does not
change. Its results move a lot between runs on this busy machine (the
delta count is lower after, with no change to that path), so it does not
show an effect of this PR in either direction.

## Risks

- The usual path no longer waits for a steering reservation that is in
progress. The request then uses the identity that is committed and
active. This is the identity that the run acts under until the steer is
accepted. The table above shows that each interleaving matches a serial
order.
- `loadAgentRunAuthentication` returns more columns (two small
correlated subqueries on `run_identity_contexts`, by primary key and by
the `(run_id, ...)` index). Other callers get extra fields and ignore
them.
- The JWT-first order depends on the stored key format. If a new key
format can contain three dot-separated base64url parts that verify as a
JWT, this order must be checked again.
- Low risk for routes: the actor object is the same, and no route
handler changes.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), by Anthropic, in Claude Code with
tool use (shell, file edits, test runs).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-13 12:38:01 -06:00
1 parent 16f00d62fb
commit c6b497d831
5 files changed
+311 -66

No files matched your search

@@ -63,7 +63,7 @@ const support = await getEmbeddedPostgresTestSupport();
} finally { capture.flush(); }
const reads = events.filter(event => event.event === "paperclip.test_db_response_capture.entry.v1"
&& event.table === "heartbeat_runs" && (event.operation === "select" || event.operation === "execute"));
expect(reads.reduce((sum, event) => sum + Number(event.calls), 0)).toBeGreaterThanOrEqual(3);
expect(reads.reduce((sum, event) => sum + Number(event.calls), 0)).toBe(1);
expect(reads.reduce((sum, event) => sum + Number(event.responseValueBytes), 0)).toBeLessThan(16_384);
expect((await captureRunIdentity(db, fixture)).run).toMatchObject(fixture.payloads);
});
@@ -0,0 +1,221 @@
import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import {
agents,
authUsers,
companies,
companyMemberships,
createDb,
heartbeatRunEvents,
heartbeatRuns,
issueComments,
issues,
runIdentityContexts,
} from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
import { createLocalAgentJwt } from "../agent-auth-jwt.js";
import { actorMiddleware } from "../middleware/auth.js";
import { errorHandler } from "../middleware/error-handler.js";
import { acceptSteeredIdentity, initializeRunIdentity, prepareSteeredIdentity, reserveSteeredIdentity } from "../services/run-identity.js";
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("agent JWT request authentication", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
let meter: ReturnType<typeof meterDatabaseStatements>;
beforeAll(async () => {
vi.stubEnv("PAPERCLIP_AGENT_JWT_SECRET", "request-authentication-test-secret");
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "default");
database = await startEmbeddedPostgresTestDatabase("paperclip-agent-jwt-request-auth-");
db = createDb(database.connectionString);
meter = meterDatabaseStatements(db, database.connectionString);
}, 30_000);
afterAll(async () => {
meter?.uninstall();
vi.unstubAllEnvs();
await db?.$client.end({ timeout: 5 });
await database?.cleanup();
}, 60_000);
async function addUser(companyId: string, userId: string) {
await db.insert(authUsers).values({ id: userId, name: userId, email: `${userId}@example.test`, emailVerified: true,
createdAt: new Date(), updatedAt: new Date() }).onConflictDoNothing();
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId,
status: "active", membershipRole: "owner" });
}
async function seed() {
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
const owner = `owner-${companyId.slice(0, 8)}`, next = `next-${companyId.slice(0, 8)}`;
await db.insert(companies).values({ id: companyId, name: "Request authentication", issuePrefix: companyId.slice(0, 8) });
await addUser(companyId, owner);
await addUser(companyId, next);
await db.insert(agents).values({ id: agentId, companyId, name: "Worker", role: "engineer", adapterType: "codex_local",
status: "running", adapterConfig: { instructions: "saved ".repeat(20_000) } });
await db.insert(issues).values({ id: issueId, companyId, title: "Request authentication task", responsibleUserId: owner });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", contextSnapshot: { issueId } });
const identity = await initializeRunIdentity(db, { companyId, runId, issueId, messageIds: [], responsibleUserId: owner,
cause: "instruction" });
const app = express();
app.use(actorMiddleware(db, { deploymentMode: "authenticated", resolveSession: async () => null }));
app.get("/actor", (req, res) => res.json(req.actor));
app.patch("/actor", (req, res) => res.json(req.actor));
app.use(errorHandler);
const token = createLocalAgentJwt(agentId, companyId, "codex_local", runId, "stale-claim-user")!;
expect(token).toBeTruthy();
return { companyId, agentId, issueId, runId, owner, next, identity, app, token };
}
type Fixture = Awaited<ReturnType<typeof seed>>;
const get = (f: Fixture, token = f.token) => request(f.app).get("/actor").set("Authorization", `Bearer ${token}`);
const patch = (f: Fixture, token = f.token) => request(f.app).patch("/actor").set("Authorization", `Bearer ${token}`);
it("authenticates a running agent with three statements and no transaction", async () => {
const f = await seed();
const before = meter.read();
meter.startLog();
const response = await get(f);
const log = meter.stopLog();
const after = meter.read();
expect(response.status).toBe(200);
expect(response.body).toMatchObject({
type: "agent", source: "agent_jwt", agentId: f.agentId, companyId: f.companyId, runId: f.runId,
identityContextId: f.identity.id, onBehalfOfUserId: f.owner,
onBehalfOfMemberships: [{ companyId: f.companyId, membershipRole: "owner", status: "active" }],
});
const statements = after.statements - before.statements;
expect({ statements, transactions: after.transactions - before.transactions, waits: after.waits - before.waits },
log.map(entry => entry.sql).join("\n---\n")).toEqual({ statements: 3, transactions: 0, waits: 3 });
expect(after.bytesReceived - before.bytesReceived).toBeLessThan(8_192);
});
it("refuses the very next write after the run is cancelled, stopped or superseded", async () => {
const cases: Array<{ revoke: Partial<typeof heartbeatRuns.$inferInsert>; code: string }> = [
{ revoke: { status: "cancelled" }, code: "agent_run_cancelled" },
{ revoke: { resultJson: { executionCancellation: { state: "requested" } } }, code: "agent_run_cancelled" },
{ revoke: { resultJson: { freshContinuationSupersededAt: new Date().toISOString() } }, code: "agent_run_superseded" },
];
for (const { revoke, code } of cases) {
const f = await seed();
expect((await patch(f)).status).toBe(200);
await db.update(heartbeatRuns).set(revoke).where(eq(heartbeatRuns.id, f.runId));
const refused = await patch(f);
expect(refused.status).toBe(403);
expect(refused.body.code).toBe(code);
}
});
it("uses the new responsible user on the request after steering is accepted", async () => {
const f = await seed();
expect((await get(f)).body).toMatchObject({ identityContextId: f.identity.id, onBehalfOfUserId: f.owner });
const messageId = randomUUID();
await db.insert(issueComments).values({ id: messageId, companyId: f.companyId, issueId: f.issueId,
authorUserId: f.next, body: "Next instruction" });
const pending = (await reserveSteeredIdentity(db, { ...f, messageId }))!;
await db.transaction(tx => acceptSteeredIdentity(tx as never, pending));
const second = await get(f);
expect(second.status).toBe(200);
expect(second.body).toMatchObject({ identityContextId: pending.id, onBehalfOfUserId: f.next });
});
function holdOpen(f: Fixture, work: (tx: Parameters<Parameters<typeof db.transaction>[0]>[0]) => Promise<unknown>) {
let release!: () => void;
const released = new Promise<void>(resolve => { release = resolve; });
let ready!: () => void;
const locked = new Promise<void>(resolve => { ready = resolve; });
const done = db.transaction(async tx => {
await tx.select({ id: issues.id }).from(issues).where(eq(issues.id, f.issueId)).for("no key update");
await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)).for("no key update");
await work(tx);
ready();
await released;
});
const holding = Promise.race([locked, done.then(() => undefined)]);
return { holding, release, done };
}
const settledWithin = <T,>(promise: Promise<T>, ms: number) =>
Promise.race([promise, new Promise<"pending">(resolve => setTimeout(() => resolve("pending"), ms))]);
async function acknowledge(f: Fixture, messageId: string) {
await db.insert(heartbeatRunEvents).values({ companyId: f.companyId, agentId: f.agentId, runId: f.runId,
seq: 1, eventType: "item.completed", sourceEventId: randomUUID(),
payload: { prpEvent: { turnId: "auth-turn", itemId: `auth-turn:steer:${messageId}`,
payload: { kind: "steering_acknowledgement" } } } });
}
it("does not wait on an uncommitted steering reservation and holds the next request until it is acknowledged", async () => {
const f = await seed();
const messageId = randomUUID();
await db.insert(issueComments).values({ id: messageId, companyId: f.companyId, issueId: f.issueId,
authorUserId: f.next, body: "Concurrent instruction" });
let pendingId = "";
const writer = holdOpen(f, async tx => {
pendingId = (await prepareSteeredIdentity(tx as never, { ...f, messageId })).id;
});
await writer.holding;
try {
const during = await settledWithin(get(f), 3_000);
expect(during).not.toBe("pending");
expect((during as request.Response).status).toBe(200);
expect((during as request.Response).body).toMatchObject({ identityContextId: f.identity.id, onBehalfOfUserId: f.owner });
} finally {
writer.release();
await writer.done;
}
expect((await get(f)).status).toBe(409);
await acknowledge(f, messageId);
expect((await get(f)).body).toMatchObject({ identityContextId: pendingId, onBehalfOfUserId: f.next });
});
it("waits for an acceptance in flight and returns the identity it commits", async () => {
const f = await seed();
const messageId = randomUUID();
await db.insert(issueComments).values({ id: messageId, companyId: f.companyId, issueId: f.issueId,
authorUserId: f.next, body: "Accepted instruction" });
const pending = (await reserveSteeredIdentity(db, { ...f, messageId }))!;
const writer = holdOpen(f, tx => acceptSteeredIdentity(tx as never, pending));
await writer.holding;
const response = get(f).then(result => result);
try {
expect(await settledWithin(response, 500)).toBe("pending");
} finally {
writer.release();
await writer.done;
}
expect((await response).body).toMatchObject({ identityContextId: pending.id, onBehalfOfUserId: f.next });
});
it("keeps the identity of the run the token names, in the company and for the agent it names", async () => {
const f = await seed();
const other = await seed();
const crossCompany = createLocalAgentJwt(other.agentId, f.companyId, "codex_local", other.runId, f.owner)!;
expect((await get(f, crossCompany)).status).toBe(401);
const foreignRun = createLocalAgentJwt(f.agentId, f.companyId, "codex_local", other.runId, null)!;
const foreign = await get(f, foreignRun);
expect(foreign.status).toBe(200);
expect(foreign.body).toMatchObject({ runId: other.runId, identityContextId: null, onBehalfOfUserId: null,
onBehalfOfMemberships: [] });
await db.update(heartbeatRuns).set({ activeIdentityContextId: other.identity.id }).where(eq(heartbeatRuns.id, f.runId));
const mismatched = await get(f);
expect(mismatched.body).toMatchObject({ identityContextId: null, onBehalfOfUserId: "stale-claim-user" });
const [context] = await db.select().from(runIdentityContexts).where(eq(runIdentityContexts.id, other.identity.id));
expect(context.runId).toBe(other.runId);
});
it("still settles a pending steering identity through the locked capture", async () => {
const f = await seed();
const messageId = randomUUID();
await db.insert(issueComments).values({ id: messageId, companyId: f.companyId, issueId: f.issueId,
authorUserId: f.next, body: "Pending instruction" });
await reserveSteeredIdentity(db, { ...f, messageId });
expect((await get(f)).status).toBe(409);
});
});
@@ -1,5 +1,6 @@
import { and, eq, sql } from "drizzle-orm";
import { heartbeatRuns, type Db } from "@paperclipai/db";
import { requestRunIdentityFields } from "../services/run-identity.js";
export function loadAgentRunAuthentication(db: Db, input: {
runId: string;
@@ -19,6 +20,7 @@ export function loadAgentRunAuthentication(db: Db, input: {
contextSnapshot: sql<Record<string, unknown>>`jsonb_build_object(
'conversationMode', ${heartbeatRuns.contextSnapshot}->'conversationMode'
)`,
...requestRunIdentityFields,
}).from(heartbeatRuns).where(and(
eq(heartbeatRuns.id, input.runId),
eq(heartbeatRuns.companyId, input.companyId),
+35 -59
View File
@@ -2,7 +2,7 @@ import { notifyMuseContactVerification } from "../modules/external-agents/index.
import { idleApiActivity } from "../services/idle-api-activity.js";
import { createHash, timingSafeEqual } from "node:crypto";
import type { Request, RequestHandler } from "express";
import { and, eq, isNull, sql } from "drizzle-orm";
import { and, eq, exists, isNull, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
activityLog,
@@ -29,7 +29,7 @@ import { isUuidLike, normalizeAgentApiKeyScope, type DeploymentMode } from "@pap
import type { BetterAuthSessionResult } from "../auth/better-auth.js";
import { logger } from "./logger.js";
import { localAgentProcessBoundary, type LocalAgentProcessBoundary } from "./local-agent-process-boundary.js";
import { captureRunIdentity } from "../services/run-identity.js";
import { resolveRequestRunIdentity } from "../services/run-identity.js";
import { boardAuthService } from "../services/board-auth.js";
import { retryIdempotentDatabaseOperation } from "../database-retry.js";
import { beginIdleTrackedWork } from "../services/task-admission.js";
@@ -70,53 +70,33 @@ function invalidAgentTokenMessage(token: string) {
return "Agent token did not verify; obtain fresh credentials and retry";
}
async function resolveLegacyRunResponsibleUserId(
db: Db,
input: { companyId: string; agentId: string; runId: string },
) {
if (!isUuidLike(input.runId)) return null;
const run = await db
.select({ responsibleUserId: heartbeatRuns.responsibleUserId })
.from(heartbeatRuns)
.where(
and(
eq(heartbeatRuns.id, input.runId),
eq(heartbeatRuns.companyId, input.companyId),
eq(heartbeatRuns.agentId, input.agentId),
),
)
.then((rows) => rows[0] ?? null);
return normalizeOptionalString(run?.responsibleUserId);
}
const agentAuthenticationFields = {
companyId: agents.companyId,
status: agents.status,
lifecycleHolds: agents.lifecycleHolds,
};
async function loadResponsibleUserMemberships(
db: Db,
input: { companyId: string; userId: string | null },
) {
if (!input.userId) return [];
const [user, memberships] = await Promise.all([
db
.select({ id: authUsers.id })
.from(authUsers)
.where(eq(authUsers.id, input.userId))
.then((rows) => rows[0] ?? null),
db
.select({
companyId: companyMemberships.companyId,
membershipRole: companyMemberships.membershipRole,
status: companyMemberships.status,
})
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, input.companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, input.userId),
eq(companyMemberships.status, "active"),
),
return db
.select({
companyId: companyMemberships.companyId,
membershipRole: companyMemberships.membershipRole,
status: companyMemberships.status,
})
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, input.companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, input.userId),
eq(companyMemberships.status, "active"),
exists(db.select({ id: authUsers.id }).from(authUsers).where(eq(authUsers.id, input.userId))),
),
]);
return user ? memberships : [];
);
}
/**
@@ -323,7 +303,8 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
return;
}
const boardKey = await boardAuth.findBoardApiKeyByToken(token);
const verifiedClaims = verifyLocalAgentJwt(token);
const boardKey = verifiedClaims ? null : await boardAuth.findBoardApiKeyByToken(token);
if (boardKey) {
const access = await boardAuth.resolveBoardAccess(boardKey.userId);
if (access.user) {
@@ -348,22 +329,21 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
}
}
const tokenHash = hashToken(token);
const key = await db
const key = verifiedClaims ? null : await db
.select()
.from(agentApiKeys)
.where(and(eq(agentApiKeys.keyHash, tokenHash), isNull(agentApiKeys.revokedAt)))
.where(and(eq(agentApiKeys.keyHash, hashToken(token)), isNull(agentApiKeys.revokedAt)))
.then((rows) => rows[0] ?? null);
if (!key) {
const claims = verifyLocalAgentJwt(token);
const claims = verifiedClaims;
if (!claims) {
next(unauthorized(invalidAgentTokenMessage(token)));
return;
}
const agentRecord = await db
.select()
.select(agentAuthenticationFields)
.from(agents)
.where(eq(agents.id, claims.sub))
.then((rows) => rows[0] ?? null);
@@ -422,11 +402,9 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
code: conversation ? "conversation_turn_cancelled" : "agent_run_cancelled" });
return;
}
if (identityRun?.activeIdentityContextId && identityRun.status === "running") {
const captured = await captureRunIdentity(db, { companyId: claims.company_id, agentId: claims.sub, runId: claims.run_id },
{ readScope: "request_authentication" });
identityRun.activeIdentityContextId = captured.context?.id ?? null;
identityRun.responsibleUserId = captured.context?.responsibleUserId ?? null;
if (identityRun) {
Object.assign(identityRun, await resolveRequestRunIdentity(db,
{ companyId: claims.company_id, agentId: claims.sub, runId: claims.run_id }, identityRun));
}
if (claims.authorizing_user_id) {
// This signed projection exists only for internal native tools. Recheck
@@ -455,11 +433,9 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
? identityRun.responsibleUserId
: claims.responsible_user_id !== undefined
? normalizeOptionalString(claims.responsible_user_id)
: await resolveLegacyRunResponsibleUserId(db, {
companyId: claims.company_id,
agentId: claims.sub,
runId: claims.run_id,
});
: isUuidLike(claims.run_id)
? normalizeOptionalString(identityRun?.responsibleUserId)
: null;
const onBehalfOfMemberships = await loadResponsibleUserMemberships(db, {
companyId: claims.company_id,
userId: onBehalfOfUserId,
@@ -488,7 +464,7 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
.where(eq(agentApiKeys.id, key.id));
const agentRecord = await db
.select()
.select(agentAuthenticationFields)
.from(agents)
.where(eq(agents.id, key.agentId))
.then((rows) => rows[0] ?? null);
+52 -6
View File
@@ -76,6 +76,20 @@ export async function explicitOperatorRunIdentity(
}
export type RunIdentityContext = typeof runIdentityContexts.$inferSelect;
function assertRunTaskIdentity(run: {
nativeIssueId?: string | null;
issueId?: string | null;
contextSnapshot?: Record<string, unknown> | null;
} | undefined) {
const issueId = run?.nativeIssueId ?? run?.issueId ?? run?.contextSnapshot?.issueId ?? run?.contextSnapshot?.taskId;
const legacyIssueId = run?.contextSnapshot?.issueId ?? run?.contextSnapshot?.taskId;
if ([issueId, legacyIssueId].some(id => id !== undefined && id !== null &&
(typeof id !== "string" || !isUuidLike(id)))) {
throw forbidden("Run task identity is invalid");
}
return issueId;
}
type Executor = Pick<Db, "select" | "insert" | "update">;
/**
@@ -100,12 +114,7 @@ async function lockIdentityTask(
.where(
and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId)),
);
const issueId = run?.nativeIssueId ?? run?.issueId ?? run?.contextSnapshot?.issueId ?? run?.contextSnapshot?.taskId;
const legacyIssueId = run?.contextSnapshot?.issueId ?? run?.contextSnapshot?.taskId;
if ([issueId, legacyIssueId].some(id => id !== undefined && id !== null &&
(typeof id !== "string" || !isUuidLike(id)))) {
throw forbidden("Run task identity is invalid");
}
const issueId = assertRunTaskIdentity(run);
if (typeof issueId === "string")
await executor
.select({ id: issues.id })
@@ -614,6 +623,43 @@ export async function captureRunIdentity<Scope extends RunIdentityReadScope | un
});
}
export const requestRunIdentityFields = {
nativeIssueId: heartbeatRuns.nativeIssueId,
issueId: heartbeatRuns.issueId,
taskContext: runTaskContextColumn,
pendingIdentityContext: sql<boolean>`exists (select 1 from run_identity_contexts pending_context
where pending_context.run_id = "heartbeat_runs"."id" and pending_context.status = 'pending')`,
identityContext: sql<{ id: string; responsibleUserId: string | null } | null>`(select
jsonb_build_object('id', active_context.id, 'responsibleUserId', active_context.responsible_user_id)
from run_identity_contexts active_context
where active_context.id = "heartbeat_runs"."active_identity_context_id"
and active_context.run_id = "heartbeat_runs"."id")`,
};
type RequestRunIdentityRow = Pick<FullIdentityRun, "status" | "activeIdentityContextId" | "responsibleUserId"> & {
nativeIssueId?: string | null;
issueId?: string | null;
taskContext?: Record<string, unknown> | null;
pendingIdentityContext?: boolean | null;
identityContext?: { id: string; responsibleUserId: string | null } | null;
};
export async function resolveRequestRunIdentity(
db: Db,
input: { companyId: string; runId: string; agentId: string },
run: RequestRunIdentityRow,
): Promise<{ activeIdentityContextId: string | null; responsibleUserId: string | null }> {
if (!run.activeIdentityContextId || run.status !== "running") {
return { activeIdentityContextId: run.activeIdentityContextId, responsibleUserId: run.responsibleUserId };
}
if (run.pendingIdentityContext) {
const captured = await captureRunIdentity(db, input, { readScope: "request_authentication" });
return { activeIdentityContextId: captured.context?.id ?? null, responsibleUserId: captured.context?.responsibleUserId ?? null };
}
assertRunTaskIdentity({ nativeIssueId: run.nativeIssueId, issueId: run.issueId, contextSnapshot: run.taskContext });
return { activeIdentityContextId: run.identityContext?.id ?? null, responsibleUserId: run.identityContext?.responsibleUserId ?? null };
}
export async function listRunIdentityContexts(
db: Db,
companyId: string,