Invalid prototype value¶
ID: js/invalid-prototype-value
Kind: problem
Security severity:
Severity: error
Precision: high
Tags:
- correctness
- language-features
- external/cwe/cwe-704
Query suites:
- javascript-security-and-quality.qls
Click to see the query in the CodeQL repository
All JavaScript objects (including functions, classes and arrays) have a prototype, which is either null
or another object. The prototype of an object can be set in two ways, both of which guard against attempts to assign an invalid prototype (such as a primitive value):
Assigning a value to the object’s
__proto__
property; if the value is not a valid prototype, the assignment is silently ignored.Using the standard library functions
Object.create
orObject.setPrototypeOf
; invalid prototype values lead to a runtime error. In summary, any attempt to set the prototype of an object to a value that is not an object ornull
will be ineffective and may lead to a runtime error.
Recommendation¶
Fix the prototype assignment by providing a valid prototype value.
Example¶
The following code attempts to create an object with prototype undefined
, which will cause an error at runtime:
let dict = Object.create(undefined);
If the intention is to create an object without a prototype object, null
should be used instead:
let dict = Object.create(null);
References¶
Mozilla Developer Network: Inheritance and the prototype chain.
Common Weakness Enumeration: CWE-704.