url_sanitizer.rb 1.54 KB
Newer Older
1
module Gitlab
2
3
  class UrlSanitizer
    def self.sanitize(content)
Douwe Maan's avatar
Douwe Maan committed
4
      regexp = URI::Parser.new.make_regexp(%w(http https ssh git))
5
6

      content.gsub(regexp) { |url| new(url).masked_url }
James Lopez's avatar
James Lopez committed
7
8
    rescue Addressable::URI::InvalidURIError
      content.gsub(regexp, '')
9
10
    end

James Lopez's avatar
James Lopez committed
11
    def self.valid?(url)
12
13
      return false unless url

James Lopez's avatar
James Lopez committed
14
15
16
17
18
19
20
      Addressable::URI.parse(url.strip)

      true
    rescue Addressable::URI::InvalidURIError
      false
    end

21
22
23
24
25
26
    def self.http_credentials_for_user(user)
      return {} unless user.respond_to?(:username)

      { user: user.username }
    end

James Lopez's avatar
James Lopez committed
27
    def initialize(url, credentials: nil)
James Lopez's avatar
James Lopez committed
28
      @url = Addressable::URI.parse(url.strip)
James Lopez's avatar
James Lopez committed
29
      @credentials = credentials
30
31
32
33
34
35
    end

    def sanitized_url
      @sanitized_url ||= safe_url.to_s
    end

36
37
38
39
40
41
42
    def masked_url
      url = @url.dup
      url.password = "*****" unless url.password.nil?
      url.user = "*****" unless url.user.nil?
      url.to_s
    end

43
44
45
46
    def credentials
      @credentials ||= { user: @url.user, password: @url.password }
    end

James Lopez's avatar
James Lopez committed
47
48
49
50
    def full_url
      @full_url ||= generate_full_url.to_s
    end

51
52
    private

James Lopez's avatar
James Lopez committed
53
    def generate_full_url
James Lopez's avatar
James Lopez committed
54
      return @url unless valid_credentials?
James Lopez's avatar
James Lopez committed
55
      @full_url = @url.dup
56
57
      @full_url.user = credentials[:user]
      @full_url.password = credentials[:password]
James Lopez's avatar
James Lopez committed
58
59
60
      @full_url
    end

61
62
63
64
65
66
    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
67
68
69
70

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