preserve relay API projection failures
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
39441ec2a5
commit
986fe93d5b
2 files changed
+263
-25
No files matched your search
@@ -1,21 +1,30 @@
|
||||
import { createClerkClient, verifyToken } from "@clerk/backend";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { vi } from "vite-plus/test";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Predicate from "effect/Predicate";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as References from "effect/References";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { RelayEnvironmentAuth } from "@t3tools/contracts/relay";
|
||||
import {
|
||||
RelayEnvironmentAuth,
|
||||
RelayEnvironmentConnectNotAuthorizedError,
|
||||
RelayInternalError,
|
||||
} from "@t3tools/contracts/relay";
|
||||
|
||||
import {
|
||||
ClerkBearerTokenVerificationError,
|
||||
ClerkTokenVerificationError,
|
||||
mapErrorTags,
|
||||
mapRelayCommonApiErrors,
|
||||
relayCors,
|
||||
relayDocsRedirectRoute,
|
||||
relayEnvironmentAuthLayer,
|
||||
@@ -27,6 +36,7 @@ import {
|
||||
} from "./Api.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts";
|
||||
import * as EnvironmentConnector from "../environments/EnvironmentConnector.ts";
|
||||
|
||||
vi.mock("@clerk/backend", () => ({
|
||||
createClerkClient: vi.fn(),
|
||||
@@ -52,6 +62,19 @@ const relaySettings: RelayConfiguration.RelayConfiguration["Service"] = {
|
||||
managedEndpointNamespace: undefined,
|
||||
};
|
||||
|
||||
const projectionTraceId = "00000000000000000000000000000042";
|
||||
const projectionParentSpan = Tracer.externalSpan({
|
||||
traceId: projectionTraceId,
|
||||
spanId: "0000000000000042",
|
||||
sampled: true,
|
||||
});
|
||||
|
||||
interface CapturedLog {
|
||||
readonly message: unknown;
|
||||
readonly cause: Cause.Cause<unknown>;
|
||||
readonly annotations: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
describe("relay client authentication", () => {
|
||||
it.effect("preserves the existing Clerk session JWT path", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -242,6 +265,14 @@ describe("relay DPoP token exchange authentication", () => {
|
||||
|
||||
describe("relay environment authentication", () => {
|
||||
it.effect("preserves credential lookup persistence failures as internal errors", () => {
|
||||
const logs: CapturedLog[] = [];
|
||||
const logger = Logger.make(({ cause, fiber, message }) => {
|
||||
logs.push({
|
||||
message,
|
||||
cause,
|
||||
annotations: fiber.getRef(References.CurrentLogAnnotations),
|
||||
});
|
||||
});
|
||||
const failure = new EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError({
|
||||
stage: "lookup-credential",
|
||||
cause: "database unavailable",
|
||||
@@ -265,8 +296,25 @@ describe("relay environment authentication", () => {
|
||||
expect(Predicate.isTagged(error, "RelayInternalError")).toBe(true);
|
||||
if (Predicate.isTagged(error, "RelayInternalError")) {
|
||||
expect(error.reason).toBe("persistence_failed");
|
||||
expect(error.traceId).toBe(projectionTraceId);
|
||||
expect(error).not.toHaveProperty("cause");
|
||||
}
|
||||
expect(logs).toEqual([
|
||||
{
|
||||
message: ["relay API failure projected to wire response"],
|
||||
cause: Cause.fail(failure),
|
||||
annotations: expect.objectContaining({
|
||||
traceId: projectionTraceId,
|
||||
sourceErrorTag: "EnvironmentCredentialAuthenticatePersistenceError",
|
||||
responseErrorTag: "RelayInternalError",
|
||||
responseCode: "internal_error",
|
||||
responseReason: "persistence_failed",
|
||||
}),
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provideService(Tracer.ParentSpan, projectionParentSpan),
|
||||
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
Effect.provideService(
|
||||
HttpServerRequest.HttpServerRequest,
|
||||
HttpServerRequest.fromWeb(new Request("https://relay.test/v1/server/link")),
|
||||
@@ -286,6 +334,128 @@ describe("relay environment authentication", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("relay API error projection", () => {
|
||||
it.effect("logs common persistence failures with the wire response trace", () => {
|
||||
const logs: CapturedLog[] = [];
|
||||
const logger = Logger.make(({ cause, fiber, message }) => {
|
||||
logs.push({
|
||||
message,
|
||||
cause,
|
||||
annotations: fiber.getRef(References.CurrentLogAnnotations),
|
||||
});
|
||||
});
|
||||
const databaseCause = new Error("database connection refused");
|
||||
const failure = new EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError({
|
||||
environmentId: "env-test",
|
||||
cause: databaseCause,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* Effect.fail(failure).pipe(
|
||||
mapRelayCommonApiErrors("not_authorized"),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(RelayInternalError);
|
||||
expect(error).toMatchObject({
|
||||
code: "internal_error",
|
||||
reason: "persistence_failed",
|
||||
traceId: projectionTraceId,
|
||||
});
|
||||
expect(error).not.toHaveProperty("cause");
|
||||
expect(logs).toEqual([
|
||||
{
|
||||
message: ["relay API failure projected to wire response"],
|
||||
cause: Cause.fail(failure),
|
||||
annotations: expect.objectContaining({
|
||||
traceId: projectionTraceId,
|
||||
sourceErrorTag: "EnvironmentCredentialRevokePersistenceError",
|
||||
responseErrorTag: "RelayInternalError",
|
||||
responseCode: "internal_error",
|
||||
responseReason: "persistence_failed",
|
||||
}),
|
||||
},
|
||||
]);
|
||||
expect(failure.cause).toBe(databaseCause);
|
||||
}).pipe(
|
||||
Effect.provideService(Tracer.ParentSpan, projectionParentSpan),
|
||||
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("logs selected server failures but not expected authorization projections", () => {
|
||||
const logs: CapturedLog[] = [];
|
||||
const logger = Logger.make(({ cause, fiber, message }) => {
|
||||
logs.push({
|
||||
message,
|
||||
cause,
|
||||
annotations: fiber.getRef(References.CurrentLogAnnotations),
|
||||
});
|
||||
});
|
||||
const serverCause = new Error("mint request transport failed");
|
||||
const serverFailure = EnvironmentConnector.EnvironmentMintRequestFailed.fromEndpoint({
|
||||
userId: "user-test",
|
||||
environmentId: "env-test",
|
||||
operation: "connect",
|
||||
stage: "send_request",
|
||||
httpBaseUrl: "https://environment.example.test",
|
||||
cause: serverCause,
|
||||
});
|
||||
const authorizationFailure = new EnvironmentConnector.EnvironmentConnectNotAuthorized({
|
||||
environmentId: "env-test",
|
||||
operation: "connect",
|
||||
reason: "environment_link_not_found",
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const serverError = yield* Effect.fail(serverFailure).pipe(
|
||||
mapErrorTags({
|
||||
EnvironmentMintRequestFailed: (_error, traceId) =>
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "upstream_unavailable",
|
||||
traceId,
|
||||
}),
|
||||
}),
|
||||
Effect.flip,
|
||||
);
|
||||
const authorizationError = yield* Effect.fail(authorizationFailure).pipe(
|
||||
mapErrorTags({
|
||||
EnvironmentConnectNotAuthorized: (_error, traceId) =>
|
||||
new RelayEnvironmentConnectNotAuthorizedError({
|
||||
code: "environment_connect_not_authorized",
|
||||
traceId,
|
||||
}),
|
||||
}),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(serverError).toMatchObject({
|
||||
reason: "upstream_unavailable",
|
||||
traceId: projectionTraceId,
|
||||
});
|
||||
expect(authorizationError.traceId).toBe(projectionTraceId);
|
||||
expect(logs).toEqual([
|
||||
{
|
||||
message: ["relay API failure projected to wire response"],
|
||||
cause: Cause.fail(serverFailure),
|
||||
annotations: expect.objectContaining({
|
||||
traceId: projectionTraceId,
|
||||
sourceErrorTag: "EnvironmentMintRequestFailed",
|
||||
responseErrorTag: "RelayInternalError",
|
||||
responseCode: "internal_error",
|
||||
responseReason: "upstream_unavailable",
|
||||
}),
|
||||
},
|
||||
]);
|
||||
expect(serverFailure.cause).toBe(serverCause);
|
||||
}).pipe(
|
||||
Effect.provideService(Tracer.ParentSpan, projectionParentSpan),
|
||||
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("relay request tracing", () => {
|
||||
it.effect(
|
||||
"does not parent endpoint spans to an ambient parent captured while building handlers",
|
||||
|
||||
+92
-24
@@ -1,5 +1,6 @@
|
||||
import { createClerkClient, verifyToken } from "@clerk/backend";
|
||||
import { sql as drizzleSql } from "drizzle-orm";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -239,8 +240,8 @@ export const relayEnvironmentAuthLayer = Layer.effect(
|
||||
const token = readHttpAuthorizationCredential(credential);
|
||||
const principal = yield* credentials.authenticate(token).pipe(
|
||||
Effect.catchTags({
|
||||
EnvironmentCredentialAuthenticatePersistenceError: () =>
|
||||
relayInternalErrorResponse("persistence_failed"),
|
||||
EnvironmentCredentialAuthenticatePersistenceError: (error) =>
|
||||
relayInternalErrorResponse("persistence_failed", error),
|
||||
}),
|
||||
);
|
||||
if (principal._tag === "None") {
|
||||
@@ -353,7 +354,7 @@ export const healthApi = HttpApiBuilder.group(
|
||||
yield* db.execute(drizzleSql`SELECT 1`);
|
||||
return { ok: true, service: "relay" as const };
|
||||
},
|
||||
Effect.catch(() => relayInternalErrorResponse("database_unavailable")),
|
||||
Effect.catch((error) => relayInternalErrorResponse("database_unavailable", error)),
|
||||
),
|
||||
);
|
||||
}),
|
||||
@@ -512,7 +513,7 @@ export const clientApi = HttpApiBuilder.group(
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 5 });
|
||||
const jti = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.catch(() => relayInternalErrorResponse("internal_error")),
|
||||
Effect.catch((error) => relayInternalErrorResponse("internal_error", error)),
|
||||
);
|
||||
const challenge = yield* relayTokens
|
||||
.issueLinkChallenge({
|
||||
@@ -522,7 +523,7 @@ export const clientApi = HttpApiBuilder.group(
|
||||
issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000),
|
||||
})
|
||||
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error")));
|
||||
.pipe(Effect.catch((error) => relayInternalErrorResponse("internal_error", error)));
|
||||
return { challenge, expiresAt: DateTime.formatIso(expiresAt) };
|
||||
}, mapRelayCommonApiErrors("not_authorized")),
|
||||
)
|
||||
@@ -536,7 +537,9 @@ export const clientApi = HttpApiBuilder.group(
|
||||
userId,
|
||||
environmentId: params.environmentId,
|
||||
})
|
||||
.pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")));
|
||||
.pipe(
|
||||
Effect.catch((error) => relayInternalErrorResponse("upstream_unavailable", error)),
|
||||
);
|
||||
const link = yield* links.getForUser({
|
||||
userId,
|
||||
environmentId: params.environmentId,
|
||||
@@ -596,7 +599,7 @@ export const tokenApi = HttpApiBuilder.group(
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.addDuration(now, RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL);
|
||||
const jti = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.catch(() => relayInternalErrorResponse("internal_error")),
|
||||
Effect.catch((error) => relayInternalErrorResponse("internal_error", error)),
|
||||
);
|
||||
return {
|
||||
access_token: yield* relayTokens
|
||||
@@ -609,7 +612,7 @@ export const tokenApi = HttpApiBuilder.group(
|
||||
clientId: args.payload.client_id,
|
||||
scopes: requestedScopes,
|
||||
})
|
||||
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))),
|
||||
.pipe(Effect.catch((error) => relayInternalErrorResponse("internal_error", error))),
|
||||
issued_token_type: RelayAccessTokenType,
|
||||
token_type: "DPoP" as const,
|
||||
expires_in: Duration.toSeconds(RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL),
|
||||
@@ -901,6 +904,50 @@ const currentTraceId = Effect.currentParentSpan.pipe(
|
||||
Effect.orElseSucceed(() => "unavailable"),
|
||||
);
|
||||
|
||||
function relayApiErrorTag(error: unknown): string {
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
typeof error._tag === "string"
|
||||
) {
|
||||
return error._tag;
|
||||
}
|
||||
if (error instanceof Error && error.name.length > 0) {
|
||||
return error.name;
|
||||
}
|
||||
return typeof error;
|
||||
}
|
||||
|
||||
function safeRelayApiLogCode(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.length <= 64 && /^[a-z0-9._-]+$/iu.test(value)
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function relayApiProjectionResponseFields(error: unknown) {
|
||||
if (typeof error !== "object" || error === null) {
|
||||
return {};
|
||||
}
|
||||
const code = "code" in error ? safeRelayApiLogCode(error.code) : undefined;
|
||||
const reason = "reason" in error ? safeRelayApiLogCode(error.reason) : undefined;
|
||||
return {
|
||||
...(code === undefined ? {} : { responseCode: code }),
|
||||
...(reason === undefined ? {} : { responseReason: reason }),
|
||||
};
|
||||
}
|
||||
|
||||
function logRelayApiProjection(cause: unknown, responseError: unknown, traceId: string) {
|
||||
return Effect.logError("relay API failure projected to wire response", Cause.fail(cause)).pipe(
|
||||
Effect.annotateLogs({
|
||||
traceId,
|
||||
sourceErrorTag: relayApiErrorTag(cause),
|
||||
responseErrorTag: relayApiErrorTag(responseError),
|
||||
...relayApiProjectionResponseFields(responseError),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const RelayCommonPersistenceError = Schema.Union([
|
||||
Devices.DeviceRegistrationPersistenceError,
|
||||
Devices.DeviceUnregistrationPersistenceError,
|
||||
@@ -930,15 +977,16 @@ type MapRelayCommonApiError<E> =
|
||||
| (Extract<E, HttpApiError.Unauthorized> extends never ? never : RelayAuthInvalidError)
|
||||
| (Extract<E, RelayCommonPersistenceError> extends never ? never : RelayInternalError);
|
||||
|
||||
function relayInternalErrorResponse(reason: RelayInternalError["reason"]) {
|
||||
return currentTraceId.pipe(
|
||||
Effect.flatMap((traceId) =>
|
||||
Effect.fail(new RelayInternalError({ code: "internal_error", reason, traceId })),
|
||||
),
|
||||
);
|
||||
function relayInternalErrorResponse(reason: RelayInternalError["reason"], cause: unknown) {
|
||||
return Effect.gen(function* () {
|
||||
const traceId = yield* currentTraceId;
|
||||
const responseError = new RelayInternalError({ code: "internal_error", reason, traceId });
|
||||
yield* logRelayApiProjection(cause, responseError, traceId);
|
||||
return yield* responseError;
|
||||
});
|
||||
}
|
||||
|
||||
function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) {
|
||||
export function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) {
|
||||
const mapError = Effect.fnUntraced(function* <E>(error: E) {
|
||||
const traceId = yield* currentTraceId;
|
||||
if (isHttpUnauthorized(error)) {
|
||||
@@ -951,13 +999,13 @@ function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) {
|
||||
);
|
||||
}
|
||||
if (isRelayCommonPersistenceError(error)) {
|
||||
return yield* Effect.fail(
|
||||
new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "persistence_failed",
|
||||
traceId,
|
||||
}) as MapRelayCommonApiError<E>,
|
||||
);
|
||||
const responseError = new RelayInternalError({
|
||||
code: "internal_error",
|
||||
reason: "persistence_failed",
|
||||
traceId,
|
||||
});
|
||||
yield* logRelayApiProjection(error, responseError, traceId);
|
||||
return yield* Effect.fail(responseError as MapRelayCommonApiError<E>);
|
||||
}
|
||||
|
||||
return yield* Effect.fail(error as MapRelayCommonApiError<E>);
|
||||
@@ -989,7 +1037,19 @@ type CatchTagCases<E, Cases> = {
|
||||
) => Effect.Effect<never, MappedTagError<Cases>>;
|
||||
} & (unknown extends E ? {} : { readonly [K in Exclude<keyof Cases, TaggedErrorTag<E>>]: never });
|
||||
|
||||
function mapErrorTags<
|
||||
const relayApiProjectedFailureLogTags = new Set([
|
||||
"ManagedEndpointProvisioningNotConfigured",
|
||||
"ManagedEndpointProvisioningFailed",
|
||||
"EnvironmentLinkUpsertPersistenceError",
|
||||
"EnvironmentCredentialCreatePersistenceError",
|
||||
"DpopProofReplayPersistenceError",
|
||||
"EnvironmentMintRequestFailed",
|
||||
"EnvironmentMintRequestTimedOut",
|
||||
"EnvironmentMintResponseInvalid",
|
||||
"ApnsDeliveryQueueSendError",
|
||||
]);
|
||||
|
||||
export function mapErrorTags<
|
||||
E,
|
||||
Cases extends MapErrorTagCases<E> &
|
||||
(unknown extends E ? {} : { readonly [K in Exclude<keyof Cases, TaggedErrorTag<E>>]: never }),
|
||||
@@ -1000,7 +1060,15 @@ function mapErrorTags<
|
||||
(error: never, traceId: string) => MappedTagError<Cases>
|
||||
>,
|
||||
(makeError) => (error: never) =>
|
||||
currentTraceId.pipe(Effect.flatMap((traceId) => Effect.fail(makeError(error, traceId)))),
|
||||
currentTraceId.pipe(
|
||||
Effect.flatMap((traceId) => {
|
||||
const responseError = makeError(error, traceId);
|
||||
const logProjection = relayApiProjectedFailureLogTags.has(relayApiErrorTag(error))
|
||||
? logRelayApiProjection(error, responseError, traceId)
|
||||
: Effect.void;
|
||||
return logProjection.pipe(Effect.andThen(Effect.fail(responseError)));
|
||||
}),
|
||||
),
|
||||
) as CatchTagCases<E, Cases>;
|
||||
|
||||
return <A, R>(
|
||||
|
||||
Reference in new issue
Block a user