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
+3
-3
@@ -8,7 +8,7 @@ is the newest changelog entry's with ~devN before its Debian revision, 0.41.0-1
|
||||
with CONTAINER_RUNTIME and DOCKER_CONTEXT from the environment; the build is moved to out/dev/,
|
||||
copied into the repository container of the project --project (LXD_PROJECT, lm-dev by default)
|
||||
made by lm-dev-lxd-project.py, and published there. The remote is the project's, read from
|
||||
tmp/lxd-project-PROJECT.json, so the script takes no --remote.
|
||||
.lm-dev-config/lxd-project-PROJECT.json, so the script takes no --remote.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -18,7 +18,7 @@ import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from lm_dev import PROJECT, ROOT, lxc_exec
|
||||
from lm_dev import PROJECT, ROOT, config_path, lxc_exec
|
||||
|
||||
SERIAL = ROOT / '.dev-build.serial'
|
||||
CHANGELOG = ROOT / 'debian-package' / 'debian' / 'changelog'
|
||||
@@ -30,7 +30,7 @@ def main():
|
||||
help=f'the test project made by lm-dev-lxd-project.py, whose remote is used (LXD_PROJECT, '
|
||||
f'default {PROJECT})')
|
||||
args = parser.parse_args()
|
||||
state_file = ROOT / 'tmp' / f'lxd-project-{args.project}.json'
|
||||
state_file = config_path(f'lxd-project-{args.project}.json')
|
||||
if not state_file.is_file():
|
||||
sys.exit(f'no {state_file}; create the project with lm-dev-lxd-project.py create')
|
||||
state = json.loads(state_file.read_text(encoding='utf-8'))
|
||||
|
||||
+126
-36
@@ -1,17 +1,22 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create or remove an LXD project for manual tests, or its uplink: lm-dev-lxd-project.py create|remove|uplink.
|
||||
"""Create or remove an LXD project for manual tests, its Vault, or its uplink: lm-dev-lxd-project.py
|
||||
create|remove|vault|uplink.
|
||||
|
||||
uplink setup creates the physical uplink network once per remote, and uplink remove deletes it
|
||||
(see uplink).
|
||||
(see uplink). vault create makes the project's Vault, vault unseal unseals it after a restart, and
|
||||
vault remove deletes it (see vault_create).
|
||||
|
||||
create makes, on the remote (--remote or LXD_REMOTE), the project (--project or LXD_PROJECT,
|
||||
lm-dev by default) with its root disks on --pool (LXD_POOL) and networks of its own, OVN networks
|
||||
on the uplink --uplink (LXD_UPLINK, uplink by default): wan, with NAT and DHCP on a subnet LXD
|
||||
picks, and lana and lanb, on subnets LXD picks without DHCP. The project's default profile puts
|
||||
eth0 on wan. The container repo serves a signed apt repository of the dev builds over HTTP;
|
||||
lm-dev-build.py publishes into it and lm-dev-vm.py installs from it. What they need is written to
|
||||
tmp/lxd-project-PROJECT.json, with the repository's key in tmp/lxd-project-PROJECT.gpg. remove
|
||||
deletes the project's instances, its networks, the project and those files.
|
||||
lm-dev-build.py publishes into it and lm-dev-vm.py installs from it. The container vault is the
|
||||
project's Vault, made first, which the scripts hand secrets to the instances through; every other
|
||||
instance gets an AppRole of its own in it and /etc/vault (lm_dev.enrol_instance). What they need is written
|
||||
to .lm-dev-config/lxd-project-PROJECT.json, with the repository's key in
|
||||
.lm-dev-config/lxd-project-PROJECT.gpg. remove deletes the project's instances, its networks, the
|
||||
project and those files.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -22,7 +27,8 @@ import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from lm_dev import PROJECT, ROOT, TESTS, lxc_exec
|
||||
from lm_dev import PROJECT, TESTS, VAULT_PORT, VaultError, config_path, enrol_instance, lxc_exec, vault_initialise, \
|
||||
vault_state, vault_unseal
|
||||
|
||||
NETWORKS = ('wan', 'lana', 'lanb')
|
||||
|
||||
@@ -33,8 +39,84 @@ def lxc(*args, project, check=True, input=None):
|
||||
check=check)
|
||||
|
||||
|
||||
def launch(args, name, user_data):
|
||||
"""Launch the container with the cloud-init user data on the project's default profile, wait until it has booted
|
||||
and has an address on eth0, and pin that address; the address."""
|
||||
lxc('launch', args.image, f'{args.remote}:{name}',
|
||||
'-c', 'cloud-init.user-data=' + (TESTS / 'cloud-init' / user_data).read_text(encoding='utf-8'),
|
||||
project=args.project)
|
||||
# cloud-init's status 2 is done with recoverable errors.
|
||||
for _ in range(120):
|
||||
if lxc_exec(args.remote, args.project, name, 'cloud-init', 'status', '--wait').returncode in (0, 2):
|
||||
break
|
||||
time.sleep(5)
|
||||
else:
|
||||
raise RuntimeError(f'the container {name} did not boot')
|
||||
for _ in range(24):
|
||||
match = re.search(r' inet (\d+\.\d+\.\d+\.\d+)/',
|
||||
lxc_exec(args.remote, args.project, name, 'ip', '-4', '-o', 'addr', 'show', 'dev',
|
||||
'eth0').stdout)
|
||||
if match:
|
||||
break
|
||||
time.sleep(5)
|
||||
else:
|
||||
raise RuntimeError(f'the container {name} has no address on eth0')
|
||||
lxc('config', 'device', 'override', f'{args.remote}:{name}', 'eth0', f'ipv4.address={match.group(1)}',
|
||||
project=args.project)
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def vault_forward(args):
|
||||
"""The listen address of the forward of the project's Vault on wan, or None."""
|
||||
listing = lxc('network', 'forward', 'list', f'{args.remote}:wan', '-f', 'json', project=args.project,
|
||||
check=False)
|
||||
if listing.returncode != 0:
|
||||
return None
|
||||
return next((forward['listen_address'] for forward in json.loads(listing.stdout) or []
|
||||
if forward.get('config', {}).get('user.service') == 'vault'), None)
|
||||
|
||||
|
||||
def vault_create(args):
|
||||
"""Make the project's Vault: the container vault (cloud-init vault.yaml), a forward of its port on wan at
|
||||
--vault-address or an allocated one, which the scripts reach it on, and its initialisation with one key share,
|
||||
unsealed, with KV v2, TOTP and AppRole; its key and root token are kept in .lm-dev-config/vault-PROJECT.json;
|
||||
the state."""
|
||||
if vault_state(args.project) is not None:
|
||||
raise RuntimeError(f'project {args.project} has a Vault; remove it with vault remove first')
|
||||
print(f'launching the Vault container {args.remote}:vault (project {args.project})')
|
||||
address = launch(args, 'vault', 'vault.yaml')
|
||||
listen = [args.vault_address] if args.vault_address else ['--allocate=ipv4']
|
||||
lxc('network', 'forward', 'create', f'{args.remote}:wan', *listen, 'user.service=vault', project=args.project)
|
||||
forward = vault_forward(args)
|
||||
if not forward:
|
||||
raise RuntimeError('the forward of the Vault was not made')
|
||||
lxc('network', 'forward', 'port', 'add', f'{args.remote}:wan', forward, 'tcp', str(VAULT_PORT), address,
|
||||
str(VAULT_PORT), project=args.project)
|
||||
state = vault_initialise(args.project, f'http://{forward}:{VAULT_PORT}', f'http://{address}:{VAULT_PORT}')
|
||||
print(f'the Vault of {args.project} is at {state["url"]}, for the instances {state["internal_url"]}; '
|
||||
f'state: {config_path(f"vault-{args.project}.json")}')
|
||||
return state
|
||||
|
||||
|
||||
def vault_remove(args):
|
||||
"""Delete the project's Vault, its forward and its state; True when all went."""
|
||||
ok = True
|
||||
if lxc('info', f'{args.remote}:vault', project=args.project, check=False).returncode == 0:
|
||||
result = lxc('delete', '--force', f'{args.remote}:vault', project=args.project, check=False)
|
||||
if result.returncode != 0:
|
||||
ok = False
|
||||
print(f'could not delete vault: {result.stderr.strip()}', file=sys.stderr)
|
||||
forward = vault_forward(args)
|
||||
if forward:
|
||||
lxc('network', 'forward', 'delete', f'{args.remote}:wan', forward, project=args.project, check=False)
|
||||
if ok:
|
||||
config_path(f'vault-{args.project}.json').unlink(missing_ok=True)
|
||||
print(f'project {args.project} has no Vault')
|
||||
return ok
|
||||
|
||||
|
||||
def create(args, state, key):
|
||||
"""Create the project with its networks and default profile, and the repository container."""
|
||||
"""Create the project with its networks and default profile, the Vault and the repository container."""
|
||||
subprocess.run(['lxc', 'project', 'create', f'{args.remote}:{args.project}', '-s', args.pool,
|
||||
'-c', 'features.images=false', '-c', 'features.networks=true'],
|
||||
capture_output=True, text=True, check=True)
|
||||
@@ -49,33 +131,16 @@ def create(args, state, key):
|
||||
lxc('profile', 'device', 'add', f'{args.remote}:default', 'eth0', 'nic', 'network=wan', 'name=eth0',
|
||||
project=args.project)
|
||||
|
||||
vault = vault_create(args)
|
||||
print(f'launching the repository container {args.remote}:repo (project {args.project})')
|
||||
lxc('launch', args.image, f'{args.remote}:repo',
|
||||
'-c', 'cloud-init.user-data=' + (TESTS / 'cloud-init' / 'repo.yaml').read_text(encoding='utf-8'),
|
||||
project=args.project)
|
||||
address = launch(args, 'repo', 'repo.yaml')
|
||||
problem = enrol_instance(args.remote, args.project, 'repo', vault)
|
||||
if problem:
|
||||
raise RuntimeError(problem)
|
||||
|
||||
def inside(*command):
|
||||
return lxc_exec(args.remote, args.project, 'repo', *command)
|
||||
|
||||
# Wait for cloud-init (status 2 is done with recoverable errors), then for the address of eth0.
|
||||
for _ in range(120):
|
||||
if inside('cloud-init', 'status', '--wait').returncode in (0, 2):
|
||||
break
|
||||
time.sleep(5)
|
||||
else:
|
||||
raise RuntimeError('the repository container did not boot')
|
||||
for _ in range(24):
|
||||
match = re.search(r' inet (\d+\.\d+\.\d+\.\d+)/',
|
||||
inside('ip', '-4', '-o', 'addr', 'show', 'dev', 'eth0').stdout)
|
||||
if match:
|
||||
break
|
||||
time.sleep(5)
|
||||
else:
|
||||
raise RuntimeError('the repository container has no address on eth0')
|
||||
address = match.group(1)
|
||||
lxc('config', 'device', 'override', f'{args.remote}:repo', 'eth0', f'ipv4.address={address}',
|
||||
project=args.project)
|
||||
|
||||
# The signing key, the publishing script and the empty indexes.
|
||||
generate = ('gpg', '--batch', '--pinentry-mode', 'loopback', '--passphrase', '', '--quick-generate-key',
|
||||
'Linux Manager test repository', 'default', 'default', 'never')
|
||||
@@ -94,6 +159,7 @@ def create(args, state, key):
|
||||
state.write_text(json.dumps({'remote': args.remote, 'project': args.project, 'networks': list(NETWORKS),
|
||||
'repository': f'http://{address}/', 'key': str(key)}, indent=2) + '\n',
|
||||
encoding='utf-8')
|
||||
state.chmod(0o600)
|
||||
print(f'project {args.project} is ready on {args.remote}: networks {", ".join(NETWORKS)}, '
|
||||
f'repository http://{address}/')
|
||||
print(f'state: {state}')
|
||||
@@ -125,6 +191,7 @@ def remove(args, state, key):
|
||||
if ok:
|
||||
state.unlink(missing_ok=True)
|
||||
key.unlink(missing_ok=True)
|
||||
config_path(f'vault-{args.project}.json').unlink(missing_ok=True)
|
||||
print(f'removed project {args.project} and its networks from {args.remote}')
|
||||
return ok
|
||||
|
||||
@@ -163,8 +230,9 @@ def uplink(args):
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument('action', choices=('create', 'remove', 'uplink'))
|
||||
parser.add_argument('operation', nargs='?', choices=('setup', 'remove'), help='after uplink: setup or remove')
|
||||
parser.add_argument('action', choices=('create', 'remove', 'vault', 'uplink'))
|
||||
parser.add_argument('operation', nargs='?', choices=('setup', 'create', 'unseal', 'remove'),
|
||||
help='after vault: create, unseal or remove; after uplink: setup or remove')
|
||||
parser.add_argument('--remote', default=os.environ.get('LXD_REMOTE'), help='the lxc remote (LXD_REMOTE)')
|
||||
parser.add_argument('--pool', default=os.environ.get('LXD_POOL'),
|
||||
help='the storage pool of the project, for create (LXD_POOL)')
|
||||
@@ -172,6 +240,9 @@ def main():
|
||||
help=f'the project (LXD_PROJECT, default {PROJECT})')
|
||||
parser.add_argument('--image', default=os.environ.get('LXD_IMAGE', 'ubuntu:26.04'),
|
||||
help='the image of the repository container (LXD_IMAGE, default ubuntu:26.04)')
|
||||
parser.add_argument('--vault-address', default=os.environ.get('LXD_VAULT_ADDRESS'),
|
||||
help="the listen address of the Vault's forward, one of the uplink's routes "
|
||||
'(LXD_VAULT_ADDRESS); without it one is allocated')
|
||||
parser.add_argument('--uplink', default=os.environ.get('LXD_UPLINK', 'uplink'),
|
||||
help='the physical uplink network of the OVN networks (LXD_UPLINK, default uplink)')
|
||||
parser.add_argument('--parent', default=os.environ.get('LXD_UPLINK_PARENT'),
|
||||
@@ -187,8 +258,9 @@ def main():
|
||||
args = parser.parse_args()
|
||||
if not args.remote:
|
||||
parser.error('--remote or LXD_REMOTE is required')
|
||||
if (args.action == 'uplink') != (args.operation is not None):
|
||||
parser.error('setup or remove follows uplink, and only uplink')
|
||||
operations = {'uplink': ('setup', 'remove'), 'vault': ('create', 'unseal', 'remove')}
|
||||
if args.operation not in operations.get(args.action, (None,)):
|
||||
parser.error('setup or remove follows uplink, create, unseal or remove follows vault, and nothing else')
|
||||
|
||||
if args.action == 'uplink':
|
||||
try:
|
||||
@@ -196,8 +268,26 @@ def main():
|
||||
except subprocess.CalledProcessError as error:
|
||||
sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}')
|
||||
return
|
||||
state = ROOT / 'tmp' / f'lxd-project-{args.project}.json'
|
||||
key = ROOT / 'tmp' / f'lxd-project-{args.project}.gpg'
|
||||
state = config_path(f'lxd-project-{args.project}.json')
|
||||
key = config_path(f'lxd-project-{args.project}.gpg')
|
||||
|
||||
if args.action == 'vault':
|
||||
try:
|
||||
if args.operation == 'create':
|
||||
vault_create(args)
|
||||
elif args.operation == 'unseal':
|
||||
current = vault_state(args.project)
|
||||
if current is None:
|
||||
sys.exit(f'project {args.project} has no Vault')
|
||||
vault_unseal(current)
|
||||
print(f'the Vault of {args.project} is unsealed')
|
||||
elif not vault_remove(args):
|
||||
sys.exit(1)
|
||||
except subprocess.CalledProcessError as error:
|
||||
sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}')
|
||||
except (RuntimeError, VaultError) as error:
|
||||
sys.exit(str(error))
|
||||
return
|
||||
|
||||
if args.action == 'remove':
|
||||
sys.exit(0 if remove(args, state, key) else 1)
|
||||
@@ -212,7 +302,7 @@ def main():
|
||||
except subprocess.CalledProcessError as error:
|
||||
sys.exit(f'{" ".join(error.cmd[:4])} failed: {error.stderr.strip()}\n'
|
||||
f'remove what was made with: {sys.argv[0]} remove --remote {args.remote} --project {args.project}')
|
||||
except RuntimeError as error:
|
||||
except (RuntimeError, VaultError) as error:
|
||||
sys.exit(f'{error}\nremove what was made with: {sys.argv[0]} remove --remote {args.remote} '
|
||||
f'--project {args.project}')
|
||||
|
||||
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Print the current TOTP code of a user of a Linux Manager VM: lm-dev-otp-code.py.
|
||||
|
||||
The code is the one of the key <vm>-<user> in the TOTP engine of the Vault of the project --project
|
||||
(LXD_PROJECT, lm-dev by default), for --user (admin by default) of the VM --vm (lm-dev), which
|
||||
lm-dev-otp-register.py or lm-dev-vm.py create enrolled.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
from lm_dev import PROJECT, VaultError, otp_code
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument('--project', default=os.environ.get('LXD_PROJECT', PROJECT),
|
||||
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
|
||||
parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)')
|
||||
parser.add_argument('--user', default='admin', help='the user (default admin)')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
print(otp_code(args.project, args.vm, args.user))
|
||||
except VaultError as error:
|
||||
sys.exit(f'no code: {error}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+10
-36
@@ -2,26 +2,17 @@
|
||||
"""Register a TOTP token for a user of a Linux Manager VM on an LXD remote: lm-dev-otp-register.py.
|
||||
|
||||
The token is enrolled for --user (admin by default) of the VM --vm (lm-dev) in the project --project
|
||||
(LXD_PROJECT, lm-dev by default) on the remote --remote (LXD_REMOTE), through lxc exec: inside the
|
||||
VM, as root, linuxmanager_users makes a new secret, and stores it once a code computed here from it
|
||||
verifies, replacing a token the user had. The secret, base32, is then written to the file
|
||||
--secret-file or OTP_FILE names, readable by its owner only, so otp.py code prints the user's codes.
|
||||
(LXD_PROJECT, lm-dev by default) on the remote --remote (LXD_REMOTE): the project's Vault generates
|
||||
the key in its TOTP engine as <vm>-<user> and hands it to the VM, where linuxmanager_users stores
|
||||
it with its current code, replacing a token the user had. The secret stays in the Vault and the
|
||||
VM; lm-dev-otp-code.py prints the user's codes.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from lm_dev import PROJECT, lxc_exec
|
||||
from otp import code_of
|
||||
|
||||
# Run in the VM as python3 -c CODE ARGUMENTS..., with the package's modules on the path.
|
||||
NEW = ("import json, sys; sys.path.insert(0, '/usr/lib/linux-manager'); import linuxmanager_users as users\n"
|
||||
"with users.session() as connection: print(json.dumps(users.otp_new(connection, sys.argv[1])))")
|
||||
ENROL = ("import sys; sys.path.insert(0, '/usr/lib/linux-manager'); import linuxmanager_users as users\n"
|
||||
"with users.session() as connection: users.otp_enrol(connection, sys.argv[1], sys.argv[2], sys.argv[3])")
|
||||
from lm_dev import PROJECT, enrol_otp, totp_key
|
||||
|
||||
|
||||
def main():
|
||||
@@ -31,31 +22,14 @@ def main():
|
||||
help=f'the project of the VM (LXD_PROJECT, default {PROJECT})')
|
||||
parser.add_argument('--vm', default='lm-dev', help='the name of the VM (default lm-dev)')
|
||||
parser.add_argument('--user', default='admin', help='the user to enrol (default admin)')
|
||||
parser.add_argument('--secret-file', default=os.environ.get('OTP_FILE'),
|
||||
help='the file the base32 secret is written to (OTP_FILE)')
|
||||
args = parser.parse_args()
|
||||
if not args.remote:
|
||||
parser.error('--remote or LXD_REMOTE is required')
|
||||
if not args.secret_file:
|
||||
parser.error('--secret-file or OTP_FILE is required')
|
||||
secret_file = pathlib.Path(args.secret_file)
|
||||
|
||||
def failure(result):
|
||||
return (result.stderr.strip().splitlines() or ['lxc exec failed'])[-1]
|
||||
|
||||
created = lxc_exec(args.remote, args.project, args.vm, 'python3', '-c', NEW, args.user)
|
||||
if created.returncode != 0:
|
||||
sys.exit(f'no new secret for {args.user}: {failure(created)}')
|
||||
secret = json.loads(created.stdout)['secret']
|
||||
enrolled = lxc_exec(args.remote, args.project, args.vm, 'python3', '-c', ENROL, args.user, secret, code_of(secret))
|
||||
if enrolled.returncode != 0:
|
||||
sys.exit(f'{args.user} was not enrolled: {failure(enrolled)}')
|
||||
|
||||
secret_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
secret_file.touch(mode=0o600)
|
||||
secret_file.chmod(0o600)
|
||||
secret_file.write_text(f'{secret}\n', encoding='utf-8')
|
||||
print(f'{args.user} of {args.remote}:{args.vm} has a new TOTP token; its secret is in {secret_file}')
|
||||
problem = enrol_otp(args.remote, args.project, args.vm, args.user)
|
||||
if problem:
|
||||
sys.exit(problem)
|
||||
print(f'{args.user} of {args.remote}:{args.vm} has a new TOTP token, the key {totp_key(args.vm, args.user)} '
|
||||
f'of the Vault of {args.project}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
+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)
|
||||
|
||||
|
||||
|
||||
+75
-47
@@ -3,34 +3,41 @@
|
||||
|
||||
create launches the VM --vm (lm-dev by default) on the remote --remote (LXD_REMOTE) in the project
|
||||
--project (LXD_PROJECT, lm-dev by default) with that project's default profile. In a test project
|
||||
made by lm-dev-lxd-project.py, which tmp/lxd-project-PROJECT.json describes, the VM gets the package
|
||||
made by lm-dev-lxd-project.py, which .lm-dev-config/lxd-project-PROJECT.json describes, the VM gets the package
|
||||
from that project's repository, as its apt source, so later dev builds reach it as updates;
|
||||
elsewhere it gets the newest out/linux-manager_*_all.deb. The administrator is admin with a
|
||||
generated password, set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env. The VM
|
||||
gets a configuration from tests/remote/configs/ (--config, core.json by default), whose @ETH0@ is
|
||||
the interface of its default route, @CIDR0@ its network and @PSK@ a generated key, written to
|
||||
tmp/vm-VM.env.
|
||||
elsewhere it gets --deb, or else the package built last, in out/ or out/dev/. The administrator is admin with a
|
||||
generated password, set as ADMIN_USERNAME and ADMIN_PASSWORD in the repository's .env, and a TOTP
|
||||
token, the key VM-admin of the project's Vault's TOTP engine, unless --no-otp is given;
|
||||
lm-dev-otp-code.py prints its codes. The VM gets a configuration from tests/remote/configs/
|
||||
(--config, core.json by default), whose @ETH0@ is the interface of its default route, @CIDR0@ its
|
||||
network and @PSK@ a generated key. The VM gets an AppRole of its own in the project's Vault
|
||||
(lm_dev.enrol_instance), with which it reads the debconf preseed with the admin's password and the
|
||||
configuration with its key, kept there as VM/preseed and VM/config, and creates its TOTP key; no
|
||||
secret is an argument or on standard input, so create needs a project with a Vault
|
||||
(lm-dev-lxd-project.py vault create). The admin's password is also kept there as VM/admin.
|
||||
|
||||
The VM's leased address is pinned on its NIC, and ports 7080 and 7081 of a listen address lead to
|
||||
the same ports of the VM, and port 2222 to its SSH port. In a test project the listen address is a
|
||||
network forward's on the project's WAN, allocated from its uplink's routes; elsewhere NAT proxy
|
||||
network forward's on the project's WAN, --forward-address (LXD_FORWARD_ADDRESS) or else one allocated
|
||||
from its uplink's routes; elsewhere NAT proxy
|
||||
devices listen on the host address --listen (LXD_LISTEN, by default the IPv4 address of the host of
|
||||
the remote's URL). remove deletes the VM, its forward and tmp/vm-VM.env; .env is left as it is.
|
||||
the remote's URL). remove deletes the VM, its forward and what the Vault keeps for it; .env is left
|
||||
as it is.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
from lm_dev import PROJECT, ROOT, TESTS, lxc_exec, set_dotenv
|
||||
from lm_dev import HANDOVER_DIR, PROJECT, ROOT, TESTS, VAULT_MOUNT, VaultError, config_path, enrol_instance, enrol_otp, \
|
||||
forget_instance, hand_over, host_address, lxc_exec, newest_deb, set_dotenv, store_secret, vault_state
|
||||
|
||||
# The listen port and the VM port of each forward or proxy: the Manager, the status web service and SSH.
|
||||
PORTS = ((7080, 7080), (7081, 7081), (2222, 22))
|
||||
@@ -50,28 +57,27 @@ def main():
|
||||
parser.add_argument('--listen', default=os.environ.get('LXD_LISTEN'),
|
||||
help="outside a test project, the LXD host address the proxies listen on (LXD_LISTEN, "
|
||||
"default the IPv4 address of the remote URL's host)")
|
||||
parser.add_argument('--forward-address', default=os.environ.get('LXD_FORWARD_ADDRESS'),
|
||||
help="with create in a test project, the forward's listen address, one of the uplink's routes "
|
||||
"(LXD_FORWARD_ADDRESS); without it one is allocated")
|
||||
parser.add_argument('--no-otp', action='store_true', help='with create, enrol no TOTP token for admin')
|
||||
parser.add_argument('--deb', help='outside a test project, the package to install (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')
|
||||
project_file = ROOT / 'tmp' / f'lxd-project-{args.project}.json'
|
||||
project_file = config_path(f'lxd-project-{args.project}.json')
|
||||
project = json.loads(project_file.read_text(encoding='utf-8')) if project_file.is_file() else None
|
||||
if project and project['remote'] != args.remote:
|
||||
sys.exit(f'{project_file} is of remote {project["remote"]}, not {args.remote}')
|
||||
if not project and args.action == 'create' and not args.listen:
|
||||
# The default listen address is the IPv4 address of the remote's host in its lxc URL.
|
||||
remotes = json.loads(subprocess.run(['lxc', 'remote', 'list', '--format', 'json'], capture_output=True,
|
||||
text=True, check=True).stdout)
|
||||
host = urllib.parse.urlsplit(remotes.get(args.remote, {}).get('Addr', '')).hostname
|
||||
try:
|
||||
args.listen = socket.getaddrinfo(host, None, socket.AF_INET)[0][4][0] if host else None
|
||||
except socket.gaierror:
|
||||
pass
|
||||
args.listen = host_address(args.remote)
|
||||
if not args.listen:
|
||||
parser.error(f'no IPv4 address of the host of remote {args.remote}; give --listen or LXD_LISTEN')
|
||||
where = f'{args.remote}:{args.vm} (project {args.project})'
|
||||
exists = subprocess.run(['lxc', 'info', f'{args.remote}:{args.vm}', '--project', args.project],
|
||||
capture_output=True).returncode == 0
|
||||
env = ROOT / 'tmp' / f'vm-{args.vm}.env'
|
||||
|
||||
def inside(*command, input=None):
|
||||
return lxc_exec(args.remote, args.project, args.vm, *command, input=input)
|
||||
@@ -95,7 +101,11 @@ def main():
|
||||
if project and (listen := forward_of_vm()):
|
||||
subprocess.run(['lxc', 'network', 'forward', 'delete', wan, listen, '--project', args.project], check=True)
|
||||
subprocess.run(['lxc', 'delete', '--force', f'{args.remote}:{args.vm}', '--project', args.project], check=True)
|
||||
env.unlink(missing_ok=True)
|
||||
if (vault := vault_state(args.project)) is not None:
|
||||
try:
|
||||
forget_instance(vault, args.vm)
|
||||
except VaultError as error:
|
||||
print(f'the Vault keeps what it had for {args.vm}: {error}', file=sys.stderr)
|
||||
print(f'removed {where}')
|
||||
return
|
||||
|
||||
@@ -104,16 +114,16 @@ def main():
|
||||
config = TESTS / 'configs' / args.config
|
||||
if not config.is_file():
|
||||
parser.error(f'no tests/remote/configs/{args.config}')
|
||||
debs = sorted((ROOT / 'out').glob('linux-manager_*_all.deb'))
|
||||
if not project and not debs:
|
||||
sys.exit('no out/linux-manager_*_all.deb; run ./build.sh first')
|
||||
source = f'the repository {project["repository"]}' if project else debs[-1].name
|
||||
deb = pathlib.Path(args.deb) if args.deb else newest_deb()
|
||||
if not project and (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')
|
||||
source = f'the repository {project["repository"]}' if project else str(deb)
|
||||
vault = vault_state(args.project)
|
||||
if vault is None:
|
||||
sys.exit(f'project {args.project} has no Vault, which the secrets reach the VM through; make it with '
|
||||
'lm-dev-lxd-project.py vault create')
|
||||
|
||||
password, psk = secrets.token_hex(16), secrets.token_hex(24)
|
||||
env.parent.mkdir(parents=True, exist_ok=True)
|
||||
env.touch(mode=0o600)
|
||||
env.chmod(0o600)
|
||||
env.write_text(f'PSK={psk}\n', encoding='utf-8')
|
||||
set_dotenv({'ADMIN_USERNAME': 'admin', 'ADMIN_PASSWORD': password})
|
||||
|
||||
reached = f'a forward on {project["networks"][0]}' if project else f'proxies on {args.listen}'
|
||||
@@ -130,6 +140,9 @@ def main():
|
||||
time.sleep(5)
|
||||
else:
|
||||
sys.exit(f'{args.vm} did not boot; remove it with remove')
|
||||
problem = enrol_instance(args.remote, args.project, args.vm, vault)
|
||||
if problem:
|
||||
sys.exit(f'{problem}; remove the VM with remove')
|
||||
for _ in range(24):
|
||||
route = re.search(r'\bdev (\S+)', inside('ip', '-4', '-o', 'route', 'show', 'default').stdout)
|
||||
address = route and re.search(r' inet (\S+) ',
|
||||
@@ -152,8 +165,10 @@ def main():
|
||||
subprocess.run(['lxc', 'config', 'device', 'override', f'{args.remote}:{args.vm}', device,
|
||||
f'ipv4.address={interface.ip}', '--project', args.project], check=True)
|
||||
if project:
|
||||
# An OVN network refuses NAT proxies; the forward's listen address is allocated from the uplink's routes.
|
||||
subprocess.run(['lxc', 'network', 'forward', 'create', wan, '--allocate=ipv4', f'user.vm={args.vm}',
|
||||
# An OVN network refuses NAT proxies; the forward's listen address is --forward-address, or one allocated
|
||||
# from the uplink's routes.
|
||||
address = [args.forward_address] if args.forward_address else ['--allocate=ipv4']
|
||||
subprocess.run(['lxc', 'network', 'forward', 'create', wan, *address, f'user.vm={args.vm}',
|
||||
'--project', args.project], check=True)
|
||||
args.listen = forward_of_vm()
|
||||
if not args.listen:
|
||||
@@ -180,12 +195,22 @@ def main():
|
||||
sys.exit(f'apt-get update failed in {args.vm}: {updated.stderr.strip()}')
|
||||
package = 'linux-manager'
|
||||
else:
|
||||
if not push(debs[-1], '/tmp/linux-manager.deb', '0644'):
|
||||
sys.exit(f'could not copy {debs[-1].name} into {args.vm}')
|
||||
if not push(deb, '/tmp/linux-manager.deb', '0644'):
|
||||
sys.exit(f'could not copy {deb} into {args.vm}')
|
||||
package = '/tmp/linux-manager.deb'
|
||||
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 {password}\n')
|
||||
if inside('debconf-set-selections', input=preseed).returncode != 0:
|
||||
try:
|
||||
store_secret(vault, f'{args.vm}/admin', {'password': password})
|
||||
except VaultError as error:
|
||||
sys.exit(f'the admin password cannot be kept in the Vault: {error}')
|
||||
if inside('install', '-d', '-m', '0700', HANDOVER_DIR).returncode != 0:
|
||||
sys.exit(f'{HANDOVER_DIR} cannot be made in {args.vm}')
|
||||
problem = hand_over(args.remote, args.project, args.vm, vault, 'preseed', preseed, f'{HANDOVER_DIR}/preseed', '0600')
|
||||
if problem:
|
||||
sys.exit(problem)
|
||||
if inside('sh', '-c', f'debconf-set-selections {HANDOVER_DIR}/preseed; status=$?; rm -f {HANDOVER_DIR}/preseed; '
|
||||
'exit $status').returncode != 0:
|
||||
sys.exit(f'debconf-set-selections failed in {args.vm}')
|
||||
result = inside('env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'install', '-y', package)
|
||||
log = ROOT / 'tmp' / f'vm-{args.vm}-install.log'
|
||||
@@ -194,22 +219,25 @@ def main():
|
||||
sys.exit(f'the package did not install; see {log}')
|
||||
|
||||
# Apply the configuration twice, as the server's certificates follow the first run.
|
||||
text = (config.read_text(encoding='utf-8').replace('@ETH0@', nic).replace('@CIDR0@', str(interface.network))
|
||||
.replace('@PSK@', psk))
|
||||
rendered = ROOT / 'tmp' / f'vm-{args.vm}.json'
|
||||
rendered.touch(mode=0o600)
|
||||
rendered.chmod(0o600)
|
||||
rendered.write_text(text, encoding='utf-8')
|
||||
pushed = push(rendered, '/etc/linux-manager/linux-manager.json', '0600')
|
||||
rendered.unlink()
|
||||
if not pushed:
|
||||
sys.exit(f'could not copy {args.config} into {args.vm}')
|
||||
text = config.read_text(encoding='utf-8').replace('@ETH0@', nic).replace('@CIDR0@', str(interface.network))
|
||||
problem = hand_over(args.remote, args.project, args.vm, vault, 'config', text.replace('@PSK@', psk),
|
||||
'/etc/linux-manager/linux-manager.json', '0600')
|
||||
if problem:
|
||||
sys.exit(f'could not give {args.vm} {args.config}: {problem}')
|
||||
for _ in range(2):
|
||||
if inside('systemctl', 'restart', 'linux-manager-setup').returncode != 0:
|
||||
if inside('linux-manager-config-edit', 'apply').returncode != 0:
|
||||
sys.exit(f'linux-manager-setup failed with {args.config}; see journalctl -u linux-manager-setup in the VM')
|
||||
|
||||
if not args.no_otp:
|
||||
problem = enrol_otp(args.remote, args.project, args.vm, 'admin')
|
||||
if problem:
|
||||
sys.exit(f'{args.vm} is up, but {problem}')
|
||||
|
||||
print(f'{args.vm} is up at {interface.ip} with {args.config}')
|
||||
print(f'administrator: admin password: {password} (also in {ROOT / ".env"})')
|
||||
print(f'administrator: admin, password in {ROOT / ".env"} (ADMIN_PASSWORD) and the Vault ({VAULT_MOUNT}/'
|
||||
f'{args.vm}/admin)')
|
||||
if not args.no_otp:
|
||||
print(f'administrator TOTP codes: bin/lm-dev-otp-code.py --project {args.project} --vm {args.vm}')
|
||||
print(f'manager: http://{args.listen}:7080/ status: http://{args.listen}:7081/ ssh: {args.listen} port 2222')
|
||||
print(f'shell: lxc exec {args.remote}:{args.vm} --project {args.project} -- su -l')
|
||||
print(f'remove: {sys.argv[0]} remove --remote {args.remote} --project {args.project} --vm {args.vm}')
|
||||
|
||||
+261
-1
@@ -1,13 +1,57 @@
|
||||
"""What the lm-dev scripts share: the repository's paths, lxc exec in an instance, and the .env of the repository."""
|
||||
"""What the lm-dev scripts share: the repository's paths, lxc in an instance, the .env of the repository, the
|
||||
persistent state in .lm-dev-config, the Vault of a test project, the AppRole of each instance in it, the hand-over of
|
||||
secrets to an instance through it, and the TOTP tokens of the users of a VM, kept in the Vault's TOTP engine.
|
||||
|
||||
A secret never reaches an instance as a command-line argument or on standard input. Each instance has an AppRole of
|
||||
its own (enrol_instance): its role ID and the helper lm-dev-vault (tests/remote/lm-dev-vault) are pushed into it, and
|
||||
its secret ID with a response-wrapping token, which the helper unwraps once into /etc/vault. The instance then logs in
|
||||
and reads what the Mac stored for it under kv/<instance>/, whole files that hold a secret (hand_over), and creates its
|
||||
own TOTP keys (enrol_otp).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
# The test data: scenarios, configurations, cloud-init files, the repository's script and the files copied in.
|
||||
TESTS = ROOT / 'tests' / 'remote'
|
||||
# The project of the manual tests, which lm-dev-lxd-project.py makes.
|
||||
PROJECT = 'lm-dev'
|
||||
# The state of the scripts that outlives a clean-up of tmp/: project and Vault states, keys and secrets; 0700.
|
||||
CONFIG = ROOT / '.lm-dev-config'
|
||||
|
||||
# The Vault: its port, the KV v2 and TOTP mounts, the lifetimes of a wrapping token and of an instance's token.
|
||||
VAULT_PORT = 8200
|
||||
VAULT_MOUNT = 'kv'
|
||||
TOTP_MOUNT = 'totp'
|
||||
WRAP_TTL = '120s'
|
||||
TOKEN_TTL = '5m'
|
||||
# In an instance: the helper, its directory of the Vault's URL and the AppRole's IDs, and the directory of files a
|
||||
# secret passes through.
|
||||
HELPER = '/usr/local/sbin/lm-dev-vault'
|
||||
ETC_VAULT = '/etc/vault'
|
||||
HANDOVER_DIR = '/run/lm-dev'
|
||||
|
||||
# Run in the VM as python3 -c CODE USER FILE: enrol the secret of the otpauth URI in FILE for USER with its current
|
||||
# code, then remove the file.
|
||||
OTP_ENROL = ("import os, sys, urllib.parse; sys.path.insert(0, '/usr/lib/linux-manager')\n"
|
||||
"import linuxmanager_users as users\n"
|
||||
"user, path = sys.argv[1:3]\n"
|
||||
"try:\n"
|
||||
" with open(path, encoding='utf-8') as handle: url = handle.read().strip()\n"
|
||||
"finally:\n"
|
||||
" os.unlink(path)\n"
|
||||
"secret = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query)['secret'][0]\n"
|
||||
"with users.session() as connection:\n"
|
||||
" users.otp_enrol(connection, user, secret, users.totp(secret).now())")
|
||||
|
||||
|
||||
def lxc_exec(remote, project, instance, *command, input=None):
|
||||
@@ -16,6 +60,12 @@ def lxc_exec(remote, project, instance, *command, input=None):
|
||||
input=input, capture_output=True, text=True)
|
||||
|
||||
|
||||
def lxc_push(remote, project, instance, source, path, mode):
|
||||
"""Copy the local file to the path in the instance with the mode; True when it was copied."""
|
||||
return subprocess.run(['lxc', 'file', 'push', str(source), f'{remote}:{instance}{path}', '--mode', mode,
|
||||
'--project', project], capture_output=True, text=True).returncode == 0
|
||||
|
||||
|
||||
def set_dotenv(values):
|
||||
"""Set the variables in the repository's .env, readable by its owner only, keeping its other lines."""
|
||||
dotenv = ROOT / '.env'
|
||||
@@ -25,3 +75,213 @@ def set_dotenv(values):
|
||||
dotenv.chmod(0o600)
|
||||
dotenv.write_text(''.join(f'{line}\n' for line in kept + [f'{key}={value}' for key, value in values.items()]),
|
||||
encoding='utf-8')
|
||||
|
||||
|
||||
def newest_deb():
|
||||
"""The package built last, release or dev build, by modification time among out/ and out/dev/; None without
|
||||
one."""
|
||||
debs = [*(ROOT / 'out').glob('linux-manager_*_all.deb'), *(ROOT / 'out' / 'dev').glob('linux-manager_*_all.deb')]
|
||||
return max(debs, key=lambda path: path.stat().st_mtime, default=None)
|
||||
|
||||
|
||||
def config_path(name):
|
||||
"""The path of a file in CONFIG, which is made with mode 0700 when it is missing."""
|
||||
CONFIG.mkdir(mode=0o700, exist_ok=True)
|
||||
CONFIG.chmod(0o700)
|
||||
return CONFIG / name
|
||||
|
||||
|
||||
def write_private(path, text):
|
||||
"""Write the text to the file, readable by its owner only."""
|
||||
path = pathlib.Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.touch(mode=0o600)
|
||||
path.chmod(0o600)
|
||||
path.write_text(text, encoding='utf-8')
|
||||
|
||||
|
||||
def host_address(remote):
|
||||
"""The IPv4 address of the host of the remote's lxc URL, or None."""
|
||||
remotes = json.loads(subprocess.run(['lxc', 'remote', 'list', '--format', 'json'], capture_output=True,
|
||||
text=True, check=True).stdout)
|
||||
host = urllib.parse.urlsplit(remotes.get(remote, {}).get('Addr', '')).hostname
|
||||
try:
|
||||
return socket.getaddrinfo(host, None, socket.AF_INET)[0][4][0] if host else None
|
||||
except socket.gaierror:
|
||||
return None
|
||||
|
||||
|
||||
class VaultError(Exception):
|
||||
"""A Vault request that failed."""
|
||||
|
||||
|
||||
def vault_call(url, method, path, body=None, token=None, wrap=None):
|
||||
"""Send the request to the Vault at url; the JSON answer, {} for none. wrap asks for a wrapped answer."""
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
if token:
|
||||
headers['X-Vault-Token'] = token
|
||||
if wrap:
|
||||
headers['X-Vault-Wrap-TTL'] = wrap
|
||||
request = urllib.request.Request(url.rstrip('/') + path, json.dumps(body).encode() if body is not None else None,
|
||||
headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
data = response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
raise VaultError(f'{method} {path}: {error.code} {error.read().decode(errors="replace").strip()}')
|
||||
except (urllib.error.URLError, OSError) as error:
|
||||
raise VaultError(f'{method} {path}: {url} cannot be reached: {error}')
|
||||
return json.loads(data) if data else {}
|
||||
|
||||
|
||||
def vault_state(project):
|
||||
"""The Vault state of the project: {url, internal_url, key, root_token}, None when it has no Vault."""
|
||||
path = config_path(f'vault-{project}.json')
|
||||
return json.loads(path.read_text(encoding='utf-8')) if path.is_file() else None
|
||||
|
||||
|
||||
def vault_initialise(project, url, internal_url):
|
||||
"""Initialise the Vault at url with one key share, unseal it, mount KV v2 and TOTP, enable AppRole and keep its
|
||||
state; the state."""
|
||||
for _ in range(60):
|
||||
try:
|
||||
if 'initialized' in vault_call(url, 'GET', '/v1/sys/init'):
|
||||
break
|
||||
except VaultError:
|
||||
pass
|
||||
time.sleep(2)
|
||||
else:
|
||||
raise VaultError(f'{url} does not answer')
|
||||
answer = vault_call(url, 'POST', '/v1/sys/init', {'secret_shares': 1, 'secret_threshold': 1})
|
||||
state = {'url': url, 'internal_url': internal_url, 'key': answer['keys_base64'][0],
|
||||
'root_token': answer['root_token']}
|
||||
write_private(config_path(f'vault-{project}.json'), json.dumps(state, indent=2) + '\n')
|
||||
vault_unseal(state)
|
||||
vault_call(url, 'POST', f'/v1/sys/mounts/{VAULT_MOUNT}', {'type': 'kv', 'options': {'version': '2'}},
|
||||
token=state['root_token'])
|
||||
vault_call(url, 'POST', f'/v1/sys/mounts/{TOTP_MOUNT}', {'type': 'totp'}, token=state['root_token'])
|
||||
vault_call(url, 'POST', '/v1/sys/auth/approle', {'type': 'approle'}, token=state['root_token'])
|
||||
return state
|
||||
|
||||
|
||||
def vault_unseal(state):
|
||||
"""Unseal the Vault of the state with its key; it is left as it is when it is unsealed."""
|
||||
answer = vault_call(state['url'], 'POST', '/v1/sys/unseal', {'key': state['key']})
|
||||
if answer.get('sealed'):
|
||||
raise VaultError(f'{state["url"]} is still sealed')
|
||||
|
||||
|
||||
def store_secret(state, path, values):
|
||||
"""Write the values, a dict of strings, as the KV v2 secret at path."""
|
||||
vault_call(state['url'], 'POST', f'/v1/{VAULT_MOUNT}/data/{path}', {'data': values}, token=state['root_token'])
|
||||
|
||||
|
||||
def enrol_instance(remote, project, instance, state):
|
||||
"""Give the instance an AppRole of its own, named after it, whose policy reads kv/<instance>/ and creates the TOTP
|
||||
keys <instance>-*, and set up /etc/vault in it; the problem, or None.
|
||||
|
||||
The instance receives the helper, the Vault's URL, the role ID and a wrapping token of a new secret ID, each as a
|
||||
file; the helper unwraps the token once, after checking that it wraps the role's secret-id request.
|
||||
"""
|
||||
policy = (f'path "{VAULT_MOUNT}/data/{instance}/*" {{ capabilities = ["read"] }}\n'
|
||||
f'path "{TOTP_MOUNT}/keys/{instance}-*" {{ capabilities = ["create", "update"] }}\n')
|
||||
role = f'/v1/auth/approle/role/{instance}'
|
||||
try:
|
||||
vault_call(state['url'], 'POST', f'/v1/sys/policies/acl/instance-{instance}', {'policy': policy},
|
||||
token=state['root_token'])
|
||||
vault_call(state['url'], 'POST', role, {'token_policies': [f'instance-{instance}'], 'token_type': 'batch',
|
||||
'token_ttl': TOKEN_TTL, 'secret_id_ttl': 0, 'secret_id_num_uses': 0},
|
||||
token=state['root_token'])
|
||||
role_id = vault_call(state['url'], 'GET', f'{role}/role-id', token=state['root_token'])['data']['role_id']
|
||||
token = vault_call(state['url'], 'POST', f'{role}/secret-id', {}, token=state['root_token'],
|
||||
wrap=WRAP_TTL)['wrap_info']['token']
|
||||
except (VaultError, KeyError) as error:
|
||||
return f'the AppRole of {instance} cannot be made: {error}'
|
||||
prepared = lxc_exec(remote, project, instance, 'install', '-d', '-m', '0700', ETC_VAULT)
|
||||
if prepared.returncode != 0:
|
||||
return f'{ETC_VAULT} cannot be made in {instance}: {prepared.stderr.strip()}'
|
||||
with tempfile.TemporaryDirectory(dir=ROOT / 'tmp' if (ROOT / 'tmp').is_dir() else None) as folder:
|
||||
local = pathlib.Path(folder)
|
||||
os.chmod(local, 0o700)
|
||||
write_private(local / 'url', state['internal_url'] + '\n')
|
||||
write_private(local / 'role-id', role_id + '\n')
|
||||
write_private(local / 'wrapped', token + '\n')
|
||||
files = ((TESTS / 'lm-dev-vault', HELPER, '0755'), (local / 'url', f'{ETC_VAULT}/url', '0644'),
|
||||
(local / 'role-id', f'{ETC_VAULT}/role-id', '0600'),
|
||||
(local / 'wrapped', f'{ETC_VAULT}/secret-id.wrapped', '0600'))
|
||||
for source, target, mode in files:
|
||||
if not lxc_push(remote, project, instance, source, target, mode):
|
||||
return f'{target} cannot be copied into {instance}'
|
||||
result = lxc_exec(remote, project, instance, HELPER, 'init', instance)
|
||||
if result.returncode != 0:
|
||||
return f'{instance} did not take its secret ID: {result.stderr.strip()}'
|
||||
return None
|
||||
|
||||
|
||||
def forget_instance(state, instance):
|
||||
"""Delete the instance's AppRole, its policy, its secrets under kv/<instance>/ and its TOTP keys."""
|
||||
url, token = state['url'], state['root_token']
|
||||
|
||||
def listed(path):
|
||||
try:
|
||||
return vault_call(url, 'LIST', path, token=token)['data']['keys']
|
||||
except VaultError:
|
||||
return []
|
||||
|
||||
vault_call(url, 'DELETE', f'/v1/auth/approle/role/{instance}', token=token)
|
||||
vault_call(url, 'DELETE', f'/v1/sys/policies/acl/instance-{instance}', token=token)
|
||||
for name in listed(f'/v1/{VAULT_MOUNT}/metadata/{instance}'):
|
||||
vault_call(url, 'DELETE', f'/v1/{VAULT_MOUNT}/metadata/{instance}/{name}', token=token)
|
||||
for key in listed(f'/v1/{TOTP_MOUNT}/keys'):
|
||||
if key.startswith(f'{instance}-'):
|
||||
vault_call(url, 'DELETE', f'/v1/{TOTP_MOUNT}/keys/{key}', token=token)
|
||||
|
||||
|
||||
def hand_over(remote, project, instance, state, name, content, destination, mode):
|
||||
"""Store the content, a file that holds a secret, as kv/<instance>/<name>, and have the instance write it to
|
||||
destination with the mode, reading it with its AppRole; the problem, or None."""
|
||||
try:
|
||||
store_secret(state, f'{instance}/{name}', {'content': content})
|
||||
except VaultError as error:
|
||||
return f'the secret {instance}/{name} cannot be stored: {error}'
|
||||
result = lxc_exec(remote, project, instance, HELPER, 'get', f'{instance}/{name}', 'content', destination, mode)
|
||||
if result.returncode != 0:
|
||||
return f'{instance}/{name} was not handed over to {instance}: {result.stderr.strip()}'
|
||||
return None
|
||||
|
||||
|
||||
def totp_key(instance, user):
|
||||
"""The name of the TOTP key of the user of the instance in the Vault's TOTP engine."""
|
||||
return f'{instance}-{user}'
|
||||
|
||||
|
||||
def enrol_otp(remote, project, instance, user):
|
||||
"""Enrol a new TOTP token for the user of the VM, replacing one the user had; the problem, or None.
|
||||
|
||||
The VM has the Vault generate the key with its AppRole and enrols its secret with its current code; the secret is
|
||||
held by the Vault and the VM only, and the codes are read from the Vault (otp_code).
|
||||
"""
|
||||
state = vault_state(project)
|
||||
if state is None:
|
||||
return f'project {project} has no Vault; make it with lm-dev-lxd-project.py vault create'
|
||||
key = totp_key(instance, user)
|
||||
try:
|
||||
vault_call(state['url'], 'DELETE', f'/v1/{TOTP_MOUNT}/keys/{key}', token=state['root_token'])
|
||||
except VaultError as error:
|
||||
return f'the TOTP key {key} cannot be replaced: {error}'
|
||||
target = f'{HANDOVER_DIR}/otp-url'
|
||||
for command in (('install', '-d', '-m', '0700', HANDOVER_DIR), (HELPER, 'totp', key, instance, user, target, '0600'),
|
||||
('python3', '-c', OTP_ENROL, user, target)):
|
||||
result = lxc_exec(remote, project, instance, *command)
|
||||
if result.returncode != 0:
|
||||
return f'{user} was not enrolled: {(result.stderr.strip().splitlines() or ["lxc exec failed"])[-1]}'
|
||||
return None
|
||||
|
||||
|
||||
def otp_code(project, instance, user):
|
||||
"""The current TOTP code of the user of the instance, from the project's Vault."""
|
||||
state = vault_state(project)
|
||||
if state is None:
|
||||
raise VaultError(f'project {project} has no Vault')
|
||||
return vault_call(state['url'], 'GET', f'/v1/{TOTP_MOUNT}/code/{totp_key(instance, user)}',
|
||||
token=state['root_token'])['data']['code']
|
||||
+31
-12
@@ -1,11 +1,14 @@
|
||||
#!/usr/bin/env python3
|
||||
"""An authenticator app on the command line: make a TOTP secret or print its current code: otp.py new|code.
|
||||
|
||||
The secret, base32, is kept in the file --secret-file or OTP_FILE names, readable by its owner
|
||||
only. new makes a new secret of 20 random bytes in that file, refusing to replace one without
|
||||
--force, and prints its otpauth URI, labelled with --account and --issuer when given. code prints
|
||||
the code of the secret now, or at the Unix time --at. The codes are RFC 6238's, with --algorithm
|
||||
(sha1 by default), --digits (6) and --period (30 seconds).
|
||||
The secret is kept in the file --secret-file or OTP_FILE names, readable by its owner only, as
|
||||
nothing but its base32 secret, or with --url as its otpauth URI, each without a line end, so the
|
||||
file is a value Vault's TOTP engine imports as it is (key=@FILE or url=@FILE). new makes a new
|
||||
secret of 20 random bytes in that file, refusing to replace one without --force, and prints its
|
||||
otpauth URI, labelled with --account and --issuer when given. code prints the code of the secret
|
||||
now, or at the Unix time --at, from either form of the file. The codes are RFC 6238's, with
|
||||
--algorithm (sha1 by default), --digits (6) and --period (30 seconds); a file holding an otpauth
|
||||
URI gives those of the URI instead.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -33,17 +36,30 @@ def code_of(secret, now=None, digits=6, period=30, algorithm='sha1'):
|
||||
return f'{value % 10 ** digits:0{digits}d}'
|
||||
|
||||
|
||||
def stored(text, digits, period, algorithm):
|
||||
"""The secret, digits, period and algorithm of the file's text: a base32 secret with the given settings, or an
|
||||
otpauth URI with its own, the given ones where it has none."""
|
||||
if not text.startswith('otpauth://'):
|
||||
return text, digits, period, algorithm
|
||||
query = {name: values[0] for name, values in urllib.parse.parse_qs(urllib.parse.urlsplit(text).query).items()}
|
||||
found = query.get('algorithm', algorithm).lower()
|
||||
if found not in ALGORITHMS:
|
||||
sys.exit(f'the otpauth URI has the unknown algorithm {found}')
|
||||
return query.get('secret', ''), int(query.get('digits', digits)), int(query.get('period', period)), found
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument('action', choices=('new', 'code'))
|
||||
parser.add_argument('--secret-file', default=os.environ.get('OTP_FILE'),
|
||||
help='the file of the base32 secret (OTP_FILE)')
|
||||
help='the file of the base32 secret or its otpauth URI (OTP_FILE)')
|
||||
parser.add_argument('--algorithm', choices=ALGORITHMS, default='sha1', help='the HMAC hash (default sha1)')
|
||||
parser.add_argument('--digits', type=int, default=6, help='the digits of a code (default 6)')
|
||||
parser.add_argument('--period', type=int, default=30, help='the seconds a code is valid (default 30)')
|
||||
parser.add_argument('--at', type=float, help='code: the Unix time of the code instead of now')
|
||||
parser.add_argument('--account', help='new: the account name in the otpauth URI')
|
||||
parser.add_argument('--issuer', help='new: the issuer in the otpauth URI')
|
||||
parser.add_argument('--url', action='store_true', help='new: store the otpauth URI instead of the secret alone')
|
||||
parser.add_argument('--force', action='store_true', help='new: replace an existing secret')
|
||||
args = parser.parse_args()
|
||||
if not args.secret_file:
|
||||
@@ -55,21 +71,24 @@ def main():
|
||||
if args.action == 'code':
|
||||
if not secret_file.is_file():
|
||||
sys.exit(f'no {secret_file}; make a secret with new')
|
||||
print(code_of(secret_file.read_text(encoding='utf-8').strip(), args.at, args.digits, args.period, args.algorithm))
|
||||
secret, digits, period, algorithm = stored(secret_file.read_text(encoding='utf-8').strip(), args.digits,
|
||||
args.period, args.algorithm)
|
||||
print(code_of(secret, args.at, digits, period, algorithm))
|
||||
return
|
||||
|
||||
if secret_file.exists() and not args.force:
|
||||
sys.exit(f'{secret_file} exists; give --force to replace its secret')
|
||||
secret = base64.b32encode(secrets.token_bytes(20)).decode()
|
||||
secret_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
secret_file.touch(mode=0o600)
|
||||
secret_file.chmod(0o600)
|
||||
secret_file.write_text(f'{secret}\n', encoding='utf-8')
|
||||
label = urllib.parse.quote(':'.join(part for part in (args.issuer, args.account) if part) or 'otp')
|
||||
query = {'secret': secret, 'algorithm': args.algorithm.upper(), 'digits': args.digits, 'period': args.period}
|
||||
if args.issuer:
|
||||
query['issuer'] = args.issuer
|
||||
print(f'otpauth://totp/{label}?{urllib.parse.urlencode(query)}')
|
||||
uri = f'otpauth://totp/{label}?{urllib.parse.urlencode(query)}'
|
||||
secret_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
secret_file.touch(mode=0o600)
|
||||
secret_file.chmod(0o600)
|
||||
secret_file.write_text(uri if args.url else secret, encoding='utf-8')
|
||||
print(uri)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
Reference in new issue
Block a user