This document provides guidelines and instructions for implementing HTML sanitization in your project.
HTML sanitization ensures that all strings, texts, and JSON containing strings or texts are sanitized by default. This helps prevent potential security vulnerabilities and ensures consistent handling of HTML content across your application.
-
Update Your ApplicationRecord: Make sure you have
include Folio::HtmlSanitization::Modelin yourApplicationRecord. -
Define Sanitization Configuration: For models that may contain HTML attributes, define a
folio_html_sanitization_configmethod to override the default configuration provided by the concern.Example configuration:
def folio_html_sanitization_config { enabled: true, attributes: { attribute_1: :unsafe_html, attribute_2: :rich_text, attribute_3: -> (value) { custom_sanitization_handler(value) }, }, } end
-
Supported Attribute Values:
:unsafe_html: Ignore the attribute and do not sanitize it.:rich_text: Keep safe HTML tags and attributes usingRails::HTML5::SafeListSanitizer.:string(default): Sanitize the attribute as plain text, stripping all HTML tags.- proc: Pass a proc (i.e.
-> (value) { custom_sanitization_handler(value) }) to handle custom sanitization logic.
-
Default Behavior: Attributes not defined in the
:attributeshash are sanitized as plain text (equivalent to:string) and stripped of all HTML usingLoofah. -
Disabling Sanitization: You can disable sanitization for a specific model by setting
{ enabled: false }in the configuration.
Here is an example override for Folio::EmailTemplate, where attributes starting with body_html are treated as rich text:
def folio_html_sanitization_config
attributes_config = {}
attribute_names.each do |attribute_name|
if attribute_name.starts_with?("body_html")
attributes_config[attribute_name.to_sym] = :rich_text
end
end
{
enabled: true,
attributes: attributes_config,
}
endBy following these steps, you can ensure that your application handles HTML content securely and consistently.