Search code examples
httpsecurityhttp-headerscontent-security-policyclient-side-attacks

Why should we include CSP headers in the HTTP response for an API?


OWASP recommends to use Content-Security-Policy: frame-ancestors 'none' in API responses in order to avoid drag-and-drop style clickjacking attacks.

However, the CSP spec seems to indicate that after the HTML page is loaded any other CSP rules in the same context would be discarded without effect. Which makes sense in my mental model of how CSP works but if OWASP recommends it then I'm sure missing something.

Can anyone explain how can a CSP header in a XHR request improve security, after the fact that the HTML page is already loaded and the "main" CSP already evaluated? How that works in the browser?


Solution

  • how can a CSP header in a XHR request improve security, after the fact that the HTML page is already loaded and the "main" CSP already evaluated?

    You are right, browsers use CSP from main page and just ignore the CSP header sent along with the XHR requests.

    But you haven't considered the second scenario - the API response is open in the browser's address bar or in a frame. In this case, cookies will be available to the response page, and if XSS is detected in the API (as, for example, in the PyPI simple endpoint API), then the user's confidential data may be available to an attacker.
    Therefore, it is better to protect API responses with the "default-src `none" policy, as well as 404/403/500, etc pages.