From 9a0f182fb204dae704d10a4067d0041a388989b0 Mon Sep 17 00:00:00 2001 From: Julian Simioni Date: Tue, 26 Jun 2018 17:57:02 -0400 Subject: [PATCH] fix(whitespace): Trim whitespace and quotes before checking text length Previously, our text sanitizer code did not trim whitespace before checking that the string was non-empty. This lead to strings consisting only of whitespace being treated as valid. Not all our downstream services (such as libpostal) accept whitespace-only input, so this causes a rather harsh error. This PR builds upon the code in https://github.com/pelias/api/pull/1170 and moves the trimming code above the nonEmptyString check. Now, a whitespace-only input string produces the normal error for empty input. Fixes https://github.com/pelias/api/issues/1158 --- sanitizer/_text.js | 7 ++++--- test/unit/sanitizer/_text.js | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/sanitizer/_text.js b/sanitizer/_text.js index cb4dc737..bae2d4a1 100644 --- a/sanitizer/_text.js +++ b/sanitizer/_text.js @@ -13,11 +13,12 @@ function _sanitize( raw, clean ){ // invalid input 'text' // must call `!check.nonEmptyString` since `check.emptyString` returns // `false` for `undefined` and `null` - if( !check.nonEmptyString( raw.text ) ){ - messages.errors.push('invalid param \'text\': text length, must be >0'); + const text = _.trim( _.trim( raw.text ), QUOTES ); + if( !check.nonEmptyString( text ) ){ + messages.errors.push('invalid param \'text\': text length, must be >0'); } else { - clean.text = _.trim( _.trim( raw.text ), QUOTES ); + clean.text = text; } return messages; diff --git a/test/unit/sanitizer/_text.js b/test/unit/sanitizer/_text.js index 7a35fbbe..6a368b41 100644 --- a/test/unit/sanitizer/_text.js +++ b/test/unit/sanitizer/_text.js @@ -124,6 +124,20 @@ module.exports.tests.text_parser = function(test, common) { t.deepEquals(validParameters, expected); t.end(); }); + + test('whitespace-only input counts as empty', (t) => { + const raw = { text: ' ' }; + const clean = {}; + + const expected_clean = {}; + + const messages = sanitizer.sanitize(raw, clean); + + t.deepEquals(clean, expected_clean); + t.deepEquals(messages.errors, ['invalid param \'text\': text length, must be >0']); + t.deepEquals(messages.warnings, [], 'no warnings'); + t.end(); + }); }; module.exports.all = (tape, common) => {