joerick/pyinstrument

CSP Conflict with PyInstrument Inline Scripts

devwaseem opened this issue · 1 comments

Context:

I am using Django with strict Content Security Policy (CSP) rules enabled. This is a security best practice that prevents malicious scripts from executing within my application. However, I am encountering a conflict with the library, which currently uses inline scripts.

Problem:

  • CSP violation: My CSP rules disallow inline scripts, which are the default method used by PyInstrument to inject its JavaScript code for profiling.
  • Workaround: I am currently bypassing the CSP violation by temporarily adding unsafe-inline to my CSP policy. However, this is a security risk and is not a sustainable solution.

Desired Solution:

To maintain a secure and compliant application, I would like PyInstrument to support CSP compliant injection of its scripts. This can be achieved by implementing a mechanism like using 'nonce-...'.

Proposed Solution:

  • Setting for CSP nonce: Introduce a new setting in PyInstrument, similar to the existing callback functionality, called PYINSTRUMENT_CSP_NONCE. This setting would accept a callable function that returns a unique nonce value.

Example:

# In settings.py
PYINSTRUMENT_CSP_NONCE = lambda: generate_unique_nonce()

# Example nonce generation function
def generate_unique_nonce():
    # ... logic to generate a unique nonce value ...
    return nonce_value

Benefits:

  • Improved security: By using a nonce, we ensure that scripts are only allowed to execute if they were specifically injected by the server, preventing malicious injection.
  • CSP compliance: The application will remain compliant with strict CSP rules, maintaining a high level of security.
  • Flexibility: The ability to define a custom nonce generation function allows for greater control and integration with existing security infrastructure.

This approach would allow PyInstrument to be used within Django applications with strict CSP rules, without compromising security.

Sure, if you want to send a PR for the above, it sounds sensible to me!