You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/engine/tests/test_wg_allowed_readback.py

243 lines
11 KiB
Python

"""Execute production WireGuard readback shell against native CLI rows."""
from __future__ import annotations
from dataclasses import replace
import os
import re
import subprocess
import pytest
import virsh_panel.fabric as fabric
import virsh_panel.vpc_dataplane as dataplane
import virsh_panel.shell_contracts as contracts
from test_vpc_nft_dataplane import _plan, WG_KEY, FABRIC_DIGEST
OTHER_KEY = 'AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI='
PREFIXES = ('100.64.0.2/32', '10.44.0.11/32', '10.44.0.99/32')
def run_shell(body, rows, *, helper=True, command_status=0, mutation_file=None):
env = dict(os.environ, VC_WG_ROWS=rows, VC_WG_COMMAND_STATUS=str(command_status),
VC_WG_KEY=WG_KEY, VC_WG_MUTATIONS=str(mutation_file or '/dev/null'))
harness = '''set -eu
mock_wg() {
if [ "$1" = show ] && [ "$2" = wg-fabric0 ]; then
case "$3" in
allowed-ips) printf '%s\\n' "$VC_WG_ROWS"; return "$VC_WG_COMMAND_STATUS" ;;
peers) printf '%s\\n' "$VC_WG_KEY" ;;
endpoints) printf '%s\\t203.0.113.2:51820\\n' "$VC_WG_KEY" ;;
latest-handshakes) printf '%s\\t123\\n' "$VC_WG_KEY" ;;
*) return 99 ;;
esac
elif [ "$1" = set ] && [ "$2" = wg-fabric0 ]; then
printf '%s\\n' "$*" >> "$VC_WG_MUTATIONS"
else
return 99
fi
}
WG=mock_wg
WG_IFACE=wg-fabric0
IFACE=wg-fabric0
'''
if helper:
harness += contracts.WG_ALLOWED_IPS_SH + '\n'
# Overlay selection is the real shared loader code, not a test stand-in.
harness += 'VPC_FABRIC_NETWORK=100.64.0.0/10\n'
for name in ('vpc_state_ipv4', 'vpc_state_allowed', 'vpc_state_private',
'vpc_state_in_fabric', 'vpc_state_overlay_from_allowed'):
match = re.search(r'(?ms)^' + name + r'\(\) (?:\{.*?^\}|\(.*?^\))',
fabric._VPC_STATE_LOADER)
if match:
harness += match.group(0) + '\n'
return subprocess.run(['/bin/sh', '-c', harness + body], env=env,
text=True, capture_output=True, check=False)
def rows_for(prefixes, separator):
return (OTHER_KEY + '\t100.64.0.3/32 10.44.0.12/32\n'
+ WG_KEY + '\t' + separator.join(prefixes) + '\n')
@pytest.mark.parametrize('separator', [' ', '\t', ',', ', '])
@pytest.mark.parametrize('prefixes', [PREFIXES, PREFIXES[::-1],
(PREFIXES[1], PREFIXES[0], PREFIXES[2])])
def test_reader_retains_every_prefix_and_selects_exact_peer(separator, prefixes):
result = run_shell('vc_wg_allowed_for_peer "$IFACE" "$VC_WG_KEY"',
rows_for(prefixes, separator))
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == ','.join(prefixes)
@pytest.mark.parametrize('bad', [
'', '(none)', '100.64.0.2/32,', ',100.64.0.2/32',
'100.64.0.2/32,,10.44.0.11/32',
'100.64.0.2/32, ,10.44.0.11/32',
'100.64.0.2/32 100.64.0.2/32', '100.64.0.2/32 invalid',
'100.64.0.2/32 0.0.0.0/33', '100.64.0.2/32 10.44.0.1/24', '100.64.0.2/32 10.44.0.256/32',
'100.64.0.2/32 10.44.00.1/32', '100.64.0.2/32 ::1/128',
])
def test_reader_rejects_bad_complete_rows_without_partial_output(bad):
result = run_shell('vc_wg_allowed_for_peer "$IFACE" "$VC_WG_KEY"',
WG_KEY + '\t' + bad)
assert result.returncode != 0
assert result.stdout == ''
@pytest.mark.parametrize('scenario', ['missing', 'duplicate', 'command_failed'])
def test_reader_rejects_ambiguous_or_failed_inventory(scenario):
rows = rows_for(PREFIXES, ' ')
if scenario == 'missing':
rows = rows.replace(WG_KEY, OTHER_KEY)
if scenario == 'duplicate':
rows += WG_KEY + '\t' + ' '.join(PREFIXES) + '\n'
result = run_shell('vc_wg_allowed_for_peer "$IFACE" "$VC_WG_KEY"', rows,
command_status=1 if scenario == 'command_failed' else 0)
assert result.returncode != 0
assert result.stdout == ''
@pytest.mark.parametrize('operation', ['apply', 'remove', 'vpc_observe', 'fabric_observe'])
@pytest.mark.parametrize('separator', [' ', '\t', ',', ', '])
@pytest.mark.parametrize('reverse', [False, True])
@pytest.mark.parametrize('overlay', ['100.64.0.2/32', '100.99.106.2/32'])
def test_generated_production_paths_read_complete_unordered_peer_rows(
tmp_path, operation, separator, reverse, overlay):
plan = _plan()
plan = replace(plan, peers=(replace(
plan.peers[0], overlay_ip=overlay.removesuffix('/32'),
tenant_allowed_ips=('10.44.0.11/32', '10.44.0.99/32')),))
expected_prefixes = (overlay, *PREFIXES[1:])
prefixes = expected_prefixes[::-1] if reverse else expected_prefixes
rows = rows_for(prefixes, separator)
mutations = tmp_path / 'mutations'
body = ''
if operation == 'apply':
script = dataplane.render_apply_script(plan)
start = script.index(
'expected_fabric_peer_keys=',
script.index('VC_VPC_APPLY_PHASE=wireguard'))
end = script.index('# The shared Fabric quarantine table', start)
body = script[start:end]
elif operation == 'remove':
script = dataplane.render_remove_script(replace(
plan, members=tuple(m for m in plan.members if m.host_id != plan.host_id)))
start = script.index('expected_fabric_peer_keys=')
end = script.index('vc_vpc_fabric_nft_live_ready || exit 74', start)
body = script[start:end]
elif operation == 'vpc_observe':
script = dataplane.render_observe_script(plan)
start = script.index('vpc_state_loaded=no')
end = script.index('expected_fabric_peer_keys=', start)
body = script[start:end]
else:
script = fabric._observe_script((), expected_digest=FABRIC_DIGEST)
start = script.index(' $WG show "$IFACE" peers 2>/dev/null | while')
end = script.index(' $IP -N -o route show', start)
body = script[start:end]
# Execute the actual generated statement/loop, faking kernel-facing wg.
if operation in ('apply', 'remove'):
body = ('vpc_state_allowed_for_peer() { printf "10.44.0.11/32,10.44.0.99/32"; }\n'
+ body)
elif operation == 'vpc_observe':
body = ('STATE="$VC_WG_MUTATIONS.state"\n'
'vpc_state_load() { VPC_STATE_STATUS=owned; }\n'
'vpc_state_allowed_for_peer() { printf "10.44.0.11/32,10.44.0.99/32"; }\n'
+ body)
result = run_shell(body, rows, mutation_file=mutations)
assert result.returncode == 0, result.stderr
if operation in ('apply', 'remove'):
assert mutations.read_text() == (
'set wg-fabric0 peer ' + WG_KEY + ' allowed-ips '
+ ','.join(expected_prefixes) + '\n')
elif operation == 'vpc_observe':
assert '__VC_VPC_WG_STATE__=host-b|owned\n' in result.stdout
assert '__VC_VPC_WG_ALLOWED__=host-b|' + WG_KEY + '|' + ','.join(sorted(expected_prefixes)) in result.stdout
else:
assert '__VC_FABRIC_PEER__=' + WG_KEY + '|203.0.113.2:51820|' + ','.join(prefixes) in result.stdout
def test_reader_subshell_preserves_caller_variables_and_ifs():
body = '''vc_wg_rows=retained
before_ifs=$IFS
vc_wg_allowed_for_peer "$IFACE" "$VC_WG_KEY" >/dev/null
[ "$vc_wg_rows" = retained ]
[ "$IFS" = "$before_ifs" ]
'''
result = run_shell(body, rows_for(PREFIXES, ' '))
assert result.returncode == 0, result.stderr
@pytest.mark.parametrize('operation', ['apply', 'remove', 'vpc_observe', 'fabric_observe'])
@pytest.mark.parametrize('scenario', ['malformed', 'duplicate', 'command_failed'])
def test_generated_paths_never_accept_partial_or_failed_readback(
tmp_path, operation, scenario):
plan = _plan()
rows = rows_for(PREFIXES, ' ')
if scenario == 'malformed':
rows = rows.rstrip() + ' unexpected\n'
elif scenario == 'duplicate':
rows += WG_KEY + '\t' + ' '.join(PREFIXES) + '\n'
mutations = tmp_path / 'mutations'
if operation == 'apply':
script = dataplane.render_apply_script(plan)
start = script.index(
'expected_fabric_peer_keys=',
script.index('VC_VPC_APPLY_PHASE=wireguard'))
end = script.index('# The shared Fabric quarantine table', start)
elif operation == 'remove':
script = dataplane.render_remove_script(replace(
plan, members=tuple(m for m in plan.members if m.host_id != plan.host_id)))
start = script.index('expected_fabric_peer_keys=')
end = script.index('vc_vpc_fabric_nft_live_ready || exit 74', start)
elif operation == 'vpc_observe':
script = dataplane.render_observe_script(plan)
start = script.index('vpc_state_loaded=no')
end = script.index('expected_fabric_peer_keys=', start)
else:
script = fabric._observe_script((), expected_digest=FABRIC_DIGEST)
start = script.index(' $WG show "$IFACE" peers 2>/dev/null | while')
end = script.index(' $IP -N -o route show', start)
body = ('STATE="$VC_WG_MUTATIONS.state"\n'
'vpc_state_load() { VPC_STATE_STATUS=owned; }\n'
'vpc_state_allowed_for_peer() { printf "10.44.0.11/32,10.44.0.99/32"; }\n'
+ script[start:end])
result = run_shell(body, rows, mutation_file=mutations,
command_status=1 if scenario == 'command_failed' else 0)
assert not mutations.exists()
if operation in ('apply', 'remove'):
assert result.returncode == 74
elif operation == 'vpc_observe':
assert result.returncode == 0, result.stderr
assert '__VC_VPC_WG_STATE__=host-b|missing\n' in result.stdout
assert '|owned' not in result.stdout
else:
assert result.returncode == 0, result.stderr
assert '__VC_FABRIC_PEER__=' + WG_KEY + '|203.0.113.2:51820|invalid\n' in result.stdout
@pytest.mark.parametrize('operation', ['apply', 'remove', 'vpc_observe', 'fabric_observe'])
def test_production_scripts_embed_reader_and_are_posix_shell_syntax(operation):
plan = _plan()
if operation == 'apply':
script = dataplane.render_apply_script(plan)
elif operation == 'remove':
script = dataplane.render_remove_script(replace(
plan, members=tuple(m for m in plan.members if m.host_id != plan.host_id)))
elif operation == 'vpc_observe':
script = dataplane.render_observe_script(plan)
else:
script = fabric._observe_script((), expected_digest=FABRIC_DIGEST)
assert contracts.WG_ALLOWED_IPS_SH in script
result = subprocess.run(['/bin/sh', '-n'], input=script, text=True,
capture_output=True, check=False)
assert result.returncode == 0, result.stderr
@pytest.mark.parametrize('prefix', ['10.44.0.0/24', '192.168.0.0/16',
'0.0.0.0/0', '203.0.113.8/29'])
def test_reader_preserves_canonical_cidrs_for_callers_to_authorize(prefix):
result = run_shell('vc_wg_allowed_for_peer "$IFACE" "$VC_WG_KEY"',
rows_for(('100.99.106.2/32', prefix), ' '))
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == '100.99.106.2/32,' + prefix