| @@ -1,5 +1,6 @@ |
| 1 | import { createClerkClient, verifyToken } from "@clerk/backend"; | 1 | import { createClerkClient, verifyToken } from "@clerk/backend"; |
| 2 | import { sql as drizzleSql } from "drizzle-orm"; | 2 | import { sql as drizzleSql } from "drizzle-orm"; |
| | 3 | import * as Cause from "effect/Cause"; |
| 3 | import * as Crypto from "effect/Crypto"; | 4 | import * as Crypto from "effect/Crypto"; |
| 4 | import * as Context from "effect/Context"; | 5 | import * as Context from "effect/Context"; |
| 5 | import * as DateTime from "effect/DateTime"; | 6 | import * as DateTime from "effect/DateTime"; |
| @@ -239,8 +240,8 @@ export const relayEnvironmentAuthLayer = Layer.effect( · 233 unmodified lines |
| 239 | const token = readHttpAuthorizationCredential(credential); | 240 | const token = readHttpAuthorizationCredential(credential); |
| 240 | const principal = yield* credentials.authenticate(token).pipe( | 241 | const principal = yield* credentials.authenticate(token).pipe( |
| 241 | Effect.catchTags({ | 242 | Effect.catchTags({ |
| 242 | EnvironmentCredentialAuthenticatePersistenceError: () => | 243 | EnvironmentCredentialAuthenticatePersistenceError: (error) => |
| 243 | relayInternalErrorResponse("persistence_failed"), | 244 | relayInternalErrorResponse("persistence_failed", error), |
| 244 | }), | 245 | }), |
| 245 | ); | 246 | ); |
| 246 | if (principal._tag === "None") { | 247 | if (principal._tag === "None") { |
| @@ -353,7 +354,7 @@ export const healthApi = HttpApiBuilder.group( · 106 unmodified lines |
| 353 | yield* db.execute(drizzleSql`SELECT 1`); | 354 | yield* db.execute(drizzleSql`SELECT 1`); |
| 354 | return { ok: true, service: "relay" as const }; | 355 | return { ok: true, service: "relay" as const }; |
| 355 | }, | 356 | }, |
| 356 | Effect.catch(() => relayInternalErrorResponse("database_unavailable")), | 357 | Effect.catch((error) => relayInternalErrorResponse("database_unavailable", error)), |
| 357 | ), | 358 | ), |
| 358 | ); | 359 | ); |
| 359 | }), | 360 | }), |
| @@ -512,7 +513,7 @@ export const clientApi = HttpApiBuilder.group( · 152 unmodified lines |
| 512 | const now = yield* DateTime.now; | 513 | const now = yield* DateTime.now; |
| 513 | const expiresAt = DateTime.add(now, { minutes: 5 }); | 514 | const expiresAt = DateTime.add(now, { minutes: 5 }); |
| 514 | const jti = yield* crypto.randomUUIDv4.pipe( | 515 | const jti = yield* crypto.randomUUIDv4.pipe( |
| 515 | Effect.catch(() => relayInternalErrorResponse("internal_error")), | 516 | Effect.catch((error) => relayInternalErrorResponse("internal_error", error)), |
| 516 | ); | 517 | ); |
| 517 | const challenge = yield* relayTokens | 518 | const challenge = yield* relayTokens |
| 518 | .issueLinkChallenge({ | 519 | .issueLinkChallenge({ |
| @@ -522,7 +523,7 @@ export const clientApi = HttpApiBuilder.group( · 3 unmodified lines |
| 522 | issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), | 523 | issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), |
| 523 | expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000), | 524 | expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000), |
| 524 | }) | 525 | }) |
| 525 | .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))); | 526 | .pipe(Effect.catch((error) => relayInternalErrorResponse("internal_error", error))); |
| 526 | return { challenge, expiresAt: DateTime.formatIso(expiresAt) }; | 527 | return { challenge, expiresAt: DateTime.formatIso(expiresAt) }; |
| 527 | }, mapRelayCommonApiErrors("not_authorized")), | 528 | }, mapRelayCommonApiErrors("not_authorized")), |
| 528 | ) | 529 | ) |
| @@ -536,7 +537,9 @@ export const clientApi = HttpApiBuilder.group( · 7 unmodified lines |
| 536 | userId, | 537 | userId, |
| 537 | environmentId: params.environmentId, | 538 | environmentId: params.environmentId, |
| 538 | }) | 539 | }) |
| 539 | .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable"))); | 540 | .pipe( |
| | 541 | Effect.catch((error) => relayInternalErrorResponse("upstream_unavailable", error)), |
| | 542 | ); |
| 540 | const link = yield* links.getForUser({ | 543 | const link = yield* links.getForUser({ |
| 541 | userId, | 544 | userId, |
| 542 | environmentId: params.environmentId, | 545 | environmentId: params.environmentId, |
| @@ -596,7 +599,7 @@ export const tokenApi = HttpApiBuilder.group( · 53 unmodified lines |
| 596 | const now = yield* DateTime.now; | 599 | const now = yield* DateTime.now; |
| 597 | const expiresAt = DateTime.addDuration(now, RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL); | 600 | const expiresAt = DateTime.addDuration(now, RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL); |
| 598 | const jti = yield* crypto.randomUUIDv4.pipe( | 601 | const jti = yield* crypto.randomUUIDv4.pipe( |
| 599 | Effect.catch(() => relayInternalErrorResponse("internal_error")), | 602 | Effect.catch((error) => relayInternalErrorResponse("internal_error", error)), |
| 600 | ); | 603 | ); |
| 601 | return { | 604 | return { |
| 602 | access_token: yield* relayTokens | 605 | access_token: yield* relayTokens |
| @@ -609,7 +612,7 @@ export const tokenApi = HttpApiBuilder.group( · 6 unmodified lines |
| 609 | clientId: args.payload.client_id, | 612 | clientId: args.payload.client_id, |
| 610 | scopes: requestedScopes, | 613 | scopes: requestedScopes, |
| 611 | }) | 614 | }) |
| 612 | .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))), | 615 | .pipe(Effect.catch((error) => relayInternalErrorResponse("internal_error", error))), |
| 613 | issued_token_type: RelayAccessTokenType, | 616 | issued_token_type: RelayAccessTokenType, |
| 614 | token_type: "DPoP" as const, | 617 | token_type: "DPoP" as const, |
| 615 | expires_in: Duration.toSeconds(RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL), | 618 | expires_in: Duration.toSeconds(RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL), |
| @@ -901,6 +904,50 @@ const currentTraceId = Effect.currentParentSpan.pipe( · 285 unmodified lines |
| 901 | Effect.orElseSucceed(() => "unavailable"), | 904 | Effect.orElseSucceed(() => "unavailable"), |
| 902 | ); | 905 | ); |
| 903 | | 906 | |
| | 907 | function relayApiErrorTag(error: unknown): string { |
| | 908 | if ( |
| | 909 | typeof error === "object" && |
| | 910 | error !== null && |
| | 911 | "_tag" in error && |
| | 912 | typeof error._tag === "string" |
| | 913 | ) { |
| | 914 | return error._tag; |
| | 915 | } |
| | 916 | if (error instanceof Error && error.name.length > 0) { |
| | 917 | return error.name; |
| | 918 | } |
| | 919 | return typeof error; |
| | 920 | } |
| | 921 | |
| | 922 | function safeRelayApiLogCode(value: unknown): string | undefined { |
| | 923 | return typeof value === "string" && value.length <= 64 && /^[a-z0-9._-]+$/iu.test(value) |
| | 924 | ? value |
| | 925 | : undefined; |
| | 926 | } |
| | 927 | |
| | 928 | function relayApiProjectionResponseFields(error: unknown) { |
| | 929 | if (typeof error !== "object" || error === null) { |
| | 930 | return {}; |
| | 931 | } |
| | 932 | const code = "code" in error ? safeRelayApiLogCode(error.code) : undefined; |
| | 933 | const reason = "reason" in error ? safeRelayApiLogCode(error.reason) : undefined; |
| | 934 | return { |
| | 935 | ...(code === undefined ? {} : { responseCode: code }), |
| | 936 | ...(reason === undefined ? {} : { responseReason: reason }), |
| | 937 | }; |
| | 938 | } |
| | 939 | |
| | 940 | function logRelayApiProjection(cause: unknown, responseError: unknown, traceId: string) { |
| | 941 | return Effect.logError("relay API failure projected to wire response", Cause.fail(cause)).pipe( |
| | 942 | Effect.annotateLogs({ |
| | 943 | traceId, |
| | 944 | sourceErrorTag: relayApiErrorTag(cause), |
| | 945 | responseErrorTag: relayApiErrorTag(responseError), |
| | 946 | ...relayApiProjectionResponseFields(responseError), |
| | 947 | }), |
| | 948 | ); |
| | 949 | } |
| | 950 | |
| 904 | const RelayCommonPersistenceError = Schema.Union([ | 951 | const RelayCommonPersistenceError = Schema.Union([ |
| 905 | Devices.DeviceRegistrationPersistenceError, | 952 | Devices.DeviceRegistrationPersistenceError, |
| 906 | Devices.DeviceUnregistrationPersistenceError, | 953 | Devices.DeviceUnregistrationPersistenceError, |
| @@ -930,15 +977,16 @@ type MapRelayCommonApiError<E> = · 23 unmodified lines |
| 930 | | (Extract<E, HttpApiError.Unauthorized> extends never ? never : RelayAuthInvalidError) | 977 | | (Extract<E, HttpApiError.Unauthorized> extends never ? never : RelayAuthInvalidError) |
| 931 | | (Extract<E, RelayCommonPersistenceError> extends never ? never : RelayInternalError); | 978 | | (Extract<E, RelayCommonPersistenceError> extends never ? never : RelayInternalError); |
| 932 | | 979 | |
| 933 | function relayInternalErrorResponse(reason: RelayInternalError["reason"]) { | 980 | function relayInternalErrorResponse(reason: RelayInternalError["reason"], cause: unknown) { |
| 934 | return currentTraceId.pipe( | 981 | return Effect.gen(function* () { |
| 935 | Effect.flatMap((traceId) => | 982 | const traceId = yield* currentTraceId; |
| 936 | Effect.fail(new RelayInternalError({ code: "internal_error", reason, traceId })), | 983 | const responseError = new RelayInternalError({ code: "internal_error", reason, traceId }); |
| 937 | ), | 984 | yield* logRelayApiProjection(cause, responseError, traceId); |
| 938 | ); | 985 | return yield* responseError; |
| | 986 | }); |
| 939 | } | 987 | } |
| 940 | | 988 | |
| 941 | function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) { | 989 | export function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) { |
| 942 | const mapError = Effect.fnUntraced(function* <E>(error: E) { | 990 | const mapError = Effect.fnUntraced(function* <E>(error: E) { |
| 943 | const traceId = yield* currentTraceId; | 991 | const traceId = yield* currentTraceId; |
| 944 | if (isHttpUnauthorized(error)) { | 992 | if (isHttpUnauthorized(error)) { |
| @@ -951,13 +999,13 @@ function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) { · 6 unmodified lines |
| 951 | ); | 999 | ); |
| 952 | } | 1000 | } |
| 953 | if (isRelayCommonPersistenceError(error)) { | 1001 | if (isRelayCommonPersistenceError(error)) { |
| 954 | return yield* Effect.fail( | 1002 | const responseError = new RelayInternalError({ |
| 955 | new RelayInternalError({ | 1003 | code: "internal_error", |
| 956 | code: "internal_error", | 1004 | reason: "persistence_failed", |
| 957 | reason: "persistence_failed", | 1005 | traceId, |
| 958 | traceId, | 1006 | }); |
| 959 | }) as MapRelayCommonApiError<E>, | 1007 | yield* logRelayApiProjection(error, responseError, traceId); |
| 960 | ); | 1008 | return yield* Effect.fail(responseError as MapRelayCommonApiError<E>); |
| 961 | } | 1009 | } |
| 962 | | 1010 | |
| 963 | return yield* Effect.fail(error as MapRelayCommonApiError<E>); | 1011 | return yield* Effect.fail(error as MapRelayCommonApiError<E>); |
| @@ -989,7 +1037,19 @@ type CatchTagCases<E, Cases> = { · 25 unmodified lines |
| 989 | ) => Effect.Effect<never, MappedTagError<Cases>>; | 1037 | ) => Effect.Effect<never, MappedTagError<Cases>>; |
| 990 | } & (unknown extends E ? {} : { readonly [K in Exclude<keyof Cases, TaggedErrorTag<E>>]: never }); | 1038 | } & (unknown extends E ? {} : { readonly [K in Exclude<keyof Cases, TaggedErrorTag<E>>]: never }); |
| 991 | | 1039 | |
| 992 | function mapErrorTags< | 1040 | const relayApiProjectedFailureLogTags = new Set([ |
| | 1041 | "ManagedEndpointProvisioningNotConfigured", |
| | 1042 | "ManagedEndpointProvisioningFailed", |
| | 1043 | "EnvironmentLinkUpsertPersistenceError", |
| | 1044 | "EnvironmentCredentialCreatePersistenceError", |
| | 1045 | "DpopProofReplayPersistenceError", |
| | 1046 | "EnvironmentMintRequestFailed", |
| | 1047 | "EnvironmentMintRequestTimedOut", |
| | 1048 | "EnvironmentMintResponseInvalid", |
| | 1049 | "ApnsDeliveryQueueSendError", |
| | 1050 | ]); |
| | 1051 | |
| | 1052 | export function mapErrorTags< |
| 993 | E, | 1053 | E, |
| 994 | Cases extends MapErrorTagCases<E> & | 1054 | Cases extends MapErrorTagCases<E> & |
| 995 | (unknown extends E ? {} : { readonly [K in Exclude<keyof Cases, TaggedErrorTag<E>>]: never }), | 1055 | (unknown extends E ? {} : { readonly [K in Exclude<keyof Cases, TaggedErrorTag<E>>]: never }), |
| @@ -1000,7 +1060,15 @@ function mapErrorTags< · 4 unmodified lines |
| 1000 | (error: never, traceId: string) => MappedTagError<Cases> | 1060 | (error: never, traceId: string) => MappedTagError<Cases> |
| 1001 | >, | 1061 | >, |
| 1002 | (makeError) => (error: never) => | 1062 | (makeError) => (error: never) => |
| 1003 | currentTraceId.pipe(Effect.flatMap((traceId) => Effect.fail(makeError(error, traceId)))), | 1063 | currentTraceId.pipe( |
| | 1064 | Effect.flatMap((traceId) => { |
| | 1065 | const responseError = makeError(error, traceId); |
| | 1066 | const logProjection = relayApiProjectedFailureLogTags.has(relayApiErrorTag(error)) |
| | 1067 | ? logRelayApiProjection(error, responseError, traceId) |
| | 1068 | : Effect.void; |
| | 1069 | return logProjection.pipe(Effect.andThen(Effect.fail(responseError))); |
| | 1070 | }), |
| | 1071 | ), |
| 1004 | ) as CatchTagCases<E, Cases>; | 1072 | ) as CatchTagCases<E, Cases>; |
| 1005 | | 1073 | |
| 1006 | return <A, R>( | 1074 | return <A, R>( |