Files
PaperClipAI/server/src/services/workload-identity.ts
T
651749bdb4 feat(connections): AWS connector with credentials minted per connection (#22195)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use outside services through connections, and the control
plane holds each connection's credentials
> - Companies want agents to "do things on AWS" with exactly the
permissions they choose, without Paperclip storing long-lived AWS keys
or rebuilding the AWS API
> - AWS hosts an MCP server that runs any AWS API call in its own
sandbox, and it accepts a one-hour bearer token that can be minted from
IAM credentials
> - This pull request adds an AWS connection that mints that token for
each connection at call time. The role method proves the connection with
the company's workload identity issuer (#22083), so no AWS key is stored
> - The benefit is that each AWS connection carries its own role and
permissions, AWS enforces them, and agents never see any AWS credential

## Linked Issues or Issue Description

Refs #22083 (workload identity issuer) and #22191 (spike findings).

**Subsystem affected**
Connections (tool access), tool gateway, shared app definitions,
instance settings.

**Problem or motivation**
Paperclip has no way to connect AWS. AWS's hosted MCP server needs a
bearer token from AWS Sign-in, minted from IAM credentials. No existing
credential path mints a header at call time from a role or key.

**Proposed solution**
Methods can declare `credentialMinter: "aws_mcp"`. The gateway and
connection health checks mint the `Authorization` header at call time,
and they share one in-memory cache per connection and grant (about 55
minutes). There are two methods:
- Role (`AssumeRoleWithWebIdentity` with a Paperclip-signed connection
token).
- Access key (the key directly, `GetFederationToken`, or `AssumeRole`).

Read-only connections add `ReadOnlyAccess` and
`AWSMCPSignInOAuthAccessPolicy` as session policies, so AWS refuses
changes. The feature is behind the `enableAwsConnector` experimental
setting.

**Alternatives considered**
- Run AWS's `mcp-proxy-for-aws` process on the control plane. Rejected:
it adds a Python runtime and processes, and gives nothing the token
exchange does not.
- Put credentials in the agent sandbox and use the AWS CLI. Deferred:
there is no per-call governance, and every sandbox would need the CLI.
- Add a new `credentialSource`. Rejected: it needs a migration, and the
`vercel_connect` database rules do not fit stored access keys.

## What Changed

- `packages/shared`:
- `credentialMinter` on connection methods. The validator requires
`mcp_remote` and `api_key`, and does not allow `keyPlacement` or another
credential source.
- The `aws` app definition (two methods, reviewed tools,
`mcpSessionRequired`, experimental key).
- The `enableAwsConnector` setting in the catalog, types and validators.
  - `aws` added to the connectable apps.
- `server/src/services/connectors/aws/mcp-credentials.ts`:
- Settings parsing and checks. The URL must be AWS's endpoint for the
saved region, and the role ARN must be valid.
- The minter: role or key session, read-only session policies, Sign-in
exchange, cache keyed on settings, key references and status, in-flight
de-duplication, eviction.
- A plain-language error mapping that never shows AWS's own text,
because that text can contain account IDs and ARNs.
- Gateway (`resolveCredentialHeadersUnrecorded`), credential access
(`resolveCredentialHeaders`), catalog discovery and health-failure
mapping:
  - The AWS branch.
- After a 401, the gateway evicts the token and mints again, then
requires an explicit retry (no replay). Discovery lists again.
- Setup:
- Minted methods may save a draft without contacting the provider. The
role must trust a connection that already exists.
- Saving an AWS role draft publishes the company's issuer, so AWS can
validate it when the customer registers it.
- `workload-identity.ts`: a draft connection can get a token, so setup
can test it. Disabled, archived or switched-off connections still get
none.
- `server/package.json`: `@aws-sdk/client-sts` and
`@aws-sdk/client-signin`. The lockfile is left to the refresh workflow.
- Artwork: AWS light and dark marks from LobeHub's MIT icon set (already
licensed in the repo). The manifest entry passes the brand checks.
- `scripts/ingest-app-definitions.mjs`: minted methods are exempt from
the `keyPlacement` requirement. The override source is
`scripts/app-definition-overrides/aws.json`. Permission reviews are
added.
- UI: the experimental settings toggle, in alphabetical position.
- Docs: `doc/connections/AWS.md`, the connections index, the issuer API
doc (draft rule), and the plan's phase table.

## Verification

- `server/src/services/connectors/aws/mcp-credentials.test.ts` (7 tests)
covers these items:
  - Both methods and the read-only policies.
  - Caching, revision, forced refresh, expiry and eviction.
  - Concurrent de-duplication.
  - The error mapping, with no AWS text leaking.
- Settings validation, including the URL and region check and the rule
that an unknown access level means read only.
- `server/src/__tests__/aws-mcp-connector.test.ts` (3 tests, real setup,
catalog and gateway code with a fake AWS and a session-requiring fake
MCP server) covers these items:
  - The setting gates setup.
  - The access key is never sent as a header or stored in config.
  - A cached token is reused.
  - After a 401, a fresh token is minted and the call is not replayed.
  - Role draft-then-resume publishes the issuer.
  - The signed token has the right `iss`, `sub` and `aud`.
  - An AWS refusal shows a plain health message without the account ID.
- Red/green:
  - Removing the gateway hook fails the access-key test.
  - Turning off `mcpSessionRequired` fails both integration tests.
- Removing draft support for minted methods fails both integration
tests.
  - Restoring each change passes again.
- Nearby suites: `tool-gateway-service`, `tool-access-service`,
`remote-mcp-connectors`, `instance-settings-service`,
`workload-identity`, plus the new files. 775 of 775 pass.
- Shared `app-definitions.test.ts` passes (42), including new
`credentialMinter` schema tests. UI `InstanceExperimentalSettings` (63)
and the brand asset tests pass. `check-app-brand-assets` validates 112
identities.
- Typecheck is clean for `packages/shared`, `server` and `ui`. The only
UI errors are in Storybook's generated catalog files, which this
worktree has not built.
- **Real AWS** (Paperclip dev account, integrated code path, issuer
behind a temporary public tunnel):
- Access key, read only: 8 tools listed. `run_script` `ListBuckets`
succeeded in 8.9 s on a cold sandbox. AWS refused `CreateBucket` ("no
session policy allows").
- Role: the draft was saved without contacting AWS, and the issuer was
published. After an IAM provider and a role trusting only that
connection were created, resuming setup listed 8 tools. `ListBuckets`
succeeded in 12.8 s. The role's own permissions refused `CreateBucket`.
- This run found two bugs the fakes did not: AWS needs MCP sessions for
calls, and the role method needs draft-first setup with the issuer
published. Both are fixed and both now have tests.
- All IAM users, keys, roles, providers and buckets were deleted, and a
listing confirmed it.
- Not run: Paperclip Cloud staging (the setting is off by default), and
`AssumeRole` from an access key with a role ARN against real AWS (unit
tests only).

## Risks

- The feature is off by default, behind `enableAwsConnector`. No
migration.
- New dependencies `@aws-sdk/client-sts` and `@aws-sdk/client-signin`
are in the existing `@aws-sdk` family (the server already uses
`client-s3`).
- Minted tokens are held only in process memory. A restart mints again.
A cached token can outlive a deactivated key by up to an hour, unless
AWS returns 401, which evicts it.
- `aws___run_script` is classified as a write, so the normal approval
and ask-first policy applies. Read-only connections rely on AWS session
policies.
- The guided setup screen and the CloudFormation template are not in
this PR. Setup uses the generic form and the documented draft and resume
steps.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, AWS SDK for JavaScript against the Paperclip dev AWS
account, a Cloudflare quick tunnel, an exploration subagent).

## 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
- [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>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-18 12:48:49 -06:00

387 lines
18 KiB
TypeScript

import { createPrivateKey, createPublicKey, randomUUID, sign, type KeyObject } from "node:crypto";
import { and, eq, gt, inArray, lte, or } from "drizzle-orm";
import {
companies,
companyWorkloadIdentityKeys,
toolAccessAuditEvents,
toolConnections,
type Db,
} from "@paperclipai/db";
import { conflict, notFound, unprocessable } from "../errors.js";
import { persistActivity, publishActivity, type LogActivityInput } from "./activity-log.js";
import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js";
import { runtimePublicOrigin } from "./cloud-runtime-identity.js";
import { generateClientKeyPair, jwkThumbprint } from "./tool-access/oauth/client-credentials.js";
/**
* Workload identity issuer: each company signs short-lived OIDC tokens that
* name one of its connections, and publishes the public keys so an outside
* cloud (AWS, GCP, Azure) can verify them without Paperclip storing that
* cloud's keys. Only the control plane can sign; agents never see these tokens.
*/
export const WORKLOAD_IDENTITY_ALGORITHM = "ES256";
export const WORKLOAD_IDENTITY_TOKEN_LIFETIME_SECONDS = 300;
/** A `next` key is published this long before it may sign, so cached key sets pick it up. */
export const WORKLOAD_IDENTITY_PUBLISH_BEFORE_USE_MS = 24 * 60 * 60 * 1000;
/** A replaced key stays published this long, so tokens it signed still verify. */
export const WORKLOAD_IDENTITY_RETIRING_GRACE_MS = 24 * 60 * 60 * 1000;
type KeyRow = typeof companyWorkloadIdentityKeys.$inferSelect;
export type WorkloadIdentityIssuerOrigin =
| { available: true; origin: string }
| { available: false; reason: "no_public_url" | "not_https" | "has_port" | "loopback" };
let configuredPublicOrigin: string | null = null;
/**
* The instance's configured public address (auth.publicBaseUrl, BETTER_AUTH_URL,
* BETTER_AUTH_BASE_URL), set once by createApp. Used after the live Cloud
* address and the PAPERCLIP_PUBLIC_URL family, which `runtimePublicOrigin` reads.
*/
export function setWorkloadIdentityConfiguredPublicOrigin(origin: string | null | undefined) {
configuredPublicOrigin = origin?.trim() || null;
}
export function workloadIdentityPublicOrigin(): string | null {
return runtimePublicOrigin() ?? configuredPublicOrigin;
}
/** AWS requires an https issuer with no port that it can reach from the internet. */
export function workloadIdentityIssuerOrigin(origin: string | null = workloadIdentityPublicOrigin()): WorkloadIdentityIssuerOrigin {
if (!origin) return { available: false, reason: "no_public_url" };
let url: URL;
try {
url = new URL(origin);
} catch {
return { available: false, reason: "no_public_url" };
}
if (url.protocol !== "https:") return { available: false, reason: "not_https" };
if (url.port !== "") return { available: false, reason: "has_port" };
const host = url.hostname.toLowerCase();
if (host === "localhost" || host.endsWith(".localhost") || host === "[::1]" || /^127\./.test(host)) {
return { available: false, reason: "loopback" };
}
return { available: true, origin: url.origin };
}
export function workloadIdentityIssuer(origin: string, companyId: string): string {
return `${origin}/oidc/companies/${companyId}`;
}
export function workloadIdentitySubject(connectionId: string): string {
return `connection:${connectionId}`;
}
/** Only public EC members, so private material can never reach the published key set. */
function publicJwkFor(row: Pick<KeyRow, "publicJwk" | "keyId">) {
const jwk = row.publicJwk;
return {
kty: "EC",
crv: jwk.crv,
x: jwk.x,
y: jwk.y,
kid: row.keyId,
alg: WORKLOAD_IDENTITY_ALGORITHM,
use: "sig",
};
}
/** Only each company's current signing key is held decrypted; a rotated-out key is dropped. */
const signingKeyCache = new Map<string, { keyId: string; privateKey: KeyObject }>();
export function resetWorkloadIdentityKeyCacheForTests() {
signingKeyCache.clear();
}
function base64Url(value: Buffer | string): string {
return Buffer.from(value).toString("base64url");
}
export function workloadIdentityService(db: Db, options: { now?: () => Date } = {}) {
const now = options.now ?? (() => new Date());
async function newKeyValues(companyId: string, status: "next" | "active") {
const generated = await generateClientKeyPair(WORKLOAD_IDENTITY_ALGORITHM, now());
const encrypted = await localEncryptedProvider.createSecret({ value: generated.privateKeyPem });
const at = now();
return {
companyId,
keyId: generated.publicKey.keyId,
algorithm: WORKLOAD_IDENTITY_ALGORITHM as "ES256",
publicJwk: generated.publicKey.publicJwk as unknown as Record<string, unknown>,
privateKeyMaterial: encrypted.material,
status,
createdAt: at,
statusChangedAt: at,
};
}
async function assertCompany(companyId: string) {
const [company] = await db.select({ id: companies.id }).from(companies).where(eq(companies.id, companyId));
if (!company) throw notFound("Company not found");
}
async function activeKey(companyId: string): Promise<KeyRow | undefined> {
const [row] = await db.select().from(companyWorkloadIdentityKeys).where(and(
eq(companyWorkloadIdentityKeys.companyId, companyId),
eq(companyWorkloadIdentityKeys.status, "active"),
));
return row;
}
/** The company's signing key, created on first use. Concurrent callers converge on one key. */
async function ensureActiveKey(companyId: string): Promise<KeyRow> {
const existing = await activeKey(companyId);
if (existing) return existing;
await assertCompany(companyId);
await db.insert(companyWorkloadIdentityKeys).values(await newKeyValues(companyId, "active")).onConflictDoNothing();
const created = await activeKey(companyId);
if (!created) throw new Error("Workload identity key could not be created");
return created;
}
async function privateKeyFor(row: KeyRow): Promise<KeyObject> {
const cached = signingKeyCache.get(row.companyId);
if (cached?.keyId === row.keyId) return cached.privateKey;
const pem = await localEncryptedProvider.resolveVersion({ material: row.privateKeyMaterial, externalRef: null });
const privateKey = createPrivateKey(pem);
// Fail closed on corruption or a wrong master key; never sign with a key that isn't the published one.
if (row.algorithm !== WORKLOAD_IDENTITY_ALGORITHM || privateKey.asymmetricKeyType !== "ec"
|| jwkThumbprint(createPublicKey(privateKey).export({ format: "jwk" })) !== row.keyId) {
throw new Error("Workload identity private key does not match its published key");
}
signingKeyCache.set(row.companyId, { keyId: row.keyId, privateKey });
return privateKey;
}
/** Published keys only, filtered in SQL so reads stay bounded however many rotations happened. */
async function publishedKeyRows(companyId: string): Promise<KeyRow[]> {
const graceStart = new Date(now().getTime() - WORKLOAD_IDENTITY_RETIRING_GRACE_MS);
return db.select().from(companyWorkloadIdentityKeys).where(and(
eq(companyWorkloadIdentityKeys.companyId, companyId),
or(
inArray(companyWorkloadIdentityKeys.status, ["next", "active"]),
and(eq(companyWorkloadIdentityKeys.status, "retiring"),
gt(companyWorkloadIdentityKeys.statusChangedAt, graceStart)),
),
));
}
/** Retiring keys past their grace period become retired, so they leave every view. */
async function settleRetiring(tx: Db, companyId: string, at: Date) {
await tx.update(companyWorkloadIdentityKeys).set({ status: "retired", statusChangedAt: at }).where(and(
eq(companyWorkloadIdentityKeys.companyId, companyId),
eq(companyWorkloadIdentityKeys.status, "retiring"),
lte(companyWorkloadIdentityKeys.statusChangedAt, new Date(at.getTime() - WORKLOAD_IDENTITY_RETIRING_GRACE_MS)),
));
}
type RotationActor = Pick<LogActivityInput, "actorType" | "actorId">;
/** Runs one rotation step and its activity entry in one transaction; publishes the entry after commit. */
async function rotate(
companyId: string,
actor: RotationActor,
step: "begin" | "complete" | "emergency",
work: (tx: Db, at: Date) => Promise<{ keyId: string; created?: boolean }>,
) {
const { result, publication } = await db.transaction(async (rawTx) => {
const tx = rawTx as unknown as Db;
await lockCompany(tx, companyId);
const at = now();
await settleRetiring(tx, companyId, at);
const result = await work(tx, at);
// A repeated "begin" while a rotation is pending changes nothing, so it is not logged.
if (result.created === false) return { result, publication: null };
const { publication } = await persistActivity(tx, {
companyId, ...actor,
action: `workload_identity.rotation_${step}`,
entityType: "company", entityId: companyId,
details: { keyId: result.keyId },
});
return { result, publication };
});
if (publication) publishActivity(publication);
if (step !== "begin") signingKeyCache.delete(companyId);
return result;
}
async function lockCompany(tx: Db, companyId: string) {
const [company] = await tx.select({ id: companies.id }).from(companies)
.where(eq(companies.id, companyId)).for("update");
if (!company) throw notFound("Company not found");
}
return {
ensureActiveKey,
/** Public key set, or null when the company has never created a key (callers answer 404). */
async publicKeySet(companyId: string): Promise<{ keys: ReturnType<typeof publicJwkFor>[] } | null> {
const keys = (await publishedKeyRows(companyId)).map(publicJwkFor);
return keys.length > 0 ? { keys } : null;
},
/** OIDC discovery document, or null when the issuer isn't usable here or the company has no key. */
async discoveryDocument(companyId: string, origin = workloadIdentityIssuerOrigin()) {
if (!origin.available) return null;
if ((await publishedKeyRows(companyId)).length === 0) return null;
const issuer = workloadIdentityIssuer(origin.origin, companyId);
return {
issuer,
jwks_uri: `${issuer}/jwks.json`,
response_types_supported: ["id_token"],
subject_types_supported: ["public"],
id_token_signing_alg_values_supported: [WORKLOAD_IDENTITY_ALGORITHM],
claims_supported: ["aud", "exp", "iat", "iss", "jti", "nbf", "sub"],
};
},
/**
* A 5-minute token that names one connection. `sub` and `aud` come from the
* connection and its method, never from agent input. The token itself is
* never stored or logged.
*/
async signConnectionToken(input: {
companyId: string;
connectionId: string;
audience: string;
/** The issuer recorded when the connection was set up; signing stops if the instance address changed. */
expectedIssuer?: string | null;
origin?: WorkloadIdentityIssuerOrigin;
}) {
if (!/^[\x21-\x7e]{1,256}$/.test(input.audience)) {
throw unprocessable("Invalid workload identity audience", { code: "workload_identity_audience_invalid" });
}
const origin = input.origin ?? workloadIdentityIssuerOrigin();
if (!origin.available) {
throw unprocessable("This Paperclip instance needs a public HTTPS address to sign identity tokens.", {
code: "workload_identity_unavailable", reason: origin.reason,
});
}
const issuer = workloadIdentityIssuer(origin.origin, input.companyId);
if (input.expectedIssuer && input.expectedIssuer !== issuer) {
throw conflict("This Paperclip instance's address changed. Update the identity provider in your cloud account.", {
code: "workload_identity_issuer_changed",
});
}
const [connection] = await db.select({ status: toolConnections.status, enabled: toolConnections.enabled })
.from(toolConnections).where(and(
eq(toolConnections.id, input.connectionId), eq(toolConnections.companyId, input.companyId),
));
if (!connection) throw notFound("Connection not found");
// Disabling a connection must stop new cloud credentials at once.
// A draft is being set up and tested; a disabled, archived or switched-off connection gets nothing.
const usable = connection.status === "draft" || (connection.status === "active" && connection.enabled);
if (!usable) {
throw unprocessable("This connection is not active.", { code: "workload_identity_connection_inactive" });
}
const key = await ensureActiveKey(input.companyId);
const privateKey = await privateKeyFor(key);
const issuedAt = Math.floor(now().getTime() / 1000);
const expiresAt = issuedAt + WORKLOAD_IDENTITY_TOKEN_LIFETIME_SECONDS;
const subject = workloadIdentitySubject(input.connectionId);
const header = { alg: WORKLOAD_IDENTITY_ALGORITHM, typ: "JWT", kid: key.keyId };
const claims = {
iss: issuer, sub: subject, aud: input.audience,
iat: issuedAt, nbf: issuedAt, exp: expiresAt, jti: randomUUID(),
};
const signingInput = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(claims))}`;
const signature = sign("sha256", Buffer.from(signingInput), { key: privateKey, dsaEncoding: "ieee-p1363" });
await db.insert(toolAccessAuditEvents).values({
companyId: input.companyId,
connectionId: input.connectionId,
actorType: "system",
actorId: "workload-identity",
action: "workload_identity.token_issued",
outcome: "success",
details: { keyId: key.keyId, audience: input.audience, expiresAt: new Date(expiresAt * 1000).toISOString() },
});
return {
token: `${signingInput}.${base64Url(signature)}`,
issuer,
subject,
keyId: key.keyId,
expiresAt: new Date(expiresAt * 1000),
};
},
/** Board view: issuer and the published keys with their states, with no private material. */
async describe(companyId: string, origin = workloadIdentityIssuerOrigin()) {
await assertCompany(companyId);
const rows = await publishedKeyRows(companyId);
return {
issuer: origin.available ? workloadIdentityIssuer(origin.origin, companyId) : null,
unavailableReason: origin.available ? null : origin.reason,
keys: rows
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())
.map((row) => ({
keyId: row.keyId,
status: row.status,
createdAt: row.createdAt.toISOString(),
statusChangedAt: row.statusChangedAt.toISOString(),
})),
};
},
/** Step 1 of a planned rotation: publish a `next` key alongside the active one. */
async beginRotation(companyId: string, actor: RotationActor) {
return rotate(companyId, actor, "begin", async (tx) => {
const rows = await tx.select().from(companyWorkloadIdentityKeys).where(and(
eq(companyWorkloadIdentityKeys.companyId, companyId),
inArray(companyWorkloadIdentityKeys.status, ["next", "active"]),
));
if (!rows.some((row) => row.status === "active")) {
throw conflict("This company has no signing key to rotate yet.", { code: "workload_identity_no_key" });
}
const pending = rows.find((row) => row.status === "next");
if (pending) return { keyId: pending.keyId, created: false };
const [created] = await tx.insert(companyWorkloadIdentityKeys)
.values(await newKeyValues(companyId, "next")).returning();
return { keyId: created!.keyId, created: true };
});
},
/** Step 2: once the `next` key has been published long enough, it signs; the old key stays published for a grace period. */
async completeRotation(companyId: string, actor: RotationActor) {
return rotate(companyId, actor, "complete", async (tx, at) => {
const [next] = await tx.select().from(companyWorkloadIdentityKeys).where(and(
eq(companyWorkloadIdentityKeys.companyId, companyId),
eq(companyWorkloadIdentityKeys.status, "next"),
));
if (!next) throw conflict("Start a rotation first.", { code: "workload_identity_no_rotation" });
const readyAt = new Date(next.createdAt.getTime() + WORKLOAD_IDENTITY_PUBLISH_BEFORE_USE_MS);
if (readyAt > at) {
throw conflict("The new key must be published for 24 hours before it can sign.", {
code: "workload_identity_rotation_not_ready", readyAt: readyAt.toISOString(),
});
}
await tx.update(companyWorkloadIdentityKeys).set({ status: "retiring", statusChangedAt: at }).where(and(
eq(companyWorkloadIdentityKeys.companyId, companyId),
eq(companyWorkloadIdentityKeys.status, "active"),
));
await tx.update(companyWorkloadIdentityKeys).set({ status: "active", statusChangedAt: at })
.where(eq(companyWorkloadIdentityKeys.id, next.id));
return { keyId: next.keyId };
});
},
/** For a key believed exposed: stop publishing every current key and sign with a fresh one immediately. */
async emergencyRotation(companyId: string, actor: RotationActor) {
return rotate(companyId, actor, "emergency", async (tx, at) => {
await tx.update(companyWorkloadIdentityKeys).set({ status: "retired", statusChangedAt: at }).where(and(
eq(companyWorkloadIdentityKeys.companyId, companyId),
inArray(companyWorkloadIdentityKeys.status, ["next", "active", "retiring"]),
));
const [created] = await tx.insert(companyWorkloadIdentityKeys)
.values(await newKeyValues(companyId, "active")).returning();
return { keyId: created!.keyId };
});
},
};
}
export type WorkloadIdentityService = ReturnType<typeof workloadIdentityService>;