Skip to content

refactor: Replace inline-scripts and onclick handlers for better CSP conformance #8246

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

Merged
merged 3 commits into from
Jun 18, 2025

Conversation

stefanw
Copy link
Contributor

@stefanw stefanw commented Jun 3, 2025

Description

This PR replaces more inline-scripts with passing data via JSON to be conformant with Content Security Policy (CSP) best practices (no script-src: unsafe-inline necessary).

Checklist

  • I have opened this pull request against main
  • I have added or modified the tests when changing logic
  • I have followed the conventional commits guidelines to add meaningful information into the changelog
  • I have read the contribution guidelines and I have joined the channel #pr-reviews on our Discord Server to find a “pr review buddy” who is going to review my pull request.

Summary by Sourcery

Improve CSP compliance by replacing inline scripts and onclick attributes in widget templates with JSON-based data injection and moving event handlers into external JavaScript modules.

Enhancements:

  • Refactor form widgets to emit initialization data as JSON in <script type="application/json" data-cms-widget-*> tags instead of inline <script> blocks
  • Update forms.apphookselect, forms.pageselectwidget, and forms.pagesmartlinkwidget modules to parse JSON payloads from data-cms-widget elements and initialize widgets accordingly
  • Remove inline onclick handlers for add-another links and language tabs in templates, using data attributes and external JS event listeners for popup and language-switch logic
  • Rename add-another link class to addlink and standardize event binding in the ApplicationConfigSelect widget

Copy link
Contributor

sourcery-ai bot commented Jun 3, 2025

Reviewer's Guide

This PR refactors widget initialization and event handlers to conform with CSP by replacing inline scripts and onclick attributes with JSON data injections and delegated JavaScript parsing and binding.

Sequence Diagram: Widget Data Initialization via JSON

sequenceDiagram
    participant PythonBackend as Python Backend (Widget)
    participant TemplateEngine as Django Template Engine
    participant BrowserHTMLDoc as Browser (HTML Document)
    participant WidgetJS as Browser (Widget JavaScript)

    PythonBackend->>PythonBackend: get_context() called
    alt PageSmartLinkWidget / ApplicationConfigSelect
        PythonBackend->>PythonBackend: Calls _build_script_data()
        PythonBackend-->>PythonBackend: Returns JSON data string
    else PageSelectWidget
        PythonBackend->>PythonBackend: Prepares JSON for widget 'name'
    end
    PythonBackend-->>TemplateEngine: Context with 'script_data' (JSON string)
    TemplateEngine->>TemplateEngine: Renders template
    TemplateEngine->>BrowserHTMLDoc: Embeds JSON in <script type="application/json" data-cms-widget-XYZ>
    BrowserHTMLDoc->>WidgetJS: HTML Document loaded
    WidgetJS->>BrowserHTMLDoc: JS queries for <script data-cms-widget-XYZ>
    BrowserHTMLDoc-->>WidgetJS: Returns script element
    WidgetJS->>WidgetJS: Parses JSON from script.textContent
    WidgetJS->>WidgetJS: Initializes widget with parsed data
Loading

Sequence Diagram: Migrating Inline 'onclick' to JavaScript Event Listeners

sequenceDiagram
    actor User
    participant Element as Browser (HTML Element e.g., Button, Link)
    participant JSModule as Browser (Relevant JS Module)
    participant TargetFunction as JavaScript Function (e.g., CMS.API.changeLanguage, window.showAddAnotherPopup)

    JSModule->>Element: Attaches 'click' event listener during initialization
    User->>Element: Clicks element
    Element->>JSModule: Executes 'click' event handler
    opt Element has data attributes
        JSModule->>Element: Reads data (e.g., from dataset)
    end
    JSModule->>TargetFunction: Calls target function (with data if any)
Loading

Updated Class Diagram: Python Widget Classes

classDiagram
    class PageSelectWidget {
        +get_context(name, value, attrs)
        %% _build_script() method removed
        %% get_context() now populates widget.script_data with JSON
    }

    class PageSmartLinkWidget {
        +get_context(name, value, attrs)
        +_build_script_data(name, value, attrs)
        %% _build_script() method removed
        %% _build_script_data() method added
        %% get_context() now calls _build_script_data()
    }

    class ApplicationConfigSelect {
        +get_context(name, value, attrs)
        +_build_script_data(name, value, attrs)
        %% _build_script() method removed
        %% _build_script_data() method added
        %% get_context() now calls _build_script_data()
    }
Loading

File-Level Changes

Change Details Files
Refactored widget script builders to emit JSON data instead of inline <script> tags
  • Removed custom _build_script methods and introduced _build_script_data to serialize initialization data as JSON
  • Updated get_context to assign script_data instead of script_init
  • Changed templates to embed JSON in <script type="application/json" data-cms-widget-*"> tags
cms/forms/widgets.py
cms/templates/cms/widgets/applicationconfigselect.html
cms/templates/cms/widgets/pageselectwidget.html
cms/templates/cms/widgets/pagesmartlinkwidget.html
Updated front-end modules to consume JSON data attributes and remove reliance on global CMS.Widgets arrays
  • Parsed initialization payload with document.querySelectorAll and JSON.parse instead of reading window.CMS.Widgets
  • Adjusted apphookselect.js to read script tag content and bind showAddAnotherPopup without inline onclick
  • Simplified page select and smartlink modules to initialize widgets from embedded JSON
cms/static/cms/js/widgets/forms.apphookselect.js
cms/static/cms/js/widgets/forms.pageselectwidget.js
cms/static/cms/js/widgets/forms.pagesmartlinkwidget.js
Extracted inline onclick handlers for language switching into delegated JavaScript events
  • Replaced inline onclick on language buttons with data-admin-url attributes
  • Added jQuery click listener in cms.changeform.js to call CMS.API.changeLanguage
  • Cleaned up change_form.html to remove inline event binding
cms/static/cms/js/modules/cms.changeform.js
cms/templates/admin/cms/page/change_form.html

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@stefanw stefanw changed the title Replace inline-scripts and onclick attributes for better CSP conformance refactor: Replace inline-scripts and onclick attributes for better CSP conformance Jun 3, 2025
@stefanw stefanw changed the title refactor: Replace inline-scripts and onclick attributes for better CSP conformance refactor: Replace inline-scripts and onclick handlers for better CSP conformance Jun 3, 2025
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @stefanw - I've reviewed your changes and found some issues that need to be addressed.

Blocking issues:

  • Config model instances are not JSON serializable (link)

General comments:

  • In cms/static/js/modules/cms.changeform.js the selector '#page_form_lang_tabs button .language_button' won’t match the <input class="language_button" /> elements—update it to something like '#page_form_lang_tabs input.language_button' so the click handler actually binds.
  • When you embed data via json.dumps into <script type="application/json">, make sure all string values (e.g. placeholder_text, config names) are properly escaped or consider using Django’s built-in json_script tag to prevent potential XSS.
  • You renamed the link class from add-another to addlink—verify that any CSS rules or JS code referencing add-another have been updated so the styles and behaviors don’t break.
Here's what I looked at during the review
  • 🔴 General issues: 1 blocking issue, 2 other issues
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@stefanw stefanw force-pushed the fix-csp-inline-scripts branch 9 times, most recently from 5c3549e to fb0534c Compare June 3, 2025 15:02
Replaced with JSON data scripts and data attributes to be
conformant with Content Security Policy best practices.
@stefanw stefanw force-pushed the fix-csp-inline-scripts branch from fb0534c to 0243d93 Compare June 3, 2025 15:30
@fsbraun
Copy link
Member

fsbraun commented Jun 3, 2025

@stefanw Nice work, thank you!

Did you test the widgets?

@marksweb
Copy link
Member

marksweb commented Jun 3, 2025

@fsbraun that class name change is something that seems questionable - is that likely to break things for people is my current thought. Though I've only had a quick glance over this.

@fsbraun
Copy link
Member

fsbraun commented Jun 3, 2025

I believe that somewhere between Django 3.2 and 4.2, the add-another class was replaced by the addlink class. So, potentially, this is an additional bugfix to actually make the icons appear for current Django versions. @stefanw Can you comment?

@stefanw
Copy link
Contributor Author

stefanw commented Jun 3, 2025

@marksweb I can add the add-another class back if that makes sense? The class used to be part of the Django admin but was removed in 3.1, so I thought replacing it with the class name that is used now for displaying a '+' sign.

@fsbraun I tested all widgets apart from the app hook config where I don't have a good sample setup.

@marksweb
Copy link
Member

marksweb commented Jun 4, 2025

@stefanw ah ok, that makes sense then! Thank you for explaining. I think it's fine to leave as it is in that case. 👍

@fsbraun fsbraun added the needs to be backported Commits need to be backported label Jun 18, 2025
Copy link
Member

@fsbraun fsbraun left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@stefanw Thanks for fixing this! Looks nice!

@fsbraun fsbraun merged commit 598d2cf into django-cms:main Jun 18, 2025
64 checks passed
fsbraun added a commit that referenced this pull request Jun 18, 2025
Replaced with JSON data scripts and data attributes to be
conformant with Content Security Policy best practices.

Co-authored-by: Fabian Braun <fsbraun@gmx.de>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs to be backported Commits need to be backported
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy