Skip to content

Commit d095146

Browse files
aididhaiqalclaude
andcommitted
fix(server): T3 Connect links from the desktop app when the backend runs in WSL
The desktop reaches its WSL backend through the distro's NAT IP, so the link-proof request host is not loopback and the server rejected it with "Invalid managed endpoint origin". Allow a non-loopback request host only for the server-assigned desktop-bootstrap session; the signed tunnel origin must still be loopback, the port must match, forwarded headers are still rejected, and relay:write is still required. Fixes #5210 Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 4d73e1d commit d095146

4 files changed

Lines changed: 321 additions & 4 deletions

File tree

‎apps/server/src/cloud/CloudLink.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import * as NodeCrypto from "node:crypto";
99
import {
1010
AuthStandardClientScopes,
11+
EnvironmentAuthenticatedPrincipal,
1112
type EnvironmentCloudLinkStateResult,
1213
type EnvironmentCloudPreferencesRequest,
1314
type EnvironmentCloudRelayConfigResult,
@@ -444,14 +445,18 @@ export class CloudLink extends Context.Service<
444445
{
445446
/**
446447
* Signs the proof the relay asks for to link this environment. The request
447-
* must reach this server directly on the loopback origin it names.
448+
* must reach this server directly. Desktop bootstrap sessions may use the
449+
* WSL IP; all other sessions must use the loopback origin they name.
448450
*/
449451
readonly linkProof: (
450452
request: RelayLinkProofRequest,
451453
httpRequest: HttpServerRequest.HttpServerRequest,
452454
) => Effect.Effect<
453455
RelayEnvironmentLinkProof,
454-
CloudLinkOriginInvalidError | CloudLinkInternalError | EnvironmentAuth.ServerAuthInternalError
456+
| CloudLinkOriginInvalidError
457+
| CloudLinkInternalError
458+
| EnvironmentAuth.ServerAuthInternalError,
459+
EnvironmentAuthenticatedPrincipal
455460
>;
456461
/** Installs the link the relay returned and, for a managed tunnel, confirms its origin. */
457462
readonly applyRelayConfig: (
@@ -628,13 +633,15 @@ const make = Effect.gen(function* () {
628633
const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function* (
629634
request: RelayLinkProofRequest,
630635
requestUrl: string,
636+
allowNonLoopbackRequestHost = false,
631637
) {
632638
const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
633639
if (
634640
!isSupportedLinkProviderKind(request) ||
635641
!isAllowedEndpointOrigin({
636642
origin: request.origin,
637643
requestUrl,
644+
allowNonLoopbackRequestHost,
638645
})
639646
) {
640647
return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" });
@@ -678,7 +685,15 @@ const make = Effect.gen(function* () {
678685
if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {
679686
return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" });
680687
}
681-
const proof = yield* makeCloudLinkProof(request, requestUrl);
688+
const session = yield* EnvironmentAuthenticatedPrincipal;
689+
// Windows reaches its WSL backend through the distro IP. Trust the
690+
// authenticated bootstrap subject, never a caller-supplied origin flag;
691+
// paired and cloud clients receive different subjects.
692+
const proof = yield* makeCloudLinkProof(
693+
request,
694+
requestUrl,
695+
session.subject === "desktop-bootstrap",
696+
);
682697
return proof satisfies RelayEnvironmentLinkProof;
683698
},
684699
Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("generate-link-proof")),

‎apps/server/src/cloud/linkChecks.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,49 @@ import { describe, expect, it } from "@effect/vitest";
22
import type { RelayLinkProofRequest } from "@t3tools/contracts/relay";
33

44
import {
5+
isAllowedEndpointOrigin,
56
isSupportedLinkProviderKind,
67
linkProofScopes,
78
parseManagedEndpointLocalOrigin,
89
} from "./linkChecks.ts";
910

11+
describe("isAllowedEndpointOrigin", () => {
12+
const origin = { localHttpHost: "127.0.0.1", localHttpPort: 3773 };
13+
14+
it("accepts the WSL NAT request only when trusted by the server", () => {
15+
expect(
16+
isAllowedEndpointOrigin({
17+
origin,
18+
requestUrl: "http://172.24.162.233:3773/api/connect/link-proof",
19+
allowNonLoopbackRequestHost: true,
20+
}),
21+
).toBe(true);
22+
expect(
23+
isAllowedEndpointOrigin({
24+
origin,
25+
requestUrl: "http://172.24.162.233:3773/api/connect/link-proof",
26+
}),
27+
).toBe(false);
28+
});
29+
30+
it("retains signed-origin and port checks", () => {
31+
expect(
32+
isAllowedEndpointOrigin({
33+
origin: { localHttpHost: "172.24.162.233", localHttpPort: 3773 },
34+
requestUrl: "http://172.24.162.233:3773/",
35+
allowNonLoopbackRequestHost: true,
36+
}),
37+
).toBe(false);
38+
expect(
39+
isAllowedEndpointOrigin({
40+
origin,
41+
requestUrl: "http://172.24.162.233:3774/",
42+
allowNonLoopbackRequestHost: true,
43+
}),
44+
).toBe(false);
45+
});
46+
});
47+
1048
describe("parseManagedEndpointLocalOrigin", () => {
1149
it.each([
1250
{

‎apps/server/src/cloud/linkChecks.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,13 +87,14 @@ export function parseManagedEndpointLocalOrigin(localOrigin: string) {
8787
export function isAllowedEndpointOrigin(input: {
8888
readonly origin: RelayManagedEndpointOrigin;
8989
readonly requestUrl: string;
90+
readonly allowNonLoopbackRequestHost?: boolean;
9091
}): boolean {
9192
if (!isLoopbackHostname(input.origin.localHttpHost)) {
9293
return false;
9394
}
9495

9596
const url = new URL(input.requestUrl);
96-
if (!isLoopbackHostname(url.hostname)) {
97+
if (!input.allowNonLoopbackRequestHost && !isLoopbackHostname(url.hostname)) {
9798
return false;
9899
}
99100

Lines changed: 263 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,263 @@
1+
import * as NodeServices from "@effect/platform-node/NodeServices";
2+
import { describe, expect, it } from "@effect/vitest";
3+
import {
4+
AuthAccessTokenType,
5+
AuthEnvironmentBootstrapTokenType,
6+
AuthTokenExchangeGrantType,
7+
EnvironmentHttpApi,
8+
EnvironmentId,
9+
} from "@t3tools/contracts";
10+
import {
11+
RelayEnvironmentLinkProofPayload,
12+
type RelayLinkProofRequest,
13+
} from "@t3tools/contracts/relay";
14+
import * as Effect from "effect/Effect";
15+
import * as Layer from "effect/Layer";
16+
import * as Schema from "effect/Schema";
17+
import { HttpClient, HttpServer } from "effect/http";
18+
import * as Etag from "effect/http/Etag";
19+
import * as HttpPlatform from "effect/http/HttpPlatform";
20+
import * as HttpRouter from "effect/http/HttpRouter";
21+
import * as HttpApi from "effect/http-api/HttpApi";
22+
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
23+
import * as NetAddress from "effect/net/NetAddress";
24+
25+
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
26+
import * as AuthHttp from "../auth/http.ts";
27+
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
28+
import * as ServerConfig from "../config.ts";
29+
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
30+
import * as SqlitePersistence from "../persistence/Sqlite.ts";
31+
import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";
32+
import * as CliTokenManager from "./CliTokenManager.ts";
33+
import * as CloudLink from "./CloudLink.ts";
34+
import * as ConnectHttp from "./http.ts";
35+
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
36+
37+
const DESKTOP_BOOTSTRAP_TOKEN = "test-desktop-bootstrap-token";
38+
const WSL_ORIGIN = "http://172.24.162.233:3773";
39+
const LOOPBACK_ORIGIN = "http://127.0.0.1:3773";
40+
const proofRequest: RelayLinkProofRequest = {
41+
challenge: "test-challenge",
42+
relayIssuer: "https://relay.example.test",
43+
endpoint: {
44+
providerKind: "cloudflare_tunnel",
45+
httpBaseUrl: "https://environment.example.test",
46+
wsBaseUrl: "wss://environment.example.test",
47+
},
48+
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
49+
};
50+
const decodeLinkProofPayload = Schema.decodeUnknownSync(RelayEnvironmentLinkProofPayload);
51+
52+
class LinkProofTestApi extends HttpApi.make("environment").add(
53+
EnvironmentHttpApi.groups.auth,
54+
EnvironmentHttpApi.groups.connect,
55+
) {}
56+
57+
const layerConfig = Layer.effect(
58+
ServerConfig.ServerConfig,
59+
Effect.gen(function* () {
60+
const config = yield* ServerConfig.ServerConfig;
61+
return {
62+
...config,
63+
mode: "desktop" as const,
64+
host: "0.0.0.0",
65+
port: 3773,
66+
desktopBootstrapToken: DESKTOP_BOOTSTRAP_TOKEN,
67+
};
68+
}),
69+
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-link-proof-test-" })));
70+
71+
// Real credential issuance, verification, origin checks and signing; no relay or tunnel is started.
72+
const layerRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe(
73+
Layer.provide([AuthHttp.layer, ConnectHttp.layer]),
74+
Layer.provide(AuthHttp.layerAuthenticatedAuth),
75+
Layer.provide(CloudLink.layer),
76+
Layer.provide(EnvironmentAuth.layer),
77+
Layer.provide([
78+
SqlitePersistence.layerMemory,
79+
ServerSecretStore.layer,
80+
ServerEnvironment.layerIdentity,
81+
Layer.mock(ServerEnvironment.ServerEnvironment)({
82+
getDescriptor: Effect.succeed({
83+
environmentId: EnvironmentId.make("wsl-environment"),
84+
label: "WSL",
85+
platform: { os: "linux", arch: "x64" },
86+
serverVersion: "0.0.0-test",
87+
capabilities: { repositoryIdentity: false },
88+
}),
89+
}),
90+
Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({}),
91+
Layer.mock(CliTokenManager.CloudCliTokenManager)({}),
92+
Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({}),
93+
Layer.mock(HttpServer.HttpServer)({
94+
address: NetAddress.inetAddressFromIpStringUnsafe("0.0.0.0", 3773),
95+
}),
96+
Layer.succeed(
97+
HttpClient.HttpClient,
98+
HttpClient.make(() => Effect.die("Unexpected relay call")),
99+
),
100+
]),
101+
Layer.provide(layerConfig),
102+
Layer.provideMerge(HttpPlatform.layer.pipe(Layer.provideMerge(Etag.layerWeak))),
103+
Layer.provideMerge(NodeServices.layer),
104+
);
105+
106+
const withClient = async (
107+
body: (client: {
108+
post: (
109+
path: string,
110+
payload: unknown,
111+
headers?: Record<string, string>,
112+
origin?: string,
113+
) => Promise<Response>;
114+
exchange: (credential: string, scope?: string) => Promise<string>;
115+
}) => Promise<void>,
116+
) => {
117+
const { handler: rawHandler, dispose } = HttpRouter.toWebHandler(layerRoutes, {
118+
disableLogger: true,
119+
});
120+
const handler = rawHandler as (request: Request) => Promise<Response>;
121+
const post = (
122+
path: string,
123+
payload: unknown,
124+
headers?: Record<string, string>,
125+
origin = WSL_ORIGIN,
126+
) =>
127+
handler(
128+
new Request(`${origin}${path}`, {
129+
method: "POST",
130+
headers: { "content-type": "application/json", ...headers },
131+
body: JSON.stringify(payload),
132+
}),
133+
);
134+
const exchange = async (credential: string, scope?: string) => {
135+
const response = await handler(
136+
new Request(`${WSL_ORIGIN}/oauth/token`, {
137+
method: "POST",
138+
body: new URLSearchParams({
139+
grant_type: AuthTokenExchangeGrantType,
140+
subject_token: credential,
141+
subject_token_type: AuthEnvironmentBootstrapTokenType,
142+
requested_token_type: AuthAccessTokenType,
143+
...(scope ? { scope } : {}),
144+
}),
145+
}),
146+
);
147+
expect(response.status).toBe(200);
148+
const payload = (await response.json()) as { access_token: string };
149+
return payload.access_token;
150+
};
151+
try {
152+
await body({ post, exchange });
153+
} finally {
154+
await dispose();
155+
}
156+
};
157+
158+
describe("link proof over the WSL desktop transport", () => {
159+
it("signs a loopback tunnel origin after desktop bootstrap token exchange", () =>
160+
withClient(async ({ post, exchange }) => {
161+
const token = await exchange(DESKTOP_BOOTSTRAP_TOKEN);
162+
const response = await post("/api/connect/link-proof", proofRequest, {
163+
authorization: `Bearer ${token}`,
164+
});
165+
expect(response.status).toBe(200);
166+
const proof = (await response.json()) as string;
167+
const payload = decodeLinkProofPayload(
168+
JSON.parse(Buffer.from(proof.split(".")[1]!, "base64url").toString()),
169+
);
170+
expect(proof.split(".")).toHaveLength(3);
171+
expect(payload).toMatchObject({
172+
origin: proofRequest.origin,
173+
challenge: proofRequest.challenge,
174+
});
175+
expect(response.headers.get("cache-control")).toBe("no-store");
176+
}));
177+
178+
it("does not pass desktop trust to a paired client or accept client-supplied provenance", () =>
179+
withClient(async ({ post, exchange }) => {
180+
const desktop = await exchange(DESKTOP_BOOTSTRAP_TOKEN);
181+
const paired = await post(
182+
"/api/auth/pairing-token",
183+
{
184+
scopes: ["relay:write"],
185+
label: "desktop-bootstrap",
186+
subject: "desktop-bootstrap",
187+
},
188+
{ authorization: `Bearer ${desktop}` },
189+
);
190+
expect(paired.status).toBe(200);
191+
const { credential } = (await paired.json()) as { credential: string };
192+
const token = await exchange(credential);
193+
const headers = { authorization: `Bearer ${token}`, "x-desktop-bootstrap": "true" };
194+
const payload = {
195+
...proofRequest,
196+
allowNonLoopbackRequestHost: true,
197+
subject: "desktop-bootstrap",
198+
};
199+
const rejected = await post("/api/connect/link-proof", payload, headers);
200+
expect(rejected.status).toBe(400);
201+
expect(await rejected.json()).toMatchObject({ message: "Invalid managed endpoint origin." });
202+
const loopback = await post(
203+
"/api/connect/link-proof",
204+
proofRequest,
205+
headers,
206+
LOOPBACK_ORIGIN,
207+
);
208+
expect(loopback.status).toBe(200);
209+
}));
210+
211+
it.each([
212+
{
213+
name: "non-loopback tunnel origin",
214+
origin: { localHttpHost: "172.24.162.233", localHttpPort: 3773 },
215+
headers: {},
216+
},
217+
{
218+
name: "mismatched port",
219+
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3774 },
220+
headers: {},
221+
},
222+
{
223+
name: "forwarded host",
224+
origin: proofRequest.origin,
225+
headers: { "x-forwarded-host": "127.0.0.1:3773" },
226+
},
227+
{
228+
name: "forwarded protocol",
229+
origin: proofRequest.origin,
230+
headers: { "x-forwarded-proto": "http" },
231+
},
232+
])("rejects $name even for desktop bootstrap", ({ origin, headers }) =>
233+
withClient(async ({ post, exchange }) => {
234+
const token = await exchange(DESKTOP_BOOTSTRAP_TOKEN);
235+
const response = await post(
236+
"/api/connect/link-proof",
237+
{ ...proofRequest, origin },
238+
{ ...headers, authorization: `Bearer ${token}` },
239+
);
240+
expect(response.status).toBe(400);
241+
expect(await response.json()).toMatchObject({ message: "Invalid managed endpoint origin." });
242+
}),
243+
);
244+
245+
it("requires relay-write scope even for desktop bootstrap", () =>
246+
withClient(async ({ post, exchange }) => {
247+
const token = await exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:read");
248+
const response = await post("/api/connect/link-proof", proofRequest, {
249+
authorization: `Bearer ${token}`,
250+
});
251+
expect(response.status).toBe(403);
252+
expect(await response.json()).toMatchObject({
253+
code: "insufficient_scope",
254+
requiredScope: "relay:write",
255+
});
256+
}));
257+
258+
it("rejects unauthenticated requests", () =>
259+
withClient(async ({ post }) => {
260+
const response = await post("/api/connect/link-proof", proofRequest);
261+
expect(response.status).toBe(401);
262+
}));
263+
});

0 commit comments

Comments
 (0)