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

http.test.ts

207 lines7.7 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as PlatformError from "effect/PlatformError";
6import * as Tracer from "effect/Tracer";
7import { HttpClient, HttpServerRequest } from "effect/unstable/http";
8​
9import { RelayClientTracer } from "@t3tools/shared/relayTracing";
10import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
11import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
12import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
13import * as CliTokenManager from "./CliTokenManager.ts";
14import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
15import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
16import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
17​
18const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
19 new ServerSecretStore.SecretStorePersistError({
20 resource: "cloud replay guard",
21 cause: PlatformError.systemError({
22 _tag: tag,
23 module: "FileSystem",
24 method: "open",
25 pathOrDescriptor: "cloud-replay-guard.bin",
26 }),
27 });
28​
29const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
30​
31function makeSecretStore(
32 create: ServerSecretStore.ServerSecretStore["Service"]["create"],
33): ServerSecretStore.ServerSecretStore["Service"] {
34 return {
35 get: unusedSecretStoreOperation,
36 set: unusedSecretStoreOperation,
37 create,
38 getOrCreateRandom: unusedSecretStoreOperation,
39 remove: unusedSecretStoreOperation,
40 };
42​
43it("preserves messages surfaced by cloud 500 responses", () => {
44 const cause = new Error("cloud operation failed");
45​
46 expect([
47 new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({ cause }).message,
48 new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({ cause }).message,
49 new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({}).message,
50 new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({ cause }).message,
51 new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({}).message,
52 new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({}).message,
53 new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({ cause }).message,
54 new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({ cause }).message,
55 ]).toEqual([
56 "Could not verify the linked cloud account.",
57 "Could not read the linked cloud account.",
58 "Cloud linked user is not installed for this environment.",
59 "Failed to sign cloud link JWT.",
60 "Cloud mint public key is not installed for this environment.",
61 "Cloud relay issuer is not installed for this environment.",
62 "Failed to sign cloud health JWT.",
63 "Failed to sign cloud mint JWT.",
64 ]);
65});
66​
67describe("consumeCloudReplayGuards", () => {
68 it.effect("reports already-created guards as replay conflicts", () =>
69 Effect.gen(function* () {
70 const consumed = yield* consumeCloudReplayGuards({
71 secrets: makeSecretStore(() => Effect.fail(storeFailure("AlreadyExists"))),
72 names: ["cloud-jti", "cloud-nonce"],
73 value: new Uint8Array(),
74 });
75​
76 expect(consumed).toBe(false);
77 }),
78 );
79​
80 it.effect("preserves replay-store availability failures", () =>
81 Effect.gen(function* () {
82 const failure = storeFailure("PermissionDenied");
83 const error = yield* Effect.flip(
84 consumeCloudReplayGuards({
85 secrets: makeSecretStore(() => Effect.fail(failure)),
86 names: ["cloud-jti", "cloud-nonce"],
87 value: new Uint8Array(),
88 }),
89 );
90​
91 expect(error).toBe(failure);
92 }),
93 );
94});
95​
96describe("relay request tracing", () => {
97 it.effect("does not accept an unauthenticated request trace parent", () =>
98 Effect.gen(function* () {
99 const spans: Array<Tracer.Span> = [];
100 const productTracer = Tracer.make({
101 span: (options) => {
102 const span = new Tracer.NativeSpan(options);
103 spans.push(span);
104 return span;
105 },
106 });
107 const request = HttpServerRequest.fromWeb(
108 new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
109 headers: {
110 traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
111 },
112 }),
113 );
114​
115 yield* traceRelayRequest(Effect.void.pipe(Effect.withSpan("relay.mint.handler"))).pipe(
116 Effect.provideService(HttpServerRequest.HttpServerRequest, request),
117 Effect.provideService(RelayClientTracer, Option.some(productTracer)),
118 );
119​
120 expect(spans).toHaveLength(1);
121 const span = spans[0]!;
122 expect(span.traceId).not.toBe("0123456789abcdef0123456789abcdef");
123 expect(Option.isNone(span.parent)).toBe(true);
124 }),
125 );
126​
127 it.effect("continues an authenticated relay trace with the product tracer", () =>
128 Effect.gen(function* () {
129 const spans: Array<Tracer.Span> = [];
130 const productTracer = Tracer.make({
131 span: (options) => {
132 const span = new Tracer.NativeSpan(options);
133 spans.push(span);
134 return span;
135 },
136 });
137 const request = HttpServerRequest.fromWeb(
138 new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
139 headers: {
140 traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
141 },
142 }),
143 );
144​
145 yield* traceAuthenticatedRelayRequest(
146 Effect.void.pipe(Effect.withSpan("relay.mint.handler")),
147 ).pipe(
148 Effect.provideService(HttpServerRequest.HttpServerRequest, request),
149 Effect.provideService(RelayClientTracer, Option.some(productTracer)),
150 );
151​
152 expect(spans).toHaveLength(1);
153 const span = spans[0]!;
154 expect(span.traceId).toBe("0123456789abcdef0123456789abcdef");
155 expect(Option.getOrUndefined(span.parent)?.spanId).toBe("0123456789abcdef");
156 }),
157 );
158});
159​
160describe("reconcileDesiredCloudLink", () => {
161 it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
162 Effect.gen(function* () {
163 const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
164​
165 expect(error).toMatchObject({
166 _tag: "EnvironmentHttpUnauthorizedError",
167 message: "Run `t3 connect link` to authorize this environment.",
168 });
169 }).pipe(
170 Effect.provideService(
171 ServerSecretStore.ServerSecretStore,
172 makeSecretStore(unusedSecretStoreOperation),
173 ),
174 Effect.provideService(
175 ServerEnvironment.ServerEnvironment,
176 ServerEnvironment.ServerEnvironment.of({
177 getEnvironmentId: unusedSecretStoreOperation(),
178 getDescriptor: unusedSecretStoreOperation(),
179 }),
180 ),
181 Effect.provideService(
182 ManagedEndpointRuntime.CloudManagedEndpointRuntime,
183 ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
184 applyConfig: unusedSecretStoreOperation,
185 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
186 ),
187 Effect.provideService(
188 EnvironmentAuth.EnvironmentAuth,
189 EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
190 ),
191 Effect.provideService(
192 CliTokenManager.CloudCliTokenManager,
193 CliTokenManager.CloudCliTokenManager.of({
194 get: unusedSecretStoreOperation(),
195 getExisting: Effect.succeed(Option.none()),
196 hasCredential: unusedSecretStoreOperation(),
197 clear: unusedSecretStoreOperation(),
198 }),
199 ),
200 Effect.provideService(
201 HttpClient.HttpClient,
202 HttpClient.make(() => unusedSecretStoreOperation()),
203 ),
204 Effect.provide(NodeServices.layer),
205 ),
206 );
207});