Skip to content

Commit 0c8be2d

Browse files
committed
Don't allow overwriting non-objects
1 parent d9c7cd8 commit 0c8be2d

File tree

3 files changed

+43
-6
lines changed

3 files changed

+43
-6
lines changed

packages/snaps-rpc-methods/jest.config.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ module.exports = deepmerge(baseConfig, {
1010
],
1111
coverageThreshold: {
1212
global: {
13-
branches: 93.28,
13+
branches: 93.33,
1414
functions: 97.46,
1515
lines: 98.03,
16-
statements: 97.61,
16+
statements: 97.62,
1717
},
1818
},
1919
});

packages/snaps-rpc-methods/src/permitted/setState.test.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,28 @@ describe('set', () => {
487487
});
488488
});
489489

490+
it('allows overwriting if a parent key is `null`', () => {
491+
const object = {
492+
nested: null,
493+
};
494+
495+
expect(set(object, 'nested.key', 'newValue')).toStrictEqual({
496+
nested: {
497+
key: 'newValue',
498+
},
499+
});
500+
});
501+
502+
it('throws if a parent key is not an object', () => {
503+
const object = {
504+
nested: 'value',
505+
};
506+
507+
expect(() => set(object, 'nested.key', 'newValue')).toThrow(
508+
'Invalid params: Cannot overwrite non-object value.',
509+
);
510+
});
511+
490512
it('throws an error if the key is a prototype pollution attempt', () => {
491513
expect(() => set({}, '__proto__.polluted', 'value')).toThrow(
492514
'Invalid params: Key contains forbidden characters.',

packages/snaps-rpc-methods/src/permitted/setState.ts

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,13 @@ import {
1212
StructError,
1313
} from '@metamask/superstruct';
1414
import type { PendingJsonRpcResponse, JsonRpcRequest } from '@metamask/utils';
15-
import { isObject, assert, JsonStruct, type Json } from '@metamask/utils';
15+
import {
16+
hasProperty,
17+
isObject,
18+
assert,
19+
JsonStruct,
20+
type Json,
21+
} from '@metamask/utils';
1622

1723
import { manageStateBuilder } from '../restricted/manageState';
1824
import type { MethodHooksObject } from '../utils';
@@ -239,9 +245,18 @@ export function set(
239245
return requiredObject;
240246
}
241247

242-
currentObject[currentKey] = isObject(currentObject[currentKey])
243-
? currentObject[currentKey]
244-
: {};
248+
if (
249+
!hasProperty(currentObject, currentKey) ||
250+
currentObject[currentKey] === null
251+
) {
252+
currentObject[currentKey] = {};
253+
}
254+
255+
if (!isObject(currentObject[currentKey])) {
256+
throw rpcErrors.invalidParams(
257+
'Invalid params: Cannot overwrite non-object value.',
258+
);
259+
}
245260

246261
currentObject = currentObject[currentKey] as Record<string, Json>;
247262
}

0 commit comments

Comments
 (0)