The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { |
| 2 | AuthStandardClientScopes, |
| 3 | EnvironmentId, |
| 4 | ORCHESTRATION_PROTOCOL_VERSION, |
| 5 | type ExecutionEnvironmentDescriptor, |
| 6 | } from "@t3tools/contracts"; |
| 7 | import { type RelayEnvironmentConnectResponse } from "@t3tools/contracts/relay"; |
| 8 | import { describe, expect, it } from "@effect/vitest"; |
| 9 | import * as Deferred from "effect/Deferred"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Fiber from "effect/Fiber"; |
| 12 | import * as Layer from "effect/Layer"; |
| 13 | import * as Option from "effect/Option"; |
| 14 | import * as Queue from "effect/Queue"; |
| 15 | import * as Ref from "effect/Ref"; |
| 16 | import * as TestClock from "effect/testing/TestClock"; |
| 17 | |
| 18 | import * as ManagedRelay from "../relay/managedRelay.ts"; |
| 19 | import * as RpcHttp from "../rpc/http.ts"; |
| 20 | import * as ClientCapabilities from "../platform/capabilities.ts"; |
| 21 | import * as RemoteEnvironmentAuthorization from "./service.ts"; |
| 22 | import * as TokenStore from "./tokenStore.ts"; |
| 23 | import { |
| 24 | BearerConnectionCredential, |
| 25 | BearerConnectionProfile, |
| 26 | type ConnectionCredential, |
| 27 | DpopConnectionCredential, |
| 28 | } from "../connection/catalog.ts"; |
| 29 | import * as ConnectionCredentialStore from "../connection/credentialStore.ts"; |
| 30 | import { BearerConnectionTarget } from "../connection/model.ts"; |
| 31 | import * as ConnectionProfileStore from "../connection/profileStore.ts"; |
| 32 | import * as ConnectionResolver from "../connection/resolver.ts"; |
| 33 | |
| 34 | const ENVIRONMENT_ID = EnvironmentId.make("environment-1"); |
| 35 | const ENDPOINT = { |
| 36 | httpBaseUrl: "https://environment.example.test", |
| 37 | wsBaseUrl: "wss://environment.example.test", |
| 38 | providerKind: "cloudflare_tunnel" as const, |
| 39 | }; |
| 40 | const DESCRIPTOR = { |
| 41 | environmentId: ENVIRONMENT_ID, |
| 42 | label: "Remote environment", |
| 43 | platform: { |
| 44 | os: "linux", |
| 45 | arch: "x64", |
| 46 | }, |
| 47 | serverVersion: "0.0.0-test", |
| 48 | capabilities: { |
| 49 | repositoryIdentity: true, |
| 50 | }, |
| 51 | }; |
| 52 | const BOOTSTRAP: RelayEnvironmentConnectResponse = { |
| 53 | environmentId: ENVIRONMENT_ID, |
| 54 | endpoint: ENDPOINT, |
| 55 | credential: "relay-bootstrap", |
| 56 | expiresAt: "2026-06-06T01:00:00.000Z", |
| 57 | }; |
| 58 | |
| 59 | type RecordedResponse = Response | ((init: RequestInit) => Response | Promise<Response>); |
| 60 | |
| 61 | function recordedFetch(responses: ReadonlyArray<RecordedResponse>, descriptor?: object) { |
| 62 | const calls: Array<readonly [RequestInfo | URL, RequestInit]> = []; |
| 63 | let responseIndex = 0; |
| 64 | const fetchFn = ((input, init) => { |
| 65 | calls.push([input, init ?? {}]); |
| 66 | if (descriptor !== undefined && String(input).endsWith("/.well-known/t3/environment")) { |
| 67 | return Promise.resolve(Response.json(descriptor)); |
| 68 | } |
| 69 | const response = responses[responseIndex++]; |
| 70 | return response === undefined |
| 71 | ? Promise.reject(new Error(`Unexpected fetch call to ${String(input)}`)) |
| 72 | : Promise.resolve(typeof response === "function" ? response(init ?? {}) : response); |
| 73 | }) satisfies typeof fetch; |
| 74 | return { calls, fetchFn }; |
| 75 | } |
| 76 | |
| 77 | const websocketTicket = (ticket: string) => |
| 78 | Response.json({ |
| 79 | ticket, |
| 80 | expiresAt: "2026-06-06T01:00:00.000Z", |
| 81 | }); |
| 82 | |
| 83 | const accessToken = (token: string, scope = AuthStandardClientScopes.join(" ")) => |
| 84 | Response.json({ |
| 85 | access_token: token, |
| 86 | issued_token_type: "urn:ietf:params:oauth:token-type:access_token", |
| 87 | token_type: "DPoP", |
| 88 | expires_in: 3_600, |
| 89 | scope, |
| 90 | }); |
| 91 | |
| 92 | const authInvalid = () => |
| 93 | Response.json( |
| 94 | { |
| 95 | _tag: "EnvironmentAuthInvalidError", |
| 96 | code: "auth_invalid", |
| 97 | reason: "invalid_credential", |
| 98 | traceId: "trace-auth-invalid", |
| 99 | }, |
| 100 | { status: 401 }, |
| 101 | ); |
| 102 | |
| 103 | const persistedToken = ( |
| 104 | input: { |
| 105 | readonly environmentId?: EnvironmentId; |
| 106 | readonly accessToken?: string; |
| 107 | readonly expiresAtEpochMs?: number; |
| 108 | readonly dpopThumbprint?: string; |
| 109 | } = {}, |
| 110 | ) => |
| 111 | new TokenStore.RemoteDpopAccessToken({ |
| 112 | environmentId: input.environmentId ?? ENVIRONMENT_ID, |
| 113 | accountId: "account-1", |
| 114 | label: DESCRIPTOR.label, |
| 115 | endpoint: ENDPOINT, |
| 116 | accessToken: input.accessToken ?? "cached-access-token", |
| 117 | expiresAtEpochMs: input.expiresAtEpochMs ?? Number.MAX_SAFE_INTEGER, |
| 118 | dpopThumbprint: input.dpopThumbprint ?? "thumbprint-1", |
| 119 | }); |
| 120 | |
| 121 | const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (input: { |
| 122 | readonly initialToken?: TokenStore.RemoteDpopAccessToken; |
| 123 | readonly responses: ReadonlyArray<RecordedResponse>; |
| 124 | /** Answers every descriptor read, so one that runs beside a ticket does not shift `responses`. */ |
| 125 | readonly descriptor?: object; |
| 126 | readonly bootstrap?: RelayEnvironmentConnectResponse; |
| 127 | readonly beforeBootstrap?: Effect.Effect<void, ManagedRelay.ManagedRelayClientError>; |
| 128 | readonly beforePut?: Effect.Effect<void>; |
| 129 | readonly clerkToken?: ClientCapabilities.CloudSession["Service"]["clerkToken"]; |
| 130 | readonly credentials?: ReadonlyArray<readonly [string, ConnectionCredential]>; |
| 131 | }) { |
| 132 | const tokens = yield* Ref.make( |
| 133 | new Map( |
| 134 | input.initialToken === undefined |
| 135 | ? [] |
| 136 | : [[input.initialToken.environmentId, input.initialToken]], |
| 137 | ), |
| 138 | ); |
| 139 | const bootstrapCalls = yield* Ref.make(0); |
| 140 | const relayInputs = yield* Ref.make< |
| 141 | ReadonlyArray<Parameters<ManagedRelay.ManagedRelayClient["Service"]["connectEnvironment"]>[0]> |
| 142 | >([]); |
| 143 | const session = yield* Ref.make<Option.Option<ClientCapabilities.CloudSessionIdentity>>( |
| 144 | Option.some({ accountId: "account-1" }), |
| 145 | ); |
| 146 | const thumbprint = yield* Ref.make("thumbprint-1"); |
| 147 | const tokenReads = yield* Queue.unbounded<EnvironmentId>(); |
| 148 | const proofInputs = yield* Ref.make< |
| 149 | ReadonlyArray<{ |
| 150 | readonly method: string; |
| 151 | readonly url: string; |
| 152 | readonly accessToken?: string; |
| 153 | }> |
| 154 | >([]); |
| 155 | const fetch = recordedFetch(input.responses, input.descriptor); |
| 156 | |
| 157 | const tokenStore = TokenStore.RemoteDpopAccessTokenStore.of({ |
| 158 | get: (environmentId) => |
| 159 | Ref.get(tokens).pipe( |
| 160 | Effect.map((current) => Option.fromUndefinedOr(current.get(environmentId))), |
| 161 | Effect.tap(() => Queue.offer(tokenReads, environmentId)), |
| 162 | ), |
| 163 | put: (token) => |
| 164 | (input.beforePut ?? Effect.void).pipe( |
| 165 | Effect.andThen( |
| 166 | Ref.update(tokens, (current) => { |
| 167 | const next = new Map(current); |
| 168 | next.set(token.environmentId, token); |
| 169 | return next; |
| 170 | }), |
| 171 | ), |
| 172 | ), |
| 173 | remove: (environmentId) => |
| 174 | Ref.update(tokens, (current) => { |
| 175 | const next = new Map(current); |
| 176 | next.delete(environmentId); |
| 177 | return next; |
| 178 | }), |
| 179 | }); |
| 180 | const signer = ManagedRelay.ManagedRelayDpopSigner.of({ |
| 181 | thumbprint: Ref.get(thumbprint), |
| 182 | createProof: (proofInput) => |
| 183 | Ref.update(proofInputs, (current) => [...current, proofInput]).pipe( |
| 184 | Effect.as(`proof:${proofInput.url}`), |
| 185 | ), |
| 186 | }); |
| 187 | const unexpected = () => Effect.die("Unexpected relay request"); |
| 188 | const relay = ManagedRelay.ManagedRelayClient.of({ |
| 189 | relayUrl: "https://relay.example.test", |
| 190 | listEnvironments: unexpected, |
| 191 | listDevices: unexpected, |
| 192 | createEnvironmentLinkChallenge: unexpected, |
| 193 | linkEnvironment: unexpected, |
| 194 | unlinkEnvironment: unexpected, |
| 195 | getT3ChatLink: unexpected, |
| 196 | createT3ChatLinkRequest: unexpected, |
| 197 | unlinkT3Chat: unexpected, |
| 198 | getEnvironmentStatus: unexpected, |
| 199 | connectEnvironment: (request) => |
| 200 | Effect.gen(function* () { |
| 201 | yield* Ref.update(bootstrapCalls, (count) => count + 1); |
| 202 | yield* Ref.update(relayInputs, (current) => [...current, request]); |
| 203 | yield* input.beforeBootstrap ?? Effect.void; |
| 204 | return input.bootstrap ?? BOOTSTRAP; |
| 205 | }), |
| 206 | registerDevice: unexpected, |
| 207 | unregisterDevice: unexpected, |
| 208 | registerLiveActivity: unexpected, |
| 209 | getAgentActivitySnapshot: unexpected, |
| 210 | resetTokenCache: Effect.void, |
| 211 | }); |
| 212 | const layer = RemoteEnvironmentAuthorization.layer.pipe( |
| 213 | Layer.provideMerge( |
| 214 | Layer.mergeAll( |
| 215 | RpcHttp.layerRemoteHttpClient(fetch.fetchFn), |
| 216 | Layer.succeed(ManagedRelay.ManagedRelayDpopSigner, signer), |
| 217 | Layer.succeed(ManagedRelay.ManagedRelayClient, relay), |
| 218 | Layer.succeed(ClientCapabilities.CloudSession, { |
| 219 | identity: Ref.get(session), |
| 220 | clerkToken: input.clerkToken ?? Effect.succeed("clerk-session"), |
| 221 | }), |
| 222 | Layer.succeed(ClientCapabilities.RelayDeviceIdentity, { |
| 223 | deviceId: Effect.succeedSome("device-1"), |
| 224 | }), |
| 225 | Layer.succeed(TokenStore.RemoteDpopAccessTokenStore, tokenStore), |
| 226 | ConnectionCredentialStore.layerMemory(input.credentials), |
| 227 | Layer.succeed( |
| 228 | ClientCapabilities.ClientPresentation, |
| 229 | ClientCapabilities.ClientPresentation.of({ |
| 230 | metadata: { |
| 231 | label: "T3 Code Test", |
| 232 | deviceType: "mobile", |
| 233 | os: "test", |
| 234 | }, |
| 235 | }), |
| 236 | ), |
| 237 | ), |
| 238 | ), |
| 239 | ); |
| 240 | return { |
| 241 | layer, |
| 242 | tokens, |
| 243 | bootstrapCalls, |
| 244 | proofInputs, |
| 245 | fetch, |
| 246 | relayInputs, |
| 247 | session, |
| 248 | thumbprint, |
| 249 | tokenReads, |
| 250 | }; |
| 251 | }); |
| 252 | |
| 253 | const requestsTo = (harness: Effect.Success<ReturnType<typeof makeHarness>>, path: string) => |
| 254 | harness.fetch.calls.filter(([url]) => String(url).endsWith(path)).length; |
| 255 | |
| 256 | const prepareDirectBearer = Effect.fn("TestRemoteAuthorization.prepareDirectBearer")(function* ( |
| 257 | harness: Effect.Success<ReturnType<typeof makeHarness>>, |
| 258 | times: number, |
| 259 | ) { |
| 260 | const target = new BearerConnectionTarget({ |
| 261 | environmentId: ENVIRONMENT_ID, |
| 262 | label: DESCRIPTOR.label, |
| 263 | connectionId: "direct-1", |
| 264 | }); |
| 265 | const entry = { |
| 266 | target, |
| 267 | profile: Option.some( |
| 268 | new BearerConnectionProfile({ |
| 269 | connectionId: target.connectionId, |
| 270 | environmentId: ENVIRONMENT_ID, |
| 271 | label: target.label, |
| 272 | httpBaseUrl: ENDPOINT.httpBaseUrl, |
| 273 | wsBaseUrl: ENDPOINT.wsBaseUrl, |
| 274 | }), |
| 275 | ), |
| 276 | enabled: true, |
| 277 | }; |
| 278 | const unused = () => Effect.die("unused"); |
| 279 | const layer = ConnectionResolver.layer.pipe( |
| 280 | Layer.provide( |
| 281 | Layer.mergeAll( |
| 282 | harness.layer, |
| 283 | Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, { |
| 284 | get: unused, |
| 285 | put: unused, |
| 286 | remove: unused, |
| 287 | }), |
| 288 | Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, { |
| 289 | get: () => Effect.succeedSome(new BearerConnectionCredential({ token: "bearer-token" })), |
| 290 | put: unused, |
| 291 | remove: unused, |
| 292 | }), |
| 293 | Layer.succeed(ClientCapabilities.PrimaryEnvironmentAuth, { |
| 294 | bearerToken: Effect.succeedNone, |
| 295 | }), |
| 296 | Layer.succeed(ClientCapabilities.SshEnvironmentGateway, { |
| 297 | provision: unused, |
| 298 | prepare: unused, |
| 299 | disconnect: unused, |
| 300 | }), |
| 301 | ), |
| 302 | ), |
| 303 | ); |
| 304 | const resolver = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layer)); |
| 305 | return yield* Effect.forEach(Array.from({ length: times }), () => |
| 306 | resolver.prepare(entry).pipe(Effect.result), |
| 307 | ); |
| 308 | }); |
| 309 | |
| 310 | describe("RemoteEnvironmentAuthorization", () => { |
| 311 | it.effect("prepares a cold direct bearer connection with one descriptor request", () => |
| 312 | Effect.gen(function* () { |
| 313 | const harness = yield* makeHarness({ |
| 314 | responses: [ |
| 315 | Response.json({ |
| 316 | ...DESCRIPTOR, |
| 317 | orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, |
| 318 | }), |
| 319 | websocketTicket("cold-ticket"), |
| 320 | ], |
| 321 | }); |
| 322 | |
| 323 | const [prepared] = yield* prepareDirectBearer(harness, 1); |
| 324 | |
| 325 | expect(prepared).toMatchObject({ |
| 326 | _tag: "Success", |
| 327 | success: { socketUrl: expect.stringContaining("wsTicket=cold-ticket") }, |
| 328 | }); |
| 329 | expect(harness.fetch.calls.map(([url]) => new URL(String(url)).pathname)).toEqual([ |
| 330 | "/.well-known/t3/environment", |
| 331 | "/api/auth/websocket-ticket/rpc", |
| 332 | ]); |
| 333 | }), |
| 334 | ); |
| 335 | |
| 336 | it.effect("renews an expired direct DPoP token with the host and keeps the renewal", () => |
| 337 | Effect.gen(function* () { |
| 338 | const renewal = (init: RequestInit) => { |
| 339 | const fields = new URLSearchParams( |
| 340 | init.body instanceof Uint8Array ? new TextDecoder().decode(init.body) : String(init.body), |
| 341 | ); |
| 342 | expect(fields.get("subject_token")).toBe("expired-direct-token"); |
| 343 | expect(fields.get("subject_token_type")).toBe( |
| 344 | "urn:ietf:params:oauth:token-type:access_token", |
| 345 | ); |
| 346 | return accessToken("renewed-direct-token"); |
| 347 | }; |
| 348 | const harness = yield* makeHarness({ |
| 349 | responses: [renewal, websocketTicket("direct-ticket")], |
| 350 | descriptor: DESCRIPTOR, |
| 351 | credentials: [ |
| 352 | [ |
| 353 | "direct-1", |
| 354 | new DpopConnectionCredential({ |
| 355 | accessToken: "expired-direct-token", |
| 356 | expiresAtEpochMs: 0, |
| 357 | }), |
| 358 | ], |
| 359 | ], |
| 360 | }); |
| 361 | |
| 362 | const [authorized, stored] = yield* Effect.gen(function* () { |
| 363 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 364 | const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore; |
| 365 | const authorized = yield* remote.authorizeDirectDpop({ |
| 366 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 367 | connectionId: "direct-1", |
| 368 | httpBaseUrl: ENDPOINT.httpBaseUrl, |
| 369 | wsBaseUrl: ENDPOINT.wsBaseUrl, |
| 370 | }); |
| 371 | return [authorized, yield* credentials.get("direct-1")] as const; |
| 372 | }).pipe(Effect.provide(harness.layer)); |
| 373 | |
| 374 | expect(authorized.socketUrl).toContain("wsTicket=direct-ticket"); |
| 375 | expect(authorized.httpAuthorization).toMatchObject({ |
| 376 | _tag: "Dpop", |
| 377 | accessToken: "renewed-direct-token", |
| 378 | directConnection: { connectionId: "direct-1", httpBaseUrl: ENDPOINT.httpBaseUrl }, |
| 379 | }); |
| 380 | expect(Option.getOrThrow(stored)).toMatchObject({ |
| 381 | _tag: "DpopConnectionCredential", |
| 382 | accessToken: "renewed-direct-token", |
| 383 | }); |
| 384 | expect((yield* Ref.get(harness.proofInputs)).map((proof) => proof.url)).toEqual([ |
| 385 | `${ENDPOINT.httpBaseUrl}/oauth/token`, |
| 386 | `${ENDPOINT.httpBaseUrl}/api/auth/websocket-ticket/rpc`, |
| 387 | `${ENDPOINT.httpBaseUrl}/ws`, |
| 388 | ]); |
| 389 | }), |
| 390 | ); |
| 391 | |
| 392 | it.effect("renews another direct host while the first host is unresponsive", () => |
| 393 | Effect.gen(function* () { |
| 394 | const started = Promise.withResolvers<void>(); |
| 395 | const release = Promise.withResolvers<Response>(); |
| 396 | const first = { connectionId: "direct-1", httpBaseUrl: ENDPOINT.httpBaseUrl }; |
| 397 | const second = { connectionId: "direct-2", httpBaseUrl: "https://other.example.test" }; |
| 398 | const harness = yield* makeHarness({ |
| 399 | responses: [ |
| 400 | () => { |
| 401 | started.resolve(); |
| 402 | return release.promise; |
| 403 | }, |
| 404 | () => accessToken("renewed-second-token"), |
| 405 | ], |
| 406 | credentials: [first, second].map(({ connectionId }) => [ |
| 407 | connectionId, |
| 408 | new DpopConnectionCredential({ accessToken: connectionId, expiresAtEpochMs: 0 }), |
| 409 | ]), |
| 410 | }); |
| 411 | |
| 412 | yield* Effect.gen(function* () { |
| 413 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 414 | const pending = yield* remote.authorizeDirectDpopHttp(first).pipe(Effect.forkScoped); |
| 415 | yield* Effect.promise(() => started.promise); |
| 416 | const healthy = yield* remote |
| 417 | .authorizeDirectDpopHttp(second) |
| 418 | .pipe(Effect.timeoutOption("1 second"), Effect.forkScoped); |
| 419 | yield* TestClock.adjust("1 second"); |
| 420 | expect(yield* Fiber.join(healthy)).toMatchObject({ |
| 421 | _tag: "Some", |
| 422 | value: { accessToken: "renewed-second-token" }, |
| 423 | }); |
| 424 | release.resolve(accessToken("renewed-first-token")); |
| 425 | expect((yield* Fiber.join(pending)).accessToken).toBe("renewed-first-token"); |
| 426 | }).pipe(Effect.scoped, Effect.provide(Layer.merge(harness.layer, TestClock.layer()))); |
| 427 | }), |
| 428 | ); |
| 429 | |
| 430 | it.effect("reuses a matching descriptor a check just read, once, while fresh", () => |
| 431 | Effect.gen(function* () { |
| 432 | const descriptor = { |
| 433 | ...DESCRIPTOR, |
| 434 | orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, |
| 435 | } as ExecutionEnvironmentDescriptor; |
| 436 | const harness = yield* makeHarness({ |
| 437 | responses: [ |
| 438 | websocketTicket("reused"), |
| 439 | ...Array.from({ length: 4 }, () => [ |
| 440 | Response.json(descriptor), |
| 441 | websocketTicket("fresh"), |
| 442 | ]).flat(), |
| 443 | websocketTicket("reused over plain HTTP"), |
| 444 | Response.json(descriptor), |
| 445 | websocketTicket("fresh"), |
| 446 | ], |
| 447 | }); |
| 448 | |
| 449 | yield* Effect.gen(function* () { |
| 450 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 451 | const authorizeAt = (httpBaseUrl: string) => |
| 452 | remote.authorizeBearer({ |
| 453 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 454 | httpBaseUrl, |
| 455 | wsBaseUrl: httpBaseUrl.replace(/^http/, "ws"), |
| 456 | bearerToken: "bearer-token", |
| 457 | connectionMethod: "direct", |
| 458 | }); |
| 459 | const authorize = authorizeAt(ENDPOINT.httpBaseUrl); |
| 460 | const remember = (value: Option.Option<ExecutionEnvironmentDescriptor>) => |
| 461 | remote.rememberCheckedDescriptor(ENDPOINT.httpBaseUrl, value, true); |
| 462 | |
| 463 | yield* remember(Option.some(descriptor)); |
| 464 | yield* authorize; |
| 465 | // Used once. |
| 466 | yield* authorize; |
| 467 | // Stale. |
| 468 | yield* remember(Option.some(descriptor)); |
| 469 | yield* TestClock.adjust("6 seconds"); |
| 470 | yield* authorize; |
| 471 | // A mismatch reads again, so a host back on the right environment is not blocked. |
| 472 | yield* remember(Option.some({ ...descriptor, environmentId: "other" as never })); |
| 473 | yield* authorize; |
| 474 | // A failed check drops an older match. |
| 475 | yield* remember(Option.some(descriptor)); |
| 476 | yield* remember(Option.none()); |
| 477 | yield* authorize; |
| 478 | // Plain HTTP is no reason to read again where the address keeps its host. |
| 479 | yield* remote.rememberCheckedDescriptor( |
| 480 | "http://127.0.0.1:3773", |
| 481 | Option.some(descriptor), |
| 482 | true, |
| 483 | ); |
| 484 | yield* authorizeAt("http://127.0.0.1:3773"); |
| 485 | // After a network change, a plain LAN address can belong to another machine. |
| 486 | yield* remote.rememberCheckedDescriptor( |
| 487 | "http://192.168.1.2:3773", |
| 488 | Option.some(descriptor), |
| 489 | false, |
| 490 | ); |
| 491 | yield* authorizeAt("http://192.168.1.2:3773"); |
| 492 | }).pipe(Effect.provide(harness.layer)); |
| 493 | |
| 494 | expect(harness.fetch.calls.map(([url]) => new URL(String(url)).pathname)).toEqual([ |
| 495 | "/api/auth/websocket-ticket/rpc", |
| 496 | ...Array.from({ length: 4 }, () => [ |
| 497 | "/.well-known/t3/environment", |
| 498 | "/api/auth/websocket-ticket/rpc", |
| 499 | ]).flat(), |
| 500 | "/api/auth/websocket-ticket/rpc", |
| 501 | "/.well-known/t3/environment", |
| 502 | "/api/auth/websocket-ticket/rpc", |
| 503 | ]); |
| 504 | }), |
| 505 | ); |
| 506 | |
| 507 | it.effect("blocks a warm direct bearer prepare when the environment changes identity", () => |
| 508 | Effect.gen(function* () { |
| 509 | const harness = yield* makeHarness({ |
| 510 | responses: [ |
| 511 | Response.json({ |
| 512 | ...DESCRIPTOR, |
| 513 | orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, |
| 514 | }), |
| 515 | websocketTicket("first-ticket"), |
| 516 | Response.json({ |
| 517 | ...DESCRIPTOR, |
| 518 | environmentId: "another-environment", |
| 519 | orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, |
| 520 | }), |
| 521 | ], |
| 522 | }); |
| 523 | |
| 524 | const [first, second] = yield* prepareDirectBearer(harness, 2); |
| 525 | |
| 526 | expect(first?._tag).toBe("Success"); |
| 527 | expect(second).toMatchObject({ |
| 528 | _tag: "Failure", |
| 529 | failure: { _tag: "ConnectionBlockedError", reason: "configuration" }, |
| 530 | }); |
| 531 | expect( |
| 532 | harness.fetch.calls.filter(([url]) => |
| 533 | String(url).endsWith("/api/auth/websocket-ticket/rpc"), |
| 534 | ), |
| 535 | ).toHaveLength(1); |
| 536 | }), |
| 537 | ); |
| 538 | it.effect("validates a fresh bearer descriptor while issuing fresh websocket tickets", () => |
| 539 | Effect.gen(function* () { |
| 540 | const harness = yield* makeHarness({ |
| 541 | responses: [ |
| 542 | Response.json(DESCRIPTOR), |
| 543 | websocketTicket("first-ticket"), |
| 544 | Response.json(DESCRIPTOR), |
| 545 | websocketTicket("second-ticket"), |
| 546 | ], |
| 547 | }); |
| 548 | |
| 549 | const [first, second] = yield* Effect.gen(function* () { |
| 550 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 551 | const authorize = () => |
| 552 | remote.authorizeBearer({ |
| 553 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 554 | httpBaseUrl: ENDPOINT.httpBaseUrl, |
| 555 | wsBaseUrl: ENDPOINT.wsBaseUrl, |
| 556 | bearerToken: "bearer-token", |
| 557 | connectionMethod: "direct", |
| 558 | }); |
| 559 | return [yield* authorize(), yield* authorize()] as const; |
| 560 | }).pipe(Effect.provide(harness.layer)); |
| 561 | |
| 562 | expect(first.socketUrl).toContain("wsTicket=first-ticket"); |
| 563 | expect(second.socketUrl).toContain("wsTicket=second-ticket"); |
| 564 | expect( |
| 565 | harness.fetch.calls.filter(([url]) => String(url).endsWith("/.well-known/t3/environment")), |
| 566 | ).toHaveLength(2); |
| 567 | expect( |
| 568 | harness.fetch.calls.filter(([url]) => |
| 569 | String(url).endsWith("/api/auth/websocket-ticket/rpc"), |
| 570 | ), |
| 571 | ).toHaveLength(2); |
| 572 | }), |
| 573 | ); |
| 574 | |
| 575 | it.effect("gives up on a silent loopback or LAN address sooner than on a remote one", () => |
| 576 | Effect.gen(function* () { |
| 577 | const silent = () => new Promise<Response>(() => {}); |
| 578 | const harness = yield* makeHarness({ responses: [silent, silent, silent] }); |
| 579 | |
| 580 | yield* Effect.gen(function* () { |
| 581 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 582 | const authorizeAt = (httpBaseUrl: string, connectionMethod: "direct" | "ssh" = "direct") => |
| 583 | remote |
| 584 | .authorizeBearer({ |
| 585 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 586 | httpBaseUrl, |
| 587 | wsBaseUrl: httpBaseUrl.replace(/^http/, "ws"), |
| 588 | bearerToken: "bearer-token", |
| 589 | connectionMethod, |
| 590 | }) |
| 591 | .pipe(Effect.flip, Effect.forkChild); |
| 592 | const lan = yield* authorizeAt("http://192.168.1.2:3773"); |
| 593 | const tailnet = yield* authorizeAt("http://100.101.102.103:3773"); |
| 594 | // An SSH forward listens on loopback but reaches a remote host. |
| 595 | const forwarded = yield* authorizeAt("http://127.0.0.1:4010", "ssh"); |
| 596 | |
| 597 | yield* TestClock.adjust("3 seconds"); |
| 598 | expect(lan.pollUnsafe()).toBeDefined(); |
| 599 | expect(tailnet.pollUnsafe()).toBeUndefined(); |
| 600 | expect(forwarded.pollUnsafe()).toBeUndefined(); |
| 601 | expect(yield* Fiber.join(lan)).toMatchObject({ |
| 602 | _tag: "ConnectionTransientError", |
| 603 | reason: "timeout", |
| 604 | }); |
| 605 | |
| 606 | yield* TestClock.adjust("7 seconds"); |
| 607 | expect(tailnet.pollUnsafe()).toBeDefined(); |
| 608 | expect(forwarded.pollUnsafe()).toBeDefined(); |
| 609 | }).pipe(Effect.provide(harness.layer)); |
| 610 | }), |
| 611 | ); |
| 612 | |
| 613 | it.effect("reuses a same-account persisted environment token without contacting the relay", () => |
| 614 | Effect.gen(function* () { |
| 615 | const cached = new TokenStore.RemoteDpopAccessToken({ |
| 616 | environmentId: ENVIRONMENT_ID, |
| 617 | accountId: "account-1", |
| 618 | label: DESCRIPTOR.label, |
| 619 | endpoint: ENDPOINT, |
| 620 | accessToken: "cached-access-token", |
| 621 | expiresAtEpochMs: Number.MAX_SAFE_INTEGER, |
| 622 | dpopThumbprint: "thumbprint-1", |
| 623 | }); |
| 624 | const harness = yield* makeHarness({ |
| 625 | initialToken: cached, |
| 626 | descriptor: DESCRIPTOR, |
| 627 | responses: [websocketTicket("cached-ticket")], |
| 628 | }); |
| 629 | |
| 630 | const authorized = yield* Effect.gen(function* () { |
| 631 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 632 | return yield* remote.authorizeDpop({ |
| 633 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 634 | }); |
| 635 | }).pipe(Effect.provide(harness.layer)); |
| 636 | |
| 637 | expect(authorized.socketUrl).toContain("wsTicket=cached-ticket"); |
| 638 | expect(authorized.socketUrl).toContain("connectionMethod=relay"); |
| 639 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0); |
| 640 | // The descriptor is read beside the ticket, so the connect needs no later read. |
| 641 | expect(authorized.descriptor).toMatchObject({ environmentId: ENVIRONMENT_ID }); |
| 642 | expect(harness.fetch.calls.map(([url]) => String(url)).toSorted()).toEqual([ |
| 643 | "https://environment.example.test/.well-known/t3/environment", |
| 644 | "https://environment.example.test/api/auth/websocket-ticket/rpc", |
| 645 | ]); |
| 646 | }), |
| 647 | ); |
| 648 | |
| 649 | it.effect("uses the T3 Connect token on a learned direct address without the relay", () => |
| 650 | Effect.gen(function* () { |
| 651 | const cached = new TokenStore.RemoteDpopAccessToken({ |
| 652 | environmentId: ENVIRONMENT_ID, |
| 653 | accountId: "account-1", |
| 654 | label: DESCRIPTOR.label, |
| 655 | endpoint: ENDPOINT, |
| 656 | accessToken: "cached-access-token", |
| 657 | expiresAtEpochMs: Number.MAX_SAFE_INTEGER, |
| 658 | dpopThumbprint: "thumbprint-1", |
| 659 | }); |
| 660 | const harness = yield* makeHarness({ |
| 661 | initialToken: cached, |
| 662 | responses: [Response.json(DESCRIPTOR), websocketTicket("lan-ticket")], |
| 663 | }); |
| 664 | |
| 665 | const authorized = yield* Effect.gen(function* () { |
| 666 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 667 | return yield* remote.authorizeDpop({ |
| 668 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 669 | directEndpoint: { |
| 670 | httpBaseUrl: "http://192.168.1.10:3773/", |
| 671 | wsBaseUrl: "ws://192.168.1.10:3773/", |
| 672 | }, |
| 673 | }); |
| 674 | }).pipe(Effect.provide(harness.layer)); |
| 675 | |
| 676 | expect(authorized.httpBaseUrl).toBe("http://192.168.1.10:3773/"); |
| 677 | expect(authorized.socketUrl).toMatch(/^ws:\/\/192\.168\.1\.10:3773\/ws\?/); |
| 678 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0); |
| 679 | expect(harness.fetch.calls.map(([url]) => String(url))).toEqual([ |
| 680 | "http://192.168.1.10:3773/.well-known/t3/environment", |
| 681 | "http://192.168.1.10:3773/api/auth/websocket-ticket/rpc", |
| 682 | ]); |
| 683 | }), |
| 684 | ); |
| 685 | |
| 686 | it.effect("sends no token to a direct address that answers as another machine", () => |
| 687 | Effect.gen(function* () { |
| 688 | const harness = yield* makeHarness({ |
| 689 | initialToken: persistedToken({ accessToken: "cached-access-token" }), |
| 690 | responses: [ |
| 691 | Response.json({ ...DESCRIPTOR, environmentId: EnvironmentId.make("someone-else") }), |
| 692 | ], |
| 693 | }); |
| 694 | |
| 695 | const error = yield* Effect.gen(function* () { |
| 696 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 697 | return yield* remote |
| 698 | .authorizeDpop({ |
| 699 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 700 | directEndpoint: { |
| 701 | httpBaseUrl: "http://192.168.1.10:3773/", |
| 702 | wsBaseUrl: "ws://192.168.1.10:3773/", |
| 703 | }, |
| 704 | }) |
| 705 | .pipe(Effect.flip); |
| 706 | }).pipe(Effect.provide(harness.layer)); |
| 707 | |
| 708 | expect(error).toMatchObject({ _tag: "ConnectionBlockedError", reason: "configuration" }); |
| 709 | expect(harness.fetch.calls.map(([url]) => String(url))).toEqual([ |
| 710 | "http://192.168.1.10:3773/.well-known/t3/environment", |
| 711 | ]); |
| 712 | expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)?.accessToken).toBe( |
| 713 | "cached-access-token", |
| 714 | ); |
| 715 | }), |
| 716 | ); |
| 717 | |
| 718 | it.effect("refreshes and persists an expired environment token", () => |
| 719 | Effect.gen(function* () { |
| 720 | const expired = new TokenStore.RemoteDpopAccessToken({ |
| 721 | environmentId: ENVIRONMENT_ID, |
| 722 | accountId: "account-1", |
| 723 | label: DESCRIPTOR.label, |
| 724 | endpoint: ENDPOINT, |
| 725 | accessToken: "expired-access-token", |
| 726 | expiresAtEpochMs: 0, |
| 727 | dpopThumbprint: "thumbprint-1", |
| 728 | }); |
| 729 | const harness = yield* makeHarness({ |
| 730 | initialToken: expired, |
| 731 | responses: [ |
| 732 | Response.json(DESCRIPTOR), |
| 733 | accessToken("fresh-access-token"), |
| 734 | websocketTicket("fresh-ticket"), |
| 735 | ], |
| 736 | }); |
| 737 | |
| 738 | const authorized = yield* Effect.gen(function* () { |
| 739 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 740 | return yield* remote.authorizeDpop({ |
| 741 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 742 | }); |
| 743 | }).pipe(Effect.provide(harness.layer)); |
| 744 | |
| 745 | expect(authorized.socketUrl).toContain("wsTicket=fresh-ticket"); |
| 746 | // The mint already read the descriptor. |
| 747 | expect(authorized.descriptor).toMatchObject({ environmentId: ENVIRONMENT_ID }); |
| 748 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 749 | expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual( |
| 750 | expect.objectContaining({ |
| 751 | accessToken: "fresh-access-token", |
| 752 | dpopThumbprint: "thumbprint-1", |
| 753 | }), |
| 754 | ); |
| 755 | expect(harness.fetch.calls).toHaveLength(3); |
| 756 | }), |
| 757 | ); |
| 758 | |
| 759 | it.effect.each([ |
| 760 | { name: "read-only", grantScopes: ["orchestration:read"] }, |
| 761 | { name: "default", grantScopes: AuthStandardClientScopes }, |
| 762 | ] as const)( |
| 763 | "inherits $name pairing grant scopes for websocket authorization and HTTP renewal", |
| 764 | ({ grantScopes }) => |
| 765 | Effect.gen(function* () { |
| 766 | const grantedScope = grantScopes.join(" "); |
| 767 | let exchangeCount = 0; |
| 768 | const tokenFields = (init: RequestInit) => |
| 769 | new URLSearchParams( |
| 770 | init.body instanceof Uint8Array |
| 771 | ? new TextDecoder().decode(init.body) |
| 772 | : String(init.body), |
| 773 | ); |
| 774 | const exchangeGrant = (init: RequestInit) => { |
| 775 | const fields = tokenFields(init); |
| 776 | expect(fields.get("scope")).toBeNull(); |
| 777 | const scope = fields.get("scope") ?? grantedScope; |
| 778 | const scopes = scope.split(" "); |
| 779 | if (scopes.some((requested) => !grantScopes.some((grant) => grant === requested))) { |
| 780 | return authInvalid(); |
| 781 | } |
| 782 | return accessToken(`access-token:${++exchangeCount}:${scopes.join(",")}`, scope); |
| 783 | }; |
| 784 | const harness = yield* makeHarness({ |
| 785 | responses: [ |
| 786 | Response.json(DESCRIPTOR), |
| 787 | exchangeGrant, |
| 788 | websocketTicket("granted-ticket"), |
| 789 | Response.json(DESCRIPTOR), |
| 790 | exchangeGrant, |
| 791 | ], |
| 792 | }); |
| 793 | |
| 794 | const [authorized, refreshed] = yield* Effect.gen(function* () { |
| 795 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 796 | const first = yield* remote.authorizeDpop({ |
| 797 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 798 | }); |
| 799 | yield* TestClock.adjust("1 hour"); |
| 800 | const refreshed = yield* remote.authorizeDpopHttp({ |
| 801 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 802 | }); |
| 803 | return [first, refreshed] as const; |
| 804 | }).pipe(Effect.provide(Layer.merge(harness.layer, TestClock.layer()))); |
| 805 | |
| 806 | expect(authorized.socketUrl).toContain("wsTicket=granted-ticket"); |
| 807 | expect(authorized.httpAuthorization).toMatchObject({ |
| 808 | _tag: "Dpop", |
| 809 | accessToken: `access-token:1:${grantScopes.join(",")}`, |
| 810 | }); |
| 811 | expect(refreshed.httpAuthorization).toMatchObject({ |
| 812 | _tag: "Dpop", |
| 813 | accessToken: `access-token:2:${grantScopes.join(",")}`, |
| 814 | }); |
| 815 | expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toMatchObject({ |
| 816 | accessToken: `access-token:2:${grantScopes.join(",")}`, |
| 817 | dpopThumbprint: "thumbprint-1", |
| 818 | }); |
| 819 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(2); |
| 820 | const exchanges = harness.fetch.calls.filter(([url]) => |
| 821 | String(url).endsWith("/oauth/token"), |
| 822 | ); |
| 823 | expect(exchanges).toHaveLength(2); |
| 824 | for (const [, init] of exchanges) { |
| 825 | expect(Object.fromEntries(tokenFields(init))).toMatchObject({ |
| 826 | subject_token: BOOTSTRAP.credential, |
| 827 | client_label: "T3 Code Test", |
| 828 | client_device_type: "mobile", |
| 829 | client_os: "test", |
| 830 | }); |
| 831 | } |
| 832 | }), |
| 833 | ); |
| 834 | |
| 835 | it.effect("renews a live socket's token in the minute before each expiry", () => |
| 836 | Effect.gen(function* () { |
| 837 | const puts = yield* Queue.unbounded<void>(); |
| 838 | const relayBlips = yield* Ref.make(1); |
| 839 | const harness = yield* makeHarness({ |
| 840 | beforeBootstrap: Ref.getAndUpdate(relayBlips, (count) => count - 1).pipe( |
| 841 | Effect.flatMap((count) => |
| 842 | count > 0 |
| 843 | ? Effect.fail( |
| 844 | new ManagedRelay.ManagedRelayRequestTimeoutError({ |
| 845 | activity: "Relay environment connection", |
| 846 | timeoutMs: 30_000, |
| 847 | traceId: null, |
| 848 | }), |
| 849 | ) |
| 850 | : Effect.void, |
| 851 | ), |
| 852 | ), |
| 853 | initialToken: persistedToken({ expiresAtEpochMs: 3_600_000 }), |
| 854 | responses: [ |
| 855 | Response.json(DESCRIPTOR), |
| 856 | accessToken("renewed-1"), |
| 857 | Response.json(DESCRIPTOR), |
| 858 | accessToken("renewed-2"), |
| 859 | ], |
| 860 | beforePut: Queue.offer(puts, undefined).pipe(Effect.asVoid), |
| 861 | }); |
| 862 | |
| 863 | yield* Effect.gen(function* () { |
| 864 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 865 | yield* remote |
| 866 | .renewDpopBeforeExpiry({ |
| 867 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 868 | expiresAtEpochMs: 3_600_000, |
| 869 | }) |
| 870 | .pipe(Effect.forkScoped); |
| 871 | yield* TestClock.adjust(3_540_000 - 1); |
| 872 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0); |
| 873 | // The first try hits a relay blip, and the retry 5 s later succeeds. |
| 874 | yield* TestClock.adjust(1); |
| 875 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 876 | yield* TestClock.adjust(5_000); |
| 877 | yield* Queue.take(puts); |
| 878 | // Renewed at 0:59:05, so the next renewal is at 1:58:05. |
| 879 | yield* TestClock.adjust(7_085_000 - 3_545_000 - 1); |
| 880 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(2); |
| 881 | yield* TestClock.adjust(1); |
| 882 | yield* Queue.take(puts); |
| 883 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(3); |
| 884 | }).pipe(Effect.scoped, Effect.provide(Layer.merge(harness.layer, TestClock.layer()))); |
| 885 | }), |
| 886 | ); |
| 887 | |
| 888 | it.effect("keeps renewing a direct socket after a failed renewal past token expiry", () => |
| 889 | Effect.gen(function* () { |
| 890 | let markLoopRenewal = () => {}; |
| 891 | const loopRenewed = new Promise<void>((resolve) => (markLoopRenewal = resolve)); |
| 892 | const connection = { connectionId: "direct-1", httpBaseUrl: ENDPOINT.httpBaseUrl }; |
| 893 | const harness = yield* makeHarness({ |
| 894 | responses: [ |
| 895 | () => Promise.reject(new TypeError("network down")), |
| 896 | () => { |
| 897 | markLoopRenewal(); |
| 898 | return accessToken("renewed-direct-token"); |
| 899 | }, |
| 900 | ], |
| 901 | credentials: [ |
| 902 | [ |
| 903 | "direct-1", |
| 904 | new DpopConnectionCredential({ accessToken: "direct-token", expiresAtEpochMs: 1_000 }), |
| 905 | ], |
| 906 | ], |
| 907 | }); |
| 908 | |
| 909 | const renewed = yield* Effect.gen(function* () { |
| 910 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 911 | yield* remote |
| 912 | .renewDpopBeforeExpiry({ |
| 913 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 914 | expiresAtEpochMs: 1_000, |
| 915 | directConnection: connection, |
| 916 | }) |
| 917 | .pipe(Effect.forkScoped); |
| 918 | // The first try, at 5 s, is already past the token's expiry and fails. |
| 919 | yield* TestClock.adjust(5_000); |
| 920 | // The host keeps a direct socket for its session's window, so the loop tries again. |
| 921 | yield* TestClock.adjust(60_000); |
| 922 | yield* Effect.promise(() => loopRenewed); |
| 923 | // Waits behind the loop's renewal and reads what it stored, with no request of its own. |
| 924 | return yield* remote.authorizeDirectDpopHttp(connection); |
| 925 | }).pipe(Effect.scoped, Effect.provide(Layer.merge(harness.layer, TestClock.layer()))); |
| 926 | |
| 927 | expect(renewed.accessToken).toBe("renewed-direct-token"); |
| 928 | }), |
| 929 | ); |
| 930 | |
| 931 | it.effect("evicts an auth-invalid cached token and obtains a fresh bootstrap", () => |
| 932 | Effect.gen(function* () { |
| 933 | const cached = new TokenStore.RemoteDpopAccessToken({ |
| 934 | environmentId: ENVIRONMENT_ID, |
| 935 | accountId: "account-1", |
| 936 | label: DESCRIPTOR.label, |
| 937 | endpoint: ENDPOINT, |
| 938 | accessToken: "invalid-access-token", |
| 939 | expiresAtEpochMs: Number.MAX_SAFE_INTEGER, |
| 940 | dpopThumbprint: "thumbprint-1", |
| 941 | }); |
| 942 | const harness = yield* makeHarness({ |
| 943 | initialToken: cached, |
| 944 | descriptor: DESCRIPTOR, |
| 945 | responses: [ |
| 946 | authInvalid(), |
| 947 | accessToken("replacement-access-token"), |
| 948 | websocketTicket("replacement-ticket"), |
| 949 | ], |
| 950 | }); |
| 951 | |
| 952 | const authorized = yield* Effect.gen(function* () { |
| 953 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 954 | return yield* remote.authorizeDpop({ |
| 955 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 956 | }); |
| 957 | }).pipe(Effect.provide(harness.layer)); |
| 958 | |
| 959 | expect(authorized.socketUrl).toContain("wsTicket=replacement-ticket"); |
| 960 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 961 | expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual( |
| 962 | expect.objectContaining({ |
| 963 | accessToken: "replacement-access-token", |
| 964 | }), |
| 965 | ); |
| 966 | expect(requestsTo(harness, "/api/auth/websocket-ticket/rpc")).toBe(2); |
| 967 | expect(requestsTo(harness, "/oauth/token")).toBe(1); |
| 968 | }), |
| 969 | ); |
| 970 | |
| 971 | it.effect("refreshes a cached endpoint after its first transient failure", () => |
| 972 | Effect.gen(function* () { |
| 973 | const cached = new TokenStore.RemoteDpopAccessToken({ |
| 974 | environmentId: ENVIRONMENT_ID, |
| 975 | accountId: "account-1", |
| 976 | label: DESCRIPTOR.label, |
| 977 | endpoint: ENDPOINT, |
| 978 | accessToken: "cached-access-token", |
| 979 | expiresAtEpochMs: Number.MAX_SAFE_INTEGER, |
| 980 | dpopThumbprint: "thumbprint-1", |
| 981 | }); |
| 982 | const harness = yield* makeHarness({ |
| 983 | initialToken: cached, |
| 984 | descriptor: DESCRIPTOR, |
| 985 | responses: [ |
| 986 | new Response("endpoint unavailable", { status: 503 }), |
| 987 | accessToken("replacement-access-token"), |
| 988 | websocketTicket("replacement-ticket"), |
| 989 | ], |
| 990 | }); |
| 991 | |
| 992 | const authorized = yield* Effect.gen(function* () { |
| 993 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 994 | return yield* remote.authorizeDpop({ |
| 995 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 996 | }); |
| 997 | }).pipe(Effect.provide(harness.layer)); |
| 998 | |
| 999 | expect(authorized.socketUrl).toContain("wsTicket=replacement-ticket"); |
| 1000 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 1001 | expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual( |
| 1002 | expect.objectContaining({ |
| 1003 | accessToken: "replacement-access-token", |
| 1004 | }), |
| 1005 | ); |
| 1006 | expect(requestsTo(harness, "/api/auth/websocket-ticket/rpc")).toBe(2); |
| 1007 | expect(requestsTo(harness, "/oauth/token")).toBe(1); |
| 1008 | }), |
| 1009 | ); |
| 1010 | |
| 1011 | it.effect("removes a newly refreshed token when websocket ticket authorization fails", () => |
| 1012 | Effect.gen(function* () { |
| 1013 | const harness = yield* makeHarness({ |
| 1014 | responses: [ |
| 1015 | Response.json(DESCRIPTOR), |
| 1016 | accessToken("unusable-access-token"), |
| 1017 | new Response("endpoint unavailable", { status: 503 }), |
| 1018 | ], |
| 1019 | }); |
| 1020 | |
| 1021 | yield* Effect.gen(function* () { |
| 1022 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1023 | return yield* remote.authorizeDpop({ |
| 1024 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 1025 | }); |
| 1026 | }).pipe(Effect.provide(harness.layer), Effect.flip); |
| 1027 | |
| 1028 | expect((yield* Ref.get(harness.tokens)).has(ENVIRONMENT_ID)).toBe(false); |
| 1029 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 1030 | expect(harness.fetch.calls).toHaveLength(3); |
| 1031 | }), |
| 1032 | ); |
| 1033 | |
| 1034 | it.effect("does not evict a replacement token when a late request rejects the old one", () => |
| 1035 | Effect.gen(function* () { |
| 1036 | const harness = yield* makeHarness({ |
| 1037 | initialToken: persistedToken(), |
| 1038 | responses: [Response.json(DESCRIPTOR), accessToken("replacement-token")], |
| 1039 | }); |
| 1040 | yield* Effect.gen(function* () { |
| 1041 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1042 | const initial = yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }); |
| 1043 | const retry = { |
| 1044 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 1045 | rejectedAccessToken: initial.httpAuthorization.accessToken, |
| 1046 | }; |
| 1047 | const first = yield* remote.authorizeDpopHttp(retry); |
| 1048 | const late = yield* remote.authorizeDpopHttp(retry); |
| 1049 | expect(first.httpAuthorization.accessToken).toBe("replacement-token"); |
| 1050 | expect(late).toEqual(first); |
| 1051 | }).pipe(Effect.provide(harness.layer)); |
| 1052 | |
| 1053 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 1054 | expect(harness.fetch.calls).toHaveLength(2); |
| 1055 | expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)?.accessToken).toBe( |
| 1056 | "replacement-token", |
| 1057 | ); |
| 1058 | }), |
| 1059 | ); |
| 1060 | |
| 1061 | it.effect("shares one in-flight renewal between concurrent HTTP requests", () => |
| 1062 | Effect.gen(function* () { |
| 1063 | const started = yield* Deferred.make<void>(); |
| 1064 | const release = yield* Deferred.make<void>(); |
| 1065 | const harness = yield* makeHarness({ |
| 1066 | initialToken: persistedToken({ expiresAtEpochMs: 0 }), |
| 1067 | beforeBootstrap: Deferred.succeed(started, undefined).pipe( |
| 1068 | Effect.andThen(Deferred.await(release)), |
| 1069 | ), |
| 1070 | responses: [Response.json(DESCRIPTOR), accessToken("shared-token")], |
| 1071 | }); |
| 1072 | yield* Effect.gen(function* () { |
| 1073 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1074 | const requests = yield* Effect.all( |
| 1075 | Array.from({ length: 6 }, () => |
| 1076 | remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }), |
| 1077 | ), |
| 1078 | { concurrency: "unbounded" }, |
| 1079 | ).pipe(Effect.forkChild); |
| 1080 | yield* Queue.takeN(harness.tokenReads, 6); |
| 1081 | yield* Deferred.await(started); |
| 1082 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 1083 | yield* Deferred.succeed(release, undefined); |
| 1084 | const results = yield* Fiber.join(requests); |
| 1085 | expect(results.map((result) => result.httpAuthorization.accessToken)).toEqual( |
| 1086 | Array(6).fill("shared-token"), |
| 1087 | ); |
| 1088 | }).pipe(Effect.provide(harness.layer)); |
| 1089 | |
| 1090 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 1091 | expect(harness.fetch.calls).toHaveLength(2); |
| 1092 | }), |
| 1093 | ); |
| 1094 | |
| 1095 | it.effect( |
| 1096 | "shares a failed renewal and allows a later attempt instead of caching its failure", |
| 1097 | () => |
| 1098 | Effect.gen(function* () { |
| 1099 | const release = yield* Deferred.make<void, ManagedRelay.ManagedRelayClientError>(); |
| 1100 | const failure = new ManagedRelay.ManagedRelayRequestTimeoutError({ |
| 1101 | activity: "Relay environment connection", |
| 1102 | timeoutMs: ManagedRelay.MANAGED_RELAY_REQUEST_TIMEOUT_MS, |
| 1103 | traceId: null, |
| 1104 | }); |
| 1105 | const harness = yield* makeHarness({ |
| 1106 | responses: [], |
| 1107 | beforeBootstrap: Deferred.await(release), |
| 1108 | }); |
| 1109 | yield* Effect.gen(function* () { |
| 1110 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1111 | const requests = yield* Effect.all( |
| 1112 | Array.from({ length: 6 }, () => |
| 1113 | remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }).pipe(Effect.flip), |
| 1114 | ), |
| 1115 | { concurrency: "unbounded" }, |
| 1116 | ).pipe(Effect.forkChild); |
| 1117 | yield* Queue.takeN(harness.tokenReads, 6); |
| 1118 | yield* Deferred.fail(release, failure); |
| 1119 | const failures = yield* Fiber.join(requests); |
| 1120 | expect(failures).toEqual( |
| 1121 | Array(6).fill( |
| 1122 | expect.objectContaining({ |
| 1123 | _tag: "ConnectionTransientError", |
| 1124 | reason: "timeout", |
| 1125 | }), |
| 1126 | ), |
| 1127 | ); |
| 1128 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 1129 | yield* remote |
| 1130 | .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }) |
| 1131 | .pipe(Effect.flip); |
| 1132 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(2); |
| 1133 | }).pipe(Effect.provide(harness.layer)); |
| 1134 | expect(harness.fetch.calls).toHaveLength(0); |
| 1135 | }), |
| 1136 | ); |
| 1137 | |
| 1138 | it.effect("does not block another environment behind a pending renewal", () => |
| 1139 | Effect.gen(function* () { |
| 1140 | const started = yield* Deferred.make<void>(); |
| 1141 | const release = yield* Deferred.make<void>(); |
| 1142 | const otherEnvironmentId = EnvironmentId.make("environment-2"); |
| 1143 | const harness = yield* makeHarness({ |
| 1144 | initialToken: persistedToken({ |
| 1145 | environmentId: otherEnvironmentId, |
| 1146 | accessToken: "other-token", |
| 1147 | }), |
| 1148 | beforeBootstrap: Deferred.succeed(started, undefined).pipe( |
| 1149 | Effect.andThen(Deferred.await(release)), |
| 1150 | ), |
| 1151 | responses: [Response.json(DESCRIPTOR), accessToken("fresh-token")], |
| 1152 | }); |
| 1153 | yield* Effect.gen(function* () { |
| 1154 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1155 | const pending = yield* remote |
| 1156 | .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }) |
| 1157 | .pipe(Effect.forkChild); |
| 1158 | yield* Deferred.await(started); |
| 1159 | const other = yield* remote.authorizeDpopHttp({ |
| 1160 | expectedEnvironmentId: otherEnvironmentId, |
| 1161 | }); |
| 1162 | expect(other.httpAuthorization.accessToken).toBe("other-token"); |
| 1163 | yield* Deferred.succeed(release, undefined); |
| 1164 | yield* Fiber.join(pending); |
| 1165 | }).pipe(Effect.provide(harness.layer)); |
| 1166 | }), |
| 1167 | ); |
| 1168 | |
| 1169 | it.effect("retries instead of blocking while the cloud session has not loaded", () => |
| 1170 | Effect.gen(function* () { |
| 1171 | const harness = yield* makeHarness({ |
| 1172 | responses: [Response.json(DESCRIPTOR), accessToken("loaded-token")], |
| 1173 | }); |
| 1174 | yield* Ref.set(harness.session, Option.none()); |
| 1175 | yield* Effect.gen(function* () { |
| 1176 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1177 | const pending = yield* remote |
| 1178 | .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }) |
| 1179 | .pipe(Effect.flip); |
| 1180 | expect(pending).toMatchObject({ |
| 1181 | _tag: "ConnectionTransientError", |
| 1182 | reason: "session-pending", |
| 1183 | }); |
| 1184 | yield* Ref.set(harness.session, Option.some({ accountId: "account-1" })); |
| 1185 | const loaded = yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }); |
| 1186 | expect(loaded.httpAuthorization.accessToken).toBe("loaded-token"); |
| 1187 | }).pipe(Effect.provide(harness.layer)); |
| 1188 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 1189 | }), |
| 1190 | ); |
| 1191 | |
| 1192 | it.effect("does not return or persist credentials after logout during renewal", () => |
| 1193 | Effect.gen(function* () { |
| 1194 | const started = yield* Deferred.make<void>(); |
| 1195 | const release = yield* Deferred.make<void>(); |
| 1196 | const harness = yield* makeHarness({ |
| 1197 | beforeBootstrap: Deferred.succeed(started, undefined).pipe( |
| 1198 | Effect.andThen(Deferred.await(release)), |
| 1199 | ), |
| 1200 | responses: [], |
| 1201 | }); |
| 1202 | yield* Effect.gen(function* () { |
| 1203 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1204 | const pending = yield* remote |
| 1205 | .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }) |
| 1206 | .pipe(Effect.flip, Effect.forkChild); |
| 1207 | yield* Deferred.await(started); |
| 1208 | yield* Ref.set(harness.session, Option.none()); |
| 1209 | yield* Deferred.succeed(release, undefined); |
| 1210 | expect(yield* Fiber.join(pending)).toMatchObject({ |
| 1211 | _tag: "ConnectionBlockedError", |
| 1212 | reason: "authentication", |
| 1213 | }); |
| 1214 | }).pipe(Effect.provide(harness.layer)); |
| 1215 | expect((yield* Ref.get(harness.tokens)).size).toBe(0); |
| 1216 | expect(harness.fetch.calls).toHaveLength(0); |
| 1217 | }), |
| 1218 | ); |
| 1219 | |
| 1220 | it.effect("removes an obsolete credential if logout overlaps the persistent write", () => |
| 1221 | Effect.gen(function* () { |
| 1222 | const started = yield* Deferred.make<void>(); |
| 1223 | const release = yield* Deferred.make<void>(); |
| 1224 | const harness = yield* makeHarness({ |
| 1225 | beforePut: Deferred.succeed(started, undefined).pipe( |
| 1226 | Effect.andThen(Deferred.await(release)), |
| 1227 | ), |
| 1228 | responses: [Response.json(DESCRIPTOR), accessToken("obsolete-token")], |
| 1229 | }); |
| 1230 | yield* Effect.gen(function* () { |
| 1231 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1232 | const pending = yield* remote |
| 1233 | .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }) |
| 1234 | .pipe(Effect.flip, Effect.forkChild); |
| 1235 | yield* Deferred.await(started); |
| 1236 | yield* Ref.set(harness.session, Option.none()); |
| 1237 | yield* Deferred.succeed(release, undefined); |
| 1238 | expect(yield* Fiber.join(pending)).toMatchObject({ |
| 1239 | _tag: "ConnectionBlockedError", |
| 1240 | reason: "authentication", |
| 1241 | }); |
| 1242 | }).pipe(Effect.provide(harness.layer)); |
| 1243 | expect((yield* Ref.get(harness.tokens)).size).toBe(0); |
| 1244 | }), |
| 1245 | ); |
| 1246 | |
| 1247 | it.effect( |
| 1248 | "renews another account's persisted token after the authorization service restarts", |
| 1249 | () => |
| 1250 | Effect.gen(function* () { |
| 1251 | const harness = yield* makeHarness({ |
| 1252 | initialToken: persistedToken(), |
| 1253 | responses: [Response.json(DESCRIPTOR), accessToken("account-2-token")], |
| 1254 | }); |
| 1255 | const authorize = Effect.gen(function* () { |
| 1256 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1257 | return yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }); |
| 1258 | }).pipe(Effect.provide(harness.layer)); |
| 1259 | |
| 1260 | expect((yield* authorize).httpAuthorization.accessToken).toBe("cached-access-token"); |
| 1261 | yield* Ref.set(harness.session, Option.some({ accountId: "account-2" })); |
| 1262 | expect((yield* authorize).httpAuthorization.accessToken).toBe("account-2-token"); |
| 1263 | expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)?.accountId).toBe("account-2"); |
| 1264 | |
| 1265 | yield* Ref.set(harness.session, Option.some({ accountId: "account-2" })); |
| 1266 | expect((yield* authorize).httpAuthorization.accessToken).toBe("account-2-token"); |
| 1267 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 1268 | expect(harness.fetch.calls).toHaveLength(2); |
| 1269 | }), |
| 1270 | ); |
| 1271 | |
| 1272 | it.effect("renews a legacy unowned token once and reuses its account-bound replacement", () => |
| 1273 | Effect.gen(function* () { |
| 1274 | const legacy = new TokenStore.RemoteDpopAccessToken({ |
| 1275 | environmentId: ENVIRONMENT_ID, |
| 1276 | label: DESCRIPTOR.label, |
| 1277 | endpoint: ENDPOINT, |
| 1278 | accessToken: "legacy-access-token", |
| 1279 | expiresAtEpochMs: Number.MAX_SAFE_INTEGER, |
| 1280 | dpopThumbprint: "thumbprint-1", |
| 1281 | }); |
| 1282 | const harness = yield* makeHarness({ |
| 1283 | initialToken: legacy, |
| 1284 | responses: [Response.json(DESCRIPTOR), accessToken("account-bound-token")], |
| 1285 | }); |
| 1286 | const authorize = Effect.gen(function* () { |
| 1287 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1288 | return yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }); |
| 1289 | }).pipe(Effect.provide(harness.layer)); |
| 1290 | |
| 1291 | expect((yield* authorize).httpAuthorization.accessToken).toBe("account-bound-token"); |
| 1292 | expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)?.accountId).toBe("account-1"); |
| 1293 | expect((yield* authorize).httpAuthorization.accessToken).toBe("account-bound-token"); |
| 1294 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 1295 | expect(harness.fetch.calls).toHaveLength(2); |
| 1296 | }), |
| 1297 | ); |
| 1298 | |
| 1299 | it.effect("requires fresh credentials after signing back into the same account", () => |
| 1300 | Effect.gen(function* () { |
| 1301 | const harness = yield* makeHarness({ |
| 1302 | initialToken: persistedToken(), |
| 1303 | responses: [Response.json(DESCRIPTOR), accessToken("new-session-token")], |
| 1304 | }); |
| 1305 | yield* Effect.gen(function* () { |
| 1306 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1307 | yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }); |
| 1308 | yield* Ref.set(harness.session, Option.none()); |
| 1309 | yield* Ref.set(harness.session, Option.some({ accountId: "account-1" })); |
| 1310 | const signedIn = yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }); |
| 1311 | expect(signedIn.httpAuthorization.accessToken).toBe("new-session-token"); |
| 1312 | }).pipe(Effect.provide(harness.layer)); |
| 1313 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 1314 | }), |
| 1315 | ); |
| 1316 | |
| 1317 | it.effect("renews a cached credential bound to a different signing key", () => |
| 1318 | Effect.gen(function* () { |
| 1319 | const harness = yield* makeHarness({ |
| 1320 | initialToken: persistedToken(), |
| 1321 | responses: [Response.json(DESCRIPTOR), accessToken("new-key-token")], |
| 1322 | }); |
| 1323 | yield* Ref.set(harness.thumbprint, "thumbprint-2"); |
| 1324 | yield* Effect.gen(function* () { |
| 1325 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1326 | const authorized = yield* remote.authorizeDpopHttp({ |
| 1327 | expectedEnvironmentId: ENVIRONMENT_ID, |
| 1328 | }); |
| 1329 | expect(authorized.httpAuthorization.accessToken).toBe("new-key-token"); |
| 1330 | }).pipe(Effect.provide(harness.layer)); |
| 1331 | expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)?.dpopThumbprint).toBe( |
| 1332 | "thumbprint-2", |
| 1333 | ); |
| 1334 | }), |
| 1335 | ); |
| 1336 | |
| 1337 | it.effect("rejects a relay bootstrap for a different environment before contacting it", () => |
| 1338 | Effect.gen(function* () { |
| 1339 | const harness = yield* makeHarness({ |
| 1340 | responses: [], |
| 1341 | bootstrap: { ...BOOTSTRAP, environmentId: EnvironmentId.make("wrong-environment") }, |
| 1342 | }); |
| 1343 | const failure = yield* Effect.gen(function* () { |
| 1344 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1345 | return yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }); |
| 1346 | }).pipe(Effect.provide(harness.layer), Effect.flip); |
| 1347 | expect(failure).toMatchObject({ _tag: "ConnectionBlockedError", reason: "configuration" }); |
| 1348 | expect(harness.fetch.calls).toHaveLength(0); |
| 1349 | }), |
| 1350 | ); |
| 1351 | |
| 1352 | it.effect("keeps a shared renewal alive when one waiting request is interrupted", () => |
| 1353 | Effect.gen(function* () { |
| 1354 | const started = yield* Deferred.make<void>(); |
| 1355 | const release = yield* Deferred.make<void>(); |
| 1356 | const harness = yield* makeHarness({ |
| 1357 | beforeBootstrap: Deferred.succeed(started, undefined).pipe( |
| 1358 | Effect.andThen(Deferred.await(release)), |
| 1359 | ), |
| 1360 | responses: [Response.json(DESCRIPTOR), accessToken("fresh-token")], |
| 1361 | }); |
| 1362 | yield* Effect.gen(function* () { |
| 1363 | const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; |
| 1364 | const pending = yield* remote |
| 1365 | .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }) |
| 1366 | .pipe(Effect.forkChild); |
| 1367 | yield* Deferred.await(started); |
| 1368 | const other = yield* remote |
| 1369 | .authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }) |
| 1370 | .pipe(Effect.forkChild); |
| 1371 | yield* Queue.takeN(harness.tokenReads, 2); |
| 1372 | yield* Fiber.interrupt(pending); |
| 1373 | yield* Deferred.succeed(release, undefined); |
| 1374 | const authorized = yield* Fiber.join(other); |
| 1375 | expect(authorized.httpAuthorization.accessToken).toBe("fresh-token"); |
| 1376 | const cached = yield* remote.authorizeDpopHttp({ expectedEnvironmentId: ENVIRONMENT_ID }); |
| 1377 | expect(cached).toEqual(authorized); |
| 1378 | }).pipe(Effect.provide(harness.layer)); |
| 1379 | expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); |
| 1380 | }), |
| 1381 | ); |
| 1382 | }); |