Enhancing CSP with ESLint: Preventing Unsafe setAttribute “style” usage

Preventing Content Security Violations using ESLint.

Content Security Policy (CSP) is a crucial component for securing web applications. One common practice is to disallow the use of the ‘element.setAttribute(“style”, …)‘ command, which can introduce security vulnerabilities.

In this article, I’ll guide you through the process of creating an Eslint rule to detect and prevent the use of ‘element.setAttribute(“style”, …)‘ in your code during the build phase. This proactive approach helps developers adhere to security best practices and reinforces your CSP.

Abstract Syntax Tree

To get started, it’s essential to understand the Abstract Syntax Tree (AST) of the ‘setAttribute’ command you aim to block. You can visualize the AST of your code using tools like AST Explorer:

In the screenshot above, you’ll find the ‘setAttribute‘ command on the left and its corresponding syntax tree on the right.

Eslint Rule

Our custom Eslint rule leverages the ‘no-restricted-syntax‘ rule, which allows us to define specific syntax elements we want to restrict. These elements are identified by their AST node types. Take a look at the screenshot for reference.

Here’s an example configuration for the ‘no-restricted-syntax‘ rule:

"no-restricted-syntax": [
  "error" 
  {
     "selector": "CallExpression[callee.property.name='setAttribute'][arguments.0.value='style']",
     "message": "CSP: You must not use element.setAttribute('style') to set styles. Use element.style instead."
  }
],

Conclusion

By implementing this rule, you can ensure that developers don’t use ‘element.setAttribute(“style”, …)‘ and encourage them to utilize safer alternatives like ‘element.style‘ for setting styles within your web applications.