From 734ae8695c2579b22376af92bc02aa4a501dfc85 Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Tue, 1 Oct 2024 14:43:45 +0100 Subject: [PATCH] updating to throw error --- .../src/set_nested_property.test.ts | 16 +++++++++------- .../nested_property/src/set_nested_property.ts | 8 +++++++- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/x-pack/packages/ml/nested_property/src/set_nested_property.test.ts b/x-pack/packages/ml/nested_property/src/set_nested_property.test.ts index eb28202d7672d..963b0611197db 100644 --- a/x-pack/packages/ml/nested_property/src/set_nested_property.test.ts +++ b/x-pack/packages/ml/nested_property/src/set_nested_property.test.ts @@ -69,12 +69,14 @@ describe('object_utils', () => { const test11 = setNestedProperty(getFalseyObject(), 'the.other_nested.value', 'update'); expect(test11.the.other_nested.value).toBe('update'); - const test12 = setNestedProperty(getTestObj(), 'the.__proto__', 'update'); - expect(test12.the).toBe('update'); - expect(test12.the.__proto__.update).toBe(undefined); - - const test13 = setNestedProperty(getTestObj(), 'the.prototype', 'update'); - expect(test13.the).toBe('update'); - expect(test13.the.prototype?.update).toBe(undefined); + expect(() => { + setNestedProperty(getTestObj(), 'the.__proto__', 'update'); + }).toThrow('Invalid accessor'); + expect(() => { + setNestedProperty(getTestObj(), 'the.prototype', 'update'); + }).toThrow('Invalid accessor'); + expect(() => { + setNestedProperty(getTestObj(), 'the.constructor', 'update'); + }).toThrow('Invalid accessor'); }); }); diff --git a/x-pack/packages/ml/nested_property/src/set_nested_property.ts b/x-pack/packages/ml/nested_property/src/set_nested_property.ts index cd760fa638d1d..6c692cb3a0a08 100644 --- a/x-pack/packages/ml/nested_property/src/set_nested_property.ts +++ b/x-pack/packages/ml/nested_property/src/set_nested_property.ts @@ -5,9 +5,15 @@ * 2.0. */ +const INVALID_ACCESSORS = ['__proto__', 'prototype', 'constructor']; + export const setNestedProperty = (obj: Record, accessor: string, value: any) => { let ref = obj; - const accessors = accessor.split('.').filter((a) => a !== '__proto__' && a !== 'prototype'); + const accessors = accessor.split('.'); + if (accessors.some((a) => INVALID_ACCESSORS.includes(a))) { + throw new Error('Invalid accessor'); + } + const len = accessors.length; for (let i = 0; i < len - 1; i++) { const attribute = accessors[i];