diff --git a/.changeset/connection-key-revoke.md b/.changeset/connection-key-revoke.md new file mode 100644 index 0000000000..a16845a184 --- /dev/null +++ b/.changeset/connection-key-revoke.md @@ -0,0 +1,14 @@ +--- +"@executor-js/hosted-server": patch +"@executor-js/hosted-web": patch +"@executor-js/hosted-cloud": patch +"@executor-js/ui": patch +"@executor-js/app-templates": patch +--- + +A scoped connection's owner can list its connection keys and revoke one at a time, so a seat's key +can be rotated without revoking the connection. `GET .../mcp-connections//keys` lists each +key's name, first characters, creation, expiry and last use, never the secret, and +`POST .../mcp-connections//keys//revoke` deletes one key: it is refused at once while the +connection and its other keys keep working. Both follow the minting rules, and every revocation is +in the audit log. The connection's dashboard page lists its keys with a Revoke button for each. diff --git a/apps/hosted/cloud/src/infrastructure/mcp-auth.ts b/apps/hosted/cloud/src/infrastructure/mcp-auth.ts index e14f158dd2..0658725850 100644 --- a/apps/hosted/cloud/src/infrastructure/mcp-auth.ts +++ b/apps/hosted/cloud/src/infrastructure/mcp-auth.ts @@ -65,6 +65,8 @@ type McpGrantApi = Pick< | "revokeMcpAgent" | "mintMcpConnectionKey" | "revokeMcpConnectionKeys" + | "listMcpConnectionKeys" + | "revokeMcpConnectionKey" >; /** diff --git a/apps/hosted/server/src/contracts/mcp-connections.ts b/apps/hosted/server/src/contracts/mcp-connections.ts index 0184e740f5..51e3b80ec6 100644 --- a/apps/hosted/server/src/contracts/mcp-connections.ts +++ b/apps/hosted/server/src/contracts/mcp-connections.ts @@ -21,6 +21,7 @@ import { } from "@executor-js/mcp-auth/connections"; import { ConnectedAgent, ConnectedAgentNotFound } from "@executor-js/mcp-auth/agents"; import { GrantId } from "@executor-js/mcp-auth"; +import { ApiError } from "@executor-js/utils/api-error"; import { Schema } from "effect"; import { HttpApiEndpoint, HttpApiGroup } from "effect/http-api"; import { AuthenticationUnavailable, RequireUser } from "./auth.ts"; @@ -69,6 +70,28 @@ export const ConnectionKey = Schema.Struct({ url: Schema.String, expiresAt: Schema.String, }); +/** + * A key bound to one scoped connection, as its owner lists it: never the secret. `start` is the + * key's first characters, so the owner can tell which installed key it is. + */ +export const ConnectionKeySummary = Schema.Struct({ + id: Schema.String, + name: Schema.NullOr(Schema.String), + start: Schema.NullOr(Schema.String), + createdAt: Schema.String, + expiresAt: Schema.NullOr(Schema.String), + /** When the key was last used, when its store records it. */ + lastRequest: Schema.NullOr(Schema.String), +}); +export type ConnectionKeySummary = typeof ConnectionKeySummary.Type; +/** The connection has no such key: it was revoked, or belongs to another connection or user. */ +export const ConnectionKeyNotFound = ApiError.define({ + tag: "ConnectionKeyNotFound", + status: 404, + fields: { key: Schema.String }, + message: "This connection key was revoked or does not belong to this connection.", +}); +export type ConnectionKeyNotFound = typeof ConnectionKeyNotFound.Type; /** * MCP grants, including a connection's own, cannot manage connections: the API refuses MCP tokens. * Connections only narrow their owner's own access, so an admin key cannot widen anything. @@ -115,6 +138,20 @@ export const HostedMcpConnections = HttpApiGroup.make("mcpConnections") error: [...errors, ConnectionNotFound], }).annotate(RequiredAction, "manage"), ) + .add( + HttpApiEndpoint.get("listKeys", `${path}/:connection/keys`, { + params: connection, + success: Schema.Array(ConnectionKeySummary), + error: [...errors, ConnectionNotFound], + }).annotate(RequiredAction, "manage"), + ) + .add( + HttpApiEndpoint.post("revokeKey", `${path}/:connection/keys/:key/revoke`, { + params: { ...connection, key: Schema.NonEmptyString }, + success: Schema.Void, + error: [...errors, ConnectionNotFound, ConnectionKeyNotFound], + }).annotate(RequiredAction, "manage"), + ) .add( HttpApiEndpoint.get("agents", agentsPath, { params: organization, diff --git a/apps/hosted/server/src/contracts/mcp.ts b/apps/hosted/server/src/contracts/mcp.ts index b718ea25fa..02ffc2af2f 100644 --- a/apps/hosted/server/src/contracts/mcp.ts +++ b/apps/hosted/server/src/contracts/mcp.ts @@ -12,6 +12,7 @@ import { Context, Schema } from "effect"; import type { Effect } from "effect"; import { OrganizationAccess, type OrganizationReference } from "./organization.ts"; import { AuthenticationUnavailable } from "./auth.ts"; +import type { ConnectionKeyNotFound, ConnectionKeySummary } from "./mcp-connections.ts"; /** MCP authority from OAuth or a PAT and current membership. Tokens never become browser sessions. */ export const McpAccess = Schema.Struct({ @@ -139,6 +140,22 @@ export interface McpConnectionStore { { readonly id: string; readonly key: string; readonly expiresAt: string }, ConnectionNotFound | AuthenticationUnavailable >; + /** The keys bound to one of the owner's standing connections, without their secrets. */ + readonly keys: ( + owner: ConnectionOwner, + id: ConnectionId, + ) => Effect.Effect< + readonly ConnectionKeySummary[], + ConnectionNotFound | AuthenticationUnavailable + >; + /** + * Delete one key bound to one of the owner's standing connections. Bearer checks read the key + * row on every request, so it is refused at once; the connection and its other keys stay. + */ + readonly revokeKey: ( + owner: ConnectionOwner, + input: { readonly id: ConnectionId; readonly key: string }, + ) => Effect.Effect; /** Revoke one of the owner's grants and delete its access and refresh tokens. */ readonly revokeAgent: ( owner: ConnectionOwner, diff --git a/apps/hosted/server/src/implementation/mcp-connections.ts b/apps/hosted/server/src/implementation/mcp-connections.ts index 56ecc87f96..9704ab63ca 100644 --- a/apps/hosted/server/src/implementation/mcp-connections.ts +++ b/apps/hosted/server/src/implementation/mcp-connections.ts @@ -34,7 +34,7 @@ const owner = Effect.gen(function* () { * logged, as connections decide which accounts an agent runs as. */ const manager = ( - action: "list" | "create" | "update" | "revoke" | "mint-key", + action: "list" | "create" | "update" | "revoke" | "mint-key" | "list-keys" | "revoke-key", connection?: string, ) => Effect.gen(function* () { @@ -44,8 +44,8 @@ const manager = ( const organization = yield* CurrentOrganization; if (organization.role !== "admin" && organization.role !== "owner") return yield* new OrganizationForbidden(); - // Minting records its own audit line for every caller, with the key it made. - if (action !== "list" && action !== "mint-key") + // Minting and revoking a key record their own audit line for every caller, with the key. + if (action === "create" || action === "update" || action === "revoke") yield* Effect.logInfo("MCP connection changed with an API credential").pipe( Effect.annotateLogs({ "executor.audit": "mcp-connection", @@ -235,6 +235,33 @@ export const hostedMcpConnectionHandlers = HttpApiBuilder.group( }; }), ) + .handle("listKeys", ({ params }) => + // Only the connection's owner: the store reports any other connection as not found. + Effect.flatMap(manager("list-keys", params.connection), (current) => + auth.connections.keys(current, params.connection), + ), + ) + .handle("revokeKey", ({ params }) => + Effect.gen(function* () { + const current = yield* manager("revoke-key", params.connection); + yield* auth.connections.revokeKey(current, { + id: params.connection, + key: params.key, + }); + const person = yield* Effect.serviceOption(CurrentPrincipal); + yield* Effect.logInfo("MCP connection key revoked").pipe( + Effect.annotateLogs({ + "executor.audit": "mcp-connection-key", + "executor.audit.action": "revoke", + "executor.audit.via": Option.isSome(person) ? "browser" : "api-credential", + "executor.user.id": current.userId, + "executor.organization.id": current.resource, + "executor.mcp.connection": params.connection, + "executor.api_key.id": params.key, + }), + ); + }), + ) .handle("agents", () => Effect.flatMap(owner, (current) => auth.connections.agents(current)), ) diff --git a/apps/hosted/server/src/implementation/mcp-oauth.ts b/apps/hosted/server/src/implementation/mcp-oauth.ts index a6dad3a0ac..73ae56bafc 100644 --- a/apps/hosted/server/src/implementation/mcp-oauth.ts +++ b/apps/hosted/server/src/implementation/mcp-oauth.ts @@ -43,6 +43,7 @@ import { connectionGrantPolicy, } from "@executor-js/mcp-auth/connections"; import { ConnectedAgent, ConnectedAgentNotFound } from "@executor-js/mcp-auth/agents"; +import { ConnectionKeyNotFound, ConnectionKeySummary } from "../contracts/mcp-connections.ts"; import { OrganizationId, OrganizationRole, organizationOwner } from "../contracts/organization.ts"; const Member = Schema.Struct({ role: OrganizationRole }); /** The user's email for `ctx.approvedBy` on the browser approval page; null when unreadable. */ @@ -197,6 +198,62 @@ const BoundKeyMetadata = Schema.Union([ Schema.Struct({ connection: Schema.String }), Schema.fromJsonString(Schema.Struct({ connection: Schema.String })), ]); +/** The owner's standing connection, or NOT_FOUND for a revoked one or another user's. */ +const requireStandingConnection = async ( + context: GenericEndpointContext["context"], + owner: { readonly userId: string; readonly resource: string; readonly id: string }, +) => { + const row = await context.adapter.findOne({ + model: "mcpConnection", + where: [{ field: "id", value: owner.id }], + }); + const stored = Schema.decodeUnknownOption(StoredConnection)(row).pipe( + Option.filter( + (connection) => + connection.revoked === false && + connection.userId === owner.userId && + connection.resource === owner.resource, + ), + ); + if (Option.isNone(stored)) throw new APIError("NOT_FOUND"); +}; +/** A stored key row's non-secret fields. */ +interface StoredKey { + readonly id: string; + readonly name?: string | null; + readonly start?: string | null; + readonly createdAt?: unknown; + readonly expiresAt?: unknown; + readonly lastRequest?: unknown; + readonly metadata: unknown; +} +/** The user's keys whose metadata binds them to this connection. */ +const boundKeys = async ( + context: GenericEndpointContext["context"], + userId: string, + connection: string, +) => { + const keys = await context.adapter.findMany({ + model: "apikey", + where: [{ field: "referenceId", value: userId }], + }); + return keys.filter((key) => + Option.match(Schema.decodeUnknownOption(BoundKeyMetadata)(key.metadata), { + onNone: () => false, + onSome: (metadata) => metadata.connection === connection, + }), + ); +}; +/** A stored timestamp as ISO text; adapters return Dates or their text. */ +const isoTime = (value: unknown) => { + const date = + value instanceof Date + ? value + : typeof value === "string" || typeof value === "number" + ? new Date(value) + : undefined; + return date === undefined || Number.isNaN(date.getTime()) ? null : date.toISOString(); +}; /** Stable metadata identifies the PAT/organization/mode partition; it is never a credential. */ const projectPatAccess = ( ctx: GenericEndpointContext, @@ -340,19 +397,7 @@ export const mcpOAuthPlugins = (options: HostedOAuthOptions) => { metadata: { SERVER_ONLY: true }, }, async (ctx) => { - const row = await ctx.context.adapter.findOne({ - model: "mcpConnection", - where: [{ field: "id", value: ctx.body.id }], - }); - const stored = Schema.decodeUnknownOption(StoredConnection)(row).pipe( - Option.filter( - (connection) => - connection.revoked === false && - connection.userId === ctx.body.userId && - connection.resource === ctx.body.resource, - ), - ); - if (Option.isNone(stored)) throw new APIError("NOT_FOUND"); + await requireStandingConnection(ctx.context, ctx.body); const created = await apiKeys.endpoints.createApiKey({ context: ctx.context, body: { @@ -381,16 +426,7 @@ export const mcpOAuthPlugins = (options: HostedOAuthOptions) => { metadata: { SERVER_ONLY: true }, }, async (ctx) => { - const keys = await ctx.context.adapter.findMany<{ id: string; metadata: unknown }>({ - model: "apikey", - where: [{ field: "referenceId", value: ctx.body.userId }], - }); - const bound = keys.filter((key) => - Option.match(Schema.decodeUnknownOption(BoundKeyMetadata)(key.metadata), { - onNone: () => false, - onSome: (metadata) => metadata.connection === ctx.body.id, - }), - ); + const bound = await boundKeys(ctx.context, ctx.body.userId, ctx.body.id); for (const key of bound) await ctx.context.adapter.delete({ model: "apikey", @@ -399,6 +435,62 @@ export const mcpOAuthPlugins = (options: HostedOAuthOptions) => { return { deleted: bound.length }; }, ), + // The keys bound to one of the owner's standing connections. Never their secrets or hashes. + listMcpConnectionKeys: createAuthEndpoint( + "/mcp/connection-keys/list", + { + method: "POST", + body: Schema.toStandardSchemaV1( + Schema.Struct({ + userId: Schema.String, + resource: Schema.String, + id: ConnectionIdSchema, + }), + ), + metadata: { SERVER_ONLY: true }, + }, + async (ctx) => { + await requireStandingConnection(ctx.context, ctx.body); + const bound = await boundKeys(ctx.context, ctx.body.userId, ctx.body.id); + return bound + .map((key) => ({ + id: key.id, + name: key.name ?? null, + start: key.start ?? null, + createdAt: isoTime(key.createdAt) ?? new Date(0).toISOString(), + expiresAt: isoTime(key.expiresAt), + lastRequest: isoTime(key.lastRequest), + })) + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); + }, + ), + // Delete one key bound to one of the owner's standing connections. The connection and its + // other keys stay; bearer checks read the key row, so the deleted key is refused at once. + revokeMcpConnectionKey: createAuthEndpoint( + "/mcp/connection-keys/revoke-one", + { + method: "POST", + body: Schema.toStandardSchemaV1( + Schema.Struct({ + userId: Schema.String, + resource: Schema.String, + id: ConnectionIdSchema, + key: Schema.String, + }), + ), + metadata: { SERVER_ONLY: true }, + }, + async (ctx) => { + await requireStandingConnection(ctx.context, ctx.body); + const bound = await boundKeys(ctx.context, ctx.body.userId, ctx.body.id); + if (!bound.some((key) => key.id === ctx.body.key)) return { revoked: false }; + await ctx.context.adapter.delete({ + model: "apikey", + where: [{ field: "id", value: ctx.body.key }], + }); + return { revoked: true }; + }, + ), getMcpBrowserAccess: createAuthEndpoint( "/mcp/browser-access", { @@ -468,6 +560,12 @@ export interface McpConnectionApi { readonly revokeMcpConnectionKeys: (input: { body: { userId: string; resource: string; id: string }; }) => Promise; + readonly listMcpConnectionKeys: (input: { + body: { userId: string; resource: string; id: string }; + }) => Promise; + readonly revokeMcpConnectionKey: (input: { + body: { userId: string; resource: string; id: string; key: string }; + }) => Promise; } /** A minted connection key: the only response that contains its secret. */ const MintedConnectionKey = Schema.Struct({ @@ -548,6 +646,31 @@ export const mcpConnectionStore = ( : new AuthenticationUnavailable(), ), ), + keys: (owner, id) => + request( + (api) => api.listMcpConnectionKeys({ body: { ...owner, id } }), + Schema.Array(ConnectionKeySummary), + ).pipe( + Effect.mapError((status) => + status === 404 + ? new ConnectionNotFound({ connection: id }) + : new AuthenticationUnavailable(), + ), + ), + revokeKey: (owner, input) => + request( + (api) => api.revokeMcpConnectionKey({ body: { ...owner, ...input } }), + Schema.Struct({ revoked: Schema.Boolean }), + ).pipe( + Effect.mapError((status) => + status === 404 + ? new ConnectionNotFound({ connection: input.id }) + : new AuthenticationUnavailable(), + ), + Effect.flatMap(({ revoked }) => + revoked ? Effect.void : Effect.fail(new ConnectionKeyNotFound({ key: input.key })), + ), + ), agents: (owner) => request((api) => api.listMcpAgents({ body: owner }), Schema.Array(ConnectedAgent)).pipe( Effect.mapError(unavailable), diff --git a/apps/hosted/web/src/contracts/errors.ts b/apps/hosted/web/src/contracts/errors.ts index b60025bcac..6cee8a3822 100644 --- a/apps/hosted/web/src/contracts/errors.ts +++ b/apps/hosted/web/src/contracts/errors.ts @@ -29,6 +29,7 @@ const errorMessage = Match.type().pipe( ConnectionNotFound: () => "This connection was revoked or no longer exists.", ConnectionIdTaken: () => "This connection could not be created. Close the form and try again.", ConnectedAgentNotFound: () => "This agent is no longer connected.", + ConnectionKeyNotFound: () => "This key was already revoked.", ConnectionAccessInvalid: ({ reason }) => ({ app: "An included app is no longer available to you. Remove it and try again.", diff --git a/apps/hosted/web/src/contracts/mcp-connections.ts b/apps/hosted/web/src/contracts/mcp-connections.ts index ef7bce8fc3..dc7e929d37 100644 --- a/apps/hosted/web/src/contracts/mcp-connections.ts +++ b/apps/hosted/web/src/contracts/mcp-connections.ts @@ -13,6 +13,7 @@ import type { ConnectionId } from "@executor-js/mcp-auth/connections"; import { GrantId } from "@executor-js/mcp-auth/grants"; import type { ConnectionKeyRequest, + ConnectionKeyRevoke, ConnectionSave, } from "@executor-js/ui/contracts/scoped-connections"; import { acknowledge, acknowledgedQuery, upsert } from "@executor-js/ui/contracts/mutations"; @@ -44,14 +45,49 @@ export const saveMcpConnectionAtom = Atom.family((organization: OrganizationRefe }), ), ); +/** One connection's keys in one organization. */ +class ConnectionKeysKey extends Data.Class<{ + readonly organization: OrganizationReference; + readonly connection: ConnectionId; +}> {} +const connectionKeysQuery = Atom.family((key: ConnectionKeysKey) => + HostedClient.query("mcpConnections", "listKeys", hydrated({ params: key })).pipe( + revalidated, + acknowledgedQuery, + ), +); +/** The keys bound to one connection, without their secrets. */ +export const mcpConnectionKeysAtom = + (organization: OrganizationReference) => (connection: ConnectionId) => + connectionKeysQuery(new ConnectionKeysKey({ organization, connection })); /** Mint a key bound to one connection; the secret is returned only by this call. */ export const mintMcpConnectionKeyAtom = Atom.family((organization: OrganizationReference) => - HostedClient.runtime.fn(({ connection, expiresInSeconds }: ConnectionKeyRequest) => + HostedClient.runtime.fn(({ connection, expiresInSeconds }: ConnectionKeyRequest, get) => Effect.flatMap(HostedClient, (client) => client.mcpConnections.mintKey({ params: { organization, connection }, payload: { expiresInSeconds }, }), + ).pipe( + Effect.tap(() => + Effect.sync(() => get.refresh(mcpConnectionKeysAtom(organization)(connection))), + ), + ), + ), +); +/** Remove the key's row only after the server deleted it; the connection and other keys stay. */ +export const revokeMcpConnectionKeyAtom = Atom.family((organization: OrganizationReference) => + HostedClient.runtime.fn(({ connection, key }: ConnectionKeyRevoke, get) => + Effect.flatMap(HostedClient, (client) => + client.mcpConnections.revokeKey({ params: { organization, connection, key } }), + ).pipe( + Effect.tap(() => + Effect.sync(() => + acknowledge(get, mcpConnectionKeysAtom(organization)(connection), (current) => + current.filter((item) => item.id !== key), + ), + ), + ), ), ), ); diff --git a/apps/hosted/web/src/implementation/pages/connect.tsx b/apps/hosted/web/src/implementation/pages/connect.tsx index 78fa022e61..2bba4b07d6 100644 --- a/apps/hosted/web/src/implementation/pages/connect.tsx +++ b/apps/hosted/web/src/implementation/pages/connect.tsx @@ -11,10 +11,12 @@ import { resourceInventoryAtom } from "../../contracts/resource-access.ts"; import { connectionToolListAtom } from "../../contracts/apps.ts"; import { mcpAgentsAtom, + mcpConnectionKeysAtom, mcpConnectionsAtom, mintMcpConnectionKeyAtom, revokeMcpAgentAtom, revokeMcpConnectionAtom, + revokeMcpConnectionKeyAtom, saveMcpConnectionAtom, } from "../../contracts/mcp-connections.ts"; import { useDocumentationUrl } from "../documentation.ts"; @@ -80,6 +82,10 @@ export function ConnectPage() { save={saveMcpConnectionAtom(organization)} revoke={revokeMcpConnectionAtom(organization)} mintKey={mintMcpConnectionKeyAtom(organization)} + keys={{ + list: mcpConnectionKeysAtom(organization), + revoke: revokeMcpConnectionKeyAtom(organization), + }} Failure={HostedFailure} docs={docs} agents={ diff --git a/e2e/test-plan.ts b/e2e/test-plan.ts index b026e1b889..4ac22bfd97 100644 --- a/e2e/test-plan.ts +++ b/e2e/test-plan.ts @@ -7366,6 +7366,17 @@ export const scenarios = plan({ local: na("Local has one subject and no organization roles or API keys."), }, }, + connectionKeyRevoke: { + fixtures: "actors", + file: "connection-keys.spec.ts", + title: + "a connection's owner lists its keys without secrets and revokes one, through the API or the dashboard, which stops that key at once while the connection and its other keys keep working, and no one else can list or revoke them", + targets: { + "self-host": scheduled, + cloud: scheduled, + local: na("Local has one subject and no organization roles or API keys."), + }, + }, callerIdentity: { fixtures: "actors", file: "caller-identity.spec.ts", diff --git a/e2e/tests/connection-keys.spec.ts b/e2e/tests/connection-keys.spec.ts index a15a295a6b..a13b660256 100644 --- a/e2e/tests/connection-keys.spec.ts +++ b/e2e/tests/connection-keys.spec.ts @@ -2,11 +2,13 @@ * A connection key is an API key bound to one scoped MCP connection, for headless agents, CI and * staff bots. Only the connection's owner mints one, it always expires, it works only at its * connection's MCP URL, the API never accepts it, revoking the connection deletes it, and every - * mint is in the audit log. + * mint is in the audit log. The owner lists a connection's keys without their secrets and revokes + * one at a time, so a seat's key can be rotated without revoking the connection. */ import { expect, layer } from "@effect/vitest"; import { Effect, Exit, Redacted, Schedule, Schema } from "effect"; import { randomBytes, randomUUID } from "node:crypto"; +import type { Page } from "playwright"; import { scenarios } from "../test-plan.ts"; import { Api, body, type Session } from "../support/api.ts"; import { Actors } from "../support/actors.ts"; @@ -26,6 +28,15 @@ const ConnectionKey = Schema.Struct({ expiresAt: Schema.String, }); const Keys = Schema.Struct({ apiKeys: Schema.Array(Schema.Struct({ id: Schema.String })) }); +/** A listed connection key: never its secret. */ +const KeySummary = Schema.Struct({ + id: Schema.String, + name: Schema.NullOr(Schema.String), + start: Schema.NullOr(Schema.String), + createdAt: Schema.String, + expiresAt: Schema.NullOr(Schema.String), + lastRequest: Schema.NullOr(Schema.String), +}); const initialize = { jsonrpc: "2.0", id: 1, @@ -238,4 +249,228 @@ layer(HostedLive, { excludeTestServices: true })("Connection keys", (it) => { }).pipe(Effect.provide(McpClient.layer)), ), ); + + it.effect(scenarios.connectionKeyRevoke.title, (context) => + withHostedCase( + context, + Effect.gen(function* () { + const api = yield* Api, + actors = yield* Actors, + mcp = yield* McpClient, + telemetry = yield* Telemetry; + const organization = actors.organization.id; + const prefix = `/api/organizations/${organization}`; + const receipt = randomUUID(); + const deployed = yield* api.request(actors.owner, "POST", `${prefix}/apps/deploy`, { + name: `Key rotation app ${receipt.slice(0, 8)}`, + files: readWriteAppFiles(receipt), + }); + expect(deployed.status, JSON.stringify(deployed.body)).toBe(200); + const app = yield* body(App, deployed); + const appPath = `${prefix}/apps/${app.id}`; + yield* Effect.addFinalizer(() => + api.request(actors.owner, "DELETE", appPath).pipe(Effect.ignore), + ); + const access = yield* body( + Access, + yield* api.request(actors.owner, "GET", `${appPath}/access`), + ); + expect( + (yield* api.request(actors.owner, "PATCH", `${appPath}/access`, { + revision: access.revision, + audience: { kind: "everyone" }, + })).status, + ).toBe(200); + const connect = (name: string) => + Effect.gen(function* () { + const created = yield* api.request(actors.member, "POST", `${prefix}/mcp-connections`, { + id: randomUUID(), + name, + apps: [{ app: app.id, runsAs: [{ kind: "app" }], tools: { kind: "readOnly" } }], + }); + expect(created.status, JSON.stringify(created.body)).toBe(200); + return yield* body(ConnectionView, created); + }); + const seat = yield* connect(`Seat ${receipt.slice(0, 6)}`); + const other = yield* connect(`Other seat ${receipt.slice(0, 6)}`); + const keysPath = (connection: string) => `${prefix}/mcp-connections/${connection}/keys`; + const revokePath = (connection: string, key: string) => + `${keysPath(connection)}/${key}/revoke`; + const mint = (name: string) => + Effect.gen(function* () { + const minted = yield* api.request(actors.member, "POST", keysPath(seat.id), { + name, + expiresInSeconds: 90 * 86400, + }); + expect(minted.status, JSON.stringify(minted.body)).toBe(200); + return yield* body(ConnectionKey, minted); + }); + + // The seat's owner mints its current key and the replacement. + const current = yield* mint(`Seat key ${receipt.slice(0, 6)}`); + const replacement = yield* mint(`Replacement ${receipt.slice(0, 6)}`); + + // The owner lists both, newest first, with names and expiry but never the secrets. + const listed = yield* api.request(actors.member, "GET", keysPath(seat.id)); + expect(listed.status, JSON.stringify(listed.body)).toBe(200); + const keys = yield* body(Schema.Array(KeySummary), listed); + expect(keys.map((key) => key.id).sort()).toEqual([current.id, replacement.id].sort()); + for (const [key, secret] of [ + [keys.find((item) => item.id === current.id), current.key], + [keys.find((item) => item.id === replacement.id), replacement.key], + ] as const) { + expect(key?.expiresAt).not.toBeNull(); + expect(key?.start).not.toBeNull(); + expect(Redacted.value(secret).startsWith(key?.start ?? "-")).toBe(true); + expect(Redacted.value(secret).length).toBeGreaterThan((key?.start ?? "").length + 16); + } + expect(keys.map((key) => key.name).sort()).toEqual( + [`Replacement ${receipt.slice(0, 6)}`, `Seat key ${receipt.slice(0, 6)}`].sort(), + ); + const listedText = JSON.stringify(listed.body); + expect(listedText).not.toContain(Redacted.value(current.key)); + expect(listedText).not.toContain(Redacted.value(replacement.key)); + expect(listedText).not.toContain('"key"'); + // Another connection lists none of them. + const otherKeys = yield* api.request(actors.member, "GET", keysPath(other.id)); + expect(otherKeys.status).toBe(200); + expect(otherKeys.body).toEqual([]); + + // No one else can list or revoke them: an admin and the organization's owner see no such + // connection, and the key itself is never accepted by the API. + for (const actor of [actors.admin, actors.owner]) { + expect((yield* api.request(actor, "GET", keysPath(seat.id))).status).toBe(404); + expect((yield* api.request(actor, "POST", revokePath(seat.id, current.id))).status).toBe( + 404, + ); + } + const asKey = ( + secret: Redacted.Redacted, + method: "GET" | "POST", + path: string, + data?: unknown, + ) => + Effect.gen(function* () { + return yield* api.request(yield* api.session(), method, path, data, { + authorization: `Bearer ${Redacted.value(secret)}`, + "x-executor-organization": organization, + accept: "application/json, text/event-stream", + }); + }); + for (const [method, path] of [ + ["GET", keysPath(seat.id)], + ["POST", revokePath(seat.id, current.id)], + ] as const) { + const refused = yield* asKey(replacement.key, method, path); + expect(refused.status, JSON.stringify(refused.body)).toBe(403); + expect(JSON.stringify(refused.body)).toContain("ConnectionKeyRefused"); + } + // A key is revoked only through its own connection. + const elsewhere = yield* api.request( + actors.member, + "POST", + revokePath(other.id, current.id), + ); + expect(elsewhere.status, JSON.stringify(elsewhere.body)).toBe(404); + expect(JSON.stringify(elsewhere.body)).toContain("ConnectionKeyNotFound"); + + // Both keys work at the seat's URL before the rotation. + const atConnection = (secret: Redacted.Redacted, label: string) => + Effect.exit( + Effect.gen(function* () { + const client = yield* mcp.connect(secret, label, { + organization, + connection: seat.id, + }); + return yield* client.use(`${label}: list tools`, (session, signal) => + session.listTools(undefined, { signal }), + ); + }), + ); + expect(Exit.isSuccess(yield* atConnection(current.key, "current key"))).toBe(true); + expect(Exit.isSuccess(yield* atConnection(replacement.key, "replacement key"))).toBe(true); + + // The owner revokes the old key; the revocation is in the audit log. + const trace = randomBytes(16).toString("hex"); + const revoked = yield* api.request( + actors.member, + "POST", + revokePath(seat.id, current.id), + undefined, + { traceparent: `00-${trace}-${randomBytes(8).toString("hex")}-01` }, + ); + expect(revoked.status, JSON.stringify(revoked.body)).toBeLessThan(300); + const audit = yield* telemetry.logs(trace, "MCP connection key revoked").pipe( + Effect.map((found) => found.join("\n")), + Effect.filterOrFail((text) => text.includes(current.id)), + Effect.retry({ schedule: Schedule.spaced("1 second"), times: 20 }), + ); + expect(audit).toContain(seat.id); + expect(audit).toContain("mcp-connection-key"); + + // The old key is refused at once at the seat's URL; the replacement keeps working. + const refused = yield* asKey(current.key, "POST", `/mcp?connection=${seat.id}`, initialize); + expect(refused.status, JSON.stringify(refused.body)).toBe(401); + expect(Exit.isFailure(yield* atConnection(current.key, "revoked key"))).toBe(true); + expect(Exit.isSuccess(yield* atConnection(replacement.key, "kept key"))).toBe(true); + // The connection stands, with only the replacement listed; revoking again finds nothing. + const connections = yield* body( + Schema.Array(ConnectionView), + yield* api.request(actors.member, "GET", `${prefix}/mcp-connections`), + ); + expect(connections.map((connection) => connection.id)).toContain(seat.id); + const remaining = yield* body( + Schema.Array(KeySummary), + yield* api.request(actors.member, "GET", keysPath(seat.id)), + ); + expect(remaining.map((key) => key.id)).toEqual([replacement.id]); + expect( + (yield* api.request(actors.member, "POST", revokePath(seat.id, current.id))).status, + ).toBe(404); + + // In the dashboard the owner sees the seat's key and revokes it after confirming. + const browser = yield* Browser; + yield* browser.login(actors.member); + yield* browser.use("Open the member's connections", (page) => + page.goto(`/org/${actors.organization.slug}/connect`), + ); + yield* browser.use("Open the seat's connection", (page) => + page.getByRole("button", { name: new RegExp(seat.name) }).click(), + ); + const keyName = `Replacement ${receipt.slice(0, 6)}`; + const keyList = (page: Page) => page.getByRole("region", { name: "Connection keys" }); + yield* browser.use("See the replacement key listed", (page) => + keyList(page) + .getByRole("listitem") + .filter({ hasText: keyName }) + .waitFor({ state: "visible" }), + ); + const shownText = yield* browser.use("Read the key list", (page) => + keyList(page).innerText(), + ); + expect(shownText).not.toContain(Redacted.value(replacement.key)); + expect(shownText).not.toContain(`Seat key ${receipt.slice(0, 6)}`); + yield* browser.use("Start revoking the key", (page) => + keyList(page) + .getByRole("button", { name: `Revoke ${keyName}`, exact: true }) + .click(), + ); + yield* browser.use("Confirm the revocation", (page) => + page.getByRole("button", { name: "Revoke key", exact: true }).click(), + ); + yield* browser.use("The key leaves the list", (page) => + keyList(page).getByText("No keys.", { exact: false }).waitFor({ state: "visible" }), + ); + expect(Exit.isFailure(yield* atConnection(replacement.key, "dashboard-revoked key"))).toBe( + true, + ); + // The connection still stands after both revocations. + const after = yield* body( + Schema.Array(ConnectionView), + yield* api.request(actors.member, "GET", `${prefix}/mcp-connections`), + ); + expect(after.map((connection) => connection.id)).toContain(seat.id); + }).pipe(Effect.provide(McpClient.layer)), + ), + ); }); diff --git a/packages/app-templates/executor/skills/app-authoring/accounts.md b/packages/app-templates/executor/skills/app-authoring/accounts.md index 60f607367d..89d96d920a 100644 --- a/packages/app-templates/executor/skills/app-authoring/accounts.md +++ b/packages/app-templates/executor/skills/app-authoring/accounts.md @@ -651,7 +651,11 @@ connection's owner mints one with `POST /api/organizations/:organization/mcp-con and `{ "expiresInSeconds": <5 to 7776000>, "name"?: "..." }`, from the dashboard session or their own API key. The response holds the only copy of the secret. A connection key works only at its connection's `url`; plain `/mcp`, other connections and the Executor API refuse it with a 403. It -expires, revoking the connection deletes it, and every mint is in the audit log. +expires, revoking the connection deletes it, and every mint is in the audit log. To rotate one, +mint the new key, install it, then revoke the old one: `GET .../mcp-connections//keys` lists +the connection's keys (id, name, first characters, created, expiry, last use; never the secret) +and `POST .../mcp-connections//keys//revoke` stops one key at once while the +connection and its other keys keep working. For one key that runs an app for everyone, a member can connect it as a shared account, and someone who can edit the app links it to the app's own requirement with `appAccounts.appLink`. diff --git a/packages/app-templates/src/implementation/executor-skill-digests.gen.ts b/packages/app-templates/src/implementation/executor-skill-digests.gen.ts index a1d123513a..5e5346b795 100644 --- a/packages/app-templates/src/implementation/executor-skill-digests.gen.ts +++ b/packages/app-templates/src/implementation/executor-skill-digests.gen.ts @@ -3,7 +3,7 @@ /** SHA-256 of each file the Executor app publishes as a skill, keyed by `/`. */ export const executorSkillDigests: Readonly> = { "app-authoring/SKILL.md": "87118b0f1b98968a64fd6ba64dce39d1fde6c78f781f34ba85063ef4e44355a3", - "app-authoring/accounts.md": "e41daf53848de95cb003f0b8ca44b2f9422fc3b285cbfce889d8e9cf7d19f02c", + "app-authoring/accounts.md": "6bfd911f629a19b1d1ac96a5cb33977426ba47eb9695d1551395c4891b52a7df", "app-authoring/deploy.md": "c720ab582e4e5e3c75996d989ed2f65840208506ed76df3fc00864cd29e7d1dc", "app-authoring/events.md": "8f7465e35c6c94b06978b89680181df60c741225de3ba8158f22f76ee7e91a5a", "app-authoring/integrations.md": "9484086b1cb68aa9a9a1a0eb4ca20654c76702eda82675b35f46861bedc30a3a", diff --git a/packages/ui/src/contracts/scoped-connections.ts b/packages/ui/src/contracts/scoped-connections.ts index d11a20c35a..de430f2e03 100644 --- a/packages/ui/src/contracts/scoped-connections.ts +++ b/packages/ui/src/contracts/scoped-connections.ts @@ -112,3 +112,23 @@ export interface MintedConnectionKey { } /** Hosts that issue connection keys bind this; the page then offers to create one. */ export type ConnectionKeyMint = Atom.AtomResultFn; +/** A key bound to one connection, as its owner lists it. It never carries the secret. */ +export interface ConnectionKeyView { + readonly id: string; + readonly name: string | null; + /** The key's first characters, to tell installed keys apart. */ + readonly start: string | null; + readonly createdAt: string; + readonly expiresAt: string | null; + readonly lastRequest: string | null; +} +/** Revoke one key bound to one connection; the connection and its other keys stay. */ +export interface ConnectionKeyRevoke { + readonly connection: ConnectionId; + readonly key: string; +} +/** Hosts that list and revoke connection keys bind these; the connection's page then shows them. */ +export interface ConnectionKeyBindings { + readonly list: (connection: ConnectionId) => Query; + readonly revoke: Atom.AtomResultFn; +} diff --git a/packages/ui/src/implementation/dashboard/scoped-connections.tsx b/packages/ui/src/implementation/dashboard/scoped-connections.tsx index 2b626724c2..7c16348b6e 100644 --- a/packages/ui/src/implementation/dashboard/scoped-connections.tsx +++ b/packages/ui/src/implementation/dashboard/scoped-connections.tsx @@ -21,7 +21,9 @@ import { connectionTargetLabel, connectionToolsLabel, connectionEventsLabel, + type ConnectionKeyBindings, type ConnectionKeyMint, + type ConnectionKeyView, type MintedConnectionKey, type ScopedConnectionBindings, } from "../../contracts/scoped-connections.ts"; @@ -46,6 +48,7 @@ import { } from "../components/dialog.tsx"; import { Popover, PopoverContent, PopoverTrigger } from "../components/popover.tsx"; import { Skeleton } from "../components/skeleton.tsx"; +import { LocalTime, RelativeTime, shortMoment } from "../components/local-time.tsx"; import { PageFrame, PageHeader } from "./page.tsx"; import { QueryView } from "./context.tsx"; import { AppIcon } from "./common.tsx"; @@ -131,6 +134,7 @@ export function ScopedConnectionsPage< save, revoke, mintKey, + keys, Failure, installation, agents, @@ -139,6 +143,8 @@ export function ScopedConnectionsPage< }: ScopedConnectionBindings & { /** Mints keys bound to one connection, when the host issues them. */ readonly mintKey?: ConnectionKeyMint; + /** Lists and revokes one connection's keys, when the host issues them. */ + readonly keys?: ConnectionKeyBindings; readonly query: Query; /** Renders every failure: inventory, connection reads, saves and revocation. */ readonly Failure: ComponentType>; @@ -297,6 +303,9 @@ export function ScopedConnectionsPage< + {keys !== undefined && ( + + )}

Connect your agent

({ ); } +const keyName = (key: ConnectionKeyView) => key.name?.trim() || "Unnamed key"; + +/** + * The keys bound to this connection, newest first, without their secrets. Revoking one stops it + * at once and leaves the connection and its other keys working, so a key can be rotated: create + * a new one, install it, then revoke the old one. + */ +function ConnectionKeys({ + connection, + keys, + Failure, +}: { + readonly connection: ConnectionView; + readonly keys: ConnectionKeyBindings; + readonly Failure: ComponentType>; +}) { + const [revoking, setRevoking] = useState(); + const submit = useAtomSet(keys.revoke, { mode: "promiseExit" }); + const state = useAtomValue(keys.revoke); + return ( +
+

Connection keys

+ + query={keys.list(connection.id)} + Failure={Failure} + pending={ +
+ +
+ } + > + {(items) => + items.length === 0 ? ( +

+ No keys. Create one for an agent, CI job or bot that cannot sign in. +

+ ) : ( +
    + {items.map((key) => { + const expired = + key.expiresAt !== null && new Date(key.expiresAt).getTime() <= Date.now(); + return ( +
  • +
    +

    + {keyName(key)} + {key.start !== null && ( + + {key.start}… + + )} +

    +

    + {"Created "} + + {key.expiresAt !== null && ( + <> + {expired ? " · Expired " : " · Expires "} + + + )} + {key.lastRequest !== null && ( + <> + {" · Last used "} + + + )} +

    +
    + +
  • + ); + })} +
+ ) + } + + { + if (!open && !state.waiting) setRevoking(undefined); + }} + > + + + Revoke {revoking === undefined ? "" : keyName(revoking)}? + + Agents using this key lose access immediately. The connection and its other keys keep + working. + + + {AsyncResult.isFailure(state) && } + + + + + + +
+ ); +} + /** Shares the scoped list's heading and row rhythm so loading does not reflow the page. */ function ConnectionListSkeleton() { return (