Skip to content

JSON schema validation is called for application/octet-stream #1012

@nflaig

Description

@nflaig

As per fasitfy docs schema validation should only be called if body is application/json

Validation will only be attempted if the content type is application-json, as described in the documentation for the content type parser.

My server is configured like this

const server = fastify({
    ajv: {customOptions: {coerceTypes: "array"}},
    querystringParser: (str) => parseQueryString(str, {comma: true, parseArrays: false}),
});

server.addContentTypeParser(
  "application/octet-stream",
  {parseAs: "buffer"},
  async (_request: FastifyRequest, payload: Buffer) => {
    // This is called
    console.log(payload) // <Buffer 00 00 00 00 00 00 00 00 00 00 00 00 ... >
    return payload;
  }
);

The schema is really simple

schema: {
   body: {type: "array"}
}

I can confirm that my content type parser is called correctly but I am still getting a schema validation error

Error: body must be array
    at defaultSchemaErrorFormatter (.../node_modules/fastify/lib/context.js:108:10)
    at wrapValidationError (.../node_modules/fastify/lib/validation.js:228:17)
    at validate (.../node_modules/fastify/lib/validation.js:146:16)
    at preValidationCallback (.../node_modules/fastify/lib/handleRequest.js:92:25)
    at handler (.../node_modules/fastify/lib/handleRequest.js:76:7)
    at .../node_modules/fastify/lib/contentTypeParser.js:192:9
    at AsyncResource.runInAsyncScope (node:async_hooks:206:9)
    at done (.../node_modules/fastify/lib/contentTypeParser.js:186:14)
    at /.../node_modules/fastify/lib/contentTypeParser.js:275:27
    at processTicksAndRejections (node:internal/process/task_queues:95:5) {
  statusCode: 400,
  code: 'FST_ERR_VALIDATION',
  validation: [
    {
      instancePath: '',
      schemaPath: '#/type',
      keyword: 'type',
      params: [Object],
      message: 'must be array'
    }
  ],
  validationContext: 'body'
}

As per docs I would expect that JSON schema validation is skipped for non JSON bodies.

Let me know if I am just misreading what the docs are saying and if anyone has an idea how to work around this any hint would be appreciated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions