CVE-2024-21636 (published 2024-01-04T20:15Z)

view_component is a framework for building reusable, testable, and encapsulated view components in Ruby on Rails. Versions prior to 3.9.0 and 2.83.0 have a cross-site scripting vulnerability that has the potential to impact anyone rendering a component directly from a controller with the view_component gem. Note that only components that define a `#call` method (i.e. instead of using a sidecar template) are affected. The return value of the `#call` method is not sanitized and can include user-defined content. In addition, the return value of the `#output_postamble` methodis not sanitized, which can also lead to cross-site scripting issues. Versions 3.9.0 and 2.83.0 have been released and fully mitigate both the `#call` and the `#output_postamble` vulnerabilities. As a workaround, sanitize the return value of `#call`.

CVSS v3 base score: 6.1, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/ViewComponent/view_component
commit_details: repo_url: https://github.com/ViewComponent/view_component
author: Cameron Dutro
author_date: 2024-01-04 11:25:54-08:00
msg: Ensure HTML output safety (#1950)
repository: repo_url: https://github.com/ViewComponent/view_component
repo_name: ViewComponent/view_component
description: A framework for building reusable, testable & encapsulated view components in Ruby on Rails.
repo_language: Ruby
owner: ViewComponent
file_changes: filename: ci.yml
change_type: ModificationType.MODIFY
diff: @@ -89,7 +89,7 @@ jobs:
       uses: actions/upload-artifact@v3.1.3
       if: always()
       with:
-        name: simplecov-resultset-rails${{matrix.rails_version}}-ruby${{matrix.ruby_version}}
+        name: simplecov-resultset-rails${{matrix.rails_version}}-ruby${{matrix.ruby_version}}-${{matrix.mode}}
         path: coverage
   primer_view_components_compatibility:
     name: Test compatibility with Primer ViewComponents (main)

programming_language: CoffeeScript
filename: .rubocop.yml
change_type: ModificationType.MODIFY
diff: @@ -1,3 +1,4 @@
+ruby_version: 2.5
 require:
   - standard
   - "rubocop-md"

programming_language: Ruby
filename: CHANGELOG.md
change_type: ModificationType.MODIFY
diff: @@ -38,6 +38,10 @@ nav_order: 5
 
     *Mitchell Henke*
 
+* Ensure HTML output safety.
+
+    *Cameron Dutro*
+
 ## 3.8.0
 
 * Use correct value for the `config.action_dispatch.show_exceptions` config option for edge Rails.

programming_language: Markdown
filename: base.rb
change_type: ModificationType.MODIFY
diff: @@ -106,9 +106,9 @@ module ViewComponent
       if render?
         # Avoid allocating new string when output_postamble is blank
         if output_postamble.blank?
-          render_template_for(@__vc_variant).to_s
+          safe_render_template_for(@__vc_variant).to_s
         else
-          render_template_for(@__vc_variant).to_s + output_postamble
+          safe_render_template_for(@__vc_variant).to_s + safe_output_postamble
         end
       else
         ""
@@ -160,7 +160,7 @@ module ViewComponent
     #
     # @return [String]
     def output_postamble
-      ""
+      @@default_output_postamble ||= "".html_safe
     end
 
     # Called before rendering the component. Override to perform operations that
@@ -307,6 +307,38 @@ module ViewComponent
       defined?(@__vc_content_evaluated) && @__vc_content_evaluated
     end
 
+    def maybe_escape_html(text)
+      return text if request && !request.format.html?
+      return text if text.nil? || text.empty?
+
+      if text.html_safe?
+        text
+      else
+        yield
+        html_escape(text)
+      end
+    end
+
+    def safe_render_template_for(variant)
+      if compiler.renders_template_for_variant?(variant)
+        render_template_for(variant)
+      else
+        maybe_escape_html(render_template_for(variant)) do
+          Kernel.warn("WARNING: The #{self.class} component rendered HTML-unsafe output. The output will be automatically escaped, but you may want to investigate.")
+        end
+      end
+    end
+
+    def safe_output_postamble
+      maybe_escape_html(output_postamble) do
+        Kernel.warn("WARNING: The #{self.class} component was provided an HTML-unsafe postamble. The postamble will be automatically escaped, but you may want to investigate.")
+      end
+    end
+
+    def compiler
+      @compiler ||= self.class.compiler
+    end
+
     # Set the controller used for testing components:
     #
     # ```ruby

programming_language: Ruby
filename: compiler.rb
change_type: ModificationType.MODIFY
diff: @@ -16,6 +16,7 @@ module ViewComponent
     def initialize(component_class)
       @component_class = component_class
       @redefinition_lock = Mutex.new
+      @variants_rendering_templates = Set.new
     end
 
     def compiled?
@@ -68,6 +69,7 @@ module ViewComponent
       else
         templates.each do |template|
           method_name = call_method_name(template[:variant])
+          @variants_rendering_templates << template[:variant]
 
           redefinition_lock.synchronize do
             component_class.silence_redefinition_of_method(method_name)
@@ -89,6 +91,10 @@ module ViewComponent
       CompileCache.register(component_class)
     end
 
+    def renders_template_for_variant?(variant)
+      @variants_rendering_templates.include?(variant)
+    end
+
     private
 
     attr_reader :component_class, :redefinition_lock

programming_language: Ruby
filename: test_helpers.rb
change_type: ModificationType.MODIFY
diff: @@ -178,13 +178,14 @@ module ViewComponent
     # @param full_path [String] The path to set for the current request.
     # @param host [String] The host to set for the current request.
     # @param method [String] The request method to set for the current request.
-    def with_request_url(full_path, host: nil, method: nil)
+    def with_request_url(full_path, host: nil, method: nil, format: :html)
       old_request_host = vc_test_request.host
       old_request_method = vc_test_request.request_method
       old_request_path_info = vc_test_request.path_info
       old_request_path_parameters = vc_test_request.path_parameters
       old_request_query_parameters = vc_test_request.query_parameters
       old_request_query_string = vc_test_request.query_string
+      old_request_format = vc_test_request.format.symbol
       old_controller = defined?(@vc_test_controller) && @vc_test_controller
 
       path, query = full_path.split("?", 2)
@@ -197,6 +198,7 @@ module ViewComponent
       vc_test_request.set_header("action_dispatch.request.query_parameters",
         Rack::Utils.parse_nested_query(query).with_indifferent_access)
       vc_test_request.set_header(Rack::QUERY_STRING, query)
+      vc_test_request.format = format
       yield
     ensure
       vc_test_request.host = old_request_host
@@ -205,6 +207,7 @@ module ViewComponent
       vc_test_request.path_parameters = old_request_path_parameters
       vc_test_request.set_header("action_dispatch.request.query_parameters", old_request_query_parameters)
       vc_test_request.set_header(Rack::QUERY_STRING, old_request_query_string)
+      vc_test_request.format = old_request_format
       @vc_test_controller = old_controller
     end
 

programming_language: Ruby
filename: after_render_component.rb
change_type: ModificationType.MODIFY
diff: @@ -2,10 +2,10 @@
 
 class AfterRenderComponent < ViewComponent::Base
   def call
-    "Hello, "
+    "Hello, ".html_safe
   end
 
   def output_postamble
-    "World!"
+    "World!".html_safe
   end
 end

programming_language: Ruby
filename: content_predicate_component.rb
change_type: ModificationType.MODIFY
diff: @@ -5,7 +5,7 @@ class ContentPredicateComponent < ViewComponent::Base
     if content?
       content
     else
-      "Default"
+      "Default".html_safe
     end
   end
 end

programming_language: Ruby
filename: custom_test_controller_component.rb
change_type: ModificationType.MODIFY
diff: @@ -2,6 +2,6 @@
 
 class CustomTestControllerComponent < ViewComponent::Base
   def call
-    helpers.foo
+    html_escape(helpers.foo)
   end
 end

programming_language: Ruby
filename: inherited_from_uncompilable_component.rb
change_type: ModificationType.MODIFY
diff: @@ -2,6 +2,6 @@
 
 class InheritedFromUncompilableComponent < UncompilableComponent
   def call
-    "<div>hello world</div>"
+    "<div>hello world</div>".html_safe
   end
 end

programming_language: Ruby
filename: inline_render_component.rb
change_type: ModificationType.MODIFY
diff: @@ -6,6 +6,6 @@ class InlineRenderComponent < ViewComponent::Base
   end
 
   def call
-    @items.map { |c| render(c) }.join
+    @items.map { |c| render(c) }.join.html_safe
   end
 end

programming_language: Ruby
filename: message_component.rb
change_type: ModificationType.MODIFY
diff: @@ -6,6 +6,6 @@ class MessageComponent < ViewComponent::Base
   end
 
   def call
-    @message
+    html_escape(@message)
   end
 end

programming_language: Ruby
filename: render_check_component.rb
change_type: ModificationType.MODIFY
diff: @@ -6,6 +6,6 @@ class RenderCheckComponent < ViewComponent::Base
   end
 
   def call
-    "Rendered"
+    "Rendered".html_safe
   end
 end

programming_language: Ruby
filename: unsafe_component.rb
change_type: ModificationType.ADD
diff: @@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+class UnsafeComponent < ViewComponent::Base
+  def call
+    user_input = "<script>alert('hello!')</script>"
+
+    "<div>hello #{user_input}</div>"
+  end
+end

programming_language: Ruby
filename: unsafe_postamble_component.rb
change_type: ModificationType.ADD
diff: @@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+class UnsafePostambleComponent < ViewComponent::Base
+  def call
+    "<div>some content</div>".html_safe
+  end
+
+  def output_postamble
+    "<script>alert('hello!')</script>"
+  end
+end

programming_language: Ruby
filename: variant_ivar_component.rb
change_type: ModificationType.MODIFY
diff: @@ -6,6 +6,6 @@ class VariantIvarComponent < ViewComponent::Base
   end
 
   def call
-    @variant.to_s
+    html_escape(@variant.to_s)
   end
 end

programming_language: Ruby
filename: integration_examples_controller.rb
change_type: ModificationType.MODIFY
diff: @@ -59,4 +59,12 @@ class IntegrationExamplesController < ActionController::Base
   def inherited_from_uncompilable_component
     render(InheritedFromUncompilableComponent.new)
   end
+
+  def unsafe_component
+    render(UnsafeComponent.new)
+  end
+
+  def unsafe_postamble_component
+    render(UnsafePostambleComponent.new)
+  end
 end

programming_language: Ruby
filename: routes.rb
change_type: ModificationType.MODIFY
diff: @@ -29,6 +29,8 @@ Sandbox::Application.routes.draw do
   get :cached_partial, to: "integration_examples#cached_partial"
   get :inherited_sidecar, to: "integration_examples#inherited_sidecar"
   get :inherited_from_uncompilable_component, to: "integration_examples#inherited_from_uncompilable_component"
+  get :unsafe_component, to: "integration_examples#unsafe_component"
+  get :unsafe_postamble_component, to: "integration_examples#unsafe_postamble_component"
   post :create, to: "integration_examples#create"
 
   constraints(lambda { |request| request.env["warden"].authenticate! }) do

programming_language: Ruby
filename: collection_test.rb
change_type: ModificationType.MODIFY
diff: @@ -12,7 +12,7 @@ module ViewComponent
       end
 
       def call
-        "<div data-name='#{product.name}'><h1>#{product.name}</h1></div>"
+        "<div data-name='#{product.name}'><h1>#{product.name}</h1></div>".html_safe
       end
     end
 

programming_language: Ruby
filename: integration_test.rb
change_type: ModificationType.MODIFY
diff: @@ -723,4 +723,22 @@ class IntegrationTest < ActionDispatch::IntegrationTest
       get "/_system_test_entrypoint?file=#{path}"
     end
   end
+
+  def test_unsafe_component
+    warnings = capture_warnings { get "/unsafe_component" }
+    assert_select("script", false)
+    assert(
+      warnings.any? { |warning| warning.include?("component rendered HTML-unsafe output") },
+      "Rendering UnsafeComponent did not emit an HTML safety warning"
+    )
+  end
+
+  def test_unsafe_postamble_component
+    warnings = capture_warnings { get "/unsafe_postamble_component" }
+    assert_select("script", false)
+    assert(
+      warnings.any? { |warning| warning.include?("component was provided an HTML-unsafe postamble") },
+      "Rendering UnsafePostambleComponent did not emit an HTML safety warning"
+    )
+  end
 end

programming_language: Ruby
filename: rendering_test.rb
change_type: ModificationType.MODIFY
diff: @@ -151,7 +151,9 @@ class RenderingTest < ViewComponent::TestCase
   end
 
   def test_render_jbuilder_template
-    render_inline(JbuilderComponent.new(message: "bar")) { "foo" }
+    with_request_url("/", format: :json) do
+      render_inline(JbuilderComponent.new(message: "bar")) { "foo" }
+    end
 
     assert_text("foo")
     assert_text("bar")
@@ -1084,7 +1086,7 @@ class RenderingTest < ViewComponent::TestCase
   end
 
   def test_content_predicate_true
-    render_inline(ContentPredicateComponent.new.with_content("foo"))
+    render_inline(ContentPredicateComponent.new.with_content("foo".html_safe))
 
     assert_text("foo")
   end

programming_language: Ruby
filename: test_helper.rb
change_type: ModificationType.MODIFY
diff: @@ -179,3 +179,11 @@ def with_compiler_mode(mode)
 ensure
   ViewComponent::Compiler.mode = previous_mode
 end
+
+def capture_warnings(&block)
+  [].tap do |warnings|
+    Kernel.stub(:warn, ->(msg) { warnings << msg }) do
+      block.call
+    end
+  end
+end

programming_language: Ruby