honojs / middleware

monorepo for Hono third-party middleware/helpers/wrappers
https://hono.dev
405 stars 139 forks source link

Unrecognized keys are sent in responses #587

Open MichailShcherbakov opened 2 months ago

MichailShcherbakov commented 2 months ago

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",
samjbobb commented 2 months ago

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 commented 2 months ago

The answer:

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

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

telcy commented 2 months ago

Would be great to have unrecognized keys stripped.