Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: validate entire array and not single elements #1280

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
"prepublishOnly": "tsc",
"postpublish": "npm run docs:publish",
"test": "jest",
"lint": "eslint --ignore-path .gitignore 'src/**/*.ts' && prettier -c ."
"lint": "eslint --ignore-path .gitignore 'src/**/*.ts' && prettier -c .",
"prettier": "prettier -w ."
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit 🤓

Suggested change
"prettier": "prettier -w ."
"lint:fix": "prettier -w ."

Then the equivalent command from eslint can be added too, if you like.

},
"engines": {
"node": ">= 8.0.0"
Expand Down
8 changes: 3 additions & 5 deletions src/context-items/standard-validation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,11 @@ it('calls the validator with the stringified value of non-array field', async ()
expect(validator).toHaveBeenCalledWith('hey');
});

it('calls the validator for each item in array field', async () => {
it('calls the validator with the stringified array value if an array is passed', async () => {
toString.mockImplementation(val => `hey${val}`);
await validation.run(context, [1, 42], meta);
expect(toString).toHaveBeenNthCalledWith(1, 1);
expect(validator).toHaveBeenNthCalledWith(1, 'hey1');
expect(toString).toHaveBeenNthCalledWith(2, 42);
expect(validator).toHaveBeenNthCalledWith(2, 'hey42');
expect(toString).toHaveBeenNthCalledWith(1, [1, 42]);
expect(validator).toHaveBeenNthCalledWith(1, 'hey1,42');
});

it('calls the validator with the value and options', async () => {
Expand Down
11 changes: 4 additions & 7 deletions src/context-items/standard-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,9 @@ export class StandardValidation implements ContextItem {
) {}

async run(context: Context, value: any, meta: Meta) {
const values = Array.isArray(value) ? value : [value];
values.forEach(value => {
const result = this.validator(this.stringify(value), ...this.options);
if (this.negated ? result : !result) {
context.addError({ type: 'field', message: this.message, value, meta });
}
});
const result = this.validator(this.stringify(value), ...this.options);
if (this.negated ? result : !result) {
context.addError({ type: 'field', message: this.message, value, meta });
}
}
}
34 changes: 34 additions & 0 deletions src/express-validator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,37 @@ describe('ExpressValidator', () => {
});
});
});

describe('High level tests', () => {
const { body } = new ExpressValidator();
it('should error when .exists() is used on a nested field of a primitive', async () => {
const req = { body: { foo: 'hello' } };
const result = await body('foo.nop').exists().run(req);
expect(result.isEmpty()).toEqual(false);
});
it('should not error when .not().exists() is used on a nested field of a primitive', async () => {
const req = { body: { foo: 'hello' } };
const result = await body('foo.nop').not().exists().run(req);
expect(result.isEmpty()).toEqual(true);
});
it('should not error when .exists() is used on a nested field of a primitive using wildcard', async () => {
const req = { body: { foo: 'hello' } };
const result = await body('foo.*.nop').exists().run(req);
expect(result.isEmpty()).toEqual(true);
});
it('should error array if no wildcard is used', async () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar feeling to #1279 (comment).

const req = { body: { foo: ['a', 'b', 'd', 'c'] } };
const result = await body('foo').isIn(['a', 'd', 'b', 'c']).run(req);
expect(result.isEmpty()).toEqual(false);
});
it('should not error array if wildcard is used', async () => {
const req = { body: { foo: ['a', 'b', 'd', 'c'] } };
const result = await body('foo.*').isIn(['a', 'd', 'b', 'c']).run(req);
expect(result.isEmpty()).toEqual(true);
});
it('should error if only the first item matches', async () => {
const req = { body: { foo: ['a', 'b', 'd', 'c'] } };
const result = await body('foo').equals('a').run(req);
expect(result.array().length).toEqual(1);
});
});
35 changes: 26 additions & 9 deletions src/field-selection.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,16 @@ describe('selectFields()', () => {
const instances = selectFields(req, ['foo', 'baz'], ['cookies']);

expect(instances).toHaveLength(2);
expect(instances[0]).toMatchObject({
expect(instances[0]).toEqual({
location: 'cookies',
path: 'foo',
originalPath: 'foo',
value: 'bar',
});
expect(instances[1]).toMatchObject({
expect(instances[1]).toEqual({
location: 'cookies',
path: 'baz',
originalPath: 'baz',
value: 'qux',
});
});
Expand Down Expand Up @@ -113,14 +115,19 @@ describe('selectFields()', () => {
const req = {
query: { foo: ['bar', 'baz'] },
};
const instances = selectFields(req, ['foo[1]'], ['query']);
const instances = selectFields(req, ['foo[1]', 'foo[2]'], ['query']);

expect(instances).toHaveLength(1);
expect(instances).toHaveLength(2);
expect(instances[0]).toMatchObject({
location: 'query',
path: 'foo[1]',
value: 'baz',
});
expect(instances[1]).toMatchObject({
location: 'query',
path: 'foo[2]',
value: undefined,
});
});

it('selects from headers using lowercase', () => {
Expand Down Expand Up @@ -154,7 +161,7 @@ describe('selectFields()', () => {
});

it('selects inexistent properties', () => {
const instances = selectFields({}, ['foo.bar.baz'], ['cookies']);
const instances = selectFields({ cookies: {} }, ['foo.bar.baz'], ['cookies']);

expect(instances).toHaveLength(1);
expect(instances[0]).toEqual({
Expand All @@ -165,14 +172,24 @@ describe('selectFields()', () => {
});
});

it('does not select properties of primitives', () => {
it('selects properties of primitives', () => {
const req = {
body: { foo: 1 },
};
const instances = selectFields(req, ['foo.toFixed'], ['body']);
expect(instances).toHaveLength(0);
});
const instances = selectFields(req, ['foo.toFixed', 'foo.nop'], ['body']);

expect(instances).toHaveLength(2);
expect(instances[0]).toMatchObject({
location: 'body',
path: 'foo.toFixed',
value: expect.any(Function),
});
expect(instances[1]).toMatchObject({
location: 'body',
path: 'foo.nop',
value: undefined,
});
});
it('deduplicates field instances', () => {
const req = {
body: {
Expand Down
18 changes: 12 additions & 6 deletions src/field-selection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,19 @@ function expandPath(object: any, path: string | string[], currPath: readonly str
const rest = segments.slice(1);

if (object != null && !_.isObjectLike(object)) {
if (key === '**' && !rest.length) {
// globstar leaves are always selected
return [reconstructFieldPath(currPath)];
if (key === '**') {
if (!rest.length) {
// globstar leaves are always selected
return [reconstructFieldPath(currPath)];
}
return [];
}

// there still are paths to traverse, but value is a primitive, stop
return [];
if (key === '*') {
// wildcard position does not exist
return [];
}
// value is a primitive, there are still still paths to traverse that will be likely undefined, we return the entire path
return [reconstructFieldPath([...currPath, ...segments])];
}

// Use a non-null value so that inexistent fields are still selected
Expand Down
Loading