keycardai-oauth 0.16.1 → 0.17.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b094722fda3937a5c428749976362c4b6b6fe64675d7cc28fd2a4855111816d9
4
- data.tar.gz: eb6d7d3536c0cc71287e843ad0e1f135d797deb0345f6e0d21613a0709f9cb92
3
+ metadata.gz: c719d8515dd3a5993acfada29fe6dc65f2391964ea44d97a17c1a5c256622122
4
+ data.tar.gz: 8b20cf6ed5f14fccd4f33249b22beaf61bf10bc29f614cdd23a31790c61de841
5
5
  SHA512:
6
- metadata.gz: 8aff3ed02700382c383616189b2427ff9862d7b1dd9d4ba3be06e0424aaf67ad260d58c57a100e52c51ac02d8bbedefdc8aa25b92980f083f6298ba0807faa17
7
- data.tar.gz: be238c65b54d8d7592a1727340272aeb075385b007bc904f03d4b59a6949215e93e1452a0a499c7ba097d3a7e2f41b233cb3948a7056d3ffb57d591e5401d0b0
6
+ metadata.gz: cf9c56ee56533cbbbd0036cc0ac8c2676691beebdece8702ecb3872cb4280dec0d5ce9f5f49e3ff63ce1880322818ae3be275f529f616fb7c19212e2f976b7b5
7
+ data.tar.gz: 3d4d3a8688daa918437d67d143dce221bb7d27084287201fb5e614767b1220204e021fd208feb18faac89a7495755978553fc76f1a4d729f8839cbcc4a381ddc
data/CHANGELOG.md CHANGED
@@ -15,6 +15,12 @@ the loopback flow (RFC 8252), JWT signing and verification with a caching JWKS
15
15
  keyring, the three application credentials (ClientSecret with multi-zone,
16
16
  WebIdentity, WorkloadIdentity with pluggable token sources), and AccessContext.
17
17
 
18
+ ## 0.17.0-keycardai-oauth (2026-11-26)
19
+
20
+
21
+ - feat(keycardai-oauth): bind metadata, challenges and audience to one resource identifier (#110)
22
+ - Implements keycard-sdk-spec#151 for keycardai-oauth and keycardai-mcp. Refs SDK-14.
23
+
18
24
  ## 0.16.1-keycardai-oauth (2026-11-26)
19
25
 
20
26
 
@@ -0,0 +1,355 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module Keycardai
6
+ module OAuth
7
+ # A validated resource identifier: either an absolute HTTP(S) URL (with host,
8
+ # no userinfo, no fragment) or an RFC 8141 URN. Preserves the raw string
9
+ # verbatim for audience matching and RFC 9728 metadata documents.
10
+ class ResourceIdentifier
11
+ PROTECTED_RESOURCE_PREFIX = "/.well-known/oauth-protected-resource"
12
+ URN_PATTERN = /\Aurn:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,30}[a-zA-Z0-9])?:\S+\z/i
13
+ USERINFO_PATTERN = %r{\Ahttps?://[^/?#]*@}i
14
+
15
+ attr_reader :raw, :origin, :metadata_path, :metadata_url, :query, :target
16
+
17
+ def self.parse(value)
18
+ unless value.is_a?(String) && !value.empty?
19
+ raise ConfigurationError, "resource_identifier must be a non-empty HTTP(S) URL or URN"
20
+ end
21
+ return new(raw: value, kind: :urn) if value.match?(URN_PATTERN)
22
+
23
+ parse_http(value)
24
+ end
25
+
26
+ def self.parse_http(value)
27
+ uri = URI.parse(value)
28
+ validate_http_uri!(uri, value)
29
+ origin = format_origin(uri)
30
+ path_suffix = empty_or_root_path?(uri.path) ? "" : uri.path
31
+ metadata_path = "#{PROTECTED_RESOURCE_PREFIX}#{path_suffix}"
32
+ query_suffix = uri.query ? "?#{uri.query}" : ""
33
+ target_path = uri.path.nil? || uri.path.empty? ? "/" : uri.path
34
+ new(raw: value, kind: :http, origin: origin, metadata_path: metadata_path,
35
+ metadata_url: "#{origin}#{metadata_path}#{query_suffix}",
36
+ query: uri.query, target: "#{target_path}#{query_suffix}")
37
+ rescue URI::InvalidURIError => e
38
+ raise ConfigurationError, "invalid resource_identifier #{value.inspect}: #{e.message}"
39
+ end
40
+
41
+ def self.validate_http_uri!(uri, value)
42
+ raise ConfigurationError, "resource_identifier must be an absolute HTTP(S) URL with a host or a URN" unless
43
+ http_with_host?(uri)
44
+ if uri.userinfo || value.match?(USERINFO_PATTERN)
45
+ raise ConfigurationError, "resource_identifier must not contain userinfo"
46
+ end
47
+ return unless uri.fragment || value.include?("#")
48
+
49
+ raise ConfigurationError, "resource_identifier must not contain a fragment"
50
+ end
51
+
52
+ def self.http_with_host?(uri)
53
+ uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
54
+ end
55
+ private_class_method :parse_http, :validate_http_uri!, :http_with_host?
56
+
57
+ def self.format_origin(uri)
58
+ port = uri.port && uri.port != uri.default_port ? ":#{uri.port}" : ""
59
+ "#{uri.scheme}://#{uri.host}#{port}"
60
+ end
61
+ private_class_method :format_origin
62
+
63
+ def self.empty_or_root_path?(path)
64
+ path.nil? || path.empty? || path == "/"
65
+ end
66
+ private_class_method :empty_or_root_path?
67
+
68
+ def initialize(raw:, kind:, origin: nil, metadata_path: nil, metadata_url: nil, query: nil, target: nil)
69
+ @raw = raw
70
+ @kind = kind
71
+ @origin = origin
72
+ @metadata_path = metadata_path
73
+ @metadata_url = metadata_url
74
+ @query = query
75
+ @target = target
76
+ freeze
77
+ end
78
+
79
+ def http?
80
+ @kind == :http
81
+ end
82
+
83
+ def urn?
84
+ @kind == :urn
85
+ end
86
+
87
+ def matches_request?(path:, query: "")
88
+ return false unless http?
89
+
90
+ request_target = query.empty? ? path : "#{path}?#{query}"
91
+ @target == request_target
92
+ end
93
+
94
+ def matches_metadata_request?(path:, query: "")
95
+ http? && @metadata_path == path && @query.to_s == query
96
+ end
97
+
98
+ def ==(other)
99
+ other.is_a?(self.class) && @raw == other.raw
100
+ end
101
+ alias eql? ==
102
+
103
+ def hash
104
+ @raw.hash
105
+ end
106
+ end
107
+
108
+ # Internal option validation and mode resolution for ResourceBinding.
109
+ module ResourceBindingResolver
110
+ ZONE_ID_PATTERN = /\A[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\z/
111
+
112
+ module_function
113
+
114
+ def derive_zone_issuer(base_issuer, zone_id)
115
+ validate_zone_id!(zone_id)
116
+ uri = parse_base_issuer(base_issuer)
117
+ port = uri.port && uri.port != uri.default_port ? ":#{uri.port}" : ""
118
+ "#{uri.scheme}://#{zone_id}.#{uri.host}#{port}"
119
+ end
120
+
121
+ def validate_zone_id!(zone_id)
122
+ return if zone_id.is_a?(String) && zone_id.match?(ZONE_ID_PATTERN)
123
+
124
+ raise ConfigurationError, "invalid zone ID #{zone_id.inspect}"
125
+ end
126
+
127
+ def parse_base_issuer(base_issuer)
128
+ if base_issuer.nil? || base_issuer.empty?
129
+ raise ConfigurationError, "base issuer is required for zone issuer derivation"
130
+ end
131
+
132
+ uri = URI.parse(base_issuer)
133
+ unless uri.is_a?(URI::HTTP) && uri.host && !uri.host.empty?
134
+ raise ConfigurationError, "issuer must be an absolute HTTP(S) URL with a host"
135
+ end
136
+
137
+ uri
138
+ rescue URI::InvalidURIError => e
139
+ raise ConfigurationError, "invalid issuer #{base_issuer.inspect}: #{e.message}"
140
+ end
141
+
142
+ def check_conflicts!(resource_id, zone_map, multi_resource, allow_any, audiences)
143
+ check_flag_conflicts!(resource_id, zone_map, multi_resource, allow_any)
144
+ check_audience_conflicts!(resource_id, zone_map, multi_resource, allow_any, audiences)
145
+ end
146
+
147
+ def check_flag_conflicts!(resource_id, zone_map, multi_resource, allow_any)
148
+ if multi_resource && allow_any
149
+ raise ConfigurationError, "multi_resource and allow_any_audience cannot both be true"
150
+ end
151
+
152
+ check_identifier_conflicts!(resource_id, zone_map, multi_resource, allow_any)
153
+ end
154
+
155
+ def check_identifier_conflicts!(resource_id, zone_map, multi_resource, allow_any)
156
+ unless resource_id.nil?
157
+ unless zone_map.nil?
158
+ raise ConfigurationError,
159
+ "resource_identifier and resource_identifiers_by_zone cannot both be set"
160
+ end
161
+ if multi_resource || allow_any
162
+ raise ConfigurationError, "resource_identifier cannot be combined with multi_resource or allow_any_audience"
163
+ end
164
+ end
165
+ return unless !zone_map.nil? && allow_any
166
+
167
+ raise ConfigurationError, "resource_identifiers_by_zone cannot be combined with allow_any_audience"
168
+ end
169
+
170
+ def check_audience_conflicts!(resource_id, zone_map, multi_resource, allow_any, audiences)
171
+ return if audiences.nil?
172
+ raise ConfigurationError, "audiences cannot be combined with resource_identifier" unless resource_id.nil?
173
+ raise ConfigurationError, "audiences cannot be combined with allow_any_audience" if allow_any
174
+ return unless !zone_map.nil? && !multi_resource
175
+
176
+ raise ConfigurationError,
177
+ "audiences cannot be combined with resource_identifiers_by_zone without multi_resource"
178
+ end
179
+
180
+ def parse_zone_map(zone_map)
181
+ unless zone_map.is_a?(Hash) && !zone_map.empty?
182
+ raise ConfigurationError, "resource_identifiers_by_zone must be a non-empty Hash"
183
+ end
184
+
185
+ zone_map.each_with_object({}) do |(zone_id, identifier), parsed|
186
+ validate_zone_id!(zone_id)
187
+ parsed[zone_id] = ResourceIdentifier.parse(identifier)
188
+ end.freeze
189
+ end
190
+
191
+ def valid_audience_list?(audiences)
192
+ audiences.is_a?(Array) && !audiences.empty? &&
193
+ audiences.all? { |item| item.is_a?(String) && !item.empty? }
194
+ end
195
+
196
+ def emit_legacy_warning(component, audiences)
197
+ if audiences.is_a?(Hash)
198
+ warn "#{component} is using a deprecated legacy audience map; pass resource_identifiers_by_zone: " \
199
+ "(or resource_identifier: for single-resource mode) instead.", uplevel: 2
200
+ else
201
+ warn "#{component} is using deprecated legacy resource configuration; pass resource_identifier:, " \
202
+ "resource_identifiers_by_zone:, multi_resource: true, or allow_any_audience: true.", uplevel: 2
203
+ end
204
+ end
205
+ end
206
+
207
+ # Validated resource-binding mode shared by TokenVerifier, AuthProvider,
208
+ # RequireBearerAuth, and MetadataApp. Selects exactly one of:
209
+ # :single_resource, :per_zone, :multi_resource, :shared_discovery,
210
+ # :allow_any_audience, or :legacy (with a one-time deprecation warning).
211
+ class ResourceBinding
212
+ attr_reader :mode, :identifier, :zone_identifiers, :audiences
213
+
214
+ def self.derive_zone_issuer(base_issuer, zone_id)
215
+ ResourceBindingResolver.derive_zone_issuer(base_issuer, zone_id)
216
+ end
217
+
218
+ def self.resolve(resource_identifier: nil, resource_identifiers_by_zone: nil,
219
+ multi_resource: false, allow_any_audience: false, audiences: nil,
220
+ accept_audiences: true, require_issuer_for_zones: false, base_issuer: nil,
221
+ warn_legacy: true, component: "Keycardai")
222
+ ResourceBindingResolver.check_conflicts!(
223
+ resource_identifier, resource_identifiers_by_zone, multi_resource, allow_any_audience, audiences
224
+ )
225
+ return build_single(resource_identifier) unless resource_identifier.nil?
226
+ unless resource_identifiers_by_zone.nil?
227
+ return build_zone_binding(resource_identifiers_by_zone, multi_resource: multi_resource,
228
+ audiences: audiences,
229
+ accept_audiences: accept_audiences,
230
+ require_issuer: require_issuer_for_zones,
231
+ base_issuer: base_issuer)
232
+ end
233
+ return build_multi_resource(audiences, accept_audiences: accept_audiences) if multi_resource
234
+ return new(mode: :allow_any_audience) if allow_any_audience
235
+
236
+ build_legacy(audiences, accept_audiences: accept_audiences, warn_legacy: warn_legacy, component: component)
237
+ end
238
+
239
+ def self.build_single(resource_id)
240
+ parsed = ResourceIdentifier.parse(resource_id)
241
+ new(mode: :single_resource, identifier: parsed, audiences: [parsed.raw].freeze)
242
+ end
243
+
244
+ def self.build_zone_binding(zone_map, multi_resource:, audiences:, accept_audiences:,
245
+ require_issuer:, base_issuer:)
246
+ parsed_map = ResourceBindingResolver.parse_zone_map(zone_map)
247
+ if require_issuer && parsed_map.values.any?(&:http?) && (base_issuer.nil? || base_issuer.empty?)
248
+ raise ConfigurationError, "issuer is required when resource_identifiers_by_zone contains HTTP(S) identifiers"
249
+ end
250
+ if multi_resource
251
+ return build_shared_discovery(parsed_map, audiences: audiences, accept_audiences: accept_audiences)
252
+ end
253
+
254
+ new(mode: :per_zone, zone_identifiers: parsed_map)
255
+ end
256
+
257
+ def self.build_shared_discovery(parsed_map, audiences:, accept_audiences:)
258
+ values = parsed_map.values.uniq
259
+ unless values.length == 1 && values.first.http?
260
+ raise ConfigurationError,
261
+ "shared discovery requires every zone in resource_identifiers_by_zone to share one HTTP(S) URL"
262
+ end
263
+ shared = values.first
264
+ if accept_audiences && !(audiences.is_a?(Array) && audiences == [shared.raw])
265
+ raise ConfigurationError,
266
+ "shared discovery requires audiences to be a singleton list containing the shared identifier"
267
+ end
268
+ new(mode: :shared_discovery, identifier: shared, zone_identifiers: parsed_map, audiences: [shared.raw].freeze)
269
+ end
270
+
271
+ def self.build_multi_resource(audiences, accept_audiences:)
272
+ if accept_audiences && !ResourceBindingResolver.valid_audience_list?(audiences)
273
+ raise ConfigurationError, "multi_resource requires a non-empty audiences array"
274
+ end
275
+
276
+ new(mode: :multi_resource, audiences: accept_audiences ? audiences.dup.freeze : nil)
277
+ end
278
+
279
+ def self.build_legacy(audiences, accept_audiences:, warn_legacy:, component:)
280
+ if accept_audiences && audiences.is_a?(Array) && audiences.empty?
281
+ raise ConfigurationError, "audiences must not be empty"
282
+ end
283
+
284
+ ResourceBindingResolver.emit_legacy_warning(component, audiences) if warn_legacy
285
+ new(mode: :legacy, audiences: audiences)
286
+ end
287
+ private_class_method :build_single, :build_zone_binding, :build_shared_discovery,
288
+ :build_multi_resource, :build_legacy
289
+
290
+ def initialize(mode:, identifier: nil, zone_identifiers: nil, audiences: nil)
291
+ @mode = mode
292
+ @identifier = identifier
293
+ @zone_identifiers = zone_identifiers
294
+ @audiences = audiences
295
+ freeze
296
+ end
297
+
298
+ def explicit?
299
+ @mode != :legacy
300
+ end
301
+
302
+ def legacy?
303
+ @mode == :legacy
304
+ end
305
+
306
+ def single_resource?
307
+ @mode == :single_resource
308
+ end
309
+
310
+ def per_zone?
311
+ @mode == :per_zone
312
+ end
313
+
314
+ def multi_resource?
315
+ @mode == :multi_resource
316
+ end
317
+
318
+ def shared_discovery?
319
+ @mode == :shared_discovery
320
+ end
321
+
322
+ def allow_any_audience?
323
+ @mode == :allow_any_audience
324
+ end
325
+
326
+ def zone_mode?
327
+ per_zone? || shared_discovery?
328
+ end
329
+
330
+ def publishes_metadata?
331
+ case @mode
332
+ when :single_resource then @identifier.http?
333
+ when :shared_discovery, :legacy then true
334
+ when :per_zone then @zone_identifiers.values.any?(&:http?)
335
+ else false
336
+ end
337
+ end
338
+
339
+ def zone_issuers(base_issuer)
340
+ return {} unless @zone_identifiers
341
+
342
+ @zone_identifiers.keys.to_h { |zone_id| [zone_id, self.class.derive_zone_issuer(base_issuer, zone_id)] }
343
+ end
344
+
345
+ def compatible_with?(other)
346
+ return false unless other.is_a?(self.class)
347
+
348
+ @mode == other.mode &&
349
+ @identifier == other.identifier &&
350
+ @zone_identifiers == other.zone_identifiers &&
351
+ @audiences == other.audiences
352
+ end
353
+ end
354
+ end
355
+ end
@@ -84,30 +84,43 @@ module Keycardai
84
84
  # zone issuer(s); JWKS and discovery caches are keyed by issuer so no
85
85
  # zone's keys are ever served for another.
86
86
  class TokenVerifier
87
- # @param issuers [String, Array<String>] trusted zone issuer URL(s)
88
- # @param audiences [String, Array<String>, nil] when set, tokens must
89
- # carry an intersecting aud; when nil, the verifier accepts a token
90
- # minted for any resource in the zone and warns once at construction
87
+ # @return [ResourceBinding] the validated resource-binding mode
88
+ attr_reader :resource_binding
89
+ # @return [Array<String>] trusted zone issuer URLs
90
+ attr_reader :issuers
91
+ # @return [Hash{String => String}] zone ID to issuer URL map in zone modes
92
+ attr_reader :zone_issuers
93
+
94
+ # @param issuers [String, Array<String>, Hash{String => String}, nil] trusted zone issuer URL(s)
95
+ # @param issuer [String, nil] single issuer URL, or base issuer URL for zone-scoped modes
96
+ # @param audiences [String, Array<String>, nil] accepted audiences in multi_resource or legacy mode
97
+ # @param resource_identifier [String, nil] exact HTTP(S) URL or URN in single-resource mode
98
+ # @param resource_identifiers_by_zone [Hash{String => String}, nil] zone ID to identifier map
99
+ # @param multi_resource [Boolean] explicit multi-resource or shared-discovery opt-in
100
+ # @param allow_any_audience [Boolean] explicit opt-out from audience validation
101
+ # @param resource_binding [ResourceBinding, nil] pre-validated binding (internal composition)
91
102
  # @param http_client [#get] pluggable transport
92
103
  # @param key_ttl [Numeric] JWKS key cache lifetime in seconds
93
104
  # @param discovery_ttl [Numeric] jwks_uri cache lifetime in seconds
94
105
  # @param fetch_timeout [Numeric] discovery and JWKS fetch timeout
95
106
  # @param clock [#call] returns the current Time; override in tests
96
- # @raise [ConfigurationError] no trusted issuer or explicitly empty audiences
97
- def initialize(issuers:, audiences: nil, http_client: HTTP::NetHTTPClient.new,
107
+ # @raise [ConfigurationError] invalid or conflicting mode options or no trusted issuer
108
+ def initialize(issuers: nil, issuer: nil, audiences: nil,
109
+ resource_identifier: nil, resource_identifiers_by_zone: nil,
110
+ multi_resource: false, allow_any_audience: false,
111
+ resource_binding: nil,
112
+ http_client: HTTP::NetHTTPClient.new,
98
113
  key_ttl: JWKSKeyring::DEFAULT_KEY_TTL, discovery_ttl: JWKSKeyring::DEFAULT_DISCOVERY_TTL,
99
114
  fetch_timeout: JWKSKeyring::DEFAULT_FETCH_TIMEOUT, clock: MetadataRetry::WALL_CLOCK)
100
- @issuers = Array(issuers).reject { |issuer| issuer.nil? || issuer.empty? }
101
- raise ConfigurationError, "TokenVerifier requires at least one trusted issuer" if @issuers.empty?
102
- raise ConfigurationError, "audiences must not be empty" if audiences.is_a?(Array) && audiences.empty?
103
-
104
- if audiences.nil?
105
- warn "Keycardai::OAuth::TokenVerifier has no audiences configured, so it accepts a token minted " \
106
- "for any resource in the zone; pass audiences: with this server's registered resource identifier.",
107
- uplevel: 1
108
- end
109
-
110
- @audiences = audiences
115
+ @resource_binding = resource_binding || ResourceBinding.resolve(
116
+ resource_identifier: resource_identifier,
117
+ resource_identifiers_by_zone: resource_identifiers_by_zone,
118
+ multi_resource: multi_resource,
119
+ allow_any_audience: allow_any_audience,
120
+ audiences: audiences,
121
+ component: "Keycardai::OAuth::TokenVerifier"
122
+ )
123
+ @issuers, @zone_issuers = resolve_issuers(issuers, issuer)
111
124
  @clock = clock
112
125
  @keyring = JWKSKeyring.new(http_client: http_client, key_ttl: key_ttl,
113
126
  discovery_ttl: discovery_ttl, fetch_timeout: fetch_timeout, clock: clock)
@@ -119,21 +132,27 @@ module Keycardai
119
132
  # @return [AccessToken]
120
133
  # @raise [InvalidTokenError, JWKSError]
121
134
  def verify_token(token)
122
- verify_against(@issuers, token)
135
+ raise InvalidTokenError, "per-zone verifier requires verify_token_for_zone" if @resource_binding.per_zone?
136
+
137
+ verify_against(@issuers, token, @resource_binding.audiences)
123
138
  end
124
139
 
125
- # Verify a bearer token pinned to one zone's issuer. A token minted by
126
- # any other zone is rejected before key resolution, and an issuer
127
- # outside the configured allowlist fails closed.
140
+ # Verify a bearer token pinned to one zone's issuer or zone ID. A token
141
+ # minted by any other zone is rejected before key resolution, and an
142
+ # unconfigured zone fails closed.
128
143
  #
129
144
  # @param token [String]
130
- # @param issuer [String] the zone's issuer URL
145
+ # @param zone_or_issuer [String] zone ID (in zone modes) or zone issuer URL
131
146
  # @return [AccessToken]
132
147
  # @raise [InvalidTokenError, JWKSError]
133
- def verify_token_for_zone(token, issuer)
134
- raise InvalidTokenError, "zone issuer is not configured on this verifier" unless @issuers.include?(issuer)
148
+ def verify_token_for_zone(token, zone_or_issuer)
149
+ return verify_per_zone(token, zone_or_issuer) if @resource_binding.per_zone?
150
+ return verify_shared_zone(token, zone_or_issuer) if @resource_binding.shared_discovery?
151
+ unless @issuers.include?(zone_or_issuer)
152
+ raise InvalidTokenError, "zone issuer is not configured on this verifier"
153
+ end
135
154
 
136
- verify_against([issuer], token)
155
+ verify_against([zone_or_issuer], token, @resource_binding.audiences)
137
156
  end
138
157
 
139
158
  # Drop all cached keys and discovery results.
@@ -145,8 +164,84 @@ module Keycardai
145
164
 
146
165
  private
147
166
 
148
- def verify_against(issuers, token)
149
- claims = JWTVerifier.new(issuers: issuers, keyring: @keyring, audiences: @audiences,
167
+ def verify_per_zone(token, zone_or_issuer)
168
+ zone_id = @zone_issuers.key?(zone_or_issuer) ? zone_or_issuer : @zone_issuers.key(zone_or_issuer)
169
+ raise InvalidTokenError, "zone is not configured on this verifier" unless zone_id
170
+
171
+ verify_against([@zone_issuers[zone_id]], token, [@resource_binding.zone_identifiers[zone_id].raw])
172
+ end
173
+
174
+ def verify_shared_zone(token, zone_or_issuer)
175
+ zone_issuer = @zone_issuers[zone_or_issuer] || (@issuers.include?(zone_or_issuer) ? zone_or_issuer : nil)
176
+ raise InvalidTokenError, "zone issuer is not configured on this verifier" unless zone_issuer
177
+
178
+ verify_against([zone_issuer], token, @resource_binding.audiences)
179
+ end
180
+
181
+ def resolve_issuers(issuers, issuer)
182
+ return resolve_zone_issuers(issuers, issuer) if @resource_binding.zone_mode?
183
+
184
+ raw = issuers.nil? ? issuer : issuers
185
+ list = Array(raw).reject { |item| item.nil? || item.empty? }.freeze
186
+ raise ConfigurationError, "TokenVerifier requires at least one trusted issuer" if list.empty?
187
+
188
+ [list, {}.freeze]
189
+ end
190
+
191
+ def resolve_zone_issuers(issuers, issuer)
192
+ return resolve_zone_issuer_hash(issuers) if issuers.is_a?(Hash)
193
+
194
+ base = issuer || (issuers if issuers.is_a?(String))
195
+ return resolve_derived_zone_issuers(base, issuers) unless base.to_s.empty?
196
+ return match_zone_issuer_array(issuers) if issuers.is_a?(Array) && !issuers.empty?
197
+
198
+ raise ConfigurationError, "TokenVerifier requires at least one trusted issuer"
199
+ end
200
+
201
+ def resolve_zone_issuer_hash(issuers)
202
+ expected = @resource_binding.zone_identifiers.keys.sort
203
+ unless issuers.keys.sort == expected
204
+ raise ConfigurationError, "issuers keys must match resource_identifiers_by_zone keys"
205
+ end
206
+
207
+ zone_map = issuers.transform_values(&:to_s).freeze
208
+ [zone_map.values.freeze, zone_map]
209
+ end
210
+
211
+ def resolve_derived_zone_issuers(base, issuers)
212
+ zone_map = @resource_binding.zone_issuers(base).freeze
213
+ if issuers.is_a?(Array) && issuers.map { |i| i.to_s.chomp("/") }.sort != zone_map.values.sort
214
+ raise ConfigurationError, "trusted issuers must match the zones in resource_identifiers_by_zone"
215
+ end
216
+
217
+ [zone_map.values.freeze, zone_map]
218
+ end
219
+
220
+ # Trusted issuers keep their configured spelling, so a token whose iss
221
+ # carries a trailing slash still matches it exactly.
222
+ def match_zone_issuer_array(issuers)
223
+ configured = issuers.map(&:to_s)
224
+ zone_map = @resource_binding.zone_identifiers.keys.to_h do |zone_id|
225
+ [zone_id, find_unique_zone_issuer!(configured, zone_id)]
226
+ end.freeze
227
+ unless zone_map.values.sort == configured.sort
228
+ raise ConfigurationError, "trusted issuers must match the zones in resource_identifiers_by_zone"
229
+ end
230
+
231
+ [zone_map.values.freeze, zone_map]
232
+ end
233
+
234
+ def find_unique_zone_issuer!(normalized, zone_id)
235
+ matched = normalized.select { |url| URI.parse(url).host&.start_with?("#{zone_id}.") }
236
+ raise ConfigurationError, "cannot uniquely match issuer for zone #{zone_id}" unless matched.length == 1
237
+
238
+ matched.first
239
+ rescue URI::InvalidURIError => e
240
+ raise ConfigurationError, "invalid issuer URL: #{e.message}"
241
+ end
242
+
243
+ def verify_against(issuers, token, audiences)
244
+ claims = JWTVerifier.new(issuers: issuers, keyring: @keyring, audiences: audiences,
150
245
  clock: @clock).verify(token)
151
246
  audience = claims["aud"]
152
247
  claims = claims.merge("aud" => [audience]) if audience.is_a?(String)
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Keycardai
4
4
  module OAuth
5
- VERSION = "0.16.1"
5
+ VERSION = "0.17.0"
6
6
  end
7
7
  end
@@ -25,6 +25,7 @@ require_relative "oauth/token_sources"
25
25
  require_relative "oauth/credential_discovery"
26
26
  require_relative "oauth/access_context"
27
27
  require_relative "oauth/exchange_tokens"
28
+ require_relative "oauth/resource_binding"
28
29
  require_relative "oauth/token_verifier"
29
30
  require_relative "oauth/token_exchange_client"
30
31
  require_relative "oauth/client_credentials_client"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: keycardai-oauth
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.16.1
4
+ version: 0.17.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Keycard
@@ -57,6 +57,7 @@ files:
57
57
  - lib/keycardai/oauth/printed_form.rb
58
58
  - lib/keycardai/oauth/private_key.rb
59
59
  - lib/keycardai/oauth/registration.rb
60
+ - lib/keycardai/oauth/resource_binding.rb
60
61
  - lib/keycardai/oauth/substitute_user.rb
61
62
  - lib/keycardai/oauth/token_exchange_client.rb
62
63
  - lib/keycardai/oauth/token_exchange_form.rb