httpclient 2.9.0 → 2.11.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.
@@ -42,7 +42,7 @@ unless defined?(SSLSocket)
42
42
  @outstr = @socket.getOutputStream
43
43
  @instr = BufferedInputStream.new(@socket.getInputStream)
44
44
  @buf = (' ' * BUF_SIZE).to_java_bytes
45
- @bufstr = ''
45
+ @bufstr = ''.dup
46
46
  end
47
47
 
48
48
  def close
@@ -128,6 +128,8 @@ unless defined?(SSLSocket)
128
128
  @bufstr << String.from_java_bytes(@buf, Encoding::BINARY)[0, size]
129
129
  end
130
130
  size
131
+ rescue java.net.SocketTimeoutException => e
132
+ raise HTTPClient::ReceiveTimeoutError.new(e.getMessage)
131
133
  rescue java.io.IOException => e
132
134
  raise OpenSSL::SSL::SSLError.new("#{e.class}: #{e.getMessage}")
133
135
  end
@@ -164,6 +166,10 @@ unless defined?(SSLSocket)
164
166
  @cert.getSubjectDN
165
167
  end
166
168
 
169
+ def public_key
170
+ @cert.getPublicKey
171
+ end
172
+
167
173
  def to_text
168
174
  @cert.toString
169
175
  end
@@ -346,7 +352,7 @@ unless defined?(SSLSocket)
346
352
  File.read(cert_source).each_line do |line|
347
353
  case line
348
354
  when /-----BEGIN CERTIFICATE-----/
349
- pem = ''
355
+ pem = ''.dup
350
356
  when /-----END CERTIFICATE-----/
351
357
  load_pem(pem)
352
358
  # keep parsing in case where multiple certificates in a file
@@ -570,6 +576,9 @@ unless defined?(SSLSocket)
570
576
  def ssl_connect(hostname)
571
577
  @ssl_socket.startHandshake
572
578
  ssl_session = @ssl_socket.getSession
579
+ if @config.verify? && !@config.verify_callback
580
+ @config.check_peer_certificates(ssl_session.getPeerCertificates)
581
+ end
573
582
  @peer_cert = JavaCertificate.new(ssl_session.getPeerCertificates.first)
574
583
  if $DEBUG
575
584
  warn("Protocol version: #{ssl_session.getProtocol}")
@@ -400,6 +400,7 @@ class HTTPClient
400
400
  if str && @debug_dev
401
401
  if str.index("\0")
402
402
  require 'hexdump'
403
+ str = str.dup
403
404
  str.force_encoding('BINARY') if str.respond_to?(:force_encoding)
404
405
  @debug_dev << HexDump.encode(str).join("\n")
405
406
  else
@@ -32,8 +32,36 @@ class HTTPClient
32
32
  #
33
33
  # HTTPClient.new { self.ssl_config.load_trust_ca }.get("https://...")
34
34
  #
35
+ # Secure operation on JRuby depends on keeping the JVM and its CA certificates
36
+ # up to date.
37
+ #
35
38
  # You may want to change trust anchor by yourself. Call clear_cert_store
36
39
  # then add_trust_ca for that purpose.
40
+ #
41
+ # == TLS certificate restrictions
42
+ #
43
+ # Blocked public keys are identified by their SPKI SHA-256 hashes in
44
+ # BLOCKED_SPKI_SHA256. The list covers eight eMudhra intermediate CA public
45
+ # keys whose corresponding private keys were compromised.
46
+ #
47
+ # With peer verification enabled and no custom verify_callback, HTTPClient
48
+ # rejects a connection before sending an HTTP request if any certificate
49
+ # supplied by the server contains a blocked eMudhra public key. This includes
50
+ # cross-signed certificates and extra certificates that are not used in the
51
+ # verification path, even when another valid path exists.
52
+ #
53
+ # Setting verify_mode to OpenSSL::SSL::VERIFY_NONE or nil disables this check.
54
+ # A custom verify_callback replaces the default verification policy, including
55
+ # the blocked public key check. The callback receives the underlying verifier's
56
+ # result and context. With peer verification enabled, its return value controls
57
+ # certificate verification.
58
+ # The caller is responsible for the custom callback's validation policy.
59
+ # Hostname verification is unchanged.
60
+ #
61
+ # On JRuby, this additional check may not detect blocked intermediates found
62
+ # only in a local trust store or obtained through JVM issuer retrieval (such as
63
+ # AIA when enabled). These paths depend on the JVM's certificate validation.
64
+ # See https://github.com/nahi/httpclient/issues/480 for background.
37
65
  class SSLConfig
38
66
  include HTTPClient::Util
39
67
  if SSLEnabled
@@ -89,6 +117,39 @@ class HTTPClient
89
117
 
90
118
  CIPHERS_DEFAULT = "ALL:!aNULL:!eNULL:!SSLv2" # OpenSSL >1.0.0 default
91
119
 
120
+ # Public keys whose SPKI SHA-256 hashes are listed below are considered blocked.
121
+ # The list covers eight eMudhra intermediate CA public keys whose corresponding
122
+ # private keys were compromised. Hashes use DER-encoded SubjectPublicKeyInfo,
123
+ # covering cross-signed variants.
124
+ # Includes six TLS keys and two code-signing keys.
125
+ # CA names are from CCADB's public intermediate certificate inventory:
126
+ # https://ccadb.my.salesforce-sites.com/mozilla/PublicAllIntermediateCertsWithPEMCSV
127
+ # Matches distrustedSPKIHashes in Go's crypto/x509 at:
128
+ # https://github.com/golang/go/blob/7f86f957633ee31a1c17a1eb8452ca7a3d9bc141/src/crypto/x509/verify.go
129
+ # Related Go mitigation: https://go.dev/issue/82345 (CVE-2026-111943).
130
+ BLOCKED_SPKI_SHA256 = [
131
+ # EM OV TLS CA - G3B
132
+ '43bffa19d6ef651451f6841e019931e96f6f2eaeff28ab4b6f1ce4576de2717b',
133
+ # EM DV TLS CA - G3C
134
+ '49dd353dc2b919a3770645117d0e60c16115e7d1bc259eefe734b00ea434fe5f',
135
+ # EM EV TLS CA - G3C
136
+ '5c0660a2b164910d8ff589c18e14552e9e0ec237dcefe2cb736d41a4811f81a0',
137
+ # EM OV TLS CA - G3C
138
+ '63ecefee431d49523bc1136c4e72d0206a477086caf606cd5cf025686c109cf8',
139
+ # EM OV CS CA - G3C
140
+ '92c063d67e8f14db71d288e11266ffdaf69cbf115f7bab14f3bc2f68d25e0e30',
141
+ # EM EV TLS CA - G3B
142
+ 'e0254c7fcdc265e2f0f8a428dabb75ab4ae039b4872d62f5ee57f0877d5a8a41',
143
+ # EM DV TLS CA - G3B
144
+ 'ebed6475c2c2d80fcb199f3fe8dd6e6b3ce60b77eb15d4e42c3dec0c6f5b5105',
145
+ # EM OV CS CA - G3B
146
+ 'ec4ffa1ad0ac88081314b7aaffef6a91f97cd57291bb5ba686c5415f5eb4f6b6',
147
+ ].map(&:freeze).freeze
148
+
149
+ def self.blocked_public_key?(public_key_der)
150
+ BLOCKED_SPKI_SHA256.include?(OpenSSL::Digest::SHA256.hexdigest(public_key_der))
151
+ end
152
+
92
153
  # Which TLS protocol version (also called method) will be used. Defaults
93
154
  # to :auto which means that OpenSSL decides (In my tests this resulted
94
155
  # with always the highest available protocol being used).
@@ -109,6 +170,7 @@ class HTTPClient
109
170
 
110
171
  # A number which represents OpenSSL's verify mode. Default value is
111
172
  # OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT.
173
+ # VERIFY_NONE or nil disables the default blocked public key check.
112
174
  attr_config :verify_mode
113
175
  # A number of verify depth. Certification path which length is longer than
114
176
  # this depth is not allowed.
@@ -119,6 +181,9 @@ class HTTPClient
119
181
  # OpenSSL's verification. handler.call is invoked with 2 arguments,
120
182
  # ok and ctx; ok is a result of general OpenSSL's verification. ctx is a
121
183
  # OpenSSL::X509::StoreContext.
184
+ # Setting a handler replaces the default verification policy, including its
185
+ # blocked public key check. The caller is responsible for the
186
+ # handler's validation policy. Hostname verification is unchanged.
122
187
  attr_config :verify_callback
123
188
  # SSL timeout in sec. nil by default.
124
189
  attr_config :timeout
@@ -311,6 +376,35 @@ class HTTPClient
311
376
  ctx.ssl_version = @ssl_version unless @ssl_version == :auto
312
377
  end
313
378
 
379
+ # Reject blocked public keys in the given certificate collection.
380
+ # Peer certificates are checked even when unused in the verification path.
381
+ def check_peer_certificates(certificates) # :nodoc:
382
+ certificates = certificates.to_a if certificates.respond_to?(:to_a)
383
+ certificates.each do |certificate|
384
+ public_key = if certificate.respond_to?(:public_key)
385
+ certificate.public_key
386
+ else
387
+ certificate.getPublicKey
388
+ end
389
+ public_key_der = if public_key.respond_to?(:getEncoded)
390
+ String.from_java_bytes(public_key.getEncoded)
391
+ elsif public_key.respond_to?(:public_to_der)
392
+ public_key.public_to_der
393
+ elsif public_key.respond_to?(:to_der)
394
+ public_key.to_der
395
+ else
396
+ # Older ruby-openssl cannot export generic PKey objects.
397
+ fields = OpenSSL::ASN1.decode(certificate.to_der).value[0].value
398
+ # The optional version field shifts SubjectPublicKeyInfo by one.
399
+ spki_index = fields[0].tag_class == :CONTEXT_SPECIFIC ? 6 : 5
400
+ fields[spki_index].to_der
401
+ end
402
+ if self.class.blocked_public_key?(public_key_der)
403
+ raise SSL::SSLError, 'certificate chain contains a blocked eMudhra public key'
404
+ end
405
+ end
406
+ end
407
+
314
408
  # post connection check proc for ruby < 1.8.5.
315
409
  # this definition must match with the one in ext/openssl/lib/openssl/ssl.rb
316
410
  def post_connection_check(peer_cert, hostname) # :nodoc:
@@ -340,8 +434,13 @@ class HTTPClient
340
434
  raise SSL::SSLError, "hostname was not match with the server certificate"
341
435
  end
342
436
 
343
- # Default callback for verification: only dumps error.
437
+ # Default callback: reject blocked public keys and report verification errors.
344
438
  def default_verify_callback(is_ok, ctx)
439
+ begin
440
+ check_peer_certificates(ctx.chain) if verify?
441
+ rescue SSL::SSLError
442
+ return false
443
+ end
345
444
  if $DEBUG
346
445
  if is_ok
347
446
  warn("ok: #{ctx.current_cert.subject.to_s.dump}")
@@ -101,6 +101,9 @@ class HTTPClient
101
101
  @ssl_socket.hostname = hostname
102
102
  end
103
103
  @ssl_socket.connect
104
+ if @config.verify? && !@config.verify_callback
105
+ @config.check_peer_certificates(@ssl_socket.peer_cert_chain)
106
+ end
104
107
  if $DEBUG
105
108
  if @ssl_socket.respond_to?(:ssl_version)
106
109
  warn("Protocol version: #{@ssl_socket.ssl_version}")
@@ -1,3 +1,3 @@
1
1
  class HTTPClient
2
- VERSION = '2.9.0'
2
+ VERSION = '2.11.0'
3
3
  end
data/lib/httpclient.rb CHANGED
@@ -1228,12 +1228,26 @@ private
1228
1228
  false
1229
1229
  end
1230
1230
 
1231
+ # Proxy authentication is only for forwarding requests. HTTPS authenticates
1232
+ # CONNECT separately in Session#connect_ssl_proxy, not the origin request
1233
+ # inside the tunnel. Use the same filters for the request and its response.
1234
+ def filter_request(req, proxy)
1235
+ proxy_request = proxy && !https?(req.header.request_uri)
1236
+ filters = @request_filter.reject { |filter|
1237
+ !proxy_request && filter.equal?(@proxy_auth)
1238
+ }
1239
+ filters.each do |filter|
1240
+ filter.filter_request(req)
1241
+ end
1242
+ # Also remove explicit values, including those added by custom filters.
1243
+ req.header.delete('Proxy-Authorization') unless proxy_request
1244
+ filters
1245
+ end
1246
+
1231
1247
  # !! CAUTION !!
1232
1248
  # Method 'do_get*' runs under MT conditon. Be careful to change.
1233
1249
  def do_get_block(req, proxy, conn, &block)
1234
- @request_filter.each do |filter|
1235
- filter.filter_request(req)
1236
- end
1250
+ filters = filter_request(req, proxy)
1237
1251
  if str = @test_loopback_response.shift
1238
1252
  dump_dummy_request_response(req.http_body.dump, str) if @debug_dev
1239
1253
  res = HTTP::Message.new_response(str, req.header)
@@ -1259,7 +1273,7 @@ private
1259
1273
  # there could be a race condition but it's OK to cache unreusable
1260
1274
  # connection because we do retry for that case.
1261
1275
  @session_manager.keep(sess) unless sess.closed?
1262
- commands = @request_filter.collect { |filter|
1276
+ commands = filters.collect { |filter|
1263
1277
  filter.filter_response(req, res)
1264
1278
  }
1265
1279
  if commands.find { |command| command == :retry }
@@ -1269,9 +1283,7 @@ private
1269
1283
  end
1270
1284
 
1271
1285
  def do_get_stream(req, proxy, conn)
1272
- @request_filter.each do |filter|
1273
- filter.filter_request(req)
1274
- end
1286
+ filters = filter_request(req, proxy)
1275
1287
  if str = @test_loopback_response.shift
1276
1288
  dump_dummy_request_response(req.http_body.dump, str) if @debug_dev
1277
1289
  conn.push(HTTP::Message.new_response(StringIO.new(str), req.header))
@@ -1292,7 +1304,7 @@ private
1292
1304
  end
1293
1305
  pipew.close
1294
1306
  @session_manager.keep(sess) unless sess.closed?
1295
- _ = @request_filter.collect { |filter|
1307
+ _ = filters.collect { |filter|
1296
1308
  filter.filter_response(req, res)
1297
1309
  }
1298
1310
  # ignore commands (not retryable in async mode)
@@ -0,0 +1,47 @@
1
+ # EM DV TLS CA - G3B, signed by emSign Root TLS CA - G3 and AAA Certificate Services.
2
+ # Public certificates from https://emudhra.we-have-a-problem.com/chains.zip
3
+ # SPKI SHA-256: ebed6475c2c2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CsGAQUFBwMC
37
+ MDEGA1UdIAQqMCgwCAYGZ4EMAQIBMA0GCysGAQQBg44hAQABMA0GCysGAQQBg44h
38
+ AQJkMEMGA1UdHwQ8MDowOKA2oDSGMmh0dHA6Ly9jcmwuY29tb2RvY2EuY29tL0FB
39
+ QUNlcnRpZmljYXRlU2VydmljZXMuY3JsMDQGCCsGAQUFBwEBBCgwJjAkBggrBgEF
40
+ BQcwAYYYaHR0cDovL29jc3AuY29tb2RvY2EuY29tMA0GCSqGSIb3DQEBCwUAA4IB
41
+ AQBzQ1IoqpdotM6gFrR4Q3YrKifOLeaj5XXunldpVE/vZn2TxC2y0s8oYiLR5ICE
42
+ wqVXSB7N6BM1Mp+Nif7Jbhb2IswAfSR4Iik8+B0iRmi7lYoNlycCgHjmsjOmZaxM
43
+ QkPmjXAJbG5f4V41OsvJZmS7lI3r0IuvEDVX3GAZ13on6IImSs9ybNpHQ7NCqkMQ
44
+ 7wH4uAO1dtpFycgJSdHaCOhHjrox2BTYGLdpUrYwY3EOAjlZ8UGgsxs7mG+xquMl
45
+ bN1LFURwfnkVMP3T/DBIZ/ys2+lNFyxK3FlArrV4/000uTnVB1lO8oGORYdXoT5V
46
+ GUyRCEIDhF5TBUuKF4E3kf1h
47
+ -----END CERTIFICATE-----
data/test/helper.rb CHANGED
@@ -6,19 +6,73 @@ require 'webrick'
6
6
  require 'webrick/httpproxy.rb'
7
7
  require 'logger'
8
8
  require 'stringio'
9
- require 'cgi'
9
+ begin
10
+ require 'cgi/escape'
11
+ rescue LoadError
12
+ require 'cgi'
13
+ end
10
14
  require 'webrick/httputils'
11
15
 
16
+ if RUBY_ENGINE == 'jruby'
17
+ require 'webrick/https'
18
+ require 'delegate'
19
+
20
+ module JRubyWEBrickSSLReadBuffer
21
+ class ReadableIO < SimpleDelegator
22
+ def initialize(socket)
23
+ @ssl_socket = socket
24
+ super(socket.to_io)
25
+ end
26
+
27
+ def wait_readable(timeout = nil)
28
+ # JRuby may buffer request bytes while completing the TLS handshake.
29
+ @ssl_socket.pending > 0 || super
30
+ end
31
+ end
32
+
33
+ module HTTPServerPatch
34
+ def run(sock)
35
+ if sock.respond_to?(:pending)
36
+ readable_io = ReadableIO.new(sock)
37
+ sock.define_singleton_method(:to_io) { readable_io }
38
+ end
39
+ super
40
+ ensure
41
+ sock.singleton_class.remove_method(:to_io) if readable_io
42
+ end
43
+ end
44
+
45
+ module HTTPRequestPatch
46
+ def parse(socket = nil)
47
+ skip_peer_cert_chain = socket.respond_to?(:peer_cert_chain) &&
48
+ socket.respond_to?(:peer_cert) && socket.peer_cert.nil?
49
+ if skip_peer_cert_chain
50
+ # WEBrick asks JRuby for a peer chain even when no client certificate was sent.
51
+ socket.define_singleton_method(:peer_cert_chain) { nil }
52
+ end
53
+ super
54
+ ensure
55
+ socket.singleton_class.remove_method(:peer_cert_chain) if skip_peer_cert_chain
56
+ end
57
+ end
58
+ end
59
+
60
+ WEBrick::HTTPServer.prepend(JRubyWEBrickSSLReadBuffer::HTTPServerPatch)
61
+ WEBrick::HTTPRequest.prepend(JRubyWEBrickSSLReadBuffer::HTTPRequestPatch)
62
+ end
63
+
12
64
 
13
65
  module Helper
14
66
  Port = 17171
15
67
  ProxyPort = 17172
16
68
 
17
69
  def serverport
70
+ setup_server unless @server
18
71
  @serverport
19
72
  end
20
73
 
21
74
  def proxyport
75
+ setup_proxyserver unless @proxyserver
22
76
  @proxyport
23
77
  end
24
78
 
@@ -43,9 +97,15 @@ module Helper
43
97
  end
44
98
 
45
99
  def teardown
46
- teardown_client if @client
47
- teardown_proxyserver if @proxyserver
48
- teardown_server if @server
100
+ begin
101
+ teardown_client if @client
102
+ ensure
103
+ begin
104
+ teardown_proxyserver if @proxyserver
105
+ ensure
106
+ teardown_server if @server
107
+ end
108
+ end
49
109
  end
50
110
 
51
111
  def setup_client
@@ -82,12 +142,12 @@ module Helper
82
142
 
83
143
  def teardown_server
84
144
  @server.shutdown
85
- #@server_thread.kill
145
+ @server_thread.join if @server_thread
86
146
  end
87
147
 
88
148
  def teardown_proxyserver
89
149
  @proxyserver.shutdown
90
- #@proxyserver_thread.kill
150
+ @proxyserver_thread.join if @proxyserver_thread
91
151
  end
92
152
 
93
153
  def start_server_thread(server)
@@ -0,0 +1,30 @@
1
+ require File.expand_path('../helper', File.dirname(__FILE__))
2
+
3
+
4
+ class JRubyMutableBuffersTest < Test::Unit::TestCase
5
+ def setup
6
+ omit('JRuby-specific test') unless RUBY_ENGINE == 'jruby'
7
+ end
8
+
9
+ def test_socket_reads_using_mutable_buffer
10
+ input = Java::JavaIo::ByteArrayInputStream.new("hello\nworld".to_java_bytes)
11
+ output = Java::JavaIo::ByteArrayOutputStream.new
12
+ socket = Object.new
13
+ socket.define_singleton_method(:getInputStream) { input }
14
+ socket.define_singleton_method(:getOutputStream) { output }
15
+ wrapped_socket = HTTPClient::JavaSocketWrap.new(socket)
16
+
17
+ assert_equal("hello\n", wrapped_socket.gets("\n"))
18
+ assert_equal('wo', wrapped_socket.read(2))
19
+ assert_equal('rld', wrapped_socket.readpartial(3))
20
+ assert_raise(EOFError) { wrapped_socket.readpartial(1) }
21
+ end
22
+
23
+ def test_trust_store_loads_multiple_pem_certificates
24
+ loader = HTTPClient::JRubySSLSocket::TrustStoreLoader.new
25
+ loader.add(File.expand_path('../ca-chain.pem', File.dirname(__FILE__)))
26
+
27
+ assert_equal(2, loader.size)
28
+ assert_equal(2, loader.trust_store.size)
29
+ end
30
+ end
@@ -5,26 +5,27 @@ class PEMUtilsTest < Test::Unit::TestCase
5
5
  include Helper
6
6
 
7
7
  def setup
8
+ omit('JRuby-specific test') unless RUBY_ENGINE == 'jruby'
8
9
  @raw_cert = "-----BEGIN CERTIFICATE-----\nMIIDOTCCAiGgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBCMRMwEQYKCZImiZPyLGQB\nGRYDb3JnMRkwFwYKCZImiZPyLGQBGRYJcnVieS1sYW5nMRAwDgYDVQQDDAdSdWJ5\nIENBMB4XDTE2MDgxMDE3MjEzNFoXDTE3MDgxMDE3MjEzNFowSzETMBEGCgmSJomT\n8ixkARkWA29yZzEZMBcGCgmSJomT8ixkARkWCXJ1YnktbGFuZzEZMBcGA1UEAwwQ\nUnVieSBjZXJ0aWZpY2F0ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\nAJCfsSXpSMpmZCVa+ZCM+QDgomnhDlvnrGDq6pasTaIspGTXgws+7r8Dt/cNe6EH\nHJpRH2cGRiO4yPcfcT9eS4X7k8OC4f33wHfACOmLu6LeoNE8ujmSk6L6WzLUI+sE\nnLZbFrXxoAo4XHsm8vEG9C+jEoXZ1p+47wrAGaDwDQTnzlMy4dT9pRQEJP2G/Rry\nUkuZn8SUWmh3/YS78iaSzsNF1cgE1ealHOrPPFDjiCGDaH/LHyUPYlbFSLZ/B7Qx\nLxi5sePLcywWq/EJrmWpgeVTDjtNijsdKv/A3qkY+fm/oD0pzt7XsfJaP9YKNyJO\nQFdxWZeiPcDF+Hwf+IwSr+kCAwEAAaMxMC8wDgYDVR0PAQH/BAQDAgeAMB0GA1Ud\nDgQWBBQNvzYzJyXemGhxbA8NMXLolDnPyjANBgkqhkiG9w0BAQsFAAOCAQEARIJV\noKejGlOTn71QutnNnu07UtTu0IHs6YqjYzzND+m4JXLN+wvYm72AFUG0b1L7dRg0\niK8XjQrlNQNVqP1Mc6tffchy20neOPOHeiO6qTdRU8P2S8D3Uwe+1qhgxjfE+cWc\nwZmWxYK4HA8c58PxWMqrkr2QqXDplG9KWLvOgrtPGiLLZcQSKhvvB63QzItHBDU6\nRayiJY3oPkK/HrIvFlySqFqzWmuyknkciOFywEHQMz/tcSFJ2QFpPj/tBz9VXohH\nZ8KscmfhZrTPBjo+ky1lz/WraWoz4LMiLnkC2ABczWLRSawu+v3Irx1NFJngt05e\npqwtqIUeg7j+JLiTaA==\n-----END CERTIFICATE-----"
9
10
  end
10
11
 
11
12
  def test_read_certificate
12
13
  assert_nothing_raised do
13
- binary = HTTPClient::JRubySSLSocket::PEMUtils.read_certificate(@raw_cert)
14
+ HTTPClient::JRubySSLSocket::PEMUtils.read_certificate(@raw_cert)
14
15
  end
15
16
  end
16
17
 
17
18
  def test_read_certificate_works_with_random_ascii_text_outside_begin_end
18
19
  raw_cert_with_ascii = "some text before begin\n" + @raw_cert + "\nsome text after end"
19
20
  assert_nothing_raised do
20
- binary = HTTPClient::JRubySSLSocket::PEMUtils.read_certificate(raw_cert_with_ascii)
21
+ HTTPClient::JRubySSLSocket::PEMUtils.read_certificate(raw_cert_with_ascii)
21
22
  end
22
23
  end
23
24
 
24
25
  def test_read_certificate_uses_all_content_if_missing_begin_end
25
26
  cert = @raw_cert.sub(/-----BEGIN CERTIFICATE-----/, '').sub(/-----END CERTIFICATE-----/, '')
26
27
  assert_nothing_raised do
27
- binary = HTTPClient::JRubySSLSocket::PEMUtils.read_certificate(cert)
28
+ HTTPClient::JRubySSLSocket::PEMUtils.read_certificate(cert)
28
29
  end
29
30
  end
30
31
 
@@ -0,0 +1,19 @@
1
+ require File.expand_path('../helper', File.dirname(__FILE__))
2
+
3
+
4
+ class JRubySocketTimeoutTest < Test::Unit::TestCase
5
+ def test_read_timeout_is_reported_as_receive_timeout
6
+ omit('JRuby-specific test') unless RUBY_ENGINE == 'jruby'
7
+ socket = HTTPClient::JavaSocketWrap.allocate
8
+ input = Object.new
9
+ input.define_singleton_method(:read) do |_buffer|
10
+ raise Java::JavaNet::SocketTimeoutException.new('Read timed out')
11
+ end
12
+ socket.instance_variable_set(:@instr, input)
13
+ socket.instance_variable_set(:@buf, Java::byte[HTTPClient::JavaSocketWrap::BUF_SIZE].new)
14
+
15
+ assert_raise(HTTPClient::ReceiveTimeoutError) do
16
+ socket.send(:fill)
17
+ end
18
+ end
19
+ end
data/test/test_auth.rb CHANGED
@@ -2,7 +2,14 @@ require File.expand_path('helper', File.dirname(__FILE__))
2
2
  require 'digest/md5'
3
3
  require 'rack'
4
4
  require 'rack/lint'
5
- require 'rack-ntlm'
5
+ # rack-ntlm-test-service 0.0.1 assigns an unused rescue variable while loading.
6
+ original_verbose = $VERBOSE
7
+ begin
8
+ $VERBOSE = nil
9
+ require 'rack-ntlm'
10
+ ensure
11
+ $VERBOSE = original_verbose
12
+ end
6
13
 
7
14
  class TestAuth < Test::Unit::TestCase
8
15
  include Helper
@@ -95,12 +102,15 @@ class TestAuth < Test::Unit::TestCase
95
102
  end
96
103
 
97
104
  def do_basic_auth(req, res)
105
+ # Drain uploads before an authentication challenge can close the connection.
106
+ req.body
98
107
  @basic_auth.authenticate(req, res)
99
108
  res['content-type'] = 'text/plain'
100
109
  res.body = 'basic_auth OK'
101
110
  end
102
111
 
103
112
  def do_digest_auth(req, res)
113
+ req.body
104
114
  @digest_auth.authenticate(req, res)
105
115
  res['content-type'] = 'text/plain'
106
116
  res['x-query'] = req.body
@@ -108,6 +118,7 @@ class TestAuth < Test::Unit::TestCase
108
118
  end
109
119
 
110
120
  def do_digest_sess_auth(req, res)
121
+ req.body
111
122
  @digest_sess_auth.authenticate(req, res)
112
123
  res['content-type'] = 'text/plain'
113
124
  res['x-query'] = req.body
@@ -128,6 +139,7 @@ class TestAuth < Test::Unit::TestCase
128
139
  @active && @value ? @value.size : 0
129
140
  end
130
141
 
142
+ remove_method(:value) if method_defined?(:value)
131
143
  def value
132
144
  @value ||= ""
133
145
  end
@@ -327,7 +339,7 @@ class TestAuth < Test::Unit::TestCase
327
339
  end
328
340
 
329
341
  def test_proxy_auth
330
- c = HTTPClient.new
342
+ c = HTTPClient.new('http://proxy.example.com:8080')
331
343
  c.set_proxy_auth('admin', 'admin')
332
344
  c.test_loopback_http_response << "HTTP/1.0 407 Unauthorized\nProxy-Authenticate: Basic realm=\"foo\"\nContent-Length: 2\n\nNG"
333
345
  c.test_loopback_http_response << "HTTP/1.0 200 OK\nContent-Length: 2\n\nOK"
@@ -337,7 +349,7 @@ class TestAuth < Test::Unit::TestCase
337
349
  end
338
350
 
339
351
  def test_proxy_auth_force
340
- c = HTTPClient.new
352
+ c = HTTPClient.new('http://proxy.example.com:8080')
341
353
  c.set_proxy_auth('admin', 'admin')
342
354
  c.force_basic_auth = true
343
355
  c.test_loopback_http_response << "HTTP/1.0 200 OK\nContent-Length: 2\n\nOK"
@@ -347,7 +359,7 @@ class TestAuth < Test::Unit::TestCase
347
359
  end
348
360
 
349
361
  def test_proxy_auth_reuses_credentials
350
- c = HTTPClient.new
362
+ c = HTTPClient.new('http://proxy.example.com:8080')
351
363
  c.set_proxy_auth('admin', 'admin')
352
364
  c.test_loopback_http_response << "HTTP/1.0 407 Unauthorized\nProxy-Authenticate: Basic realm=\"foo\"\nContent-Length: 2\n\nNG"
353
365
  c.test_loopback_http_response << "HTTP/1.0 200 OK\nContent-Length: 2\n\nOK"
@@ -359,7 +371,7 @@ class TestAuth < Test::Unit::TestCase
359
371
  end
360
372
 
361
373
  def test_digest_proxy_auth_loop
362
- c = HTTPClient.new
374
+ c = HTTPClient.new('http://proxy.example.com:8080')
363
375
  c.set_proxy_auth('admin', 'admin')
364
376
  c.test_loopback_http_response << "HTTP/1.0 407 Unauthorized\nProxy-Authenticate: Digest realm=\"foo\", nonce=\"nonce\", stale=false\nContent-Length: 2\n\nNG"
365
377
  c.test_loopback_http_response << "HTTP/1.0 200 OK\nContent-Length: 2\n\nOK"
@@ -390,7 +402,7 @@ class TestAuth < Test::Unit::TestCase
390
402
  end
391
403
 
392
404
  def test_prefer_digest_to_basic_proxy_auth
393
- c = HTTPClient.new
405
+ c = HTTPClient.new('http://proxy.example.com:8080')
394
406
  c.set_proxy_auth('admin', 'admin')
395
407
  c.test_loopback_http_response << "HTTP/1.0 407 Unauthorized\nProxy-Authenticate: Digest realm=\"foo\", nonce=\"nonce\", stale=false\nProxy-Authenticate: Basic realm=\"bar\"\nContent-Length: 2\n\nNG"
396
408
  c.test_loopback_http_response << "HTTP/1.0 200 OK\nContent-Length: 2\n\nOK"
@@ -405,7 +417,7 @@ class TestAuth < Test::Unit::TestCase
405
417
  end
406
418
 
407
419
  def test_digest_proxy_auth_reuses_credentials
408
- c = HTTPClient.new
420
+ c = HTTPClient.new('http://proxy.example.com:8080')
409
421
  c.set_proxy_auth('admin', 'admin')
410
422
  c.test_loopback_http_response << "HTTP/1.0 407 Unauthorized\nProxy-Authenticate: Digest realm=\"foo\", nonce=\"nonce\", stale=false\nContent-Length: 2\n\nNG"
411
423
  c.test_loopback_http_response << "HTTP/1.0 200 OK\nContent-Length: 2\n\nOK"
@@ -0,0 +1,42 @@
1
+ require File.expand_path('test_auth', File.dirname(__FILE__))
2
+
3
+ class TestAuthFixture < Test::Unit::TestCase
4
+ Request = Struct.new(:events) do
5
+ def body
6
+ events << :read_body
7
+ 'upload body'
8
+ end
9
+ end
10
+
11
+ Authenticator = Struct.new(:events) do
12
+ def authenticate(_request, _response)
13
+ events << :authenticate
14
+ raise WEBrick::HTTPStatus::Unauthorized
15
+ end
16
+ end
17
+
18
+ def test_basic_auth_drains_body_before_challenge
19
+ assert_body_drained_before_challenge(:basic_auth)
20
+ end
21
+
22
+ def test_digest_auth_drains_body_before_challenge
23
+ assert_body_drained_before_challenge(:digest_auth)
24
+ end
25
+
26
+ def test_digest_sess_auth_drains_body_before_challenge
27
+ assert_body_drained_before_challenge(:digest_sess_auth)
28
+ end
29
+
30
+ private
31
+
32
+ def assert_body_drained_before_challenge(kind)
33
+ events = []
34
+ fixture = TestAuth.allocate
35
+ fixture.instance_variable_set("@#{kind}", Authenticator.new(events))
36
+
37
+ assert_raise(WEBrick::HTTPStatus::Unauthorized) do
38
+ fixture.send("do_#{kind}", Request.new(events), Object.new)
39
+ end
40
+ assert_equal([:read_body, :authenticate], events)
41
+ end
42
+ end