Skip to content

Commit 4e86ceb

Browse files
fix(server): websocket tickets name the route they open
A websocket ticket minted over authenticated HTTP could open any ticket-authenticated route, and a DPoP session's ticket carried no trace of the client's proof key, so the socket upgrade accepted it from anyone holding the ticket string. Tickets now carry an audience, minted at `/api/auth/websocket-ticket/rpc` or `/media`, and the server rejects a ticket on a route it was not minted for. A DPoP client's RPC ticket also carries its proof-key thumbprint, and the upgrade requires a fresh DPoP proof in the `dpop` query parameter, verified against that key and the ticket and consumed through the existing replay store. Media routes keep one unbound ticket across their images, event streams and sockets. Clients that predate this mint at the bare path and keep working. Model: Claude Fable 5.1 via Claude Code in T3 Code. Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent 3afb9b3 commit 4e86ceb

17 files changed

Lines changed: 413 additions & 94 deletions

File tree

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

Lines changed: 162 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
1+
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync or sign.
2+
import * as NodeCrypto from "node:crypto";
3+
14
import * as NodeServices from "@effect/platform-node/NodeServices";
25
import { authScopeResponse, AuthStandardClientScopes } from "@t3tools/contracts";
6+
import {
7+
computeDpopAccessTokenHash,
8+
computeDpopJwkThumbprint,
9+
type DpopPublicJwk,
10+
} from "@t3tools/shared/dpop";
311
import { expect, it } from "@effect/vitest";
12+
import * as DateTime from "effect/DateTime";
413
import * as Effect from "effect/Effect";
514
import * as Layer from "effect/Layer";
615
import * as Redacted from "effect/Redacted";
@@ -68,6 +77,36 @@ const requestMetadata = {
6877
ipAddress: "192.168.1.23",
6978
};
7079

80+
const makeDpopKey = () => {
81+
const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" });
82+
const publicJwk = publicKey.export({ format: "jwk" }) as DpopPublicJwk;
83+
let proofCount = 0;
84+
return {
85+
thumbprint: computeDpopJwkThumbprint(publicJwk),
86+
sign: (input: {
87+
readonly method: string;
88+
readonly url: string;
89+
readonly token: string;
90+
readonly iat: number;
91+
}) => {
92+
const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
93+
const header = encode({ typ: "dpop+jwt", alg: "ES256", jwk: publicJwk });
94+
const payload = encode({
95+
htm: input.method,
96+
htu: input.url,
97+
jti: `proof-${++proofCount}`,
98+
iat: input.iat,
99+
ath: computeDpopAccessTokenHash(input.token),
100+
});
101+
const signature = NodeCrypto.sign("sha256", Buffer.from(`${header}.${payload}`), {
102+
key: privateKey,
103+
dsaEncoding: "ieee-p1363",
104+
}).toString("base64url");
105+
return `${header}.${payload}.${signature}`;
106+
},
107+
};
108+
};
109+
71110
it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
72111
it.effect("uses the reusable dev cookie without overriding a normal scoped cookie", () =>
73112
Effect.gen(function* () {
@@ -527,11 +566,14 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
527566
const pairing = yield* serverAuth.issuePairingCredential();
528567
const exchanged = yield* serverAuth.createBrowserSession(pairing.credential, requestMetadata);
529568
const upgrade = (headers: Record<string, string>) =>
530-
serverAuth.authenticateWebSocketUpgrade({
531-
url: "/ws",
532-
cookies: { [sessions.cookieName]: exchanged.sessionToken },
533-
headers: { host: "192.168.1.50:3773", ...headers },
534-
} as never);
569+
serverAuth.authenticateWebSocketUpgrade(
570+
{
571+
url: "/ws",
572+
cookies: { [sessions.cookieName]: exchanged.sessionToken },
573+
headers: { host: "192.168.1.50:3773", ...headers },
574+
} as never,
575+
"rpc",
576+
);
535577

536578
yield* upgrade({ origin: "http://192.168.1.50:3773" });
537579
yield* upgrade({
@@ -588,16 +630,122 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
588630
Effect.gen(function* () {
589631
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
590632
const bearer = yield* serverAuth.issueSession();
591-
const verified = yield* serverAuth.authenticateWebSocketUpgrade({
592-
url: "/ws",
593-
cookies: {},
594-
headers: {
595-
host: "192.168.1.50:3773",
596-
origin: "http://192.168.1.50:8080",
597-
authorization: `Bearer ${bearer.token}`,
598-
},
599-
} as never);
633+
const verified = yield* serverAuth.authenticateWebSocketUpgrade(
634+
{
635+
url: "/ws",
636+
cookies: {},
637+
headers: {
638+
host: "192.168.1.50:3773",
639+
origin: "http://192.168.1.50:8080",
640+
authorization: `Bearer ${bearer.token}`,
641+
},
642+
} as never,
643+
"rpc",
644+
);
600645
expect(verified.sessionId).toBe(bearer.sessionId);
601646
}).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
602647
);
648+
649+
it.effect("binds a DPoP session's RPC socket ticket to its proof key", () =>
650+
Effect.gen(function* () {
651+
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
652+
const sessions = yield* SessionStore.SessionStore;
653+
const key = makeDpopKey();
654+
const other = makeDpopKey();
655+
const exchanged = yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
656+
"desktop-bootstrap-token",
657+
["orchestration:read"],
658+
requestMetadata,
659+
{ proofKeyThumbprint: key.thumbprint },
660+
);
661+
const session = yield* sessions.verify(exchanged.access_token);
662+
const host = "192.168.1.50:3773";
663+
const socketUrl = `http://${host}/ws`;
664+
const iat = Math.floor((yield* DateTime.now).epochMilliseconds / 1_000);
665+
const upgrade = (ticket: string, use: "rpc" | "media", proof?: string) =>
666+
serverAuth.authenticateWebSocketUpgrade(
667+
{
668+
method: "GET",
669+
url: `/ws?orchestrationProtocol=2&wsTicket=${ticket}${proof ? `&dpop=${proof}` : ""}`,
670+
cookies: {},
671+
headers: { host },
672+
} as never,
673+
use,
674+
);
675+
676+
const rpc = yield* serverAuth.issueWebSocketTicket(session, { use: "rpc" });
677+
const bare = yield* Effect.flip(upgrade(rpc.ticket, "rpc"));
678+
expect(bare._tag).toBe("ServerAuthInvalidCredentialError");
679+
const signed = yield* upgrade(
680+
rpc.ticket,
681+
"rpc",
682+
key.sign({ method: "GET", url: socketUrl, token: rpc.ticket, iat }),
683+
);
684+
expect(signed.sessionId).toBe(session.sessionId);
685+
686+
const wrongKey = yield* Effect.flip(
687+
upgrade(
688+
rpc.ticket,
689+
"rpc",
690+
other.sign({ method: "GET", url: socketUrl, token: rpc.ticket, iat }),
691+
),
692+
);
693+
expect(wrongKey._tag).toBe("ServerAuthInvalidCredentialError");
694+
const onMedia = yield* Effect.flip(
695+
upgrade(
696+
rpc.ticket,
697+
"media",
698+
key.sign({ method: "GET", url: socketUrl, token: rpc.ticket, iat }),
699+
),
700+
);
701+
expect(onMedia._tag).toBe("ServerAuthInvalidCredentialError");
702+
703+
const media = yield* serverAuth.issueWebSocketTicket(session, { use: "media" });
704+
expect((yield* upgrade(media.ticket, "media")).sessionId).toBe(session.sessionId);
705+
const mediaOnRpc = yield* Effect.flip(upgrade(media.ticket, "rpc"));
706+
expect(mediaOnRpc._tag).toBe("ServerAuthInvalidCredentialError");
707+
708+
// Clients that predate ticket binding still connect with the unbound ticket they mint.
709+
const legacy = yield* serverAuth.issueWebSocketTicket(session);
710+
expect((yield* upgrade(legacy.ticket, "rpc")).sessionId).toBe(session.sessionId);
711+
}).pipe(
712+
Effect.provide(layerEnvironmentAuth({ desktopBootstrapToken: "desktop-bootstrap-token" })),
713+
),
714+
);
715+
716+
it.effect("rejects a replayed proof on a bound RPC socket ticket", () =>
717+
Effect.gen(function* () {
718+
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
719+
const sessions = yield* SessionStore.SessionStore;
720+
const key = makeDpopKey();
721+
const exchanged = yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
722+
"desktop-bootstrap-token",
723+
["orchestration:read"],
724+
requestMetadata,
725+
{ proofKeyThumbprint: key.thumbprint },
726+
);
727+
const session = yield* sessions.verify(exchanged.access_token);
728+
const rpc = yield* serverAuth.issueWebSocketTicket(session, { use: "rpc" });
729+
const request = {
730+
method: "GET",
731+
url: `/ws?wsTicket=${rpc.ticket}&dpop=${key.sign({
732+
method: "GET",
733+
url: "http://192.168.1.50:3773/ws",
734+
token: rpc.ticket,
735+
iat: Math.floor((yield* DateTime.now).epochMilliseconds / 1_000),
736+
})}`,
737+
cookies: {},
738+
headers: { host: "192.168.1.50:3773" },
739+
} as never;
740+
741+
yield* serverAuth.authenticateWebSocketUpgrade(request, "rpc");
742+
const replayed = yield* Effect.flip(serverAuth.authenticateWebSocketUpgrade(request, "rpc"));
743+
expect(replayed._tag).toBe("ServerAuthInvalidCredentialError");
744+
if (replayed._tag === "ServerAuthInvalidCredentialError") {
745+
expect(replayed.dpopFailureReason).toBe("replay");
746+
}
747+
}).pipe(
748+
Effect.provide(layerEnvironmentAuth({ desktopBootstrapToken: "desktop-bootstrap-token" })),
749+
),
750+
);
603751
});

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

Lines changed: 75 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
type ServerAuthDescriptor,
2222
type ServerAuthSessionMethod,
2323
type AuthWebSocketTicketResult,
24+
type AuthWebSocketTicketUse,
2425
DpopFailureReason,
2526
type DpopFailureReason as DpopFailureReasonType,
2627
} from "@t3tools/contracts";
@@ -543,9 +544,11 @@ export class EnvironmentAuth extends Context.Service<
543544
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
544545
readonly authenticateWebSocketUpgrade: (
545546
request: HttpServerRequest.HttpServerRequest,
547+
use: AuthWebSocketTicketUse,
546548
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
547549
readonly issueWebSocketTicket: (
548-
session: Pick<AuthenticatedSession, "sessionId">,
550+
session: Pick<AuthenticatedSession, "sessionId" | "proofKeyThumbprint">,
551+
input?: { readonly use?: AuthWebSocketTicketUse },
549552
) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
550553
readonly issueStartupPairingUrl: (
551554
baseUrl: string,
@@ -591,6 +594,7 @@ type BootstrapExchangeResult = {
591594
const AUTHORIZATION_PREFIX = "Bearer ";
592595
const DPOP_AUTHORIZATION_PREFIX = "DPoP ";
593596
const WEBSOCKET_TICKET_QUERY_PARAM = "wsTicket";
597+
const WEBSOCKET_PROOF_QUERY_PARAM = "dpop";
594598

595599
const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
596600
const leftCanManage = left.scopes.includes(AuthAccessWriteScope);
@@ -1220,41 +1224,87 @@ export const make = Effect.gen(function* () {
12201224
Effect.withSpan("EnvironmentAuth.issueStartupPairingUrl"),
12211225
);
12221226

1223-
const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
1224-
sessions.issueWebSocketToken(session.sessionId).pipe(
1225-
Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
1226-
Effect.map(
1227-
(issued) =>
1228-
({
1229-
ticket: issued.token,
1230-
expiresAt: DateTime.toUtc(issued.expiresAt),
1231-
}) satisfies AuthWebSocketTicketResult,
1232-
),
1233-
Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
1234-
);
1227+
// Only the RPC socket's ticket is bound to the client's proof key. The media
1228+
// routes reuse one ticket across <img>, EventSource and several sockets, and
1229+
// each of those would need its own single-use proof.
1230+
const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (
1231+
session,
1232+
input,
1233+
) =>
1234+
sessions
1235+
.issueWebSocketToken(session.sessionId, {
1236+
...(input?.use ? { audience: input.use } : {}),
1237+
...(input?.use === "rpc" && session.proofKeyThumbprint
1238+
? { proofKeyThumbprint: session.proofKeyThumbprint }
1239+
: {}),
1240+
})
1241+
.pipe(
1242+
Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
1243+
Effect.map(
1244+
(issued) =>
1245+
({
1246+
ticket: issued.token,
1247+
expiresAt: DateTime.toUtc(issued.expiresAt),
1248+
}) satisfies AuthWebSocketTicketResult,
1249+
),
1250+
Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
1251+
);
12351252

12361253
const authenticateHttpRequest: EnvironmentAuth["Service"]["authenticateHttpRequest"] = (
12371254
request,
12381255
) =>
12391256
authenticateRequest(request).pipe(Effect.withSpan("EnvironmentAuth.authenticateHttpRequest"));
12401257

12411258
const authenticateWebSocketUpgrade: EnvironmentAuth["Service"]["authenticateWebSocketUpgrade"] =
1242-
Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request) {
1259+
Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request, use) {
12431260
const requestUrl = HttpServerRequest.toURL(request);
12441261
if (Option.isSome(requestUrl)) {
12451262
const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);
12461263
if (websocketTicket && websocketTicket.trim().length > 0) {
1247-
return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(
1248-
mapSessionVerificationErrors,
1249-
Effect.flatMap(rejectMcpClientAudience),
1250-
Effect.map((session) => ({
1251-
sessionId: session.sessionId,
1252-
subject: session.subject,
1253-
method: session.method,
1254-
scopes: session.scopes,
1255-
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
1256-
})),
1257-
);
1264+
const session = yield* sessions
1265+
.verifyWebSocketToken(websocketTicket)
1266+
.pipe(mapSessionVerificationErrors, Effect.flatMap(rejectMcpClientAudience));
1267+
if (session.audience !== undefined && session.audience !== use) {
1268+
return yield* new ServerAuthInvalidCredentialError({
1269+
diagnostic: `WebSocket ticket was issued for the ${session.audience} route.`,
1270+
});
1271+
}
1272+
if (session.proofKeyThumbprint) {
1273+
// A WebSocket cannot set headers, so the proof rides in the query.
1274+
// The ticket is the token the proof hashes, and the proof's jti is
1275+
// consumed like any other, so a captured socket URL is dead once the
1276+
// client has used it. Beating the client to first use still needs an
1277+
// active interceptor, which only encrypted transport rules out.
1278+
const proof =
1279+
request.headers.dpop ??
1280+
requestUrl.value.searchParams.get(WEBSOCKET_PROOF_QUERY_PARAM) ??
1281+
undefined;
1282+
if (!proof) {
1283+
return yield* new ServerAuthInvalidCredentialError({
1284+
diagnostic: "DPoP-bound WebSocket ticket requires a DPoP proof.",
1285+
dpopFailureReason: "invalid_proof",
1286+
});
1287+
}
1288+
yield* verifyRequestDpopProof({
1289+
request,
1290+
proof,
1291+
expectedThumbprint: session.proofKeyThumbprint,
1292+
expectedAccessToken: websocketTicket,
1293+
}).pipe(
1294+
Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),
1295+
Effect.provideService(Crypto.Crypto, crypto),
1296+
);
1297+
}
1298+
return {
1299+
sessionId: session.sessionId,
1300+
subject: session.subject,
1301+
method: session.method,
1302+
scopes: session.scopes,
1303+
...(session.proofKeyThumbprint
1304+
? { proofKeyThumbprint: session.proofKeyThumbprint }
1305+
: {}),
1306+
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
1307+
};
12581308
}
12591309
}
12601310

0 commit comments

Comments
 (0)