test.py 85 KB
Newer Older
Vincent Pelletier's avatar
Vincent Pelletier committed
1
# This file is part of caucase
2
# Copyright (C) 2017-2019  Nexedi
Vincent Pelletier's avatar
Vincent Pelletier committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#     Alain Takoudjou <alain.takoudjou@nexedi.com>
#     Vincent Pelletier <vincent@nexedi.com>
#
# caucase 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.
#
# caucase 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 caucase.  If not, see <http://www.gnu.org/licenses/>.
"""
Caucase - Certificate Authority for Users, Certificate Authority for SErvices

Test suite
"""
23
# pylint: disable=too-many-lines, too-many-public-methods
Vincent Pelletier's avatar
Vincent Pelletier committed
24
from __future__ import absolute_import
25
import contextlib
26
from Cookie import SimpleCookie
Vincent Pelletier's avatar
Vincent Pelletier committed
27 28
import datetime
import errno
Vincent Pelletier's avatar
Vincent Pelletier committed
29
import functools
Vincent Pelletier's avatar
Vincent Pelletier committed
30
import glob
31
import HTMLParser
32
import httplib
33
from io import BytesIO, StringIO
Vincent Pelletier's avatar
Vincent Pelletier committed
34
import ipaddress
35
import json
Vincent Pelletier's avatar
Vincent Pelletier committed
36 37 38 39 40
import os
import random
import shutil
import socket
import sqlite3
41
import ssl
Vincent Pelletier's avatar
Vincent Pelletier committed
42 43
import sys
import tempfile
44
import threading
Vincent Pelletier's avatar
Vincent Pelletier committed
45
import time
Vincent Pelletier's avatar
Vincent Pelletier committed
46
import unittest
47
from urllib import quote, urlencode
Vincent Pelletier's avatar
Vincent Pelletier committed
48
import urlparse
Vincent Pelletier's avatar
Vincent Pelletier committed
49 50
from cryptography import x509
from cryptography.hazmat.backends import default_backend
51
from cryptography.hazmat.primitives import hashes
Vincent Pelletier's avatar
Vincent Pelletier committed
52
from caucase import cli
53
from caucase.ca import Extension
54
from caucase.client import CaucaseError, CaucaseClient
55
from caucase.exceptions import CertificateVerificationError
56 57 58
# Do not import caucase.http into this namespace: 2to3 will import standard
# http module, which will then be masqued by caucase's http submodule.
import caucase.http
Vincent Pelletier's avatar
Vincent Pelletier committed
59 60 61 62 63 64 65 66
from caucase import utils
from caucase import exceptions
from caucase import wsgi
from caucase.storage import SQLite3Storage

_cryptography_backend = default_backend()

NOT_CAUCASE_OID = '2.25.285541874270823339875695650038637483518'
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
A_YEAR_IN_SECONDS = 60 * 60 * 24 * 365 # Roughly a year

class assertHTMLNoScriptAlert(HTMLParser.HTMLParser):
  """
  Raise AssertionError if it finds a <script> tag containing "alert".
  """
  _in_script = False

  def __init__(self, data):
    HTMLParser.HTMLParser.__init__(self)
    self.feed(data)
    self.close()

  def reset(self):
    """
    Out of script tag.
    """
    HTMLParser.HTMLParser.reset(self)
    self._in_script = False

  def handle_starttag(self, tag, attrs):
    """
    Update whether a script tag was entered.
    """
    assert not self._in_script
    self._in_script = tag == 'script'

  def handle_endtag(self, tag): # pragma: no cover
    """
    Track leaving script tag.
    """
    if tag == 'script':
      assert self._in_script
      self._in_script = False

  def handle_data(self, data):
    """
    Check script tag content.
    """
    assert not self._in_script or 'alert' not in data, (
      '<script>...alert...</script> found'
    )
Vincent Pelletier's avatar
Vincent Pelletier committed
109

110
def canConnect(address): # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
111 112 113 114 115
  """
  Returns True if a connection can be established to given address, False
  otherwise.
  """
  try:
116
    sock = socket.create_connection(address)
117
  except socket.error as e:
Vincent Pelletier's avatar
Vincent Pelletier committed
118 119 120
    if e.errno == errno.ECONNREFUSED:
      return False
    raise
121 122
  else:
    sock.close()
Vincent Pelletier's avatar
Vincent Pelletier committed
123 124
  return True

125
def retry(callback, try_count=200, try_delay=0.1): # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
126 127 128 129 130 131 132 133
  """
  Poll <callback> every <try_delay> for <try_count> times or until it returns
  a true value.
  Always returns the value returned by latest callback invocation.
  """
  for _ in xrange(try_count):
    result = callback()
    if result:
134
      break
Vincent Pelletier's avatar
Vincent Pelletier committed
135
    time.sleep(try_delay)
136
  return result
Vincent Pelletier's avatar
Vincent Pelletier committed
137

138 139 140
class FakeStreamRequest(object):
  """
  For testing StreamRequestHandler subclasses
141
  (like caucase.http.CaucaseWSGIRequestHandler).
142 143 144 145 146 147 148 149 150 151 152 153 154 155
  """
  def __init__(self, rfile, wfile):
    """
    rfile & wfile: Both halves of emulated socket.
    """
    self._rfile = rfile
    self._wfile = wfile

  def makefile(self, mode, _):
    """
    Fake splitting the socket.
    """
    return self._rfile if 'r' in mode else self._wfile

156
  # pylint: disable=unused-argument
157
  def sendall(self, data, flags=None): # pragma: no cover
158 159 160
    """
    Redirect sendall.
    """
161
    self._wfile.write(data)
162
  # pylint: enable=unused-argument
163

164 165 166 167 168 169 170 171 172 173 174 175 176 177
class NoCloseFileProxy(object):
  """
  Intercept .close() calls, for example to allow reading StringIO content
  despite attempted closure.
  """
  def __init__(self, real_file):
    """
    real_file: Object toforward all non-close calls to.
    """
    self._real_file = real_file

  def __getattr__(self, name):
    return getattr(self._real_file, name)

178
  def close(self): # pragma: no cover
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    """
    Don't.
    """
    pass

class FakeAppServer(object):
  """
  Minimal fake WSGI app server.
  """
  def __init__(self, app):
    self._app = app
    self.base_environ = {}

  def get_app(self):
    """
    Retrieve app.
    """
    return self._app

198
class DummyApp(object):
199
  """
200
  Simple WSGI app with limited (but simple) scripting.
201
  """
202 203 204 205 206 207 208
  def __init__(self, callback=lambda x: []):
    """
    callback (callable)
      Received environ as argument,
      Expected to return response body as an iterable.
    """
    self._callback = callback
209

210 211 212 213 214 215
  def __call__(self, environ, start_response):
    """
    WSGI entry point
    """
    start_response('200 OK', [])
    return self._callback(environ)
216

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
ON_EVENT_RAISE = object()
ON_EVENT_EXPIRE = object()
class UntilEvent(object):
  """
  Like utils.until, but with a threading.Event replacing
  KeyboardInterrupt as the early interruption source.
  """
  def __init__(self, event):
    """
    event (Event)
      Event to wait upon. Set and cleared outside this class.
    """
    self._event = event
    self._action = ON_EVENT_RAISE
    self._wait_event = threading.Event()
    self._wait_event.clear()

  @property
  def action(self):
    """
    Retrieve current action. Not very useful.
    """
239
    return self._action # pragma: no cover
240 241 242 243 244 245 246

  @action.setter
  def action(self, value):
    """
    Change the action which will happen on next event wakeup.
    """
    if value not in (ON_EVENT_RAISE, ON_EVENT_EXPIRE):
247
      raise ValueError # pragma: no cover
248 249
    self._action = value

250
  def wait(self, timeout=10):
251 252 253 254 255
    """
    Wait for event to be waited upon at least once.
    timeout (float)
      Maximum number of seconds to wait for.
    """
256 257 258
    if not self._wait_event.wait(timeout): # pragma: no cover
      raise AssertionError('Timeout reached')
    self._wait_event.clear()
259 260 261

  def __call__(self, deadline):
    """
262 263 264
    Sleep until event is set, then
    - if self.action is ON_EVENT_RAISE, raises utils.SleepInterrupt.
    - if self.action is ON_EVENT_EXPIRE, deadline time it returned.
265 266
    """
    now = datetime.datetime.utcnow()
267
    if now < deadline:
268
      self._wait_event.set()
269 270
      assert self._event.wait(10)
      self._event.clear()
271 272 273 274 275 276
      if self._action is ON_EVENT_EXPIRE:
        now = deadline
      else:
        raise utils.SleepInterrupt
    return now

Vincent Pelletier's avatar
Vincent Pelletier committed
277 278 279 280 281 282 283 284 285 286 287 288
def print_buffer_on_error(func):
  """
  Write output buffer to stdout when wrapped method raises.
  func is expected to be a method from CaucaseTest class.
  """
  @functools.wraps(func)
  def wrapper(self, *args, **kw):
    """
    Write output buffer to stdout when wrapped method raises.
    """
    try:
      return func(self, *args, **kw)
289
    except Exception: # pragma : no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
290 291 292 293 294
      sys.stdout.write(utils.toBytes(os.linesep))
      sys.stdout.write(self.caucase_test_output.getvalue())
      raise
  return wrapper

295 296 297 298 299 300 301 302 303 304 305 306 307
@contextlib.contextmanager
def captureStdout():
  """
  Replace stdout with a BytesIO object for the duration of the context manager,
  and provide it to caller.
  """
  orig_stdout = sys.stdout
  sys.stdout = stdout = BytesIO()
  try:
    yield stdout
  finally:
    sys.stdout = orig_stdout

Vincent Pelletier's avatar
Vincent Pelletier committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
class CaucaseTest(unittest.TestCase):
  """
  Test a complete caucase setup: spawn a caucase-http server on CAUCASE_NETLOC
  and use caucase-cli to access it.
  """
  _server = None

  def setUp(self):
    """
    Prepare test data directory and file paths, and start caucased as most
    tests will need to interact with it.
    """
    self._data_dir = data_dir = tempfile.mkdtemp(prefix='caucase_test_')

    self._client_dir = client_dir = os.path.join(data_dir, 'client')
    os.mkdir(client_dir)
    # pylint: disable=bad-whitespace
    self._client_ca_crt      = os.path.join(client_dir, 'cas.crt.pem')
    self._client_user_ca_crt = os.path.join(client_dir, 'cau.crt.pem')
    self._client_crl         = os.path.join(client_dir, 'cas.crl.pem')
    self._client_user_crl    = os.path.join(client_dir, 'cau.crl.pem')
    # pylint: enable=bad-whitespace

331
    self._server_event = threading.Event()
Vincent Pelletier's avatar
Vincent Pelletier committed
332 333 334 335 336 337
    self._server_dir = server_dir = os.path.join(data_dir, 'server')
    os.mkdir(server_dir)
    # pylint: disable=bad-whitespace
    self._server_db          = os.path.join(server_dir, 'caucase.sqlite')
    self._server_key         = os.path.join(server_dir, 'server.key.pem')
    self._server_backup_path = os.path.join(server_dir, 'backup')
338
    self._server_cors_store  = os.path.join(server_dir, 'cors.key')
Vincent Pelletier's avatar
Vincent Pelletier committed
339
    # pylint: enable=bad-whitespace
Vincent Pelletier's avatar
Vincent Pelletier committed
340
    self.caucase_test_output = BytesIO()
Vincent Pelletier's avatar
Vincent Pelletier committed
341 342
    os.mkdir(self._server_backup_path)

Vincent Pelletier's avatar
Vincent Pelletier committed
343 344 345 346
    self._server_netloc = netloc = os.getenv(
      'CAUCASE_NETLOC',
      'localhost:8000',
    )
Vincent Pelletier's avatar
Vincent Pelletier committed
347 348 349 350 351 352 353 354 355
    self._caucase_url = 'http://' + netloc
    parsed_url = urlparse.urlparse(self._caucase_url)
    self.assertFalse(
      canConnect((parsed_url.hostname, parsed_url.port)),
      'Something else is already listening on %r, define CAUCASE_NETLOC '
      'environment variable with a different ip/port' % (netloc, ),
    )
    self._startServer()

Vincent Pelletier's avatar
Vincent Pelletier committed
356
  @print_buffer_on_error
Vincent Pelletier's avatar
Vincent Pelletier committed
357 358 359 360 361 362 363 364
  def tearDown(self):
    """
    Stop any running caucased and delete all test data files.
    """
    if self._server.is_alive():
      self._stopServer()
    shutil.rmtree(self._data_dir)

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 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 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
  @staticmethod
  def _getCAKeyPair(extension_list=(), not_before=None, not_after=None):
    """
    Build a reasonably-realistic CA, return key & self-signed cert.
    """
    if not_before is None:
      not_before = datetime.datetime.utcnow()
    if not_after is None:
      not_after = not_before + datetime.timedelta(10, 0)
    private_key = utils.generatePrivateKey(2048)
    subject = x509.Name([
      x509.NameAttribute(
        oid=x509.oid.NameOID.COMMON_NAME,
        value=u'John Doe CA',
      ),
    ])
    public_key = private_key.public_key()
    subject_key_identifier = x509.SubjectKeyIdentifier.from_public_key(
      public_key,
    )
    return private_key, x509.CertificateBuilder(
      subject_name=subject,
      issuer_name=subject,
      not_valid_before=not_before,
      not_valid_after=not_after,
      serial_number=x509.random_serial_number(),
      public_key=public_key,
      extensions=[
        Extension(
          subject_key_identifier,
          critical=False, # "MUST mark this extension as non-critical"
        ),
        Extension(
          x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(
            # Dummy extension, from_issuer_subject_key_identifier accesses
            # .data directly
            Extension(
              subject_key_identifier,
              critical=False,
            ),
          ),
          critical=False, # "MUST mark this extension as non-critical"
        ),
        Extension(
          x509.BasicConstraints(
            ca=True,
            path_length=0,
          ),
          critical=True, # "MUST mark the extension as critical"
        ),
        Extension(
          x509.KeyUsage(
            # pylint: disable=bad-whitespace
            digital_signature =False,
            content_commitment=False,
            key_encipherment  =False,
            data_encipherment =False,
            key_agreement     =False,
            key_cert_sign     =True,
            crl_sign          =True,
            encipher_only     =False,
            decipher_only     =False,
            # pylint: enable=bad-whitespace
          ),
          critical=True, # "SHOULD mark this extension critical"
        ),
      ] + list(extension_list),
    ).sign(
      private_key=private_key,
      algorithm=hashes.SHA256(),
      backend=_cryptography_backend,
    )

  @staticmethod
  def _getKeyPair(
    ca_key,
    ca_crt,
    extension_list=(),
    not_before=None,
    not_after=None,
  ):
    """
    Build a reasonably-realistic signed cert, return key & self-signed cert.
    """
    if not_before is None:
      not_before = datetime.datetime.utcnow()
    if not_after is None:
      not_after = not_before + datetime.timedelta(10, 0)
    crt_key = utils.generatePrivateKey(2048)
    return crt_key, x509.CertificateBuilder(
      subject_name=x509.Name([
        x509.NameAttribute(
          oid=x509.oid.NameOID.ORGANIZATIONAL_UNIT_NAME,
          value=u'Jane Doe',
        ),
      ]),
      issuer_name=ca_crt.subject,
      not_valid_before=not_before,
      not_valid_after=not_after,
      serial_number=x509.random_serial_number(),
      public_key=crt_key.public_key(),
      extensions=[
        Extension(
          x509.KeyUsage(
            # pylint: disable=bad-whitespace
            digital_signature =True,
            content_commitment=False,
            key_encipherment  =True,
            data_encipherment =False,
            key_agreement     =False,
            key_cert_sign     =False,
            crl_sign          =False,
            encipher_only     =False,
            decipher_only     =False,
            # pylint: enable=bad-whitespace
          ),
          critical=True,
        ),
      ] + list(extension_list),
    ).sign(
      private_key=ca_key,
      algorithm=hashes.SHA256(),
      backend=_cryptography_backend,
    )

  def _skipIfOpenSSLDoesNotSupportIPContraints(self):
    ca_key, ca_crt = self._getCAKeyPair(
      extension_list=[
        Extension(
          x509.NameConstraints(
            permitted_subtrees=[
              x509.IPAddress(ipaddress.ip_network(u'127.0.0.1')),
            ],
            excluded_subtrees=None,
          ),
          critical=True,
        ),
      ],
    )
    _, crt = self._getKeyPair(
      ca_key=ca_key,
      ca_crt=ca_crt,
    )
    try:
      # pylint: disable=protected-access
      utils._verifyCertificateChain(
        cert=crt,
        trusted_cert_list=[ca_crt],
        crl=None,
      )
      # pylint: enable=protected-access
Vincent Pelletier's avatar
Vincent Pelletier committed
516
    except CertificateVerificationError: # pragma: no cover
517 518
      raise unittest.SkipTest('OpenSSL versoin does not support IP constraints')

Vincent Pelletier's avatar
Vincent Pelletier committed
519 520 521 522 523 524 525 526
  def _restoreServer(
    self,
    backup_path,
    key_path,
    new_csr_path,
    new_key_path,
  ):
    """
527
    Start caucased-manage --restore-backup .
Vincent Pelletier's avatar
Vincent Pelletier committed
528 529
    Returns its exit status.
    """
530
    try:
531
      caucase.http.manage(
532
        argv=(
Vincent Pelletier's avatar
Vincent Pelletier committed
533 534 535 536 537 538 539
          '--db', self._server_db,
          '--restore-backup',
          backup_path,
          key_path,
          new_csr_path,
          new_key_path,
        ),
540
      )
541
    except SystemExit as e:
542
      return e.code # pragma: no cover
543
    except: # pylint: disable=bare-except
544 545 546
      return 1
    return 0

Vincent Pelletier's avatar
Vincent Pelletier committed
547 548 549 550
  def _startServer(self, *argv):
    """
    Start caucased server
    """
551
    self._server_until = until = UntilEvent(self._server_event)
552
    self._server = server = threading.Thread(
553
      target=caucase.http.main,
Vincent Pelletier's avatar
Vincent Pelletier committed
554 555 556 557 558 559 560
      kwargs={
        'argv': (
          '--db', self._server_db,
          '--server-key', self._server_key,
          '--netloc', self._server_netloc,
          #'--threshold', '31',
          #'--key-len', '2048',
561
          '--cors-key-store', self._server_cors_store,
Vincent Pelletier's avatar
Vincent Pelletier committed
562
        ) + argv,
563
        'until': until,
Vincent Pelletier's avatar
Vincent Pelletier committed
564 565
        'log_file': self.caucase_test_output,
        'error_file': self.caucase_test_output,
Vincent Pelletier's avatar
Vincent Pelletier committed
566 567 568 569 570 571
      }
    )
    server.daemon = True
    server.start()
    parsed_url = urlparse.urlparse(self._caucase_url)
    if not retry(
572 573 574 575
      lambda: (
        self.assertTrue(server.is_alive(), 'caucased crashed on startup') or
        canConnect((parsed_url.hostname, parsed_url.port))
      ),
576
    ): # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
577 578 579 580 581 582 583 584 585 586
      self._stopServer()
      raise AssertionError('Could not connect to %r after 1 second' % (
        self._caucase_url,
      ))

  def _stopServer(self):
    """
    Stop a running caucased server
    """
    server = self._server
587
    self._server_until.action = ON_EVENT_RAISE
588 589
    self._server_event.set()
    server.join(2)
590
    if server.is_alive(): # pragma: no cover
591
      raise ValueError('%r does not wish to die' % (server, ))
Vincent Pelletier's avatar
Vincent Pelletier committed
592 593 594 595 596 597 598

  def _runClient(self, *argv):
    """
    Run client with given arguments.

    Returns stdout.
    """
599 600 601 602 603 604 605 606 607 608 609 610 611
    with captureStdout() as stdout:
      try:
        cli.main(
          argv=(
            '--ca-url', self._caucase_url,
            '--ca-crt', self._client_ca_crt,
            '--user-ca-crt', self._client_user_ca_crt,
            '--crl', self._client_crl,
            '--user-crl', self._client_user_crl,
          ) + argv,
        )
      except SystemExit:
        pass
Vincent Pelletier's avatar
Vincent Pelletier committed
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
    return stdout.getvalue()

  @staticmethod
  def _setCertificateRemainingLifeTime(key, crt, delta):
    """
    Re-sign <crt> with <key>, shifting both its not_valid_before and
    not_valid_after dates so that its remaining validity period
    becomes <delta> and its validity span stays unchanged.
    """
    new_not_valid_after_date = datetime.datetime.utcnow() + delta
    return x509.CertificateBuilder(
      subject_name=crt.subject,
      issuer_name=crt.issuer,
      not_valid_before=new_not_valid_after_date - (
        crt.not_valid_after - crt.not_valid_before
      ),
      not_valid_after=new_not_valid_after_date,
      serial_number=crt.serial_number,
      public_key=crt.public_key(),
      extensions=crt.extensions,
    ).sign(
      private_key=key,
      algorithm=crt.signature_hash_algorithm,
      backend=_cryptography_backend,
    )

  def _setCACertificateRemainingLifeTime(self, mode, serial, delta):
    """
    Find the CA certificate with <serial> in caucase <mode> ("service"
    or "user") and pass it to _setCertificateRemainingLifeTime with <delta>.
    """
    int(serial) # Must already be an integer
    prefix = {
      'user': 'cau',
      'service': 'cas',
    }[mode]
    db = sqlite3.connect(self._server_db)
    db.row_factory = sqlite3.Row
    with db:
      c = db.cursor()
      c.execute(
        'SELECT rowid, key, crt FROM ' + prefix + 'ca',
      )
      while True:
        row = c.fetchone()
657
        if row is None: # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
658
          raise Exception('CA with serial %r not found' % (serial, ))
659
        crt = utils.load_ca_certificate(utils.toBytes(row['crt']))
Vincent Pelletier's avatar
Vincent Pelletier committed
660 661
        if crt.serial_number == serial:
          new_crt = self._setCertificateRemainingLifeTime(
662
            key=utils.load_privatekey(utils.toBytes(row['key'])),
Vincent Pelletier's avatar
Vincent Pelletier committed
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
            crt=crt,
            delta=delta,
          )
          new_crt_pem = utils.dump_certificate(new_crt)
          c.execute(
            'UPDATE ' + prefix + 'ca SET '
            'expiration_date=?, crt=? '
            'WHERE rowid=?',
            (
              utils.datetime2timestamp(new_crt.not_valid_after),
              new_crt_pem,
              row['rowid'],
            ),
          )
          return new_crt_pem

  def _getBaseName(self):
    """
    Returns a random file name, prefixed by data directory.
    """
    return os.path.join(
      self._data_dir,
      str(random.getrandbits(32)),
    )

  @staticmethod
  def _createPrivateKey(basename, key_len=2048):
    """
    Create a private key and store it to file.
    """
    name = basename + '.key.pem'
    assert not os.path.exists(name)
695
    with open(name, 'wb') as key_file:
Vincent Pelletier's avatar
Vincent Pelletier committed
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
      key_file.write(utils.dump_privatekey(
        utils.generatePrivateKey(key_len=key_len),
      ))
    return name

  @staticmethod
  def _getBasicCSRBuilder():
    """
    Initiate a minimal CSR builder.
    """
    return x509.CertificateSigningRequestBuilder(
      subject_name=x509.Name([
        x509.NameAttribute(
          oid=x509.oid.NameOID.COMMON_NAME,
          value=u'test',
        ),
      ]),
    )

  @staticmethod
  def _finalizeCSR(basename, key_path, csr_builder):
    """
    Sign, serialise and store given CSR Builder to file.
    """
    name = basename + '.csr.pem'
    assert not os.path.exists(name)
722
    with open(name, 'wb') as csr_file:
Vincent Pelletier's avatar
Vincent Pelletier committed
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 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 803 804 805 806 807 808 809
      csr_file.write(
        utils.dump_certificate_request(
          csr_builder.sign(
            private_key=utils.load_privatekey(utils.getKey(key_path)),
            algorithm=utils.DEFAULT_DIGEST_CLASS(),
            backend=_cryptography_backend,
          ),
        ),
      )
    return name

  def _createBasicCSR(self, basename, key_path):
    """
    Creates a basic CSR and returns its path.
    """
    return self._finalizeCSR(
      basename,
      key_path,
      self._getBasicCSRBuilder(),
    )

  def _createFirstUser(self, add_extensions=False):
    """
    Create first user, whose CSR is automatically signed.
    """
    basename = self._getBaseName()
    user_key_path = self._createPrivateKey(basename)
    csr_builder = self._getBasicCSRBuilder()
    if add_extensions:
      csr_builder = csr_builder.add_extension(
        x509.CertificatePolicies([
          x509.PolicyInformation(
            x509.oid.ObjectIdentifier(NOT_CAUCASE_OID),
            None,
          )
        ]),
        critical=False,
      )
    csr_path = self._finalizeCSR(
      basename,
      user_key_path,
      csr_builder,
    )
    out, = self._runClient(
      '--mode', 'user',
      '--send-csr', csr_path,
    ).splitlines()
    csr_id, csr_path_out = out.split()
    # Sanity check output
    self.assertEqual(csr_path, csr_path_out)
    int(csr_id)
    self.assertRaises(TypeError, utils.getCert, user_key_path)
    self._runClient(
      '--mode', 'user',
      '--get-crt', csr_id, user_key_path,
    )
    # Does not raise anymore, we have a certificate
    utils.getCert(user_key_path)
    return user_key_path

  def _createAndApproveCertificate(self, user_key_path, mode):
    """
    Create a CSR, submit it, approve it and retrieve the certificate.
    """
    basename = self._getBaseName()
    key_path = self._createPrivateKey(basename)
    csr_path = self._createBasicCSR(basename, key_path)
    out, = self._runClient(
      '--mode', mode,
      '--send-csr', csr_path,
    ).splitlines()
    csr_id, csr_path_out = out.split()
    # Sanity check output
    self.assertEqual(csr_path, csr_path_out)
    int(csr_id)
    self.assertRaises(TypeError, utils.getCert, key_path)
    out = self._runClient(
      '--mode', mode,
      '--get-crt', csr_id, key_path,
    ).splitlines()
    self.assertRaises(TypeError, utils.getCert, key_path)
    self.assertEqual([csr_id + ' CSR still pending'], out)
    csr2_path = csr_path + '.2'
    self._runClient(
      '--mode', mode,
      '--get-csr', csr_id, csr2_path,
    )
810 811
    with open(csr_path, 'rb') as csr_file, open(csr2_path, 'rb') as csr2_file:
      self.assertEqual(csr_file.read(), csr2_file.read())
Vincent Pelletier's avatar
Vincent Pelletier committed
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 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 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 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    # Sign using user cert
    # Note: assuming user does not know the csr_id and keeps their own copy of
    # issued certificates.
    out = self._runClient(
      '--mode', mode,
      '--user-key', user_key_path,
      '--list-csr',
    ).splitlines()
    self.assertEqual([csr_id], [x.split(None, 1)[0] for x in out[2:-1]])
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--mode', mode,
      '--user-key', user_key_path,
      '--sign-csr', str(int(csr_id) + 1),
    )
    out = self._runClient(
      '--mode', mode,
      '--user-key', user_key_path,
      '--sign-csr', csr_id,
    )
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--mode', mode,
      '--user-key', user_key_path,
      '--sign-csr', csr_id,
    )
    # Now requester can get their certificate
    out, = self._runClient(
      '--mode', mode,
      '--get-crt', csr_id, key_path,
    ).splitlines()
    # Does not raise anymore, we have a certificate
    utils.getCert(user_key_path)
    return key_path

  def testBasicUsage(self):
    """
    Everybody plays by the rules (which includes trying to access when
    revoked).
    """
    self.assertFalse(os.path.exists(self._client_ca_crt))
    self.assertFalse(os.path.exists(self._client_crl))
    self.assertFalse(os.path.exists(self._client_user_ca_crt))
    self.assertFalse(os.path.exists(self._client_user_crl))
    # Running client creates CAS files (service CA & service CRL)
    self._runClient()
    self.assertTrue(os.path.exists(self._client_ca_crt))
    self.assertTrue(os.path.exists(self._client_crl))
    self.assertFalse(os.path.exists(self._client_user_ca_crt))
    self.assertFalse(os.path.exists(self._client_user_crl))
    # Running in "user" mode also created the CAU CA, but not the CAU CRL
    self._runClient('--mode', 'user')
    self.assertTrue(os.path.exists(self._client_ca_crt))
    self.assertTrue(os.path.exists(self._client_crl))
    self.assertTrue(os.path.exists(self._client_user_ca_crt))
    self.assertFalse(os.path.exists(self._client_user_crl))

    cas_crt_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_ca_crt)
    ]
    cau_crt_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_user_ca_crt)
    ]
    # No CA renewal happened yet
    self.assertEqual(len(cas_crt_list), 1)
    self.assertEqual(len(cau_crt_list), 1)

    # Get a user key pair
    user_key_path = self._createFirstUser()
    # It must have been auto-signed
    self.assertTrue(utils.isCertificateAutoSigned(utils.load_certificate(
      # utils.getCert(user_key_path) does not raise anymore
      utils.getCert(user_key_path),
      cau_crt_list,
      None,
    )))

    # Get a not-auto-approved service crt (the first auto-approved one was for
    # the http server itself)
    service_key = self._createAndApproveCertificate(
      user_key_path,
      'service',
    )
    self.assertFalse(utils.isCertificateAutoSigned(utils.load_certificate(
      utils.getCert(service_key),
      cas_crt_list,
      None,
    )))

    # Get a not-auto-approved user crt
    user2_key_path = self._createAndApproveCertificate(
      user_key_path,
      'user',
    )
    self.assertFalse(utils.isCertificateAutoSigned(utils.load_certificate(
      utils.getCert(user2_key_path),
      cau_crt_list,
      None,
    )))
    # It can itself sign certificates...
    service2_key_path = self._createAndApproveCertificate(
      user2_key_path,
      'service',
    )
    user3_key_path = self._createAndApproveCertificate(
      user2_key_path,
      'user',
    )
    self._runClient(
      '--user-key', user2_key_path,
      '--list-csr',
    )
    self._runClient(
      '--mode', 'user',
      '--user-key', user2_key_path,
      '--list-csr',
    )
    # ...until it gets revoked
    self._runClient(
      '--user-key', user_key_path,
      '--mode', 'user',
      '--revoke-other-crt', user2_key_path,
      '--update-user',
    )
    self.assertRaises(
      CaucaseError,
      self._createAndApproveCertificate,
      user2_key_path,
      'service',
    )
    self.assertRaises(
      CaucaseError,
      self._createAndApproveCertificate,
      user2_key_path,
      'user',
    )
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--user-key', user2_key_path,
      '--list-csr',
    )
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--mode', 'user',
      '--user-key', user2_key_path,
      '--list-csr',
    )
    # But the user it approved still works...
    self._runClient(
      '--user-key', user3_key_path,
      '--list-csr',
    )
    # ...until it revokes itself
    self._runClient(
      '--mode', 'user',
      '--user-key', user3_key_path,
      '--revoke-serial', str(
        utils.load_certificate(
          utils.getCert(user3_key_path),
          cau_crt_list,
          None,
        ).serial_number,
      )
    )
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--user-key', user3_key_path,
      '--list-csr',
    )
    # And the service it approved works too
    service2_crt_before, service2_key_before, _ = utils.getKeyPair(
      service2_key_path,
    )
    self._runClient(
      # 100 days is longer than certificate life, so it will be immediately
      # renewed.
      '--threshold', '100',
      '--renew-crt', service2_key_path, '',
    )
    service2_crt_after, service2_key_after, _ = utils.getKeyPair(
      service2_key_path,
    )
    # Certificate and key were renewed...
    self.assertNotEqual(service2_crt_before, service2_crt_after)
    self.assertNotEqual(service2_key_before, service2_key_after)
    # ...and not just swapped
    self.assertNotEqual(service2_crt_before, service2_key_after)
    self.assertNotEqual(service2_key_before, service2_crt_after)
    # It can revoke itself...
    self._runClient(
      '--revoke-crt', service2_key_path, '',
    )
    # ...and then it cannot renew itself any more...
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--threshold', '100',
      '--renew-crt', service2_key_path, '',
    )
    service2_crt_after2, service2_key_after2, _ = utils.getKeyPair(
      service2_key_path,
    )
    # and crt & key did not change
    self.assertEqual(service2_crt_after, service2_crt_after2)
    self.assertEqual(service2_key_after, service2_key_after2)
    # revoking again one's own certificate fails
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--revoke-crt', service2_key_path, '',
    )
    # as does revoking with an authenticated user
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--user-key', user_key_path,
      '--revoke-other-crt', service2_key_path,
    )
    # and revoking by serial
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--user-key', user_key_path,
      '--revoke-serial', str(
        utils.load_certificate(
          utils.getCert(service2_key_path),
          cas_crt_list,
          None,
        ).serial_number,
      ),
    )

    # Rejecting a CSR
    basename = self._getBaseName()
    key_path = self._createPrivateKey(basename)
    csr_path = self._createBasicCSR(basename, key_path)
    out, = self._runClient(
      '--send-csr', csr_path,
    ).splitlines()
    csr_id, csr_path_out = out.split()
    # Sanity check output
    self.assertEqual(csr_path, csr_path_out)
    int(csr_id)
    self.assertRaises(TypeError, utils.getCert, key_path)
    out = self._runClient(
      '--get-crt', csr_id, key_path,
    ).splitlines()
    self.assertRaises(TypeError, utils.getCert, key_path)
    self.assertEqual([csr_id + ' CSR still pending'], out)
    out = self._runClient(
      '--user-key', user_key_path,
      '--reject-csr', csr_id,
    ).splitlines()
    # Re-rejecting fails
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--user-key', user_key_path,
      '--reject-csr', csr_id,
    )
    # like rejecting a non-existing crt
    self.assertRaises(
      CaucaseError,
      self._runClient,
      '--user-key', user_key_path,
      '--reject-csr', str(int(csr_id) + 1),
    )
    out = self._runClient(
      '--get-crt', csr_id, key_path,
    ).splitlines()
    self.assertRaises(TypeError, utils.getCert, key_path)
    self.assertEqual([
Vincent Pelletier's avatar
Vincent Pelletier committed
1091
      csr_id + ' not found - maybe CSR was rejected ?'
Vincent Pelletier's avatar
Vincent Pelletier committed
1092 1093
    ], out)

1094 1095 1096 1097 1098 1099 1100 1101
  def testBadCSR(self):
    """
    Submitting an invalid CSR.

    Requires bypassing cli, as it does its own checks.
    """
    client = CaucaseClient(self._caucase_url + '/cas')
    try:
1102
      client.createCertificateSigningRequest('Not actually a CSR')
1103
    except CaucaseError as e:
1104
      self.assertEqual(e.args[0], 400, e)
1105
    else: # pragma: no cover
1106 1107
      raise AssertionError('Did not raise CaucaseError(400, ...)')

Vincent Pelletier's avatar
Vincent Pelletier committed
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
  def testUpdateUser(self):
    """
    Verify that CAU certificate and revocation list are created when the
    (rarely needed) --update-user option is given.
    """
    self.assertFalse(os.path.exists(self._client_ca_crt))
    self.assertFalse(os.path.exists(self._client_crl))
    self.assertFalse(os.path.exists(self._client_user_ca_crt))
    self.assertFalse(os.path.exists(self._client_user_crl))
    self._runClient('--update-user')
    self.assertTrue(os.path.exists(self._client_ca_crt))
    self.assertTrue(os.path.exists(self._client_crl))
    self.assertTrue(os.path.exists(self._client_user_ca_crt))
    self.assertTrue(os.path.exists(self._client_user_crl))

  def testMaxCSR(self):
    """
    Verify that the number of pending CSR is properly constrained.
    """
    csr_list = []
    def assertCanSend(count):
      """
      Check that caucased accepts <count> CSR, and rejects the next one.
      Appends the data of created CSRs (csr_id and csr_path) to csr_list.
      """
      for _ in xrange(count):
        basename = self._getBaseName()
        csr_path = self._createBasicCSR(
          basename,
          self._createPrivateKey(basename),
        )
        out, = self._runClient('--send-csr', csr_path).splitlines()
        csr_id, _ = out.split()
        csr_list.append((csr_id, csr_path))
      basename = self._getBaseName()
      bad_csr_path = self._createBasicCSR(
        basename,
        self._createPrivateKey(basename),
      )
      self.assertRaises(
        CaucaseError,
        self._runClient,
        '--send-csr',
        bad_csr_path,
      )

    user_key_path = self._createFirstUser()
    self._stopServer()
    self._startServer(
      '--service-max-csr', '5',
    )
    assertCanSend(5)
    # But resubmitting one of the accepted ones is still fine
    _, csr_path = csr_list[0]
    self._runClient('--send-csr', csr_path)

    # Accepted certificates do not count towards the total, even if not
    # retrieved by owner
    csr_id, csr_path = csr_list.pop()
    self._runClient(
      '--user-key', user_key_path,
      '--sign-csr', csr_id,
    )
    assertCanSend(1)
    # Rejected certificates do not count towards the total.

    csr_id, _ = csr_list.pop()
    self._runClient(
      '--user-key', user_key_path,
      '--reject-csr', csr_id,
    )
    assertCanSend(1)

  def testLockAutoSignAmount(self):
    """
    Verify that auto-approve limit freezing works.
    """
    self._stopServer()
    self._startServer(
      '--user-auto-approve-count', '2',
      '--lock-auto-approve-count',
    )
    self._stopServer()
    self._startServer(
      '--user-auto-approve-count', '3',
    )
    self._createFirstUser()
    self._createFirstUser()
    self.assertRaises(TypeError, self._createFirstUser)
    self._stopServer()
    self._startServer(
      '--user-auto-approve-count', '3',
      '--lock-auto-approve-count',
    )
    self.assertRaises(TypeError, self._createFirstUser)

  def testCSRFiltering(self):
    """
    Verify that requester cannot get any extension or extension value they
    ask for. Caucase has to protect itself to be trustworthy, but also to let
    some liberty to requester.
    """
    def checkCRT(key_path):
      """
      Verify key_path to contain exactly one certificate, itself containing
      all expected extensions.
      """
      crt = utils.load_certificate(
        utils.getCert(key_path),
        cas_crt_list,
        None,
      )
      # CA-only extension, must not be present in certificate
      self.assertRaises(
        x509.ExtensionNotFound,
        crt.extensions.get_extension_for_class,
        x509.NameConstraints,
      )
      for expected_value in [
        expected_key_usage,
        expected_extended_usage,
        expected_alt_name,
        expected_policies,
        expected_basic_constraints,
      ]:
        extension = crt.extensions.get_extension_for_class(
          expected_value.__class__,
        )
        self.assertEqual(
          extension.value,
          expected_value,
        )
        self.assertTrue(extension.critical)
    requested_key_usage = x509.KeyUsage(
      # pylint: disable=bad-whitespace
      digital_signature =True,
      content_commitment=True,
      key_encipherment  =True,
      data_encipherment =True,
      key_agreement     =True,
      key_cert_sign     =True,
      crl_sign          =True,
      encipher_only     =True,
      decipher_only     =False,
      # pylint: enable=bad-whitespace
    )
    expected_key_usage = x509.KeyUsage(
      # pylint: disable=bad-whitespace
      digital_signature =True,
      content_commitment=True,
      key_encipherment  =True,
      data_encipherment =True,
      key_agreement     =True,
      key_cert_sign     =False,
      crl_sign          =False,
      encipher_only     =True,
      decipher_only     =False,
      # pylint: enable=bad-whitespace
    )
    requested_extended_usage = x509.ExtendedKeyUsage([
      x509.oid.ExtendedKeyUsageOID.OCSP_SIGNING,
      x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH,
    ])
    expected_extended_usage = x509.ExtendedKeyUsage([
      x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH,
    ])
    requested_alt_name = expected_alt_name = x509.SubjectAlternativeName([
1275 1276 1277
      x509.RFC822Name(u'nobody@example.com'),
      x509.DNSName(u'example.com'),
      x509.UniformResourceIdentifier(u'https://example.com/a/b/c'),
Vincent Pelletier's avatar
Vincent Pelletier committed
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
      x509.IPAddress(ipaddress.IPv4Address(u'127.0.0.1')),
      x509.IPAddress(ipaddress.IPv6Address(u'::1')),
      x509.IPAddress(ipaddress.IPv4Network(u'127.0.0.0/8')),
      x509.IPAddress(ipaddress.IPv6Network(u'::/64')),
    ])
    requested_policies = x509.CertificatePolicies([
      x509.PolicyInformation(
        x509.oid.ObjectIdentifier(utils.CAUCASE_OID_RESERVED),
        None,
      ),
      x509.PolicyInformation(
        x509.oid.ObjectIdentifier(NOT_CAUCASE_OID),
        None,
      ),
    ])
    expected_policies = x509.CertificatePolicies([
      x509.PolicyInformation(
        x509.oid.ObjectIdentifier(NOT_CAUCASE_OID),
        None,
      ),
    ])
    requested_basic_constraints = x509.BasicConstraints(
      ca=True,
      path_length=42,
    )
    expected_basic_constraints = x509.BasicConstraints(
      ca=False,
      path_length=None,
    )

    # Check stored CSR filtering
    user_key_path = self._createFirstUser(add_extensions=True)
    basename = self._getBaseName()
    key_path = self._createPrivateKey(basename)
    requested_csr_path = self._finalizeCSR(
      basename,
      key_path,
      self._getBasicCSRBuilder(
      ).add_extension(requested_key_usage, critical=True,
      ).add_extension(requested_extended_usage, critical=True,
      ).add_extension(requested_alt_name, critical=True,
      ).add_extension(requested_policies, critical=True,
      ).add_extension(requested_basic_constraints, critical=True,
      ).add_extension(
1322
        x509.NameConstraints([x509.DNSName(u'com')], None),
Vincent Pelletier's avatar
Vincent Pelletier committed
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
        critical=True,
      ),
    )
    out, = self._runClient(
      '--send-csr', requested_csr_path,
    ).splitlines()
    csr_id, _ = out.split()
    int(csr_id)
    self._runClient(
      '--user-key', user_key_path,
      '--sign-csr', csr_id,
    )
    self._runClient(
      '--get-crt', csr_id, key_path,
    )
    cas_crt_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_ca_crt)
    ]
    cau_crt_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_user_ca_crt)
    ]
    checkCRT(key_path)

    # Check renewed CRT filtering does not alter clean signed certificate
    # content (especially, caucase auto-signed flag must not appear).
1350 1351
    with open(key_path, 'rb') as key_file:
      before_key = key_file.read()
Vincent Pelletier's avatar
Vincent Pelletier committed
1352 1353 1354 1355
    self._runClient(
      '--threshold', '100',
      '--renew-crt', key_path, '',
    )
1356 1357
    with open(key_path, 'rb') as key_file:
      after_key = key_file.read()
Vincent Pelletier's avatar
Vincent Pelletier committed
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
    assert before_key != after_key
    checkCRT(key_path)

    # Check content of auto-issued user certificate
    user_crt = utils.load_certificate(
      utils.getCert(user_key_path),
      cau_crt_list,
      None,
    )
    user_certificate_policies = user_crt.extensions.get_extension_for_class(
      x509.CertificatePolicies,
    )
    self.assertEqual(
      user_certificate_policies.value,
      x509.CertificatePolicies([
        x509.PolicyInformation(
          x509.oid.ObjectIdentifier(NOT_CAUCASE_OID),
          None,
        ),
        utils.CAUCASE_POLICY_INFORMATION_AUTO_SIGNED,
      ]),
    )
    self.assertFalse(user_certificate_policies.critical)

    # Check template CSR: must be taken into account, but it also gets
    # filtered.
    basename2 = self._getBaseName()
    key_path2 = self._createPrivateKey(basename2)
    out, = self._runClient(
      '--send-csr', self._finalizeCSR(
        basename2,
        key_path2,
        self._getBasicCSRBuilder(),
      ),
    ).splitlines()
    csr_id, _ = out.split()
    int(csr_id)
    self._runClient(
      '--user-key', user_key_path,
      '--sign-csr-with', csr_id, requested_csr_path,
    )
    self._runClient(
      '--get-crt', csr_id, key_path2,
    )
    checkCRT(key_path2)

  def testCACertRenewal(self):
    """
    Exercise CA certificate rollout procedure.
    """
    user_key_path = self._createFirstUser()
    cau_crt, = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_user_ca_crt)
    ]
    self._stopServer()
    # CA expires in 100 days: longer than one certificate life,
    # but shorter than two. A new CA must be generated and distributed,
    # but not used for new signatures yet.
    new_cau_crt_pem = self._setCACertificateRemainingLifeTime(
      'user',
      cau_crt.serial_number,
      datetime.timedelta(100, 0),
    )
    # As we will use this crt as trust anchor, we must make the client believe
    # it knew it all along.
1424
    with open(self._client_user_ca_crt, 'wb') as client_user_ca_crt_file:
Vincent Pelletier's avatar
Vincent Pelletier committed
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
      client_user_ca_crt_file.write(new_cau_crt_pem)
    self._startServer()
    new_user_key = self._createAndApproveCertificate(
      user_key_path,
      'user',
    )
    # Must not raise: we are signed with the "old" ca.
    utils.load_certificate(
      utils.getCert(new_user_key),
      [cau_crt],
      None,
    )
    # We must now know the new CA
    cau_crt_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_user_ca_crt)
    ]
    new_cau_crt, = [
      x for x in cau_crt_list
      if x.serial_number != cau_crt.serial_number
    ]
    self._stopServer()
    # New CA now exists for 100 days: longer than one certificate life.
    # It may (must) be used for new signatures.
    self._setCACertificateRemainingLifeTime(
      'user',
      new_cau_crt.serial_number,
      new_cau_crt.not_valid_after - new_cau_crt.not_valid_before -
      datetime.timedelta(100, 0),
    )
    self._startServer()
    self._runClient(
      '--mode', 'user',
      # 100 days is longer than certificate life, so it will be immediately
      # renewed.
      '--threshold', '100',
      '--renew-crt', new_user_key, '',
    )
    self.assertRaises(
      exceptions.CertificateVerificationError,
      utils.load_certificate,
      utils.getCert(new_user_key),
      [cau_crt],
      None,
    )
    utils.load_certificate(
      utils.getCert(new_user_key),
      cau_crt_list,
      None,
    )

  def testCaucasedCertRenewal(self):
    """
    Exercise caucased internal certificate renewal procedure.
    """
    user_key_path = self._createFirstUser()
    self._stopServer()
    # If server certificate is deleted, it gets re-created, even it CAS
    # reached its certificate auto-approval limit.
    os.unlink(self._server_key)
    self._startServer()
1486
    if not retry(lambda: os.path.exists(self._server_key)): # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
      raise AssertionError('%r was not recreated within 1 second' % (
        self._server_key,
      ))
    # But user still trusts the server
    self._runClient(
      '--mode', 'user',
      # 100 days is longer than certificate life, so it will be immediately
      # renewed.
      '--threshold', '100',
      '--renew-crt', user_key_path, '',
    )
    # Server certificate will expire in 20 days, the key must be renewed
1499 1500
    # (but we have to peek at HTTP CAS private key, cover your eyes)
    (http_cas_key, ), = sqlite3.connect(
Vincent Pelletier's avatar
Vincent Pelletier committed
1501 1502
      self._server_db,
    ).cursor().execute(
1503
      'SELECT key FROM http_casca',
Vincent Pelletier's avatar
Vincent Pelletier committed
1504 1505 1506
    ).fetchall()

    self._stopServer()
1507
    crt_pem, key_pem, ca_crt_pem = utils.getCertKeyAndCACert(
Vincent Pelletier's avatar
Vincent Pelletier committed
1508
      self._server_key,
1509
      crl=None,
Vincent Pelletier's avatar
Vincent Pelletier committed
1510
    )
1511
    with open(self._server_key, 'wb') as server_key_file:
Vincent Pelletier's avatar
Vincent Pelletier committed
1512 1513 1514
      server_key_file.write(key_pem)
      server_key_file.write(utils.dump_certificate(
        self._setCertificateRemainingLifeTime(
1515
          key=utils.load_privatekey(utils.toBytes(http_cas_key)),
Vincent Pelletier's avatar
Vincent Pelletier committed
1516 1517 1518
          crt=utils.load_certificate(
            crt_pem,
            [
1519
              utils.load_ca_certificate(ca_crt_pem),
Vincent Pelletier's avatar
Vincent Pelletier committed
1520 1521 1522 1523 1524 1525
            ],
            None,
          ),
          delta=datetime.timedelta(20, 0)
        )
      ))
1526
      server_key_file.write(ca_crt_pem)
1527
    def readServerKey():
1528 1529 1530
      """
      Read server key from file.
      """
1531 1532 1533
      with open(self._server_key, 'rb') as server_key_file:
        return server_key_file.read()
    reference_server_key = readServerKey()
Vincent Pelletier's avatar
Vincent Pelletier committed
1534 1535
    self._startServer()
    if not retry(
1536
      lambda: readServerKey() != reference_server_key,
1537
    ): # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
      raise AssertionError('Server did not renew its key pair within 1 second')
    # But user still trusts the server
    self._runClient(
      '--mode', 'user',
      # 100 days is longer than certificate life, so it will be immediately
      # renewed.
      '--threshold', '100',
      '--renew-crt', user_key_path, '',
    )

1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
  def testCORSTokenManager(self):
    """
    Test key expiration and onNewKey invocation.
    """
    new_key_list = []
    old_key_value = '\x00' * 32
    wsgi.CORSTokenManager(
      secret_list=(
        # A secret which is still valid, but old enough to not be used.
        (time.time() + A_YEAR_IN_SECONDS // 2 - 86400, old_key_value),
      ),
      onNewKey=new_key_list.append,
    ).sign('')
    # pylint: disable=unbalanced-tuple-unpacking
    ((_, old_key), (_, _)), = new_key_list
    # pylint: enable=unbalanced-tuple-unpacking
    self.assertEqual(old_key, old_key_value)

Vincent Pelletier's avatar
Vincent Pelletier committed
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
  def testWSGI(self):
    """
    Test wsgi class reaction to malformed requests.

    For tests which are not accessible through the client module (as it tries
    to only produce valid requests).
    """
    self._runClient('--mode', 'user', '--update-user')
    cau_list = [
      utils.load_ca_certificate(x)
      for x in utils.getCertList(self._client_user_ca_crt)
    ]
1578 1579
    with open(self._client_user_crl, 'rb') as client_user_crl_file:
      cau_crl = client_user_crl_file.read()
Vincent Pelletier's avatar
Vincent Pelletier committed
1580 1581 1582 1583
    class DummyCAU(object):
      """
      Mock CAU.
      """
1584
      digest_list = ['sha256']
1585 1586 1587

      @staticmethod
      def getCACertificateList():
Vincent Pelletier's avatar
Vincent Pelletier committed
1588 1589 1590 1591 1592
        """
        Return cau ca list.
        """
        return cau_list

1593 1594 1595 1596 1597
      @staticmethod
      def getCACertificate():
        """
        Return a dummy string as CA certificate
        """
1598
        return b'notreallyPEM'
1599

1600 1601
      @staticmethod
      def getCertificateRevocationList():
Vincent Pelletier's avatar
Vincent Pelletier committed
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
        """
        Return cau crl.
        """
        return cau_crl

      @staticmethod
      def appendCertificateSigningRequest(_):
        """
        Raise to exercise the "unexpected exception" code path in WSGI.
        """
        raise ValueError('Some generic exception')

1614
      @staticmethod
1615
      def _placeholder(_): # pragma: no cover
1616 1617 1618 1619 1620 1621 1622 1623 1624
        """
        Placeholder methods, for when method lookup happens before noticing
        issues in the query.
        """
        raise AssertionError('code should fail before actually calling this')

      getCertificateSigningRequest = _placeholder
      getCertificate = _placeholder

1625 1626 1627
    server_name = u'caucase.example.com'
    server_http_port = 8000
    server_https_port = server_http_port + 1
1628 1629 1630
    application = wsgi.Application(
      DummyCAU(),
      None,
1631 1632
      'http://%s:%i' % (server_name, server_http_port),
      'https://%s:%i' % (server_name, server_https_port),
1633 1634
      wsgi.CORSTokenManager(),
    )
Vincent Pelletier's avatar
Vincent Pelletier committed
1635 1636 1637 1638
    def request(environ):
      """
      Non-standard shorthand for invoking the WSGI application.
      """
Vincent Pelletier's avatar
Vincent Pelletier committed
1639
      environ.setdefault('wsgi.errors', self.caucase_test_output)
1640
      environ.setdefault('wsgi.url_scheme', 'http')
1641 1642
      environ.setdefault('SERVER_NAME', server_name)
      environ.setdefault('SERVER_PORT', str(server_http_port))
Vincent Pelletier's avatar
Vincent Pelletier committed
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
      start_response_list = []
      body = list(application(
        environ,
        lambda status, header_list: start_response_list.append(
          (status, header_list),
        ),
      ))
      # pylint: disable=unbalanced-tuple-unpacking
      (status, header_list), = start_response_list
      # pylint: enable=unbalanced-tuple-unpacking
      status, reason = status.split(' ', 1)
1654 1655 1656 1657 1658
      header_dict = {}
      for key, value in header_list:
        if key in header_dict: # pragma: no cover
          value = header_dict[key] + ',' + value
        header_dict[key] = value
1659
      return int(status), reason, header_dict, b''.join(body)
1660
    UNAUTHORISED_STATUS = 401
Vincent Pelletier's avatar
Vincent Pelletier committed
1661

1662 1663 1664 1665 1666 1667 1668 1669
    HATEOAS_HTTP_PREFIX = u"http://%s:%i/base/path" % (
      server_name,
      server_http_port,
    )
    HATEOAS_HTTPS_PREFIX = u"https://%s:%i/base/path" % (
      server_name,
      server_https_port,
    )
1670
    status, _, header_dict, body = request({
1671 1672 1673 1674
      'SCRIPT_NAME': '/base/path',
      'REQUEST_METHOD': 'GET',
    })
    self.maxDiff = None
1675 1676 1677
    self.assertEqual(status, 200)
    self.assertEqual(header_dict['Content-Type'], 'application/hal+json')
    self.assertEqual(json.loads(body), {
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
      u"_links": {
        u"getCAUHAL": {
          u"href": HATEOAS_HTTP_PREFIX + u"/cau",
          u"title": u"cau",
        },
        u"self": {
          u"href": HATEOAS_HTTP_PREFIX,
        },
        u"getCASHAL": {
          u"href": HATEOAS_HTTP_PREFIX + u"/cas",
          u"title": u"cas",
        },
      },
    })
1692
    status, _, header_dict, body = request({
1693 1694 1695 1696
      'SCRIPT_NAME': '/base/path',
      'PATH_INFO': '/cau/',
      'REQUEST_METHOD': 'GET',
    })
1697 1698 1699
    self.assertEqual(status, 200)
    self.assertEqual(header_dict['Content-Type'], 'application/hal+json')
    self.assertEqual(json.loads(body), {
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
      u"_actions": {
        u"createCertificate": {
          u"href": HATEOAS_HTTPS_PREFIX + u"/cau/crt/{+crt_id}",
          u"method": u"PUT",
          u"templated": True,
          u"title": u"Accept pending certificate signing request",
        },
        u"renewCertificate": {
          u"href": HATEOAS_HTTP_PREFIX + u"/cau/crt/renew",
          u"method": u"PUT",
          u"title": u"Renew a certificate",
        },
        u"revokeCertificate": {
          u"href": HATEOAS_HTTP_PREFIX + u"/cau/crt/revoke",
          u"method": u"PUT",
          u"title": u"Revoke a certificate",
        },
        u"createCertificateSigningRequest": {
          u"href": HATEOAS_HTTP_PREFIX + u"/cau/csr",
          u"method": u"PUT",
          u"title": u"Request a new certificate signature.",
        },
        u"deletePendingCertificateRequest": {
          u"href": HATEOAS_HTTPS_PREFIX + u"/cau/csr/{+csr_id}",
          u"method": u"DELETE",
          u"templated": True,
          u"title": u"Reject a pending certificate signing request.",
        },
      },
      u"_links": {
        u"getCertificateRevocationList": {
          u"href": HATEOAS_HTTP_PREFIX + u"/cau/crl",
          u"title": u"Retrieve latest certificate revocation list.",
        },
        u"getCACertificate": {
          u"href": HATEOAS_HTTP_PREFIX + u"/cau/crt/ca.crt.pem",
          u"title": u"Retrieve current CA certificate.",
        },
        u"self": {
          u"href": HATEOAS_HTTP_PREFIX + u"/cau",
        },
        u"getCertificate": {
          u"href": HATEOAS_HTTP_PREFIX + u"/cau/crt/{+csr_id}",
          u"templated": True,
          u"title": u"Retrieve a signed certificate.",
        },
        u"getPendingCertificateRequestList": {
          u"href": HATEOAS_HTTPS_PREFIX + u"/cau/csr",
          u"title": u"List pending certificate signing requests.",
        },
        u"getCACertificateChain": {
          u"href": HATEOAS_HTTP_PREFIX + u"/cau/crt/ca.crt.json",
          u"title": u"Retrieve current CA certificate trust chain.",
        },
        u"getCertificateSigningRequest": {
          u"href": HATEOAS_HTTP_PREFIX + u"/cau/csr/{+csr_id}",
          u"templated": True,
          u"title": u"Retrieve a pending certificate signing request.",
        },
        u"home": {
          u"href": HATEOAS_HTTP_PREFIX,
        },
      },
    })
Vincent Pelletier's avatar
Vincent Pelletier committed
1764 1765
    self.assertEqual(request({
      'PATH_INFO': '/foo/bar',
1766
      'REQUEST_METHOD': 'GET',
Vincent Pelletier's avatar
Vincent Pelletier committed
1767 1768 1769
    })[0], 404)
    self.assertEqual(request({
      'PATH_INFO': '/cau/__init__',
1770
      'REQUEST_METHOD': 'GET',
Vincent Pelletier's avatar
Vincent Pelletier committed
1771 1772 1773
    })[0], 404)
    self.assertEqual(request({
      'PATH_INFO': '/cau/does_not_exist',
1774
      'REQUEST_METHOD': 'GET',
Vincent Pelletier's avatar
Vincent Pelletier committed
1775 1776 1777 1778 1779 1780
    })[0], 404)

    self.assertEqual(request({
      'PATH_INFO': '/cau/crl/123',
      'REQUEST_METHOD': 'GET',
    })[0], 404)
1781

1782
    min_date = int(time.time())
1783
    status, _, header_dict, _ = request({
Vincent Pelletier's avatar
Vincent Pelletier committed
1784 1785
      'PATH_INFO': '/cau/crl',
      'REQUEST_METHOD': 'PUT',
1786
    })
1787
    max_date = int(time.time())
1788 1789 1790 1791 1792 1793 1794 1795
    self.assertEqual(status, 405)
    self.assertItemsEqual(
      [x.strip() for x in header_dict['Allow'].split(',')],
      ['GET', 'OPTIONS'],
    )
    response_date = utils.IMFfixdate2timestamp(header_dict['Date'])
    self.assertGreaterEqual(response_date, min_date)
    self.assertLessEqual(response_date, max_date)
Vincent Pelletier's avatar
Vincent Pelletier committed
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 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

    self.assertEqual(request({
      'PATH_INFO': '/cau/csr/123/456',
      'REQUEST_METHOD': 'GET',
    })[0], 404)
    self.assertEqual(request({
      'PATH_INFO': '/cau/csr/123',
      'REQUEST_METHOD': 'POST',
    })[0], 405)
    self.assertEqual(request({
      'PATH_INFO': '/cau/csr/a',
      'REQUEST_METHOD': 'GET',
    })[0], 400)
    self.assertEqual(request({
      'PATH_INFO': '/cau/csr',
      'REQUEST_METHOD': 'GET',
    })[0], UNAUTHORISED_STATUS)
    self.assertEqual(request({
      'PATH_INFO': '/cau/csr/123',
      'REQUEST_METHOD': 'PUT',
    })[0], 404)
    self.assertEqual(request({
      'PATH_INFO': '/cau/csr',
      'REQUEST_METHOD': 'PUT',
      'wsgi.input': StringIO(),
    })[0], 500)
    self.assertEqual(request({
      'PATH_INFO': '/cau/csr',
      'REQUEST_METHOD': 'DELETE',
    })[0], 404)
    self.assertEqual(request({
      'PATH_INFO': '/cau/csr/123/456',
      'REQUEST_METHOD': 'DELETE',
    })[0], 404)
    self.assertEqual(request({
      'PATH_INFO': '/cau/csr/123',
      'REQUEST_METHOD': 'DELETE',
    })[0], UNAUTHORISED_STATUS)

    self.assertEqual(request({
      'PATH_INFO': '/cau/crt',
      'REQUEST_METHOD': 'GET',
    })[0], 404)
    self.assertEqual(request({
      'PATH_INFO': '/cau/crt/123/456',
      'REQUEST_METHOD': 'GET',
    })[0], 404)
    self.assertEqual(request({
      'PATH_INFO': '/cau/crt/a',
      'REQUEST_METHOD': 'GET',
    })[0], 400)
    self.assertEqual(request({
      'PATH_INFO': '/cau/crt/renew',
      'REQUEST_METHOD': 'PUT',
      'CONTENT_TYPE': 'text/plain',
    })[0], 400)
    self.assertEqual(request({
      'PATH_INFO': '/cau/crt/renew',
      'REQUEST_METHOD': 'PUT',
      'CONTENT_TYPE': 'application/json',
      'CONTENT_LENGTH': 'a',
1857
      'wsgi.input': StringIO(),
Vincent Pelletier's avatar
Vincent Pelletier committed
1858 1859 1860 1861 1862
    })[0], 400)
    self.assertEqual(request({
      'PATH_INFO': '/cau/crt/renew',
      'REQUEST_METHOD': 'PUT',
      'CONTENT_TYPE': 'application/json',
1863 1864
      'CONTENT_LENGTH': str(wsgi.MAX_BODY_LENGTH + 1),
      'wsgi.input': StringIO(),
Vincent Pelletier's avatar
Vincent Pelletier committed
1865 1866 1867 1868 1869
    })[0], 413)
    self.assertEqual(request({
      'PATH_INFO': '/cau/crt/renew',
      'REQUEST_METHOD': 'PUT',
      'CONTENT_TYPE': 'application/json',
1870
      'wsgi.input': StringIO(u'{'),
Vincent Pelletier's avatar
Vincent Pelletier committed
1871 1872 1873 1874 1875
    })[0], 400)
    self.assertEqual(request({
      'PATH_INFO': '/cau/crt/revoke',
      'REQUEST_METHOD': 'PUT',
      'CONTENT_TYPE': 'application/json',
1876
      'wsgi.input': StringIO(u'{"digest": null}'),
Vincent Pelletier's avatar
Vincent Pelletier committed
1877
    })[0], UNAUTHORISED_STATUS)
1878 1879 1880 1881
    self.assertEqual(request({
      'PATH_INFO': '/cau/crt/revoke',
      'REQUEST_METHOD': 'PUT',
      'CONTENT_TYPE': 'application/json',
1882
      'wsgi.input': StringIO(u'{"digest":"sha256","payload":""}'),
1883
    })[0], 400)
Vincent Pelletier's avatar
Vincent Pelletier committed
1884 1885 1886 1887
    self.assertEqual(request({
      'PATH_INFO': '/cau/crt/a',
      'REQUEST_METHOD': 'PUT',
      'CONTENT_TYPE': 'text/plain',
1888
      'wsgi.input': StringIO(u''),
Vincent Pelletier's avatar
Vincent Pelletier committed
1889 1890 1891 1892 1893
    })[0], 400)
    self.assertEqual(request({
      'PATH_INFO': '/cau/crt/123',
      'REQUEST_METHOD': 'PUT',
      'CONTENT_TYPE': 'text/plain',
1894
      'wsgi.input': StringIO(u''),
Vincent Pelletier's avatar
Vincent Pelletier committed
1895 1896 1897 1898 1899
    })[0], UNAUTHORISED_STATUS)
    self.assertEqual(request({
      'PATH_INFO': '/cau/crt/123',
      'REQUEST_METHOD': 'PUT',
      'CONTENT_TYPE': 'text/plain',
1900
      'wsgi.input': StringIO(u'foo'),
Vincent Pelletier's avatar
Vincent Pelletier committed
1901 1902 1903 1904 1905 1906
    })[0], 400)
    self.assertEqual(request({
      'PATH_INFO': '/cau/crt/123',
      'REQUEST_METHOD': 'POST',
    })[0], 405)

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
    # CORS
    cross_origin = 'https://example.com:443'
    # Non-CORS OPTIONS: success without CORS headers
    status, _, header_dict, _ = request({
      'PATH_INFO': '/',
      'REQUEST_METHOD': 'OPTIONS',
    })
    self.assertEqual(status, 204)
    self.assertNotIn(
      'Access-Control-Allow-Credentials',
      header_dict,
    )
    self.assertNotIn(
      'Access-Control-Allow-Origin',
      header_dict,
    )
    self.assertNotIn(
      'Vary',
      header_dict,
    )
    self.assertNotIn(
      'Access-Control-Allow-Methods',
      header_dict,
    )
    self.assertNotIn(
      'Access-Control-Allow-Headers',
      header_dict,
    )
    # All origins can access /
    status, _, header_dict, _ = request({
      'PATH_INFO': '/',
      'REQUEST_METHOD': 'OPTIONS',
      'HTTP_ORIGIN': cross_origin,
    })
    self.assertEqual(status, 204)
    self.assertEqual(
      header_dict['Access-Control-Allow-Credentials'],
      'true',
    )
    self.assertEqual(
      header_dict['Access-Control-Allow-Origin'],
      cross_origin,
    )
    self.assertEqual(
      header_dict['Vary'],
      'Origin',
    )
    self.assertItemsEqual(
      [
        x.strip()
        for x in header_dict['Access-Control-Allow-Methods'].split(',')
      ],
      ['GET', 'OPTIONS'],
    )
    self.assertItemsEqual(
      [
        x.strip()
        for x in header_dict['Access-Control-Allow-Headers'].split(',')
      ],
      [
        'Content-Type',
        'User-Agent',
      ],
    )
    # User confirmation is needed to GET /cau/crt/ca.crt.pem
    # ... OPTIONS succeeds and lists allowed methods
    status, _, header_dict, _ = request({
      'PATH_INFO': '/cau/crt/ca.crt.pem',
      'REQUEST_METHOD': 'OPTIONS',
      'HTTP_ORIGIN': cross_origin,
    })
    self.assertEqual(status, 204)
    self.assertItemsEqual(
      ['GET', 'OPTIONS'],
      [
        x.strip()
        for x in header_dict['Access-Control-Allow-Methods'].split(',')
      ],
    )
    # ... calling PUT tells Unauthorised with proper header
    status, _, header_dict, _ = request({
      'PATH_INFO': '/cau/crt/ca.crt.pem',
      'REQUEST_METHOD': 'GET',
      'HTTP_ORIGIN': cross_origin,
    })
    self.assertEqual(status, UNAUTHORISED_STATUS)
    self.assertEqual(
      header_dict['WWW-Authenticate'],
      'cors url=' + quote(
1996
          'https://%s:%i/cors?' % (server_name, server_https_port) +
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 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
        urlencode([('origin', cross_origin)]) +
        '{&return}',
      ),
    )
    # ... it also fails cleanly when called with an invalid cookie
    self.assertEqual(
      request({
        'PATH_INFO': '/cau/crt/ca.crt.pem',
        'REQUEST_METHOD': 'GET',
        'HTTP_ORIGIN': cross_origin,
        'HTTP_COOKIE': 'cors=a',
      })[0],
      UNAUTHORISED_STATUS,
    )
    return_url = 'http://example.com/foo?d=<script>alert("boo !")</script>'
    # POST to /cors with origin is forbidden
    self.assertEqual(
      request({
        'wsgi.url_scheme': 'https',
        'PATH_INFO': '/cors',
        'QUERY_STRING': urlencode((
          ('origin', cross_origin),
          ('return', return_url),
        )),
        'REQUEST_METHOD': 'POST',
        'HTTP_ORIGIN': cross_origin,
      })[0],
      403,
    )
    # GET /cors on http redirects to https
    status, _, header_dict, _ = request({
      'wsgi.url_scheme': 'http',
      'PATH_INFO': '/cors',
      'QUERY_STRING': urlencode((
        ('origin', cross_origin),
        ('return', return_url),
      )),
      'REQUEST_METHOD': 'GET',
    })
    self.assertEqual(status, 302)
    self.assertTrue(
      header_dict['Location'].startswith('https://'),
      header_dict['Location'],
    )
    # GET /cors with missing arguments (here, "return") fails visibly
    self.assertEqual(
      request({
        'wsgi.url_scheme': 'https',
        'PATH_INFO': '/cors',
        'QUERY_STRING': urlencode((
          ('origin', cross_origin),
        )),
        'REQUEST_METHOD': 'GET',
      })[0],
      400,
    )
    # GET /cors return an html page with anti-clickjacking headers
    status, _, header_dict, body = request({
      'wsgi.url_scheme': 'https',
      'PATH_INFO': '/cors',
      'QUERY_STRING': urlencode((
        ('origin', cross_origin),
        ('return', return_url),
      )),
      'REQUEST_METHOD': 'GET',
    })
    self.assertEqual(status, 200)
    self.assertEqual(header_dict['Content-Type'], 'text/html')
    self.assertEqual(header_dict['X-Frame-Options'], 'DENY')
    self.assertEqual(
      header_dict['Content-Security-Policy'],
      "frame-ancestors 'none'",
    )
2070
    assertHTMLNoScriptAlert(utils.toUnicode(body))
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
    # POST /cors sets cookie
    def getCORSPostEnvironment(kw=(), input_dict=(
      ('return_to', return_url),
      ('origin', cross_origin),
      ('grant', '1'),
    )):
      """
      Build "request"'s "environ" argument for CORS requests.
      """
      base_request_reader_dict = {
        'wsgi.url_scheme': 'https',
        'PATH_INFO': '/cors',
        'REQUEST_METHOD': 'POST',
        'CONTENT_TYPE': 'application/x-www-form-urlencoded',
2085
        'wsgi.input': StringIO(utils.toUnicode(urlencode(input_dict))),
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
      }
      base_request_reader_dict.update(kw)
      return base_request_reader_dict
    def getCORSCookie(value):
      """
      Build CORS cookie with custome value
      """
      return SimpleCookie({'cors': json.dumps(value)})['cors'].OutputString()
    self.assertEqual(
      request(getCORSPostEnvironment(kw={'wsgi.url_scheme': 'http'}))[0],
      404,
    )
    self.assertEqual(
      request(getCORSPostEnvironment(kw={'CONTENT_TYPE': 'text/plain'}))[0],
      400,
    )
    self.assertEqual(
      request(getCORSPostEnvironment(
        input_dict={
          'return_to': return_url,
          'origin': cross_origin,
          # Missing "grant"
        },
      ))[0],
      400,
    )
    self.assertEqual(
      request(getCORSPostEnvironment(
        input_dict={
          'return_to': return_url,
          'origin': cross_origin,
          'grant': 'a', # Non-integer "grant"
        },
      ))[0],
      400,
    )
    status, _, header_dict, _ = request(getCORSPostEnvironment())
    self.assertEqual(status, 302)
    self.assertEqual(header_dict['Location'], return_url)
    good_token = json.loads(
      SimpleCookie(header_dict['Set-Cookie'])['cors'].value,
    )[cross_origin]
    # Recycling a valid token for another domain does not grant access
    status, _, header_dict, _ = request(getCORSPostEnvironment(
      input_dict={
        'return_to': 'http://example.org',
        'origin': 'http://example.org:80',
        'grant': '1',
      }
    ))
    self.assertEqual(status, 302)
    bad_token = json.loads(
      SimpleCookie(header_dict['Set-Cookie'])['cors'].value,
    )['http://example.org:80']
    status, _, header_dict, _ = request({
      'PATH_INFO': '/cau/crt/ca.crt.pem',
      'REQUEST_METHOD': 'GET',
      'HTTP_ORIGIN': cross_origin,
      'HTTP_COOKIE': getCORSCookie({
        cross_origin: bad_token,
      }),
    })
    self.assertEqual(status, UNAUTHORISED_STATUS)
    self.assertEqual(
      SimpleCookie(header_dict['Set-Cookie'])['cors'].value,
      '{}',
    )
    # Accessing with invalid token fails
    head, body, _ = good_token.split('.')
    _, _, signature = bad_token.split('.')
    status, _, header_dict, _ = request({
      'PATH_INFO': '/cau/crt/ca.crt.pem',
      'REQUEST_METHOD': 'GET',
      'HTTP_ORIGIN': cross_origin,
      'HTTP_COOKIE': getCORSCookie({
        cross_origin: '%s.%s.%s' % (
          head,
          body,
          signature,
        ),
      }),
    })
    self.assertEqual(status, UNAUTHORISED_STATUS)
    self.assertEqual(
      SimpleCookie(header_dict['Set-Cookie'])['cors'].value,
      '{}',
    )
    # Accessing with valid token works
    status, _, header_dict, _ = request({
      'PATH_INFO': '/cau/crt/ca.crt.pem',
      'REQUEST_METHOD': 'GET',
      'HTTP_ORIGIN': cross_origin,
      'HTTP_COOKIE': getCORSCookie({
        cross_origin: good_token,
      }),
    })
    self.assertEqual(status, 200)
    self.assertItemsEqual(
      [
        x.strip()
        for x in header_dict[
          'Access-Control-Expose-Headers'
        ].split(',')
      ],
      [
        'Location',
        'WWW-Authenticate',
      ],
    )

Vincent Pelletier's avatar
Vincent Pelletier committed
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
  def testProbe(self):
    """
    Exercise caucase-probe command.
    """
    cli.probe([self._caucase_url])

  def testBackup(self):
    """
    Exercise backup generation and restoration.
    """
    backup_glob = os.path.join(self._server_backup_path, '*.sql.caucased')
    user_key_path = self._createFirstUser()
    user2_key_path = self._createAndApproveCertificate(
      user_key_path,
      'user',
    )
    # user2 sacrifice their private key, and prepare its replacement
    basename = self._getBaseName()
    user2_new_key_path = self._createPrivateKey(basename)
    user2_new_csr_path = self._createBasicCSR(basename, user2_new_key_path)

    # Restart caucased to not have to wait for next backup deadline
    self._stopServer()
    # Note: backup could have triggered between first and second user's key
    # creation. We need it to be signed by both keys, so delete any backup file
    # which would exist at this point.
2222
    for backup_path in glob.glob(backup_glob): # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
2223 2224 2225 2226 2227 2228 2229
      os.unlink(backup_path)
    before_backup = list(SQLite3Storage(
      self._server_db,
      table_prefix='cau',
    ).dumpIterator())
    self._startServer('--backup-directory', self._server_backup_path)
    backup_path_list = retry(lambda: glob.glob(backup_glob))
2230
    if not backup_path_list: # pragma: no cover
Vincent Pelletier's avatar
Vincent Pelletier committed
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2