Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: chanfana assumes all instances of ZodError thrown from a route's handle method are 400 user request validation errors #166

Open
ilyasotkov opened this issue Aug 12, 2024 · 0 comments

Comments

@ilyasotkov
Copy link

Bug description: If a route's handle method throws a ZodError that's not coming from validateRequest, chanfana erroneously returns 400 to the user, also exposing the route's internal implementation details in the response body.

Desired behavior: only errors thrown from getValidatedData are assumed to be a user request validation error.

Example:

import { fromIttyRouter, OpenAPIRoute } from 'chanfana';
import { json, Router } from 'itty-router';
import { z } from 'zod';

const schema = z.object({ hello: z.string().default('world') });

export class MyRoute extends OpenAPIRoute {
  schema = {
    request: {
      body: {
        content: {
          'application/json': {
            schema,
          },
        },
      },
    },
    responses: {
      '201': {
        description: 'Return request body after validation',
        content: {
          'application/json': {
            schema,
          },
        },
      },
    },
  };

  async handle() {
    const data = await this.getValidatedData<typeof this.schema>();

    // Internal logic executed after successful user request validation
    const internalSchema = z.object({ internal: z.string().max(3) });
    internalSchema.parse({ internal: 'Highly senstive data' });

    return json(data.body);
  }
}

export default fromIttyRouter(Router()).post('/hello', MyRoute);

for all valid requests will always return 400 Bad Request

    {
      "errors": [
        {
          "code": "invalid_type",
          "expected": "string",
          "message": "Required",
          "path": [
            "internal",
          ],
          "received": "undefined",
        },
      ],
      "result": {},
      "success": false,
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant