Skip to content

Commit

Permalink
fix(interpreter): ensure regexp correctly works with null & `unde…
Browse files Browse the repository at this point in the history
…fined` values (#14)

* fix(js/interpreters): prevent regex() from returning true when value is undefined

if key is not defined or if value is undefined, the regex should not evaluate it because it can lead
to false positive.
The undefined type is evaluated as a string 'undefined',\i undefined should be
evaluated with the "exist" operator

* test(js/intepreters.spec): regex: add test for undefined values

Co-authored-by: Jérémy <jeremy.huard@doeo.fr>
Co-authored-by: Sergii <sergiy.stotskiy@gmail.com>
  • Loading branch information
3 people committed Aug 25, 2020
1 parent ee007d0 commit 061e5b0
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
9 changes: 9 additions & 0 deletions packages/js/spec/interpreters.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,15 @@ describe('Condition Interpreter', () => {
expect(interpret(condition, item('ucast@github.com'))).to.be.true
expect(interpret(condition, item('some text'))).to.be.false
})

it('return false if key is `undefined` or `null`', () => {
const condition = new Field('regex', 'email', /i/)

expect(interpret(condition, { email: 'ucast@github.com', })).to.be.true
expect(interpret(condition, { email: undefined, })).to.be.false
expect(interpret(condition, { email: null, })).to.be.false
expect(interpret(condition, {})).to.be.false
})
})

describe('where', () => {
Expand Down
6 changes: 4 additions & 2 deletions packages/js/src/interpreters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export const exists: Interpret<Field<boolean>> = (node, object, { get }) => {
};

export const mod = testValueOrArray<[number, number], number>((node, value) => {
return value % node.value[0] === node.value[1];
return typeof value === 'number' && value % node.value[0] === node.value[1];
});

export const size: Interpret<Field<number>, AnyObject | unknown[]> = (node, object, { get }) => {
Expand All @@ -88,7 +88,9 @@ export const size: Interpret<Field<number>, AnyObject | unknown[]> = (node, obje
: test(items);
};

export const regex = testValueOrArray<RegExp, string>((node, value) => node.value.test(value));
export const regex = testValueOrArray<RegExp, string>((node, value) => {
return typeof value === 'string' && node.value.test(value);
});

export const within = testValueOrArray<unknown[], unknown>((node, object, { equal }) => {
return includes(node.value, object, equal);
Expand Down

0 comments on commit 061e5b0

Please sign in to comment.