|
| 1 | +import { describe, it, expect } from '@jest/globals'; |
| 2 | +import shallowCopy from '../../src/utils/shallowCopy'; |
| 3 | + |
| 4 | +describe('shallowCopy', () => { |
| 5 | + it('copies a plain object', () => { |
| 6 | + const obj = { a: 1, b: 2 }; |
| 7 | + const copy = shallowCopy(obj); |
| 8 | + expect(copy).toEqual({ a: 1, b: 2 }); |
| 9 | + expect(copy).not.toBe(obj); |
| 10 | + }); |
| 11 | + |
| 12 | + it('copies an array', () => { |
| 13 | + const arr = [1, 2, 3]; |
| 14 | + const copy = shallowCopy(arr); |
| 15 | + expect(copy).toEqual([1, 2, 3]); |
| 16 | + expect(copy).not.toBe(arr); |
| 17 | + }); |
| 18 | + |
| 19 | + it('should not propagate __proto__ key from source object', () => { |
| 20 | + type User = { user: string; admin?: boolean }; |
| 21 | + |
| 22 | + // @ts-expect-error -- testing prototype pollution |
| 23 | + delete Object.prototype.admin; |
| 24 | + |
| 25 | + // JSON.parse creates an own property named "__proto__" (not the actual prototype) |
| 26 | + const malicious = JSON.parse('{"user":"Eve","__proto__":{"admin":true}}'); |
| 27 | + |
| 28 | + const copy = shallowCopy(malicious); |
| 29 | + |
| 30 | + // The copy should NOT have admin on its prototype chain |
| 31 | + expect((copy as User).admin).toBeUndefined(); |
| 32 | + |
| 33 | + // Global Object prototype should NOT be polluted |
| 34 | + expect(({} as User).admin).toBeUndefined(); |
| 35 | + |
| 36 | + // @ts-expect-error -- cleanup |
| 37 | + delete Object.prototype.admin; |
| 38 | + }); |
| 39 | + |
| 40 | + it('should not propagate constructor key from source object', () => { |
| 41 | + type User = { user: string; admin?: boolean }; |
| 42 | + |
| 43 | + const malicious: User = { |
| 44 | + user: 'Eve', |
| 45 | + // @ts-expect-error -- intentionally setting constructor to test pollution |
| 46 | + constructor: { prototype: { admin: true } }, |
| 47 | + }; |
| 48 | + |
| 49 | + const copy = shallowCopy(malicious); |
| 50 | + |
| 51 | + expect((copy as User).admin).toBeUndefined(); |
| 52 | + |
| 53 | + // The constructor of a plain new object should still be Object |
| 54 | + expect({}.constructor).toBe(Object); |
| 55 | + }); |
| 56 | +}); |
0 commit comments