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
1 change: 1 addition & 0 deletions changelog.d/220.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Release evidence now cites local proof for MCP tokens signed by a loopback issuer, a skewed client clock and a bounded MySQL pool at capacity, and lists their remaining gaps: hosted WorkOS and real MCP host checks, no client clock correction, and queued transactions that cancel only when a connection frees.
1 change: 1 addition & 0 deletions changelog.d/221.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A request cancelled while it waits for a database connection no longer runs its SQL later; a statement already sent to MySQL still completes.
10 changes: 5 additions & 5 deletions docs/release-evidence.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@anthropic-ai/sdk": "0.129.0",
"@better-auth/cimd": "1.7.7",
"@better-auth/oauth-provider": "1.7.7",
"@effect/experimental": "0.61.1",
"@effect/platform": "0.97.2",
"@effect/platform-node": "0.108.2",
"@effect/sql": "0.52.1",
Expand Down
74 changes: 68 additions & 6 deletions server/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
* that turn mysql2 row values into wire-ready values. Domain code decodes rows with
* `SqlSchema` from `@effect/sql` using these column schemas; nothing else touches raw rows.
*/
import * as Reactivity from '@effect/experimental/Reactivity';
import { MysqlClient } from '@effect/sql-mysql2';
import { SqlClient, type SqlError } from '@effect/sql';
import { Effect, Layer, ParseResult, type Redacted, Schema } from 'effect';
import { SqlClient, type SqlConnection, SqlError } from '@effect/sql';
import { Context, Effect, Exit, Fiber, Layer, ParseResult, type Redacted, Schema, Scope, Stream } from 'effect';
import { Sha256Hex, UtcTimestamp, Unavailable, type WorkspaceId } from '@sanctum/contracts';

/** Connection settings; config.ts reads them from the environment. */
Expand All @@ -23,10 +24,10 @@ export interface MysqlOptions {

/**
* Pool options: DATETIME(6) and BIGINT/DECIMAL arrive as strings (no millisecond Date or
* rounded Number), connection waits are bounded by `queueLimit`; without `caCert` the
* connection is unencrypted (local and test servers).
* rounded Number), connection waits are gated and bounded in `gatedClient`; without `caCert`
* the connection is unencrypted (local and test servers).
*/
const mysqlLayer = (mysql: MysqlOptions) =>
const pooledClient = (mysql: MysqlOptions) =>
MysqlClient.layer({
host: mysql.host,
port: mysql.port,
Expand Down Expand Up @@ -62,8 +63,69 @@ export const verifyUtcSession = Effect.gen(function*() {
}
});

/**
* The pool cannot drop a waiter: mysql2 keeps the queued callback of a cancelled request, and
* @effect/sql-mysql2 then still dispatches that request's statement once a connection frees.
* Waiting therefore happens here, in a FIFO semaphore whose waiters leave when interrupted;
* a statement or transaction asks the pool for a connection only while holding one of its
* `maxConnections` permits, so the pool's own queue never forms. A statement already dispatched
* is not cancelled: MySQL runs it to completion and keeps its permit and connection until then.
* As in mysql2, more than `queueLimit` waiters are refused (0 is unbounded).
*/
const gatedClient = (mysql: MysqlOptions) =>
Layer.scopedContext(
Effect.gen(function* () {
const pooled = yield* MysqlClient.MysqlClient;
const permits = yield* Effect.makeSemaphore(mysql.maxConnections);
let busy = 0;
let waiting = 0;
const giveBack = Effect.suspend(() => {
busy--;
return permits.release(1);
});
// Waiting is interruptible only where the caller is: a cleanup write of an interrupted fiber still waits its turn.
const reserve = Effect.uninterruptibleMask(restore =>
Effect.suspend(() => {
if (busy >= mysql.maxConnections && mysql.queueLimit > 0 && waiting >= mysql.queueLimit) return Effect.fail(new SqlError.SqlError({ cause: new Error('Queue limit reached.'), message: 'Failed to acquire connection' }));
waiting++;
return restore(permits.take(1)).pipe(Effect.onExit(exit => Effect.sync(() => { waiting--; if (Exit.isSuccess(exit)) busy++; })));
}).pipe(
// A failed acquisition leaves no finalizer behind and its scope may never close, so the permit goes back here.
Effect.zipRight(Effect.onError(pooled.reserve, () => giveBack)),
Effect.tap(() => Effect.addFinalizer(() => giveBack)),
),
);
// An interrupted statement is not aborted: MySQL still runs it on its connection, which must not be handed out before it
// answers. A daemon therefore owns the permit and connection until then, while the caller may leave at once.
const held = <A>(use: (connection: SqlConnection.Connection) => Effect.Effect<A, SqlError.SqlError>) =>
Effect.uninterruptibleMask(restore =>
Effect.flatMap(Scope.make(), scope =>
restore(Scope.extend(reserve, scope)).pipe(
Effect.onError(cause => Scope.close(scope, Exit.failCause(cause))),
Effect.flatMap(connection => Effect.forkDaemon(Effect.onExit(use(connection), exit => Scope.close(scope, exit)))),
Effect.flatMap(statement => restore(Fiber.join(statement))),
),
),
);
const statements: SqlConnection.Connection = {
execute: (sql, params, transform) => held(c => c.execute(sql, params, transform)),
executeRaw: (sql, params) => held(c => c.executeRaw(sql, params)),
executeValues: (sql, params) => held(c => c.executeValues(sql, params)),
executeUnprepared: (sql, params, transform) => held(c => c.executeUnprepared(sql, params, transform)),
executeStream: (sql, params, transform) => Stream.unwrapScoped(Effect.map(reserve, c => c.executeStream(sql, params, transform))),
};
const client = yield* SqlClient.make({
acquirer: Effect.succeed(statements),
transactionAcquirer: reserve,
compiler: MysqlClient.makeCompiler(),
spanAttributes: [['db.system.name', 'mysql']],
});
return Context.make(SqlClient.SqlClient, client);
}),
).pipe(Layer.provide(Reactivity.layer), Layer.provide(pooledClient(mysql)));

/** Pool plus the UTC precondition; API and worker each build their own process-scoped layer. */
export const dbLayer = (mysql: MysqlOptions) => Layer.effectDiscard(verifyUtcSession).pipe(Layer.provideMerge(mysqlLayer(mysql)));
export const dbLayer = (mysql: MysqlOptions) => Layer.effectDiscard(verifyUtcSession).pipe(Layer.provideMerge(gatedClient(mysql)));

const MYSQL_DATETIME = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?)$/;

Expand Down
55 changes: 47 additions & 8 deletions server/tests/mcp.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { randomUUID } from 'node:crypto';
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { SqlClient } from '@effect/sql';
import { describe, expect, it } from '@effect/vitest';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
Expand All @@ -7,10 +9,10 @@ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
import { LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS } from '@modelcontextprotocol/sdk/types.js';
import type { AccessScope } from '@sanctum/contracts';
import { createClient } from '@sanctum/sdk';
import { Effect, Option, TestClock } from 'effect';
import { createLocalJWKSet, exportJWK, generateKeyPair, SignJWT } from 'jose';
import { ConfigProvider, Effect, Option, TestClock } from 'effect';
import { createLocalJWKSet, type CryptoKey, exportJWK, generateKeyPair, SignJWT } from 'jose';
import { type JsonSchema, deref, operations } from '../../scripts/generate-sdks.ts';
import { MCP_SESSION_IDLE_MS, MCP_TOOL_NAMES, mcpTools } from '../src/mcp.ts';
import { MCP_SESSION_IDLE_MS, MCP_TOOL_NAMES, McpAuthorizationFromEnv, McpAuthorizationServer, mcpTools } from '../src/mcp.ts';
import { addMember, linkWorkspaceOrg } from '../src/store.ts';
import { HOLD_SOURCE_ID } from './support/fake-domain.ts';
import { seedWorkspace } from './support/fixtures.ts';
Expand All @@ -21,21 +23,21 @@ const RESOURCE = 'https://sanctum.fixture.test/mcp';
const { publicKey, privateKey } = await generateKeyPair('ES256');
const keys = createLocalJWKSet({ keys: [{ ...(await exportJWK(publicKey)), alg: 'ES256' }] });

const sign = (subject: string, scope: string, claims: { aud?: string; exp?: number; workspace_id?: string; org_id?: string } = {}) =>
const sign = (subject: string, scope: string, claims: { aud?: string; exp?: number; iss?: string; key?: CryptoKey; workspace_id?: string; org_id?: string } = {}) =>
new SignJWT({ scope, ...(claims.workspace_id ? { workspace_id: claims.workspace_id } : {}), ...(claims.org_id ? { org_id: claims.org_id } : {}) })
.setProtectedHeader({ alg: 'ES256' })
.setIssuer(ISSUER)
.setIssuer(claims.iss ?? ISSUER)
.setSubject(subject)
.setAudience(claims.aud ?? RESOURCE)
.setExpirationTime(claims.exp ?? Math.floor(Date.now() / 1000) + 600)
.sign(privateKey);
.sign(claims.key ?? privateKey);

/** Links a fixture issuer subject to a seeded principal, as sign-in would after verification. */
const identify = (access: AccessScope) =>
const identify = (access: AccessScope, issuer = ISSUER) =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const subject = `sub-${access.principal.id}`;
yield* sql`INSERT INTO principal_identities (issuer, subject, principal_id, verified_at) VALUES (${ISSUER}, ${subject}, ${access.principal.id}, UTC_TIMESTAMP(6))`;
yield* sql`INSERT INTO principal_identities (issuer, subject, principal_id, verified_at) VALUES (${issuer}, ${subject}, ${access.principal.id}, UTC_TIMESTAMP(6))`;
return subject;
});

Expand Down Expand Up @@ -163,6 +165,43 @@ describe('MCP over Streamable HTTP', () => {
}),
);

it.scoped('accepts a token signed by the configured loopback issuer and refuses a wrong issuer, audience or key', () =>
Effect.gen(function* () {
// The issuer publishes only its JWKS; Sanctum reads the same three settings production does.
const jwks = JSON.stringify({ keys: [{ ...(yield* Effect.promise(() => exportJWK(publicKey))), alg: 'ES256' }] });
const fixture = yield* Effect.acquireRelease(
Effect.async<Server>(resume => {
const server = createServer((request, response) =>
request.url === '/jwks' ? response.writeHead(200, { 'content-type': 'application/json' }).end(jwks) : response.writeHead(404).end(),
).listen(0, '127.0.0.1', () => resume(Effect.succeed(server)));
}),
server => Effect.async<void>(resume => void server.close(() => resume(Effect.void))),
);
const issuer = `http://127.0.0.1:${(fixture.address() as AddressInfo).port}`;
const env = ConfigProvider.fromJson({ SANCTUM_MCP_RESOURCE: RESOURCE, SANCTUM_MCP_ISSUER: issuer, SANCTUM_MCP_JWKS_URL: `${issuer}/jwks` });
const auth = yield* McpAuthorizationServer.pipe(Effect.provide(McpAuthorizationFromEnv), Effect.withConfigProvider(env));
const { url, db, domain } = yield* serveFake(auth);
const [member] = yield* Effect.provide(seedWorkspace('Loopback', ['member']), db);
const subject = yield* Effect.provide(identify(member!, issuer), db);
const meeting = domain.addMeeting(member!, 'Loopback sync');

const metadata = yield* Effect.promise(() => fetch(`${url}/.well-known/oauth-protected-resource/mcp`).then(r => r.json()));
expect(metadata).toMatchObject({ resource: RESOURCE, authorization_servers: [issuer] });
const { client } = yield* connect(url, yield* Effect.promise(() => sign(subject, 'context:read', { iss: issuer })));
expect(yield* Effect.promise(() => client.callTool({ name: 'list_meetings', arguments: {} }))).toMatchObject({ structuredContent: { meetings: [{ id: meeting.id }] } });

const { privateKey: unpublished } = yield* Effect.promise(() => generateKeyPair('ES256'));
const refused = [
yield* Effect.promise(() => sign(subject, 'context:read')),
yield* Effect.promise(() => sign(subject, 'context:read', { iss: issuer, aud: 'https://other.test/mcp' })),
yield* Effect.promise(() => sign(subject, 'context:read', { iss: issuer, key: unpublished })),
];
const statuses: number[] = [];
for (const token of refused) statuses.push((yield* Effect.promise(() => post(url, token, initialize(LATEST_PROTOCOL_VERSION)))).status);
expect(statuses).toEqual([401, 401, 401]);
}),
);

it.scoped('grants configured default scopes only to tokens that name no Sanctum scope', () =>
Effect.gen(function* () {
const { url, db, domain } = yield* serveFake(Option.some({ resource: RESOURCE, issuer: ISSUER, keys, defaultScopes: ['context:read', 'workspace:admin'] }));
Expand Down
Loading
Loading