nats-pure 2.6.0 → 2.8.0

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.
@@ -27,6 +27,7 @@ require "json"
27
27
  require "monitor"
28
28
  require "uri"
29
29
  require "securerandom"
30
+ require "ipaddr"
30
31
  require "concurrent"
31
32
 
32
33
  begin
@@ -213,10 +214,13 @@ module NATS
213
214
  # Secure TLS options
214
215
  @tls = nil
215
216
 
216
- # Hostname of current server; used for when TLS host
217
- # verification is enabled.
217
+ # The TLS name of the current server: the name its certificate is
218
+ # verified against unless tls: {hostname:} is set, and the name a
219
+ # discovered IP address it lists inherits.
218
220
  @hostname = nil
219
- @single_url_connect_used = false
221
+
222
+ # The discovered servers reported to on_error for having no such name.
223
+ @without_tls_name = {}
220
224
 
221
225
  # Track whether connect has been already been called.
222
226
  @connect_called = false
@@ -225,6 +229,9 @@ module NATS
225
229
  # that the connection was closed meanwhile.
226
230
  @close_generation = 0
227
231
 
232
+ # The thread whose close runs the disconnect and close callbacks.
233
+ @close_callbacks_thread = nil
234
+
228
235
  # New style request/response implementation.
229
236
  @resp_sub = nil
230
237
  @resp_map = nil
@@ -293,6 +300,7 @@ module NATS
293
300
  private def parse_and_validate_options
294
301
  # Reset these in case we have reconnected via fork.
295
302
  @server_pool = []
303
+ @without_tls_name = {}
296
304
  @resp_sub = nil
297
305
  @resp_map = nil
298
306
  @resp_sub_prefix = nil
@@ -319,7 +327,6 @@ module NATS
319
327
  if srvs.any? { |u| %w[tls wss].include? u.scheme } && !opts[:tls]
320
328
  opts[:tls] = {context: tls_context}
321
329
  end
322
- @single_url_connect_used = true if srvs.size == 1
323
330
  when Hash
324
331
  opts = uri
325
332
  end
@@ -358,12 +365,19 @@ module NATS
358
365
  else
359
366
  URI.parse(u)
360
367
  end
368
+ # A configured server is verified against the host of its URL.
361
369
  @server_pool << {
362
370
  uri: nats_uri,
363
- hostname: nats_uri.hostname
371
+ hostname: nats_uri.hostname,
372
+ tls_name: nats_uri.hostname
364
373
  }
365
374
  end
366
375
 
376
+ # The pool drops a server after failed attempts. Listed again by a
377
+ # server, a configured server is still verified against the host of
378
+ # its URL.
379
+ @configured_servers = @server_pool.map { |srv| [srv[:uri].hostname, srv[:uri].port] }
380
+
367
381
  if @options[:old_style_request]
368
382
  # Replace for this instance the implementation
369
383
  # of request to use the old_request style.
@@ -399,16 +413,8 @@ module NATS
399
413
  begin
400
414
  srv = select_next_server
401
415
 
402
- # Use the hostname from the server for TLS hostname verification.
403
- if client_using_secure_connection? && single_url_connect_used?
404
- # Always reuse the original hostname used to connect.
405
- @hostname ||= srv[:hostname]
406
- else
407
- @hostname = srv[:hostname]
408
- end
409
-
410
416
  # Create TCP socket connection to NATS.
411
- @io = create_socket
417
+ @io = create_socket(srv)
412
418
  @io.connect
413
419
 
414
420
  # Capture state that we have had a TCP connection established against
@@ -479,8 +485,10 @@ module NATS
479
485
  return publish_msg(NATS::Msg.new(subject: subject, data: msg, reply: opt_reply, header: options[:header]))
480
486
  end
481
487
 
482
- # Accounting
483
488
  msg_size = msg.bytesize
489
+ check_max_payload!(msg_size)
490
+
491
+ # Accounting
484
492
  @stats[:out_msgs] += 1
485
493
  @stats[:out_bytes] += msg_size
486
494
 
@@ -497,10 +505,6 @@ module NATS
497
505
  msg.data ||= "".dup
498
506
  msg_size = msg.data.bytesize
499
507
 
500
- # Accounting
501
- @stats[:out_msgs] += 1
502
- @stats[:out_bytes] += msg_size
503
-
504
508
  if msg.header
505
509
  hdr = "".dup
506
510
  hdr << NATS_HDR_LINE
@@ -510,8 +514,20 @@ module NATS
510
514
  hdr << CR_LF
511
515
  hdr_len = hdr.bytesize
512
516
  total_size = msg_size + hdr_len
517
+ check_max_payload!(total_size)
518
+
519
+ # Accounting
520
+ @stats[:out_msgs] += 1
521
+ @stats[:out_bytes] += msg_size
522
+
513
523
  send_command("HPUB #{msg.subject} #{msg.reply} #{hdr_len} #{total_size}\r\n#{hdr}#{msg.data}\r\n")
514
524
  else
525
+ check_max_payload!(msg_size)
526
+
527
+ # Accounting
528
+ @stats[:out_msgs] += 1
529
+ @stats[:out_bytes] += msg_size
530
+
515
531
  send_command("PUB #{msg.subject} #{msg.reply} #{msg_size}\r\n#{msg.data}\r\n")
516
532
  end
517
533
 
@@ -845,6 +861,8 @@ module NATS
845
861
  # callback option to know when the connection has moved from draining to closed.
846
862
  def drain
847
863
  return if draining?
864
+ # There is no connection to drain while reconnecting.
865
+ return close if reconnecting?
848
866
 
849
867
  synchronize do
850
868
  @drain_t ||= Thread.new { do_drain }
@@ -876,8 +894,13 @@ module NATS
876
894
  raise(NATS::IO::ClientError, "custom inbox may not begin with '.'") if @inbox_prefix.start_with?(".")
877
895
  end
878
896
 
879
- def process_info(line)
897
+ # Takes an INFO from the server. Unless ignore_discovered_urls is set,
898
+ # or discover is false, the servers it lists replace the discovered
899
+ # servers; those of the first INFO of an attempt (first: true) are only
900
+ # added.
901
+ def process_info(line, discover: true, first: false)
880
902
  parsed_info = JSON.parse(line)
903
+ skipped = []
881
904
 
882
905
  # INFO can be received asynchronously too,
883
906
  # so has to be done under the lock.
@@ -889,13 +912,20 @@ module NATS
889
912
 
890
913
  # Detect any announced server that we might not be aware of...
891
914
  connect_urls = @server_info[:connect_urls]
892
- if !@options[:ignore_discovered_urls] && connect_urls
893
- srvs = []
894
- connect_urls.each do |url|
895
- # Use the same scheme as the currently in use URI.
896
- scheme = @uri.scheme
897
- u = URI.parse("#{scheme}://#{url}")
915
+ if discover && !@options[:ignore_discovered_urls] && connect_urls
916
+ uris = connect_urls.filter_map { |url| discovered_uri(url) }
917
+
918
+ # A later list drops the discovered servers it no longer names.
919
+ # The configured servers and the current one stay, and an empty
920
+ # list changes nothing.
921
+ if !first && !connect_urls.empty?
922
+ server_pool.reject! do |srv|
923
+ srv[:discovered] && [@uri, *uris].none? { |u| srv[:uri].hostname == u.hostname && srv[:uri].port == u.port }
924
+ end
925
+ end
898
926
 
927
+ srvs = []
928
+ uris.each do |u|
899
929
  # Skip in case it is the current server which we already know
900
930
  next if @uri.hostname == u.hostname && @uri.port == u.port
901
931
 
@@ -903,6 +933,8 @@ module NATS
903
933
  srv[:uri].hostname == u.hostname && srv[:uri].port == u.port
904
934
  end
905
935
 
936
+ # The first server that lists a server decides its credentials
937
+ # and its TLS name.
906
938
  if !present
907
939
  # Let explicit user and pass options set the credentials.
908
940
  u.user = options[:user] if options[:user]
@@ -914,8 +946,18 @@ module NATS
914
946
  u.password ||= @uri.password if @uri.password
915
947
  end
916
948
 
917
- # NOTE: Auto discovery won't work here when TLS host verification is enabled.
918
- srv = {uri: u, reconnect_attempts: 0, discovered: true, hostname: u.hostname}
949
+ tls_name = @configured_servers.include?([u.hostname, u.port]) ? u.hostname : discovered_tls_name(u)
950
+
951
+ # Over TLS, a server with no name to verify its certificate
952
+ # against is not connected to. It is reported once per connect.
953
+ if tls_name.nil? && client_using_secure_connection? && !@tls&.fetch(:hostname, nil)
954
+ key = "#{u.host}:#{u.port}"
955
+ skipped << without_tls_name_error(key) unless @without_tls_name[key]
956
+ @without_tls_name[key] = true
957
+ next
958
+ end
959
+
960
+ srv = {uri: u, reconnect_attempts: 0, discovered: true, hostname: u.hostname, tls_name: tls_name}
919
961
  srvs << srv
920
962
  end
921
963
  end
@@ -925,10 +967,59 @@ module NATS
925
967
  server_pool.push(*srvs)
926
968
  end
927
969
  end
970
+ skipped.each { |e| err_cb_call(self, e, nil) } if @err_cb
928
971
 
929
972
  @server_info
930
973
  end
931
974
 
975
+ # The URI of a connect_urls entry, with the scheme of the current
976
+ # connection, or nil to skip the entry. nats-server writes an entry as
977
+ # host:port, with an IPv6 address in brackets. An entry with a scheme is
978
+ # skipped, and so is one that is not host:port. User info in an entry is
979
+ # dropped: a discovered server gets the client's own credentials.
980
+ def discovered_uri(entry)
981
+ return nil unless entry.is_a?(String) && !entry.include?("://")
982
+
983
+ u = URI.parse("nats://#{entry}")
984
+ return nil if u.host.to_s.empty? || !u.port&.between?(1, 65535) || !u.path.empty? || u.query || u.fragment
985
+
986
+ URI.parse("#{@uri.scheme}://#{u.host}:#{u.port}")
987
+ rescue URI::Error
988
+ nil
989
+ end
990
+
991
+ # The name the certificate of a server discovered on the current
992
+ # connection is verified against, and that is sent as SNI. A host name
993
+ # is verified against itself. An IP address is one more address of the
994
+ # current server: it is verified against the name the current server is
995
+ # verified against, and so, over any number of hops, against the name
996
+ # of a configured server, or a discovered host name. It has no name
997
+ # when that name is an IP address too. With
998
+ # tls: {verify_discovered_servers_by_ip: true}, an IP address is
999
+ # verified against itself. tls: {hostname:} overrides every name.
1000
+ def discovered_tls_name(uri)
1001
+ return uri.hostname unless ip_address?(uri.hostname)
1002
+ return uri.hostname if verify_discovered_servers_by_ip?
1003
+
1004
+ @hostname unless ip_address?(@hostname)
1005
+ end
1006
+
1007
+ # The error for a discovered server, given as host:port, that has no
1008
+ # name to verify its certificate against.
1009
+ def without_tls_name_error(server)
1010
+ NATS::IO::ConnectError.new("nats: skipping the discovered server #{server}, which has no name to verify its certificate against; " \
1011
+ "tls: {hostname:} sets the name every server is verified against, or tls: {verify_discovered_servers_by_ip: true} " \
1012
+ "verifies a discovered IP address against itself, which is safe only where the CA that issued the certificates is not shared with others")
1013
+ end
1014
+
1015
+ # Whether host is an IPv4 or IPv6 address.
1016
+ def ip_address?(host)
1017
+ IPAddr.new(host.to_s)
1018
+ true
1019
+ rescue IPAddr::Error
1020
+ false
1021
+ end
1022
+
932
1023
  def process_hdr(header)
933
1024
  hdr = nil
934
1025
  if header
@@ -1083,6 +1174,9 @@ module NATS
1083
1174
  @uri.user = @options[:user] if @options[:user]
1084
1175
  @uri.password = @options[:pass] if @options[:pass]
1085
1176
 
1177
+ # Its TLS name, which a discovered IP address it lists inherits.
1178
+ @hostname = srv[:tls_name]
1179
+
1086
1180
  srv
1087
1181
  end
1088
1182
 
@@ -1107,12 +1201,51 @@ module NATS
1107
1201
  # Insecure TLS versions not supported already:
1108
1202
  # https://github.com/ruby/openssl/commit/3e5a009966bd7f806f7180d82cf830a04be28986
1109
1203
  #
1110
- tls_context.set_params
1204
+ # With insecure_skip_verify there is no context of the user to leave
1205
+ # verification to, so this one verifies nothing.
1206
+ if insecure_skip_verify?
1207
+ tls_context.set_params(verify_mode: OpenSSL::SSL::VERIFY_NONE, verify_hostname: false)
1208
+ else
1209
+ # The client checks the name after the handshake (verify_server!),
1210
+ # where the error can list the names of the certificate.
1211
+ tls_context.set_params(verify_hostname: false)
1212
+ end
1111
1213
  end
1112
1214
  end
1113
1215
 
1114
- def single_url_connect_used?
1115
- @single_url_connect_used
1216
+ # tls: {insecure_skip_verify: true} turns the client's check of the
1217
+ # server's certificate off. Only true does, so that a value such as
1218
+ # "false" keeps the check on.
1219
+ def insecure_skip_verify?
1220
+ !!@tls && @tls[:insecure_skip_verify] == true
1221
+ end
1222
+
1223
+ # tls: {handshake_first: true} starts the TLS handshake before the server
1224
+ # sends INFO, for servers with handshake_first in their tls block.
1225
+ def handshake_first?
1226
+ !!@tls && !!@tls[:handshake_first]
1227
+ end
1228
+
1229
+ # tls: {verify_discovered_servers_by_ip: true} verifies a discovered IP
1230
+ # address against itself, for clusters whose certificates carry only IP
1231
+ # addresses. Only true does.
1232
+ def verify_discovered_servers_by_ip?
1233
+ !!@tls && @tls[:verify_discovered_servers_by_ip] == true
1234
+ end
1235
+
1236
+ # The server closes the connection when a payload is over max_payload from
1237
+ # INFO (a later async INFO can lower it). Reject before the bytes are
1238
+ # queued, so the socket stays up. The size is the PUB body, or the HPUB
1239
+ # header block and body together: that is the size the server measures.
1240
+ # A limit of 0, or none yet, is not a limit, and the server skips it too.
1241
+ # A closed client is reported as such before the size is considered.
1242
+ private def check_max_payload!(size)
1243
+ raise NATS::IO::ConnectionClosedError if closed?
1244
+
1245
+ limit = @server_info[:max_payload]
1246
+ return unless limit.is_a?(Integer) && limit.positive? && size > limit
1247
+
1248
+ raise NATS::IO::MaxPayloadError, "nats: maximum payload exceeded"
1116
1249
  end
1117
1250
 
1118
1251
  def send_command(command)
@@ -1171,7 +1304,13 @@ module NATS
1171
1304
  end
1172
1305
 
1173
1306
  def do_drain
1174
- synchronize { @status = DRAINING_SUBS }
1307
+ # A reconnect that started after drain was called leaves no
1308
+ # connection to drain.
1309
+ reconnecting = synchronize do
1310
+ @status = DRAINING_SUBS unless reconnecting?
1311
+ reconnecting?
1312
+ end
1313
+ return close if reconnecting
1175
1314
 
1176
1315
  # Do unsubscribe protocol for all the susbcriptions, then have a single thread
1177
1316
  # waiting until all subs are done or drain timeout error reported to async error cb.
@@ -1453,6 +1592,17 @@ module NATS
1453
1592
  end
1454
1593
 
1455
1594
  def process_connect_init
1595
+ # A server with handshake_first expects the TLS handshake before INFO.
1596
+ # A wss:// connection has its TLS before the WebSocket upgrade.
1597
+ tls_first = handshake_first? && %w[nats tls].include?(@uri.scheme)
1598
+ @io.setup_tls! if tls_first
1599
+
1600
+ # A client that asks for TLS and has none yet starts it after INFO,
1601
+ # or fails the attempt. The servers of an INFO read before the TLS
1602
+ # handshake are not used, whether the attempt goes on or fails: the
1603
+ # discovered servers come from the INFOs received inside TLS.
1604
+ tls_after_info = client_using_secure_connection? && !tls_first && @uri.scheme != "wss"
1605
+
1456
1606
  # FIXME: Can receive PING as well here in recent versions.
1457
1607
  line = @io.read_line(options[:connect_timeout])
1458
1608
  if !line || line.empty?
@@ -1461,12 +1611,14 @@ module NATS
1461
1611
 
1462
1612
  if (match = line.match(NATS::Protocol::INFO))
1463
1613
  info_json = match.captures.first
1464
- process_info(info_json)
1614
+ process_info(info_json, discover: !tls_after_info, first: true)
1465
1615
  else
1466
1616
  raise NATS::IO::ConnectError.new("nats: protocol exception, INFO not valid")
1467
1617
  end
1468
1618
 
1469
- if server_using_secure_connection? && client_using_secure_connection?
1619
+ if tls_first
1620
+ # The connection has TLS already.
1621
+ elsif server_using_secure_connection? && client_using_secure_connection?
1470
1622
  @io.setup_tls!
1471
1623
  # Server > v2.9.19 returns tls_required regardless of no_tls for WebSocket config being used so need to check URI.
1472
1624
  elsif server_using_secure_connection? && !client_using_secure_connection? && (@uri.scheme != "ws")
@@ -1486,27 +1638,68 @@ module NATS
1486
1638
  # Send ping/pong after connect
1487
1639
  @io.write(PING_REQUEST)
1488
1640
 
1489
- next_op = @io.read_line(options[:connect_timeout])
1490
- if @options[:verbose]
1491
- # Need to get another command here if verbose
1492
- raise NATS::IO::ConnectError.new("expected to receive +OK") unless next_op =~ NATS::Protocol::OK
1493
- next_op = @io.read_line(options[:connect_timeout])
1641
+ next_op = next_connect_op(MonotonicTime.now + options[:connect_timeout])
1642
+ raise NATS::IO::ConnectError.new("expected PONG, got #{next_op}") unless next_op =~ NATS::Protocol::PONG
1643
+
1644
+ # On a connection that started TLS after INFO, nats-server 2.12 and
1645
+ # later send an INFO right after the first PONG, inside TLS. The
1646
+ # client waits for it, to know the servers it lists when connect
1647
+ # returns. The version in the INFO read before the handshake decides
1648
+ # only whether the client waits.
1649
+ if tls_after_info && !@options[:ignore_discovered_urls] && sends_info_after_first_pong?(@server_info[:version])
1650
+ read_info_after_first_pong
1494
1651
  end
1652
+ end
1495
1653
 
1496
- case next_op
1497
- when NATS::Protocol::PONG
1498
- # do nothing
1499
- when NATS::Protocol::ERR
1500
- if @server_info[:auth_required]
1501
- raise NATS::IO::AuthError.new($1)
1654
+ # Reads the next operation of an attempt after CONNECT, until deadline.
1655
+ # A PING is answered and +OK is skipped: in verbose mode the server
1656
+ # answers CONNECT with +OK. A -ERR fails the attempt with the server's
1657
+ # error.
1658
+ def next_connect_op(deadline)
1659
+ loop do
1660
+ timeout = deadline - MonotonicTime.now
1661
+ raise NATS::IO::SocketTimeoutError if timeout <= 0
1662
+
1663
+ op = @io.read_line(timeout)
1664
+ case op
1665
+ when NATS::Protocol::PING
1666
+ @io.write(PONG_RESPONSE, timeout)
1667
+ when NATS::Protocol::OK
1668
+ # Skipped.
1669
+ when NATS::Protocol::ERR
1670
+ raise(@server_info[:auth_required] ? NATS::IO::AuthError.new($1) : NATS::IO::ServerError.new($1))
1502
1671
  else
1503
- raise NATS::IO::ServerError.new($1)
1672
+ return op
1504
1673
  end
1505
- else
1506
- raise NATS::IO::ConnectError.new("expected PONG, got #{next_op}")
1507
1674
  end
1508
1675
  end
1509
1676
 
1677
+ # Reads the INFO that follows the first PONG, for up to connect_timeout
1678
+ # from that PONG. When none comes in time, the client reports connected
1679
+ # without it, and the read loop takes it when it comes. Any other
1680
+ # operation, or a closed connection, fails the attempt.
1681
+ def read_info_after_first_pong
1682
+ op = begin
1683
+ next_connect_op(MonotonicTime.now + options[:connect_timeout])
1684
+ rescue NATS::IO::SocketTimeoutError
1685
+ # A close from another thread can end the wait the same way.
1686
+ raise if closed?
1687
+
1688
+ return
1689
+ end
1690
+ raise NATS::IO::ConnectError.new("expected INFO, got #{op}") unless op =~ NATS::Protocol::INFO
1691
+
1692
+ process_info($1)
1693
+ end
1694
+
1695
+ # Whether a server of this version sends an INFO right after the PONG
1696
+ # to the first PING, as nats-server does from 2.12.0 on. Only the three
1697
+ # numbers count, so a pre-release counts as its release.
1698
+ def sends_info_after_first_pong?(version)
1699
+ numbers = /\A(\d+)\.(\d+)\.(\d+)(?:[-+]|\z)/.match(version.to_s)&.captures&.map(&:to_i)
1700
+ !numbers.nil? && (numbers <=> [2, 12, 0]) >= 0
1701
+ end
1702
+
1510
1703
  # Reconnect logic. generation is @close_generation from when the
1511
1704
  # reconnect started; a close since then cancels the reconnect.
1512
1705
  def attempt_reconnect(generation)
@@ -1524,16 +1717,8 @@ module NATS
1524
1717
 
1525
1718
  srv = select_next_server
1526
1719
 
1527
- # Set hostname to use for TLS hostname verification
1528
- if client_using_secure_connection? && single_url_connect_used?
1529
- # Reuse original hostname name in case of using TLS.
1530
- @hostname ||= srv[:hostname]
1531
- else
1532
- @hostname = srv[:hostname]
1533
- end
1534
-
1535
1720
  # Establish TCP connection with new server
1536
- @io = create_socket
1721
+ @io = create_socket(srv)
1537
1722
  @io.connect
1538
1723
  @stats[:reconnects] += 1
1539
1724
 
@@ -1631,8 +1816,10 @@ module NATS
1631
1816
  end
1632
1817
 
1633
1818
  # Try to write any pending flushes in case
1634
- # we have a connection then close it.
1635
- should_flush = @pending_queue && @io && @io.socket && !@io.closed?
1819
+ # we have a connection then close it. While connecting or
1820
+ # reconnecting there is none: @io is an attempt that has not sent
1821
+ # CONNECT, or has failed.
1822
+ should_flush = !reconnecting? && !connecting? && @pending_queue && @io && @io.socket && !@io.closed?
1636
1823
  if should_flush
1637
1824
  begin
1638
1825
  cmds = []
@@ -1649,9 +1836,16 @@ module NATS
1649
1836
  # Destroy any remaining subscriptions.
1650
1837
  @subs.clear
1651
1838
 
1652
- if do_cbs
1653
- @disconnect_cb&.call(@last_err)
1654
- @close_cb&.call
1839
+ # A close from one of these callbacks closes without calling them
1840
+ # again.
1841
+ if do_cbs && @close_callbacks_thread != Thread.current
1842
+ begin
1843
+ @close_callbacks_thread = Thread.current
1844
+ @disconnect_cb&.call(@last_err)
1845
+ @close_cb&.call
1846
+ ensure
1847
+ @close_callbacks_thread = nil
1848
+ end
1655
1849
  end
1656
1850
 
1657
1851
  @status = conn_status
@@ -1793,7 +1987,7 @@ module NATS
1793
1987
  @options[:reconnect]
1794
1988
  end
1795
1989
 
1796
- def create_socket
1990
+ def create_socket(srv)
1797
1991
  socket_class = case @uri.scheme
1798
1992
  when "nats", "tls"
1799
1993
  NATS::IO::Socket
@@ -1804,9 +1998,15 @@ module NATS
1804
1998
  raise NotImplementedError, "#{@uri.scheme} protocol is not supported, check NATS cluster URL spelling"
1805
1999
  end
1806
2000
 
2001
+ # tls: {hostname:} sets the name every server is verified against,
2002
+ # and that is sent as SNI. discovered: a discovered server, verified
2003
+ # against the name the client gave it.
2004
+ hostname = @tls&.fetch(:hostname, nil)
2005
+
1807
2006
  socket_class.new(
1808
2007
  uri: @uri,
1809
- tls: {context: tls_context, hostname: @hostname},
2008
+ tls: {context: tls_context, hostname: hostname || @hostname, insecure_skip_verify: insecure_skip_verify?,
2009
+ discovered: !!srv[:discovered] && !hostname},
1810
2010
  connect_timeout: NATS::IO::DEFAULT_CONNECT_TIMEOUT
1811
2011
  )
1812
2012
  end
@@ -2023,44 +2223,56 @@ module NATS
2023
2223
 
2024
2224
  # (Re-)connect using secure connection if server and client agreed on using it.
2025
2225
  def setup_tls!
2226
+ # Bytes the server sent after INFO and before the handshake are
2227
+ # dropped: from here on, only what comes through TLS is read.
2228
+ @unread&.clear
2229
+
2026
2230
  # Setup TLS connection by rewrapping the socket
2027
2231
  tls_socket = OpenSSL::SSL::SSLSocket.new(@socket, @tls.fetch(:context))
2028
2232
 
2029
2233
  # Close TCP socket after closing TLS socket as well.
2030
2234
  tls_socket.sync_close = true
2031
2235
 
2032
- # Required to enable hostname verification if Ruby runtime supports it (>= 2.4):
2236
+ # Sets SNI, and the name that a context with verify_hostname checks
2237
+ # during the handshake on CRuby:
2033
2238
  # https://github.com/ruby/openssl/commit/028e495734e9e6aa5dba1a2e130b08f66cf31a21
2034
2239
  tls_socket.hostname = @tls[:hostname]
2035
2240
 
2036
- tls_socket.connect
2241
+ begin
2242
+ tls_socket.connect
2243
+ rescue OpenSSL::SSL::SSLError => e
2244
+ e = OpenSSL::SSL::SSLError.new(name_check_failed(tls_socket.peer_cert_chain&.first)) if name_check_failed?(tls_socket)
2245
+ # Nothing is sent on a connection whose handshake failed.
2246
+ tls_socket.close
2247
+ raise e
2248
+ end
2249
+ verify_server!(tls_socket) unless @tls[:insecure_skip_verify]
2037
2250
  @socket = tls_socket
2038
2251
  end
2039
2252
 
2253
+ # Reads a line, up to and including "\n", or returns nil when the
2254
+ # connection is closed first. A read from the socket can take more
2255
+ # than the line, as one TLS record can carry several lines, so the
2256
+ # rest is kept for the next read_line or read. The deadline counts
2257
+ # from the call, for the whole line.
2040
2258
  def read_line(deadline = nil)
2041
- # FIXME: Should accumulate and read in a non blocking way instead
2042
- unless ::IO.select([@socket], nil, nil, deadline)
2043
- raise NATS::IO::SocketTimeoutError
2259
+ @unread ||= String.new
2260
+ limit = deadline && MonotonicTime.now + deadline
2261
+ until (idx = @unread.index("\n"))
2262
+ raise NATS::IO::SocketTimeoutError if limit && MonotonicTime.now >= limit
2263
+
2264
+ @unread << read_socket(MAX_SOCKET_READ_BYTES, limit)
2044
2265
  end
2045
- @socket.gets
2266
+ @unread.slice!(0, idx + 1)
2267
+ rescue EOFError
2268
+ nil
2046
2269
  end
2047
2270
 
2048
2271
  def read(max_bytes, deadline = nil)
2049
- begin
2050
- @socket.read_nonblock(max_bytes)
2051
- rescue ::IO::WaitReadable
2052
- if ::IO.select([@socket], nil, nil, deadline)
2053
- retry
2054
- else
2055
- raise NATS::IO::SocketTimeoutError
2056
- end
2057
- rescue ::IO::WaitWritable
2058
- if ::IO.select(nil, [@socket], nil, deadline)
2059
- retry
2060
- else
2061
- raise NATS::IO::SocketTimeoutError
2062
- end
2063
- end
2272
+ # Hand over what read_line read beyond its last line first.
2273
+ return @unread.slice!(0, max_bytes) if @unread && !@unread.empty?
2274
+
2275
+ read_socket(max_bytes, deadline && MonotonicTime.now + deadline)
2064
2276
  rescue EOFError => e
2065
2277
  if (RUBY_ENGINE == "jruby") && (e.message == "No message available")
2066
2278
  # FIXME: <EOFError: No message available> can happen in jruby
@@ -2117,6 +2329,160 @@ module NATS
2117
2329
 
2118
2330
  private
2119
2331
 
2332
+ # limit: a MonotonicTime.now value, or nil to wait without one. A TLS
2333
+ # socket can be readable and still raise IO::WaitReadable until the
2334
+ # rest of a record comes, so each wait takes only the time left.
2335
+ def read_socket(max_bytes, limit)
2336
+ @socket.read_nonblock(max_bytes)
2337
+ rescue ::IO::WaitReadable
2338
+ if ::IO.select([@socket], nil, nil, time_left(limit))
2339
+ retry
2340
+ else
2341
+ raise NATS::IO::SocketTimeoutError
2342
+ end
2343
+ rescue ::IO::WaitWritable
2344
+ if ::IO.select(nil, [@socket], nil, time_left(limit))
2345
+ retry
2346
+ else
2347
+ raise NATS::IO::SocketTimeoutError
2348
+ end
2349
+ end
2350
+
2351
+ # The seconds until limit, or nil without one. Raises
2352
+ # NATS::IO::SocketTimeoutError once limit has passed.
2353
+ def time_left(limit)
2354
+ return nil unless limit
2355
+
2356
+ left = limit - MonotonicTime.now
2357
+ raise NATS::IO::SocketTimeoutError if left <= 0
2358
+
2359
+ left
2360
+ end
2361
+
2362
+ # A context checks only what it is set up to check: one made with
2363
+ # OpenSSL::SSL::SSLContext.new checks nothing, and jruby-openssl before
2364
+ # 0.19.0 checks no name during the handshake. So the client checks the
2365
+ # chain and the name after every handshake, before it sends anything.
2366
+ def verify_server!(tls_socket)
2367
+ # jruby-openssl keeps the result of the last check per context, so
2368
+ # after a resumed session, or with another handshake on the same
2369
+ # context, the result can be that of another server. With VERIFY_PEER
2370
+ # it fails the handshake when the chain does not verify.
2371
+ if RUBY_ENGINE == "jruby"
2372
+ if (tls_socket.context.verify_mode.to_i & OpenSSL::SSL::VERIFY_PEER).zero?
2373
+ raise OpenSSL::SSL::SSLError, "certificate verify failed (the context does not set VERIFY_PEER) for #{@uri.host}:#{@uri.port}"
2374
+ end
2375
+ elsif (result = tls_socket.verify_result) != OpenSSL::X509::V_OK
2376
+ # A context with verify_hostname but without VERIFY_PEER completes
2377
+ # the handshake after the name check failed.
2378
+ raise OpenSSL::SSL::SSLError, name_check_failed(tls_socket.peer_cert) if name_check_failed?(tls_socket)
2379
+ raise OpenSSL::SSL::SSLError, "certificate verify failed (#{verify_error_string(result)}) for #{@uri.host}:#{@uri.port}"
2380
+ end
2381
+
2382
+ cert = tls_socket.peer_cert
2383
+ unless certificate_identity?(cert, @tls[:hostname])
2384
+ raise OpenSSL::SSL::SSLError, name_check_failed(cert)
2385
+ end
2386
+ rescue
2387
+ tls_socket.close
2388
+ raise
2389
+ end
2390
+
2391
+ # Whether the certificate is issued for name, by the rules of CRuby's
2392
+ # OpenSSL::SSL.verify_certificate_identity: the DNS names and IP
2393
+ # addresses of subjectAltName, else the common name. That of
2394
+ # jruby-openssl before 0.19.0 compares the printed names, in which ::1
2395
+ # is 0:0:0:0:0:0:0:1.
2396
+ def certificate_identity?(cert, name)
2397
+ return false unless cert
2398
+
2399
+ ip = begin
2400
+ IPAddr.new(name).hton
2401
+ rescue IPAddr::Error
2402
+ nil
2403
+ end
2404
+ sans = subject_alt_names(cert).select { |san| san.tag == 2 || san.tag == 7 }
2405
+ if sans.empty?
2406
+ return cert.subject.to_a.any? { |oid, value| oid == "CN" && OpenSSL::SSL.verify_hostname(name, value) }
2407
+ end
2408
+
2409
+ sans.any? { |san| (san.tag == 2) ? OpenSSL::SSL.verify_hostname(name, san.value) : san.value == ip }
2410
+ rescue OpenSSL::ASN1::ASN1Error
2411
+ false
2412
+ end
2413
+
2414
+ # The GeneralName entries of the certificate's subjectAltName: tag 2 is
2415
+ # a DNS name, tag 7 an IP address in network byte order.
2416
+ def subject_alt_names(cert)
2417
+ cert.extensions.select { |ext| ext.oid == "subjectAltName" }.flat_map do |ext|
2418
+ ostr = OpenSSL::ASN1.decode(ext.to_der).value.last
2419
+ OpenSSL::ASN1.decode(ostr.value).value
2420
+ end
2421
+ end
2422
+
2423
+ # Whether the handshake failed on the name: on CRuby a context with
2424
+ # verify_hostname checks it during the handshake.
2425
+ def name_check_failed?(tls_socket)
2426
+ defined?(OpenSSL::X509::V_ERR_HOSTNAME_MISMATCH) &&
2427
+ tls_socket.verify_result == OpenSSL::X509::V_ERR_HOSTNAME_MISMATCH
2428
+ end
2429
+
2430
+ # The error for a certificate that is not issued for the name the
2431
+ # server is verified against: that name, the names the certificate is
2432
+ # issued for (at most four) and the setting for the name. Without the
2433
+ # certificate it leaves the names out: OpenSSL 1.1 keeps none when the
2434
+ # name check fails during the handshake. For a discovered server, also
2435
+ # what the cluster can advertise instead, and the setting for
2436
+ # certificates that carry the server's IP address.
2437
+ def name_check_failed(cert)
2438
+ names = cert ? certificate_names(cert) : []
2439
+ text = "hostname #{@tls[:hostname].inspect} does not match the server certificate of #{@uri.host}:#{@uri.port}"
2440
+ if cert
2441
+ issued_for = names.empty? ? "no name" : names.first(4).map(&:inspect).join(", ")
2442
+ issued_for += " and #{names.size - 4} more" if names.size > 4
2443
+ text += ", which is issued for #{issued_for}"
2444
+ end
2445
+ text += "; tls: {hostname:} sets the name every server is verified against"
2446
+ return text unless @tls[:discovered]
2447
+
2448
+ advertise = %w[ws wss].include?(@uri.scheme) ? "advertise in the websocket block of nats-server" : "client_advertise in nats-server"
2449
+ text += ", or each server of the cluster can advertise a name its certificate is issued for (#{advertise})"
2450
+ if issued_for_address?(names)
2451
+ text += ", or tls: {verify_discovered_servers_by_ip: true} verifies a discovered IP address against itself, " \
2452
+ "which is safe only where the CA that issued the certificates is not shared with others"
2453
+ end
2454
+ text
2455
+ end
2456
+
2457
+ # Whether names hold the IP address the server was dialed at.
2458
+ def issued_for_address?(names)
2459
+ names.include?(IPAddr.new(@uri.hostname).to_s)
2460
+ rescue IPAddr::Error
2461
+ false
2462
+ end
2463
+
2464
+ # The names certificate_identity? checks: the DNS names and IP
2465
+ # addresses of subjectAltName, else the common name.
2466
+ def certificate_names(cert)
2467
+ names = subject_alt_names(cert).filter_map do |san|
2468
+ case san.tag
2469
+ when 2 then san.value
2470
+ when 7 then IPAddr.new_ntoh(san.value).to_s if [4, 16].include?(san.value.bytesize)
2471
+ end
2472
+ end
2473
+ return names unless names.empty?
2474
+
2475
+ cert.subject.to_a.filter_map { |oid, value| value if oid == "CN" }
2476
+ rescue OpenSSL::ASN1::ASN1Error
2477
+ []
2478
+ end
2479
+
2480
+ def verify_error_string(code)
2481
+ store_ctx = OpenSSL::X509::StoreContext.new(OpenSSL::X509::Store.new)
2482
+ store_ctx.error = code
2483
+ store_ctx.error_string
2484
+ end
2485
+
2120
2486
  def connect_addrinfo(ai, port, timeout)
2121
2487
  sock = ::Socket.new(::Socket.const_get(ai[0]), ::Socket::SOCK_STREAM, 0)
2122
2488
  sockaddr = ::Socket.pack_sockaddr_in(port, ai[3])