diff --git a/vaultlocker/dmcrypt.py b/vaultlocker/dmcrypt.py index 97e19d1..b827baf 100644 --- a/vaultlocker/dmcrypt.py +++ b/vaultlocker/dmcrypt.py @@ -22,6 +22,12 @@ KEY_SIZE = 4096 +#: Maximum time to wait for a cryptsetup command. +CRYPTSETUP_TIMEOUT_SECONDS = 300 + +#: Maximum time to wait for a udevadm command. +UDEVADM_TIMEOUT_SECONDS = 60 + def _key_bytes(key): """Normalize key material for subprocess input. @@ -68,6 +74,7 @@ def luks_format(key, device, uuid): subprocess.check_output( command, input=_key_bytes(key), + timeout=CRYPTSETUP_TIMEOUT_SECONDS, ) @@ -99,6 +106,7 @@ def luks_open(key, uuid, device=None): subprocess.check_output( command, input=_key_bytes(key), + timeout=CRYPTSETUP_TIMEOUT_SECONDS, ) return handle @@ -115,7 +123,10 @@ def luks_uuid(device): 'luksUUID', device, ] - return subprocess.check_output(command).decode('utf-8').strip() + return subprocess.check_output( + command, + timeout=CRYPTSETUP_TIMEOUT_SECONDS, + ).decode('utf-8').strip() def luks_test_key(key, device): @@ -141,8 +152,13 @@ def luks_test_key(key, device): subprocess.check_output( command, input=_key_bytes(key), + timeout=CRYPTSETUP_TIMEOUT_SECONDS, ) except subprocess.CalledProcessError as exc: + # cryptsetup returns exit code 2 for incorrect passphrase + # with --test-passphrase, this confirms that the given key + # does not unlock the device. Other exit codes are inconclusive + # and should be raised. if exc.returncode == 2: return False raise @@ -183,6 +199,7 @@ def luks_add_key(existing_key, new_key, device): command, input=_key_bytes(new_key), pass_fds=(existing_key_fd,), + timeout=CRYPTSETUP_TIMEOUT_SECONDS, ) finally: os.close(existing_key_fd) @@ -203,7 +220,10 @@ def udevadm_rescan(device): '--name-match={}'.format(device), '--action=add' ] - subprocess.check_output(command) + subprocess.check_output( + command, + timeout=UDEVADM_TIMEOUT_SECONDS, + ) def udevadm_settle(uuid): @@ -220,4 +240,7 @@ def udevadm_settle(uuid): 'settle', '--exit-if-exists=/dev/disk/by-uuid/{}'.format(uuid), ] - subprocess.check_output(command) + subprocess.check_output( + command, + timeout=UDEVADM_TIMEOUT_SECONDS, + ) diff --git a/vaultlocker/exceptions.py b/vaultlocker/exceptions.py index ceb1cd5..f25893b 100644 --- a/vaultlocker/exceptions.py +++ b/vaultlocker/exceptions.py @@ -12,8 +12,11 @@ # License for the specific language governing permissions and limitations # under the License. +"""Errors returned as controlled command failures.""" + class VaultlockerException(Exception): + """Base class for controlled vaultlocker errors.""" def __init__(self, *args): if args: @@ -25,7 +28,12 @@ def __str__(self): return self.message +class ConfigurationError(VaultlockerException): + """The vaultlocker configuration is missing or invalid.""" + + class VaultWriteError(VaultlockerException): + """Writing a key to Vault failed.""" def __init__(self, path, error): super().__init__("Can't write to vault at path {}, error: {}".format( @@ -33,20 +41,15 @@ def __init__(self, path, error): class VaultReadError(VaultlockerException): + """Reading a key back from Vault failed.""" def __init__(self, path, error): super().__init__("Can't read vault at path {}, error: {}".format( path, error)) -class VaultDeleteError(VaultlockerException): - - def __init__(self, path, error): - super().__init__("Can't delete vault key at path {}, error: {}".format( - path, error)) - - class VaultKeyMismatch(VaultlockerException): + """A key read back from Vault does not match what was written.""" def __init__(self, path): super().__init__( @@ -54,8 +57,58 @@ def __init__(self, path): path)) +class VaultConnectionError(VaultlockerException): + """Vault was unavailable or authentication failed after retries.""" + + def __init__(self, error): + super().__init__("Unable to connect to Vault: {}".format(error)) + + +class ManagedKeyInvalidError(VaultlockerException): + """The managed key stored in Vault is missing or malformed.""" + + def __init__(self, path): + super().__init__( + "Vault secret at {} does not contain dmcrypt_key".format(path) + ) + + +class ManagedKeyNotFoundError(VaultlockerException): + """No Vault key exists at the expected path.""" + + def __init__(self, path): + super().__init__( + 'No vaultlocker-managed key found at {}'.format(path) + ) + + +class ExistingKeyInvalidError(VaultlockerException): + """Existing LUKS credential is missing, unreadable, or wrong.""" + + class LUKSFailure(VaultlockerException): + """Base class for all cryptsetup/LUKS-related errors.""" def __init__(self, block_device, error): super().__init__("Can't operate on {}. Error: {}".format( block_device, error)) + + +class LuksValidationError(LUKSFailure): + """The device's LUKS state could not be verified.""" + + +class LuksFormatError(LUKSFailure): + """Formatting a LUKS device failed.""" + + +class LuksAddKeyError(LUKSFailure): + """Adding a LUKS key failed.""" + + +class MapperOpenError(LUKSFailure): + """Opening the dm-crypt mapper failed.""" + + +class BootConfigError(LUKSFailure): + """Registering the boot-time unlock mechanism failed.""" diff --git a/vaultlocker/exit_codes.py b/vaultlocker/exit_codes.py new file mode 100644 index 0000000..3df8639 --- /dev/null +++ b/vaultlocker/exit_codes.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- + +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +"""Process exit codes for the vaultlocker CLI.""" + +from enum import IntEnum + + +class ExitCode(IntEnum): + """Exit codes returned by the vaultlocker command.""" + + SUCCESS = 0 + UNEXPECTED_FAILURE = 1 + + # argparse uses exit code 2 for invalid command-line arguments. + HANDLED_FAILURE = 3 diff --git a/vaultlocker/shell.py b/vaultlocker/shell.py index 2b5b0ca..f31639c 100644 --- a/vaultlocker/shell.py +++ b/vaultlocker/shell.py @@ -16,6 +16,7 @@ import configparser import functools import getpass +import json import logging import os import platform @@ -30,12 +31,15 @@ from vaultlocker import boot_unlock from vaultlocker import dmcrypt from vaultlocker import exceptions +from vaultlocker.exit_codes import ExitCode from vaultlocker import vault logger = logging.getLogger(__name__) DEFAULT_CONF_FILE = '/etc/vaultlocker/vaultlocker.conf' +REQUIRED_VAULT_SETTINGS = ('url', 'approle', 'secret_id', 'backend') + def _vault_client(config): """Helper wrapper to create Vault Client @@ -59,11 +63,11 @@ def _get_kv_version(config): :param config: configparser object of vaultlocker config :returns: str: KV version ('1' or '2') - :raises ValueError: If the configured value is not '1' or '2'. + :raises exceptions.ConfigurationError: if the value is not '1' or '2' """ version = config.get('vault', 'kv_version', fallback=vault.KV_VERSION_1) if version not in (vault.KV_VERSION_1, vault.KV_VERSION_2): - raise ValueError( + raise exceptions.ConfigurationError( "Invalid kv_version '{}' in vaultlocker config; " "must be '{}' or '{}'".format( version, vault.KV_VERSION_1, vault.KV_VERSION_2 @@ -180,7 +184,12 @@ def _store_and_validate_key(store, path, key): read_error, ) - if key != stored_data['dmcrypt_key']: + stored_key = stored_data.get('dmcrypt_key') if isinstance( + stored_data, dict) else None + if not stored_key: + raise exceptions.ManagedKeyInvalidError(vault_path) + + if key != stored_key: raise exceptions.VaultKeyMismatch(vault_path) @@ -191,10 +200,19 @@ def _read_existing_key(key_file): :param: key_file: file path, or None to use standard input. :returns: bytes containing the existing key. + :raises exceptions.ExistingKeyInvalidError: if the key file cannot be + read, or the resulting key material is empty. """ if key_file: - with open(key_file, 'rb') as key_source: - key = key_source.read() + try: + with open(key_file, 'rb') as key_source: + key = key_source.read() + except OSError as read_error: + raise exceptions.ExistingKeyInvalidError( + 'Unable to read existing key file {}: {}'.format( + key_file, read_error, + ) + ) elif sys.stdin.isatty(): key = getpass.getpass( 'Existing LUKS passphrase: ' @@ -203,167 +221,335 @@ def _read_existing_key(key_file): key = sys.stdin.buffer.read() if not key: - raise ValueError('Existing LUKS key cannot be empty') + raise exceptions.ExistingKeyInvalidError( + 'Existing LUKS key cannot be empty' + ) return key -def _get_or_create_managed_key(store, path): - """Return an existing managed key or create one and store it in Vault. +def _mapper_path(block_uuid): + """Return the dm-crypt mapper path for a LUKS UUID.""" + return '/dev/mapper/crypt-{}'.format(block_uuid) - :param: store: Vault key-value store object. - :param: path: path to the managed key in Vault. - :returns: managed key as str - """ + +def _by_uuid_path(block_uuid): + """Return the by-UUID path for a LUKS UUID.""" + return '/dev/disk/by-uuid/{}'.format(block_uuid) + + +def _register_boot_unlock(block_device, block_uuid, config_path): + """Register the device for boot-time unlocking.""" try: - stored_data = store.read(path) - except hvac.exceptions.InvalidPath: - key = dmcrypt.generate_key() - _store_and_validate_key(store, path, key) - return key - - if ( - not isinstance(stored_data, dict) or - not stored_data.get('dmcrypt_key') - ): - raise ValueError( - 'Vault secret at {}/{} does not contain dmcrypt_key'.format( - store.mount_point, - path, - ) + boot_unlock.register(block_uuid, config_path) + except (subprocess.CalledProcessError, + subprocess.TimeoutExpired, + OSError) as boot_error: + logger.error( + 'Registering boot unlock for %s failed: %s', + block_uuid, + _subprocess_error_output(boot_error), + ) + raise exceptions.BootConfigError( + block_device, _subprocess_error_output(boot_error), ) - return stored_data['dmcrypt_key'] +def _subprocess_error_output(error): + """Return output from a subprocess error.""" + output = getattr(error, 'output', None) + if output is None: + output = getattr(error, 'stderr', None) + return output if output else str(error) -def _enroll_block_device(args, client, config, existing_key): - """Add a Vault-managed key to an existing LUKS device. - :param: args: argparser generated CLI arguments. - :param: client: hvac.Client for Vault access. - :param: config: configparser object of vaultlocker config. - :param: existing_key: existing key used to unlock the device. - """ - block_device = args.block_device[0] +def _subprocess_error_returncode(error): + """Return a subprocess error's exit code, if available.""" + return getattr(error, 'returncode', None) - try: - block_uuid = dmcrypt.luks_uuid(block_device) - if not dmcrypt.luks_test_key(existing_key, block_device): - raise ValueError( - 'Existing key does not unlock {}'.format(block_device) - ) +# cryptsetup returns 1 when luksUUID finds no LUKS header. +_NO_LUKS_HEADER_EXIT_CODE = 1 + + +def _get_existing_luks_uuid(block_device): + """Return the device UUID, or None when it has no LUKS header.""" + try: + return dmcrypt.luks_uuid(block_device) except subprocess.CalledProcessError as luks_error: - raise exceptions.LUKSFailure( + if luks_error.returncode == _NO_LUKS_HEADER_EXIT_CODE: + return None + raise exceptions.LuksValidationError( + block_device, + 'Unable to determine whether {} already has a LUKS header ' + '(cryptsetup exit code {}): {}'.format( + block_device, + luks_error.returncode, + _subprocess_error_output(luks_error), + ), + ) + except subprocess.TimeoutExpired as luks_error: + raise exceptions.LuksValidationError( block_device, - luks_error.output, + 'Timed out determining whether {} already has a LUKS ' + 'header: {}'.format( + block_device, _subprocess_error_output(luks_error), + ), ) - path = _vault_secret_path(block_uuid, config) - store = _vault_store(client, config) - key = _get_or_create_managed_key(store, path) +def _key_unlocks_device(key, block_device): + """Return whether the key unlocks the device.""" try: - if not dmcrypt.luks_test_key(key, block_device): - dmcrypt.luks_add_key( - existing_key, - key, - block_device, - ) + return dmcrypt.luks_test_key(key, block_device) + except (subprocess.CalledProcessError, + subprocess.TimeoutExpired) as e: + raise exceptions.LuksValidationError( + block_device, + 'Unable to determine whether the key unlocks {}: {}'.format( + block_device, _subprocess_error_output(e), + ), + ) from e - if not dmcrypt.luks_test_key(key, block_device): - raise exceptions.LUKSFailure( - block_device, - 'Vaultlocker managed key unable to unlock the device', - ) - if not _device_exists(block_uuid): +def _read_vault_key(store, path): + """Read a Vault key, or return None when the path does not exist.""" + try: + stored_data = store.read(path) + except hvac.exceptions.InvalidPath: + return None + + key = stored_data.get('dmcrypt_key') if isinstance( + stored_data, dict) else None + if not key: + raise exceptions.ManagedKeyInvalidError( + '{}/{}'.format(store.mount_point, path) + ) + + return key + + +def _ensure_vault_key(store, path, expected_key): + """Ensure Vault has the expected key without overwriting data.""" + current_key = _read_vault_key(store, path) + if current_key is None: + _store_and_validate_key(store, path, expected_key) + return + + if current_key != expected_key: + raise exceptions.VaultKeyMismatch( + '{}/{}'.format(store.mount_point, path) + ) + + +def _open_and_register_device(block_device, block_uuid, key, config_path): + """Open the mapper if needed and register it for boot.""" + if not _device_exists(block_uuid): + try: dmcrypt.luks_open(key, block_uuid, block_device) + except (subprocess.CalledProcessError, + subprocess.TimeoutExpired) as open_error: + raise exceptions.MapperOpenError( + block_device, _subprocess_error_output(open_error), + ) - except subprocess.CalledProcessError as luks_error: - logger.error( - 'LUKS enrollment for %s failed with error code: %s\n' - 'LUKS output: %s', + _register_boot_unlock(block_device, block_uuid, config_path) + + return { + "luks_uuid": block_uuid, + "mapper_path": _mapper_path(block_uuid), + } + + +def _open_existing_managed_device(args, client, config, block_device, + block_uuid): + """Reuse an encrypted device when its Vault key can unlock it.""" + if args.uuid and args.uuid != block_uuid: + raise exceptions.LuksValidationError( block_device, - luks_error.returncode, - luks_error.output, + 'device already contains a LUKS header with UUID {} which does ' + 'not match the requested UUID {}'.format(block_uuid, args.uuid), ) - raise exceptions.LUKSFailure( + + store = _vault_store(client, config) + path = _vault_secret_path(block_uuid, config) + vault_key = _read_vault_key(store, path) + + if vault_key is None: + raise exceptions.LuksValidationError( block_device, - luks_error.output, + 'device already contains a LUKS header but no ' + 'vaultlocker-managed key is present in Vault', ) - boot_unlock.register(block_uuid, args.config) + if not _key_unlocks_device(vault_key, block_device): + raise exceptions.LuksValidationError( + block_device, + 'device already contains a LUKS header but the managed key ' + 'does not unlock it', + ) + return _open_and_register_device( + block_device, block_uuid, vault_key, args.config, + ) -def _encrypt_block_device(args, client, config): - """Encrypt and open a block device - Store the encryption key in Vault before formatting the device. +def _format_completed(block_device, block_uuid, key): + """Check whether a failed or timed-out format completed.""" + try: + current_uuid = dmcrypt.luks_uuid(block_device) + except (subprocess.CalledProcessError, subprocess.TimeoutExpired): + return False - :param: args: argparser generated cli arguments - :param: client: hvac.Client for Vault access - :param: config: configparser object of vaultlocker config - """ - block_device = args.block_device[0] - key = dmcrypt.generate_key() - block_uuid = str(uuid.uuid4()) if not args.uuid else args.uuid + if current_uuid != block_uuid: + return False - path = _vault_secret_path(block_uuid, config) - vault_path = '{}/{}'.format( - _vault_mount_point(config), - path, - ) + return _key_unlocks_device(key, block_device) + + +def _format_device(args, client, config, block_device, block_uuid, key): + """Store the key, format the device, and finish its setup.""" store = _vault_store(client, config) + path = _vault_secret_path(block_uuid, config) - # NOTE: store and validate key before trying to encrypt disk - _store_and_validate_key(store, path, key) + _ensure_vault_key(store, path, key) - # Remove the stored key if formatting fails. try: dmcrypt.luks_format(key, block_device, block_uuid) - except subprocess.CalledProcessError as luks_error: - logger.error( - 'LUKS formatting %s failed with error code: %s\n' - 'LUKS output: %s', - block_device, - luks_error.returncode, - luks_error.output, + except (subprocess.CalledProcessError, + subprocess.TimeoutExpired) as luks_error: + if not _format_completed(block_device, block_uuid, key): + logger.error( + 'LUKS formatting %s failed with error code: %s\n' + 'LUKS output: %s', + block_device, + _subprocess_error_returncode(luks_error), + _subprocess_error_output(luks_error), + ) + raise exceptions.LuksFormatError( + block_device, _subprocess_error_output(luks_error), + ) + logger.warning( + 'cryptsetup luksFormat for %s reported an error (%s) but the ' + 'device now has the expected UUID and key; continuing', + block_device, luks_error, ) - try: - store.delete(path) - except hvac.exceptions.VaultError as del_error: - raise exceptions.VaultDeleteError(vault_path, del_error) - - raise exceptions.LUKSFailure(block_device, luks_error.output) - if not boot_unlock.running_in_snap(): try: - # Ask udev to create the UUID link used during boot. + # Ask udev to create the by-UUID link used during boot. dmcrypt.udevadm_rescan(block_device) dmcrypt.udevadm_settle(block_uuid) - except subprocess.CalledProcessError as udev_error: + except (subprocess.CalledProcessError, + subprocess.TimeoutExpired) as udev_error: logger.warning( 'udev processing for %s failed with error code: %s\n' 'udev output: %s', block_device, - udev_error.returncode, - udev_error.output, + _subprocess_error_returncode(udev_error), + _subprocess_error_output(udev_error), ) + if not os.path.exists(_by_uuid_path(block_uuid)): + logger.warning( + 'by-uuid symlink for %s not present yet; udev should ' + 'create it shortly', + block_uuid, + ) + + return _open_and_register_device( + block_device, block_uuid, key, args.config, + ) + + +def _encrypt_block_device(args, client, config, new_uuid, + new_key): + """Encrypt a plain device or reuse an encrypted one. + + :param: args: argparser generated cli arguments + :param: client: hvac.Client for Vault access + :param: config: configparser object of vaultlocker config + :param: new_uuid: UUID to use when formatting a plain device + :param: new_key: key to use when formatting a plain device + :returns: dict containing the LUKS UUID and mapper path + """ + block_device = args.block_device[0] + + existing_uuid = _get_existing_luks_uuid(block_device) + if existing_uuid is not None: + return _open_existing_managed_device( + args, client, config, block_device, existing_uuid, + ) + + return _format_device( + args, client, config, block_device, new_uuid, new_key, + ) + + +def _enroll_block_device(args, client, config, get_operator_key): + """Add or reuse a Vault-managed key on an existing LUKS device. + + :param: args: argparser generated cli arguments + :param: client: hvac.Client for Vault access + :param: config: configparser object of vaultlocker config + :param: get_operator_key: callable that returns the device's existing key + :returns: dict containing the LUKS UUID and mapper path + """ + block_device = args.block_device[0] try: - dmcrypt.luks_open(key, block_uuid, block_device) - except subprocess.CalledProcessError as luks_error: - raise exceptions.LUKSFailure(block_device, luks_error.output) + block_uuid = dmcrypt.luks_uuid(block_device) + except (subprocess.CalledProcessError, + subprocess.TimeoutExpired) as luks_error: + raise exceptions.LuksValidationError( + block_device, _subprocess_error_output(luks_error), + ) + + store = _vault_store(client, config) + path = _vault_secret_path(block_uuid, config) + vault_key = _read_vault_key(store, path) + + if vault_key is not None and _key_unlocks_device(vault_key, block_device): + # Reuse an enrolled key without asking for the current key. + return _open_and_register_device( + block_device, block_uuid, vault_key, args.config, + ) + + # Read the operator's key only when the device needs to change. + current_key = get_operator_key() + if not _key_unlocks_device(current_key, block_device): + raise exceptions.ExistingKeyInvalidError( + 'Existing key does not unlock {}'.format(block_device) + ) + + if vault_key is None: + vault_key = dmcrypt.generate_key() + _store_and_validate_key(store, path, vault_key) + + try: + dmcrypt.luks_add_key(current_key, vault_key, block_device) + except (subprocess.CalledProcessError, + subprocess.TimeoutExpired) as luks_error: + logger.warning( + 'luksAddKey for %s reported an error (%s); checking whether ' + 'the managed key was added despite the error before failing', + block_device, luks_error, + ) + + if not _key_unlocks_device(vault_key, block_device): + raise exceptions.LuksAddKeyError( + block_device, + 'Vaultlocker managed key unable to unlock the device', + ) - boot_unlock.register(block_uuid, args.config) + return _open_and_register_device( + block_device, block_uuid, vault_key, args.config, + ) def _decrypt_block_device(args, client, config): - """Open a LUKS/dm-crypt encrypted block device + """Open a LUKS/dm-crypt encrypted block device. - The device's dm-crypt key is retrieved from Vault + The device's dm-crypt key is retrieved from Vault. :param: args: argparser generated cli arguments :param: client: hvac.Client for Vault access @@ -381,32 +567,36 @@ def _decrypt_block_device(args, client, config): path = _vault_secret_path(block_uuid, config) store = _vault_store(client, config) - try: - stored_data = store.read(path) - except hvac.exceptions.InvalidPath: - raise ValueError( - 'Unable to locate key for {}'.format(block_uuid) + vault_key = _read_vault_key(store, path) + if vault_key is None: + raise exceptions.ManagedKeyNotFoundError( + '{}/{}'.format(store.mount_point, path) ) - key = stored_data['dmcrypt_key'] - - dmcrypt.luks_open(key, block_uuid) + try: + dmcrypt.luks_open(vault_key, block_uuid) + except (subprocess.CalledProcessError, + subprocess.TimeoutExpired) as open_error: + raise exceptions.MapperOpenError( + 'UUID={}'.format(block_uuid), + _subprocess_error_output(open_error), + ) def _device_exists(block_uuid): """Checks if the device already exists.""" - handle = 'crypt-{}'.format(block_uuid) - path = "/dev/mapper/{}".format(handle) + path = _mapper_path(block_uuid) logger.info('Checking if %s exists.', path) return os.path.exists(path) def _do_it_with_persistence(func, args, config): - """Exec func with retries based on provided cli flags + """Run an operation, retrying temporary Vault availability failures. :param: func: function to attempt to execute :param: args: argparser generated cli arguments :param: config: configparser object of vaultlocker config + :returns: the operation result """ @tenacity.retry( wait=tenacity.wait_fixed(1), @@ -416,61 +606,87 @@ def _do_it_with_persistence(func, args, config): else tenacity.stop_after_attempt(1) ), retry=( - tenacity.retry_if_exception(hvac.exceptions.VaultNotInitialized) | - tenacity.retry_if_exception(hvac.exceptions.VaultDown) + tenacity.retry_if_exception_type( + hvac.exceptions.VaultNotInitialized) | + tenacity.retry_if_exception_type(hvac.exceptions.VaultDown) ) ) def _do_it(): client = _vault_client(config) - func(args, client, config) - _do_it() + return func(args, client, config) + + try: + return _do_it() + except hvac.exceptions.VaultError as vault_error: + raise exceptions.VaultConnectionError(vault_error) from vault_error def encrypt(args, config): - """Encrypt and open handler + """Encrypt and open handler. + + Generate one UUID and key, then reuse them for every retry. :param: args: argparser generated cli arguments :param: config: configparser object of vaultlocker config """ - _do_it_with_persistence(_encrypt_block_device, args, config) + new_uuid = args.uuid or str(uuid.uuid4()) + new_key = dmcrypt.generate_key() + + encrypt_device = functools.partial( + _encrypt_block_device, + new_uuid=new_uuid, + new_key=new_key, + ) + + return _do_it_with_persistence(encrypt_device, args, config) def enroll(args, config): """Enroll and open handler. - :param: args: argparser generated CLI arguments. - :param: config: configparser object of vaultlocker config. + Read the operator key only when the device needs to change. + + :param: args: argparser generated cli arguments + :param: config: configparser object of vaultlocker config """ - # Read the existing key once because stdin cannot be reread during retries, - # then bind it to the enrollment operation. - existing_key = _read_existing_key(args.existing_key_file) + operator_key_cache = {} - enroll_operation = functools.partial( + def get_operator_key(): + if 'value' not in operator_key_cache: + operator_key_cache['value'] = _read_existing_key( + args.existing_key_file, + ) + return operator_key_cache['value'] + + enroll_device = functools.partial( _enroll_block_device, - existing_key=existing_key, + get_operator_key=get_operator_key, ) - _do_it_with_persistence( - enroll_operation, + return _do_it_with_persistence( + enroll_device, args, config, ) def decrypt(args, config): - """Decrypt and open handler + """Decrypt and open handler. + + The device's dm-crypt key is retrieved from Vault. :param: args: argparser generated cli arguments :param: config: configparser object of vaultlocker config """ - _do_it_with_persistence(_decrypt_block_device, args, config) + return _do_it_with_persistence(_decrypt_block_device, args, config) def get_config(config_path): - """Read vaultlocker configuration from config file + """Read and validate a vaultlocker configuration file. :param: config_path: path to the configuration file :returns: configparser. Parsed configuration options + :raises exceptions.ConfigurationError: if the file is invalid """ if any(character.isspace() for character in config_path): raise ValueError( @@ -478,16 +694,35 @@ def get_config(config_path): ) config = configparser.ConfigParser() - if os.path.exists(config_path): - config.read(config_path) - else: - raise FileNotFoundError( - "Configuration file not found: {}".format(config_path) - ) + + try: + with open(config_path, 'r') as config_file: + config.read_file(config_file) + + for option in REQUIRED_VAULT_SETTINGS: + value = config.get('vault', option) + if not value.strip(): + raise exceptions.ConfigurationError( + "Configuration option [vault] {} cannot be empty".format( + option, + ) + ) + + _get_kv_version(config) + except exceptions.ConfigurationError: + raise + except (OSError, configparser.Error) as config_error: + raise exceptions.ConfigurationError( + "Unable to load configuration {}: {}".format( + config_path, config_error, + ) + ) from config_error + return config def main(): + """Run the command and print structured results.""" parser = argparse.ArgumentParser('vaultlocker') parser.set_defaults(prog=parser.prog) subparsers = parser.add_subparsers( @@ -550,17 +785,28 @@ def main(): args = parser.parse_args() - logging.basicConfig(level=logging.DEBUG) + logging.basicConfig(level=logging.DEBUG, stream=sys.stderr) try: - if (len(vars(args)) <= 2): + if not hasattr(args, 'func'): parser.print_help() else: - args.func(args, get_config(args.config)) - except Exception as e: - raise SystemExit( - '{prog}: {msg}'.format( - prog=args.prog, - msg=e, - ) + result = args.func(args, get_config(args.config)) + if isinstance(result, dict): + print(json.dumps(result)) + except exceptions.VaultlockerException as vault_error: + print( + json.dumps({ + "error": str(vault_error), + }), + file=sys.stderr, + ) + sys.exit(ExitCode.HANDLED_FAILURE) + except Exception as error: + print( + json.dumps({ + "error": str(error), + }), + file=sys.stderr, ) + sys.exit(ExitCode.UNEXPECTED_FAILURE) diff --git a/vaultlocker/tests/functional/base.py b/vaultlocker/tests/functional/base.py index e9e4c26..ace5731 100644 --- a/vaultlocker/tests/functional/base.py +++ b/vaultlocker/tests/functional/base.py @@ -17,23 +17,39 @@ import hvac import os +import shutil +import tempfile from unittest import mock import uuid from oslotest import base +from vaultlocker import shell -TEST_POLICY = ''' + +KV1_POLICY = ''' path "{backend}/*" {{ capabilities = ["create", "read", "update", "delete", "list"] }} ''' +KV2_POLICY = ''' +path "{backend}/data/*" {{ + capabilities = ["create", "read", "update", "delete", "list"] +}} +path "{backend}/metadata/*" {{ + capabilities = ["read", "delete", "list"] +}} +''' + class VaultlockerFuncBaseTestCase(base.BaseTestCase): """Test case base class for all functional tests.""" + #: KV secrets engine version under test. + kv_version = '1' + def setUp(self): super(VaultlockerFuncBaseTestCase, self).setUp() self.vault_client = None @@ -56,7 +72,7 @@ def setUp(self): backend_type='kv', path=self.vault_backend, description='vaultlocker test backend', - options={'version': '1'}, + options={'version': self.kv_version}, ) try: @@ -64,9 +80,10 @@ def setUp(self): except hvac.exceptions.InvalidRequest: pass + policy = KV2_POLICY if self.kv_version == '2' else KV1_POLICY self.vault_client.sys.create_or_update_policy( name=self.vault_policy, - policy=TEST_POLICY.format(backend=self.vault_backend), + policy=policy.format(backend=self.vault_backend), ) self.vault_client.auth.approle.create_or_update_approle( @@ -89,6 +106,7 @@ def setUp(self): 'approle': self.approle_uuid, 'secret_id': self.secret_id, 'backend': self.vault_backend, + 'kv_version': self.kv_version, } } self.config = mock.MagicMock() @@ -97,6 +115,10 @@ def setUp(self): k, kwargs.get('fallback') ) + self.temp_dir = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.temp_dir, ignore_errors=True) + self.config_path = os.path.join(self.temp_dir, 'vaultlocker.conf') + def tearDown(self): super(VaultlockerFuncBaseTestCase, self).tearDown() if self.vault_client: @@ -104,3 +126,11 @@ def tearDown(self): path=self.vault_backend, ) self.vault_client.sys.delete_policy(name=self.vault_policy) + + def vault_store(self): + """Return a KV store configured for this test's backend.""" + return shell._vault_store(self.vault_client, self.config) + + def secret_path(self, device_uuid): + """Return the secret path used for a device UUID.""" + return shell._vault_secret_path(device_uuid, self.config) diff --git a/vaultlocker/tests/functional/test_keystorage.py b/vaultlocker/tests/functional/test_keystorage.py index 9c25b92..39243bf 100644 --- a/vaultlocker/tests/functional/test_keystorage.py +++ b/vaultlocker/tests/functional/test_keystorage.py @@ -28,7 +28,11 @@ @mock.patch.object(shell.dmcrypt, 'luks_open') class KeyStorageTestCase(base.VaultlockerFuncBaseTestCase): - """Test storage and retrieval of dm-crypt keys from vault""" + """Functional tests for vaultlocker key storage. + + The device operations are mocked; the Vault interactions are real. + Subclasses run this suite against KV version 1 and 2. + """ def test_encrypt(self, _luks_open, _luks_format, _boot_unlock, _udevadm_rescan, _udevadm_settle): @@ -38,57 +42,202 @@ def test_encrypt(self, _luks_open, _luks_format, _boot_unlock, args.uuid = 'passed-UUID' args.block_device = ['/dev/sdb'] args.retry = -1 - args.config = '/etc/vaultlocker/vaultlocker.conf' + args.config = self.config_path + + # The device itself is not real in this test environment: tell + # the device-state check it is looking at a device with no + # LUKS header yet, the normal case for a first-time encrypt. + with mock.patch.object( + shell.dmcrypt, 'luks_uuid', + side_effect=shell.subprocess.CalledProcessError( + returncode=1, cmd='cryptsetup luksUUID', + )): + shell.encrypt(args, self.config) - shell.encrypt(args, self.config) - _luks_format.assert_called_once_with(mock.ANY, - '/dev/sdb', + _luks_format.assert_called_once_with(mock.ANY, '/dev/sdb', 'passed-UUID') - _luks_open.assert_called_once_with( - mock.ANY, 'passed-UUID', '/dev/sdb' - ) - _boot_unlock.register.assert_called_once_with( - 'passed-UUID', args.config - ) + _luks_open.assert_called_once_with(mock.ANY, 'passed-UUID', + '/dev/sdb') + _boot_unlock.register.assert_called_once_with('passed-UUID', + self.config_path) _udevadm_rescan.assert_called_once_with('/dev/sdb') _udevadm_settle.assert_called_once_with('passed-UUID') - stored_data = self.vault_client.read( - shell._get_vault_path('passed-UUID', - self.config) + stored = self.vault_store().read(self.secret_path('passed-UUID')) + self.assertIn('dmcrypt_key', stored, + 'dm-crypt key data is missing from Vault') + + def test_encrypt_does_not_replace_a_different_key( + self, _luks_open, _luks_format, _boot_unlock, + _udevadm_rescan, _udevadm_settle): + """A UUID collision leaves the existing Vault secret untouched.""" + path = self.secret_path('passed-UUID') + self.vault_store().write( + path, {'dmcrypt_key': 'existing-managed-key'}, ) - self.assertIsNotNone(stored_data, - 'Key data missing from vault') - self.assertIn('dmcrypt_key', stored_data['data'], - 'dm-crypt key data is missing') + + args = mock.MagicMock() + args.uuid = 'passed-UUID' + args.block_device = ['/dev/sdb'] + args.retry = -1 + args.config = self.config_path + + with mock.patch.object( + shell.dmcrypt, 'luks_uuid', + side_effect=shell.subprocess.CalledProcessError( + returncode=1, cmd='cryptsetup luksUUID', + )): + self.assertRaises( + shell.exceptions.VaultKeyMismatch, + shell.encrypt, args, self.config, + ) + + self.assertEqual( + {'dmcrypt_key': 'existing-managed-key'}, + self.vault_store().read(path), + ) + _luks_format.assert_not_called() + + def test_encrypt_does_not_replace_malformed_data( + self, _luks_open, _luks_format, _boot_unlock, + _udevadm_rescan, _udevadm_settle): + """Malformed data at a proposed UUID is preserved for inspection.""" + path = self.secret_path('passed-UUID') + malformed = {'unexpected': 'value'} + self.vault_store().write(path, malformed) + + args = mock.MagicMock() + args.uuid = 'passed-UUID' + args.block_device = ['/dev/sdb'] + args.retry = -1 + args.config = self.config_path + + with mock.patch.object( + shell.dmcrypt, 'luks_uuid', + side_effect=shell.subprocess.CalledProcessError( + returncode=1, cmd='cryptsetup luksUUID', + )): + self.assertRaises( + shell.exceptions.ManagedKeyInvalidError, + shell.encrypt, args, self.config, + ) + + self.assertEqual(malformed, self.vault_store().read(path)) + _luks_format.assert_not_called() def test_decrypt(self, _luks_open, _luks_format, _boot_unlock, _udevadm_rescan, _udevadm_settle): - """Test decrypt function retrieves correct key from vault""" + """Decrypt reads the key from Vault and opens the mapper.""" args = mock.MagicMock() args.uuid = ['passed-UUID'] args.retry = -1 + args.config = self.config_path + + self.vault_store().write( + self.secret_path('passed-UUID'), + {'dmcrypt_key': 'testkey'}, + ) - self.vault_client.write(shell._get_vault_path('passed-UUID', - self.config), - dmcrypt_key='testkey') + with mock.patch.object(shell, '_device_exists', return_value=False): + shell.decrypt(args, self.config) - shell.decrypt(args, self.config) _luks_format.assert_not_called() _boot_unlock.register.assert_not_called() - _luks_open.assert_called_once_with('testkey', - 'passed-UUID') + _luks_open.assert_called_once_with('testkey', 'passed-UUID') def test_decrypt_missing_key(self, _luks_open, _luks_format, _boot_unlock, _udevadm_rescan, _udevadm_settle): - """Test decrypt function errors if a key is missing from vault""" + """Decrypt errors if the key is missing from Vault.""" args = mock.MagicMock() args.uuid = ['passed-UUID'] args.retry = -1 + args.config = self.config_path + + with mock.patch.object(shell, '_device_exists', return_value=False): + self.assertRaises( + shell.exceptions.ManagedKeyNotFoundError, + shell.decrypt, args, self.config, + ) - self.assertRaises(ValueError, - shell.decrypt, - args, self.config) _luks_format.assert_not_called() _boot_unlock.register.assert_not_called() _luks_open.assert_not_called() + + def test_enroll_adds_managed_key(self, _luks_open, _luks_format, + _boot_unlock, _udevadm_rescan, + _udevadm_settle): + """Enroll adds a Vault-managed key to an existing LUKS device.""" + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + args.retry = -1 + args.config = self.config_path + + with mock.patch.object(shell.dmcrypt, 'luks_uuid', + return_value='passed-UUID'), \ + mock.patch.object(shell.dmcrypt, 'luks_test_key', + side_effect=[True, True]), \ + mock.patch.object(shell.dmcrypt, 'luks_add_key') as add_key, \ + mock.patch.object(shell, '_device_exists', + return_value=False): + shell._enroll_block_device(args, self.vault_client, + self.config, lambda: b'operatorpass') + + add_key.assert_called_once_with(b'operatorpass', mock.ANY, + '/dev/sdb') + _luks_open.assert_called_once_with(mock.ANY, 'passed-UUID', + '/dev/sdb') + _boot_unlock.register.assert_called_once_with('passed-UUID', + self.config_path) + + stored = self.vault_store().read(self.secret_path('passed-UUID')) + self.assertIn('dmcrypt_key', stored, + 'managed key data is missing from Vault') + + def test_enroll_reuses_existing_managed_key(self, _luks_open, + _luks_format, _boot_unlock, + _udevadm_rescan, + _udevadm_settle): + """A managed key already in Vault is reused without re-adding it.""" + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + args.retry = -1 + args.config = self.config_path + + self.vault_store().write( + self.secret_path('passed-UUID'), + {'dmcrypt_key': 'existing-managed-key'}, + ) + + # The managed key already unlocks the device, so the original + # credential must never be requested. + never_load_credential = mock.MagicMock( + side_effect=AssertionError('credential should not be read'), + ) + + with mock.patch.object(shell.dmcrypt, 'luks_uuid', + return_value='passed-UUID'), \ + mock.patch.object(shell.dmcrypt, 'luks_test_key', + return_value=True), \ + mock.patch.object(shell.dmcrypt, 'luks_add_key') as add_key, \ + mock.patch.object(shell, '_device_exists', + return_value=True): + shell._enroll_block_device(args, self.vault_client, + self.config, never_load_credential) + + never_load_credential.assert_not_called() + add_key.assert_not_called() + _luks_open.assert_not_called() + _boot_unlock.register.assert_called_once_with('passed-UUID', + self.config_path) + + +class KeyStorageV1TestCase(KeyStorageTestCase): + """Run the key storage suite against KV version 1.""" + + kv_version = '1' + + +class KeyStorageV2TestCase(KeyStorageTestCase): + """Run the key storage suite against KV version 2.""" + + kv_version = '2' diff --git a/vaultlocker/tests/unit/test_command_results.py b/vaultlocker/tests/unit/test_command_results.py new file mode 100644 index 0000000..3cd6a42 --- /dev/null +++ b/vaultlocker/tests/unit/test_command_results.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- + +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import json + +from unittest import mock + +import hvac + +from vaultlocker import exceptions +from vaultlocker.exit_codes import ExitCode +from vaultlocker import shell +from vaultlocker.tests.unit import base + + +class TestCommandResults(base.TestCase): + + @mock.patch.object(shell.sys, 'argv', [ + 'vaultlocker', 'encrypt', '/dev/sdb', + ]) + @mock.patch('builtins.print') + @mock.patch.object(shell, 'get_config') + @mock.patch.object(shell, 'encrypt') + def test_main_prints_json_result(self, encrypt, get_config, print_): + result = { + 'luks_uuid': 'test-uuid', + 'mapper_path': '/dev/mapper/crypt-test-uuid', + } + encrypt.return_value = result + + shell.main() + + print_.assert_called_once_with(json.dumps(result)) + + @mock.patch.object(shell.sys, 'argv', [ + 'vaultlocker', 'encrypt', '/dev/sdb', + ]) + @mock.patch('builtins.print') + @mock.patch.object(shell, 'get_config') + def test_main_returns_handled_failure_for_controlled_error( + self, get_config, print_): + get_config.side_effect = exceptions.ConfigurationError('invalid') + + with self.assertRaises(SystemExit) as error: + shell.main() + + self.assertEqual(ExitCode.HANDLED_FAILURE, error.exception.code) + print_.assert_called_once_with( + json.dumps({ + 'error': 'invalid', + }), + file=shell.sys.stderr, + ) + + @mock.patch.object(shell.sys, 'argv', [ + 'vaultlocker', 'encrypt', '/dev/sdb', + ]) + @mock.patch('builtins.print') + @mock.patch.object(shell, 'get_config') + def test_main_returns_unexpected_failure_for_unknown_error( + self, get_config, print_): + get_config.side_effect = RuntimeError('unexpected') + + with self.assertRaises(SystemExit) as error: + shell.main() + + self.assertEqual(ExitCode.UNEXPECTED_FAILURE, error.exception.code) + print_.assert_called_once_with( + json.dumps({ + 'error': 'unexpected', + }), + file=shell.sys.stderr, + ) + + @mock.patch.object(shell, '_vault_client') + def test_retry_wrapper_returns_operation_result(self, vault_client): + operation = mock.Mock(return_value={'luks_uuid': 'test-uuid'}) + args = mock.Mock(retry=-1) + config = mock.Mock() + + result = shell._do_it_with_persistence(operation, args, config) + + self.assertEqual({'luks_uuid': 'test-uuid'}, result) + operation.assert_called_once_with( + args, vault_client.return_value, config, + ) + + @mock.patch.object(shell, '_vault_client') + def test_retry_wrapper_reports_vault_errors(self, vault_client): + vault_client.side_effect = hvac.exceptions.Forbidden('denied') + + with self.assertRaises(exceptions.VaultConnectionError): + shell._do_it_with_persistence( + mock.Mock(), mock.Mock(retry=-1), mock.Mock(), + ) diff --git a/vaultlocker/tests/unit/test_dmcrypt.py b/vaultlocker/tests/unit/test_dmcrypt.py index 8518482..dfe1852 100644 --- a/vaultlocker/tests/unit/test_dmcrypt.py +++ b/vaultlocker/tests/unit/test_dmcrypt.py @@ -38,7 +38,8 @@ def test_luks_format(self, _subprocess): '--uuid', 'test-uuid', '--key-file', '-', 'luksFormat', '/dev/sdb'], - input='mykey'.encode('UTF-8') + input='mykey'.encode('UTF-8'), + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, ) def test_key_bytes_from_string(self): @@ -60,7 +61,8 @@ def test_luks_open(self, _subprocess): '--key-file', '-', 'open', 'UUID=test-uuid', 'crypt-test-uuid', '--type', 'luks'], - input='mykey'.encode('UTF-8') + input='mykey'.encode('UTF-8'), + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, ) @mock.patch.object(dmcrypt, 'subprocess') @@ -72,7 +74,8 @@ def test_luks_open_by_device(self, _subprocess): '--key-file', '-', 'open', '/dev/sdb', 'crypt-test-uuid', '--type', 'luks'], - input='mykey'.encode('UTF-8') + input='mykey'.encode('UTF-8'), + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, ) @mock.patch.object(dmcrypt, 'os') @@ -94,7 +97,8 @@ def test_luks_uuid(self, _subprocess): _subprocess.check_output.assert_called_once_with( ['cryptsetup', 'luksUUID', - '/dev/sdb'] + '/dev/sdb'], + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, ) @mock.patch.object(dmcrypt.subprocess, 'check_output') @@ -110,7 +114,8 @@ def test_luks_uuid_failure(self, _check_output): _check_output.assert_called_once_with( ['cryptsetup', 'luksUUID', - '/dev/sdb'] + '/dev/sdb'], + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, ) @mock.patch.object(dmcrypt, 'subprocess') @@ -125,7 +130,8 @@ def test_luks_test_key_valid(self, _subprocess): 'open', '--test-passphrase', '/dev/sdb'], - input=b'mykey' + input=b'mykey', + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, ) @mock.patch.object(dmcrypt.subprocess, 'check_output') @@ -145,7 +151,8 @@ def test_luks_test_key_invalid(self, _check_output): 'open', '--test-passphrase', '/dev/sdb'], - input=b'mykey' + input=b'mykey', + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, ) @mock.patch.object(dmcrypt.subprocess, 'check_output') @@ -165,7 +172,8 @@ def test_luks_test_key_command_failure(self, _check_output): 'open', '--test-passphrase', '/dev/sdb'], - input=b'mykey' + input=b'mykey', + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, ) @mock.patch.object(dmcrypt, 'subprocess') @@ -189,7 +197,8 @@ def test_luks_add_key(self, _os, _subprocess): '--new-keyfile', '-', 'luksAddKey', '/dev/sdb'], input=b'new-key', - pass_fds=(10,) + pass_fds=(10,), + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, ) _os.close.assert_called_once_with(10) @@ -218,7 +227,8 @@ def test_luks_add_key_failure_closes_fd( '--new-keyfile', '-', 'luksAddKey', '/dev/sdb'], input=b'new-key', - pass_fds=(10,) + pass_fds=(10,), + timeout=dmcrypt.CRYPTSETUP_TIMEOUT_SECONDS, ) _os.close.assert_called_once_with(10) @@ -229,7 +239,8 @@ def test_udevadm_rescan(self, _subprocess): ['udevadm', 'trigger', '--name-match=/dev/vdb', - '--action=add'] + '--action=add'], + timeout=dmcrypt.UDEVADM_TIMEOUT_SECONDS, ) @mock.patch.object(dmcrypt, 'subprocess') @@ -238,5 +249,15 @@ def test_udevadm_settle(self, _subprocess): _subprocess.check_output.assert_called_once_with( ['udevadm', 'settle', - '--exit-if-exists=/dev/disk/by-uuid/myuuid'] + '--exit-if-exists=/dev/disk/by-uuid/myuuid'], + timeout=dmcrypt.UDEVADM_TIMEOUT_SECONDS, + ) + + @mock.patch.object(dmcrypt.subprocess, 'check_output') + def test_luks_format_timeout_propagates(self, _check_output): + _check_output.side_effect = subprocess.TimeoutExpired( + cmd='cryptsetup', timeout=1, ) + + with self.assertRaises(subprocess.TimeoutExpired): + dmcrypt.luks_format('mykey', '/dev/sdb', 'test-uuid') diff --git a/vaultlocker/tests/unit/test_exceptions.py b/vaultlocker/tests/unit/test_exceptions.py new file mode 100644 index 0000000..86f4903 --- /dev/null +++ b/vaultlocker/tests/unit/test_exceptions.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- + +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +"""Tests for `vaultlocker.exceptions`.""" + +from vaultlocker import exceptions +from vaultlocker.tests.unit import base + + +class TestExceptions(base.TestCase): + + def test_base_default_message(self): + error = exceptions.VaultlockerException() + + self.assertEqual('Empty VaultlockerException', str(error)) + + def test_base_uses_first_argument_as_message(self): + error = exceptions.VaultlockerException('boom') + + self.assertEqual('boom', str(error)) + + def test_managed_key_not_found_message(self): + error = exceptions.ManagedKeyNotFoundError('mount/host/uuid') + + self.assertIn('mount/host/uuid', str(error)) + + def test_luks_failure_message(self): + error = exceptions.LuksFormatError('/dev/sdb', 'boom') + + self.assertEqual("Can't operate on /dev/sdb. Error: boom", str(error)) diff --git a/vaultlocker/tests/unit/test_vaultlocker.py b/vaultlocker/tests/unit/test_vaultlocker.py index 82a6960..746d209 100644 --- a/vaultlocker/tests/unit/test_vaultlocker.py +++ b/vaultlocker/tests/unit/test_vaultlocker.py @@ -20,6 +20,8 @@ """ import configparser +import io +import json import subprocess from unittest import mock @@ -27,6 +29,7 @@ import hvac from vaultlocker import exceptions +from vaultlocker.exit_codes import ExitCode from vaultlocker import shell from vaultlocker.tests.unit import base @@ -97,15 +100,14 @@ def test_vault_store_uses_configured_mount_and_version(self, _kv_store): ) self.assertIs(result, _kv_store.get_store.return_value) + @mock.patch.object(shell, '_device_exists', return_value=False) @mock.patch.object(shell, 'get_hostname') @mock.patch.object(shell, '_vault_store') @mock.patch.object(shell, 'boot_unlock') @mock.patch.object(shell, 'dmcrypt') - def test_encrypt(self, _dmcrypt, _boot_unlock, _vault_store, - _get_hostname): + def test_decrypt(self, _dmcrypt, _boot_unlock, _vault_store, + _get_hostname, _device_exists): _get_hostname.return_value = 'host' - _boot_unlock.running_in_snap.return_value = False - _dmcrypt.generate_key.return_value = 'testkey' store = _vault_store.return_value store.read.return_value = { @@ -113,164 +115,96 @@ def test_encrypt(self, _dmcrypt, _boot_unlock, _vault_store, } args = mock.MagicMock() - args.uuid = 'passed-UUID' - args.block_device = ['/dev/sdb'] + args.uuid = ['passed-UUID'] client = mock.MagicMock() - shell._encrypt_block_device(args, client, self.config) + shell._decrypt_block_device(args, client, self.config) - store.write.assert_called_once_with( - 'host/passed-UUID', - {'dmcrypt_key': 'testkey'}, - ) store.read.assert_called_once_with('host/passed-UUID') - - _dmcrypt.luks_format.assert_called_once_with( - 'testkey', '/dev/sdb', 'passed-UUID' - ) - _dmcrypt.udevadm_rescan.assert_called_once_with('/dev/sdb') - _dmcrypt.udevadm_settle.assert_called_once_with('passed-UUID') - _dmcrypt.luks_open.assert_called_once_with( - 'testkey', 'passed-UUID', '/dev/sdb' - ) - _boot_unlock.register.assert_called_once_with( - 'passed-UUID', args.config, - ) - - @mock.patch.object(shell, 'get_hostname', return_value='host') - @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'boot_unlock') - @mock.patch.object(shell, 'dmcrypt') - def test_encrypt_skips_udev_in_snap(self, _dmcrypt, _boot_unlock, - _vault_store, _get_hostname): - _boot_unlock.running_in_snap.return_value = True - _dmcrypt.generate_key.return_value = 'testkey' - _vault_store.return_value.read.return_value = { - 'dmcrypt_key': 'testkey', - } - args = mock.MagicMock() - args.uuid = 'passed-UUID' - args.block_device = ['/dev/sdb'] - - shell._encrypt_block_device(args, mock.MagicMock(), self.config) - - _dmcrypt.udevadm_rescan.assert_not_called() - _dmcrypt.udevadm_settle.assert_not_called() - _dmcrypt.luks_open.assert_called_once_with( - 'testkey', 'passed-UUID', '/dev/sdb' - ) - _boot_unlock.register.assert_called_once_with( - 'passed-UUID', args.config, - ) - - @mock.patch.object(shell, 'get_hostname', return_value='host') - @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'boot_unlock') - @mock.patch.object(shell, 'dmcrypt') - def test_encrypt_continues_after_udev_failure( - self, _dmcrypt, _boot_unlock, _vault_store, _get_hostname): - _boot_unlock.running_in_snap.return_value = False - _dmcrypt.generate_key.return_value = 'testkey' - _dmcrypt.udevadm_rescan.side_effect = subprocess.CalledProcessError( - returncode=1, cmd='udevadm trigger', output=b'failed', - ) - _vault_store.return_value.read.return_value = { - 'dmcrypt_key': 'testkey', - } - args = mock.MagicMock() - args.uuid = 'passed-UUID' - args.block_device = ['/dev/sdb'] - - shell._encrypt_block_device(args, mock.MagicMock(), self.config) - - _dmcrypt.udevadm_rescan.assert_called_once_with('/dev/sdb') - _dmcrypt.udevadm_settle.assert_not_called() _dmcrypt.luks_open.assert_called_once_with( - 'testkey', 'passed-UUID', '/dev/sdb' - ) - _boot_unlock.register.assert_called_once_with( - 'passed-UUID', args.config, + 'testkey', 'passed-UUID' ) + _boot_unlock.register.assert_not_called() + @mock.patch.object(shell, '_device_exists', return_value=False) @mock.patch.object(shell, 'get_hostname') @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'boot_unlock') @mock.patch.object(shell, 'dmcrypt') - def test_encrypt_key_mismatch(self, _dmcrypt, _boot_unlock, - _vault_store, _get_hostname): + def test_decrypt_missing_key(self, _dmcrypt, _vault_store, _get_hostname, + _device_exists): _get_hostname.return_value = 'host' - _dmcrypt.generate_key.return_value = 'testkey' store = _vault_store.return_value - store.read.return_value = { - 'dmcrypt_key': 'brokendata', - } + store.mount_point = 'vaultlocker-test' + store.read.side_effect = hvac.exceptions.InvalidPath('missing') args = mock.MagicMock() - args.uuid = 'passed-UUID' - args.block_device = ['/dev/sdb'] + args.uuid = ['passed-UUID'] client = mock.MagicMock() - self.assertRaises( - exceptions.VaultKeyMismatch, - shell._encrypt_block_device, - args, client, self.config - ) + with self.assertRaises(exceptions.ManagedKeyNotFoundError) as error: + shell._decrypt_block_device(args, client, self.config) - _dmcrypt.luks_format.assert_not_called() - _boot_unlock.register.assert_not_called() + self.assertIn( + 'vaultlocker-test/host/passed-UUID', + str(error.exception), + ) + _dmcrypt.luks_open.assert_not_called() @mock.patch.object(shell, '_device_exists', return_value=False) - @mock.patch.object(shell, 'get_hostname') + @mock.patch.object(shell, 'get_hostname', return_value='host') @mock.patch.object(shell, '_vault_store') @mock.patch.object(shell, 'dmcrypt') - def test_decrypt(self, _dmcrypt, _vault_store, _get_hostname, - _device_exists): - _get_hostname.return_value = 'host' - + def test_decrypt_rejects_invalid_managed_key_data( + self, _dmcrypt, _vault_store, _get_hostname, _device_exists): store = _vault_store.return_value - store.read.return_value = { - 'dmcrypt_key': 'testkey', - } + store.mount_point = 'vaultlocker-test' args = mock.MagicMock() args.uuid = ['passed-UUID'] - client = mock.MagicMock() - - shell._decrypt_block_device(args, client, self.config) - - store.read.assert_called_once_with('host/passed-UUID') - _dmcrypt.luks_open.assert_called_once_with( - 'testkey', 'passed-UUID' + invalid_data = ( + 'not-a-mapping', + {}, + {'dmcrypt_key': ''}, ) + for stored_data in invalid_data: + with self.subTest(stored_data=stored_data): + store.read.return_value = stored_data + with self.assertRaises(exceptions.ManagedKeyInvalidError): + shell._decrypt_block_device( + args, mock.MagicMock(), self.config, + ) + + _dmcrypt.luks_open.assert_not_called() @mock.patch.object(shell, '_device_exists', return_value=False) - @mock.patch.object(shell, 'get_hostname') + @mock.patch.object(shell, 'get_hostname', return_value='host') @mock.patch.object(shell, '_vault_store') @mock.patch.object(shell, 'dmcrypt') - def test_decrypt_missing_key(self, _dmcrypt, _vault_store, _get_hostname, - _device_exists): - _get_hostname.return_value = 'host' - + def test_decrypt_wraps_mapper_open_failures( + self, _dmcrypt, _vault_store, _get_hostname, _device_exists): store = _vault_store.return_value - store.read.side_effect = hvac.exceptions.InvalidPath('missing') + store.read.return_value = {'dmcrypt_key': 'testkey'} args = mock.MagicMock() args.uuid = ['passed-UUID'] - client = mock.MagicMock() - - with self.assertRaises(ValueError) as error: - shell._decrypt_block_device(args, client, self.config) - - self.assertEqual( - 'Unable to locate key for passed-UUID', - str(error.exception), + failures = ( + subprocess.CalledProcessError( + returncode=1, cmd='cryptsetup open', + ), + subprocess.TimeoutExpired(cmd='cryptsetup open', timeout=300), ) - _dmcrypt.luks_open.assert_not_called() + for failure in failures: + with self.subTest(failure=failure): + _dmcrypt.luks_open.side_effect = failure + with self.assertRaises(exceptions.MapperOpenError): + shell._decrypt_block_device( + args, mock.MagicMock(), self.config, + ) @mock.patch.object(shell, '_device_exists', return_value=False) @mock.patch.object(shell, 'get_hostname') @@ -316,83 +250,11 @@ def test_get_vault_path(self, _get_hostname): 'vaultlocker-test/myhost/my-UUID' ) - @mock.patch.object(shell, 'get_hostname') - @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'boot_unlock') - @mock.patch.object(shell, 'dmcrypt') - def test_encrypt_luks_failure(self, _dmcrypt, _boot_unlock, - _vault_store, _get_hostname): - _get_hostname.return_value = 'host' - _dmcrypt.generate_key.return_value = 'testkey' - _dmcrypt.luks_format.side_effect = \ - subprocess.CalledProcessError(returncode=-1, - cmd='echo Unit Test') - - store = _vault_store.return_value - store.read.return_value = { - 'dmcrypt_key': 'testkey', - } - - args = mock.MagicMock() - args.uuid = 'passed-UUID' - args.block_device = ['/dev/sdb'] - - client = mock.MagicMock() - - self.assertRaises( - exceptions.LUKSFailure, - shell._encrypt_block_device, - args, client, self.config - ) - - store.delete.assert_called_once_with('host/passed-UUID') - _boot_unlock.register.assert_not_called() - - @mock.patch.object(shell, 'get_hostname') - @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'dmcrypt') - def test_vault_write_operation(self, _dmcrypt, _vault_store, - _get_hostname): - _get_hostname.return_value = 'host' - _dmcrypt.generate_key.return_value = 'testkey' - - store = _vault_store.return_value - store.write.side_effect = hvac.exceptions.Forbidden('denied') - - args = mock.MagicMock() - args.uuid = 'passed-UUID' - args.block_device = ['/dev/sdb'] - - client = mock.MagicMock() - - self.assertRaises( - exceptions.VaultWriteError, - shell._encrypt_block_device, - args, client, self.config - ) - - @mock.patch.object(shell, 'get_hostname') - @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'dmcrypt') - def test_vault_read_operation(self, _dmcrypt, _vault_store, - _get_hostname): - _get_hostname.return_value = 'host' - _dmcrypt.generate_key.return_value = 'testkey' - - store = _vault_store.return_value - store.read.side_effect = hvac.exceptions.Forbidden('denied') - - args = mock.MagicMock() - args.uuid = 'passed-UUID' - args.block_device = ['/dev/sdb'] - - client = mock.MagicMock() + @mock.patch.object(shell.os.path, 'exists', return_value=True) + def test_device_exists(self, _exists): + self.assertTrue(shell._device_exists('test-uuid')) - self.assertRaises( - exceptions.VaultReadError, - shell._encrypt_block_device, - args, client, self.config - ) + _exists.assert_called_once_with('/dev/mapper/crypt-test-uuid') @mock.patch.object(shell, 'socket') @mock.patch.object(shell, 'platform') @@ -484,184 +346,25 @@ def test_read_existing_key_from_file(self, _open): _open.assert_called_once_with('/path/to/key', 'rb') - @mock.patch.object(shell.dmcrypt, 'generate_key') - def test_get_or_create_managed_key_reuses_existing( - self, _generate_key): - store = mock.MagicMock() - store.read.return_value = { - 'dmcrypt_key': 'managed-key', - } - - self.assertEqual( - 'managed-key', - shell._get_or_create_managed_key( - store, - 'host/test-uuid', - ), - ) - - store.read.assert_called_once_with('host/test-uuid') - _generate_key.assert_not_called() - - @mock.patch.object(shell, '_store_and_validate_key') - @mock.patch.object(shell.dmcrypt, 'generate_key') - def test_get_or_create_managed_key_creates_missing( - self, _generate_key, _store_and_validate_key): - store = mock.MagicMock() - store.read.side_effect = hvac.exceptions.InvalidPath( - 'missing', - ) - _generate_key.return_value = 'managed-key' - - self.assertEqual( - 'managed-key', - shell._get_or_create_managed_key( - store, - 'host/test-uuid', - ), - ) - - _generate_key.assert_called_once_with() - _store_and_validate_key.assert_called_once_with( - store, - 'host/test-uuid', - 'managed-key', - ) - - @mock.patch.object(shell.dmcrypt, 'generate_key') - def test_get_or_create_managed_key_error( - self, _generate_key): - store = mock.MagicMock() - store.read.side_effect = hvac.exceptions.Forbidden( - 'denied', - ) - - with self.assertRaises(hvac.exceptions.Forbidden): - shell._get_or_create_managed_key( - store, - 'host/test-uuid', - ) - - _generate_key.assert_not_called() - - @mock.patch.object(shell, '_device_exists', return_value=False) - @mock.patch.object(shell, '_get_or_create_managed_key') - @mock.patch.object(shell, 'get_hostname') - @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'boot_unlock') - @mock.patch.object(shell, 'dmcrypt') - def test_enroll_block_device( - self, _dmcrypt, _boot_unlock, _vault_store, - _get_hostname, _get_managed_key, _device_exists): - _get_hostname.return_value = 'host' - _get_managed_key.return_value = 'managed-key' - - _dmcrypt.luks_uuid.return_value = 'test-uuid' - _dmcrypt.luks_test_key.side_effect = [ - True, - False, - True, - ] - - args = mock.MagicMock() - args.block_device = ['/dev/sdb'] - client = mock.MagicMock() - - shell._enroll_block_device( - args, - client, - self.config, - b'existing-key', - ) - - _dmcrypt.luks_uuid.assert_called_once_with('/dev/sdb') - _dmcrypt.luks_test_key.assert_has_calls([ - mock.call(b'existing-key', '/dev/sdb'), - mock.call('managed-key', '/dev/sdb'), - mock.call('managed-key', '/dev/sdb'), - ]) - _get_managed_key.assert_called_once_with( - _vault_store.return_value, - 'host/test-uuid', - ) - _dmcrypt.luks_add_key.assert_called_once_with( - b'existing-key', - 'managed-key', - '/dev/sdb', - ) - _dmcrypt.luks_open.assert_called_once_with( - 'managed-key', - 'test-uuid', - '/dev/sdb', - ) - _boot_unlock.register.assert_called_once_with( - 'test-uuid', args.config, - ) - - @mock.patch.object(shell, '_device_exists', return_value=True) - @mock.patch.object(shell, '_get_or_create_managed_key') - @mock.patch.object(shell, 'get_hostname') - @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'boot_unlock') - @mock.patch.object(shell, 'dmcrypt') - def test_enroll_block_device_already_enrolled( - self, _dmcrypt, _boot_unlock, _vault_store, - _get_hostname, _get_managed_key, _device_exists): - _get_hostname.return_value = 'host' - _get_managed_key.return_value = 'managed-key' - - _dmcrypt.luks_uuid.return_value = 'test-uuid' - _dmcrypt.luks_test_key.side_effect = [ - True, - True, - ] - - args = mock.MagicMock() - args.block_device = ['/dev/sdb'] - - shell._enroll_block_device( - args, - mock.MagicMock(), - self.config, - b'existing-key', - ) - - _dmcrypt.luks_add_key.assert_not_called() - _dmcrypt.luks_open.assert_not_called() - _boot_unlock.register.assert_called_once_with( - 'test-uuid', args.config, - ) + @mock.patch('builtins.open', side_effect=OSError('no such file')) + def test_read_existing_key_file_unreadable(self, _open): + with self.assertRaises(exceptions.ExistingKeyInvalidError) as error: + shell._read_existing_key('/path/to/key') - @mock.patch.object(shell, '_get_or_create_managed_key') - @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'boot_unlock') - @mock.patch.object(shell, 'dmcrypt') - def test_enroll_block_device_rejects_invalid_existing_key( - self, _dmcrypt, _boot_unlock, _vault_store, - _get_managed_key): - _dmcrypt.luks_uuid.return_value = 'test-uuid' - _dmcrypt.luks_test_key.return_value = False + self.assertIn('no such file', str(error.exception)) - args = mock.MagicMock() - args.block_device = ['/dev/sdb'] + @mock.patch.object(shell, 'sys') + def test_read_existing_key_empty_is_invalid(self, _sys): + _sys.stdin.isatty.return_value = False + _sys.stdin.buffer.read.return_value = b'' - with self.assertRaises(ValueError) as error: - shell._enroll_block_device( - args, - mock.MagicMock(), - self.config, - b'wrong-key', - ) + with self.assertRaises(exceptions.ExistingKeyInvalidError) as error: + shell._read_existing_key(None) self.assertEqual( - 'Existing key does not unlock /dev/sdb', + 'Existing LUKS key cannot be empty', str(error.exception), ) - _vault_store.assert_not_called() - _get_managed_key.assert_not_called() - _dmcrypt.luks_add_key.assert_not_called() - _dmcrypt.luks_open.assert_not_called() - _boot_unlock.register.assert_not_called() @mock.patch.object( shell.sys, @@ -690,30 +393,1352 @@ def test_main_parses_enroll( self.assertEqual(['/dev/sdb'], args.block_device) self.assertIs(self.config, config) + @mock.patch.object(shell, '_vault_client') + def test_do_it_with_persistence_returns_result( + self, _vault_client): + args = mock.MagicMock() + args.retry = 0 + func = mock.MagicMock(return_value={'luks_uuid': 'test-uuid'}) -class TestKVConfiguration(base.TestCase): + result = shell._do_it_with_persistence( + func, args, self.config, + ) - def _config(self, kv_version=None): - config = configparser.ConfigParser() - config.add_section('vault') - config.set('vault', 'backend', 'vaultlocker-test') + self.assertEqual({'luks_uuid': 'test-uuid'}, result) + func.assert_called_once_with(args, _vault_client.return_value, + self.config) - if kv_version is not None: - config.set('vault', 'kv_version', kv_version) + @mock.patch.object(shell, '_vault_client') + def test_do_it_with_persistence_wraps_vault_connection_error( + self, _vault_client): + _vault_client.side_effect = hvac.exceptions.VaultDown('down') - return config + args = mock.MagicMock() + args.retry = 0 + func = mock.MagicMock() - def test_kv_version_defaults_to_one(self): - self.assertEqual( - '1', - shell._get_kv_version(self._config()), - ) + with self.assertRaises(exceptions.VaultConnectionError): + shell._do_it_with_persistence(func, args, self.config) - def test_kv_version_one(self): - self.assertEqual( - '1', - shell._get_kv_version(self._config('1')), - ) + func.assert_not_called() + + @mock.patch.object(shell.sys, 'argv', + ['vaultlocker', 'encrypt', '/dev/sdb']) + @mock.patch.object(shell, 'get_config') + @mock.patch.object(shell, 'encrypt') + def test_main_prints_json_result_on_success( + self, _encrypt, _get_config): + _get_config.return_value = self.config + _encrypt.return_value = { + 'luks_uuid': 'test-uuid', + 'mapper_path': '/dev/mapper/crypt-test-uuid', + } + + with mock.patch('builtins.print') as _print: + shell.main() + + _print.assert_called_once_with( + json.dumps({ + 'luks_uuid': 'test-uuid', + 'mapper_path': '/dev/mapper/crypt-test-uuid', + }), + ) + + @mock.patch.object(shell.sys, 'exit') + @mock.patch.object(shell.sys, 'argv', + ['vaultlocker', 'encrypt', '/dev/sdb']) + @mock.patch.object(shell, 'get_config') + @mock.patch.object(shell, 'encrypt') + def test_main_handled_failure_exit_code( + self, _encrypt, _get_config, _exit): + """A controlled exception uses the handled-failure exit code.""" + _get_config.return_value = self.config + _encrypt.side_effect = exceptions.LuksFormatError( + '/dev/sdb', 'boom', + ) + + with mock.patch('builtins.print') as _print: + shell.main() + + _exit.assert_called_once_with(ExitCode.HANDLED_FAILURE) + printed = _print.call_args[0][0] + self.assertEqual( + { + 'error': "Can't operate on /dev/sdb. Error: boom", + }, + json.loads(printed), + ) + self.assertEqual(shell.sys.stderr, _print.call_args[1]['file']) + + @mock.patch.object(shell.sys, 'exit') + @mock.patch.object(shell.sys, 'argv', + ['vaultlocker', 'enroll', '/dev/sdb']) + @mock.patch.object(shell, 'get_config') + @mock.patch.object(shell, 'enroll') + def test_main_handled_validation_failure_exit_code( + self, _enroll, _get_config, _exit): + _get_config.return_value = self.config + _enroll.side_effect = exceptions.ExistingKeyInvalidError( + 'Existing key does not unlock /dev/sdb', + ) + + with mock.patch('builtins.print') as _print: + shell.main() + + _exit.assert_called_once_with(ExitCode.HANDLED_FAILURE) + printed = _print.call_args[0][0] + self.assertEqual( + { + 'error': 'Existing key does not unlock /dev/sdb', + }, + json.loads(printed), + ) + self.assertEqual(shell.sys.stderr, _print.call_args[1]['file']) + + @mock.patch.object(shell.sys, 'exit') + @mock.patch.object(shell.sys, 'argv', + ['vaultlocker', 'encrypt', '/dev/sdb']) + @mock.patch.object(shell, 'get_config') + @mock.patch.object(shell, 'encrypt') + def test_main_configuration_failure_is_handled( + self, _encrypt, _get_config, _exit): + _get_config.side_effect = exceptions.ConfigurationError( + 'invalid configuration', + ) + + with mock.patch('builtins.print') as _print: + shell.main() + + _encrypt.assert_not_called() + _exit.assert_called_once_with(ExitCode.HANDLED_FAILURE) + self.assertEqual( + { + 'error': 'invalid configuration', + }, + json.loads(_print.call_args[0][0]), + ) + + @mock.patch.object(shell.sys, 'argv', + ['vaultlocker', 'decrypt', 'test-uuid']) + @mock.patch.object(shell, 'get_config') + @mock.patch.object(shell, 'decrypt') + def test_failure_json_is_the_final_nonempty_stderr_line( + self, _decrypt, _get_config): + """Machine callers can ignore diagnostics and parse the final line.""" + _get_config.return_value = self.config + + def fail_after_diagnostic(*_args): + print('DEBUG diagnostic', file=shell.sys.stderr) + raise exceptions.ManagedKeyInvalidError( + 'vaultlocker-test/host/test-uuid', + ) + + _decrypt.side_effect = fail_after_diagnostic + stderr = io.StringIO() + + with mock.patch.object(shell.sys, 'stderr', stderr): + with self.assertRaises(SystemExit) as error: + shell.main() + + self.assertEqual(ExitCode.HANDLED_FAILURE, error.exception.code) + stderr_lines = [ + line for line in stderr.getvalue().splitlines() if line.strip() + ] + self.assertEqual('DEBUG diagnostic', stderr_lines[0]) + self.assertEqual( + { + 'error': ( + 'Vault secret at vaultlocker-test/host/test-uuid ' + 'does not contain dmcrypt_key' + ), + }, + json.loads(stderr_lines[-1]), + ) + + @mock.patch.object(shell.sys, 'exit') + @mock.patch.object(shell.sys, 'argv', + ['vaultlocker', 'encrypt', '/dev/sdb']) + @mock.patch.object(shell, 'get_config') + @mock.patch.object(shell, 'encrypt') + def test_main_unexpected_failure_exit_code( + self, _encrypt, _get_config, _exit): + """An unrecognized exception uses the unexpected-failure exit code.""" + _get_config.return_value = self.config + _encrypt.side_effect = RuntimeError('unexpected') + + with mock.patch('builtins.print') as _print: + shell.main() + + _exit.assert_called_once_with(ExitCode.UNEXPECTED_FAILURE) + printed = _print.call_args[0][0] + self.assertEqual( + { + 'error': 'unexpected', + }, + json.loads(printed), + ) + self.assertEqual(shell.sys.stderr, _print.call_args[1]['file']) + + @mock.patch.object(shell.argparse.ArgumentParser, 'print_help') + @mock.patch.object(shell.sys, 'argv', ['vaultlocker']) + def test_main_no_subcommand_prints_help(self, _print_help): + shell.main() + + _print_help.assert_called_once() + + @mock.patch.object(shell.sys, 'argv', ['vaultlocker', 'encrypt']) + def test_main_usage_error_is_not_handled_failure_exit_code(self): + """A CLI usage error must not be mistaken for a controlled result. + + argparse itself exits with status 2 on a missing required + argument, before any of vaultlocker's own error handling runs. + That must stay distinct from ``ExitCode.HANDLED_FAILURE``. + """ + with self.assertRaises(SystemExit) as error: + shell.main() + + self.assertEqual(2, error.exception.code) + self.assertNotEqual( + ExitCode.HANDLED_FAILURE, error.exception.code, + ) + + +class TestTenacityRetryBoundary(base.TestCase): + """Tests which Vault failures are retried.""" + + @mock.patch.object(shell, '_vault_client') + def test_vault_down_is_retried_within_the_bound( + self, _vault_client): + _vault_client.side_effect = [ + hvac.exceptions.VaultDown('sealed'), + mock.MagicMock(), + ] + + args = mock.MagicMock() + args.retry = 3 + func = mock.MagicMock(return_value={'luks_uuid': 'test-uuid'}) + + result = shell._do_it_with_persistence(func, args, mock.MagicMock()) + + self.assertEqual({'luks_uuid': 'test-uuid'}, result) + self.assertEqual(2, _vault_client.call_count) + func.assert_called_once() + + @mock.patch.object(shell, '_vault_client') + def test_credential_failure_is_not_retried(self, _vault_client): + _vault_client.side_effect = hvac.exceptions.Forbidden('bad creds') + + args = mock.MagicMock() + # A long window shows that credential errors still fail immediately. + args.retry = 10 + func = mock.MagicMock() + + with self.assertRaises(exceptions.VaultConnectionError): + shell._do_it_with_persistence(func, args, mock.MagicMock()) + + self.assertEqual(1, _vault_client.call_count) + func.assert_not_called() + + @mock.patch.object(shell, '_vault_client') + def test_unbounded_retry_still_fails_fast_on_credentials( + self, _vault_client): + """The default retry setting makes one attempt.""" + _vault_client.side_effect = hvac.exceptions.Forbidden('bad creds') + + args = mock.MagicMock() + args.retry = -1 + func = mock.MagicMock() + + with self.assertRaises(exceptions.VaultConnectionError): + shell._do_it_with_persistence(func, args, mock.MagicMock()) + + self.assertEqual(1, _vault_client.call_count) + func.assert_not_called() + + +class TestStoreAndValidateKey(base.TestCase): + """Shared write-then-verify used by every path that stores a key.""" + + def test_writes_and_confirms_the_key(self): + store = mock.MagicMock() + store.mount_point = 'vaultlocker-test' + store.read.return_value = {'dmcrypt_key': 'the-key'} + + shell._store_and_validate_key(store, 'host/uuid', 'the-key') + + store.write.assert_called_once_with( + 'host/uuid', {'dmcrypt_key': 'the-key'}, + ) + store.read.assert_called_once_with('host/uuid') + + def test_write_failure_is_reported(self): + store = mock.MagicMock() + store.mount_point = 'vaultlocker-test' + store.write.side_effect = hvac.exceptions.Forbidden('denied') + + with self.assertRaises(exceptions.VaultWriteError) as error: + shell._store_and_validate_key(store, 'host/uuid', 'the-key') + + self.assertIn('vaultlocker-test/host/uuid', str(error.exception)) + + def test_read_back_failure_is_reported(self): + store = mock.MagicMock() + store.mount_point = 'vaultlocker-test' + store.read.side_effect = hvac.exceptions.Forbidden('denied') + + with self.assertRaises(exceptions.VaultReadError) as error: + shell._store_and_validate_key(store, 'host/uuid', 'the-key') + + self.assertIn('vaultlocker-test/host/uuid', str(error.exception)) + + def test_malformed_read_back_is_reported(self): + store = mock.MagicMock() + store.mount_point = 'vaultlocker-test' + store.read.return_value = {'dmcrypt_key': ''} + + with self.assertRaises( + exceptions.ManagedKeyInvalidError) as error: + shell._store_and_validate_key( + store, 'host/uuid', 'the-key', + ) + + self.assertIn('vaultlocker-test/host/uuid', str(error.exception)) + + def test_mismatched_read_back_is_reported(self): + """A mismatched key is rejected.""" + store = mock.MagicMock() + store.mount_point = 'vaultlocker-test' + store.read.return_value = {'dmcrypt_key': 'a-different-key'} + + with self.assertRaises(exceptions.VaultKeyMismatch) as error: + shell._store_and_validate_key(store, 'host/uuid', 'the-key') + + self.assertIn('vaultlocker-test/host/uuid', str(error.exception)) + + +class TestReadLuksUuid(base.TestCase): + """Tests reading a device's LUKS UUID.""" + + @mock.patch.object(shell.dmcrypt, 'luks_uuid') + def test_returns_uuid_for_existing_header(self, _luks_uuid): + _luks_uuid.return_value = 'existing-uuid' + + self.assertEqual( + 'existing-uuid', shell._get_existing_luks_uuid('/dev/sdb'), + ) + + @mock.patch.object(shell.dmcrypt, 'luks_uuid') + def test_returns_none_for_the_no_header_exit_code(self, _luks_uuid): + _luks_uuid.side_effect = subprocess.CalledProcessError( + returncode=1, cmd='cryptsetup luksUUID', + ) + + self.assertIsNone(shell._get_existing_luks_uuid('/dev/sdb')) + + @mock.patch.object(shell.dmcrypt, 'luks_uuid') + def test_other_error_codes_are_not_treated_as_plain(self, _luks_uuid): + _luks_uuid.side_effect = subprocess.CalledProcessError( + returncode=5, cmd='cryptsetup luksUUID', + ) + + with self.assertRaises(exceptions.LuksValidationError) as error: + shell._get_existing_luks_uuid('/dev/sdb') + + self.assertIn('/dev/sdb', str(error.exception)) + + @mock.patch.object(shell.dmcrypt, 'luks_uuid') + def test_timeout_is_not_treated_as_plain(self, _luks_uuid): + _luks_uuid.side_effect = subprocess.TimeoutExpired( + cmd='cryptsetup', timeout=300, + ) + + with self.assertRaises(exceptions.LuksValidationError): + shell._get_existing_luks_uuid('/dev/sdb') + + +class TestCanUnlockDevice(base.TestCase): + """Tests checking whether a key unlocks a device.""" + + @mock.patch.object(shell.dmcrypt, 'luks_test_key', return_value=True) + def test_true_when_the_key_works(self, _luks_test_key): + self.assertTrue(shell._key_unlocks_device('key', '/dev/sdb')) + + @mock.patch.object(shell.dmcrypt, 'luks_test_key', return_value=False) + def test_false_when_the_key_does_not_work(self, _luks_test_key): + self.assertFalse(shell._key_unlocks_device('key', '/dev/sdb')) + + @mock.patch.object(shell.dmcrypt, 'luks_test_key') + def test_error_when_the_probe_itself_fails(self, _luks_test_key): + _luks_test_key.side_effect = subprocess.CalledProcessError( + returncode=-1, cmd='cryptsetup', + ) + + with self.assertRaises(exceptions.LuksValidationError): + shell._key_unlocks_device('key', '/dev/sdb') + + @mock.patch.object(shell.dmcrypt, 'luks_test_key') + def test_error_when_the_probe_times_out(self, _luks_test_key): + _luks_test_key.side_effect = subprocess.TimeoutExpired( + cmd='cryptsetup', timeout=300, + ) + + with self.assertRaises(exceptions.LuksValidationError): + shell._key_unlocks_device('key', '/dev/sdb') + + +class TestReadVaultKey(base.TestCase): + """Tests reading Vault keys.""" + + def test_none_when_nothing_stored(self): + store = mock.MagicMock() + store.read.side_effect = hvac.exceptions.InvalidPath('missing') + + self.assertIsNone(shell._read_vault_key(store, 'host/uuid')) + + def test_returns_stored_key(self): + store = mock.MagicMock() + store.read.return_value = {'dmcrypt_key': 'managed-key'} + + self.assertEqual( + 'managed-key', + shell._read_vault_key(store, 'host/uuid'), + ) + + def test_rejects_malformed_data_without_overwriting(self): + store = mock.MagicMock() + store.mount_point = 'vaultlocker-test' + store.read.return_value = {'not-a-key': 'value'} + + with self.assertRaises(exceptions.ManagedKeyInvalidError) as error: + shell._read_vault_key(store, 'host/uuid') + + self.assertIn('vaultlocker-test/host/uuid', str(error.exception)) + store.write.assert_not_called() + store.delete.assert_not_called() + + def test_rejects_non_dict_data_without_overwriting(self): + store = mock.MagicMock() + store.mount_point = 'vaultlocker-test' + store.read.return_value = 'not-a-dict' + + with self.assertRaises(exceptions.ManagedKeyInvalidError): + shell._read_vault_key(store, 'host/uuid') + + store.write.assert_not_called() + + +class TestEnsureVaultKey(base.TestCase): + """Tests safely storing a Vault key.""" + + def test_absent_key_is_written_and_verified(self): + store = mock.MagicMock() + store.mount_point = 'vaultlocker-test' + store.read.side_effect = [ + hvac.exceptions.InvalidPath('missing'), + {'dmcrypt_key': 'expected-key'}, + ] + + shell._ensure_vault_key( + store, 'host/uuid', 'expected-key', + ) + + store.write.assert_called_once_with( + 'host/uuid', {'dmcrypt_key': 'expected-key'}, + ) + + def test_same_existing_key_is_reused_without_writing(self): + store = mock.MagicMock() + store.read.return_value = {'dmcrypt_key': 'expected-key'} + + shell._ensure_vault_key( + store, 'host/uuid', 'expected-key', + ) + + store.write.assert_not_called() + + def test_different_existing_key_fails_without_writing(self): + store = mock.MagicMock() + store.mount_point = 'vaultlocker-test' + store.read.return_value = {'dmcrypt_key': 'existing-key'} + + with self.assertRaises(exceptions.VaultKeyMismatch): + shell._ensure_vault_key( + store, 'host/uuid', 'expected-key', + ) + + store.write.assert_not_called() + + +class TestOpenAndRegisterDevice(base.TestCase): + """Tests opening and registering a device.""" + + @mock.patch.object(shell, '_register_boot_unlock') + @mock.patch.object(shell, '_device_exists', return_value=False) + @mock.patch.object(shell, 'dmcrypt') + def test_opens_mapper_when_missing( + self, _dmcrypt, _device_exists, _register): + result = shell._open_and_register_device( + '/dev/sdb', 'test-uuid', 'the-key', '/path/to/conf', + ) + + _dmcrypt.luks_open.assert_called_once_with( + 'the-key', 'test-uuid', '/dev/sdb', + ) + _register.assert_called_once_with( + '/dev/sdb', 'test-uuid', '/path/to/conf', + ) + self.assertEqual( + { + 'luks_uuid': 'test-uuid', + 'mapper_path': '/dev/mapper/crypt-test-uuid', + }, + result, + ) + + @mock.patch.object(shell, '_register_boot_unlock') + @mock.patch.object(shell, '_device_exists', return_value=True) + @mock.patch.object(shell, 'dmcrypt') + def test_skips_opening_an_already_open_mapper( + self, _dmcrypt, _device_exists, _register): + """An open mapper is not opened again.""" + result = shell._open_and_register_device( + '/dev/sdb', 'test-uuid', 'the-key', '/path/to/conf', + ) + + _dmcrypt.luks_open.assert_not_called() + _register.assert_called_once_with( + '/dev/sdb', 'test-uuid', '/path/to/conf', + ) + self.assertEqual('test-uuid', result['luks_uuid']) + + @mock.patch.object(shell, '_device_exists', return_value=False) + @mock.patch.object(shell, 'dmcrypt') + def test_mapper_open_failure_is_reported(self, _dmcrypt, _device_exists): + _dmcrypt.luks_open.side_effect = subprocess.CalledProcessError( + returncode=-1, cmd='cryptsetup', + ) + + with self.assertRaises(exceptions.MapperOpenError): + shell._open_and_register_device( + '/dev/sdb', 'test-uuid', 'the-key', '/path/to/conf', + ) + + +class TestReuseEncryptedDevice(base.TestCase): + """Tests reusing an encrypted device.""" + + @mock.patch.object(shell, '_open_and_register_device') + @mock.patch.object(shell, '_key_unlocks_device', return_value=True) + @mock.patch.object(shell, '_read_vault_key') + @mock.patch.object(shell, '_vault_store') + def test_reuses_when_the_managed_key_works( + self, _vault_store, _read_vault_key, _key_unlocks_device, + _open_and_register): + _read_vault_key.return_value = 'managed-key' + _open_and_register.return_value = {'luks_uuid': 'existing-uuid'} + + args = mock.MagicMock() + args.uuid = None + args.config = '/path/to/conf' + + result = shell._open_existing_managed_device( + args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + 'existing-uuid', + ) + + _key_unlocks_device.assert_called_once_with('managed-key', '/dev/sdb') + _open_and_register.assert_called_once_with( + '/dev/sdb', 'existing-uuid', 'managed-key', '/path/to/conf', + ) + self.assertEqual({'luks_uuid': 'existing-uuid'}, result) + + @mock.patch.object(shell, '_vault_store') + def test_rejects_a_uuid_that_does_not_match_the_device( + self, _vault_store): + args = mock.MagicMock() + args.uuid = 'requested-uuid' + + with self.assertRaises(exceptions.LuksValidationError): + shell._open_existing_managed_device( + args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + 'existing-uuid', + ) + + _vault_store.assert_not_called() + + @mock.patch.object(shell, '_read_vault_key', return_value=None) + @mock.patch.object(shell, '_vault_store') + def test_refuses_a_device_with_no_managed_key( + self, _vault_store, _read_vault_key): + """An unmanaged device is not reformatted.""" + args = mock.MagicMock() + args.uuid = None + + with self.assertRaises(exceptions.LuksValidationError) as error: + shell._open_existing_managed_device( + args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + 'existing-uuid', + ) + + self.assertIn('no', str(error.exception)) + + @mock.patch.object(shell, '_key_unlocks_device', return_value=False) + @mock.patch.object(shell, '_read_vault_key') + @mock.patch.object(shell, '_vault_store') + def test_refuses_a_managed_key_that_does_not_unlock_it( + self, _vault_store, _read_vault_key, _key_unlocks_device): + _read_vault_key.return_value = 'wrong-key' + + args = mock.MagicMock() + args.uuid = None + + with self.assertRaises(exceptions.LuksValidationError): + shell._open_existing_managed_device( + args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + 'existing-uuid', + ) + + +class TestFormatCompleted(base.TestCase): + """Tests checking a failed format.""" + + @mock.patch.object(shell, '_key_unlocks_device', return_value=True) + @mock.patch.object(shell.dmcrypt, 'luks_uuid', return_value='the-uuid') + def test_true_when_uuid_and_key_both_match(self, _luks_uuid, + _key_unlocks_device): + self.assertTrue( + shell._format_completed('/dev/sdb', 'the-uuid', 'the-key'), + ) + + @mock.patch.object(shell.dmcrypt, 'luks_uuid') + def test_false_when_the_device_cannot_be_inspected(self, _luks_uuid): + _luks_uuid.side_effect = subprocess.CalledProcessError( + returncode=1, cmd='cryptsetup', + ) + + self.assertFalse( + shell._format_completed('/dev/sdb', 'the-uuid', 'the-key'), + ) + + @mock.patch.object(shell.dmcrypt, 'luks_uuid', return_value='other-uuid') + def test_false_when_the_uuid_does_not_match(self, _luks_uuid): + self.assertFalse( + shell._format_completed('/dev/sdb', 'the-uuid', 'the-key'), + ) + + @mock.patch.object(shell, '_key_unlocks_device', return_value=False) + @mock.patch.object(shell.dmcrypt, 'luks_uuid', return_value='the-uuid') + def test_false_when_the_key_does_not_unlock_it( + self, _luks_uuid, _key_unlocks_device): + self.assertFalse( + shell._format_completed('/dev/sdb', 'the-uuid', 'the-key'), + ) + + +class TestFormatDevice(base.TestCase): + """Tests formatting a plain device.""" + + @mock.patch.object(shell.dmcrypt, 'luks_format') + @mock.patch.object(shell, '_vault_store') + def test_different_existing_key_prevents_write_and_format( + self, _vault_store, _luks_format): + store = _vault_store.return_value + store.mount_point = 'vaultlocker-test' + store.read.return_value = {'dmcrypt_key': 'existing-key'} + + args = mock.MagicMock() + + with self.assertRaises(exceptions.VaultKeyMismatch): + shell._format_device( + args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + 'new-uuid', 'expected-key', + ) + + store.write.assert_not_called() + _luks_format.assert_not_called() + + @mock.patch.object(shell.dmcrypt, 'luks_format') + @mock.patch.object(shell, '_vault_store') + def test_malformed_existing_key_prevents_write_and_format( + self, _vault_store, _luks_format): + store = _vault_store.return_value + store.mount_point = 'vaultlocker-test' + + malformed_data = ( + 'not-a-mapping', + {}, + {'dmcrypt_key': ''}, + ) + for stored_data in malformed_data: + with self.subTest(stored_data=stored_data): + store.read.return_value = stored_data + with self.assertRaises(exceptions.ManagedKeyInvalidError): + shell._format_device( + mock.MagicMock(), mock.MagicMock(), + mock.MagicMock(), '/dev/sdb', 'new-uuid', + 'expected-key', + ) + + store.write.assert_not_called() + _luks_format.assert_not_called() + + @mock.patch.object( + shell.boot_unlock, 'running_in_snap', return_value=False, + ) + @mock.patch.object(shell, '_open_and_register_device') + @mock.patch.object(shell, '_ensure_vault_key') + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'udevadm_settle') + @mock.patch.object(shell.dmcrypt, 'udevadm_rescan') + @mock.patch.object(shell.dmcrypt, 'luks_format') + def test_formats_stores_key_first_and_completes( + self, _luks_format, _udevadm_rescan, _udevadm_settle, + _vault_store, _ensure_vault_key, _open_and_register, + _running_in_snap): + _open_and_register.return_value = {'luks_uuid': 'new-uuid'} + + args = mock.MagicMock() + args.config = '/path/to/conf' + + result = shell._format_device( + args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + 'new-uuid', 'new-key', + ) + + _ensure_vault_key.assert_called_once_with( + _vault_store.return_value, mock.ANY, 'new-key', + ) + _luks_format.assert_called_once_with('new-key', '/dev/sdb', + 'new-uuid') + _udevadm_rescan.assert_called_once_with('/dev/sdb') + _udevadm_settle.assert_called_once_with('new-uuid') + _open_and_register.assert_called_once_with( + '/dev/sdb', 'new-uuid', 'new-key', '/path/to/conf', + ) + self.assertEqual({'luks_uuid': 'new-uuid'}, result) + + @mock.patch.object(shell.boot_unlock, 'running_in_snap', + return_value=True) + @mock.patch.object(shell, '_open_and_register_device') + @mock.patch.object(shell, '_ensure_vault_key') + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'udevadm_settle') + @mock.patch.object(shell.dmcrypt, 'udevadm_rescan') + @mock.patch.object(shell.dmcrypt, 'luks_format') + def test_format_skips_udev_in_snap( + self, _luks_format, _udevadm_rescan, _udevadm_settle, + _vault_store, _ensure_vault_key, _open_and_register, + _running_in_snap): + args = mock.MagicMock() + args.config = '/path/to/conf' + + shell._format_device( + args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + 'new-uuid', 'new-key', + ) + + _luks_format.assert_called_once_with( + 'new-key', '/dev/sdb', 'new-uuid', + ) + _udevadm_rescan.assert_not_called() + _udevadm_settle.assert_not_called() + _open_and_register.assert_called_once_with( + '/dev/sdb', 'new-uuid', 'new-key', '/path/to/conf', + ) + + @mock.patch.object(shell, '_open_and_register_device') + @mock.patch.object(shell, '_format_completed', return_value=True) + @mock.patch.object(shell, '_ensure_vault_key') + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'udevadm_settle') + @mock.patch.object(shell.dmcrypt, 'udevadm_rescan') + @mock.patch.object(shell.dmcrypt, 'luks_format') + def test_timeout_that_actually_completed_is_not_fatal( + self, _luks_format, _udevadm_rescan, _udevadm_settle, + _vault_store, _ensure_vault_key, _format_completed, + _open_and_register): + """A completed format survives a timeout.""" + _luks_format.side_effect = subprocess.TimeoutExpired( + cmd='cryptsetup', timeout=300, + ) + _open_and_register.return_value = {'luks_uuid': 'new-uuid'} + + args = mock.MagicMock() + args.config = '/path/to/conf' + + result = shell._format_device( + args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + 'new-uuid', 'new-key', + ) + + _format_completed.assert_called_once_with( + '/dev/sdb', 'new-uuid', 'new-key', + ) + _open_and_register.assert_called_once_with( + '/dev/sdb', 'new-uuid', 'new-key', '/path/to/conf', + ) + self.assertEqual({'luks_uuid': 'new-uuid'}, result) + + @mock.patch.object(shell, '_format_completed', return_value=False) + @mock.patch.object(shell, '_ensure_vault_key') + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'luks_format') + def test_genuine_format_failure_preserves_the_vault_key( + self, _luks_format, _vault_store, _ensure_vault_key, + _format_completed): + """The Vault key must survive a genuine format failure. + + It must never be deleted once luksFormat may have started: it + may be the only thing that can unlock the device. + """ + _luks_format.side_effect = subprocess.CalledProcessError( + returncode=-1, cmd='cryptsetup', + ) + + args = mock.MagicMock() + args.config = '/path/to/conf' + + with self.assertRaises(exceptions.LuksFormatError): + shell._format_device( + args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + 'new-uuid', 'new-key', + ) + + store = _vault_store.return_value + store.delete.assert_not_called() + + @mock.patch.object(shell, '_open_and_register_device') + @mock.patch.object(shell, '_ensure_vault_key') + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'udevadm_settle') + @mock.patch.object(shell.dmcrypt, 'udevadm_rescan') + @mock.patch.object(shell.dmcrypt, 'luks_format') + def test_udev_failure_is_not_fatal( + self, _luks_format, _udevadm_rescan, _udevadm_settle, + _vault_store, _ensure_vault_key, _open_and_register): + _udevadm_rescan.side_effect = subprocess.CalledProcessError( + returncode=-1, cmd='udevadm', + ) + _open_and_register.return_value = {'luks_uuid': 'new-uuid'} + + args = mock.MagicMock() + args.config = '/path/to/conf' + + result = shell._format_device( + args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + 'new-uuid', 'new-key', + ) + + self.assertEqual({'luks_uuid': 'new-uuid'}, result) + + @mock.patch.object(shell.os.path, 'exists', return_value=True) + @mock.patch.object(shell, '_open_and_register_device') + @mock.patch.object(shell, '_ensure_vault_key') + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'udevadm_settle') + @mock.patch.object(shell.dmcrypt, 'udevadm_rescan') + @mock.patch.object(shell.dmcrypt, 'luks_format') + def test_udev_failure_with_existing_symlink_is_quiet( + self, _luks_format, _udevadm_rescan, _udevadm_settle, + _vault_store, _ensure_vault_key, _open_and_register, _exists): + _udevadm_rescan.side_effect = subprocess.CalledProcessError( + returncode=-1, cmd='udevadm', + ) + _open_and_register.return_value = {'luks_uuid': 'new-uuid'} + + args = mock.MagicMock() + args.config = '/path/to/conf' + + result = shell._format_device( + args, mock.MagicMock(), mock.MagicMock(), '/dev/sdb', + 'new-uuid', 'new-key', + ) + + self.assertEqual({'luks_uuid': 'new-uuid'}, result) + + +class TestEncryptBlockDevice(base.TestCase): + """Tests choosing between reuse and format.""" + + @mock.patch.object(shell, '_format_device') + @mock.patch.object(shell, '_open_existing_managed_device') + @mock.patch.object(shell, '_get_existing_luks_uuid', return_value=None) + def test_dispatches_to_format_when_plain( + self, _read_uuid, _reuse, _format_device): + _format_device.return_value = {'luks_uuid': 'new-uuid'} + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + + result = shell._encrypt_block_device( + args, mock.MagicMock(), mock.MagicMock(), + new_uuid='new-uuid', new_key='new-key', + ) + + _reuse.assert_not_called() + _format_device.assert_called_once_with( + args, mock.ANY, mock.ANY, '/dev/sdb', + 'new-uuid', 'new-key', + ) + self.assertEqual({'luks_uuid': 'new-uuid'}, result) + + @mock.patch.object(shell, '_format_device') + @mock.patch.object(shell, '_open_existing_managed_device') + @mock.patch.object(shell, '_get_existing_luks_uuid', + return_value='existing-uuid') + def test_dispatches_to_reuse_when_already_luks( + self, _read_uuid, _reuse, _format_device): + _reuse.return_value = {'luks_uuid': 'existing-uuid'} + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + + result = shell._encrypt_block_device( + args, mock.MagicMock(), mock.MagicMock(), + new_uuid='new-uuid', new_key='new-key', + ) + + _format_device.assert_not_called() + _reuse.assert_called_once_with( + args, mock.ANY, mock.ANY, '/dev/sdb', 'existing-uuid', + ) + self.assertEqual({'luks_uuid': 'existing-uuid'}, result) + + +class TestEncryptHandler(base.TestCase): + """Tests the encrypt handler.""" + + @mock.patch.object(shell, '_do_it_with_persistence') + @mock.patch.object(shell.dmcrypt, 'generate_key', + return_value='generated-key') + @mock.patch.object(shell.uuid, 'uuid4', return_value='generated-uuid') + def test_generates_a_uuid_when_none_was_requested( + self, _uuid4, _generate_key, _do): + args = mock.MagicMock() + args.uuid = None + config = mock.MagicMock() + + shell.encrypt(args, config) + + _uuid4.assert_called_once() + operation = _do.call_args[0][0] + self.assertEqual( + 'generated-uuid', operation.keywords['new_uuid'], + ) + self.assertEqual( + 'generated-key', operation.keywords['new_key'], + ) + + @mock.patch.object(shell, '_do_it_with_persistence') + @mock.patch.object(shell.dmcrypt, 'generate_key', + return_value='generated-key') + @mock.patch.object(shell.uuid, 'uuid4') + def test_uses_the_requested_uuid_without_generating_one( + self, _uuid4, _generate_key, _do): + args = mock.MagicMock() + args.uuid = 'requested-uuid' + config = mock.MagicMock() + + shell.encrypt(args, config) + + _uuid4.assert_not_called() + operation = _do.call_args[0][0] + self.assertEqual( + 'requested-uuid', operation.keywords['new_uuid'], + ) + + @mock.patch.object(shell, '_encrypt_block_device') + @mock.patch.object(shell, '_vault_client') + @mock.patch.object(shell.dmcrypt, 'generate_key', + return_value='generated-key') + @mock.patch.object(shell.uuid, 'uuid4', return_value='generated-uuid') + def test_new_uuid_and_key_are_stable_across_internal_retries( + self, _uuid4, _generate_key, _vault_client, + _encrypt_impl): + """Retries keep the same UUID and key.""" + _vault_client.return_value = mock.MagicMock() + _encrypt_impl.side_effect = [ + hvac.exceptions.VaultDown('sealed'), + { + 'luks_uuid': 'generated-uuid', + 'mapper_path': '/dev/mapper/crypt-generated-uuid', + }, + ] + + args = mock.MagicMock() + args.uuid = None + args.retry = 3 + config = mock.MagicMock() + + result = shell.encrypt(args, config) + + _uuid4.assert_called_once() + _generate_key.assert_called_once() + self.assertEqual(2, _encrypt_impl.call_count) + for call in _encrypt_impl.call_args_list: + self.assertEqual( + 'generated-uuid', call.kwargs['new_uuid'], + ) + self.assertEqual('generated-key', call.kwargs['new_key']) + self.assertEqual('generated-uuid', result['luks_uuid']) + + +class TestEnrollBlockDevice(base.TestCase): + """Tests adding or reusing a Vault key.""" + + @mock.patch.object(shell, '_open_and_register_device') + @mock.patch.object(shell, '_read_vault_key') + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'luks_uuid', return_value='test-uuid') + def test_succeeds_without_the_original_credential_when_already_enrolled( + self, _luks_uuid, _vault_store, _read_vault_key, + _open_and_register): + """A repeated enrollment does not need the current key.""" + _read_vault_key.return_value = 'managed-key' + _open_and_register.return_value = {'luks_uuid': 'test-uuid'} + + get_operator_key = mock.MagicMock( + side_effect=AssertionError('credential should not be read'), + ) + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + args.config = '/path/to/conf' + + with mock.patch.object( + shell, '_key_unlocks_device', return_value=True, + ) as key_check: + result = shell._enroll_block_device( + args, mock.MagicMock(), mock.MagicMock(), get_operator_key, + ) + + get_operator_key.assert_not_called() + key_check.assert_called_once_with('managed-key', '/dev/sdb') + _open_and_register.assert_called_once_with( + '/dev/sdb', 'test-uuid', 'managed-key', '/path/to/conf', + ) + self.assertEqual({'luks_uuid': 'test-uuid'}, result) + + @mock.patch.object(shell, '_open_and_register_device') + @mock.patch.object(shell, '_store_and_validate_key') + @mock.patch.object(shell, '_read_vault_key', return_value=None) + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'luks_add_key') + @mock.patch.object(shell.dmcrypt, 'generate_key', + return_value='new-managed-key') + @mock.patch.object(shell.dmcrypt, 'luks_uuid', return_value='test-uuid') + def test_generates_and_adds_a_managed_key_when_none_exists( + self, _luks_uuid, _generate_key, _luks_add_key, _vault_store, + _read_vault_key, _store_and_validate_key, _open_and_register): + _open_and_register.return_value = {'luks_uuid': 'test-uuid'} + get_operator_key = mock.MagicMock(return_value=b'existing-key') + + def can_unlock(key, device): + return key == b'existing-key' or key == 'new-managed-key' + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + args.config = '/path/to/conf' + + with mock.patch.object( + shell, '_key_unlocks_device', + side_effect=can_unlock, + ) as key_check: + result = shell._enroll_block_device( + args, mock.MagicMock(), mock.MagicMock(), get_operator_key, + ) + + get_operator_key.assert_called_once() + _store_and_validate_key.assert_called_once_with( + _vault_store.return_value, mock.ANY, 'new-managed-key', + ) + _luks_add_key.assert_called_once_with( + b'existing-key', 'new-managed-key', '/dev/sdb', + ) + _open_and_register.assert_called_once_with( + '/dev/sdb', 'test-uuid', 'new-managed-key', '/path/to/conf', + ) + self.assertEqual({'luks_uuid': 'test-uuid'}, result) + self.assertEqual(2, key_check.call_count) + + @mock.patch.object(shell, '_open_and_register_device') + @mock.patch.object(shell, '_store_and_validate_key') + @mock.patch.object(shell, '_read_vault_key') + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'luks_add_key') + @mock.patch.object(shell.dmcrypt, 'generate_key') + @mock.patch.object(shell.dmcrypt, 'luks_uuid', return_value='test-uuid') + def test_reuses_a_pre_provisioned_managed_key_instead_of_replacing_it( + self, _luks_uuid, _generate_key, _luks_add_key, _vault_store, + _read_vault_key, _store_and_validate_key, _open_and_register): + """A saved Vault key is reused.""" + _read_vault_key.return_value = 'pre-provisioned-key' + _open_and_register.return_value = {'luks_uuid': 'test-uuid'} + get_operator_key = mock.MagicMock(return_value=b'existing-key') + + # Check before and after adding the key. + unlock_results = [False, True, True] + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + args.config = '/path/to/conf' + + with mock.patch.object( + shell, '_key_unlocks_device', + side_effect=unlock_results): + shell._enroll_block_device( + args, mock.MagicMock(), mock.MagicMock(), get_operator_key, + ) + + _generate_key.assert_not_called() + _store_and_validate_key.assert_not_called() + _luks_add_key.assert_called_once_with( + b'existing-key', 'pre-provisioned-key', '/dev/sdb', + ) + + @mock.patch.object(shell.dmcrypt, 'luks_add_key') + @mock.patch.object(shell.dmcrypt, 'luks_test_key') + @mock.patch.object(shell, '_read_vault_key', return_value='managed-key') + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'luks_uuid', return_value='test-uuid') + def test_inconclusive_managed_key_probe_does_not_add_another_key( + self, _luks_uuid, _vault_store, _read_vault_key, + _luks_test_key, _luks_add_key): + _luks_test_key.side_effect = subprocess.TimeoutExpired( + cmd='cryptsetup', timeout=300, + ) + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + get_operator_key = mock.MagicMock(return_value=b'existing-key') + + with self.assertRaises(exceptions.LuksValidationError): + shell._enroll_block_device( + args, mock.MagicMock(), mock.MagicMock(), get_operator_key, + ) + + get_operator_key.assert_not_called() + _luks_add_key.assert_not_called() + + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'luks_uuid') + def test_uuid_lookup_failure_is_reported_before_touching_vault( + self, _luks_uuid, _vault_store): + _luks_uuid.side_effect = subprocess.CalledProcessError( + returncode=-1, cmd='cryptsetup', + ) + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + + with self.assertRaises(exceptions.LuksValidationError): + shell._enroll_block_device( + args, mock.MagicMock(), mock.MagicMock(), + mock.MagicMock(), + ) + + _vault_store.assert_not_called() + + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'luks_uuid') + def test_uuid_lookup_timeout_is_reported_before_touching_vault( + self, _luks_uuid, _vault_store): + _luks_uuid.side_effect = subprocess.TimeoutExpired( + cmd='cryptsetup', timeout=300, + ) + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + + with self.assertRaises(exceptions.LuksValidationError): + shell._enroll_block_device( + args, mock.MagicMock(), mock.MagicMock(), + mock.MagicMock(), + ) + + _vault_store.assert_not_called() + + @mock.patch.object(shell, '_read_vault_key', return_value=None) + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'luks_uuid', return_value='test-uuid') + def test_rejects_an_existing_credential_that_does_not_unlock_it( + self, _luks_uuid, _vault_store, _read_vault_key): + get_operator_key = mock.MagicMock(return_value=b'wrong-key') + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + + with mock.patch.object( + shell, '_key_unlocks_device', return_value=False, + ): + with self.assertRaises( + exceptions.ExistingKeyInvalidError) as error: + shell._enroll_block_device( + args, mock.MagicMock(), mock.MagicMock(), + get_operator_key, + ) + + self.assertEqual( + 'Existing key does not unlock /dev/sdb', + str(error.exception), + ) + get_operator_key.assert_called_once() + + @mock.patch.object(shell, '_open_and_register_device') + @mock.patch.object(shell, '_store_and_validate_key') + @mock.patch.object(shell, '_read_vault_key', return_value=None) + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'luks_add_key') + @mock.patch.object(shell.dmcrypt, 'generate_key', + return_value='new-managed-key') + @mock.patch.object(shell.dmcrypt, 'luks_uuid', return_value='test-uuid') + def test_add_key_timeout_that_actually_completed_is_not_fatal( + self, _luks_uuid, _generate_key, _luks_add_key, _vault_store, + _read_vault_key, _store_and_validate_key, _open_and_register): + """A completed key addition survives a timeout.""" + _luks_add_key.side_effect = subprocess.TimeoutExpired( + cmd='cryptsetup', timeout=300, + ) + _open_and_register.return_value = {'luks_uuid': 'test-uuid'} + get_operator_key = mock.MagicMock(return_value=b'existing-key') + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + args.config = '/path/to/conf' + + with mock.patch.object( + shell, '_key_unlocks_device', return_value=True, + ): + result = shell._enroll_block_device( + args, mock.MagicMock(), mock.MagicMock(), get_operator_key, + ) + + self.assertEqual({'luks_uuid': 'test-uuid'}, result) + + @mock.patch.object(shell, '_store_and_validate_key') + @mock.patch.object(shell, '_read_vault_key', return_value=None) + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'luks_add_key') + @mock.patch.object(shell.dmcrypt, 'generate_key', + return_value='new-managed-key') + @mock.patch.object(shell.dmcrypt, 'luks_uuid', return_value='test-uuid') + def test_add_key_failure_preserves_the_managed_key( + self, _luks_uuid, _generate_key, _luks_add_key, _vault_store, + _read_vault_key, _store_and_validate_key): + _luks_add_key.side_effect = subprocess.CalledProcessError( + returncode=-1, cmd='cryptsetup', + ) + get_operator_key = mock.MagicMock(return_value=b'existing-key') + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + + def can_unlock(key, device): + return key == b'existing-key' + + with mock.patch.object( + shell, '_key_unlocks_device', + side_effect=can_unlock): + with self.assertRaises(exceptions.LuksAddKeyError): + shell._enroll_block_device( + args, mock.MagicMock(), mock.MagicMock(), + get_operator_key, + ) + + store = _vault_store.return_value + store.delete.assert_not_called() + + @mock.patch.object(shell, '_store_and_validate_key') + @mock.patch.object(shell, '_read_vault_key', return_value=None) + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'luks_add_key') + @mock.patch.object(shell.dmcrypt, 'generate_key', + return_value='new-managed-key') + @mock.patch.object(shell.dmcrypt, 'luks_uuid', return_value='test-uuid') + def test_add_key_that_silently_did_not_take_is_reported( + self, _luks_uuid, _generate_key, _luks_add_key, _vault_store, + _read_vault_key, _store_and_validate_key): + """An ineffective key addition is rejected.""" + get_operator_key = mock.MagicMock(return_value=b'existing-key') + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + + def can_unlock(key, device): + return key == b'existing-key' + + with mock.patch.object( + shell, '_key_unlocks_device', + side_effect=can_unlock): + with self.assertRaises(exceptions.LuksAddKeyError): + shell._enroll_block_device( + args, mock.MagicMock(), mock.MagicMock(), + get_operator_key, + ) + + _luks_add_key.assert_called_once() + + +class TestEnrollHandler(base.TestCase): + """Tests the enroll handler.""" + + @mock.patch.object(shell, '_do_it_with_persistence') + @mock.patch.object(shell, '_read_existing_key', return_value=b'secret') + def test_credential_is_cached_across_repeated_use( + self, _read_existing_key, _do): + args = mock.MagicMock() + args.existing_key_file = '/path/to/key' + config = mock.MagicMock() + + shell.enroll(args, config) + + operation = _do.call_args[0][0] + get_operator_key = operation.keywords['get_operator_key'] + + # Repeated reads use the cached key. + first = get_operator_key() + second = get_operator_key() + + self.assertEqual(b'secret', first) + self.assertEqual(b'secret', second) + _read_existing_key.assert_called_once_with('/path/to/key') + + @mock.patch.object(shell, '_do_it_with_persistence') + @mock.patch.object(shell, '_read_existing_key') + def test_credential_is_never_read_when_not_needed( + self, _read_existing_key, _do): + args = mock.MagicMock() + args.existing_key_file = None + config = mock.MagicMock() + + shell.enroll(args, config) + + # The mocked operation does not request the current key. + _read_existing_key.assert_not_called() + + +class TestKVConfiguration(base.TestCase): + + def _config(self, kv_version=None): + config = configparser.ConfigParser() + config.add_section('vault') + config.set('vault', 'backend', 'vaultlocker-test') + + if kv_version is not None: + config.set('vault', 'kv_version', kv_version) + + return config + + def test_kv_version_defaults_to_one(self): + self.assertEqual( + '1', + shell._get_kv_version(self._config()), + ) + + def test_kv_version_one(self): + self.assertEqual( + '1', + shell._get_kv_version(self._config('1')), + ) def test_kv_version_two(self): self.assertEqual( @@ -722,7 +1747,7 @@ def test_kv_version_two(self): ) def test_kv_version_rejects_other_number(self): - with self.assertRaises(ValueError) as error: + with self.assertRaises(exceptions.ConfigurationError) as error: shell._get_kv_version(self._config('3')) self.assertIn( @@ -738,3 +1763,223 @@ def test_secret_path_is_relative_to_mount(self, _get_hostname): 'test-host/test-uuid', shell._vault_secret_path('test-uuid', self._config()), ) + + +class TestHandlersAndConfig(base.TestCase): + """Coverage for the thin CLI handlers and config loading.""" + + @mock.patch.object(shell, '_do_it_with_persistence') + def test_encrypt_handler_delegates(self, _do): + _do.return_value = {'luks_uuid': 'test-uuid'} + args = mock.MagicMock() + args.uuid = 'passed-uuid' + config = mock.MagicMock() + + with mock.patch.object(shell.dmcrypt, 'generate_key', + return_value='key'): + result = shell.encrypt(args, config) + + operation = _do.call_args[0][0] + self.assertIs(shell._encrypt_block_device, operation.func) + self.assertEqual('passed-uuid', operation.keywords['new_uuid']) + self.assertIs(args, _do.call_args[0][1]) + self.assertIs(config, _do.call_args[0][2]) + self.assertEqual({'luks_uuid': 'test-uuid'}, result) + + @mock.patch.object(shell, '_do_it_with_persistence') + def test_enroll_handler_delegates(self, _do): + _do.return_value = {'luks_uuid': 'test-uuid'} + args = mock.MagicMock() + args.existing_key_file = '/path/to/key' + config = mock.MagicMock() + + result = shell.enroll(args, config) + + operation = _do.call_args[0][0] + self.assertIs(shell._enroll_block_device, operation.func) + self.assertTrue(callable(operation.keywords['get_operator_key'])) + self.assertIs(args, _do.call_args[0][1]) + self.assertIs(config, _do.call_args[0][2]) + self.assertEqual({'luks_uuid': 'test-uuid'}, result) + + @mock.patch.object(shell, '_do_it_with_persistence') + def test_decrypt_handler_delegates(self, _do): + _do.return_value = None + args = mock.MagicMock() + config = mock.MagicMock() + + result = shell.decrypt(args, config) + + _do.assert_called_once_with( + shell._decrypt_block_device, args, config, + ) + self.assertIsNone(result) + + def test_get_config_reads_and_validates_existing_file(self): + contents = """[vault] +url = https://vault.example +approle = role-id +secret_id = secret-id +backend = vaultlocker +kv_version = 2 +""" + with mock.patch( + 'builtins.open', mock.mock_open(read_data=contents)) as _open: + config = shell.get_config('/path/to/conf') + + _open.assert_called_once_with('/path/to/conf', 'r') + self.assertIsInstance(config, shell.configparser.ConfigParser) + self.assertEqual('2', config.get('vault', 'kv_version')) + + @mock.patch('builtins.open', side_effect=FileNotFoundError('missing')) + def test_get_config_missing_file_is_controlled(self, _open): + with self.assertRaises(exceptions.ConfigurationError) as error: + shell.get_config('/path/to/conf') + + self.assertIn( + 'Unable to load configuration /path/to/conf', + str(error.exception), + ) + + def test_get_config_malformed_file_is_controlled(self): + with mock.patch( + 'builtins.open', + mock.mock_open(read_data='not an ini file')): + with self.assertRaises(exceptions.ConfigurationError): + shell.get_config('/path/to/conf') + + def test_get_config_missing_required_option_is_controlled(self): + contents = """[vault] +url = https://vault.example +approle = role-id +secret_id = secret-id +""" + with mock.patch( + 'builtins.open', mock.mock_open(read_data=contents)): + with self.assertRaises(exceptions.ConfigurationError): + shell.get_config('/path/to/conf') + + def test_get_config_empty_required_option_is_controlled(self): + contents = """[vault] +url = https://vault.example +approle = role-id +secret_id = secret-id +backend = +""" + with mock.patch( + 'builtins.open', mock.mock_open(read_data=contents)): + with self.assertRaises(exceptions.ConfigurationError): + shell.get_config('/path/to/conf') + + def test_get_config_invalid_kv_version_is_controlled(self): + contents = """[vault] +url = https://vault.example +approle = role-id +secret_id = secret-id +backend = vaultlocker +kv_version = 3 +""" + with mock.patch( + 'builtins.open', mock.mock_open(read_data=contents)): + with self.assertRaises(exceptions.ConfigurationError): + shell.get_config('/path/to/conf') + + +class TestSubprocessTimeouts(base.TestCase): + """Cryptsetup timeouts are handled the same as ordinary failures.""" + + @mock.patch.object(shell, '_open_and_register_device') + @mock.patch.object(shell, '_ensure_vault_key') + @mock.patch.object(shell, '_vault_store') + @mock.patch.object(shell.dmcrypt, 'luks_uuid') + def test_encrypt_format_timeout_that_did_not_complete_fails( + self, _luks_uuid, _vault_store, _ensure_vault_key, + _open_and_register): + _luks_uuid.side_effect = [ + subprocess.CalledProcessError( + returncode=1, cmd='cryptsetup luksUUID', + ), + subprocess.TimeoutExpired(cmd='cryptsetup', timeout=300), + ] + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + args.config = '/path/to/conf' + + with mock.patch.object(shell.dmcrypt, 'luks_format') as _format: + _format.side_effect = subprocess.TimeoutExpired( + cmd='cryptsetup', timeout=300, + ) + + with self.assertRaises(exceptions.LuksFormatError): + shell._encrypt_block_device( + args, mock.MagicMock(), mock.MagicMock(), + new_uuid='passed-UUID', new_key='testkey', + ) + + _open_and_register.assert_not_called() + store = _vault_store.return_value + store.delete.assert_not_called() + + @mock.patch.object(shell, '_vault_store') + def test_enroll_validation_timeout_is_reported(self, _vault_store): + with mock.patch.object(shell.dmcrypt, 'luks_uuid') as _luks_uuid: + _luks_uuid.side_effect = subprocess.TimeoutExpired( + cmd='cryptsetup', timeout=300, + ) + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + + with self.assertRaises(exceptions.LuksValidationError): + shell._enroll_block_device( + args, mock.MagicMock(), mock.MagicMock(), + mock.MagicMock(), + ) + + _vault_store.assert_not_called() + + +class TestSubprocessErrorHelpers(base.TestCase): + + def test_output_prefers_captured_output(self): + error = subprocess.CalledProcessError( + returncode=1, cmd='cryptsetup', output=b'boom', + ) + self.assertEqual(b'boom', shell._subprocess_error_output(error)) + + def test_output_falls_back_to_stderr(self): + error = subprocess.TimeoutExpired( + cmd='cryptsetup', timeout=1, stderr=b'stderr-text', + ) + self.assertEqual(b'stderr-text', shell._subprocess_error_output(error)) + + def test_output_falls_back_to_string(self): + error = subprocess.TimeoutExpired(cmd='cryptsetup', timeout=1) + self.assertEqual(str(error), shell._subprocess_error_output(error)) + + def test_returncode(self): + error = subprocess.CalledProcessError(returncode=3, cmd='x') + self.assertEqual(3, shell._subprocess_error_returncode(error)) + + timeout = subprocess.TimeoutExpired(cmd='x', timeout=1) + self.assertIsNone(shell._subprocess_error_returncode(timeout)) + + +class TestRegisterBootUnlock(base.TestCase): + """Tests for boot-unlock registration failure classification.""" + + @mock.patch.object(shell, 'boot_unlock') + def test_registers_boot_unlock(self, _boot_unlock): + shell._register_boot_unlock('/dev/sdb', 'test-uuid', '/cfg') + + _boot_unlock.register.assert_called_once_with('test-uuid', '/cfg') + + @mock.patch.object(shell, 'boot_unlock') + def test_wraps_failure_as_boot_config_error(self, _boot_unlock): + _boot_unlock.register.side_effect = subprocess.CalledProcessError( + returncode=1, cmd='pebble', + ) + + with self.assertRaises(exceptions.BootConfigError): + shell._register_boot_unlock('/dev/sdb', 'test-uuid', '/cfg')