tina4ruby 3.13.166 → 3.13.167

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d04d22eb673ab5a73c2d8768040ee336d6fa44de17487a562c8cb2505685ad72
4
- data.tar.gz: 8702a864280bf6a8e695551a5de3b4c3f211991c7a00e584e57bb00ce835fb25
3
+ metadata.gz: bf9cbd70decc616d093b7afdeee71b3e60be05767c7a1b9f1f886b636b1c7a6a
4
+ data.tar.gz: 360d7553e0ab7c70f2b2b76da81bcd0ad5b37b3194f9e0455a0b80757ac0de3f
5
5
  SHA512:
6
- metadata.gz: 2419a7e1eb7f052869ce8e89a6376b43b065abf27c9218c71904df2f8da7283df76978ccf542ef87d310fd8da6998bc3cd97d2e88200b4153a187d2124368bf7
7
- data.tar.gz: a5e07b3b8eaca98cc838b4ba514b482ea5c4bfea0be2babb9565f004ba8fcbed3e9c0bdc21c13e897b437daf5aba059bbc89d51cbc27d63f06e4467cde11d1e3
6
+ metadata.gz: 9083cf03a64c921103bb384c0148a6225737b6325f6cd9004c4c97f30e8c745c182897976ac2e701e5bbb70d68bf25523042b1fb8c8a5a09ce3205fc21657297
7
+ data.tar.gz: 1843fb88895bd6ada61cde4b4417e62a90790844cbf03124a8c895cc3bb2b3da328e9a841120ddbdc9b19c34ad1f05df3c43f54566ce32648af65c6063418f3e
data/CHANGELOG.md CHANGED
@@ -6,6 +6,25 @@ number means the same thing everywhere.
6
6
  **The authoritative release notes for every shipped version live in the documentation:**
7
7
  https://tina4.com/ruby/36-releases
8
8
 
9
+ ## 3.13.167 - 2026-11-30
10
+
11
+ ### Security
12
+
13
+ - `Tina4::API` refuses a header whose name is not an RFC 9110 token, or whose value contains CR, LF or NUL (GHSA-wjrr-pmm8-x4h8). A CR/LF in a header name injected extra request headers (Net::HTTP checks values only). A refused header returns the normal error result and sends nothing; `stream_*` raise `APIStreamError` (#194).
14
+ - `Tina4::API` no longer follows a redirect from https to http, or a 307/308 that would resend a request body to a different origin; the 3xx is returned to the caller (GHSA-9pmj-4fhx-wh27, low). Same-origin 307/308, 301/302/303 (non-GET still becomes GET) and bodiless cross-origin redirects behave as before (#194).
15
+ - CSRF form tokens fail closed on session binding. A token carrying a `session_id` is refused when the request's session id cannot be resolved, and a token with no `session_id` is refused on any request that carries a session; both used to pass. The id is read with `get_session_id`. Forms rendered with `form_token()` during a request are unaffected. **Upgrade:** hand-minted `Auth.get_token({"type" => "form"})` tokens must carry the session's id (#196).
16
+ - Routes match with `%2F` and `%25` kept encoded, and each parameter (HTTP and WebSocket) is decoded exactly once as UTF-8, whichever server runs the app; the same rule as tina4-php and tina4-python. The built-in server decoded the whole path before routing, so `/f/a%2Fb` could reach a two-segment route and `/caf%C3%A9` answered 500. Static files are looked up by the decoded path, with the traversal and dotfile checks on the decoded form, and the `/__dev_reload` upgrade gate tests the same decoded path (#197).
17
+ - The health endpoint (`/health`, `/__health`, `TINA4_HEALTH_PATH`) reports `version` only with `TINA4_DEBUG=true`; in production the body is `{"status", "uptime", "framework"}` (ADR-0078). Read the version from `Tina4::VERSION` instead. `GET /__frond/live/{name}` answers an unknown name with a `text/plain` 404 instead of reflecting the name as HTML (#198).
18
+
19
+ ### Fixed
20
+
21
+ - `Tina4::API#post`, `#put`, `#patch` and `#send_request` ignored an explicit `content_type:` because the client's default `Content-Type: application/json` header was applied afterwards. An explicit `content_type:` now wins; when omitted, a Content-Type configured in the client's headers applies, else `application/json` (#195).
22
+ - A route with a literal non-ASCII or space segment is reachable under Puma (`/caf%C3%A9` reaches `/café`), and a malformed escape in a parameter no longer answers 500 (#197).
23
+
24
+ ### Changed
25
+
26
+ - Under the built-in server, `request.path` / `PATH_INFO` is the raw path, as it already was under Puma (#197).
27
+
9
28
  ## 3.13.166 - 2026-11-24
10
29
 
11
30
  ### Security
data/lib/tina4/api.rb CHANGED
@@ -49,6 +49,17 @@ module Tina4
49
49
  API_KEEP_ON_CROSS_ORIGIN = %w[user-agent accept accept-encoding accept-language
50
50
  content-type content-length].freeze
51
51
 
52
+ # A header field name must be an RFC 9110 token. Net::HTTP writes a name
53
+ # verbatim, so a CR/LF in it would add a header line of the caller's choosing.
54
+ API_HEADER_NAME = /\A[!\#$%&'*+.^_`|~0-9A-Za-z-]+\z/
55
+
56
+ # CR and LF end a header line and NUL truncates it in many parsers: none may
57
+ # appear in a header value. Checked here rather than left to Net::HTTP.
58
+ API_HEADER_VALUE_FORBIDDEN = /[\r\n\0]/
59
+
60
+ # The redirects that keep the method and body on the next hop.
61
+ API_BODY_PRESERVING_REDIRECTS = [307, 308].freeze
62
+
52
63
  # A curated extension -> MIME map for guessing a multipart part's Content-Type
53
64
  # from its filename (Ruby core ships no mimetypes db, and pulling one in would
54
65
  # break the zero-dependency promise). tina4: a small built-in map covering the
@@ -150,44 +161,30 @@ module Tina4
150
161
  end
151
162
  end
152
163
 
164
+ # Every verb refuses a header that could split the header block (see
165
+ # check_header!) with the normal error result; nothing is sent.
153
166
  def get(path, params: {})
154
167
  uri = build_uri(path, params)
155
168
  request = Net::HTTP::Get.new(uri)
156
169
  apply_headers(request, {})
157
170
  execute(uri, request)
171
+ rescue APIHeaderError => e
172
+ error_response(e.message)
158
173
  end
159
174
 
160
- def post(path, body: nil, content_type: "application/json")
161
- uri = build_uri(path)
162
- request = Net::HTTP::Post.new(uri)
163
- if body
164
- request.body = body.is_a?(String) ? body : JSON.generate(body)
165
- request["Content-Type"] = content_type
166
- end
167
- apply_headers(request, {})
168
- execute(uri, request)
175
+ # POST/PUT/PATCH Content-Type precedence: an explicit `content_type:` wins;
176
+ # when omitted (nil) the Content-Type configured in the client's headers
177
+ # applies, and that is application/json unless the caller configured another.
178
+ def post(path, body: nil, content_type: nil)
179
+ send_with_body(Net::HTTP::Post, path, body, content_type)
169
180
  end
170
181
 
171
- def put(path, body: nil, content_type: "application/json")
172
- uri = build_uri(path)
173
- request = Net::HTTP::Put.new(uri)
174
- if body
175
- request.body = body.is_a?(String) ? body : JSON.generate(body)
176
- request["Content-Type"] = content_type
177
- end
178
- apply_headers(request, {})
179
- execute(uri, request)
182
+ def put(path, body: nil, content_type: nil)
183
+ send_with_body(Net::HTTP::Put, path, body, content_type)
180
184
  end
181
185
 
182
- def patch(path, body: nil, content_type: "application/json")
183
- uri = build_uri(path)
184
- request = Net::HTTP::Patch.new(uri)
185
- if body
186
- request.body = body.is_a?(String) ? body : JSON.generate(body)
187
- request["Content-Type"] = content_type
188
- end
189
- apply_headers(request, {})
190
- execute(uri, request)
186
+ def patch(path, body: nil, content_type: nil)
187
+ send_with_body(Net::HTTP::Patch, path, body, content_type)
191
188
  end
192
189
 
193
190
  def delete(path, body: nil)
@@ -196,6 +193,8 @@ module Tina4
196
193
  request.body = body.is_a?(String) ? body : JSON.generate(body) if body
197
194
  apply_headers(request, {})
198
195
  execute(uri, request)
196
+ rescue APIHeaderError => e
197
+ error_response(e.message)
199
198
  end
200
199
 
201
200
  # POST a multipart/form-data body — a file plus optional text fields.
@@ -246,16 +245,7 @@ module Tina4
246
245
  body = build_multipart_body(boundary, field_name, upload_name, content,
247
246
  part_content_type, extra_fields)
248
247
 
249
- uri = build_uri(path)
250
- request = Net::HTTP::Post.new(uri)
251
- request.body = body
252
- # Apply the client default headers (auth, etc.) FIRST, then force the
253
- # multipart Content-Type so it wins over the default application/json,
254
- # then any per-call headers last (parity with the Python master's order).
255
- apply_headers(request, {})
256
- request["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
257
- headers.each { |key, value| request[key] = value }
258
- execute(uri, request)
248
+ send_multipart(path, boundary, body, headers)
259
249
  end
260
250
 
261
251
  # Stream a GET response body to dest_path in chunks.
@@ -278,9 +268,10 @@ module Tina4
278
268
  headers["Cookie"] = cookie if @cookies_enabled && cookie
279
269
  headers = origin_headers(uri, headers)
280
270
 
281
- return download_via_transport(uri, headers, dest_path) if @transport
282
-
283
271
  begin
272
+ headers.each { |key, value| check_header!(key, value) }
273
+ return download_via_transport(uri, headers, dest_path) if @transport
274
+
284
275
  result = network_call("GET", uri, headers, nil, stream_to: dest_path)
285
276
  code = result[:status]
286
277
  if result[:path]
@@ -310,7 +301,7 @@ module Tina4
310
301
  self
311
302
  end
312
303
 
313
- def send_request(method = "GET", path = "", body: nil, content_type: "application/json")
304
+ def send_request(method = "GET", path = "", body: nil, content_type: nil)
314
305
  case method.upcase
315
306
  when "GET" then get(path)
316
307
  when "POST" then post(path, body: body, content_type: content_type)
@@ -473,20 +464,7 @@ module Tina4
473
464
  raise APIStreamError.new(e.message)
474
465
  end
475
466
 
476
- request = request_class.new(uri)
477
- apply_headers(request, headers || {})
478
- cookie = cookie_header
479
- request["Cookie"] = cookie if @cookies_enabled && cookie
480
- unless same_origin?(uri, URI.parse(@base_url))
481
- request.delete("Authorization")
482
- request.delete("Cookie")
483
- end
484
- if body
485
- request.body = body.is_a?(String) ? body : JSON.generate(body)
486
- request["Content-Type"] = content_type if content_type
487
- elsif content_type
488
- request["Content-Type"] = content_type
489
- end
467
+ request = build_stream_request(request_class, uri, headers, body, content_type)
490
468
 
491
469
  # ADR-0060: connect_timeout (else TINA4_API_CONNECT_TIMEOUT, else 10s)
492
470
  # bounds establishment and raises Net::OpenTimeout; timeout (else
@@ -529,6 +507,25 @@ module Tina4
529
507
  raise APIStreamTimeoutError, "stream exceeded its total timeout of #{total_bound}s"
530
508
  end
531
509
 
510
+ # The Net::HTTP request for one stream: client headers, per-call headers,
511
+ # the cookie jar and the body. A header that could split the header block
512
+ # raises APIStreamError, the stream's error contract, before any connect.
513
+ def build_stream_request(request_class, uri, headers, body, content_type)
514
+ request = request_class.new(uri)
515
+ apply_headers(request, headers || {})
516
+ cookie = cookie_header
517
+ request["Cookie"] = cookie if @cookies_enabled && cookie
518
+ unless same_origin?(uri, URI.parse(@base_url))
519
+ request.delete("Authorization")
520
+ request.delete("Cookie")
521
+ end
522
+ request.body = body.is_a?(String) ? body : JSON.generate(body) if body
523
+ set_header(request, "Content-Type", content_type) if content_type
524
+ request
525
+ rescue APIHeaderError => e
526
+ raise APIStreamError.new(e.message)
527
+ end
528
+
532
529
  # A positive number of seconds from an env var; anything else falls back.
533
530
  def stream_env_seconds(name, fallback)
534
531
  seconds = Float(ENV[name].to_s.strip, exception: false)
@@ -551,10 +548,56 @@ module Tina4
551
548
 
552
549
  def apply_headers(request, extra_headers)
553
550
  configured_headers(request.uri).merge(extra_headers).each do |key, value|
554
- request[key] = value
551
+ set_header(request, key, value)
555
552
  end
556
553
  end
557
554
 
555
+ # POST/PUT/PATCH: JSON-encode a non-String body, apply the client headers, then
556
+ # label it with an explicit content_type (which beats the configured one).
557
+ def send_with_body(request_class, path, body, content_type)
558
+ uri = build_uri(path)
559
+ request = request_class.new(uri)
560
+ request.body = body.is_a?(String) ? body : JSON.generate(body) if body
561
+ apply_headers(request, {})
562
+ set_header(request, "Content-Type", content_type) if body && content_type
563
+ execute(uri, request)
564
+ rescue APIHeaderError => e
565
+ error_response(e.message)
566
+ end
567
+
568
+ # Send an assembled multipart body. The client default headers (auth, etc.)
569
+ # go FIRST, then the multipart Content-Type so it wins over the default
570
+ # application/json, then any per-call headers last (parity with the Python
571
+ # master's order).
572
+ def send_multipart(path, boundary, body, headers)
573
+ uri = build_uri(path)
574
+ request = Net::HTTP::Post.new(uri)
575
+ request.body = body
576
+ apply_headers(request, {})
577
+ request["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
578
+ headers.each { |key, value| set_header(request, key, value) }
579
+ execute(uri, request)
580
+ rescue APIHeaderError => e
581
+ error_response(e.message)
582
+ end
583
+
584
+ # Set one header on a Net::HTTP request once check_header! accepts it.
585
+ def set_header(request, key, value)
586
+ check_header!(key, value)
587
+ request[key] = value
588
+ end
589
+
590
+ # Raise APIHeaderError unless the name is an RFC 9110 token and the value
591
+ # (each element, for an Array) holds no CR, LF or NUL. The value is never
592
+ # echoed: it may be a credential.
593
+ def check_header!(key, value)
594
+ name = key.to_s.b
595
+ raise APIHeaderError, "refused header: invalid name #{name.inspect}" unless name.match?(API_HEADER_NAME)
596
+ return unless Array(value).any? { |item| item.to_s.b.match?(API_HEADER_VALUE_FORBIDDEN) }
597
+
598
+ raise APIHeaderError, "refused header #{name}: CR, LF and NUL are not allowed in a value"
599
+ end
600
+
558
601
  # Headers configured on the client belong to its base origin, like the
559
602
  # token: a target on another origin gets only the cross-origin-safe ones. A
560
603
  # client with no base has no origin to bind them to, and sends them to the
@@ -644,17 +687,15 @@ module Tina4
644
687
  resp_headers = {}
645
688
  body_string = nil
646
689
  wrote_file = false
647
- location = nil
648
- redirect_code = nil
690
+ next_uri = nil
649
691
 
650
692
  http.start do |conn|
651
693
  conn.request(request) do |response|
652
694
  status = response.code.to_i
653
695
  resp_headers = response.to_hash
654
- if API_REDIRECT_STATUSES.include?(status) && remaining.positive? && response["location"]
696
+ if remaining.positive? &&
697
+ (next_uri = redirect_target(status, current_uri, response["location"], current_method, current_body))
655
698
  response.read_body { |_chunk| } # drain (and discard) the redirect body
656
- location = response["location"]
657
- redirect_code = status
658
699
  else
659
700
  store_cookies(response.get_fields("Set-Cookie"))
660
701
  if stream_to && (200..299).cover?(status)
@@ -684,16 +725,15 @@ module Tina4
684
725
  end
685
726
  end
686
727
 
687
- if location
688
- new_uri = URI.join(current_uri.to_s, location)
689
- current_headers = keep_cross_origin(current_headers) unless same_origin?(current_uri, new_uri)
728
+ if next_uri
729
+ current_headers = keep_cross_origin(current_headers) unless same_origin?(current_uri, next_uri)
690
730
  # 301/302/303 downgrade a non-GET/HEAD to GET and drop the body
691
731
  # (matches urllib); 307/308 preserve method + body.
692
- if [301, 302, 303].include?(redirect_code) && !%w[GET HEAD].include?(current_method)
732
+ if [301, 302, 303].include?(status) && !%w[GET HEAD].include?(current_method)
693
733
  current_method = "GET"
694
734
  current_body = nil
695
735
  end
696
- current_uri = new_uri
736
+ current_uri = next_uri
697
737
  remaining -= 1
698
738
  next
699
739
  end
@@ -716,12 +756,32 @@ module Tina4
716
756
  end
717
757
  request = klass.new(uri)
718
758
  headers.each do |key, value|
719
- request[key] = value.is_a?(Array) ? value.first : value
759
+ set_header(request, key, value.is_a?(Array) ? value.first : value)
720
760
  end
721
761
  request.body = body if body && !%w[GET HEAD].include?(method)
722
762
  request
723
763
  end
724
764
 
765
+ # The URI of the next hop, or nil when the response is not a redirect to
766
+ # follow and goes back to the caller as it is. Two hops are never followed:
767
+ # https -> http, which would send the request (and any credential the
768
+ # caller set for the target) in cleartext, and a 307/308 that would resend
769
+ # a request body to a different origin than the caller addressed.
770
+ def redirect_target(status, current_uri, location, method, body)
771
+ return nil unless API_REDIRECT_STATUSES.include?(status) && location
772
+
773
+ target = URI.join(current_uri.to_s, location)
774
+ return nil if current_uri.scheme.to_s.casecmp?("https") && target.scheme.to_s.casecmp?("http")
775
+ return target unless API_BODY_PRESERVING_REDIRECTS.include?(status) && sends_body?(method, body)
776
+
777
+ same_origin?(current_uri, target) ? target : nil
778
+ end
779
+
780
+ # True when a request with this method and body puts a body on the wire.
781
+ def sends_body?(method, body)
782
+ !body.nil? && !body.to_s.empty? && !%w[GET HEAD].include?(method)
783
+ end
784
+
725
785
  # Invoke a user-injected transport and normalize its result into an
726
786
  # APIResponse. The transport fully replaces the network call.
727
787
  def transport_response(method, url, headers, body)
@@ -891,6 +951,11 @@ module Tina4
891
951
  # AiClient treat APIStreamError as an HTTP status failure.
892
952
  class APIStreamTimeoutError < Timeout::Error; end
893
953
 
954
+ # A header name or value that could split the request's header block. The
955
+ # verbs turn it into their normal error result (status 0, nothing sent) and
956
+ # the stream_* calls into an APIStreamError; it never reaches a caller.
957
+ class APIHeaderError < ArgumentError; end
958
+
894
959
  class APIResponse
895
960
  attr_reader :status, :body, :headers, :error, :path
896
961
 
@@ -189,19 +189,24 @@ module Tina4
189
189
  # WebSocket upgrade - match against registered ws_routes.
190
190
  def websocket_upgrade(ctx)
191
191
  return nil unless websocket_upgrade?(ctx.env)
192
+
193
+ # The gates below test the path the ROUTER matches, never the path as
194
+ # sent: find_ws_route decodes "/__d%65v_reload" to the /__dev_reload
195
+ # route, so a prefix test on the encoded form would skip every gate.
196
+ path = Tina4::RoutePath.matchable(ctx.path)
192
197
  # The AI/test port never holds a live-reload socket: fall through to
193
198
  # dev_routes, which answers "Not available on AI port" (Python's built-in
194
199
  # server refuses the same upgrade with 404).
195
- return nil if ctx.path == "/__dev_reload" && ctx.env["tina4.ai_port"]
200
+ return nil if path == "/__dev_reload" && ctx.env["tina4.ai_port"]
196
201
 
197
202
  # ADR-0082: the dev reload socket answers only a loopback / TINA4_HOST
198
203
  # Host - the same rule the /__dev HTTP gate applies (DNS rebinding).
199
- if ctx.path.start_with?("/__dev") && !Tina4::DevAdmin.dev_host_allowed?(ctx.env)
204
+ if path.start_with?("/__dev") && !Tina4::DevAdmin.dev_host_allowed?(ctx.env)
200
205
  return [403, { "content-type" => "text/plain" }, ["Forbidden: host not allowed"]]
201
206
  end
202
207
  # ...and only from a raw socket peer the /__dev HTTP gate would let in, so
203
208
  # a remote caller that claims "Host: localhost" cannot open it.
204
- if ctx.path.start_with?("/__dev") && !Tina4::DevAdmin.dev_peer_allowed?((ctx.env["REMOTE_ADDR"] || "").to_s)
209
+ if path.start_with?("/__dev") && !Tina4::DevAdmin.dev_peer_allowed?((ctx.env["REMOTE_ADDR"] || "").to_s)
205
210
  return [403, { "content-type" => "text/plain" }, ["Forbidden: peer not allowed"]]
206
211
  end
207
212
 
data/lib/tina4/frond.rb CHANGED
@@ -3067,14 +3067,19 @@ module Tina4
3067
3067
  @@class_live_ws_paths[name]
3068
3068
  end
3069
3069
 
3070
+ # The content type of a /__frond/live 404, which echoes the requested name.
3071
+ LIVE_MISS_CONTENT_TYPE = "text/plain; charset=utf-8"
3072
+
3070
3073
  # Handle GET /__frond/live/{name}: resolve the provider, run it with the
3071
3074
  # live request (auth re-applies), re-render the fragment, return via the
3072
3075
  # response callable. 404 for unknown name / unrendered fragment. Mirrors
3073
3076
  # Python's live_endpoint and PHP's respondLive.
3074
3077
  def self.respond_live(request, response, name)
3075
3078
  provider = @@class_live_sources[name]
3079
+ # A 404 echoes the URL-decoded name, so it goes out as text/plain
3080
+ # (parity with Python/PHP); as text/html it reflected caller markup.
3076
3081
  if !@@class_live_fragments.key?(name) && provider.nil?
3077
- return response.call("live block not found: #{name}", 404)
3082
+ return response.call("live block not found: #{name}", 404, LIVE_MISS_CONTENT_TYPE)
3078
3083
  end
3079
3084
 
3080
3085
  context = {}
@@ -3084,7 +3089,7 @@ module Tina4
3084
3089
  end
3085
3090
 
3086
3091
  html = render_live(name, context)
3087
- return response.call("live fragment not registered yet: #{name}", 404) if html.nil?
3092
+ return response.call("live fragment not registered yet: #{name}", 404, LIVE_MISS_CONTENT_TYPE) if html.nil?
3088
3093
 
3089
3094
  response.call(html)
3090
3095
  end
data/lib/tina4/health.rb CHANGED
@@ -55,27 +55,23 @@ module Tina4
55
55
 
56
56
 
57
57
  def handle(_request, response)
58
- now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
59
- uptime = (now - START_TIME).round(2)
60
-
61
- payload = {
62
- status: "ok",
63
- version: Tina4::VERSION,
64
- uptime: uptime,
65
- framework: "tina4-ruby"
66
- }
67
-
68
- response.json(payload)
58
+ response.json(status)
69
59
  end
70
60
 
61
+ # tina4: ADR-0078 - the exact release version is a debug-only diagnostic.
62
+ # In production it only helps match the instance to known vulnerabilities;
63
+ # a liveness probe reads the status code, and the image publish gate reads
64
+ # Tina4::VERSION directly. Debug is the one dev-mode gate every other dev
65
+ # surface reads (ErrorOverlay.is_debug_mode), evaluated per request.
71
66
  def status
72
67
  now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
73
- {
68
+ body = {
74
69
  status: "ok",
75
- version: Tina4::VERSION,
76
70
  uptime: (now - START_TIME).round(2),
77
71
  framework: "tina4-ruby"
78
72
  }
73
+ body[:version] = Tina4::VERSION if Tina4::ErrorOverlay.is_debug_mode
74
+ body
79
75
  end
80
76
  end
81
77
  end
@@ -469,7 +469,12 @@ module Tina4
469
469
  def build_env(method, target, version, headers, body_bytes, listener, peer)
470
470
  target = absolute_form_path(target)
471
471
  raw_path, query = target.split("?", 2)
472
- path_info = normalize_path(percent_decode(raw_path.to_s))
472
+ # PATH_INFO stays percent-encoded, exactly as Puma hands it over (and
473
+ # as tina4-php's server and PHP-FPM do): the router decodes the path
474
+ # itself, keeping %2F and %25 encoded, and decodes each captured
475
+ # parameter once (Router.matchable_path). Decoding the whole path here
476
+ # let %2F split one parameter into two segments and decoded %2541 twice.
477
+ path_info = normalize_path(raw_path.to_s)
473
478
 
474
479
  env = {
475
480
  "REQUEST_METHOD" => method,
@@ -519,13 +524,11 @@ module Tina4
519
524
  path.start_with?("/") ? path : "/#{path}"
520
525
  end
521
526
 
522
- def percent_decode(path)
523
- path.b.gsub(/%\h\h/) { |escape| escape[1, 2].hex.chr }
524
- end
525
-
526
527
  # The same normalisation the previous built-in server (WEBrick) applied
527
528
  # before routing: collapse "//", resolve "." and ".." segments, and refuse a
528
- # path that climbs above the root or carries a NUL.
529
+ # path that climbs above the root or carries a NUL. It runs on the path as
530
+ # sent; an ENCODED dot segment (%2e%2e) is not resolved here, and the
531
+ # static-file lookup refuses it after decoding (RackApp#try_static).
529
532
  def normalize_path(path)
530
533
  raise RequestRefused.new(400, MALFORMED_HEAD) if path.include?("\0")
531
534
  return path if path == "*"
@@ -654,7 +654,10 @@ module Tina4
654
654
  # - Validates the token with Auth.valid_token using the resolved secret, and
655
655
  # enforces that the token's "type" claim is "form" -- a non-form JWT in the
656
656
  # formToken slot is rejected even when its signature verifies.
657
- # - If the token carries a session_id, it must match the request session's id.
657
+ # - Session binding, fail-closed both ways: a token that carries a
658
+ # session_id passes only when the request session's id resolves and is
659
+ # equal; a token with no session_id passes only when the request has no
660
+ # session at all (see .session_binding_holds?).
658
661
  # - Every rejection is HTTP 403 with the CSRF_INVALID envelope
659
662
  # ({error:true, code:"CSRF_INVALID", message:, status:403}) via
660
663
  # response.error -- byte-identical to Python/PHP/Node.
@@ -752,35 +755,52 @@ module Tina4
752
755
  return [request, response.error("CSRF_INVALID", "Invalid or missing form token", 403)]
753
756
  end
754
757
 
755
- # 12. Session binding -- a token minted for one session cannot be replayed
756
- # against another. Read the request session's OWN id: Tina4::Session
757
- # exposes get_session_id (NOT session_id -- reading session_id then
758
- # session.get("session_id") looked up a DATA key, never the id, so
759
- # binding silently never fired against a real session). A plain Hash
760
- # session exposes "session_id".
761
- token_session_id = payload["session_id"]
762
- if token_session_id
763
- session = request.respond_to?(:session) ? request.session : nil
764
- current_session_id =
765
- if session.nil?
766
- nil
767
- elsif session.respond_to?(:session_id)
768
- session.session_id
769
- elsif session.respond_to?(:get_session_id)
770
- session.get_session_id
771
- elsif session.is_a?(Hash)
772
- session["session_id"]
773
- end
774
-
775
- if current_session_id && token_session_id != current_session_id
776
- return [request, response.error("CSRF_INVALID", "Invalid or missing form token", 403)]
777
- end
758
+ # 12. Session binding -- a token is accepted only on the session it was
759
+ # minted for (see .session_binding_holds?).
760
+ unless session_binding_holds?(payload["session_id"], current_session_id(request))
761
+ return [request, response.error("CSRF_INVALID", "Invalid or missing form token", 403)]
778
762
  end
779
763
 
780
764
  # 13. All checks passed.
781
765
  [request, response]
782
766
  end
783
767
 
768
+ # The id of the session this request carries, or nil when it has none.
769
+ # Read through the session's OWN accessor, get_session_id (Tina4::Session
770
+ # and LazySession), never a data key: session.get("session_id") looks up
771
+ # stored data, which no framework code sets, so binding never fired. An
772
+ # ended session (destroyed, id cleared) has no id.
773
+ def current_session_id(request)
774
+ session = request.respond_to?(:session) ? request.session : nil
775
+ return nil unless session.respond_to?(:get_session_id)
776
+
777
+ sid = session.get_session_id.to_s
778
+ sid.empty? ? nil : sid
779
+ end
780
+
781
+ # Whether a form token's session_id claim fits the request's session id.
782
+ #
783
+ # A BOUND token (non-empty session_id) needs the request's id to resolve
784
+ # AND be equal: a missing or unloadable session must never switch the
785
+ # binding off.
786
+ #
787
+ # An UNBOUND token passes only when the request has no session at all.
788
+ # Frond binds every token it renders during a request to that request's
789
+ # session, and every dispatched request has one (a fresh session is kept
790
+ # by the _tina4_csrf marker, so a page rendered before the visitor had a
791
+ # session still posts back under the same id). An unbound token therefore
792
+ # comes only from a render outside a request or a hand-minted token, and
793
+ # accepting it on a request that has a session would let any visitor
794
+ # replay it against any other for its whole lifetime. With no session at
795
+ # all there is nothing to bind to, and Frond itself mints unbound tokens
796
+ # then, so the form keeps working.
797
+ def session_binding_holds?(token_session_id, current_id)
798
+ claim = token_session_id.to_s
799
+ return current_id.nil? if claim.empty?
800
+
801
+ !current_id.nil? && claim == current_id
802
+ end
803
+
784
804
  # Auto-attach CsrfMiddleware when TINA4_CSRF is enabled in the environment.
785
805
  #
786
806
  # CSRF is OFF by default: with TINA4_CSRF unset the middleware is never
@@ -233,7 +233,11 @@ module Tina4
233
233
  end
234
234
 
235
235
  def try_static(path, env = nil)
236
- return nil if path.include?("..")
236
+ # Files are looked up by the DECODED path (a file named "my file.txt" is
237
+ # requested as /my%20file.txt), and every check below runs on it, so an
238
+ # encoded "..", "/" or backslash is refused like a literal one.
239
+ path = static_lookup_path(path)
240
+ return nil if path.nil? || path.include?("..")
237
241
 
238
242
  # Security: never serve a dotfile (.env, .git/config, .htpasswd, ...).
239
243
  # Reject any leading-dot segment in the REQUEST path before touching the
@@ -296,6 +300,18 @@ module Tina4
296
300
 
297
301
  # Whether any separator-delimited segment of `path` is hidden (begins with a
298
302
  # dot). Refuses `.env`/`.git`; a `..` segment also begins with a dot.
303
+ # The request path percent-decoded for a filesystem lookup, or nil when it
304
+ # must not be looked up. "+" stays "+" (a literal plus in a path, never a
305
+ # space). A path that decodes to a control character (NUL, CR, LF, ...) or
306
+ # to invalid UTF-8 never names a servable file.
307
+ def static_lookup_path(path)
308
+ decoded = path.to_s.b.gsub(/%\h\h/) { |escape| escape[1, 2].hex.chr }.force_encoding(Encoding::UTF_8)
309
+ return nil unless decoded.valid_encoding?
310
+ return nil if decoded.match?(/[\x00-\x1F\x7F]/)
311
+
312
+ decoded
313
+ end
314
+
299
315
  def hidden_segment?(path)
300
316
  path.split(File::SEPARATOR).any? { |segment| !segment.empty? && segment.start_with?(".") }
301
317
  end
@@ -0,0 +1,64 @@
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
+ # The request path a route is matched against, and the decoding of the
11
+ # parameters it captures. Its own module so a path gate that runs BEFORE the
12
+ # router (the /__dev_reload upgrade gate) tests the same path the router
13
+ # matches. Same rule as tina4-php and tina4-python.
14
+ module RoutePath
15
+ # An escape that is decoded before matching: every %XX EXCEPT %2F (an
16
+ # encoded "/" must stay inside its segment, so /f/a%2Fb can never reach
17
+ # /f/{x}/{y}) and %25 (an encoded "%" must not start a new escape, so
18
+ # %252F stays the text "%2F", never a slash).
19
+ MATCH_DECODED_ESCAPE = /%(?!2[fF]|25)\h\h/
20
+ # Any percent-escape: how a captured parameter is decoded.
21
+ ANY_ESCAPE = /%\h\h/
22
+
23
+ module_function
24
+
25
+ # The path the router matches: backslashes read as "/", one leading "/",
26
+ # no trailing "/", then .matchable. Only a LITERAL backslash becomes a
27
+ # separator; an encoded one (%5C) is decoded after this and stays inside
28
+ # its segment.
29
+ def routing_path(path)
30
+ normalized = path.to_s.gsub("\\", "/")
31
+ normalized = "/#{normalized}" unless normalized.start_with?("/")
32
+ normalized == "/" ? normalized : matchable(normalized.chomp("/"))
33
+ end
34
+
35
+ # +path+ is the path as it arrived, still percent-encoded (Rack
36
+ # PATH_INFO). Every escape is decoded except %2F and %25, so a literal
37
+ # route reads naturally ("/caf%C3%A9" reaches "/café", "/two%20words"
38
+ # reaches "/two words") while an encoded slash never crosses a segment
39
+ # boundary. "+" is a literal plus, never a space. Each captured parameter
40
+ # is then decoded exactly once by .decode_param.
41
+ def matchable(path)
42
+ percent_decode(path, MATCH_DECODED_ESCAPE)
43
+ end
44
+
45
+ # Decode one captured path parameter, exactly once: every escape, "+"
46
+ # kept as "+", returned as UTF-8 text. Rack delivers PATH_INFO as
47
+ # ASCII-8BIT, and an ASCII-8BIT `{id}` binds to SQL as a BLOB, which
48
+ # SQLite gives no numeric affinity.
49
+ def decode_param(value)
50
+ return value unless value.is_a?(::String)
51
+
52
+ percent_decode(value, ANY_ESCAPE)
53
+ end
54
+
55
+ # Replace every +escape+ match in +text+ by the byte it encodes and read
56
+ # the bytes back as UTF-8, invalid sequences replaced (U+FFFD). Never
57
+ # raises: a malformed escape ("%A", "%zz") stays as written.
58
+ def percent_decode(text, escape)
59
+ bytes = text.to_s.b
60
+ bytes = bytes.gsub(escape) { |e| e[1, 2].hex.chr } if bytes.include?("%")
61
+ bytes.force_encoding(Encoding::UTF_8).scrub
62
+ end
63
+ end
64
+ end
data/lib/tina4/router.rb CHANGED
@@ -8,6 +8,7 @@
8
8
 
9
9
  require "fileutils"
10
10
  require "json"
11
+ require_relative "route_path"
11
12
 
12
13
  module Tina4
13
14
  class Route
@@ -158,14 +159,13 @@ module Tina4
158
159
  else
159
160
  params = {}
160
161
  @param_names.each_with_index do |param_def, i|
161
- raw_value = match[i + 1]
162
- # Rack delivers PATH_INFO (and therefore these captures) as
163
- # ASCII-8BIT. Relabel as UTF-8 so an untyped param binds to SQL as
164
- # TEXT, not a BLOB: SQLite gives a BLOB no numeric affinity, so a
165
- # `{id}` bound as ASCII-8BIT never matches an INTEGER column
166
- # (GET /users/{id} 404s a real row). No transcode — URL path bytes
167
- # are already UTF-8. Parity: Python/PHP/Node path params are text.
168
- raw_value = raw_value.dup.force_encoding(Encoding::UTF_8) if raw_value.is_a?(::String)
162
+ # Each capture is percent-decoded exactly once, here (the matched
163
+ # path kept %2F and %25 encoded - see RoutePath.matchable), and
164
+ # comes back as UTF-8 text. Rack delivers PATH_INFO as ASCII-8BIT, and
165
+ # an ASCII-8BIT `{id}` binds to SQL as a BLOB, which SQLite gives no
166
+ # numeric affinity (GET /users/{id} 404s a real row). Parity:
167
+ # Python/PHP/Node path params are text.
168
+ raw_value = RoutePath.decode_param(match[i + 1])
169
169
  params[param_def[:name]] = cast_param(raw_value, param_def[:type])
170
170
  end
171
171
  params
@@ -395,11 +395,8 @@ module Tina4
395
395
  else
396
396
  params = {}
397
397
  @param_names.each_with_index do |param_def, i|
398
- raw_value = match[i + 1]
399
- # Same ASCII-8BIT -> UTF-8 relabel as the HTTP Route matcher above,
400
- # so a WS path param binds to SQL as TEXT (not a BLOB).
401
- raw_value = raw_value.dup.force_encoding(Encoding::UTF_8) if raw_value.is_a?(::String)
402
- params[param_def[:name]] = raw_value
398
+ # Decoded once, as UTF-8 text - same as the HTTP Route matcher above.
399
+ params[param_def[:name]] = RoutePath.decode_param(match[i + 1])
403
400
  end
404
401
  params
405
402
  end
@@ -498,9 +495,7 @@ module Tina4
498
495
  # Find a matching WebSocket route for a given path.
499
496
  # Returns [ws_route, params] or nil.
500
497
  def find_ws_route(path)
501
- normalized = path.gsub("\\", "/")
502
- normalized = "/#{normalized}" unless normalized.start_with?("/")
503
- normalized = normalized.chomp("/") unless normalized == "/"
498
+ normalized = RoutePath.routing_path(path)
504
499
 
505
500
  ws_routes.each do |ws_route|
506
501
  params = ws_route.match?(normalized)
@@ -593,10 +588,8 @@ module Tina4
593
588
 
594
589
  def find_route(method, path)
595
590
  normalized_method = method.upcase
596
- # Normalize path once (not per-route)
597
- normalized_path = path.gsub("\\", "/")
598
- normalized_path = "/#{normalized_path}" unless normalized_path.start_with?("/")
599
- normalized_path = normalized_path.chomp("/") unless normalized_path == "/"
591
+ # Normalize and decode the path once (not per-route)
592
+ normalized_path = RoutePath.routing_path(path)
600
593
 
601
594
  # Candidates in REGISTRATION order, which is what Python, PHP and Node
602
595
  # all do. This used to be `ANY + method`, which made an ANY route beat
@@ -643,9 +636,7 @@ module Tina4
643
636
  # (HEAD auto-fallback). OPTIONS is appended whenever the path has any
644
637
  # registered method (the framework auto-handles OPTIONS).
645
638
  def methods_allowed_for_path(path)
646
- normalized_path = path.gsub("\\", "/")
647
- normalized_path = "/#{normalized_path}" unless normalized_path.start_with?("/")
648
- normalized_path = normalized_path.chomp("/") unless normalized_path == "/"
639
+ normalized_path = RoutePath.routing_path(path)
649
640
 
650
641
  method_order = %w[GET POST PUT PATCH DELETE HEAD OPTIONS]
651
642
  seen = []
data/lib/tina4/version.rb CHANGED
@@ -7,5 +7,5 @@
7
7
 
8
8
 
9
9
  module Tina4
10
- VERSION = "3.13.166"
10
+ VERSION = "3.13.167"
11
11
  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.166
4
+ version: 3.13.167
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-26 00:00:00.000000000 Z
11
+ date: 2026-11-30 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: sqlite3
@@ -331,6 +331,7 @@ files:
331
331
  - lib/tina4/request.rb
332
332
  - lib/tina4/response.rb
333
333
  - lib/tina4/response_cache.rb
334
+ - lib/tina4/route_path.rb
334
335
  - lib/tina4/router.rb
335
336
  - lib/tina4/row_symbolizer.rb
336
337
  - lib/tina4/secret_file.rb