Skip to content
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

Add img as allowed tag to sanitizer #5983

Merged
merged 1 commit into from
Dec 3, 2024
Merged

Conversation

jorg-vr
Copy link
Contributor

@jorg-vr jorg-vr commented Dec 3, 2024

This pull request adds img as allowed tag in sanitized html.
This to support more complex SVG's without allowing scripts.

  • Tests were added

@jorg-vr jorg-vr added the enhancement A change that isn't substantial enough to be called a feature label Dec 3, 2024
@jorg-vr jorg-vr self-assigned this Dec 3, 2024
@jorg-vr jorg-vr requested a review from bmesuere as a code owner December 3, 2024 10:24
Copy link
Contributor

coderabbitai bot commented Dec 3, 2024

Walkthrough

The pull request modifies the ApplicationHelper module to enhance the sanitize method by allowing <img> tags in sanitized HTML content. It also refines several URL and path generation methods to raise errors for nil parameters and includes conditional checks for routing. Additionally, the navbar_link and activatable_link_to methods are updated to check for rendering conditions. The corresponding test suite is updated with new tests for the sanitize method, ensuring robust validation of allowed and filtered HTML content.

Changes

File Change Summary
app/helpers/application_helper.rb - Updated sanitize method to allow <img> tags.
- Refined URL/path methods to raise errors for nil activity parameter.
- Updated navbar_link and activatable_link_to methods to check rendering conditions.
test/helpers/application_helper_test.rb - Added tests for sanitize method to allow images.
- Updated existing tests to check for filtering of <use> tags and other dangerous tags.
- Minor formatting adjustments in test HTML strings.

Possibly related PRs

  • Add polyline as allowed svg tag #5853: The changes in this PR also modify the sanitize method in the ApplicationHelper module to alter the allowed tags, specifically adding a new SVG tag, which is directly related to the modifications made in the main PR regarding allowed tags in the same method.

Suggested reviewers

  • bmesuere

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a82c3bb and c930c95.

📒 Files selected for processing (2)
  • app/helpers/application_helper.rb (1 hunks)
  • test/helpers/application_helper_test.rb (2 hunks)
🔇 Additional comments (2)
test/helpers/application_helper_test.rb (2)

74-77: LGTM! Good security test coverage.

The test appropriately covers SVG-specific XSS attack vectors:

  • Nested script tags within SVG
  • The use tag with javascript: protocol in xlink:href

Also applies to: 84-84


108-117: 🛠️ Refactor suggestion

Enhance security test coverage for img tags.

While the basic functionality is tested, consider adding tests for the following security scenarios:

  1. Filtering of dangerous event handlers (e.g., onerror, onload)
  2. SVG images that might contain embedded scripts
  3. URL scheme restrictions (e.g., javascript: URLs)

Let's check if there are any existing tests covering these scenarios:

Add these test cases:

 test 'sanitize helper should allow images' do
   # test link image and base64 image
   dirty_html = <<~HTML
     <img src="https://example.com/image.jpg" alt="Image">
     <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
+    <img src="javascript:alert(1)" onerror="alert(2)" onload="alert(3)">
+    <img src="data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIj48L3N2Zz4=">
   HTML
   clean_html = sanitize dirty_html

-  assert_equal dirty_html, clean_html
+  assert_match(/https:\/\/example\.com/, clean_html)
+  assert_match(/data:image\/png;base64,/, clean_html)
+  assert_no_match(/javascript:/, clean_html)
+  assert_no_match(/onerror|onload/, clean_html)
+  assert_no_match(/data:image\/svg\+xml/, clean_html)
 end

@@ -134,7 +134,7 @@ def markdown_unsafe(source)

def sanitize(html)
@tags ||= Rails::Html::SafeListSanitizer.allowed_tags.to_a +
%w[table thead tbody tr td th colgroup col style summary details] +
%w[table thead tbody tr td th colgroup col style summary details img] +
Copy link
Contributor

@coderabbitai coderabbitai bot Dec 3, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add security controls for img tag attributes and URLs.

While adding the img tag, consider implementing these security controls:

  1. Explicitly allow only safe img attributes (src, alt, width, height, title)
  2. Implement URL scheme restrictions for the src attribute
  3. Consider using a URL allowlist for external images

Here's a suggested implementation:

 @tags ||= Rails::Html::SafeListSanitizer.allowed_tags.to_a +
-          %w[table thead tbody tr td th colgroup col style summary details img] +
+          %w[table thead tbody tr td th colgroup col style summary details] +
+          %w[img] +
           %w[svg g style circle line rect path polygon polyline text defs]
 @attributes ||= Rails::Html::SafeListSanitizer.allowed_attributes.to_a +
                 %w[style target data-bs-toggle data-parent data-tab data-line data-element id] +
-                %w[viewBox width height version style class transform id x y rx ry x1 y1 x2 y2 d points fill stroke stroke-width stroke-dasharray cx cy r font-size font-family font-weight font-variant textLength writing-mode glyph-orientation-vertical text-orientation color]
+                %w[viewBox width height version style class transform id x y rx ry x1 y1 x2 y2 d points fill stroke stroke-width stroke-dasharray cx cy r font-size font-family font-weight font-variant textLength writing-mode glyph-orientation-vertical text-orientation color] +
+                %w[src alt title]

+# Add URL scheme restrictions
+def sanitize(html)
+  # ... existing code ...
+  
+  # Additional URL scheme filtering for img src
+  sanitized.gsub(/(<img[^>]*\ssrc=["'])(.*?)(["'][^>]*>)/) do |match|
+    prefix, url, suffix = Regexp.last_match[1..3]
+    if url.start_with?('data:image/png;base64,', 'data:image/jpeg;base64,', 'data:image/gif;base64,', 'https://')
+      match
+    else
+      prefix + '#' + suffix # or remove the img tag entirely
+    end
+  end.html_safe
+end

Consider also implementing a configuration option for URL allowlist:

# config/initializers/sanitizer.rb
Rails.application.config.allowed_image_domains = ['example.com', 'your-cdn.com']

Copy link
Contributor

Choose a reason for hiding this comment

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

@jorg-vr: could you also support SVG-images; the URL is then formatted as

<img src="data:image/svg+xml;base64,..."/>

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@jorg-vr jorg-vr merged commit 3cad0b6 into main Dec 3, 2024
16 checks passed
@jorg-vr jorg-vr deleted the enhance/allow-use-for-exercise branch December 3, 2024 10:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement A change that isn't substantial enough to be called a feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants