Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/strip-proto-validation-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'formik': patch
---

Strip own `__proto__` keys from validation errors before merging them, so an error object created with `JSON.parse` can no longer replace the prototype of the merged `errors`.
62 changes: 61 additions & 1 deletion packages/formik/src/Formik.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,9 @@ export function useFormik<Values extends FormikValues = FormikValues>({
props.validate ? runValidateHandler(values) : {},
]).then(([fieldErrors, schemaErrors, validateErrors]) => {
const combinedErrors = deepmerge.all<FormikErrors<Values>>(
[fieldErrors, schemaErrors, validateErrors],
[fieldErrors, schemaErrors, validateErrors].map(
stripUnsafeErrorKeys
),
{ arrayMerge }
);
return combinedErrors;
Expand Down Expand Up @@ -1119,6 +1121,64 @@ export function prepareDataForValidation<T extends FormikValues>(
return data;
}

/**
* Returns `errors` without any own `__proto__` keys (at any depth of plain
* objects and arrays).
*
* Objects created with `JSON.parse` (or `Object.defineProperty`) can carry an
* own `__proto__` key. deepmerge assigns every source key onto the merged
* result, so such a key would replace the prototype of the merged errors object
* instead of being copied as data, letting inherited "errors" appear on fields
* that were never reported. The input is returned as-is when it has no such key.
*/
function stripUnsafeErrorKeys<T>(errors: T): T {
if (Array.isArray(errors)) {
let copy: any[] | undefined;
errors.forEach((item, index) => {
const safeItem = stripUnsafeErrorKeys(item);
if (safeItem !== item) {
copy = copy || errors.slice();
copy[index] = safeItem;
}
});
return (copy || errors) as any;
}

if (!isPlainErrorObject(errors)) {
return errors;
}

const source = errors as any;
// built key by key so that `__proto__` is never assigned
const copy: any = {};
let changed = false;
Object.keys(source).forEach(key => {
if (key === '__proto__') {
changed = true;
return;
}
const value = source[key];
const safeValue = stripUnsafeErrorKeys(value);
if (safeValue !== value) {
changed = true;
}
copy[key] = safeValue;
});
return changed ? copy : errors;
}

function isPlainErrorObject(value: any): boolean {
if (value === null || typeof value !== 'object') {
return false;
}
// leave React elements (valid error messages) and class instances untouched
if (value.$$typeof !== undefined) {
return false;
}
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}

/**
* deepmerge array merging algorithm
* https://github.com/KyleAMathews/deepmerge#combine-array
Expand Down
54 changes: 54 additions & 0 deletions packages/formik/test/Formik.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1487,6 +1487,60 @@ describe('<Formik>', () => {
});
});

it('should not let a `__proto__` key in validation errors replace the prototype of the merged errors', async () => {
const validate = () =>
JSON.parse(
'{"__proto__": {"name": "poisoned", "isAdmin": true}, "age": "required"}'
);

const { getProps } = renderFormik({ validate });

await act(async () => {
await getProps().validateForm();
});

const errors = getProps().errors as any;
expect(Object.getPrototypeOf(errors)).toBe(Object.prototype);
expect(errors.name).toBeUndefined();
expect(errors.isAdmin).toBeUndefined();
expect(errors).toEqual({ age: 'required' });
expect(({} as any).isAdmin).toBeUndefined();
});

it('should strip nested `__proto__` keys while keeping merged validation errors', async () => {
const validate = () =>
JSON.parse(
'{"users": [{"firstName": "required", "__proto__": {"lastName": "poisoned"}}], "meta": {"__proto__": {"x": 1}, "y": "bad"}}'
);

const validationSchema = Yup.object({
users: Yup.array().of(
Yup.object({
lastName: Yup.string().required('required'),
})
),
});

const { getProps } = renderFormik({
initialValues: { users: [{ firstName: '', lastName: '' }] } as any,
validate,
validationSchema,
});

await act(async () => {
await getProps().validateForm();
});

const errors = getProps().errors as any;
expect(errors).toEqual({
users: [{ firstName: 'required', lastName: 'required' }],
meta: { y: 'bad' },
});
expect(Object.getPrototypeOf(errors.users[0])).toBe(Object.prototype);
expect(Object.getPrototypeOf(errors.meta)).toBe(Object.prototype);
expect(errors.meta.x).toBeUndefined();
});

it('should not eat an error thrown by the validationSchema', async () => {
const validationSchema = () => {
throw new Error('broken validations');
Expand Down