Skip to content

httpapi: a handler result that fails its own success schema answers 400 Bad Request, and since 4.0.1 is not reported #8823

Closed

Description

@aniravi24

What happens

When a handler succeeds with a value that does not encode with the endpoint's declared success schema, HttpApiBuilder answers 400 Bad Request with an empty body. That failure is a server bug (the server broke its own contract), but the client is told its request was bad.

Since 4.0.1 the failure also reaches no ErrorReporter. #8706 (closing #8696) added [ErrorReporter.ignore] = true to HttpApiSchemaError, which is right for invalid requests. Response encoding failures are wrapped in the same class, so they are now ignored too. On 4.0.0 they still answered 400 but were at least reported.

This is a follow-up to #8696 / #8706, not a request to revert them: request decoding failures should stay 400 and unreported.

Why

packages/effect/src/http-api/HttpApiBuilder.ts, handlerToHttpEffect (main) wraps response encoding in HttpApiSchemaError, the same class used for Params, Headers, Query and Payload decoding (L865-L882):

const encoded = yield* HttpApiSchemaError.wrap(
  "Body",
  encodeStream?.(response, context) ??
    (responseHeaders !== undefined ? encodeWithHeaders!.encodeBody(response) : encodeSuccess(response))
)
if (encodeWithHeaders === undefined || responseHeaders === undefined) return encoded
const encodedHeaders = yield* HttpApiSchemaError.wrap(
  "ResponseHeaders",
  encodeWithHeaders.encodeHeaders.get(encoded.status)!(responseHeaders)
)

HttpApiSchemaError is ignored by reporters and always responds 400 (HttpApiError.ts):

readonly [ErrorReporter.ignore] = true
// ...
[HttpServerRespondable.symbol]() {
  return Effect.succeed(badRequestResponse)
}

Encoding a declared error that fails its schema already takes the other path, Effect.orDie(encodeError(error)) (L908), so only the success path is affected.

Because the encoding runs inside applyMiddleware, HttpApiMiddleware.layerSchemaErrorTransform (HttpApiMiddleware.ts) also receives these Body / ResponseHeaders errors. An app that maps schema errors to a detailed 4xx response sends the server's own encoding failure to the client as a validation error.

Reproduction

Uses only public APIs. /by-age?age=abc is a real client error (query fails FiniteFromString). /me is a server bug: the handler returns { age: "42" } (e.g. from an untyped source) for a { age: Number } success schema.

bun add [email protected]
bun repro.ts
repro.ts
import { Effect, ErrorReporter, Layer, Schema } from "effect"
import { HttpRouter, HttpServer } from "effect/http"
import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from "effect/http-api"

const Api = HttpApi.make("api").add(
  HttpApiGroup.make("users").add(
    // Client error: the request does not match the declared query schema.
    HttpApiEndpoint.get("byAge", "/by-age", {
      query: { age: Schema.FiniteFromString },
      success: Schema.Struct({ age: Schema.Number })
    }),
    // Server bug: the handler's success value does not match the declared success schema.
    HttpApiEndpoint.get("me", "/me", {
      success: Schema.Struct({ age: Schema.Number })
    })
  )
)

const UsersLive = HttpApiBuilder.group(Api, "users", (handlers) =>
  handlers
    .handle("byAge", ({ query }) => Effect.succeed({ age: query.age }))
    // e.g. a row from an untyped source where `age` came back as a string
    .handle("me", () => Effect.succeed(JSON.parse(`{ "age": "42" }`))))

const reports: Array<string> = []
const Reporter = ErrorReporter.layer([
  ErrorReporter.make(({ error }) => {
    reports.push(`${error.name}: ${error.message.split("\n")[0]}`)
  })
])

const { handler, dispose } = HttpRouter.toWebHandler(
  HttpApiBuilder.layer(Api).pipe(
    Layer.provide(UsersLive),
    Layer.provide(HttpServer.layerServices),
    Layer.provide(Reporter)
  ),
  { disableLogger: true }
)

for (const path of ["/by-age?age=abc", "/me"]) {
  reports.length = 0
  const response = await handler(new Request(`http://localhost${path}`))
  console.log(`GET ${path} -> ${response.status}, reported: ${JSON.stringify(reports)}`)
}

await dispose()

Output on [email protected]:

GET /by-age?age=abc -> 400, reported: []
GET /me -> 400, reported: []

Same script on [email protected] (before #8706):

GET /by-age?age=abc -> 400, reported: ["HttpApiSchemaError: Query"]
GET /me -> 400, reported: ["HttpApiSchemaError: Body"]

The /by-age line is what #8696 fixed. The /me line is the problem here: expected a 500 and a report.

Suggested fix

Treat response encoding failures as defects, the same way the declared-error path does, instead of wrapping them in HttpApiSchemaError:

-      const encoded = yield* HttpApiSchemaError.wrap(
-        "Body",
+      const encoded = yield* Effect.orDie(
         encodeStream?.(response, context) ??
           (responseHeaders !== undefined ? encodeWithHeaders!.encodeBody(response) : encodeSuccess(response))
       )
       if (encodeWithHeaders === undefined || responseHeaders === undefined) return encoded
-      const encodedHeaders = yield* HttpApiSchemaError.wrap(
-        "ResponseHeaders",
+      const encodedHeaders = yield* Effect.orDie(
         encodeWithHeaders.encodeHeaders.get(encoded.status)!(responseHeaders)
       )

The SchemaError defect is not marked ignored, so Effect.withErrorReporting (already applied right after) reports it, and the server answers 500. HttpApiSchemaError then only covers request decoding, which matches the module doc ("HttpApiSchemaError for request decoding failures"), and layerSchemaErrorTransform no longer sees server-side failures. The "Body" and "ResponseHeaders" members of kind would become unused, and the class doc ("request or response component") would need the matching edit; whether to drop the two kinds is your call.

With the same two-line change applied to node_modules/effect/dist/http-api/HttpApiBuilder.js from 4.0.1, the repro prints:

GET /by-age?age=abc -> 400, reported: []
GET /me -> 500, reported: ["SchemaError: Expected number"]

An alternative that keeps a single error class: make [ErrorReporter.ignore] and the respondable depend on kind (not ignored and 500 for Body / ResponseHeaders). That leaves response failures visible to layerSchemaErrorTransform, so I'd lean towards the orDie change.

Environment

  • effect 4.0.1. HttpApiBuilder.ts and HttpApiError.ts in the published package's src are identical to main at bd00773.
  • Bun 1.4.2; the repro typechecks with TypeScript 7.0.2

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions