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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +62 -0
- data/lib/tina4/ai.rb +3 -2
- data/lib/tina4/api.rb +19 -5
- data/lib/tina4/auth.rb +105 -9
- data/lib/tina4/cli.rb +2 -9
- data/lib/tina4/cors.rb +4 -2
- data/lib/tina4/dev_admin.rb +39 -21
- data/lib/tina4/dispatch_pipeline.rb +63 -28
- data/lib/tina4/drivers/bolt_graph_driver.rb +6 -4
- data/lib/tina4/executable_path.rb +29 -0
- data/lib/tina4/frond.rb +4 -3
- data/lib/tina4/http_server.rb +5 -0
- data/lib/tina4/mcp.rb +3 -1
- data/lib/tina4/middleware.rb +87 -53
- data/lib/tina4/mqtt.rb +4 -1
- data/lib/tina4/port_probe.rb +88 -0
- data/lib/tina4/port_takeover.rb +34 -15
- data/lib/tina4/rack_app.rb +36 -10
- data/lib/tina4/rate_limit_policy.rb +101 -0
- data/lib/tina4/rate_limiter.rb +55 -31
- data/lib/tina4/request.rb +12 -3
- data/lib/tina4/response.rb +13 -9
- data/lib/tina4/response_cache.rb +44 -0
- data/lib/tina4/router.rb +17 -2
- data/lib/tina4/session.rb +129 -15
- data/lib/tina4/session_handlers/database_handler.rb +1 -1
- data/lib/tina4/session_handlers/file_handler.rb +40 -6
- data/lib/tina4/session_handlers/memcached_handler.rb +1 -1
- data/lib/tina4/session_handlers/mongo_handler.rb +37 -3
- data/lib/tina4/session_handlers/redis_handler.rb +1 -1
- data/lib/tina4/session_handlers/resp_session_handler.rb +5 -3
- data/lib/tina4/session_handlers/valkey_handler.rb +1 -1
- data/lib/tina4/sso.rb +132 -40
- data/lib/tina4/sso_jwks.rb +12 -6
- data/lib/tina4/swagger.rb +3 -1
- data/lib/tina4/version.rb +1 -1
- data/lib/tina4/webserver.rb +7 -11
- data/lib/tina4/websocket.rb +24 -0
- data/lib/tina4.rb +11 -7
- metadata +5 -16
|
@@ -110,10 +110,12 @@ module Tina4
|
|
|
110
110
|
|
|
111
111
|
def connect
|
|
112
112
|
@socket = open_socket
|
|
113
|
-
# Bolt handshake: magic preamble + four offered versions, MSB first
|
|
114
|
-
#
|
|
115
|
-
#
|
|
116
|
-
|
|
113
|
+
# Bolt handshake: magic preamble + four offered versions, MSB first,
|
|
114
|
+
# most preferred first. All four are Bolt 4.x, whose HELLO / RUN / PULL
|
|
115
|
+
# framing is what this driver speaks. 4.4 alone was not enough: Memgraph
|
|
116
|
+
# 2.21 does not implement 4.4 (it answered the handshake with a FAILURE
|
|
117
|
+
# instead of a version), while it accepts 4.3 / 4.1. Neo4j 5 still picks 4.4.
|
|
118
|
+
@socket.write(["6060B017".to_i(16), 0x00000404, 0x00000304, 0x00000104, 0x00000004].pack("N5"))
|
|
117
119
|
negotiated = @socket.read(4)&.unpack1("N")
|
|
118
120
|
if negotiated.nil? || negotiated.zero?
|
|
119
121
|
raise BoltConnectError, "server offered no compatible Bolt version"
|
|
@@ -0,0 +1,29 @@
|
|
|
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
|
+
module Tina4
|
|
9
|
+
# Locate an executable on PATH: the stdlib-only equivalent of Python's
|
|
10
|
+
# shutil.which (no gem, no shell). Honours PATHEXT on Windows, where a shell
|
|
11
|
+
# probe such as `which x > /dev/null` cannot work (cmd.exe has neither).
|
|
12
|
+
module ExecutablePath
|
|
13
|
+
module_function
|
|
14
|
+
|
|
15
|
+
# Full path of *cmd* on *path*, or nil.
|
|
16
|
+
def find(cmd, path: ENV.fetch("PATH", ""), pathext: ENV["PATHEXT"])
|
|
17
|
+
exts = pathext ? pathext.split(File::PATH_SEPARATOR) : [""]
|
|
18
|
+
path.split(File::PATH_SEPARATOR).each do |dir|
|
|
19
|
+
next if dir.empty?
|
|
20
|
+
|
|
21
|
+
exts.each do |ext|
|
|
22
|
+
candidate = File.join(dir, "#{cmd}#{ext}")
|
|
23
|
+
return candidate if File.executable?(candidate) && !File.directory?(candidate)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
nil
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
end
|
data/lib/tina4/frond.rb
CHANGED
|
@@ -3546,9 +3546,10 @@ module Tina4
|
|
|
3546
3546
|
|
|
3547
3547
|
# get_token's expires_in is MINUTES, like every framework's. This used to
|
|
3548
3548
|
# pass minutes * 60, so a form token lived 60 hours, not 60 minutes
|
|
3549
|
-
# (ADR-0079 s5).
|
|
3550
|
-
|
|
3551
|
-
|
|
3549
|
+
# (ADR-0079 s5). The lifetime is the one rule every token uses:
|
|
3550
|
+
# TINA4_TOKEN_EXPIRES_IN, then TINA4_TOKEN_LIMIT, then 60 (a bad value
|
|
3551
|
+
# falls back to 60).
|
|
3552
|
+
Tina4::Auth.create_token(payload, expires_in: Tina4::Auth.token_lifetime_minutes)
|
|
3552
3553
|
end
|
|
3553
3554
|
|
|
3554
3555
|
def self.generate_form_token(descriptor = "")
|
data/lib/tina4/http_server.rb
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
require "socket"
|
|
10
|
+
require_relative "port_probe"
|
|
10
11
|
require "io/wait"
|
|
11
12
|
require "stringio"
|
|
12
13
|
require "json"
|
|
@@ -113,6 +114,10 @@ module Tina4
|
|
|
113
114
|
# Bind a listener. Raises on a failed bind (the caller decides whether that
|
|
114
115
|
# is fatal - the main port is, a loopback sibling or the AI port is not).
|
|
115
116
|
def listen(host, port, app)
|
|
117
|
+
# Windows binds 0.0.0.0:P beside another process's 127.0.0.1:P (and the
|
|
118
|
+
# reverse), so refuse a held port first, as POSIX's bind itself does.
|
|
119
|
+
Tina4::PortProbe.ensure_valid_port!(port)
|
|
120
|
+
Tina4::PortProbe.ensure_free!(host, port) if Tina4::PortProbe.windows?
|
|
116
121
|
socket = TCPServer.new(host, port)
|
|
117
122
|
@listeners << Listener.new(socket, app, port.to_s)
|
|
118
123
|
socket
|
data/lib/tina4/mcp.rb
CHANGED
|
@@ -970,7 +970,9 @@ module Tina4
|
|
|
970
970
|
{
|
|
971
971
|
"method" => route.method.to_s,
|
|
972
972
|
"path" => route.path.to_s,
|
|
973
|
-
|
|
973
|
+
# Both gates (Route#requires_auth?): a legacy auth_handler route
|
|
974
|
+
# 403s an anonymous caller though auth_required is false.
|
|
975
|
+
"auth_required" => route.requires_auth?,
|
|
974
976
|
"middleware" => route.middleware.map { |attached| Tina4.middleware_label(attached) }
|
|
975
977
|
}
|
|
976
978
|
end
|
data/lib/tina4/middleware.rb
CHANGED
|
@@ -499,71 +499,68 @@ module Tina4
|
|
|
499
499
|
end
|
|
500
500
|
|
|
501
501
|
# RateLimiterMiddleware -- tracks requests per IP, returns 429 when exceeded.
|
|
502
|
-
# Config via env: TINA4_RATE_LIMIT (default 100
|
|
502
|
+
# Config via env, read once at boot: TINA4_RATE_LIMIT (default 100; false, 0,
|
|
503
|
+
# no or off switches it off), TINA4_RATE_WINDOW (default 60s). A value that
|
|
504
|
+
# cannot work stops the boot (see Tina4::RateLimiter). Health and readiness
|
|
505
|
+
# probes are never counted.
|
|
506
|
+
#
|
|
507
|
+
# The framework attaches Tina4::DefaultRateLimiter globally at boot once
|
|
508
|
+
# TINA4_RATE_LIMIT is set; registered globally it runs before route matching
|
|
509
|
+
# and the auth gate, so a 404 and a failed sign-in count. Attached to one
|
|
510
|
+
# route it gives that route its own count, after the auth gate.
|
|
503
511
|
class RateLimiterMiddleware
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
512
|
+
def self.inherited(subclass)
|
|
513
|
+
super
|
|
514
|
+
subclass.send(:init_store)
|
|
515
|
+
end
|
|
507
516
|
|
|
508
517
|
class << self
|
|
518
|
+
# Registered globally, run before route matching (Middleware.pre_match_middleware).
|
|
519
|
+
def pre_match?
|
|
520
|
+
true
|
|
521
|
+
end
|
|
522
|
+
|
|
509
523
|
def before_rate_limit(request, response)
|
|
510
|
-
|
|
511
|
-
|
|
524
|
+
settings = Tina4::RateLimitPolicy.current
|
|
525
|
+
return [request, response] if settings[:off] || Tina4::RateLimitPolicy.probe?(request)
|
|
526
|
+
|
|
527
|
+
limit = settings[:limit]
|
|
528
|
+
window = settings[:window]
|
|
512
529
|
ip = request.ip || "unknown"
|
|
513
530
|
now = Time.now
|
|
514
531
|
|
|
515
532
|
cleanup_if_needed(now, window)
|
|
516
533
|
|
|
517
|
-
@mutex.synchronize
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
entries.reject! { |t| t < cutoff }
|
|
524
|
-
|
|
525
|
-
if entries.length >= limit
|
|
526
|
-
oldest = entries.first
|
|
527
|
-
retry_after = [(oldest + window - now).ceil, 1].max
|
|
528
|
-
|
|
529
|
-
response.headers["X-RateLimit-Limit"] = limit.to_s
|
|
530
|
-
response.headers["X-RateLimit-Remaining"] = "0"
|
|
531
|
-
response.headers["X-RateLimit-Reset"] = (oldest + window).to_i.to_s
|
|
532
|
-
response.headers["Retry-After"] = retry_after.to_s
|
|
533
|
-
response.json({ error: "Too Many Requests", retry_after: retry_after }, 429)
|
|
534
|
-
|
|
535
|
-
return [request, response]
|
|
536
|
-
end
|
|
537
|
-
|
|
538
|
-
entries << now
|
|
539
|
-
|
|
540
|
-
response.headers["X-RateLimit-Limit"] = limit.to_s
|
|
541
|
-
response.headers["X-RateLimit-Remaining"] = (limit - entries.length).to_s
|
|
542
|
-
response.headers["X-RateLimit-Reset"] = (now + window).to_i.to_s
|
|
534
|
+
result = @mutex.synchronize { Tina4::RateLimiter.hit(@store, ip, limit, window, now) }
|
|
535
|
+
response.headers["X-RateLimit-Limit"] = limit.to_s
|
|
536
|
+
if result[:allowed]
|
|
537
|
+
response.headers["X-RateLimit-Remaining"] = (limit - result[:count]).to_s
|
|
538
|
+
response.headers["X-RateLimit-Reset"] = (now + window).to_i.to_s
|
|
539
|
+
return [request, response]
|
|
543
540
|
end
|
|
544
541
|
|
|
542
|
+
oldest = result[:oldest]
|
|
543
|
+
retry_after = [(oldest + window - now).ceil, 1].max
|
|
544
|
+
response.headers["X-RateLimit-Remaining"] = "0"
|
|
545
|
+
response.headers["X-RateLimit-Reset"] = (oldest + window).to_i.to_s
|
|
546
|
+
response.headers["Retry-After"] = retry_after.to_s
|
|
547
|
+
response.json({ error: "Too Many Requests", retry_after: retry_after }, 429)
|
|
545
548
|
[request, response]
|
|
546
549
|
end
|
|
547
550
|
|
|
548
551
|
def check(ip)
|
|
549
|
-
|
|
550
|
-
|
|
552
|
+
settings = Tina4::RateLimitPolicy.current
|
|
553
|
+
limit = settings[:limit]
|
|
554
|
+
window = settings[:window]
|
|
551
555
|
now = Time.now
|
|
552
556
|
|
|
553
557
|
@mutex.synchronize do
|
|
554
|
-
@store
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
remaining = [limit - entries.length, 0].max
|
|
559
|
-
reset_at = entries.empty? ? window : (entries.first + window - now).ceil
|
|
560
|
-
|
|
561
|
-
if entries.length >= limit
|
|
562
|
-
return [false, { limit: limit, remaining: 0, reset: reset_at, window: window }]
|
|
558
|
+
result = Tina4::RateLimiter.hit(@store, ip, limit, window, now)
|
|
559
|
+
unless result[:allowed]
|
|
560
|
+
return [false, { limit: limit, remaining: 0, reset: (result[:oldest] + window - now).ceil, window: window }]
|
|
563
561
|
end
|
|
564
562
|
|
|
565
|
-
|
|
566
|
-
[true, { limit: limit, remaining: remaining - 1, reset: window, window: window }]
|
|
563
|
+
[true, { limit: limit, remaining: limit - result[:count], reset: window, window: window }]
|
|
567
564
|
end
|
|
568
565
|
end
|
|
569
566
|
|
|
@@ -572,23 +569,50 @@ module Tina4
|
|
|
572
569
|
@mutex.synchronize { @store.clear }
|
|
573
570
|
end
|
|
574
571
|
|
|
572
|
+
def reset_warnings!
|
|
573
|
+
Tina4::RateLimiter.reset_warnings!
|
|
574
|
+
end
|
|
575
|
+
|
|
575
576
|
private
|
|
576
577
|
|
|
578
|
+
def init_store
|
|
579
|
+
@store = {}
|
|
580
|
+
@mutex = Mutex.new
|
|
581
|
+
@last_cleanup = Time.now
|
|
582
|
+
end
|
|
583
|
+
|
|
584
|
+
# Sweep addresses whose window has passed, once a window.
|
|
577
585
|
def cleanup_if_needed(now, window)
|
|
578
586
|
return if now - @last_cleanup < window
|
|
579
587
|
|
|
580
588
|
@mutex.synchronize do
|
|
581
589
|
return if now - @last_cleanup < window
|
|
582
590
|
|
|
583
|
-
|
|
584
|
-
@store.delete_if do |_ip, entries|
|
|
585
|
-
entries.reject! { |t| t < cutoff }
|
|
586
|
-
entries.empty?
|
|
587
|
-
end
|
|
591
|
+
Tina4::RateLimiter.sweep(@store, now - window)
|
|
588
592
|
@last_cleanup = now
|
|
589
593
|
end
|
|
590
594
|
end
|
|
591
595
|
end
|
|
596
|
+
|
|
597
|
+
init_store
|
|
598
|
+
end
|
|
599
|
+
|
|
600
|
+
# The limiter Tina4.initialize! attaches globally once TINA4_RATE_LIMIT is set
|
|
601
|
+
# (see Tina4::RateLimiter). Its own class, so its count is separate from a
|
|
602
|
+
# RateLimiterMiddleware attached to a route.
|
|
603
|
+
class DefaultRateLimiter < RateLimiterMiddleware
|
|
604
|
+
class << self
|
|
605
|
+
# Read the policy once (raises RateLimitConfigError for a value that cannot
|
|
606
|
+
# work) and attach globally when TINA4_RATE_LIMIT is set and not off,
|
|
607
|
+
# unless the app already registered RateLimiterMiddleware globally itself.
|
|
608
|
+
def attach_from_env
|
|
609
|
+
return false unless Tina4::RateLimitPolicy.load![:enabled]
|
|
610
|
+
return true if Tina4::Middleware.global_middleware.include?(RateLimiterMiddleware)
|
|
611
|
+
|
|
612
|
+
Tina4::Middleware.use(self)
|
|
613
|
+
true
|
|
614
|
+
end
|
|
615
|
+
end
|
|
592
616
|
end
|
|
593
617
|
|
|
594
618
|
# RequestLoggerMiddleware -- logs method, path, and elapsed time for every request.
|
|
@@ -647,7 +671,9 @@ module Tina4
|
|
|
647
671
|
# blank (there is NO built-in default), and a blank HMAC key is publicly
|
|
648
672
|
# reproducible -- so no token can be trusted and every write is rejected
|
|
649
673
|
# (403). This is the SEC-01 no-default-secret guarantee.
|
|
650
|
-
# - Skips a request
|
|
674
|
+
# - Skips a request whose Authorization: Bearer value is a valid identity
|
|
675
|
+
# token or the TINA4_API_KEY (API clients), read untrimmed: a value with whitespace
|
|
676
|
+
# around it does not skip.
|
|
651
677
|
# - Reads request.body["formToken"] then the X-Form-Token header.
|
|
652
678
|
# - Rejects a token sent in the query string (403 + a logged warning) -- a
|
|
653
679
|
# URL leaks through logs, referers and history.
|
|
@@ -706,11 +732,19 @@ module Tina4
|
|
|
706
732
|
# not subject to the cookie-replay attack CSRF defends against.
|
|
707
733
|
headers = request.respond_to?(:headers) ? request.headers : {}
|
|
708
734
|
auth_header = (headers["authorization"] || headers["Authorization"] || "").to_s
|
|
709
|
-
|
|
710
|
-
|
|
735
|
+
# The scheme is read with the shared helper, so "bearer" and "BEARER"
|
|
736
|
+
# count like "Bearer" (RFC 9110 s11.1). A value with whitespace around
|
|
737
|
+
# it still does not excuse the request from the form-token check: only
|
|
738
|
+
# "<scheme> <token>" with exactly one space and no padding skips it.
|
|
739
|
+
bearer_token = Tina4::Auth.bearer_from_header(auth_header).to_s
|
|
740
|
+
bearer_token = "" unless auth_header == "#{auth_header[0, 6]} #{bearer_token}"
|
|
741
|
+
unless bearer_token.empty?
|
|
711
742
|
# Only an IDENTITY token marks an API client; a form token in the
|
|
712
743
|
# Bearer slot is not one and does not skip the check (ADR-0079 s1).
|
|
713
744
|
return [request, response] if !bearer_token.empty? && Tina4::Auth.identity_payload?(Tina4::Auth.valid_token(bearer_token))
|
|
745
|
+
# The TINA4_API_KEY authenticates a client, not a browser: no form
|
|
746
|
+
# token is asked of it either.
|
|
747
|
+
return [request, response] if Tina4::Auth.validate_api_key(bearer_token)
|
|
714
748
|
end
|
|
715
749
|
|
|
716
750
|
# 7. A token in the query string leaks through logs/referers/history --
|
data/lib/tina4/mqtt.rb
CHANGED
|
@@ -620,7 +620,10 @@ module Tina4
|
|
|
620
620
|
fixed_header = String.new(capacity: 5, encoding: Encoding::BINARY)
|
|
621
621
|
fixed_header << header << self.class.encode_remaining_length(body.bytesize)
|
|
622
622
|
@write_mutex.synchronize do
|
|
623
|
-
|
|
623
|
+
# Never pass an EMPTY body as a second argument: on Windows (Ruby 3.3,
|
|
624
|
+
# measured) IO#write(header, "") sends nothing at all, so a PINGREQ or
|
|
625
|
+
# DISCONNECT (no body) never left the client and its answer timed out.
|
|
626
|
+
body.empty? ? @socket.write(fixed_header) : @socket.write(fixed_header, body)
|
|
624
627
|
@last_write_at = monotonic
|
|
625
628
|
end
|
|
626
629
|
true
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
# Copyright (c) 2026 Code Infinity
|
|
3
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
4
|
+
# This Source Code Form is subject to the terms of the Mozilla Public
|
|
5
|
+
# License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
6
|
+
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
7
|
+
|
|
8
|
+
require "socket"
|
|
9
|
+
|
|
10
|
+
module Tina4
|
|
11
|
+
# "Is this port free to serve on?" without ever listening, on every platform.
|
|
12
|
+
#
|
|
13
|
+
# Two defects this replaces:
|
|
14
|
+
#
|
|
15
|
+
# * The probes were `TCPServer.new(host, port).close`: TCPServer LISTENS, so a
|
|
16
|
+
# client that connected in that window was accepted into the backlog and
|
|
17
|
+
# then dropped. A probe only BINDS.
|
|
18
|
+
# * Windows bind semantics. A plain bind of 0.0.0.0:P succeeds while another
|
|
19
|
+
# process LISTENS on 127.0.0.1:P, and a bind of 127.0.0.1:P succeeds while
|
|
20
|
+
# another listens on 0.0.0.0:P (the more specific address then takes that
|
|
21
|
+
# traffic). So a server could start "successfully" on a port another
|
|
22
|
+
# process was serving. On Windows the probe binds with SO_EXCLUSIVEADDRUSE
|
|
23
|
+
# both the address itself and its family's wildcard, which fails if ANY
|
|
24
|
+
# socket of that family holds the port.
|
|
25
|
+
module PortProbe
|
|
26
|
+
# SO_EXCLUSIVEADDRUSE is ((int)(~SO_REUSEADDR)) in winsock2.h; Ruby does not
|
|
27
|
+
# define the constant.
|
|
28
|
+
SO_EXCLUSIVEADDRUSE = ~0x0004
|
|
29
|
+
|
|
30
|
+
module_function
|
|
31
|
+
|
|
32
|
+
def windows?
|
|
33
|
+
RUBY_PLATFORM.match?(/mswin|mingw|cygwin/)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Raise SocketError for a port outside 0..65535. Windows does not reject
|
|
37
|
+
# one: it binds the port number modulo 65536 (66535 became 999), so a
|
|
38
|
+
# server would listen somewhere other than where it says it is.
|
|
39
|
+
def ensure_valid_port!(port)
|
|
40
|
+
value = Integer(port)
|
|
41
|
+
return value if value.between?(0, 65_535)
|
|
42
|
+
|
|
43
|
+
raise SocketError, "port #{port} is out of range (0-65535)"
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# True when nothing holds *port* for *host*. Port 0 (any free port) is
|
|
47
|
+
# always free.
|
|
48
|
+
def free?(host, port)
|
|
49
|
+
ensure_valid_port!(port)
|
|
50
|
+
return true if port.to_i.zero?
|
|
51
|
+
|
|
52
|
+
hosts = windows? ? [host, wildcard_for(host)].uniq : [host]
|
|
53
|
+
hosts.all? { |candidate| bind_only?(candidate, port) }
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Raise Errno::EADDRINUSE unless free?(host, port). Called before a server
|
|
57
|
+
# bind so Windows refuses a port another process is listening on, exactly
|
|
58
|
+
# as POSIX does.
|
|
59
|
+
def ensure_free!(host, port)
|
|
60
|
+
raise Errno::EADDRINUSE, "#{host}:#{port} is held by another socket" unless free?(host, port)
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Bind (never listen) a socket on host:port and close it.
|
|
64
|
+
def bind_only?(host, port)
|
|
65
|
+
address = Addrinfo.tcp(host, port)
|
|
66
|
+
socket = Socket.new(address.afamily, :STREAM)
|
|
67
|
+
if windows?
|
|
68
|
+
socket.setsockopt(Socket::SOL_SOCKET, SO_EXCLUSIVEADDRUSE, 1)
|
|
69
|
+
else
|
|
70
|
+
# As TCPServer does on POSIX, so a port in TIME_WAIT still reads free.
|
|
71
|
+
socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1)
|
|
72
|
+
end
|
|
73
|
+
socket.bind(address)
|
|
74
|
+
true
|
|
75
|
+
rescue Errno::EADDRINUSE, Errno::EACCES
|
|
76
|
+
false
|
|
77
|
+
ensure
|
|
78
|
+
socket&.close
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# The wildcard address of *host*'s family ("0.0.0.0" or "::").
|
|
82
|
+
def wildcard_for(host)
|
|
83
|
+
Addrinfo.tcp(host, 0).ipv6? ? "::" : "0.0.0.0"
|
|
84
|
+
rescue SocketError
|
|
85
|
+
"0.0.0.0"
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
data/lib/tina4/port_takeover.rb
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
require "socket"
|
|
10
|
+
require_relative "port_probe"
|
|
10
11
|
|
|
11
12
|
module Tina4
|
|
12
13
|
# Identity-checked port takeover, shared by the CLI and the runtime paths.
|
|
@@ -139,15 +140,7 @@ module Tina4
|
|
|
139
140
|
# Raw lsof/netstat PID tokens for whatever holds *port*.
|
|
140
141
|
def port_holders(port)
|
|
141
142
|
if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
|
|
142
|
-
|
|
143
|
-
`netstat -ano 2>&1`.each_line do |line|
|
|
144
|
-
next unless line.include?(":#{port}") &&
|
|
145
|
-
(line.include?("LISTENING") || line.include?("ESTABLISHED"))
|
|
146
|
-
|
|
147
|
-
candidate = line.strip.split(/\s+/).last
|
|
148
|
-
tokens << candidate if candidate&.match?(/\A\d+\z/)
|
|
149
|
-
end
|
|
150
|
-
tokens
|
|
143
|
+
netstat_holders(`netstat -ano 2>&1`, port)
|
|
151
144
|
else
|
|
152
145
|
`lsof -ti :#{port} 2>/dev/null`.split
|
|
153
146
|
end
|
|
@@ -155,11 +148,28 @@ module Tina4
|
|
|
155
148
|
[]
|
|
156
149
|
end
|
|
157
150
|
|
|
158
|
-
#
|
|
159
|
-
#
|
|
151
|
+
# PID tokens of the TCP sockets whose LOCAL port is exactly *port*, from
|
|
152
|
+
# `netstat -ano` output (Windows). A row is
|
|
153
|
+
# TCP <local addr>:<port> <foreign addr>:<port> <STATE> <PID>
|
|
154
|
+
# and only the local column's last ":" field is compared, as a whole number:
|
|
155
|
+
# a substring match on ":5123" also hit listeners on 51230-51239 and
|
|
156
|
+
# connections whose FOREIGN end was 5123, so a free port was reported as
|
|
157
|
+
# held by a non-Tina4 process. Only LISTENING / ESTABLISHED rows count.
|
|
158
|
+
def netstat_holders(output, port)
|
|
159
|
+
wanted = port.to_s
|
|
160
|
+
output.each_line.filter_map do |line|
|
|
161
|
+
proto, local, _foreign, state, pid = line.split
|
|
162
|
+
next unless proto == "TCP" && %w[LISTENING ESTABLISHED].include?(state)
|
|
163
|
+
next unless local.to_s.rpartition(":").last == wanted
|
|
164
|
+
|
|
165
|
+
pid if pid&.match?(/\A\d+\z/)
|
|
166
|
+
end
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
# True when *host*:*port* is free to serve on right now: a bind-only probe
|
|
170
|
+
# that never listens (Tina4::PortProbe).
|
|
160
171
|
def bindable?(host, port)
|
|
161
|
-
|
|
162
|
-
true
|
|
172
|
+
Tina4::PortProbe.free?(host, port)
|
|
163
173
|
rescue StandardError
|
|
164
174
|
false
|
|
165
175
|
end
|
|
@@ -183,6 +193,13 @@ module Tina4
|
|
|
183
193
|
"-- free it or choose another port.")
|
|
184
194
|
end
|
|
185
195
|
|
|
196
|
+
# TERM asks a POSIX dev server to shut down cleanly. Windows has no TERM
|
|
197
|
+
# for another process (Process.kill raises EINVAL), so there the only stop
|
|
198
|
+
# is KILL (TerminateProcess).
|
|
199
|
+
def stop_signal
|
|
200
|
+
RUBY_PLATFORM =~ /mswin|mingw|cygwin/ ? "KILL" : "TERM"
|
|
201
|
+
end
|
|
202
|
+
|
|
186
203
|
# Reclaim *port* ONLY from an identity-confirmed Tina4 dev server. The single
|
|
187
204
|
# guarded path for both the CLI (`tina4 serve`) and the runtime bind-failure
|
|
188
205
|
# fallback. `dev`/`no_takeover` are passed in so this stays pure and directly
|
|
@@ -200,7 +217,9 @@ module Tina4
|
|
|
200
217
|
me = Process.pid
|
|
201
218
|
my_group = begin
|
|
202
219
|
Process.getpgrp
|
|
203
|
-
rescue StandardError
|
|
220
|
+
rescue StandardError, NotImplementedError
|
|
221
|
+
# Windows has no process groups: getpgrp raises NotImplementedError,
|
|
222
|
+
# which is a ScriptError, not a StandardError.
|
|
204
223
|
nil
|
|
205
224
|
end
|
|
206
225
|
holders = selectable_pids(tokens.join(" "), me, my_group)
|
|
@@ -216,7 +235,7 @@ module Tina4
|
|
|
216
235
|
|
|
217
236
|
killed = []
|
|
218
237
|
tina4_holders.each do |pid|
|
|
219
|
-
Process.kill(
|
|
238
|
+
Process.kill(stop_signal, pid)
|
|
220
239
|
killed << pid
|
|
221
240
|
rescue Errno::ESRCH, Errno::EPERM
|
|
222
241
|
# already gone or no permission
|
data/lib/tina4/rack_app.rb
CHANGED
|
@@ -1275,9 +1275,16 @@ module Tina4
|
|
|
1275
1275
|
[code, { "content-type" => "text/html" }, [html]]
|
|
1276
1276
|
end
|
|
1277
1277
|
|
|
1278
|
+
# Whether the gate asks this request for a token on +route+. A bare ANY
|
|
1279
|
+
# route is public for reads and secured for writes (ADR-0019). A role or
|
|
1280
|
+
# permission guard always needs a token, in whichever order .no_auth and
|
|
1281
|
+
# .role/.can were chained: without one the guard could never be satisfied.
|
|
1282
|
+
def self._route_needs_token?(route, http_method)
|
|
1283
|
+
route.auth_required_for?(http_method) || route.guarded?
|
|
1284
|
+
end
|
|
1285
|
+
|
|
1278
1286
|
def self.enforce_route_auth(env, route)
|
|
1279
|
-
|
|
1280
|
-
return nil unless route.auth_required_for?(env["REQUEST_METHOD"])
|
|
1287
|
+
return nil unless _route_needs_token?(route, env["REQUEST_METHOD"])
|
|
1281
1288
|
|
|
1282
1289
|
# ERR-DEC-02 (#342): a browser gets errors/401.twig, an API client the JSON
|
|
1283
1290
|
# envelope — the same negotiation every other framework error uses. Was an
|
|
@@ -1291,6 +1298,9 @@ module Tina4
|
|
|
1291
1298
|
# write came from, not who sent it: it is skipped and the next slot is
|
|
1292
1299
|
# tried (ADR-0079 s1). So a logged-in user posting a rendered form (form
|
|
1293
1300
|
# token in the body, auth token in the session) is still authenticated.
|
|
1301
|
+
# A body token that fails verification is skipped too (ADR-0079 s1.3); a
|
|
1302
|
+
# failed Bearer token is a 401 before the session or a live SSO identity
|
|
1303
|
+
# is consulted.
|
|
1294
1304
|
candidates = []
|
|
1295
1305
|
auth_header = env["HTTP_AUTHORIZATION"] || ""
|
|
1296
1306
|
candidates << [Regexp.last_match(1), :header] if auth_header =~ /\ABearer\s++(.+)\z/i
|
|
@@ -1303,7 +1313,7 @@ module Tina4
|
|
|
1303
1313
|
end
|
|
1304
1314
|
return unauthorized if verdict == :denied
|
|
1305
1315
|
|
|
1306
|
-
unless
|
|
1316
|
+
unless _authenticated?(env)
|
|
1307
1317
|
# Request path, so the same log-loud-then-degrade policy as
|
|
1308
1318
|
# Request#session (ADR-0021): an unreachable session store must not turn
|
|
1309
1319
|
# the auth gate into a 500. It degrades to an empty session, which means
|
|
@@ -1321,7 +1331,7 @@ module Tina4
|
|
|
1321
1331
|
end
|
|
1322
1332
|
end
|
|
1323
1333
|
end
|
|
1324
|
-
return unauthorized unless
|
|
1334
|
+
return unauthorized unless _authenticated?(env)
|
|
1325
1335
|
|
|
1326
1336
|
# ── RBAC guards (Feature 138): authorization AFTER authentication ──
|
|
1327
1337
|
# Auth has passed (401 ruled out above). If the route carries role/
|
|
@@ -1332,6 +1342,12 @@ module Tina4
|
|
|
1332
1342
|
nil
|
|
1333
1343
|
end
|
|
1334
1344
|
|
|
1345
|
+
# True once a slot has authenticated the request: a verified payload, or
|
|
1346
|
+
# the API key (which attaches no payload).
|
|
1347
|
+
def self._authenticated?(env)
|
|
1348
|
+
env.key?("tina4.auth_payload") || env["tina4.auth_api_key"] == true
|
|
1349
|
+
end
|
|
1350
|
+
|
|
1335
1351
|
# Judge one token from one slot: :accepted (env["tina4.auth_payload"] set),
|
|
1336
1352
|
# :skip (a valid form token - not an identity, try the next slot) or
|
|
1337
1353
|
# :denied (anything else).
|
|
@@ -1340,19 +1356,29 @@ module Tina4
|
|
|
1340
1356
|
# (OpenSSL.fixed_length_secure_compare), matching tina4_python's _check_auth.
|
|
1341
1357
|
# A plain `token == api_key` returns as soon as two bytes differ, so response
|
|
1342
1358
|
# timing would leak the key a character at a time.
|
|
1359
|
+
#
|
|
1360
|
+
# The API key is accepted in the Bearer slot only, and attaches NO user
|
|
1361
|
+
# (request.user stays nil), so a role or permission guard still refuses it.
|
|
1362
|
+
# env["tina4.auth_api_key"] records how the request was authenticated.
|
|
1343
1363
|
def self._authenticate_token(env, token, source)
|
|
1344
|
-
if Tina4::Auth.validate_api_key(token)
|
|
1345
|
-
env["tina4.
|
|
1364
|
+
if source == :header && Tina4::Auth.validate_api_key(token)
|
|
1365
|
+
env["tina4.auth_api_key"] = true
|
|
1346
1366
|
return :accepted
|
|
1347
1367
|
end
|
|
1348
1368
|
payload = Tina4::Auth.valid_token(token)
|
|
1349
|
-
|
|
1369
|
+
# The body slot carries form tokens, so a body token that FAILS (an
|
|
1370
|
+
# expired or invalid form token) is skipped like a valid form token, as if
|
|
1371
|
+
# no body token had been sent (ADR-0079 s1.3). A failed Bearer or session
|
|
1372
|
+
# token is refused.
|
|
1373
|
+
return(source == :body ? :skip : :denied) unless payload
|
|
1350
1374
|
return :skip unless Tina4::Auth.identity_payload?(payload)
|
|
1351
1375
|
|
|
1352
1376
|
env["tina4.auth_payload"] = payload
|
|
1353
|
-
# When a body token authenticates,
|
|
1354
|
-
#
|
|
1355
|
-
|
|
1377
|
+
# When a body token authenticates, hand the same token back as FreshToken
|
|
1378
|
+
# (identity tokens only) so frond.js can send it in the Authorization
|
|
1379
|
+
# header from now on. It is NOT re-signed with a new lifetime: renewal here
|
|
1380
|
+
# would let one token be kept alive for ever, so it keeps its own expiry.
|
|
1381
|
+
env["tina4.fresh_token"] = token if source == :body
|
|
1356
1382
|
:accepted
|
|
1357
1383
|
end
|
|
1358
1384
|
|