Incorrect suffix check¶
ID: js/incorrect-suffix-checkKind: problemSecurity severity: 7.8Severity: errorPrecision: highTags: - security - correctness - external/cwe/cwe-020Query suites: - javascript-code-scanning.qls - javascript-security-extended.qls - javascript-security-and-quality.qls
Click to see the query in the CodeQL repository
TheindexOf andlastIndexOf methods are sometimes used to check if a substring occurs at a certain position in a string. However, if the returned index is compared to an expression that might evaluate to -1, the check may pass in some cases where the substring was not found at all.
Specifically, this can easily happen when implementingendsWith usingindexOf.
Recommendation¶
UseString.prototype.endsWith if it is available. Otherwise, explicitly handle the -1 case, either by checking the relative lengths of the strings, or by checking if the returned index is -1.
Example¶
The following example useslastIndexOf to determine if the stringx ends with the stringy:
functionendsWith(x,y){returnx.lastIndexOf(y)===x.length-y.length;}
However, ify is one character longer thanx, the right-hand sidex.length-y.length becomes -1, which then equals the return value oflastIndexOf. This will make the test pass, even thoughx does not end withy.
To avoid this, explicitly check for the -1 case:
functionendsWith(x,y){letindex=x.lastIndexOf(y);returnindex!==-1&&index===x.length-y.length;}
References¶
Common Weakness Enumeration:CWE-20.