File: sanitizer.rb

package info (click to toggle)
ruby-rails-html-sanitizer 1.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 192 kB
  • sloc: ruby: 1,658; makefile: 6
file content (423 lines) | stat: -rw-r--r-- 14,848 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# frozen_string_literal: true

module Rails
  module HTML
    class Sanitizer
      class << self
        def html5_support?
          return @html5_support if defined?(@html5_support)

          @html5_support = Loofah.respond_to?(:html5_support?) && Loofah.html5_support?
        end

        def best_supported_vendor
          html5_support? ? Rails::HTML5::Sanitizer : Rails::HTML4::Sanitizer
        end
      end

      def sanitize(html, options = {})
        raise NotImplementedError, "subclasses must implement sanitize method."
      end

      private
        def remove_xpaths(node, xpaths)
          node.xpath(*xpaths).remove
          node
        end

        def properly_encode(fragment, options)
          fragment.xml? ? fragment.to_xml(options) : fragment.to_html(options)
        end
    end

    module Concern
      module ComposedSanitize
        def sanitize(html, options = {})
          return unless html
          return html if html.empty?

          serialize(scrub(parse_fragment(html), options))
        end
      end

      module Parser
        module HTML4
          def parse_fragment(html)
            Loofah.html4_fragment(html)
          end
        end

        module HTML5
          def parse_fragment(html)
            Loofah.html5_fragment(html)
          end
        end if Rails::HTML::Sanitizer.html5_support?
      end

      module Scrubber
        module Full
          def scrub(fragment, options = {})
            fragment.scrub!(TextOnlyScrubber.new)
          end
        end

        module Link
          def initialize
            super
            @link_scrubber = TargetScrubber.new
            @link_scrubber.tags = %w(a)
            @link_scrubber.attributes = %w(href)
          end

          def scrub(fragment, options = {})
            fragment.scrub!(@link_scrubber)
          end
        end

        module SafeList
          # The default safe list for tags
          DEFAULT_ALLOWED_TAGS = Set.new([
                                           "a",
                                           "abbr",
                                           "acronym",
                                           "address",
                                           "b",
                                           "big",
                                           "blockquote",
                                           "br",
                                           "cite",
                                           "code",
                                           "dd",
                                           "del",
                                           "dfn",
                                           "div",
                                           "dl",
                                           "dt",
                                           "em",
                                           "h1",
                                           "h2",
                                           "h3",
                                           "h4",
                                           "h5",
                                           "h6",
                                           "hr",
                                           "i",
                                           "img",
                                           "ins",
                                           "kbd",
                                           "li",
                                           "mark",
                                           "ol",
                                           "p",
                                           "pre",
                                           "samp",
                                           "small",
                                           "span",
                                           "strong",
                                           "sub",
                                           "sup",
                                           "time",
                                           "tt",
                                           "ul",
                                           "var",
                                         ]).freeze

          # The default safe list for attributes
          DEFAULT_ALLOWED_ATTRIBUTES = Set.new([
                                                 "abbr",
                                                 "alt",
                                                 "cite",
                                                 "class",
                                                 "datetime",
                                                 "height",
                                                 "href",
                                                 "lang",
                                                 "name",
                                                 "src",
                                                 "title",
                                                 "width",
                                                 "xml:lang",
                                               ]).freeze

          def self.included(klass)
            class << klass
              attr_accessor :allowed_tags
              attr_accessor :allowed_attributes
            end

            klass.allowed_tags = DEFAULT_ALLOWED_TAGS.dup
            klass.allowed_attributes = DEFAULT_ALLOWED_ATTRIBUTES.dup
          end

          def initialize(prune: false)
            @permit_scrubber = PermitScrubber.new(prune: prune)
          end

          def scrub(fragment, options = {})
            if scrubber = options[:scrubber]
              # No duck typing, Loofah ensures subclass of Loofah::Scrubber
              fragment.scrub!(scrubber)
            elsif allowed_tags(options) || allowed_attributes(options)
              @permit_scrubber.tags = allowed_tags(options)
              @permit_scrubber.attributes = allowed_attributes(options)
              fragment.scrub!(@permit_scrubber)
            else
              fragment.scrub!(:strip)
            end
          end

          def sanitize_css(style_string)
            Loofah::HTML5::Scrub.scrub_css(style_string)
          end

          private
            def allowed_tags(options)
              options[:tags] || self.class.allowed_tags
            end

            def allowed_attributes(options)
              options[:attributes] || self.class.allowed_attributes
            end
        end
      end

      module Serializer
        module UTF8Encode
          def serialize(fragment)
            properly_encode(fragment, encoding: "UTF-8")
          end
        end
      end
    end
  end

  module HTML4
    module Sanitizer
      module VendorMethods
        def full_sanitizer
          Rails::HTML4::FullSanitizer
        end

        def link_sanitizer
          Rails::HTML4::LinkSanitizer
        end

        def safe_list_sanitizer
          Rails::HTML4::SafeListSanitizer
        end

        def white_list_sanitizer # :nodoc:
          safe_list_sanitizer
        end
      end

      extend VendorMethods
    end

    # == Rails::HTML4::FullSanitizer
    #
    # Removes all tags from HTML4 but strips out scripts, forms and comments.
    #
    #   full_sanitizer = Rails::HTML4::FullSanitizer.new
    #   full_sanitizer.sanitize("<b>Bold</b> no more!  <a href='more.html'>See more here</a>...")
    #   # => "Bold no more!  See more here..."
    #
    class FullSanitizer < Rails::HTML::Sanitizer
      include HTML::Concern::ComposedSanitize
      include HTML::Concern::Parser::HTML4
      include HTML::Concern::Scrubber::Full
      include HTML::Concern::Serializer::UTF8Encode
    end

    # == Rails::HTML4::LinkSanitizer
    #
    # Removes +a+ tags and +href+ attributes from HTML4 leaving only the link text.
    #
    #   link_sanitizer = Rails::HTML4::LinkSanitizer.new
    #   link_sanitizer.sanitize('<a href="example.com">Only the link text will be kept.</a>')
    #   # => "Only the link text will be kept."
    #
    class LinkSanitizer < Rails::HTML::Sanitizer
      include HTML::Concern::ComposedSanitize
      include HTML::Concern::Parser::HTML4
      include HTML::Concern::Scrubber::Link
      include HTML::Concern::Serializer::UTF8Encode
    end

    # == Rails::HTML4::SafeListSanitizer
    #
    # Sanitizes HTML4 and CSS from an extensive safe list.
    #
    # === Whitespace
    #
    # We can't make any guarantees about whitespace being kept or stripped.  Loofah uses Nokogiri,
    # which wraps either a C or Java parser for the respective Ruby implementation.  Those two
    # parsers determine how whitespace is ultimately handled.
    #
    # When the stripped markup will be rendered the users browser won't take whitespace into account
    # anyway. It might be better to suggest your users wrap their whitespace sensitive content in
    # pre tags or that you do so automatically.
    #
    # === Options
    #
    # Sanitizes both html and css via the safe lists found in
    # Rails::HTML::Concern::Scrubber::SafeList
    #
    # SafeListSanitizer also accepts options to configure the safe list used when sanitizing html.
    # There's a class level option:
    #
    #   Rails::HTML4::SafeListSanitizer.allowed_tags = %w(table tr td)
    #   Rails::HTML4::SafeListSanitizer.allowed_attributes = %w(id class style)
    #
    # Tags and attributes can also be passed to +sanitize+.  Passed options take precedence over the
    # class level options.
    #
    # === Examples
    #
    #   safe_list_sanitizer = Rails::HTML4::SafeListSanitizer.new
    #
    #   # default: sanitize via a extensive safe list of allowed elements
    #   safe_list_sanitizer.sanitize(@article.body)
    #
    #   # sanitize via the supplied tags and attributes
    #   safe_list_sanitizer.sanitize(
    #     @article.body,
    #     tags: %w(table tr td),
    #     attributes: %w(id class style),
    #   )
    #
    #   # sanitize via a custom Loofah scrubber
    #   safe_list_sanitizer.sanitize(@article.body, scrubber: ArticleScrubber.new)
    #
    #   # prune nodes from the tree instead of stripping tags and leaving inner content
    #   safe_list_sanitizer = Rails::HTML4::SafeListSanitizer.new(prune: true)
    #
    #   # the sanitizer can also sanitize CSS
    #   safe_list_sanitizer.sanitize_css('background-color: #000;')
    #
    class SafeListSanitizer < Rails::HTML::Sanitizer
      include HTML::Concern::ComposedSanitize
      include HTML::Concern::Parser::HTML4
      include HTML::Concern::Scrubber::SafeList
      include HTML::Concern::Serializer::UTF8Encode
    end
  end

  module HTML5
    class Sanitizer
      class << self
        def full_sanitizer
          Rails::HTML5::FullSanitizer
        end

        def link_sanitizer
          Rails::HTML5::LinkSanitizer
        end

        def safe_list_sanitizer
          Rails::HTML5::SafeListSanitizer
        end

        def white_list_sanitizer # :nodoc:
          safe_list_sanitizer
        end
      end
    end

    # == Rails::HTML5::FullSanitizer
    #
    # Removes all tags from HTML5 but strips out scripts, forms and comments.
    #
    #   full_sanitizer = Rails::HTML5::FullSanitizer.new
    #   full_sanitizer.sanitize("<b>Bold</b> no more!  <a href='more.html'>See more here</a>...")
    #   # => "Bold no more!  See more here..."
    #
    class FullSanitizer < Rails::HTML::Sanitizer
      include HTML::Concern::ComposedSanitize
      include HTML::Concern::Parser::HTML5
      include HTML::Concern::Scrubber::Full
      include HTML::Concern::Serializer::UTF8Encode
    end

    # == Rails::HTML5::LinkSanitizer
    #
    # Removes +a+ tags and +href+ attributes from HTML5 leaving only the link text.
    #
    #   link_sanitizer = Rails::HTML5::LinkSanitizer.new
    #   link_sanitizer.sanitize('<a href="example.com">Only the link text will be kept.</a>')
    #   # => "Only the link text will be kept."
    #
    class LinkSanitizer < Rails::HTML::Sanitizer
      include HTML::Concern::ComposedSanitize
      include HTML::Concern::Parser::HTML5
      include HTML::Concern::Scrubber::Link
      include HTML::Concern::Serializer::UTF8Encode
    end

    # == Rails::HTML5::SafeListSanitizer
    #
    # Sanitizes HTML5 and CSS from an extensive safe list.
    #
    # === Whitespace
    #
    # We can't make any guarantees about whitespace being kept or stripped.  Loofah uses Nokogiri,
    # which wraps either a C or Java parser for the respective Ruby implementation.  Those two
    # parsers determine how whitespace is ultimately handled.
    #
    # When the stripped markup will be rendered the users browser won't take whitespace into account
    # anyway. It might be better to suggest your users wrap their whitespace sensitive content in
    # pre tags or that you do so automatically.
    #
    # === Options
    #
    # Sanitizes both html and css via the safe lists found in
    # Rails::HTML::Concern::Scrubber::SafeList
    #
    # SafeListSanitizer also accepts options to configure the safe list used when sanitizing html.
    # There's a class level option:
    #
    #   Rails::HTML5::SafeListSanitizer.allowed_tags = %w(table tr td)
    #   Rails::HTML5::SafeListSanitizer.allowed_attributes = %w(id class style)
    #
    # Tags and attributes can also be passed to +sanitize+.  Passed options take precedence over the
    # class level options.
    #
    # === Examples
    #
    #   safe_list_sanitizer = Rails::HTML5::SafeListSanitizer.new
    #
    #   # default: sanitize via a extensive safe list of allowed elements
    #   safe_list_sanitizer.sanitize(@article.body)
    #
    #   # sanitize via the supplied tags and attributes
    #   safe_list_sanitizer.sanitize(
    #     @article.body,
    #     tags: %w(table tr td),
    #     attributes: %w(id class style),
    #   )
    #
    #   # sanitize via a custom Loofah scrubber
    #   safe_list_sanitizer.sanitize(@article.body, scrubber: ArticleScrubber.new)
    #
    #   # prune nodes from the tree instead of stripping tags and leaving inner content
    #   safe_list_sanitizer = Rails::HTML5::SafeListSanitizer.new(prune: true)
    #
    #   # the sanitizer can also sanitize CSS
    #   safe_list_sanitizer.sanitize_css('background-color: #000;')
    #
    class SafeListSanitizer < Rails::HTML::Sanitizer
      include HTML::Concern::ComposedSanitize
      include HTML::Concern::Parser::HTML5
      include HTML::Concern::Scrubber::SafeList
      include HTML::Concern::Serializer::UTF8Encode
    end
  end if Rails::HTML::Sanitizer.html5_support?

  module HTML
    Sanitizer.extend(HTML4::Sanitizer::VendorMethods) # :nodoc:
    FullSanitizer = HTML4::FullSanitizer # :nodoc:
    LinkSanitizer = HTML4::LinkSanitizer # :nodoc:
    SafeListSanitizer = HTML4::SafeListSanitizer # :nodoc:
    WhiteListSanitizer = SafeListSanitizer # :nodoc:
  end
end