diff --git a/.github/workflows/build-snap.yml b/.github/workflows/build-snap.yml index e508348..2ae41d6 100644 --- a/.github/workflows/build-snap.yml +++ b/.github/workflows/build-snap.yml @@ -1,4 +1,4 @@ -name: vaultlocker snap +name: vaultlocker snap build and VM tests on: - pull_request @@ -36,3 +36,76 @@ jobs: - name: Verify snap help run: vaultlocker -h + + test-snap-vm: + name: Test snap in VM + needs: build + runs-on: ubuntu-24.04 + timeout-minutes: 60 + env: + VAULTLOCKER_TEST_VM: vaultlocker-vm + LXD_STORAGE_POOL: default + LXD_STORAGE_VOLUME: vaultlocker-scratch + steps: + - name: Check out Git repository + uses: actions/checkout@v7 + + - name: Download snap artifact + uses: actions/download-artifact@v8 + with: + name: snap + path: snap-artifact + + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: '3.12' + + - name: Install test dependencies + run: | + pip install -r requirements-noble.txt + pip install -r test-requirements.txt + pip install . + + - name: Set up LXD + uses: canonical/setup-lxd@v1 + + - name: Create VM and scratch disk + run: | + lxc storage volume create "$LXD_STORAGE_POOL" "$LXD_STORAGE_VOLUME" \ + --type=block size=512MiB + lxc launch ubuntu:24.04 "$VAULTLOCKER_TEST_VM" --vm \ + --config limits.cpu=2 --config limits.memory=4GiB + lxc storage volume attach "$LXD_STORAGE_POOL" "$LXD_STORAGE_VOLUME" \ + "$VAULTLOCKER_TEST_VM" + timeout 300 bash -c \ + 'until lxc exec "$VAULTLOCKER_TEST_VM" -- true; do sleep 5; done' + lxc exec "$VAULTLOCKER_TEST_VM" -- cloud-init status --wait + lxc exec "$VAULTLOCKER_TEST_VM" -- apt-get update + lxc exec "$VAULTLOCKER_TEST_VM" -- apt-get install -y \ + cryptsetup dmsetup curl snapd + + mapfile -t scratch_devices < <( + lxc exec "$VAULTLOCKER_TEST_VM" -- lsblk -bndo PATH,TYPE,SIZE | + awk '$2 == "disk" && $3 == 536870912 {print $1}' + ) + test "${#scratch_devices[@]}" -eq 1 + lxc exec "$VAULTLOCKER_TEST_VM" -- test -b "${scratch_devices[0]}" + echo "VAULTLOCKER_TEST_DEVICE=${scratch_devices[0]}" >> "$GITHUB_ENV" + + - name: Run snap VM functional tests + run: | + snap_path="$(find "$GITHUB_WORKSPACE/snap-artifact" -maxdepth 1 \ + -name '*.snap' -print -quit)" + test -n "$snap_path" + VAULTLOCKER_SNAP_PATH="$snap_path" \ + python -c 'from vaultlocker.tests.functional.snap.base import snap_tests_enabled; assert snap_tests_enabled()' + VAULTLOCKER_SNAP_PATH="$snap_path" \ + stestr run --serial '^vaultlocker.tests.functional.snap.*' + + - name: Clean up VM + if: always() + run: | + lxc delete "$VAULTLOCKER_TEST_VM" --force || true + lxc storage volume delete "$LXD_STORAGE_POOL" \ + "$LXD_STORAGE_VOLUME" || true \ No newline at end of file diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml index 385fae1..8883343 100644 --- a/snap/snapcraft.yaml +++ b/snap/snapcraft.yaml @@ -38,11 +38,27 @@ parts: craftctl set version="${version}" craftctl set grade="${grade}" craftctl default + pebble: + plugin: nil + stage-snaps: + - pebble apps: vaultlocker: command: bin/vaultlocker + environment: + PEBBLE: /var/snap/vaultlocker/common/pebble plugs: - network - dm-crypt - block-devices + pebble: + command: bin/pebble run --create-dirs + daemon: simple + environment: + PEBBLE: /var/snap/vaultlocker/common/pebble + plugs: + - network + - network-bind + - dm-crypt + - block-devices diff --git a/tools/vaultlocker-decrypt@.service b/tools/vaultlocker-decrypt@.service index 8c32e9f..e0ba41d 100644 --- a/tools/vaultlocker-decrypt@.service +++ b/tools/vaultlocker-decrypt@.service @@ -7,8 +7,9 @@ After=nss-lookup.target [Service] Type=oneshot KillMode=none +Environment=VAULTLOCKER_CONFIG=/etc/vaultlocker/vaultlocker.conf Environment=VAULTLOCKER_TIMEOUT=10000 -ExecStart=/bin/sh -c 'vaultlocker --retry $VAULTLOCKER_TIMEOUT decrypt %i' +ExecStart=/bin/sh -c 'vaultlocker --retry $VAULTLOCKER_TIMEOUT --config "$VAULTLOCKER_CONFIG" decrypt %i' TimeoutSec=0 [Install] diff --git a/vaultlocker/boot_unlock.py b/vaultlocker/boot_unlock.py new file mode 100644 index 0000000..2adf329 --- /dev/null +++ b/vaultlocker/boot_unlock.py @@ -0,0 +1,66 @@ +# -*- 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. + +"""Select the boot-time unlock backend for the running distribution. + +The classic (deb/pip) deployment uses a systemd template unit plus a +per-device configuration drop-in. The snap deployment uses Pebble +layers because a strictly confined snap cannot manipulate host systemd +units at runtime. +""" + +import logging +import os + +from vaultlocker import pebble_layers +from vaultlocker import systemd + +logger = logging.getLogger(__name__) + +#: Environment variable snapd sets when a process runs inside a snap. +SNAP_ENV_VAR = 'SNAP' + +#: Default number of seconds to retry Vault at boot before giving up +#: for this attempt (the unlock service is retried again afterwards). +DEFAULT_RETRY_TIMEOUT_SECONDS = 10000 + + +def running_in_snap(): + """Return True when running inside a snap environment. + + :returns: bool. + """ + return bool(os.environ.get(SNAP_ENV_VAR)) + + +def register(block_uuid, config_path, + timeout=DEFAULT_RETRY_TIMEOUT_SECONDS): + """Register boot-time unlock for a managed device. + + Chooses the Pebble backend inside a snap and the systemd backend + otherwise. + + :param: block_uuid: UUID of the encrypted block device. + :param: config_path: Path to the vaultlocker configuration file. + :param: timeout: Seconds to retry connecting to Vault at boot. + """ + if running_in_snap(): + logger.info('Registering snap (Pebble) boot unlock for %s', + block_uuid) + pebble_layers.register_boot_unlock( + block_uuid, config_path, timeout, + ) + else: + logger.info('Registering systemd boot unlock for %s', block_uuid) + systemd.register_decrypt_service(block_uuid, config_path) diff --git a/vaultlocker/dmcrypt.py b/vaultlocker/dmcrypt.py index 7ab3432..97e19d1 100644 --- a/vaultlocker/dmcrypt.py +++ b/vaultlocker/dmcrypt.py @@ -71,25 +71,27 @@ def luks_format(key, device, uuid): ) -def luks_open(key, uuid): - """LUKS open a block device by UUID. +def luks_open(key, uuid, device=None): + """LUKS open a block device. Open a block device using dm-crypt/LUKS with the - provided key and uuid + provided key and device path or UUID. :param: key: string containing the encryption key to use. :param: uuid: uuid to use for encrypted block device. + :param: device: optional block device path. If omitted, use the UUID. :returns: str. dm-crypt mapping """ logger.info('LUKS opening %s', uuid) handle = 'crypt-{}'.format(uuid) + source = device if device else 'UUID={}'.format(uuid) command = [ 'cryptsetup', '--batch-mode', '--key-file', '-', 'open', - 'UUID={}'.format(uuid), + source, handle, '--type', 'luks', diff --git a/vaultlocker/pebble_layers.py b/vaultlocker/pebble_layers.py new file mode 100644 index 0000000..6c5199d --- /dev/null +++ b/vaultlocker/pebble_layers.py @@ -0,0 +1,227 @@ +# -*- 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. + +"""Boot-time unlock via Pebble layers for the snap distribution. + +A strictly confined snap cannot write or enable arbitrary host systemd +template-unit instances at runtime, so the snap runs Pebble as its +supervised init process (``daemon: simple``) and registers one Pebble +service per managed device. Pebble's children run inside the same +confinement context as any other snap app, so the ``dm-crypt`` and +``block-devices`` interfaces continue to apply. +""" + +import fcntl +import logging +import os +import re +import shlex +import subprocess +import textwrap + +logger = logging.getLogger(__name__) + +#: Pebble CLI binary installed alongside the snap. +PEBBLE_BINARY = 'pebble' + +#: Environment variable pointing at the Pebble configuration directory. +PEBBLE_DIR_ENV_VAR = 'PEBBLE' + +#: Pebble's default configuration directory. +DEFAULT_PEBBLE_DIR = '/var/lib/pebble/default' + +#: Prefix for the Pebble layer label for each managed device. +LAYER_LABEL_PREFIX = 'vaultlocker-decrypt-' + +#: Name of the directory Pebble loads layer files from. +LAYERS_DIR_NAME = 'layers' + +#: Name of the file used to serialize Pebble layer updates. +LAYER_LOCK_NAME = '.vaultlocker-layers.lock' + +#: First numeric prefix used for per-device layer files. Pebble orders +#: layers by this prefix and requires a unique prefix per layer file. +LAYER_PREFIX_START = 100 + +#: Regular expression matching the numeric prefix of a layer filename. +LAYER_PREFIX_PATTERN = re.compile(r'^(\d+)-') + +#: Delays controlling Pebble's restart backoff for an unlock service. +BACKOFF_DELAY = '5s' +BACKOFF_LIMIT = '30s' + + +def pebble_dir(): + """Return the Pebble configuration directory for this environment. + + :returns: str. Pebble directory path. + """ + return os.environ.get(PEBBLE_DIR_ENV_VAR) or DEFAULT_PEBBLE_DIR + + +def layer_label(block_uuid): + """Return the Pebble layer label for a managed device. + + :param: block_uuid: UUID of the encrypted block device. + :returns: str. Pebble layer label. + """ + return '{}{}'.format(LAYER_LABEL_PREFIX, block_uuid) + + +def service_name(block_uuid): + """Return the Pebble service name for a managed device. + + :param: block_uuid: UUID of the encrypted block device. + :returns: str. Pebble service name. + """ + return 'decrypt-{}'.format(block_uuid) + + +def render_layer(block_uuid, config_path, timeout): + """Render the Pebble layer YAML for a managed device. + + The service retries on failure so that a temporarily unavailable + Vault does not leave the device permanently locked, matching the + systemd-based behaviour used outside the snap. + + :param: block_uuid: UUID of the encrypted block device. + :param: config_path: Path to the vaultlocker configuration file. + :param: timeout: Seconds to retry connecting to Vault. + :returns: str. Pebble layer YAML. + """ + command = ( + 'vaultlocker --retry {timeout} --config {config} ' + 'decrypt {uuid}' + ).format( + timeout=timeout, + config=shlex.quote(config_path), + uuid=block_uuid, + ) + return textwrap.dedent( + """\ + services: + {service}: + override: replace + command: {command} + startup: enabled + on-success: ignore + on-failure: restart + backoff-delay: {backoff_delay} + backoff-limit: {backoff_limit} + """ + ).format( + service=service_name(block_uuid), + command=command, + backoff_delay=BACKOFF_DELAY, + backoff_limit=BACKOFF_LIMIT, + ) + + +def _existing_layer_path(layers_dir, label): + """Return the path of an existing layer file for a label, if any. + + :param: layers_dir: Pebble layers directory. + :param: label: Pebble layer label. + :returns: str path, or None. + """ + suffix = '-{}.yaml'.format(label) + for name in os.listdir(layers_dir): + if name.endswith(suffix): + return os.path.join(layers_dir, name) + return None + + +def _next_layer_prefix(layers_dir): + """Return the next unused numeric layer prefix. + + Pebble orders layers by a unique numeric filename prefix. + + :param: layers_dir: Pebble layers directory. + :returns: int. Next prefix. + """ + highest = LAYER_PREFIX_START - 1 + for name in os.listdir(layers_dir): + match = LAYER_PREFIX_PATTERN.match(name) + if match: + highest = max(highest, int(match.group(1))) + return highest + 1 + + +def _layer_path(layers_dir, label): + """Return the persistent layer path for a device label. + + Reuses the existing file for the label (so a rewrite replaces it) and + otherwise allocates a new unique numeric prefix. + + :param: layers_dir: Pebble layers directory. + :param: label: Pebble layer label. + :returns: str. Layer file path. + """ + existing = _existing_layer_path(layers_dir, label) + if existing is not None: + return existing + + prefix = _next_layer_prefix(layers_dir) + return os.path.join( + layers_dir, '{:03d}-{}.yaml'.format(prefix, label), + ) + + +def register_boot_unlock(block_uuid, config_path, timeout): + """Register a Pebble service to unlock a managed device at boot. + + The layer is written to Pebble's persistent layers directory so it is + picked up on every Pebble start (including host boot). It is also added + to Pebble's current plan before the plan is replanned so the service is + scheduled immediately. + + :param: block_uuid: UUID of the encrypted block device. + :param: config_path: Path to the vaultlocker configuration file. + :param: timeout: Seconds to retry connecting to Vault. + """ + label = layer_label(block_uuid) + layer = render_layer(block_uuid, config_path, timeout) + + pebble_config_dir = pebble_dir() + layers_dir = os.path.join(pebble_config_dir, LAYERS_DIR_NAME) + os.makedirs(layers_dir, exist_ok=True) + lock_path = os.path.join(pebble_config_dir, LAYER_LOCK_NAME) + + # Prevent concurrent calls from choosing the same layer number. + with open(lock_path, 'a+b') as lock_file: + fcntl.flock(lock_file, fcntl.LOCK_EX) + + layer_path = _layer_path(layers_dir, label) + temporary_path = '{}.tmp'.format(layer_path) + + logger.info('Writing Pebble unlock layer %s', layer_path) + with open(temporary_path, 'w', encoding='utf-8') as layer_file: + layer_file.write(layer) + os.replace(temporary_path, layer_path) + + # Add the layer, or update it if this device is already registered. + subprocess.run( + [PEBBLE_BINARY, 'add', '--combine', label, layer_path], + check=True, + capture_output=True, + ) + + # A successful unlock exits immediately, which Pebble can report as a + # failed service start. Use --no-wait and return once Pebble accepts the + # replan instead of waiting for the one-shot service to exit. + subprocess.run( + [PEBBLE_BINARY, 'replan', '--no-wait'], + check=True, + capture_output=True, + ) diff --git a/vaultlocker/shell.py b/vaultlocker/shell.py index bae36ce..2b5b0ca 100644 --- a/vaultlocker/shell.py +++ b/vaultlocker/shell.py @@ -27,9 +27,9 @@ import hvac import tenacity +from vaultlocker import boot_unlock from vaultlocker import dmcrypt from vaultlocker import exceptions -from vaultlocker import systemd from vaultlocker import vault logger = logging.getLogger(__name__) @@ -278,7 +278,7 @@ def _enroll_block_device(args, client, config, existing_key): ) if not _device_exists(block_uuid): - dmcrypt.luks_open(key, block_uuid) + dmcrypt.luks_open(key, block_uuid, block_device) except subprocess.CalledProcessError as luks_error: logger.error( @@ -293,15 +293,13 @@ def _enroll_block_device(args, client, config, existing_key): luks_error.output, ) - systemd.enable( - 'vaultlocker-decrypt@{}.service'.format(block_uuid) - ) + boot_unlock.register(block_uuid, args.config) def _encrypt_block_device(args, client, config): """Encrypt and open a block device - Stores the dm-crypt key direct in vault + Store the encryption key in Vault before formatting the device. :param: args: argparser generated cli arguments :param: client: hvac.Client for Vault access @@ -321,17 +319,9 @@ def _encrypt_block_device(args, client, config): # NOTE: store and validate key before trying to encrypt disk _store_and_validate_key(store, path, key) - # All function calls within try/catch raise a CalledProcessError - # if return code is non-zero - # This way if any of the calls fail, the key can be removed from vault + # Remove the stored key if formatting fails. try: dmcrypt.luks_format(key, block_device, block_uuid) - # Ensure sym link for new encrypted device is created - # LP Bug #1780332 - # TODO(lucas): Temporarily disabled for initial snap packaging - # dmcrypt.udevadm_rescan(block_device) - # dmcrypt.udevadm_settle(block_uuid) - dmcrypt.luks_open(key, block_uuid) except subprocess.CalledProcessError as luks_error: logger.error( 'LUKS formatting %s failed with error code: %s\n' @@ -348,7 +338,26 @@ def _encrypt_block_device(args, client, config): raise exceptions.LUKSFailure(block_device, luks_error.output) - systemd.enable('vaultlocker-decrypt@{}.service'.format(block_uuid)) + if not boot_unlock.running_in_snap(): + try: + # Ask udev to create the UUID link used during boot. + dmcrypt.udevadm_rescan(block_device) + dmcrypt.udevadm_settle(block_uuid) + except subprocess.CalledProcessError 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, + ) + + try: + dmcrypt.luks_open(key, block_uuid, block_device) + except subprocess.CalledProcessError as luks_error: + raise exceptions.LUKSFailure(block_device, luks_error.output) + + boot_unlock.register(block_uuid, args.config) def _decrypt_block_device(args, client, config): @@ -463,6 +472,11 @@ def get_config(config_path): :param: config_path: path to the configuration file :returns: configparser. Parsed configuration options """ + if any(character.isspace() for character in config_path): + raise ValueError( + 'Configuration path cannot contain whitespace' + ) + config = configparser.ConfigParser() if os.path.exists(config_path): config.read(config_path) diff --git a/vaultlocker/systemd.py b/vaultlocker/systemd.py index d0f3d95..ed5fae5 100644 --- a/vaultlocker/systemd.py +++ b/vaultlocker/systemd.py @@ -13,11 +13,22 @@ # under the License. import logging +import os import subprocess logger = logging.getLogger(__name__) +#: Directory systemd reads unit files and drop-ins from. +SYSTEMD_UNIT_DIR = '/etc/systemd/system' + +#: Template for the per-device boot-time unlock unit. +DECRYPT_SERVICE_TEMPLATE = 'vaultlocker-decrypt@{}.service' + +#: Name of the drop-in file written per managed device. +CONFIG_DROPIN_NAME = 'config.conf' + + def enable(service_name): """Enable a systemd unit @@ -26,3 +37,50 @@ def enable(service_name): logging.info('Enabling systemd unit for {}'.format(service_name)) cmd = ['systemctl', 'enable', service_name] subprocess.check_call(cmd) + + +def config_dropin_path(service_name): + """Return the config drop-in path for a per-device unlock unit. + + :param: service_name: Name of the templated unit instance. + :returns: str. Full path to the drop-in override file. + """ + return os.path.join( + SYSTEMD_UNIT_DIR, + '{}.d'.format(service_name), + CONFIG_DROPIN_NAME, + ) + + +def write_config_dropin(service_name, config_path): + """Write a drop-in pinning a unit instance to a vaultlocker config. + + Per-application vaultlocker instances keep their own configuration + file, so the boot-time unlock unit for a device must use the same + configuration file that managed the device. + + :param: service_name: Name of the templated unit instance. + :param: config_path: Path to the vaultlocker configuration file. + """ + dropin_path = config_dropin_path(service_name) + os.makedirs(os.path.dirname(dropin_path), exist_ok=True) + logging.info('Writing config drop-in %s', dropin_path) + with open(dropin_path, 'w') as dropin: + dropin.write( + '[Service]\n' + 'Environment=VAULTLOCKER_CONFIG={}\n'.format(config_path) + ) + + +def register_decrypt_service(block_uuid, config_path): + """Configure and enable boot-time unlock for a managed device. + + Writes the per-device configuration drop-in and enables the + templated decrypt unit. + + :param: block_uuid: UUID of the encrypted block device. + :param: config_path: Path to the vaultlocker configuration file. + """ + service_name = DECRYPT_SERVICE_TEMPLATE.format(block_uuid) + write_config_dropin(service_name, config_path) + enable(service_name) diff --git a/vaultlocker/tests/functional/snap/README.rst b/vaultlocker/tests/functional/snap/README.rst new file mode 100644 index 0000000..9947317 --- /dev/null +++ b/vaultlocker/tests/functional/snap/README.rst @@ -0,0 +1,64 @@ +Snap VM functional tests +======================== + +These tests exercise the real ``vaultlocker`` snap on a virtual machine, +covering behavior that requires a real host: + +* after a reboot the device unlocks without the original credential; +* while Vault is unavailable the device stays locked and unlocks once + Vault returns; +* a snap refresh keeps the enrollment and does not add another managed + key. + +Unlike the other functional tests, these do not mock device operations. +They install the built snap, create a real LUKS device, enroll it, and +reboot the VM to exercise Pebble boot-time unlock. + +Prerequisites +------------- + +* An LXD virtual machine running Ubuntu 24.04 with a dedicated scratch + block device that persists across reboots. +* The ``lxc`` client available on the test host. +* A built ``vaultlocker`` snap. + +Environment variables +--------------------- + +``VAULTLOCKER_TEST_VM`` + Name of the LXD VM to use (required). + +``VAULTLOCKER_SNAP_PATH`` + Path to the built ``vaultlocker`` ``.snap`` on the test host (required). + +``VAULTLOCKER_TEST_DEVICE`` + Persistent block device to use inside the VM (default ``/dev/sdb``). + +The tests are skipped when ``VAULTLOCKER_TEST_VM`` or +``VAULTLOCKER_SNAP_PATH`` is unset. + +Creating a suitable VM +---------------------- + +Create a virtual machine with a scratch disk: + +:: + + lxc launch ubuntu:24.04 vaultlocker-vm --vm + truncate -s 512M /tmp/vaultlocker-scratch.img + lxc config device add vaultlocker-vm scratch disk \ + source=/tmp/vaultlocker-scratch.img + lxc restart vaultlocker-vm + +Running +------- + +:: + + VAULTLOCKER_TEST_VM=vaultlocker-vm \ + VAULTLOCKER_SNAP_PATH=./vaultlocker_0.1_amd64.snap \ + stestr run "^vaultlocker.tests.functional.snap.*" + +The tests reinstall the snap and reinitialise a file-backed Vault service +at the start of each run, so they do not depend on the VM's prior state. +The test Vault is stopped at the end of the run. diff --git a/vaultlocker/tests/functional/snap/__init__.py b/vaultlocker/tests/functional/snap/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/vaultlocker/tests/functional/snap/base.py b/vaultlocker/tests/functional/snap/base.py new file mode 100644 index 0000000..0f8d482 --- /dev/null +++ b/vaultlocker/tests/functional/snap/base.py @@ -0,0 +1,434 @@ +# -*- 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. + +"""Base class for vaultlocker snap functional tests. + +These tests exercise the real snap on a virtual machine, including +dm-crypt, Pebble boot-time unlock and Vault availability. They are skipped +unless ``VAULTLOCKER_SNAP_PATH`` and ``VAULTLOCKER_TEST_VM`` are set and the +``lxc`` client is available. + +Prerequisites: + +* An LXD virtual machine (Ubuntu 24.04) named by ``VAULTLOCKER_TEST_VM`` + with a dedicated scratch block device named by + ``VAULTLOCKER_TEST_DEVICE`` (default ``/dev/sdb``). The device must persist + across reboots. +* ``VAULTLOCKER_SNAP_PATH`` pointing at a built ``vaultlocker`` ``.snap``. + +Provisioning is idempotent: the snap is reinstalled and the test Vault is +reinitialised at the start of each test class, so a run does not depend on +the VM's prior state. +""" + +import json +import os +import shutil +import subprocess +import time +import unittest + +VM_ENV = "VAULTLOCKER_TEST_VM" +SNAP_PATH_ENV = "VAULTLOCKER_SNAP_PATH" +DEVICE_ENV = "VAULTLOCKER_TEST_DEVICE" + +INTERFACES = [ + "dm-crypt", + "block-devices", +] + +SNAP_REMOTE_PATH = "/root/vaultlocker.snap" +VAULT_COMMON = "/var/snap/vault/common" +VAULT_ADDR = "http://127.0.0.1:8200" +VAULTLOCKER_COMMON = "/var/snap/vaultlocker/common" +VAULTLOCKER_CONF = "{}/vaultlocker.conf".format(VAULTLOCKER_COMMON) +PASSPHRASE = "operatorpass" +PASSPHRASE_FILE = "{}/passphrase".format(VAULTLOCKER_COMMON) + +BOOT_TIMEOUT = 240 +MAPPER_TIMEOUT = 180 +POLL_INTERVAL = 3 + +VAULT_HCL = """storage "file" {{ path = "{common}/data" }} +listener "tcp" {{ + address = "127.0.0.1:8200" + tls_disable = true +}} +disable_mlock = true +""".format(common=VAULT_COMMON) + +VAULT_UNIT = """[Unit] +Description=Vault test server (file storage) +After=network-online.target + +[Service] +ExecStart=/snap/bin/vault server -config={common}/vault.hcl +Restart=on-failure + +[Install] +WantedBy=multi-user.target +""".format(common=VAULT_COMMON) + +VAULT_SETUP_SCRIPT = """#!/bin/bash +set -euo pipefail +export VAULT_ADDR={addr} +vault operator init -key-shares=1 -key-threshold=1 -format=json \ + > {common}/init.json +python3 - <<'PY' +import json +data = json.load(open("{common}/init.json")) +open("{common}/unseal-key", "w").write(data["unseal_keys_b64"][0]) +open("{common}/root-token", "w").write(data["root_token"]) +PY +vault operator unseal "$(cat {common}/unseal-key)" >/dev/null +export VAULT_TOKEN="$(cat {common}/root-token)" +vault secrets enable -path=vaultlocker kv-v2 +vault auth enable approle +cat > {common}/policy.hcl <<'POLICY' +path "vaultlocker/data/*" {{ + capabilities = ["create", "read", "update", "delete"] +}} +path "vaultlocker/metadata/*" {{ + capabilities = ["read", "delete", "list"] +}} +POLICY +vault policy write vaultlocker {common}/policy.hcl >/dev/null +vault write auth/approle/role/vaultlocker token_policies=vaultlocker \ + token_ttl=1h token_max_ttl=4h secret_id_ttl=0 >/dev/null +""".format(addr=VAULT_ADDR, common=VAULT_COMMON) + +VAULT_ROLE_ID_SCRIPT = """#!/bin/bash +set -euo pipefail +export VAULT_ADDR={addr} +export VAULT_TOKEN="$(cat {common}/root-token)" +vault read -format=json auth/approle/role/vaultlocker/role-id +""".format(addr=VAULT_ADDR, common=VAULT_COMMON) + +VAULT_SECRET_ID_SCRIPT = """#!/bin/bash +set -euo pipefail +export VAULT_ADDR={addr} +export VAULT_TOKEN="$(cat {common}/root-token)" +vault write -f -format=json auth/approle/role/vaultlocker/secret-id +""".format(addr=VAULT_ADDR, common=VAULT_COMMON) + + +def snap_tests_enabled(): + """Return True when the snap VM functional tests can run.""" + return all([ + os.environ.get(VM_ENV), + os.environ.get(SNAP_PATH_ENV), + shutil.which("lxc"), + ]) + + +@unittest.skipUnless( + snap_tests_enabled(), + "Set {} and {} (and install lxc) to run snap VM tests".format( + VM_ENV, SNAP_PATH_ENV + ), +) +class SnapVMFunctionalTest(unittest.TestCase): + """Base class provisioning the snap and Vault on a VM.""" + + vm = None + snap_path = None + device = None + + @classmethod + def setUpClass(cls): + """Provision the VM, snap and Vault, then enroll the device.""" + cls.vm = os.environ[VM_ENV] + cls.snap_path = os.environ[SNAP_PATH_ENV] + cls.device = os.environ.get(DEVICE_ENV, "/dev/sdb") + + cls._start_vm() + cls._install_snap() + cls._connect_interfaces() + cls._write_passphrase_file() + cls._setup_vault() + cls._write_vaultlocker_config() + cls._prepare_luks_device() + cls._enroll_device() + + @classmethod + def tearDownClass(cls): + """Stop the test Vault service.""" + cls._exec("systemctl stop vault-test.service || true", check=False) + + # -- VM helpers ------------------------------------------------------ + + @classmethod + def _lxc(cls, *args, check=True): + """Run a local lxc command.""" + return subprocess.run( + ["lxc"] + list(args), + check=check, + capture_output=True, + text=True, + ) + + @classmethod + def _exec(cls, command, check=True, timeout=600): + """Run a shell command inside the VM.""" + return subprocess.run( + ["lxc", "exec", cls.vm, "--", "bash", "-lc", command], + check=check, + capture_output=True, + text=True, + timeout=timeout, + ) + + @classmethod + def _push(cls, local_path, remote_path): + """Copy a local file into the VM.""" + cls._lxc( + "file", + "push", + str(local_path), + "{}{}".format(cls.vm, remote_path), + ) + + @classmethod + def _write_remote(cls, path, content): + """Write content to a file inside the VM.""" + subprocess.run( + ["lxc", "exec", cls.vm, "--", "tee", path], + check=True, + capture_output=True, + text=True, + input=content, + ) + + @classmethod + def _run_script(cls, name, content, check=True): + """Write and run a script inside the VM.""" + path = "/root/{}.sh".format(name) + cls._write_remote(path, content) + return cls._exec("bash {}".format(path), check=check) + + @classmethod + def _start_vm(cls): + """Start the VM if needed and wait until it is reachable.""" + cls._lxc("start", cls.vm, check=False) + deadline = time.monotonic() + BOOT_TIMEOUT + while time.monotonic() < deadline: + if cls._exec("true", check=False).returncode == 0: + return + time.sleep(POLL_INTERVAL) + raise RuntimeError("VM {} did not become ready".format(cls.vm)) + + @classmethod + def _reboot_vm(cls): + """Restart the VM and wait until the test Vault is reachable.""" + cls._lxc("restart", cls.vm) + cls._start_vm() + cls._wait_for_vault() + + # -- Provisioning ---------------------------------------------------- + + @classmethod + def _install_snap(cls): + """Install the built snap and clear any previous state.""" + cls._push(cls.snap_path, SNAP_REMOTE_PATH) + cls._exec("snap remove vaultlocker >/dev/null 2>&1 || true") + cls._exec("rm -rf {}/* || true".format(VAULTLOCKER_COMMON)) + cls._exec( + "snap install --dangerous --jailmode {}".format(SNAP_REMOTE_PATH) + ) + + @classmethod + def _connect_interfaces(cls): + """Connect the snap interfaces required for dm-crypt.""" + for iface in INTERFACES: + cls._exec( + "snap connect vaultlocker:{} || true".format(iface), + check=False, + ) + + @classmethod + def _write_passphrase_file(cls): + """Write the operator LUKS passphrase for enrollment.""" + cls._exec("mkdir -p {}".format(VAULTLOCKER_COMMON)) + cls._exec( + "printf %s {} > {}".format(PASSPHRASE, PASSPHRASE_FILE) + ) + + @classmethod + def _setup_vault(cls): + """Install, initialise and configure a file-backed Vault service.""" + cls._exec("snap install vault || true", check=False) + cls._exec("mkdir -p {}/data".format(VAULT_COMMON)) + cls._write_remote( + "{}/vault.hcl".format(VAULT_COMMON), VAULT_HCL + ) + cls._write_remote( + "/etc/systemd/system/vault-test.service", VAULT_UNIT + ) + cls._exec( + "systemctl stop vault-test.service || true", check=False + ) + cls._exec("rm -rf {}/data/* || true".format(VAULT_COMMON)) + cls._exec("systemctl daemon-reload") + cls._exec("systemctl enable --now vault-test.service") + cls._wait_for_vault() + cls._run_script("vault-setup", VAULT_SETUP_SCRIPT) + + @classmethod + def _wait_for_vault(cls): + """Wait until the Vault HTTP endpoint responds.""" + deadline = time.monotonic() + 90 + while time.monotonic() < deadline: + result = cls._exec( + "curl -s -o /dev/null -w '%{{http_code}}' {}".format( + VAULT_ADDR + ), + check=False, + ) + code = result.stdout.strip() + if code and code != "000": + return + time.sleep(POLL_INTERVAL) + raise RuntimeError("Vault did not start") + + @classmethod + def _unseal_vault(cls): + """Unseal the test Vault.""" + cls._exec( + "export VAULT_ADDR={}; vault operator unseal " + "$(cat {}/unseal-key)".format(VAULT_ADDR, VAULT_COMMON) + ) + + @classmethod + def _write_vaultlocker_config(cls): + """Write the vaultlocker config using a fresh AppRole.""" + role_out = cls._run_script("vault-role-id", VAULT_ROLE_ID_SCRIPT) + role_id = json.loads(role_out.stdout)["data"]["role_id"] + secret_out = cls._run_script( + "vault-secret-id", VAULT_SECRET_ID_SCRIPT + ) + secret_id = json.loads(secret_out.stdout)["data"]["secret_id"] + config = ( + "[vault]\n" + "url = {url}\n" + "approle = {role}\n" + "secret_id = {secret}\n" + "backend = vaultlocker\n" + "kv_version = 2\n" + ).format(url=VAULT_ADDR, role=role_id, secret=secret_id) + cls._write_remote(VAULTLOCKER_CONF, config) + + @classmethod + def _prepare_luks_device(cls): + """Create a fresh LUKS container with the operator passphrase.""" + cls._exec( + "for m in $(dmsetup ls --target crypt 2>/dev/null " + "| awk '{print $1}'); do cryptsetup close \"$m\" || true; " + "done", + check=False, + ) + cls._exec("wipefs -a {} || true".format(cls.device), check=False) + cls._exec( + "dd if=/dev/zero of={} bs=1M count=16 status=none".format( + cls.device + ) + ) + cls._exec( + "cryptsetup --batch-mode --key-file {} luksFormat {}".format( + PASSPHRASE_FILE, cls.device + ) + ) + + @classmethod + def _enroll_device(cls): + """Enroll the device with a Vault-managed key.""" + cls._exec( + "snap run vaultlocker --config {} enroll " + "--existing-key-file {} {}".format( + VAULTLOCKER_CONF, PASSPHRASE_FILE, cls.device + ) + ) + + # -- Queries --------------------------------------------------------- + + @classmethod + def _luks_uuid(cls): + """Return the LUKS UUID of the test device.""" + result = cls._exec("cryptsetup luksUUID {}".format(cls.device)) + return result.stdout.strip() + + @classmethod + def _mapper_path(cls): + """Return the mapper path for the test device.""" + return "/dev/mapper/crypt-{}".format(cls._luks_uuid()) + + @classmethod + def _mapper_exists(cls): + """Return True when the mapper device exists.""" + result = cls._exec( + "test -e {}".format(cls._mapper_path()), check=False + ) + return result.returncode == 0 + + @classmethod + def _wait_for_mapper(cls, present, timeout=MAPPER_TIMEOUT): + """Wait up to timeout for the mapper to reach the desired state.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if cls._mapper_exists() == present: + return True + time.sleep(POLL_INTERVAL) + return False + + @classmethod + def _keyslot_count(cls): + """Return the number of LUKS keyslots in use.""" + result = cls._exec("cryptsetup luksDump {}".format(cls.device)) + count = 0 + for line in result.stdout.splitlines(): + stripped = line.strip() + if stripped[:2].rstrip(":").isdigit() and ": luks2" in stripped: + count += 1 + return count + + @classmethod + def _layer_files(cls): + """Return the persistent Pebble layer files for the device.""" + result = cls._exec( + "ls {}/pebble/layers/ 2>/dev/null || true".format( + VAULTLOCKER_COMMON + ) + ) + return [ + name for name in result.stdout.split() if name.endswith(".yaml") + ] + + @classmethod + def _original_passphrase_unlocks(cls): + """Return True when the operator passphrase still unlocks it.""" + result = cls._exec( + "cryptsetup --batch-mode --key-file {} " + "open --test-passphrase {}".format( + PASSPHRASE_FILE, cls.device + ), + check=False, + ) + return result.returncode == 0 + + @classmethod + def _close_mapper(cls): + """Close the mapper device if it is open.""" + cls._exec( + "cryptsetup close crypt-{} || true".format(cls._luks_uuid()), + check=False, + ) diff --git a/vaultlocker/tests/functional/snap/test_snap_vm.py b/vaultlocker/tests/functional/snap/test_snap_vm.py new file mode 100644 index 0000000..2ad95a6 --- /dev/null +++ b/vaultlocker/tests/functional/snap/test_snap_vm.py @@ -0,0 +1,94 @@ +# -*- 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. + +"""Snap functional tests for encrypted-storage reboot and refresh. + +These tests cover behavior that requires a real host: + +* after a reboot the device unlocks without the original credential; +* while Vault is unavailable the device stays locked and unlocks once + Vault returns; +* a snap refresh keeps the enrollment and does not add another managed + key. + +The test class provisions a file-backed Vault service and the built +``vaultlocker`` snap on the target VM, then reboots the VM as needed. +""" + +from vaultlocker.tests.functional.snap import base + + +class SnapRebootRefreshTest(base.SnapVMFunctionalTest): + """Reboot, Vault-unavailability and refresh behaviour of the snap.""" + + def test_snap_refresh_preserves_enrollment(self): + """A snap refresh keeps the managed key and does not add a key.""" + keyslots_before = self._keyslot_count() + layers_before = sorted(self._layer_files()) + + # Operator passphrase plus one Vaultlocker-managed key. + self.assertEqual(2, keyslots_before) + self.assertTrue(self._original_passphrase_unlocks()) + self.assertTrue(layers_before) + + # Reinstall the snap from the same file: this refreshes to a new + # revision and must preserve SNAP_COMMON. + self._exec( + "snap install --dangerous {}".format(base.SNAP_REMOTE_PATH) + ) + + self.assertEqual(layers_before, sorted(self._layer_files())) + self.assertEqual(keyslots_before, self._keyslot_count()) + self.assertTrue(self._original_passphrase_unlocks()) + + # The boot-time unlock service is still scheduled after the refresh. + self._close_mapper() + self._exec("systemctl restart snap.vaultlocker.pebble.service") + self.assertTrue( + self._wait_for_mapper(True), + "mapper was not restored after a snap refresh", + ) + + def test_reboot_unlock_without_credentials(self): + """After a reboot the device unlocks without the original secret.""" + self._close_mapper() + self.assertFalse(self._mapper_exists()) + + self._reboot_vm() + # The test Vault starts sealed after a reboot. Unseal it and wait + # for Vaultlocker to restore the mapper, without running the CLI. + self._unseal_vault() + + self.assertTrue( + self._wait_for_mapper(True), + "mapper was not restored after reboot", + ) + + def test_vault_unavailable_at_boot(self): + """Storage stays locked while Vault is unavailable, then unlocks.""" + self._close_mapper() + self.assertFalse(self._mapper_exists()) + + self._reboot_vm() + # Vault is sealed, so the device must remain locked. + self.assertFalse( + self._wait_for_mapper(True, timeout=30), + "mapper should not appear while Vault is unavailable", + ) + + self._unseal_vault() + self.assertTrue( + self._wait_for_mapper(True), + "mapper was not restored after Vault returned", + ) diff --git a/vaultlocker/tests/functional/test_keystorage.py b/vaultlocker/tests/functional/test_keystorage.py index ebfbda8..9c25b92 100644 --- a/vaultlocker/tests/functional/test_keystorage.py +++ b/vaultlocker/tests/functional/test_keystorage.py @@ -23,34 +23,35 @@ @mock.patch.object(shell.dmcrypt, 'udevadm_settle') @mock.patch.object(shell.dmcrypt, 'udevadm_rescan') -@mock.patch.object(shell, 'systemd') +@mock.patch.object(shell, 'boot_unlock') @mock.patch.object(shell.dmcrypt, 'luks_format') @mock.patch.object(shell.dmcrypt, 'luks_open') class KeyStorageTestCase(base.VaultlockerFuncBaseTestCase): """Test storage and retrieval of dm-crypt keys from vault""" - def test_encrypt(self, _luks_open, _luks_format, _systemd, + def test_encrypt(self, _luks_open, _luks_format, _boot_unlock, _udevadm_rescan, _udevadm_settle): """Test encrypt function stores correct data in vault""" + _boot_unlock.running_in_snap.return_value = False args = mock.MagicMock() args.uuid = 'passed-UUID' args.block_device = ['/dev/sdb'] args.retry = -1 + args.config = '/etc/vaultlocker/vaultlocker.conf' shell.encrypt(args, self.config) _luks_format.assert_called_once_with(mock.ANY, '/dev/sdb', 'passed-UUID') - _luks_open.assert_called_once_with(mock.ANY, - 'passed-UUID') - _systemd.enable.assert_called_once_with( - 'vaultlocker-decrypt@passed-UUID.service' + _luks_open.assert_called_once_with( + mock.ANY, 'passed-UUID', '/dev/sdb' ) - - # TODO(lucas): Temporarily disabled for initial snap packaging - # _udevadm_rescan.assert_called_once_with('/dev/sdb') - # _udevadm_settle.assert_called_once_with('passed-UUID') + _boot_unlock.register.assert_called_once_with( + 'passed-UUID', args.config + ) + _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', @@ -61,7 +62,7 @@ def test_encrypt(self, _luks_open, _luks_format, _systemd, self.assertIn('dmcrypt_key', stored_data['data'], 'dm-crypt key data is missing') - def test_decrypt(self, _luks_open, _luks_format, _systemd, + def test_decrypt(self, _luks_open, _luks_format, _boot_unlock, _udevadm_rescan, _udevadm_settle): """Test decrypt function retrieves correct key from vault""" args = mock.MagicMock() @@ -74,11 +75,11 @@ def test_decrypt(self, _luks_open, _luks_format, _systemd, shell.decrypt(args, self.config) _luks_format.assert_not_called() - _systemd.enable.assert_not_called() + _boot_unlock.register.assert_not_called() _luks_open.assert_called_once_with('testkey', 'passed-UUID') - def test_decrypt_missing_key(self, _luks_open, _luks_format, _systemd, + 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""" args = mock.MagicMock() @@ -89,5 +90,5 @@ def test_decrypt_missing_key(self, _luks_open, _luks_format, _systemd, shell.decrypt, args, self.config) _luks_format.assert_not_called() - _systemd.enable.assert_not_called() + _boot_unlock.register.assert_not_called() _luks_open.assert_not_called() diff --git a/vaultlocker/tests/unit/test_boot_unlock.py b/vaultlocker/tests/unit/test_boot_unlock.py new file mode 100644 index 0000000..b73c7eb --- /dev/null +++ b/vaultlocker/tests/unit/test_boot_unlock.py @@ -0,0 +1,61 @@ +# -*- 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. + +""" +test_boot_unlock +---------------------------------- + +Tests for `boot_unlock` module. +""" + +from unittest import mock + +from vaultlocker import boot_unlock +from vaultlocker.tests.unit import base + + +class TestBootUnlock(base.TestCase): + + @mock.patch.object(boot_unlock, 'pebble_layers') + @mock.patch.object(boot_unlock, 'systemd') + def test_register_uses_pebble_inside_snap( + self, _systemd, _pebble_layers): + with mock.patch.dict( + boot_unlock.os.environ, {'SNAP': '/snap/vaultlocker'}): + boot_unlock.register('test-uuid', '/path/to/conf', timeout=42) + + _pebble_layers.register_boot_unlock.assert_called_once_with( + 'test-uuid', '/path/to/conf', 42, + ) + _systemd.register_decrypt_service.assert_not_called() + + @mock.patch.object(boot_unlock, 'pebble_layers') + @mock.patch.object(boot_unlock, 'systemd') + def test_register_uses_systemd_outside_snap( + self, _systemd, _pebble_layers): + with mock.patch.dict(boot_unlock.os.environ, {}, clear=True): + boot_unlock.register('test-uuid', '/path/to/conf') + + _systemd.register_decrypt_service.assert_called_once_with( + 'test-uuid', '/path/to/conf', + ) + _pebble_layers.register_boot_unlock.assert_not_called() + + def test_running_in_snap_detects_environment(self): + with mock.patch.dict( + boot_unlock.os.environ, {'SNAP': '/snap/vaultlocker'}): + self.assertTrue(boot_unlock.running_in_snap()) + + with mock.patch.dict(boot_unlock.os.environ, {}, clear=True): + self.assertFalse(boot_unlock.running_in_snap()) diff --git a/vaultlocker/tests/unit/test_dmcrypt.py b/vaultlocker/tests/unit/test_dmcrypt.py index eb35133..8518482 100644 --- a/vaultlocker/tests/unit/test_dmcrypt.py +++ b/vaultlocker/tests/unit/test_dmcrypt.py @@ -63,6 +63,18 @@ def test_luks_open(self, _subprocess): input='mykey'.encode('UTF-8') ) + @mock.patch.object(dmcrypt, 'subprocess') + def test_luks_open_by_device(self, _subprocess): + dmcrypt.luks_open('mykey', 'test-uuid', '/dev/sdb') + _subprocess.check_output.assert_called_once_with( + ['cryptsetup', + '--batch-mode', + '--key-file', '-', + 'open', '/dev/sdb', 'crypt-test-uuid', + '--type', 'luks'], + input='mykey'.encode('UTF-8') + ) + @mock.patch.object(dmcrypt, 'os') def test_generate_key(self, _os): _key = b'randomdatastringfromentropy' diff --git a/vaultlocker/tests/unit/test_pebble_layers.py b/vaultlocker/tests/unit/test_pebble_layers.py new file mode 100644 index 0000000..8b6985e --- /dev/null +++ b/vaultlocker/tests/unit/test_pebble_layers.py @@ -0,0 +1,209 @@ +# -*- 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. + +""" +test_pebble_layers +---------------------------------- + +Tests for `pebble_layers` module. +""" + +import subprocess +from unittest import mock + +from vaultlocker import pebble_layers +from vaultlocker.tests.unit import base + +LAYER_PATH = '/data/pebble/layers/100-vaultlocker-decrypt-test-uuid.yaml' +LOCK_PATH = '/data/pebble/.vaultlocker-layers.lock' + + +class TestPebbleLayers(base.TestCase): + + def test_layer_label(self): + self.assertEqual( + 'vaultlocker-decrypt-test-uuid', + pebble_layers.layer_label('test-uuid'), + ) + + def test_service_name(self): + self.assertEqual( + 'decrypt-test-uuid', + pebble_layers.service_name('test-uuid'), + ) + + def test_render_layer(self): + layer = pebble_layers.render_layer( + 'test-uuid', '/path/to/conf', 1234, + ) + + self.assertIn('decrypt-test-uuid:', layer) + self.assertIn( + 'command: vaultlocker --retry 1234 --config ' + '/path/to/conf decrypt test-uuid', + layer, + ) + self.assertIn('startup: enabled', layer) + self.assertIn('on-success: ignore', layer) + self.assertIn('on-failure: restart', layer) + self.assertIn('backoff-delay: 5s', layer) + self.assertIn('backoff-limit: 30s', layer) + + def test_pebble_dir_defaults(self): + with mock.patch.dict(pebble_layers.os.environ, {}, clear=True): + self.assertEqual( + pebble_layers.DEFAULT_PEBBLE_DIR, + pebble_layers.pebble_dir(), + ) + + def test_pebble_dir_from_environment(self): + with mock.patch.dict( + pebble_layers.os.environ, {'PEBBLE': '/data/pebble'}): + self.assertEqual('/data/pebble', pebble_layers.pebble_dir()) + + @mock.patch.object(pebble_layers.fcntl, 'flock') + @mock.patch.object(pebble_layers.os, 'listdir', return_value=[]) + @mock.patch.object(pebble_layers.os, 'replace') + @mock.patch.object(pebble_layers.os, 'makedirs') + @mock.patch.object(pebble_layers.subprocess, 'run') + @mock.patch('builtins.open', new_callable=mock.mock_open) + def test_register_boot_unlock( + self, _open, _run, _makedirs, _replace, _listdir, _flock): + with mock.patch.dict( + pebble_layers.os.environ, {'PEBBLE': '/data/pebble'}): + pebble_layers.register_boot_unlock( + 'test-uuid', '/path/to/conf', 1234, + ) + + _makedirs.assert_called_once_with( + '/data/pebble/layers', exist_ok=True, + ) + self.assertEqual( + [ + mock.call(LOCK_PATH, 'a+b'), + mock.call(LAYER_PATH + '.tmp', 'w', encoding='utf-8'), + ], + _open.call_args_list, + ) + _flock.assert_called_once_with( + _open.return_value, pebble_layers.fcntl.LOCK_EX, + ) + _open.return_value.write.assert_called_once() + _replace.assert_called_once_with( + LAYER_PATH + '.tmp', LAYER_PATH, + ) + self.assertEqual( + [ + mock.call( + ['pebble', 'add', '--combine', + 'vaultlocker-decrypt-test-uuid', LAYER_PATH], + check=True, capture_output=True, + ), + mock.call( + ['pebble', 'replan', '--no-wait'], + check=True, capture_output=True, + ), + ], + _run.call_args_list, + ) + + @mock.patch.object(pebble_layers.fcntl, 'flock') + @mock.patch.object(pebble_layers.os, 'listdir', return_value=[]) + @mock.patch.object(pebble_layers.os, 'replace') + @mock.patch.object(pebble_layers.os, 'makedirs') + @mock.patch.object(pebble_layers.subprocess, 'run') + @mock.patch('builtins.open', new_callable=mock.mock_open) + def test_register_boot_unlock_propagates_replan_failure( + self, _open, _run, _makedirs, _replace, _listdir, _flock): + _run.side_effect = [ + None, + subprocess.CalledProcessError( + returncode=1, cmd='pebble replan --no-wait' + ), + ] + + with mock.patch.dict( + pebble_layers.os.environ, {'PEBBLE': '/data/pebble'}): + with self.assertRaises(subprocess.CalledProcessError): + pebble_layers.register_boot_unlock( + 'test-uuid', '/path/to/conf', 1234, + ) + + _replace.assert_called_once_with( + LAYER_PATH + '.tmp', LAYER_PATH, + ) + self.assertEqual(2, _run.call_count) + + @mock.patch.object(pebble_layers.fcntl, 'flock') + @mock.patch.object(pebble_layers.os, 'listdir', return_value=[]) + @mock.patch.object(pebble_layers.os, 'replace') + @mock.patch.object(pebble_layers.os, 'makedirs') + @mock.patch.object(pebble_layers.subprocess, 'run') + @mock.patch('builtins.open', new_callable=mock.mock_open) + def test_register_boot_unlock_propagates_add_failure( + self, _open, _run, _makedirs, _replace, _listdir, _flock): + _run.side_effect = subprocess.CalledProcessError( + returncode=1, cmd='pebble add', + ) + + with mock.patch.dict( + pebble_layers.os.environ, {'PEBBLE': '/data/pebble'}): + with self.assertRaises(subprocess.CalledProcessError): + pebble_layers.register_boot_unlock( + 'test-uuid', '/path/to/conf', 1234, + ) + + _run.assert_called_once_with( + ['pebble', 'add', '--combine', + 'vaultlocker-decrypt-test-uuid', LAYER_PATH], + check=True, capture_output=True, + ) + + +class TestLayerPath(base.TestCase): + """Tests for numeric layer prefix allocation.""" + + def test_allocates_first_prefix(self): + with mock.patch.object(pebble_layers.os, 'listdir', return_value=[]): + path = pebble_layers._layer_path( + '/data/pebble/layers', 'vaultlocker-decrypt-u', + ) + + self.assertEqual( + '/data/pebble/layers/100-vaultlocker-decrypt-u.yaml', path, + ) + + def test_allocates_next_prefix(self): + names = ['100-a.yaml', 'notanumber.txt', '101-b.yaml'] + with mock.patch.object( + pebble_layers.os, 'listdir', return_value=names): + path = pebble_layers._layer_path( + '/data/pebble/layers', 'vaultlocker-decrypt-u', + ) + + self.assertEqual( + '/data/pebble/layers/102-vaultlocker-decrypt-u.yaml', path, + ) + + def test_reuses_existing_label(self): + names = ['100-a.yaml', '101-vaultlocker-decrypt-u.yaml'] + with mock.patch.object( + pebble_layers.os, 'listdir', return_value=names): + path = pebble_layers._layer_path( + '/data/pebble/layers', 'vaultlocker-decrypt-u', + ) + + self.assertEqual( + '/data/pebble/layers/101-vaultlocker-decrypt-u.yaml', path, + ) diff --git a/vaultlocker/tests/unit/test_systemd.py b/vaultlocker/tests/unit/test_systemd.py index 1617042..29b9e5f 100644 --- a/vaultlocker/tests/unit/test_systemd.py +++ b/vaultlocker/tests/unit/test_systemd.py @@ -33,3 +33,50 @@ def test_enable(self, _subprocess): _subprocess.check_call.assert_called_once_with( ['systemctl', 'enable', 'my-service.service'] ) + + def test_config_dropin_path(self): + self.assertEqual( + '/etc/systemd/system/' + 'vaultlocker-decrypt@test-uuid.service.d/config.conf', + systemd.config_dropin_path( + 'vaultlocker-decrypt@test-uuid.service', + ), + ) + + @mock.patch.object(systemd.os, 'makedirs') + @mock.patch('builtins.open', new_callable=mock.mock_open) + def test_write_config_dropin(self, _open, _makedirs): + systemd.write_config_dropin( + 'vaultlocker-decrypt@test-uuid.service', + '/var/snap/vaultlocker/common/app/vaultlocker.conf', + ) + + _makedirs.assert_called_once_with( + '/etc/systemd/system/' + 'vaultlocker-decrypt@test-uuid.service.d', + exist_ok=True, + ) + _open.assert_called_once_with( + '/etc/systemd/system/' + 'vaultlocker-decrypt@test-uuid.service.d/config.conf', + 'w', + ) + handle = _open() + handle.write.assert_called_once_with( + '[Service]\n' + 'Environment=VAULTLOCKER_CONFIG=' + '/var/snap/vaultlocker/common/app/vaultlocker.conf\n' + ) + + @mock.patch.object(systemd, 'enable') + @mock.patch.object(systemd, 'write_config_dropin') + def test_register_decrypt_service(self, _write_dropin, _enable): + systemd.register_decrypt_service('test-uuid', '/path/to/conf') + + _write_dropin.assert_called_once_with( + 'vaultlocker-decrypt@test-uuid.service', + '/path/to/conf', + ) + _enable.assert_called_once_with( + 'vaultlocker-decrypt@test-uuid.service', + ) diff --git a/vaultlocker/tests/unit/test_vaultlocker.py b/vaultlocker/tests/unit/test_vaultlocker.py index 05b9822..82a6960 100644 --- a/vaultlocker/tests/unit/test_vaultlocker.py +++ b/vaultlocker/tests/unit/test_vaultlocker.py @@ -60,6 +60,17 @@ def _hostname_config(self, hostname=None): return config + def test_get_config_rejects_path_with_whitespace(self): + invalid_paths = [ + '/path with spaces/vaultlocker.conf', + '/path\twith-tab/vaultlocker.conf', + ] + + for config_path in invalid_paths: + with self.subTest(config_path=config_path): + with self.assertRaises(ValueError): + shell.get_config(config_path) + @mock.patch.object(shell.hvac, 'Client') def test_vault_client_uses_approle_login(self, _client): client = _client.return_value @@ -88,10 +99,12 @@ def test_vault_store_uses_configured_mount_and_version(self, _kv_store): @mock.patch.object(shell, 'get_hostname') @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'systemd') + @mock.patch.object(shell, 'boot_unlock') @mock.patch.object(shell, 'dmcrypt') - def test_encrypt(self, _dmcrypt, _systemd, _vault_store, _get_hostname): + def test_encrypt(self, _dmcrypt, _boot_unlock, _vault_store, + _get_hostname): _get_hostname.return_value = 'host' + _boot_unlock.running_in_snap.return_value = False _dmcrypt.generate_key.return_value = 'testkey' store = _vault_store.return_value @@ -116,18 +129,75 @@ def test_encrypt(self, _dmcrypt, _systemd, _vault_store, _get_hostname): _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' + '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' ) - _systemd.enable.assert_called_once_with( - 'vaultlocker-decrypt@passed-UUID.service' + _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, ) @mock.patch.object(shell, 'get_hostname') @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'systemd') + @mock.patch.object(shell, 'boot_unlock') @mock.patch.object(shell, 'dmcrypt') - def test_encrypt_key_mismatch(self, _dmcrypt, _systemd, + def test_encrypt_key_mismatch(self, _dmcrypt, _boot_unlock, _vault_store, _get_hostname): _get_hostname.return_value = 'host' _dmcrypt.generate_key.return_value = 'testkey' @@ -150,7 +220,7 @@ def test_encrypt_key_mismatch(self, _dmcrypt, _systemd, ) _dmcrypt.luks_format.assert_not_called() - _systemd.enable.assert_not_called() + _boot_unlock.register.assert_not_called() @mock.patch.object(shell, '_device_exists', return_value=False) @mock.patch.object(shell, 'get_hostname') @@ -248,9 +318,9 @@ def test_get_vault_path(self, _get_hostname): @mock.patch.object(shell, 'get_hostname') @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'systemd') + @mock.patch.object(shell, 'boot_unlock') @mock.patch.object(shell, 'dmcrypt') - def test_encrypt_luks_failure(self, _dmcrypt, _systemd, + def test_encrypt_luks_failure(self, _dmcrypt, _boot_unlock, _vault_store, _get_hostname): _get_hostname.return_value = 'host' _dmcrypt.generate_key.return_value = 'testkey' @@ -276,7 +346,7 @@ def test_encrypt_luks_failure(self, _dmcrypt, _systemd, ) store.delete.assert_called_once_with('host/passed-UUID') - _systemd.enable.assert_not_called() + _boot_unlock.register.assert_not_called() @mock.patch.object(shell, 'get_hostname') @mock.patch.object(shell, '_vault_store') @@ -478,10 +548,10 @@ def test_get_or_create_managed_key_error( @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, 'systemd') + @mock.patch.object(shell, 'boot_unlock') @mock.patch.object(shell, 'dmcrypt') def test_enroll_block_device( - self, _dmcrypt, _systemd, _vault_store, + 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' @@ -522,19 +592,20 @@ def test_enroll_block_device( _dmcrypt.luks_open.assert_called_once_with( 'managed-key', 'test-uuid', + '/dev/sdb', ) - _systemd.enable.assert_called_once_with( - 'vaultlocker-decrypt@test-uuid.service', + _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, 'systemd') + @mock.patch.object(shell, 'boot_unlock') @mock.patch.object(shell, 'dmcrypt') def test_enroll_block_device_already_enrolled( - self, _dmcrypt, _systemd, _vault_store, + 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' @@ -557,16 +628,16 @@ def test_enroll_block_device_already_enrolled( _dmcrypt.luks_add_key.assert_not_called() _dmcrypt.luks_open.assert_not_called() - _systemd.enable.assert_called_once_with( - 'vaultlocker-decrypt@test-uuid.service', + _boot_unlock.register.assert_called_once_with( + 'test-uuid', args.config, ) @mock.patch.object(shell, '_get_or_create_managed_key') @mock.patch.object(shell, '_vault_store') - @mock.patch.object(shell, 'systemd') + @mock.patch.object(shell, 'boot_unlock') @mock.patch.object(shell, 'dmcrypt') def test_enroll_block_device_rejects_invalid_existing_key( - self, _dmcrypt, _systemd, _vault_store, + self, _dmcrypt, _boot_unlock, _vault_store, _get_managed_key): _dmcrypt.luks_uuid.return_value = 'test-uuid' _dmcrypt.luks_test_key.return_value = False @@ -590,7 +661,7 @@ def test_enroll_block_device_rejects_invalid_existing_key( _get_managed_key.assert_not_called() _dmcrypt.luks_add_key.assert_not_called() _dmcrypt.luks_open.assert_not_called() - _systemd.enable.assert_not_called() + _boot_unlock.register.assert_not_called() @mock.patch.object( shell.sys,