Class: Gitlab::UrlSanitizer

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/url_sanitizer.rb

Constant Summary collapse

ALLOWED_SCHEMES =
%w[http https ssh git].freeze
ALLOWED_WEB_SCHEMES =
%w[http https].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, credentials: nil) ⇒ UrlSanitizer

Returns a new instance of UrlSanitizer.


31
32
33
34
35
36
37
38
# File 'lib/gitlab/url_sanitizer.rb', line 31

def initialize(url, credentials: nil)
  %i[user password].each do |symbol|
    credentials[symbol] = credentials[symbol].presence if credentials&.key?(symbol)
  end

  @credentials = credentials
  @url = parse_url(url)
end

Class Method Details

.sanitize(content) ⇒ Object


8
9
10
11
12
13
14
# File 'lib/gitlab/url_sanitizer.rb', line 8

def self.sanitize(content)
  regexp = URI::DEFAULT_PARSER.make_regexp(ALLOWED_SCHEMES)

  content.gsub(regexp) { |url| new(url).masked_url }
rescue Addressable::URI::InvalidURIError
  content.gsub(regexp, '')
end

.valid?(url, allowed_schemes: ALLOWED_SCHEMES) ⇒ Boolean

Returns:

  • (Boolean)

16
17
18
19
20
21
22
23
24
25
# File 'lib/gitlab/url_sanitizer.rb', line 16

def self.valid?(url, allowed_schemes: ALLOWED_SCHEMES)
  return false unless url.present?
  return false unless url.is_a?(String)

  uri = Addressable::URI.parse(url.strip)

  allowed_schemes.include?(uri.scheme)
rescue Addressable::URI::InvalidURIError
  false
end

.valid_web?(url) ⇒ Boolean

Returns:

  • (Boolean)

27
28
29
# File 'lib/gitlab/url_sanitizer.rb', line 27

def self.valid_web?(url)
  valid?(url, allowed_schemes: ALLOWED_WEB_SCHEMES)
end

Instance Method Details

#credentialsObject


51
52
53
# File 'lib/gitlab/url_sanitizer.rb', line 51

def credentials
  @credentials ||= { user: @url.user.presence, password: @url.password.presence }
end

#full_urlObject


59
60
61
# File 'lib/gitlab/url_sanitizer.rb', line 59

def full_url
  @full_url ||= generate_full_url.to_s
end

#masked_urlObject


44
45
46
47
48
49
# File 'lib/gitlab/url_sanitizer.rb', line 44

def masked_url
  url = @url.dup
  url.password = "*****" if url.password.present?
  url.user = "*****" if url.user.present?
  url.to_s
end

#sanitized_urlObject


40
41
42
# File 'lib/gitlab/url_sanitizer.rb', line 40

def sanitized_url
  @sanitized_url ||= safe_url.to_s
end

#userObject


55
56
57
# File 'lib/gitlab/url_sanitizer.rb', line 55

def user
  credentials[:user]
end