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

http.test.ts

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