Skip to content

fix Incorrect suffix check #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

odaysec
Copy link

@odaysec odaysec commented May 5, 2025

if (path.indexOf('.css') == path.length - 4) {

fix the issue, replace the indexOf-based suffix check with a more robust approach. The best solution is to use String.prototype.endsWith, which is specifically designed for this purpose and avoids the pitfalls of indexOf. If endsWith is not available in the runtime environment, explicitly handle the -1 case by checking the relative lengths of the strings.

In this case, we will replace path.indexOf('.css') == path.length - 4 with path.endsWith('.css'). This change ensures that the code correctly identifies whether path ends with .css without relying on potentially error-prone calculations.

The indexOf and lastIndexOf 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 implementing endsWith using indexOf.

Recommendation

Use String.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.

POC

The following uses lastIndexOf to determine if the string x ends with the string y:

function endsWith(x, y) {
  return x.lastIndexOf(y) === x.length - y.length;
}

However, if y is one character longer than x, the right-hand side x.length - y.length becomes -1, which then equals the return value of lastIndexOf. This will make the test pass, even though x does not end with y.

To avoid this, explicitly check for the -1 case:

function endsWith(x, y) {
  let index = x.lastIndexOf(y);
  return index !== -1 && index === x.length - y.length;
}

References

String.prototype.endsWith
String.prototype.indexOf
CWE-20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant