mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 20:12:20 +01:00
## 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>
1027 lines
39 KiB
TypeScript
1027 lines
39 KiB
TypeScript
import { notifyMuseContactVerification } from "../modules/external-agents/index.js";
|
|
import { idleApiActivity } from "../services/idle-api-activity.js";
|
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
import type { Request, RequestHandler } from "express";
|
|
import { and, eq, exists, isNull, sql } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import {
|
|
activityLog,
|
|
agentApiKeys,
|
|
agents,
|
|
authUsers,
|
|
companies,
|
|
companyMemberships,
|
|
heartbeatRuns,
|
|
instanceUserRoles,
|
|
} from "@paperclipai/db";
|
|
import {
|
|
MAX_ISSUE_PREFIX_ATTEMPTS,
|
|
deriveIssuePrefixBase,
|
|
isIssuePrefixConflict,
|
|
issuePrefixSuffixForAttempt,
|
|
pickAvailableIssuePrefix,
|
|
rekeyCompanyIssueIdentifiers,
|
|
} from "../services/issue-prefix.js";
|
|
import { verifyLocalAgentJwt } from "../agent-auth-jwt.js";
|
|
import { agentRunSupersededByFreshContinuation, agentRunWritesRevoked } from "../agent-run-cancellation.js";
|
|
import { loadAgentRunAuthentication } from "./agent-run-authentication.js";
|
|
import { isUuidLike, normalizeAgentApiKeyScope, type DeploymentMode } from "@paperclipai/shared";
|
|
import type { BetterAuthSessionResult } from "../auth/better-auth.js";
|
|
import { logger } from "./logger.js";
|
|
import { localAgentProcessBoundary, type LocalAgentProcessBoundary } from "./local-agent-process-boundary.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";
|
|
import { notifyChatCompanyAuthorityChange } from "../services/chat-run-milestone-notifications.js";
|
|
|
|
export {
|
|
isTransientDbConnectionError,
|
|
retryIdempotentDatabaseOperation as retryOnTransientDbConnectionError,
|
|
} from "../database-retry.js";
|
|
|
|
import { syncCloudTenantWrites } from "./cloud-tenant-sync.js";
|
|
import { resolveOwnerInstanceAdmin } from "../services/cloud-tenant-authority.js";
|
|
import { ensureHumanRoleDefaultGrants } from "../services/principal-access-compatibility.js";
|
|
import { forbidden, unauthorized, unprocessable } from "../errors.js";
|
|
|
|
export { isCloudManagedInstance } from "../services/cloud-instance.js";
|
|
import { cloudTenantPrimaryCompanyId, isCloudManagedInstance } from "../services/cloud-instance.js";
|
|
|
|
function hashToken(token: string) {
|
|
return createHash("sha256").update(token).digest("hex");
|
|
}
|
|
|
|
function normalizeOptionalString(value: string | null | undefined) {
|
|
return value?.trim() || null;
|
|
}
|
|
|
|
function invalidAgentTokenMessage(token: string) {
|
|
try {
|
|
const payload = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8")) as {
|
|
exp?: unknown;
|
|
};
|
|
if (typeof payload.exp === "number" && payload.exp <= Math.floor(Date.now() / 1000)) {
|
|
return "Expired agent token; obtain fresh credentials and retry";
|
|
}
|
|
} catch {
|
|
// Malformed and incorrectly signed tokens share the generic failure below.
|
|
}
|
|
return "Agent token did not verify; obtain fresh credentials and retry";
|
|
}
|
|
|
|
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 [];
|
|
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))),
|
|
),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* The user's own active company memberships — the exact company scope a
|
|
* locally authenticated session actor carries. Shared by the session path
|
|
* and the Cloud trusted-header path so both resolve the same access set.
|
|
*/
|
|
async function loadActiveUserCompanyMemberships(db: Db, userId: string) {
|
|
return db
|
|
.select({
|
|
companyId: companyMemberships.companyId,
|
|
membershipRole: companyMemberships.membershipRole,
|
|
status: companyMemberships.status,
|
|
})
|
|
.from(companyMemberships)
|
|
.where(
|
|
and(
|
|
eq(companyMemberships.principalType, "user"),
|
|
eq(companyMemberships.principalId, userId),
|
|
eq(companyMemberships.status, "active"),
|
|
),
|
|
);
|
|
}
|
|
|
|
async function auditAgentJwtRunHeaderMismatch(
|
|
db: Db,
|
|
input: { companyId: string; agentId: string; claimRunId: string; headerRunId: string; method: string; url: string },
|
|
) {
|
|
try {
|
|
// The claimed run id is untrusted input from a rejected token. activity_log
|
|
// .run_id is a real FK to heartbeat_runs, so writing it unconditionally
|
|
// makes the insert fail — and the catch swallows it — exactly when the
|
|
// claim is bogus. Keep the claim in entityId/details and populate the FK
|
|
// column only when the row actually exists.
|
|
const claimedRunExists = isUuidLike(input.claimRunId)
|
|
? await db
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, input.claimRunId))
|
|
.then((rows) => rows.length > 0)
|
|
: false;
|
|
await db.insert(activityLog).values({
|
|
companyId: input.companyId,
|
|
actorType: "agent",
|
|
actorId: input.agentId,
|
|
action: "auth.agent_jwt_run_header_mismatch",
|
|
entityType: "heartbeat_run",
|
|
entityId: input.claimRunId,
|
|
...(isUuidLike(input.agentId) ? { agentId: input.agentId } : {}),
|
|
...(claimedRunExists ? { runId: input.claimRunId } : {}),
|
|
details: {
|
|
claimRunId: input.claimRunId,
|
|
headerRunId: input.headerRunId,
|
|
method: input.method,
|
|
url: input.url,
|
|
},
|
|
});
|
|
} catch (err) {
|
|
logger.warn(
|
|
{ err, companyId: input.companyId, agentId: input.agentId, claimRunId: input.claimRunId },
|
|
"Failed to audit rejected agent JWT run header mismatch",
|
|
);
|
|
}
|
|
}
|
|
|
|
async function auditAgentKeyMissingResponsibleUser(
|
|
db: Db,
|
|
input: { companyId: string; agentId: string; keyId: string; method: string; url: string },
|
|
) {
|
|
try {
|
|
await db.insert(activityLog).values({
|
|
companyId: input.companyId,
|
|
actorType: "agent",
|
|
actorId: input.agentId,
|
|
action: "auth.agent_key_missing_responsible_user",
|
|
entityType: "agent_api_key",
|
|
entityId: input.keyId,
|
|
...(isUuidLike(input.agentId) ? { agentId: input.agentId } : {}),
|
|
details: {
|
|
method: input.method,
|
|
url: input.url,
|
|
},
|
|
});
|
|
} catch (err) {
|
|
logger.warn(
|
|
{ err, companyId: input.companyId, agentId: input.agentId, keyId: input.keyId },
|
|
"Failed to audit rejected agent key without responsible user binding",
|
|
);
|
|
}
|
|
}
|
|
|
|
interface ActorMiddlewareOptions {
|
|
deploymentMode: DeploymentMode;
|
|
resolveSession?: (req: Request) => Promise<BetterAuthSessionResult | null>;
|
|
localAgentProcessBoundary?: LocalAgentProcessBoundary | null;
|
|
}
|
|
|
|
const publicRoutineWebhookPath = /^\/api\/routine-triggers\/public\/[a-f0-9]{24}\/fire\/?$/i;
|
|
|
|
const publicMcpGatewayProtocolPath = /^\/mcp\/gateways\/gw_[a-f0-9]{32}\/?$/i;
|
|
|
|
export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHandler {
|
|
const boardAuth = boardAuthService(db);
|
|
const localBoundary = opts.deploymentMode === "local_trusted"
|
|
? opts.localAgentProcessBoundary === undefined ? localAgentProcessBoundary() : opts.localAgentProcessBoundary
|
|
: null;
|
|
const authenticate: RequestHandler = async (req, _res, next) => {
|
|
req.actor =
|
|
opts.deploymentMode === "local_trusted"
|
|
? {
|
|
type: "board",
|
|
userId: "local-board",
|
|
userName: "Local Board",
|
|
userEmail: null,
|
|
isInstanceAdmin: true,
|
|
source: "local_implicit",
|
|
}
|
|
: { type: "none", source: "none" };
|
|
|
|
// Routine ingress authenticates its own bearer/signature. Never interpret
|
|
// webhook credentials as agent keys or attach an ambient browser session.
|
|
if (req.method === "POST" && publicRoutineWebhookPath.test(req.path)) {
|
|
req.actor = { type: "none", source: "none" };
|
|
next();
|
|
return;
|
|
}
|
|
|
|
const runIdHeader = req.header("x-paperclip-run-id");
|
|
|
|
const authHeader = req.header("authorization");
|
|
const hasBearerCredentials = /^bearer(?:\s|$)/i.test(authHeader ?? "");
|
|
|
|
// Public MCP gateway protocol requests carry a pcgw_* bearer that is
|
|
// validated by the gateway service itself. Do not interpret that bearer as
|
|
// a board key or agent JWT here: doing so rejects the MCP handshake before
|
|
// the protocol route can verify its run-scoped credential. Keep this bypass
|
|
// restricted to the unguessable public gateway path; all /api routes retain
|
|
// the normal actor authentication path below.
|
|
if (hasBearerCredentials && publicMcpGatewayProtocolPath.test(req.path)) {
|
|
if (runIdHeader) req.actor.runId = runIdHeader;
|
|
next();
|
|
return;
|
|
}
|
|
|
|
if (!hasBearerCredentials) {
|
|
if (opts.deploymentMode === "authenticated" && opts.resolveSession) {
|
|
const cloudTenantActor = await resolveCloudTenantActor(db, req);
|
|
if (cloudTenantActor) {
|
|
req.actor = {
|
|
...cloudTenantActor,
|
|
runId: runIdHeader ?? undefined,
|
|
};
|
|
next();
|
|
return;
|
|
}
|
|
|
|
let session: BetterAuthSessionResult | null = null;
|
|
try {
|
|
session = await opts.resolveSession(req);
|
|
} catch (err) {
|
|
logger.warn(
|
|
{ err, method: req.method, url: req.originalUrl },
|
|
"Failed to resolve auth session from request headers",
|
|
);
|
|
}
|
|
if (session?.user?.id && session.session?.id) {
|
|
const userId = session.user.id;
|
|
const [roleRow, memberships] = await Promise.all([
|
|
db
|
|
.select({ id: instanceUserRoles.id })
|
|
.from(instanceUserRoles)
|
|
.where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
|
|
.then((rows) => rows[0] ?? null),
|
|
loadActiveUserCompanyMemberships(db, userId),
|
|
]);
|
|
req.actor = {
|
|
type: "board",
|
|
userId,
|
|
sessionId: session.session.id,
|
|
userName: session.user.name ?? null,
|
|
userEmail: session.user.email ?? null,
|
|
companyIds: memberships.map((row) => row.companyId),
|
|
memberships,
|
|
isInstanceAdmin: Boolean(roleRow),
|
|
runId: runIdHeader ?? undefined,
|
|
source: "session",
|
|
};
|
|
next();
|
|
return;
|
|
}
|
|
}
|
|
if (req.actor.source === "local_implicit"
|
|
&& !(await localBoundary?.grantsImplicitBoard(req.socket))) {
|
|
req.actor = { type: "none", source: "none" };
|
|
}
|
|
if (runIdHeader) req.actor.runId = runIdHeader;
|
|
next();
|
|
return;
|
|
}
|
|
|
|
const token = authHeader!.slice("bearer".length).trim();
|
|
if (!token) {
|
|
next(unauthorized("Empty bearer token; provide valid agent credentials and retry"));
|
|
return;
|
|
}
|
|
|
|
const verifiedClaims = verifyLocalAgentJwt(token);
|
|
const boardKey = verifiedClaims ? null : await boardAuth.findBoardApiKeyByToken(token);
|
|
if (boardKey) {
|
|
const access = await boardAuth.resolveBoardAccess(boardKey.userId);
|
|
if (access.user) {
|
|
await boardAuth.touchBoardApiKey(boardKey.id);
|
|
req.actor = {
|
|
type: "board",
|
|
userId: boardKey.userId,
|
|
userName: access.user?.name ?? null,
|
|
userEmail: access.user?.email ?? null,
|
|
companyIds: access.companyIds,
|
|
memberships: access.memberships,
|
|
isInstanceAdmin: access.isInstanceAdmin,
|
|
keyId: boardKey.id,
|
|
runId: runIdHeader || undefined,
|
|
source: "board_key",
|
|
};
|
|
if (isCloudManagedInstance() && (access.isInstanceAdmin || access.companyIds.length)) {
|
|
_res.once("finish", () => { if (_res.statusCode >= 200 && _res.statusCode < 400) idleApiActivity.record(); });
|
|
}
|
|
next();
|
|
return;
|
|
}
|
|
}
|
|
|
|
const key = verifiedClaims ? null : await db
|
|
.select()
|
|
.from(agentApiKeys)
|
|
.where(and(eq(agentApiKeys.keyHash, hashToken(token)), isNull(agentApiKeys.revokedAt)))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
if (!key) {
|
|
const claims = verifiedClaims;
|
|
if (!claims) {
|
|
next(unauthorized(invalidAgentTokenMessage(token)));
|
|
return;
|
|
}
|
|
|
|
const agentRecord = await db
|
|
.select(agentAuthenticationFields)
|
|
.from(agents)
|
|
.where(eq(agents.id, claims.sub))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
if (!agentRecord || agentRecord.companyId !== claims.company_id) {
|
|
next(unauthorized("Agent record is missing or belongs to another company; obtain fresh credentials and retry"));
|
|
return;
|
|
}
|
|
|
|
if (agentRecord.lifecycleHolds?.includes("setup")) {
|
|
next(unauthorized("Agent setup is incomplete and cannot authenticate"));
|
|
return;
|
|
}
|
|
if (agentRecord.status === "terminated") {
|
|
next(unauthorized("Agent is terminated and cannot authenticate"));
|
|
return;
|
|
}
|
|
if (agentRecord.status === "pending_approval") {
|
|
next(unauthorized("Agent is pending approval and cannot authenticate"));
|
|
return;
|
|
}
|
|
|
|
const normalizedRunIdHeader = normalizeOptionalString(runIdHeader);
|
|
if (normalizedRunIdHeader && normalizedRunIdHeader !== claims.run_id) {
|
|
await auditAgentJwtRunHeaderMismatch(db, {
|
|
companyId: claims.company_id,
|
|
agentId: claims.sub,
|
|
claimRunId: claims.run_id,
|
|
headerRunId: normalizedRunIdHeader,
|
|
method: req.method,
|
|
url: req.originalUrl,
|
|
});
|
|
next(
|
|
unprocessable("X-Paperclip-Run-Id does not match signed agent JWT run_id", {
|
|
code: "agent_jwt_run_id_mismatch",
|
|
claimRunId: claims.run_id,
|
|
headerRunId: normalizedRunIdHeader,
|
|
}),
|
|
);
|
|
return;
|
|
}
|
|
|
|
const [identityRun] = await loadAgentRunAuthentication(db, {
|
|
runId: claims.run_id,
|
|
companyId: claims.company_id,
|
|
agentId: claims.sub,
|
|
});
|
|
if (agentRunWritesRevoked(identityRun)
|
|
&& !["GET", "HEAD", "OPTIONS"].includes(req.method)) {
|
|
const conversation = identityRun?.contextSnapshot?.conversationMode === true;
|
|
if (agentRunSupersededByFreshContinuation(identityRun)) {
|
|
_res.status(403).json({ error: "A newer run continues this task. End the turn.", code: "agent_run_superseded" });
|
|
return;
|
|
}
|
|
_res.status(403).json({ error: conversation ? "This conversation turn was cancelled" : "This run was cancelled",
|
|
code: conversation ? "conversation_turn_cancelled" : "agent_run_cancelled" });
|
|
return;
|
|
}
|
|
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
|
|
// the admitted run and current immutable binding on every API call.
|
|
try {
|
|
const { parseNativeExecutionInput } = await import("../vendor/paperclip-runner/index.js");
|
|
const { museRunnerBroker } = await import("../services/muse-runner-broker.js");
|
|
const [nativeRun] = await db.select({ status: heartbeatRuns.status, runtimeMode: heartbeatRuns.runtimeMode,
|
|
nativeExecutionInput: sql<unknown>`${heartbeatRuns.runnerProfileJson}->'nativeExecutionInput'`,
|
|
}).from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.id, claims.run_id), eq(heartbeatRuns.companyId, claims.company_id), eq(heartbeatRuns.agentId, claims.sub),
|
|
));
|
|
const execution = parseNativeExecutionInput(nativeRun?.nativeExecutionInput);
|
|
if (nativeRun?.status !== "running" || nativeRun.runtimeMode !== "native" || execution.schema !== "paperclip.native-execution-input.v8"
|
|
|| execution.binding.runId !== claims.run_id || execution.binding.agentId !== claims.sub || execution.binding.companyId !== claims.company_id
|
|
|| await museRunnerBroker(db).authorizingUserIdForBinding(execution.provider.binding) !== claims.authorizing_user_id) {
|
|
throw new Error("Muse internal tool authority mismatch");
|
|
}
|
|
await museRunnerBroker(db).assertRunAuthority(execution);
|
|
} catch {
|
|
_res.status(403).json({ error: "Muse native tool authority is unavailable" });
|
|
return;
|
|
}
|
|
}
|
|
const onBehalfOfUserId = identityRun?.activeIdentityContextId
|
|
? identityRun.responsibleUserId
|
|
: claims.responsible_user_id !== undefined
|
|
? normalizeOptionalString(claims.responsible_user_id)
|
|
: isUuidLike(claims.run_id)
|
|
? normalizeOptionalString(identityRun?.responsibleUserId)
|
|
: null;
|
|
const onBehalfOfMemberships = await loadResponsibleUserMemberships(db, {
|
|
companyId: claims.company_id,
|
|
userId: onBehalfOfUserId,
|
|
});
|
|
|
|
req.actor = {
|
|
type: "agent",
|
|
agentId: claims.sub,
|
|
companyId: claims.company_id,
|
|
keyId: undefined,
|
|
keyScope: normalizeAgentApiKeyScope(claims.key_scope),
|
|
runId: claims.run_id,
|
|
onBehalfOfUserId,
|
|
...(claims.authorizing_user_id ? { authorizingUserId: claims.authorizing_user_id } : {}),
|
|
identityContextId: identityRun?.activeIdentityContextId ?? null,
|
|
onBehalfOfMemberships,
|
|
source: "agent_jwt",
|
|
};
|
|
next();
|
|
return;
|
|
}
|
|
|
|
await db
|
|
.update(agentApiKeys)
|
|
.set({ lastUsedAt: new Date() })
|
|
.where(eq(agentApiKeys.id, key.id));
|
|
|
|
const agentRecord = await db
|
|
.select(agentAuthenticationFields)
|
|
.from(agents)
|
|
.where(eq(agents.id, key.agentId))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
if (!agentRecord || agentRecord.companyId !== key.companyId) {
|
|
next(unauthorized("Agent record is missing or belongs to another company; obtain fresh credentials and retry"));
|
|
return;
|
|
}
|
|
if (agentRecord.lifecycleHolds?.includes("setup")) {
|
|
next(unauthorized("Agent setup is incomplete and cannot authenticate"));
|
|
return;
|
|
}
|
|
if (agentRecord.status === "terminated") {
|
|
next(unauthorized("Agent is terminated and cannot authenticate"));
|
|
return;
|
|
}
|
|
if (agentRecord.status === "pending_approval") {
|
|
next(unauthorized("Agent is pending approval and cannot authenticate"));
|
|
return;
|
|
}
|
|
|
|
const responsibleUserId = normalizeOptionalString(key.responsibleUserId);
|
|
if (!responsibleUserId) {
|
|
await auditAgentKeyMissingResponsibleUser(db, {
|
|
companyId: key.companyId,
|
|
agentId: key.agentId,
|
|
keyId: key.id,
|
|
method: req.method,
|
|
url: req.originalUrl,
|
|
});
|
|
next(forbidden("Responsible user is unavailable for this agent key", {
|
|
code: "RESPONSIBLE_USER_UNAVAILABLE",
|
|
}));
|
|
return;
|
|
}
|
|
|
|
req.actor = {
|
|
type: "agent",
|
|
agentId: key.agentId,
|
|
companyId: key.companyId,
|
|
keyId: key.id,
|
|
keyScope: normalizeAgentApiKeyScope(key.scopeConfig),
|
|
onBehalfOfUserId: responsibleUserId,
|
|
onBehalfOfMemberships: await loadResponsibleUserMemberships(db, {
|
|
companyId: key.companyId,
|
|
userId: responsibleUserId,
|
|
}),
|
|
runId: runIdHeader || undefined,
|
|
source: "agent_key",
|
|
};
|
|
if (isCloudManagedInstance() && req.actor.onBehalfOfMemberships?.length) {
|
|
_res.once("finish", () => { if (_res.statusCode >= 200 && _res.statusCode < 400) idleApiActivity.record(); });
|
|
}
|
|
next();
|
|
};
|
|
return async (req, res, next) => {
|
|
// Health and task-drain requests bypass tenant admission, but resolving
|
|
// their actor can still write users, companies, memberships and key usage.
|
|
// Finish all authentication before entering the next handler: the report
|
|
// must count concurrent authentication, without counting its own auth.
|
|
const finish = beginIdleTrackedWork();
|
|
let continueRequest: (() => void) | undefined;
|
|
try {
|
|
await authenticate(req, res, (error?: unknown) => {
|
|
continueRequest = () => next(error);
|
|
});
|
|
} finally {
|
|
finish();
|
|
}
|
|
continueRequest?.();
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Minimal header accessor `resolveCloudTenantActor` needs. Express `Request`
|
|
* satisfies it directly; websocket upgrade paths adapt a raw
|
|
* `IncomingMessage` with {@link cloudActorHeaderSourceFromHeaders} since
|
|
* trusted-header authentication must work identically for upgrades — a
|
|
* cloud-proxied browser has no local Better Auth session to fall back on.
|
|
*/
|
|
export interface CloudActorHeaderSource {
|
|
header(name: string): string | undefined;
|
|
}
|
|
|
|
/** Adapts a raw header map (e.g. `IncomingMessage.headers`) to {@link CloudActorHeaderSource}. */
|
|
export function cloudActorHeaderSourceFromHeaders(
|
|
headers: Record<string, string | string[] | undefined>,
|
|
): CloudActorHeaderSource {
|
|
return {
|
|
header(name: string) {
|
|
const value = headers[name.toLowerCase()];
|
|
return Array.isArray(value) ? value[0] : value;
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Trusted-header actor resolution with bounded transient-connection retries.
|
|
* The tenant sync inside is idempotent end to end — every write is an
|
|
* upsert/on-conflict/delete and the write debounce records only after the
|
|
* whole sync succeeds — so replaying it after a dropped connection is safe,
|
|
* and turns a golden-path authentication 500 into a served request.
|
|
*/
|
|
export async function resolveCloudTenantActor(
|
|
db: Db,
|
|
req: CloudActorHeaderSource,
|
|
): Promise<Express.Request["actor"] | null> {
|
|
return retryIdempotentDatabaseOperation(() => resolveCloudTenantActorOnce(db, req));
|
|
}
|
|
|
|
async function resolveCloudTenantActorOnce(
|
|
db: Db,
|
|
req: CloudActorHeaderSource,
|
|
): Promise<Express.Request["actor"] | null> {
|
|
const expectedToken = process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN?.trim();
|
|
if (!expectedToken) return null;
|
|
|
|
const token = req.header("x-paperclip-cloud-tenant-token")?.trim();
|
|
if (!token || !constantTimeStringEqual(token, expectedToken)) return null;
|
|
|
|
const userId = requiredCloudHeader(req, "x-paperclip-cloud-user-id");
|
|
const userEmail = requiredCloudHeader(req, "x-paperclip-cloud-user-email").toLowerCase();
|
|
const stackId = requiredCloudHeader(req, "x-paperclip-cloud-stack-id");
|
|
const stackRole = stackMembershipRole(req.header("x-paperclip-cloud-stack-role"));
|
|
const userName = req.header("x-paperclip-cloud-user-name")?.trim() || userEmail;
|
|
const paperclipCompanyId = req.header("x-paperclip-cloud-paperclip-company-id")?.trim();
|
|
const paperclipCompanyName = req
|
|
.header("x-paperclip-cloud-paperclip-company-name")
|
|
?.trim();
|
|
const companyId = cloudTenantCompanyId(stackId);
|
|
const companyName = paperclipCompanyName || humanizeCloudStackSlug(stackId);
|
|
const membershipRole = stackRole === "owner" || stackRole === "admin" ? "owner" : stackRole;
|
|
const syncFingerprint = JSON.stringify([
|
|
userEmail, userName, stackId, stackRole, paperclipCompanyId ?? "", paperclipCompanyName ?? "",
|
|
]);
|
|
let effectiveMembership: { companyId: string; membershipRole: string | null; status: string } = {
|
|
companyId,
|
|
membershipRole,
|
|
status: "active",
|
|
};
|
|
|
|
// Earlier cloud_tenant builds granted every tenant user `instance_admin`.
|
|
// Stale rows from those deployments would still elevate this user through
|
|
// the BetterAuth session path, board API keys, and the authorization
|
|
// service's own instanceUserRoles lookup — so actively purge them on every
|
|
// trusted-header authentication instead of merely no longer inserting them.
|
|
//
|
|
// Every request runs this path, static files included. The purge and the
|
|
// tenant sync stay ordered; the two reads below are independent of them, so
|
|
// they run concurrently. A loaded database then costs one round trip per
|
|
// request rather than three in a row.
|
|
const purgeAndSync = (async () => {
|
|
await db
|
|
.delete(instanceUserRoles)
|
|
.where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")));
|
|
|
|
await syncCloudTenantWrites(db, userId, syncFingerprint, async () => {
|
|
const now = new Date();
|
|
await db
|
|
.insert(authUsers)
|
|
.values({
|
|
id: userId,
|
|
name: userName,
|
|
email: userEmail,
|
|
emailVerified: true,
|
|
image: null,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
})
|
|
.onConflictDoUpdate({
|
|
target: authUsers.id,
|
|
set: { name: userName, email: userEmail, emailVerified: true, updatedAt: now },
|
|
setWhere: sql`${authUsers.name} is distinct from ${userName}
|
|
or ${authUsers.email} is distinct from ${userEmail}
|
|
or ${authUsers.emailVerified} is distinct from true`,
|
|
});
|
|
|
|
await insertCloudTenantCompany(db, { companyId, companyName, now });
|
|
if (paperclipCompanyName) {
|
|
await repairCloudTenantCompanyName(db, {
|
|
companyId,
|
|
paperclipCompanyId,
|
|
paperclipCompanyName,
|
|
now,
|
|
});
|
|
}
|
|
// Derive any legacy prefix from the repaired name, preserving the helper's
|
|
// exact legacy-marker guards and the operator's own edits.
|
|
await repairCloudTenantCompanyProvisionDefaults(db, { companyId, stackId, now });
|
|
|
|
effectiveMembership = await db.transaction(async tx => {
|
|
const [existing] = await tx.select({
|
|
status: companyMemberships.status,
|
|
membershipRole: companyMemberships.membershipRole,
|
|
}).from(companyMemberships).where(and(
|
|
eq(companyMemberships.companyId, companyId),
|
|
eq(companyMemberships.principalType, "user"),
|
|
eq(companyMemberships.principalId, userId),
|
|
)).for("update");
|
|
// Serialize authority restoration and its notice while retaining the
|
|
// guarded upsert that leaves unchanged memberships untouched.
|
|
if (!existing || existing.status !== "active" || existing.membershipRole === "viewer") {
|
|
await notifyChatCompanyAuthorityChange(tx, { companyId });
|
|
await notifyMuseContactVerification(tx, { companyId, operatorId: userId });
|
|
}
|
|
return tx
|
|
.insert(companyMemberships)
|
|
.values({ companyId, principalType: "user", principalId: userId, status: "active", membershipRole, updatedAt: now })
|
|
.onConflictDoUpdate({
|
|
target: [companyMemberships.companyId, companyMemberships.principalType, companyMemberships.principalId],
|
|
set: { status: "active", membershipRole, updatedAt: now },
|
|
setWhere: sql`${companyMemberships.status} is distinct from 'active'
|
|
or ${companyMemberships.membershipRole} is distinct from ${membershipRole}`,
|
|
})
|
|
.returning({ companyId: companyMemberships.companyId, membershipRole: companyMemberships.membershipRole, status: companyMemberships.status })
|
|
// PostgreSQL returns no row for an unchanged ON CONFLICT ... WHERE.
|
|
// That condition itself proves the existing role/status match the input.
|
|
.then((rows) => rows[0] ?? { companyId, membershipRole, status: "active" });
|
|
});
|
|
|
|
// An unchanged membership can still lack default grants after a partial
|
|
// sync or an older deployment; keep this repair inside every actual sync.
|
|
await ensureHumanRoleDefaultGrants(db, {
|
|
companyId,
|
|
principalId: userId,
|
|
membershipRole: effectiveMembership.membershipRole ?? membershipRole,
|
|
grantedByUserId: null,
|
|
});
|
|
});
|
|
})();
|
|
|
|
// The stack's seeded company is only where Cloud provisioned this user.
|
|
// Companies created afterwards on the instance (imports, in-app company
|
|
// creation) attach real membership rows for the user, so union those with
|
|
// the pinned primary — the same active-membership scope a locally
|
|
// authenticated session actor carries. Strictly this user's own rows; the
|
|
// membership-creating flows seed their own permission grants, so nothing
|
|
// needs seeding per request here. The sync above writes only the primary
|
|
// company's membership, which this read excludes, so it need not wait for
|
|
// the sync. A read failure degrades to the pinned primary instead of
|
|
// blocking authentication, mirroring the fail-closed owner-elevation
|
|
// resolution below.
|
|
const additionalMembershipsRead: Promise<{ companyId: string; membershipRole: string | null; status: string }[]> =
|
|
loadActiveUserCompanyMemberships(db, userId).then(
|
|
(rows) => rows.filter((row) => row.companyId !== companyId),
|
|
(err) => {
|
|
logger.warn(
|
|
{ err, userId, stackId },
|
|
"Failed to load cloud tenant user's company memberships; scoping actor to the stack's primary company",
|
|
);
|
|
return [];
|
|
},
|
|
);
|
|
// Computed per request, never persisted: the stack owner is elevated to
|
|
// instance admin of their own dedicated instance only while the
|
|
// `enableOwnerInstanceAdmin` flag is on. Non-owner stack roles stay
|
|
// company-scoped. Turning the flag off de-elevates on the next request —
|
|
// there is no role row to clean up.
|
|
const ownerInstanceAdminRead = resolveOwnerInstanceAdmin(db, stackRole);
|
|
|
|
// Settle every started statement before an error leaves: the caller stops
|
|
// counting authentication work for idle and drain checks when this throws,
|
|
// and the owner-settings read can insert the missing settings row.
|
|
const [synced, membershipsRead, ownerRead] = await Promise.allSettled([
|
|
purgeAndSync,
|
|
additionalMembershipsRead,
|
|
ownerInstanceAdminRead,
|
|
]);
|
|
if (synced.status === "rejected") throw synced.reason;
|
|
if (membershipsRead.status === "rejected") throw membershipsRead.reason;
|
|
if (ownerRead.status === "rejected") throw ownerRead.reason;
|
|
const additionalMemberships = membershipsRead.value;
|
|
const isInstanceAdmin = ownerRead.value;
|
|
|
|
return {
|
|
type: "board",
|
|
userId,
|
|
userName,
|
|
userEmail,
|
|
companyIds: [companyId, ...additionalMemberships.map((row) => row.companyId)],
|
|
memberships: [
|
|
{
|
|
companyId,
|
|
membershipRole: effectiveMembership.membershipRole ?? membershipRole,
|
|
status: effectiveMembership.status,
|
|
},
|
|
...additionalMemberships,
|
|
],
|
|
isInstanceAdmin,
|
|
canManageExperimentalSettings: stackRole === "admin",
|
|
source: "cloud_tenant",
|
|
};
|
|
}
|
|
|
|
function requiredCloudHeader(req: CloudActorHeaderSource, name: string): string {
|
|
const value = req.header(name)?.trim();
|
|
if (!value) {
|
|
throw new Error(`Missing trusted Cloud tenant header ${name}`);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function stackMembershipRole(value: string | undefined): "owner" | "admin" | "member" | "support" {
|
|
if (value === "owner" || value === "admin" || value === "member" || value === "support") {
|
|
return value;
|
|
}
|
|
throw new Error("Invalid trusted Cloud tenant stack role");
|
|
}
|
|
|
|
function constantTimeStringEqual(left: string, right: string): boolean {
|
|
const leftBuffer = Buffer.from(left);
|
|
const rightBuffer = Buffer.from(right);
|
|
return leftBuffer.length === rightBuffer.length && timingSafeEqual(leftBuffer, rightBuffer);
|
|
}
|
|
|
|
function cloudTenantCompanyId(stackId: string): string {
|
|
return cloudTenantPrimaryCompanyId(stackId);
|
|
}
|
|
|
|
export function humanizeCloudStackSlug(stackId: string): string {
|
|
const slug = stackId
|
|
.trim()
|
|
.replace(/^paperclip-stack-/i, "")
|
|
.replace(/^stack-/i, "");
|
|
const displayName = slug
|
|
.split(/[-_]+/)
|
|
.filter(Boolean)
|
|
.map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`)
|
|
.join(" ");
|
|
return displayName || "Workspace";
|
|
}
|
|
|
|
export function isKnownBadCloudCompanyName(
|
|
name: string,
|
|
ids: { companyId: string; paperclipCompanyId?: string },
|
|
): boolean {
|
|
const normalized = name.trim();
|
|
return (
|
|
/^paperclip-stack-.+/i.test(normalized) ||
|
|
/^stack-.+\s+paperclip$/i.test(normalized) ||
|
|
normalized === ids.companyId ||
|
|
(ids.paperclipCompanyId !== undefined &&
|
|
normalized === ids.paperclipCompanyId)
|
|
);
|
|
}
|
|
|
|
async function repairCloudTenantCompanyName(
|
|
db: Db,
|
|
input: {
|
|
companyId: string;
|
|
paperclipCompanyId?: string;
|
|
paperclipCompanyName: string;
|
|
now: Date;
|
|
},
|
|
): Promise<void> {
|
|
try {
|
|
const existing = await db
|
|
.select({ name: companies.name })
|
|
.from(companies)
|
|
.where(eq(companies.id, input.companyId))
|
|
.then((rows) => rows[0]);
|
|
if (
|
|
!existing ||
|
|
!isKnownBadCloudCompanyName(existing.name, {
|
|
companyId: input.companyId,
|
|
paperclipCompanyId: input.paperclipCompanyId,
|
|
})
|
|
) {
|
|
return;
|
|
}
|
|
await db.transaction(async (tx) => {
|
|
const [updated] = await tx
|
|
.update(companies)
|
|
.set({ name: input.paperclipCompanyName, updatedAt: input.now })
|
|
.where(
|
|
and(
|
|
eq(companies.id, input.companyId),
|
|
// A user may rename the company between the read above and this
|
|
// repair. Match the exact observed machine name so that concurrent
|
|
// genuine renames always win.
|
|
eq(companies.name, existing.name),
|
|
),
|
|
)
|
|
.returning({ id: companies.id });
|
|
if (!updated) return;
|
|
|
|
await tx.insert(activityLog).values({
|
|
companyId: input.companyId,
|
|
actorType: "system",
|
|
actorId: "cloud-tenant-auth",
|
|
action: "company.updated",
|
|
entityType: "company",
|
|
entityId: input.companyId,
|
|
details: {
|
|
source: "cloud_tenant_auth",
|
|
reason: "legacy_machine_name_repair",
|
|
previousName: existing.name,
|
|
name: input.paperclipCompanyName,
|
|
},
|
|
});
|
|
});
|
|
} catch (err) {
|
|
logger.warn(
|
|
{ err, companyId: input.companyId },
|
|
"Failed to repair legacy Cloud tenant company name",
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Claims the tenant company row for this stack.
|
|
*
|
|
* The prefix derives from the company name, exactly as it does for a
|
|
* self-hosted company. Each attempt is a standalone INSERT, so a failed
|
|
* attempt is its own implicit transaction and cannot poison a surrounding
|
|
* one. `onConflictDoNothing` only absorbs the `companies.id` conflict — a
|
|
* prefix that another company already holds still raises `23505`, so the loop
|
|
* moves on to the next suffix.
|
|
*/
|
|
async function insertCloudTenantCompany(
|
|
db: Db,
|
|
input: { companyId: string; companyName: string; now: Date },
|
|
): Promise<void> {
|
|
const base = deriveIssuePrefixBase(input.companyName);
|
|
for (let attempt = 1; attempt <= MAX_ISSUE_PREFIX_ATTEMPTS; attempt += 1) {
|
|
try {
|
|
await db
|
|
.insert(companies)
|
|
.values({
|
|
id: input.companyId,
|
|
name: input.companyName,
|
|
description: null,
|
|
status: "active",
|
|
issuePrefix: `${base}${issuePrefixSuffixForAttempt(attempt)}`,
|
|
updatedAt: input.now,
|
|
})
|
|
.onConflictDoNothing({
|
|
target: companies.id,
|
|
});
|
|
return;
|
|
} catch (error) {
|
|
if (!isIssuePrefixConflict(error)) throw error;
|
|
}
|
|
}
|
|
throw new Error("Unable to allocate a unique issue prefix for the tenant company");
|
|
}
|
|
|
|
/**
|
|
* The issue prefix that pre-name-derivation builds gave a tenant company.
|
|
*
|
|
* This derivation survives only as the detector for the one-time repair
|
|
* below. Nothing mints a prefix this way any more.
|
|
*/
|
|
function legacyProvisionedIssuePrefix(stackId: string): string {
|
|
const hash = createHash("sha256").update(stackId).digest("hex").slice(0, 4).toUpperCase();
|
|
return `PC${hash}`;
|
|
}
|
|
|
|
/** The placeholder description that pre-name-derivation builds wrote. */
|
|
const LEGACY_PROVISIONED_DESCRIPTION_PREFIX = "Provisioned by Paperclip Cloud for stack ";
|
|
|
|
/**
|
|
* One-time repair for companies claimed by a pre-name-derivation build.
|
|
*
|
|
* Those companies carry an opaque hash prefix and a placeholder description
|
|
* that the operator never chose. Re-derive the prefix from the company's
|
|
* current name, re-key the stored issue and case identifiers onto it, and drop
|
|
* the placeholder. Both guards stop matching once the repair lands, so a later
|
|
* pass is a no-op.
|
|
*/
|
|
async function repairCloudTenantCompanyProvisionDefaults(
|
|
db: Db,
|
|
input: { companyId: string; stackId: string; now: Date },
|
|
): Promise<void> {
|
|
try {
|
|
const existing = await db
|
|
.select({
|
|
name: companies.name,
|
|
issuePrefix: companies.issuePrefix,
|
|
description: companies.description,
|
|
})
|
|
.from(companies)
|
|
.where(eq(companies.id, input.companyId))
|
|
.then((rows) => rows[0]);
|
|
if (!existing) return;
|
|
|
|
const legacyPrefix = legacyProvisionedIssuePrefix(input.stackId);
|
|
const legacyDescription = existing.description?.startsWith(LEGACY_PROVISIONED_DESCRIPTION_PREFIX)
|
|
? existing.description
|
|
: null;
|
|
if (existing.issuePrefix !== legacyPrefix) {
|
|
if (!legacyDescription) return;
|
|
// The prefix was already re-derived, so only the placeholder is left.
|
|
await db
|
|
.update(companies)
|
|
.set({ description: null, updatedAt: input.now })
|
|
.where(and(
|
|
eq(companies.id, input.companyId),
|
|
eq(companies.description, legacyDescription),
|
|
));
|
|
return;
|
|
}
|
|
|
|
await db.transaction(async (tx) => {
|
|
const candidate = await pickAvailableIssuePrefix(tx, deriveIssuePrefixBase(existing.name));
|
|
if (!candidate || candidate === legacyPrefix) return;
|
|
|
|
const [updated] = await tx
|
|
.update(companies)
|
|
.set({
|
|
issuePrefix: candidate,
|
|
...(legacyDescription ? { description: null } : {}),
|
|
updatedAt: input.now,
|
|
})
|
|
.where(and(
|
|
eq(companies.id, input.companyId),
|
|
// A user may rename the company between the read above and this
|
|
// repair. Match the exact observed legacy prefix so that concurrent
|
|
// genuine renames always win.
|
|
eq(companies.issuePrefix, legacyPrefix),
|
|
))
|
|
.returning({ id: companies.id });
|
|
if (!updated) return;
|
|
|
|
const rekeyed = await rekeyCompanyIssueIdentifiers(tx, {
|
|
companyId: input.companyId,
|
|
fromPrefix: legacyPrefix,
|
|
toPrefix: candidate,
|
|
});
|
|
|
|
await tx.insert(activityLog).values({
|
|
companyId: input.companyId,
|
|
actorType: "system",
|
|
actorId: "cloud-tenant-auth",
|
|
action: "company.updated",
|
|
entityType: "company",
|
|
entityId: input.companyId,
|
|
details: {
|
|
source: "cloud_tenant_auth",
|
|
reason: "legacy_provision_defaults_repair",
|
|
previousIssuePrefix: legacyPrefix,
|
|
issuePrefix: candidate,
|
|
descriptionCleared: legacyDescription !== null,
|
|
issuesRekeyed: rekeyed.issues,
|
|
casesRekeyed: rekeyed.cases,
|
|
},
|
|
});
|
|
});
|
|
} catch (err) {
|
|
logger.warn(
|
|
{ err, companyId: input.companyId },
|
|
"Failed to repair legacy tenant company provisioning defaults",
|
|
);
|
|
}
|
|
}
|
|
|
|
export function requireBoard(req: Express.Request) {
|
|
return req.actor.type === "board";
|
|
}
|