|
| 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