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
@@ -0,0 +1,101 @@
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
+
9
+ module Tina4
10
+ # TINA4_RATE_LIMIT or TINA4_RATE_WINDOW holds a value that cannot work.
11
+ class RateLimitConfigError < ArgumentError; end
12
+
13
+ # The rate-limit policy: TINA4_RATE_LIMIT / TINA4_RATE_WINDOW read and checked
14
+ # once at boot, the off switch, and the health/readiness paths that are never
15
+ # counted. The limiter itself is Tina4::RateLimiter.
16
+ module RateLimitPolicy
17
+ DEFAULT_LIMIT = 100
18
+ DEFAULT_WINDOW = 60 # seconds
19
+ # The values that switch limiting off, as for every Tina4 opt-out (ADR-0101).
20
+ OFF_VALUES = %w[false 0 no off].freeze
21
+
22
+ @warned = {}
23
+ @policy = nil
24
+
25
+ class << self
26
+ # The policy from the environment. Raises RateLimitConfigError.
27
+ # { enabled:, off:, limit:, window:, probe_paths: }
28
+ def parse(env = ENV)
29
+ raw_limit = env["TINA4_RATE_LIMIT"].to_s
30
+ raw_window = env["TINA4_RATE_WINDOW"].to_s
31
+ value = raw_limit.strip
32
+ off = OFF_VALUES.include?(value.downcase)
33
+ limit = off || value.empty? ? DEFAULT_LIMIT : positive_int("TINA4_RATE_LIMIT", raw_limit, "requests per window")
34
+ window = raw_window.strip.empty? ? DEFAULT_WINDOW : positive_int("TINA4_RATE_WINDOW", raw_window, "seconds")
35
+ {
36
+ enabled: !off && !value.empty?, off: off, limit: limit, window: window,
37
+ probe_paths: probe_paths(env)
38
+ }
39
+ end
40
+
41
+ # Read the policy once, at boot. Raises RateLimitConfigError.
42
+ def load!
43
+ @policy = parse
44
+ log_once("off", "TINA4_RATE_LIMIT=#{ENV['TINA4_RATE_LIMIT']}: rate limiting disabled.") if @policy[:off]
45
+ @policy
46
+ end
47
+
48
+ # The policy read at boot. Before a boot it is read from the environment
49
+ # each time, without being kept.
50
+ def current
51
+ @policy || parse
52
+ end
53
+
54
+ # Forget the loaded policy and the logged-once ledger (for tests).
55
+ def reset!
56
+ @policy = nil
57
+ @warned = {}
58
+ end
59
+
60
+ # A health or readiness probe, which is never counted.
61
+ def probe?(request)
62
+ path = request.respond_to?(:path) ? request.path.to_s : ""
63
+ current[:probe_paths].include?(normalise(path))
64
+ end
65
+
66
+ private
67
+
68
+ def positive_int(name, raw, what)
69
+ value = raw.to_s.strip
70
+ return value.to_i if value.match?(/\A\d+\z/) && value.to_i.positive?
71
+
72
+ extra = name == "TINA4_RATE_LIMIT" ? ", or to off to switch rate limiting off." : "."
73
+ raise RateLimitConfigError, "#{name}=#{raw.inspect} is not valid: set it to a positive whole number of #{what}#{extra}"
74
+ end
75
+
76
+ def probe_paths(env)
77
+ health = env["TINA4_HEALTH_PATH"].to_s.strip
78
+ ready = env["TINA4_READINESS_PATH"].to_s.strip
79
+ [health.empty? ? "/__health" : health, "/__health", "/health",
80
+ ready.empty? ? "/__ready" : ready, "/__ready", "/ready"].map { |p| normalise(p) }
81
+ end
82
+
83
+ # A loop, not a regex: the path is client input.
84
+ def normalise(path)
85
+ trimmed = path.split("?").first.to_s
86
+ trimmed = trimmed.chomp("/") while trimmed.end_with?("/")
87
+ trimmed.empty? ? "/" : trimmed
88
+ end
89
+
90
+ # A rare duplicate line under a race is harmless; no lock needed.
91
+ def log_once(key, message)
92
+ return if @warned[key]
93
+
94
+ @warned[key] = true
95
+ Tina4::Log.warning(message)
96
+ rescue StandardError
97
+ nil # logging must never break a request
98
+ end
99
+ end
100
+ end
101
+ end
@@ -7,15 +7,52 @@
7
7
 
8
8
 
9
9
  module Tina4
10
+ # Sliding-window rate limiter, per client address.
11
+ #
12
+ # Tina4.initialize! reads the policy once and attaches Tina4::DefaultRateLimiter
13
+ # globally (before route matching and the auth gate) when TINA4_RATE_LIMIT is set.
14
+ # TINA4_RATE_LIMIT -- requests per window (default 100). false, 0, no or off
15
+ # switches every limiter that reads it off (logged once).
16
+ # TINA4_RATE_WINDOW -- window in seconds (default 60).
17
+ # Any other value that is not a positive whole number stops the boot with a
18
+ # RateLimitConfigError naming the setting.
19
+ #
20
+ # Health and readiness probes (TINA4_HEALTH_PATH or /__health, /health,
21
+ # TINA4_READINESS_PATH or /__ready, /ready) are never counted. The client
22
+ # address is request.ip, which honours forwarding headers only from
23
+ # TINA4_TRUSTED_PROXIES. Addresses whose window has passed are swept once a
24
+ # window. Known limitation until Feature 35 (ADR-0049): counts are per process.
10
25
  class RateLimiter
11
26
  DEFAULT_LIMIT = 100
12
27
  DEFAULT_WINDOW = 60 # seconds
13
28
 
29
+ class << self
30
+ # One sliding-window step (caller holds the lock).
31
+ # Returns { allowed:, count:, oldest: }; count includes this request when allowed.
32
+ def hit(store, ip, limit, window, now)
33
+ entries = (store[ip] || []).select { |t| t > now - window }
34
+ store[ip] = entries
35
+ if entries.length >= limit
36
+ { allowed: false, count: entries.length, oldest: entries.first }
37
+ else
38
+ entries << now
39
+ { allowed: true, count: entries.length, oldest: entries.first }
40
+ end
41
+ end
42
+
43
+ def sweep(store, cutoff)
44
+ store.delete_if { |_ip, entries| entries.empty? || entries.last <= cutoff }
45
+ end
46
+ end
47
+
14
48
  attr_reader :limit, :window
15
49
 
50
+ # Numbers given here are used as they are; the rest are read from the
51
+ # environment now. Raises RateLimitConfigError.
16
52
  def initialize(limit: nil, window: nil)
17
- @limit = (limit || ENV["TINA4_RATE_LIMIT"] || DEFAULT_LIMIT).to_i
18
- @window = (window || ENV["TINA4_RATE_WINDOW"] || DEFAULT_WINDOW).to_i
53
+ policy = limit && window ? nil : RateLimitPolicy.parse
54
+ @limit = limit ? limit.to_i : policy[:limit]
55
+ @window = window ? window.to_i : policy[:window]
19
56
  @store = {} # ip => [timestamps]
20
57
  @mutex = Mutex.new
21
58
  @last_cleanup = Time.now
@@ -29,35 +66,23 @@ module Tina4
29
66
  cleanup_if_needed(now)
30
67
 
31
68
  @mutex.synchronize do
32
- @store[ip] ||= []
33
- entries = @store[ip]
34
-
35
- # Remove expired entries (sliding window)
36
- cutoff = now - @window
37
- entries.reject! { |t| t < cutoff }
38
-
39
- if entries.length >= @limit
40
- # Rate limited
41
- oldest = entries.first
42
- reset_at = (oldest + @window).to_i
43
- retry_after = [(oldest + @window - now).ceil, 1].max
44
-
69
+ result = self.class.hit(@store, ip, @limit, @window, now)
70
+ oldest = result[:oldest]
71
+ if result[:allowed]
45
72
  {
46
- allowed: false,
73
+ allowed: true,
47
74
  limit: @limit,
48
- remaining: 0,
49
- reset: reset_at,
50
- retry_after: retry_after
75
+ remaining: @limit - result[:count],
76
+ reset: (now + @window).to_i,
77
+ retry_after: nil
51
78
  }
52
79
  else
53
- entries << now
54
-
55
80
  {
56
- allowed: true,
81
+ allowed: false,
57
82
  limit: @limit,
58
- remaining: @limit - entries.length,
59
- reset: (now + @window).to_i,
60
- retry_after: nil
83
+ remaining: 0,
84
+ reset: (oldest + @window).to_i,
85
+ retry_after: [(oldest + @window - now).ceil, 1].max
61
86
  }
62
87
  end
63
88
  end
@@ -93,7 +118,10 @@ module Tina4
93
118
  end
94
119
 
95
120
  # Standardized middleware hook — enforces rate limiting before the route handler.
121
+ # Health and readiness probes pass untouched.
96
122
  def before_rate_limit(request, response)
123
+ return [request, response] if RateLimitPolicy.probe?(request)
124
+
97
125
  ip = request.respond_to?(:ip) ? request.ip : "unknown"
98
126
  apply(ip, response)
99
127
  [request, response]
@@ -117,18 +145,14 @@ module Tina4
117
145
 
118
146
  private
119
147
 
120
- # Clean up expired entries periodically (every window interval)
148
+ # Sweep addresses whose window has passed, once a window.
121
149
  def cleanup_if_needed(now)
122
150
  return if now - @last_cleanup < @window
123
151
 
124
152
  @mutex.synchronize do
125
153
  return if now - @last_cleanup < @window
126
154
 
127
- cutoff = now - @window
128
- @store.delete_if do |_ip, entries|
129
- entries.reject! { |t| t < cutoff }
130
- entries.empty?
131
- end
155
+ self.class.sweep(@store, now - @window)
132
156
  @last_cleanup = now
133
157
  end
134
158
  end
data/lib/tina4/request.rb CHANGED
@@ -11,6 +11,7 @@ require "ipaddr"
11
11
  require "stringio"
12
12
  require_relative "parse_json"
13
13
  require_relative "form_parser"
14
+ require_relative "route_path"
14
15
 
15
16
  module Tina4
16
17
  # A Hash subclass that supports indifferent access (both string and symbol keys).
@@ -123,7 +124,11 @@ module Tina4
123
124
  end
124
125
 
125
126
  class Request
126
- attr_reader :env, :method, :path, :query_string, :content_type,
127
+ # +path+ is the path as the router matches it: every percent-escape decoded
128
+ # once except %2F and %25 (Tina4::RoutePath.matchable), so a middleware
129
+ # that decides by path reads the same path the router matches. +raw_path+
130
+ # is the path exactly as sent, still percent-encoded.
131
+ attr_reader :env, :method, :path, :raw_path, :query_string, :content_type,
127
132
  :ip, :remote_ip
128
133
  # :route is the matched Route, attached by the dispatcher before post-match
129
134
  # middleware runs (DispatchPipeline#prepare_route_request). CsrfMiddleware
@@ -245,7 +250,10 @@ module Tina4
245
250
  def initialize(env, path_params = {})
246
251
  @env = env
247
252
  @method = env["REQUEST_METHOD"]
248
- @path = env["PATH_INFO"] || "/"
253
+ @raw_path = env["PATH_INFO"] || "/"
254
+ # Decoded once, from the path as sent, by the same function the router
255
+ # matches with - never decoded a second time.
256
+ @path = Tina4::RoutePath.matchable(@raw_path)
249
257
  @query_string = env["QUERY_STRING"] || ""
250
258
  @content_type = env["CONTENT_TYPE"] || ""
251
259
  @path_params = path_params
@@ -329,7 +337,8 @@ module Tina4
329
337
  # Only append :port when the host doesn't already include one
330
338
  # (HTTP_HOST often does) and it's not the default for the scheme.
331
339
  url_str += ":#{port}" if port && !host.include?(":") && port.to_s != "80" && port.to_s != "443"
332
- url_str += @path
340
+ # Built from the path as sent: a URL keeps its percent-encoding.
341
+ url_str += @raw_path
333
342
  url_str += "?#{@query_string}" unless @query_string.empty?
334
343
  url_str
335
344
  end
@@ -109,9 +109,13 @@ module Tina4
109
109
 
110
110
  # Callable response — auto-detects content type from data.
111
111
  # Matches Python __call__ / PHP __invoke / Node response() pattern.
112
- def call(data = nil, status_code = 200, content_type = nil)
112
+ #
113
+ # With no status the response keeps the one it already has: 200 on a fresh
114
+ # response, or whatever #status set before the call. The same rule holds
115
+ # for #json, #html, #text, #xml and #render (ADR-0019 decision 3).
116
+ def call(data = nil, status_code = nil, content_type = nil)
113
117
  Response.check_header!("Content-Type", content_type) if content_type
114
- @status_code = status_code
118
+ @status_code = status_code unless status_code.nil?
115
119
  data = jsonable(data)
116
120
  if content_type
117
121
  @headers["content-type"] = content_type
@@ -127,7 +131,7 @@ module Tina4
127
131
  end
128
132
 
129
133
  def json(data, status_or_opts = nil, status: nil)
130
- @status_code = status || (status_or_opts.is_a?(Integer) ? status_or_opts : 200)
134
+ @status_code = status || (status_or_opts.is_a?(Integer) ? status_or_opts : @status_code)
131
135
  @headers["content-type"] = JSON_CONTENT_TYPE
132
136
  data = jsonable(data)
133
137
  @body = data.is_a?(String) ? data : JSON.generate(data)
@@ -153,21 +157,21 @@ module Tina4
153
157
  private :jsonable
154
158
 
155
159
  def html(content, status_or_opts = nil, status: nil)
156
- @status_code = status || (status_or_opts.is_a?(Integer) ? status_or_opts : 200)
160
+ @status_code = status || (status_or_opts.is_a?(Integer) ? status_or_opts : @status_code)
157
161
  @headers["content-type"] = HTML_CONTENT_TYPE
158
162
  @body = content.to_s
159
163
  self
160
164
  end
161
165
 
162
166
  def text(content, status_or_opts = nil, status: nil)
163
- @status_code = status || (status_or_opts.is_a?(Integer) ? status_or_opts : 200)
167
+ @status_code = status || (status_or_opts.is_a?(Integer) ? status_or_opts : @status_code)
164
168
  @headers["content-type"] = TEXT_CONTENT_TYPE
165
169
  @body = content.to_s
166
170
  self
167
171
  end
168
172
 
169
- def xml(content, status: 200)
170
- @status_code = status
173
+ def xml(content, status: nil)
174
+ @status_code = status || @status_code
171
175
  @headers["content-type"] = XML_CONTENT_TYPE
172
176
  @body = content.to_s
173
177
  self
@@ -251,8 +255,8 @@ module Tina4
251
255
  # Render a Frond/Twig template file with data and return self. Tries
252
256
  # the user template directory first, falling back to the framework's
253
257
  # built-in templates. Sets the response body to the rendered HTML.
254
- def render(template_path, data = {}, status: 200, template_dir: nil)
255
- @status_code = status
258
+ def render(template_path, data = {}, status: nil, template_dir: nil)
259
+ @status_code = status || @status_code
256
260
  @headers["content-type"] = HTML_CONTENT_TYPE
257
261
 
258
262
  engine = template_dir ? Tina4::Frond.new(template_dir: template_dir) : Tina4.get_frond
@@ -5,6 +5,7 @@
5
5
  # License, v. 2.0. If a copy of the MPL was not distributed with this
6
6
  # file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
7
 
8
+ require "time"
8
9
 
9
10
  module Tina4
10
11
  # Multi-backend response cache for GET requests.
@@ -396,6 +397,12 @@ module Tina4
396
397
  return unless may_store?(request, response)
397
398
 
398
399
  effective_ttl = ttl || @ttl
400
+ lifetime = freshness_lifetime(response)
401
+ unless lifetime.nil?
402
+ return if lifetime <= 0
403
+
404
+ effective_ttl = [effective_ttl, lifetime].min
405
+ end
399
406
  key = cache_key(method, url)
400
407
  expires_at = Time.now.to_f + effective_ttl
401
408
  vary = vary_fields(response)
@@ -430,6 +437,43 @@ module Tina4
430
437
  # carrying Authorization (RFC 9111 s3.5).
431
438
  SHARED_CACHE_DIRECTIVES = %w[public s-maxage must-revalidate].freeze
432
439
 
440
+ # The response's own freshness lifetime in seconds, for a SHARED cache.
441
+ #
442
+ # RFC 9111 s4.2.1: s-maxage first, then max-age, then Expires. nil when the
443
+ # response states none, which leaves the configured TTL to decide. A value
444
+ # that cannot be read counts as already stale (0): s4.2.1 asks a cache to
445
+ # treat invalid freshness information as stale, and s5.3 says an Expires
446
+ # that is not a valid date ("0" above all) is in the past.
447
+ #
448
+ # This cache can neither revalidate nor serve a stale response (s4.2.4), so
449
+ # an entry never outlives this lifetime, and a response that is stale on
450
+ # arrival (max-age=0, s-maxage=0, Expires: 0) is not stored at all,
451
+ # whatever public or must-revalidate says.
452
+ #
453
+ # @param response [Object, nil]
454
+ # @return [Integer, nil]
455
+ def freshness_lifetime(response)
456
+ directives = {}
457
+ header_value(response, "Cache-Control").to_s.split(",").each do |token|
458
+ name, value = token.split("=", 2)
459
+ name = name.to_s.strip.downcase
460
+ directives[name] = value.to_s.strip.delete('"') unless name.empty? || directives.key?(name)
461
+ end
462
+ %w[s-maxage max-age].each do |name|
463
+ next unless directives.key?(name)
464
+
465
+ return directives[name].match?(/\A[0-9]+\z/) ? directives[name].to_i : 0
466
+ end
467
+ expires = header_value(response, "Expires")
468
+ return nil if expires.nil?
469
+
470
+ begin
471
+ [(Time.httpdate(expires.strip) - Time.now).to_i, 0].max
472
+ rescue ArgumentError
473
+ 0
474
+ end
475
+ end
476
+
433
477
  # Case-insensitive header lookup on a request or response.
434
478
  #
435
479
  # @param carrier [Object, nil]
data/lib/tina4/router.rb CHANGED
@@ -61,14 +61,29 @@ module Tina4
61
61
  self
62
62
  end
63
63
 
64
- # Opt out of the secure-by-default auth on write routes.
64
+ # Whether an anonymous caller is refused: the bearer gate (auth_required or
65
+ # a .role/.can guard, a 401) or a legacy per-route auth_handler (a 403). The
66
+ # dev-admin route list and the MCP route_list tool report this, so neither
67
+ # can call a route open that a gate refuses. Swagger applies the same flags.
68
+ def requires_auth?
69
+ auth_required == true || guarded? || !auth_handler.nil?
70
+ end
71
+
72
+ # Opt out of the secure-by-default auth on write routes. A .role/.can guard
73
+ # on the same route still applies and still needs a token, in either order.
65
74
  # Returns self for chaining: Router.post("/login") { ... }.no_auth
66
75
  def no_auth
67
- @auth_required = false
76
+ @auth_required = !@roles.empty? || !@perms.empty?
68
77
  @auth_write_methods = false
69
78
  self
70
79
  end
71
80
 
81
+ # True when the route carries a .role/.can guard: it needs a token whatever
82
+ # .no_auth / auth_required say, since the guard could never pass without one.
83
+ def guarded?
84
+ !@roles.empty? || !@perms.empty?
85
+ end
86
+
72
87
  # Whether a request with +http_method+ must carry a token on this route.
73
88
  def auth_required_for?(http_method)
74
89
  return true if @auth_required
data/lib/tina4/session.rb CHANGED
@@ -7,6 +7,7 @@
7
7
 
8
8
  require "securerandom"
9
9
  require "json"
10
+ require "digest"
10
11
 
11
12
  module Tina4
12
13
  class Session
@@ -63,9 +64,62 @@ module Tina4
63
64
  # module-level session_cookie_name() (tina4_python/session/__init__.py).
64
65
  #
65
66
  # TINA4_SESSION_NAME Cookie name (default: tina4_session)
67
+ #
68
+ # A value that is not an HTTP token (an "=", ";", space, line break or any
69
+ # other separator) could never be read back, so it is ignored: the error is
70
+ # logged once and "tina4_session" is used instead (ADR-0068's cookie rule).
71
+ COOKIE_NAME_PATTERN = /\A[!#$%&'*+\-.^_`|~0-9A-Za-z]+\z/
72
+ @logged_cookie_names = {}
73
+
66
74
  def self.cookie_name
67
75
  name = ENV["TINA4_SESSION_NAME"]
68
- name.nil? || name.empty? ? "tina4_session" : name
76
+ return "tina4_session" if name.nil? || name.empty?
77
+ return name if COOKIE_NAME_PATTERN.match?(name)
78
+
79
+ unless @logged_cookie_names.key?(name)
80
+ @logged_cookie_names[name] = true
81
+ Tina4::Log.error(
82
+ "Cookie name must be a valid HTTP token [#{JSON.generate(name, ascii_only: true)}]: " "TINA4_SESSION_NAME is ignored and the session cookie is named tina4_session"
83
+ )
84
+ end
85
+ "tina4_session"
86
+ end
87
+
88
+ DEFAULT_TTL = 3600
89
+
90
+ # Saves of one session id inside this process take one of these locks, so
91
+ # two requests (threads) that finish together merge one after the other
92
+ # instead of both merging into the same old record. Striped, so the set never
93
+ # grows with the number of sessions. Saves from different processes are not
94
+ # covered: see #save.
95
+ SAVE_LOCKS = Array.new(64) { Mutex.new }.freeze
96
+
97
+ @ttl_warned = {}
98
+
99
+ # The session lifetime in seconds, from TINA4_SESSION_TTL. The one reader of
100
+ # the setting, so the stored deadline and the cookie never disagree:
101
+ #
102
+ # * unset or blank: 3600;
103
+ # * a whole number of zero or more: that many seconds. 0 means the session
104
+ # never expires: the record keeps no deadline and the cookie carries no
105
+ # Max-Age, so the browser keeps it until it closes;
106
+ # * anything else (-1, abc, 1e3, 12.5): 3600, with one warning naming the
107
+ # setting. A negative lifetime handed the browser a cookie it deletes at
108
+ # once, and text failed every request.
109
+ def self.configured_ttl
110
+ raw = ENV["TINA4_SESSION_TTL"]
111
+ return DEFAULT_TTL if raw.nil? || raw.strip.empty?
112
+ return raw.strip.to_i if raw.strip.match?(/\A\d+\z/)
113
+
114
+ unless @ttl_warned[raw]
115
+ @ttl_warned[raw] = true
116
+ begin
117
+ Tina4::Log.warning("TINA4_SESSION_TTL=#{raw.inspect} is not a whole number of seconds (0 or more); using #{DEFAULT_TTL}")
118
+ rescue StandardError
119
+ warn("TINA4_SESSION_TTL=#{raw.inspect} is not a whole number of seconds (0 or more); using #{DEFAULT_TTL}")
120
+ end
121
+ end
122
+ DEFAULT_TTL
69
123
  end
70
124
 
71
125
  def initialize(env, options = {})
@@ -87,17 +141,14 @@ module Tina4
87
141
  # an explicit :max_age (an explicit option always wins). Keeps the cookie
88
142
  # honouring TINA4_SESSION_TTL now that rack_app routes the Set-Cookie
89
143
  # through #cookie_header instead of hand-writing it (issue #31).
90
- unless options.key?(:max_age)
91
- ttl_env = ENV["TINA4_SESSION_TTL"]
92
- @options[:max_age] = Integer(ttl_env) if ttl_env && !ttl_env.strip.empty?
93
- end
144
+ @options[:max_age] = self.class.configured_ttl unless options.key?(:max_age)
94
145
  # The BACKEND lifetime, resolved once and forwarded to handler#write on
95
146
  # every save (parity with Python's Session._ttl, which flows the same way).
96
147
  # #save used to call safe_write(@id, @data) with NO ttl, so the cookie said
97
148
  # Max-Age=900 while the stored record lived for the handler's own default -
98
149
  # a silent disagreement between what the browser was told and what the
99
150
  # store actually did. One resolver, both directions.
100
- @ttl = (options[:ttl] || ENV["TINA4_SESSION_TTL"] || 3600).to_i
151
+ @ttl = (options[:ttl] || self.class.configured_ttl).to_i
101
152
  # TINA4_SESSION_BACKEND — selects the storage handler unless the caller
102
153
  # explicitly passed :handler (same precedence as :cookie_name above; an
103
154
  # explicit option always wins over the environment). Without this the
@@ -216,9 +267,38 @@ module Tina4
216
267
  # deadline to move." A brand-new, unmodified session (minted id, @stored
217
268
  # false) therefore still no-ops, exactly as before; a modified session of
218
269
  # any kind still writes.
270
+ #
271
+ # Two requests of this session finishing together in this process take turns
272
+ # (SAVE_LOCKS), so each merges into the record the other just wrote and both
273
+ # changes are kept. Across processes the saves can still overlap: each writes
274
+ # a whole record (the file store renames a finished file into place), so the
275
+ # record is never left broken, but the later save can drop what the earlier
276
+ # one changed (last writer wins).
219
277
  def save
220
278
  return true if @id.nil? || fresh?
279
+ # The id came from the cookie through a failed read: the store has not
280
+ # confirmed it, so nothing is written under it (the modified flag is kept).
281
+ return false if @unconfirmed
282
+
283
+ SAVE_LOCKS[Digest::SHA256.hexdigest(@id)[0, 8].to_i(16) % SAVE_LOCKS.size].synchronize { save_merged }
284
+ end
285
+
286
+ # Whether the store holds this session: it was resumed, or a save has written
287
+ # it. Only such a session is given a cookie: a cookie for a session whose
288
+ # write failed would name nothing, and would replace the one the browser
289
+ # already holds.
290
+ # Whether the cookie's id was kept through a failed store read. Such a
291
+ # session is never written and never given a cookie (not even an expiring
292
+ # one) for the rest of the request.
293
+ def unconfirmed?
294
+ @unconfirmed == true
295
+ end
296
+
297
+ def stored?
298
+ !@id.nil? && @stored == true
299
+ end
221
300
 
301
+ private def save_merged
222
302
  record = @data
223
303
  if @stored
224
304
  current, failed = current_record
@@ -266,6 +346,14 @@ module Tina4
266
346
  def destroy
267
347
  safe_destroy(@id) if @id
268
348
  forget
349
+ @destroyed = true
350
+ end
351
+
352
+ # Whether #destroy ran in this request. Only then does the response tell the
353
+ # browser to drop the cookie; a session #save found ended by another request
354
+ # is forgotten with no cookie at all (ADR-0087).
355
+ def destroyed?
356
+ @destroyed == true
269
357
  end
270
358
 
271
359
  # Get a session value with optional default.
@@ -352,7 +440,10 @@ module Tina4
352
440
  end
353
441
  end
354
442
  @id = SecureRandom.hex(32)
355
- safe_destroy(old_id)
443
+ # An id kept through a failed read names a record this request never saw:
444
+ # it is left alone rather than destroyed with nothing carried.
445
+ safe_destroy(old_id) unless @unconfirmed
446
+ @unconfirmed = false
356
447
  @modified = true
357
448
  # Nothing is stored under the new id yet, so the save writes it whole.
358
449
  @stored = false
@@ -401,6 +492,11 @@ module Tina4
401
492
  end
402
493
 
403
494
  def cookie_header(cookie_name = nil)
495
+ max_age = @options[:max_age].to_i
496
+ build_cookie(cookie_name, @id, max_age.positive? ? max_age : nil)
497
+ end
498
+
499
+ private def build_cookie(cookie_name, value, max_age)
404
500
  name = cookie_name || @options[:cookie_name]
405
501
  samesite = ENV["TINA4_SESSION_SAMESITE"] || "Lax"
406
502
  # HttpOnly defaults to true (existing behaviour); flip off only when explicitly false.
@@ -408,20 +504,32 @@ module Tina4
408
504
  # Secure is set when ANY of the unified-contract conditions hold (parity
409
505
  # with tina4-php#175/#179): TINA4_SESSION_SECURE is truthy, OR SameSite is
410
506
  # None (browsers reject a None cookie without Secure per RFC 6265bis), OR
411
- # the request itself is https (proxy-aware, from @request_secure). A plain
412
- # HTTP request with the flag unset and SameSite != None stays non-Secure.
507
+ # the request itself is https (@request_secure: the connection's scheme, or
508
+ # X-Forwarded-Proto from a proxy listed in TINA4_TRUSTED_PROXIES). Behind a
509
+ # TLS proxy that is not listed, TINA4_SESSION_SECURE=true forces it on. A
510
+ # plain HTTP request with the flag unset and SameSite != None stays
511
+ # non-Secure.
413
512
  secure = %w[true 1 yes on].include?((ENV["TINA4_SESSION_SECURE"] || "false").to_s.strip.downcase) ||
414
513
  samesite.to_s.strip.casecmp("none").zero? ||
415
514
  @request_secure == true
416
515
 
417
- parts = ["#{name}=#{@id}", "Path=/"]
516
+ parts = ["#{name}=#{value}", "Path=/"]
418
517
  parts << "HttpOnly" if httponly
419
518
  parts << "Secure" if secure
420
519
  parts << "SameSite=#{samesite}"
421
- parts << "Max-Age=#{@options[:max_age]}"
520
+ # A lifetime of 0 never expires: no Max-Age, so the browser keeps the
521
+ # cookie until it closes. Max-Age=0 would delete it at once.
522
+ parts << "Max-Age=#{max_age}" unless max_age.nil?
422
523
  parts.join("; ")
423
524
  end
424
525
 
526
+ # A Set-Cookie value that tells the browser to drop the session cookie: an
527
+ # empty value with Max-Age=0 and the same attributes it was set with. Sent on
528
+ # the response of a request that ended the session its cookie named.
529
+ def clear_cookie_header(cookie_name = nil)
530
+ build_cookie(cookie_name, "", 0)
531
+ end
532
+
425
533
  private
426
534
 
427
535
  # The session id carried on the incoming cookie, or nil. A pure parser —
@@ -454,7 +562,13 @@ module Tina4
454
562
  # Sets @id/@data/@modified and returns the resolved id.
455
563
  def adopt_or_mint(session_id)
456
564
  session_id = nil unless self.class.valid_session_id?(session_id)
565
+ @read_failed = false
457
566
  data = session_id.nil? ? nil : existing_session_data(session_id)
567
+ # An id kept through a failed read is not confirmed by the store: nothing
568
+ # is written under it for the rest of this request and no cookie goes out.
569
+ # A save would otherwise store an id the client chose, or write a
570
+ # near-empty record over the user's real one.
571
+ @unconfirmed = @read_failed
458
572
  if data.nil?
459
573
  session_id = SecureRandom.hex(32)
460
574
  data = {}
@@ -464,9 +578,7 @@ module Tina4
464
578
  @modified = false
465
579
  # @stored: this request is working on a record the store holds, so a save
466
580
  # must never re-create it once it has gone. An empty record does not
467
- # count: it is no session. A failed read adopts the id with {}
468
- # (#existing_session_data): not a record this request has seen, so its
469
- # first save writes whole.
581
+ # count: it is no session.
470
582
  @stored = !data.empty?
471
583
  # @loaded: one fingerprint per key of what this request last saw stored;
472
584
  # #save compares the live data against it to find what THIS request
@@ -545,7 +657,8 @@ module Tina4
545
657
  # A backend FAILURE is deliberately NOT "no session": it logs and returns {},
546
658
  # so the id is still adopted. Reading an outage as "unknown" would rotate
547
659
  # every id and log the entire userbase out on a single Redis blip — the
548
- # opposite of the log-loud + degrade policy below.
660
+ # opposite of the log-loud + degrade policy below (ADR-0021 s6). The id is
661
+ # then unconfirmed (@unconfirmed, see #adopt_or_mint).
549
662
  def existing_session_data(session_id)
550
663
  return nil if degraded?
551
664
 
@@ -554,6 +667,7 @@ module Tina4
554
667
  rescue StandardError => e
555
668
  log_backend_error("read", e)
556
669
  raise if @strict
670
+ @read_failed = true
557
671
  {}
558
672
  end
559
673