Module: OmniauthOpenidFederation::Tasks::LocalEndpointTester

Defined in:
lib/omniauth_openid_federation/tasks/local_endpoint_tester.rb

Class Method Summary collapse

Class Method Details

.detect_key_status(jwks) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/omniauth_openid_federation/tasks/local_endpoint_tester.rb', line 145

def self.detect_key_status(jwks)
  return {type: :unknown, count: 0, recommendation: "No keys found in entity statement"} unless jwks

  keys = jwks.is_a?(Hash) ? (jwks["keys"] || jwks[:keys] || []) : []
  return {type: :unknown, count: 0, recommendation: "No keys found in entity statement"} if keys.empty?

  # Check for duplicate kids (indicates single key used for both signing and encryption)
  kids = keys.map { |k| k["kid"] || k[:kid] }.compact
  duplicate_kids = kids.length != kids.uniq.length

  # Check use fields
  uses = keys.map { |k| k["use"] || k[:use] }.compact.uniq
  has_sig = uses.include?("sig")
  has_enc = uses.include?("enc")
  has_both_uses = has_sig && has_enc

  if duplicate_kids
    {
      type: :single,
      count: keys.length,
      recommendation: "⚠️  Single key detected (duplicate Key IDs). This is NOT RECOMMENDED for production. Use separate signing and encryption keys for better security. Generate with: rake openid_federation:prepare_client_keys[separate]"
    }
  elsif has_both_uses && keys.length >= 2
    {
      type: :separate,
      count: keys.length,
      recommendation: "✅ Separate keys detected (recommended for production)"
    }
  elsif keys.length == 1
    {
      type: :single,
      count: 1,
      recommendation: "⚠️  Single key detected. This is NOT RECOMMENDED for production. Use separate signing and encryption keys for better security. Generate with: rake openid_federation:prepare_client_keys[separate]"
    }
  else
    {
      type: :unknown,
      count: keys.length,
      recommendation: "Key configuration unclear. Ensure keys have unique Key IDs and proper 'use' fields ('sig' for signing, 'enc' for encryption)"
    }
  end
end

.run(base_url:) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/omniauth_openid_federation/tasks/local_endpoint_tester.rb', line 11

def self.run(base_url:)
  entity_statement_url = "#{base_url}/.well-known/openid-federation"
  validation_warnings = []

  # Fetch and parse entity statement
  begin
    entity_statement = Federation::EntityStatement.fetch!(
      entity_statement_url,
      fingerprint: nil # Don't validate fingerprint for local testing
    )
  rescue ValidationError => e
    # Don't block execution - treat validation errors as warnings
    validation_warnings << e.message
    # Try to parse anyway for diagnostic purposes
    begin
      require "json"
      require "base64"
      response = HttpClient.get(entity_statement_url)
      entity_statement = Federation::EntityStatement.new(response.body.to_s)
    rescue
      raise FetchError, "Failed to fetch entity statement: #{e.message}"
    end
  end

  begin
     = entity_statement.parse
  rescue ValidationError => e
    validation_warnings << e.message
    # Try to extract basic info even if validation fails
    begin
      require "json"
      require "base64"
      jwt_parts = entity_statement.entity_statement.split(".")
      payload = JSON.parse(Base64.urlsafe_decode64(jwt_parts[1]))
      # Preserve original structure (string keys from JSON)
       = {
        issuer: payload["iss"],
        sub: payload["sub"],
        exp: payload["exp"],
        iat: payload["iat"],
        jwks: payload["jwks"],
        metadata: payload["metadata"] || {}
      }
    rescue
      raise FetchError, "Failed to parse entity statement: #{e.message}"
    end
  end

  # Extract endpoints - handle both provider and relying party entity types
   = [:metadata] || {}
   = [:openid_provider] || ["openid_provider"] || {}
   = [:openid_relying_party] || ["openid_relying_party"] || {}

  endpoints = {}

  # Provider endpoints
  if .any?
    endpoints["Authorization Endpoint"] = [:authorization_endpoint] || ["authorization_endpoint"]
    endpoints["Token Endpoint"] = [:token_endpoint] || ["token_endpoint"]
    endpoints["UserInfo Endpoint"] = [:userinfo_endpoint] || ["userinfo_endpoint"]
    endpoints["JWKS URI"] = [:jwks_uri] || ["jwks_uri"]
    endpoints["Signed JWKS URI"] = [:signed_jwks_uri] || ["signed_jwks_uri"]
    endpoints["End Session Endpoint"] = [:end_session_endpoint] || ["end_session_endpoint"]
  end

  # Relying Party endpoints (JWKS only)
  if .any?
    endpoints["JWKS URI"] ||= [:jwks_uri] || ["jwks_uri"]
    endpoints["Signed JWKS URI"] ||= [:signed_jwks_uri] || ["signed_jwks_uri"]
  end

  endpoints.compact!

  # Detect key configuration status
  key_status = detect_key_status([:jwks])

  # Test endpoints
  results = {}
  entity_jwks = [:jwks]

  endpoints.each do |name, url|
    next unless url

    begin
      case name
      when "JWKS URI"
        jwks = Jwks::Fetch.run(url)
        key_count = jwks["keys"]&.length || 0
        results[name] = {status: :success, keys: key_count}

      when "Signed JWKS URI"
        signed_jwks = Federation::SignedJWKS.fetch!(
          url,
          entity_jwks,
          force_refresh: true
        )
        key_count = signed_jwks["keys"]&.length || 0
        results[name] = {status: :success, keys: key_count}

      else
        begin
          URI.parse(url)
        rescue URI::InvalidURIError => error
          results[name] = {status: :error, message: "Invalid URL: #{error.message}"}
          next
        end

        response = HttpClient.get(url, max_retries: 0)

        results[name] = if response.status.code < 400
          {status: :success, code: response.status.code.to_s}
        else
          {status: :warning, code: response.status.code.to_s, body: response.body.to_s}
        end
      end
    rescue FetchError, Federation::SignedJWKS::FetchError => e
      results[name] = {status: :error, message: e.message}
    rescue Federation::SignedJWKS::ValidationError => e
      results[name] = {status: :error, message: e.message}
    rescue => e
      results[name] = {status: :error, message: e.message}
    end
  end

  {
    success: true,
    entity_statement: entity_statement,
    metadata: ,
    results: results,
    key_status: key_status,
    validation_warnings: validation_warnings
  }
end