Open History to see the last commit
1import { createClerkClient, verifyToken } from "@clerk/backend";
2import { describe, expect, it } from "@effect/vitest";
3import { vi } from "vite-plus/test";
4import * as Context from "effect/Context";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Predicate from "effect/Predicate";
11import * as Redacted from "effect/Redacted";
12import * as TestClock from "effect/testing/TestClock";
13import * as Tracer from "effect/Tracer";
14import * as HttpRouter from "effect/unstable/http/HttpRouter";
15import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
16import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
17import { RelayEnvironmentAuth } from "@t3tools/contracts/relay";
18
19import {
20 RELAY_REQUEST_DEADLINE_MS,
21 relayCors,
22 relayDocsRedirectRoute,
23 relayEnvironmentAuthLayer,
24 relayNotFoundRoute,
25 traceRelayHttpRequestWith,
26 verifyRelayClientBearerToken,
27 withoutCapturedParentSpan,
28} from "./Api.ts";
29import * as RelayConfiguration from "../Config.ts";
30import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts";
31
32vi.mock("@clerk/backend", () => ({
33 createClerkClient: vi.fn(),
34 verifyToken: vi.fn(),
35}));
36
37const relaySettings: RelayConfiguration.RelayConfiguration["Service"] = {
38 relayIssuer: "https://relay.example.test",
39 apns: {
40 teamId: "apns-team",
41 keyId: "apns-key",
42 privateKey: Redacted.make("apns-private-key"),
43 bundleId: "com.example.t3",
44 environment: "sandbox",
45 },
46 clerkSecretKey: Redacted.make("clerk-secret-key"),
47 clerkPublishableKey: "pk_test_test",
48 clerkJwtAudience: "t3-code-relay",
49 apnsDeliveryJobSigningSecret: Redacted.make("apns-delivery-secret"),
50 cloudMintPrivateKey: Redacted.make("cloud-mint-private-key"),
51 cloudMintPublicKey: "cloud-mint-public-key",
52 managedEndpointBaseDomain: undefined,
53 managedEndpointNamespace: undefined,
54};
55
56describe("relay client authentication", () => {
57 it.effect("preserves the existing Clerk session JWT path", () =>
58 Effect.gen(function* () {
59 vi.mocked(verifyToken).mockResolvedValue({
60 sub: "user_session",
61 aud: relaySettings.clerkJwtAudience,
62 } as never);
63
64 expect(yield* verifyRelayClientBearerToken(relaySettings, "session-token")).toEqual({
65 sub: "user_session",
66 mode: "clerk_session_bearer",
67 });
68 expect(verifyToken).toHaveBeenCalledWith("session-token", {
69 secretKey: "clerk-secret-key",
70 audience: relaySettings.clerkJwtAudience,
71 });
72 expect(createClerkClient).not.toHaveBeenCalled();
73 }).pipe(
74 Effect.ensuring(
75 Effect.sync(() => {
76 vi.mocked(verifyToken).mockReset();
77 vi.mocked(createClerkClient).mockReset();
78 }),
79 ),
80 ),
81 );
82
83 it.effect("falls back to Clerk OAuth token verification for the headless CLI", () =>
84 Effect.gen(function* () {
85 vi.mocked(verifyToken).mockRejectedValue(new Error("not a session JWT"));
86 vi.mocked(createClerkClient).mockReturnValue({
87 authenticateRequest: vi.fn().mockResolvedValue({
88 isAuthenticated: true,
89 toAuth: () => ({ userId: "user_oauth" }),
90 }),
91 } as never);
92
93 expect(yield* verifyRelayClientBearerToken(relaySettings, "oauth-token")).toEqual({
94 sub: "user_oauth",
95 mode: "clerk_oauth_bearer",
96 });
97 expect(createClerkClient).toHaveBeenCalledWith({
98 secretKey: "clerk-secret-key",
99 publishableKey: "pk_test_test",
100 });
101 }).pipe(
102 Effect.ensuring(
103 Effect.sync(() => {
104 vi.mocked(verifyToken).mockReset();
105 vi.mocked(createClerkClient).mockReset();
106 }),
107 ),
108 ),
109 );
110});
111
112describe("relay environment authentication", () => {
113 it.effect("preserves credential lookup persistence failures as internal errors", () => {
114 const failure = new EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError({
115 stage: "lookup-credential",
116 cause: "database unavailable",
117 });
118 const credentials: EnvironmentCredentials.EnvironmentCredentials["Service"] = {
119 create: () => Effect.die("unused create"),
120 authenticate: () => Effect.fail(failure),
121 revokeForEnvironmentPublicKey: () => Effect.die("unused revoke"),
122 };
123
124 return Effect.gen(function* () {
125 const auth = yield* RelayEnvironmentAuth;
126 const error = yield* Effect.flip(
127 auth.environmentBearer(Effect.succeed(HttpServerResponse.empty()), {
128 credential: Redacted.make("environment-credential"),
129 endpoint: {} as never,
130 group: {} as never,
131 }),
132 );
133
134 expect(Predicate.isTagged(error, "RelayInternalError")).toBe(true);
135 if (Predicate.isTagged(error, "RelayInternalError")) {
136 expect(error.reason).toBe("persistence_failed");
137 }
138 }).pipe(
139 Effect.provideService(
140 HttpServerRequest.HttpServerRequest,
141 HttpServerRequest.fromWeb(new Request("https://relay.test/v1/server/link")),
142 ),
143 Effect.provideService(HttpServerRequest.ParsedSearchParams, {}),
144 Effect.provideService(HttpRouter.RouteContext, {
145 params: {},
146 route: {} as never,
147 }),
148 Effect.provide(
149 relayEnvironmentAuthLayer.pipe(
150 Layer.provide(Layer.succeed(EnvironmentCredentials.EnvironmentCredentials, credentials)),
151 ),
152 ),
153 Effect.scoped,
154 );
155 });
156});
157
158describe("relay request tracing", () => {
159 it.effect(
160 "does not parent endpoint spans to an ambient parent captured while building handlers",
161 () =>
162 Effect.gen(function* () {
163 const spans: Array<Tracer.NativeSpan> = [];
164 const tracer = Tracer.make({
165 span: (options) => {
166 const span = new Tracer.NativeSpan(options);
167 spans.push(span);
168 return span;
169 },
170 });
171 const ambientParent = Tracer.externalSpan({
172 traceId: "00000000000000000000000000000001",
173 spanId: "0000000000000001",
174 sampled: true,
175 });
176 const endpoint = yield* withoutCapturedParentSpan(
177 Effect.context<never>().pipe(
178 Effect.map((capturedContext: Context.Context<never>) =>
179 Effect.succeed(HttpServerResponse.empty({ status: 204 })).pipe(
180 Effect.withSpan("relay.test.endpoint"),
181 Effect.provideContext(capturedContext),
182 ),
183 ),
184 ),
185 ).pipe(Effect.provideService(Tracer.ParentSpan, ambientParent));
186 const request = HttpServerRequest.fromWeb(
187 new Request("https://relay.test/v1/mobile/devices?client=mobile", {
188 method: "POST",
189 headers: {
190 authorization: "Bearer secret",
191 dpop: "signed-proof",
192 },
193 }),
194 );
195
196 yield* traceRelayHttpRequestWith(endpoint, Layer.succeed(Tracer.Tracer, tracer)).pipe(
197 Effect.provideService(HttpServerRequest.HttpServerRequest, request),
198 );
199
200 expect(spans.map((span) => span.name)).toEqual(["http.server POST", "relay.test.endpoint"]);
201 expect(spans[0]?.kind).toBe("server");
202 expect(spans[0]?.attributes.get("url.path")).toBe("/v1/mobile/devices");
203 expect(spans[0]?.attributes.get("http.response.status_code")).toBe(204);
204 expect(spans[0]?.attributes.get("http.request.header.authorization")).toBe("<redacted>");
205 expect(spans[0]?.attributes.get("http.request.header.dpop")).toBe("<redacted>");
206 expect(Option.isNone(spans[0]!.parent)).toBe(true);
207 expect(Option.getOrUndefined(spans[1]!.parent)?.spanId).toBe(spans[0]?.spanId);
208 }),
209 );
210
211 it.effect("fails hung requests with a 504 before the client's 10s abort", () =>
212 Effect.gen(function* () {
213 const spans: Array<Tracer.NativeSpan> = [];
214 const tracer = Tracer.make({
215 span: (options) => {
216 const span = new Tracer.NativeSpan(options);
217 spans.push(span);
218 return span;
219 },
220 });
221 const request = HttpServerRequest.fromWeb(
222 new Request("https://relay.test/v1/mobile/devices", { method: "POST" }),
223 );
224
225 const fiber = yield* traceRelayHttpRequestWith(
226 Effect.never,
227 Layer.succeed(Tracer.Tracer, tracer),
228 ).pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request), Effect.forkChild);
229 yield* TestClock.adjust(Duration.millis(RELAY_REQUEST_DEADLINE_MS));
230 const response = yield* Fiber.join(fiber);
231
232 expect(response.status).toBe(504);
233 expect(spans[0]?.attributes.get("relay.request.deadline_exceeded")).toBe(true);
234 expect(spans[0]?.attributes.get("http.response.status_code")).toBe(504);
235 }),
236 );
237});
238
239describe("relay routing fallback", () => {
240 it.effect("redirects the relay root to the API docs", () =>
241 Effect.gen(function* () {
242 const request = HttpServerRequest.fromWeb(new Request("https://relay.test/"));
243 const httpEffect = yield* HttpRouter.toHttpEffect(
244 Layer.mergeAll(relayDocsRedirectRoute, relayNotFoundRoute, relayCors),
245 );
246 const response = yield* httpEffect.pipe(
247 Effect.provideService(HttpServerRequest.HttpServerRequest, request),
248 );
249
250 expect(response.status).toBe(302);
251 expect(response.headers.location).toBe("/docs");
252 expect(response.headers["access-control-allow-origin"]).toBe("*");
253 }).pipe(Effect.scoped),
254 );
255
256 it.effect("returns a CORS-compatible 404 response for unmatched paths", () =>
257 Effect.gen(function* () {
258 const request = HttpServerRequest.fromWeb(
259 new Request("https://relay.test/v1/environmentsd", { method: "GET" }),
260 );
261 const httpEffect = yield* HttpRouter.toHttpEffect(Layer.merge(relayNotFoundRoute, relayCors));
262 const response = yield* httpEffect.pipe(
263 Effect.provideService(HttpServerRequest.HttpServerRequest, request),
264 );
265
266 expect(response.status).toBe(404);
267 expect(response.headers["access-control-allow-origin"]).toBe("*");
268 }).pipe(Effect.scoped),
269 );
270});