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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0d6e19c42c25658a10f4c46db06e6ab07d5acc144278ae8fed9e51f8a8844321
4
- data.tar.gz: 36f3cccf40308a427df9cefdf607c75f75cd3e84f6fe2af4fa9ec22a71172cef
3
+ metadata.gz: 006dfd2bf4f2761543025845509184da359c10b6d38e7bcafcc1e98a35cace33
4
+ data.tar.gz: e36bcec7e88380baf29a2851ade5e1d416a6e5e9148a8f89d1ec7c70bc0529f6
5
5
  SHA512:
6
- metadata.gz: a5039b825b26654fe5e208667b6f82bb0f4e86a97d892d500aefb674c0797fe2b9056c6cc29875970197c8108bb372f6b2fbbc0d5e4337b72ee5cb781781ba79
7
- data.tar.gz: '09e8def1489bfd54ccfc697411caf49bed1c949ad7fb4037066651c47101e1543dd714d3c7b79c6114adb443392baed6780ccb53c4a5a8f399d144112c358267'
6
+ metadata.gz: 076aa3ee54d9f0f04e45292cb4ce3745870cc4f5ee47214cdf8a961c663267b439815876d358aeaedd74ca3f05c949462849ef0b4e1473569225dc880897ea77
7
+ data.tar.gz: 541cbe368833257ea4a9a2daf913dacbc20092867843ac3a8cb322e3dffe093acad422374e96d76e8d791d3edd23b6a97e71cb920f71b2ba51599a6af8d6f117
data/CHANGELOG.md CHANGED
@@ -6,6 +6,68 @@ 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.170 - 2026-12-05
10
+
11
+ ### Hardening and behaviour changes
12
+
13
+ - **The API key attaches no user.** `Authorization: Bearer <TINA4_API_KEY>` still opens a secured route, but `request.user` is now nil (it was `{"_auth" => "api_key"}`), and the key is accepted from the Bearer header only (it was also accepted as the body `formToken`). `.role()`/`.can()` routes still answer 403. The gate records the key in `env["tina4.auth_api_key"]` (#219).
14
+ - **`FreshToken` keeps the expiry it arrived with.** For a body `formToken` the gate returns the same token instead of re-signing it with a new full lifetime (#219).
15
+ - `valid_token` returns nil for a signed token whose payload is not a JSON object (the gate used to answer 500), and `validate_api_key` compares bytes (a value with the key's length in characters but not in bytes raised, and the gate answered 500) (#219).
16
+ - **Token time claims:** a claim that is not a finite number (such as `1e400`) is a 401, not a 500 (#223).
17
+ - **Password hashes:** `check_password` refuses a stored iteration count that is not a plain whole number from 1 to 5,000,000 (`1000x` was read as 1000), or an empty salt or hash, before any hashing; `hash_password` raises `ArgumentError` outside that range. The default stays 260000 (#219, #223).
18
+ - A route with `.role()`/`.can()` that is also `.no_auth` keeps its guard in either order (no token is 401, the wrong role is 403); it used to answer anonymous callers when `.no_auth` came after the guard. The route reports `auth_required` as true, and the Swagger document marks it as needing a token (#215).
19
+ - With `TINA4_CSRF` on, a Bearer value with whitespace around it no longer exempts a write from the form-token check. The scheme is read in any case through the new `Tina4::Auth.bearer_from_header` (#215, #219).
20
+ - **Proxy headers:** the CORS same-origin check honours `X-Forwarded-Host` only from a peer listed in `TINA4_TRUSTED_PROXIES`, as `X-Forwarded-Proto` already was (#218).
21
+ - **Sessions:** a failed store read keeps the cookie's id but marks it unconfirmed, so for the rest of that request nothing is written under that id and no cookie is sent (#218).
22
+ - **Sign-in:** the skill references now call `request.session.regenerate` at sign-in, so the id the browser had before signing in does not open the signed-in session. Do the same in your own sign-in routes (#222).
23
+ - **Rate limiter:** the global limiter runs before route matching and the auth gate, so 404s and failed sign-ins count (#217).
24
+ - **SSO:** introspection mode (the default) now checks the ID token's `iss`, `aud`/`azp`, `exp`, `iat`, `sub` and `nonce`, as `TINA4_SSO_VERIFY=jwks` does; its `sub` must match the introspected subject, and a refresh that returns an ID token is checked the same way. `iat` is required in both modes. A wrong `state` gets a 400 without cancelling the sign-in in progress (#216).
25
+ - **SSO settings have ceilings:** `TINA4_SSO_CLOCK_SKEW` at most 300 and `TINA4_SSO_JWKS_MAX_AGE` at most 86400, plain ASCII digits only; anything else fails configuration with an error naming the setting (#223).
26
+ - **`request.path` is the path the router matches:** percent-escapes decoded once, except `%2F` and `%25`. `request.raw_path` is the path as sent. Path-pattern middleware (`Tina4::Middleware.before(pattern)`) matches the decoded path too (#220).
27
+ - **Response cache:** an entry never outlives the response's own `s-maxage`/`max-age`/`Expires`, and a response that is stale on arrival is not stored (#220).
28
+
29
+ ### Fixes
30
+
31
+ - **Token lifetimes:** a lifetime of 0 now means the default lifetime (`TINA4_TOKEN_EXPIRES_IN`, then `TINA4_TOKEN_LIMIT`, then 60 minutes); it used to give a token that had already expired. A negative lifetime also uses the default, with one warning. `get_token` and `refresh_token` honour both settings (they were a fixed 60), and so do Frond form tokens (`abc` or `0` gave form tokens that had already expired) (#219).
32
+ - With `TINA4_CSRF` on, a write authenticated by `TINA4_API_KEY` is not asked for a form token (#215).
33
+ - The dev-admin route list and the MCP `route_list` report both auth gates (`Route#requires_auth?`) (#214).
34
+ - **Sign-out always works.** `POST /auth/logout` is public and ends the local session even after the provider's token lifetime has passed, or with no session. `post_logout_redirect_uri` defaults to the local path on the origin of `TINA4_SSO_REDIRECT_URI` (#216).
35
+ - **Session cookie:** it is re-sent on every response for a stored session and added to the route's own `Set-Cookie` headers instead of replacing them; `destroy()` sends an expired cookie (#218).
36
+ - **Concurrent session saves:** the file store writes to a temporary file and renames it into place, so a reader never sees a half-written record; saves of one session in one process take turns. Across processes the later save wins (documented in CLAUDE.md) (#218).
37
+ - A status set with `response.status(...)` is kept by `call`, `json`, `html`, `text`, `xml` and `render` called without a status (#220).
38
+ - `Tina4::API.new("")` sends its Authorization header, and per-call Authorization/Cookie headers, to the URL each call names. Jar cookies still need a base URL; a redirect to another origin still drops them (#220).
39
+ - A DNS or TLS failure while fetching SSO discovery counts as a failed fetch instead of escaping as `SocketError` (#223).
40
+ - The rate limiter sweeps idle addresses once a window (#217).
41
+
42
+ ### Windows
43
+
44
+ - **Port probes bind without listening,** on the server's own host, and on Windows a bind beside another listener (`0.0.0.0` next to `127.0.0.1`) no longer succeeds. This covers the web server, the HTTP server, WebSocket and `Tina4.find_available_port`. A listen port outside 0..65535 raises instead of wrapping (#221).
45
+ - **Port takeover:** the netstat lookup matches the exact local port (5123 also matched 51230-51239), and stopping the holder no longer fails on Windows (#221).
46
+ - **MQTT keepalive works on Windows:** PINGREQ was never sent, so pings timed out and the broker dropped the connection (#221).
47
+ - **WebSocket close no longer hangs on Windows** when the connection's reader is waiting for data, so a dev-admin disconnect is answered (#221).
48
+ - **Memgraph:** the Bolt handshake offers versions 4.4, 4.3, 4.1 and 4.0; Memgraph 2.21 refused the 4.4-only offer. This applies on every platform (#221).
49
+ - **Dev-admin runs git, the test runner and the dependency installer without a shell,** from argument lists with `chdir:`, so they work on Windows and request values are always passed as data (#221).
50
+ - The AI installer finds tools through the `PATHEXT`-aware lookup the CLI uses (#221).
51
+ - The full rspec suite runs on Windows against the lab services; in the repo's Gemfile, rdkafka and mysql2 move to optional `:kafka` and `:mysql` groups (no dependency added or removed) (#221).
52
+
53
+ ### Behaviour changes users will notice
54
+
55
+ - **Setting `TINA4_RATE_LIMIT` switches the limiter on** at `Tina4.initialize!`; before, nothing attached it at boot. A `TINA4_RATE_LIMIT` or `TINA4_RATE_WINDOW` that is not a positive whole number stops the boot with `Tina4::RateLimitConfigError` naming the setting. `false`, `0`, `no` or `off` switches it off (logged once). The policy is read once; health and readiness probes are never counted (#217).
56
+ - **SSO starts while the provider is unreachable.** One warning is logged and the app serves; the SSO routes answer `503 SSO_PROVIDER_UNAVAILABLE` and retry discovery at most once every 60 seconds (#223).
57
+ - **`TINA4_SESSION_TTL=0` never expires,** and the cookie lasts for the browser session (it went out with `Max-Age=0`); Redis/Valkey store such a record with `SET`. Negative, decimal and text values use 3600 with one warning (text used to fail every request) (#218).
58
+ - An invalid `TINA4_SESSION_NAME` (not an HTTP token) is replaced by `tina4_session` with one logged error (#222).
59
+ - A MongoDB session store with credentials (in `TINA4_SESSION_MONGO_URI` or the new `TINA4_SESSION_MONGO_USERNAME`/`TINA4_SESSION_MONGO_PASSWORD`) logs in through the `mongo` gem only; without it each operation fails with an error naming it (#222).
60
+ - A body `formToken` that fails verification is skipped, so a signed-in user posting a stale form is authenticated by the session (it was a 401) (#219).
61
+ - On a request the auth gate refuses, the app-wide after-hooks now run and the route's own do not (#220).
62
+
63
+ ### Upgrade notes
64
+
65
+ - Tokens: tina4-ruby never minted a token without `exp` (a lifetime of 0 or less gave one that had already expired), so no rotation is needed for tokens it minted. If `TINA4_SECRET` is shared with an app on another Tina4 framework that minted tokens with a lifetime of 0 or less, rotate it.
66
+ - Behind a TLS-terminating proxy, list it in `TINA4_TRUSTED_PROXIES` (or set `TINA4_SESSION_SECURE=true`). Only a listed proxy's `X-Forwarded-Proto`/`X-Forwarded-Host` counts for the session cookie's `Secure` flag, HSTS and the CORS same-origin check, and the rate limiter tells clients apart only through a listed proxy.
67
+ - A MongoDB session store with credentials needs the official driver: add the `mongo` gem.
68
+ - An invalid rate-limit setting now stops startup: check `TINA4_RATE_LIMIT` and `TINA4_RATE_WINDOW` before you deploy.
69
+ - Code that read `request.user["_auth"]` to detect the API key should check `env["tina4.auth_api_key"] == true`.
70
+
9
71
  ## 3.13.169 - 2026-12-02
10
72
 
11
73
  ### Breaking: behaviour that changed
data/lib/tina4/ai.rb CHANGED
@@ -10,6 +10,7 @@ require "fileutils"
10
10
  require "net/http"
11
11
  require "uri"
12
12
  require_relative "version" # the context files name Tina4::VERSION; `ai` runs before lib/tina4 loads
13
+ require_relative "executable_path" # PATH lookup that works on Windows (no `which`, no /dev/null)
13
14
 
14
15
  module Tina4
15
16
  # Tina4 AI -- Install AI coding assistant context files.
@@ -200,7 +201,7 @@ module Tina4
200
201
  end
201
202
 
202
203
  # tina4-ai tools option
203
- tina4_ai_installed = system("which mdview > /dev/null 2>&1")
204
+ tina4_ai_installed = !Tina4::ExecutablePath.find("mdview").nil?
204
205
  marker = tina4_ai_installed ? " #{green}[installed]#{reset}" : ""
205
206
  puts " 8. Install tina4-ai tools (requires Python)#{marker}"
206
207
  puts
@@ -469,7 +470,7 @@ module Tina4
469
470
  def install_tina4_ai
470
471
  puts " Installing tina4-ai tools..."
471
472
  %w[pip3 pip].each do |cmd|
472
- next unless system("which #{cmd} > /dev/null 2>&1")
473
+ next if Tina4::ExecutablePath.find(cmd).nil?
473
474
 
474
475
  result = `#{cmd} install --upgrade tina4-ai 2>&1`
475
476
  # Subprocess output is ASCII-8BIT — force UTF-8 with byte replacement
data/lib/tina4/api.rb CHANGED
@@ -265,7 +265,7 @@ module Tina4
265
265
  uri = build_uri(path, params)
266
266
  headers = configured_headers(uri).dup
267
267
  cookie = cookie_header
268
- headers["Cookie"] = cookie if @cookies_enabled && cookie
268
+ headers["Cookie"] = cookie if jar_cookie_allowed? && cookie
269
269
  headers = origin_headers(uri, headers)
270
270
 
271
271
  begin
@@ -514,8 +514,8 @@ module Tina4
514
514
  request = request_class.new(uri)
515
515
  apply_headers(request, headers || {})
516
516
  cookie = cookie_header
517
- request["Cookie"] = cookie if @cookies_enabled && cookie
518
- unless same_origin?(uri, URI.parse(@base_url))
517
+ request["Cookie"] = cookie if jar_cookie_allowed? && cookie
518
+ if off_base_origin?(uri)
519
519
  request.delete("Authorization")
520
520
  request.delete("Cookie")
521
521
  end
@@ -543,7 +543,21 @@ module Tina4
543
543
  end
544
544
 
545
545
  def origin_headers(uri, headers)
546
- same_origin?(uri, URI.parse(@base_url)) ? headers : strip_cross_origin(headers)
546
+ off_base_origin?(uri) ? strip_cross_origin(headers) : headers
547
+ end
548
+
549
+ # Only a client WITH a base URL has an origin to hold its credentials to.
550
+ # Without one, the URL each call names is the origin: the Authorization
551
+ # header goes to it, like every other configured header. A redirect to
552
+ # another origin still drops it.
553
+ def off_base_origin?(uri)
554
+ !@base_url.empty? && !same_origin?(uri, URI.parse(@base_url))
555
+ end
556
+
557
+ # The cookie jar belongs to the base origin, so a client without one never
558
+ # sends jar cookies.
559
+ def jar_cookie_allowed?
560
+ @cookies_enabled && !@base_url.empty?
547
561
  end
548
562
 
549
563
  def apply_headers(request, extra_headers)
@@ -636,7 +650,7 @@ module Tina4
636
650
  headers = {}
637
651
  request.each_header { |key, value| headers[key] = value }
638
652
  cookie = cookie_header
639
- headers["cookie"] = cookie if @cookies_enabled && cookie
653
+ headers["cookie"] = cookie if jar_cookie_allowed? && cookie
640
654
  headers = origin_headers(uri, headers)
641
655
  body = request.body
642
656
 
data/lib/tina4/auth.rb CHANGED
@@ -68,6 +68,12 @@ module Tina4
68
68
  # rejected for no real reason; RFC 7519 explicitly allows "a small leeway".
69
69
  JWT_LEEWAY_SECONDS = 60
70
70
 
71
+ # The largest PBKDF2 iteration count a stored password hash may carry, and
72
+ # that hash_password will write. 260000 is the default; the ceiling leaves
73
+ # room for a stronger setting while keeping one check to a few seconds, so
74
+ # a stored value can never make a sign-in run for minutes.
75
+ MAX_PASSWORD_ITERATIONS = 5_000_000
76
+
71
77
  # Token purposes that are never an identity (ADR-0079 s1). Frond's
72
78
  # form_token signs a JWT with the same TINA4_SECRET as an auth token, marked
73
79
  # "type" => "form". A form token proves where a write came from, never who
@@ -80,6 +86,10 @@ module Tina4
80
86
  # HMAC made with it.
81
87
  MIN_SECRET_BYTES = 32
82
88
 
89
+ # Token lifetime in MINUTES when a caller passes none and no setting is
90
+ # usable. See token_lifetime_minutes.
91
+ DEFAULT_TOKEN_LIFETIME_MINUTES = 60
92
+
83
93
  # The HMAC signing key is blank or shorter than MIN_SECRET_BYTES. An
84
94
  # ArgumentError, Ruby's equivalent of Python's ValueError.
85
95
  class InsecureSecretError < ArgumentError; end
@@ -102,6 +112,60 @@ module Tina4
102
112
  @public_key = nil
103
113
  end
104
114
 
115
+ # The default token lifetime in MINUTES: TINA4_TOKEN_EXPIRES_IN, else the
116
+ # older name TINA4_TOKEN_LIMIT, else 60. One rule for every helper that
117
+ # mints a token (get_token, refresh_token and Frond's form tokens). A
118
+ # setting that is not a positive whole number is reported once and the
119
+ # default is used, so a typo can never make every token dead on arrival.
120
+ def token_lifetime_minutes
121
+ %w[TINA4_TOKEN_EXPIRES_IN TINA4_TOKEN_LIMIT].each do |name|
122
+ raw = ENV[name]
123
+ next if raw.nil? || raw.strip.empty?
124
+
125
+ value = raw.strip
126
+ return value.to_i if value.match?(/\A\d+\z/) && value.to_i.positive?
127
+
128
+ @reported_bad_lifetimes ||= {}
129
+ unless @reported_bad_lifetimes["#{name}=#{raw}"]
130
+ @reported_bad_lifetimes["#{name}=#{raw}"] = true
131
+ log_warning("Auth: #{name}=#{raw.inspect} is not a positive whole number of minutes; " \
132
+ "tokens use the default lifetime of #{DEFAULT_TOKEN_LIFETIME_MINUTES} minutes.")
133
+ end
134
+ return DEFAULT_TOKEN_LIFETIME_MINUTES
135
+ end
136
+ DEFAULT_TOKEN_LIFETIME_MINUTES
137
+ end
138
+
139
+ # A requested lifetime in minutes, or the configured default: nil or 0
140
+ # means token_lifetime_minutes, and a negative lifetime falls back to it
141
+ # too (reported once), so a token is never minted already expired by
142
+ # accident.
143
+ def effective_lifetime(minutes)
144
+ return minutes if minutes.is_a?(Numeric) && minutes.positive?
145
+
146
+ if minutes.is_a?(Numeric) && minutes.negative?
147
+ @reported_bad_lifetimes ||= {}
148
+ unless @reported_bad_lifetimes["expires_in=#{minutes}"]
149
+ @reported_bad_lifetimes["expires_in=#{minutes}"] = true
150
+ log_warning("Auth: a token lifetime of #{minutes} minutes is not positive; " "the configured default lifetime is used instead.")
151
+ end
152
+ end
153
+ token_lifetime_minutes
154
+ end
155
+
156
+ # The token from an "Authorization: Bearer <token>" value, or nil. The
157
+ # scheme name is matched without regard to case (RFC 9110 s11.1) and
158
+ # blanks around the scheme and the token are ignored, so "bearer x",
159
+ # "BEARER x" and "Bearer x" all yield "x". Same helper as
160
+ # bearer_token_from_header (Python), Auth::bearerFromHeader (PHP) and
161
+ # bearerFromHeader (Node).
162
+ def bearer_from_header(value)
163
+ return nil unless value.is_a?(String)
164
+
165
+ match = value.match(/\A\s*bearer\s+(\S(?:.*\S)?)\s*\z/im)
166
+ match && match[1]
167
+ end
168
+
105
169
  # True when a VERIFIED payload may stand for a caller's identity. A payload
106
170
  # whose "type" is a reserved non-identity purpose (a Frond form token) is
107
171
  # refused; application payloads are otherwise untouched.
@@ -274,6 +338,18 @@ module Tina4
274
338
  return nil unless yield("#{parts[0]}.#{parts[1]}", base64url_decode(parts[2]))
275
339
 
276
340
  payload = Tina4.parse_json(base64url_decode(parts[1]))
341
+ claims_hold?(payload) ? payload : nil
342
+ rescue ArgumentError, JSON::ParserError, OpenSSL::OpenSSLError
343
+ nil
344
+ end
345
+
346
+ # True when a VERIFIED payload is a JSON object whose exp/nbf claims hold.
347
+ def claims_hold?(payload)
348
+ # Only a JSON object is a token payload. A list, string or number has no
349
+ # claims to check (and used to raise NoMethodError here, a 500 at the
350
+ # route gate).
351
+ return false unless payload.is_a?(Hash)
352
+
277
353
  now = Time.now.to_i
278
354
 
279
355
  # RFC 7519 s4.1.4: "The processing of the 'exp' claim requires that the
@@ -286,7 +362,7 @@ module Tina4
286
362
  # one that never expires.
287
363
  if payload.key?("exp")
288
364
  exp = numeric_date(payload["exp"])
289
- return nil if exp.nil? || now >= exp
365
+ return false if exp.nil? || now >= exp
290
366
  end
291
367
 
292
368
  # "nbf" (not-before): a post-dated token is not valid yet. Tolerate
@@ -295,12 +371,10 @@ module Tina4
295
371
  # exp; NO nbf key at all stays unconstrained (non-breaking).
296
372
  if payload.key?("nbf")
297
373
  nbf = numeric_date(payload["nbf"])
298
- return nil if nbf.nil? || now + JWT_LEEWAY_SECONDS < nbf
374
+ return false if nbf.nil? || now + JWT_LEEWAY_SECONDS < nbf
299
375
  end
300
376
 
301
- payload
302
- rescue ArgumentError, JSON::ParserError, OpenSSL::OpenSSLError
303
- nil
377
+ true
304
378
  end
305
379
 
306
380
  # Build a JWT with Ruby's OpenSSL::HMAC (no gem needed). The algorithm is the
@@ -371,7 +445,11 @@ module Tina4
371
445
  # deliberately post-dated tokens, which stays fully supported when the caller
372
446
  # passes its own "nbf" in the payload. Python/PHP/Node never auto-stamped it,
373
447
  # so Ruby doing so was the parity break.
374
- def get_token(payload, expires_in: 60, secret: nil, algorithm: nil)
448
+ # `expires_in:` is MINUTES; nil or 0 uses token_lifetime_minutes, and a
449
+ # negative lifetime falls back to it too (reported once). Every token
450
+ # carries exp.
451
+ def get_token(payload, expires_in: nil, secret: nil, algorithm: nil)
452
+ expires_in = effective_lifetime(expires_in)
375
453
  now = Time.now.to_i
376
454
  claims = payload.merge(
377
455
  "iat" => now,
@@ -413,6 +491,9 @@ module Tina4
413
491
  end
414
492
 
415
493
  def hash_password(password, salt = nil, iterations = 260000)
494
+ unless iterations.is_a?(Integer) && iterations.between?(1, MAX_PASSWORD_ITERATIONS)
495
+ raise ArgumentError, "iterations must be a whole number from 1 to #{MAX_PASSWORD_ITERATIONS}"
496
+ end
416
497
  salt ||= SecureRandom.hex(16)
417
498
  dk = OpenSSL::KDF.pbkdf2_hmac(password, salt: salt, iterations: iterations, length: 32, hash: "sha256")
418
499
  "pbkdf2_sha256$#{iterations}$#{salt}$#{dk.unpack1('H*')}"
@@ -421,6 +502,13 @@ module Tina4
421
502
  def check_password(password, hash)
422
503
  parts = hash.split('$')
423
504
  return false unless parts.length == 4 && parts[0] == 'pbkdf2_sha256'
505
+ # A stored value that is not a well-formed hash is refused: the iteration
506
+ # count must be plain digits and a whole number from 1 to
507
+ # MAX_PASSWORD_ITERATIONS ("1000x".to_i was 1000, and a stored count had no
508
+ # upper bound), checked before any hashing work.
509
+ return false unless parts[1].match?(/\A\d+\z/) && parts[1].to_i.between?(1, MAX_PASSWORD_ITERATIONS)
510
+ return false if parts[2].empty? || parts[3].empty?
511
+
424
512
  iterations = parts[1].to_i
425
513
  salt = parts[2]
426
514
  expected = parts[3]
@@ -449,7 +537,7 @@ module Tina4
449
537
  # is PRESERVED — matching the Python master, and keeping the promise made
450
538
  # when auto-nbf was removed: a deliberately post-dated claim is the issuer's,
451
539
  # and a refresh must not quietly erase it.
452
- def refresh_token(token, expires_in: 60)
540
+ def refresh_token(token, expires_in: nil)
453
541
  return nil unless valid_token(token)
454
542
 
455
543
  payload = get_payload(token)
@@ -502,7 +590,13 @@ module Tina4
502
590
  expected ||= ENV["TINA4_API_KEY"]
503
591
  return false if expected.nil? || expected.empty?
504
592
  return false if provided.nil? || provided.empty?
505
- return false if provided.length != expected.length
593
+
594
+ # Compare BYTES. A character-length check let "AAAé" through to
595
+ # fixed_length_secure_compare against "AAAA" (same length in characters,
596
+ # not in bytes), which raised - a 500 at the route gate.
597
+ provided = provided.to_s.b
598
+ expected = expected.to_s.b
599
+ return false if provided.bytesize != expected.bytesize
506
600
 
507
601
  OpenSSL.fixed_length_secure_compare(provided, expected)
508
602
  end
@@ -586,8 +680,10 @@ module Tina4
586
680
  # _numeric_date; Ruby needs no bool special-case because TrueClass is not
587
681
  # an Integer (in Python bool IS an int subclass, so exp: true would compare
588
682
  # as 1970).
683
+ # A Float that is not finite (a JSON 1e400 reads as Infinity) is not a date
684
+ # either: Infinity.to_i raised FloatDomainError and the gate answered 500.
589
685
  def numeric_date(value)
590
- return nil unless value.is_a?(Integer) || value.is_a?(Float)
686
+ return nil unless value.is_a?(Integer) || (value.is_a?(Float) && value.finite?)
591
687
 
592
688
  value.to_i
593
689
  end
data/lib/tina4/cli.rb CHANGED
@@ -17,6 +17,7 @@ require "open3" # Open3.capture2e — captures `ruby -c` output+status for `
17
17
  require_relative "port_takeover"
18
18
  require_relative "batch_spawn" # Tina4::BatchSpawn - runs a tina4.cmd client with its arguments intact
19
19
  require_relative "env" # Tina4::Env.is_truthy -- resolve_config runs before lib/tina4 loads
20
+ require_relative "executable_path" # Tina4::ExecutablePath.find - PATH lookup, PATHEXT-aware
20
21
 
21
22
  module Tina4
22
23
  class CLI
@@ -1562,15 +1563,7 @@ module Tina4
1562
1563
  # Locate an executable on PATH — the stdlib-only equivalent of Python's
1563
1564
  # shutil.which (no new gem). Honours PATHEXT on Windows.
1564
1565
  def which_executable(cmd)
1565
- exts = ENV["PATHEXT"] ? ENV["PATHEXT"].split(File::PATH_SEPARATOR) : [""]
1566
- ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).each do |dir|
1567
- next if dir.empty?
1568
- exts.each do |ext|
1569
- candidate = File.join(dir, "#{cmd}#{ext}")
1570
- return candidate if File.executable?(candidate) && !File.directory?(candidate)
1571
- end
1572
- end
1573
- nil
1566
+ Tina4::ExecutablePath.find(cmd)
1574
1567
  end
1575
1568
 
1576
1569
  # ── version ───────────────────────────────────────────────────────────
data/lib/tina4/cors.rb CHANGED
@@ -171,14 +171,16 @@ module Tina4
171
171
  # Whether the request's Origin is the request's OWN origin
172
172
  # (tina4-python #139). Own origin = scheme://host[:port], the scheme
173
173
  # proxy-aware (Request.secure_scheme?, X-Forwarded-Proto first hop) and
174
- # the host from X-Forwarded-Host, else Host. Both sides are normalised:
174
+ # the host from X-Forwarded-Host, else Host. Both forwarded headers count
175
+ # only from a proxy listed in TINA4_TRUSTED_PROXIES. Both sides are normalised:
175
176
  # lower-cased, default ports (http:80, https:443) dropped.
176
177
  def same_origin?(env)
177
178
  origin = normalize_origin(env["HTTP_ORIGIN"])
178
179
  return false if origin.nil?
179
180
 
180
181
  scheme = Tina4::Request.secure_scheme?(env) ? "https" : "http"
181
- host = (env["HTTP_X_FORWARDED_HOST"] || env["HTTP_HOST"]).to_s.split(",").first.to_s.strip
182
+ forwarded_host = Tina4.trusted_proxy?(env["REMOTE_ADDR"].to_s) ? env["HTTP_X_FORWARDED_HOST"] : nil
183
+ host = (forwarded_host || env["HTTP_HOST"]).to_s.split(",").first.to_s.strip
182
184
  return false if host.empty?
183
185
 
184
186
  origin == normalize_origin("#{scheme}://#{host}")
@@ -19,6 +19,7 @@ require "open3" # scaffold_run shells to exe/tina4ruby generate <kind> <name>
19
19
  require_relative "metrics"
20
20
  require_relative "parse_json"
21
21
  require_relative "secret_file"
22
+ require_relative "executable_path" # Tina4::ExecutablePath.find - is bundler on PATH
22
23
 
23
24
  module Tina4
24
25
  # Thread-safe in-memory message log for dev dashboard
@@ -1003,8 +1004,10 @@ module Tina4
1003
1004
  path: route.path,
1004
1005
  middleware: route.respond_to?(:middleware_count) ? route.middleware_count : 0,
1005
1006
  cache: route.respond_to?(:cached?) ? route.cached? : false,
1006
- secure: !route.auth_handler.nil?,
1007
- auth_required: !route.auth_handler.nil?,
1007
+ # What the gates enforce (Route#requires_auth?). Read auth_handler
1008
+ # only, so every plain write route showed as open.
1009
+ secure: route.requires_auth?,
1010
+ auth_required: route.requires_auth?,
1008
1011
  handler: handler_name,
1009
1012
  module: mod
1010
1013
  }
@@ -1132,14 +1135,15 @@ module Tina4
1132
1135
  # `bundle exec rspec` when a Gemfile + bundler are present.
1133
1136
  def run_tests_payload
1134
1137
  root = Dir.pwd
1135
- runner = if File.exist?(File.join(root, "Gemfile")) &&
1136
- system("command -v bundle > /dev/null 2>&1")
1137
- "bundle exec rspec --no-color"
1138
+ runner = if File.exist?(File.join(root, "Gemfile")) && Tina4::ExecutablePath.find("bundle")
1139
+ %w[bundle exec rspec --no-color]
1138
1140
  else
1139
- "rspec --no-color"
1141
+ %w[rspec --no-color]
1140
1142
  end
1141
- output = `cd #{Shellwords.escape(root)} && #{runner} 2>&1`
1142
- code = $?.exitstatus.to_i
1143
+ # An argument vector run through `ruby -S`, never a shell string: see
1144
+ # git_output for why a backtick string fails on Windows.
1145
+ output, status = Open3.capture2e(RbConfig.ruby, "-S", *runner, chdir: root)
1146
+ code = status.exitstatus.to_i
1143
1147
  { ok: code.zero?, code: code, output: output.strip }
1144
1148
  rescue => e
1145
1149
  { ok: false, code: -1, output: e.message }
@@ -1794,17 +1798,15 @@ module Tina4
1794
1798
  # forward-slash); the project root may sit inside a larger repo, so the
1795
1799
  # toplevel is returned too for rebasing. Empty on any error / no git.
1796
1800
  def dev_git_info(root)
1797
- require "shellwords" unless defined?(Shellwords)
1798
- esc = Shellwords.escape(root)
1799
- inside = `cd #{esc} && git rev-parse --is-inside-work-tree 2>/dev/null`.strip
1801
+ inside = git_output(root, "rev-parse", "--is-inside-work-tree").strip
1800
1802
  return { branch: "", git_root: nil, status: {} } unless inside == "true"
1801
1803
 
1802
- branch = `cd #{esc} && git rev-parse --abbrev-ref HEAD 2>/dev/null`.strip
1803
- top = `cd #{esc} && git rev-parse --show-toplevel 2>/dev/null`.strip
1804
+ branch = git_output(root, "rev-parse", "--abbrev-ref", "HEAD").strip
1805
+ top = git_output(root, "rev-parse", "--show-toplevel").strip
1804
1806
  git_root = top.empty? ? nil : top.tr("\\", "/").sub(%r{/+\z}, "")
1805
1807
 
1806
1808
  status = {}
1807
- `cd #{esc} && git status --porcelain -uall 2>/dev/null`.each_line do |line|
1809
+ git_output(root, "status", "--porcelain", "-uall").each_line do |line|
1808
1810
  line = line.chomp
1809
1811
  next if line.length < 4
1810
1812
  code = line[0, 2].strip
@@ -2057,12 +2059,15 @@ module Tina4
2057
2059
  # Prefer `bundle add` — it updates the Gemfile AND installs the gem, so a
2058
2060
  # dev dep is deployed (not just recorded). Fall back to appending to the
2059
2061
  # Gemfile when bundler isn't available.
2060
- if system("command -v bundle > /dev/null 2>&1")
2062
+ if Tina4::ExecutablePath.find("bundle")
2061
2063
  cmd = ["bundle", "add", name]
2062
2064
  cmd += ["--version", version] unless version.empty?
2063
2065
  cmd += ["--group", "development"] if dev
2064
- out = `#{cmd.map { |c| Shellwords.escape(c) }.join(' ')} 2>&1`
2065
- return { ok: true, gem: name, output: out.strip } if $?.success?
2066
+ # Argument vector through `ruby -S bundle` (never bundle.bat, never a
2067
+ # shell string): the name and version reach bundler as data on every
2068
+ # platform, cmd.exe never re-parses them.
2069
+ out, status = Open3.capture2e(RbConfig.ruby, "-S", *cmd, chdir: Dir.pwd)
2070
+ return { ok: true, gem: name, output: out.strip } if status.success?
2066
2071
  return { ok: false, error: out.strip }
2067
2072
  end
2068
2073
 
@@ -2075,13 +2080,26 @@ module Tina4
2075
2080
  { ok: true, gem: name, note: "added to Gemfile; run `bundle install`" }
2076
2081
  end
2077
2082
 
2083
+ # stdout of `git <args>` run IN *dir*; "" when git fails or is absent.
2084
+ # An argument vector with chdir:, never a shell string: a Ruby backtick
2085
+ # runs cmd.exe on Windows, which has no /dev/null (so `2>/dev/null` made
2086
+ # every one of these calls fail there) and does not honour the POSIX
2087
+ # quoting Shellwords produces.
2088
+ def git_output(dir, *args)
2089
+ out, _err, status = Open3.capture3("git", *args, chdir: dir)
2090
+ status.success? ? out : ""
2091
+ rescue SystemCallError
2092
+ ""
2093
+ end
2094
+
2078
2095
  def git_status_payload
2079
2096
  begin
2080
- inside = `cd #{Shellwords.escape(Dir.pwd)} && git rev-parse --is-inside-work-tree 2>/dev/null`.strip
2097
+ root = Dir.pwd
2098
+ inside = git_output(root, "rev-parse", "--is-inside-work-tree").strip
2081
2099
  return { error: "Not a git repository" } if inside != "true"
2082
- branch = `cd #{Shellwords.escape(Dir.pwd)} && git branch --show-current 2>/dev/null`.strip
2083
- status = `cd #{Shellwords.escape(Dir.pwd)} && git status --porcelain 2>/dev/null`.strip.split("\n").reject(&:empty?)
2084
- recent = `cd #{Shellwords.escape(Dir.pwd)} && git log --oneline -5 2>/dev/null`.strip.split("\n").reject(&:empty?)
2100
+ branch = git_output(root, "branch", "--show-current").strip
2101
+ status = git_output(root, "status", "--porcelain").strip.split("\n").reject(&:empty?)
2102
+ recent = git_output(root, "log", "--oneline", "-5").strip.split("\n").reject(&:empty?)
2085
2103
  { branch: branch, status: status, recent_commits: recent }
2086
2104
  rescue => e
2087
2105
  { error: "git unavailable: #{e.message}" }
@@ -656,41 +656,70 @@ module Tina4
656
656
  end
657
657
  end
658
658
 
659
- # Read the INCOMING session cookie by the SAME configured name the write
660
- # side emits - via the one shared resolver (Session.cookie_name), exact
661
- # `name=` prefix. A hardcoded "tina4_session=" here never matches a cookie
662
- # renamed through TINA4_SESSION_NAME, so the auto-Set-Cookie would be
663
- # needlessly re-emitted on every request that already carries the renamed
664
- # cookie. Parity with Python's core/server._init_session cookie_prefix.
665
- cookie_prefix = "#{Tina4::Session.cookie_name}="
666
- cookie_val = (ctx.env["HTTP_COOKIE"] || "").split(";").map(&:strip)
667
- .find { |part| part.start_with?(cookie_prefix) }
668
- &.slice(cookie_prefix.length..)
669
- if session_needs_cookie?(sess, cookie_val)
670
- # Route through Session#cookie_header rather than hand-writing the
671
- # header, so TINA4_SESSION_SECURE / _SAMESITE / _HTTPONLY / _NAME / _TTL
672
- # are all honoured and Secure reflects the request scheme. The old
673
- # hand-written literal ignored every attribute except TTL and hardcoded
674
- # SameSite=Lax + HttpOnly, making the security env vars silent no-ops
675
- # (issue #31).
676
- headers["set-cookie"] = sess.cookie_header
677
- end
659
+ # Added to the route's own cookies, never in place of them.
660
+ line = session_cookie_line(sess, incoming_session_cookie(ctx.env))
661
+ add_set_cookie(headers, line) if line
678
662
  [status, headers, body_parts]
679
663
  end
680
664
 
681
- # Whether the response must carry a session cookie: the session has an id the
682
- # request did not already send, and it is not a fresh one. A fresh session
683
- # (minted for this request and never written: a route that only read it, or
684
- # the replacement for a cookie the store does not know) was not stored, so a
685
- # cookie for it would name nothing - the next request could not resume it and
686
- # would be handed another one.
687
- def session_needs_cookie?(sess, cookie_val)
688
- sid = sess.id
689
- return false unless sid && sid != cookie_val
665
+ # The INCOMING session cookie, read by the SAME configured name the write
666
+ # side emits - via the one shared resolver (Session.cookie_name), exact
667
+ # `name=` prefix, so a cookie renamed through TINA4_SESSION_NAME is found.
668
+ # Parity with Python's core/server._init_session cookie_prefix.
669
+ def incoming_session_cookie(env)
670
+ cookie_prefix = "#{Tina4::Session.cookie_name}="
671
+ (env["HTTP_COOKIE"] || "").split(";").map(&:strip)
672
+ .find { |part| part.start_with?(cookie_prefix) }
673
+ &.slice(cookie_prefix.length..)
674
+ end
675
+
676
+ # The Set-Cookie line this response owes for the session, or nil. Built by
677
+ # Session#cookie_header rather than by hand, so TINA4_SESSION_SECURE /
678
+ # _SAMESITE / _HTTPONLY / _NAME / _TTL are all honoured and Secure reflects
679
+ # the request scheme (issue #31). A request that called #destroy on the
680
+ # session its cookie named gets an expired cookie, so the browser stops
681
+ # presenting the dead id.
682
+ def session_cookie_line(sess, cookie_val)
683
+ return sess.cookie_header if session_needs_cookie?(sess)
684
+ # A session kept through a failed store read gets no cookie at all, not
685
+ # even an expiring one (ADR-0021 s6).
686
+ return nil if sess.respond_to?(:unconfirmed?) && sess.unconfirmed?
687
+ # Only after #destroy: a session #save found ended by another request is
688
+ # forgotten with no cookie (ADR-0087).
689
+ return nil unless sess.respond_to?(:destroyed?) && sess.destroyed?
690
+ return nil unless sess.id.nil? && cookie_val && !cookie_val.empty?
691
+
692
+ sess.clear_cookie_header
693
+ end
694
+
695
+ # Whether the response must carry the session cookie: every response for a
696
+ # session the store holds does, the same id included. The save just moved
697
+ # the stored deadline forward and the cookie's Max-Age has to move with it;
698
+ # sent only when the id changed, the browser dropped the cookie one
699
+ # TINA4_SESSION_TTL after the first visit while the server still held the
700
+ # session. A session the store does not hold (minted for this request and
701
+ # never written, or one whose write failed during an outage) gets none: a
702
+ # cookie for it would name nothing and would replace the one the browser
703
+ # holds.
704
+ def session_needs_cookie?(sess)
705
+ return false unless sess.id
706
+ return sess.stored? if sess.respond_to?(:stored?)
690
707
 
691
708
  !(sess.respond_to?(:fresh?) && sess.fresh?)
692
709
  end
693
710
 
711
+ # Add one Set-Cookie line to a Rack header hash that may already carry the
712
+ # route's own cookies (newline-joined, or an Array under Rack 3).
713
+ def add_set_cookie(headers, line)
714
+ existing = headers["set-cookie"]
715
+ headers["set-cookie"] =
716
+ case existing
717
+ when nil, "" then line
718
+ when Array then existing + [line]
719
+ else "#{existing}\n#{line}"
720
+ end
721
+ end
722
+
694
723
  # Milliseconds since the request entered the pipeline.
695
724
  def elapsed_ms(ctx)
696
725
  ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - ctx.started_at) * 1000).round(3)
@@ -748,6 +777,12 @@ module Tina4
748
777
  unauthorized = self.class.enforce_route_auth(ctx.env, ctx.route)
749
778
 
750
779
  if unauthorized
780
+ # The global before-hooks ran, so their after-hooks run too, on the
781
+ # refused status; the route's own middleware was never entered, so none
782
+ # of its after-hooks run.
783
+ ctx.response.status(unauthorized[0]) if ctx.response.respond_to?(:status)
784
+ Tina4::Middleware.run_after(Tina4::Middleware.global_middleware, ctx.request, ctx.response)
785
+
751
786
  # Carry the middleware headers onto the 401. This is the case the
752
787
  # pre/post split exists for: a browser shown a 401 with no CORS headers
753
788
  # reports a CORS error, so the real status never reaches the developer.