test.py 228 KB
Newer Older
Łukasz Nowak's avatar
Łukasz Nowak committed
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
Łukasz Nowak's avatar
Łukasz Nowak committed
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
Łukasz Nowak's avatar
Łukasz Nowak committed
32 33 34 35
from requests_toolbelt.adapters import source
import json
import multiprocessing
import subprocess
36
from unittest import skip
Łukasz Nowak's avatar
Łukasz Nowak committed
37 38
import ssl
from BaseHTTPServer import HTTPServer
39
from BaseHTTPServer import BaseHTTPRequestHandler
Łukasz Nowak's avatar
Łukasz Nowak committed
40
import time
41
import tempfile
42
import ipaddress
43 44
import StringIO
import gzip
45
import base64
46
import re
47
from slapos.recipe.librecipe import generateHashFromFiles
48
import xml.etree.ElementTree as ET
49
import urlparse
50
import socket
51 52


53 54 55 56
try:
    import lzma
except ImportError:
    from backports import lzma
Łukasz Nowak's avatar
Łukasz Nowak committed
57

58 59 60 61 62 63 64 65 66
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

67 68
from slapos.testing.testcase import makeModuleSetUpAndTestCaseClass
from slapos.testing.utils import findFreeTCPPort
69
from slapos.testing.utils import getPromisePluginParameterDict
70 71 72 73 74
setUpModule, SlapOSInstanceTestCase = makeModuleSetUpAndTestCaseClass(
    os.path.abspath(
        os.path.join(os.path.dirname(__file__), '..', 'software.cfg')))


Łukasz Nowak's avatar
Łukasz Nowak committed
75 76 77
# ports chosen to not collide with test systems
HTTP_PORT = '11080'
HTTPS_PORT = '11443'
78 79
CAUCASE_PORT = '15090'
KEDIFA_PORT = '15080'
Łukasz Nowak's avatar
Łukasz Nowak committed
80

81 82 83
# IP to originate requests from
# has to be not partition one
SOURCE_IP = '127.0.0.1'
Łukasz Nowak's avatar
Łukasz Nowak committed
84

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
# "--resolve" inspired from https://stackoverflow.com/a/44378047/9256748
DNS_CACHE = {}


def add_custom_dns(domain, port, ip):
  port = int(port)
  key = (domain, port)
  value = (socket.AF_INET, 1, 6, '', (ip, port))
  DNS_CACHE[key] = [value]


def new_getaddrinfo(*args):
  return DNS_CACHE[args[:2]]


Łukasz Nowak's avatar
Łukasz Nowak committed
100
# for development: debugging logs and install Ctrl+C handler
101
if os.environ.get('SLAPOS_TEST_DEBUG'):
Łukasz Nowak's avatar
Łukasz Nowak committed
102 103 104 105 106
  import logging
  logging.basicConfig(level=logging.DEBUG)
  import unittest
  unittest.installHandler()

107

108
def der2pem(der):
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  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


124
def createSelfSignedCertificate(name_list):
125
  key, key_pem = createKey()
126 127 128
  subject_alternative_name_list = x509.SubjectAlternativeName(
    [x509.DNSName(unicode(q)) for q in name_list]
  )
129
  subject = issuer = x509.Name([
130
    x509.NameAttribute(NameOID.COMMON_NAME, u'Test Self Signed Certificate'),
131 132 133 134 135
  ])
  certificate = x509.CertificateBuilder().subject_name(
    subject
  ).issuer_name(
    issuer
136 137 138
  ).add_extension(
      subject_alternative_name_list,
      critical=False,
139 140 141 142 143 144 145 146 147 148 149 150 151
  ).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


152
def createCSR(common_name, ip=None):
153
  key, key_pem = createKey()
154 155 156 157 158
  subject_alternative_name_list = []
  if ip is not None:
    subject_alternative_name_list.append(
      x509.IPAddress(ipaddress.ip_address(unicode(ip)))
    )
159 160
  csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([
     x509.NameAttribute(NameOID.COMMON_NAME, unicode(common_name)),
161 162 163 164 165 166 167 168 169
  ]))

  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())
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
  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,
204
      extensions=csr.extensions,
205 206 207 208 209 210 211 212 213 214 215 216
      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)
Łukasz Nowak's avatar
Łukasz Nowak committed
217

218

219
def subprocess_status_output(*args, **kwargs):
220 221 222 223
  prc = subprocess.Popen(
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    *args,
224
    **kwargs)
225
  out, err = prc.communicate()
226 227 228 229 230
  return prc.returncode, out


def subprocess_output(*args, **kwargs):
  return subprocess_status_output(*args, **kwargs)[1]
231 232


Łukasz Nowak's avatar
Łukasz Nowak committed
233
def isHTTP2(domain, ip):
234
  curl_command = 'curl --http2 -v -k -H "Host: %(domain)s" ' \
Łukasz Nowak's avatar
Łukasz Nowak committed
235 236
    'https://%(domain)s:%(https_port)s/ '\
    '--resolve %(domain)s:%(https_port)s:%(ip)s' % dict(
237
      ip=ip, domain=domain, https_port=HTTPS_PORT)
Łukasz Nowak's avatar
Łukasz Nowak committed
238 239 240 241 242 243 244 245 246 247 248 249 250
  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


class TestDataMixin(object):
  def getTrimmedProcessInfo(self):
    return '\n'.join(sorted([
      '%(group)s:%(name)s %(statename)s' % q for q
251 252
      in self.callSupervisorMethod('getAllProcessInfo')
      if q['name'] != 'watchdog' and q['group'] != 'watchdog']))
Łukasz Nowak's avatar
Łukasz Nowak committed
253

254 255
  def assertTestData(self, runtime_data, hash_value_dict=None, msg=None):
    if hash_value_dict is None:
256
      hash_value_dict = {}
257
    filename = '%s-%s.txt' % (self.id(), 'CADDY')
Łukasz Nowak's avatar
Łukasz Nowak committed
258 259 260 261 262 263 264 265
    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 = ''

266 267 268
    for hash_type, hash_value in hash_value_dict.items():
      runtime_data = runtime_data.replace(hash_value, '{hash-%s}' % (
        hash_type),)
269

Łukasz Nowak's avatar
Łukasz Nowak committed
270 271
    maxDiff = self.maxDiff
    self.maxDiff = None
272 273
    longMessage = self.longMessage
    self.longMessage = True
Łukasz Nowak's avatar
Łukasz Nowak committed
274 275 276
    try:
      self.assertMultiLineEqual(
        test_data,
277 278
        runtime_data,
        msg=msg
Łukasz Nowak's avatar
Łukasz Nowak committed
279 280 281
      )
    except AssertionError:
      if os.environ.get('SAVE_TEST_DATA', '0') == '1':
282
        open(test_data_file, 'w').write(runtime_data.strip() + '\n')
Łukasz Nowak's avatar
Łukasz Nowak committed
283 284 285
      raise
    finally:
      self.maxDiff = maxDiff
286
      self.longMessage = longMessage
Łukasz Nowak's avatar
Łukasz Nowak committed
287

288 289 290
  def _test_file_list(self, slave_dir_list, IGNORE_PATH_LIST=None):
    if IGNORE_PATH_LIST is None:
      IGNORE_PATH_LIST = []
Łukasz Nowak's avatar
Łukasz Nowak committed
291
    runtime_data = []
292 293
    for slave_var in glob.glob(os.path.join(self.instance_path, '*')):
      for entry in os.walk(os.path.join(slave_var, *slave_dir_list)):
Łukasz Nowak's avatar
Łukasz Nowak committed
294 295 296 297 298 299 300 301 302
        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):
303
    self._test_file_list(['var', 'log'], [
304 305
      # no control at all when cron would kick in, ignore it
      'cron.log',
306 307 308 309
      # appears late and is quite unstable, no need to assert
      'trafficserver/.diags.log.meta',
      'trafficserver/.manager.log.meta',
      'trafficserver/.squid.log.meta',
Łukasz Nowak's avatar
Łukasz Nowak committed
310
      'trafficserver/diags.log',
311
      'trafficserver/squid.log',
312
      # not important, appears sometimes
313 314
      'trafficserver/.error.log.meta',
      'trafficserver/error.log',
315 316
      'trafficserver/.traffic.out.meta',
      'trafficserver/traffic.out',
Łukasz Nowak's avatar
Łukasz Nowak committed
317 318 319
    ])

  def test_file_list_run(self):
320
    self._test_file_list(['var', 'run'], [
321 322 323
      # can't be sure regarding its presence
      'caddy_configuration_last_state',
      'validate_configuration_state_signature',
Łukasz Nowak's avatar
Łukasz Nowak committed
324 325
      # run by cron from time to time
      'monitor/monitor-collect.pid',
326 327
      # no control regarding if it would or not be running
      'monitor/monitor-bootstrap.pid',
Łukasz Nowak's avatar
Łukasz Nowak committed
328 329
    ])

330 331 332
  def test_file_list_etc_cron_d(self):
    self._test_file_list(['etc', 'cron.d'])

333 334 335
  def test_file_list_plugin(self):
    self._test_file_list(['etc', 'plugin'], ['.pyc'])

Łukasz Nowak's avatar
Łukasz Nowak committed
336 337 338
  def test_supervisor_state(self):
    # give a chance for etc/run scripts to finish
    time.sleep(1)
339

340 341 342
    hash_file_list = [os.path.join(
        self.computer_partition_root_path, 'software_release/buildout.cfg')]
    hash_value_dict = {
343
      'generic': generateHashFromFiles(hash_file_list),
344 345 346 347 348
    }
    for caddy_wrapper_path in glob.glob(os.path.join(
      self.instance_path, '*', 'bin', 'caddy-wrapper')):
      partition_id = caddy_wrapper_path.split('/')[-3]
      hash_value_dict[
349
        'caddy-%s' % (partition_id)] = generateHashFromFiles(
350
        [caddy_wrapper_path] + hash_file_list
351
      )
352 353 354 355 356 357 358
    for backend_haproxy_wrapper_path in glob.glob(os.path.join(
      self.instance_path, '*', 'bin', 'backend-haproxy-wrapper')):
      partition_id = backend_haproxy_wrapper_path.split('/')[-3]
      hash_value_dict[
        'backend-haproxy-%s' % (partition_id)] = generateHashFromFiles(
        [backend_haproxy_wrapper_path] + hash_file_list
      )
359
    for rejected_slave_publish_path in glob.glob(os.path.join(
360
      self.instance_path, '*', 'etc', 'nginx-rejected-slave.conf')):
361 362 363 364 365
      partition_id = rejected_slave_publish_path.split('/')[-3]
      rejected_slave_pem_path = os.path.join(
        self.instance_path, partition_id, 'etc', 'rejected-slave.pem')
      hash_value_dict[
        'rejected-slave-publish'
366
      ] = generateHashFromFiles(
367
        [rejected_slave_publish_path, rejected_slave_pem_path] + hash_file_list
368
      )
369

Łukasz Nowak's avatar
Łukasz Nowak committed
370
    runtime_data = self.getTrimmedProcessInfo()
371
    self.assertTestData(runtime_data, hash_value_dict=hash_value_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
372

373

374
def fakeHTTPSResult(domain, real_ip, path, port=HTTPS_PORT,
375
                    headers=None, cookies=None, source_ip=SOURCE_IP):
376 377 378 379 380
  if headers is None:
    headers = {}
  # workaround request problem of setting Accept-Encoding
  # https://github.com/requests/requests/issues/2234
  headers.setdefault('Accept-Encoding', 'dummy')
381 382 383 384 385
  # Headers to tricks the whole system, like rouge user would do
  headers.setdefault('X-Forwarded-For', '192.168.0.1')
  headers.setdefault('X-Forwarded-Proto', 'irc')
  headers.setdefault('X-Forwarded-Port', '17')

386 387 388 389 390
  session = requests.Session()
  if source_ip is not None:
    new_source = source.SourceAddressAdapter(source_ip)
    session.mount('http://', new_source)
    session.mount('https://', new_source)
391 392 393 394 395 396 397 398 399 400 401 402 403
  socket_getaddrinfo = socket.getaddrinfo
  try:
    add_custom_dns(domain, port, real_ip)
    socket.getaddrinfo = new_getaddrinfo
    return session.get(
      'https://%s:%s/%s' % (domain, port, path),
      verify=False,
      allow_redirects=False,
      headers=headers,
      cookies=cookies
    )
  finally:
    socket.getaddrinfo = socket_getaddrinfo
404 405 406


def fakeHTTPResult(domain, real_ip, path, port=HTTP_PORT,
407
                   headers=None, source_ip=SOURCE_IP):
408 409 410 411 412
  if headers is None:
    headers = {}
  # workaround request problem of setting Accept-Encoding
  # https://github.com/requests/requests/issues/2234
  headers.setdefault('Accept-Encoding', 'dummy')
413 414 415 416 417 418 419 420 421 422 423
  # Headers to tricks the whole system, like rouge user would do
  headers.setdefault('X-Forwarded-For', '192.168.0.1')
  headers.setdefault('X-Forwarded-Proto', 'irc')
  headers.setdefault('X-Forwarded-Port', '17')
  headers['Host'] = '%s:%s' % (domain, port)
  session = requests.Session()
  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(
424 425 426 427 428
    'http://%s:%s/%s' % (real_ip, port, path),
    headers=headers,
    allow_redirects=False,
  )

429

430
class TestHandler(BaseHTTPRequestHandler):
431 432
  identification = None

433 434 435 436 437
  def do_GET(self):
    timeout = int(self.headers.dict.get('timeout', '0'))
    compress = int(self.headers.dict.get('compress', '0'))
    time.sleep(timeout)
    self.send_response(200)
Łukasz Nowak's avatar
Łukasz Nowak committed
438

439 440 441
    if self.identification is not None:
      self.send_header('X-Backend-Identification', self.identification)

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
    drop_header_list = []
    for header in self.headers.dict.get('x-drop-header', '').split():
      drop_header_list.append(header)
    prefix = 'x-reply-header-'
    length = len(prefix)
    for key, value in self.headers.dict.items():
      if key.startswith(prefix):
        self.send_header(
          '-'.join([q.capitalize() for q in key[length:].split('-')]),
          value.strip()
        )

    if 'Content-Type' not in drop_header_list:
      self.send_header("Content-Type", "application/json")
    if 'Set-Cookie' not in drop_header_list:
      self.send_header('Set-Cookie', 'secured=value;secure')
      self.send_header('Set-Cookie', 'nonsecured=value')

    if 'x-reply-body' not in self.headers.dict:
      response = {
        'Path': self.path,
        'Incoming Headers': self.headers.dict
      }
      response = json.dumps(response, indent=2)
    else:
      response = base64.b64decode(self.headers.dict['x-reply-body'])
    if compress:
      self.send_header('Content-Encoding', 'gzip')
      out = StringIO.StringIO()
      # compress with level 0, to find out if in the middle someting would
      # like to alter the compression
      with gzip.GzipFile(fileobj=out, mode="w", compresslevel=0) as f:
        f.write(response)
      response = out.getvalue()
      self.send_header('Backend-Content-Length', len(response))
    if 'Content-Length' not in drop_header_list:
      self.send_header('Content-Length', len(response))
    self.end_headers()
    self.wfile.write(response)


483
class HttpFrontendTestCase(SlapOSInstanceTestCase):
484 485 486
  # show full diffs, as it is required for proper analysis of problems
  maxDiff = None

487 488 489
  # minimise partition path
  __partition_reference__ = 'T-'

490
  @classmethod
491 492 493 494 495
  def getInstanceSoftwareType(cls):
    # Because of unknown problem yet, the root instance software type changes
    # from RootSoftwareInstance to '', so always request it with given type
    return "RootSoftwareInstance"

Łukasz Nowak's avatar
Łukasz Nowak committed
496
  @classmethod
497
  def prepareCertificate(cls):
498
    cls.another_server_ca = CertificateAuthority("Another Server Root CA")
499 500
    cls.test_server_ca = CertificateAuthority("Test Server Root CA")
    key, key_pem, csr, csr_pem = createCSR(
501
      "testserver.example.com", cls._ipv4_address)
502 503 504 505 506 507 508 509 510 511
    _, 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()
512 513 514 515 516 517 518 519 520 521 522

  @classmethod
  def startServerProcess(cls):
    server = HTTPServer(
      (cls._ipv4_address, cls._server_http_port),
      TestHandler)

    server_https = HTTPServer(
      (cls._ipv4_address, cls._server_https_port),
      TestHandler)

Łukasz Nowak's avatar
Łukasz Nowak committed
523 524
    server_https.socket = ssl.wrap_socket(
      server_https.socket,
525
      certfile=cls.test_server_certificate_file.name,
Łukasz Nowak's avatar
Łukasz Nowak committed
526 527
      server_side=True)

528
    cls.backend_url = 'http://%s:%s/' % server.server_address
529 530
    cls.server_process = multiprocessing.Process(
      target=server.serve_forever, name='HTTPServer')
Łukasz Nowak's avatar
Łukasz Nowak committed
531
    cls.server_process.start()
532 533
    cls.logger.debug('Started process %s' % (cls.server_process,))

534
    cls.backend_https_url = 'https://%s:%s/' % server_https.server_address
Łukasz Nowak's avatar
Łukasz Nowak committed
535
    cls.server_https_process = multiprocessing.Process(
536
      target=server_https.serve_forever, name='HTTPSServer')
Łukasz Nowak's avatar
Łukasz Nowak committed
537
    cls.server_https_process.start()
538
    cls.logger.debug('Started process %s' % (cls.server_https_process,))
Łukasz Nowak's avatar
Łukasz Nowak committed
539 540

  @classmethod
541
  def cleanUpCertificate(cls):
542 543
    if getattr(cls, 'test_server_certificate_file', None) is not None:
      os.unlink(cls.test_server_certificate_file.name)
544 545 546

  @classmethod
  def stopServerProcess(cls):
547 548 549
    for server in ['server_process', 'server_https_process']:
      process = getattr(cls, server, None)
      if process is not None:
550 551
        cls.logger.debug('Stopping process %s' % (process,))
        process.join(10)
552
        process.terminate()
553 554 555 556
        time.sleep(0.1)
        if process.is_alive():
          cls.logger.warning(
            'Process %s still alive' % (process, ))
Łukasz Nowak's avatar
Łukasz Nowak committed
557

558 559 560 561 562
  @classmethod
  def setUpMaster(cls):
    # run partition until AIKC finishes
    cls.runComputerPartitionUntil(
      cls.untilNotReadyYetNotInMasterKeyGenerateAuthUrl)
563
    parameter_dict = cls.requestDefaultInstance().getConnectionParameterDict()
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
    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

579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
  @classmethod
  def runKedifaUpdater(cls):
    kedifa_updater = None
    for kedifa_updater in sorted(glob.glob(
        os.path.join(
          cls.instance_path, '*', 'etc', 'service', 'kedifa-updater*'))):
      # fetch first kedifa-updater, as by default most of the tests are using
      # only one running partition; in case if test does not need
      # kedifa-updater this method can be overridden
      break
    if kedifa_updater is not None:
      # try few times kedifa_updater
      for i in range(10):
        return_code, output = subprocess_status_output(
          [kedifa_updater, '--once'])
        if return_code == 0:
          break
        # wait for the other updater to work
        time.sleep(2)
      # assert that in the worst case last run was correct
      assert return_code == 0, output
      # give caddy a moment to refresh its config, as sending signal does not
      # block until caddy is refreshed
      time.sleep(2)

604 605 606
  @classmethod
  def createWildcardExampleComCertificate(cls):
    _, cls.key_pem, _, cls.certificate_pem = createSelfSignedCertificate(
607 608 609 610 611
      [
        '*.customdomain.example.com',
        '*.example.com',
        '*.alias1.example.com',
      ])
612

Łukasz Nowak's avatar
Łukasz Nowak committed
613
  @classmethod
614 615 616
  def runComputerPartitionUntil(cls, until):
    max_try = 10
    try_num = 1
617
    while True:
618 619 620 621
      if until():
        break
      if try_num > max_try:
        raise ValueError('Failed to run computer partition with %r' % (until,))
622
      try:
623
        cls.slap.waitForInstance()
624
      except Exception:
625 626
        cls.logger.exception("Error during until run")
      try_num += 1
Łukasz Nowak's avatar
Łukasz Nowak committed
627 628

  @classmethod
629 630 631 632 633 634 635 636 637 638 639 640 641 642
  def untilNotReadyYetNotInMasterKeyGenerateAuthUrl(cls):
    parameter_dict = cls.requestDefaultInstance().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

  @classmethod
  def callSupervisorMethod(cls, method, *args, **kwargs):
    with cls.slap.instance_supervisor_rpc as instance_supervisor:
      return getattr(instance_supervisor, method)(*args, **kwargs)

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
  def assertRejectedSlavePromiseWithPop(self, parameter_dict):
    rejected_slave_promise_url = parameter_dict.pop(
      'rejected-slave-promise-url')

    try:
      result = requests.get(rejected_slave_promise_url, verify=False)
      if result.text == '':
        result_json = {}
      else:
        result_json = result.json()
      self.assertEqual(
        parameter_dict['rejected-slave-dict'],
        result_json
      )
    except AssertionError:
      raise
    except Exception as e:
      self.fail(e)

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
  def assertLogAccessUrlWithPop(self, parameter_dict):
    log_access_url = parameter_dict.pop('log-access-url')

    self.assertTrue(len(log_access_url) >= 1)
    # check only the first one, as second frontend will be stopped
    log_access = log_access_url[0]
    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(
      httplib.OK,
      result.status_code,
      'While accessing %r of %r the status code was %r' % (
        url, frontend, result.status_code))
678 679 680 681 682 683 684 685 686
    # check that the result is correct JSON, which allows to access
    # information about all logs
    self.assertEqual(
      'application/json',
      result.headers['Content-Type']
    )
    self.assertEqual(
      sorted([q['name'] for q in result.json()]),
      ['access.log', 'backend.log', 'error.log'])
687 688 689 690 691 692 693 694
    self.assertEqual(
      httplib.OK,
      requests.get(url + 'access.log', verify=False).status_code
    )
    self.assertEqual(
      httplib.OK,
      requests.get(url + 'error.log', verify=False).status_code
    )
695 696
    # assert only for few tests, as backend log is not available for many of
    # them, as it's created on the fly
697 698
    for test_name in [
      'test_url', 'test_auth_to_backend', 'test_compressed_result']:
699 700 701 702 703
      if self.id().endswith(test_name):
        self.assertEqual(
          httplib.OK,
          requests.get(url + 'backend.log', verify=False).status_code
        )
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728

  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,))
    kedifa_ipv6_base = 'https://[%s]:%s' % (self._ipv6_address, KEDIFA_PORT)
    base = '^' + kedifa_ipv6_base.replace(
      '[', r'\[').replace(']', r'\]') + '/.{32}'
    self.assertRegexpMatches(
      generate_auth_url,
      base + r'\/generateauth$'
    )
    self.assertRegexpMatches(
      upload_url,
      base + r'\?auth=$'
    )

    kedifa_caucase_url = parameter_dict.pop('kedifa-caucase-url')
    self.assertEqual(
      kedifa_caucase_url,
      'http://[%s]:%s' % (self._ipv6_address, CAUCASE_PORT),
    )

    return generate_auth_url, upload_url

729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
  def assertBackendHaproxyStatisticUrl(self, parameter_dict):
    url_key = 'caddy-frontend-1-backend-haproxy-statistic-url'
    backend_haproxy_statistic_url_dict = {}
    for key in parameter_dict.keys():
      if key.startswith('caddy-frontend') and key.endswith(
        'backend-haproxy-statistic-url'):
        backend_haproxy_statistic_url_dict[key] = parameter_dict.pop(key)
    self.assertEqual(
      [url_key],
      backend_haproxy_statistic_url_dict.keys()
    )

    backend_haproxy_statistic_url = backend_haproxy_statistic_url_dict[url_key]
    result = requests.get(
      backend_haproxy_statistic_url,
      verify=False,
    )
    self.assertEqual(httplib.OK, result.status_code)
    self.assertIn('testing partition 0', result.text)
    self.assertIn('Statistics Report for HAProxy', result.text)

750 751 752 753 754 755 756 757 758 759 760
  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))
    self.assertEqual(value, j[key])
Łukasz Nowak's avatar
Łukasz Nowak committed
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802

  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()
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 850 851 852 853 854 855 856 857 858 859 860 861 862
    super(HttpFrontendTestCase, self).tearDown()

  def parseParameterDict(self, parameter_dict):
    parsed_parameter_dict = {}
    for key, value in parameter_dict.items():
      if key in [
        'rejected-slave-dict',
        'warning-slave-dict',
        'warning-list',
        'request-error-list',
        'log-access-url']:
        value = json.loads(value)
      parsed_parameter_dict[key] = value
    return parsed_parameter_dict

  def getMasterPartitionPath(self):
    return '/' + os.path.join(
      *glob.glob(
        os.path.join(
          self.instance_path, '*', 'etc', 'Caddyfile-rejected-slave'
        )
      )[0].split('/')[:-2])

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

  @classmethod
  def waitForMethod(cls, name, method):
    wait_time = 600
    begin = time.time()
    try_num = 0
    cls.logger.debug('%s for %is' % (name, wait_time,))
    while True:
      try:
        try_num += 1
        method()
      except Exception:
        if time.time() - begin > wait_time:
          cls.logger.exception(
            "Error during %s after %.2fs" % (name, (time.time() - begin),))
          raise
        else:
          time.sleep(0.5)
      else:
        cls.logger.info("%s took %.2fs" % (name, (time.time() - begin),))
        break

  @classmethod
  def waitForCaddy(cls):
    def method():
      fakeHTTPSResult(
        cls._ipv4_address, cls._ipv4_address,
        '/',
      )
    cls.waitForMethod('waitForCaddy', method)

  @classmethod
  def _cleanup(cls, snapshot_name):
863
    cls.cleanUpCertificate()
864 865 866 867 868 869 870
    cls.stopServerProcess()
    super(HttpFrontendTestCase, cls)._cleanup(snapshot_name)

  @classmethod
  def setUpClass(cls):
    try:
      cls.createWildcardExampleComCertificate()
871 872 873 874 875
      cls.prepareCertificate()
      # find ports once to be able startServerProcess many times
      cls._server_http_port = findFreeTCPPort(cls._ipv4_address)
      cls._server_https_port = findFreeTCPPort(cls._ipv4_address)
      cls._server_https_auth_port = findFreeTCPPort(cls._ipv4_address)
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 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 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
      cls.startServerProcess()
    except BaseException:
      cls.logger.exception("Error during setUpClass")
      cls._cleanup("{}.{}.setUpClass".format(cls.__module__, cls.__name__))
      cls.setUp = lambda self: self.fail('Setup Class failed.')
      raise

    super(HttpFrontendTestCase, cls).setUpClass()

    try:
      # expose instance directory
      cls.instance_path = cls.slap.instance_directory
      # expose software directory, extract from found computer partition
      cls.software_path = os.path.realpath(os.path.join(
          cls.computer_partition_root_path, 'software_release'))
      # do working directory
      cls.working_directory = os.path.join(os.path.realpath(
          os.environ.get(
              'SLAPOS_TEST_WORKING_DIR',
              os.path.join(os.getcwd(), '.slapos'))),
          'caddy-frontend-test')
      if not os.path.isdir(cls.working_directory):
        os.mkdir(cls.working_directory)
      cls.setUpMaster()
      cls.waitForCaddy()
    except BaseException:
      cls.logger.exception("Error during setUpClass")
      # "{}.{}.setUpClass".format(cls.__module__, cls.__name__) is already used
      # by SlapOSInstanceTestCase.setUpClass so we use another name for
      # snapshot, to make sure we don't store another snapshot in same
      # directory.
      cls._cleanup("{}.SlaveHttpFrontendTestCase.{}.setUpClass".format(
        cls.__module__, cls.__name__))
      cls.setUp = lambda self: self.fail('Setup Class failed.')
      raise


class SlaveHttpFrontendTestCase(HttpFrontendTestCase):
  @classmethod
  def requestDefaultInstance(cls, state='started'):
    default_instance = super(
      SlaveHttpFrontendTestCase, cls).requestDefaultInstance(state=state)
    if state != 'destroyed':
      cls.requestSlaves()
    return default_instance

  @classmethod
  def requestSlaves(cls):
    software_url = cls.getSoftwareURL()
    for slave_reference, partition_parameter_kw in cls\
            .getSlaveParameterDictDict().items():
      cls.logger.debug(
        'requesting slave "%s" software:%s parameters:%s',
        slave_reference, software_url, partition_parameter_kw)
      cls.slap.request(
        software_release=software_url,
        partition_reference=slave_reference,
        partition_parameter_kw=partition_parameter_kw,
        shared=True
      )

  @classmethod
  def setUpClass(cls):
    super(SlaveHttpFrontendTestCase, cls).setUpClass()

    try:
      cls.setUpSlaves()
      cls.waitForSlave()
    except BaseException:
      cls.logger.exception("Error during setUpClass")
      # "{}.{}.setUpClass".format(cls.__module__, cls.__name__) is already used
      # by SlapOSInstanceTestCase.setUpClass so we use another name for
      # snapshot, to make sure we don't store another snapshot in same
      # directory.
      cls._cleanup("{}.SlaveHttpFrontendTestCase.{}.setUpClass".format(
        cls.__module__, cls.__name__))
      cls.setUp = lambda self: self.fail('Setup Class failed.')
      raise

  @classmethod
  def waitForSlave(cls):
    def method():
      for parameter_dict in cls.getSlaveConnectionParameterDictList():
        if 'domain' in parameter_dict and 'public-ipv4' in parameter_dict:
          try:
            fakeHTTPSResult(
              parameter_dict['domain'], parameter_dict['public-ipv4'], '/')
          except requests.exceptions.InvalidURL:
            # ignore slaves to which connection is impossible by default
            continue
    cls.waitForMethod('waitForSlave', method)

  @classmethod
  def getSlaveConnectionParameterDictList(cls):
    parameter_dict_list = []

    for slave_reference, partition_parameter_kw in cls\
            .getSlaveParameterDictDict().items():
      parameter_dict_list.append(cls.slap.request(
        software_release=cls.getSoftwareURL(),
        partition_reference=slave_reference,
        partition_parameter_kw=partition_parameter_kw,
        shared=True
      ).getConnectionParameterDict())
    return parameter_dict_list

  @classmethod
  def untilSlavePartitionReady(cls):
    # all on-watch services shall not be exited
    for process in cls.callSupervisorMethod('getAllProcessInfo'):
      if process['name'].endswith('-on-watch') and \
        process['statename'] == 'EXITED':
        if process['name'].startswith('monitor-http'):
          continue
        return False

    for parameter_dict in cls.getSlaveConnectionParameterDictList():
      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 not(log_access_ready and key_generate_auth_ready):
        return False

    return True

  @classmethod
  def setUpSlaves(cls):
    cls.runComputerPartitionUntil(
      cls.untilSlavePartitionReady)
1006 1007 1008 1009 1010 1011
    cls.updateSlaveConnectionParameterDictDict()

  @classmethod
  def updateSlaveConnectionParameterDictDict(cls):
    cls.slave_connection_parameter_dict_dict = {}
    # run partition for slaves to be setup
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
    request = cls.slap.request
    for slave_reference, partition_parameter_kw in cls\
            .getSlaveParameterDictDict().items():
      slave_instance = request(
        software_release=cls.getSoftwareURL(),
        partition_reference=slave_reference,
        partition_parameter_kw=partition_parameter_kw,
        shared=True
      )
      cls.slave_connection_parameter_dict_dict[slave_reference] = \
          slave_instance.getConnectionParameterDict()
Łukasz Nowak's avatar
Łukasz Nowak committed
1023

1024 1025 1026 1027 1028 1029 1030
  def parseSlaveParameterDict(self, key):
    return self.parseParameterDict(
      self.slave_connection_parameter_dict_dict[
        key
      ]
    )

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
  def assertSlaveBase(self, reference):
    parameter_dict = self.parseSlaveParameterDict(reference)
    self.assertLogAccessUrlWithPop(parameter_dict)
    self.assertKedifaKeysWithPop(parameter_dict, '')
    hostname = reference.translate(None, '_-').lower()
    self.assertEqual(
      {
        'domain': '%s.example.com' % (hostname,),
        'replication_number': '1',
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
1043
        'public-ipv4': self._ipv4_address,
1044
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
1045 1046 1047 1048 1049 1050
      },
      parameter_dict
    )

    return parameter_dict

Łukasz Nowak's avatar
Łukasz Nowak committed
1051

1052
class TestMasterRequestDomain(HttpFrontendTestCase, TestDataMixin):
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
    }

  def test(self):
    parameter_dict = self.parseConnectionParameterDict()
    self.assertKeyWithPop('monitor-setup-url', parameter_dict)
1066
    self.assertBackendHaproxyStatisticUrl(parameter_dict)
1067 1068 1069 1070 1071
    self.assertKedifaKeysWithPop(parameter_dict, 'master-')
    self.assertRejectedSlavePromiseWithPop(parameter_dict)

    self.assertEqual(
      {
1072
        'monitor-base-url': 'https://[%s]:8401' % self._ipv6_address,
1073
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
1074
        'domain': 'example.com',
1075
        'accepted-slave-amount': '0',
1076
        'rejected-slave-amount': '0',
1077
        'slave-amount': '0',
1078 1079 1080 1081 1082 1083
        'rejected-slave-dict': {}
      },
      parameter_dict
    )


1084
class TestMasterRequest(HttpFrontendTestCase, TestDataMixin):
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
    }

  def test(self):
    parameter_dict = self.parseConnectionParameterDict()
    self.assertKeyWithPop('monitor-setup-url', parameter_dict)
1097
    self.assertBackendHaproxyStatisticUrl(parameter_dict)
1098 1099 1100 1101
    self.assertKedifaKeysWithPop(parameter_dict, 'master-')
    self.assertRejectedSlavePromiseWithPop(parameter_dict)
    self.assertEqual(
      {
1102
        'monitor-base-url': 'https://[%s]:8401' % self._ipv6_address,
1103
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
1104
        'domain': 'None',
1105
        'accepted-slave-amount': '0',
1106
        'rejected-slave-amount': '0',
1107
        'slave-amount': '0',
1108 1109 1110 1111 1112
        'rejected-slave-dict': {}},
      parameter_dict
    )


Łukasz Nowak's avatar
Łukasz Nowak committed
1113 1114 1115 1116 1117
class TestSlave(SlaveHttpFrontendTestCase, TestDataMixin):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
1118
      'public-ipv4': cls._ipv4_address,
Łukasz Nowak's avatar
Łukasz Nowak committed
1119 1120
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
1121 1122
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
1123
      'mpm-graceful-shutdown-timeout': 2,
1124
      'request-timeout': '12',
Łukasz Nowak's avatar
Łukasz Nowak committed
1125 1126
    }

1127
  @classmethod
1128
  def prepareCertificate(cls):
1129 1130 1131 1132 1133
    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 = \
1134
        createSelfSignedCertificate(['customdomainsslcrtsslkey.example.com'])
1135
    super(TestSlave, cls).prepareCertificate()
1136

Łukasz Nowak's avatar
Łukasz Nowak committed
1137 1138 1139 1140 1141
  @classmethod
  def getSlaveParameterDictDict(cls):
    return {
      'empty': {
      },
1142
      'Url': {
1143 1144 1145
        # make URL "incorrect", with whitespace, nevertheless it shall be
        # correctly handled
        'url': ' ' + cls.backend_url + ' ',
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
        # authenticating to http backend shall be no-op
        'authenticate-to-backend': True,
      },
      'auth-to-backend': {
        # in here use reserved port for the backend, which is going to be
        # started later
        'url': 'https://%s:%s/' % (
          cls._ipv4_address, cls._server_https_auth_port),
        'authenticate-to-backend': True,
      },
      'auth-to-backend-not-configured': {
        # in here use reserved port for the backend, which is going to be
        # started later
        'url': 'https://%s:%s/' % (
          cls._ipv4_address, cls._server_https_auth_port),
      },
      'auth-to-backend-backend-ignore': {
        'url': cls.backend_https_url,
        'authenticate-to-backend': True,
Łukasz Nowak's avatar
Łukasz Nowak committed
1165 1166
      },
      'url_https-url': {
1167 1168
        'url': cls.backend_url + 'http',
        'https-url': cls.backend_url + 'https',
1169 1170 1171
        'backend-connect-timeout': 10,
        'backend-connect-retries': 5,
        'request-timeout': 15,
Łukasz Nowak's avatar
Łukasz Nowak committed
1172 1173 1174 1175 1176
      },
      'server-alias': {
        'url': cls.backend_url,
        'server-alias': 'alias1.example.com alias2.example.com',
      },
1177 1178 1179 1180
      'server-alias-empty': {
        'url': cls.backend_url,
        'server-alias': '',
      },
1181 1182 1183 1184
      'server-alias-wildcard': {
        'url': cls.backend_url,
        'server-alias': '*.alias1.example.com',
      },
1185 1186 1187 1188 1189 1190 1191 1192 1193
      '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',
      },
Łukasz Nowak's avatar
Łukasz Nowak committed
1194 1195 1196
      'ssl-proxy-verify_ssl_proxy_ca_crt': {
        'url': cls.backend_https_url,
        'ssl-proxy-verify': True,
1197
        'ssl_proxy_ca_crt': cls.test_server_ca.certificate_pem,
Łukasz Nowak's avatar
Łukasz Nowak committed
1198
      },
1199 1200 1201 1202 1203
      '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,
      },
Łukasz Nowak's avatar
Łukasz Nowak committed
1204 1205 1206 1207 1208 1209
      'ssl-proxy-verify-unverified': {
        'url': cls.backend_https_url,
        'ssl-proxy-verify': True,
      },
      'https-only': {
        'url': cls.backend_url,
1210
        'https-only': False,
Łukasz Nowak's avatar
Łukasz Nowak committed
1211 1212 1213
      },
      'custom_domain': {
        'url': cls.backend_url,
1214
        'custom_domain': 'mycustomdomain.example.com',
Łukasz Nowak's avatar
Łukasz Nowak committed
1215
      },
1216 1217 1218 1219
      'custom_domain_wildcard': {
        'url': cls.backend_url,
        'custom_domain': '*.customdomain.example.com',
      },
1220 1221 1222 1223 1224
      'custom_domain_server_alias': {
        'url': cls.backend_url,
        'custom_domain': 'mycustomdomainserveralias.example.com',
        'server-alias': 'mycustomdomainserveralias1.example.com',
      },
Łukasz Nowak's avatar
Łukasz Nowak committed
1225 1226 1227 1228
      'custom_domain_ssl_crt_ssl_key': {
        'url': cls.backend_url,
        'custom_domain': 'customdomainsslcrtsslkey.example.com',
      },
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
      '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,
      },
Łukasz Nowak's avatar
Łukasz Nowak committed
1242 1243 1244 1245
      'type-zope': {
        'url': cls.backend_url,
        'type': 'zope',
      },
1246 1247 1248 1249 1250
      'type-zope-prefer-gzip-encoding-to-backend': {
        'url': cls.backend_url,
        'prefer-gzip-encoding-to-backend': 'true',
        'type': 'zope',
      },
1251 1252 1253 1254
      'type-zope-prefer-gzip-encoding-to-backend-https-only': {
        'url': cls.backend_url,
        'prefer-gzip-encoding-to-backend': 'true',
        'type': 'zope',
1255
        'https-only': 'false',
1256
      },
Łukasz Nowak's avatar
Łukasz Nowak committed
1257 1258 1259 1260
      'type-zope-ssl-proxy-verify_ssl_proxy_ca_crt': {
        'url': cls.backend_https_url,
        'type': 'zope',
        'ssl-proxy-verify': True,
1261
        'ssl_proxy_ca_crt': cls.test_server_ca.certificate_pem,
Łukasz Nowak's avatar
Łukasz Nowak committed
1262
      },
1263 1264 1265 1266 1267 1268
      '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,
      },
Łukasz Nowak's avatar
Łukasz Nowak committed
1269 1270 1271 1272 1273 1274 1275 1276
      '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',
1277 1278
        'virtualhostroot-http-port': '12345',
        'https-only': 'false',
Łukasz Nowak's avatar
Łukasz Nowak committed
1279 1280 1281 1282 1283 1284 1285 1286 1287
      },
      'type-zope-virtualhostroot-https-port': {
        'url': cls.backend_url,
        'type': 'zope',
        'virtualhostroot-https-port': '12345'
      },
      'type-zope-path': {
        'url': cls.backend_url,
        'type': 'zope',
1288
        'path': '///path/to/some/resource///',
Łukasz Nowak's avatar
Łukasz Nowak committed
1289 1290 1291 1292
      },
      'type-zope-default-path': {
        'url': cls.backend_url,
        'type': 'zope',
1293
        'default-path': '///default-path/to/some/resource///',
Łukasz Nowak's avatar
Łukasz Nowak committed
1294 1295 1296 1297 1298
      },
      'type-notebook': {
        'url': cls.backend_url,
        'type': 'notebook',
      },
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
      'type-websocket': {
        'url': cls.backend_url,
        'type': 'websocket',
      },
      'type-websocket-websocket-path-list': {
        'url': cls.backend_url,
        'type': 'websocket',
        'websocket-path-list': '////ws//// /with%20space/',
      },
      'type-websocket-websocket-transparent-false': {
        'url': cls.backend_url,
        'type': 'websocket',
        'websocket-transparent': 'false',
      },
      'type-websocket-websocket-path-list-websocket-transparent-false': {
        'url': cls.backend_url,
        'type': 'websocket',
        'websocket-path-list': '////ws//// /with%20space/',
        'websocket-transparent': 'false',
      },
1319 1320 1321 1322
      # 'type-eventsource': {
      #   'url': cls.backend_url,
      #   'type': 'eventsource',
      # },
Łukasz Nowak's avatar
Łukasz Nowak committed
1323 1324 1325 1326
      'type-redirect': {
        'url': cls.backend_url,
        'type': 'redirect',
      },
1327 1328 1329 1330 1331
      'type-redirect-custom_domain': {
        'url': cls.backend_url,
        'type': 'redirect',
        'custom_domain': 'customdomaintyperedirect.example.com',
      },
Łukasz Nowak's avatar
Łukasz Nowak committed
1332 1333 1334 1335
      'enable_cache': {
        'url': cls.backend_url,
        'enable_cache': True,
      },
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
      'enable_cache_custom_domain': {
        'url': cls.backend_url,
        'enable_cache': True,
        'custom_domain': 'customdomainenablecache.example.com',
      },
      'enable_cache_server_alias': {
        'url': cls.backend_url,
        'enable_cache': True,
        'server-alias': 'enablecacheserveralias1.example.com',
      },
Łukasz Nowak's avatar
Łukasz Nowak committed
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
      '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,
1368
        'ssl_proxy_ca_crt': cls.test_server_ca.certificate_pem,
Łukasz Nowak's avatar
Łukasz Nowak committed
1369 1370
        'ssl-proxy-verify': True,
      },
1371 1372 1373 1374 1375 1376
      '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,
      },
Łukasz Nowak's avatar
Łukasz Nowak committed
1377 1378 1379 1380 1381 1382 1383
      'enable-http2-default': {
        'url': cls.backend_url,
      },
      'prefer-gzip-encoding-to-backend': {
        'url': cls.backend_url,
        'prefer-gzip-encoding-to-backend': 'true',
      },
1384 1385 1386
      'prefer-gzip-encoding-to-backend-https-only': {
        'url': cls.backend_url,
        'prefer-gzip-encoding-to-backend': 'true',
1387
        'https-only': 'false',
1388
      },
Łukasz Nowak's avatar
Łukasz Nowak committed
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
      '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',
      },
1399 1400
      'ciphers': {
        'ciphers': 'RSA-3DES-EDE-CBC-SHA RSA-AES128-CBC-SHA',
Łukasz Nowak's avatar
Łukasz Nowak committed
1401 1402 1403
      }
    }

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
  monitor_setup_url_key = 'monitor-setup-url'

  def test_monitor_setup(self):
    IP = self._ipv6_address
    self.monitor_configuration_list = [
      {
        'htmlUrl': 'https://[%s]:8401/public/feed' % (IP,),
        'text': 'testing partition 0',
        'title': 'testing partition 0',
        'type': 'rss',
        'url': 'https://[%s]:8401/share/private/' % (IP,),
        'version': 'RSS',
        'xmlUrl': 'https://[%s]:8401/public/feed' % (IP,),
      },
      {
        'htmlUrl': 'https://[%s]:8402/public/feed' % (IP,),
        'text': 'kedifa',
        'title': 'kedifa',
        'type': 'rss',
        'url': 'https://[%s]:8402/share/private/' % (IP,),
        'version': 'RSS',
        'xmlUrl': 'https://[%s]:8402/public/feed' % (IP,),
      },
      {
        'htmlUrl': 'https://[%s]:8411/public/feed' % (IP,),
        'text': 'caddy-frontend-1',
        'title': 'caddy-frontend-1',
        'type': 'rss',
        'url': 'https://[%s]:8411/share/private/' % (IP,),
        'version': 'RSS',
        'xmlUrl': 'https://[%s]:8411/public/feed' % (IP,),
      },
    ]
    connection_parameter_dict = self\
        .computer_partition.getConnectionParameterDict()
    self.assertTrue(
      self.monitor_setup_url_key in connection_parameter_dict,
      '%s not in %s' % (self.monitor_setup_url_key, connection_parameter_dict))
    monitor_setup_url_value = connection_parameter_dict[
      self.monitor_setup_url_key]
    monitor_url_match = re.match(r'.*url=(.*)', monitor_setup_url_value)
    self.assertNotEqual(
      None, monitor_url_match, '%s not parsable' % (monitor_setup_url_value,))
    self.assertEqual(1, len(monitor_url_match.groups()))
    monitor_url = monitor_url_match.groups()[0]
    monitor_url_split = monitor_url.split('&')
    self.assertEqual(
      3, len(monitor_url_split), '%s not splitabble' % (monitor_url,))
    self.monitor_url = monitor_url_split[0]
    monitor_username = monitor_url_split[1].split('=')
    self.assertEqual(
      2, len(monitor_username), '%s not splittable' % (monitor_username))
    monitor_password = monitor_url_split[2].split('=')
    self.assertEqual(
      2, len(monitor_password), '%s not splittable' % (monitor_password))
    self.monitor_username = monitor_username[1]
    self.monitor_password = monitor_password[1]

    opml_text = requests.get(self.monitor_url, verify=False).text
    opml = ET.fromstring(opml_text)

    body = opml[1]
    self.assertEqual('body', body.tag)

    outline_list = body[0].findall('outline')

    self.assertEqual(
      self.monitor_configuration_list,
      [q.attrib for q in outline_list]
    )

    expected_status_code_list = []
    got_status_code_list = []
    for monitor_configuration in self.monitor_configuration_list:
      status_code = requests.get(
          monitor_configuration['url'],
          verify=False,
          auth=(self.monitor_username, self.monitor_password)
        ).status_code
      expected_status_code_list.append(
        {
          'url': monitor_configuration['url'],
          'status_code': 200
        }
      )
      got_status_code_list.append(
        {
          'url': monitor_configuration['url'],
          'status_code': status_code
        }
      )
    self.assertEqual(
      expected_status_code_list,
      got_status_code_list
    )

Łukasz Nowak's avatar
Łukasz Nowak committed
1500 1501 1502 1503
  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, '*',))
1504 1505 1506
      if not os.path.exists(
        os.path.join(q, 'etc', 'trafficserver')) and os.path.exists(
          os.path.join(q, 'buildout.cfg'))][0]
Łukasz Nowak's avatar
Łukasz Nowak committed
1507 1508 1509 1510 1511 1512 1513

  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]

1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
  def test_trafficserver_logrotate(self):
    ats_partition = [
      q for q in glob.glob(os.path.join(self.instance_path, '*',))
      if os.path.exists(os.path.join(q, 'bin', 'trafficserver-rotate'))][0]
    ats_log_dir = os.path.join(ats_partition, 'var', 'log', 'trafficserver')
    ats_logrotate_dir = os.path.join(
      ats_partition, 'srv', 'backup', 'logrotate', 'trafficserver')
    ats_rotate = os.path.join(ats_partition, 'bin', 'trafficserver-rotate')

    old_file_name = 'log-old.old'
    older_file_name = 'log-older.old'
    with open(os.path.join(ats_log_dir, old_file_name), 'w') as fh:
      fh.write('old')
    with open(os.path.join(ats_log_dir, older_file_name), 'w') as fh:
      fh.write('older')

    # check rotation
    result, output = subprocess_status_output([ats_rotate])

    self.assertEqual(0, result)

    self.assertEqual(
1536 1537
      set(['log-old.old.xz', 'log-older.old.xz']),
      set(os.listdir(ats_logrotate_dir)))
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
    self.assertFalse(old_file_name + '.xz' in os.listdir(ats_log_dir))
    self.assertFalse(older_file_name + '.xz' in os.listdir(ats_log_dir))

    with lzma.open(
      os.path.join(ats_logrotate_dir, old_file_name + '.xz')) as fh:
      self.assertEqual(
        'old',
        fh.read()
      )
    with lzma.open(
      os.path.join(ats_logrotate_dir, older_file_name + '.xz')) as fh:
      self.assertEqual(
        'older',
        fh.read()
      )

    # check retention
    old_time = time.time() - (400 * 24 * 3600)
    os.utime(
      os.path.join(ats_logrotate_dir, older_file_name + '.xz'),
      (old_time, old_time))
    result, output = subprocess_status_output([ats_rotate])

    self.assertEqual(0, result)
    self.assertEqual(
      ['log-old.old.xz'],
      os.listdir(ats_logrotate_dir))

Łukasz Nowak's avatar
Łukasz Nowak committed
1566
  def test_master_partition_state(self):
1567
    parameter_dict = self.parseConnectionParameterDict()
Łukasz Nowak's avatar
Łukasz Nowak committed
1568
    self.assertKeyWithPop('monitor-setup-url', parameter_dict)
1569
    self.assertBackendHaproxyStatisticUrl(parameter_dict)
1570
    self.assertKedifaKeysWithPop(parameter_dict, 'master-')
1571
    self.assertRejectedSlavePromiseWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
1572

1573
    expected_parameter_dict = {
1574
      'monitor-base-url': 'https://[%s]:8401' % self._ipv6_address,
1575
      'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
1576
      'domain': 'example.com',
1577
      'accepted-slave-amount': '56',
1578
      'rejected-slave-amount': '0',
1579
      'slave-amount': '56',
1580
      'rejected-slave-dict': {
1581 1582 1583 1584 1585
      },
      'warning-slave-dict': {
        '_Url': [
          "slave url ' %(backend)s ' has been converted to '%(backend)s'" % {
            'backend': self.backend_url}]}
1586
    }
1587 1588 1589

    self.assertEqual(
      expected_parameter_dict,
Łukasz Nowak's avatar
Łukasz Nowak committed
1590 1591 1592 1593 1594
      parameter_dict
    )

    partition_path = self.getMasterPartitionPath()

1595 1596 1597 1598 1599 1600 1601 1602
    # 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())

1603 1604 1605 1606 1607 1608 1609
  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()
    )

1610 1611 1612 1613 1614
  def test_monitor_conf(self):
    monitor_conf_list = glob.glob(
      os.path.join(
        self.instance_path, '*', 'etc', 'monitor.conf'
      ))
1615
    self.assertEqual(3, len(monitor_conf_list))
1616 1617 1618 1619 1620 1621 1622 1623
    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
    )

1624 1625
  def test_empty(self):
    parameter_dict = self.assertSlaveBase('empty')
1626
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
1627 1628
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
    self.assertEqual(
1629
      self.certificate_pem,
1630
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
1631

1632
    self.assertEqual(httplib.SERVICE_UNAVAILABLE, result.status_code)
Łukasz Nowak's avatar
Łukasz Nowak committed
1633

1634
    result_http = fakeHTTPResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
1635
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
1636 1637 1638 1639 1640 1641
    self.assertEqual(
      httplib.FOUND,
      result_http.status_code
    )

    self.assertEqual(
1642
      'https://empty.example.com:%s/test-path' % (HTTP_PORT,),
1643 1644
      result_http.headers['Location']
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
1645 1646

    # check that 404 is as configured
1647
    result_missing = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
1648
      'forsuredoesnotexists.example.com', parameter_dict['public-ipv4'], '')
1649
    self.assertEqual(httplib.NOT_FOUND, result_missing.status_code)
Łukasz Nowak's avatar
Łukasz Nowak committed
1650 1651 1652 1653 1654 1655
    self.assertEqual(
      """<html>
<head>
  <title>Instance not found</title>
</head>
<body>
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
<h1>The instance has not been found</h1>
<p>The reasons of this could be:</p>
<ul>
<li>the instance does not exists or the URL is incorrect
<ul>
<li>in this case please check the URL
</ul>
<li>the instance has been stopped
<ul>
<li>in this case please check in the SlapOS Master if the instance is """
      """started or wait a bit for it to start
</ul>
</ul>
Łukasz Nowak's avatar
Łukasz Nowak committed
1669 1670 1671 1672 1673 1674
</body>
</html>
""",
      result_missing.text
    )

1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
  def test_server_polluted_keys_removed(self):
    buildout_file = os.path.join(
      self.getMasterPartitionPath(), 'buildout-switch-softwaretype.cfg')
    for line in [
      q for q in open(buildout_file).readlines()
      if q.startswith('config-slave-list') or q.startswith(
          'config-extra_slave_instance_list')]:
      self.assertFalse('slave_title' in line)
      self.assertFalse('slap_software_type' in line)
      self.assertFalse('connection-parameter-hash' in line)
      self.assertFalse('timestamp' in line)

1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
  def assertBackendHeaders(
    self, backend_header_dict, domain, source_ip=SOURCE_IP, port=HTTPS_PORT,
    proto='https', ignore_header_list=None):
    if ignore_header_list is None:
      ignore_header_list = []
    self.assertFalse('remote_user' in backend_header_dict.keys())
    if 'Host' not in ignore_header_list:
      self.assertEqual(
        backend_header_dict['host'],
        '%s:%s' % (domain, port))
    self.assertEqual(
1698
      backend_header_dict['x-forwarded-for'],
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
      source_ip
    )
    self.assertEqual(
      backend_header_dict['x-forwarded-port'],
      port
    )
    self.assertEqual(
      backend_header_dict['x-forwarded-proto'],
      proto
    )

1710 1711 1712 1713 1714 1715 1716 1717 1718
  def test_telemetry_disabled(self):
    # here we trust that telemetry not present in error log means it was
    # really disabled
    error_log_file = glob.glob(
      os.path.join(
       self.instance_path, '*', 'var', 'log', 'frontend-error.log'))[0]
    with open(error_log_file) as fh:
      self.assertNotIn('Sending telemetry', fh.read(), 'Telemetry enabled')

Łukasz Nowak's avatar
Łukasz Nowak committed
1719
  def test_url(self):
1720
    parameter_dict = self.assertSlaveBase('Url')
Łukasz Nowak's avatar
Łukasz Nowak committed
1721

1722
    result = fakeHTTPSResult(
1723
      parameter_dict['domain'], parameter_dict['public-ipv4'],
1724
      'test-path/deep/.././deeper',
1725
      headers={
1726
        'Timeout': '10',  # more than default backend-connect-timeout == 5
1727 1728
        'Accept-Encoding': 'gzip',
      }
1729
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
1730 1731

    self.assertEqual(
1732
      self.certificate_pem,
1733
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
1734

1735
    self.assertEqualResultJson(result, 'Path', '/test-path/deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
1736 1737 1738 1739 1740 1741

    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))

1742
    self.assertEqual(j['Incoming Headers']['timeout'], '10')
1743
    self.assertFalse('Content-Encoding' in result.headers)
1744
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])
1745

Łukasz Nowak's avatar
Łukasz Nowak committed
1746
    self.assertEqual(
1747 1748
      'secured=value;secure, nonsecured=value',
      result.headers['Set-Cookie']
Łukasz Nowak's avatar
Łukasz Nowak committed
1749 1750
    )

1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
    # check access log
    log_file = glob.glob(
      os.path.join(
        self.instance_path, '*', 'var', 'log', 'httpd', '_Url_access_log'
      ))[0]

    log_regexp = r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} - - ' \
                 r'\[\d{2}\/.{3}\/\d{4}\:\d{2}\:\d{2}\:\d{2} \+\d{4}\] ' \
                 r'"GET \/test-path\/deep\/..\/.\/deeper HTTP\/1.1" \d{3} ' \
                 r'\d+ "-" "python-requests.*" \d+'

    self.assertRegexpMatches(
      open(log_file, 'r').readlines()[-1],
      log_regexp)

    # check backend log
    log_file = glob.glob(
      os.path.join(
        self.instance_path, '*', 'var', 'log', 'httpd', '_Url_backend_log'
      ))[0]

    log_regexp = r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+ ' \
                 r'\[\d{2}\/.{3}\/\d{4}\:\d{2}\:\d{2}\:\d{2}.\d{3}\] ' \
1774
                 r'http-backend _Url-http\/_Url-backend ' \
1775 1776 1777 1778 1779 1780 1781 1782 1783
                 r'\d+/\d+\/\d+\/\d+\/\d+ ' \
                 r'200 \d+ - - ---- ' \
                 r'\d\/\d\/\d\/\d\/\d \d\/\d ' \
                 r'"GET /test-path/deeper HTTP/1.1"'

    self.assertRegexpMatches(
      open(log_file, 'r').readlines()[-1],
      log_regexp)

1784
    result_http = fakeHTTPResult(
1785 1786
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
1787

1788 1789 1790 1791
    self.assertEqual(
      httplib.FOUND,
      result_http.status_code
    )
1792

Łukasz Nowak's avatar
Łukasz Nowak committed
1793
    self.assertEqual(
1794
      'https://url.example.com:%s/test-path/deeper' % (HTTP_PORT,),
1795
      result_http.headers['Location']
Łukasz Nowak's avatar
Łukasz Nowak committed
1796 1797
    )

1798 1799 1800 1801
    # check that timeouts are correctly set in the haproxy configuration
    backend_configuration_file = glob.glob(os.path.join(
      self.instance_path, '*', 'etc', 'backend-haproxy.cfg'))[0]
    with open(backend_configuration_file) as fh:
1802
      content = fh.read()
1803
    self.assertIn("""backend _Url-http
1804 1805
  timeout server 12s
  timeout connect 5s
1806 1807
  retries 3""", content)
    self.assertIn("""  timeout queue 60s
1808 1809 1810
  timeout server 12s
  timeout client 12s
  timeout connect 5s
1811 1812 1813 1814
  retries 3""", content)
    # check that no needless entries are generated
    self.assertIn("backend _Url-http\n", content)
    self.assertNotIn("backend _Url-https\n", content)
1815

1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
  def test_auth_to_backend(self):
    parameter_dict = self.assertSlaveBase('auth-to-backend')
    # 1. fetch certificate from backend-client-caucase-url
    master_parameter_dict = self.parseConnectionParameterDict()
    caucase_url = master_parameter_dict['backend-client-caucase-url']
    ca_certificate = requests.get(caucase_url + '/cas/crt/ca.crt.pem')
    assert ca_certificate.status_code == httplib.OK
    ca_certificate_file = os.path.join(
      self.working_directory, 'ca-backend-client.crt.pem')
    with open(ca_certificate_file, 'w') as fh:
      fh.write(ca_certificate.text)

    # 2. start backend with this certificate
    class OwnTestHandler(TestHandler):
      identification = 'Auth Backend'

    server_https_auth = HTTPServer(
      (self._ipv4_address, self._server_https_auth_port),
      OwnTestHandler)

    server_https_auth.socket = ssl.wrap_socket(
      server_https_auth.socket,
      certfile=self.test_server_certificate_file.name,
      cert_reqs=ssl.CERT_REQUIRED,
      ca_certs=ca_certificate_file,
      server_side=True)

    backend_https_auth_url = 'https://%s:%s/' \
        % server_https_auth.server_address

    server_https_auth_process = multiprocessing.Process(
      target=server_https_auth.serve_forever, name='HTTPSServerAuth')
    server_https_auth_process.start()
    self.logger.debug('Started process %s' % (server_https_auth_process,))
    try:
      # 3. assert that you can't fetch nothing without key
      try:
        requests.get(backend_https_auth_url, verify=False)
      except Exception:
        pass
      else:
        self.fail(
          'Access to %r shall be not possible without certificate' % (
            backend_https_auth_url,))
      # 4. check that you can access this backend via frontend
      #    (so it means that auth to backend worked)
      result = fakeHTTPSResult(
        parameter_dict['domain'], parameter_dict['public-ipv4'],
        'test-path/deep/.././deeper',
        headers={
          'Timeout': '10',  # more than default backend-connect-timeout == 5
          'Accept-Encoding': 'gzip',
        }
      )

      self.assertEqual(
        self.certificate_pem,
        der2pem(result.peercert))

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

      try:
        j = result.json()
      except Exception:
        raise ValueError('JSON decode problem in:\n%s' % (result.text,))

      self.assertEqual(j['Incoming Headers']['timeout'], '10')
      self.assertFalse('Content-Encoding' in result.headers)
      self.assertBackendHeaders(
         j['Incoming Headers'], parameter_dict['domain'])

      self.assertEqual(
        'secured=value;secure, nonsecured=value',
        result.headers['Set-Cookie']
      )
      # proof that proper backend was accessed
      self.assertEqual(
        'Auth Backend',
        result.headers['X-Backend-Identification']
      )
    finally:
      self.logger.debug('Stopping process %s' % (server_https_auth_process,))
      server_https_auth_process.join(10)
      server_https_auth_process.terminate()
      time.sleep(0.1)
      if server_https_auth_process.is_alive():
        self.logger.warning(
          'Process %s still alive' % (server_https_auth_process, ))

  def test_auth_to_backend_not_configured(self):
    parameter_dict = self.assertSlaveBase('auth-to-backend-not-configured')
    # 1. fetch certificate from backend-client-caucase-url
    master_parameter_dict = self.parseConnectionParameterDict()
    caucase_url = master_parameter_dict['backend-client-caucase-url']
    ca_certificate = requests.get(caucase_url + '/cas/crt/ca.crt.pem')
    assert ca_certificate.status_code == httplib.OK
    ca_certificate_file = os.path.join(
      self.working_directory, 'ca-backend-client.crt.pem')
    with open(ca_certificate_file, 'w') as fh:
      fh.write(ca_certificate.text)

    # 2. start backend with this certificate
    class OwnTestHandler(TestHandler):
      identification = 'Auth Backend'

    server_https_auth = HTTPServer(
      (self._ipv4_address, self._server_https_auth_port),
      OwnTestHandler)

    server_https_auth.socket = ssl.wrap_socket(
      server_https_auth.socket,
      certfile=self.test_server_certificate_file.name,
      cert_reqs=ssl.CERT_REQUIRED,
      ca_certs=ca_certificate_file,
      server_side=True)

    backend_https_auth_url = 'https://%s:%s/' \
        % server_https_auth.server_address

    server_https_auth_process = multiprocessing.Process(
      target=server_https_auth.serve_forever, name='HTTPSServerAuth')
    server_https_auth_process.start()
    self.logger.debug('Started process %s' % (server_https_auth_process,))
    try:
      # 3. assert that you can't fetch nothing without key
      try:
        requests.get(backend_https_auth_url, verify=False)
      except Exception:
        pass
      else:
        self.fail(
          'Access to %r shall be not possible without certificate' % (
            backend_https_auth_url,))
      # 4. check that you can access this backend via frontend
      #    (so it means that auth to backend worked)
      result = fakeHTTPSResult(
        parameter_dict['domain'], parameter_dict['public-ipv4'],
        'test-path/deep/.././deeper',
        headers={
          'Timeout': '10',  # more than default backend-connect-timeout == 5
          'Accept-Encoding': 'gzip',
        }
      )

      self.assertEqual(
        self.certificate_pem,
        der2pem(result.peercert))

      self.assertEqual(
        result.status_code,
        httplib.BAD_GATEWAY
      )
    finally:
      self.logger.debug('Stopping process %s' % (server_https_auth_process,))
      server_https_auth_process.join(10)
      server_https_auth_process.terminate()
      time.sleep(0.1)
      if server_https_auth_process.is_alive():
        self.logger.warning(
          'Process %s still alive' % (server_https_auth_process, ))

  def test_auth_to_backend_backend_ignore(self):
    parameter_dict = self.assertSlaveBase('auth-to-backend-backend-ignore')

    result = fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={
        'Timeout': '10',  # more than default backend-connect-timeout == 5
        'Accept-Encoding': 'gzip',
      }
    )

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

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

    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))

    self.assertEqual(j['Incoming Headers']['timeout'], '10')
    self.assertFalse('Content-Encoding' in result.headers)
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])

    self.assertEqual(
      'secured=value;secure, nonsecured=value',
      result.headers['Set-Cookie']
    )

    result_http = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')

    self.assertEqual(
      httplib.FOUND,
      result_http.status_code
    )

    self.assertEqual(
      'https://authtobackendbackendignore.example.com:%s/test-path/deeper' % (
        HTTP_PORT,),
      result_http.headers['Location']
    )

2024 2025
  def test_compressed_result(self):
    parameter_dict = self.assertSlaveBase('Url')
2026
    result_compressed = fakeHTTPSResult(
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={
        'Accept-Encoding': 'gzip',
        'Compress': '1',
      }
    )
    self.assertEqual(
      'gzip',
      result_compressed.headers['Content-Encoding']
    )

    # Assert that no tampering was done with the request
    # (compression/decompression)
    # Backend compresses with 0 level, so decompression/compression
    # would change somthing
    self.assertEqual(
      result_compressed.headers['Content-Length'],
      result_compressed.headers['Backend-Content-Length']
    )

2048
    result_not_compressed = fakeHTTPSResult(
2049 2050 2051 2052 2053 2054 2055 2056
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={
        'Accept-Encoding': 'gzip',
      }
    )
    self.assertFalse('Content-Encoding' in result_not_compressed.headers)

2057 2058
  def test_no_content_type_alter(self):
    parameter_dict = self.assertSlaveBase('Url')
2059
    result = fakeHTTPSResult(
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={
        'Accept-Encoding': 'gzip',
        'X-Reply-Body': base64.b64encode(
          b"""<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>"""),
        'X-Drop-Header': 'Content-Type'
      }
    )

    self.assertEqual(
      'text/xml; charset=utf-8',
      result.headers['Content-Type']
    )

2081
  @skip('Feature postponed')
Łukasz Nowak's avatar
Łukasz Nowak committed
2082
  def test_url_ipv6_access(self):
2083
    parameter_dict = self.parseSlaveParameterDict('url')
2084
    self.assertLogAccessUrlWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
2085 2086 2087 2088 2089 2090 2091
    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',
2092
        'public-ipv4': self._ipv4_address,
2093 2094
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
2095 2096
    )

2097 2098 2099
    result_ipv6 = fakeHTTPSResult(
      parameter_dict['domain'], self._ipv6_address, 'test-path',
      source_ip=self._ipv6_address)
Łukasz Nowak's avatar
Łukasz Nowak committed
2100 2101

    self.assertEqual(
2102
       self._ipv6_address,
2103
       result_ipv6.json()['Incoming Headers']['x-forwarded-for']
Łukasz Nowak's avatar
Łukasz Nowak committed
2104 2105 2106
    )

    self.assertEqual(
2107
      self.certificate_pem,
2108
      der2pem(result_ipv6.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
2109 2110 2111 2112

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

  def test_type_zope_path(self):
2113
    parameter_dict = self.assertSlaveBase('type-zope-path')
Łukasz Nowak's avatar
Łukasz Nowak committed
2114

2115
    result = fakeHTTPSResult(
2116 2117
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
2118 2119

    self.assertEqual(
2120
      self.certificate_pem,
2121
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
2122 2123 2124 2125

    self.assertEqualResultJson(
      result,
      'Path',
2126 2127 2128 2129
      '/VirtualHostBase/'
      'https//typezopepath.example.com:443/path/to/some/resource'
      '/VirtualHostRoot/'
      'test-path/deeper'
Łukasz Nowak's avatar
Łukasz Nowak committed
2130 2131 2132
    )

  def test_type_zope_default_path(self):
2133
    parameter_dict = self.assertSlaveBase('type-zope-default-path')
Łukasz Nowak's avatar
Łukasz Nowak committed
2134

2135
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
2136 2137 2138
      parameter_dict['domain'], parameter_dict['public-ipv4'], '')

    self.assertEqual(
2139
      self.certificate_pem,
2140
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
2141

2142 2143 2144 2145 2146
    self.assertEqual(
      httplib.MOVED_PERMANENTLY,
      result.status_code
    )

Łukasz Nowak's avatar
Łukasz Nowak committed
2147
    self.assertEqual(
2148 2149
      'https://typezopedefaultpath.example.com:%s/'
      'default-path/to/some/resource' % (
2150 2151
        HTTPS_PORT,),
      result.headers['Location']
Łukasz Nowak's avatar
Łukasz Nowak committed
2152 2153 2154
    )

  def test_server_alias(self):
2155
    parameter_dict = self.assertSlaveBase('server-alias')
Łukasz Nowak's avatar
Łukasz Nowak committed
2156

2157
    result = fakeHTTPSResult(
2158 2159
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
2160 2161

    self.assertEqual(
2162
      self.certificate_pem,
2163
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
2164

2165
    self.assertEqualResultJson(result, 'Path', '/test-path/deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
2166

2167
    result = fakeHTTPSResult(
2168 2169
      'alias1.example.com', parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
2170 2171

    self.assertEqual(
2172
      self.certificate_pem,
2173
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
2174

2175
    self.assertEqualResultJson(result, 'Path', '/test-path/deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
2176

2177
    result = fakeHTTPSResult(
2178 2179
      'alias2.example.com', parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
2180 2181

    self.assertEqual(
2182
      self.certificate_pem,
2183
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
2184

2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
  def test_server_alias_empty(self):
    parameter_dict = self.assertSlaveBase('server-alias-empty')

    result = fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={
        'Timeout': '10',  # more than default backend-connect-timeout == 5
        'Accept-Encoding': 'gzip',
      }
    )

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

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

    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))

    self.assertEqual(j['Incoming Headers']['timeout'], '10')
    self.assertFalse('Content-Encoding' in result.headers)
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])

    self.assertEqual(
      'secured=value;secure, nonsecured=value',
      result.headers['Set-Cookie']
    )

2217
  def test_server_alias_wildcard(self):
2218
    parameter_dict = self.parseSlaveParameterDict('server-alias-wildcard')
2219
    self.assertLogAccessUrlWithPop(parameter_dict)
2220
    self.assertKedifaKeysWithPop(parameter_dict)
2221 2222 2223 2224 2225 2226 2227
    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',
2228
        'public-ipv4': self._ipv4_address,
2229
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
2230 2231 2232 2233
      },
      parameter_dict
    )

2234
    result = fakeHTTPSResult(
2235 2236 2237
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
2238
      self.certificate_pem,
2239 2240 2241 2242
      der2pem(result.peercert))

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

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

    self.assertEqual(
2247
      self.certificate_pem,
2248 2249
      der2pem(result.peercert))

Łukasz Nowak's avatar
Łukasz Nowak committed
2250 2251
    self.assertEqualResultJson(result, 'Path', '/test-path')

2252
  def test_server_alias_duplicated(self):
2253
    parameter_dict = self.parseSlaveParameterDict('server-alias-duplicated')
2254
    self.assertLogAccessUrlWithPop(parameter_dict)
2255
    self.assertKedifaKeysWithPop(parameter_dict)
2256 2257 2258 2259 2260 2261 2262
    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',
2263
        'public-ipv4': self._ipv4_address,
2264
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
2265 2266 2267 2268
      },
      parameter_dict
    )

2269
    result = fakeHTTPSResult(
2270 2271 2272
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
2273
      self.certificate_pem,
2274 2275 2276 2277
      der2pem(result.peercert))

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

2278
    result = fakeHTTPSResult(
2279 2280 2281
      'alias3.example.com', parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
2282
      self.certificate_pem,
2283 2284 2285 2286 2287
      der2pem(result.peercert))

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

  def test_server_alias_custom_domain_duplicated(self):
2288 2289
    parameter_dict = self.parseSlaveParameterDict(
      'server-alias_custom_domain-duplicated')
2290
    self.assertLogAccessUrlWithPop(parameter_dict)
2291
    self.assertKedifaKeysWithPop(parameter_dict)
2292 2293 2294 2295 2296 2297 2298
    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',
2299
        'public-ipv4': self._ipv4_address,
2300
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
2301 2302 2303 2304
      },
      parameter_dict
    )

2305
    result = fakeHTTPSResult(
2306 2307 2308
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
2309
      self.certificate_pem,
2310 2311 2312 2313
      der2pem(result.peercert))

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

Łukasz Nowak's avatar
Łukasz Nowak committed
2314 2315 2316 2317 2318 2319
  @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):
2320 2321
    parameter_dict = self.parseSlaveParameterDict(
      'custom_domain_ssl_crt_ssl_key_ssl_ca_crt')
2322
    self.assertLogAccessUrlWithPop(parameter_dict)
2323
    generate_auth, upload_url = self.assertKedifaKeysWithPop(parameter_dict)
2324 2325 2326 2327 2328 2329 2330 2331
    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',
2332
        'public-ipv4': self._ipv4_address,
2333
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
2334 2335 2336
      },
      parameter_dict
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
2337

2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352
    # 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)
2353
    self.runKedifaUpdater()
2354

2355
    result = fakeHTTPSResult(
2356 2357 2358
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
2359
      self.customdomain_ca_certificate_pem,
2360 2361 2362 2363
      der2pem(result.peercert))

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

2364 2365
    certificate_file_list = glob.glob(os.path.join(
      self.instance_path, '*', 'srv', 'autocert',
2366
      '_custom_domain_ssl_crt_ssl_key_ssl_ca_crt.pem'))
2367 2368 2369 2370 2371
    self.assertEqual(1, len(certificate_file_list))
    certificate_file = certificate_file_list[0]
    with open(certificate_file) as out:
      self.assertEqual(data, out.read())

2372
  def test_ssl_ca_crt_only(self):
2373
    parameter_dict = self.parseSlaveParameterDict('ssl_ca_crt_only')
2374 2375
    self.assertLogAccessUrlWithPop(parameter_dict)
    generate_auth, upload_url = self.assertKedifaKeysWithPop(parameter_dict)
2376 2377
    self.assertEqual(
      {
2378 2379 2380 2381 2382 2383
        'domain': 'sslcacrtonly.example.com',
        'replication_number': '1',
        'url': 'http://sslcacrtonly.example.com',
        'site_url': 'http://sslcacrtonly.example.com',
        'secure_access':
        'https://sslcacrtonly.example.com',
2384
        'public-ipv4': self._ipv4_address,
2385
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
2386 2387
      },
      parameter_dict
2388
    )
2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403
    # 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.ca.certificate_pem

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

    self.assertEqual(httplib.UNPROCESSABLE_ENTITY, upload.status_code)
    self.assertEqual('Key incorrect', upload.text)
2404 2405

  def test_ssl_ca_crt_garbage(self):
2406
    parameter_dict = self.parseSlaveParameterDict('ssl_ca_crt_garbage')
2407
    self.assertLogAccessUrlWithPop(parameter_dict)
2408
    generate_auth, upload_url = self.assertKedifaKeysWithPop(parameter_dict)
2409 2410 2411 2412 2413 2414 2415 2416
    self.assertEqual(
      {
        'domain': 'sslcacrtgarbage.example.com',
        'replication_number': '1',
        'url': 'http://sslcacrtgarbage.example.com',
        'site_url': 'http://sslcacrtgarbage.example.com',
        'secure_access':
        'https://sslcacrtgarbage.example.com',
2417
        'public-ipv4': self._ipv4_address,
2418
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
2419 2420 2421 2422
      },
      parameter_dict
    )

2423 2424 2425 2426 2427 2428
    # 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)

2429 2430 2431 2432 2433
    _, ca_key_pem, csr, _ = createCSR(
      parameter_dict['domain'])
    _, ca_certificate_pem = self.ca.signCSR(csr)

    data = ca_certificate_pem + ca_key_pem + 'some garbage'
2434 2435 2436 2437 2438 2439
    upload = requests.put(
      upload_url + auth.text,
      data=data,
      verify=self.ca_certificate_file)

    self.assertEqual(httplib.CREATED, upload.status_code)
2440
    self.runKedifaUpdater()
2441

2442
    result = fakeHTTPSResult(
2443
        parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
2444

2445 2446 2447 2448 2449 2450 2451
    self.assertEqual(
      ca_certificate_pem,
      der2pem(result.peercert)
    )

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

2452 2453
    certificate_file_list = glob.glob(os.path.join(
      self.instance_path, '*', 'srv', 'autocert',
2454
      '_ssl_ca_crt_garbage.pem'))
2455 2456 2457 2458 2459
    self.assertEqual(1, len(certificate_file_list))
    certificate_file = certificate_file_list[0]
    with open(certificate_file) as out:
      self.assertEqual(data, out.read())

2460
  def test_ssl_ca_crt_does_not_match(self):
2461
    parameter_dict = self.parseSlaveParameterDict('ssl_ca_crt_does_not_match')
2462
    self.assertLogAccessUrlWithPop(parameter_dict)
2463
    generate_auth, upload_url = self.assertKedifaKeysWithPop(parameter_dict)
2464 2465 2466 2467 2468 2469 2470 2471
    self.assertEqual(
      {
        'domain': 'sslcacrtdoesnotmatch.example.com',
        'replication_number': '1',
        'url': 'http://sslcacrtdoesnotmatch.example.com',
        'site_url': 'http://sslcacrtdoesnotmatch.example.com',
        'secure_access':
        'https://sslcacrtdoesnotmatch.example.com',
2472
        'public-ipv4': self._ipv4_address,
2473
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
2474 2475 2476
      },
      parameter_dict
    )
2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
    # 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.certificate_pem + self.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)
2491
    self.runKedifaUpdater()
2492

2493
    result = fakeHTTPSResult(
2494 2495 2496
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
2497
      self.certificate_pem,
2498 2499 2500
      der2pem(result.peercert))

    self.assertEqualResultJson(result, 'Path', '/test-path')
Łukasz Nowak's avatar
Łukasz Nowak committed
2501

2502 2503
    certificate_file_list = glob.glob(os.path.join(
      self.instance_path, '*', 'srv', 'autocert',
2504
      '_ssl_ca_crt_does_not_match.pem'))
2505 2506 2507 2508 2509
    self.assertEqual(1, len(certificate_file_list))
    certificate_file = certificate_file_list[0]
    with open(certificate_file) as out:
      self.assertEqual(data, out.read())

Łukasz Nowak's avatar
Łukasz Nowak committed
2510
  def test_https_only(self):
2511
    parameter_dict = self.assertSlaveBase('https-only')
Łukasz Nowak's avatar
Łukasz Nowak committed
2512

2513
    result = fakeHTTPSResult(
2514 2515
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
2516 2517

    self.assertEqual(
2518
      self.certificate_pem,
2519
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
2520

2521
    self.assertEqualResultJson(result, 'Path', '/test-path/deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
2522

2523
    result_http = fakeHTTPResult(
2524 2525
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
2526

2527
    self.assertEqualResultJson(result_http, 'Path', '/test-path/deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
2528 2529

  def test_custom_domain(self):
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
    reference = 'custom_domain'
    hostname = 'mycustomdomain'
    parameter_dict = self.parseSlaveParameterDict(reference)
    self.assertLogAccessUrlWithPop(parameter_dict)
    self.assertKedifaKeysWithPop(parameter_dict, '')
    self.assertEqual(
      {
        'domain': '%s.example.com' % (hostname,),
        'replication_number': '1',
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
2542
        'public-ipv4': self._ipv4_address,
2543
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
2544 2545 2546
      },
      parameter_dict
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
2547

2548
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
2549 2550 2551
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
2552
      self.certificate_pem,
2553
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
2554 2555 2556

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

2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569
  def test_custom_domain_server_alias(self):
    reference = 'custom_domain_server_alias'
    hostname = 'mycustomdomainserveralias'
    parameter_dict = self.parseSlaveParameterDict(reference)
    self.assertLogAccessUrlWithPop(parameter_dict)
    self.assertKedifaKeysWithPop(parameter_dict, '')
    self.assertEqual(
      {
        'domain': '%s.example.com' % (hostname,),
        'replication_number': '1',
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
2570
        'public-ipv4': self._ipv4_address,
2571
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
2572 2573 2574 2575
      },
      parameter_dict
    )

2576
    result = fakeHTTPSResult(
2577 2578 2579 2580 2581 2582 2583 2584
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

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

2585
    result = fakeHTTPSResult(
2586 2587 2588 2589 2590 2591 2592 2593 2594
      'mycustomdomainserveralias1.example.com', parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

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

2595
  def test_custom_domain_wildcard(self):
2596
    parameter_dict = self.parseSlaveParameterDict('custom_domain_wildcard')
2597
    self.assertLogAccessUrlWithPop(parameter_dict)
2598
    self.assertKedifaKeysWithPop(parameter_dict)
2599 2600 2601 2602 2603 2604 2605
    self.assertEqual(
      {
        'domain': '*.customdomain.example.com',
        'replication_number': '1',
        'url': 'http://*.customdomain.example.com',
        'site_url': 'http://*.customdomain.example.com',
        'secure_access': 'https://*.customdomain.example.com',
2606
        'public-ipv4': self._ipv4_address,
2607
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
2608 2609 2610 2611
      },
      parameter_dict
    )

2612
    result = fakeHTTPSResult(
2613 2614 2615 2616
      'wild.customdomain.example.com', parameter_dict['public-ipv4'],
      'test-path')

    self.assertEqual(
2617
      self.certificate_pem,
2618 2619 2620 2621
      der2pem(result.peercert))

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

Łukasz Nowak's avatar
Łukasz Nowak committed
2622
  def test_custom_domain_ssl_crt_ssl_key(self):
2623 2624
    reference = 'custom_domain_ssl_crt_ssl_key'
    parameter_dict = self.parseSlaveParameterDict(reference)
2625
    self.assertLogAccessUrlWithPop(parameter_dict)
2626 2627 2628
    generate_auth, upload_url = self.assertKedifaKeysWithPop(parameter_dict)

    hostname = reference.translate(None, '_-')
Łukasz Nowak's avatar
Łukasz Nowak committed
2629 2630
    self.assertEqual(
      {
2631
        'domain': '%s.example.com' % (hostname,),
Łukasz Nowak's avatar
Łukasz Nowak committed
2632
        'replication_number': '1',
2633 2634 2635
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
2636
        'public-ipv4': self._ipv4_address,
2637
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
2638 2639
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
2640 2641
    )

2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653
    # 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_certificate_pem + \
        self.customdomain_key_pem
    upload = requests.put(
      upload_url + auth.text,
      data=data,
      verify=self.ca_certificate_file)
    self.assertEqual(httplib.CREATED, upload.status_code)
2654
    self.runKedifaUpdater()
2655

2656
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
2657 2658 2659
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
2660
      self.customdomain_certificate_pem,
2661
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
2662 2663 2664 2665

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

  def test_type_zope(self):
2666
    parameter_dict = self.assertSlaveBase('type-zope')
Łukasz Nowak's avatar
Łukasz Nowak committed
2667

2668
    result = fakeHTTPSResult(
2669 2670
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
2671 2672

    self.assertEqual(
2673
      self.certificate_pem,
2674
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
2675 2676 2677 2678 2679

    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
2680
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])
Łukasz Nowak's avatar
Łukasz Nowak committed
2681 2682 2683 2684 2685

    self.assertEqualResultJson(
      result,
      'Path',
      '/VirtualHostBase/https//typezope.example.com:443/'
2686
      '/VirtualHostRoot/test-path/deeper'
Łukasz Nowak's avatar
Łukasz Nowak committed
2687 2688
    )

2689
    result = fakeHTTPResult(
2690 2691
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
2692

2693 2694 2695
    self.assertEqual(
      httplib.FOUND,
      result.status_code
Łukasz Nowak's avatar
Łukasz Nowak committed
2696 2697
    )

2698
    self.assertEqual(
2699 2700
      'https://typezope.example.com:%s/test-path/deep/.././deeper' % (
        HTTP_PORT,),
2701 2702 2703 2704
      result.headers['Location']
    )

  def test_type_zope_prefer_gzip_encoding_to_backend_https_only(self):
2705
    parameter_dict = self.assertSlaveBase(
2706
      'type-zope-prefer-gzip-encoding-to-backend-https-only')
2707

2708
    result = fakeHTTPSResult(
2709 2710
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
2711 2712 2713 2714 2715 2716 2717 2718 2719

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
2720
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])
2721 2722 2723 2724 2725

    self.assertEqualResultJson(
      result,
      'Path',
      '/VirtualHostBase/https//'
2726
      'typezopeprefergzipencodingtobackendhttpsonly.example.com:443/'
2727
      '/VirtualHostRoot/test-path/deeper'
2728 2729
    )

2730
    result = fakeHTTPResult(
2731 2732
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
2733 2734 2735 2736 2737

    self.assertEqualResultJson(
      result,
      'Path',
      '/VirtualHostBase/http//'
2738
      'typezopeprefergzipencodingtobackendhttpsonly.example.com:80/'
2739
      '/VirtualHostRoot/test-path/deeper'
2740 2741
    )

2742
    result = fakeHTTPSResult(
2743 2744
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754
      headers={'Accept-Encoding': 'gzip, deflate'})

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
2755
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])
2756 2757 2758 2759 2760

    self.assertEqualResultJson(
      result,
      'Path',
      '/VirtualHostBase/https//'
2761
      'typezopeprefergzipencodingtobackendhttpsonly.example.com:443/'
2762
      '/VirtualHostRoot/test-path/deeper'
2763 2764 2765 2766
    )
    self.assertEqual(
      'gzip', result.json()['Incoming Headers']['accept-encoding'])

2767
    result = fakeHTTPResult(
2768 2769
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
2770 2771 2772 2773 2774 2775
      headers={'Accept-Encoding': 'gzip, deflate'})

    self.assertEqualResultJson(
      result,
      'Path',
      '/VirtualHostBase/http//'
2776
      'typezopeprefergzipencodingtobackendhttpsonly.example.com:80/'
2777
      '/VirtualHostRoot/test-path/deeper'
2778 2779 2780 2781
    )
    self.assertEqual(
      'gzip', result.json()['Incoming Headers']['accept-encoding'])

2782
  def test_type_zope_prefer_gzip_encoding_to_backend(self):
2783
    parameter_dict = self.assertSlaveBase(
2784
      'type-zope-prefer-gzip-encoding-to-backend')
2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797

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

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
2798
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])
2799 2800 2801 2802 2803

    self.assertEqualResultJson(
      result,
      'Path',
      '/VirtualHostBase/https//'
2804
      'typezopeprefergzipencodingtobackend.example.com:443/'
2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
      '/VirtualHostRoot/test-path/deeper'
    )

    result = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')

    self.assertEqual(
      httplib.FOUND,
      result.status_code
    )

    self.assertEqual(
2818 2819
      'https://%s:%s/test-path/deep/.././deeper' % (
        parameter_dict['domain'], HTTP_PORT),
2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
      result.headers['Location']
    )

    result = fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={'Accept-Encoding': 'gzip, deflate'})

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
2836
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])
2837 2838 2839 2840 2841

    self.assertEqualResultJson(
      result,
      'Path',
      '/VirtualHostBase/https//'
2842
      'typezopeprefergzipencodingtobackend.example.com:443/'
2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858
      '/VirtualHostRoot/test-path/deeper'
    )
    self.assertEqual(
      'gzip', result.json()['Incoming Headers']['accept-encoding'])

    result = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={'Accept-Encoding': 'gzip, deflate'})

    self.assertEqual(
      httplib.FOUND,
      result.status_code
    )

    self.assertEqual(
2859 2860
      'https://%s:%s/test-path/deep/.././deeper' % (
        parameter_dict['domain'], HTTP_PORT),
2861 2862 2863
      result.headers['Location']
    )

Łukasz Nowak's avatar
Łukasz Nowak committed
2864
  def test_type_zope_virtualhostroot_http_port(self):
2865
    parameter_dict = self.assertSlaveBase(
2866
      'type-zope-virtualhostroot-http-port')
Łukasz Nowak's avatar
Łukasz Nowak committed
2867

2868
    result = fakeHTTPResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqualResultJson(
      result,
      'Path',
      '/VirtualHostBase/http//typezopevirtualhostroothttpport'
      '.example.com:12345//VirtualHostRoot/test-path'
    )

  def test_type_zope_virtualhostroot_https_port(self):
2879
    parameter_dict = self.assertSlaveBase(
2880
      'type-zope-virtualhostroot-https-port')
Łukasz Nowak's avatar
Łukasz Nowak committed
2881

2882
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
2883 2884 2885
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
2886
      self.certificate_pem,
2887
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
2888 2889 2890 2891 2892 2893 2894 2895 2896

    self.assertEqualResultJson(
      result,
      'Path',
      '/VirtualHostBase/https//typezopevirtualhostroothttpsport'
      '.example.com:12345//VirtualHostRoot/test-path'
    )

  def test_type_notebook(self):
2897 2898
    reference = 'type-notebook'
    parameter_dict = self.parseSlaveParameterDict(reference)
2899
    self.assertLogAccessUrlWithPop(parameter_dict)
2900 2901
    hostname = reference.translate(None, '_-')
    self.assertKedifaKeysWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
2902 2903
    self.assertEqual(
      {
2904
        'domain': '%s.example.com' % (hostname,),
Łukasz Nowak's avatar
Łukasz Nowak committed
2905
        'replication_number': '1',
2906 2907 2908
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
2909
        'public-ipv4': self._ipv4_address,
2910
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
2911 2912
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
2913 2914
    )

2915
    result = fakeHTTPSResult(
2916 2917
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path',
2918
      HTTPS_PORT)
Łukasz Nowak's avatar
Łukasz Nowak committed
2919 2920

    self.assertEqual(
2921
      self.certificate_pem,
2922
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
2923 2924 2925

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

2926
    result = fakeHTTPSResult(
2927 2928
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test/terminals/websocket/test',
2929
      HTTPS_PORT)
2930 2931 2932 2933 2934 2935

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    self.assertEqualResultJson(result, 'Path', '/terminals/websocket')
2936 2937
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))
2938

Łukasz Nowak's avatar
Łukasz Nowak committed
2939
  def test_type_websocket(self):
2940 2941 2942
    parameter_dict = self.assertSlaveBase(
      'type-websocket')

2943
    result = fakeHTTPSResult(
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path',
      headers={'Connection': 'Upgrade'})

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    self.assertEqualResultJson(
      result,
      'Path',
      '/test-path'
    )
    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
2960
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])
2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972
    self.assertEqual(
      'Upgrade',
      j['Incoming Headers']['connection']
    )
    self.assertTrue('x-real-ip' in j['Incoming Headers'])
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))

  def test_type_websocket_websocket_transparent_false(self):
    parameter_dict = self.assertSlaveBase(
      'type-websocket-websocket-transparent-false')

2973
    result = fakeHTTPSResult(
2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path',
      headers={'Connection': 'Upgrade'})

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    self.assertEqualResultJson(
      result,
      'Path',
      '/test-path'
    )
    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
2990 2991 2992 2993
    parsed = urlparse.urlparse(self.backend_url)
    self.assertBackendHeaders(
      j['Incoming Headers'], parsed.hostname, port='17', proto='irc',
      ignore_header_list=['Host'])
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
    self.assertEqual(
      'Upgrade',
      j['Incoming Headers']['connection']
    )
    self.assertFalse('x-real-ip' in j['Incoming Headers'])
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))

  def test_type_websocket_websocket_path_list(self):
    parameter_dict = self.assertSlaveBase(
      'type-websocket-websocket-path-list')

3006
    result = fakeHTTPSResult(
3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path',
      headers={'Connection': 'Upgrade'})

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    self.assertEqualResultJson(
      result,
      'Path',
      '/test-path'
    )
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))
    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
3025
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])
3026 3027
    self.assertTrue('x-real-ip' in j['Incoming Headers'])

3028
    result = fakeHTTPSResult(
3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'ws/test-path',
      headers={'Connection': 'Upgrade'})

    self.assertEqualResultJson(
      result,
      'Path',
      '/ws/test-path'
    )
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))
    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
3043
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])
3044 3045 3046 3047 3048 3049
    self.assertEqual(
      'Upgrade',
      j['Incoming Headers']['connection']
    )
    self.assertTrue('x-real-ip' in j['Incoming Headers'])

3050
    result = fakeHTTPSResult(
3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'with%20space/test-path', headers={'Connection': 'Upgrade'})

    self.assertEqualResultJson(
      result,
      'Path',
      '/with%20space/test-path'
    )
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))
    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
3065
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])
3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076
    self.assertEqual(
      'Upgrade',
      j['Incoming Headers']['connection']
    )
    self.assertTrue('x-real-ip' in j['Incoming Headers'])

  def test_type_websocket_websocket_path_list_websocket_transparent_false(
    self):
    parameter_dict = self.assertSlaveBase(
      'type-websocket-websocket-path-list-websocket-transparent-false')

3077
    result = fakeHTTPSResult(
3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path',
      headers={'Connection': 'Upgrade'})

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    self.assertEqualResultJson(
      result,
      'Path',
      '/test-path'
    )
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))
    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
3096 3097 3098 3099
    parsed = urlparse.urlparse(self.backend_url)
    self.assertBackendHeaders(
      j['Incoming Headers'], parsed.hostname, port='17', proto='irc',
      ignore_header_list=['Host'])
3100 3101
    self.assertFalse('x-real-ip' in j['Incoming Headers'])

3102
    result = fakeHTTPSResult(
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'ws/test-path',
      headers={'Connection': 'Upgrade'})

    self.assertEqualResultJson(
      result,
      'Path',
      '/ws/test-path'
    )
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))
    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
3117 3118 3119
    self.assertBackendHeaders(
      j['Incoming Headers'], parsed.hostname, port='17', proto='irc',
      ignore_header_list=['Host'])
3120 3121 3122 3123 3124 3125
    self.assertEqual(
      'Upgrade',
      j['Incoming Headers']['connection']
    )
    self.assertFalse('x-real-ip' in j['Incoming Headers'])

3126
    result = fakeHTTPSResult(
3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'with%20space/test-path', headers={'Connection': 'Upgrade'})

    self.assertEqualResultJson(
      result,
      'Path',
      '/with%20space/test-path'
    )
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))
    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
3141 3142 3143
    self.assertBackendHeaders(
      j['Incoming Headers'], parsed.hostname, port='17', proto='irc',
      ignore_header_list=['Host'])
3144 3145 3146 3147 3148
    self.assertEqual(
      'Upgrade',
      j['Incoming Headers']['connection']
    )
    self.assertFalse('x-real-ip' in j['Incoming Headers'])
Łukasz Nowak's avatar
Łukasz Nowak committed
3149

3150
  @skip('Feature postponed')
Łukasz Nowak's avatar
Łukasz Nowak committed
3151 3152 3153 3154 3155 3156
  def test_type_eventsource(self):
    # Caddy: For event source, if I understand
    #        https://github.com/mholt/caddy/issues/1355 correctly, we could use
    #        Caddy as a proxy in front of nginx-push-stream . If we have a
    #        "central shared" caddy instance, can it handle keeping connections
    #        opens for many clients ?
3157
    parameter_dict = self.parseSlaveParameterDict('type-eventsource')
3158
    self.assertLogAccessUrlWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
3159 3160 3161 3162 3163 3164 3165
    self.assertEqual(
      {
        'domain': 'typeeventsource.nginx.example.com',
        'replication_number': '1',
        'url': 'http://typeeventsource.nginx.example.com',
        'site_url': 'http://typeeventsource.nginx.example.com',
        'secure_access': 'https://typeeventsource.nginx.example.com',
3166
        'public-ipv4': self._ipv4_address,
3167
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
3168 3169
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
3170 3171
    )

3172
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
3173
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'pub',
3174 3175
      #  NGINX_HTTPS_PORT
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
3176 3177

    self.assertEqual(
3178
      self.certificate_pem,
3179
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
3180 3181

    self.assertEqual(
3182 3183
      '',
      result.content
Łukasz Nowak's avatar
Łukasz Nowak committed
3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
    )
    headers = result.headers.copy()
    self.assertKeyWithPop('Expires', headers)
    self.assertKeyWithPop('Date', headers)
    self.assertEqual(
      {
        'X-Nginx-PushStream-Explain': 'No channel id provided.',
        'Content-Length': '0',
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Connection': 'keep-alive',
        'Server': 'nginx'
3195 3196
      },
      headers
Łukasz Nowak's avatar
Łukasz Nowak committed
3197 3198 3199
    )

  def test_type_redirect(self):
3200
    parameter_dict = self.assertSlaveBase('type-redirect')
Łukasz Nowak's avatar
Łukasz Nowak committed
3201

3202
    result = fakeHTTPSResult(
3203 3204
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
3205 3206

    self.assertEqual(
3207
      self.certificate_pem,
3208
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
3209

3210 3211 3212 3213 3214
    self.assertEqual(
      httplib.FOUND,
      result.status_code
    )

Łukasz Nowak's avatar
Łukasz Nowak committed
3215
    self.assertEqual(
3216
      '%stest-path/deeper' % (self.backend_url,),
3217
      result.headers['Location']
Łukasz Nowak's avatar
Łukasz Nowak committed
3218 3219
    )

3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256
  def test_type_redirect_custom_domain(self):
    reference = 'type-redirect-custom_domain'
    hostname = 'customdomaintyperedirect'
    parameter_dict = self.parseSlaveParameterDict(reference)
    self.assertLogAccessUrlWithPop(parameter_dict)
    self.assertKedifaKeysWithPop(parameter_dict, '')
    self.assertEqual(
      {
        'domain': '%s.example.com' % (hostname,),
        'replication_number': '1',
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
      },
      parameter_dict
    )

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

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    self.assertEqual(
      httplib.FOUND,
      result.status_code
    )

    self.assertEqual(
      '%stest-path/deeper' % (self.backend_url,),
      result.headers['Location']
    )

3257 3258 3259 3260 3261
  def test_ssl_proxy_verify_ssl_proxy_ca_crt_unverified(self):
    parameter_dict = self.parseSlaveParameterDict(
      'ssl-proxy-verify_ssl_proxy_ca_crt-unverified')

    self.assertLogAccessUrlWithPop(parameter_dict)
3262
    self.assertKedifaKeysWithPop(parameter_dict)
3263 3264 3265 3266 3267 3268 3269 3270 3271
    self.assertEqual(
      {
        'domain': 'sslproxyverifysslproxycacrtunverified.example.com',
        'replication_number': '1',
        'url': 'http://sslproxyverifysslproxycacrtunverified.example.com',
        'site_url':
        'http://sslproxyverifysslproxycacrtunverified.example.com',
        'secure_access':
        'https://sslproxyverifysslproxycacrtunverified.example.com',
3272
        'public-ipv4': self._ipv4_address,
3273
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
3274 3275 3276 3277
      },
      parameter_dict
    )

3278
    result = fakeHTTPSResult(
3279 3280 3281 3282 3283 3284 3285
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    self.assertEqual(
3286
      httplib.SERVICE_UNAVAILABLE,
3287 3288 3289
      result.status_code
    )

3290
    result_http = fakeHTTPResult(
3291 3292 3293
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
3294
      httplib.FOUND,
3295 3296 3297
      result_http.status_code
    )

3298
    self.assertEqual(
3299 3300
      'https://sslproxyverifysslproxycacrtunverified.example.com:%s/'
      'test-path' % (HTTP_PORT,),
3301 3302 3303
      result_http.headers['Location']
    )

Łukasz Nowak's avatar
Łukasz Nowak committed
3304
  def test_ssl_proxy_verify_ssl_proxy_ca_crt(self):
3305
    parameter_dict = self.assertSlaveBase('ssl-proxy-verify_ssl_proxy_ca_crt')
Łukasz Nowak's avatar
Łukasz Nowak committed
3306

3307
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
3308 3309 3310
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
3311
      self.certificate_pem,
3312
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
3313

3314 3315 3316 3317 3318 3319
    self.assertEqualResultJson(result, 'Path', '/test-path')

    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
3320
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])
3321

3322
    self.assertFalse('Content-Encoding' in result.headers)
3323 3324 3325 3326

    self.assertEqual(
      'secured=value;secure, nonsecured=value',
      result.headers['Set-Cookie']
3327
    )
3328

3329
    result_http = fakeHTTPResult(
3330
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
3331

3332 3333 3334 3335
    self.assertEqual(
      httplib.FOUND,
      result_http.status_code
    )
3336 3337

    self.assertEqual(
3338 3339
      'https://sslproxyverifysslproxycacrt.example.com:%s/test-path' % (
        HTTP_PORT,),
3340
      result_http.headers['Location']
3341
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
3342 3343

  def test_ssl_proxy_verify_unverified(self):
3344
    parameter_dict = self.assertSlaveBase('ssl-proxy-verify-unverified')
Łukasz Nowak's avatar
Łukasz Nowak committed
3345

3346
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
3347 3348 3349
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
3350
      self.certificate_pem,
3351
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
3352 3353

    self.assertEqual(
3354
      httplib.SERVICE_UNAVAILABLE,
3355
      result.status_code
Łukasz Nowak's avatar
Łukasz Nowak committed
3356 3357
    )

3358 3359 3360 3361 3362
  def test_enable_cache_ssl_proxy_verify_ssl_proxy_ca_crt_unverified(self):
    parameter_dict = self.parseSlaveParameterDict(
      'enable_cache-ssl-proxy-verify_ssl_proxy_ca_crt-unverified')

    self.assertLogAccessUrlWithPop(parameter_dict)
3363
    self.assertKedifaKeysWithPop(parameter_dict)
3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374
    self.assertEqual(
      {
        'domain':
        'enablecachesslproxyverifysslproxycacrtunverified.example.com',
        'replication_number': '1',
        'url':
        'http://enablecachesslproxyverifysslproxycacrtunverified.example.com',
        'site_url':
        'http://enablecachesslproxyverifysslproxycacrtunverified.example.com',
        'secure_access':
        'https://enablecachesslproxyverifysslproxycacrtunverified.example.com',
3375
        'public-ipv4': self._ipv4_address,
3376
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
3377 3378 3379 3380
      },
      parameter_dict
    )

3381
    result = fakeHTTPSResult(
3382 3383
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
3384 3385 3386 3387 3388 3389

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    self.assertEqual(
3390
      httplib.SERVICE_UNAVAILABLE,
3391 3392 3393
      result.status_code
    )

3394
    result_http = fakeHTTPResult(
3395 3396
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deeper')
3397 3398

    self.assertEqual(
3399
      httplib.FOUND,
3400 3401 3402
      result_http.status_code
    )

3403
    self.assertEqual(
3404 3405
      'https://enablecachesslproxyverifysslproxycacrtunverified.example.com'
      ':%s/test-path/deeper' % (HTTP_PORT,),
3406 3407 3408
      result_http.headers['Location']
    )

Łukasz Nowak's avatar
Łukasz Nowak committed
3409
  def test_enable_cache_ssl_proxy_verify_ssl_proxy_ca_crt(self):
3410
    parameter_dict = self.assertSlaveBase(
3411
      'enable_cache-ssl-proxy-verify_ssl_proxy_ca_crt')
Łukasz Nowak's avatar
Łukasz Nowak committed
3412

3413
    result = fakeHTTPSResult(
3414 3415
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
3416 3417

    self.assertEqual(
3418
      self.certificate_pem,
3419
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
3420

3421
    self.assertEqualResultJson(result, 'Path', '/test-path/deeper')
3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434

    headers = result.headers.copy()

    self.assertKeyWithPop('Server', headers)
    self.assertKeyWithPop('Date', headers)
    self.assertKeyWithPop('Age', headers)

    # drop keys appearing randomly in headers
    headers.pop('Transfer-Encoding', None)
    headers.pop('Content-Length', None)
    headers.pop('Connection', None)
    headers.pop('Keep-Alive', None)

3435
    self.assertEqual(
3436 3437 3438 3439
      {
        'Content-type': 'application/json',
        'Set-Cookie': 'secured=value;secure, nonsecured=value',
      },
3440
      headers
3441
    )
3442

Łukasz Nowak's avatar
Łukasz Nowak committed
3443
  def test_enable_cache_ssl_proxy_verify_unverified(self):
3444
    parameter_dict = self.assertSlaveBase(
3445
      'enable_cache-ssl-proxy-verify-unverified')
Łukasz Nowak's avatar
Łukasz Nowak committed
3446

3447
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
3448 3449 3450
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
3451
      self.certificate_pem,
3452
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
3453 3454

    self.assertEqual(
3455
      httplib.SERVICE_UNAVAILABLE,
3456
      result.status_code
Łukasz Nowak's avatar
Łukasz Nowak committed
3457 3458
    )

3459 3460 3461 3462 3463
  def test_type_zope_ssl_proxy_verify_ssl_proxy_ca_crt_unverified(self):
    parameter_dict = self.parseSlaveParameterDict(
      'type-zope-ssl-proxy-verify_ssl_proxy_ca_crt-unverified')

    self.assertLogAccessUrlWithPop(parameter_dict)
3464
    self.assertKedifaKeysWithPop(parameter_dict)
3465 3466 3467 3468 3469 3470 3471 3472 3473 3474
    self.assertEqual(
      {
        'domain': 'typezopesslproxyverifysslproxycacrtunverified.example.com',
        'replication_number': '1',
        'url':
        'http://typezopesslproxyverifysslproxycacrtunverified.example.com',
        'site_url':
        'http://typezopesslproxyverifysslproxycacrtunverified.example.com',
        'secure_access':
        'https://typezopesslproxyverifysslproxycacrtunverified.example.com',
3475
        'public-ipv4': self._ipv4_address,
3476
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
3477 3478 3479 3480
      },
      parameter_dict
    )

3481
    result = fakeHTTPSResult(
3482 3483 3484 3485 3486 3487 3488
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

    self.assertEqual(
3489
      httplib.SERVICE_UNAVAILABLE,
3490 3491 3492
      result.status_code
    )

3493
    result_http = fakeHTTPResult(
3494 3495 3496
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
3497
      httplib.FOUND,
3498 3499 3500
      result_http.status_code
    )

3501
    self.assertEqual(
3502 3503
      'https://typezopesslproxyverifysslproxycacrtunverified.example.com:%s/'
      'test-path' % (HTTP_PORT,),
3504 3505 3506
      result_http.headers['Location']
    )

Łukasz Nowak's avatar
Łukasz Nowak committed
3507
  def test_type_zope_ssl_proxy_verify_ssl_proxy_ca_crt(self):
3508
    parameter_dict = self.assertSlaveBase(
3509
      'type-zope-ssl-proxy-verify_ssl_proxy_ca_crt')
Łukasz Nowak's avatar
Łukasz Nowak committed
3510

3511
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
3512 3513 3514
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
3515
      self.certificate_pem,
3516
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
3517

3518 3519 3520 3521
    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
3522
    self.assertBackendHeaders(j['Incoming Headers'], parameter_dict['domain'])
3523 3524 3525 3526 3527 3528 3529

    self.assertEqualResultJson(
      result,
      'Path',
      '/VirtualHostBase/https//'
      'typezopesslproxyverifysslproxycacrt.example.com:443/'
      '/VirtualHostRoot/test-path'
3530
    )
3531

3532
    result = fakeHTTPResult(
3533
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
3534

3535 3536 3537 3538 3539 3540
    self.assertEqual(
      httplib.FOUND,
      result.status_code
    )

    self.assertEqual(
3541 3542
      'https://typezopesslproxyverifysslproxycacrt.example.com:'
      '%s/test-path' % (HTTP_PORT,),
3543
      result.headers['Location']
3544
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
3545 3546

  def test_type_zope_ssl_proxy_verify_unverified(self):
3547
    parameter_dict = self.assertSlaveBase(
3548
      'type-zope-ssl-proxy-verify-unverified')
Łukasz Nowak's avatar
Łukasz Nowak committed
3549

3550
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
3551 3552 3553
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
3554
      self.certificate_pem,
3555
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
3556 3557

    self.assertEqual(
3558
      httplib.SERVICE_UNAVAILABLE,
3559
      result.status_code
Łukasz Nowak's avatar
Łukasz Nowak committed
3560 3561 3562
    )

  def test_monitor_ipv6_test(self):
3563 3564
    parameter_dict = self.assertSlaveBase('monitor-ipv6-test')

3565
    result = fakeHTTPSResult(
3566 3567
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

Łukasz Nowak's avatar
Łukasz Nowak committed
3568
    self.assertEqual(
3569
      self.certificate_pem,
3570
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
3571

3572
    self.assertEqual(httplib.SERVICE_UNAVAILABLE, result.status_code)
Łukasz Nowak's avatar
Łukasz Nowak committed
3573

3574
    result_http = fakeHTTPResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
3575
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
3576 3577 3578 3579 3580 3581
    self.assertEqual(
      httplib.FOUND,
      result_http.status_code
    )

    self.assertEqual(
3582
      'https://monitoripv6test.example.com:%s/test-path' % (HTTP_PORT,),
3583 3584
      result_http.headers['Location']
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
3585 3586 3587

    monitor_file = glob.glob(
      os.path.join(
3588 3589 3590
        self.instance_path, '*', 'etc', 'plugin',
        'check-_monitor-ipv6-test-ipv6-packet-list-test.py'))[0]
    # get promise module and check that parameters are ok
Łukasz Nowak's avatar
Łukasz Nowak committed
3591
    self.assertEqual(
3592
      getPromisePluginParameterDict(monitor_file),
3593 3594 3595 3596
      {
        'frequency': '720',
        'address': 'monitor-ipv6-test'
      }
Łukasz Nowak's avatar
Łukasz Nowak committed
3597 3598 3599
    )

  def test_monitor_ipv4_test(self):
3600
    parameter_dict = self.assertSlaveBase('monitor-ipv4-test')
Łukasz Nowak's avatar
Łukasz Nowak committed
3601

3602
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
3603 3604 3605
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
3606
      self.certificate_pem,
3607
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
3608

3609
    self.assertEqual(httplib.SERVICE_UNAVAILABLE, result.status_code)
Łukasz Nowak's avatar
Łukasz Nowak committed
3610

3611
    result_http = fakeHTTPResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
3612
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
3613 3614 3615 3616 3617 3618
    self.assertEqual(
      httplib.FOUND,
      result_http.status_code
    )

    self.assertEqual(
3619
      'https://monitoripv4test.example.com:%s/test-path' % (HTTP_PORT,),
3620 3621
      result_http.headers['Location']
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
3622 3623 3624

    monitor_file = glob.glob(
      os.path.join(
3625 3626 3627
        self.instance_path, '*', 'etc', 'plugin',
        'check-_monitor-ipv4-test-ipv4-packet-list-test.py'))[0]
    # get promise module and check that parameters are ok
Łukasz Nowak's avatar
Łukasz Nowak committed
3628
    self.assertEqual(
3629
      getPromisePluginParameterDict(monitor_file),
3630 3631 3632 3633 3634
      {
        'frequency': '720',
        'ipv4': 'true',
        'address': 'monitor-ipv4-test',
      }
Łukasz Nowak's avatar
Łukasz Nowak committed
3635 3636
    )

3637 3638 3639
  def test_ciphers(self):
    parameter_dict = self.assertSlaveBase('ciphers')

3640
    result = fakeHTTPSResult(
3641 3642 3643 3644 3645 3646
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

3647
    self.assertEqual(httplib.SERVICE_UNAVAILABLE, result.status_code)
3648

3649
    result_http = fakeHTTPResult(
3650
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
3651 3652 3653 3654 3655 3656 3657

    self.assertEqual(
      httplib.FOUND,
      result_http.status_code
    )

    self.assertEqual(
3658
      'https://ciphers.example.com:%s/test-path' % (HTTP_PORT,),
3659 3660
      result_http.headers['Location']
    )
3661 3662 3663 3664 3665 3666 3667 3668 3669 3670

    configuration_file = glob.glob(
      os.path.join(
        self.instance_path, '*', 'etc', 'caddy-slave-conf.d', '_ciphers.conf'
      ))[0]
    self.assertTrue(
      'ciphers RSA-3DES-EDE-CBC-SHA RSA-AES128-CBC-SHA'
      in open(configuration_file).read()
    )

3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
  def test_enable_cache_custom_domain(self):
    reference = 'enable_cache_custom_domain'
    hostname = 'customdomainenablecache'
    parameter_dict = self.parseSlaveParameterDict(reference)
    self.assertLogAccessUrlWithPop(parameter_dict)
    self.assertKedifaKeysWithPop(parameter_dict, '')
    self.assertEqual(
      {
        'domain': '%s.example.com' % (hostname,),
        'replication_number': '1',
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
3684
        'public-ipv4': self._ipv4_address,
3685
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
3686 3687 3688 3689
      },
      parameter_dict
    )

3690
    result = fakeHTTPSResult(
3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper', headers={
        'X-Reply-Header-Cache-Control': 'max-age=1, stale-while-'
        'revalidate=3600, stale-if-error=3600'})

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

    headers = result.headers.copy()

    self.assertKeyWithPop('Server', headers)
    self.assertKeyWithPop('Date', headers)
    self.assertKeyWithPop('Age', headers)

    # drop keys appearing randomly in headers
    headers.pop('Transfer-Encoding', None)
    headers.pop('Content-Length', None)
    headers.pop('Connection', None)
    headers.pop('Keep-Alive', None)

    self.assertEqual(
      {
        'Content-type': 'application/json',
        'Set-Cookie': 'secured=value;secure, nonsecured=value',
        'Cache-Control': 'max-age=1, stale-while-revalidate=3600, '
                         'stale-if-error=3600'
      },
      headers
    )

    backend_headers = result.json()['Incoming Headers']
3721
    self.assertBackendHeaders(backend_headers, parameter_dict['domain'])
3722 3723 3724 3725
    via = backend_headers.pop('via', None)
    self.assertNotEqual(via, None)
    self.assertRegexpMatches(
      via,
3726
      r'^http\/1.1 caddy-frontend-1\[.*\] \(ApacheTrafficServer\/8.1.0\)$'
3727 3728 3729 3730 3731
    )

  def test_enable_cache_server_alias(self):
    parameter_dict = self.assertSlaveBase('enable_cache_server_alias')

3732
    result = fakeHTTPSResult(
3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper', headers={
        'X-Reply-Header-Cache-Control': 'max-age=1, stale-while-'
        'revalidate=3600, stale-if-error=3600'})

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

    headers = result.headers.copy()

    self.assertKeyWithPop('Server', headers)
    self.assertKeyWithPop('Date', headers)
    self.assertKeyWithPop('Age', headers)

    # drop keys appearing randomly in headers
    headers.pop('Transfer-Encoding', None)
    headers.pop('Content-Length', None)
    headers.pop('Connection', None)
    headers.pop('Keep-Alive', None)

    self.assertEqual(
      {
        'Content-type': 'application/json',
        'Set-Cookie': 'secured=value;secure, nonsecured=value',
        'Cache-Control': 'max-age=1, stale-while-revalidate=3600, '
                         'stale-if-error=3600'
      },
      headers
    )

    backend_headers = result.json()['Incoming Headers']
3763
    self.assertBackendHeaders(backend_headers, parameter_dict['domain'])
3764 3765 3766 3767
    via = backend_headers.pop('via', None)
    self.assertNotEqual(via, None)
    self.assertRegexpMatches(
      via,
3768
      r'^http\/1.1 caddy-frontend-1\[.*\] \(ApacheTrafficServer\/8.1.0\)$'
3769 3770
    )

3771
    result = fakeHTTPResult(
3772 3773 3774 3775 3776
      'enablecacheserveralias1.example.com', parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper', headers={
        'X-Reply-Header-Cache-Control': 'max-age=1, stale-while-'
        'revalidate=3600, stale-if-error=3600'})
    self.assertEqual(
3777 3778
      httplib.FOUND,
      result.status_code
3779 3780
    )

3781
    self.assertEqual(
3782 3783
      'https://enablecacheserveralias1.example.com:%s/test-path/deeper' % (
        HTTP_PORT,),
3784
      result.headers['Location']
3785 3786
    )

Łukasz Nowak's avatar
Łukasz Nowak committed
3787
  def test_enable_cache(self):
3788
    parameter_dict = self.assertSlaveBase('enable_cache')
Łukasz Nowak's avatar
Łukasz Nowak committed
3789

3790
    source_ip = '127.0.0.1'
3791
    result = fakeHTTPSResult(
3792
      parameter_dict['domain'], parameter_dict['public-ipv4'],
3793 3794
      'test-path/deep/.././deeper', headers={
        'X-Reply-Header-Cache-Control': 'max-age=1, stale-while-'
3795 3796 3797 3798
        'revalidate=3600, stale-if-error=3600',
      },
      source_ip=source_ip
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
3799

3800
    self.assertEqualResultJson(result, 'Path', '/test-path/deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
3801 3802 3803 3804 3805

    headers = result.headers.copy()

    self.assertKeyWithPop('Server', headers)
    self.assertKeyWithPop('Date', headers)
3806
    self.assertKeyWithPop('Age', headers)
Łukasz Nowak's avatar
Łukasz Nowak committed
3807 3808 3809 3810 3811 3812 3813 3814

    # drop keys appearing randomly in headers
    headers.pop('Transfer-Encoding', None)
    headers.pop('Content-Length', None)
    headers.pop('Connection', None)
    headers.pop('Keep-Alive', None)

    self.assertEqual(
3815 3816
      {
        'Content-type': 'application/json',
3817 3818 3819 3820
        'Set-Cookie': 'secured=value;secure, nonsecured=value',
        'Cache-Control': 'max-age=1, stale-while-revalidate=3600, '
                         'stale-if-error=3600'
      },
3821
      headers
Łukasz Nowak's avatar
Łukasz Nowak committed
3822 3823
    )

3824
    backend_headers = result.json()['Incoming Headers']
3825
    self.assertBackendHeaders(backend_headers, parameter_dict['domain'])
3826 3827 3828 3829
    via = backend_headers.pop('via', None)
    self.assertNotEqual(via, None)
    self.assertRegexpMatches(
      via,
3830
      r'^http\/1.1 caddy-frontend-1\[.*\] \(ApacheTrafficServer\/8.1.0\)$'
3831 3832
    )

3833 3834 3835 3836 3837 3838
    # check stale-if-error support (assumes stale-while-revalidate is same)
    # wait a bit for max-age to expire
    time.sleep(2)
    # real check: cache access provides old data, access cache directly, as
    # caddy has to be stopped
    try:
3839 3840 3841 3842 3843 3844
      # stop the backend, to have error on while connecting to it
      self.stopServerProcess()

      result = fakeHTTPSResult(
        parameter_dict['domain'], parameter_dict['public-ipv4'],
        'test-path/deep/.././deeper', headers={
3845
          'X-Reply-Header-Cache-Control': 'max-age=1, stale-while-'
3846 3847 3848 3849
          'revalidate=3600, stale-if-error=3600',
        },
        source_ip=source_ip
      )
3850 3851 3852 3853 3854 3855
      self.assertEqual(result.status_code, httplib.OK)
      self.assertEqualResultJson(result, 'Path', '/test-path/deeper')
      headers = result.headers.copy()
      self.assertKeyWithPop('Server', headers)
      self.assertKeyWithPop('Date', headers)
      self.assertKeyWithPop('Age', headers)
3856
      self.assertKeyWithPop('Expires', headers)
3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876
      # drop keys appearing randomly in headers
      headers.pop('Transfer-Encoding', None)
      headers.pop('Content-Length', None)
      headers.pop('Connection', None)
      headers.pop('Keep-Alive', None)

      self.assertEqual(
        {
          'Content-type': 'application/json',
          # ATS does not cache the cookied text content, see:
          # https://docs.trafficserver.apache.org/en/7.1.x/admin-guide/\
          # configuration/cache-basics.en.html#caching-cookied-objects
          # 'Set-Cookie': 'secured=value;secure, nonsecured=value',
          'Cache-Control': 'max-age=1, stale-while-revalidate=3600, '
                           'stale-if-error=3600',
        },
        headers
      )

      backend_headers = result.json()['Incoming Headers']
3877
      self.assertBackendHeaders(backend_headers, parameter_dict['domain'])
3878 3879 3880 3881
      via = backend_headers.pop('via', None)
      self.assertNotEqual(via, None)
      self.assertRegexpMatches(
        via,
3882
        r'^http\/1.1 caddy-frontend-1\[.*\] \(ApacheTrafficServer\/8.1.0\)$'
3883 3884
      )
    finally:
3885
      self.startServerProcess()
3886
    # END: check stale-if-error support
3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922
    # BEGIN: Check that squid.log is correctly filled in
    ats_log_file_list = glob.glob(
      os.path.join(
        self.instance_path, '*', 'var', 'log', 'trafficserver', 'squid.log'
      ))
    if len(ats_log_file_list) == 1:
      ats_log_file = ats_log_file_list[0]
    direct_pattern = re.compile(
      r'.*TCP_MISS/200 .*test-path/deeper.*enablecache.example.com'
      '.* - DIRECT*')
    refresh_pattern = re.compile(
      r'.*TCP_REFRESH_MISS/200 .*test-path/deeper.*enablecache.example.com'
      '.* - DIRECT*')
    # ATS needs some time to flush logs
    timeout = 5
    b = time.time()
    while True:
      direct_pattern_match = 0
      refresh_pattern_match = 0
      if (time.time() - b) > timeout:
        break
      with open(ats_log_file) as fh:
        for line in fh.readlines():
          if direct_pattern.match(line):
            direct_pattern_match += 1
          if refresh_pattern.match(line):
            refresh_pattern_match += 1
      if direct_pattern_match > 0 and refresh_pattern_match:
        break
      time.sleep(0.1)

    with open(ats_log_file) as fh:
      ats_log = fh.read()
    self.assertRegexpMatches(ats_log, direct_pattern)
    self.assertRegexpMatches(ats_log, refresh_pattern)
    # END: Check that squid.log is correctly filled in
3923

3924 3925 3926 3927
  def test_enable_cache_ats_timeout(self):
    parameter_dict = self.assertSlaveBase('enable_cache')
    # check that timeout seen by ATS does not result in many queries done
    # to the backend and that next request works like a charm
3928
    result = fakeHTTPSResult(
3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test_enable_cache_ats_timeout', headers={
        'Timeout': '15',
        'X-Reply-Header-Cache-Control': 'max-age=1, stale-while-'
        'revalidate=3600, stale-if-error=3600'})

    # ATS timed out
    self.assertEqual(
      httplib.GATEWAY_TIMEOUT,
      result.status_code
    )

3941
    backend_haproxy_log_file = glob.glob(
3942
      os.path.join(
3943
        self.instance_path, '*', 'var', 'log', 'backend-haproxy.log'
3944 3945 3946 3947
      ))[0]

    matching_line_amount = 0
    pattern = re.compile(
3948 3949 3950
      r'.* _enable_cache-http.backend .* 504 .*'
      '"GET .test_enable_cache_ats_timeout HTTP.1.1"$')
    with open(backend_haproxy_log_file) as fh:
3951 3952 3953 3954
      for line in fh.readlines():
        if pattern.match(line):
          matching_line_amount += 1

3955
    # Haproxy backend received maximum one connection
3956
    self.assertIn(matching_line_amount, [0, 1])
3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990

    timeout = 5
    b = time.time()
    # ATS created squid.log with a delay
    while True:
      if (time.time() - b) > timeout:
        self.fail('Squid log file did not appear in %ss' % (timeout,))
      ats_log_file_list = glob.glob(
        os.path.join(
          self.instance_path, '*', 'var', 'log', 'trafficserver', 'squid.log'
        ))
      if len(ats_log_file_list) == 1:
        ats_log_file = ats_log_file_list[0]
        break
      time.sleep(0.1)

    pattern = re.compile(
      r'.*ERR_READ_TIMEOUT/504 .*test_enable_cache_ats_timeout'
      '.*TIMEOUT_DIRECT*')
    timeout = 5
    b = time.time()
    # ATS needs some time to flush logs
    while True:
      matching_line_amount = 0
      if (time.time() - b) > timeout:
        break
      with open(ats_log_file) as fh:
        for line in fh.readlines():
          if pattern.match(line):
            matching_line_amount += 1
      if matching_line_amount > 0:
        break
      time.sleep(0.1)

3991 3992
    # ATS has maximum one entry for this query
    self.assertIn(matching_line_amount, [0, 1])
3993 3994

    # the result is available immediately after
3995
    result = fakeHTTPSResult(
3996 3997 3998 3999 4000 4001 4002
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper', headers={
        'X-Reply-Header-Cache-Control': 'max-age=1, stale-while-'
        'revalidate=3600, stale-if-error=3600'})

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

Łukasz Nowak's avatar
Łukasz Nowak committed
4003
  def test_enable_cache_disable_no_cache_request(self):
4004
    parameter_dict = self.assertSlaveBase(
4005
      'enable_cache-disable-no-cache-request')
Łukasz Nowak's avatar
Łukasz Nowak committed
4006

4007
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
4008 4009 4010 4011
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path',
      headers={'Pragma': 'no-cache', 'Cache-Control': 'something'})

    self.assertEqual(
4012
      self.certificate_pem,
4013
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
4014 4015 4016 4017 4018 4019 4020

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

    headers = result.headers.copy()

    self.assertKeyWithPop('Server', headers)
    self.assertKeyWithPop('Date', headers)
4021
    self.assertKeyWithPop('Age', headers)
Łukasz Nowak's avatar
Łukasz Nowak committed
4022 4023 4024 4025 4026 4027 4028 4029

    # drop keys appearing randomly in headers
    headers.pop('Transfer-Encoding', None)
    headers.pop('Content-Length', None)
    headers.pop('Connection', None)
    headers.pop('Keep-Alive', None)

    self.assertEqual(
4030 4031 4032 4033
      {
        'Content-type': 'application/json',
        'Set-Cookie': 'secured=value;secure, nonsecured=value'
      },
4034
      headers
Łukasz Nowak's avatar
Łukasz Nowak committed
4035 4036
    )

4037
    backend_headers = result.json()['Incoming Headers']
4038
    self.assertBackendHeaders(backend_headers, parameter_dict['domain'])
4039 4040 4041 4042
    via = backend_headers.pop('via', None)
    self.assertNotEqual(via, None)
    self.assertRegexpMatches(
      via,
4043
      r'^http\/1.1 caddy-frontend-1\[.*\] \(ApacheTrafficServer\/8.1.0\)$'
4044 4045
    )

Łukasz Nowak's avatar
Łukasz Nowak committed
4046 4047 4048 4049 4050 4051 4052
    try:
      j = result.json()
    except Exception:
      raise ValueError('JSON decode problem in:\n%s' % (result.text,))
    self.assertFalse('pragma' in j['Incoming Headers'].keys())

  def test_enable_cache_disable_via_header(self):
4053
    parameter_dict = self.assertSlaveBase('enable_cache-disable-via-header')
Łukasz Nowak's avatar
Łukasz Nowak committed
4054

4055
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
4056 4057 4058
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
4059
      self.certificate_pem,
4060
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
4061 4062 4063 4064 4065 4066 4067

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

    headers = result.headers.copy()

    self.assertKeyWithPop('Server', headers)
    self.assertKeyWithPop('Date', headers)
4068
    self.assertKeyWithPop('Age', headers)
Łukasz Nowak's avatar
Łukasz Nowak committed
4069 4070 4071 4072 4073 4074 4075 4076

    # drop keys appearing randomly in headers
    headers.pop('Transfer-Encoding', None)
    headers.pop('Content-Length', None)
    headers.pop('Connection', None)
    headers.pop('Keep-Alive', None)

    self.assertEqual(
4077 4078 4079 4080
      {
        'Content-type': 'application/json',
        'Set-Cookie': 'secured=value;secure, nonsecured=value',
      },
4081
      headers
Łukasz Nowak's avatar
Łukasz Nowak committed
4082 4083
    )

4084
    backend_headers = result.json()['Incoming Headers']
4085
    self.assertBackendHeaders(backend_headers, parameter_dict['domain'])
4086 4087 4088 4089
    via = backend_headers.pop('via', None)
    self.assertNotEqual(via, None)
    self.assertRegexpMatches(
      via,
4090
      r'^http\/1.1 caddy-frontend-1\[.*\] \(ApacheTrafficServer\/8.1.0\)$'
4091 4092
    )

Łukasz Nowak's avatar
Łukasz Nowak committed
4093
  def test_enable_http2_false(self):
4094
    parameter_dict = self.assertSlaveBase('enable-http2-false')
Łukasz Nowak's avatar
Łukasz Nowak committed
4095

4096
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
4097 4098 4099
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
4100
      self.certificate_pem,
4101
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116

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

    headers = result.headers.copy()

    self.assertKeyWithPop('Server', headers)
    self.assertKeyWithPop('Date', headers)

    # drop vary-keys
    headers.pop('Content-Length', None)
    headers.pop('Transfer-Encoding', None)
    headers.pop('Connection', None)
    headers.pop('Keep-Alive', None)

    self.assertEqual(
4117 4118 4119
      {
        'Content-Type': 'application/json',
        'Set-Cookie': 'secured=value;secure, nonsecured=value',
4120 4121
      },
      headers
Łukasz Nowak's avatar
Łukasz Nowak committed
4122 4123 4124 4125 4126 4127
    )

    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))

  def test_enable_http2_default(self):
4128
    parameter_dict = self.assertSlaveBase('enable-http2-default')
Łukasz Nowak's avatar
Łukasz Nowak committed
4129

4130
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
4131 4132 4133
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
4134
      self.certificate_pem,
4135
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150

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

    headers = result.headers.copy()

    self.assertKeyWithPop('Server', headers)
    self.assertKeyWithPop('Date', headers)

    # drop vary-keys
    headers.pop('Content-Length', None)
    headers.pop('Transfer-Encoding', None)
    headers.pop('Connection', None)
    headers.pop('Keep-Alive', None)

    self.assertEqual(
4151 4152 4153
      {
        'Content-type': 'application/json',
        'Set-Cookie': 'secured=value;secure, nonsecured=value',
4154 4155
      },
      headers
Łukasz Nowak's avatar
Łukasz Nowak committed
4156 4157 4158 4159 4160
    )

    self.assertTrue(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))

4161 4162 4163
  def test_prefer_gzip_encoding_to_backend_https_only(self):
    parameter_dict = self.assertSlaveBase(
      'prefer-gzip-encoding-to-backend-https-only')
Łukasz Nowak's avatar
Łukasz Nowak committed
4164

4165
    result = fakeHTTPSResult(
4166 4167
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
Łukasz Nowak's avatar
Łukasz Nowak committed
4168 4169 4170
      headers={'Accept-Encoding': 'gzip, deflate'})

    self.assertEqual(
4171
      self.certificate_pem,
4172
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
4173

4174
    self.assertEqualResultJson(result, 'Path', '/test-path/deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
4175

4176 4177
    self.assertBackendHeaders(
      result.json()['Incoming Headers'], parameter_dict['domain'])
Łukasz Nowak's avatar
Łukasz Nowak committed
4178
    self.assertEqual(
4179
      'gzip', result.json()['Incoming Headers']['accept-encoding'])
Łukasz Nowak's avatar
Łukasz Nowak committed
4180

4181
    result = fakeHTTPSResult(
4182 4183
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
Łukasz Nowak's avatar
Łukasz Nowak committed
4184 4185
      headers={'Accept-Encoding': 'deflate'})

4186
    self.assertEqualResultJson(result, 'Path', '/test-path/deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
4187

4188 4189
    self.assertBackendHeaders(
      result.json()['Incoming Headers'], parameter_dict['domain'])
Łukasz Nowak's avatar
Łukasz Nowak committed
4190
    self.assertEqual(
4191
      'deflate', result.json()['Incoming Headers']['accept-encoding'])
Łukasz Nowak's avatar
Łukasz Nowak committed
4192

4193
    result = fakeHTTPSResult(
4194 4195
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
4196 4197 4198 4199 4200

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

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

4203
    result = fakeHTTPSResult(
4204 4205
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
4206

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

4209 4210 4211 4212 4213 4214 4215
    result = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={'Accept-Encoding': 'gzip, deflate'})

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

4216 4217 4218
    self.assertBackendHeaders(
      result.json()['Incoming Headers'], parameter_dict['domain'],
      port=HTTP_PORT, proto='http')
4219 4220 4221 4222 4223 4224 4225 4226 4227 4228
    self.assertEqual(
      'gzip', result.json()['Incoming Headers']['accept-encoding'])

    result = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={'Accept-Encoding': 'deflate'})

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

4229 4230 4231
    self.assertBackendHeaders(
      result.json()['Incoming Headers'], parameter_dict['domain'],
      port=HTTP_PORT, proto='http')
4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246
    self.assertEqual(
      'deflate', result.json()['Incoming Headers']['accept-encoding'])

    result = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')

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

    result = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')

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

4247
  def test_prefer_gzip_encoding_to_backend(self):
4248
    parameter_dict = self.assertSlaveBase(
4249
      'prefer-gzip-encoding-to-backend')
4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261

    result = fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={'Accept-Encoding': 'gzip, deflate'})

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

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

4262 4263
    self.assertBackendHeaders(
      result.json()['Incoming Headers'], parameter_dict['domain'])
4264 4265 4266 4267 4268 4269 4270 4271 4272 4273
    self.assertEqual(
      'gzip', result.json()['Incoming Headers']['accept-encoding'])

    result = fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={'Accept-Encoding': 'deflate'})

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

4274 4275
    self.assertBackendHeaders(
      result.json()['Incoming Headers'], parameter_dict['domain'])
4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305
    self.assertEqual(
      'deflate', result.json()['Incoming Headers']['accept-encoding'])

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

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

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

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

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

    result = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={'Accept-Encoding': 'gzip, deflate'})

    self.assertEqual(
      httplib.FOUND,
      result.status_code
    )

    self.assertEqual(
4306
      'https://%s:%s/test-path/deeper' % (parameter_dict['domain'], HTTP_PORT),
4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320
      result.headers['Location']
    )

    result = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper',
      headers={'Accept-Encoding': 'deflate'})

    self.assertEqual(
      httplib.FOUND,
      result.status_code
    )

    self.assertEqual(
4321
      'https://%s:%s/test-path/deeper' % (parameter_dict['domain'], HTTP_PORT),
4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334
      result.headers['Location']
    )

    result = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')

    self.assertEqual(
      httplib.FOUND,
      result.status_code
    )

    self.assertEqual(
4335
      'https://%s:%s/test-path/deeper' % (parameter_dict['domain'], HTTP_PORT),
4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348
      result.headers['Location']
    )

    result = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')

    self.assertEqual(
      httplib.FOUND,
      result.status_code
    )

    self.assertEqual(
4349
      'https://%s:%s/test-path/deeper' % (parameter_dict['domain'], HTTP_PORT),
4350 4351 4352
      result.headers['Location']
    )

Łukasz Nowak's avatar
Łukasz Nowak committed
4353
  def test_disabled_cookie_list(self):
4354
    parameter_dict = self.assertSlaveBase('disabled-cookie-list')
Łukasz Nowak's avatar
Łukasz Nowak committed
4355

4356
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
4357 4358 4359 4360 4361 4362 4363 4364
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path',
      cookies=dict(
          Chocolate='absent',
          Vanilia='absent',
          Coffee='present'
        ))

    self.assertEqual(
4365
      self.certificate_pem,
4366
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
4367 4368 4369

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

4370 4371
    self.assertBackendHeaders(
      result.json()['Incoming Headers'], parameter_dict['domain'])
Łukasz Nowak's avatar
Łukasz Nowak committed
4372
    self.assertEqual(
4373
      'Coffee=present', result.json()['Incoming Headers']['cookie'])
Łukasz Nowak's avatar
Łukasz Nowak committed
4374 4375

  def test_https_url(self):
4376
    parameter_dict = self.assertSlaveBase('url_https-url')
Łukasz Nowak's avatar
Łukasz Nowak committed
4377

4378
    result = fakeHTTPSResult(
4379 4380
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
4381 4382

    self.assertEqual(
4383
      self.certificate_pem,
4384
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
4385

4386
    self.assertEqualResultJson(result, 'Path', '/https/test-path/deeper')
Łukasz Nowak's avatar
Łukasz Nowak committed
4387

4388
    result_http = fakeHTTPResult(
4389 4390
      parameter_dict['domain'], parameter_dict['public-ipv4'],
      'test-path/deep/.././deeper')
4391 4392 4393 4394 4395 4396 4397

    self.assertEqual(
      httplib.FOUND,
      result_http.status_code
    )

    self.assertEqual(
4398
      'https://urlhttpsurl.example.com:%s/test-path/deeper' % (HTTP_PORT,),
4399 4400
      result_http.headers['Location']
    )
Łukasz Nowak's avatar
Łukasz Nowak committed
4401

4402 4403 4404 4405 4406 4407 4408 4409 4410 4411
    # check that timeouts are correctly set in the haproxy configuration
    backend_configuration_file = glob.glob(os.path.join(
      self.instance_path, '*', 'etc', 'backend-haproxy.cfg'))[0]
    with open(backend_configuration_file) as fh:
      content = fh.read()
      self.assertTrue("""backend _url_https-url-http
  timeout server 15s
  timeout connect 10s
  retries 5""" in content)

Łukasz Nowak's avatar
Łukasz Nowak committed
4412

4413
@skip('Impossible to instantiate cluster with stopped partition')
Łukasz Nowak's avatar
Łukasz Nowak committed
4414 4415 4416 4417 4418
class TestReplicateSlave(SlaveHttpFrontendTestCase, TestDataMixin):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
4419
      'public-ipv4': cls._ipv4_address,
Łukasz Nowak's avatar
Łukasz Nowak committed
4420
      '-frontend-quantity': 2,
4421
      '-sla-2-computer_guid': cls.slap._computer_id,
Łukasz Nowak's avatar
Łukasz Nowak committed
4422 4423 4424
      '-frontend-2-state': 'stopped',
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
4425 4426
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
Łukasz Nowak's avatar
Łukasz Nowak committed
4427 4428 4429 4430 4431 4432 4433
    }

  @classmethod
  def getSlaveParameterDictDict(cls):
    return {
      'replicate': {
        'url': cls.backend_url,
4434
        'enable_cache': True,
Łukasz Nowak's avatar
Łukasz Nowak committed
4435 4436 4437 4438
      },
    }

  def test(self):
4439
    parameter_dict = self.parseSlaveParameterDict('replicate')
4440
    self.assertLogAccessUrlWithPop(parameter_dict)
4441
    self.assertKedifaKeysWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
4442 4443 4444 4445 4446 4447 4448
    self.assertEqual(
      {
        'domain': 'replicate.example.com',
        'replication_number': '2',
        'url': 'http://replicate.example.com',
        'site_url': 'http://replicate.example.com',
        'secure_access': 'https://replicate.example.com',
4449
        'public-ipv4': self._ipv4_address,
4450
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
4451 4452
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
4453 4454
    )

4455
    result = fakeHTTPSResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
4456 4457 4458
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
4459
      self.certificate_pem,
4460
      der2pem(result.peercert))
Łukasz Nowak's avatar
Łukasz Nowak committed
4461 4462 4463

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

4464
    result_http = fakeHTTPResult(
Łukasz Nowak's avatar
Łukasz Nowak committed
4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
    self.assertEqualResultJson(result_http, 'Path', '/test-path')

    # prove 2nd frontend by inspection of the instance
    slave_configuration_name = '_replicate.conf'
    slave_configuration_file_list = [
      '/'.join([f[0], slave_configuration_name]) for f in [
        q for q in os.walk(self.instance_path)
        if slave_configuration_name in q[2]
      ]
    ]

    self.assertEqual(
      2, len(slave_configuration_file_list), slave_configuration_file_list)


4481
@skip('Impossible to instantiate cluster with destroyed partition')
4482 4483 4484 4485 4486
class TestReplicateSlaveOtherDestroyed(SlaveHttpFrontendTestCase):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
4487
      'public-ipv4': cls._ipv4_address,
4488
      '-frontend-quantity': 2,
4489
      '-sla-2-computer_guid': cls.slap._computer_id,
4490 4491 4492 4493 4494 4495 4496 4497 4498
      '-frontend-2-state': 'destroyed',
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
    }

  @classmethod
  def getSlaveParameterDictDict(cls):
4499 4500 4501 4502 4503 4504
    return {
      'empty': {
        'url': cls.backend_url,
        'enable_cache': True,
      }
    }
4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520

  def test_extra_slave_instance_list_not_present_destroyed_request(self):
    buildout_file = os.path.join(
      self.getMasterPartitionPath(), 'buildout-switch-softwaretype.cfg')
    with open(buildout_file) as fh:
      buildout_file_content = fh.read()
      node_1_present = re.search(
        "^config-frontend-name = !py!'caddy-frontend-1'$",
        buildout_file_content, flags=re.M) is not None
      node_2_present = re.search(
        "^config-frontend-name = !py!'caddy-frontend-2'$",
        buildout_file_content, flags=re.M) is not None
    self.assertTrue(node_1_present)
    self.assertFalse(node_2_present)


Łukasz Nowak's avatar
Łukasz Nowak committed
4521 4522 4523 4524 4525 4526
class TestEnableHttp2ByDefaultFalseSlave(SlaveHttpFrontendTestCase,
                                         TestDataMixin):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
4527
      'public-ipv4': cls._ipv4_address,
Łukasz Nowak's avatar
Łukasz Nowak committed
4528 4529 4530
      'enable-http2-by-default': 'false',
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
4531 4532
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
Łukasz Nowak's avatar
Łukasz Nowak committed
4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545
    }

  @classmethod
  def getSlaveParameterDictDict(cls):
    return {
      'enable-http2-default': {
      },
      'enable-http2-false': {
        'enable-http2': 'false',
      },
      'enable-http2-true': {
        'enable-http2': 'true',
      },
4546 4547 4548 4549
      'dummy-cached': {
        'url': cls.backend_url,
        'enable_cache': True,
      }
Łukasz Nowak's avatar
Łukasz Nowak committed
4550 4551 4552
    }

  def test_enable_http2_default(self):
4553
    parameter_dict = self.parseSlaveParameterDict('enable-http2-default')
4554
    self.assertLogAccessUrlWithPop(parameter_dict)
4555
    self.assertKedifaKeysWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
4556 4557 4558 4559 4560 4561 4562 4563
    self.assertEqual(
      {
        'domain': 'enablehttp2default.example.com',
        'replication_number': '1',
        'url': 'http://enablehttp2default.example.com',
        'site_url': 'http://enablehttp2default.example.com',
        'secure_access':
        'https://enablehttp2default.example.com',
4564
        'public-ipv4': self._ipv4_address,
4565
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
4566 4567
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
4568 4569 4570 4571 4572 4573
    )

    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))

  def test_enable_http2_false(self):
4574
    parameter_dict = self.parseSlaveParameterDict('enable-http2-false')
4575
    self.assertLogAccessUrlWithPop(parameter_dict)
4576
    self.assertKedifaKeysWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
4577 4578 4579 4580 4581 4582 4583 4584
    self.assertEqual(
      {
        'domain': 'enablehttp2false.example.com',
        'replication_number': '1',
        'url': 'http://enablehttp2false.example.com',
        'site_url': 'http://enablehttp2false.example.com',
        'secure_access':
        'https://enablehttp2false.example.com',
4585
        'public-ipv4': self._ipv4_address,
4586
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
4587 4588
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
4589 4590 4591 4592 4593 4594
    )

    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))

  def test_enable_http2_true(self):
4595
    parameter_dict = self.parseSlaveParameterDict('enable-http2-true')
4596
    self.assertLogAccessUrlWithPop(parameter_dict)
4597
    self.assertKedifaKeysWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
4598 4599 4600 4601 4602 4603 4604 4605
    self.assertEqual(
      {
        'domain': 'enablehttp2true.example.com',
        'replication_number': '1',
        'url': 'http://enablehttp2true.example.com',
        'site_url': 'http://enablehttp2true.example.com',
        'secure_access':
        'https://enablehttp2true.example.com',
4606
        'public-ipv4': self._ipv4_address,
4607
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
4608 4609
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621
    )

    self.assertTrue(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))


class TestEnableHttp2ByDefaultDefaultSlave(SlaveHttpFrontendTestCase,
                                           TestDataMixin):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
4622
      'public-ipv4': cls._ipv4_address,
Łukasz Nowak's avatar
Łukasz Nowak committed
4623 4624
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
4625 4626
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
Łukasz Nowak's avatar
Łukasz Nowak committed
4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639
    }

  @classmethod
  def getSlaveParameterDictDict(cls):
    return {
      'enable-http2-default': {
      },
      'enable-http2-false': {
        'enable-http2': 'false',
      },
      'enable-http2-true': {
        'enable-http2': 'true',
      },
4640 4641 4642 4643
      'dummy-cached': {
        'url': cls.backend_url,
        'enable_cache': True,
      }
Łukasz Nowak's avatar
Łukasz Nowak committed
4644 4645 4646
    }

  def test_enable_http2_default(self):
4647
    parameter_dict = self.parseSlaveParameterDict('enable-http2-default')
4648
    self.assertLogAccessUrlWithPop(parameter_dict)
4649
    self.assertKedifaKeysWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
4650 4651 4652 4653 4654 4655 4656 4657
    self.assertEqual(
      {
        'domain': 'enablehttp2default.example.com',
        'replication_number': '1',
        'url': 'http://enablehttp2default.example.com',
        'site_url': 'http://enablehttp2default.example.com',
        'secure_access':
        'https://enablehttp2default.example.com',
4658
        'public-ipv4': self._ipv4_address,
4659
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
4660 4661
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
4662 4663 4664 4665 4666 4667
    )

    self.assertTrue(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))

  def test_enable_http2_false(self):
4668
    parameter_dict = self.parseSlaveParameterDict('enable-http2-false')
4669
    self.assertLogAccessUrlWithPop(parameter_dict)
4670
    self.assertKedifaKeysWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
4671 4672 4673 4674 4675 4676 4677 4678
    self.assertEqual(
      {
        'domain': 'enablehttp2false.example.com',
        'replication_number': '1',
        'url': 'http://enablehttp2false.example.com',
        'site_url': 'http://enablehttp2false.example.com',
        'secure_access':
        'https://enablehttp2false.example.com',
4679
        'public-ipv4': self._ipv4_address,
4680
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
4681 4682
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
4683 4684 4685 4686 4687 4688
    )

    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))

  def test_enable_http2_true(self):
4689
    parameter_dict = self.parseSlaveParameterDict('enable-http2-true')
4690
    self.assertLogAccessUrlWithPop(parameter_dict)
4691
    self.assertKedifaKeysWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
4692 4693 4694
    self.assertEqual(
      {
        'domain': 'enablehttp2true.example.com',
4695
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
Łukasz Nowak's avatar
Łukasz Nowak committed
4696 4697 4698 4699 4700
        'replication_number': '1',
        'url': 'http://enablehttp2true.example.com',
        'site_url': 'http://enablehttp2true.example.com',
        'secure_access':
        'https://enablehttp2true.example.com',
4701
        'public-ipv4': self._ipv4_address,
4702 4703
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716
    )

    self.assertTrue(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))


class TestRe6stVerificationUrlDefaultSlave(SlaveHttpFrontendTestCase,
                                           TestDataMixin):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
4717 4718
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
Łukasz Nowak's avatar
Łukasz Nowak committed
4719 4720 4721 4722 4723 4724
    }

  @classmethod
  def getSlaveParameterDictDict(cls):
    return {
      'default': {
4725 4726
        'url': cls.backend_url,
        'enable_cache': True
Łukasz Nowak's avatar
Łukasz Nowak committed
4727 4728 4729
      },
    }

4730 4731 4732 4733 4734
  @classmethod
  def waitForSlave(cls):
    # no need to wait for slave availability here
    return True

Łukasz Nowak's avatar
Łukasz Nowak committed
4735
  def test_default(self):
4736
    parameter_dict = self.parseSlaveParameterDict('default')
4737
    self.assertLogAccessUrlWithPop(parameter_dict)
4738
    self.assertKedifaKeysWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
4739 4740 4741 4742 4743 4744 4745
    self.assertEqual(
      {
        'domain': 'default.None',
        'replication_number': '1',
        'url': 'http://default.None',
        'site_url': 'http://default.None',
        'secure_access': 'https://default.None',
4746
        'public-ipv4': 'None',
4747
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
4748 4749
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
4750 4751 4752 4753
    )

    re6st_connectivity_promise_list = glob.glob(
      os.path.join(
4754 4755
        self.instance_path, '*', 'etc', 'plugin',
        're6st-connectivity.py'))
Łukasz Nowak's avatar
Łukasz Nowak committed
4756 4757

    self.assertEqual(1, len(re6st_connectivity_promise_list))
4758
    re6st_connectivity_promise_file = re6st_connectivity_promise_list[0]
Łukasz Nowak's avatar
Łukasz Nowak committed
4759

4760
    self.assertEqual(
4761
      getPromisePluginParameterDict(re6st_connectivity_promise_file),
4762 4763 4764
      {
        'url': 'http://[2001:67c:1254:4::1]/index.html',
      }
Łukasz Nowak's avatar
Łukasz Nowak committed
4765 4766 4767
    )


4768
@skip('New test system cannot be used with failing promises')
Łukasz Nowak's avatar
Łukasz Nowak committed
4769 4770 4771 4772 4773 4774 4775 4776
class TestRe6stVerificationUrlSlave(SlaveHttpFrontendTestCase,
                                    TestDataMixin):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      're6st-verification-url': 'some-re6st-verification-url',
4777 4778
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
Łukasz Nowak's avatar
Łukasz Nowak committed
4779 4780 4781 4782 4783 4784
    }

  @classmethod
  def getSlaveParameterDictDict(cls):
    return {
      'default': {
4785 4786
        'url': cls.backend_url,
        'enable_cache': True,
Łukasz Nowak's avatar
Łukasz Nowak committed
4787 4788 4789 4790
      },
    }

  def test_default(self):
4791
    parameter_dict = self.parseSlaveParameterDict('default')
4792
    self.assertLogAccessUrlWithPop(parameter_dict)
4793
    self.assertKedifaKeysWithPop(parameter_dict)
Łukasz Nowak's avatar
Łukasz Nowak committed
4794 4795 4796 4797 4798 4799 4800
    self.assertEqual(
      {
        'domain': 'default.None',
        'replication_number': '1',
        'url': 'http://default.None',
        'site_url': 'http://default.None',
        'secure_access': 'https://default.None',
4801
        'public-ipv4': 'None',
4802 4803
      },
      parameter_dict
Łukasz Nowak's avatar
Łukasz Nowak committed
4804 4805 4806 4807
    )

    re6st_connectivity_promise_list = glob.glob(
      os.path.join(
4808 4809
        self.instance_path, '*', 'etc', 'plugin',
        're6st-connectivity.py'))
Łukasz Nowak's avatar
Łukasz Nowak committed
4810 4811

    self.assertEqual(1, len(re6st_connectivity_promise_list))
4812
    re6st_connectivity_promise_file = re6st_connectivity_promise_list[0]
Łukasz Nowak's avatar
Łukasz Nowak committed
4813

4814
    self.assertEqual(
4815
      getPromisePluginParameterDict(re6st_connectivity_promise_file),
4816 4817 4818
      {
        'url': 'some-re6st-verification-url',
      }
Łukasz Nowak's avatar
Łukasz Nowak committed
4819
    )
4820 4821


4822
@skip('Impossible to instantiate cluster with stopped partition')
4823 4824 4825 4826 4827
class TestDefaultMonitorHttpdPort(SlaveHttpFrontendTestCase, TestDataMixin):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      '-frontend-1-state': 'stopped',
4828 4829
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
4830 4831
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
4832 4833
    }

4834 4835 4836 4837
  @classmethod
  def runKedifaUpdater(cls):
    return

4838 4839 4840 4841 4842 4843
  @classmethod
  def getSlaveParameterDictDict(cls):
    return {
      'test': {
        'url': cls.backend_url,
      },
4844 4845 4846 4847
      'testcached': {
        'url': cls.backend_url,
        'enable_cache': True,
      },
4848 4849 4850
    }

  def test(self):
4851
    parameter_dict = self.parseSlaveParameterDict('test')
4852
    self.assertKeyWithPop('log-access-url', parameter_dict)
4853
    self.assertKedifaKeysWithPop(parameter_dict)
4854 4855 4856 4857
    self.assertEqual(
      {
        'domain': 'test.None', 'replication_number': '1',
        'url': 'http://test.None', 'site_url': 'http://test.None',
4858
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
4859
        'secure_access': 'https://test.None', 'public-ipv4': 'None'},
4860
      parameter_dict
4861 4862
    )
    master_monitor_conf = open(os.path.join(
4863
      self.instance_path, 'T-0', 'etc',
4864 4865
      'monitor-httpd.conf')).read()
    slave_monitor_conf = open(os.path.join(
4866
      self.instance_path, 'T-2', 'etc',
4867 4868 4869
      'monitor-httpd.conf')).read()

    self.assertTrue(
4870
      'Listen [%s]:8196' % (self._ipv6_address,) in master_monitor_conf)
4871
    self.assertTrue(
4872
      'Listen [%s]:8072' % (self._ipv6_address,) in slave_monitor_conf)
Łukasz Nowak's avatar
Łukasz Nowak committed
4873 4874


4875
class TestSlaveGlobalDisableHttp2(TestSlave):
4876 4877
  @classmethod
  def getInstanceParameterDict(cls):
4878 4879 4880 4881
    instance_parameter_dict = super(
      TestSlaveGlobalDisableHttp2, cls).getInstanceParameterDict()
    instance_parameter_dict['global-disable-http2'] = 'TrUe'
    return instance_parameter_dict
4882

4883 4884
  def test_enable_http2_default(self):
    parameter_dict = self.parseSlaveParameterDict('enable-http2-default')
4885
    self.assertLogAccessUrlWithPop(parameter_dict)
4886
    self.assertKedifaKeysWithPop(parameter_dict)
4887 4888
    self.assertEqual(
      {
4889
        'domain': 'enablehttp2default.example.com',
4890
        'replication_number': '1',
4891 4892 4893 4894
        'url': 'http://enablehttp2default.example.com',
        'site_url': 'http://enablehttp2default.example.com',
        'secure_access':
        'https://enablehttp2default.example.com',
4895
        'public-ipv4': self._ipv4_address,
4896
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
4897 4898
      },
      parameter_dict
4899 4900
    )

4901
    result = fakeHTTPSResult(
4902 4903 4904
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
4905
      self.certificate_pem,
4906
      der2pem(result.peercert))
4907 4908 4909

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

4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920
    headers = result.headers.copy()

    self.assertKeyWithPop('Server', headers)
    self.assertKeyWithPop('Date', headers)

    # drop vary-keys
    headers.pop('Content-Length', None)
    headers.pop('Transfer-Encoding', None)
    headers.pop('Connection', None)
    headers.pop('Keep-Alive', None)

4921
    self.assertEqual(
4922
      {
4923 4924
        'Content-type': 'application/json',
        'Set-Cookie': 'secured=value;secure, nonsecured=value',
4925
      },
4926
      headers
4927
    )
4928

4929 4930
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))
4931

4932

4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944
class TestEnableHttp2ByDefaultFalseSlaveGlobalDisableHttp2(
  TestEnableHttp2ByDefaultFalseSlave):
  @classmethod
  def getInstanceParameterDict(cls):
    instance_parameter_dict = super(
      TestEnableHttp2ByDefaultFalseSlaveGlobalDisableHttp2,
      cls).getInstanceParameterDict()
    instance_parameter_dict['global-disable-http2'] = 'TrUe'
    return instance_parameter_dict

  def test_enable_http2_true(self):
    parameter_dict = self.parseSlaveParameterDict('enable-http2-true')
4945
    self.assertLogAccessUrlWithPop(parameter_dict)
4946
    self.assertKedifaKeysWithPop(parameter_dict)
4947 4948
    self.assertEqual(
      {
4949
        'domain': 'enablehttp2true.example.com',
4950
        'replication_number': '1',
4951 4952
        'url': 'http://enablehttp2true.example.com',
        'site_url': 'http://enablehttp2true.example.com',
4953
        'secure_access':
4954
        'https://enablehttp2true.example.com',
4955
        'public-ipv4': self._ipv4_address,
4956
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
4957 4958
      },
      parameter_dict
4959 4960
    )

4961 4962
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))
4963 4964


4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976
class TestEnableHttp2ByDefaultDefaultSlaveGlobalDisableHttp2(
  TestEnableHttp2ByDefaultDefaultSlave):
  @classmethod
  def getInstanceParameterDict(cls):
    instance_parameter_dict = super(
      TestEnableHttp2ByDefaultDefaultSlaveGlobalDisableHttp2,
      cls).getInstanceParameterDict()
    instance_parameter_dict['global-disable-http2'] = 'TrUe'
    return instance_parameter_dict

  def test_enable_http2_true(self):
    parameter_dict = self.parseSlaveParameterDict('enable-http2-true')
4977
    self.assertLogAccessUrlWithPop(parameter_dict)
4978
    self.assertKedifaKeysWithPop(parameter_dict)
4979 4980
    self.assertEqual(
      {
4981
        'domain': 'enablehttp2true.example.com',
4982
        'replication_number': '1',
4983 4984
        'url': 'http://enablehttp2true.example.com',
        'site_url': 'http://enablehttp2true.example.com',
4985
        'secure_access':
4986
        'https://enablehttp2true.example.com',
4987
        'public-ipv4': self._ipv4_address,
4988
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
4989 4990
      },
      parameter_dict
4991 4992
    )

4993 4994
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))
4995

4996 4997
  def test_enable_http2_default(self):
    parameter_dict = self.parseSlaveParameterDict('enable-http2-default')
4998
    self.assertLogAccessUrlWithPop(parameter_dict)
4999
    self.assertKedifaKeysWithPop(parameter_dict)
5000 5001
    self.assertEqual(
      {
5002
        'domain': 'enablehttp2default.example.com',
5003
        'replication_number': '1',
5004 5005 5006 5007
        'url': 'http://enablehttp2default.example.com',
        'site_url': 'http://enablehttp2default.example.com',
        'secure_access':
        'https://enablehttp2default.example.com',
5008
        'public-ipv4': self._ipv4_address,
5009
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5010 5011
      },
      parameter_dict
5012 5013
    )

5014 5015
    self.assertFalse(
      isHTTP2(parameter_dict['domain'], parameter_dict['public-ipv4']))
5016 5017


5018 5019 5020 5021 5022 5023 5024
class TestSlaveSlapOSMasterCertificateCompatibilityOverrideMaster(
  SlaveHttpFrontendTestCase, TestDataMixin):
  @classmethod
  def setUpMaster(cls):
    # run partition until AIKC finishes
    cls.runComputerPartitionUntil(
      cls.untilNotReadyYetNotInMasterKeyGenerateAuthUrl)
5025

5026 5027 5028 5029 5030 5031 5032
    parameter_dict = cls.requestDefaultInstance().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)
    # Do not upload certificates for the master partition
5033

5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
      'public-ipv4': cls._ipv4_address,
      'apache-certificate': cls.certificate_pem,
      'apache-key': cls.key_pem,
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
      'mpm-graceful-shutdown-timeout': 2,
    }

  @classmethod
  def getSlaveParameterDictDict(cls):
    return {
      'ssl_from_master_kedifa_overrides_master_certificate': {
        'url': cls.backend_url,
        'enable_cache': True
      },
    }

  def test_ssl_from_master_kedifa_overrides_master_certificate(self):
    reference = 'ssl_from_master_kedifa_overrides_master_certificate'
    parameter_dict = self.parseSlaveParameterDict(reference)
5060
    self.assertLogAccessUrlWithPop(parameter_dict)
5061
    self.assertKedifaKeysWithPop(parameter_dict)
5062
    hostname = reference.translate(None, '_-')
5063 5064
    self.assertEqual(
      {
5065
        'domain': '%s.example.com' % (hostname,),
5066
        'replication_number': '1',
5067 5068 5069
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
5070
        'public-ipv4': self._ipv4_address,
5071
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5072 5073
      },
      parameter_dict
5074 5075
    )

5076
    result = fakeHTTPSResult(
5077 5078 5079
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
5080
      self.certificate_pem,
5081
      der2pem(result.peercert))
5082

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

5085 5086
    _, key_pem, _, certificate_pem = \
        createSelfSignedCertificate([parameter_dict['domain']])
5087

5088 5089 5090 5091 5092 5093 5094 5095 5096 5097
    master_parameter_dict = \
        self.requestDefaultInstance().getConnectionParameterDict()
    auth = requests.get(
      master_parameter_dict['master-key-generate-auth-url'],
      verify=self.ca_certificate_file)
    requests.put(
      master_parameter_dict['master-key-upload-url'] + auth.text,
      data=key_pem + certificate_pem,
      verify=self.ca_certificate_file)
    self.runKedifaUpdater()
5098

5099
    result = fakeHTTPSResult(
5100 5101 5102
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
5103
      certificate_pem,
5104
      der2pem(result.peercert))
5105

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

5108

5109 5110
class TestSlaveSlapOSMasterCertificateCompatibility(
  SlaveHttpFrontendTestCase, TestDataMixin):
5111 5112

  @classmethod
5113 5114 5115 5116
  def setUpMaster(cls):
    # run partition until AIKC finishes
    cls.runComputerPartitionUntil(
      cls.untilNotReadyYetNotInMasterKeyGenerateAuthUrl)
5117

5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187
    parameter_dict = cls.requestDefaultInstance().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)
    # Do not upload certificates for the master partition

  @classmethod
  def prepareCertificate(cls):
    _, cls.ssl_from_slave_key_pem, _, cls.ssl_from_slave_certificate_pem = \
      createSelfSignedCertificate(
        [
          'sslfromslave.example.com',
        ])
    _, cls.ssl_from_slave_kedifa_overrides_key_pem, _, \
        cls.ssl_from_slave_kedifa_overrides_certificate_pem = \
        createSelfSignedCertificate(
          [
            'sslfromslavekedifaoverrides.example.com',
          ])
    _, cls.type_notebook_ssl_from_slave_key_pem, _, \
        cls.type_notebook_ssl_from_slave_certificate_pem = \
        createSelfSignedCertificate(
          [
            'typenotebooksslfromslave.example.com',
          ])
    _, cls.type_notebook_ssl_from_slave_kedifa_overrides_key_pem, _, \
        cls.type_notebook_ssl_from_slave_kedifa_overrides_certificate_pem = \
        createSelfSignedCertificate(
          [
            'typenotebooksslfromslavekedifaoverrides.example.com',
          ])

    cls.ca = CertificateAuthority(
      'TestSlaveSlapOSMasterCertificateCompatibility')

    _, cls.customdomain_ca_key_pem, csr, _ = createCSR(
      'customdomainsslcrtsslkeysslcacrt.example.com')
    _, cls.customdomain_ca_certificate_pem = cls.ca.signCSR(csr)

    _, cls.sslcacrtgarbage_ca_key_pem, csr, _ = createCSR(
      'sslcacrtgarbage.example.com')
    _, cls.sslcacrtgarbage_ca_certificate_pem = cls.ca.signCSR(csr)

    _, cls.ssl_from_slave_ca_key_pem, csr, _ = createCSR(
      'sslfromslave.example.com')
    _, cls.ssl_from_slave_ca_certificate_pem = cls.ca.signCSR(csr)

    _, cls.customdomain_key_pem, _, cls.customdomain_certificate_pem = \
        createSelfSignedCertificate(['customdomainsslcrtsslkey.example.com'])

    super(
      TestSlaveSlapOSMasterCertificateCompatibility, cls).prepareCertificate()

  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
      'public-ipv4': cls._ipv4_address,
      'apache-certificate': cls.certificate_pem,
      'apache-key': cls.key_pem,
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
      'mpm-graceful-shutdown-timeout': 2,
    }

  @classmethod
5188 5189
  def getSlaveParameterDictDict(cls):
    return {
5190 5191 5192
      'ssl_from_master': {
        'url': cls.backend_url,
        'enable_cache': True,
5193
      },
5194 5195
      'ssl_from_master_kedifa_overrides': {
        'url': cls.backend_url,
5196
      },
5197 5198 5199 5200
      'ssl_from_slave': {
        'url': cls.backend_url,
        'ssl_crt': cls.ssl_from_slave_certificate_pem,
        'ssl_key': cls.ssl_from_slave_key_pem,
5201
      },
5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244
      'ssl_from_slave_kedifa_overrides': {
        'url': cls.backend_url,
        'ssl_crt': cls.ssl_from_slave_kedifa_overrides_certificate_pem,
        'ssl_key': cls.ssl_from_slave_kedifa_overrides_key_pem,
      },
      'custom_domain_ssl_crt_ssl_key': {
        'url': cls.backend_url,
        'ssl_crt': cls.customdomain_certificate_pem,
        'ssl_key': cls.customdomain_key_pem,
        'custom_domain': 'customdomainsslcrtsslkey.example.com'
      },
      'custom_domain_ssl_crt_ssl_key_ssl_ca_crt': {
        'url': cls.backend_url,
        'ssl_crt': cls.customdomain_ca_certificate_pem,
        'ssl_key': cls.customdomain_ca_key_pem,
        'ssl_ca_crt': cls.ca.certificate_pem,
        'custom_domain': 'customdomainsslcrtsslkeysslcacrt.example.com',
      },
      'ssl_ca_crt_garbage': {
        'url': cls.backend_url,
        'ssl_crt': cls.sslcacrtgarbage_ca_certificate_pem,
        'ssl_key': cls.sslcacrtgarbage_ca_key_pem,
        'ssl_ca_crt': 'some garbage',
      },
      'ssl_ca_crt_does_not_match': {
        'url': cls.backend_url,
        'ssl_crt': cls.certificate_pem,
        'ssl_key': cls.key_pem,
        'ssl_ca_crt': cls.ca.certificate_pem,
      },
      'type-notebook-ssl_from_master': {
        'url': cls.backend_url,
        'type': 'notebook',
      },
      'type-notebook-ssl_from_slave': {
        'url': cls.backend_url,
        'ssl_crt': cls.type_notebook_ssl_from_slave_certificate_pem,
        'ssl_key': cls.type_notebook_ssl_from_slave_key_pem,
        'type': 'notebook',
      },
      'type-notebook-ssl_from_master_kedifa_overrides': {
        'url': cls.backend_url,
        'type': 'notebook',
5245
      },
5246 5247 5248 5249 5250 5251 5252 5253
      'type-notebook-ssl_from_slave_kedifa_overrides': {
        'url': cls.backend_url,
        'ssl_crt':
        cls.type_notebook_ssl_from_slave_kedifa_overrides_certificate_pem,
        'ssl_key':
        cls.type_notebook_ssl_from_slave_kedifa_overrides_key_pem,
        'type': 'notebook',
      }
5254 5255 5256
    }

  def test_master_partition_state(self):
5257
    parameter_dict = self.parseConnectionParameterDict()
5258
    self.assertKeyWithPop('monitor-setup-url', parameter_dict)
5259
    self.assertBackendHaproxyStatisticUrl(parameter_dict)
5260
    self.assertKedifaKeysWithPop(parameter_dict, 'master-')
5261
    self.assertRejectedSlavePromiseWithPop(parameter_dict)
5262 5263

    expected_parameter_dict = {
5264
      'monitor-base-url': 'https://[%s]:8401' % self._ipv6_address,
5265
      'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5266
      'domain': 'example.com',
5267 5268 5269
      'accepted-slave-amount': '12',
      'rejected-slave-amount': '0',
      'slave-amount': '12',
5270
      'rejected-slave-dict': {
5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322
        # u"_ssl_ca_crt_only":
        # [u"ssl_ca_crt is present, so ssl_crt and ssl_key are required"],
        # u"_ssl_key-ssl_crt-unsafe":
        # [u"slave ssl_key and ssl_crt does not match"]
      },
      'warning-list': [
        u'apache-certificate is obsolete, please use master-key-upload-url',
        u'apache-key is obsolete, please use master-key-upload-url',
      ],
      'warning-slave-dict': {
        u'_custom_domain_ssl_crt_ssl_key': [
          u'ssl_key is obsolete, please use key-upload-url',
          u'ssl_crt is obsolete, please use key-upload-url'
        ],
        u'_custom_domain_ssl_crt_ssl_key_ssl_ca_crt': [
          u'ssl_key is obsolete, please use key-upload-url',
          u'ssl_crt is obsolete, please use key-upload-url',
          u'ssl_ca_crt is obsolete, please use key-upload-url'
        ],
        u'_ssl_ca_crt_does_not_match': [
          u'ssl_key is obsolete, please use key-upload-url',
          u'ssl_crt is obsolete, please use key-upload-url',
          u'ssl_ca_crt is obsolete, please use key-upload-url',
        ],
        u'_ssl_ca_crt_garbage': [
          u'ssl_key is obsolete, please use key-upload-url',
          u'ssl_crt is obsolete, please use key-upload-url',
          u'ssl_ca_crt is obsolete, please use key-upload-url',
        ],
        # u'_ssl_ca_crt_only': [
        #   u'ssl_ca_crt is obsolete, please use key-upload-url',
        # ],
        u'_ssl_from_slave': [
          u'ssl_key is obsolete, please use key-upload-url',
          u'ssl_crt is obsolete, please use key-upload-url',
        ],
        u'_ssl_from_slave_kedifa_overrides': [
          u'ssl_key is obsolete, please use key-upload-url',
          u'ssl_crt is obsolete, please use key-upload-url',
        ],
        # u'_ssl_key-ssl_crt-unsafe': [
        #   u'ssl_key is obsolete, please use key-upload-url',
        #   u'ssl_crt is obsolete, please use key-upload-url',
        # ],
        u'_type-notebook-ssl_from_slave': [
          u'ssl_key is obsolete, please use key-upload-url',
          u'ssl_crt is obsolete, please use key-upload-url',
        ],
        u'_type-notebook-ssl_from_slave_kedifa_overrides': [
          u'ssl_key is obsolete, please use key-upload-url',
          u'ssl_crt is obsolete, please use key-upload-url',
        ],
5323
      }
5324
    }
5325 5326 5327 5328 5329 5330

    self.assertEqual(
      expected_parameter_dict,
      parameter_dict
    )

5331 5332
  def test_ssl_from_master(self):
    parameter_dict = self.parseSlaveParameterDict('ssl_from_master')
5333
    self.assertLogAccessUrlWithPop(parameter_dict)
5334 5335
    self.assertKedifaKeysWithPop(parameter_dict, '')
    hostname = 'ssl_from_master'.translate(None, '_-')
5336 5337
    self.assertEqual(
      {
5338
        'domain': '%s.example.com' % (hostname,),
5339
        'replication_number': '1',
5340 5341 5342
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
5343
        'public-ipv4': self._ipv4_address,
5344
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5345 5346
      },
      parameter_dict
5347
    )
5348

5349 5350
    result = fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
5351

5352
    self.assertEqual(
5353 5354
      self.certificate_pem,
      der2pem(result.peercert))
5355

5356 5357 5358 5359 5360 5361 5362 5363
    self.assertEqualResultJson(result, 'Path', '/test-path')

  def test_ssl_from_master_kedifa_overrides(self):
    reference = 'ssl_from_master_kedifa_overrides'
    parameter_dict = self.parseSlaveParameterDict(reference)
    self.assertLogAccessUrlWithPop(parameter_dict)
    generate_auth, upload_url = self.assertKedifaKeysWithPop(parameter_dict)
    hostname = reference.translate(None, '_-')
5364 5365
    self.assertEqual(
      {
5366 5367 5368 5369 5370 5371 5372
        'domain': '%s.example.com' % (hostname,),
        'replication_number': '1',
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5373 5374
      },
      parameter_dict
5375
    )
5376

5377 5378
    result = fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
5379 5380 5381 5382 5383 5384 5385

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

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

5386 5387
    _, key_pem, _, certificate_pem = \
        createSelfSignedCertificate([parameter_dict['domain']])
5388

5389 5390 5391 5392 5393
    # 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)
5394

5395
    data = certificate_pem + key_pem
5396

5397 5398 5399 5400 5401 5402
    upload = requests.put(
      upload_url + auth.text,
      data=data,
      verify=self.ca_certificate_file)
    self.assertEqual(httplib.CREATED, upload.status_code)
    self.runKedifaUpdater()
5403

5404 5405
    result = fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
5406

5407 5408 5409
    self.assertEqual(
      certificate_pem,
      der2pem(result.peercert))
5410

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

5413 5414 5415
  def test_ssl_from_slave(self):
    reference = 'ssl_from_slave'
    parameter_dict = self.parseSlaveParameterDict(reference)
5416
    self.assertLogAccessUrlWithPop(parameter_dict)
5417
    self.assertKedifaKeysWithPop(parameter_dict)
5418 5419

    hostname = reference.translate(None, '_-')
5420 5421
    self.assertEqual(
      {
5422
        'domain': '%s.example.com' % (hostname,),
5423
        'replication_number': '1',
5424 5425 5426
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
5427
        'public-ipv4': self._ipv4_address,
5428
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5429 5430 5431 5432
        'warning-list': [
          'ssl_key is obsolete, please use key-upload-url',
          'ssl_crt is obsolete, please use key-upload-url',
         ]
5433 5434 5435 5436
      },
      parameter_dict
    )

5437 5438
    result = fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
5439

5440 5441 5442
    self.assertEqual(
      self.ssl_from_slave_certificate_pem,
      der2pem(result.peercert))
5443

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

5446 5447 5448
  def test_ssl_from_slave_kedifa_overrides(self):
    reference = 'ssl_from_slave_kedifa_overrides'
    parameter_dict = self.parseSlaveParameterDict(reference)
5449
    self.assertLogAccessUrlWithPop(parameter_dict)
5450 5451 5452
    generate_auth, upload_url = self.assertKedifaKeysWithPop(parameter_dict)

    hostname = reference.translate(None, '_-')
5453 5454
    self.assertEqual(
      {
5455
        'domain': '%s.example.com' % (hostname,),
5456
        'replication_number': '1',
5457 5458 5459
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
5460
        'public-ipv4': self._ipv4_address,
5461
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5462 5463 5464 5465
        'warning-list': [
          'ssl_key is obsolete, please use key-upload-url',
          'ssl_crt is obsolete, please use key-upload-url',
         ]
5466 5467 5468 5469
      },
      parameter_dict
    )

5470 5471
    result = fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
5472

5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509
    self.assertEqual(
      self.ssl_from_slave_kedifa_overrides_certificate_pem,
      der2pem(result.peercert))

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

    _, key_pem, _, certificate_pem = \
        createSelfSignedCertificate([parameter_dict['domain']])

    # 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 = certificate_pem + key_pem

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

    self.runKedifaUpdater()

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

    self.assertEqual(
      certificate_pem,
      der2pem(result.peercert))

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

  def test_type_notebook_ssl_from_master(self):
    reference = 'type-notebook-ssl_from_master'
    parameter_dict = self.parseSlaveParameterDict(reference)
5510
    self.assertLogAccessUrlWithPop(parameter_dict)
5511
    hostname = reference.translate(None, '_-')
5512
    self.assertKedifaKeysWithPop(parameter_dict)
5513 5514
    self.assertEqual(
      {
5515
        'domain': '%s.example.com' % (hostname,),
5516
        'replication_number': '1',
5517 5518 5519
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
5520
        'public-ipv4': self._ipv4_address,
5521
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5522 5523 5524 5525
      },
      parameter_dict
    )

5526 5527 5528
    result = fakeHTTPSResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path',
      HTTPS_PORT)
5529

5530 5531 5532
    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))
5533

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

5536 5537
  def test_type_notebook_ssl_from_master_kedifa_overrides(self):
    reference = 'type-notebook-ssl_from_master_kedifa_overrides'
5538 5539
    parameter_dict = self.parseSlaveParameterDict(reference)
    self.assertLogAccessUrlWithPop(parameter_dict)
5540
    generate_auth, upload_url = self.assertKedifaKeysWithPop(parameter_dict)
5541 5542 5543 5544 5545 5546 5547 5548
    hostname = reference.translate(None, '_-')
    self.assertEqual(
      {
        'domain': '%s.example.com' % (hostname,),
        'replication_number': '1',
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
5549 5550
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5551 5552 5553 5554
      },
      parameter_dict
    )

5555
    result = fakeHTTPSResult(
5556 5557
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path',
      HTTPS_PORT)
5558 5559 5560 5561 5562 5563 5564 5565 5566 5567

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

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

    _, key_pem, _, certificate_pem = \
        createSelfSignedCertificate([parameter_dict['domain']])

5568
    # as now the place to put the key is known put the key there
5569
    auth = requests.get(
5570
      generate_auth,
5571
      verify=self.ca_certificate_file)
5572 5573 5574 5575 5576 5577 5578
    self.assertEqual(httplib.CREATED, auth.status_code)

    data = certificate_pem + key_pem

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

5582
    self.runKedifaUpdater()
5583

5584
    result = fakeHTTPSResult(
5585 5586
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path',
      HTTPS_PORT)
5587 5588 5589 5590 5591 5592 5593

    self.assertEqual(
      certificate_pem,
      der2pem(result.peercert))

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

5594 5595 5596
  def test_type_notebook_ssl_from_slave(self):
    reference = 'type-notebook-ssl_from_slave'
    parameter_dict = self.parseSlaveParameterDict(reference)
5597
    self.assertLogAccessUrlWithPop(parameter_dict)
5598 5599
    hostname = reference.translate(None, '_-')
    self.assertKedifaKeysWithPop(parameter_dict)
5600 5601 5602 5603 5604 5605 5606
    self.assertEqual(
      {
        'domain': '%s.example.com' % (hostname,),
        'replication_number': '1',
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
5607 5608
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5609 5610 5611 5612
        'warning-list': [
          'ssl_key is obsolete, please use key-upload-url',
          'ssl_crt is obsolete, please use key-upload-url',
         ]
5613 5614 5615 5616
      },
      parameter_dict
    )

5617
    result = fakeHTTPSResult(
5618 5619
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path',
      HTTPS_PORT)
5620 5621

    self.assertEqual(
5622
      self.type_notebook_ssl_from_slave_certificate_pem,
5623 5624 5625 5626
      der2pem(result.peercert))

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

5627 5628
  def test_type_notebook_ssl_from_slave_kedifa_overrides(self):
    reference = 'type-notebook-ssl_from_slave_kedifa_overrides'
5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639
    parameter_dict = self.parseSlaveParameterDict(reference)
    self.assertLogAccessUrlWithPop(parameter_dict)
    generate_auth, upload_url = self.assertKedifaKeysWithPop(parameter_dict)
    hostname = reference.translate(None, '_-')
    self.assertEqual(
      {
        'domain': '%s.example.com' % (hostname,),
        'replication_number': '1',
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
5640 5641
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5642 5643 5644 5645
        'warning-list': [
          'ssl_key is obsolete, please use key-upload-url',
          'ssl_crt is obsolete, please use key-upload-url',
         ]
5646 5647 5648 5649
      },
      parameter_dict
    )

5650
    result = fakeHTTPSResult(
5651 5652
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path',
      HTTPS_PORT)
5653 5654

    self.assertEqual(
5655
      self.type_notebook_ssl_from_slave_kedifa_overrides_certificate_pem,
5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675
      der2pem(result.peercert))

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

    _, key_pem, _, certificate_pem = \
        createSelfSignedCertificate([parameter_dict['domain']])

    # 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 = certificate_pem + key_pem

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

5677
    self.runKedifaUpdater()
5678

5679
    result = fakeHTTPSResult(
5680 5681
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path',
      HTTPS_PORT)
5682 5683 5684 5685 5686 5687 5688

    self.assertEqual(
      certificate_pem,
      der2pem(result.peercert))

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

5689 5690 5691
  @skip('Not implemented in new test system')
  def test_custom_domain_ssl_crt_ssl_key(self):
    reference = 'custom_domain_ssl_crt_ssl_key'
5692 5693
    parameter_dict = self.parseSlaveParameterDict(reference)
    self.assertLogAccessUrlWithPop(parameter_dict)
5694
    generate_auth, upload_url = self.assertKedifaKeysWithPop(parameter_dict)
5695 5696 5697 5698 5699 5700 5701 5702 5703

    hostname = reference.translate(None, '_-')
    self.assertEqual(
      {
        'domain': '%s.example.com' % (hostname,),
        'replication_number': '1',
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
5704
        'public-ipv4': self._ipv4_address,
5705
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5706 5707
        'warning-list': ['ssl_key is obsolete, please use key-upload-url',
                         'ssl_crt is obsolete, please use key-upload-url']
5708 5709 5710 5711
      },
      parameter_dict
    )

5712
    result = fakeHTTPSResult(
5713 5714 5715
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
5716
      self.customdomain_certificate_pem,
5717 5718 5719 5720
      der2pem(result.peercert))

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

5721 5722 5723
  def test_ssl_ca_crt(self):
    parameter_dict = self.parseSlaveParameterDict(
      'custom_domain_ssl_crt_ssl_key_ssl_ca_crt')
5724 5725 5726 5727
    self.assertLogAccessUrlWithPop(parameter_dict)
    generate_auth, upload_url = self.assertKedifaKeysWithPop(parameter_dict)
    self.assertEqual(
      {
5728
        'domain': 'customdomainsslcrtsslkeysslcacrt.example.com',
5729
        'replication_number': '1',
5730 5731 5732 5733
        'url': 'http://customdomainsslcrtsslkeysslcacrt.example.com',
        'site_url': 'http://customdomainsslcrtsslkeysslcacrt.example.com',
        'secure_access':
        'https://customdomainsslcrtsslkeysslcacrt.example.com',
5734
        'public-ipv4': self._ipv4_address,
5735
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5736 5737 5738
        'warning-list': [
          'ssl_key is obsolete, please use key-upload-url',
          'ssl_crt is obsolete, please use key-upload-url',
5739 5740
          'ssl_ca_crt is obsolete, please use key-upload-url'
        ]
5741 5742 5743 5744
      },
      parameter_dict
    )

5745
    result = fakeHTTPSResult(
5746 5747 5748
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
5749
      self.customdomain_ca_certificate_pem,
5750 5751 5752 5753
      der2pem(result.peercert))

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

5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765
    certificate_file_list = glob.glob(os.path.join(
      self.instance_path, '*', 'srv', 'bbb-ssl',
      '_custom_domain_ssl_crt_ssl_key_ssl_ca_crt.crt'))
    self.assertEqual(1, len(certificate_file_list))
    certificate_file = certificate_file_list[0]
    with open(certificate_file) as out:
      expected = self.customdomain_ca_certificate_pem + '\n' + \
        self.ca.certificate_pem + '\n' + self.customdomain_ca_key_pem
      self.assertEqual(
        expected,
        out.read()
      )
5766

5767 5768
    ca = CertificateAuthority(
      'TestSlaveSlapOSMasterCertificateCompatibility')
5769

5770 5771 5772
    _, customdomain_ca_key_pem, csr, _ = createCSR(
      'customdomainsslcrtsslkeysslcacrt.example.com')
    _, customdomain_ca_certificate_pem = ca.signCSR(csr)
5773

5774 5775 5776 5777 5778 5779 5780
    slave_parameter_dict = self.getSlaveParameterDictDict()[
      'custom_domain_ssl_crt_ssl_key_ssl_ca_crt'].copy()
    slave_parameter_dict.update(
      ssl_crt=customdomain_ca_certificate_pem,
      ssl_key=customdomain_ca_key_pem,
      ssl_ca_crt=ca.certificate_pem,
    )
5781

5782 5783 5784 5785 5786 5787
    self.slap.request(
        software_release=self.getSoftwareURL(),
        partition_reference='custom_domain_ssl_crt_ssl_key_ssl_ca_crt',
        partition_parameter_kw=slave_parameter_dict,
        shared=True
    )
5788

5789 5790
    self.slap.waitForInstance()
    self.runKedifaUpdater()
5791
    result = fakeHTTPSResult(
5792 5793 5794
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
5795
      customdomain_ca_certificate_pem,
5796 5797 5798 5799
      der2pem(result.peercert))

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

5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814
    certificate_file_list = glob.glob(os.path.join(
      self.instance_path, '*', 'srv', 'bbb-ssl',
      '_custom_domain_ssl_crt_ssl_key_ssl_ca_crt.crt'))
    self.assertEqual(1, len(certificate_file_list))
    certificate_file = certificate_file_list[0]
    with open(certificate_file) as out:
      expected = customdomain_ca_certificate_pem + '\n' + ca.certificate_pem \
        + '\n' + customdomain_ca_key_pem
      self.assertEqual(
        expected,
        out.read()
      )

  def test_ssl_ca_crt_garbage(self):
    parameter_dict = self.parseSlaveParameterDict('ssl_ca_crt_garbage')
5815 5816 5817 5818
    self.assertLogAccessUrlWithPop(parameter_dict)
    self.assertKedifaKeysWithPop(parameter_dict)
    self.assertEqual(
      {
5819
        'domain': 'sslcacrtgarbage.example.com',
5820
        'replication_number': '1',
5821 5822 5823 5824
        'url': 'http://sslcacrtgarbage.example.com',
        'site_url': 'http://sslcacrtgarbage.example.com',
        'secure_access':
        'https://sslcacrtgarbage.example.com',
5825 5826
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5827 5828 5829 5830
        'warning-list': [
          'ssl_key is obsolete, please use key-upload-url',
          'ssl_crt is obsolete, please use key-upload-url',
          'ssl_ca_crt is obsolete, please use key-upload-url']
5831 5832 5833 5834
      },
      parameter_dict
    )

5835
    result = fakeHTTPSResult(
5836
        parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
5837 5838

    self.assertEqual(
5839 5840 5841
      self.sslcacrtgarbage_ca_certificate_pem,
      der2pem(result.peercert)
    )
5842 5843 5844

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

5845 5846
  def test_ssl_ca_crt_does_not_match(self):
    parameter_dict = self.parseSlaveParameterDict('ssl_ca_crt_does_not_match')
5847
    self.assertLogAccessUrlWithPop(parameter_dict)
5848
    self.assertKedifaKeysWithPop(parameter_dict)
5849 5850
    self.assertEqual(
      {
5851
        'domain': 'sslcacrtdoesnotmatch.example.com',
5852
        'replication_number': '1',
5853 5854 5855 5856
        'url': 'http://sslcacrtdoesnotmatch.example.com',
        'site_url': 'http://sslcacrtdoesnotmatch.example.com',
        'secure_access':
        'https://sslcacrtdoesnotmatch.example.com',
5857 5858
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5859 5860 5861 5862 5863
        'warning-list': [
          'ssl_key is obsolete, please use key-upload-url',
          'ssl_crt is obsolete, please use key-upload-url',
          'ssl_ca_crt is obsolete, please use key-upload-url'
        ]
5864 5865 5866 5867
      },
      parameter_dict
    )

5868
    result = fakeHTTPSResult(
5869
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
5870 5871 5872 5873 5874

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886
    certificate_file_list = glob.glob(os.path.join(
      self.instance_path, '*', 'srv', 'bbb-ssl',
      '_ssl_ca_crt_does_not_match.crt'))
    self.assertEqual(1, len(certificate_file_list))
    certificate_file = certificate_file_list[0]
    with open(certificate_file) as out:
      expected = self.certificate_pem + '\n' + self.ca.certificate_pem + \
        '\n' + self.key_pem
      self.assertEqual(
        expected,
        out.read()
      )
5887 5888


5889 5890 5891 5892 5893 5894 5895
class TestSlaveSlapOSMasterCertificateCompatibilityUpdate(
  SlaveHttpFrontendTestCase, TestDataMixin):
  @classmethod
  def setUpMaster(cls):
    # run partition until AIKC finishes
    cls.runComputerPartitionUntil(
      cls.untilNotReadyYetNotInMasterKeyGenerateAuthUrl)
5896

5897 5898 5899 5900 5901 5902 5903
    parameter_dict = cls.requestDefaultInstance().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)
    # Do not upload certificates for the master partition
5904

5905 5906 5907 5908 5909 5910 5911 5912
  instance_parameter_dict = {
    'domain': 'example.com',
    'port': HTTPS_PORT,
    'plain_http_port': HTTP_PORT,
    'kedifa_port': KEDIFA_PORT,
    'caucase_port': CAUCASE_PORT,
    'mpm-graceful-shutdown-timeout': 2,
  }
5913

5914 5915 5916 5917 5918 5919 5920 5921 5922
  @classmethod
  def getInstanceParameterDict(cls):
    if 'apache-certificate' not in cls.instance_parameter_dict:
      cls.instance_parameter_dict.update(**{
        'apache-certificate': cls.certificate_pem,
        'apache-key': cls.key_pem,
      })
    cls.instance_parameter_dict['public-ipv4'] = cls._ipv4_address
    return cls.instance_parameter_dict
5923

5924 5925 5926 5927 5928 5929 5930 5931
  @classmethod
  def getSlaveParameterDictDict(cls):
    return {
      'ssl_from_master': {
        'url': cls.backend_url,
        'enable_cache': True,
      },
    }
5932

5933 5934 5935
  def test_master_partition_state(self):
    parameter_dict = self.parseConnectionParameterDict()
    self.assertKeyWithPop('monitor-setup-url', parameter_dict)
5936
    self.assertBackendHaproxyStatisticUrl(parameter_dict)
5937 5938
    self.assertKedifaKeysWithPop(parameter_dict, 'master-')
    self.assertRejectedSlavePromiseWithPop(parameter_dict)
5939

5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952
    expected_parameter_dict = {
      'monitor-base-url': 'https://[%s]:8401' % self._ipv6_address,
      'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
      'domain': 'example.com',
      'accepted-slave-amount': '1',
      'rejected-slave-amount': '0',
      'rejected-slave-dict': {},
      'slave-amount': '1',
      'warning-list': [
        u'apache-certificate is obsolete, please use master-key-upload-url',
        u'apache-key is obsolete, please use master-key-upload-url',
      ],
    }
5953 5954

    self.assertEqual(
5955
      expected_parameter_dict,
5956 5957 5958
      parameter_dict
    )

5959 5960
  def test_apache_key_apache_certificate_update(self):
    parameter_dict = self.parseSlaveParameterDict('ssl_from_master')
5961
    self.assertLogAccessUrlWithPop(parameter_dict)
5962 5963
    self.assertKedifaKeysWithPop(parameter_dict, '')
    hostname = 'ssl_from_master'.translate(None, '_-')
5964 5965
    self.assertEqual(
      {
5966
        'domain': '%s.example.com' % (hostname,),
5967
        'replication_number': '1',
5968 5969 5970
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
5971
        'public-ipv4': self._ipv4_address,
5972
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
5973 5974 5975 5976
      },
      parameter_dict
    )

5977
    result = fakeHTTPSResult(
5978
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
5979 5980

    self.assertEqual(
5981
      self.certificate_pem,
5982 5983 5984 5985
      der2pem(result.peercert))

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

5986 5987 5988 5989 5990 5991
    _, key_pem, _, certificate_pem = createSelfSignedCertificate(
      [
        '*.customdomain.example.com',
        '*.example.com',
        '*.alias1.example.com',
      ])
5992

5993 5994 5995
    self.instance_parameter_dict.update(**{
      'apache-certificate': certificate_pem,
      'apache-key': key_pem,
5996

5997 5998 5999
    })
    self.requestDefaultInstance()
    self.slap.waitForInstance()
6000
    self.runKedifaUpdater()
6001

6002
    result = fakeHTTPSResult(
6003
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
6004 6005 6006 6007 6008 6009 6010 6011

    self.assertEqual(
      certificate_pem,
      der2pem(result.peercert))

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


6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024
class TestSlaveCiphers(SlaveHttpFrontendTestCase, TestDataMixin):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
      'public-ipv4': cls._ipv4_address,
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
      'mpm-graceful-shutdown-timeout': 2,
      'ciphers': 'ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-RSA-AES256-GCM-SHA384'
    }
6025

6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042
  @classmethod
  def getSlaveParameterDictDict(cls):
    return {
      'default_ciphers': {
        'url': cls.backend_url,
        'enable_cache': True,
      },
      'own_ciphers': {
        'ciphers': 'ECDHE-ECDSA-AES128-GCM-SHA256 ECDHE-RSA-AES128-GCM-SHA256',
        'url': cls.backend_url,
        'enable_cache': True,
      },
    }

  def test_master_partition_state(self):
    parameter_dict = self.parseConnectionParameterDict()
    self.assertKeyWithPop('monitor-setup-url', parameter_dict)
6043
    self.assertBackendHaproxyStatisticUrl(parameter_dict)
6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055
    self.assertKedifaKeysWithPop(parameter_dict, 'master-')
    self.assertRejectedSlavePromiseWithPop(parameter_dict)

    expected_parameter_dict = {
      'monitor-base-url': 'https://[%s]:8401' % self._ipv6_address,
      'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
      'domain': 'example.com',
      'accepted-slave-amount': '2',
      'rejected-slave-amount': '0',
      'slave-amount': '2',
      'rejected-slave-dict': {}
    }
6056 6057

    self.assertEqual(
6058
      expected_parameter_dict,
6059 6060 6061
      parameter_dict
    )

6062 6063 6064
  def test_default_ciphers(self):
    parameter_dict = self.assertSlaveBase('default_ciphers')

6065
    result = fakeHTTPSResult(
6066 6067 6068
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
6069
      self.certificate_pem,
6070 6071
      der2pem(result.peercert))

6072
    self.assertEqual(httplib.OK, result.status_code)
6073

6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085
    result_http = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
    self.assertEqual(httplib.FOUND, result_http.status_code)

    configuration_file = glob.glob(
      os.path.join(
        self.instance_path, '*', 'etc', 'caddy-slave-conf.d',
        '_default_ciphers.conf'
      ))[0]
    self.assertTrue(
      'ciphers ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-RSA-AES256-GCM-SHA384'
      in open(configuration_file).read()
6086 6087
    )

6088 6089 6090
  def test_own_ciphers(self):
    parameter_dict = self.assertSlaveBase('own_ciphers')

6091
    result = fakeHTTPSResult(
6092 6093 6094
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
6095
      self.certificate_pem,
6096 6097
      der2pem(result.peercert))

6098
    self.assertEqual(httplib.OK, result.status_code)
6099

6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139
    result_http = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
    self.assertEqual(httplib.FOUND, result_http.status_code)

    configuration_file = glob.glob(
      os.path.join(
        self.instance_path, '*', 'etc', 'caddy-slave-conf.d',
        '_own_ciphers.conf'
      ))[0]
    self.assertTrue(
      'ciphers ECDHE-ECDSA-AES128-GCM-SHA256 ECDHE-RSA-AES128-GCM-SHA256'
      in open(configuration_file).read()
    )


class TestSlaveRejectReportUnsafeDamaged(SlaveHttpFrontendTestCase):
  @classmethod
  def prepareCertificate(cls):
    cls.ca = CertificateAuthority('TestSlaveRejectReportUnsafeDamaged')
    super(TestSlaveRejectReportUnsafeDamaged, cls).prepareCertificate()

  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
      'public-ipv4': cls._ipv4_address,
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
    }

  @classmethod
  def setUpClass(cls):
    super(TestSlaveRejectReportUnsafeDamaged, cls).setUpClass()
    cls.fillSlaveParameterDictDict()
    cls.requestSlaves()
    try:
      cls.slap.waitForInstance(
        max_retry=2  # two runs shall be enough
6140
      )
6141 6142 6143 6144
    except Exception:
      # ignores exceptions, as problems are tested
      pass
    cls.updateSlaveConnectionParameterDictDict()
6145

6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165
  slave_parameter_dict_dict = {}

  @classmethod
  def getSlaveParameterDictDict(cls):
    return cls.slave_parameter_dict_dict

  @classmethod
  def fillSlaveParameterDictDict(cls):
    cls.slave_parameter_dict_dict = {
      'url': {
        'url': "https://[fd46::c2ae]:!py!u'123123'",
      },
      'https-url': {
        'https-url': "https://[fd46::c2ae]:!py!u'123123'",
      },
      'ssl-proxy-verify_ssl_proxy_ca_crt_damaged': {
        'url': cls.backend_https_url,
        'ssl-proxy-verify': True,
        'ssl_proxy_ca_crt': 'damaged',
      },
6166 6167 6168 6169 6170
      'ssl-proxy-verify_ssl_proxy_ca_crt_empty': {
        'url': cls.backend_https_url,
        'ssl-proxy-verify': True,
        'ssl_proxy_ca_crt': '',
      },
6171 6172 6173 6174
      'bad-backend': {
        'url': 'http://1:2:3:4',
        'https-url': 'http://host.domain:badport',
      },
6175 6176 6177 6178
      'empty-backend': {
        'url': '',
        'https-url': '',
      },
6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234
      'custom_domain-unsafe': {
        'custom_domain': '${section:option} afterspace\nafternewline',
      },
      'server-alias-unsafe': {
        'server-alias': '${section:option} afterspace',
      },
      'server-alias-same': {
        'url': cls.backend_url,
        'server-alias': 'serveraliassame.example.com',
      },
      'virtualhostroot-http-port-unsafe': {
        'type': 'zope',
        'url': cls.backend_url,
        'virtualhostroot-http-port': '${section:option}',
      },
      'virtualhostroot-https-port-unsafe': {
        'type': 'zope',
        'url': cls.backend_url,
        'virtualhostroot-https-port': '${section:option}',
      },
      'default-path-unsafe': {
        'type': 'zope',
        'url': cls.backend_url,
        'default-path': '${section:option}\nn"\newline\n}\n}proxy\n/slashed',
      },
      'monitor-ipv4-test-unsafe': {
        'monitor-ipv4-test': '${section:option}\nafternewline ipv4',
      },
      'monitor-ipv6-test-unsafe': {
        'monitor-ipv6-test': '${section:option}\nafternewline ipv6',
      },
      'bad-ciphers': {
        'ciphers': 'bad ECDHE-ECDSA-AES256-GCM-SHA384 again',
      },
      'site_1': {
        'custom_domain': 'duplicate.example.com',
      },
      'site_2': {
        'custom_domain': 'duplicate.example.com',
      },
      'site_3': {
        'server-alias': 'duplicate.example.com',
      },
      'site_4': {
        'custom_domain': 'duplicate.example.com',
        'server-alias': 'duplicate.example.com',
      },
      'ssl_ca_crt_only': {
        'url': cls.backend_url,
        'ssl_ca_crt': cls.ca.certificate_pem,
      },
      'ssl_key-ssl_crt-unsafe': {
        'ssl_key': '${section:option}ssl_keyunsafe\nunsafe',
        'ssl_crt': '${section:option}ssl_crtunsafe\nunsafe',
      },
    }
6235

6236 6237 6238
  def test_master_partition_state(self):
    parameter_dict = self.parseConnectionParameterDict()
    self.assertKeyWithPop('monitor-setup-url', parameter_dict)
6239
    self.assertBackendHaproxyStatisticUrl(parameter_dict)
6240 6241
    self.assertKedifaKeysWithPop(parameter_dict, 'master-')
    self.assertRejectedSlavePromiseWithPop(parameter_dict)
6242

6243 6244 6245 6246 6247
    expected_parameter_dict = {
      'monitor-base-url': 'https://[%s]:8401' % self._ipv6_address,
      'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
      'domain': 'example.com',
      'accepted-slave-amount': '7',
6248 6249
      'rejected-slave-amount': '14',
      'slave-amount': '21',
6250 6251 6252 6253 6254 6255 6256
      'rejected-slave-dict': {
        '_https-url': ['slave https-url "https://[fd46::c2ae]:!py!u\'123123\'"'
                       ' invalid'],
        '_url': [u'slave url "https://[fd46::c2ae]:!py!u\'123123\'" invalid'],
        '_ssl-proxy-verify_ssl_proxy_ca_crt_damaged': [
          'ssl_proxy_ca_crt is invalid'
        ],
6257 6258 6259
        '_ssl-proxy-verify_ssl_proxy_ca_crt_empty': [
          'ssl_proxy_ca_crt is invalid'
        ],
6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277
        '_bad-ciphers': [
          "Cipher 'bad' is not supported.",
          "Cipher 'again' is not supported."
        ],
        '_custom_domain-unsafe': [
          "custom_domain '${section:option} afterspace\\nafternewline' invalid"
        ],
        '_server-alias-unsafe': [
          "server-alias '${section:option}' not valid",
          "server-alias 'afterspace' not valid"
        ],
        '_site_2': ["custom_domain 'duplicate.example.com' clashes"],
        '_site_3': ["server-alias 'duplicate.example.com' clashes"],
        '_site_4': ["custom_domain 'duplicate.example.com' clashes"],
        '_ssl_ca_crt_only': [
          "ssl_ca_crt is present, so ssl_crt and ssl_key are required"],
        '_ssl_key-ssl_crt-unsafe': [
          "slave ssl_key and ssl_crt does not match"],
6278 6279 6280
        '_bad-backend': [
          "slave url 'http://1:2:3:4' invalid",
          "slave https-url 'http://host.domain:badport' invalid"],
6281 6282 6283
        '_empty-backend': [
          "slave url '' invalid",
          "slave https-url '' invalid"],
6284 6285 6286 6287 6288 6289 6290 6291
      },
      'warning-slave-dict': {
        '_ssl_ca_crt_only': [
          'ssl_ca_crt is obsolete, please use key-upload-url'],
        '_ssl_key-ssl_crt-unsafe': [
          'ssl_key is obsolete, please use key-upload-url',
          'ssl_crt is obsolete, please use key-upload-url']}
    }
6292

6293 6294 6295
    self.assertEqual(
      expected_parameter_dict,
      parameter_dict
6296 6297
    )

6298 6299
  def test_url(self):
    parameter_dict = self.parseSlaveParameterDict('url')
6300
    self.assertEqual(
6301 6302 6303 6304 6305 6306
      {
        'request-error-list': [
          "slave url \"https://[fd46::c2ae]:!py!u'123123'\" invalid"]
      },
      parameter_dict
    )
6307

6308 6309
  def test_https_url(self):
    parameter_dict = self.parseSlaveParameterDict('https-url')
6310 6311
    self.assertEqual(
      {
6312 6313
        'request-error-list': [
          "slave https-url \"https://[fd46::c2ae]:!py!u'123123'\" invalid"]
6314 6315 6316 6317
      },
      parameter_dict
    )

6318 6319 6320
  def test_ssl_proxy_verify_ssl_proxy_ca_crt_damaged(self):
    parameter_dict = self.parseSlaveParameterDict(
      'ssl-proxy-verify_ssl_proxy_ca_crt_damaged')
6321
    self.assertEqual(
6322 6323
      {'request-error-list': ["ssl_proxy_ca_crt is invalid"]},
      parameter_dict
6324 6325
    )

6326 6327 6328 6329 6330 6331 6332 6333
  def test_ssl_proxy_verify_ssl_proxy_ca_crt_empty(self):
    parameter_dict = self.parseSlaveParameterDict(
      'ssl-proxy-verify_ssl_proxy_ca_crt_empty')
    self.assertEqual(
      {'request-error-list': ["ssl_proxy_ca_crt is invalid"]},
      parameter_dict
    )

6334 6335
  def test_server_alias_same(self):
    parameter_dict = self.parseSlaveParameterDict('server-alias-same')
6336 6337 6338 6339
    self.assertLogAccessUrlWithPop(parameter_dict)
    self.assertKedifaKeysWithPop(parameter_dict)
    self.assertEqual(
      {
6340
        'domain': 'serveraliassame.example.com',
6341
        'replication_number': '1',
6342 6343 6344
        'url': 'http://serveraliassame.example.com',
        'site_url': 'http://serveraliassame.example.com',
        'secure_access': 'https://serveraliassame.example.com',
6345
        'public-ipv4': self._ipv4_address,
6346
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
6347 6348 6349 6350
      },
      parameter_dict
    )

6351
    result = fakeHTTPSResult(
6352 6353 6354 6355 6356 6357
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

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

6360 6361
  def test_custom_domain_unsafe(self):
    parameter_dict = self.parseSlaveParameterDict('custom_domain-unsafe')
6362 6363
    self.assertEqual(
      {
6364 6365 6366
        'request-error-list': [
          "custom_domain '${section:option} afterspace\\nafternewline' invalid"
        ]
6367 6368 6369 6370
      },
      parameter_dict
    )

6371 6372 6373 6374 6375 6376 6377
  def test_server_alias_unsafe(self):
    parameter_dict = self.parseSlaveParameterDict('server-alias-unsafe')
    self.assertEqual(
      {
        'request-error-list': [
          "server-alias '${section:option}' not valid", "server-alias "
          "'afterspace' not valid"]
6378
      },
6379 6380
      parameter_dict
    )
6381

6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392
  def test_bad_ciphers(self):
    parameter_dict = self.parseSlaveParameterDict('bad-ciphers')
    self.assertEqual(
      {
        'request-error-list': [
          "Cipher 'bad' is not supported.",
          "Cipher 'again' is not supported."
        ]
      },
      parameter_dict
    )
6393

6394 6395 6396 6397 6398
  def test_virtualhostroot_http_port_unsafe(self):
    parameter_dict = self.parseSlaveParameterDict(
      'virtualhostroot-http-port-unsafe')
    self.assertLogAccessUrlWithPop(parameter_dict)
    self.assertKedifaKeysWithPop(parameter_dict)
6399
    self.assertEqual(
6400 6401 6402 6403 6404 6405 6406 6407 6408 6409
      {
        'domain': 'virtualhostroothttpportunsafe.example.com',
        'replication_number': '1',
        'url': 'http://virtualhostroothttpportunsafe.example.com',
        'site_url': 'http://virtualhostroothttpportunsafe.example.com',
        'secure_access':
        'https://virtualhostroothttpportunsafe.example.com',
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
      },
6410 6411 6412
      parameter_dict
    )

6413 6414 6415 6416 6417 6418 6419 6420
    result = fakeHTTPResult(
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(httplib.FOUND, result.status_code)

  def test_virtualhostroot_https_port_unsafe(self):
    parameter_dict = self.parseSlaveParameterDict(
      'virtualhostroot-https-port-unsafe')
6421
    self.assertLogAccessUrlWithPop(parameter_dict)
6422
    self.assertKedifaKeysWithPop(parameter_dict)
6423 6424
    self.assertEqual(
      {
6425
        'domain': 'virtualhostroothttpsportunsafe.example.com',
6426
        'replication_number': '1',
6427 6428 6429 6430
        'url': 'http://virtualhostroothttpsportunsafe.example.com',
        'site_url': 'http://virtualhostroothttpsportunsafe.example.com',
        'secure_access':
        'https://virtualhostroothttpsportunsafe.example.com',
6431 6432
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
6433 6434 6435 6436
      },
      parameter_dict
    )

6437
    result = fakeHTTPSResult(
6438 6439 6440 6441 6442 6443
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

6444 6445 6446 6447 6448 6449
    self.assertEqualResultJson(
      result,
      'Path',
      '/VirtualHostBase/https//virtualhostroothttpsportunsafe'
      '.example.com:0//VirtualHostRoot/test-path'
    )
6450

6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466
  def default_path_unsafe(self):
    parameter_dict = self.parseSlaveParameterDict('default-path-unsafe')
    self.assertLogAccessUrlWithPop(parameter_dict)
    self.assertKedifaKeysWithPop(parameter_dict, 'master-')
    self.assertEqual(
      {
        'domain': 'defaultpathunsafe.example.com',
        'replication_number': '1',
        'url': 'http://defaultpathunsafe.example.com',
        'site_url': 'http://defaultpathunsafe.example.com',
        'secure_access': 'https://defaultpathunsafe.example.com',
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
      },
      parameter_dict
    )
6467

6468
    result = fakeHTTPSResult(
6469
      parameter_dict['domain'], parameter_dict['public-ipv4'], '')
6470 6471

    self.assertEqual(
6472
      self.certificate_pem,
6473 6474
      der2pem(result.peercert))

6475 6476 6477 6478
    self.assertEqual(
      httplib.MOVED_PERMANENTLY,
      result.status_code
    )
6479

6480 6481 6482 6483 6484
    self.assertEqual(
      'https://defaultpathunsafe.example.com:%s/%%24%%7Bsection%%3Aoption%%7D'
      '%%0An%%22%%0Aewline%%0A%%7D%%0A%%7Dproxy%%0A/slashed' % (HTTPS_PORT,),
      result.headers['Location']
    )
6485

6486 6487 6488 6489
  def test_monitor_ipv4_test_unsafe(self):
    parameter_dict = self.parseSlaveParameterDict('monitor-ipv4-test-unsafe')
    self.assertLogAccessUrlWithPop(parameter_dict)
    self.assertKedifaKeysWithPop(parameter_dict)
6490
    self.assertEqual(
6491 6492 6493 6494 6495 6496 6497 6498 6499
      {
        'domain': 'monitoripv4testunsafe.example.com',
        'replication_number': '1',
        'url': 'http://monitoripv4testunsafe.example.com',
        'site_url': 'http://monitoripv4testunsafe.example.com',
        'secure_access': 'https://monitoripv4testunsafe.example.com',
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
      },
6500 6501 6502
      parameter_dict
    )

6503
    result = fakeHTTPSResult(
6504 6505 6506 6507 6508 6509
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

6510
    self.assertEqual(httplib.SERVICE_UNAVAILABLE, result.status_code)
6511

6512
    result_http = fakeHTTPResult(
6513
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
6514
    self.assertEqual(httplib.FOUND, result_http.status_code)
6515

6516
    monitor_file = glob.glob(
6517
      os.path.join(
6518 6519 6520 6521 6522
        self.instance_path, '*', 'etc', 'plugin',
        'check-_monitor-ipv4-test-unsafe-ipv4-packet-list-test.py'))[0]
    # get promise module and check that parameters are ok

    self.assertEqual(
6523
      getPromisePluginParameterDict(monitor_file),
6524 6525 6526 6527 6528
      {
        'frequency': '720',
        'ipv4': 'true',
        'address': '${section:option}\nafternewline ipv4',
      }
6529 6530
    )

6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546
  def test_monitor_ipv6_test_unsafe(self):
    parameter_dict = self.parseSlaveParameterDict('monitor-ipv6-test-unsafe')
    self.assertLogAccessUrlWithPop(parameter_dict)
    self.assertKedifaKeysWithPop(parameter_dict)
    self.assertEqual(
      {
        'domain': 'monitoripv6testunsafe.example.com',
        'replication_number': '1',
        'url': 'http://monitoripv6testunsafe.example.com',
        'site_url': 'http://monitoripv6testunsafe.example.com',
        'secure_access': 'https://monitoripv6testunsafe.example.com',
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
      },
      parameter_dict
    )
6547

6548
    result = fakeHTTPSResult(
6549 6550 6551 6552 6553 6554
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')

    self.assertEqual(
      self.certificate_pem,
      der2pem(result.peercert))

6555
    self.assertEqual(httplib.SERVICE_UNAVAILABLE, result.status_code)
6556

6557
    result_http = fakeHTTPResult(
6558
      parameter_dict['domain'], parameter_dict['public-ipv4'], 'test-path')
6559
    self.assertEqual(httplib.FOUND, result_http.status_code)
6560

6561
    monitor_file = glob.glob(
6562
      os.path.join(
6563 6564 6565 6566
        self.instance_path, '*', 'etc', 'plugin',
        'check-_monitor-ipv6-test-unsafe-ipv6-packet-list-test.py'))[0]
    # get promise module and check that parameters are ok
    self.assertEqual(
6567
      getPromisePluginParameterDict(monitor_file),
6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641
      {
        'frequency': '720',
        'address': '${section:option}\nafternewline ipv6'
      }
    )

  def test_site_1(self):
    parameter_dict = self.parseSlaveParameterDict('site_1')
    self.assertLogAccessUrlWithPop(parameter_dict)
    self.assertKedifaKeysWithPop(parameter_dict)
    self.assertEqual(
      {
        'domain': 'duplicate.example.com',
        'replication_number': '1',
        'url': 'http://duplicate.example.com',
        'site_url': 'http://duplicate.example.com',
        'secure_access': 'https://duplicate.example.com',
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
      },
      parameter_dict
    )

  def test_site_2(self):
    parameter_dict = self.parseSlaveParameterDict('site_2')
    self.assertEqual(
      {
        'request-error-list': ["custom_domain 'duplicate.example.com' clashes"]
      },
      parameter_dict
    )

  def test_site_3(self):
    parameter_dict = self.parseSlaveParameterDict('site_3')
    self.assertEqual(
      {
        'request-error-list': ["server-alias 'duplicate.example.com' clashes"]
      },
      parameter_dict,
    )

  def test_site_4(self):
    parameter_dict = self.parseSlaveParameterDict('site_4')
    self.assertEqual(
      {
        'request-error-list': ["custom_domain 'duplicate.example.com' clashes"]
      },
      parameter_dict
    )

  def test_ssl_ca_crt_only(self):
    parameter_dict = self.parseSlaveParameterDict('ssl_ca_crt_only')

    self.assertEqual(
      parameter_dict,
      {
        'request-error-list': [
          "ssl_ca_crt is present, so ssl_crt and ssl_key are required"],
        'warning-list': [
          'ssl_ca_crt is obsolete, please use key-upload-url',
        ],
      }
    )

  def test_ssl_key_ssl_crt_unsafe(self):
    parameter_dict = self.parseSlaveParameterDict('ssl_key-ssl_crt-unsafe')
    self.assertEqual(
      {
        'request-error-list': ["slave ssl_key and ssl_crt does not match"],
        'warning-list': [
          'ssl_key is obsolete, please use key-upload-url',
          'ssl_crt is obsolete, please use key-upload-url']
      },
      parameter_dict
6642
    )
6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653

  def test_bad_backend(self):
    parameter_dict = self.parseSlaveParameterDict('bad-backend')
    self.assertEqual(
      {
        'request-error-list': [
          "slave url 'http://1:2:3:4' invalid",
          "slave https-url 'http://host.domain:badport' invalid"],
      },
      parameter_dict
    )
6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664

  def test_empty_backend(self):
    parameter_dict = self.parseSlaveParameterDict('empty-backend')
    self.assertEqual(
      {
        'request-error-list': [
          "slave url '' invalid",
          "slave https-url '' invalid"],
      },
      parameter_dict
    )
6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753


class TestSlaveHostHaproxyClash(SlaveHttpFrontendTestCase, TestDataMixin):
  @classmethod
  def getInstanceParameterDict(cls):
    return {
      'domain': 'example.com',
      'public-ipv4': cls._ipv4_address,
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
      'mpm-graceful-shutdown-timeout': 2,
      'request-timeout': '12',
    }

  @classmethod
  def getSlaveParameterDictDict(cls):
    # Note: The slaves are specifically constructed to have an order which
    #       is triggering the problem. Slave list is sorted in many places,
    #       and such slave configuration will result with them begin seen
    #       by backend haproxy configuration in exactly the way seen below
    #       Ordering it here will not help at all.
    return {
      'wildcard': {
        'url': cls.backend_url + 'wildcard',
        'custom_domain': '*.alias1.example.com',
      },
      'zspecific': {
        'url': cls.backend_url + 'zspecific',
        'custom_domain': 'zspecific.alias1.example.com',
      },
    }

  def test(self):
    parameter_dict_wildcard = self.parseSlaveParameterDict('wildcard')
    self.assertLogAccessUrlWithPop(parameter_dict_wildcard)
    self.assertKedifaKeysWithPop(parameter_dict_wildcard, '')
    hostname = '*.alias1'
    self.assertEqual(
      {
        'domain': '%s.example.com' % (hostname,),
        'replication_number': '1',
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
      },
      parameter_dict_wildcard
    )
    parameter_dict_specific = self.parseSlaveParameterDict('zspecific')
    self.assertLogAccessUrlWithPop(parameter_dict_specific)
    self.assertKedifaKeysWithPop(parameter_dict_specific, '')
    hostname = 'zspecific.alias1'
    self.assertEqual(
      {
        'domain': '%s.example.com' % (hostname,),
        'replication_number': '1',
        'url': 'http://%s.example.com' % (hostname, ),
        'site_url': 'http://%s.example.com' % (hostname, ),
        'secure_access': 'https://%s.example.com' % (hostname, ),
        'public-ipv4': self._ipv4_address,
        'backend-client-caucase-url': 'http://[%s]:8990' % self._ipv6_address,
      },
      parameter_dict_specific
    )

    result_wildcard = fakeHTTPSResult(
      'other.alias1.example.com', parameter_dict_wildcard['public-ipv4'],
      'test-path',
      headers={
        'Timeout': '10',  # more than default backend-connect-timeout == 5
        'Accept-Encoding': 'gzip',
      }
    )
    self.assertEqual(self.certificate_pem, der2pem(result_wildcard.peercert))
    self.assertEqualResultJson(result_wildcard, 'Path', '/wildcard/test-path')

    result_specific = fakeHTTPSResult(
      'zspecific.alias1.example.com', parameter_dict_specific['public-ipv4'],
      'test-path',
      headers={
        'Timeout': '10',  # more than default backend-connect-timeout == 5
        'Accept-Encoding': 'gzip',
      }
    )
    self.assertEqual(self.certificate_pem, der2pem(result_specific.peercert))
    self.assertEqualResultJson(result_specific, 'Path', '/zspecific/test-path')
6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768


class TestPassedRequestParameter(HttpFrontendTestCase):
  # special SRs to check out
  frontend_2_sr = 'special_sr_for_2'
  frontend_3_sr = 'special_sr_for_3'
  kedifa_sr = 'special_sr_for_kedifa'

  @classmethod
  def setUpClass(cls):
    super(TestPassedRequestParameter, cls).setUpClass()
    cls.slap.supply(cls.frontend_2_sr, cls.slap._computer_id)
    cls.slap.supply(cls.frontend_3_sr, cls.slap._computer_id)
    cls.slap.supply(cls.kedifa_sr, cls.slap._computer_id)

6769 6770 6771 6772 6773 6774 6775 6776 6777 6778
  @classmethod
  def tearDownClass(cls):
    cls.slap.supply(
      cls.frontend_2_sr, cls.slap._computer_id, state="destroyed")
    cls.slap.supply(
      cls.frontend_3_sr, cls.slap._computer_id, state="destroyed")
    cls.slap.supply(
      cls.kedifa_sr, cls.slap._computer_id, state="destroyed")
    super(TestPassedRequestParameter, cls).tearDownClass()

6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791
  instance_parameter_dict = {
      'port': HTTPS_PORT,
      'plain_http_port': HTTP_PORT,
      'kedifa_port': KEDIFA_PORT,
      'caucase_port': CAUCASE_PORT,
  }

  @classmethod
  def getInstanceParameterDict(cls):
    return cls.instance_parameter_dict

  def test(self):
    self.instance_parameter_dict.update({
6792
      # master partition parameters
6793 6794
      '-frontend-quantity': 3,
      '-sla-2-computer_guid': self.slap._computer_id,
6795
      '-sla-3-computer_guid': self.slap._computer_id,
6796 6797 6798 6799 6800
      '-frontend-2-state': 'stopped',
      '-frontend-2-software-release-url': self.frontend_2_sr,
      '-frontend-3-state': 'stopped',
      '-frontend-3-software-release-url': self.frontend_3_sr,
      '-kedifa-software-release-url': self.kedifa_sr,
6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819
      'automatic-internal-kedifa-caucase-csr': False,
      'automatic-internal-backend-client-caucase-csr': False,
      # all nodes partition parameters
      'apache-certificate': self.certificate_pem,
      'apache-key': self.key_pem,
      'domain': 'example.com',
      'enable-http2-by-default': True,
      'global-disable-http2': True,
      'mpm-graceful-shutdown-timeout': 2,
      'public-ipv4': '255.255.255.255',
      're6st-verification-url': 're6st-verification-url',
      'backend-connect-timeout': 2,
      'backend-connect-retries': 1,
      'ciphers': 'ciphers',
      'request-timeout': 100,
      'authenticate-to-backend': True,
      # specific parameters
      '-frontend-config-1-ram-cache-size': '512K',
      '-frontend-config-2-ram-cache-size': '256K',
6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830
    })

    # re-request instance with updated parameters
    self.requestDefaultInstance()

    # run once instance, it's only needed for later checks
    try:
      self.slap.waitForInstance()
    except Exception:
      pass

6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844
    computer = self.slap._slap.registerComputer('local')
    # state of parameters of all instances
    partition_parameter_dict_dict = {}
    for partition in computer.getComputerPartitionList():
      if partition.getState() == 'destroyed':
        continue
      parameter_dict = partition.getInstanceParameterDict()
      instance_title = parameter_dict['instance_title']
      if '_' in parameter_dict:
        # "flatten" the instance parameter
        parameter_dict = json.loads(parameter_dict['_'])
      partition_parameter_dict_dict[instance_title] = parameter_dict
      parameter_dict[
        'X-software_release_url'] = partition.getSoftwareRelease().getURI()
6845 6846

    base_software_url = self.getSoftwareURL()
6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019

    # drop some very varying parameters
    def assertKeyWithPop(d, k):
      self.assertIn(k, d)
      d.pop(k)
    assertKeyWithPop(
      partition_parameter_dict_dict['caddy-frontend-1'],
      'master-key-download-url')
    assertKeyWithPop(
      partition_parameter_dict_dict['caddy-frontend-2'],
      'master-key-download-url')
    assertKeyWithPop(
      partition_parameter_dict_dict['caddy-frontend-3'],
      'master-key-download-url')
    assertKeyWithPop(
      partition_parameter_dict_dict['testing partition 0'],
      'timestamp')
    assertKeyWithPop(
      partition_parameter_dict_dict['testing partition 0'],
      'ip_list')

    monitor_password = partition_parameter_dict_dict[
      'caddy-frontend-1'].pop('monitor-password')
    self.assertEqual(
      monitor_password,
      partition_parameter_dict_dict[
        'caddy-frontend-2'].pop('monitor-password')
    )
    self.assertEqual(
      monitor_password,
      partition_parameter_dict_dict[
        'caddy-frontend-3'].pop('monitor-password')
    )
    self.assertEqual(
      monitor_password,
      partition_parameter_dict_dict[
        'kedifa'].pop('monitor-password')
    )

    backend_client_caucase_url = u'http://[%s]:8990' % (self._ipv6_address,)
    kedifa_caucase_url = u'http://[%s]:15090' % (self._ipv6_address,)
    expected_partition_parameter_dict_dict = {
      'caddy-frontend-1': {
        'X-software_release_url': base_software_url,
        u'apache-certificate': unicode(self.certificate_pem),
        u'apache-key': unicode(self.key_pem),
        u'authenticate-to-backend': u'True',
        u'backend-client-caucase-url': backend_client_caucase_url,
        u'backend-connect-retries': u'1',
        u'backend-connect-timeout': u'2',
        u'ciphers': u'ciphers',
        u'cluster-identification': u'testing partition 0',
        u'domain': u'example.com',
        u'enable-http2-by-default': u'True',
        u'extra_slave_instance_list': u'[]',
        u'frontend-name': u'caddy-frontend-1',
        u'global-disable-http2': u'True',
        u'kedifa-caucase-url': kedifa_caucase_url,
        u'monitor-cors-domains': u'monitor.app.officejs.com',
        u'monitor-httpd-port': 8411,
        u'monitor-username': u'admin',
        u'mpm-graceful-shutdown-timeout': u'2',
        u'plain_http_port': '11080',
        u'port': '11443',
        u'public-ipv4': u'255.255.255.255',
        u'ram-cache-size': u'512K',
        u're6st-verification-url': u're6st-verification-url',
        u'request-timeout': u'100',
        u'slave-kedifa-information': u'{}'
      },
      'caddy-frontend-2': {
        'X-software_release_url': self.frontend_2_sr,
        u'apache-certificate': unicode(self.certificate_pem),
        u'apache-key': unicode(self.key_pem),
        u'authenticate-to-backend': u'True',
        u'backend-client-caucase-url': backend_client_caucase_url,
        u'backend-connect-retries': u'1',
        u'backend-connect-timeout': u'2',
        u'ciphers': u'ciphers',
        u'cluster-identification': u'testing partition 0',
        u'domain': u'example.com',
        u'enable-http2-by-default': u'True',
        u'extra_slave_instance_list': u'[]',
        u'frontend-name': u'caddy-frontend-2',
        u'global-disable-http2': u'True',
        u'kedifa-caucase-url': kedifa_caucase_url,
        u'monitor-cors-domains': u'monitor.app.officejs.com',
        u'monitor-httpd-port': 8412,
        u'monitor-username': u'admin',
        u'mpm-graceful-shutdown-timeout': u'2',
        u'plain_http_port': u'11080',
        u'port': u'11443',
        u'public-ipv4': u'255.255.255.255',
        u'ram-cache-size': u'256K',
        u're6st-verification-url': u're6st-verification-url',
        u'request-timeout': u'100',
        u'slave-kedifa-information': u'{}'
      },
      'caddy-frontend-3': {
        'X-software_release_url': self.frontend_3_sr,
        u'apache-certificate': unicode(self.certificate_pem),
        u'apache-key': unicode(self.key_pem),
        u'authenticate-to-backend': u'True',
        u'backend-client-caucase-url': backend_client_caucase_url,
        u'backend-connect-retries': u'1',
        u'backend-connect-timeout': u'2',
        u'ciphers': u'ciphers',
        u'cluster-identification': u'testing partition 0',
        u'domain': u'example.com',
        u'enable-http2-by-default': u'True',
        u'extra_slave_instance_list': u'[]',
        u'frontend-name': u'caddy-frontend-3',
        u'global-disable-http2': u'True',
        u'kedifa-caucase-url': kedifa_caucase_url,
        u'monitor-cors-domains': u'monitor.app.officejs.com',
        u'monitor-httpd-port': 8413,
        u'monitor-username': u'admin',
        u'mpm-graceful-shutdown-timeout': u'2',
        u'plain_http_port': u'11080',
        u'port': u'11443',
        u'public-ipv4': u'255.255.255.255',
        u're6st-verification-url': u're6st-verification-url',
        u'request-timeout': u'100',
        u'slave-kedifa-information': u'{}'
      },
      'kedifa': {
        'X-software_release_url': self.kedifa_sr,
        u'caucase_port': u'15090',
        u'cluster-identification': u'testing partition 0',
        u'kedifa_port': u'15080',
        u'monitor-cors-domains': u'monitor.app.officejs.com',
        u'monitor-httpd-port': u'8402',
        u'monitor-username': u'admin',
        u'slave-list': []
      },
      'testing partition 0': {
        '-frontend-2-software-release-url': self.frontend_2_sr,
        '-frontend-2-state': 'stopped',
        '-frontend-3-software-release-url': self.frontend_3_sr,
        '-frontend-3-state': 'stopped',
        '-frontend-config-1-ram-cache-size': '512K',
        '-frontend-config-2-ram-cache-size': '256K',
        '-frontend-quantity': '3',
        '-kedifa-software-release-url': self.kedifa_sr,
        '-sla-2-computer_guid': 'local',
        '-sla-3-computer_guid': 'local',
        'X-software_release_url': base_software_url,
        'apache-certificate': unicode(self.certificate_pem),
        'apache-key': unicode(self.key_pem),
        'authenticate-to-backend': 'True',
        'automatic-internal-backend-client-caucase-csr': 'False',
        'automatic-internal-kedifa-caucase-csr': 'False',
        'backend-connect-retries': '1',
        'backend-connect-timeout': '2',
        'caucase_port': '15090',
        'ciphers': 'ciphers',
        'domain': 'example.com',
        'enable-http2-by-default': 'True',
        'full_address_list': [],
        'global-disable-http2': 'True',
        'instance_title': 'testing partition 0',
        'kedifa_port': '15080',
        'mpm-graceful-shutdown-timeout': '2',
        'plain_http_port': '11080',
        'port': '11443',
        'public-ipv4': '255.255.255.255',
        're6st-verification-url': 're6st-verification-url',
        'request-timeout': '100',
        'root_instance_title': 'testing partition 0',
        'slap_software_type': 'RootSoftwareInstance',
        'slave_instance_list': []
      }
    }
7020
    self.assertEqual(
7021 7022
      expected_partition_parameter_dict_dict,
      partition_parameter_dict_dict
7023
    )