Skip to content

Commit 050fbe6

Browse files
[codex] Structure cloud HTTP boundary errors (#3246)
Co-authored-by: codex <[email protected]>
1 parent 8090110 commit 050fbe6

5 files changed

Lines changed: 759 additions & 155 deletions

File tree

‎apps/mobile/src/features/cloud/linkEnvironment.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -607,7 +607,8 @@ describe("mobile cloud link environment client", () => {
607607
Response.json(
608608
{
609609
_tag: "EnvironmentHttpUnauthorizedError",
610-
message: "Invalid environment bearer session.",
610+
reason: "cloud_cli_authorization_required",
611+
message: "Run `t3 connect link` to authorize this environment.",
611612
},
612613
{ status: 401 },
613614
),
@@ -623,7 +624,7 @@ describe("mobile cloud link environment client", () => {
623624
).pipe(Effect.flip);
624625
expect(error._tag).toBe("CloudEnvironmentLinkError");
625626
expect(error.message).toBe(
626-
"Could not obtain environment link proof: Invalid environment bearer session.",
627+
"Could not obtain environment link proof: Run `t3 connect link` to authorize this environment.",
627628
);
628629
expect(fetchMock).toHaveBeenCalledTimes(2);
629630
}),

‎apps/server/src/cloud/http.test.ts‎

Lines changed: 212 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,40 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
22
import { describe, expect, it } from "@effect/vitest";
3+
import * as ConfigProvider from "effect/ConfigProvider";
34
import * as Effect from "effect/Effect";
5+
import * as Layer from "effect/Layer";
6+
import * as Logger from "effect/Logger";
47
import * as Option from "effect/Option";
58
import * as PlatformError from "effect/PlatformError";
9+
import * as Schema from "effect/Schema";
610
import * as Tracer from "effect/Tracer";
7-
import { HttpClient, HttpServerRequest } from "effect/unstable/http";
11+
import * as HttpClient from "effect/unstable/http/HttpClient";
12+
import * as HttpClientError from "effect/unstable/http/HttpClientError";
13+
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
14+
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
15+
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
16+
import { EnvironmentHttpInternalServerError } from "@t3tools/contracts";
817

918
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
1019
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
1120
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
1221
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
1322
import * as CliTokenManager from "./CliTokenManager.ts";
14-
import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
23+
import {
24+
CloudRelayRequestError,
25+
consumeCloudReplayGuards,
26+
reconcileDesiredCloudLink,
27+
} from "./http.ts";
1528
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
1629
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
1730

31+
const encodeEnvironmentHttpInternalServerError = Schema.encodeUnknownSync(
32+
EnvironmentHttpInternalServerError,
33+
);
34+
const decodeEnvironmentHttpInternalServerError = Schema.decodeUnknownSync(
35+
EnvironmentHttpInternalServerError,
36+
);
37+
1838
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
1939
new ServerSecretStore.SecretStorePersistError({
2040
operation: "create",
@@ -42,6 +62,55 @@ function makeSecretStore(
4262
};
4363
}
4464

65+
function reconcileWith(input: {
66+
readonly getExisting: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"];
67+
readonly httpClient?: HttpClient.HttpClient;
68+
readonly env?: Readonly<Record<string, string>>;
69+
}) {
70+
return reconcileDesiredCloudLink("http://127.0.0.1:3774").pipe(
71+
Effect.provideService(
72+
ServerSecretStore.ServerSecretStore,
73+
makeSecretStore(unusedSecretStoreOperation),
74+
),
75+
Effect.provideService(
76+
ServerEnvironment.ServerEnvironment,
77+
ServerEnvironment.ServerEnvironment.of({
78+
getEnvironmentId: unusedSecretStoreOperation(),
79+
getDescriptor: unusedSecretStoreOperation(),
80+
}),
81+
),
82+
Effect.provideService(
83+
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
84+
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
85+
applyConfig: unusedSecretStoreOperation,
86+
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
87+
),
88+
Effect.provideService(
89+
EnvironmentAuth.EnvironmentAuth,
90+
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
91+
),
92+
Effect.provideService(
93+
CliTokenManager.CloudCliTokenManager,
94+
CliTokenManager.CloudCliTokenManager.of({
95+
get: unusedSecretStoreOperation(),
96+
getExisting: input.getExisting,
97+
hasCredential: unusedSecretStoreOperation(),
98+
clear: unusedSecretStoreOperation(),
99+
}),
100+
),
101+
Effect.provideService(
102+
HttpClient.HttpClient,
103+
input.httpClient ?? HttpClient.make(() => unusedSecretStoreOperation()),
104+
),
105+
Effect.provide(
106+
Layer.mergeAll(
107+
NodeServices.layer,
108+
ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
109+
),
110+
),
111+
);
112+
}
113+
45114
it("preserves messages surfaced by cloud 500 responses", () => {
46115
const cause = new Error("cloud operation failed");
47116

@@ -95,6 +164,84 @@ describe("consumeCloudReplayGuards", () => {
95164
);
96165
});
97166

167+
describe("CloudRelayRequestError", () => {
168+
it("classifies response failures without deriving its message from the cause", () => {
169+
const requestUrl =
170+
"https://relay-user:[email protected]/private/environment-links?token=relay-secret#relay-fragment";
171+
const request = HttpClientRequest.post(requestUrl);
172+
const response = HttpClientResponse.fromWeb(
173+
request,
174+
new Response("sensitive upstream response", { status: 502 }),
175+
);
176+
const upstreamCause = new Error("sensitive upstream response details");
177+
const cause = new HttpClientError.HttpClientError({
178+
reason: new HttpClientError.StatusCodeError({
179+
request,
180+
response,
181+
cause: upstreamCause,
182+
}),
183+
});
184+
185+
const error = CloudRelayRequestError.fromClientFailure({
186+
operation: "create-environment-link",
187+
url: request.url,
188+
cause,
189+
});
190+
191+
expect(error).toMatchObject({
192+
operation: "create-environment-link",
193+
phase: "check-response-status",
194+
method: "POST",
195+
requestUrlInputLength: requestUrl.length,
196+
requestUrlProtocol: "https:",
197+
requestUrlHostname: "relay.example.test",
198+
responseStatus: 502,
199+
cause,
200+
});
201+
expect(error.cause).toBe(cause);
202+
expect(error).not.toHaveProperty("url");
203+
expect(error.message).toBe(
204+
"T3 Connect relay create-environment-link failed during check-response-status with response status 502.",
205+
);
206+
expect(error.message).not.toContain(upstreamCause.message);
207+
for (const secret of [
208+
"relay-user",
209+
"relay-password",
210+
"/private/environment-links",
211+
"relay-secret",
212+
"relay-fragment",
213+
]) {
214+
expect(error.message).not.toContain(secret);
215+
expect(Object.values(error).join(" ")).not.toContain(secret);
216+
}
217+
});
218+
});
219+
220+
it("keeps internal causes out of encoded HTTP error bodies", () => {
221+
const cause = new Error("private upstream detail");
222+
const error = new EnvironmentHttpInternalServerError({
223+
operation: "generate_link_proof",
224+
cause,
225+
});
226+
227+
expect(error.cause).toBe(cause);
228+
expect(encodeEnvironmentHttpInternalServerError(error)).toEqual({
229+
_tag: "EnvironmentHttpInternalServerError",
230+
operation: "generate_link_proof",
231+
message: "Could not generate environment link proof.",
232+
});
233+
});
234+
235+
it("decodes legacy message-only HTTP errors during rolling deployments", () => {
236+
const error = decodeEnvironmentHttpInternalServerError({
237+
_tag: "EnvironmentHttpInternalServerError",
238+
message: "Legacy environment server failure.",
239+
});
240+
241+
expect(error.operation).toBeUndefined();
242+
expect(error.message).toBe("Legacy environment server failure.");
243+
});
244+
98245
describe("relay request tracing", () => {
99246
it.effect("does not accept an unauthenticated request trace parent", () =>
100247
Effect.gen(function* () {
@@ -162,48 +309,74 @@ describe("relay request tracing", () => {
162309
describe("reconcileDesiredCloudLink", () => {
163310
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
164311
Effect.gen(function* () {
165-
const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
312+
const error = yield* Effect.flip(
313+
reconcileWith({ getExisting: Effect.succeed(Option.none()) }),
314+
);
166315

167316
expect(error).toMatchObject({
168317
_tag: "EnvironmentHttpUnauthorizedError",
318+
reason: "cloud_cli_authorization_required",
169319
message: "Run `t3 connect link` to authorize this environment.",
170320
});
171-
}).pipe(
172-
Effect.provideService(
173-
ServerSecretStore.ServerSecretStore,
174-
makeSecretStore(unusedSecretStoreOperation),
175-
),
176-
Effect.provideService(
177-
ServerEnvironment.ServerEnvironment,
178-
ServerEnvironment.ServerEnvironment.of({
179-
getEnvironmentId: unusedSecretStoreOperation(),
180-
getDescriptor: unusedSecretStoreOperation(),
181-
}),
182-
),
183-
Effect.provideService(
184-
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
185-
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
186-
applyConfig: unusedSecretStoreOperation,
187-
} satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
188-
),
189-
Effect.provideService(
190-
EnvironmentAuth.EnvironmentAuth,
191-
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
192-
),
193-
Effect.provideService(
194-
CliTokenManager.CloudCliTokenManager,
195-
CliTokenManager.CloudCliTokenManager.of({
196-
get: unusedSecretStoreOperation(),
197-
getExisting: Effect.succeed(Option.none()),
198-
hasCredential: unusedSecretStoreOperation(),
199-
clear: unusedSecretStoreOperation(),
321+
}),
322+
);
323+
324+
it.effect("redacts relay transport failures behind a stable structural message", () => {
325+
const transportCause = new Error("upstream included a sensitive database password");
326+
const capturedLogs: Array<ReadonlyArray<unknown>> = [];
327+
const logger = Logger.make(({ message }) => {
328+
capturedLogs.push(Array.isArray(message) ? message : [message]);
329+
});
330+
const httpClient = HttpClient.make((request) =>
331+
Effect.fail(
332+
new HttpClientError.HttpClientError({
333+
reason: new HttpClientError.TransportError({ request, cause: transportCause }),
200334
}),
201335
),
202-
Effect.provideService(
203-
HttpClient.HttpClient,
204-
HttpClient.make(() => unusedSecretStoreOperation()),
205-
),
206-
Effect.provide(NodeServices.layer),
207-
),
208-
);
336+
);
337+
338+
return Effect.gen(function* () {
339+
const error = yield* Effect.flip(
340+
reconcileWith({
341+
getExisting: Effect.succeed(
342+
Option.some({
343+
accessToken: "access-token",
344+
refreshToken: "refresh-token",
345+
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
346+
}),
347+
),
348+
httpClient,
349+
env: { T3CODE_RELAY_URL: "https://relay.example.test" },
350+
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))),
351+
);
352+
353+
expect(error).toMatchObject({
354+
_tag: "EnvironmentHttpInternalServerError",
355+
operation: "relay_request",
356+
relayOperation: "create-link-challenge",
357+
relayPhase: "send-request",
358+
message: "T3 Connect relay create-link-challenge failed during send-request.",
359+
cause: {
360+
_tag: "CloudRelayRequestError",
361+
operation: "create-link-challenge",
362+
phase: "send-request",
363+
},
364+
});
365+
expect(error.message).not.toContain(transportCause.message);
366+
expect(capturedLogs).toHaveLength(1);
367+
const logFields = capturedLogs[0]?.find(
368+
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
369+
);
370+
expect(logFields).toMatchObject({
371+
operation: "relay_request",
372+
relayOperation: "create-link-challenge",
373+
relayPhase: "send-request",
374+
causeTag: "CloudRelayRequestError",
375+
});
376+
expect(logFields).not.toHaveProperty("cause");
377+
expect(capturedLogs[0]?.filter((value) => typeof value === "string").join(" ")).not.toContain(
378+
transportCause.message,
379+
);
380+
});
381+
});
209382
});

0 commit comments

Comments
 (0)