Skip to content

Broken JSON Schema resolution #1881

@jsumners

Description

@jsumners

🐛 Bug Report

When using a reference to a full schema definition, instead of to a sub resource of the referenced schema, Fastify's schema resolution incorrectly mutates the reference name. The result is that it cannot find the referenced schema.

To Reproduce

Steps to reproduce the behavior:

Paste your code here:

'use strict';

const AJV = require('ajv');
const ajv = new AJV();

ajv.addSchema({
  $id: 'urn:schema:foo',
  definitions: {
    foo: { type: 'string' }
  },

  type: 'object',
  properties: {
    foo: { $ref: '#/definitions/foo' }
  }
});

ajv.addSchema({
  $id: 'urn:schema:response',
  type: 'object',
  properties: {
    bar: { $ref: 'urn:schema:foo' }
  }
});

const fastify = require('fastify')();
fastify.setSchemaCompiler(schema => ajv.compile(schema));
fastify.setSchemaResolver(name => ajv.getSchema(name).schema);

fastify.route({
  path: '/',
  method: 'GET',
  schema: {
    response: {
      '2xx': ajv.getSchema('urn:schema:response').schema
    }
  },
  handler(req, reply) {
    reply.send({ bar: { foo: 'bar' } });
  }
});

fastify.inject({ url: '/' }, (err, response) => {
  if (err) {
    throw err;
  }
  console.log(response.body);
});

Expected behavior

The urn:schema:foo reference should resolve to an object schema.

Cause

const refId = refValue.slice(0, refValue.indexOf('#'))

Notice that on this line the value of refValue will be 'urn:schema:foo'. Since this string does not have a # character, the line will execute refValue.slice(0, -1) which will yield 'urn:schema:fo'.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugConfirmed bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions