Module: Clavis::Security::HttpsEnforcer

Defined in:
lib/clavis/security/https_enforcer.rb

Class Method Summary collapse

Class Method Details

.create_http_clientFaraday::Connection

Creates a new HTTP client with proper TLS configuration

Returns:

  • (Faraday::Connection)

    A configured HTTP client



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/clavis/security/https_enforcer.rb', line 40

def create_http_client
  Faraday.new do |conn|
    conn.ssl.verify = Clavis.configuration.should_verify_ssl?
    conn.ssl.min_version = Clavis.configuration.minimum_tls_version if Clavis.configuration.minimum_tls_version

    # Add middleware
    conn.request :url_encoded
    conn.response :json, content_type: /\bjson$/
    conn.adapter Faraday.default_adapter
  end
end

.enforce_https(url) ⇒ String

Enforces HTTPS for a URL

Parameters:

  • url (String)

    The URL to enforce HTTPS for

Returns:

  • (String)

    The URL with HTTPS enforced



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/clavis/security/https_enforcer.rb', line 13

def enforce_https(url)
  return url unless Clavis.configuration.enforce_https
  return url if url.nil? || url.empty?

  begin
    uri = URI.parse(url)

    # Skip if already HTTPS
    return url if uri.scheme == "https"

    # Allow HTTP for localhost in development if configured
    if localhost?(uri.host) &&
       Clavis.configuration.allow_http_localhost &&
       (defined?(Rails) && !Rails.env.production?)
      return url
    end

    # Upgrade to HTTPS
    uri.scheme = "https"
    uri.to_s
  rescue URI::InvalidURIError
    url
  end
end

.https?(url) ⇒ Boolean

Checks if a URL is using HTTPS

Parameters:

  • url (String)

    The URL to check

Returns:

  • (Boolean)

    Whether the URL is using HTTPS



55
56
57
58
59
60
61
62
63
64
# File 'lib/clavis/security/https_enforcer.rb', line 55

def https?(url)
  return false if url.nil? || url.empty?

  begin
    uri = URI.parse(url)
    uri.scheme == "https"
  rescue URI::InvalidURIError
    false
  end
end

.warn_if_not_https(url, context = nil) ⇒ Object

Logs a warning if a URL is not using HTTPS

Parameters:

  • url (String)

    The URL to check

  • context (String) (defaults to: nil)

    The context for the warning



69
70
71
72
73
74
75
76
77
# File 'lib/clavis/security/https_enforcer.rb', line 69

def warn_if_not_https(url, context = nil)
  return if https?(url)

  message = "WARNING: Non-HTTPS URL detected"
  message += " in #{context}" if context
  message += ": #{url}"

  Clavis.logger.warn(message)
end