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,243 +0,0 @@
1
- # Mock OpenID Provider (OP) Server
2
-
3
- A standalone Rack/Sinatra application for testing OpenID Federation flows.
4
-
5
- ## Features
6
-
7
- - Entity Configuration endpoint (`/.well-known/openid-federation`)
8
- - Fetch Endpoint (`/.well-known/openid-federation/fetch`) for Subordinate Statements
9
- - Authorization Endpoint (`/auth`) with trust chain resolution
10
- - Token Endpoint (`/token`) with ID Token signing
11
- - JWKS endpoints (standard and signed)
12
- - UserInfo endpoint (mock)
13
-
14
- ## Quick Start
15
-
16
- ### 1. Install Dependencies
17
-
18
- ```bash
19
- bundle install
20
- ```
21
-
22
- ### 2. Configure
23
-
24
- Copy the example configuration:
25
-
26
- ```bash
27
- cp examples/config/mock_op.yml.example examples/config/mock_op.yml
28
- ```
29
-
30
- Edit `examples/config/mock_op.yml` with your settings:
31
-
32
- ```yaml
33
- entity_id: "https://op.example.com"
34
- server_host: "localhost:9292"
35
- signing_key: |
36
- -----BEGIN RSA PRIVATE KEY-----
37
- ...
38
- -----END RSA PRIVATE KEY-----
39
- trust_anchors:
40
- - entity_id: "https://ta.example.com"
41
- jwks:
42
- keys: [...]
43
- ```
44
-
45
- ### 3. Generate Keys (if needed)
46
-
47
- ```bash
48
- # Generate OP signing key
49
- openssl genrsa -out op-private-key.pem 2048
50
- openssl rsa -in op-private-key.pem -pubout -out op-public-key.pem
51
-
52
- # Extract JWKS from public key (or use the rake task)
53
- rake openid_federation:prepare_client_keys
54
- ```
55
-
56
- ### 4. Run Server
57
-
58
- ```bash
59
- # Option 1: Direct Ruby execution
60
- ruby examples/mock_op_server.rb
61
-
62
- # Option 2: Using Rack
63
- rackup examples/mock_op_server.ru
64
-
65
- # Option 3: With specific port
66
- rackup -p 9292 examples/mock_op_server.ru
67
- ```
68
-
69
- ## Configuration Options
70
-
71
- ### Environment Variables
72
-
73
- Instead of YAML, you can use environment variables:
74
-
75
- ```bash
76
- export OP_ENTITY_ID="https://op.example.com"
77
- export OP_SERVER_HOST="localhost:9292"
78
- export OP_SIGNING_KEY="$(cat op-private-key.pem)"
79
- export OP_TRUST_ANCHORS='[{"entity_id":"https://ta.example.com","jwks":{"keys":[...]}}]'
80
- export OP_AUTHORITY_HINTS="https://federation.example.com"
81
- ```
82
-
83
- ### YAML Configuration
84
-
85
- See `examples/config/mock_op.yml.example` for full configuration options.
86
-
87
- ## Testing Scenarios
88
-
89
- ### 1. Direct Entity Statement (No Trust Chain)
90
-
91
- ```bash
92
- # Fetch OP's Entity Configuration
93
- curl http://localhost:9292/.well-known/openid-federation
94
-
95
- # Use in RP configuration
96
- config.omniauth :openid_federation,
97
- issuer: "https://op.example.com",
98
- entity_statement_url: "http://localhost:9292/.well-known/openid-federation",
99
- client_options: { ... }
100
- ```
101
-
102
- ### 2. Trust Chain Resolution
103
-
104
- ```bash
105
- # Configure trust anchors in mock_op.yml
106
- trust_anchors:
107
- - entity_id: "https://ta.example.com"
108
- jwks: {...}
109
-
110
- # RP with trust chain
111
- # The OP will resolve the RP's trust chain automatically
112
- curl "http://localhost:9292/auth?client_id=https://rp.example.com&redirect_uri=https://rp.example.com/callback"
113
- ```
114
-
115
- ### 3. Subordinate Statements
116
-
117
- ```bash
118
- # Configure subordinate statements in mock_op.yml
119
- subordinate_statements:
120
- "https://rp.example.com":
121
- metadata: {...}
122
- metadata_policy: {...}
123
-
124
- # Fetch Subordinate Statement
125
- curl "http://localhost:9292/.well-known/openid-federation/fetch?sub=https://rp.example.com"
126
- ```
127
-
128
- ## Endpoints
129
-
130
- | Endpoint | Method | Description |
131
- |----------|--------|-------------|
132
- | `/.well-known/openid-federation` | GET | Entity Configuration (JWT) |
133
- | `/.well-known/openid-federation/fetch` | GET | Fetch Subordinate Statement (requires `sub` parameter) |
134
- | `/.well-known/jwks.json` | GET | Standard JWKS (JSON) |
135
- | `/.well-known/signed-jwks.json` | GET | Signed JWKS (JWT) |
136
- | `/auth` | GET | Authorization Endpoint (requires `client_id`, `redirect_uri`) |
137
- | `/token` | POST | Token Endpoint (requires `code`, `grant_type=authorization_code`) |
138
- | `/userinfo` | GET | UserInfo Endpoint (mock data) |
139
- | `/` | GET | Health check and endpoint list |
140
-
141
- ## Example Flow
142
-
143
- ### 1. RP Discovers OP
144
-
145
- ```bash
146
- # RP fetches OP's Entity Configuration
147
- curl http://localhost:9292/.well-known/openid-federation
148
- ```
149
-
150
- ### 2. RP Initiates Authentication
151
-
152
- ```bash
153
- # RP redirects user to authorization endpoint
154
- # client_id is the RP's Entity ID (for automatic registration)
155
- curl "http://localhost:9292/auth?client_id=https://rp.example.com&redirect_uri=https://rp.example.com/callback&state=xyz&nonce=abc"
156
- ```
157
-
158
- ### 3. OP Resolves RP's Trust Chain
159
-
160
- The OP automatically:
161
- - Resolves RP's trust chain using `TrustChainResolver`
162
- - Merges metadata policies using `MetadataPolicyMerger`
163
- - Validates RP's effective metadata
164
- - Redirects back to RP with authorization code
165
-
166
- ### 4. RP Exchanges Code for Tokens
167
-
168
- ```bash
169
- curl -X POST http://localhost:9292/token \
170
- -d "grant_type=authorization_code" \
171
- -d "code=<authorization_code>" \
172
- -d "redirect_uri=https://rp.example.com/callback" \
173
- -d "client_id=https://rp.example.com"
174
- ```
175
-
176
- ### 5. RP Validates ID Token
177
-
178
- The RP validates the ID Token using the OP's JWKS from the effective metadata.
179
-
180
- ## Integration with Real RP
181
-
182
- To test with a real RP application:
183
-
184
- ```ruby
185
- # In RP's config/initializers/devise.rb
186
- config.omniauth :openid_federation,
187
- issuer: "http://localhost:9292",
188
- entity_statement_url: "http://localhost:9292/.well-known/openid-federation",
189
- trust_anchors: [
190
- {
191
- entity_id: "https://ta.example.com",
192
- jwks: trust_anchor_jwks
193
- }
194
- ],
195
- client_options: {
196
- identifier: "https://rp.example.com", # RP's Entity ID
197
- redirect_uri: "http://localhost:3000/users/auth/openid_federation/callback",
198
- private_key: rp_private_key
199
- }
200
- ```
201
-
202
- ## Limitations
203
-
204
- This is a **mock server for testing only**:
205
-
206
- - WARNING: No real user authentication (always returns mock user)
207
- - WARNING: Authorization codes stored in memory (lost on restart)
208
- - WARNING: No database persistence
209
- - WARNING: No production security hardening
210
- - WARNING: ID Tokens contain mock user data
211
-
212
- ## Production Considerations
213
-
214
- For production use, you would need:
215
-
216
- - Real user authentication system
217
- - Database for authorization codes and tokens
218
- - Proper session management
219
- - Security hardening (rate limiting, CSRF protection, etc.)
220
- - Real user data in ID Tokens
221
- - Proper error handling and logging
222
-
223
- ## Troubleshooting
224
-
225
- **"Federation endpoint not configured"**
226
- - Ensure `signing_key` is provided in config
227
- - Check that `entity_id` is set
228
-
229
- **"Trust chain resolution failed"**
230
- - Verify `trust_anchors` are correctly configured
231
- - Ensure trust anchor JWKS are valid
232
- - Check that RP's Entity ID is resolvable
233
-
234
- **"Subordinate Statement not found"**
235
- - Configure `subordinate_statements` in `mock_op.yml`
236
- - Ensure subject Entity ID matches exactly
237
-
238
- ## See Also
239
-
240
- - [OpenID Federation 1.0 Specification](https://openid.net/specs/openid-federation-1_0.html)
241
- - [Main README](../README.md)
242
- - [Federation Endpoint Documentation](../README.md#publishing-federation-endpoint)
243
-
@@ -1,37 +0,0 @@
1
- # Example OmniAuth callback controller for Devise
2
- # Copy this to app/controllers/users/omniauth_callbacks_controller.rb
3
-
4
- class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
5
- # Skip Rails CSRF protection for OAuth callbacks
6
- # OAuth callbacks from external providers cannot include Rails CSRF tokens
7
- # CSRF protection is handled by OAuth state parameter validation in the strategy
8
- skip_before_action :verify_authenticity_token, only: [:openid_federation, :failure]
9
- skip_before_action :authenticate_user!, only: [:openid_federation, :failure]
10
-
11
- def openid_federation
12
- auth = request.env["omniauth.auth"]
13
-
14
- @user = User.find_or_create_from_omniauth(auth)
15
-
16
- if @user&.persisted?
17
- sign_in_and_redirect @user, event: :authentication
18
- else
19
- redirect_to root_path, alert: "Authentication failed"
20
- end
21
- end
22
-
23
- def failure
24
- error_type = request.env["omniauth.error.type"] || :unknown
25
- error_message = request.env["omniauth.error"]&.message || "Authentication failed"
26
-
27
- Rails.logger.error({
28
- message: "OmniAuth authentication failure",
29
- error_type: error_type,
30
- error_message: error_message,
31
- strategy: request.env["omniauth.strategy"]&.name
32
- })
33
-
34
- redirect_to root_path, alert: "Authentication failed: #{error_type}"
35
- end
36
- end
37
-
@@ -1,60 +0,0 @@
1
- # Background job for proactive JWKS key rotation
2
- # This job runs periodically to refresh JWKS cache before expiration,
3
- # ensuring keys are always up-to-date without blocking client requests.
4
- #
5
- # Usage:
6
- # 1. Schedule this job to run periodically (e.g., every 12 hours)
7
- # 2. Configure cache TTL to be longer than job frequency (e.g., 24 hours)
8
- # 3. This ensures keys are refreshed proactively, not reactively
9
- #
10
- # Example scheduling (using GoodJob, Sidekiq, or similar):
11
- #
12
- # # config/initializers/schedule.rb (for GoodJob)
13
- # GoodJob::Cron::Schedule.add("jwks_rotation", {
14
- # cron: "0 */12 * * *", # Every 12 hours
15
- # class: "JwksRotationJob"
16
- # })
17
- #
18
- # # Or with Sidekiq-Cron
19
- # Sidekiq::Cron::Job.create(
20
- # name: "JWKS Rotation",
21
- # cron: "0 */12 * * *",
22
- # class: "JwksRotationJob"
23
- # )
24
- class JwksRotationJob < ApplicationJob
25
- queue_as :default
26
-
27
- # Rotate JWKS for a specific provider
28
- #
29
- # @param jwks_uri [String] The JWKS URI to refresh
30
- # @param entity_statement_path [String, nil] Path to entity statement for signed JWKS
31
- def perform(jwks_uri, entity_statement_path: nil)
32
- OmniauthOpenidFederation.rotate_jwks(jwks_uri, entity_statement_path: entity_statement_path)
33
- rescue => e
34
- # Log error but don't fail - request-level rotation will handle it
35
- Rails.logger.error("[JwksRotationJob] Failed to rotate JWKS for #{jwks_uri}: #{e.class} - #{e.message}")
36
- # Optionally, send to error tracking service (Sentry, Rollbar, etc.)
37
- # Sentry.capture_exception(e) if defined?(Sentry)
38
- raise # Re-raise to allow job retry if configured
39
- end
40
-
41
- # Rotate JWKS for all configured providers
42
- # This is useful when you have multiple providers configured
43
- def self.rotate_all
44
- # Example: Get all providers from Devise config
45
- providers = Devise.omniauth_configs.keys.select { |k| k.to_s.start_with?("openid") }
46
-
47
- providers.each do |provider_name|
48
- config = Devise.omniauth_configs[provider_name]
49
- options = config.options
50
- client_options = options[:client_options] || options["client_options"] || {}
51
- jwks_uri = client_options[:jwks_uri] || client_options["jwks_uri"]
52
- entity_statement_path = options[:entity_statement_path] || options["entity_statement_path"]
53
-
54
- if jwks_uri
55
- perform_later(jwks_uri, entity_statement_path: entity_statement_path)
56
- end
57
- end
58
- end
59
- end
60
-
@@ -1,39 +0,0 @@
1
- # Example User model with OmniAuth integration
2
- # Add these methods to your existing User model
3
-
4
- class User < ApplicationRecord
5
- # Required columns (add via migration):
6
- # - provider (string)
7
- # - uid (string)
8
- # - email (string)
9
- # - name (string)
10
- # - first_name (string, optional)
11
- # - last_name (string, optional)
12
-
13
- def self.find_or_create_from_omniauth(auth)
14
- user = find_by(provider: auth.provider, uid: auth.uid)
15
-
16
- if user
17
- # Update existing user info
18
- user.update(
19
- email: auth.info.email,
20
- name: auth.info.name,
21
- first_name: auth.info.first_name,
22
- last_name: auth.info.last_name
23
- )
24
- else
25
- # Create new user
26
- user = create(
27
- provider: auth.provider,
28
- uid: auth.uid,
29
- email: auth.info.email,
30
- name: auth.info.name,
31
- first_name: auth.info.first_name,
32
- last_name: auth.info.last_name
33
- )
34
- end
35
-
36
- user
37
- end
38
- end
39
-
@@ -1,120 +0,0 @@
1
- # Example Devise configuration for OmniAuth OpenID Federation
2
- # Copy this to config/initializers/devise.rb and customize for your provider
3
- #
4
- # This example uses a configuration class pattern (OpenIdConnectConfig)
5
- # See examples/config/open_id_connect_config.rb.example for the config class
6
-
7
- require "omniauth_openid_federation"
8
-
9
- # Configure global settings (optional but recommended)
10
- OmniauthOpenidFederation.configure do |config|
11
- if Rails.env.development?
12
- config.http_options = { ssl: { verify_mode: OpenSSL::SSL::VERIFY_PEER, ca_file: (OpenSSL::X509::DEFAULT_CERT_FILE if File.exist?(OpenSSL::X509::DEFAULT_CERT_FILE)) } }
13
- end
14
-
15
- config.cache_ttl = 24 * 60 * 60
16
- config.rotate_on_errors = true
17
- config.http_timeout = 10
18
- config.max_retries = 3
19
- config.verify_ssl = true
20
-
21
- # Security instrumentation - get notified about security events, MITM attacks, etc.
22
- # Example with Sentry:
23
- # config.instrumentation = ->(event, data) do
24
- # Sentry.capture_message(
25
- # "OpenID Federation: #{event}",
26
- # level: data[:severity] == :error ? :error : :warning,
27
- # extra: data
28
- # )
29
- # end
30
-
31
- # Example with Honeybadger:
32
- # config.instrumentation = ->(event, data) do
33
- # Honeybadger.notify("OpenID Federation: #{event}", context: data)
34
- # end
35
-
36
- # Example with custom logger:
37
- # config.instrumentation = ->(event, data) do
38
- # Rails.logger.warn("[Security] #{event}: #{data.inspect}")
39
- # end
40
- end
41
-
42
- # Load configuration from config class
43
- open_id_config = OpenIdConnectConfig.new
44
-
45
- if open_id_config.enabled?
46
- Devise.setup do |config|
47
- # ... your other Devise configuration ...
48
-
49
- # OmniAuth 2.0+ defaults to POST only for CSRF protection (CVE-2015-9284)
50
- # Always use POST for security - forms must include CSRF token
51
- if defined?(OmniAuth)
52
- OmniAuth.config.allowed_request_methods = [:post]
53
- OmniAuth.config.silence_get_warning = false
54
-
55
- # Configure CSRF validation to check tokens only for request phase (initiating OAuth)
56
- # Callback phase uses OAuth state parameter for CSRF protection (validated in strategy)
57
- # This ensures:
58
- # - Request phase: Forms must include Rails CSRF tokens (standard Rails protection)
59
- # - Callback phase: OAuth state parameter provides CSRF protection (external providers can't include Rails tokens)
60
- OmniAuth.config.request_validation_phase = lambda do |env|
61
- request = Rack::Request.new(env)
62
- path = request.path
63
-
64
- # Skip CSRF validation for callback paths (external providers can't include Rails CSRF tokens)
65
- # OAuth state parameter provides CSRF protection for callbacks (validated in OpenIDFederation strategy)
66
- return true if path.end_with?("/callback")
67
-
68
- # For request phase, use Rails' standard CSRF token validation
69
- # This ensures forms must include valid CSRF tokens when initiating OAuth
70
- session = env["rack.session"] || {}
71
- token = request.params["authenticity_token"] || request.get_header("X-CSRF-Token")
72
- expected_token = session[:_csrf_token] || session["_csrf_token"]
73
-
74
- # Validate CSRF token using constant-time comparison
75
- if token.present? && expected_token.present?
76
- ActiveSupport::SecurityUtils.secure_compare(token.to_s, expected_token.to_s)
77
- else
78
- false
79
- end
80
- end
81
- end
82
-
83
- config.omniauth :openid_federation,
84
- strategy_class: OmniAuth::Strategies::OpenIDFederation,
85
- name: :openid_federation,
86
- scope: [:openid],
87
- response_type: "code",
88
- discovery: true,
89
- client_auth_method: :jwt_bearer,
90
- client_signing_alg: :RS256,
91
- entity_statement_path: open_id_config.entity_statement_absolute_path,
92
- always_encrypt_request_object: true,
93
- # Allow-list of custom parameter names to include in signed request object
94
- # Parameters must be present in request.params and listed here to be included
95
- request_object_params: [:ftn_spname], # Example: include ftn_spname if present
96
- # Proc to modify params before adding to signed request object
97
- # Useful for combining config values with form values, adding config-based params, etc.
98
- prepare_request_object_params: proc do |params|
99
- # Example: Combine config acr_values with form acr_values
100
- form_acr_values = params["acr_values"]&.to_s&.strip
101
- config_acr_values = open_id_config.acr_values.to_s.strip
102
-
103
- if config_acr_values.present? && form_acr_values.present?
104
- params["acr_values"] = "#{config_acr_values} #{form_acr_values}".strip
105
- elsif config_acr_values.present?
106
- params["acr_values"] = config_acr_values
107
- end
108
-
109
- # Example: Add custom parameter from config
110
- params["ftn_spname"] = open_id_config.ftn_spname if open_id_config.ftn_spname.present?
111
-
112
- params
113
- end,
114
- client_options: {
115
- identifier: open_id_config.client_id,
116
- redirect_uri: open_id_config.redirect_uri,
117
- private_key: open_id_config.private_key
118
- }
119
- end
120
- end