middleware icon indicating copy to clipboard operation
middleware copied to clipboard

Unrecognized keys are sent in responses

Open radqut opened this issue 1 year ago • 4 comments

By default Zod object schemas strip out unrecognized keys during parsing. It works fine in requests, but it doesn't work in responses.

Example:

.openapi(
    createRoute({
      method: "post",
      path: "/test",
      responses: {
        201: {
          content: {
            "application/json": {
              schema: z.object({
                shouldBePassed: z.string(),
              }),
            },
          },
          description: "",
        },
      },
    }),
    async (c) => {
      return c.json({ shouldBePassed: "1", shouldNotBePassed: "2" }, 201);
    }
  )

The route returns the next reponse:

{
  "shouldBePassed": "1",
  "shouldNotBePassed": "2"
}

But the response should be:

{
  "shouldBePassed": "1"
}

Deps:

"hono": "4.4.7",
"@hono/zod-validator": "0.2.2",

radqut avatar Jun 20 '24 14:06 radqut

It appears to me that the response schema is not used for any type checking or run time parsing of the router return value. You can return anything from the router.

Am I missing anything?

If true, we’re missing an important check. One value of types on an API return value is to help prevent developers from accidentally returning extra, possibly sensitive data.

samjbobb avatar Jul 03 '24 03:07 samjbobb

The answer:

You are correct, Hono's Validator does not validate the response.

https://github.com/honojs/middleware/issues/181

samjbobb avatar Jul 03 '24 04:07 samjbobb

Would be great to have unrecognized keys stripped.

telcy avatar Jul 11 '24 13:07 telcy

Is this something that is still in the pipeline somewhere? Willing to help on this, though not very familiar with the Hono codebase yet.

dbrxnds avatar Apr 24 '25 13:04 dbrxnds