summaryrefslogtreecommitdiff
path: root/test/webrick/test_ssl_server.rb
blob: 4e52598bf59cc2f5bf1fc33f402069f2cad171d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
require "test/unit"
require "webrick"
require "webrick/ssl"
require_relative "utils"
require 'timeout'

class TestWEBrickSSLServer < Test::Unit::TestCase
  class Echo < WEBrick::GenericServer
    def run(sock)
      while line = sock.gets
        sock << line
      end
    end
  end

  def test_self_signed_cert_server
    assert_self_signed_cert(
      :SSLEnable => true,
      :SSLCertName => [["C", "JP"], ["O", "www.ruby-lang.org"], ["CN", "Ruby"]],
    )
  end

  def test_self_signed_cert_server_with_string
    assert_self_signed_cert(
      :SSLEnable => true,
      :SSLCertName => "/C=JP/O=www.ruby-lang.org/CN=Ruby",
    )
  end

  def assert_self_signed_cert(config)
    TestWEBrick.start_server(Echo, config){|server, addr, port, log|
      io = TCPSocket.new(addr, port)
      sock = OpenSSL::SSL::SSLSocket.new(io)
      sock.connect
      sock.puts(server.ssl_context.cert.subject.to_s)
      assert_equal("/C=JP/O=www.ruby-lang.org/CN=Ruby\n", sock.gets, log.call)
      sock.close
      io.close
    }
  end

  def test_slow_connect
    poke = lambda do |io, msg|
      begin
        sock = OpenSSL::SSL::SSLSocket.new(io)
        sock.connect
        sock.puts(msg)
        assert_equal "#{msg}\n", sock.gets, msg
      ensure
        sock&.close
        io.close
      end
    end
    config = {
      :SSLEnable => true,
      :SSLCertName => "/C=JP/O=www.ruby-lang.org/CN=Ruby",
    }
    EnvUtil.timeout(10) do
      TestWEBrick.start_server(Echo, config) do |server, addr, port, log|
        outer = TCPSocket.new(addr, port)
        inner = TCPSocket.new(addr, port)
        poke.call(inner, 'fast TLS negotiation')
        poke.call(outer, 'slow TLS negotiation')
      end
    end
  end
end