feature: the VPN, the router, the name server and WebDAV are components switched on the System tab and installed on demand, Caddy from the Ubuntu archive is a dependency and serves every HTTP and HTTPS port, HTTPS is chosen at install, its certificate is of the Servers Issuing CA or self-signed by default, of ACME or of another CA, the issuing CAs are in one tab, a locked account is unlocked again, the name of a CA is fixed once the CA exists, and a run of setup is no longer cut short by a change.
Release / release (push) Failing after 8s
Release / release (push) Failing after 8s
This commit is contained in:
1 parent
a649331aa2
commit
a7bfabcb89
97 files changed
+4498
-1834
No files matched your search
+123
-38
@@ -4,10 +4,12 @@
|
||||
The remote and its storage pool are required, as --remote and --pool or LXD_REMOTE and
|
||||
LXD_POOL. The instances live in a project of their own, --project (LXD_TEST_PROJECT, lm-test by
|
||||
default), which must not exist and is removed with its networks after each scenario unless --keep
|
||||
is given. The package is the newest out/linux-manager_*_all.deb. The administrator's name and
|
||||
password are set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env, and the pre-shared
|
||||
key is written to tmp/remote-test.env. Each check prints PASS, FAIL or SKIP; the run exits 1 when a
|
||||
check failed.
|
||||
is given. The package is --deb, or else the one built last, in out/ or out/dev/. The administrator, admin, has a
|
||||
password generated per run, kept in the scenario's Vault as <server>/admin. Each scenario's
|
||||
project gets a Vault, the container lm-vault reached on the LXD host's address; every other instance
|
||||
with a default route, the hosts of isolated LANs apart, gets an AppRole of its own in it and
|
||||
/etc/vault once it is ready, and reads the files that hold a secret from it (Lab.hand_over), never as an argument or on standard input. Each check prints PASS, FAIL or SKIP; the run exits 1 when a check
|
||||
failed.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -15,17 +17,25 @@ import importlib
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import secrets
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from lm_dev import ROOT, TESTS, lxc_exec, set_dotenv
|
||||
from lm_dev import HANDOVER_DIR, ROOT, TESTS, VAULT_PORT, VaultError, config_path, enrol_instance, hand_over, \
|
||||
host_address, lxc_exec, newest_deb, store_secret, vault_initialise
|
||||
|
||||
TMP = ROOT / 'tmp' / 'remote-test'
|
||||
|
||||
#: Seconds a server's component installations may take before a configuration fails.
|
||||
INSTALL_WAIT = 900
|
||||
SCENARIOS = sorted(path.stem for path in (TESTS / 'scenarios').glob('*.py') if path.stem != '__init__')
|
||||
|
||||
# The Vault of a scenario: its bridge with outbound NAT, and the container's MAC address and address on it.
|
||||
VAULT_NETWORK = ('lmt-vault', '10.99.99.1/24', '00:16:3e:4c:99:10', '10.99.99.10/24')
|
||||
|
||||
|
||||
class Lab:
|
||||
"""The instances and networks of a run on one LXD remote and project, and the results of its checks.
|
||||
@@ -47,6 +57,9 @@ class Lab:
|
||||
self.networks = []
|
||||
self.macs = {}
|
||||
self.addresses = {}
|
||||
self.vault = None
|
||||
self.enrolled = set()
|
||||
self.routed = set()
|
||||
|
||||
def lxc(self, *args, check=True):
|
||||
"""Run lxc with the arguments and the project; raise CalledProcessError when it fails, unless check is false."""
|
||||
@@ -108,6 +121,33 @@ class Lab:
|
||||
result = self.on(name, *command)
|
||||
self.result(description, re.search(pattern, result.stdout + result.stderr, re.M) is None)
|
||||
|
||||
def start_vault(self):
|
||||
"""Launch the scenario's Vault, the container lm-vault, reached by the Mac and the instances on the LXD host's
|
||||
address through a proxy device, and initialise it."""
|
||||
host = host_address(self.remote)
|
||||
if not host:
|
||||
raise RuntimeError(f'no IPv4 address of the host of remote {self.remote} for the Vault')
|
||||
network, gateway, mac, address = VAULT_NETWORK
|
||||
self.network(network, gateway)
|
||||
self.instance('lm-vault', 'container', 'vault.yaml', (network, mac, address, gateway.split('/')[0]))
|
||||
if not self.ready('lm-vault'):
|
||||
raise RuntimeError('the Vault container did not boot')
|
||||
self.lxc('config', 'device', 'add', f'{self.remote}:lm-vault', 'vault', 'proxy',
|
||||
f'listen=tcp:{host}:{VAULT_PORT}', f'connect=tcp:127.0.0.1:{VAULT_PORT}')
|
||||
url = f'http://{host}:{VAULT_PORT}'
|
||||
try:
|
||||
self.vault = vault_initialise(self.project, url, url)
|
||||
except VaultError as error:
|
||||
raise RuntimeError(f'the Vault was not initialised: {error}')
|
||||
|
||||
def hand_over(self, name, secret, content, destination, mode='0600'):
|
||||
"""Give the instance the content, a file that holds a secret, through the Vault as <name>/<secret>, written
|
||||
to destination; True when it was handed over."""
|
||||
problem = hand_over(self.remote, self.project, name, self.vault, secret, content, destination, mode)
|
||||
if problem:
|
||||
print(problem, file=sys.stderr)
|
||||
return problem is None
|
||||
|
||||
def network(self, name, address):
|
||||
"""Create a bridge with outbound NAT at the gateway address GATEWAY/PREFIX, or without a host address when None.
|
||||
|
||||
@@ -129,6 +169,8 @@ class Lab:
|
||||
"""
|
||||
self.macs[name] = [nic[1] for nic in nics]
|
||||
self.addresses[name] = nics[0][2]
|
||||
if any(len(nic) > 3 for nic in nics):
|
||||
self.routed.add(name)
|
||||
netcfg = 'version: 2\nethernets:\n'
|
||||
for index, (_, mac, address, *gateway) in enumerate(nics):
|
||||
if kind == 'vm':
|
||||
@@ -152,7 +194,8 @@ class Lab:
|
||||
self.lxc('start', f'{self.remote}:{name}')
|
||||
|
||||
def ready(self, *names):
|
||||
"""Wait for each instance's agent and cloud-init, then for its first address; False when one is not ready.
|
||||
"""Wait for each instance's agent and cloud-init, then for its first address, and give an instance with a
|
||||
default route, other than the Vault, its AppRole the first time; False when one is not ready.
|
||||
|
||||
cloud-init's status 2, done with recoverable errors, counts as booted. An instance whose first
|
||||
NIC takes its address from DHCP waits for any IPv4 address outside lo.
|
||||
@@ -174,6 +217,15 @@ class Lab:
|
||||
else:
|
||||
print(f'{name} has no address {address or "from DHCP"}', file=sys.stderr)
|
||||
return False
|
||||
if name != 'lm-vault' and name in self.routed and name not in self.enrolled:
|
||||
problem = enrol_instance(self.remote, self.project, name, self.vault)
|
||||
if problem:
|
||||
print(problem, file=sys.stderr)
|
||||
return False
|
||||
if self.on(name, 'install', '-d', '-m', '0700', HANDOVER_DIR).returncode != 0:
|
||||
print(f'{HANDOVER_DIR} cannot be made in {name}', file=sys.stderr)
|
||||
return False
|
||||
self.enrolled.add(name)
|
||||
return True
|
||||
|
||||
def nic_of(self, name, index):
|
||||
@@ -204,16 +256,24 @@ class Lab:
|
||||
'wireguard-tools', 'openvpn', 'curl').returncode == 0)
|
||||
|
||||
def setup_run(self, name):
|
||||
"""Run linux-manager-setup and wait for it; True when it succeeded."""
|
||||
return self.on(name, 'systemctl', 'restart', 'linux-manager-setup').returncode == 0
|
||||
"""Have linux-manager-setup run, after a run in progress, and wait for it; True when it succeeded."""
|
||||
return self.on(name, 'linux-manager-config-edit', 'apply').returncode == 0
|
||||
|
||||
def server(self, name, config):
|
||||
"""Install the package with the test administrator, then apply the configuration; True when both succeeded."""
|
||||
if not self.push(self.deb, name, '/tmp/linux-manager.deb'):
|
||||
return False
|
||||
preseed = (f'linux-manager linux-manager/admin_username string admin\n'
|
||||
preseed = ('linux-manager linux-manager/admin_username string admin\n'
|
||||
f'linux-manager linux-manager/admin_password password {self.admin_password}\n')
|
||||
if self.on(name, 'debconf-set-selections', input=preseed).returncode != 0:
|
||||
try:
|
||||
store_secret(self.vault, f'{name}/admin', {'password': self.admin_password})
|
||||
except VaultError as error:
|
||||
print(f'the admin password cannot be kept in the Vault: {error}', file=sys.stderr)
|
||||
return False
|
||||
if not self.hand_over(name, 'preseed', preseed, f'{HANDOVER_DIR}/preseed'):
|
||||
return False
|
||||
if self.on(name, 'sh', '-c', f'debconf-set-selections {HANDOVER_DIR}/preseed; status=$?; '
|
||||
f'rm -f {HANDOVER_DIR}/preseed; exit $status').returncode != 0:
|
||||
return False
|
||||
result = self.on(name, 'env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y',
|
||||
'/tmp/linux-manager.deb')
|
||||
@@ -223,10 +283,10 @@ class Lab:
|
||||
def render(self, name, config):
|
||||
"""Replace the server's configuration, with its placeholders filled in.
|
||||
|
||||
@PSK@ is the pre-shared key, @ETH0@ and @ETH1@ the names of the server's NICs and @CIDR0@ the
|
||||
network of its first address.
|
||||
@PSK@ is the pre-shared key, @ETH0@ and @ETH1@ the names of the server's NICs and @CIDR0@ the network of its
|
||||
first address; the configuration reaches the server through the Vault.
|
||||
"""
|
||||
text = (TESTS / 'configs' / config).read_text(encoding='utf-8').replace('@PSK@', self.psk)
|
||||
text = (TESTS / 'configs' / config).read_text(encoding='utf-8')
|
||||
for index in (0, 1):
|
||||
placeholder = f'@ETH{index}@'
|
||||
if placeholder in text:
|
||||
@@ -236,11 +296,25 @@ class Lab:
|
||||
text = text.replace(placeholder, nic)
|
||||
if '@CIDR0@' in text:
|
||||
text = text.replace('@CIDR0@', str(self.address(name).network))
|
||||
return self.push_text(text, name, '/etc/linux-manager/linux-manager.json', '0600')
|
||||
return self.hand_over(name, 'config', text.replace('@PSK@', self.psk), '/etc/linux-manager/linux-manager.json')
|
||||
|
||||
def installed(self, name):
|
||||
"""Wait for the installations of the server's components (linux-manager-install@*) to end, up to INSTALL_WAIT
|
||||
seconds; True when none failed."""
|
||||
deadline = time.monotonic() + INSTALL_WAIT
|
||||
while time.monotonic() < deadline:
|
||||
running = self.on(name, 'systemctl', 'list-units', '--no-legend', '--state=activating,active',
|
||||
'linux-manager-install@*').stdout.strip()
|
||||
if not running:
|
||||
return not self.on(name, 'systemctl', 'list-units', '--no-legend', '--state=failed',
|
||||
'linux-manager-install@*').stdout.strip()
|
||||
time.sleep(5)
|
||||
return False
|
||||
|
||||
def configure(self, name, config):
|
||||
"""Render the configuration and apply it twice, as the server's certificates follow the first run."""
|
||||
return self.render(name, config) and self.setup_run(name) and self.setup_run(name)
|
||||
"""Render the configuration and apply it, wait for the packages of its components, and apply it again, as the
|
||||
components and the server's certificates follow the first run."""
|
||||
return self.render(name, config) and self.setup_run(name) and self.installed(name) and self.setup_run(name)
|
||||
|
||||
def echo_server(self, name):
|
||||
"""Answer HTTP on port 8080 of the instance with the address of the client."""
|
||||
@@ -248,10 +322,14 @@ class Lab:
|
||||
self.on(name, 'systemd-run', '--unit=lm-test-echo', 'python3', '/root/echo.py').returncode == 0)
|
||||
|
||||
def vpn_user(self, name):
|
||||
"""Add the VPN user alice, whose password is the administrator's; True when it was added."""
|
||||
return self.on(name, 'linux-manager-user', '--json', 'add', 'alice', '--first-name', 'Alice',
|
||||
'--last-name', 'Test', '--email', 'alice@example.org',
|
||||
input=self.admin_password + '\n').returncode == 0
|
||||
"""Add the VPN user alice, whose password is the administrator's, read from a file the Vault gives the
|
||||
server; True when it was added."""
|
||||
secret = f'{HANDOVER_DIR}/alice.password'
|
||||
if not self.hand_over(name, 'alice', f'{self.admin_password}\n', secret):
|
||||
return False
|
||||
return self.on(name, 'sh', '-c', 'linux-manager-user --json add alice --first-name Alice --last-name Test '
|
||||
f'--email alice@example.org < {secret}; status=$?; rm -f {secret}; '
|
||||
'exit $status').returncode == 0
|
||||
|
||||
def alice(self, name):
|
||||
"""User alice from the server's user list, or None."""
|
||||
@@ -259,10 +337,13 @@ class Lab:
|
||||
return next((user for user in listing.get('users', []) if user.get('name') == 'alice'), None)
|
||||
|
||||
def wireguard_client(self, client, server, endpoint, address, allowed):
|
||||
"""Give alice a peer of a new client key and bring wg0 up on the client towards the server, for allowed only."""
|
||||
private_key = self.on(client, 'wg', 'genkey').stdout.strip()
|
||||
public_key = self.on(client, 'wg', 'pubkey', input=private_key + '\n').stdout.strip()
|
||||
if not private_key or not public_key:
|
||||
"""Give alice a peer of a new client key and bring wg0 up on the client towards the server, for allowed only.
|
||||
|
||||
The client's private key is made in the client and never leaves it; wg0.conf is completed there.
|
||||
"""
|
||||
public_key = self.on(client, 'sh', '-c', 'umask 077; wg genkey > /etc/wireguard/private.key && '
|
||||
'wg pubkey < /etc/wireguard/private.key').stdout.strip()
|
||||
if not public_key:
|
||||
return False
|
||||
if not self.push(TESTS / 'wireguard_peer.py', server, '/root/wireguard_peer.py'):
|
||||
return False
|
||||
@@ -271,9 +352,14 @@ class Lab:
|
||||
if not self.setup_run(server):
|
||||
return False
|
||||
server_key = self.on(server, 'cat', '/etc/wireguard/wg0.pub').stdout.strip()
|
||||
conf = (f'[Interface]\nPrivateKey = {private_key}\nAddress = {address}/32\n\n'
|
||||
conf = (f'[Interface]\nPrivateKey = @KEY@\nAddress = {address}/32\n\n'
|
||||
f'[Peer]\nPublicKey = {server_key}\nEndpoint = {endpoint}:51820\nAllowedIPs = {allowed}\n')
|
||||
return (self.push_text(conf, client, '/etc/wireguard/wg0.conf', '0600') and
|
||||
# awk reads the key from its file, so it is no argument of any process.
|
||||
complete = ("umask 077; awk 'NR == FNR { key = $0; next } { gsub(\"@KEY@\", key) } 1' "
|
||||
'/etc/wireguard/private.key /etc/wireguard/wg0.template > /etc/wireguard/wg0.conf && '
|
||||
'rm -f /etc/wireguard/wg0.template')
|
||||
return (self.push_text(conf, client, '/etc/wireguard/wg0.template', '0600') and
|
||||
self.on(client, 'sh', '-c', complete).returncode == 0 and
|
||||
self.on(client, 'bash', '/usr/bin/wg-quick', 'up', 'wg0').returncode == 0)
|
||||
|
||||
def wireguard_module(self, name):
|
||||
@@ -291,6 +377,8 @@ class Lab:
|
||||
listing = self.lxc('list', f'{self.remote}:', '-c', 'n', '-f', 'csv', check=False)
|
||||
for name in listing.stdout.split():
|
||||
self.lxc('delete', '--force', f'{self.remote}:{name}', check=False)
|
||||
config_path(f'vault-{self.project}.json').unlink(missing_ok=True)
|
||||
self.vault = None
|
||||
for name in self.networks:
|
||||
subprocess.run(['lxc', 'network', 'delete', f'{self.remote}:{name}'], capture_output=True)
|
||||
self.networks = []
|
||||
@@ -308,6 +396,7 @@ def main():
|
||||
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'),
|
||||
help='the image of every instance (LXD_IMAGE, default ubuntu:26.04)')
|
||||
parser.add_argument('--keep', action='store_true', help='leave the project and the networks in place')
|
||||
parser.add_argument('--deb', help='the package to test (default the one built last, in out/ or out/dev/)')
|
||||
args = parser.parse_args()
|
||||
if not args.remote:
|
||||
parser.error('--remote or LXD_REMOTE is required')
|
||||
@@ -318,21 +407,16 @@ def main():
|
||||
if unknown:
|
||||
parser.error(f'no scenario {", ".join(unknown)}')
|
||||
|
||||
debs = sorted((ROOT / 'out').glob('linux-manager_*_all.deb'))
|
||||
if not debs:
|
||||
sys.exit('no out/linux-manager_*_all.deb; run ./build.sh first')
|
||||
deb = pathlib.Path(args.deb) if args.deb else newest_deb()
|
||||
if deb is None or not deb.is_file():
|
||||
sys.exit(f'no package {args.deb}' if args.deb else 'no out/linux-manager_*_all.deb; run ./build.sh first')
|
||||
if subprocess.run(['lxc', 'project', 'show', f'{args.remote}:{args.project}'], capture_output=True).returncode == 0:
|
||||
sys.exit(f'project {args.project} exists on {args.remote}; remove it or choose another with --project')
|
||||
|
||||
TMP.mkdir(parents=True, exist_ok=True)
|
||||
lab = Lab(args.remote, args.project, args.pool, args.image, args.keep, debs[-1],
|
||||
lab = Lab(args.remote, args.project, args.pool, args.image, args.keep, deb,
|
||||
secrets.token_hex(16), secrets.token_hex(24))
|
||||
env = ROOT / 'tmp' / 'remote-test.env'
|
||||
env.touch(mode=0o600)
|
||||
env.chmod(0o600)
|
||||
env.write_text(f'PSK={lab.psk}\n', encoding='utf-8')
|
||||
set_dotenv({'ADMIN_USERNAME': 'admin', 'ADMIN_PASSWORD': lab.admin_password})
|
||||
print(f'package: {debs[-1].name}; remote: {args.remote}; project: {args.project}; image: {args.image}')
|
||||
print(f'package: {deb}; remote: {args.remote}; project: {args.project}; image: {args.image}')
|
||||
|
||||
sys.path.insert(0, str(TESTS))
|
||||
try:
|
||||
@@ -341,6 +425,7 @@ def main():
|
||||
'-c', 'features.images=false'], capture_output=True, check=True)
|
||||
print(f'== {name}')
|
||||
try:
|
||||
lab.start_vault()
|
||||
importlib.import_module(f'scenarios.{name}').run(lab)
|
||||
except (subprocess.CalledProcessError, RuntimeError) as error:
|
||||
detail = error.stderr.strip() if isinstance(error, subprocess.CalledProcessError) else str(error)
|
||||
@@ -351,8 +436,8 @@ def main():
|
||||
sys.exit(130)
|
||||
|
||||
print(f'== passed {lab.passed}, failed {lab.failed}, skipped {lab.skipped}')
|
||||
print("Not covered: IKEv2 client access, HTTPS with Let's Encrypt, the OpenID Provider and passkeys,")
|
||||
print('PowerDNS answering from outside, the Azure and GCP platform modules.')
|
||||
print("Not covered: IKEv2 client access, HTTPS with Let's Encrypt, passkeys, PowerDNS answering from")
|
||||
print('outside, the Azure and GCP platform modules.')
|
||||
sys.exit(1 if lab.failed else 0)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user