omniauth_openid_federation 2.2.1 → 2.3.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.
@@ -1,774 +0,0 @@
1
- #!/usr/bin/env ruby
2
- # frozen_string_literal: true
3
-
4
- # Enhanced Mock OpenID Provider (OP) Server for OpenID Federation Testing
5
- #
6
- # Standalone Webrick server that acts as a mock OP server
7
- # for testing OpenID Federation flows. It supports:
8
- # - Entity Configuration endpoint (/.well-known/openid-federation)
9
- # - Fetch Endpoint (/.well-known/openid-federation/fetch)
10
- # - Authorization Endpoint (/auth) with trust chain resolution and request object validation
11
- # - Token Endpoint (/token) with ID Token signing
12
- # - Request object validation (signed and optionally encrypted)
13
- # - Error injection modes for testing failure scenarios
14
- #
15
- # Configuration:
16
- # - Load from YAML file: config/mock_op.yml
17
- # - Or set environment variables
18
- #
19
- # Usage:
20
- # ruby examples/mock_op_server.rb
21
- #
22
- # Access:
23
- # http://localhost:9292/.well-known/openid-federation
24
- # http://localhost:9292/auth?request=<signed_jwt>
25
- # http://localhost:9292/token (POST with code)
26
- #
27
- # Error Injection Modes (via query param ?error_mode=<mode>):
28
- # - invalid_statement: Return invalid entity statement
29
- # - wrong_keys: Return wrong JWKS keys
30
- # - invalid_request: Reject request object
31
- # - invalid_signature: Return invalid signature
32
- # - expired_statement: Return expired entity statement
33
- # - missing_metadata: Return statement without metadata
34
-
35
- require "bundler/setup"
36
- require "webrick"
37
- require "yaml"
38
- require "json"
39
- require "jwt"
40
- require "openssl"
41
- require "base64"
42
- require "uri"
43
- require "cgi"
44
- require "securerandom"
45
-
46
- # Add the gem to the load path
47
- $LOAD_PATH.unshift(File.expand_path("../lib", __dir__))
48
- require "omniauth_openid_federation"
49
-
50
- class MockOPServer
51
- # Load configuration from YAML or environment
52
- def self.load_config
53
- config_path = File.expand_path("../config/mock_op.yml", __dir__)
54
- if File.exist?(config_path)
55
- YAML.load_file(config_path)
56
- else
57
- # Fall back to environment variables
58
- {
59
- "entity_id" => ENV["OP_ENTITY_ID"] || "http://localhost:9292",
60
- "server_host" => ENV["OP_SERVER_HOST"] || "localhost:9292",
61
- "signing_key" => ENV["OP_SIGNING_KEY"],
62
- "encryption_key" => ENV["OP_ENCRYPTION_KEY"],
63
- "trust_anchors" => parse_trust_anchors(ENV["OP_TRUST_ANCHORS"]),
64
- "authority_hints" => parse_array(ENV["OP_AUTHORITY_HINTS"]),
65
- "op_metadata" => parse_json(ENV["OP_METADATA"]) || default_op_metadata,
66
- "require_request_encryption" => ENV["OP_REQUIRE_ENCRYPTION"] == "true",
67
- "validate_request_objects" => ENV["OP_VALIDATE_REQUESTS"] != "false"
68
- }
69
- end
70
- end
71
-
72
- def self.parse_trust_anchors(str)
73
- return [] unless str
74
- JSON.parse(str)
75
- rescue JSON::ParserError
76
- []
77
- end
78
-
79
- def self.parse_array(str)
80
- return [] unless str
81
- str.split(",").map(&:strip)
82
- end
83
-
84
- def self.parse_json(str)
85
- return nil unless str
86
- JSON.parse(str)
87
- rescue JSON::ParserError
88
- nil
89
- end
90
-
91
- def self.default_op_metadata
92
- {
93
- "issuer" => "http://localhost:9292",
94
- "authorization_endpoint" => "http://localhost:9292/auth",
95
- "token_endpoint" => "http://localhost:9292/token",
96
- "userinfo_endpoint" => "http://localhost:9292/userinfo",
97
- "jwks_uri" => "http://localhost:9292/.well-known/jwks.json",
98
- "signed_jwks_uri" => "http://localhost:9292/.well-known/signed-jwks.json",
99
- "client_registration_types_supported" => ["automatic", "explicit"],
100
- "response_types_supported" => ["code"],
101
- "grant_types_supported" => ["authorization_code"],
102
- "id_token_signing_alg_values_supported" => ["RS256"],
103
- "id_token_encryption_alg_values_supported" => ["RSA-OAEP"],
104
- "id_token_encryption_enc_values_supported" => ["A128CBC-HS256"],
105
- "request_object_signing_alg_values_supported" => ["RS256"],
106
- "request_object_encryption_alg_values_supported" => ["RSA-OAEP"],
107
- "request_object_encryption_enc_values_supported" => ["A128CBC-HS256"],
108
- "scopes_supported" => ["openid", "profile", "email"]
109
- }
110
- end
111
-
112
- def self.load_signing_key(key_data)
113
- if OmniauthOpenidFederation::StringHelpers.blank?(key_data)
114
- # Generate a new key for testing
115
- OpenSSL::PKey::RSA.new(2048)
116
- elsif key_data.is_a?(String)
117
- if key_data.include?("BEGIN")
118
- OpenSSL::PKey::RSA.new(key_data)
119
- else
120
- OpenSSL::PKey::RSA.new(Base64.decode64(key_data))
121
- end
122
- else
123
- raise "Invalid signing key format"
124
- end
125
- end
126
-
127
- def self.load_encryption_key(key_data)
128
- return nil if OmniauthOpenidFederation::StringHelpers.blank?(key_data)
129
- load_signing_key(key_data)
130
- end
131
-
132
- def self.normalize_trust_anchors(trust_anchors)
133
- trust_anchors.map do |ta|
134
- {
135
- entity_id: ta["entity_id"] || ta[:entity_id],
136
- jwks: ta["jwks"] || ta[:jwks]
137
- }
138
- end
139
- end
140
-
141
- # Initialize configuration
142
- CONFIG = load_config
143
- ENTITY_ID = CONFIG["entity_id"] || "http://localhost:9292"
144
- SERVER_HOST = CONFIG["server_host"] || "localhost:9292"
145
- SIGNING_KEY = load_signing_key(CONFIG["signing_key"])
146
- ENCRYPTION_KEY = load_encryption_key(CONFIG["encryption_key"]) || SIGNING_KEY
147
- TRUST_ANCHORS = CONFIG["trust_anchors"] || []
148
- AUTHORITY_HINTS = CONFIG["authority_hints"] || []
149
- OP_METADATA = CONFIG["op_metadata"] || default_op_metadata
150
- REQUIRE_REQUEST_ENCRYPTION = CONFIG["require_request_encryption"] || false
151
- VALIDATE_REQUEST_OBJECTS = CONFIG["validate_request_objects"] != false
152
-
153
- # Store for authorization codes (in production, use a database)
154
- AUTHORIZATION_CODES = {}
155
-
156
- # Store for registered RPs (for testing)
157
- REGISTERED_RPS = {}
158
-
159
- # Configure FederationEndpoint (deferred until server starts)
160
- def self.configure_federation_endpoint
161
- base_url = base_url_static
162
- # Use localhost URLs if entity_id is localhost (for isolation)
163
- if ENTITY_ID.include?("localhost")
164
- # Override metadata to use localhost URLs
165
- metadata = OP_METADATA.dup
166
- metadata["issuer"] = ENTITY_ID
167
- metadata["authorization_endpoint"] = "#{base_url}/auth"
168
- metadata["token_endpoint"] = "#{base_url}/token"
169
- metadata["userinfo_endpoint"] = "#{base_url}/userinfo"
170
- metadata["jwks_uri"] = "#{base_url}/.well-known/jwks.json"
171
- metadata["signed_jwks_uri"] = "#{base_url}/.well-known/signed-jwks.json"
172
- else
173
- metadata = OP_METADATA.merge(
174
- "issuer" => ENTITY_ID,
175
- "authorization_endpoint" => "#{base_url}/auth",
176
- "token_endpoint" => "#{base_url}/token",
177
- "userinfo_endpoint" => "#{base_url}/userinfo",
178
- "jwks_uri" => "#{base_url}/.well-known/jwks.json",
179
- "signed_jwks_uri" => "#{base_url}/.well-known/signed-jwks.json"
180
- )
181
- end
182
-
183
- OmniauthOpenidFederation::FederationEndpoint.auto_configure(
184
- issuer: ENTITY_ID,
185
- private_key: SIGNING_KEY,
186
- metadata: {
187
- openid_provider: metadata
188
- }
189
- )
190
-
191
- # Set authority_hints if provided (must be done after auto_configure)
192
- if AUTHORITY_HINTS.any?
193
- OmniauthOpenidFederation::FederationEndpoint.configure do |config|
194
- config.authority_hints = AUTHORITY_HINTS
195
- end
196
- end
197
- end
198
-
199
- # Configure subordinate statements if provided
200
- def self.configure_subordinate_statements
201
- if CONFIG["subordinate_statements"]
202
- OmniauthOpenidFederation::FederationEndpoint.configure do |config|
203
- config.subordinate_statements = CONFIG["subordinate_statements"]
204
- end
205
- end
206
- end
207
-
208
- def self.base_url_static
209
- "http://#{SERVER_HOST}"
210
- end
211
-
212
- # Webrick servlet to handle requests
213
- class Servlet < WEBrick::HTTPServlet::AbstractServlet
214
- def service(req, res)
215
- path = req.path
216
- method = req.request_method
217
- params = parse_query(req.query_string)
218
- error_mode = params["error_mode"] || req.header["x-error-mode"]&.first
219
-
220
- # Parse body for POST requests
221
- body_params = {}
222
- if method == "POST" && req.body && !req.body.empty?
223
- body_params = if req.content_type&.include?("application/json")
224
- begin
225
- JSON.parse(req.body)
226
- rescue
227
- {}
228
- end
229
- else
230
- parse_form_data(req.body)
231
- end
232
- end
233
-
234
- # Merge query params and body params
235
- all_params = params.merge(body_params)
236
-
237
- case [method, path]
238
- when ["GET", "/"]
239
- handle_health_check(req, res)
240
- when ["GET", "/.well-known/openid-federation"]
241
- handle_entity_configuration(req, res, error_mode)
242
- when ["GET", "/.well-known/openid-federation/fetch"]
243
- handle_fetch(req, res, params, error_mode)
244
- when ["GET", "/.well-known/jwks.json"]
245
- handle_jwks(req, res, error_mode)
246
- when ["GET", "/.well-known/signed-jwks.json"]
247
- handle_signed_jwks(req, res, error_mode)
248
- when ["GET", "/auth"]
249
- handle_authorization(req, res, all_params, error_mode)
250
- when ["POST", "/token"]
251
- handle_token(req, res, all_params)
252
- when ["GET", "/userinfo"]
253
- handle_userinfo(req, res)
254
- else
255
- res.status = 404
256
- res.content_type = "application/json"
257
- res.body = {error: "not_found", error_description: "Endpoint not found"}.to_json
258
- end
259
- end
260
-
261
- private
262
-
263
- def parse_query(query_string)
264
- return {} unless query_string
265
- CGI.parse(query_string).transform_values { |v| v.first }
266
- end
267
-
268
- def parse_form_data(body)
269
- return {} unless body
270
- CGI.parse(body).transform_values { |v| v.first }
271
- end
272
-
273
- def base_url(req)
274
- scheme = req.request_uri.scheme || "http"
275
- host = req.host
276
- port = req.port
277
- port_str = ((port == 80 && scheme == "http") || (port == 443 && scheme == "https")) ? "" : ":#{port}"
278
- "#{scheme}://#{host}#{port_str}"
279
- end
280
-
281
- def json_response(res, data, status: 200)
282
- res.status = status
283
- res.content_type = "application/json"
284
- res.body = data.to_json
285
- end
286
-
287
- def error_response(res, error, description, status: 400)
288
- json_response(res, {error: error, error_description: description}, status: status)
289
- end
290
-
291
- def handle_health_check(req, res)
292
- json_response(res, {
293
- status: "ok",
294
- entity_id: MockOPServer::ENTITY_ID,
295
- endpoints: {
296
- entity_configuration: "#{base_url(req)}/.well-known/openid-federation",
297
- fetch: "#{base_url(req)}/.well-known/openid-federation/fetch",
298
- authorization: "#{base_url(req)}/auth",
299
- token: "#{base_url(req)}/token",
300
- userinfo: "#{base_url(req)}/userinfo"
301
- },
302
- error_modes: [
303
- "invalid_statement",
304
- "wrong_keys",
305
- "invalid_request",
306
- "invalid_signature",
307
- "expired_statement",
308
- "missing_metadata"
309
- ]
310
- })
311
- end
312
-
313
- def handle_entity_configuration(req, res, error_mode)
314
- if error_mode == "invalid_statement"
315
- res.status = 200
316
- res.content_type = "application/jwt"
317
- res.body = "invalid.entity.statement"
318
- return
319
- end
320
-
321
- if error_mode == "expired_statement"
322
- res.status = 200
323
- res.content_type = "application/jwt"
324
- res.body = generate_expired_entity_statement
325
- return
326
- end
327
-
328
- if error_mode == "wrong_keys"
329
- res.status = 200
330
- res.content_type = "application/jwt"
331
- res.body = generate_entity_statement_with_wrong_keys
332
- return
333
- end
334
-
335
- if error_mode == "missing_metadata"
336
- res.status = 200
337
- res.content_type = "application/jwt"
338
- res.body = generate_entity_statement_without_metadata
339
- return
340
- end
341
-
342
- entity_statement = OmniauthOpenidFederation::FederationEndpoint.generate_entity_statement
343
- res.status = 200
344
- res.content_type = "application/jwt"
345
- res["Cache-Control"] = "public, max-age=3600"
346
- res.body = entity_statement
347
- end
348
-
349
- def handle_fetch(req, res, params, error_mode)
350
- subject_entity_id = params["sub"]
351
-
352
- unless subject_entity_id
353
- return error_response(res, "invalid_request", "Missing required parameter: sub")
354
- end
355
-
356
- if subject_entity_id == MockOPServer::ENTITY_ID
357
- return error_response(res, "invalid_request", "Subject cannot be the issuer")
358
- end
359
-
360
- if error_mode == "invalid_statement"
361
- res.status = 200
362
- res.content_type = "application/entity-statement+jwt"
363
- res.body = "invalid.subordinate.statement"
364
- return
365
- end
366
-
367
- subordinate_statement = OmniauthOpenidFederation::FederationEndpoint.get_subordinate_statement(subject_entity_id)
368
-
369
- unless subordinate_statement
370
- return error_response(res, "not_found", "Subordinate Statement not found for subject: #{subject_entity_id}", status: 404)
371
- end
372
-
373
- res.status = 200
374
- res.content_type = "application/entity-statement+jwt"
375
- res["Cache-Control"] = "public, max-age=3600"
376
- res.body = subordinate_statement
377
- end
378
-
379
- def handle_jwks(req, res, error_mode)
380
- if error_mode == "wrong_keys"
381
- wrong_key = OpenSSL::PKey::RSA.new(2048)
382
- jwk = JWT::JWK.new(wrong_key.public_key)
383
- jwks = {keys: [jwk.export]}
384
- return json_response(res, jwks)
385
- end
386
-
387
- jwks = OmniauthOpenidFederation::FederationEndpoint.current_jwks
388
- res.status = 200
389
- res.content_type = "application/json"
390
- res["Cache-Control"] = "public, max-age=3600"
391
- res.body = jwks.to_json
392
- end
393
-
394
- def handle_signed_jwks(req, res, error_mode)
395
- if error_mode == "invalid_signature"
396
- res.status = 200
397
- res.content_type = "application/jwt"
398
- res.body = generate_invalid_signed_jwks
399
- return
400
- end
401
-
402
- signed_jwks = OmniauthOpenidFederation::FederationEndpoint.generate_signed_jwks
403
- res.status = 200
404
- res.content_type = "application/jwt"
405
- res["Cache-Control"] = "public, max-age=3600"
406
- res.body = signed_jwks
407
- end
408
-
409
- def handle_authorization(req, res, params, error_mode)
410
- request_object = params["request"]
411
- client_id = params["client_id"]
412
- redirect_uri = params["redirect_uri"]
413
- state = params["state"]
414
- nonce = params["nonce"]
415
-
416
- # Validate request object if present
417
- if request_object
418
- if error_mode == "invalid_request"
419
- return error_response(res, "invalid_request_object", "Request object validation failed")
420
- end
421
-
422
- begin
423
- validated_request = validate_request_object(request_object, error_mode)
424
- client_id = validated_request[:client_id] || validated_request["client_id"] || client_id
425
- redirect_uri = validated_request[:redirect_uri] || validated_request["redirect_uri"] || redirect_uri
426
- state = validated_request[:state] || validated_request["state"] || state
427
- nonce = validated_request[:nonce] || validated_request["nonce"] || nonce
428
- rescue OmniauthOpenidFederation::DecryptionError => e
429
- return error_response(res, "invalid_request_object", "Request object decryption failed: #{e.message}")
430
- rescue => e
431
- return error_response(res, "invalid_request_object", "Request object validation failed: #{e.message}")
432
- end
433
- end
434
-
435
- unless client_id && redirect_uri
436
- return error_response(res, "invalid_request", "Missing required parameters: client_id, redirect_uri")
437
- end
438
-
439
- # Resolve RP's trust chain if client_id is an Entity ID
440
- rp_effective_metadata = nil
441
- if is_entity_id?(client_id) && MockOPServer::TRUST_ANCHORS.any?
442
- begin
443
- resolver = OmniauthOpenidFederation::Federation::TrustChainResolver.new(
444
- leaf_entity_id: client_id,
445
- trust_anchors: MockOPServer.normalize_trust_anchors(MockOPServer::TRUST_ANCHORS)
446
- )
447
- trust_chain = resolver.resolve!
448
-
449
- # Extract RP metadata from trust chain
450
- leaf_statement = trust_chain.first
451
- leaf_parsed = leaf_statement.is_a?(Hash) ? leaf_statement : leaf_statement.parse
452
- leaf_metadata = extract_metadata_from_parsed(leaf_parsed)
453
-
454
- # Merge metadata policies
455
- merger = OmniauthOpenidFederation::Federation::MetadataPolicyMerger.new(trust_chain: trust_chain)
456
- rp_effective_metadata = merger.merge_and_apply(leaf_metadata)
457
- rescue => e
458
- return error_response(res, "invalid_client", "Failed to resolve client trust chain: #{e.message}")
459
- end
460
- end
461
-
462
- # Extract redirect_uri from effective metadata if available
463
- if rp_effective_metadata
464
- rp_metadata = rp_effective_metadata[:openid_relying_party] || rp_effective_metadata["openid_relying_party"]
465
- if rp_metadata
466
- allowed_redirect_uris = rp_metadata[:redirect_uris] || rp_metadata["redirect_uris"] || []
467
- unless allowed_redirect_uris.include?(redirect_uri)
468
- return error_response(res, "invalid_request", "redirect_uri not in client's allowed redirect_uris")
469
- end
470
- end
471
- end
472
-
473
- # Generate authorization code
474
- code = SecureRandom.hex(32)
475
- MockOPServer::AUTHORIZATION_CODES[code] = {
476
- client_id: client_id,
477
- redirect_uri: redirect_uri,
478
- state: state,
479
- nonce: nonce,
480
- created_at: OmniauthOpenidFederation::TimeHelpers.now
481
- }
482
-
483
- # Redirect back to RP with authorization code
484
- redirect_uri_with_code = URI.parse(redirect_uri)
485
- query_params = redirect_uri_with_code.query ? CGI.parse(redirect_uri_with_code.query) : {}
486
- query_params["code"] = [code]
487
- query_params["state"] = [state] if state
488
- query_params["iss"] = [MockOPServer::ENTITY_ID]
489
-
490
- redirect_uri_with_code.query = URI.encode_www_form(query_params.flatten.map { |k, v| [k, v] }.flatten)
491
- res.status = 302
492
- res["Location"] = redirect_uri_with_code.to_s
493
- end
494
-
495
- def handle_token(req, res, params)
496
- grant_type = params["grant_type"]
497
- code = params["code"]
498
- redirect_uri = params["redirect_uri"]
499
- params["client_id"]
500
-
501
- unless grant_type == "authorization_code"
502
- return error_response(res, "unsupported_grant_type", "Only authorization_code grant type is supported")
503
- end
504
-
505
- unless code
506
- return error_response(res, "invalid_request", "Missing authorization code")
507
- end
508
-
509
- code_data = MockOPServer::AUTHORIZATION_CODES.delete(code)
510
- unless code_data
511
- return error_response(res, "invalid_grant", "Invalid or expired authorization code", status: 401)
512
- end
513
-
514
- # Validate redirect_uri matches
515
- if redirect_uri && redirect_uri != code_data[:redirect_uri]
516
- return error_response(res, "invalid_grant", "redirect_uri mismatch", status: 401)
517
- end
518
-
519
- # Generate ID Token
520
- id_token = generate_id_token(
521
- client_id: code_data[:client_id],
522
- nonce: code_data[:nonce]
523
- )
524
-
525
- # Generate Access Token (mock)
526
- access_token = SecureRandom.hex(32)
527
-
528
- json_response(res, {
529
- access_token: access_token,
530
- token_type: "Bearer",
531
- expires_in: 3600,
532
- id_token: id_token
533
- })
534
- end
535
-
536
- def handle_userinfo(req, res)
537
- json_response(res, {
538
- sub: "user123",
539
- name: "Test User",
540
- email: "test@example.com"
541
- })
542
- end
543
-
544
- def is_entity_id?(str)
545
- str.is_a?(String) && str.start_with?("http://", "https://")
546
- end
547
-
548
- def extract_metadata_from_parsed(parsed)
549
- metadata = parsed[:metadata] || parsed["metadata"] || {}
550
- result = {}
551
- metadata.each do |entity_type, entity_metadata|
552
- result[entity_type.to_sym] = entity_metadata
553
- end
554
- result
555
- end
556
-
557
- def validate_request_object(request_jwt, error_mode = nil)
558
- # Check if it's encrypted (JWE - 5 parts)
559
- parts_count = request_jwt.split(".").length
560
- if parts_count == 5
561
- # Error injection: malformed encrypted request (triggered by error_mode)
562
- if error_mode == "malformed_encryption"
563
- raise OmniauthOpenidFederation::DecryptionError, "Malformed encrypted request object"
564
- end
565
-
566
- # Try to decrypt - will fail if wrong key was used
567
- begin
568
- request_jwt = OmniauthOpenidFederation::Jwe.decrypt(request_jwt, MockOPServer::ENCRYPTION_KEY)
569
- rescue => e
570
- raise OmniauthOpenidFederation::DecryptionError, "Failed to decrypt request object: #{e.message}"
571
- end
572
- elsif parts_count != 3 && error_mode == "malformed_encryption"
573
- # Not a valid JWT or JWE format
574
- raise OmniauthOpenidFederation::DecryptionError, "Malformed encrypted request object"
575
- end
576
-
577
- # Decode and validate the request object
578
- parts = request_jwt.split(".")
579
- raise OmniauthOpenidFederation::ValidationError, "Invalid JWT format" if parts.length != 3
580
-
581
- header = JSON.parse(Base64.urlsafe_decode64(parts[0]))
582
- payload = JSON.parse(Base64.urlsafe_decode64(parts[1]))
583
-
584
- # Validate algorithm
585
- alg = header["alg"] || header[:alg]
586
- unless alg == "RS256"
587
- raise OmniauthOpenidFederation::ValidationError, "Unsupported algorithm: #{alg}"
588
- end
589
-
590
- # Extract client_id to get their JWKS
591
- client_id = payload["client_id"] || payload[:client_id]
592
- unless client_id
593
- raise OmniauthOpenidFederation::ValidationError, "Missing client_id in request object"
594
- end
595
-
596
- # Fetch client's entity statement to get their JWKS
597
- if is_entity_id?(client_id)
598
- begin
599
- # If client_id is localhost, use direct localhost URL (for isolation)
600
- client_url = if client_id.include?("localhost")
601
- port = client_id.match(/:(\d+)/)&.captures&.first || "9293"
602
- "http://localhost:#{port}/.well-known/openid-federation"
603
- else
604
- "#{client_id}/.well-known/openid-federation"
605
- end
606
-
607
- client_statement = OmniauthOpenidFederation::Federation::EntityStatement.fetch!(
608
- client_url
609
- )
610
- client_parsed = client_statement.parse
611
- client_jwks = client_parsed[:jwks] || client_parsed["jwks"] || {}
612
- client_keys = client_jwks[:keys] || client_jwks["keys"] || []
613
-
614
- # Find the key used for signing
615
- kid = header["kid"] || header[:kid]
616
- signing_key_data = client_keys.find { |k| (k["kid"] || k[:kid]) == kid }
617
-
618
- unless signing_key_data
619
- raise OmniauthOpenidFederation::ValidationError, "Signing key not found in client JWKS"
620
- end
621
-
622
- # Convert JWK to OpenSSL key
623
- public_key = OmniauthOpenidFederation::KeyExtractor.jwk_to_openssl_key(signing_key_data)
624
-
625
- # Verify signature
626
- JWT.decode(request_jwt, public_key, true, {algorithm: "RS256"})
627
- rescue => e
628
- raise OmniauthOpenidFederation::ValidationError, "Request object validation failed: #{e.message}"
629
- end
630
- end
631
-
632
- payload
633
- end
634
-
635
- def generate_id_token(client_id:, nonce: nil)
636
- now = Time.now.to_i
637
- jwks = OmniauthOpenidFederation::FederationEndpoint.current_jwks
638
- signing_key = OmniauthOpenidFederation::FederationEndpoint.configuration.private_key
639
- kid = jwks["keys"]&.first&.dig("kid") || jwks[:keys]&.first&.dig(:kid)
640
-
641
- payload = {
642
- iss: MockOPServer::ENTITY_ID,
643
- sub: "user123",
644
- aud: client_id,
645
- exp: now + 3600,
646
- iat: now,
647
- nonce: nonce
648
- }
649
-
650
- header = {
651
- alg: "RS256",
652
- typ: "JWT",
653
- kid: kid
654
- }
655
-
656
- JWT.encode(payload, signing_key, "RS256", header)
657
- end
658
-
659
- def generate_expired_entity_statement
660
- jwk = JWT::JWK.new(MockOPServer::SIGNING_KEY.public_key)
661
- jwk_export = jwk.export
662
- jwk_export[:kid] = jwk_export[:kid] || SecureRandom.hex(16)
663
-
664
- payload = {
665
- iss: MockOPServer::ENTITY_ID,
666
- sub: MockOPServer::ENTITY_ID,
667
- iat: Time.now.to_i - 7200,
668
- exp: Time.now.to_i - 3600,
669
- jwks: {keys: [jwk_export]},
670
- metadata: {
671
- openid_provider: MockOPServer::OP_METADATA
672
- }
673
- }
674
-
675
- header = {alg: "RS256", typ: "entity-statement+jwt", kid: jwk_export[:kid]}
676
- JWT.encode(payload, MockOPServer::SIGNING_KEY, "RS256", header)
677
- end
678
-
679
- def generate_entity_statement_with_wrong_keys
680
- wrong_key = OpenSSL::PKey::RSA.new(2048)
681
- jwk = JWT::JWK.new(wrong_key.public_key)
682
- jwk_export = jwk.export
683
- jwk_export[:kid] = jwk_export[:kid] || SecureRandom.hex(16)
684
-
685
- payload = {
686
- iss: MockOPServer::ENTITY_ID,
687
- sub: MockOPServer::ENTITY_ID,
688
- iat: Time.now.to_i,
689
- exp: Time.now.to_i + 3600,
690
- jwks: {keys: [jwk_export]},
691
- metadata: {
692
- openid_provider: MockOPServer::OP_METADATA
693
- }
694
- }
695
-
696
- header = {alg: "RS256", typ: "entity-statement+jwt", kid: jwk_export[:kid]}
697
- JWT.encode(payload, MockOPServer::SIGNING_KEY, "RS256", header)
698
- end
699
-
700
- def generate_entity_statement_without_metadata
701
- jwk = JWT::JWK.new(MockOPServer::SIGNING_KEY.public_key)
702
- jwk_export = jwk.export
703
- jwk_export[:kid] = jwk_export[:kid] || SecureRandom.hex(16)
704
-
705
- payload = {
706
- iss: MockOPServer::ENTITY_ID,
707
- sub: MockOPServer::ENTITY_ID,
708
- iat: Time.now.to_i,
709
- exp: Time.now.to_i + 3600,
710
- jwks: {keys: [jwk_export]}
711
- }
712
-
713
- header = {alg: "RS256", typ: "entity-statement+jwt", kid: jwk_export[:kid]}
714
- JWT.encode(payload, MockOPServer::SIGNING_KEY, "RS256", header)
715
- end
716
-
717
- def generate_invalid_signed_jwks
718
- wrong_key = OpenSSL::PKey::RSA.new(2048)
719
- jwk = JWT::JWK.new(wrong_key.public_key)
720
- jwk_export = jwk.export
721
-
722
- payload = {
723
- keys: [jwk_export]
724
- }
725
-
726
- header = {alg: "RS256", typ: "JWT", kid: jwk_export[:kid]}
727
- JWT.encode(payload, wrong_key, "RS256", header)
728
- end
729
- end
730
-
731
- def self.run!
732
- port = ENV["PORT"]&.to_i || 9292
733
- bind = ENV["BIND"] || "localhost"
734
-
735
- server = WEBrick::HTTPServer.new(Port: port, BindAddress: bind)
736
- server.mount("/", Servlet)
737
-
738
- trap("INT") { server.shutdown }
739
- trap("TERM") { server.shutdown }
740
-
741
- server.start
742
- end
743
- end
744
-
745
- # Run the server
746
- if __FILE__ == $0
747
- # Configure federation endpoint before starting
748
- MockOPServer.configure_federation_endpoint
749
- MockOPServer.configure_subordinate_statements
750
-
751
- puts "Starting Enhanced Mock OP Server..."
752
- puts "Entity ID: #{MockOPServer::ENTITY_ID}"
753
- puts "Server: http://#{MockOPServer::SERVER_HOST}"
754
- puts ""
755
- puts "Endpoints:"
756
- puts " GET /.well-known/openid-federation - Entity Configuration"
757
- puts " GET /.well-known/openid-federation/fetch?sub=<entity_id> - Fetch Subordinate Statement"
758
- puts " GET /.well-known/jwks.json - JWKS"
759
- puts " GET /.well-known/signed-jwks.json - Signed JWKS"
760
- puts " GET /auth?request=<signed_jwt> - Authorization (with request object validation)"
761
- puts " POST /token - Token Exchange"
762
- puts " GET /userinfo - UserInfo (mock)"
763
- puts ""
764
- puts "Error Injection Modes (add ?error_mode=<mode> to any endpoint):"
765
- puts " - invalid_statement: Return invalid entity statement"
766
- puts " - wrong_keys: Return wrong JWKS keys"
767
- puts " - invalid_request: Reject request object"
768
- puts " - invalid_signature: Return invalid signature"
769
- puts " - expired_statement: Return expired entity statement"
770
- puts " - missing_metadata: Return statement without metadata"
771
- puts ""
772
-
773
- MockOPServer.run!
774
- end