tina4ruby 3.13.169 → 3.13.170

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.
Files changed (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +62 -0
  3. data/lib/tina4/ai.rb +3 -2
  4. data/lib/tina4/api.rb +19 -5
  5. data/lib/tina4/auth.rb +105 -9
  6. data/lib/tina4/cli.rb +2 -9
  7. data/lib/tina4/cors.rb +4 -2
  8. data/lib/tina4/dev_admin.rb +39 -21
  9. data/lib/tina4/dispatch_pipeline.rb +63 -28
  10. data/lib/tina4/drivers/bolt_graph_driver.rb +6 -4
  11. data/lib/tina4/executable_path.rb +29 -0
  12. data/lib/tina4/frond.rb +4 -3
  13. data/lib/tina4/http_server.rb +5 -0
  14. data/lib/tina4/mcp.rb +3 -1
  15. data/lib/tina4/middleware.rb +87 -53
  16. data/lib/tina4/mqtt.rb +4 -1
  17. data/lib/tina4/port_probe.rb +88 -0
  18. data/lib/tina4/port_takeover.rb +34 -15
  19. data/lib/tina4/rack_app.rb +36 -10
  20. data/lib/tina4/rate_limit_policy.rb +101 -0
  21. data/lib/tina4/rate_limiter.rb +55 -31
  22. data/lib/tina4/request.rb +12 -3
  23. data/lib/tina4/response.rb +13 -9
  24. data/lib/tina4/response_cache.rb +44 -0
  25. data/lib/tina4/router.rb +17 -2
  26. data/lib/tina4/session.rb +129 -15
  27. data/lib/tina4/session_handlers/database_handler.rb +1 -1
  28. data/lib/tina4/session_handlers/file_handler.rb +40 -6
  29. data/lib/tina4/session_handlers/memcached_handler.rb +1 -1
  30. data/lib/tina4/session_handlers/mongo_handler.rb +37 -3
  31. data/lib/tina4/session_handlers/redis_handler.rb +1 -1
  32. data/lib/tina4/session_handlers/resp_session_handler.rb +5 -3
  33. data/lib/tina4/session_handlers/valkey_handler.rb +1 -1
  34. data/lib/tina4/sso.rb +132 -40
  35. data/lib/tina4/sso_jwks.rb +12 -6
  36. data/lib/tina4/swagger.rb +3 -1
  37. data/lib/tina4/version.rb +1 -1
  38. data/lib/tina4/webserver.rb +7 -11
  39. data/lib/tina4/websocket.rb +24 -0
  40. data/lib/tina4.rb +11 -7
  41. metadata +5 -16
@@ -118,7 +118,7 @@ module Tina4
118
118
  def initialize(options = {})
119
119
  # TINA4_SESSION_TTL reaches every backend (ADR-0024); was a hard-coded
120
120
  # 86400. 3600 matches Python (the master), PHP and Node.
121
- @ttl = (options[:ttl] || ENV["TINA4_SESSION_TTL"] || 3600).to_i
121
+ @ttl = (options[:ttl] || Tina4::Session.configured_ttl).to_i
122
122
  @db_option = options[:db]
123
123
  @db = nil
124
124
  @table_ready = false
@@ -8,6 +8,7 @@
8
8
  require "json"
9
9
  require "fileutils"
10
10
  require "digest"
11
+ require "securerandom"
11
12
 
12
13
  module Tina4
13
14
  module SessionHandlers
@@ -36,7 +37,7 @@ module Tina4
36
37
  # so an operator setting a 15-minute session got 24 hours here and got
37
38
  # it right only on memcached - the one handler that read the variable.
38
39
  # 3600 is the default in Python (the master), PHP and Node.
39
- @ttl = (options[:ttl] || ENV["TINA4_SESSION_TTL"] || 3600).to_i
40
+ @ttl = (options[:ttl] || Tina4::Session.configured_ttl).to_i
40
41
  FileUtils.mkdir_p(@dir)
41
42
  end
42
43
 
@@ -44,7 +45,7 @@ module Tina4
44
45
  path = session_path(session_id)
45
46
  return nil unless File.exist?(path)
46
47
 
47
- stored = JSON.parse(File.read(path))
48
+ stored = JSON.parse(retrying { File.read(path) })
48
49
  if expired?(stored, path)
49
50
  File.delete(path)
50
51
  return nil
@@ -74,10 +75,7 @@ module Tina4
74
75
  def write(session_id, data, ttl = 0)
75
76
  effective_ttl = ttl.to_i.positive? ? ttl.to_i : @ttl
76
77
  expires_at = effective_ttl.positive? ? Time.now.to_f + effective_ttl : 0.0
77
- File.write(
78
- session_path(session_id),
79
- JSON.generate({ "_data" => data, "_expires" => expires_at })
80
- )
78
+ replace_file(session_path(session_id), JSON.generate({ "_data" => data, "_expires" => expires_at }))
81
79
  end
82
80
 
83
81
  def destroy(session_id)
@@ -99,6 +97,42 @@ module Tina4
99
97
 
100
98
  private
101
99
 
100
+ # On Windows a record cannot be opened while a save renames its
101
+ # replacement into place, and the rename is refused while the record is
102
+ # open. Either is tried again this many times, 10 ms apart, before the
103
+ # error is reported. POSIX has neither window.
104
+ WINDOWS_RETRIES = Gem.win_platform? ? 99 : 0
105
+
106
+ def retrying
107
+ attempts = 0
108
+ begin
109
+ yield
110
+ rescue Errno::EACCES
111
+ attempts += 1
112
+ raise if attempts > WINDOWS_RETRIES
113
+
114
+ sleep 0.01
115
+ retry
116
+ end
117
+ end
118
+
119
+ # Write +text+ to +path+ whole or not at all: to a temporary file beside it,
120
+ # then renamed over it. A request reading the session while another saves
121
+ # it sees the old record or the new one, never a half-written file, which
122
+ # read as no session at all and ended the session for that request. A
123
+ # record the operator made read-only is still refused, as the in-place
124
+ # write refused it: the rename alone would replace it.
125
+ def replace_file(path, text)
126
+ retrying { File.open(path, "r+") {} } if File.exist?(path)
127
+ tmp = "#{path}.#{SecureRandom.hex(6)}.tmp"
128
+ File.write(tmp, text)
129
+ begin
130
+ retrying { File.rename(tmp, path) }
131
+ ensure
132
+ File.delete(tmp) if File.exist?(tmp)
133
+ end
134
+ end
135
+
102
136
  # Delete every genuinely-expired record. An absent or zero deadline means
103
137
  # never expires, so such a record is never a sweep candidate.
104
138
  def sweep(max_age = nil)
@@ -54,7 +54,7 @@ module Tina4
54
54
  @host = options[:host] || ENV["TINA4_SESSION_MEMCACHED_HOST"] || "localhost"
55
55
  @port = (options[:port] || ENV["TINA4_SESSION_MEMCACHED_PORT"] || 11_211).to_i
56
56
  @prefix = options[:prefix] || ENV["TINA4_SESSION_MEMCACHED_PREFIX"] || "tina4:session:"
57
- @ttl = (options[:ttl] || ENV["TINA4_SESSION_TTL"] || 3600).to_i
57
+ @ttl = (options[:ttl] || Tina4::Session.configured_ttl).to_i
58
58
  @timeout = (options[:timeout] || 5).to_f
59
59
  end
60
60
 
@@ -52,10 +52,11 @@ module Tina4
52
52
  def initialize(options = {})
53
53
  # TINA4_SESSION_TTL reaches every backend (ADR-0024); was a hard-coded
54
54
  # 86400. 3600 matches Python (the master), PHP and Node.
55
- @ttl = (options[:ttl] || ENV["TINA4_SESSION_TTL"] || 3600).to_i
55
+ @ttl = (options[:ttl] || Tina4::Session.configured_ttl).to_i
56
56
  @uri = options[:uri] || ENV["TINA4_SESSION_MONGO_URI"] || ENV["TINA4_SESSION_MONGO_URL"] || "mongodb://localhost:27017"
57
57
  @database = options[:database] || ENV["TINA4_SESSION_MONGO_DB"] || "tina4"
58
58
  @collection_name = options[:collection] || ENV["TINA4_SESSION_MONGO_COLLECTION"] || "sessions"
59
+ resolve_login(options)
59
60
  @gem_available = gem_available?
60
61
  end
61
62
 
@@ -248,13 +249,46 @@ module Tina4
248
249
  # request path cannot take one transport while a directly-constructed
249
250
  # handler takes the other. A per-operation branch is a branch that can be
250
251
  # wrong on one path only - which is exactly how a fallback ships untested.
252
+ # What the store says when it has credentials but no driver to log in with.
253
+ NEEDS_DRIVER_MESSAGE = "the MongoDB session store has login credentials (in TINA4_SESSION_MONGO_URI or " "TINA4_SESSION_MONGO_USERNAME/TINA4_SESSION_MONGO_PASSWORD) but the mongo gem is not " "installed, and the built-in client cannot log in. Install it: gem install mongo"
254
+
255
+ # Credentials: the USERNAME/PASSWORD pair (options first, then the
256
+ # environment); blank means unset.
257
+ def resolve_login(options)
258
+ @username, @password = %i[username password].map do |key|
259
+ value = (options[key] || ENV["TINA4_SESSION_MONGO_#{key.upcase}"]).to_s
260
+ value.empty? ? nil : value
261
+ end
262
+ end
263
+
264
+ # Credentials in the URI (user info before the host) or the USERNAME/PASSWORD pair.
265
+ def login?
266
+ return true if @username || @password
267
+
268
+ authority = @uri.to_s.sub(%r{\A[a-z+]+://}i, "").split("/", 2).first.to_s
269
+ authority.include?("@")
270
+ end
271
+
272
+ def client_options
273
+ options = { database: @database }
274
+ if @username
275
+ options[:user] = @username
276
+ options[:password] = @password.to_s
277
+ end
278
+ options
279
+ end
280
+
251
281
  def collection
252
282
  if @gem_available
253
- client = self.class.shared_transport(transport_key) { Mongo::Client.new(@uri, database: @database) }
283
+ client = self.class.shared_transport(transport_key) { Mongo::Client.new(@uri, **client_options) }
254
284
  collection = client[@collection_name]
255
285
  ensure_ttl_index(collection)
256
286
  collection
257
287
  else
288
+ # The built-in client has no login. With credentials configured it
289
+ # refuses, loudly, instead of talking to the server without them.
290
+ raise NEEDS_DRIVER_MESSAGE if login?
291
+
258
292
  self.class.shared_transport(transport_key) { build_wire_client }
259
293
  end
260
294
  end
@@ -264,7 +298,7 @@ module Tina4
264
298
  # a MongoWireClient is bound to a single collection.
265
299
  def transport_key
266
300
  if @gem_available
267
- [:gem, @uri, @database]
301
+ [:gem, @uri, @database, @username]
268
302
  else
269
303
  [:wire, @uri, @database, @collection_name]
270
304
  end
@@ -32,7 +32,7 @@ module Tina4
32
32
  @prefix = options[:prefix] || ENV["TINA4_SESSION_REDIS_PREFIX"] || "tina4:session:"
33
33
  # TINA4_SESSION_TTL reaches every backend (ADR-0024); was a hard-coded
34
34
  # 86400. 3600 matches Python (the master), PHP and Node.
35
- @ttl = (options[:ttl] || ENV["TINA4_SESSION_TTL"] || 3600).to_i
35
+ @ttl = (options[:ttl] || Tina4::Session.configured_ttl).to_i
36
36
  @host = options[:host] || ENV["TINA4_SESSION_REDIS_HOST"] || "localhost"
37
37
  @port = options[:port] || (ENV["TINA4_SESSION_REDIS_PORT"] ? ENV["TINA4_SESSION_REDIS_PORT"].to_i : 6379)
38
38
  @db = options[:db] || (ENV["TINA4_SESSION_REDIS_DB"] ? ENV["TINA4_SESSION_REDIS_DB"].to_i : 0)
@@ -41,10 +41,12 @@ module Tina4
41
41
  key = "#{@prefix}#{session_id}"
42
42
  payload = JSON.generate(data)
43
43
  effective_ttl = ttl.to_i.positive? ? ttl.to_i : @ttl
44
- if @redis
45
- @redis.setex(key, effective_ttl, payload)
44
+ client = @redis || @resp
45
+ # TINA4_SESSION_TTL=0 never expires: a plain SET. SETEX refuses 0.
46
+ if effective_ttl.positive?
47
+ client.setex(key, effective_ttl, payload)
46
48
  else
47
- @resp.setex(key, effective_ttl, payload)
49
+ client.set(key, payload)
48
50
  end
49
51
  end
50
52
 
@@ -26,7 +26,7 @@ module Tina4
26
26
  # now falls back to TINA4_SESSION_TTL - the ONE session-lifetime variable
27
27
  # every backend must honour (ADR-0024) - instead of a hard-coded 86400.
28
28
  # 3600 matches Python (the master), PHP and Node.
29
- @ttl = (options[:ttl] || ENV["TINA4_SESSION_VALKEY_TTL"] || ENV["TINA4_SESSION_TTL"] || 3600).to_i
29
+ @ttl = (options[:ttl] || ENV["TINA4_SESSION_VALKEY_TTL"] || Tina4::Session.configured_ttl).to_i
30
30
  @host = options[:host] || ENV["TINA4_SESSION_VALKEY_HOST"] || "localhost"
31
31
  @port = options[:port] || (ENV["TINA4_SESSION_VALKEY_PORT"] ? ENV["TINA4_SESSION_VALKEY_PORT"].to_i : 6379)
32
32
  @db = options[:db] || (ENV["TINA4_SESSION_VALKEY_DB"] ? ENV["TINA4_SESSION_VALKEY_DB"].to_i : 0)
data/lib/tina4/sso.rb CHANGED
@@ -19,10 +19,22 @@ require_relative "sso_jwks"
19
19
  module Tina4
20
20
  class SsoError < StandardError; end
21
21
 
22
+ # The provider's discovery document could not be fetched (network, HTTP or a
23
+ # body that is not a JSON object). Not a configuration error: the SSO routes
24
+ # answer 503 SSO_PROVIDER_UNAVAILABLE and the fetch is retried later.
25
+ class SsoProviderUnavailable < SsoError; end
26
+
22
27
  # Provider-neutral, configuration-first OpenID Connect SSO.
23
28
  class Sso
24
29
  PENDING_KEY = "_tina4_sso_pending"
25
30
  SESSION_KEY = "_tina4_sso"
31
+ # Ceilings for the two time settings: a larger leeway would switch the ID
32
+ # token's expiry check off, and keys trusted longer than a day would keep a
33
+ # key the provider removed working long after it was withdrawn.
34
+ MAX_CLOCK_SKEW = 300
35
+ MAX_JWKS_MAX_AGE = 86_400
36
+ # After a failed discovery fetch the next one waits this long.
37
+ DISCOVERY_RETRY_SECONDS = 60
26
38
 
27
39
  # The stored SSO identity, only while it is live (ADR-0079 s5). +stored+ is
28
40
  # the reserved _tina4_sso session value. The identity needs an issuer and a
@@ -51,14 +63,16 @@ module Tina4
51
63
  :verify, :post_logout_redirect_uri, :claim_map, :clock_skew, :jwks_max_age
52
64
  @mounted = false
53
65
 
54
- # TINA4_SSO_CLOCK_SKEW: seconds of leeway on ID-token exp/nbf, a non-negative integer (default 60).
55
- # A non-negative integer number of seconds: option, else env, else default.
56
- # TINA4_SSO_CLOCK_SKEW (default 60) is the leeway on ID-token exp/nbf;
57
- # TINA4_SSO_JWKS_MAX_AGE (default 3600) is how long fetched signing keys are trusted.
58
- def self.parse_seconds(options, key, name, default)
66
+ # A whole number of seconds from 0 to the ceiling: option, else env, else default.
67
+ # TINA4_SSO_CLOCK_SKEW (default 60, at most 300) is the leeway on ID-token exp/iat/nbf;
68
+ # TINA4_SSO_JWKS_MAX_AGE (default 3600, at most 86400) is how long fetched signing
69
+ # keys are trusted. Text must be plain ASCII digits.
70
+ def self.parse_seconds(options, key, name, default, ceiling)
59
71
  raw = options.key?(key) ? options[key] : (ENV[name] || default)
60
- raw = raw.strip.to_i if raw.is_a?(String) && raw.strip.match?(/\A\d+\z/)
61
- raise SsoError, "#{name} must be a non-negative integer" unless raw.is_a?(Integer) && raw >= 0
72
+ raw = raw.strip.match?(/\A[0-9]+\z/) ? raw.strip.to_i : nil if raw.is_a?(String)
73
+ unless raw.is_a?(Integer) && raw.between?(0, ceiling)
74
+ raise SsoError, "#{name} must be a whole number of seconds from 0 to #{ceiling}"
75
+ end
62
76
 
63
77
  raw
64
78
  end
@@ -72,9 +86,10 @@ module Tina4
72
86
  @verify = (options[:verify] || ENV["TINA4_SSO_VERIFY"] || "introspection").downcase
73
87
  @post_logout_redirect_uri = options[:post_logout_redirect_uri] || ENV["TINA4_SSO_POST_LOGOUT_REDIRECT_URI"]
74
88
  @claim_map = options[:claim_map] || json_env("TINA4_SSO_CLAIM_MAP", {})
75
- @clock_skew = self.class.parse_seconds(options, :clock_skew, "TINA4_SSO_CLOCK_SKEW", 60)
76
- @jwks_max_age = self.class.parse_seconds(options, :jwks_max_age, "TINA4_SSO_JWKS_MAX_AGE", 3600)
89
+ @clock_skew = self.class.parse_seconds(options, :clock_skew, "TINA4_SSO_CLOCK_SKEW", 60, MAX_CLOCK_SKEW)
90
+ @jwks_max_age = self.class.parse_seconds(options, :jwks_max_age, "TINA4_SSO_JWKS_MAX_AGE", 3600, MAX_JWKS_MAX_AGE)
77
91
  @metadata = {}
92
+ @discovery_failure = nil # [monotonic time, error] of the last failed discovery
78
93
  @jwks_verifier = nil
79
94
  validate_config!
80
95
  end
@@ -132,13 +147,46 @@ module Tina4
132
147
  result = Tina4.parse_json(response.body)
133
148
  raise SsoError, "OIDC provider returned a non-object response" unless result.is_a?(Hash)
134
149
  result
135
- rescue JSON::ParserError, IOError, SystemCallError, Timeout::Error => e
150
+ rescue JSON::ParserError, IOError, SystemCallError, SocketError, Timeout::Error, OpenSSL::SSL::SSLError => e
136
151
  raise SsoError, "OIDC provider request failed", cause: e
137
152
  end
138
153
 
154
+ # The provider's validated discovery document, fetched on first use and cached.
155
+ # A fetch that fails raises SsoProviderUnavailable; a document that is wrong
156
+ # (another issuer, a missing or insecure endpoint) raises SsoError. Either way
157
+ # the next fetch waits DISCOVERY_RETRY_SECONDS (force skips the wait).
139
158
  def discover(force = false)
140
159
  return @metadata.dup unless @metadata.empty? || force
141
- result = request_json("#{@issuer}/.well-known/openid-configuration")
160
+ failure = @discovery_failure
161
+ if failure && !force && monotonic - failure[0] < DISCOVERY_RETRY_SECONDS
162
+ raise failure[1].class, failure[1].message
163
+ end
164
+ begin
165
+ result = discover_document
166
+ rescue SsoError => e
167
+ @discovery_failure = [monotonic, e]
168
+ raise
169
+ end
170
+ @discovery_failure = nil
171
+ @metadata = result
172
+ result.dup
173
+ end
174
+
175
+ # Forget a failed discovery, so the next use fetches at once.
176
+ def clear_discovery_failure
177
+ @discovery_failure = nil
178
+ end
179
+
180
+ private def monotonic
181
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
182
+ end
183
+
184
+ private def discover_document
185
+ begin
186
+ result = request_json("#{@issuer}/.well-known/openid-configuration")
187
+ rescue SsoError => e
188
+ raise SsoProviderUnavailable, "OIDC provider is unavailable", cause: e
189
+ end
142
190
  raise SsoError, "OIDC discovery issuer does not exactly match configuration" unless result["issuer"] == @issuer
143
191
  required = %w[authorization_endpoint token_endpoint]
144
192
  required << (@verify == "introspection" ? "introspection_endpoint" : "jwks_uri")
@@ -146,8 +194,7 @@ module Tina4
146
194
  raise SsoError, "OIDC discovery is missing #{key}" if result[key].to_s.empty?
147
195
  self.class.secure_url!(result[key], key)
148
196
  end
149
- @metadata = result
150
- result.dup
197
+ result
151
198
  end
152
199
 
153
200
  def self.safe_return(value)
@@ -184,13 +231,6 @@ module Tina4
184
231
  a.bytesize == b.bytesize && OpenSSL.fixed_length_secure_compare(a, b)
185
232
  end
186
233
 
187
- def self.jwt_payload(token)
188
- part = token.split(".")[1].to_s
189
- Tina4.parse_json(Tina4::Base64.urlsafe_decode64(part.ljust((part.length + 3) / 4 * 4, "=")))
190
- rescue JSON::ParserError, ArgumentError
191
- raise SsoError, "provider returned an invalid ID token"
192
- end
193
-
194
234
  def introspect(access_token)
195
235
  result = request_json(discover["introspection_endpoint"],
196
236
  form: { token: access_token, token_type_hint: "access_token" }, basic: true)
@@ -204,10 +244,14 @@ module Tina4
204
244
  result
205
245
  end
206
246
 
207
- # jwks mode: the ID token's verified claims (ADR-0114, Tina4::JwksVerifier).
208
- def verify_id_token(token, nonce = nil)
247
+ # The ID token's verified claims, in both modes (ADR-0114, Tina4::JwksVerifier):
248
+ # iss, aud/azp, exp, iat, sub and (at sign-in) the nonce. jwks mode also checks
249
+ # the signature against the provider's JWKS; introspection mode leaves the
250
+ # signature to TLS, as the token comes straight from the token endpoint
251
+ # (OIDC Core 3.1.3.7).
252
+ def verify_id_token(token, nonce = nil, signature: true)
209
253
  @jwks_verifier ||= JwksVerifier.new(@issuer, @client_id, @clock_skew, -> { request_json(discover["jwks_uri"]) }, @jwks_max_age)
210
- @jwks_verifier.verify(token, nonce)
254
+ @jwks_verifier.verify(token, nonce, signature: signature)
211
255
  end
212
256
 
213
257
  # Merge UserInfo over verified claims, only for the same subject (OIDC Core 5.3.2).
@@ -224,6 +268,16 @@ module Tina4
224
268
  claims.merge(info)
225
269
  end
226
270
 
271
+ # The introspected identity must be the ID token's subject (OIDC Core 3.1.3.7).
272
+ # An introspection answer without a sub (RFC 7662 makes it optional) takes the
273
+ # ID token's, so UserInfo is then checked against the verified subject.
274
+ def self.introspected_subject(claims, id_claims)
275
+ return claims.merge("sub" => id_claims["sub"]) if claims["sub"].nil?
276
+ raise SsoError, "OIDC ID token subject does not match the introspected token" unless claims["sub"] == id_claims["sub"]
277
+
278
+ claims
279
+ end
280
+
227
281
  # jwks mode: verify a returned ID token (no nonce) for the same subject, else keep the identity.
228
282
  def refreshed_identity(stored, tokens, metadata)
229
283
  raise SsoError, "OIDC refresh response is incomplete" if tokens["access_token"].to_s.empty?
@@ -269,10 +323,12 @@ module Tina4
269
323
  current = session(request_or_session)
270
324
  values = query || self.class.query_of(request_or_session)
271
325
  pending = current&.get(PENDING_KEY)
272
- current&.delete(PENDING_KEY)
326
+ # Compare first, consume after: a callback with a wrong state is refused and
327
+ # leaves the sign-in in progress alone; only the matching one uses it up.
273
328
  unless pending.is_a?(Hash) && !values["code"].to_s.empty? && self.class.secure_equal(values["state"], pending["state"])
274
329
  raise SsoError, "OIDC callback state is invalid or already consumed"
275
330
  end
331
+ current.delete(PENDING_KEY)
276
332
  raise SsoError, "OIDC callback state has expired" if Time.now.to_i - pending.fetch("created_at", 0).to_i > 600
277
333
  metadata = discover
278
334
  tokens = request_json(metadata["token_endpoint"], form: {
@@ -280,15 +336,9 @@ module Tina4
280
336
  client_id: @client_id, code_verifier: pending["verifier"]
281
337
  }, basic: !@client_secret.to_s.empty?)
282
338
  raise SsoError, "OIDC token response is incomplete" if tokens["access_token"].to_s.empty? || tokens["id_token"].to_s.empty?
283
- if @verify == "jwks"
284
- claims = with_userinfo(verify_id_token(tokens["id_token"], pending["nonce"].to_s), tokens["access_token"], metadata)
285
- else
286
- claims = introspect(tokens["access_token"])
287
- unless self.class.secure_equal(self.class.jwt_payload(tokens["id_token"])["nonce"], pending["nonce"])
288
- raise SsoError, "OIDC ID token nonce mismatch"
289
- end
290
- claims = with_userinfo(claims, tokens["access_token"], metadata)
291
- end
339
+ claims = verify_id_token(tokens["id_token"], pending["nonce"].to_s, signature: @verify == "jwks")
340
+ claims = self.class.introspected_subject(introspect(tokens["access_token"]), claims) if @verify == "introspection"
341
+ claims = with_userinfo(claims, tokens["access_token"], metadata)
292
342
  identity = normalize(claims)
293
343
  current.regenerate
294
344
  current.set(SESSION_KEY, {
@@ -319,7 +369,11 @@ module Tina4
319
369
  if @verify == "jwks"
320
370
  value = refreshed_identity(stored, tokens, metadata)
321
371
  else
322
- value = normalize(with_userinfo(introspect(tokens["access_token"]), tokens["access_token"], metadata))
372
+ claims = introspect(tokens["access_token"])
373
+ unless tokens["id_token"].to_s.empty?
374
+ claims = self.class.introspected_subject(claims, verify_id_token(tokens["id_token"], signature: false))
375
+ end
376
+ value = normalize(with_userinfo(claims, tokens["access_token"], metadata))
323
377
  end
324
378
  current.set(SESSION_KEY, stored.merge(
325
379
  "identity" => value, "access_token" => tokens["access_token"],
@@ -333,13 +387,30 @@ module Tina4
333
387
  raise
334
388
  end
335
389
 
390
+ # The local path on this application's origin, which is the redirect URI's.
391
+ def absolute_return(path)
392
+ uri = URI.parse(@redirect_uri)
393
+ port = uri.port == uri.default_port ? "" : ":#{uri.port}"
394
+ "#{uri.scheme}://#{uri.host}#{port}#{path}"
395
+ end
396
+
397
+ # End the local session, whatever state the SSO identity is in, then hand off.
398
+ # The session (and the provider tokens in it) is destroyed first and always.
399
+ # The provider is told an ABSOLUTE return address: TINA4_SSO_POST_LOGOUT_REDIRECT_URI
400
+ # when set, else the safe local path on the redirect URI's origin.
336
401
  def logout(request_or_session, return_to = "/")
337
402
  current = session(request_or_session)
338
403
  stored = current&.get(SESSION_KEY)
339
404
  current&.destroy
340
- endpoint = discover["end_session_endpoint"]
341
- target = @post_logout_redirect_uri || self.class.safe_return(return_to)
342
- return target unless endpoint
405
+ local = self.class.safe_return(return_to)
406
+ endpoint = begin
407
+ discover["end_session_endpoint"]
408
+ rescue SsoError
409
+ nil
410
+ end
411
+ return @post_logout_redirect_uri || local unless endpoint
412
+
413
+ target = @post_logout_redirect_uri || absolute_return(local)
343
414
  params = { post_logout_redirect_uri: target, client_id: @client_id }
344
415
  params[:id_token_hint] = stored["id_token"] if stored.is_a?(Hash) && stored["id_token"]
345
416
  "#{endpoint}?#{URI.encode_www_form(params)}"
@@ -352,20 +423,41 @@ module Tina4
352
423
  unless collisions.empty?
353
424
  raise SsoError, "SSO route collision: #{collisions.map { |route| "#{route.method} #{route.path}" }.join(', ')}"
354
425
  end
355
- sso = from_issuer
426
+ # Configuration errors fail here. Discovery is tried once: a wrong document
427
+ # stops the start-up, but a provider that cannot be reached only logs a
428
+ # warning - the application serves, ordinary routes never need the
429
+ # provider, and the SSO routes fetch discovery when they are first used.
430
+ sso = new
431
+ begin
432
+ sso.discover
433
+ rescue SsoProviderUnavailable
434
+ sso.clear_discovery_failure
435
+ Tina4::Log.warning("SSO: the identity provider could not be reached at start-up; serving anyway, " "and the SSO routes will fetch its discovery document when first used")
436
+ end
437
+ unavailable = lambda do |response|
438
+ response.error("SSO_PROVIDER_UNAVAILABLE", "The identity provider could not be reached", 503)
439
+ end
356
440
  Tina4::Router.get("/auth/login") do |request, response|
357
- response.redirect(sso.login(request, query_of(request)["return_to"] || "/"))
441
+ begin
442
+ response.redirect(sso.login(request, query_of(request)["return_to"] || "/"))
443
+ rescue SsoProviderUnavailable
444
+ unavailable.call(response)
445
+ end
358
446
  end
359
447
  Tina4::Router.get("/auth/callback") do |request, response|
360
448
  begin
361
449
  response.redirect(sso.callback(request)["return_to"])
450
+ rescue SsoProviderUnavailable
451
+ unavailable.call(response)
362
452
  rescue SsoError => e
363
453
  response.json({ error: "SSO_CALLBACK_FAILED", message: e.message }, 400)
364
454
  end
365
455
  end
456
+ # Public on purpose: signing out must work once the provider's token lifetime
457
+ # has passed, which is exactly when the gate stops counting the identity.
366
458
  Tina4::Router.post("/auth/logout") do |request, response|
367
459
  response.redirect(sso.logout(request, query_of(request)["return_to"] || "/"))
368
- end
460
+ end.no_auth
369
461
  @mounted = true
370
462
  true
371
463
  end
@@ -11,7 +11,7 @@ require_relative "base64"
11
11
  require_relative "parse_json"
12
12
 
13
13
  module Tina4
14
- # ID-token verification against the provider's JWKS (ADR-0114, TINA4_SSO_VERIFY=jwks).
14
+ # ID-token verification against the provider's JWKS (ADR-0114), in both SSO modes.
15
15
  # Stdlib OpenSSL does the signature maths; this class only parses and checks, and
16
16
  # builds the SubjectPublicKeyInfo of a JWK with OpenSSL::ASN1.
17
17
  class JwksVerifier
@@ -39,11 +39,15 @@ module Tina4
39
39
  end
40
40
 
41
41
  # The verified claims of an ID token, or SsoError. A nil nonce skips the nonce check.
42
- def verify(token, nonce = nil)
43
- parts, header, claims, signature = self.class.parse(token)
44
- alg, kid = self.class.algorithm(header)
45
- key = self.class.public_key(signing_key(kid, alg), alg)
46
- self.class.check_signature(alg, key, "#{parts[0]}.#{parts[1]}", signature)
42
+ # signature: false checks the claims only and leaves the signature to TLS, for a
43
+ # token received straight from the token endpoint (OIDC Core 3.1.3.7).
44
+ def verify(token, nonce = nil, signature: true)
45
+ parts, header, claims, raw_signature = self.class.parse(token)
46
+ if signature
47
+ alg, kid = self.class.algorithm(header)
48
+ key = self.class.public_key(signing_key(kid, alg), alg)
49
+ self.class.check_signature(alg, key, "#{parts[0]}.#{parts[1]}", raw_signature)
50
+ end
47
51
  check_claims(claims, nonce)
48
52
  claims
49
53
  end
@@ -176,6 +180,8 @@ module Tina4
176
180
  now = Time.now.to_f
177
181
  raise SsoError, "OIDC ID token exp is missing or invalid" unless claims["exp"].is_a?(Numeric)
178
182
  raise SsoError, "OIDC ID token has expired" if now >= claims["exp"] + @clock_skew
183
+ raise SsoError, "OIDC ID token iat is missing or invalid" unless claims["iat"].is_a?(Numeric)
184
+ raise SsoError, "OIDC ID token was issued in the future" if claims["iat"] > now + @clock_skew
179
185
  return unless claims.key?("nbf")
180
186
  raise SsoError, "OIDC ID token nbf is invalid" unless claims["nbf"].is_a?(Numeric)
181
187
  raise SsoError, "OIDC ID token is not yet valid" if now < claims["nbf"] - @clock_skew
data/lib/tina4/swagger.rb CHANGED
@@ -319,7 +319,9 @@ module Tina4
319
319
  #
320
320
  # Both flags are honoured. A custom auth_handler protects a route even
321
321
  # when auth_required is false for its method, so it is still documented.
322
- if route.auth_required || route.auth_handler
322
+ # A role/permission guard needs a token whatever auth_required says
323
+ # (the gate's own rule), so a guarded route is documented as secured.
324
+ if route.auth_required || route.auth_handler || route.guarded?
323
325
  requirements = [{ default_scheme => [] }]
324
326
  requirements << { "ssoSession" => [] } if default_scheme == "bearerAuth" && schemes.key?("ssoSession")
325
327
  return sanitize_security(requirements, schemes)
data/lib/tina4/version.rb CHANGED
@@ -7,5 +7,5 @@
7
7
 
8
8
 
9
9
  module Tina4
10
- VERSION = "3.13.169"
10
+ VERSION = "3.13.170"
11
11
  end
@@ -78,19 +78,15 @@ module Tina4
78
78
 
79
79
  require "socket"
80
80
 
81
- # Ensure the main port is available — kill whatever is on it if needed
82
- begin
83
- test = TCPServer.new("0.0.0.0", @port)
84
- test.close
85
- rescue Errno::EADDRINUSE
81
+ # Ensure the main port is available — kill whatever is on it if needed.
82
+ # A bind-only probe (Tina4::PortProbe) of the server's OWN host, with the
83
+ # server's own socket options: a listen-then-close probe accepted and
84
+ # dropped any client that connected in between, and probing a different
85
+ # address than the one bound missed a stale holder on that address.
86
+ unless Tina4::PortProbe.free?(@host, @port)
86
87
  free_port(@port)
87
88
  # Verify the port is now free; raise if still occupied
88
- begin
89
- test = TCPServer.new("0.0.0.0", @port)
90
- test.close
91
- rescue Errno::EADDRINUSE
92
- raise "Could not free port #{@port}"
93
- end
89
+ raise "Could not free port #{@port}" unless Tina4::PortProbe.free?(@host, @port)
94
90
  end
95
91
 
96
92
  Tina4.print_banner(host: @host, port: @port, server_name: Tina4::HttpServer::SOFTWARE)
@@ -6,6 +6,8 @@
6
6
  # file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
7
 
8
8
  require "socket"
9
+ require "io/wait"
10
+ require_relative "port_probe"
9
11
  require "digest"
10
12
  require_relative "base64"
11
13
  require "json"
@@ -251,6 +253,8 @@ module Tina4
251
253
  # seen and no handshake could complete (the socket was left open, too).
252
254
  def start(host: "0.0.0.0", port: 7147)
253
255
  require "socket"
256
+ Tina4::PortProbe.ensure_valid_port!(port)
257
+ Tina4::PortProbe.ensure_free!(host, port) if Tina4::PortProbe.windows? # see HttpServer#listen
254
258
  @server_socket = TCPServer.new(host, port)
255
259
  @running = true
256
260
  @server_thread = Thread.new do
@@ -931,7 +935,27 @@ module Tina4
931
935
  @socket.close rescue nil
932
936
  end
933
937
 
938
+ # How long the reader waits for a frame before re-checking @closed (Windows).
939
+ WINDOWS_READ_SLICE = 1
940
+
941
+ # Windows: once the server has used read_nonblock on the socket it is in
942
+ # non-blocking mode, and a thread waiting in getbyte on such a socket is NOT
943
+ # woken by another thread's IO#close (Ruby 3.3, measured; shutdown does not
944
+ # wake it either) - close then waits forever, which hung the dev-admin
945
+ # disconnect. So the idle wait for the next frame is done in bounded slices
946
+ # that notice #close within WINDOWS_READ_SLICE seconds. False once closed.
947
+ def await_frame
948
+ return true unless Gem.win_platform? && @socket.is_a?(BasicSocket)
949
+
950
+ until @socket.wait_readable(WINDOWS_READ_SLICE)
951
+ return false if @closed
952
+ end
953
+ true
954
+ end
955
+
934
956
  def read_frame
957
+ return nil unless await_frame
958
+
935
959
  first_byte = @socket.getbyte
936
960
  return nil unless first_byte
937
961