summaryrefslogtreecommitdiff
path: root/lib/gitlab/markdown/sanitization_filter.rb
blob: 88781fea0c8d96460dd32d0105ff44ccecf1aaab (plain)
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
require 'html/pipeline/filter'
require 'html/pipeline/sanitization_filter'

module Gitlab
  module Markdown
    # Sanitize HTML
    #
    # Extends HTML::Pipeline::SanitizationFilter with a custom whitelist.
    class SanitizationFilter < HTML::Pipeline::SanitizationFilter
      def whitelist
        whitelist = super

        # Only push these customizations once
        unless customized?(whitelist[:transformers])
          # Allow code highlighting
          whitelist[:attributes]['pre'] = %w(class)
          whitelist[:attributes]['span'] = %w(class)

          # Allow table alignment
          whitelist[:attributes]['th'] = %w(style)
          whitelist[:attributes]['td'] = %w(style)

          # Allow span elements
          whitelist[:elements].push('span')

          # Remove `rel` attribute from `a` elements
          whitelist[:transformers].push(remove_rel)

          # Remove `class` attribute from non-highlight spans
          whitelist[:transformers].push(clean_spans)
        end

        whitelist
      end

      private

      def remove_rel
        lambda do |env|
          if env[:node_name] == 'a'
            env[:node].remove_attribute('rel')
          end
        end
      end

      def clean_spans
        lambda do |env|
          return unless env[:node_name] == 'span'
          return unless env[:node].has_attribute?('class')

          unless has_ancestor?(env[:node], 'pre')
            env[:node].remove_attribute('class')
          end
        end
      end

      def customized?(transformers)
        transformers.last.source_location[0] == __FILE__
      end
    end
  end
end