omniauth_oidc 0.2.7 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+
5
+ module OmniauthOidc
6
+ # Custom OIDC client using Net::HTTP
7
+ class Client
8
+ attr_accessor :identifier, :secret, :authorization_endpoint, :token_endpoint, :userinfo_endpoint,
9
+ :host, :redirect_uri
10
+
11
+ def initialize(options = {})
12
+ @identifier = options[:identifier] || options["identifier"]
13
+ @secret = options[:secret] || options["secret"]
14
+ @authorization_endpoint = options[:authorization_endpoint] || options["authorization_endpoint"]
15
+ @token_endpoint = options[:token_endpoint] || options["token_endpoint"]
16
+ @userinfo_endpoint = options[:userinfo_endpoint] || options["userinfo_endpoint"]
17
+ @redirect_uri = options[:redirect_uri] || options["redirect_uri"]
18
+ end
19
+
20
+ def authorization_uri(params = {})
21
+ uri = URI.parse(authorization_endpoint)
22
+ query_params = {
23
+ client_id: identifier,
24
+ response_type: params[:response_type] || "code",
25
+ scope: params[:scope] || "openid profile email",
26
+ redirect_uri: params[:redirect_uri] || @redirect_uri,
27
+ state: params[:state],
28
+ nonce: params[:nonce]
29
+ }.compact
30
+
31
+ # Add PKCE parameters if provided
32
+ query_params[:code_challenge] = params[:code_challenge] if params[:code_challenge]
33
+ query_params[:code_challenge_method] = params[:code_challenge_method] if params[:code_challenge_method]
34
+
35
+ # Add any additional params
36
+ query_params.merge!(params[:extra_params]) if params[:extra_params]
37
+
38
+ uri.query = URI.encode_www_form(query_params)
39
+ uri.to_s
40
+ end
41
+
42
+ def access_token!(params = {}) # rubocop:disable Metrics/MethodLength
43
+ body_params = {
44
+ grant_type: "authorization_code",
45
+ code: params[:code],
46
+ redirect_uri: params[:redirect_uri] || @redirect_uri,
47
+ client_id: identifier,
48
+ client_secret: secret
49
+ }
50
+
51
+ # Add PKCE verifier if provided
52
+ body_params[:code_verifier] = params[:code_verifier] if params[:code_verifier]
53
+
54
+ OmniauthOidc::Logging.instrument("token.exchange", code: "[FILTERED]") do
55
+ response = HttpClient.post(
56
+ token_endpoint,
57
+ body: URI.encode_www_form(body_params),
58
+ headers: {
59
+ "Content-Type" => "application/x-www-form-urlencoded",
60
+ "Accept" => "application/json"
61
+ }
62
+ )
63
+
64
+ ResponseObjects::AccessToken.new(response)
65
+ end
66
+ rescue HttpClient::HttpError => e
67
+ raise OmniauthOidc::TokenError, "Token exchange failed: #{e.message}"
68
+ end
69
+
70
+ def userinfo!(access_token)
71
+ OmniauthOidc::Logging.instrument("userinfo.fetch", endpoint: userinfo_endpoint) do
72
+ response = HttpClient.get(
73
+ userinfo_endpoint,
74
+ headers: {
75
+ "Authorization" => "Bearer #{access_token}",
76
+ "Accept" => "application/json"
77
+ }
78
+ )
79
+
80
+ ResponseObjects::UserInfo.new(response)
81
+ end
82
+ rescue HttpClient::HttpError => e
83
+ raise OmniauthOidc::TokenError, "Failed to fetch user info: #{e.message}"
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OmniauthOidc
4
+ # Fetches and parses OpenID Connect configuration from .well-known endpoint
5
+ class ConfigFetcher
6
+ DEFAULT_CACHE_TTL = 3600 # 1 hour in seconds
7
+
8
+ # Discovery fields the gem reads. Missing ones return nil instead of raising NoMethodError.
9
+ STANDARD_FIELDS = %i[
10
+ issuer authorization_endpoint token_endpoint userinfo_endpoint jwks_uri
11
+ end_session_endpoint scopes_supported id_token_signing_alg_values_supported
12
+ ].freeze
13
+
14
+ # Fields without which the gem cannot verify tokens or start a login
15
+ REQUIRED_FIELDS = %i[issuer authorization_endpoint].freeze
16
+
17
+ CACHE = TtlCache.new(ttl: DEFAULT_CACHE_TTL, name: "Discovery")
18
+ private_constant :CACHE
19
+
20
+ # Config object with dynamic attribute access for OIDC discovery fields
21
+ class Config
22
+ def initialize(attributes = {})
23
+ @attributes = attributes
24
+ end
25
+
26
+ STANDARD_FIELDS.each do |field|
27
+ define_method(field) { self[field] }
28
+ end
29
+
30
+ def [](key)
31
+ @attributes[key.to_sym] || @attributes[key.to_s]
32
+ end
33
+
34
+ def []=(key, value)
35
+ @attributes[key.to_sym] = value
36
+ @attributes[key.to_s] = value
37
+ end
38
+
39
+ def respond_to_missing?(method_name, include_private = false)
40
+ setter = method_name.to_s.end_with?("=")
41
+ key = setter ? method_name.to_s.chomp("=") : method_name.to_s
42
+ setter || @attributes.key?(key.to_sym) || @attributes.key?(key) || super
43
+ end
44
+
45
+ private
46
+
47
+ def method_missing(method_name, *args)
48
+ name = method_name.to_s
49
+
50
+ if name.end_with?("=")
51
+ key = name.chomp("=")
52
+ @attributes[key.to_sym] = args.first
53
+ @attributes[key] = args.first
54
+ elsif @attributes.key?(name.to_sym)
55
+ @attributes[name.to_sym]
56
+ elsif @attributes.key?(name)
57
+ @attributes[name]
58
+ else
59
+ super
60
+ end
61
+ end
62
+ end
63
+
64
+ class << self
65
+ def fetch(endpoint_url, max_retries: 3)
66
+ retries = 0
67
+ begin
68
+ response = OmniauthOidc::HttpClient.get(endpoint_url)
69
+ config = Config.new(deep_symbolize_keys(response))
70
+ rescue OmniauthOidc::HttpClient::HttpError => e
71
+ retries += 1
72
+ retry if retries < max_retries
73
+ raise OmniauthOidc::ConfigurationError, "Failed to fetch OIDC configuration: #{e.message}"
74
+ rescue StandardError => e
75
+ raise OmniauthOidc::ConfigurationError, "Failed to fetch OIDC configuration: #{e.message}"
76
+ end
77
+
78
+ validate!(config, endpoint_url)
79
+ config
80
+ end
81
+
82
+ # Fetches the discovery document, reusing it across requests for ttl seconds.
83
+ # Failed fetches are not cached. A ttl of 0 disables caching.
84
+ def fetch_cached(endpoint_url, ttl: DEFAULT_CACHE_TTL)
85
+ CACHE.fetch(endpoint_url, ttl: ttl) { fetch(endpoint_url) }
86
+ end
87
+
88
+ def clear_cache!
89
+ CACHE.clear!
90
+ end
91
+
92
+ private
93
+
94
+ def validate!(config, endpoint_url)
95
+ missing = REQUIRED_FIELDS.reject { |field| config[field].is_a?(String) && !config[field].empty? }
96
+ return if missing.empty?
97
+
98
+ raise OmniauthOidc::ConfigurationError,
99
+ "OIDC configuration from #{endpoint_url} is missing required fields: #{missing.join(", ")}"
100
+ end
101
+
102
+ # Recursively converts keys of a hash to symbols while retaining the original string keys
103
+ def deep_symbolize_keys(hash)
104
+ result = {}
105
+ hash.each do |key, value|
106
+ sym_key = key.to_sym
107
+ result[sym_key] = value.is_a?(Hash) ? deep_symbolize_keys(value) : value
108
+ result[key] = result[sym_key] # Add the string key as well
109
+ end
110
+ result
111
+ end
112
+ end
113
+ end
114
+ end
@@ -3,7 +3,26 @@
3
3
  module OmniauthOidc
4
4
  class Error < RuntimeError; end
5
5
 
6
+ # Authentication flow errors
6
7
  class MissingCodeError < Error; end
7
-
8
8
  class MissingIdTokenError < Error; end
9
+
10
+ # Configuration errors
11
+ class ConfigurationError < Error; end
12
+ class MissingConfigurationError < ConfigurationError; end
13
+
14
+ # Token/JWT errors
15
+ class TokenError < Error; end
16
+ class TokenVerificationError < TokenError; end
17
+ class TokenExpiredError < TokenError; end
18
+ class InvalidAlgorithmError < TokenError; end
19
+ class InvalidSignatureError < TokenError; end
20
+ class InvalidIssuerError < TokenError; end
21
+ class InvalidAudienceError < TokenError; end
22
+ class InvalidNonceError < TokenError; end
23
+
24
+ # JWKS errors
25
+ class JwksError < Error; end
26
+ class JwksFetchError < JwksError; end
27
+ class KeyNotFoundError < JwksError; end
9
28
  end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "json"
6
+
7
+ module OmniauthOidc
8
+ # Simple HTTP client using Net::HTTP
9
+ class HttpClient
10
+ class HttpError < StandardError; end
11
+
12
+ MAX_REDIRECTS = 5
13
+
14
+ # Explicit timeouts in seconds. Net::HTTP defaults to 60s each, which would let a
15
+ # hanging provider tie up the calling thread for minutes.
16
+ OPEN_TIMEOUT = 5
17
+ READ_TIMEOUT = 10
18
+ WRITE_TIMEOUT = 10
19
+
20
+ def self.get(url, headers: {})
21
+ uri = URI.parse(url)
22
+ request = Net::HTTP::Get.new(uri)
23
+ headers.each { |key, value| request[key] = value }
24
+
25
+ response = execute_request(uri, request)
26
+ handle_response(response, url, headers: headers, redirects_remaining: MAX_REDIRECTS)
27
+ end
28
+
29
+ def self.post(url, body: nil, headers: {})
30
+ uri = URI.parse(url)
31
+ request = Net::HTTP::Post.new(uri)
32
+ request["Content-Type"] = "application/x-www-form-urlencoded" unless headers["Content-Type"]
33
+ headers.each { |key, value| request[key] = value }
34
+ request.body = body if body
35
+
36
+ response = execute_request(uri, request)
37
+ handle_response(response, url)
38
+ end
39
+
40
+ def self.execute_request(uri, request)
41
+ OmniauthOidc::Logging.instrument("http.request", method: request.method, uri: uri.to_s) do
42
+ Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https", open_timeout: OPEN_TIMEOUT,
43
+ read_timeout: READ_TIMEOUT, write_timeout: WRITE_TIMEOUT) do |http|
44
+ http.request(request)
45
+ end
46
+ end
47
+ end
48
+ private_class_method :execute_request
49
+
50
+ def self.handle_response(response, url, headers: {}, redirects_remaining: 0)
51
+ case response
52
+ when Net::HTTPSuccess
53
+ parse_json_response(response.body)
54
+ when Net::HTTPRedirection
55
+ raise HttpError, "Too many redirects for #{url}" if redirects_remaining <= 0
56
+
57
+ location = response["location"]
58
+ raise HttpError, "HTTP redirect from #{url} with no location header" unless location
59
+
60
+ redirect_uri = URI.parse(location)
61
+ # Resolve relative redirects
62
+ redirect_uri = URI.join(url, location) unless redirect_uri.host
63
+
64
+ OmniauthOidc::Logging.debug("Following redirect", from: url, to: redirect_uri.to_s)
65
+ follow_redirect(redirect_uri, headers: redirect_headers(URI.parse(url), redirect_uri, headers),
66
+ redirects_remaining: redirects_remaining - 1)
67
+ else
68
+ raise HttpError, "HTTP request failed: #{response.code} #{response.message} for #{url}"
69
+ end
70
+ end
71
+ private_class_method :handle_response
72
+
73
+ def self.follow_redirect(uri, headers: {}, redirects_remaining: 0)
74
+ request = Net::HTTP::Get.new(uri)
75
+ headers.each { |key, value| request[key] = value }
76
+
77
+ response = execute_request(uri, request)
78
+ handle_response(response, uri.to_s, headers: headers, redirects_remaining: redirects_remaining)
79
+ end
80
+ private_class_method :follow_redirect
81
+
82
+ # Refuses HTTPS to HTTP downgrades, and drops credentials when a redirect leaves the
83
+ # original origin, so a bearer token is never sent in cleartext or to another host.
84
+ def self.redirect_headers(from, to, headers)
85
+ if from.scheme == "https" && to.scheme != "https"
86
+ raise HttpError, "Refusing to follow redirect from #{from} to non-HTTPS #{to}"
87
+ end
88
+
89
+ same_origin = [from.scheme, from.host, from.port] == [to.scheme, to.host, to.port]
90
+ return headers if same_origin
91
+
92
+ headers.reject { |key, _| key.to_s.casecmp?("Authorization") }
93
+ end
94
+ private_class_method :redirect_headers
95
+
96
+ def self.parse_json_response(body)
97
+ JSON.parse(body)
98
+ rescue JSON::ParserError => e
99
+ raise HttpError, "Failed to parse JSON response: #{e.message}"
100
+ end
101
+ private_class_method :parse_json_response
102
+ end
103
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "jwt"
4
+ require "openssl"
5
+
6
+ module OmniauthOidc
7
+ # Handles JWK/JWKS operations for JWT verification
8
+ class JwkHandler
9
+ # Parsed key with its kid for matching
10
+ KeyWithId = Struct.new(:kid, :keypair, keyword_init: true)
11
+
12
+ def self.parse_jwks(jwks_data)
13
+ return nil unless jwks_data
14
+
15
+ jwks_data = JSON.parse(jwks_data) if jwks_data.is_a?(String)
16
+
17
+ # Handle JWKS (set of keys)
18
+ if jwks_data["keys"]
19
+ jwks_data["keys"].filter_map { |key_data| jwk_to_key(key_data) }
20
+ # Handle single JWK
21
+ else
22
+ [jwk_to_key(jwks_data)].compact
23
+ end
24
+ end
25
+
26
+ def self.jwk_to_key(jwk_data)
27
+ keypair = JWT::JWK.import(jwk_data).keypair
28
+ kid = jwk_data["kid"] || jwk_data[:kid]
29
+ KeyWithId.new(kid: kid, keypair: keypair)
30
+ rescue StandardError => e
31
+ OmniauthOidc::Logging.error("Failed to import JWK", error: e.message)
32
+ nil
33
+ end
34
+
35
+ # Find the right key from JWKS based on kid (key ID)
36
+ def self.find_key(keys, kid = nil)
37
+ return keys.first&.keypair if kid.nil? || keys.size <= 1
38
+
39
+ matched = keys.find { |k| k.kid == kid }
40
+ if matched
41
+ matched.keypair
42
+ else
43
+ OmniauthOidc::Logging.warn("No JWK found matching kid '#{kid}', falling back to first key")
44
+ keys.first&.keypair
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OmniauthOidc
4
+ # Process-wide JWKS cache with configurable TTL and force refresh capability
5
+ class JwksCache < TtlCache
6
+ DEFAULT_TTL = 3600 # 1 hour in seconds
7
+ INSTANCE_MUTEX = Mutex.new
8
+ private_constant :INSTANCE_MUTEX
9
+
10
+ class << self
11
+ def instance
12
+ @instance || INSTANCE_MUTEX.synchronize { @instance ||= new }
13
+ end
14
+
15
+ # Clear all cached keys (useful for testing)
16
+ def clear!
17
+ instance.clear!
18
+ end
19
+
20
+ # Force refresh a specific JWKS URI on next access
21
+ def invalidate(jwks_uri)
22
+ instance.invalidate(jwks_uri)
23
+ end
24
+ end
25
+
26
+ def initialize(ttl: DEFAULT_TTL)
27
+ super(ttl: ttl, name: "JWKS")
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "logger"
4
+
5
+ module OmniauthOidc
6
+ # Logging module providing both Ruby Logger and ActiveSupport::Notifications support
7
+ module Logging
8
+ class << self
9
+ attr_writer :logger
10
+
11
+ def logger
12
+ @logger ||= default_logger
13
+ end
14
+
15
+ def log_level=(level)
16
+ logger.level = level
17
+ end
18
+
19
+ def instrument(event_name, payload = {}, &block)
20
+ full_event_name = "#{event_name}.omniauth_oidc"
21
+
22
+ # Always log the event
23
+ log_event(event_name, payload)
24
+
25
+ # Use ActiveSupport::Notifications if available
26
+ if defined?(ActiveSupport::Notifications)
27
+ ActiveSupport::Notifications.instrument(full_event_name, payload, &block)
28
+ elsif block
29
+ yield payload
30
+ end
31
+ end
32
+
33
+ def debug(message, context = {})
34
+ log(:debug, message, context)
35
+ end
36
+
37
+ def info(message, context = {})
38
+ log(:info, message, context)
39
+ end
40
+
41
+ def warn(message, context = {})
42
+ log(:warn, message, context)
43
+ end
44
+
45
+ def error(message, context = {})
46
+ log(:error, message, context)
47
+ end
48
+
49
+ private
50
+
51
+ def default_logger
52
+ Logger.new($stdout).tap do |log|
53
+ log.progname = "OmniauthOidc"
54
+ log.level = Logger::WARN # Default to WARN to avoid noise
55
+ end
56
+ end
57
+
58
+ def log(level, message, context)
59
+ formatted_message = context.empty? ? message : "#{message} #{context.inspect}"
60
+ logger.send(level, formatted_message)
61
+ end
62
+
63
+ def log_event(event_name, payload)
64
+ # Log at debug level for instrumentation events
65
+ sanitized_payload = sanitize_payload(payload)
66
+ debug("Event: #{event_name}", sanitized_payload)
67
+ end
68
+
69
+ def sanitize_payload(payload)
70
+ # Remove sensitive data from logs
71
+ sensitive_keys = %i[secret client_secret access_token id_token refresh_token code_verifier]
72
+ payload.reject { |k, _| sensitive_keys.include?(k.to_sym) }
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OmniauthOidc
4
+ # Simple response objects to replace OpenIDConnect::ResponseObject classes
5
+ module ResponseObjects
6
+ # Represents an OIDC ID Token with claims
7
+ class IdToken
8
+ attr_reader :raw_attributes
9
+
10
+ def initialize(attributes = {})
11
+ @raw_attributes = attributes.is_a?(Hash) ? attributes : attributes.to_h
12
+ end
13
+
14
+ def sub
15
+ raw_attributes["sub"]
16
+ end
17
+
18
+ def iss
19
+ raw_attributes["iss"]
20
+ end
21
+
22
+ def aud
23
+ raw_attributes["aud"]
24
+ end
25
+
26
+ def exp
27
+ raw_attributes["exp"]
28
+ end
29
+
30
+ def iat
31
+ raw_attributes["iat"]
32
+ end
33
+
34
+ def nonce
35
+ raw_attributes["nonce"]
36
+ end
37
+
38
+ # Allow method-style access to claims
39
+ def method_missing(method_name, *args)
40
+ return raw_attributes[method_name.to_s] if raw_attributes.key?(method_name.to_s)
41
+
42
+ super
43
+ end
44
+
45
+ def respond_to_missing?(method_name, include_private = false)
46
+ raw_attributes.key?(method_name.to_s) || super
47
+ end
48
+ end
49
+
50
+ # Represents OIDC UserInfo response
51
+ class UserInfo
52
+ attr_reader :raw_attributes
53
+
54
+ def initialize(attributes = {})
55
+ @raw_attributes = attributes.is_a?(Hash) ? attributes : attributes.to_h
56
+ end
57
+
58
+ # Standard OIDC claims
59
+ def sub
60
+ raw_attributes["sub"]
61
+ end
62
+
63
+ def name
64
+ raw_attributes["name"]
65
+ end
66
+
67
+ def given_name
68
+ raw_attributes["given_name"]
69
+ end
70
+
71
+ def family_name
72
+ raw_attributes["family_name"]
73
+ end
74
+
75
+ def middle_name
76
+ raw_attributes["middle_name"]
77
+ end
78
+
79
+ def nickname
80
+ raw_attributes["nickname"]
81
+ end
82
+
83
+ def preferred_username
84
+ raw_attributes["preferred_username"]
85
+ end
86
+
87
+ def profile
88
+ raw_attributes["profile"]
89
+ end
90
+
91
+ def picture
92
+ raw_attributes["picture"]
93
+ end
94
+
95
+ def website
96
+ raw_attributes["website"]
97
+ end
98
+
99
+ def email
100
+ raw_attributes["email"]
101
+ end
102
+
103
+ def email_verified
104
+ raw_attributes["email_verified"]
105
+ end
106
+
107
+ def gender
108
+ raw_attributes["gender"]
109
+ end
110
+
111
+ def birthdate
112
+ raw_attributes["birthdate"]
113
+ end
114
+
115
+ def zoneinfo
116
+ raw_attributes["zoneinfo"]
117
+ end
118
+
119
+ def locale
120
+ raw_attributes["locale"]
121
+ end
122
+
123
+ def phone_number
124
+ raw_attributes["phone_number"]
125
+ end
126
+
127
+ def phone_number_verified
128
+ raw_attributes["phone_number_verified"]
129
+ end
130
+
131
+ def address
132
+ raw_attributes["address"]
133
+ end
134
+
135
+ def updated_at
136
+ raw_attributes["updated_at"]
137
+ end
138
+
139
+ # Allow method-style access to custom claims
140
+ def method_missing(method_name, *args)
141
+ return raw_attributes[method_name.to_s] if raw_attributes.key?(method_name.to_s)
142
+
143
+ super
144
+ end
145
+
146
+ def respond_to_missing?(method_name, include_private = false)
147
+ raw_attributes.key?(method_name.to_s) || super
148
+ end
149
+ end
150
+
151
+ # Represents an OAuth2 Access Token
152
+ class AccessToken
153
+ attr_reader :access_token, :token_type, :expires_in, :refresh_token, :scope, :id_token
154
+
155
+ def initialize(attributes = {})
156
+ @access_token = attributes["access_token"] || attributes[:access_token]
157
+ @token_type = attributes["token_type"] || attributes[:token_type]
158
+ @expires_in = attributes["expires_in"] || attributes[:expires_in]
159
+ @refresh_token = attributes["refresh_token"] || attributes[:refresh_token]
160
+ @scope = attributes["scope"] || attributes[:scope]
161
+ @id_token = attributes["id_token"] || attributes[:id_token]
162
+ end
163
+
164
+ def to_h
165
+ {
166
+ "access_token" => access_token,
167
+ "token_type" => token_type,
168
+ "expires_in" => expires_in,
169
+ "refresh_token" => refresh_token,
170
+ "scope" => scope,
171
+ "id_token" => id_token
172
+ }.compact
173
+ end
174
+ end
175
+ end
176
+ end