url_sanitizer.rb 1.18 KB
Newer Older
1
module Gitlab
2
3
4
5
6
7
8
  class UrlSanitizer
    def self.sanitize(content)
      regexp = URI::Parser.new.make_regexp(['http', 'https', 'ssh', 'git'])

      content.gsub(regexp) { |url| new(url).masked_url }
    end

James Lopez's avatar
James Lopez committed
9
    def initialize(url, credentials: nil)
10
      @url = Addressable::URI.parse(URI.encode(url))
James Lopez's avatar
James Lopez committed
11
      @credentials = credentials
12
13
14
15
16
17
    end

    def sanitized_url
      @sanitized_url ||= safe_url.to_s
    end

18
19
20
21
22
23
24
    def masked_url
      url = @url.dup
      url.password = "*****" unless url.password.nil?
      url.user = "*****" unless url.user.nil?
      url.to_s
    end

25
26
27
28
    def credentials
      @credentials ||= { user: @url.user, password: @url.password }
    end

James Lopez's avatar
James Lopez committed
29
30
31
32
    def full_url
      @full_url ||= generate_full_url.to_s
    end

33
34
    private

James Lopez's avatar
James Lopez committed
35
    def generate_full_url
James Lopez's avatar
James Lopez committed
36
      return @url unless valid_credentials?
James Lopez's avatar
James Lopez committed
37
      @full_url = @url.dup
38
39
      @full_url.user = credentials[:user]
      @full_url.password = credentials[:password]
James Lopez's avatar
James Lopez committed
40
41
42
      @full_url
    end

43
44
45
46
47
48
    def safe_url
      safe_url = @url.dup
      safe_url.password = nil
      safe_url.user = nil
      safe_url
    end
James Lopez's avatar
James Lopez committed
49
50
51
52

    def valid_credentials?
      credentials && credentials.is_a?(Hash) && credentials.any?
    end
53
  end
James Lopez's avatar
James Lopez committed
54
end