Skip to content

Commit a8a32bb

Browse files
Rish-itmaria-rcks
andauthored
fix(server): accept case-insensitive MCP bearer schemes (#23782)
Co-authored-by: maria-rcks <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent 4ed4950 commit a8a32bb

5 files changed

Lines changed: 150 additions & 26 deletions

File tree

‎apps/server/src/auth/EnvironmentAuth.test.ts‎

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,13 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
188188
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
189189
const token = "reusable-dev-auth-token-that-is-long-enough";
190190
const devExchange = yield* serverAuth.createBrowserSession(token, requestMetadata);
191-
for (const authorization of ["Bearer invalid", ""] as const) {
191+
for (const authorization of [
192+
"Bearer invalid",
193+
"bearer invalid",
194+
"bEaReR invalid",
195+
"Basic invalid",
196+
"",
197+
] as const) {
192198
const request = {
193199
cookies: { [devExchange.cookieName ?? "missing"]: devExchange.sessionToken },
194200
headers: { authorization },
@@ -671,24 +677,27 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
671677
}).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web" }))),
672678
);
673679

674-
it.effect("keeps bearer socket upgrades independent of the page origin", () =>
675-
Effect.gen(function* () {
676-
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
677-
const bearer = yield* serverAuth.issueSession();
678-
const verified = yield* serverAuth.authenticateWebSocketUpgrade(
679-
{
680+
it.effect.each(["Bearer", "bearer", "bEaReR"])(
681+
"accepts %s for HTTP and socket upgrades regardless of page origin",
682+
(scheme) =>
683+
Effect.gen(function* () {
684+
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
685+
const bearer = yield* serverAuth.issueSession();
686+
const request = {
680687
url: "/ws",
681688
cookies: {},
682689
headers: {
683690
host: "192.168.1.50:3773",
684691
origin: "http://192.168.1.50:8080",
685-
authorization: `Bearer ${bearer.token}`,
692+
authorization: `${scheme} ${bearer.token}`,
686693
},
687-
} as never,
688-
"rpc",
689-
);
690-
expect(verified.sessionId).toBe(bearer.sessionId);
691-
}).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
694+
} as never;
695+
const verified = yield* serverAuth.authenticateWebSocketUpgrade(request, "rpc");
696+
expect(verified.sessionId).toBe(bearer.sessionId);
697+
expect((yield* serverAuth.authenticateHttpRequest(request)).sessionId).toBe(
698+
bearer.sessionId,
699+
);
700+
}).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
692701
);
693702

694703
it.effect("binds a DPoP session's RPC socket ticket to its proof key", () =>

‎apps/server/src/auth/EnvironmentAuth.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -628,9 +628,9 @@ const mapSessionVerificationErrors = <A, R>(
628628
),
629629
);
630630

631-
function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
631+
export function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
632632
const header = request.headers["authorization"];
633-
if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
633+
if (typeof header !== "string" || !/^Bearer /i.test(header)) {
634634
return null;
635635
}
636636
const token = header.slice(AUTHORIZATION_PREFIX.length).trim();

‎apps/server/src/auth/McpOAuth.test.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -295,12 +295,14 @@ it.live("signs in with a pairing code and issues a token only /mcp accepts", ()
295295

296296
expect((yield* exchange(verifier)).status).toBe(400);
297297

298-
const client = yield* auth.authenticateMcpClient(
299-
HttpServerRequest.fromWeb(
300-
at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }),
301-
),
302-
);
303-
expect(client).toMatchObject({ label: "Claude Code", access: "auto" });
298+
for (const scheme of ["Bearer", "bearer", "bEaReR"]) {
299+
const client = yield* auth.authenticateMcpClient(
300+
HttpServerRequest.fromWeb(
301+
at("/mcp", { headers: { authorization: `${scheme} ${token.access_token}` } }),
302+
),
303+
);
304+
expect(client).toMatchObject({ label: "Claude Code", access: "auto" });
305+
}
304306

305307
const session = yield* handler(
306308
at("/api/auth/session", { headers: { authorization: `Bearer ${token.access_token}` } }),

‎apps/server/src/mcp/McpHttpServer.test.ts‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,20 @@ import * as Context from "effect/Context";
2020
import * as Deferred from "effect/Deferred";
2121
import * as Effect from "effect/Effect";
2222
import * as Layer from "effect/Layer";
23+
import * as Logger from "effect/Logger";
2324
import * as Schema from "effect/Schema";
2425
import * as Stream from "effect/Stream";
2526
import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
2627
import { HttpBody, HttpClient, HttpClientRequest, HttpRouter } from "effect/http";
2728

2829
import * as ProjectService from "../project/ProjectService.ts";
30+
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
31+
import * as McpOAuth from "../auth/McpOAuth.ts";
32+
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
33+
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
34+
import * as Sqlite from "../persistence/Sqlite.ts";
35+
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
36+
2937
import * as DeviceService from "../device/DeviceService.ts";
3038
import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts";
3139
import * as ServerConfig from "../config.ts";
@@ -946,6 +954,106 @@ it.effect("admits provider and OAuth client credentials and points only clients
946954
).pipe(Effect.provide(NodeHttpServer.layerTest)),
947955
);
948956

957+
it.effect("accepts case-insensitive MCP bearer schemes and diagnoses rejected credentials", () => {
958+
const messages: Array<unknown> = [];
959+
const logger = Logger.make(({ message }) => messages.push(message));
960+
const layerAuth = Layer.mergeAll(EnvironmentAuth.layer, McpSessionRegistry.layer).pipe(
961+
Layer.provideMerge(
962+
Layer.mock(ServerEnvironment.ServerEnvironment)({
963+
getEnvironmentId: Effect.succeed(environmentId),
964+
}),
965+
),
966+
Layer.provideMerge(Sqlite.layerMemory),
967+
Layer.provide(ServerSecretStore.layer),
968+
Layer.provide(ManagedPolicy.layerTest()),
969+
Layer.provideMerge(ServerEnvironment.layerIdentity),
970+
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-auth-header-test-" })),
971+
Layer.provideMerge(NodeServices.layer),
972+
);
973+
return Effect.scoped(
974+
Effect.gen(function* () {
975+
const auth = yield* EnvironmentAuth.EnvironmentAuth;
976+
const registry = yield* McpSessionRegistry.McpSessionRegistry;
977+
const issued = yield* registry.issue({
978+
threadId,
979+
providerInstanceId: ProviderInstanceId.make("codex"),
980+
});
981+
const providerToken = issued.config.authorizationHeader.slice("Bearer ".length);
982+
const oauth = yield* auth.issueMcpClientSession({
983+
label: "MCP header test",
984+
access: "read-only",
985+
peerLink: false,
986+
client: { deviceType: "bot" },
987+
});
988+
yield* HttpRouter.serve(
989+
McpHttpServer.layerMcpTransport.pipe(
990+
Layer.provide(McpOAuth.layerMcpClientAuthenticator),
991+
Layer.provide(ServerSettings.layerTest()),
992+
),
993+
{ disableListenLog: true, disableLogger: true },
994+
).pipe(Layer.build);
995+
const httpClient = yield* HttpClient.HttpClient;
996+
const initialize = (authorization?: string) =>
997+
httpClient.post("/mcp", {
998+
headers: {
999+
accept: "application/json, text/event-stream",
1000+
...(authorization === undefined ? {} : { authorization }),
1001+
},
1002+
body: HttpBody.text(
1003+
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-header-test","version":"1.0.0"}}}`,
1004+
"application/json",
1005+
),
1006+
});
1007+
1008+
for (const scheme of ["Bearer", "bearer", "bEaReR"]) {
1009+
for (const [kind, token] of [
1010+
["provider", providerToken],
1011+
["OAuth", oauth.token],
1012+
]) {
1013+
const response = yield* initialize(`${scheme} ${token}`);
1014+
expect.soft(response.status, `${kind} ${scheme}`).toBe(200);
1015+
}
1016+
}
1017+
messages.length = 0;
1018+
for (const [authorization, reason] of [
1019+
[undefined, "missing_authorization_header"],
1020+
[`Basic ${providerToken}`, "unsupported_scheme"],
1021+
["Bearer", "missing_bearer_token"],
1022+
["bEaReR ", "missing_bearer_token"],
1023+
[`bearer ${providerToken.toUpperCase()}`, "unknown_or_expired_token"],
1024+
[`bEaReR ${oauth.token.toUpperCase()}`, "unknown_or_expired_token"],
1025+
] as const) {
1026+
const response = yield* initialize(authorization);
1027+
expect(response.status).toBe(401);
1028+
expect
1029+
.soft(messages.at(-1))
1030+
.toEqual(["rejected MCP request with an unusable credential", { reason }]);
1031+
const body = yield* response.text;
1032+
expect(body).not.toContain(providerToken);
1033+
expect(body).not.toContain(oauth.token);
1034+
expect(JSON.stringify(response.headers)).not.toContain(providerToken);
1035+
expect(JSON.stringify(response.headers)).not.toContain(oauth.token);
1036+
}
1037+
yield* registry.revokeThread(threadId);
1038+
yield* auth.revokeSession(oauth.sessionId);
1039+
for (const token of [providerToken, oauth.token]) {
1040+
expect((yield* initialize(`bearer ${token}`)).status).toBe(401);
1041+
}
1042+
expect(JSON.stringify(messages)).not.toContain(providerToken);
1043+
expect(JSON.stringify(messages)).not.toContain(oauth.token);
1044+
expect(JSON.stringify(messages)).not.toContain(providerToken.toUpperCase());
1045+
expect(JSON.stringify(messages)).not.toContain(oauth.token.toUpperCase());
1046+
}),
1047+
).pipe(
1048+
Effect.provide(
1049+
layerAuth.pipe(
1050+
Layer.provideMerge(NodeHttpServer.layerTest),
1051+
Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
1052+
),
1053+
),
1054+
);
1055+
});
1056+
9491057
it.effect("hides tools for links and refuses another environment while the beta is off", () =>
9501058
Effect.scoped(
9511059
Effect.gen(function* () {

‎apps/server/src/mcp/McpHttpServer.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
} from "@t3tools/contracts";
2525

2626
import packageJson from "../../package.json" with { type: "json" };
27+
import { parseBearerToken } from "../auth/EnvironmentAuth.ts";
2728
import * as ServerConfig from "../config.ts";
2829
import * as ServerSettings from "../serverSettings.ts";
2930
import * as DeviceService from "../device/DeviceService.ts";
@@ -204,18 +205,22 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
204205
return Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
205206
const request = yield* HttpServerRequest.HttpServerRequest;
206207
const authorization = request.headers.authorization;
207-
const token =
208-
authorization?.startsWith("Bearer ") === true
209-
? authorization.slice("Bearer ".length).trim()
210-
: "";
208+
const token = parseBearerToken(request) ?? "";
211209
const invocation =
212210
(yield* registry.resolve(token)) ??
213211
(Option.isSome(clients) && token.length > 0
214212
? yield* clients.value.authenticate(request)
215213
: undefined);
216214
if (!invocation) {
217215
yield* Effect.logWarning("rejected MCP request with an unusable credential", {
218-
reason: token.length === 0 ? "missing_bearer_token" : "unknown_or_expired_token",
216+
reason:
217+
authorization === undefined
218+
? "missing_authorization_header"
219+
: authorization.split(" ", 1)[0]?.toLowerCase() !== "bearer"
220+
? "unsupported_scheme"
221+
: token.length === 0
222+
? "missing_bearer_token"
223+
: "unknown_or_expired_token",
219224
});
220225
return unauthorized({
221226
request,

0 commit comments

Comments
 (0)