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.
@@ -0,0 +1,184 @@
1
+ # frozen_string_literal: true
2
+ # Copyright (c) 2026 Code Infinity
3
+ # SPDX-License-Identifier: MPL-2.0
4
+ # This Source Code Form is subject to the terms of the Mozilla Public
5
+ # License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ # file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+
8
+ require "json"
9
+ require "openssl"
10
+ require_relative "base64"
11
+ require_relative "parse_json"
12
+
13
+ module Tina4
14
+ # ID-token verification against the provider's JWKS (ADR-0114, TINA4_SSO_VERIFY=jwks).
15
+ # Stdlib OpenSSL does the signature maths; this class only parses and checks, and
16
+ # builds the SubjectPublicKeyInfo of a JWK with OpenSSL::ASN1.
17
+ class JwksVerifier
18
+ # Only these algorithms are accepted, each pinned to the key type (and curve)
19
+ # that may verify it. none, HS* and everything else are refused before a key is used.
20
+ ALGORITHMS = { "RS256" => ["RSA", nil], "ES256" => ["EC", "P-256"] }.freeze
21
+
22
+ # At most one unknown-kid refetch per window (seconds): invented kids never
23
+ # become a fetch per request.
24
+ REFETCH_COOLDOWN = 60
25
+
26
+ NO_KEY_ID = "OIDC ID token has no key id"
27
+
28
+ # +fetch_jwks+ is a callable returning the provider's JWKS document.
29
+ def initialize(issuer, client_id, clock_skew, fetch_jwks, max_age = 3600)
30
+ @issuer = issuer
31
+ @client_id = client_id
32
+ @clock_skew = clock_skew
33
+ @fetch_jwks = fetch_jwks
34
+ @max_age = max_age
35
+ @keys = nil
36
+ @published = []
37
+ @loaded_at = nil
38
+ @refetched_at = nil
39
+ end
40
+
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)
47
+ check_claims(claims, nonce)
48
+ claims
49
+ end
50
+
51
+ def self.b64url(part)
52
+ Tina4::Base64.urlsafe_decode64(part.to_s.dup)
53
+ end
54
+
55
+ def self.parse(token)
56
+ parts = token.is_a?(String) ? token.split(".", -1) : []
57
+ raise SsoError, "OIDC ID token is malformed" unless parts.length == 3
58
+
59
+ header = Tina4.parse_json(b64url(parts[0]))
60
+ claims = Tina4.parse_json(b64url(parts[1]))
61
+ raise SsoError, "OIDC ID token is malformed" unless header.is_a?(Hash) && claims.is_a?(Hash)
62
+
63
+ [parts, header, claims, b64url(parts[2])]
64
+ rescue JSON::ParserError, ArgumentError
65
+ raise SsoError, "OIDC ID token is malformed"
66
+ end
67
+
68
+ def self.algorithm(header)
69
+ alg = header["alg"]
70
+ kid = header["kid"]
71
+ raise SsoError, "OIDC ID token algorithm is not allowed" unless alg.is_a?(String) && ALGORITHMS.key?(alg)
72
+ raise SsoError, NO_KEY_ID unless kid.nil? || (kid.is_a?(String) && !kid.empty?)
73
+
74
+ [alg, kid]
75
+ end
76
+
77
+ def self.der_integer(bytes)
78
+ OpenSSL::ASN1::Integer.new(OpenSSL::BN.new(bytes, 2))
79
+ end
80
+
81
+ # A key of the algorithm's type (and curve) whose own use and alg agree with it.
82
+ def self.fits?(jwk, alg)
83
+ kty, crv = ALGORITHMS[alg]
84
+ return false if jwk["kty"] != kty || (crv && jwk["crv"] != crv)
85
+
86
+ jwk.fetch("use", "sig") == "sig" && jwk.fetch("alg", alg) == alg
87
+ end
88
+
89
+ # Import a JWK the algorithm may use.
90
+ def self.public_key(jwk, alg)
91
+ raise SsoError, "OIDC ID token signing key does not match its algorithm" unless fits?(jwk, alg)
92
+
93
+ OpenSSL::PKey.read(spki(jwk, ALGORITHMS[alg][0]).to_der)
94
+ rescue ArgumentError, OpenSSL::PKey::PKeyError, OpenSSL::ASN1::ASN1Error, OpenSSL::BNError
95
+ raise SsoError, "OIDC ID token signing key is malformed"
96
+ end
97
+
98
+ # The SubjectPublicKeyInfo of an RSA or P-256 JWK (an ASN.1 encoding of its public numbers).
99
+ def self.spki(jwk, kty)
100
+ if kty == "RSA"
101
+ numbers = OpenSSL::ASN1::Sequence.new([der_integer(b64url(jwk["n"])), der_integer(b64url(jwk["e"]))])
102
+ algorithm = [OpenSSL::ASN1::ObjectId.new("rsaEncryption"), OpenSSL::ASN1::Null.new(nil)]
103
+ return OpenSSL::ASN1::Sequence.new([OpenSSL::ASN1::Sequence.new(algorithm), OpenSSL::ASN1::BitString.new(numbers.to_der)])
104
+ end
105
+ x = b64url(jwk["x"])
106
+ y = b64url(jwk["y"])
107
+ raise ArgumentError, "P-256 coordinates are 32 bytes" unless x.bytesize == 32 && y.bytesize == 32
108
+
109
+ algorithm = [OpenSSL::ASN1::ObjectId.new("id-ecPublicKey"), OpenSSL::ASN1::ObjectId.new("prime256v1")]
110
+ OpenSSL::ASN1::Sequence.new([OpenSSL::ASN1::Sequence.new(algorithm), OpenSSL::ASN1::BitString.new("\x04".b + x + y)])
111
+ end
112
+
113
+ def self.check_signature(alg, key, signing_input, signature)
114
+ if alg == "ES256"
115
+ signature = signature.bytesize == 64 ? OpenSSL::ASN1::Sequence.new([der_integer(signature[0, 32]), der_integer(signature[32, 32])]).to_der : ""
116
+ end
117
+ valid = !signature.empty? && key.verify("SHA256", signature, signing_input)
118
+ raise SsoError, "OIDC ID token signature is invalid" unless valid
119
+ rescue OpenSSL::PKey::PKeyError
120
+ raise SsoError, "OIDC ID token signature is invalid"
121
+ end
122
+
123
+ private
124
+
125
+ # Fetch the key set and REPLACE the cache, so a key the provider removed stops verifying.
126
+ def load
127
+ keys = @fetch_jwks.call["keys"]
128
+ raise SsoError, "OIDC JWKS is malformed" unless keys.is_a?(Array)
129
+
130
+ @published = keys.select { |key| key.is_a?(Hash) }
131
+ @keys = @published.each_with_object({}) { |key, cache| cache[key["kid"]] = key if key["kid"].is_a?(String) }
132
+ @loaded_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
133
+ end
134
+
135
+ # The JWK for kid, or the one key that fits alg when the token names none. The set
136
+ # is fetched on first use and again once older than the max age; an unknown kid
137
+ # refetches once, unless this verification already fetched, at most once per cooldown.
138
+ def signing_key(kid, alg)
139
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
140
+ fresh = @keys.nil? || now - @loaded_at >= @max_age
141
+ load if fresh
142
+ return only_fitting_key(alg) if kid.nil?
143
+
144
+ if !@keys.key?(kid) && !fresh && (@refetched_at.nil? || now - @refetched_at >= REFETCH_COOLDOWN)
145
+ @refetched_at = now
146
+ load
147
+ end
148
+ @keys.fetch(kid) { raise SsoError, "OIDC ID token signing key is unknown" }
149
+ end
150
+
151
+ # A token without a kid is verified only when exactly one published key fits its algorithm.
152
+ def only_fitting_key(alg)
153
+ fitting = @published.select { |key| self.class.fits?(key, alg) }
154
+ raise SsoError, NO_KEY_ID unless fitting.length == 1
155
+
156
+ fitting.first
157
+ end
158
+
159
+ def check_claims(claims, nonce)
160
+ raise SsoError, "OIDC ID token has no subject" unless claims["sub"].is_a?(String) && !claims["sub"].empty?
161
+ raise SsoError, "OIDC ID token issuer mismatch" unless claims["iss"] == @issuer
162
+
163
+ check_audience(claims)
164
+ check_times(claims)
165
+ raise SsoError, "OIDC ID token nonce mismatch" if nonce && !Tina4::Sso.secure_equal(claims["nonce"], nonce)
166
+ end
167
+
168
+ def check_audience(claims)
169
+ audience = claims["aud"]
170
+ valid = audience.is_a?(String) ? audience == @client_id : audience.is_a?(Array) && audience.include?(@client_id)
171
+ raise SsoError, "OIDC ID token audience mismatch" unless valid
172
+ raise SsoError, "OIDC ID token authorized party mismatch" if claims.key?("azp") && claims["azp"] != @client_id
173
+ end
174
+
175
+ def check_times(claims)
176
+ now = Time.now.to_f
177
+ raise SsoError, "OIDC ID token exp is missing or invalid" unless claims["exp"].is_a?(Numeric)
178
+ raise SsoError, "OIDC ID token has expired" if now >= claims["exp"] + @clock_skew
179
+ return unless claims.key?("nbf")
180
+ raise SsoError, "OIDC ID token nbf is invalid" unless claims["nbf"].is_a?(Numeric)
181
+ raise SsoError, "OIDC ID token is not yet valid" if now < claims["nbf"] - @clock_skew
182
+ end
183
+ end
184
+ end
data/lib/tina4/version.rb CHANGED
@@ -7,5 +7,5 @@
7
7
 
8
8
 
9
9
  module Tina4
10
- VERSION = "3.13.167"
10
+ VERSION = "3.13.169"
11
11
  end
@@ -54,6 +54,42 @@ module Tina4
54
54
  allowed.include?(origin)
55
55
  end
56
56
 
57
+ # Default for TINA4_WS_MAX_CONNECTIONS, the same 10000 as tina4-python.
58
+ WS_DEFAULT_MAX_CONNECTIONS = 10_000
59
+
60
+ # The most open WebSocket connections a server holds, TINA4_WS_MAX_CONNECTIONS.
61
+ # A value that is not a positive whole number uses the default.
62
+ def self.ws_max_connections
63
+ raw = (ENV["TINA4_WS_MAX_CONNECTIONS"] || "").strip
64
+ raw.match?(/\A\d+\z/) && raw.to_i.positive? ? raw.to_i : WS_DEFAULT_MAX_CONNECTIONS
65
+ end
66
+
67
+ # True when +open+ connections already reach TINA4_WS_MAX_CONNECTIONS: the next
68
+ # upgrade is answered 503 before the handshake. A closed connection frees its slot.
69
+ def self.ws_at_connection_cap?(open)
70
+ open >= ws_max_connections
71
+ end
72
+
73
+ # Default for TINA4_WS_MAX_FRAME_SIZE: 1 MiB, the same as tina4-python and tina4-php.
74
+ WS_DEFAULT_MAX_FRAME_SIZE = 1_048_576
75
+
76
+ # The largest frame payload a WebSocket server accepts, TINA4_WS_MAX_FRAME_SIZE
77
+ # bytes. A value that is not a positive whole number uses the default.
78
+ def self.ws_max_frame_size
79
+ raw = (ENV["TINA4_WS_MAX_FRAME_SIZE"] || "").strip
80
+ raw.match?(/\A\d+\z/) && raw.to_i.positive? ? raw.to_i : WS_DEFAULT_MAX_FRAME_SIZE
81
+ end
82
+
83
+ # Why a frame's declared payload length is refused, or nil when it is accepted.
84
+ # Checked on the frame header, before the payload is waited for. A 64-bit length
85
+ # with its most significant bit set is forbidden by RFC 6455 section 5.2.
86
+ def self.ws_frame_length_refusal(length, max_payload)
87
+ return "WebSocket frame length has its most significant bit set" if length >= (1 << 63)
88
+ return nil if max_payload.nil? || length <= max_payload
89
+
90
+ "WebSocket frame payload of #{length} bytes is past the #{max_payload}-byte limit"
91
+ end
92
+
57
93
  # Extract a bearer token from a WebSocket upgrade handshake.
58
94
  #
59
95
  # Order (mirrors Python's tina4_python.websocket.ws_token):
@@ -659,6 +695,15 @@ module Tina4
659
695
  return
660
696
  end
661
697
 
698
+ # Connection cap (TINA4_WS_MAX_CONNECTIONS, default 10000), counted on the
699
+ # engine that owns this connection: past it the upgrade is answered 503
700
+ # before the handshake; a closed connection frees its slot. Mirrors Python.
701
+ if Tina4.ws_at_connection_cap?(manager.connections.size)
702
+ socket.write("HTTP/1.1 503 Service Unavailable\r\n\r\n") rescue nil
703
+ socket.close rescue nil
704
+ return
705
+ end
706
+
662
707
  accept = Tina4.compute_accept_key(key)
663
708
 
664
709
  # When the client offered the "bearer" subprotocol (the browser transport,
@@ -890,28 +935,19 @@ module Tina4
890
935
  first_byte = @socket.getbyte
891
936
  return nil unless first_byte
892
937
 
893
- fin = (first_byte & 0x80) != 0
894
- opcode = first_byte & 0x0F
895
938
  second_byte = @socket.getbyte
896
939
  return nil unless second_byte
897
940
 
898
- masked = (second_byte & 0x80) != 0
899
- length = second_byte & 0x7F
900
-
901
- if length == 126
902
- length = @socket.read(2).unpack1("n")
903
- elsif length == 127
904
- length = @socket.read(8).unpack1("Q>")
905
- end
941
+ # Refuse an oversized or malformed length on the header, before the payload
942
+ # is read; nil ends the frame loop, which closes the connection.
943
+ length = read_payload_length(second_byte & 0x7F)
944
+ return nil unless length && frame_length_accepted?(length)
906
945
 
907
- mask_key = masked ? @socket.read(4).bytes : nil
946
+ mask_key = (second_byte & 0x80) != 0 ? @socket.read(4).bytes : nil
908
947
  data = @socket.read(length) || ""
948
+ data = data.bytes.each_with_index.map { |b, i| b ^ mask_key[i % 4] }.pack("C*") if mask_key
909
949
 
910
- if masked && mask_key
911
- data = data.bytes.each_with_index.map { |b, i| b ^ mask_key[i % 4] }.pack("C*")
912
- end
913
-
914
- { fin: fin, opcode: opcode, data: data }
950
+ { fin: (first_byte & 0x80) != 0, opcode: first_byte & 0x0F, data: data }
915
951
  rescue IOError, EOFError
916
952
  nil
917
953
  end
@@ -922,6 +958,25 @@ module Tina4
922
958
 
923
959
  private
924
960
 
961
+ # The payload length: the 7-bit value, or the 16- or 64-bit extended length
962
+ # that follows it (RFC 6455 section 5.2). nil when the extended length is cut short.
963
+ def read_payload_length(length)
964
+ size = { 126 => 2, 127 => 8 }[length]
965
+ return length unless size
966
+
967
+ raw = @socket.read(size)
968
+ raw&.bytesize == size ? raw.unpack1(size == 2 ? "n" : "Q>") : nil
969
+ end
970
+
971
+ # TINA4_WS_MAX_FRAME_SIZE and the RFC 6455 top-bit rule, checked on the header.
972
+ def frame_length_accepted?(length)
973
+ refusal = Tina4.ws_frame_length_refusal(length, Tina4.ws_max_frame_size)
974
+ return true unless refusal
975
+
976
+ Tina4::Log.warning("WebSocket connection closed: #{refusal}")
977
+ false
978
+ end
979
+
925
980
  def write_lock
926
981
  @write_lock ||= Mutex.new
927
982
  end
data/lib/tina4.rb CHANGED
@@ -373,6 +373,20 @@ module Tina4
373
373
  # A CI variable set to one of these does not mean CI (ADR-0070 ci_false).
374
374
  CI_FALSE_VALUES = %w[false 0 no off].freeze
375
375
 
376
+ # A file under src/ failed to load during a STRICT discovery pass - the boot
377
+ # pass outside debug (ADR-0112, tina4-python#336). The original error is
378
+ # `cause`; `file` names the file.
379
+ class DiscoveryError < StandardError
380
+ attr_reader :file
381
+
382
+ def initialize(file, error)
383
+ @file = file
384
+ super("Refusing to start: #{file} failed to load (#{error.class}: #{error.message}). " \
385
+ "A production boot stops on a file that cannot load, so the app never serves without it. " \
386
+ "Fix the file, or set TINA4_STRICT_DISCOVER=false to serve without it (ADR-0112).")
387
+ end
388
+ end
389
+
376
390
  class << self
377
391
  attr_accessor :root_dir
378
392
  attr_reader :database
@@ -523,8 +537,11 @@ module Tina4
523
537
  # Python registers its built-ins first for the same reason.
524
538
  register_builtin_routes!
525
539
 
526
- # Auto-discover routes
527
- auto_discover(root_dir)
540
+ # Auto-discover routes. Outside debug this pass is strict (ADR-0112,
541
+ # tina4-python#336): a file that fails to load raises
542
+ # Tina4::DiscoveryError out of initialize!, like the insecure-secret
543
+ # refusal above, so the process exits 1 instead of serving without it.
544
+ auto_discover(root_dir, strict: strict_discover?)
528
545
 
529
546
  # Configuration-first OIDC mounts after application discovery so a
530
547
  # canonical-path collision fails loudly rather than being shadowed.
@@ -1002,15 +1019,9 @@ module Tina4
1002
1019
  safe_url = Tina4::DatabaseUrl.without_credentials(db_url)
1003
1020
  begin
1004
1021
  database = bind_database(Tina4::Database.new(db_url))
1005
- if database.pool
1006
- # Pooled mode connects lazily on first use, so `connected` is true
1007
- # before anything has connected. Say what is actually known: the pool
1008
- # exists. Verifying a connection here would change boot behaviour
1009
- # (an unreachable database would cost a connect timeout at boot);
1010
- # the first query reports a failure with its cause instead.
1011
- Tina4::Log.info("Database pool configured (#{database.pool_size} connections, " \
1012
- "not yet connected - connects on first use): #{safe_url}")
1013
- elsif !database.connected
1022
+ # A pool opens its first connection at construction exactly as the
1023
+ # single connection does (ADR-0074), so both report the same way.
1024
+ if !database.connected
1014
1025
  # Database.new logs-and-degrades on a failed connect instead of
1015
1026
  # raising, so only claim a connection the database itself reports.
1016
1027
  Tina4::Log.warning("Database not connected: #{safe_url}")
@@ -1028,7 +1039,23 @@ module Tina4
1028
1039
  end
1029
1040
  end
1030
1041
 
1031
- def auto_discover(root_dir)
1042
+ # Whether the BOOT discovery pass stops on the first file that fails to
1043
+ # load (ADR-0112): strict outside debug, lenient in debug, and
1044
+ # TINA4_STRICT_DISCOVER set to any value overrides that either way.
1045
+ def strict_discover?
1046
+ raw = ENV.fetch("TINA4_STRICT_DISCOVER", "").strip
1047
+ return Tina4::Env.is_truthy(raw) unless raw.empty?
1048
+
1049
+ !Tina4::ErrorOverlay.is_debug_mode
1050
+ end
1051
+
1052
+ # Load every route/API/ORM file. A file that fails to load - any error
1053
+ # Ruby raises while loading it, a SyntaxError or LoadError included - is
1054
+ # logged and marked (Router.record_broken_route_import), and discovery
1055
+ # moves on. With strict: true (the boot pass outside debug, ADR-0112) it raises
1056
+ # Tina4::DiscoveryError instead, naming the file, with the original error
1057
+ # as its cause.
1058
+ def auto_discover(root_dir, strict: false)
1032
1059
  # src/ prefixed directories take priority over root-level ones
1033
1060
  discover_dirs = %w[src/routes routes src/api api src/orm orm]
1034
1061
  discover_dirs.each do |dir|
@@ -1039,8 +1066,10 @@ module Tina4
1039
1066
  begin
1040
1067
  load file
1041
1068
  Tina4::Log.debug("Auto-loaded: #{file}")
1042
- rescue => e
1069
+ rescue ScriptError, StandardError => e
1043
1070
  Tina4::Log.error("Failed to load #{file}: #{e.message}")
1071
+ Tina4::Router.record_broken_route_import(file, e)
1072
+ raise Tina4::DiscoveryError.new(file, e) if strict
1044
1073
  end
1045
1074
  end
1046
1075
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tina4ruby
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.13.167
4
+ version: 3.13.169
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tina4 Team
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-11-30 00:00:00.000000000 Z
11
+ date: 2026-12-03 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: sqlite3
@@ -354,6 +354,7 @@ files:
354
354
  - lib/tina4/sqlite3_gem.rb
355
355
  - lib/tina4/sqlite_path_resolver.rb
356
356
  - lib/tina4/sso.rb
357
+ - lib/tina4/sso_jwks.rb
357
358
  - lib/tina4/ssrf.rb
358
359
  - lib/tina4/swagger.rb
359
360
  - lib/tina4/tcp.rb