Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/connection-key-revoke.md
Original file line number Diff line number Diff line change
@@ -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/<id>/keys` lists each
key's name, first characters, creation, expiry and last use, never the secret, and
`POST .../mcp-connections/<id>/keys/<key>/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.
2 changes: 2 additions & 0 deletions apps/hosted/cloud/src/infrastructure/mcp-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ type McpGrantApi = Pick<
| "revokeMcpAgent"
| "mintMcpConnectionKey"
| "revokeMcpConnectionKeys"
| "listMcpConnectionKeys"
| "revokeMcpConnectionKey"
>;

/**
Expand Down
37 changes: 37 additions & 0 deletions apps/hosted/server/src/contracts/mcp-connections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down
17 changes: 17 additions & 0 deletions apps/hosted/server/src/contracts/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -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<void, ConnectionNotFound | ConnectionKeyNotFound | AuthenticationUnavailable>;
/** Revoke one of the owner's grants and delete its access and refresh tokens. */
readonly revokeAgent: (
owner: ConnectionOwner,
Expand Down
33 changes: 30 additions & 3 deletions apps/hosted/server/src/implementation/mcp-connections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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* () {
Expand All @@ -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",
Expand Down Expand Up @@ -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)),
)
Expand Down
169 changes: 146 additions & 23 deletions apps/hosted/server/src/implementation/mcp-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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<StoredKey>({
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,
Expand Down Expand Up @@ -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: {
Expand Down Expand Up @@ -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",
Expand All @@ -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",
{
Expand Down Expand Up @@ -468,6 +560,12 @@ export interface McpConnectionApi {
readonly revokeMcpConnectionKeys: (input: {
body: { userId: string; resource: string; id: string };
}) => Promise<unknown>;
readonly listMcpConnectionKeys: (input: {
body: { userId: string; resource: string; id: string };
}) => Promise<unknown>;
readonly revokeMcpConnectionKey: (input: {
body: { userId: string; resource: string; id: string; key: string };
}) => Promise<unknown>;
}
/** A minted connection key: the only response that contains its secret. */
const MintedConnectionKey = Schema.Struct({
Expand Down Expand Up @@ -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),
Expand Down
1 change: 1 addition & 0 deletions apps/hosted/web/src/contracts/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const errorMessage = Match.type<HostedError>().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.",
Expand Down
Loading
Loading