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
13 changes: 13 additions & 0 deletions .changeset/connection-id-reuse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
"@executor-js/mcp-auth": patch
"@executor-js/hosted-server": patch
---

A member can create a scoped MCP connection with the ID of one of their own revoked connections, so
the `/mcp?connection=<id>` URL agents were given keeps its address. This replaces the revoked record.
It does not restore it. Grants that name the ID are revoked again. Its OAuth resources are enabled,
and the new record's creation time becomes its generation. Connection keys minted before then, and
PAT grant IDs that carry an older generation, are refused at the URL and deleted. A grant stored
while its connection was revoked or replaced is revoked when it is created. Creating a live
connection again returns it unchanged only when the name and access match. A different body, or
another user's live or revoked ID, still fails with `ConnectionIdTaken`.
35 changes: 27 additions & 8 deletions apps/hosted/server/src/implementation/bearer-access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@ const PatRow = Schema.Struct({
userId: Schema.String,
metadata: Schema.NullOr(Schema.String),
expiresAt: Schema.NullOr(Schema.Number),
createdAt: Schema.Number,
usable: Schema.Boolean,
contended: Schema.Boolean,
userExists: Schema.Boolean,
Expand Down Expand Up @@ -449,7 +450,7 @@ const loadPat = (
) =>
sql`
with k as (
select id, "referenceId", metadata, "expiresAt",
select id, "referenceId", metadata, "expiresAt", "createdAt",
enabled is not false and remaining is null as usable,
enabled is not false and "expiresAt" < to_timestamp(${at}::float8 / 1000) as expired,
"lastRequest" > to_timestamp(${at - lastRequestPrecision}::float8 / 1000) as recorded
Expand All @@ -472,6 +473,7 @@ const loadPat = (
k."referenceId" as "userId",
k.metadata,
floor(extract(epoch from k."expiresAt") * 1000)::float8 as "expiresAt",
floor(extract(epoch from k."createdAt") * 1000)::float8 as "createdAt",
k.usable and not coalesce(k.expired, false)
and (coalesce(k.recorded, false) or exists (select 1 from used)) as usable,
k.usable and not coalesce(k.expired, false) and not coalesce(k.recorded, false)
Expand Down Expand Up @@ -550,6 +552,8 @@ const patAccess = (sql: SqlClient.SqlClient, token: string, request: BearerReque
organizationSlug: membership?.slug ?? null,
/** The scoped connection this key is bound to, if it was minted for one. */
connection: metadata?.connection,
/** When the key was minted, in epoch milliseconds. */
createdAt: row.createdAt,
};
});

Expand All @@ -558,12 +562,15 @@ const ConnectionRow = Schema.Struct({
resource: Schema.String,
revoked: Schema.NullOr(Schema.Boolean),
policy: Schema.String,
createdAt: Schema.Number,
});

/**
* The policy a PAT gets at a scoped connection's URL: the connection's own, read on every use. Only
* the connection's owner may use it, in the organization it was made for, while it stands. The PAT
* has its user's full authority, so the connection can only narrow it. None when it does not stand.
* Its generation is when the record was made: a revoked connection's ID can be used again, and
* credentials and grant IDs from before then must not match the new record.
*/
export const patConnectionPolicy = (
sql: SqlClient.SqlClient,
Expand All @@ -572,7 +579,8 @@ export const patConnectionPolicy = (
organization: string,
) =>
Effect.gen(function* () {
const rows = yield* sql`select "userId", resource, revoked, policy::text as policy
const rows = yield* sql`select "userId", resource, revoked, policy::text as policy,
floor(extract(epoch from "createdAt") * 1000)::float8 as "createdAt"
from "mcpConnection" where id = ${connection}`;
const row = Schema.decodeUnknownOption(ConnectionRow)(rows[0]);
if (
Expand All @@ -581,10 +589,11 @@ export const patConnectionPolicy = (
row.value.userId !== userId ||
row.value.resource !== organization
)
return Option.none<GrantPolicy>();
return Option.none<{ readonly policy: GrantPolicy; readonly generation: number }>();
const generation = row.value.createdAt;
return Schema.decodeUnknownOption(Schema.fromJsonString(ConnectionPolicy))(
row.value.policy,
).pipe(Option.map(connectionGrantPolicy));
).pipe(Option.map((policy) => ({ policy: connectionGrantPolicy(policy), generation })));
});

/** MCP authority for an OAuth grant or a PAT, with live grant, connection and membership. */
Expand Down Expand Up @@ -620,17 +629,26 @@ export const mcpBearerAccess = (
// grant, which the URL's delivery check refuses and names the URL it serves.
const scoped =
request.connection === undefined
? Option.none<GrantPolicy>()
? Option.none<{ readonly policy: GrantPolicy; readonly generation: number }>()
: yield* patConnectionPolicy(
sql,
request.connection,
key.userId,
key.access.organization,
).pipe(Effect.mapError(() => unavailable));
// A connection key dies with its connection: it has no unscoped grant to fall back on.
if (key.connection !== undefined && Option.isNone(scoped)) return yield* unauthorized;
// A connection key dies with its connection: it has no unscoped grant to fall back on. A
// connection made again with a revoked one's ID is another connection, not the key's.
if (
key.connection !== undefined &&
(Option.isNone(scoped) || key.createdAt < scoped.value.generation)
)
return yield* unauthorized;
const connection = Option.isSome(scoped) ? request.connection : undefined;
const policy: GrantPolicy = Option.getOrElse(scoped, () => ({ kind: "all" }) as const);
const generation = Option.isSome(scoped) ? scoped.value.generation : undefined;
const policy: GrantPolicy = Option.match(scoped, {
onNone: () => ({ kind: "all" }) as const,
onSome: (value) => value.policy,
});
return McpAccess.make({
userId: key.userId,
email: key.email,
Expand All @@ -641,6 +659,7 @@ export const mcpBearerAccess = (
organization: key.access.organization,
mode,
...(connection === undefined ? {} : { connection }),
...(generation === undefined ? {} : { generation }),
}),
policy,
target: { kind: "mcp", mode, ...(connection === undefined ? {} : { connection }) },
Expand Down
17 changes: 16 additions & 1 deletion apps/hosted/server/src/implementation/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,25 @@ const grantStanding = (sql: SqlClient.SqlClient, id: string) =>
if (expiresAt !== null && (yield* Clock.currentTimeMillis) > expiresAt) return Option.none();
// A PAT grant at a connection's URL stands only while that connection does, with its policy.
const connection = pat.value.connection;
// A grant ID from before the connection was made again names the revoked one.
const generation = pat.value.generation;
const policy =
connection === undefined
? Option.some(GrantPolicy.make({ kind: "all" }))
: yield* patConnectionPolicy(sql, connection, key.value.userId, pat.value.organization);
: yield* patConnectionPolicy(
sql,
connection,
key.value.userId,
pat.value.organization,
).pipe(
Effect.map(
Option.flatMap((current) =>
generation === undefined || generation === current.generation
? Option.some(current.policy)
: Option.none(),
),
),
);
return Option.map(policy, (policy) => ({
userId: key.value.userId,
organization: pat.value.organization,
Expand Down
58 changes: 55 additions & 3 deletions apps/hosted/server/src/implementation/mcp-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,11 @@ export const PatGrant = Schema.Struct({
mode: ApprovalMode,
/** The scoped connection whose URL the PAT was used at; its policy narrows the PAT's. */
connection: Schema.optionalKey(ConnectionIdSchema),
/**
* When that connection was made, in epoch milliseconds. A revoked connection's ID can name a
* new connection; a grant ID from the revoked one must not resolve to it.
*/
generation: Schema.optionalKey(Schema.Number),
});
const patGrantPrefix = "pat:";
/** The PAT a synthetic grant ID names, or none for an OAuth grant ID. */
Expand Down Expand Up @@ -188,6 +193,7 @@ const StoredConnection = Schema.Struct({
resource: Schema.String,
revoked: Schema.Boolean,
policy: Schema.Unknown,
createdAt: Schema.Date,
});
const ConnectionPolicyJson = Schema.Union([
ConnectionPolicy,
Expand Down Expand Up @@ -261,6 +267,7 @@ const projectPatAccess = (
organization: OrganizationId,
mode: ApprovalMode,
connection?: ConnectionId,
generation?: number,
) =>
Effect.gen(function* () {
yield* requirePinnedOrganization(identity, organization);
Expand All @@ -281,7 +288,8 @@ const projectPatAccess = (
(stored) =>
stored.revoked === false &&
stored.userId === identity.userId &&
stored.resource === organization,
stored.resource === organization &&
(generation === undefined || generation === stored.createdAt.getTime()),
),
Option.flatMap((stored) =>
Schema.decodeUnknownOption(ConnectionPolicyJson)(stored.policy),
Expand All @@ -306,6 +314,7 @@ const projectPatAccess = (
organization,
mode,
...(connection === undefined ? {} : { connection }),
...(generation === undefined ? {} : { generation }),
}),
policy,
target: { kind: "mcp", mode, ...(connection === undefined ? {} : { connection }) },
Expand Down Expand Up @@ -411,7 +420,8 @@ export const mcpOAuthPlugins = (options: HostedOAuthOptions) => {
return { id: created.id, key: created.key, expiresAt: created.expiresAt.toISOString() };
},
),
// Revoking a connection deletes the keys bound to it; bearer checks already refuse them.
// Revoking a connection deletes the keys bound to it; bearer checks already refuse them. A
// connection made again with a revoked one's ID keeps only keys minted for the new one.
revokeMcpConnectionKeys: createAuthEndpoint(
"/mcp/connection-keys/revoke",
{
Expand All @@ -426,7 +436,40 @@ export const mcpOAuthPlugins = (options: HostedOAuthOptions) => {
metadata: { SERVER_ONLY: true },
},
async (ctx) => {
const bound = await boundKeys(ctx.context, ctx.body.userId, ctx.body.id);
const connection = Schema.decodeUnknownOption(StoredConnection)(
await ctx.context.adapter.findOne({
model: "mcpConnection",
where: [{ field: "id", value: ctx.body.id }],
}),
).pipe(
Option.filter(
(stored) =>
stored.revoked === false &&
stored.userId === ctx.body.userId &&
stored.resource === ctx.body.resource,
),
);
const keys = await ctx.context.adapter.findMany<{
id: string;
metadata: unknown;
createdAt: 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,
}) &&
Option.match(connection, {
onNone: () => true,
onSome: (current) =>
!(key.createdAt instanceof Date) ||
key.createdAt.getTime() < current.createdAt.getTime(),
}),
);
for (const key of bound)
await ctx.context.adapter.delete({
model: "apikey",
Expand Down Expand Up @@ -514,6 +557,7 @@ export const mcpOAuthPlugins = (options: HostedOAuthOptions) => {
target.organization,
target.mode,
target.connection,
target.generation,
);
}),
),
Expand Down Expand Up @@ -602,6 +646,14 @@ export const mcpConnectionStore = (
),
create: (owner, input) =>
request((api) => api.createMcpConnection({ body: { ...owner, ...input } }), Connection).pipe(
// A revoked connection's ID may name the new one. Delete keys left from the revoked one,
// which bearer checks already refuse, as revoking it would have.
Effect.tap(() =>
request(
(api) => api.revokeMcpConnectionKeys({ body: { ...owner, id: input.id } }),
Schema.Struct({ deleted: Schema.Number }),
),
),
Effect.mapError((status) =>
status === 409
? new ConnectionIdTaken({ connection: input.id })
Expand Down
4 changes: 2 additions & 2 deletions e2e/test-plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5878,7 +5878,7 @@ export const scenarios = plan({
fixtures: "actors",
file: "mcp-connections.spec.ts",
title:
"Scoped connections issue their own MCP URL and follow live edits, read-only rules and revocation",
"Scoped connections issue their own MCP URL and follow live edits, read-only rules and revocation, and a revoked ID can name a new connection without reviving its grants",
targets: {
"self-host": scheduled,
cloud: scheduled,
Expand Down Expand Up @@ -7359,7 +7359,7 @@ export const scenarios = plan({
fixtures: "actors",
file: "connection-keys.spec.ts",
title:
"a connection key minted by its connection's owner, through the API or the dashboard, expires, works only at that connection's MCP URL, is refused by the API and elsewhere, dies with the connection and is audited",
"a connection key minted by its connection's owner, through the API or the dashboard, expires, works only at that connection's MCP URL, is refused by the API and elsewhere, dies with the connection and is audited, and stays refused when its owner makes a new connection with the revoked ID",
targets: {
"self-host": scheduled,
cloud: scheduled,
Expand Down
72 changes: 71 additions & 1 deletion e2e/tests/connection-keys.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ const ConnectionKey = Schema.Struct({
url: Schema.String,
expiresAt: Schema.String,
});
const ConnectionWithTimes = Schema.Struct({
...ConnectionView.fields,
createdAt: 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({
Expand Down Expand Up @@ -90,7 +94,7 @@ layer(HostedLive, { excludeTestServices: true })("Connection keys", (it) => {
apps: policy,
});
expect(created.status, JSON.stringify(created.body)).toBe(200);
return yield* body(ConnectionView, created);
return yield* body(ConnectionWithTimes, created);
});
const bound = yield* connect(`Bound ${receipt.slice(0, 6)}`);
const other = yield* connect(`Other ${receipt.slice(0, 6)}`);
Expand Down Expand Up @@ -246,6 +250,72 @@ layer(HostedLive, { excludeTestServices: true })("Connection keys", (it) => {
yield* api.request(actors.member, "GET", "/api/auth/api-key/list"),
);
expect(remaining.apiKeys.map((item) => item.id)).not.toContain(key.id);

// Its owner can make a connection with the revoked one's ID again, so the URL agents were
// given keeps its address. It is a new connection: keys minted for the revoked one stay
// refused there and everywhere else, and only a key minted for the new one works.
const create = (actor: Session, data: unknown) =>
api.request(actor, "POST", `${prefix}/mcp-connections`, data);
const again = yield* create(actors.member, {
id: bound.id,
name: `Again ${receipt.slice(0, 6)}`,
apps: policy,
});
expect(again.status, JSON.stringify(again.body)).toBe(200);
const reused = yield* body(ConnectionWithTimes, again);
expect(reused.url).toBe(bound.url);
expect(Date.parse(reused.createdAt)).toBeGreaterThan(Date.parse(bound.createdAt));
for (const [label, secret] of [
["API-minted key", key.key],
["dashboard key", Redacted.make(shown.trim())],
] as const) {
expect(
Exit.isFailure(yield* atConnection(secret, `${label} at the new connection`)),
label,
).toBe(true);
for (const path of [bound.url.slice(bound.url.indexOf("/mcp")), "/mcp"]) {
const refused = yield* asKey(secret, "POST", path, initialize);
expect(refused.status, `${label} at ${path}: ${JSON.stringify(refused.body)}`).toBe(
401,
);
}
}
const fresh = yield* body(
ConnectionKey,
yield* mint(actors.member, bound.id, { name: "After reuse", expiresInSeconds: 3600 }),
);
expect(Exit.isSuccess(yield* atConnection(fresh.key, "key for the new connection"))).toBe(
true,
);
// A retry with the same body returns the live connection unchanged; another body is a
// different connection, and the ID is taken.
const retried = yield* create(actors.member, {
id: bound.id,
name: reused.name,
apps: policy,
});
expect(retried.status, JSON.stringify(retried.body)).toBe(200);
expect((yield* body(ConnectionWithTimes, retried)).createdAt).toBe(reused.createdAt);
const taken = yield* create(actors.member, {
id: bound.id,
name: `Different ${receipt.slice(0, 6)}`,
apps: policy,
});
expect(taken.status, JSON.stringify(taken.body)).toBe(409);
expect(JSON.stringify(taken.body)).toContain("ConnectionIdTaken");
// IDs belong to the user who made them: another member cannot take a live or revoked one.
expect(
(yield* api.request(
actors.member,
"POST",
`${prefix}/mcp-connections/${other.id}/revoke`,
)).status,
).toBeLessThan(300);
for (const id of [bound.id, other.id]) {
const refused = yield* create(actors.admin, { id, name: "Not theirs", apps: policy });
expect(refused.status, JSON.stringify(refused.body)).toBe(409);
expect(JSON.stringify(refused.body)).toContain("ConnectionIdTaken");
}
}).pipe(Effect.provide(McpClient.layer)),
),
);
Expand Down
Loading
Loading