Class: Aspera::WebServerSimple

Inherits:
WEBrick::HTTPServer
  • Object
show all
Defined in:
lib/aspera/web_server_simple.rb

Overview

Simple WEBrick server with HTTPS support

Direct Known Subclasses

Aspera::WebAuth::Server

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri, cert: nil, key: nil, chain: nil) ⇒ WebServerSimple

Returns a new instance of WebServerSimple.

Parameters:

  • uri (URI) —

    Local address where server will listen (use scheme, host and port only), port 0 for any free port

  • cert (String) (defaults to: nil) —

    Path to certificate file, either with extension .p12 or .pfx, else assumed PEM

  • key (String) (defaults to: nil) —

    Path to key file (PEM) or passphrase (pkcs12)

  • chain (String) (defaults to: nil) —

    Path to certificate chain file (PEM only)



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/aspera/web_server_simple.rb', line 117

def initialize(uri, cert: nil, key: nil, chain: nil)
  Aspera.assert_type(uri, URI)
  @uri = uri.dup
  # see https://www.rubydoc.info/stdlib/webrick/WEBrick/Config
  webrick_options = {
    # without brackets of IPv6 address
    BindAddress: @uri.hostname,
    Port:        @uri.port,
    Logger:      WebrickLogger.new(Log.log),
    AccessLog:   [[self, WEBrick::AccessLog::COMMON_LOG_FORMAT]] # replace default access log to call local method "<<" below
  }
  case @uri.scheme
  when 'http'
    Log.log.debug('HTTP mode')
  when 'https'
    # Required lazily: webrick/ssl.rb reads OpenSSL::OPENSSL_VERSION at load time,
    # a constant CosmoRuby's OpenSSL shim does not define, so requiring it
    # unconditionally at file load would break any command in a Cosmo build
    # even when no HTTPS server is ever started.
    require 'webrick/https'
    webrick_options[:SSLEnable] = true
    if cert.nil? && key.nil?
      webrick_options[:SSLCertName] = [['CN', WEBrick::Utils.getservername]]
    elsif cert && PKCS12_EXT.include?(File.extname(cert).downcase)
      # PKCS12
      Log.log.debug('Using PKCS12 certificate')
      Aspera.assert(!key.nil?, type: ParameterError) { 'PKCS12 requires a key (password)' }
      pkcs12 = OpenSSL::PKCS12.new(File.read(cert), key)
      webrick_options[:SSLCertificate] = pkcs12.certificate
      webrick_options[:SSLPrivateKey] = pkcs12.key
      webrick_options[:SSLExtraChainCert] = pkcs12.ca_certs
    else
      Log.log.debug('Using PEM certificate')
      webrick_options[:SSLPrivateKey] = if key.nil?
        OpenSSL::PKey::RSA.new(4096)
      else
        OpenSSL::PKey::RSA.new(File.read(key))
      end
      webrick_options[:SSLCertificate] = if cert.nil?
        self.class.self_signed_cert(webrick_options[:SSLPrivateKey])
      else
        OpenSSL::X509::Certificate.new(File.read(cert))
      end
      webrick_options[:SSLExtraChainCert] = self.class.read_chain_file(chain) unless chain.nil?
      Aspera.assert(webrick_options[:SSLCertificate].public_key.to_der == webrick_options[:SSLPrivateKey].public_key.to_der, type: ParameterError) { 'key and cert do not match' }
    end
  end
  # call constructor of parent class, but capture STDERR
  # self signed certificate generates characters on STDERR
  # see create_self_signed_cert in webrick/ssl.rb
  Log.capture_stderr { super(webrick_options) }
  @uri.port = config[:Port]
end

Instance Attribute Details

#uri ⇒ URI (readonly)

Returns URL of the server, with the port it listens on: any free port if 0 was given.

Returns:

  • (URI) —

    URL of the server, with the port it listens on: any free port if 0 was given



34
35
36
# File 'lib/aspera/web_server_simple.rb', line 34

def uri
  @uri
end

Class Method Details

.assert_protected(host, protected:, what:, type: ParameterError) ⇒ Object

Refuse a server without protection reachable from the network: anyone could call it

Parameters:

  • host (String) —

    Host name or IP address the server listens on

  • protected (Boolean) —

    true if requests are authenticated or restricted

  • what (String) —

    Parameters that protect the server, for the error message

  • type (Exception) (defaults to: ParameterError) —

    Exception to raise

Raises:

  • (Exception) —

    if not protected and host is not a loopback address



79
80
81
82
83
# File 'lib/aspera/web_server_simple.rb', line 79

def assert_protected(host, protected:, what:, type: ParameterError)
  Aspera.assert(protected || loopback?(host), type: type) do
    "#{what} is required when the server listens on an address that is not loopback (localhost, 127.0.0.0/8, ::1): #{host}"
  end
end

.loopback?(host) ⇒ Boolean

Returns true if the server is reachable from the local host only.

Parameters:

  • host (String) —

    Host name or IP address the server listens on

Returns:

  • (Boolean) —

    true if the server is reachable from the local host only



39
40
41
42
43
44
45
46
47
# File 'lib/aspera/web_server_simple.rb', line 39

def loopback?(host)
  return true if host.eql?('localhost')
  address = IPAddr.new(host)
  # Older versions of ipaddr do not see IPv4-mapped IPv6 addresses (::ffff:127.0.0.1) as loopback
  address = address.native if address.ipv4_mapped?
  address.loopback?
rescue IPAddr::Error
  false
end

.read_chain_file(chain) ⇒ Array<OpenSSL::X509::Certificate>

Returns list of Certificates from chain file.

Returns:

  • (Array<OpenSSL::X509::Certificate>) —

    list of Certificates from chain file



108
109
110
# File 'lib/aspera/web_server_simple.rb', line 108

def read_chain_file(chain)
  File.read(chain).scan(/-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----/m).map { |i| OpenSSL::X509::Certificate.new(i) }
end

.self_signed_cert(private_key, digest: 'SHA256') ⇒ Object

Generate or fill and self sign certificate



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/aspera/web_server_simple.rb', line 86

def self_signed_cert(private_key, digest: 'SHA256')
  cert = OpenSSL::X509::Certificate.new
  cert.subject = cert.issuer = OpenSSL::X509::Name.parse(GENERIC_ISSUER)
  cert.not_before = Time.now - CLOCK_SKEW_OFFSET_SEC
  cert.not_after  = cert.not_before + ONE_YEAR_SECONDS
  cert.public_key = private_key.public_key
  cert.serial = 0x0
  cert.version = 2
  ef = OpenSSL::X509::ExtensionFactory.new
  ef.issuer_certificate = cert
  ef.subject_certificate = cert
  cert.extensions = [
    ef.create_extension('basicConstraints', 'CA:TRUE', true),
    ef.create_extension('subjectKeyIdentifier', 'hash')
    # ef.create_extension('keyUsage', 'cRLSign,keyCertSign', true),
  ]
  cert.add_extension(ef.create_extension('authorityKeyIdentifier', 'keyid:always,issuer:always'))
  cert.sign(private_key, OpenSSL::Digest.new(digest))
  cert
end

.serve(parameters, servlet, protected:, what:, type: ParameterError) ⇒ Object

Start a server with one servlet on the path of url, until signal INT or TERM. A server without protection reachable from the network is refused, see assert_protected.

Parameters:

  • parameters (Hash) —

    Parameters of the command, see url

  • servlet (Class) —

    Servlet

  • protected (Boolean) —

    true if requests are authenticated or restricted

  • what (String) —

    Parameters that protect the server, for the error message

  • type (Exception) (defaults to: ParameterError) —

    Exception to raise

Yield Returns:

  • (Array) —

    Arguments of the servlet, evaluated once parameters are checked



65
66
67
68
69
70
71
# File 'lib/aspera/web_server_simple.rb', line 65

def serve(parameters, servlet, protected:, what:, type: ParameterError)
  uri = url(parameters)
  assert_protected(uri.hostname, protected: protected, what: what, type: type)
  server = new(uri, **parameters.slice(*PARAMS))
  server.mount(uri.path, servlet, *yield)
  server.start
end

.servlet_parameters(parameters) ⇒ Hash

Returns Parameters of the servlet: other than url, cert, key, chain.

Parameters:

  • parameters (Hash) —

    Parameters of a command that starts a server, see url

Returns:

  • (Hash) —

    Parameters of the servlet: other than url, cert, key, chain



55
# File 'lib/aspera/web_server_simple.rb', line 55

def servlet_parameters(parameters) = parameters.except(:url, *PARAMS)

.url(parameters) ⇒ URI

Returns URL of the server: url, or DEFAULT_URL.

Parameters:

  • parameters (Hash) —

    Parameters of a command that starts a server (symbol keys): url, cert, key, chain, others are for the servlet

Returns:

  • (URI) —

    URL of the server: url, or DEFAULT_URL



51
# File 'lib/aspera/web_server_simple.rb', line 51

def url(parameters) = URI.parse(parameters.fetch(:url, DEFAULT_URL))

Instance Method Details

#<<(access_log) ⇒ Object

Log of web server access (option AccessLog): the request line has the query, e.g. the code of a browser login, which is hidden (see Secret::Hider#hide_serialized_secrets), also with the logger of a host application



186
187
188
189
190
191
192
# File 'lib/aspera/web_server_simple.rb', line 186

def <<(access_log)
  Log.log.debug do
    line = access_log.chomp
    line = Secret::Hider.instance.hide_serialized_secrets(line) unless Secret::Hider.instance.log_secrets
    "webrick log #{line}"
  end
end

#start ⇒ Object

Serve requests until #shutdown. In the main thread, signals INT and TERM call #shutdown. In another thread, signals are left to the application, which calls #shutdown, e.g. INT interrupts the main thread.



174
175
176
177
178
179
180
181
182
# File 'lib/aspera/web_server_simple.rb', line 174

def start
  Log.log.info { "Listening on #{@uri}" }
  if Thread.current.equal?(Thread.main)
    # kill (-TERM) for graceful shutdown
    handler = proc { shutdown }
    %i{INT TERM}.each { |sig| trap(sig, &handler) }
  end
  super
end