Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

layer.test.ts

406 lines13.7 KB

1import { AuthStandardClientScopes, EnvironmentId } from "@t3tools/contracts";
2import { describe, expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Ref from "effect/Ref";
7import * as TestClock from "effect/testing/TestClock";
8​
9import * as ManagedRelay from "../relay/managedRelay.ts";
10import { remoteHttpClientLayer } from "../rpc/http.ts";
11import * as ClientCapabilities from "../platform/capabilities.ts";
12import * as RemoteEnvironmentAuthorization from "./service.ts";
13import * as TokenStore from "./tokenStore.ts";
14​
15const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
16const ENDPOINT = {
17 httpBaseUrl: "https://environment.example.test",
18 wsBaseUrl: "wss://environment.example.test",
19 providerKind: "cloudflare_tunnel" as const,
20};
21const DESCRIPTOR = {
22 environmentId: ENVIRONMENT_ID,
23 label: "Remote environment",
24 platform: {
25 os: "linux",
26 arch: "x64",
27 },
28 serverVersion: "0.0.0-test",
29 capabilities: {
30 repositoryIdentity: true,
31 },
32};
33const BOOTSTRAP: RemoteEnvironmentAuthorization.RelayEnvironmentAuthorization = {
34 environmentId: ENVIRONMENT_ID,
35 endpoint: ENDPOINT,
36 credential: "relay-bootstrap",
37};
38​
39function recordedFetch(responses: ReadonlyArray<Response>) {
40 const calls: Array<readonly [RequestInfo | URL, RequestInit]> = [];
41 let responseIndex = 0;
42 const fetchFn = ((input, init) => {
43 calls.push([input, init ?? {}]);
44 const response = responses[responseIndex++];
45 return response === undefined
46 ? Promise.reject(new Error(`Unexpected fetch call to ${String(input)}`))
47 : Promise.resolve(response);
48 }) satisfies typeof fetch;
49 return { calls, fetchFn };
51​
52const websocketTicket = (ticket: string) =>
53 Response.json({
54 ticket,
55 expiresAt: "2026-06-06T01:00:00.000Z",
56 });
57​
58const accessToken = (token: string) =>
59 Response.json({
60 access_token: token,
61 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
62 token_type: "DPoP",
63 expires_in: 3_600,
64 scope: AuthStandardClientScopes.join(" "),
65 });
66​
67const authInvalid = () =>
68 Response.json(
69 {
70 _tag: "EnvironmentAuthInvalidError",
71 code: "auth_invalid",
72 reason: "invalid_credential",
73 traceId: "trace-auth-invalid",
74 },
75 { status: 401 },
76 );
77​
78const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (input: {
79 readonly initialToken?: TokenStore.RemoteDpopAccessToken;
80 readonly responses: ReadonlyArray<Response>;
81}) {
82 const tokens = yield* Ref.make(
83 new Map(
84 input.initialToken === undefined
85 ? []
86 : [[input.initialToken.environmentId, input.initialToken]],
87 ),
88 );
89 const bootstrapCalls = yield* Ref.make(0);
90 const proofInputs = yield* Ref.make<
91 ReadonlyArray<{
92 readonly method: string;
93 readonly url: string;
94 readonly accessToken?: string;
95 }>
96 >([]);
97 const fetch = recordedFetch(input.responses);
98​
99 const tokenStore = TokenStore.RemoteDpopAccessTokenStore.of({
100 get: (environmentId) =>
101 Ref.get(tokens).pipe(
102 Effect.map((current) => Option.fromUndefinedOr(current.get(environmentId))),
103 ),
104 put: (token) =>
105 Ref.update(tokens, (current) => {
106 const next = new Map(current);
107 next.set(token.environmentId, token);
108 return next;
109 }),
110 remove: (environmentId) =>
111 Ref.update(tokens, (current) => {
112 const next = new Map(current);
113 next.delete(environmentId);
114 return next;
115 }),
116 });
117 const signer = ManagedRelay.ManagedRelayDpopSigner.of({
118 thumbprint: Effect.succeed("thumbprint-1"),
119 createProof: (proofInput) =>
120 Ref.update(proofInputs, (current) => [...current, proofInput]).pipe(
121 Effect.as(`proof:${proofInput.url}`),
122 ),
123 });
124 const layer = RemoteEnvironmentAuthorization.layer.pipe(
125 Layer.provide(
126 Layer.mergeAll(
127 remoteHttpClientLayer(fetch.fetchFn),
128 Layer.succeed(ManagedRelay.ManagedRelayDpopSigner, signer),
129 Layer.succeed(TokenStore.RemoteDpopAccessTokenStore, tokenStore),
130 Layer.succeed(
131 ClientCapabilities.ClientPresentation,
132 ClientCapabilities.ClientPresentation.of({
133 metadata: {
134 label: "T3 Code Test",
135 deviceType: "mobile",
136 os: "test",
137 },
138 scopes: AuthStandardClientScopes,
139 }),
140 ),
141 ),
142 ),
143 );
144 const obtainBootstrap = Ref.update(bootstrapCalls, (count) => count + 1).pipe(
145 Effect.as(BOOTSTRAP),
146 );
147​
148 return {
149 layer,
150 tokens,
151 bootstrapCalls,
152 proofInputs,
153 fetch,
154 obtainBootstrap,
155 };
156});
157​
158describe("RemoteEnvironmentAuthorization", () => {
159 it.effect("reuses a validated bearer descriptor while issuing fresh websocket tickets", () =>
160 Effect.gen(function* () {
161 const harness = yield* makeHarness({
162 responses: [
163 Response.json(DESCRIPTOR),
164 websocketTicket("first-ticket"),
165 websocketTicket("second-ticket"),
166 ],
167 });
168​
169 const [first, second] = yield* Effect.gen(function* () {
170 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
171 const authorize = () =>
172 remote.authorizeBearer({
173 expectedEnvironmentId: ENVIRONMENT_ID,
174 httpBaseUrl: ENDPOINT.httpBaseUrl,
175 wsBaseUrl: ENDPOINT.wsBaseUrl,
176 bearerToken: "bearer-token",
177 });
178 return [yield* authorize(), yield* authorize()] as const;
179 }).pipe(Effect.provide(harness.layer));
180​
181 expect(first.socketUrl).toContain("wsTicket=first-ticket");
182 expect(second.socketUrl).toContain("wsTicket=second-ticket");
183 expect(
184 harness.fetch.calls.filter(([url]) => String(url).endsWith("/.well-known/t3/environment")),
185 ).toHaveLength(1);
186 expect(
187 harness.fetch.calls.filter(([url]) => String(url).endsWith("/api/auth/websocket-ticket")),
188 ).toHaveLength(2);
189 }),
190 );
191​
192 it.effect("revalidates a bearer descriptor after the cache expires", () =>
193 Effect.gen(function* () {
194 const reassignedEnvironmentId = EnvironmentId.make("environment-2");
195 const harness = yield* makeHarness({
196 responses: [
197 Response.json(DESCRIPTOR),
198 websocketTicket("first-ticket"),
199 Response.json({
200 ...DESCRIPTOR,
201 environmentId: reassignedEnvironmentId,
202 }),
203 ],
204 });
205​
206 const failure = yield* Effect.gen(function* () {
207 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
208 const authorize = () =>
209 remote.authorizeBearer({
210 expectedEnvironmentId: ENVIRONMENT_ID,
211 httpBaseUrl: ENDPOINT.httpBaseUrl,
212 wsBaseUrl: ENDPOINT.wsBaseUrl,
213 bearerToken: "bearer-token",
214 });
215​
216 yield* authorize();
217 yield* TestClock.adjust("10 seconds");
218 return yield* authorize().pipe(Effect.flip);
219 }).pipe(Effect.provide(Layer.merge(harness.layer, TestClock.layer())));
220​
221 expect(failure).toEqual(
222 expect.objectContaining({
223 _tag: "ConnectionBlockedError",
224 reason: "configuration",
225 detail: `Connected environment ${reassignedEnvironmentId} does not match ${ENVIRONMENT_ID}.`,
226 }),
227 );
228 expect(
229 harness.fetch.calls.filter(([url]) => String(url).endsWith("/.well-known/t3/environment")),
230 ).toHaveLength(2);
231 }),
232 );
233​
234 it.effect("reuses a valid persisted environment token without contacting the relay", () =>
235 Effect.gen(function* () {
236 const cached = new TokenStore.RemoteDpopAccessToken({
237 environmentId: ENVIRONMENT_ID,
238 label: DESCRIPTOR.label,
239 endpoint: ENDPOINT,
240 accessToken: "cached-access-token",
241 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
242 dpopThumbprint: "thumbprint-1",
243 });
244 const harness = yield* makeHarness({
245 initialToken: cached,
246 responses: [websocketTicket("cached-ticket")],
247 });
248​
249 const authorized = yield* Effect.gen(function* () {
250 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
251 return yield* remote.authorizeDpop({
252 expectedEnvironmentId: ENVIRONMENT_ID,
253 obtainBootstrap: harness.obtainBootstrap,
254 });
255 }).pipe(Effect.provide(harness.layer));
256​
257 expect(authorized.socketUrl).toContain("wsTicket=cached-ticket");
258 expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0);
259 expect(harness.fetch.calls).toHaveLength(1);
260 expect(String(harness.fetch.calls[0]?.[0])).toBe(
261 "https://environment.example.test/api/auth/websocket-ticket",
262 );
263 }),
264 );
265​
266 it.effect("refreshes and persists an expired environment token", () =>
267 Effect.gen(function* () {
268 const expired = new TokenStore.RemoteDpopAccessToken({
269 environmentId: ENVIRONMENT_ID,
270 label: DESCRIPTOR.label,
271 endpoint: ENDPOINT,
272 accessToken: "expired-access-token",
273 expiresAtEpochMs: 0,
274 dpopThumbprint: "thumbprint-1",
275 });
276 const harness = yield* makeHarness({
277 initialToken: expired,
278 responses: [
279 Response.json(DESCRIPTOR),
280 accessToken("fresh-access-token"),
281 websocketTicket("fresh-ticket"),
282 ],
283 });
284​
285 const authorized = yield* Effect.gen(function* () {
286 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
287 return yield* remote.authorizeDpop({
288 expectedEnvironmentId: ENVIRONMENT_ID,
289 obtainBootstrap: harness.obtainBootstrap,
290 });
291 }).pipe(Effect.provide(harness.layer));
292​
293 expect(authorized.socketUrl).toContain("wsTicket=fresh-ticket");
294 expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
295 expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual(
296 expect.objectContaining({
297 accessToken: "fresh-access-token",
298 dpopThumbprint: "thumbprint-1",
299 }),
300 );
301 expect(harness.fetch.calls).toHaveLength(3);
302 }),
303 );
304​
305 it.effect("evicts an auth-invalid cached token and obtains a fresh bootstrap", () =>
306 Effect.gen(function* () {
307 const cached = new TokenStore.RemoteDpopAccessToken({
308 environmentId: ENVIRONMENT_ID,
309 label: DESCRIPTOR.label,
310 endpoint: ENDPOINT,
311 accessToken: "invalid-access-token",
312 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
313 dpopThumbprint: "thumbprint-1",
314 });
315 const harness = yield* makeHarness({
316 initialToken: cached,
317 responses: [
318 authInvalid(),
319 Response.json(DESCRIPTOR),
320 accessToken("replacement-access-token"),
321 websocketTicket("replacement-ticket"),
322 ],
323 });
324​
325 const authorized = yield* Effect.gen(function* () {
326 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
327 return yield* remote.authorizeDpop({
328 expectedEnvironmentId: ENVIRONMENT_ID,
329 obtainBootstrap: harness.obtainBootstrap,
330 });
331 }).pipe(Effect.provide(harness.layer));
332​
333 expect(authorized.socketUrl).toContain("wsTicket=replacement-ticket");
334 expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
335 expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual(
336 expect.objectContaining({
337 accessToken: "replacement-access-token",
338 }),
339 );
340 expect(harness.fetch.calls).toHaveLength(4);
341 }),
342 );
343​
344 it.effect("refreshes a cached endpoint after its first transient failure", () =>
345 Effect.gen(function* () {
346 const cached = new TokenStore.RemoteDpopAccessToken({
347 environmentId: ENVIRONMENT_ID,
348 label: DESCRIPTOR.label,
349 endpoint: ENDPOINT,
350 accessToken: "cached-access-token",
351 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
352 dpopThumbprint: "thumbprint-1",
353 });
354 const harness = yield* makeHarness({
355 initialToken: cached,
356 responses: [
357 new Response("endpoint unavailable", { status: 503 }),
358 Response.json(DESCRIPTOR),
359 accessToken("replacement-access-token"),
360 websocketTicket("replacement-ticket"),
361 ],
362 });
363​
364 const authorized = yield* Effect.gen(function* () {
365 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
366 return yield* remote.authorizeDpop({
367 expectedEnvironmentId: ENVIRONMENT_ID,
368 obtainBootstrap: harness.obtainBootstrap,
369 });
370 }).pipe(Effect.provide(harness.layer));
371​
372 expect(authorized.socketUrl).toContain("wsTicket=replacement-ticket");
373 expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
374 expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual(
375 expect.objectContaining({
376 accessToken: "replacement-access-token",
377 }),
378 );
379 expect(harness.fetch.calls).toHaveLength(4);
380 }),
381 );
382​
383 it.effect("does not persist a refreshed token until its websocket ticket succeeds", () =>
384 Effect.gen(function* () {
385 const harness = yield* makeHarness({
386 responses: [
387 Response.json(DESCRIPTOR),
388 accessToken("unusable-access-token"),
389 new Response("endpoint unavailable", { status: 503 }),
390 ],
391 });
392​
393 yield* Effect.gen(function* () {
394 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
395 return yield* remote.authorizeDpop({
396 expectedEnvironmentId: ENVIRONMENT_ID,
397 obtainBootstrap: harness.obtainBootstrap,
398 });
399 }).pipe(Effect.provide(harness.layer), Effect.flip);
400​
401 expect((yield* Ref.get(harness.tokens)).has(ENVIRONMENT_ID)).toBe(false);
402 expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
403 expect(harness.fetch.calls).toHaveLength(3);
404 }),
405 );
406});