Skip to content

Joi.validate() returns default object reference instead of clone #773

@tnunes

Description

@tnunes

Hi,

Apparently, Joi is returning a reference to the original default object declared in a schema, allowing schema mutation by validation results consumers, which can result in nasty, hard to find bugs.

var schema = Joi.object().default({ key: 'original_value' });

var firstResult = Joi.validate(undefined, schema);
console.log(firstResult);   // <- { error: null, value: { key: 'original_value' } }

firstResult.value.key = 'mutated_value';

var secondResult = Joi.validate(undefined, schema);
console.log(secondResult);  // <- { error: null, value: { key: 'mutated_value' } }

As shown in the code snippet, various calls to validate() that cause a default value to be returned, return the original object, instead of a copy of it.

This can be confirmed by checking that the schema._flags.default property is indeed mutated after the firstResult.value.key = 'mutated_value'; statement.

I'm not sure if this is by design (performance reasons?) or if it's a bug, but either way it allows a validation schema to be changed by any code that consumes the resulting object.

I believe validate() should always return a copy of the default object, therefore preventing unintended changes to the original schema.

Metadata

Metadata

Assignees

Labels

bugBug or defect

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions