diff --git a/.coveragerc b/.coveragerc index df1e5e0..b9694c1 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,6 +1,9 @@ [run] branch = True source = vaultlocker +omit = + vaultlocker/tests/* [report] ignore_errors = True +fail_under = 90 diff --git a/README.rst b/README.rst index 76ac935..b697174 100644 --- a/README.rst +++ b/README.rst @@ -82,13 +82,22 @@ UUID):: sudo vaultlocker decrypt f65b9e66-8f0c-4cae-b6f5-6ec85ea134f2 -Vault authentication --------------------- +Vault authentication and cluster identity +----------------------------------------- Authentication to Vault is done using an AppRole with a secret_id; its assumed that a CIDR based ACL is in use to only allow permitted systems within the Data Center to login and retrieve secrets from Vault. +After authentication, vaultlocker saves the Vault cluster ID in ``.cluster-id``. +If the ID later changes, ``encrypt`` and ``enroll`` operations will fail with an error. +``decrypt`` will log a warning and try to find the key in the observed Vault cluster. If +that Vault does not have the key, vaultlocker cannot unlock the device. + +If the change is unexpected, check the Vault url and restore the connection to +the original cluster. Deleting the pin does not move existing keys. +Vaultlocker does not support automatically migrating keys between clusters. + * Free software: Apache license * Documentation: https://docs.openstack.org/vaultlocker/latest * Source: https://git.openstack.org/cgit/openstack/vaultlocker diff --git a/tox.ini b/tox.ini index f823071..bde351d 100644 --- a/tox.ini +++ b/tox.ini @@ -51,6 +51,7 @@ commands = coverage combine coverage html -d cover coverage xml -o cover/coverage.xml + coverage report --show-missing [testenv:docs] commands = python setup.py build_sphinx diff --git a/vaultlocker/exceptions.py b/vaultlocker/exceptions.py index f25893b..37c7ce9 100644 --- a/vaultlocker/exceptions.py +++ b/vaultlocker/exceptions.py @@ -112,3 +112,17 @@ class MapperOpenError(LUKSFailure): class BootConfigError(LUKSFailure): """Registering the boot-time unlock mechanism failed.""" + + +class ClusterIdentityError(VaultlockerException): + """The Vault cluster identity could not be verified.""" + + +class ClusterIdentityMismatchError(ClusterIdentityError): + """The connected Vault cluster does not match the saved cluster.""" + + def __init__(self, expected, actual): + super().__init__( + "Vault cluster identity mismatch: pinned cluster_id={}, " + "observed cluster_id={}".format(expected, actual) + ) diff --git a/vaultlocker/shell.py b/vaultlocker/shell.py index f31639c..9b85ef6 100644 --- a/vaultlocker/shell.py +++ b/vaultlocker/shell.py @@ -19,10 +19,12 @@ import json import logging import os +from pathlib import Path import platform import socket import subprocess import sys +import tempfile import uuid import hvac @@ -40,22 +42,96 @@ REQUIRED_VAULT_SETTINGS = ('url', 'approle', 'secret_id', 'backend') +#: Suffix of the sidecar file pinning the Vault cluster identity. +CLUSTER_ID_SUFFIX = '.cluster-id' -def _vault_client(config): - """Helper wrapper to create Vault Client - :param: config: configparser object of vaultlocker config - :returns: hvac.Client. configured Vault Client object - """ - client = hvac.Client( +def _vault_client(config): + """Create an unauthenticated Vault client.""" + return hvac.Client( url=config.get('vault', 'url'), - verify=config.get('vault', 'ca_bundle', fallback=True) + verify=config.get('vault', 'ca_bundle', fallback=True), ) + + +def _login_to_vault(client, config): + """Authenticate a Vault client with AppRole credentials.""" client.auth.approle.login( role_id=config.get('vault', 'approle'), - secret_id=config.get('vault', 'secret_id') + secret_id=config.get('vault', 'secret_id'), ) - return client + + +def _cluster_pin_path(config_path): + """Return the cluster pin path for a configuration file.""" + return '{}{}'.format(config_path, CLUSTER_ID_SUFFIX) + + +def _read_cluster_pin(path): + """Read the cluster pin from a sidecar.""" + try: + with open(path, 'r', encoding='utf-8') as sidecar: + value = sidecar.read().strip() + except (OSError, UnicodeError) as read_error: + raise exceptions.ClusterIdentityError( + 'Unable to read Vault cluster identity {}: {}'.format( + path, read_error, + ) + ) from read_error + if not value: + raise exceptions.ClusterIdentityError( + 'Invalid Vault cluster identity in {}'.format(path) + ) + return value + + +def _create_cluster_pin(path, cluster_id): + """Create a complete pin without replacing an existing one.""" + path = Path(path) + try: + # For almost all runs, the pin already exists. + try: + path.lstat() + except FileNotFoundError: + pass + else: + return _read_cluster_pin(path) + + fd, temporary_name = tempfile.mkstemp(dir=path.parent) + temporary_path = Path(temporary_name) + try: + with os.fdopen(fd, 'w', encoding='utf-8') as temp_file: + os.fchmod(temp_file.fileno(), 0o600) + temp_file.write(cluster_id) + + try: + os.link(temporary_path, path) + except FileExistsError: + # Another process created it first. + return _read_cluster_pin(path) + + return cluster_id + finally: + temporary_path.unlink(missing_ok=True) + except (OSError, UnicodeError) as error: + raise exceptions.ClusterIdentityError( + 'Unable to create Vault cluster identity {}: {}'.format( + path, error, + ) + ) from error + + +def _verify_cluster_identity(client, config_path): + """Pin the Vault cluster on first use and verify later connections.""" + observed_id = vault.get_cluster_id(client) + + pin_path = _cluster_pin_path(config_path) + pinned_id = _create_cluster_pin(pin_path, observed_id) + + if pinned_id != observed_id: + raise exceptions.ClusterIdentityMismatchError( + pinned_id, observed_id, + ) def _get_kv_version(config): @@ -590,12 +666,14 @@ def _device_exists(block_uuid): return os.path.exists(path) -def _do_it_with_persistence(func, args, config): +def _do_it_with_persistence(func, args, config, + fail_on_cluster_mismatch=True): """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 + :param: fail_on_cluster_mismatch: whether to stop on a mismatch :returns: the operation result """ @tenacity.retry( @@ -613,6 +691,13 @@ def _do_it_with_persistence(func, args, config): ) def _do_it(): client = _vault_client(config) + _login_to_vault(client, config) + try: + _verify_cluster_identity(client, args.config) + except exceptions.ClusterIdentityMismatchError as mismatch_error: + if fail_on_cluster_mismatch: + raise + logger.warning('Cluster identity mismatch: %s', mismatch_error) return func(args, client, config) try: @@ -678,7 +763,10 @@ def decrypt(args, config): :param: args: argparser generated cli arguments :param: config: configparser object of vaultlocker config """ - return _do_it_with_persistence(_decrypt_block_device, args, config) + return _do_it_with_persistence( + _decrypt_block_device, args, config, + fail_on_cluster_mismatch=False, + ) def get_config(config_path): diff --git a/vaultlocker/tests/functional/test_keystorage.py b/vaultlocker/tests/functional/test_keystorage.py index 39243bf..83825a7 100644 --- a/vaultlocker/tests/functional/test_keystorage.py +++ b/vaultlocker/tests/functional/test_keystorage.py @@ -34,6 +34,94 @@ class KeyStorageTestCase(base.VaultlockerFuncBaseTestCase): Subclasses run this suite against KV version 1 and 2. """ + def test_cluster_identity_pin_with_real_vault( + self, _luks_open, _luks_format, _boot_unlock, + _udevadm_rescan, _udevadm_settle): + """Seal status provides the value stored in the pin.""" + shell._verify_cluster_identity(self.vault_client, self.config_path) + + pin_path = shell._cluster_pin_path(self.config_path) + with open(pin_path, 'r', encoding='utf-8') as sidecar: + self.assertEqual( + shell.vault.get_cluster_id(self.vault_client), + sidecar.read(), + ) + + def _write_mismatching_pin(self): + pin_path = shell._cluster_pin_path(self.config_path) + with open(pin_path, 'w', encoding='utf-8') as sidecar: + sidecar.write('different-cluster') + return pin_path + + def test_cluster_mismatch_stops_encrypt( + self, _luks_open, _luks_format, _boot_unlock, + _udevadm_rescan, _udevadm_settle): + """Encrypt does not change a device on a cluster mismatch.""" + pin_path = self._write_mismatching_pin() + + args = mock.MagicMock() + args.uuid = 'passed-UUID' + args.block_device = ['/dev/sdb'] + args.retry = -1 + args.config = self.config_path + + with self.assertRaises(shell.exceptions.ClusterIdentityMismatchError): + shell.encrypt(args, self.config) + + _luks_open.assert_not_called() + _luks_format.assert_not_called() + with open(pin_path, 'r', encoding='utf-8') as sidecar: + self.assertEqual('different-cluster', sidecar.read()) + + def test_cluster_mismatch_stops_enroll( + self, _luks_open, _luks_format, _boot_unlock, + _udevadm_rescan, _udevadm_settle): + """Enroll does not change a device on a cluster mismatch.""" + pin_path = self._write_mismatching_pin() + + args = mock.MagicMock() + args.block_device = ['/dev/sdb'] + args.existing_key_file = None + args.retry = -1 + args.config = self.config_path + + with mock.patch.object(shell, '_read_existing_key') as read_key: + with self.assertRaises( + shell.exceptions.ClusterIdentityMismatchError): + shell.enroll(args, self.config) + + read_key.assert_not_called() + _luks_open.assert_not_called() + with open(pin_path, 'r', encoding='utf-8') as sidecar: + self.assertEqual('different-cluster', sidecar.read()) + + def test_cluster_mismatch_warns_and_attempts_decrypt( + self, _luks_open, _luks_format, _boot_unlock, + _udevadm_rescan, _udevadm_settle): + """Decrypt attempts an unlock with a key from the observed Vault.""" + pin_path = self._write_mismatching_pin() + self.vault_store().write( + self.secret_path('passed-UUID'), + {'dmcrypt_key': 'testkey'}, + ) + + 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): + with self.assertLogs(shell.logger, level='WARNING') as logged: + shell.decrypt(args, self.config) + + self.assertTrue(any( + 'Vault cluster identity mismatch' in warning + for warning in logged.output + )) + _luks_open.assert_called_once_with('testkey', 'passed-UUID') + with open(pin_path, 'r', encoding='utf-8') as sidecar: + self.assertEqual('different-cluster', sidecar.read()) + def test_encrypt(self, _luks_open, _luks_format, _boot_unlock, _udevadm_rescan, _udevadm_settle): """Test encrypt function stores correct data in vault""" diff --git a/vaultlocker/tests/unit/test_command_results.py b/vaultlocker/tests/unit/test_command_results.py index 3cd6a42..a2d54bd 100644 --- a/vaultlocker/tests/unit/test_command_results.py +++ b/vaultlocker/tests/unit/test_command_results.py @@ -83,8 +83,10 @@ def test_main_returns_unexpected_failure_for_unknown_error( file=shell.sys.stderr, ) + @mock.patch.object(shell, '_verify_cluster_identity') @mock.patch.object(shell, '_vault_client') - def test_retry_wrapper_returns_operation_result(self, vault_client): + def test_retry_wrapper_returns_operation_result( + self, vault_client, verify_cluster_identity): operation = mock.Mock(return_value={'luks_uuid': 'test-uuid'}) args = mock.Mock(retry=-1) config = mock.Mock() @@ -95,6 +97,9 @@ def test_retry_wrapper_returns_operation_result(self, vault_client): operation.assert_called_once_with( args, vault_client.return_value, config, ) + verify_cluster_identity.assert_called_once_with( + vault_client.return_value, args.config, + ) @mock.patch.object(shell, '_vault_client') def test_retry_wrapper_reports_vault_errors(self, vault_client): diff --git a/vaultlocker/tests/unit/test_exceptions.py b/vaultlocker/tests/unit/test_exceptions.py index 86f4903..0faf0ac 100644 --- a/vaultlocker/tests/unit/test_exceptions.py +++ b/vaultlocker/tests/unit/test_exceptions.py @@ -30,6 +30,13 @@ def test_base_uses_first_argument_as_message(self): self.assertEqual('boom', str(error)) + def test_cluster_identity_mismatch_message(self): + error = exceptions.ClusterIdentityMismatchError('cluster-a', + 'cluster-b') + + self.assertIn('cluster-a', str(error)) + self.assertIn('cluster-b', str(error)) + def test_managed_key_not_found_message(self): error = exceptions.ManagedKeyNotFoundError('mount/host/uuid') diff --git a/vaultlocker/tests/unit/test_vault.py b/vaultlocker/tests/unit/test_vault.py index c611f51..555139b 100644 --- a/vaultlocker/tests/unit/test_vault.py +++ b/vaultlocker/tests/unit/test_vault.py @@ -21,6 +21,7 @@ import hvac +from vaultlocker import exceptions from vaultlocker.tests.unit import base from vaultlocker import vault @@ -181,3 +182,32 @@ def test_get_store_rejects_unsupported_version(self): ) self.assertIn("Unsupported kv_version '3'", str(error.exception)) + + +class TestClusterId(base.TestCase): + + def setUp(self): + super().setUp() + self.client = mock.MagicMock() + + def test_get_cluster_id(self): + self.client.sys.read_seal_status.return_value = { + 'cluster_id': 'test-cluster-id', + } + + self.assertEqual( + 'test-cluster-id', + vault.get_cluster_id(self.client), + ) + self.client.sys.read_seal_status.assert_called_once_with() + + def test_invalid_cluster_id_fails(self): + invalid_responses = ( + {}, {'cluster_id': ''}, {'cluster_id': None}, + {'cluster_id': 42}, None, + ) + for response in invalid_responses: + with self.subTest(response=response): + self.client.sys.read_seal_status.return_value = response + with self.assertRaises(exceptions.ClusterIdentityError): + vault.get_cluster_id(self.client) diff --git a/vaultlocker/tests/unit/test_vaultlocker.py b/vaultlocker/tests/unit/test_vaultlocker.py index 746d209..d014ba3 100644 --- a/vaultlocker/tests/unit/test_vaultlocker.py +++ b/vaultlocker/tests/unit/test_vaultlocker.py @@ -22,7 +22,9 @@ import configparser import io import json +import os import subprocess +import tempfile from unittest import mock @@ -75,17 +77,27 @@ def test_get_config_rejects_path_with_whitespace(self): shell.get_config(config_path) @mock.patch.object(shell.hvac, 'Client') - def test_vault_client_uses_approle_login(self, _client): + def test_vault_client_is_not_authenticated(self, _client): client = _client.return_value result = shell._vault_client(self.config) + _client.assert_called_once_with( + url=self._test_config['url'], + verify=True, + ) + client.auth.approle.login.assert_not_called() + self.assertIs(result, client) + + def test_login_to_vault_uses_approle(self): + client = mock.MagicMock() + + shell._login_to_vault(client, self.config) + client.auth.approle.login.assert_called_once_with( role_id=self._test_config['approle'], secret_id=self._test_config['secret_id'], ) - client.auth_approle.assert_not_called() - self.assertIs(result, client) @mock.patch.object(shell.vault, 'KVStore') def test_vault_store_uses_configured_mount_and_version(self, _kv_store): @@ -393,9 +405,11 @@ def test_main_parses_enroll( self.assertEqual(['/dev/sdb'], args.block_device) self.assertIs(self.config, config) + @mock.patch.object(shell, '_login_to_vault') + @mock.patch.object(shell, '_verify_cluster_identity') @mock.patch.object(shell, '_vault_client') def test_do_it_with_persistence_returns_result( - self, _vault_client): + self, _vault_client, _verify_cluster_identity, _login_to_vault): args = mock.MagicMock() args.retry = 0 func = mock.MagicMock(return_value={'luks_uuid': 'test-uuid'}) @@ -405,22 +419,46 @@ def test_do_it_with_persistence_returns_result( ) self.assertEqual({'luks_uuid': 'test-uuid'}, result) - func.assert_called_once_with(args, _vault_client.return_value, - self.config) + client = _vault_client.return_value + _login_to_vault.assert_called_once_with(client, self.config) + _verify_cluster_identity.assert_called_once_with(client, args.config) + func.assert_called_once_with(args, client, self.config) + + @mock.patch.object(shell, '_login_to_vault') + @mock.patch.object(shell, '_verify_cluster_identity') + @mock.patch.object(shell, '_vault_client') + def test_identity_is_checked_after_login( + self, _vault_client, _verify_cluster_identity, _login_to_vault): + calls = [] + _verify_cluster_identity.side_effect = ( + lambda *_args: calls.append('identity') + ) + _login_to_vault.side_effect = lambda *_args: calls.append('login') + operation = mock.MagicMock( + side_effect=lambda *_args: calls.append('operation'), + ) + args = mock.MagicMock(retry=0) + + shell._do_it_with_persistence(operation, args, self.config) + + self.assertEqual(['login', 'identity', 'operation'], calls) + @mock.patch.object(shell, '_login_to_vault') + @mock.patch.object(shell, '_verify_cluster_identity') @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') + self, _vault_client, _verify_cluster_identity, _login_to_vault): + _login_to_vault.side_effect = hvac.exceptions.VaultDown('down') args = mock.MagicMock() args.retry = 0 - func = mock.MagicMock() + operation = mock.MagicMock() with self.assertRaises(exceptions.VaultConnectionError): - shell._do_it_with_persistence(func, args, self.config) + shell._do_it_with_persistence(operation, args, self.config) - func.assert_not_called() + _verify_cluster_identity.assert_not_called() + operation.assert_not_called() @mock.patch.object(shell.sys, 'argv', ['vaultlocker', 'encrypt', '/dev/sdb']) @@ -606,54 +644,72 @@ def test_main_usage_error_is_not_handled_failure_exit_code(self): class TestTenacityRetryBoundary(base.TestCase): """Tests which Vault failures are retried.""" + @mock.patch.object(shell, '_login_to_vault') + @mock.patch.object(shell, '_verify_cluster_identity') @mock.patch.object(shell, '_vault_client') def test_vault_down_is_retried_within_the_bound( - self, _vault_client): - _vault_client.side_effect = [ + self, _vault_client, _verify_cluster_identity, _login_to_vault): + _login_to_vault.side_effect = [ hvac.exceptions.VaultDown('sealed'), - mock.MagicMock(), + None, ] args = mock.MagicMock() args.retry = 3 - func = mock.MagicMock(return_value={'luks_uuid': 'test-uuid'}) + operation = mock.MagicMock( + return_value={'luks_uuid': 'test-uuid'}, + ) - result = shell._do_it_with_persistence(func, args, mock.MagicMock()) + result = shell._do_it_with_persistence( + operation, args, mock.MagicMock(), + ) self.assertEqual({'luks_uuid': 'test-uuid'}, result) self.assertEqual(2, _vault_client.call_count) - func.assert_called_once() + _verify_cluster_identity.assert_called_once_with( + _vault_client.return_value, args.config, + ) + self.assertEqual(2, _login_to_vault.call_count) + operation.assert_called_once() + @mock.patch.object(shell, '_login_to_vault') + @mock.patch.object(shell, '_verify_cluster_identity') @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') + def test_credential_failure_is_not_retried( + self, _vault_client, _verify_cluster_identity, _login_to_vault): + _login_to_vault.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() + operation = mock.MagicMock() with self.assertRaises(exceptions.VaultConnectionError): - shell._do_it_with_persistence(func, args, mock.MagicMock()) + shell._do_it_with_persistence( + operation, args, mock.MagicMock(), + ) - self.assertEqual(1, _vault_client.call_count) - func.assert_not_called() + self.assertEqual(1, _login_to_vault.call_count) + operation.assert_not_called() + @mock.patch.object(shell, '_login_to_vault') + @mock.patch.object(shell, '_verify_cluster_identity') @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') + self, _vault_client, _verify_cluster_identity, _login_to_vault): + """The default retry setting attempts login once.""" + _login_to_vault.side_effect = hvac.exceptions.Forbidden('bad creds') args = mock.MagicMock() args.retry = -1 - func = mock.MagicMock() + operation = mock.MagicMock() with self.assertRaises(exceptions.VaultConnectionError): - shell._do_it_with_persistence(func, args, mock.MagicMock()) + shell._do_it_with_persistence( + operation, args, mock.MagicMock(), + ) - self.assertEqual(1, _vault_client.call_count) - func.assert_not_called() + self.assertEqual(1, _login_to_vault.call_count) + operation.assert_not_called() class TestStoreAndValidateKey(base.TestCase): @@ -1348,13 +1404,14 @@ def test_uses_the_requested_uuid_without_generating_one( ) @mock.patch.object(shell, '_encrypt_block_device') + @mock.patch.object(shell, '_verify_cluster_identity') @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): + _verify_cluster_identity, _encrypt_impl): """Retries keep the same UUID and key.""" _vault_client.return_value = mock.MagicMock() _encrypt_impl.side_effect = [ @@ -1812,6 +1869,7 @@ def test_decrypt_handler_delegates(self, _do): _do.assert_called_once_with( shell._decrypt_block_device, args, config, + fail_on_cluster_mismatch=False, ) self.assertIsNone(result) @@ -1885,6 +1943,211 @@ def test_get_config_invalid_kv_version_is_controlled(self): shell.get_config('/path/to/conf') +class TestClusterIdentity(base.TestCase): + """Tests Vault cluster identity pinning.""" + + def setUp(self): + super().setUp() + self.temp_dir = tempfile.TemporaryDirectory() + self.addCleanup(self.temp_dir.cleanup) + self.config_path = os.path.join( + self.temp_dir.name, 'vaultlocker.conf', + ) + self.pin_path = '{}.cluster-id'.format(self.config_path) + + def _write_pin(self, value): + with open(self.pin_path, 'w', encoding='utf-8') as sidecar: + sidecar.write(value) + + @mock.patch.object(shell.vault, 'get_cluster_id', return_value='cluster-a') + def test_first_use_creates_pin(self, _get_cluster_id): + shell._verify_cluster_identity(mock.MagicMock(), self.config_path) + + with open(self.pin_path, 'r', encoding='utf-8') as sidecar: + self.assertEqual('cluster-a', sidecar.read()) + + @mock.patch.object(shell.vault, 'get_cluster_id', return_value='cluster-a') + def test_matching_pin_succeeds(self, _get_cluster_id): + self._write_pin('cluster-a') + + with mock.patch.object(shell.tempfile, 'mkstemp') as _mkstemp: + shell._verify_cluster_identity( + mock.MagicMock(), self.config_path, + ) + + _mkstemp.assert_not_called() + + @mock.patch.object(shell.vault, 'get_cluster_id', return_value='cluster-a') + def test_concurrent_pin_is_not_replaced(self, _get_cluster_id): + real_link = os.link + + def create_competing_pin(source, destination): + with open(destination, 'x', encoding='utf-8') as sidecar: + sidecar.write('cluster-b') + return real_link(source, destination) + + with mock.patch.object( + shell.os, 'link', side_effect=create_competing_pin): + with self.assertRaises(exceptions.ClusterIdentityMismatchError): + shell._verify_cluster_identity( + mock.MagicMock(), self.config_path, + ) + + with open(self.pin_path, 'r', encoding='utf-8') as sidecar: + self.assertEqual('cluster-b', sidecar.read()) + self.assertEqual([os.path.basename(self.pin_path)], + os.listdir(self.temp_dir.name)) + + @mock.patch.object(shell.vault, 'get_cluster_id', return_value='cluster-b') + def test_mismatching_pin_fails(self, _get_cluster_id): + self._write_pin('cluster-a') + + with self.assertRaises(exceptions.ClusterIdentityMismatchError): + shell._verify_cluster_identity( + mock.MagicMock(), self.config_path, + ) + + with open(self.pin_path, 'r', encoding='utf-8') as sidecar: + self.assertEqual('cluster-a', sidecar.read()) + + @mock.patch.object(shell.vault, 'get_cluster_id', return_value='cluster-a') + def test_empty_pin_fails(self, _get_cluster_id): + self._write_pin('') + + with self.assertRaises(exceptions.ClusterIdentityError): + shell._verify_cluster_identity( + mock.MagicMock(), self.config_path, + ) + + def test_file_errors_are_controlled(self): + with mock.patch('builtins.open', side_effect=OSError('unavailable')): + with self.assertRaises(exceptions.ClusterIdentityError): + shell._read_cluster_pin(self.pin_path) + + with mock.patch.object( + shell.tempfile, 'mkstemp', + side_effect=OSError('unavailable')): + with self.assertRaises(exceptions.ClusterIdentityError): + shell._create_cluster_pin(self.pin_path, 'cluster-a') + + with mock.patch.object( + shell.os, 'link', side_effect=OSError('unavailable')): + with self.assertRaises(exceptions.ClusterIdentityError): + shell._create_cluster_pin(self.pin_path, 'cluster-a') + self.assertEqual([], os.listdir(self.temp_dir.name)) + + def test_two_config_paths_pin_independently(self): + second_config = os.path.join(self.temp_dir.name, 'second.conf') + with mock.patch.object( + shell.vault, 'get_cluster_id', + side_effect=['cluster-a', 'cluster-b']): + shell._verify_cluster_identity( + mock.MagicMock(), self.config_path, + ) + shell._verify_cluster_identity( + mock.MagicMock(), second_config, + ) + + with open(self.pin_path, 'r', encoding='utf-8') as first_pin: + self.assertEqual('cluster-a', first_pin.read()) + with open( + '{}.cluster-id'.format(second_config), + 'r', encoding='utf-8', + ) as second_pin: + self.assertEqual('cluster-b', second_pin.read()) + + @mock.patch.object(shell, '_login_to_vault') + @mock.patch.object(shell, '_vault_client') + def test_verification_failure_runs_no_operation( + self, _vault_client, _login_to_vault): + self._write_pin('cluster-a') + operation = mock.MagicMock() + args = mock.MagicMock(retry=0, config=self.config_path) + + with mock.patch.object( + shell.vault, 'get_cluster_id', return_value='cluster-b'): + with self.assertRaises( + exceptions.ClusterIdentityMismatchError): + shell._do_it_with_persistence( + operation, args, mock.MagicMock(), + ) + + _login_to_vault.assert_called_once_with( + _vault_client.return_value, mock.ANY, + ) + operation.assert_not_called() + with open(self.pin_path, 'r', encoding='utf-8') as sidecar: + self.assertEqual('cluster-a', sidecar.read()) + + @mock.patch.object(shell, '_decrypt_block_device', + return_value='unlocked') + @mock.patch.object(shell, '_verify_cluster_identity') + @mock.patch.object(shell, '_login_to_vault') + @mock.patch.object(shell, '_vault_client') + def test_decrypt_warns_and_runs_after_cluster_mismatch( + self, _vault_client, _login_to_vault, + _verify_cluster_identity, _decrypt_block_device): + _verify_cluster_identity.side_effect = ( + exceptions.ClusterIdentityMismatchError('cluster-a', 'cluster-b') + ) + args = mock.MagicMock(retry=0, config=self.config_path) + config = mock.MagicMock() + + with self.assertLogs(shell.logger, level='WARNING') as logged: + result = shell.decrypt(args, config) + + self.assertEqual('unlocked', result) + self.assertIn('Vault cluster identity mismatch', logged.output[0]) + client = _vault_client.return_value + _login_to_vault.assert_called_once_with(client, config) + _verify_cluster_identity.assert_called_once_with( + client, self.config_path, + ) + _decrypt_block_device.assert_called_once_with(args, client, config) + + def test_encrypt_and_enroll_stop_after_cluster_mismatch(self): + mismatch = exceptions.ClusterIdentityMismatchError( + 'cluster-a', 'cluster-b', + ) + args = mock.MagicMock( + retry=0, config=self.config_path, uuid='test-uuid', + existing_key_file=None, + ) + config = mock.MagicMock() + + with mock.patch.object(shell, '_vault_client'), \ + mock.patch.object(shell, '_login_to_vault'), \ + mock.patch.object(shell, '_verify_cluster_identity', + side_effect=mismatch), \ + mock.patch.object(shell, '_encrypt_block_device') as encrypt, \ + mock.patch.object(shell, '_enroll_block_device') as enroll: + for handler in (shell.encrypt, shell.enroll): + with self.subTest(handler=handler.__name__): + with self.assertRaises( + exceptions.ClusterIdentityMismatchError): + handler(args, config) + + encrypt.assert_not_called() + enroll.assert_not_called() + + @mock.patch.object(shell, '_decrypt_block_device') + @mock.patch.object(shell, '_verify_cluster_identity') + @mock.patch.object(shell, '_login_to_vault') + @mock.patch.object(shell, '_vault_client') + def test_decrypt_still_fails_on_invalid_cluster_pin( + self, _vault_client, _login_to_vault, + _verify_cluster_identity, _decrypt_block_device): + _verify_cluster_identity.side_effect = ( + exceptions.ClusterIdentityError('invalid pin') + ) + args = mock.MagicMock(retry=0, config=self.config_path) + + with self.assertRaises(exceptions.ClusterIdentityError): + shell.decrypt(args, mock.MagicMock()) + + _decrypt_block_device.assert_not_called() + + class TestSubprocessTimeouts(base.TestCase): """Cryptsetup timeouts are handled the same as ordinary failures.""" diff --git a/vaultlocker/vault.py b/vaultlocker/vault.py index 607a00e..0252660 100644 --- a/vaultlocker/vault.py +++ b/vaultlocker/vault.py @@ -15,10 +15,27 @@ import hvac +from vaultlocker import exceptions + KV_VERSION_1 = '1' KV_VERSION_2 = '2' +def get_cluster_id(client: hvac.Client) -> str: + """Return a valid cluster ID from Vault's seal status.""" + response = client.sys.read_seal_status() + if not isinstance(response, dict): + raise exceptions.ClusterIdentityError( + 'Vault seal status is not a JSON object' + ) + cluster_id = response.get('cluster_id') + if not isinstance(cluster_id, str) or not cluster_id: + raise exceptions.ClusterIdentityError( + 'Vault seal status has no valid cluster_id' + ) + return cluster_id + + class KVStoreBase(abc.ABC): """Base class for accessing a Vault KV secrets engine."""