tina4ruby 3.13.167 → 3.13.169

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.
@@ -103,19 +103,35 @@ module Tina4
103
103
  "or an '@' appears outside the user:password part (percent-encode it as %40). " \
104
104
  "The URL itself is not shown because it can contain a password."
105
105
 
106
- # Credential KEYWORDS in the two keyword=value forms that carry one: the
107
- # ODBC connection string (";"-separated) and the libpq/JDBC query string
108
- # ("&"-separated). A braced value is matched FIRST because an ODBC value
109
- # containing ";" must be braced - stopping at the ";" would leave the tail
110
- # of the password in the output, which is exactly the bug shape this file
111
- # exists to close.
106
+ # A secret-valued KEY (ADR-0113): one named, case-insensitively, password,
107
+ # pass, pwd, passwd or sslpassword, or one whose name contains password,
108
+ # secret or token (api_token, client_secret, ...). The same rule in all four
109
+ # frameworks. A key is only matched whole: "bypass" and "passfile" are not
110
+ # secret-valued, and sslmode, application_name and charset stay visible.
111
+ SECRET_KEY = /pass|pwd|passwd|[\w.\-]*?(?:password|secret|token)[\w.\-]*/i.freeze
112
+
113
+ # Secret-valued keywords in the two keyword=value forms a connection string
114
+ # uses: the ODBC connection string (";"-separated) and a URL query or a
115
+ # libpq conninfo ("&"-separated). The key is kept and its value replaced. A
116
+ # braced value is matched FIRST because an ODBC value containing ";" must be
117
+ # braced - stopping at the ";" would leave the tail of the password behind.
112
118
  #
113
119
  # UID/USER are deliberately NOT redacted: a username is not a secret, and it
114
120
  # is most of what makes a failed connection diagnosable.
115
- CREDENTIAL_KEYWORDS = /\b(PWD|PASSWORD)\s*=\s*(?:\{[^}]*\}|[^;&]*)/i.freeze
121
+ CREDENTIAL_KEYWORDS = /(?<![\w.\-])(#{SECRET_KEY.source})\s*=\s*(?:\{[^}]*\}|[^;&]*)/i.freeze
116
122
 
117
123
  attr_reader :engine, :host, :port, :database, :username, :password,
118
- :connection_string
124
+ :connection_string, :options
125
+
126
+ # Engines whose query string is connection OPTIONS (ADR-0113). sqlite and
127
+ # odbc are parsed raw (a path, a driver string); mongodb keeps handing its
128
+ # URL to the driver, which validates its own options.
129
+ OPTION_ENGINES = %w[postgres mysql mssql firebird].freeze
130
+
131
+ # libpq keywords that name the endpoint or a credential. They belong in the
132
+ # URL itself, where the credential precedence applies - in the query libpq
133
+ # would let them silently override it (ADR-0113).
134
+ POSTGRES_QUERY_FORBIDDEN = %w[host hostaddr port dbname user password passfile service].freeze
119
135
 
120
136
  def initialize(url, username: nil, password: nil)
121
137
  raise ArgumentError, "DatabaseUrl: the URL is empty" if url.nil? || url.to_s.strip.empty?
@@ -127,6 +143,7 @@ module Tina4
127
143
  @username = nil
128
144
  @password = nil
129
145
  @connection_string = nil
146
+ @options = {}
130
147
 
131
148
  if url.start_with?("sqlite:", "sqlite3:")
132
149
  parse_sqlite(url)
@@ -153,6 +170,77 @@ module Tina4
153
170
  @password = password if @password.nil? && password && !password.empty?
154
171
  end
155
172
 
173
+ # The query string as connection options (ADR-0113): key => ordered list of
174
+ # values, each percent-decoded ONCE. "+" stays "+" (a URL query is not a
175
+ # form). An empty segment is skipped; a key without "=" has the value "".
176
+ # A "%" not followed by two hex digits is refused - and never echoed, since
177
+ # an option value can be a secret.
178
+ def self.parse_query(query)
179
+ options = {}
180
+ query.to_s.split("&").each do |segment|
181
+ next if segment.empty?
182
+
183
+ key, _eq, value = segment.partition("=")
184
+ (options[decode_query_part(key)] ||= []) << decode_query_part(value)
185
+ end
186
+ options
187
+ end
188
+
189
+ def self.decode_query_part(text)
190
+ if text.match?(/%(?![0-9A-Fa-f]{2})/)
191
+ raise ArgumentError.new("DatabaseUrl: malformed percent-encoding in the query"), cause: nil
192
+ end
193
+
194
+ text.b.gsub(/%[0-9A-Fa-f]{2}/) { |m| [m[1, 2].hex].pack("C") }.force_encoding(Encoding::UTF_8)
195
+ end
196
+ private_class_method :decode_query_part
197
+
198
+ # The provider's option check (ADR-0113): a key given more than once, a key
199
+ # the provider does not honour, or a value outside the allowed set is
200
+ # refused BEFORE connecting. +supported+ maps each key to its allowed
201
+ # values (nil = any value). The message names the engine and the key,
202
+ # never the value. Returns the options, one value per key.
203
+ def self.check_options!(engine, options, supported)
204
+ options.each_with_object({}) do |(key, values), out|
205
+ raise ArgumentError.new("DatabaseUrl: option '#{key}' is given more than once"), cause: nil if values.length > 1
206
+
207
+ unless supported.key?(key)
208
+ raise ArgumentError.new("DatabaseUrl: unsupported option '#{key}' for #{engine} " "(supported: #{supported.keys.join(', ')})"), cause: nil
209
+ end
210
+ allowed = supported[key]
211
+ if allowed && !allowed.include?(values.first)
212
+ raise ArgumentError.new("DatabaseUrl: invalid value for option '#{key}' for #{engine} " "(expected: #{allowed.join(', ')})"), cause: nil
213
+ end
214
+ out[key] = values.first
215
+ end
216
+ end
217
+
218
+ # The options a driver receives, checked against +supported+ - or {} when
219
+ # +connection_string+ is not a URL (a libpq conninfo, a bare Firebird path).
220
+ def self.driver_options!(connection_string, engine, supported)
221
+ text = connection_string.to_s
222
+ return {} unless text.match?(URL_PREFIX)
223
+
224
+ check_options!(engine, new(text).options, supported)
225
+ end
226
+
227
+ # PostgreSQL's check: libpq validates its OWN keywords (an unknown one is
228
+ # refused by libpq), so the only keys Tina4 refuses are the endpoint and
229
+ # credential ones, plus a repeated key. Returns the options as given.
230
+ def self.postgres_options!(connection_string)
231
+ text = connection_string.to_s
232
+ return {} unless text.match?(URL_PREFIX)
233
+
234
+ options = new(text).options
235
+ options.each do |key, values|
236
+ raise ArgumentError.new("DatabaseUrl: option '#{key}' is given more than once"), cause: nil if values.length > 1
237
+ next unless POSTGRES_QUERY_FORBIDDEN.include?(key)
238
+
239
+ raise ArgumentError.new("DatabaseUrl: option '#{key}' is not allowed in the query for postgres " "(set it in the URL itself)"), cause: nil
240
+ end
241
+ options
242
+ end
243
+
156
244
  # Parse the configured URL, or nil when the variable is not set.
157
245
  def self.from_env(key = "TINA4_DATABASE_URL")
158
246
  url = (ENV[key] || "").strip
@@ -316,7 +404,9 @@ module Tina4
316
404
  span = password_span(raw)
317
405
  secrets << raw[span.first...span.last] if span
318
406
  begin
319
- secrets << new(raw).password
407
+ parsed = new(raw)
408
+ secrets << parsed.password
409
+ secrets.concat(secret_option_values(parsed.options))
320
410
  rescue StandardError
321
411
  nil
322
412
  end
@@ -325,6 +415,13 @@ module Tina4
325
415
  REDACTED
326
416
  end
327
417
 
418
+ # The values of the secret-valued keys in parsed query options: a driver
419
+ # that quotes one back on its own (outside its key=value pair) is masked too.
420
+ def self.secret_option_values(options)
421
+ options.select { |key, _| key.match?(/\A(?:#{SECRET_KEY.source})\z/i) }.values.flatten
422
+ end
423
+ private_class_method :secret_option_values
424
+
328
425
  # Replace each secret, and each piece of it, with the marker. A piece is
329
426
  # only masked where it is not part of a longer word: the driver quotes it
330
427
  # cut at a delimiter, so it stands alone there - while "word" from a
@@ -579,6 +676,15 @@ module Tina4
579
676
  scheme = match[1].downcase
580
677
  @engine = engine_for!(scheme)
581
678
  userinfo, hostpart = self.class.split_userinfo(url[match[0].length..])
679
+ # ADR-0113: for the option engines the query is split off HERE and parsed
680
+ # by #parse_query, so a malformed or URI-hostile option value is refused
681
+ # by name instead of failing URI.parse with the value in the message.
682
+ query = nil
683
+ if OPTION_ENGINES.include?(@engine)
684
+ without_fragment = hostpart.partition("#").first
685
+ hostpart, has_query, query = without_fragment.partition("?")
686
+ query = nil if has_query.empty?
687
+ end
582
688
  parsed = self.class.parse_hostpart(scheme, hostpart)
583
689
  # Raised OUTSIDE any rescue, and with cause: nil, so the InvalidURIError
584
690
  # (whose message holds the value) is never chained onto this one.
@@ -595,6 +701,9 @@ module Tina4
595
701
  # one or two leading slashes and rejects a relative path outright.
596
702
  database = strip_one_slash(parsed.path.to_s)
597
703
  @database = database.empty? && @engine == "mongodb" ? "tina4" : database
704
+ # ADR-0113: the query is OPTIONS, split off by the same rule (the
705
+ # userinfo is already gone, so a "?" in a password is never the query).
706
+ @options = self.class.parse_query(query) if OPTION_ENGINES.include?(@engine)
598
707
  end
599
708
 
600
709
  # The canonical engine for a scheme, or a refusal naming the scheme only.
@@ -803,11 +803,17 @@ module Tina4
803
803
  route_params = ctx.path_params || {}
804
804
 
805
805
  invoke = lambda do |req, resp|
806
+ # :request/:req and :response/:res are resolved BEFORE the path params:
807
+ # a route "/items/{request}" must not hand the URL segment to the
808
+ # handler's request argument (parity with tina4-nodejs#233). The segment
809
+ # is still in request.params.
806
810
  args = handler_params.map do |name|
807
- if route_params.key?(name)
808
- route_params[name]
809
- elsif name == :request || name == :req
811
+ if name == :request || name == :req
810
812
  req
813
+ elsif name == :response || name == :res
814
+ resp
815
+ elsif route_params.key?(name)
816
+ route_params[name]
811
817
  else
812
818
  resp
813
819
  end
@@ -177,7 +177,13 @@ module Tina4
177
177
  end
178
178
  end
179
179
 
180
+ # The URL query options Firebird honours (ADR-0113); anything else is
181
+ # refused. (PHP's `driver` option picks between its two Firebird drivers;
182
+ # Ruby has one, so it is refused here like any unknown key.)
183
+ URL_OPTIONS = { "charset" => nil }.freeze
184
+
180
185
  def connect(connection_string, username: nil, password: nil, charset: nil)
186
+ Tina4::DatabaseUrl.driver_options!(connection_string, "firebird", URL_OPTIONS)
181
187
  require "fb"
182
188
  require "uri"
183
189
  uri = URI.parse(connection_string)
@@ -23,7 +23,21 @@ module Tina4
23
23
  include SchemaSplit
24
24
  attr_reader :connection
25
25
 
26
+ # The URL query options SQL Server honours here (ADR-0113). tiny_tds sits
27
+ # on FreeTDS, which has no per-connection TLS setting (tiny_tds 3.4 takes
28
+ # none) and never verifies a server certificate without a configured CA:
29
+ # encrypt=false and either trustServerCertificate value describe what it
30
+ # does; encrypt=true would connect in plain text, so it is refused.
31
+ URL_OPTIONS = {
32
+ "encrypt" => %w[true false],
33
+ "trustServerCertificate" => %w[true false]
34
+ }.freeze
35
+
26
36
  def connect(connection_string, username: nil, password: nil)
37
+ url_options = Tina4::DatabaseUrl.driver_options!(connection_string, "mssql", URL_OPTIONS)
38
+ if url_options["encrypt"] == "true"
39
+ raise ArgumentError.new("DatabaseUrl: option 'encrypt=true' is not supported by the tiny_tds " "driver: it cannot require TLS per connection"), cause: nil
40
+ end
27
41
  begin
28
42
  require "tiny_tds"
29
43
  rescue LoadError
@@ -229,8 +243,10 @@ module Tina4
229
243
  # polynomial-redos without altering a single successful parse.
230
244
  match = str.match(%r{(?:mssql|sqlserver)://(?:(\w++):([^@]++)@)?([^:/]++)(?::(\d++))?/(.+)})
231
245
  if match
246
+ # The query is connection OPTIONS (ADR-0113), never part of the
247
+ # database name: `.../sales?encrypt=false` connects to `sales`.
232
248
  { username: match[1], password: match[2], host: match[3],
233
- port: match[4]&.to_i, database: match[5] }
249
+ port: match[4]&.to_i, database: match[5].sub(/[?#].*\z/m, "") }
234
250
  else
235
251
  { host: "localhost", database: str }
236
252
  end
@@ -28,7 +28,17 @@ module Tina4
28
28
  include SchemaSplit
29
29
  attr_reader :connection
30
30
 
31
+ # The URL query options MySQL honours (ADR-0113); anything else is refused.
32
+ URL_OPTIONS = { "charset" => nil }.freeze
33
+
34
+ # The checked URL options as mysql2 settings: ?charset=<name> is the
35
+ # connection character set (mysql2 :encoding).
36
+ def self.url_driver_options(url_options)
37
+ url_options.key?("charset") ? { encoding: url_options["charset"] } : {}
38
+ end
39
+
31
40
  def connect(connection_string, username: nil, password: nil)
41
+ url_options = Tina4::DatabaseUrl.driver_options!(connection_string, "mysql", URL_OPTIONS)
32
42
  begin
33
43
  require "mysql2"
34
44
  rescue LoadError
@@ -62,6 +72,7 @@ module Tina4
62
72
  # no bound sat past 20s and needed SIGKILL.
63
73
  seconds = Tina4::DatabaseAdapter.connect_timeout_whole_seconds
64
74
  options[:connect_timeout] = seconds if seconds
75
+ options.merge!(self.class.url_driver_options(url_options))
65
76
  Tina4::DatabaseAdapter.bounding_connect(options[:host], options[:port]) do
66
77
  @connection = Mysql2::Client.new(**options)
67
78
  end
@@ -71,6 +82,18 @@ module Tina4
71
82
  @connection&.close
72
83
  end
73
84
 
85
+ # A forked child must never speak on the parent's session (ADR-0074).
86
+ # Point this copy of the socket at /dev/null: freeing the client (its
87
+ # COM_QUIT) or a prepared statement it made (COM_STMT_CLOSE) then writes
88
+ # nowhere - measured: one freed statement broke the parent's connection.
89
+ def leave_after_fork!
90
+ return unless @connection
91
+
92
+ @connection.automatic_close = false if @connection.respond_to?(:automatic_close=)
93
+ fd = @connection.socket
94
+ IO.for_fd(fd, autoclose: false).reopen(IO::NULL) if fd.is_a?(Integer) && fd >= 0
95
+ end
96
+
74
97
  # Apply the MySQL dialect rewrites the translator owns: +||+ -> CONCAT and
75
98
  # ILIKE -> LOWER() LIKE LOWER() (both literal-safe). MySQL reads a bare +||+
76
99
  # as logical OR and has no ILIKE, so portable canonical SQL must be rewritten
@@ -39,6 +39,10 @@ module Tina4
39
39
 
40
40
  def connect(connection_string, username: nil, password: nil)
41
41
  @connect_args = [connection_string, username, password]
42
+ # ADR-0113: the URL's query reaches libpq as connection keywords (libpq
43
+ # refuses an unknown one itself); Tina4 refuses a repeated key and the
44
+ # endpoint/credential keywords, which belong in the URL itself.
45
+ Tina4::DatabaseUrl.postgres_options!(connection_string)
42
46
  begin
43
47
  require "pg"
44
48
  rescue LoadError
@@ -73,6 +77,13 @@ module Tina4
73
77
  @connection&.close
74
78
  end
75
79
 
80
+ # A forked child must never speak on the parent's session (ADR-0074):
81
+ # point this copy of the socket at /dev/null, so freeing the connection
82
+ # sends its terminate message nowhere.
83
+ def leave_after_fork!
84
+ @connection&.socket_io&.reopen(IO::NULL)
85
+ end
86
+
76
87
  # ── Reconnect after a dropped link (parity with the Python master #236/#242; #244) ──
77
88
  # The pg gem does not reconnect itself: once the server drops the link
78
89
  # (failover, idle reap, pg_terminate_backend) every exec raises until it is
@@ -85,6 +96,10 @@ module Tina4
85
96
  @connection.nil? || @connection.status == PG::CONNECTION_BAD
86
97
  end
87
98
 
99
+ # The owning Database's connect hooks (one shared Array), replayed on a
100
+ # connection this driver re-opens after the server dropped it (ADR-0110).
101
+ attr_writer :connect_hooks
102
+
88
103
  def reconnect
89
104
  begin
90
105
  @connection&.close
@@ -92,12 +107,47 @@ module Tina4
92
107
  # already gone
93
108
  end
94
109
  @connection = nil
110
+ @hooks_owed = true
95
111
  cs, user, pass = @connect_args
96
112
  connect(cs, username: user, password: pass)
113
+ Tina4::Log.warning("PostgreSQL connection was closed by the server - reconnected.")
114
+ replay_connect_hooks
115
+ end
116
+
117
+ # Run the connect hooks on a connection a reconnect just opened, before
118
+ # any statement runs on it: session state (SET, set_config) does not
119
+ # survive a reconnect otherwise (ADR-0110, tina4-python#337). A hook that
120
+ # fails closes the new connection again, so the next statement reconnects
121
+ # and replays them afresh instead of running on a session without its
122
+ # state.
123
+ def replay_connect_hooks
124
+ return unless @hooks_owed
125
+
126
+ begin
127
+ (@connect_hooks || []).each { |hook| hook.call(self) }
128
+ rescue StandardError
129
+ begin
130
+ @connection&.close
131
+ rescue StandardError
132
+ nil
133
+ end
134
+ @connection = nil
135
+ raise
136
+ end
137
+ @hooks_owed = false
138
+ end
139
+
140
+ # The SERVER's transaction status from the last ReadyForQuery - a local
141
+ # read, no round trip. A transaction opened with raw SQL ("BEGIN")
142
+ # leaves @in_transaction false but is not idle here.
143
+ def connection_idle?
144
+ !@connection.nil? && @connection.transaction_status == PG::PQTRANS_IDLE
97
145
  end
98
146
 
99
147
  def exec_with_reconnect
100
148
  reconnect if !@in_transaction && connection_dead?
149
+ # Read before the statement: once the link is gone it is unknown.
150
+ idle = connection_idle?
101
151
  begin
102
152
  yield
103
153
  rescue PG::Error => e
@@ -105,6 +155,18 @@ module Tina4
105
155
  # explicit transaction is reconnected and retried once.
106
156
  raise e if @in_transaction || !connection_dead?
107
157
 
158
+ unless idle && Tina4::DatabaseAdapter.reconnect_retry?
159
+ # Uncommitted work went down with the old link (a raw BEGIN), or
160
+ # TINA4_DB_RECONNECT_RETRY=false: heal the link now, but the
161
+ # caller sees the error - nothing is re-run on its own (ADR-0110).
162
+ begin
163
+ reconnect
164
+ rescue StandardError
165
+ # the next statement's pre-check retries the reconnect
166
+ end
167
+ raise e
168
+ end
169
+
108
170
  reconnect
109
171
  yield
110
172
  end
@@ -52,7 +52,15 @@ module Tina4
52
52
  # died with "database is locked". 5000 ms matches PHP's busyTimeout(5000)
53
53
  # and Python's sqlite3 default. Set BEFORE the WAL pragma so that write
54
54
  # waits too.
55
- @connection.busy_timeout = 5000
55
+ #
56
+ # busy_handler_timeout (sqlite3 >= 2.0) waits WITHOUT holding the GVL.
57
+ # busy_timeout waits inside SQLite holding it, so in a threaded server
58
+ # the thread that holds the write lock could not run to release it.
59
+ if @connection.respond_to?(:busy_handler_timeout=)
60
+ @connection.busy_handler_timeout = 5000
61
+ else
62
+ @connection.busy_timeout = 5000
63
+ end
56
64
  @connection.execute("PRAGMA journal_mode=WAL")
57
65
  @connection.execute("PRAGMA foreign_keys=ON")
58
66
  end
data/lib/tina4/sso.rb CHANGED
@@ -14,6 +14,7 @@ require "openssl"
14
14
  require "securerandom"
15
15
  require "uri"
16
16
  require_relative "parse_json"
17
+ require_relative "sso_jwks"
17
18
 
18
19
  module Tina4
19
20
  class SsoError < StandardError; end
@@ -47,9 +48,21 @@ module Tina4
47
48
  lifetime.positive? ? Time.now.to_i + lifetime : 0
48
49
  end
49
50
  attr_reader :issuer, :client_id, :client_secret, :redirect_uri, :scopes,
50
- :verify, :post_logout_redirect_uri, :claim_map
51
+ :verify, :post_logout_redirect_uri, :claim_map, :clock_skew, :jwks_max_age
51
52
  @mounted = false
52
53
 
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)
59
+ 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
62
+
63
+ raw
64
+ end
65
+
53
66
  def initialize(options = {})
54
67
  @issuer = (options[:issuer] || ENV["TINA4_SSO_ISSUER"] || "").sub(%r{/$}, "")
55
68
  @client_id = options[:client_id] || ENV["TINA4_SSO_CLIENT_ID"] || ""
@@ -59,7 +72,10 @@ module Tina4
59
72
  @verify = (options[:verify] || ENV["TINA4_SSO_VERIFY"] || "introspection").downcase
60
73
  @post_logout_redirect_uri = options[:post_logout_redirect_uri] || ENV["TINA4_SSO_POST_LOGOUT_REDIRECT_URI"]
61
74
  @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)
62
77
  @metadata = {}
78
+ @jwks_verifier = nil
63
79
  validate_config!
64
80
  end
65
81
 
@@ -95,7 +111,6 @@ module Tina4
95
111
  self.class.secure_url!(@issuer, "issuer")
96
112
  self.class.secure_url!(@redirect_uri, "redirect URI")
97
113
  raise SsoError, "TINA4_SSO_VERIFY must be introspection or jwks" unless %w[introspection jwks].include?(@verify)
98
- raise SsoError, "jwks verification requires an installed cryptography capability" if @verify == "jwks"
99
114
  raise SsoError, "introspection verification requires TINA4_SSO_CLIENT_SECRET" if @verify == "introspection" && @client_secret.to_s.empty?
100
115
  raise SsoError, "TINA4_SSO_SCOPES must be a list containing openid" unless @scopes.is_a?(Array) && @scopes.include?("openid")
101
116
  end
@@ -126,7 +141,7 @@ module Tina4
126
141
  result = request_json("#{@issuer}/.well-known/openid-configuration")
127
142
  raise SsoError, "OIDC discovery issuer does not exactly match configuration" unless result["issuer"] == @issuer
128
143
  required = %w[authorization_endpoint token_endpoint]
129
- required << "introspection_endpoint" if @verify == "introspection"
144
+ required << (@verify == "introspection" ? "introspection_endpoint" : "jwks_uri")
130
145
  required.each do |key|
131
146
  raise SsoError, "OIDC discovery is missing #{key}" if result[key].to_s.empty?
132
147
  self.class.secure_url!(result[key], key)
@@ -189,6 +204,37 @@ module Tina4
189
204
  result
190
205
  end
191
206
 
207
+ # jwks mode: the ID token's verified claims (ADR-0114, Tina4::JwksVerifier).
208
+ def verify_id_token(token, nonce = nil)
209
+ @jwks_verifier ||= JwksVerifier.new(@issuer, @client_id, @clock_skew, -> { request_json(discover["jwks_uri"]) }, @jwks_max_age)
210
+ @jwks_verifier.verify(token, nonce)
211
+ end
212
+
213
+ # Merge UserInfo over verified claims, only for the same subject (OIDC Core 5.3.2).
214
+ # Both modes: the subject is the ID token's (jwks) or the introspected one; an
215
+ # introspection response without a sub (RFC 7662 makes it optional) takes UserInfo's.
216
+ def with_userinfo(claims, access_token, metadata)
217
+ return claims unless metadata["userinfo_endpoint"]
218
+
219
+ info = request_json(metadata["userinfo_endpoint"], bearer: access_token)
220
+ if !claims["sub"].nil? && info["sub"] != claims["sub"]
221
+ raise SsoError, "OIDC UserInfo subject does not match the verified token"
222
+ end
223
+
224
+ claims.merge(info)
225
+ end
226
+
227
+ # jwks mode: verify a returned ID token (no nonce) for the same subject, else keep the identity.
228
+ def refreshed_identity(stored, tokens, metadata)
229
+ raise SsoError, "OIDC refresh response is incomplete" if tokens["access_token"].to_s.empty?
230
+ return stored["identity"] if tokens["id_token"].to_s.empty?
231
+
232
+ claims = verify_id_token(tokens["id_token"])
233
+ raise SsoError, "OIDC refreshed ID token subject changed" unless normalize(claims)["subject"] == stored.dig("identity", "subject")
234
+
235
+ normalize(with_userinfo(claims, tokens["access_token"], metadata))
236
+ end
237
+
192
238
  def claim(claims, configured, fallback)
193
239
  (configured || fallback).split(".").reduce(claims) { |value, key| value.is_a?(Hash) ? value[key] : nil }
194
240
  end
@@ -234,12 +280,15 @@ module Tina4
234
280
  client_id: @client_id, code_verifier: pending["verifier"]
235
281
  }, basic: !@client_secret.to_s.empty?)
236
282
  raise SsoError, "OIDC token response is incomplete" if tokens["access_token"].to_s.empty? || tokens["id_token"].to_s.empty?
237
- raise SsoError, "JWKS verification requires an installed cryptography capability" if @verify == "jwks"
238
- claims = introspect(tokens["access_token"])
239
- unless self.class.secure_equal(self.class.jwt_payload(tokens["id_token"])["nonce"], pending["nonce"])
240
- raise SsoError, "OIDC ID token nonce mismatch"
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)
241
291
  end
242
- claims.merge!(request_json(metadata["userinfo_endpoint"], bearer: tokens["access_token"])) if metadata["userinfo_endpoint"]
243
292
  identity = normalize(claims)
244
293
  current.regenerate
245
294
  current.set(SESSION_KEY, {
@@ -267,9 +316,11 @@ module Tina4
267
316
  tokens = request_json(metadata["token_endpoint"], form: {
268
317
  grant_type: "refresh_token", refresh_token: stored["refresh_token"], client_id: @client_id
269
318
  }, basic: !@client_secret.to_s.empty?)
270
- claims = introspect(tokens["access_token"])
271
- claims.merge!(request_json(metadata["userinfo_endpoint"], bearer: tokens["access_token"])) if metadata["userinfo_endpoint"]
272
- value = normalize(claims)
319
+ if @verify == "jwks"
320
+ value = refreshed_identity(stored, tokens, metadata)
321
+ else
322
+ value = normalize(with_userinfo(introspect(tokens["access_token"]), tokens["access_token"], metadata))
323
+ end
273
324
  current.set(SESSION_KEY, stored.merge(
274
325
  "identity" => value, "access_token" => tokens["access_token"],
275
326
  "refresh_token" => tokens["refresh_token"] || stored["refresh_token"],