From ed25e95c299190e9aace62569d4b8306b2d8e614 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Fern=C3=A1ndez=20Haro?= Date: Wed, 19 Jun 2024 11:19:38 +0200 Subject: [PATCH] `strictUnknown` should honor local explicit `.unknown(false)` (#3037) --- lib/types/keys.js | 4 +-- test/index.js | 67 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/lib/types/keys.js b/lib/types/keys.js index de039a5c..baa85fe7 100755 --- a/lib/types/keys.js +++ b/lib/types/keys.js @@ -31,7 +31,7 @@ module.exports = Any.extend({ flags: { - unknown: { default: false } + unknown: { default: undefined } }, terms: { @@ -972,7 +972,7 @@ internals.unknown = function (schema, value, unprocessed, errors, state, prefs) return; } - if (prefs.stripUnknown && !schema._flags.unknown || + if (prefs.stripUnknown && typeof schema._flags.unknown === 'undefined' || prefs.skipFunctions) { const stripUnknown = prefs.stripUnknown ? (prefs.stripUnknown === true ? true : !!prefs.stripUnknown.objects) : false; diff --git a/test/index.js b/test/index.js index 2f4e46b4..6c2244aa 100755 --- a/test/index.js +++ b/test/index.js @@ -635,6 +635,73 @@ describe('Joi', () => { Helper.validate(schema, { stripUnknown: { arrays: false, objects: true }, allowUnknown: true }, [[obj, true, { a: 1, b: 'a' }]]); }); + it('validates enforces local behavior of unknown(true) when stripUnknown is set', () => { + + const schema = Joi.object({ + a: Joi.number().min(0).max(3), + loosyObject: Joi.object({ + b1: Joi.string() + }).unknown(true), // allows extra keys + anotherLoosyObject: Joi.object({ + c1: Joi.string() + }).unknown() // also allows extra keys + }); + + const obj = { + a: 1, + loosyObject: { + b1: 'c1', + b2: 'c2' + }, + anotherLoosyObject: { + c1: 'c1', + c2: 'c2' + } + }; + + Helper.validate(schema, { stripUnknown: true }, [[obj, true, { + a: 1, + loosyObject: { + b1: 'c1', + b2: 'c2' + }, + anotherLoosyObject: { + c1: 'c1', + c2: 'c2' + } + }]]); + }); + + it('validates enforces local behavior of unknown(false) when stripUnknown is set', () => { + + const schema = Joi.object({ + a: Joi.number().min(0).max(3), + strictObject: Joi.object({ + b1: Joi.string() + }).unknown(false) // it shouldn't allow extra keys + }); + + const obj = { + a: 1, + strictObject: { + b1: 'b1', + b2: 'b2' + } + }; + + Helper.validate(schema, { stripUnknown: true }, [[obj, false, { + message: '"strictObject.b2" is not allowed', + path: ['strictObject', 'b2'], + type: 'object.unknown', + context: { + child: 'b2', + label: 'strictObject.b2', + key: 'b2', + value: 'b2' + } + }]]); + }); + it('validates dependencies when stripUnknown is set', () => { const schema = Joi.object({