test.py 174 KB
Newer Older
1 2 3 4 5 6 7 8 9
##############################################################################
#
# Copyright (c) 2018 Nexedi SA and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
10
# Service Company
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import glob
import os
import requests
31
import httplib
32 33 34 35
from requests_toolbelt.adapters import source
import json
import multiprocessing
import subprocess
36
from unittest import skip, expectedFailure
37
import ssl
38
import signal
39
from BaseHTTPServer import HTTPServer
40
from BaseHTTPServer import BaseHTTPRequestHandler
41 42
from forcediphttpsadapter.adapters import ForcedIPHTTPSAdapter
import time
43
import tempfile
44
import ipaddress
45

46 47
from utils import SlapOSInstanceTestCase
from utils import findFreeTCPPort
48

49 50 51 52 53 54 55 56 57
import datetime

from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID

58 59
SLAPOS_TEST_IPV4 = os.environ['SLAPOS_TEST_IPV4']
SLAPOS_TEST_IPV6 = os.environ['SLAPOS_TEST_IPV6']
60 61 62 63 64 65 66 67 68

# ports chosen to not collide with test systems
HTTP_PORT = '11080'
HTTPS_PORT = '11443'
NGINX_HTTP_PORT = '12080'
NGINX_HTTPS_PORT = '12443'
MONITOR_HTTPD_PORT = '13000'
MONITOR_F1_HTTPD_PORT = '13001'
MONITOR_F2_HTTPD_PORT = '13002'
69 70
CAUCASE_PORT = '15090'
KEDIFA_PORT = '15080'
71

72 73
KEDIFA_IPV6_BASE = 'https://[%s]:%s' % (SLAPOS_TEST_IPV6, KEDIFA_PORT)

74 75

# for development: debugging logs and install Ctrl+C handler
76
if os.environ.get('SLAPOS_TEST_DEBUG'):
77 78 79 80 81
  import logging
  logging.basicConfig(level=logging.DEBUG)
  import unittest
  unittest.installHandler()

82

83
def der2pem(der):
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
  certificate = x509.load_der_x509_certificate(der, default_backend())
  return certificate.public_bytes(serialization.Encoding.PEM)


def createKey():
  key = rsa.generate_private_key(
    public_exponent=65537, key_size=2048, backend=default_backend())
  key_pem = key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.TraditionalOpenSSL,
    encryption_algorithm=serialization.NoEncryption()
  )
  return key, key_pem


99
def createSelfSignedCertificate(name_list):
100
  key, key_pem = createKey()
101 102 103
  subject_alternative_name_list = x509.SubjectAlternativeName(
    [x509.DNSName(unicode(q)) for q in name_list]
  )
104
  subject = issuer = x509.Name([
105
    x509.NameAttribute(NameOID.COMMON_NAME, u'Test Self Signed Certificate'),
106 107 108 109 110
  ])
  certificate = x509.CertificateBuilder().subject_name(
    subject
  ).issuer_name(
    issuer
111 112 113
  ).add_extension(
      subject_alternative_name_list,
      critical=False,
114 115 116 117 118 119 120 121 122 123 124 125 126
  ).public_key(
    key.public_key()
  ).serial_number(
    x509.random_serial_number()
  ).not_valid_before(
    datetime.datetime.utcnow() - datetime.timedelta(days=2)
  ).not_valid_after(
    datetime.datetime.utcnow() + datetime.timedelta(days=5)
  ).sign(key, hashes.SHA256(), default_backend())
  certificate_pem = certificate.public_bytes(serialization.Encoding.PEM)
  return key, key_pem, certificate, certificate_pem


127
def createCSR(common_name, ip=None):
128
  key, key_pem = createKey()
129 130 131 132 133
  subject_alternative_name_list = []
  if ip is not None:
    subject_alternative_name_list.append(
      x509.IPAddress(ipaddress.ip_address(unicode(ip)))
    )
134 135
  csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([
     x509.NameAttribute(NameOID.COMMON_NAME, unicode(common_name)),
136 137 138 139 140 141 142 143 144
  ]))

  if len(subject_alternative_name_list):
    csr = csr.add_extension(
      x509.SubjectAlternativeName(subject_alternative_name_list),
      critical=False
    )

  csr = csr.sign(key, hashes.SHA256(), default_backend())
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 170 171 172 173 174 175 176 177 178
  csr_pem = csr.public_bytes(serialization.Encoding.PEM)
  return key, key_pem, csr, csr_pem


class CertificateAuthority(object):
  def __init__(self, common_name):
    self.key, self.key_pem = createKey()
    public_key = self.key.public_key()
    builder = x509.CertificateBuilder()
    builder = builder.subject_name(x509.Name([
      x509.NameAttribute(NameOID.COMMON_NAME, unicode(common_name)),
    ]))
    builder = builder.issuer_name(x509.Name([
      x509.NameAttribute(NameOID.COMMON_NAME, unicode(common_name)),
    ]))
    builder = builder.not_valid_before(
      datetime.datetime.utcnow() - datetime.timedelta(days=2))
    builder = builder.not_valid_after(
      datetime.datetime.utcnow() + datetime.timedelta(days=30))
    builder = builder.serial_number(x509.random_serial_number())
    builder = builder.public_key(public_key)
    builder = builder.add_extension(
      x509.BasicConstraints(ca=True, path_length=None), critical=True,
    )
    self.certificate = builder.sign(
      private_key=self.key, algorithm=hashes.SHA256(),
      backend=default_backend()
    )
    self.certificate_pem = self.certificate.public_bytes(
      serialization.Encoding.PEM)

  def signCSR(self, csr):
    builder = x509.CertificateBuilder(
      subject_name=csr.subject,
179
      extensions=csr.extensions,
180 181 182 183 184 185 186 187 188 189 190 191
      issuer_name=self.certificate.subject,
      not_valid_before=datetime.datetime.utcnow() - datetime.timedelta(days=1),
      not_valid_after=datetime.datetime.utcnow() + datetime.timedelta(days=30),
      serial_number=x509.random_serial_number(),
      public_key=csr.public_key(),
    )
    certificate = builder.sign(
      private_key=self.key,
      algorithm=hashes.SHA256(),
      backend=default_backend()
    )
    return certificate, certificate.public_bytes(serialization.Encoding.PEM)
192

193

194
def subprocess_status_output(*args, **kwargs):
195 196 197 198
  prc = subprocess.Popen(
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    *args,
199
    **kwargs)
200
  out, err = prc.communicate()
201 202 203 204 205
  return prc.returncode, out


def subprocess_output(*args, **kwargs):
  return subprocess_status_output(*args, **kwargs)[1]
206 207


208
def isHTTP2(domain, ip):
209
  curl_command = 'curl --http2 -v -k -H "Host: %(domain)s" ' \
210 211
    'https://%(domain)s:%(https_port)s/ '\
    '--resolve %(domain)s:%(https_port)s:%(ip)s' % dict(
212
      ip=ip, domain=domain, https_port=HTTPS_PORT)
213 214 215 216 217 218 219 220 221
  prc = subprocess.Popen(
    curl_command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE
  )
  out, err = prc.communicate()
  assert prc.returncode == 0, "Problem running %r. Output:\n%s\nError:\n%s" % (
    curl_command, out, err)
  return 'Using HTTP2, server supports multi-use' in err


222 223 224 225 226 227 228 229 230 231
def getQUIC(url, ip, port):
  quic_client_command = 'quic_client --disable-certificate-verification '\
    '--port=%(port)s --host=%(host)s %(url)s' % dict(
      port=port, host=ip, url=url)
  try:
    return True, subprocess.check_output(
      quic_client_command.split(), stderr=subprocess.STDOUT)
  except subprocess.CalledProcessError as e:
    return False, e.output

232

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
def getPluginParameterDict(software_path, filepath):
  bin_file = os.path.join(software_path, 'bin', 'test-plugin-promise')
  with open(bin_file, 'w') as f:
    f.write("""#!%s/bin/pythonwitheggs
import os
import importlib
import sys
import json

filepath = sys.argv[1]
sys.path[0:0] = [os.path.dirname(filepath)]
filename = os.path.basename(filepath)
module = importlib.import_module(os.path.splitext(filename)[0])

print json.dumps(module.extra_config_dict)
    """ % software_path)

  os.chmod(bin_file, 0755)
  result = subprocess_output([bin_file, filepath]).strip()
  try:
    return json.loads(result)
  except ValueError, e:
    raise ValueError("%s\nResult was: %s" % (e, result))
256

257

258
class TestDataMixin(object):
259 260 261 262 263 264 265 266 267 268 269 270
  @staticmethod
  def generateHashFromFiles(file_list):
    import hashlib
    hasher = hashlib.md5()
    for path in file_list:
      with open(path, 'r') as afile:
        buf = afile.read()
      hasher.update("%s\n" % len(buf))
      hasher.update(buf)
    hash = hasher.hexdigest()
    return hash

271 272 273 274 275
  def getTrimmedProcessInfo(self):
    return '\n'.join(sorted([
      '%(group)s:%(name)s %(statename)s' % q for q
      in self.getSupervisorRPCServer().supervisor.getAllProcessInfo()]))

276
  def assertTestData(self, runtime_data, hash_value=None, msg=None):
277
    filename = '%s-%s.txt' % (self.id(), 'CADDY')
278 279 280 281 282 283 284 285
    test_data_file = os.path.join(
      os.path.dirname(os.path.realpath(__file__)), 'test_data', filename)

    try:
      test_data = open(test_data_file).read().strip()
    except IOError:
      test_data = ''

286 287
    if hash_value is not None:
      runtime_data = runtime_data.replace(hash_value, '{hash}')
288

289 290
    maxDiff = self.maxDiff
    self.maxDiff = None
291 292
    longMessage = self.longMessage
    self.longMessage = True
293 294 295
    try:
      self.assertMultiLineEqual(
        test_data,
296 297
        runtime_data,
        msg=msg
298 299 300 301 302 303 304
      )
    except AssertionError:
      if os.environ.get('SAVE_TEST_DATA', '0') == '1':
        open(test_data_file, 'w').write(runtime_data.strip())
      raise
    finally:
      self.maxDiff = maxDiff
305
      self.longMessage = longMessage
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320

  def _test_file_list(self, slave_dir, IGNORE_PATH_LIST):
    runtime_data = []
    for slave_var in glob.glob(os.path.join(self.instance_path, '*', 'var')):
      for entry in os.walk(os.path.join(slave_var, slave_dir)):
        for filename in entry[2]:
          path = os.path.join(
            entry[0][len(self.instance_path) + 1:], filename)
          if not any([path.endswith(q) for q in IGNORE_PATH_LIST]):
            runtime_data.append(path)
    runtime_data = '\n'.join(sorted(runtime_data))
    self.assertTestData(runtime_data)

  def test_file_list_log(self):
    self._test_file_list('log', [
321 322
      # no control at all when cron would kick in, ignore it
      'cron.log',
323 324 325 326 327
      # appears late and is quite unstable, no need to assert
      'trafficserver/.diags.log.meta',
      'trafficserver/.manager.log.meta',
      'trafficserver/.squid.log.meta',
      'trafficserver/.traffic.out.meta',
328
      'trafficserver/diags.log',
329
      'trafficserver/squid.log',
330
      # not important, appears sometimes
331 332
      'trafficserver/.error.log.meta',
      'trafficserver/error.log',
333 334 335 336 337 338
    ])

  def test_file_list_run(self):
    self._test_file_list('run', [
      # run by cron from time to time
      'monitor/monitor-collect.pid',
339 340 341
      # may appear or not
      'var/run/caddy_graceful_signature.tmp',
      'var/run/nginx_graceful_signature.tmp',
342 343 344 345 346
    ])

  def test_supervisor_state(self):
    # give a chance for etc/run scripts to finish
    time.sleep(1)
347 348 349 350 351 352 353 354

    hash_files = [
      'software_release/buildout.cfg',
    ]
    hash_files = [os.path.join(self.computer_partition_root_path, path)
                  for path in hash_files]
    h = self.generateHashFromFiles(hash_files)

355
    runtime_data = self.getTrimmedProcessInfo()
356
    self.assertTestData(runtime_data, hash_value=h)
357

358 359 360 361 362 363 364 365 366
  def test_promise_run_plugin(self):
    ignored_plugin_list = [
      '__init__.py',  # that's not a plugin
      'monitor-http-frontend.py',  # can't check w/o functioning frontend
    ]
    runpromise_bin = os.path.join(
      self.software_path, 'bin', 'monitor.runpromise')
    partition_path_list = glob.glob(os.path.join(self.instance_path, '*'))
    promise_status_list = []
367
    msg = []
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    for partition_path in sorted(partition_path_list):
      plugin_path_list = sorted(glob.glob(
          os.path.join(partition_path, 'etc', 'plugin', '*.py')
      ))
      strip = len(os.path.join(partition_path, 'etc', 'plugin')) + 1
      for plugin_path in plugin_path_list:
        monitor_conf = os.path.join(partition_path, 'etc', 'monitor.conf')
        plugin = plugin_path[strip:]
        if plugin in ignored_plugin_list:
          continue
        plugin_status, plugin_result = subprocess_status_output([
          runpromise_bin,
          '-c', monitor_conf,
          '--run-only', plugin
        ])
383 384 385
        if plugin_status == 1:
          msg.append(plugin_result)

386 387 388
        # sanity check
        if 'Checking promise %s' % plugin not in plugin_result:
          plugin_status = 1
389
          msg.append(plugin_result)
390 391 392 393 394
        promise_status_list.append(
          '%s: %s' % (
            plugin_path[len(self.instance_path) + 1:],
            plugin_status == 0 and 'OK' or 'ERROR'))

395 396 397
    if msg:
      msg = ''.join(msg).strip()
    self.assertTestData('\n'.join(promise_status_list), msg=(msg or None))
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414

  def test_promise_run_promise(self):
    partition_path_list = glob.glob(os.path.join(self.instance_path, '*'))
    promise_status_list = []
    for partition_path in sorted(partition_path_list):
      promise_path_list = sorted(glob.glob(
          os.path.join(partition_path, 'etc', 'promise', '*')
      ))
      for promise_path in promise_path_list:
        promise_result = subprocess.call([promise_path])
        promise_status_list.append(
          '%s: %s' % (
            promise_path[len(self.instance_path) + 1:],
            promise_result == 0 and 'OK' or 'ERROR'))

    self.assertTestData('\n'.join(promise_status_list))

415

416
class HttpFrontendTestCase(SlapOSInstanceTestCase):
417 418 419
  # show full diffs, as it is required for proper analysis of problems
  maxDiff = None

420 421
  @classmethod
  def getSoftwareURLList(cls):
422 423 424
    return (
      os.path.abspath(
        os.path.join(os.path.dirname(__file__), '..', 'software.cfg')), )
425 426 427 428 429 430 431 432 433 434 435 436 437 438

  @classmethod
  def setUpClass(cls):
    super(HttpFrontendTestCase, cls).setUpClass()
    # extra class attributes used in HttpFrontendTestCase

    # expose instance directory
    cls.instance_path = os.path.join(
        cls.config['working_directory'],
        'inst')
    # expose software directory, extract from found computer partition
    cls.software_path = os.path.realpath(os.path.join(
        cls.computer_partition_root_path, 'software_release'))

439
  def assertLogAccessUrlWithPop(self, parameter_dict):
440 441
    log_access_url = parameter_dict.pop('log-access-url')

442
    self.assertTrue(len(log_access_url) >= 1)
443
    # check only the first one, as second frontend will be stopped
444
    log_access = log_access_url[0]
445 446 447 448 449 450
    entry = log_access.split(': ')
    if len(entry) != 2:
      self.fail('Cannot parse %r' % (log_access,))
    frontend, url = entry
    result = requests.get(url, verify=False)
    self.assertEqual(
451
      httplib.OK,
452
      result.status_code,
453 454 455
      'While accessing %r of %r the status code was %r' % (
        url, frontend, result.status_code))

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
  def assertKedifaKeysWithPop(self, parameter_dict, prefix=''):
    generate_auth_url = parameter_dict.pop('%skey-generate-auth-url' % (
      prefix,))
    upload_url = parameter_dict.pop('%skey-upload-url' % (prefix,))
    base = '^' + KEDIFA_IPV6_BASE.replace(
      '[', r'\[').replace(']', r'\]') + '/.{32}'
    self.assertRegexpMatches(
      generate_auth_url,
      base + r'\/generateauth$'
    )
    self.assertRegexpMatches(
      upload_url,
      base + r'\?auth=$'
    )

    return generate_auth_url, upload_url

473 474 475 476 477 478 479 480 481 482
  def assertKeyWithPop(self, key, d):
    self.assertTrue(key in d, 'Key %r is missing in %r' % (key, d))
    d.pop(key)

  def assertEqualResultJson(self, result, key, value):
    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
    self.assertTrue(key in j, 'No key %r in %s' % (key, j))
483
    self.assertEqual(value, j[key])
484

485 486 487 488 489
  def parseParameterDict(self, parameter_dict):
    parsed_parameter_dict = {}
    for key, value in parameter_dict.items():
      if key in [
        'rejected-slave-dict',
490 491
        'warning-slave-dict',
        'warning-list',
492 493 494 495 496 497 498 499 500 501 502
        'request-error-list',
        'log-access-url']:
        value = json.loads(value)
      parsed_parameter_dict[key] = value
    return parsed_parameter_dict

  def parseConnectionParameterDict(self):
    return self.parseParameterDict(
      self.computer_partition.getConnectionParameterDict()
    )

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
  @classmethod
  def runComputerPartitionUntil(cls, until):
    max_try = 10
    try_num = 1
    while True:
      if try_num > max_try:
        raise ValueError('Failed to run computer partition with %r' % (until,))
      cls.runComputerPartition(max_quantity=1)
      if until():
        break
      try_num += 1

  @classmethod
  def untilNotReadyYetNotInMasterKeyGenerateAuthUrl(cls):
    parameter_dict = cls.computer_partition.getConnectionParameterDict()
    key = 'master-key-generate-auth-url'
    if key not in parameter_dict:
      return False
    if 'NotReadyYet' in parameter_dict[key]:
      return False
    return True

525 526 527 528 529 530 531 532 533 534

class TestMasterRequest(HttpFrontendTestCase, TestDataMixin):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      'nginx_port': NGINX_HTTPS_PORT,
      'plain_nginx_port': NGINX_HTTP_PORT,
      'monitor-httpd-port': MONITOR_HTTPD_PORT,
535 536
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
537 538 539
    }

  def test(self):
540 541 542
    # run partition until AIKC finishes
    self.runComputerPartitionUntil(
      self.untilNotReadyYetNotInMasterKeyGenerateAuthUrl)
543
    parameter_dict = self.parseConnectionParameterDict()
544
    self.assertKeyWithPop('monitor-setup-url', parameter_dict)
545
    self.assertKedifaKeysWithPop(parameter_dict, 'master-')
546 547 548 549
    self.assertEqual(
      {
        'monitor-base-url': None,
        'domain': 'None',
550 551
        'kedifa-caucase-url': 'http://[%s]:%s' % (
           SLAPOS_TEST_IPV6, CAUCASE_PORT),
552 553 554
        'accepted-slave-amount': '0',
        'rejected-slave-amount': '0',
        'slave-amount': '0',
555
        'rejected-slave-dict': {}},
556 557 558 559 560 561 562 563 564 565 566 567 568 569
      parameter_dict
    )


class TestMasterRequestDomain(HttpFrontendTestCase, TestDataMixin):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      'nginx_port': NGINX_HTTPS_PORT,
      'plain_nginx_port': NGINX_HTTP_PORT,
      'monitor-httpd-port': MONITOR_HTTPD_PORT,
570 571
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
572 573 574
    }

  def test(self):
575 576 577
    # run partition until AIKC finishes
    self.runComputerPartitionUntil(
      self.untilNotReadyYetNotInMasterKeyGenerateAuthUrl)
578
    parameter_dict = self.parseConnectionParameterDict()
579
    self.assertKeyWithPop('monitor-setup-url', parameter_dict)
580
    self.assertKedifaKeysWithPop(parameter_dict, 'master-')
581 582 583 584 585

    self.assertEqual(
      {
        'monitor-base-url': None,
        'domain': 'example.com',
586 587
        'kedifa-caucase-url': 'http://[%s]:%s' % (
           SLAPOS_TEST_IPV6, CAUCASE_PORT),
588 589 590
        'accepted-slave-amount': '0',
        'rejected-slave-amount': '0',
        'slave-amount': '0',
591
        'rejected-slave-dict': {}
592 593 594 595 596
      },
      parameter_dict
    )


597 598
class TestHandler(BaseHTTPRequestHandler):
  def do_GET(self):
599
    timeout = int(self.headers.dict.get('timeout', '0'))
600
    time.sleep(timeout)
601
    self.send_response(200)
602 603

    prefix = 'x-reply-header-'
604
    length = len(prefix)
605 606 607
    for key, value in self.headers.dict.items():
      if key.startswith(prefix):
        self.send_header(
608
          '-'.join([q.capitalize() for q in key[length:].split('-')]),
609 610 611
          value.strip()
        )

612 613 614 615 616 617 618 619 620 621 622
    self.send_header("Content-type", "application/json")
    self.send_header('Set-Cookie', 'secured=value;secure')
    self.send_header('Set-Cookie', 'nonsecured=value')
    self.end_headers()
    response = {
      'Path': self.path,
      'Incoming Headers': self.headers.dict
    }
    self.wfile.write(json.dumps(response, indent=2))


623 624 625 626
class SlaveHttpFrontendTestCase(HttpFrontendTestCase):
  @classmethod
  def startServerProcess(cls):
    server = HTTPServer(
627
      (SLAPOS_TEST_IPV4, findFreeTCPPort(SLAPOS_TEST_IPV4)),
628
      TestHandler)
629 630

    server_https = HTTPServer(
631
      (SLAPOS_TEST_IPV4, findFreeTCPPort(SLAPOS_TEST_IPV4)),
632
      TestHandler)
633

634
    cls.another_server_ca = CertificateAuthority("Another Server Root CA")
635 636
    cls.test_server_ca = CertificateAuthority("Test Server Root CA")
    key, key_pem, csr, csr_pem = createCSR(
637
      "testserver.example.com", SLAPOS_TEST_IPV4)
638 639 640 641 642 643 644 645 646 647
    _, cls.test_server_certificate_pem = cls.test_server_ca.signCSR(csr)

    cls.test_server_certificate_file = tempfile.NamedTemporaryFile(
      delete=False
    )

    cls.test_server_certificate_file.write(
        cls.test_server_certificate_pem + key_pem
      )
    cls.test_server_certificate_file.close()
648 649
    server_https.socket = ssl.wrap_socket(
      server_https.socket,
650
      certfile=cls.test_server_certificate_file.name,
651 652
      server_side=True)

653
    cls.backend_url = 'http://%s:%s/' % server.server_address
654 655
    cls.server_process = multiprocessing.Process(target=server.serve_forever)
    cls.server_process.start()
656
    cls.backend_https_url = 'https://%s:%s/' % server_https.server_address
657 658 659 660 661 662
    cls.server_https_process = multiprocessing.Process(
      target=server_https.serve_forever)
    cls.server_https_process.start()

  @classmethod
  def stopServerProcess(cls):
663 664
    if getattr(cls, 'test_server_certificate_file', None) is not None:
      os.unlink(cls.test_server_certificate_file.name)
665 666 667 668
    for server in ['server_process', 'server_https_process']:
      process = getattr(cls, server, None)
      if process is not None:
        process.terminate()
669

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
  @classmethod
  def setUpMaster(cls):
    # run partition until AIKC finishes
    cls.runComputerPartitionUntil(
      cls.untilNotReadyYetNotInMasterKeyGenerateAuthUrl)
    parameter_dict = cls.computer_partition.getConnectionParameterDict()
    ca_certificate = requests.get(
      parameter_dict['kedifa-caucase-url'] + '/cas/crt/ca.crt.pem')
    assert ca_certificate.status_code == httplib.OK
    cls.ca_certificate_file = os.path.join(cls.working_directory, 'ca.crt.pem')
    open(cls.ca_certificate_file, 'w').write(ca_certificate.text)
    auth = requests.get(
      parameter_dict['master-key-generate-auth-url'],
      verify=cls.ca_certificate_file)
    assert auth.status_code == httplib.CREATED
    upload = requests.put(
      parameter_dict['master-key-upload-url'] + auth.text,
      data=cls.key_pem + cls.certificate_pem,
      verify=cls.ca_certificate_file)
    assert upload.status_code == httplib.CREATED

  @classmethod
  def untilSlavePartitionReady(cls):
    for slave_reference, partition_parameter_kw in cls\
            .getSlaveParameterDictDict().items():
      parameter_dict = cls.slapos_controler.slap.registerOpenOrder().request(
        software_release=cls.software_url_list[0],
        partition_reference=slave_reference,
        partition_parameter_kw=partition_parameter_kw,
        shared=True
      ).getConnectionParameterDict()

      log_access_ready = 'log-access-url' in parameter_dict
      key = 'key-generate-auth-url'
      key_generate_auth_ready = key in parameter_dict \
          and 'NotReadyYet' not in parameter_dict[key]
      if log_access_ready and key_generate_auth_ready:
        return True
    return False

710 711 712 713 714 715 716 717 718 719 720 721
  @classmethod
  def setUpSlaves(cls):
    cls.slave_connection_parameter_dict_dict = {}
    request = cls.slapos_controler.slap.registerOpenOrder().request
    for slave_reference, partition_parameter_kw in cls\
            .getSlaveParameterDictDict().items():
      slave_instance = request(
        software_release=cls.software_url_list[0],
        partition_reference=slave_reference,
        partition_parameter_kw=partition_parameter_kw,
        shared=True
      )
722 723 724
    # run partition for slaves to be setup
    cls.runComputerPartitionUntil(
      cls.untilSlavePartitionReady)
725 726 727 728 729 730 731 732 733 734 735
    for slave_reference, partition_parameter_kw in cls\
            .getSlaveParameterDictDict().items():
      slave_instance = request(
        software_release=cls.software_url_list[0],
        partition_reference=slave_reference,
        partition_parameter_kw=partition_parameter_kw,
        shared=True
      )
      cls.slave_connection_parameter_dict_dict[slave_reference] = \
          slave_instance.getConnectionParameterDict()

736 737 738
  @classmethod
  def createWildcardExampleComCertificate(cls):
    _, cls.key_pem, _, cls.certificate_pem = createSelfSignedCertificate(
739 740 741 742 743 744
      [
        '*.customdomain.example.com',
        '*.example.com',
        '*.nginx.example.com',
        '*.alias1.example.com',
      ])
745

746 747 748
  @classmethod
  def setUpClass(cls):
    try:
749
      cls.createWildcardExampleComCertificate()
750 751
      cls.startServerProcess()
      super(SlaveHttpFrontendTestCase, cls).setUpClass()
752 753 754 755 756 757
      cls.setup_master_exception = None
      cls.setup_slave_exception = None
      # Swallow setup master and slave exceptions, as not all tests depend on
      # it, and can provide important information about bad state of the
      # test environment
      cls.setUpMaster()
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
      cls.setUpSlaves()
    except Exception:
      cls.tearDownClass()
      raise

  @classmethod
  def tearDownClass(cls):
    super(SlaveHttpFrontendTestCase, cls).tearDownClass()
    cls.stopServerProcess()

  def fakeHTTPSResult(self, domain, real_ip, path, port=HTTPS_PORT,
                      headers=None, cookies=None, source_ip=None):
    if headers is None:
      headers = {}
    headers.setdefault('REMOTE_USER', 'SOME_REMOTE_USER')
773 774 775
    # workaround request problem of setting Accept-Encoding
    # https://github.com/requests/requests/issues/2234
    headers.setdefault('Accept-Encoding', 'dummy')
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
    session = requests.Session()
    session.mount(
      'https://%s:%s' % (domain, port),
      ForcedIPHTTPSAdapter(
        dest_ip=real_ip))
    if source_ip is not None:
      new_source = source.SourceAddressAdapter(source_ip)
      session.mount('http://', new_source)
      session.mount('https://', new_source)
    return session.get(
      'https://%s:%s/%s' % (domain, port, path),
      verify=False,
      allow_redirects=False,
      headers=headers,
      cookies=cookies
    )

  def fakeHTTPResult(self, domain, real_ip, path, port=HTTP_PORT,
                     headers=None):
    if headers is None:
      headers = {}
    headers.setdefault('REMOTE_USER', 'SOME_REMOTE_USER')
798 799 800
    # workaround request problem of setting Accept-Encoding
    # https://github.com/requests/requests/issues/2234
    headers.setdefault('Accept-Encoding', 'dummy')
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
    headers['Host'] = domain
    return requests.get(
      'http://%s:%s/%s' % (real_ip, port, path),
      headers=headers,
      allow_redirects=False,
    )

  def patchRequests(self):
    HTTPResponse = requests.packages.urllib3.response.HTTPResponse
    HTTPResponse.orig__init__ = HTTPResponse.__init__

    def new_HTTPResponse__init__(self, *args, **kwargs):
      self.orig__init__(*args, **kwargs)
      try:
        self.peercert = self._connection.sock.getpeercert(binary_form=True)
      except AttributeError:
        pass
    HTTPResponse.__init__ = new_HTTPResponse__init__

    HTTPAdapter = requests.adapters.HTTPAdapter
    HTTPAdapter.orig_build_response = HTTPAdapter.build_response

    def new_HTTPAdapter_build_response(self, request, resp):
      response = self.orig_build_response(request, resp)
      try:
        response.peercert = resp.peercert
      except AttributeError:
        pass
      return response
    HTTPAdapter.build_response = new_HTTPAdapter_build_response

  def unpatchRequests(self):
    HTTPResponse = requests.packages.urllib3.response.HTTPResponse
    if getattr(HTTPResponse, 'orig__init__', None) is not None:
      HTTPResponse.__init__ = HTTPResponse.orig__init__
      del(HTTPResponse.orig__init__)

    HTTPAdapter = requests.adapters.HTTPAdapter
    if getattr(HTTPAdapter, 'orig_build_response', None) is not None:
      HTTPAdapter.build_response = HTTPAdapter.orig_build_response
      del(HTTPAdapter.orig_build_response)

  def setUp(self):
    # patch requests in order to being able to extract SSL certs
    self.patchRequests()

  def tearDown(self):
    self.unpatchRequests()

850 851 852 853 854 855 856
  def parseSlaveParameterDict(self, key):
    return self.parseParameterDict(
      self.slave_connection_parameter_dict_dict[
        key
      ]
    )

857 858

class TestSlave(SlaveHttpFrontendTestCase, TestDataMixin):
859 860 861
  caddy_custom_https = '''# caddy_custom_https_filled_in_accepted
https://caddycustomhttpsaccepted.example.com:%%(https_port)s {
  bind %%(local_ipv4)s
862
  tls %%(certificate)s %%(certificate)s
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891

  log / %%(access_log)s {combined}
  errors %%(error_log)s

  proxy / %(url)s {
    transparent
    timeout 600s
    insecure_skip_verify
  }
}
'''

  caddy_custom_http = '''# caddy_custom_http_filled_in_accepted
http://caddycustomhttpsaccepted.example.com:%%(http_port)s {
  bind %%(local_ipv4)s
  log / %%(access_log)s {combined}
  errors %%(error_log)s

  proxy / %(url)s {
    transparent
    timeout 600s
    insecure_skip_verify
  }
}
'''

  apache_custom_https = '''# apache_custom_https_filled_in_accepted
https://apachecustomhttpsaccepted.example.com:%%(https_port)s {
  bind %%(local_ipv4)s
892
  tls %%(certificate)s %%(certificate)s
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918

  log / %%(access_log)s {combined}
  errors %%(error_log)s

  proxy / %(url)s {
    transparent
    timeout 600s
    insecure_skip_verify
  }
}
'''

  apache_custom_http = '''# apache_custom_http_filled_in_accepted
http://apachecustomhttpsaccepted.example.com:%%(http_port)s {
  bind %%(local_ipv4)s
  log / %%(access_log)s {combined}
  errors %%(error_log)s

  proxy / %(url)s {
    transparent
    timeout 600s
    insecure_skip_verify
  }
}
'''

919 920 921 922 923
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
      'nginx-domain': 'nginx.example.com',
924
      'public-ipv4': SLAPOS_TEST_IPV4,
925 926
      '-frontend-authorized-slave-string':
      '_apache_custom_http_s-accepted _caddy_custom_http_s-accepted',
927 928 929 930 931 932
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      'nginx_port': NGINX_HTTPS_PORT,
      'plain_nginx_port': NGINX_HTTP_PORT,
      'monitor-httpd-port': MONITOR_HTTPD_PORT,
      '-frontend-config-1-monitor-httpd-port': MONITOR_F1_HTTPD_PORT,
933 934
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
935
      'mpm-graceful-shutdown-timeout': 2,
936 937
    }

938 939 940 941 942 943 944
  @classmethod
  def setUpSlaves(cls):
    cls.ca = CertificateAuthority('TestSlave')
    _, cls.customdomain_ca_key_pem, csr, _ = createCSR(
      'customdomainsslcrtsslkeysslcacrt.example.com')
    _, cls.customdomain_ca_certificate_pem = cls.ca.signCSR(csr)
    _, cls.customdomain_key_pem, _, cls.customdomain_certificate_pem = \
945
        createSelfSignedCertificate(['customdomainsslcrtsslkey.example.com'])
946 947
    super(TestSlave, cls).setUpSlaves()

948 949 950 951 952
  @classmethod
  def getSlaveParameterDictDict(cls):
    return {
      'empty': {
      },
953
      'Url': {
954 955 956
        'url': cls.backend_url,
      },
      'url_https-url': {
957 958
        'url': cls.backend_url + 'http',
        'https-url': cls.backend_url + 'https',
959 960 961 962 963
      },
      'server-alias': {
        'url': cls.backend_url,
        'server-alias': 'alias1.example.com alias2.example.com',
      },
964 965 966 967
      'server-alias-wildcard': {
        'url': cls.backend_url,
        'server-alias': '*.alias1.example.com',
      },
968 969 970 971 972 973 974 975 976
      'server-alias-duplicated': {
        'url': cls.backend_url,
        'server-alias': 'alias3.example.com alias3.example.com',
      },
      'server-alias_custom_domain-duplicated': {
        'url': cls.backend_url,
        'custom_domain': 'alias4.example.com',
        'server-alias': 'alias4.example.com alias4.example.com',
      },
977 978 979
      'ssl-proxy-verify_ssl_proxy_ca_crt': {
        'url': cls.backend_https_url,
        'ssl-proxy-verify': True,
980
        'ssl_proxy_ca_crt': cls.test_server_ca.certificate_pem,
981
      },
982 983 984 985 986
      'ssl-proxy-verify_ssl_proxy_ca_crt-unverified': {
        'url': cls.backend_https_url,
        'ssl-proxy-verify': True,
        'ssl_proxy_ca_crt': cls.another_server_ca.certificate_pem,
      },
987 988 989 990 991 992 993 994 995 996 997 998
      'ssl-proxy-verify-unverified': {
        'url': cls.backend_https_url,
        'ssl-proxy-verify': True,
      },
      'https-only': {
        'url': cls.backend_url,
        'https-only': True,
      },
      'custom_domain': {
        'url': cls.backend_url,
        'custom_domain': 'customdomain.example.com',
      },
999 1000 1001 1002
      'custom_domain_wildcard': {
        'url': cls.backend_url,
        'custom_domain': '*.customdomain.example.com',
      },
1003 1004 1005 1006
      'custom_domain_ssl_crt_ssl_key': {
        'url': cls.backend_url,
        'custom_domain': 'customdomainsslcrtsslkey.example.com',
      },
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
      'custom_domain_ssl_crt_ssl_key_ssl_ca_crt': {
        'url': cls.backend_url,
        'custom_domain': 'customdomainsslcrtsslkeysslcacrt.example.com',
      },
      'ssl_ca_crt_only': {
        'url': cls.backend_url,
      },
      'ssl_ca_crt_garbage': {
        'url': cls.backend_url,
      },
      'ssl_ca_crt_does_not_match': {
        'url': cls.backend_url,
      },
1020 1021 1022 1023
      'type-zope': {
        'url': cls.backend_url,
        'type': 'zope',
      },
1024 1025 1026 1027 1028
      'type-zope-prefer-gzip-encoding-to-backend': {
        'url': cls.backend_url,
        'prefer-gzip-encoding-to-backend': 'true',
        'type': 'zope',
      },
1029 1030 1031 1032
      'type-zope-ssl-proxy-verify_ssl_proxy_ca_crt': {
        'url': cls.backend_https_url,
        'type': 'zope',
        'ssl-proxy-verify': True,
1033
        'ssl_proxy_ca_crt': cls.test_server_ca.certificate_pem,
1034
      },
1035 1036 1037 1038 1039 1040
      'type-zope-ssl-proxy-verify_ssl_proxy_ca_crt-unverified': {
        'url': cls.backend_https_url,
        'type': 'zope',
        'ssl-proxy-verify': True,
        'ssl_proxy_ca_crt': cls.another_server_ca.certificate_pem,
      },
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
      'type-zope-ssl-proxy-verify-unverified': {
        'url': cls.backend_https_url,
        'type': 'zope',
        'ssl-proxy-verify': True,
      },
      'type-zope-virtualhostroot-http-port': {
        'url': cls.backend_url,
        'type': 'zope',
        'virtualhostroot-http-port': '12345'
      },
      'type-zope-virtualhostroot-https-port': {
        'url': cls.backend_url,
        'type': 'zope',
        'virtualhostroot-https-port': '12345'
      },
      'type-zope-path': {
        'url': cls.backend_url,
        'type': 'zope',
1059
        'path': '///path/to/some/resource///',
1060 1061 1062 1063
      },
      'type-zope-default-path': {
        'url': cls.backend_url,
        'type': 'zope',
1064
        'default-path': '///default-path/to/some/resource///',
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
      },
      'type-notebook': {
        'url': cls.backend_url,
        'type': 'notebook',
      },
      'type-eventsource': {
        'url': cls.backend_url,
        'type': 'eventsource',
      },
      'type-redirect': {
        'url': cls.backend_url,
        'type': 'redirect',
      },
      'enable_cache': {
        'url': cls.backend_url,
        'enable_cache': True,
      },
      'enable_cache-disable-no-cache-request': {
        'url': cls.backend_url,
        'enable_cache': True,
        'disable-no-cache-request': True,
      },
      'enable_cache-disable-via-header': {
        'url': cls.backend_url,
        'enable_cache': True,
        'disable-via-header': True,
      },
      'enable-http2-false': {
        'url': cls.backend_url,
        'enable-http2': False,
      },
      'enable_cache-ssl-proxy-verify-unverified': {
        'url': cls.backend_https_url,
        'enable_cache': True,
        'ssl-proxy-verify': True,
      },
      'enable_cache-ssl-proxy-verify_ssl_proxy_ca_crt': {
        'url': cls.backend_https_url,
        'enable_cache': True,
1104
        'ssl_proxy_ca_crt': cls.test_server_ca.certificate_pem,
1105 1106
        'ssl-proxy-verify': True,
      },
1107 1108 1109 1110 1111 1112
      'enable_cache-ssl-proxy-verify_ssl_proxy_ca_crt-unverified': {
        'url': cls.backend_https_url,
        'enable_cache': True,
        'ssl_proxy_ca_crt': cls.another_server_ca.certificate_pem,
        'ssl-proxy-verify': True,
      },
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
      'enable-http2-default': {
        'url': cls.backend_url,
      },
      'apache_custom_http_s-rejected': {
        'url': cls.backend_url,
        'apache_custom_https': '# apache_custom_https_filled_in_rejected',
        'apache_custom_http': '# apache_custom_http_filled_in_rejected',
      },
      'apache_custom_http_s-accepted': {
        'url': cls.backend_url,
1123 1124 1125 1126
        'apache_custom_https': cls.apache_custom_https % dict(
          url=cls.backend_url),
        'apache_custom_http': cls.apache_custom_http % dict(
          url=cls.backend_url),
1127
      },
1128 1129 1130 1131 1132 1133 1134
      'caddy_custom_http_s-rejected': {
        'url': cls.backend_url,
        'caddy_custom_https': '# caddy_custom_https_filled_in_rejected',
        'caddy_custom_http': '# caddy_custom_http_filled_in_rejected',
      },
      'caddy_custom_http_s-accepted': {
        'url': cls.backend_url,
1135 1136 1137 1138
        'caddy_custom_https': cls.caddy_custom_https % dict(
          url=cls.backend_url),
        'caddy_custom_http': cls.caddy_custom_http % dict(
          url=cls.backend_url),
1139
      },
1140 1141 1142 1143 1144 1145
      # this has to be rejected
      'caddy_custom_http_s': {
        'url': cls.backend_url,
        'caddy_custom_https': '# caddy_custom_https_filled_in_rejected_2',
        'caddy_custom_http': '# caddy_custom_http_filled_in_rejected_2',
      },
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
      'prefer-gzip-encoding-to-backend': {
        'url': cls.backend_url,
        'prefer-gzip-encoding-to-backend': 'true',
      },
      'disabled-cookie-list': {
        'url': cls.backend_url,
        'disabled-cookie-list': 'Chocolate Vanilia',
      },
      'monitor-ipv4-test': {
        'monitor-ipv4-test': 'monitor-ipv4-test',
      },
      'monitor-ipv6-test': {
        'monitor-ipv6-test': 'monitor-ipv6-test',
      },
      're6st-optimal-test': {
        're6st-optimal-test': 'ipv6,ipv4',
      }
    }

  def getMasterPartitionPath(self):
    # partition w/o etc/trafficserver, but with buildout.cfg
    return [
      q for q in glob.glob(os.path.join(self.instance_path, '*',))
1169 1170 1171
      if not os.path.exists(
        os.path.join(q, 'etc', 'trafficserver')) and os.path.exists(
          os.path.join(q, 'buildout.cfg'))][0]
1172 1173 1174 1175 1176 1177 1178 1179

  def getSlavePartitionPath(self):
    # partition w/ etc/trafficserver
    return [
      q for q in glob.glob(os.path.join(self.instance_path, '*',))
      if os.path.exists(os.path.join(q, 'etc', 'trafficserver'))][0]

  def test_master_partition_state(self):
1180
    parameter_dict = self.parseConnectionParameterDict()
1181
    self.assertKeyWithPop('monitor-setup-url', parameter_dict)
1182
    self.assertKedifaKeysWithPop(parameter_dict, 'master-')
1183

1184 1185 1186
    expected_parameter_dict = {
      'monitor-base-url': None,
      'domain': 'example.com',
1187 1188
      'accepted-slave-amount': '45',
      'rejected-slave-amount': '3',
1189
      'slave-amount': '48',
1190 1191
      'kedifa-caucase-url': 'http://[%s]:%s' % (
        SLAPOS_TEST_IPV6, CAUCASE_PORT),
1192 1193 1194 1195
      'rejected-slave-dict': {
        "_apache_custom_http_s-rejected": ["slave not authorized"],
        "_caddy_custom_http_s": ["slave not authorized"],
        "_caddy_custom_http_s-rejected": ["slave not authorized"],
1196
      }
1197
    }
1198 1199 1200

    self.assertEqual(
      expected_parameter_dict,
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
      parameter_dict
    )

    partition_path = self.getMasterPartitionPath()

    self.assertEqual(
      set([
        'promise-monitor-httpd-is-process-older-than-dependency-set',
      ]),
      set(os.listdir(os.path.join(partition_path, 'etc', 'promise'))))

1212 1213 1214 1215
    self.assertEqual(
      set([
        'monitor-bootstrap-status.py',
        'check-free-disk-space.py',
1216 1217
        'monitor-http-frontend.py',
        'monitor-httpd-listening-on-tcp.py',
1218
        'buildout-T-0-status.py',
1219 1220 1221 1222 1223 1224
        '__init__.py',
      ]),
      set([
        q for q in os.listdir(os.path.join(partition_path, 'etc', 'plugin'))
        if not q.endswith('.pyc')]))

1225 1226 1227 1228 1229 1230 1231 1232
    # check that monitor cors domains are correctly setup by file presence, as
    # we trust monitor stack being tested in proper place and it is too hard
    # to have working monitor with local proxy
    self.assertTestData(
      open(
        os.path.join(
          partition_path, 'etc', 'httpd-cors.cfg'), 'r').read().strip())

1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
  def test_slave_partition_state(self):
    partition_path = self.getSlavePartitionPath()
    self.assertTrue(
      '-grace 2s' in
      open(os.path.join(partition_path, 'bin', 'caddy-wrapper'), 'r').read()
    )

    self.assertTrue(
      '-grace 2s' in
      open(os.path.join(partition_path, 'bin', 'nginx-wrapper'), 'r').read()
    )

1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
  def test_monitor_conf(self):
    monitor_conf_list = glob.glob(
      os.path.join(
        self.instance_path, '*', 'etc', 'monitor.conf'
      ))
    self.assertEqual(2, len(monitor_conf_list))
    expected = [(False, q) for q in monitor_conf_list]
    got = [('!py!' in open(q).read(), q) for q in monitor_conf_list]
    # check that no monitor.conf in generated configuratio has magic !py!
    self.assertEqual(
      expected,
      got
    )

1259 1260
  def assertSlaveBase(self, reference):
    parameter_dict = self.parseSlaveParameterDict(reference)
1261
    self.assertLogAccessUrlWithPop(parameter_dict)
1262 1263
    self.assertKedifaKeysWithPop(parameter_dict, '')
    hostname = reference.translate(None, '_-').lower()
1264 1265
    self.assertEqual(
      {
1266
        'domain': '%s.example.com' % (hostname,),
1267
        'replication_number': '1',
1268 1269 1270
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
1271
        'public-ipv4': SLAPOS_TEST_IPV4,
1272 1273
      },
      parameter_dict
1274 1275
    )

1276 1277 1278 1279
    return parameter_dict

  def test_empty(self):
    parameter_dict = self.assertSlaveBase('empty')
1280 1281 1282
    result = self.fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
    self.assertEqual(
1283
      self.certificate_pem,
1284
      der2pem(result.peercert))
1285

1286
    self.assertEqual(httplib.NOT_FOUND, result.status_code)
1287 1288 1289 1290 1291 1292 1293

    # check that log file contains verbose log
    log_file = glob.glob(
      os.path.join(
        self.instance_path, '*', 'var', 'log', 'httpd', '_empty_access_log'
      ))[0]

1294
    log_regexp = r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} - SOME_REMOTE_USER ' \
1295 1296 1297
                 r'\[\d{2}\/.{3}\/\d{4}\:\d{2}\:\d{2}\:\d{2} \+\d{4}\] ' \
                 r'"GET \/test-path HTTP\/1.1" 404 \d+ "-" '\
                 r'"python-requests.*" \d+'
1298

1299 1300
    self.assertRegexpMatches(
      open(log_file, 'r').read(),
1301
      log_regexp)
1302 1303
    result_http = self.fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
1304
    self.assertEqual(httplib.NOT_FOUND, result_http.status_code)
1305 1306 1307 1308

    # check that 404 is as configured
    result_missing = self.fakeHTTPSResult(
      'forsuredoesnotexists.example.com', parameter_dict['public-ipv4'], '')
1309
    self.assertEqual(httplib.NOT_FOUND, result_missing.status_code)
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
    self.assertEqual(
      """<html>
<head>
  <title>Instance not found</title>
</head>
<body>
<h1>This instance has not been found.</h1>
<p>If this error persists, please check your instance URL and status on S"""
      """lapOS Master.</p>
</body>
</html>
""",
      result_missing.text
    )

  def test_url(self):
1326
    parameter_dict = self.assertSlaveBase('Url')
1327 1328

    result = self.fakeHTTPSResult(
1329
      parameter_dict['domain'], parameter_dict['public-ipv4'],
1330 1331 1332
      'test-path/deep/.././deeper',
      headers={'Timeout': '10'}  # more than default proxy-try-duration == 5
    )
1333 1334

    self.assertEqual(
1335
      self.certificate_pem,
1336
      der2pem(result.peercert))
1337

1338
    self.assertEqualResultJson(result, 'Path', '/test-path/deeper')
1339 1340 1341 1342 1343 1344 1345

    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
    self.assertFalse('remote_user' in j['Incoming Headers'].keys())

1346 1347
    self.assertEqual(j['Incoming Headers']['timeout'], '10')

1348
    self.assertFalse('Content-Encoding' in result.headers)
1349

1350
    self.assertEqual(
1351 1352
      'secured=value;secure, nonsecured=value',
      result.headers['Set-Cookie']
1353 1354 1355
    )

    result_http = self.fakeHTTPResult(
1356 1357 1358
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
    self.assertEqualResultJson(result_http, 'Path', '/test-path/deeper')
1359 1360 1361 1362 1363 1364 1365

    try:
      j = result_http.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
    self.assertFalse('remote_user' in j['Incoming Headers'].keys())

1366
    self.assertFalse('Content-Encoding' in result_http.headers)
1367

1368
    self.assertEqual(
1369 1370
      'secured=value;secure, nonsecured=value',
      result_http.headers['Set-Cookie']
1371 1372
    )

1373 1374
    # check that try_duration == 5 in the test_url slave
    slave_configuration_file = glob.glob(os.path.join(
1375
      self.instance_path, '*', 'etc', '*slave-conf.d', '_Url.conf'))[0]
1376 1377 1378 1379 1380
    with open(slave_configuration_file) as fh:
      content = fh.read()
      self.assertTrue('try_duration 5s' in content)
      self.assertTrue('try_interval 250ms' in content)

1381
  @skip('Feature postponed')
1382
  def test_url_ipv6_access(self):
1383
    parameter_dict = self.parseSlaveParameterDict('url')
1384
    self.assertLogAccessUrlWithPop(parameter_dict)
1385 1386 1387 1388 1389 1390 1391
    self.assertEqual(
      {
        'domain': 'url.example.com',
        'replication_number': '1',
        'url': 'http://url.example.com',
        'site_url': 'http://url.example.com',
        'secure_access': 'https://url.example.com',
1392
        'public-ipv4': SLAPOS_TEST_IPV4,
1393 1394
      },
      parameter_dict
1395 1396 1397
    )

    result_ipv6 = self.fakeHTTPSResult(
1398 1399
      parameter_dict['domain'], SLAPOS_TEST_IPV6, 'test-path',
      source_ip=SLAPOS_TEST_IPV6)
1400 1401

    self.assertEqual(
1402
       SLAPOS_TEST_IPV6,
1403
       result_ipv6.json()['Incoming Headers']['x-forwarded-for']
1404 1405 1406
    )

    self.assertEqual(
1407
      self.certificate_pem,
1408
      der2pem(result_ipv6.peercert))
1409 1410 1411 1412

    self.assertEqualResultJson(result_ipv6, 'Path', '/test-path')

  def test_type_zope_path(self):
1413
    parameter_dict = self.assertSlaveBase('type-zope-path')
1414 1415

    result = self.fakeHTTPSResult(
1416 1417
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
1418 1419

    self.assertEqual(
1420
      self.certificate_pem,
1421
      der2pem(result.peercert))
1422 1423 1424 1425

    self.assertEqualResultJson(
      result,
      'Path',
1426 1427 1428 1429
      '/VirtualHostBase/'
      'https//typezopepath.example.com:443/path/to/some/resource'
      '/VirtualHostRoot/'
      'test-path/deeper'
1430 1431 1432
    )

  def test_type_zope_default_path(self):
1433
    parameter_dict = self.assertSlaveBase('type-zope-default-path')
1434 1435 1436 1437 1438

    result = self.fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], '')

    self.assertEqual(
1439
      self.certificate_pem,
1440
      der2pem(result.peercert))
1441

1442 1443 1444 1445 1446
    self.assertEqual(
      httplib.MOVED_PERMANENTLY,
      result.status_code
    )

1447
    self.assertEqual(
1448 1449
      'https://typezopedefaultpath.example.com:%s/'
      'default-path/to/some/resource' % (
1450 1451
        HTTPS_PORT,),
      result.headers['Location']
1452 1453 1454
    )

  def test_server_alias(self):
1455
    parameter_dict = self.assertSlaveBase('server-alias')
1456 1457

    result = self.fakeHTTPSResult(
1458 1459
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
1460 1461

    self.assertEqual(
1462
      self.certificate_pem,
1463
      der2pem(result.peercert))
1464

1465
    self.assertEqualResultJson(result, 'Path', '/test-path/deeper')
1466 1467

    result = self.fakeHTTPSResult(
1468 1469
      'alias1.example.com', parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
1470 1471

    self.assertEqual(
1472
      self.certificate_pem,
1473
      der2pem(result.peercert))
1474

1475
    self.assertEqualResultJson(result, 'Path', '/test-path/deeper')
1476 1477

    result = self.fakeHTTPSResult(
1478 1479
      'alias2.example.com', parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
1480 1481

    self.assertEqual(
1482
      self.certificate_pem,
1483
      der2pem(result.peercert))
1484

1485
  def test_server_alias_wildcard(self):
1486
    parameter_dict = self.parseSlaveParameterDict('server-alias-wildcard')
1487
    self.assertLogAccessUrlWithPop(parameter_dict)
1488
    self.assertKedifaKeysWithPop(parameter_dict)
1489 1490 1491 1492 1493 1494 1495
    self.assertEqual(
      {
        'domain': 'serveraliaswildcard.example.com',
        'replication_number': '1',
        'url': 'http://serveraliaswildcard.example.com',
        'site_url': 'http://serveraliaswildcard.example.com',
        'secure_access': 'https://serveraliaswildcard.example.com',
1496
        'public-ipv4': SLAPOS_TEST_IPV4,
1497 1498 1499 1500 1501 1502 1503 1504
      },
      parameter_dict
    )

    result = self.fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
1505
      self.certificate_pem,
1506 1507 1508 1509 1510 1511 1512 1513
      der2pem(result.peercert))

    self.assertEqualResultJson(result, 'Path', '/test-path')

    result = self.fakeHTTPSResult(
      'wild.alias1.example.com', parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
1514
      self.certificate_pem,
1515 1516
      der2pem(result.peercert))

1517 1518
    self.assertEqualResultJson(result, 'Path', '/test-path')

1519
  def test_server_alias_duplicated(self):
1520
    parameter_dict = self.parseSlaveParameterDict('server-alias-duplicated')
1521
    self.assertLogAccessUrlWithPop(parameter_dict)
1522
    self.assertKedifaKeysWithPop(parameter_dict)
1523 1524 1525 1526 1527 1528 1529
    self.assertEqual(
      {
        'domain': 'serveraliasduplicated.example.com',
        'replication_number': '1',
        'url': 'http://serveraliasduplicated.example.com',
        'site_url': 'http://serveraliasduplicated.example.com',
        'secure_access': 'https://serveraliasduplicated.example.com',
1530
        'public-ipv4': SLAPOS_TEST_IPV4,
1531 1532 1533 1534 1535 1536 1537 1538
      },
      parameter_dict
    )

    result = self.fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
1539
      self.certificate_pem,
1540 1541 1542 1543 1544 1545 1546 1547
      der2pem(result.peercert))

    self.assertEqualResultJson(result, 'Path', '/test-path')

    result = self.fakeHTTPSResult(
      'alias3.example.com', parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
1548
      self.certificate_pem,
1549 1550 1551 1552 1553
      der2pem(result.peercert))

    self.assertEqualResultJson(result, 'Path', '/test-path')

  def test_server_alias_custom_domain_duplicated(self):
1554 1555
    parameter_dict = self.parseSlaveParameterDict(
      'server-alias_custom_domain-duplicated')
1556
    self.assertLogAccessUrlWithPop(parameter_dict)
1557
    self.assertKedifaKeysWithPop(parameter_dict)
1558 1559 1560 1561 1562 1563 1564
    self.assertEqual(
      {
        'domain': 'alias4.example.com',
        'replication_number': '1',
        'url': 'http://alias4.example.com',
        'site_url': 'http://alias4.example.com',
        'secure_access': 'https://alias4.example.com',
1565
        'public-ipv4': SLAPOS_TEST_IPV4,
1566 1567 1568 1569 1570 1571 1572 1573
      },
      parameter_dict
    )

    result = self.fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
1574
      self.certificate_pem,
1575 1576 1577 1578
      der2pem(result.peercert))

    self.assertEqualResultJson(result, 'Path', '/test-path')

1579 1580 1581 1582 1583 1584
  @skip('Feature postponed')
  def test_check_error_log(self):
    # Caddy: Need to implement similar thing like check-error-on-apache-log
    raise NotImplementedError(self.id())

  def test_ssl_ca_crt(self):
1585 1586
    parameter_dict = self.parseSlaveParameterDict(
      'custom_domain_ssl_crt_ssl_key_ssl_ca_crt')
1587
    self.assertLogAccessUrlWithPop(parameter_dict)
1588
    generate_auth, upload_url = self.assertKedifaKeysWithPop(parameter_dict)
1589 1590 1591 1592 1593 1594 1595 1596
    self.assertEqual(
      {
        'domain': 'customdomainsslcrtsslkeysslcacrt.example.com',
        'replication_number': '1',
        'url': 'http://customdomainsslcrtsslkeysslcacrt.example.com',
        'site_url': 'http://customdomainsslcrtsslkeysslcacrt.example.com',
        'secure_access':
        'https://customdomainsslcrtsslkeysslcacrt.example.com',
1597
        'public-ipv4': SLAPOS_TEST_IPV4,
1598 1599 1600
      },
      parameter_dict
    )
1601

1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
    # as now the place to put the key is known put the key there
    auth = requests.get(
      generate_auth,
      verify=self.ca_certificate_file)
    self.assertEqual(httplib.CREATED, auth.status_code)

    data = self.customdomain_ca_certificate_pem + \
        self.customdomain_ca_key_pem + \
        self.ca.certificate_pem

    upload = requests.put(
      upload_url + auth.text,
      data=data,
      verify=self.ca_certificate_file)
    self.assertEqual(httplib.CREATED, upload.status_code)

    # after partitions being processed the key will be used for this slave
    self.runComputerPartition(max_quantity=1)

1621 1622 1623 1624
    result = self.fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
1625
      self.customdomain_ca_certificate_pem,
1626 1627 1628 1629
      der2pem(result.peercert))

    self.assertEqualResultJson(result, 'Path', '/test-path')

1630 1631 1632 1633 1634 1635 1636 1637
    certificate_file_list = glob.