Fix Fabric distro profile and runtime readback compatibility
parent
6a9918108e
commit
b11856d600
@ -0,0 +1,170 @@
|
||||
"""Run the actual rendered NetworkManager keyfile publication fragment."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from virsh_panel.fabric import _apply_script, parse_fabric_plan
|
||||
|
||||
|
||||
@pytest.fixture(params=["native_nftables", "firewalld_nft"])
|
||||
def rendered_nm_publication(request):
|
||||
plan = parse_fabric_plan({
|
||||
"fabric_id": "nm-dir-test", "region": "test",
|
||||
"overlay_cidr": "100.64.1.0/24", "revision": 1,
|
||||
"nodes": [
|
||||
{"host_id": "a", "overlay_ip": "100.64.1.1",
|
||||
"endpoint": "203.0.113.1:51820"},
|
||||
{"host_id": "b", "overlay_ip": "100.64.1.2",
|
||||
"endpoint": "203.0.113.2:51820"},
|
||||
],
|
||||
})
|
||||
keys = {
|
||||
"a": base64.b64encode(bytes([1]) * 32).decode(),
|
||||
"b": base64.b64encode(bytes([2]) * 32).decode(),
|
||||
}
|
||||
rendered = _apply_script(
|
||||
plan, plan.nodes[0], keys,
|
||||
deployment_mode="networkmanager_nmcli", firewall_mode=request.param,
|
||||
)
|
||||
transaction_start = rendered.index(
|
||||
"COMMITTED=no\nROLLBACK_FAILED=no\nJOURNAL_READY=no\n",
|
||||
)
|
||||
functions_start = rendered.index("snapshot_file() {", transaction_start)
|
||||
functions_end = rendered.index("restore_file() {", functions_start)
|
||||
helper_publish = rendered.index(
|
||||
'publish_desired_file "$_tmp_helper" "$HELPER" helper',
|
||||
)
|
||||
nm_start = rendered.index(
|
||||
'if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then\n'
|
||||
" if [ -e /etc/NetworkManager/system-connections ] || "
|
||||
"[ -L /etc/NetworkManager/system-connections ]; then",
|
||||
helper_publish,
|
||||
)
|
||||
nm_end = rendered.index(
|
||||
'\nif [ "$DEPLOYMENT_MODE" = ifupdown ]; then', nm_start,
|
||||
)
|
||||
return rendered[functions_start:functions_end], rendered[nm_start:nm_end]
|
||||
|
||||
|
||||
_STAT_TOOL = r'''import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
|
||||
assert sys.argv[1] == "-c"
|
||||
path = Path(sys.argv[3])
|
||||
value = path.stat()
|
||||
uid = os.environ["VC_DIR_UID"] if str(path) == os.environ["VC_DIR"] else "0"
|
||||
mode = format(stat.S_IMODE(value.st_mode), "o")
|
||||
fields = {"%u": uid, "%a": mode, "%u:%a": uid + ":" + mode}
|
||||
print(fields[sys.argv[2]])
|
||||
'''
|
||||
|
||||
|
||||
def _run_publication(rendered_nm_publication, tmp_path: Path, *,
|
||||
mode: int | None = 0o700, uid: int = 0,
|
||||
kind: str = "directory"):
|
||||
functions, publication = rendered_nm_publication
|
||||
manager = tmp_path / "NetworkManager"
|
||||
manager.mkdir()
|
||||
directory = manager / "system-connections"
|
||||
if kind == "symlink":
|
||||
other = tmp_path / "other"
|
||||
other.mkdir(mode=0o700)
|
||||
directory.symlink_to(other, target_is_directory=True)
|
||||
elif kind == "dangling-symlink":
|
||||
directory.symlink_to(tmp_path / "absent", target_is_directory=True)
|
||||
elif kind == "file":
|
||||
directory.write_text("external", encoding="utf-8")
|
||||
elif mode is not None:
|
||||
directory.mkdir()
|
||||
directory.chmod(mode)
|
||||
txn = tmp_path / "txn"
|
||||
txn.mkdir(mode=0o700)
|
||||
marker = txn / "nm_profile.absent"
|
||||
marker.touch(mode=0o600)
|
||||
key = tmp_path / "test.key"
|
||||
test_key = base64.b64encode(bytes([3]) * 32).decode() + "\n"
|
||||
key.write_text(test_key, encoding="utf-8")
|
||||
key.chmod(0o600)
|
||||
stat_tool = tmp_path / "stat-tool"
|
||||
stat_tool.write_text(
|
||||
"#!/bin/sh\nexec " + shlex.quote(sys.executable) + " -c "
|
||||
+ shlex.quote(_STAT_TOOL) + ' "$@"\n', encoding="utf-8",
|
||||
)
|
||||
stat_tool.chmod(0o700)
|
||||
publication = publication.replace(
|
||||
"/etc/NetworkManager/system-connections", str(directory),
|
||||
)
|
||||
profile = directory / "virt-cloud-wg-fabric0.nmconnection"
|
||||
result = subprocess.run(
|
||||
["/bin/sh", "-c", "\n".join((
|
||||
"set -eu", "umask 077", functions,
|
||||
'STAT="$VC_STAT"', "CMP=cmp", 'TXN="$VC_TXN"',
|
||||
'KEY="$VC_KEY"', 'NM_PROFILE="$VC_PROFILE"',
|
||||
"DEPLOYMENT_MODE=networkmanager_nmcli", publication,
|
||||
))],
|
||||
env={**os.environ, "VC_STAT": str(stat_tool), "VC_TXN": str(txn),
|
||||
"VC_KEY": str(key), "VC_PROFILE": str(profile),
|
||||
"VC_DIR": str(directory), "VC_DIR_UID": str(uid)},
|
||||
check=False, capture_output=True, text=True,
|
||||
)
|
||||
return result, directory, profile, txn, test_key
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", [0o700, 0o750, 0o755])
|
||||
def test_preserves_secure_existing_nm_directory_and_publishes_0600_profile(
|
||||
rendered_nm_publication, tmp_path: Path, mode):
|
||||
result, directory, profile, txn, key = _run_publication(
|
||||
rendered_nm_publication, tmp_path, mode=mode,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert directory.stat().st_mode & 0o7777 == mode
|
||||
assert profile.stat().st_mode & 0o7777 == 0o600
|
||||
content = profile.read_text(encoding="utf-8")
|
||||
assert "private-key=" + key in content
|
||||
assert "interface-name=wg-fabric0\n" in content
|
||||
assert "autoconnect=false\n" in content
|
||||
snapshot = txn / "nm_profile.desired"
|
||||
assert snapshot.read_bytes() == profile.read_bytes()
|
||||
assert snapshot.stat().st_mode & 0o7777 == 0o600
|
||||
|
||||
|
||||
def test_creates_new_nm_directory_as_root_private(
|
||||
rendered_nm_publication, tmp_path: Path):
|
||||
result, directory, profile, _, _ = _run_publication(
|
||||
rendered_nm_publication, tmp_path, mode=None,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert directory.stat().st_mode & 0o7777 == 0o700
|
||||
assert profile.stat().st_mode & 0o7777 == 0o600
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("mode", "uid", "kind"), [
|
||||
(0o775, 0, "directory"), (0o777, 0, "directory"),
|
||||
(0o757, 0, "directory"), (0o770, 0, "directory"),
|
||||
(0o1755, 0, "directory"), (0o700, 1000, "directory"),
|
||||
(0o700, 0, "symlink"), (0o700, 0, "dangling-symlink"),
|
||||
(0o700, 0, "file"),
|
||||
])
|
||||
def test_rejects_unsafe_nm_directory_without_publishing_or_chmod(
|
||||
rendered_nm_publication, tmp_path: Path, mode, uid, kind):
|
||||
result, directory, profile, txn, _ = _run_publication(
|
||||
rendered_nm_publication, tmp_path, mode=mode, uid=uid, kind=kind,
|
||||
)
|
||||
assert result.returncode == 71
|
||||
assert not profile.exists()
|
||||
assert not (txn / "nm_profile.desired").exists()
|
||||
if kind == "directory":
|
||||
assert directory.stat().st_mode & 0o7777 == mode
|
||||
elif kind in {"symlink", "dangling-symlink"}:
|
||||
assert directory.is_symlink()
|
||||
else:
|
||||
assert directory.read_text(encoding="utf-8") == "external"
|
||||
@ -0,0 +1,246 @@
|
||||
"""Run real rendered Fabric route and boot-nft readback programs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from virsh_panel.fabric import (
|
||||
FIREWALL_MODE_FIREWALLD,
|
||||
_BOOT_HELPER,
|
||||
_FABRIC_NFT_VALIDATION_SH,
|
||||
_apply_script,
|
||||
_nft_rules_text,
|
||||
_observe_script,
|
||||
parse_fabric_plan,
|
||||
)
|
||||
|
||||
|
||||
def _plan():
|
||||
return parse_fabric_plan({
|
||||
"fabric_id": "route-test", "region": "hk",
|
||||
"overlay_cidr": "100.64.1.0/24", "revision": 1,
|
||||
"nodes": [
|
||||
{"host_id": "a", "overlay_ip": "100.64.1.1",
|
||||
"endpoint": "203.0.113.1:51820"},
|
||||
{"host_id": "b", "overlay_ip": "100.64.1.2",
|
||||
"endpoint": "203.0.113.2:51820"},
|
||||
],
|
||||
})
|
||||
|
||||
|
||||
def _render_apply(mode="ifupdown"):
|
||||
plan = _plan()
|
||||
keys = {node.host_id: base64.b64encode(bytes([index]) * 32).decode()
|
||||
for index, node in enumerate(plan.nodes, 1)}
|
||||
return _apply_script(plan, plan.nodes[0], keys, deployment_mode=mode,
|
||||
firewall_mode=FIREWALL_MODE_FIREWALLD)
|
||||
|
||||
|
||||
def _assignment(script, name, start=0):
|
||||
begin = script.index(name + "=$(printf", start)
|
||||
end = script.index("')", begin) + 2
|
||||
return script[begin:end]
|
||||
|
||||
|
||||
def _route_program(variant):
|
||||
if variant.startswith("apply_"):
|
||||
script = _render_apply()
|
||||
# Embedded helper is intentionally not the program under test.
|
||||
start = script.index("MANAGED_ROUTES=")
|
||||
name = {"apply_preflight": "route_conflict",
|
||||
"apply_final": "final_route_extra",
|
||||
"apply_seen": "final_route_seen"}[variant]
|
||||
if variant == "apply_seen":
|
||||
start = script.index("for final_expected_route in", start)
|
||||
else:
|
||||
script = _BOOT_HELPER
|
||||
start = 0
|
||||
name = {"boot_preflight": "route_conflict",
|
||||
"boot_final": "route_extra",
|
||||
"boot_seen": "route_seen"}[variant]
|
||||
if variant == "boot_preflight":
|
||||
start = script.index("if ! fabric_routes=")
|
||||
if variant == "boot_seen":
|
||||
start = script.index("for expected_route in")
|
||||
return _assignment(script, name, start) + f'\nprintf "%s" "${name}"\n'
|
||||
|
||||
|
||||
def _run_route(variant, routes, vpc_file="/dev/null"):
|
||||
result = subprocess.run(
|
||||
["/bin/sh", "-eu", "-c", _route_program(variant)],
|
||||
capture_output=True, text=True, check=False,
|
||||
env={"IFACE": "wg-fabric0", "overlay": "100.64.1.1",
|
||||
"allowed_routes": "100.64.1.2/32",
|
||||
"MANAGED_ROUTES": "100.64.1.2/32", "OLD_MANAGED_ROUTES": "",
|
||||
"fabric_routes": routes, "actual_fabric_routes": routes,
|
||||
"final_fabric_routes": routes, "VPC_ROUTE_FILE": str(vpc_file),
|
||||
"expected_route": "100.64.1.2/32",
|
||||
"final_expected_route": "100.64.1.2/32"},
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
return result.stdout
|
||||
|
||||
|
||||
EXTRA_VARIANTS = ("apply_preflight", "apply_final",
|
||||
"boot_preflight", "boot_final")
|
||||
OWN_ROUTE = ("local 100.64.1.1 dev wg-fabric0 table local proto kernel "
|
||||
"scope host src 100.64.1.1\n")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant", EXTRA_VARIANTS)
|
||||
@pytest.mark.parametrize("prefix", ["100.64.1.2", "100.64.1.2/32"])
|
||||
def test_real_host_route_and_owned_local_route_are_equivalent(variant, prefix):
|
||||
routes = f"{prefix} dev wg-fabric0 scope link\n" + OWN_ROUTE
|
||||
assert _run_route(variant, routes) == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant", ["apply_seen", "boot_seen"])
|
||||
@pytest.mark.parametrize("prefix", ["100.64.1.2", "100.64.1.2/32"])
|
||||
def test_real_host_route_positive_readback(variant, prefix):
|
||||
assert _run_route(variant, f"{prefix} dev wg-fabric0 scope link\n") == "1"
|
||||
assert _run_route(variant, OWN_ROUTE) == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant", EXTRA_VARIANTS)
|
||||
@pytest.mark.parametrize("foreign", [
|
||||
"100.64.1.2/24 dev wg-fabric0 scope link",
|
||||
"100.64.1.3 dev wg-fabric0 scope link",
|
||||
"100.64.1.02 dev wg-fabric0 scope link",
|
||||
"100.64.1.256 dev wg-fabric0 scope link",
|
||||
"100.64.1.2 dev br0 scope link",
|
||||
"100.64.1.2 dev wg-fabric0 table 100 scope link",
|
||||
"local 100.64.1.1 dev br0 table local proto kernel scope host",
|
||||
"local 100.64.1.1 dev wg-fabric0 table 100 proto kernel scope host",
|
||||
"default dev wg-fabric0",
|
||||
"100.64.1.2 dev wg-fabric0\n100.64.1.2/32 dev wg-fabric0",
|
||||
])
|
||||
def test_host_canonicalization_keeps_foreign_and_duplicate_routes_blocked(
|
||||
variant, foreign):
|
||||
assert _run_route(variant, foreign + "\n") in ("foreign", "extra")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant", EXTRA_VARIANTS)
|
||||
def test_vpc_host_route_requires_exact_owned_tuple_and_protocol(tmp_path, variant):
|
||||
vpc_file = tmp_path / "routes"
|
||||
vpc_file.write_text(
|
||||
"10.1.0.3/32|wg-fabric0|100|100.64.1.2|100\n", encoding="utf-8")
|
||||
normal = "100.64.1.2 dev wg-fabric0 scope link\n" + OWN_ROUTE
|
||||
vpc = ("10.1.0.3 via 100.64.1.2 dev wg-fabric0 table 100 "
|
||||
"proto 186 metric 100 scope link\n")
|
||||
assert _run_route(variant, normal + vpc, vpc_file) == ""
|
||||
for changed in (vpc.replace("proto 186", "proto static"),
|
||||
vpc.replace("metric 100", "metric 101"),
|
||||
vpc.replace("table 100", "table 101"),
|
||||
vpc.replace("via 100.64.1.2", "via 100.64.1.3")):
|
||||
assert _run_route(variant, normal + changed, vpc_file) in ("foreign", "extra")
|
||||
|
||||
|
||||
def _boot_nft_program():
|
||||
start = _BOOT_HELPER.index("validate_nft_table() {")
|
||||
end = _BOOT_HELPER.index("\nfabric_acl_ready()", start)
|
||||
return (_FABRIC_NFT_VALIDATION_SH + "\n" + _BOOT_HELPER[start:end]
|
||||
+ '\ntable=$(cat)\nvalidate_nft_table "$table"\n')
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indent", ["spaces", "tabs"])
|
||||
@pytest.mark.parametrize("named_output", [False, True])
|
||||
def test_boot_nft_owner_readback_ignores_only_serialization_indentation(
|
||||
indent, named_output):
|
||||
plan = _plan()
|
||||
rules = _nft_rules_text(plan.digest)
|
||||
if indent == "tabs":
|
||||
rules = re.sub(r"^( )+", lambda match: "\t" * (len(match[0]) // 4),
|
||||
rules, flags=re.MULTILINE)
|
||||
if named_output:
|
||||
rules = rules.replace("hook output priority -100", "hook output priority dstnat")
|
||||
result = subprocess.run(["/bin/sh", "-eu", "-c", _boot_nft_program()],
|
||||
input=rules, capture_output=True, text=True,
|
||||
env={"EXPECTED_DIGEST": plan.digest}, check=False)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize("drift", ["digest", "verdict", "extra_rule", "extra_chain"])
|
||||
def test_boot_nft_whitespace_fix_keeps_complete_ownership_validation(drift):
|
||||
plan = _plan()
|
||||
rules = _nft_rules_text(plan.digest)
|
||||
if drift == "digest":
|
||||
rules = rules.replace(plan.digest, "a" * 64)
|
||||
elif drift == "verdict":
|
||||
rules = rules.replace("counter drop", "counter accept", 1)
|
||||
elif drift == "extra_rule":
|
||||
rules = rules.replace(" chain output {", (
|
||||
' chain output {\n oifname "wg-fabric0" accept'))
|
||||
else:
|
||||
rules = rules.replace(" chain output {", " chain foreign {\n }\n chain output {")
|
||||
result = subprocess.run(["/bin/sh", "-eu", "-c", _boot_nft_program()],
|
||||
input=rules, capture_output=True, text=True,
|
||||
env={"EXPECTED_DIGEST": plan.digest}, check=False)
|
||||
assert result.returncode != 0
|
||||
|
||||
|
||||
def test_observe_route_awk_runs_begin_outside_record_action(tmp_path):
|
||||
script = _observe_script(("100.64.1.2",), "100.64.1.1",
|
||||
endpoint_ips=("203.0.113.2",),
|
||||
deployment_mode="ifupdown",
|
||||
firewall_mode=FIREWALL_MODE_FIREWALLD)
|
||||
start = script.index('awk -v vpc_file="${VPC_ROUTE_FILE:-}"')
|
||||
program = script[start:script.index("\n }'", start) + len("\n }'")]
|
||||
program = program.replace('"${VPC_ROUTE_FILE:-}"', '"$VPC_ROUTE_FILE"')
|
||||
vpc_file = tmp_path / "routes"
|
||||
vpc_file.write_text("10.1.0.3/32|wg-fabric0|100|100.64.1.2|100\n",
|
||||
encoding="utf-8")
|
||||
routes = ("100.64.1.2 dev wg-fabric0 scope link\n" + OWN_ROUTE
|
||||
+ "10.1.0.3 via 100.64.1.2 dev wg-fabric0 table 100 proto 186 metric 100\n")
|
||||
result = subprocess.run(["/bin/sh", "-eu", "-c", program], input=routes,
|
||||
capture_output=True, text=True, check=False,
|
||||
env={"VPC_ROUTE_FILE": str(vpc_file), "VPC_STATE_STATUS": "valid"})
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert result.stdout.splitlines() == [
|
||||
"__VC_FABRIC_ROUTE__=100.64.1.2/32|main|wg-fabric0",
|
||||
"__VC_FABRIC_ROUTE__=100.64.1.1/32|local|wg-fabric0",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["ifupdown", "networkmanager_nmcli"])
|
||||
def test_apply_and_boot_replace_the_same_route_priority_as_selected_manager(mode):
|
||||
script = _render_apply(mode)
|
||||
generated = re.findall(r"^\$IP route replace [^\n]+$", script, re.MULTILINE)
|
||||
assert len(generated) == 1
|
||||
# Inspect the rendered keyfile rather than invent a second expected metric.
|
||||
keyfile_metric = re.search(r"^route-metric=([0-9]+)$", script, re.MULTILINE)[1]
|
||||
metric = keyfile_metric if mode == "networkmanager_nmcli" else "0"
|
||||
assert (" metric " + keyfile_metric in generated[0]) == (
|
||||
mode == "networkmanager_nmcli")
|
||||
|
||||
boot_start = _BOOT_HELPER.index(
|
||||
"while IFS='|' read -r kind a b c d; do\n"
|
||||
" [ \"$kind\" = route ] || continue\n",
|
||||
_BOOT_HELPER.index('"$WG" set "$IFACE" listen-port "$listen"'),
|
||||
)
|
||||
boot_end = _BOOT_HELPER.index("done < \"$CONF\"", boot_start) + len('done < "$CONF"')
|
||||
# Run actual shell commands with an argv-only IP double. This test has no
|
||||
# route mutation privileges; it verifies both sources address the same
|
||||
# kernel route key, independently of optional host integration tests.
|
||||
capture = 'mock_ip() { printf "%s\\n" "$*"; }; IP=mock_ip\n'
|
||||
apply = subprocess.run(["/bin/sh", "-eu", "-c", capture + generated[0]],
|
||||
capture_output=True, text=True,
|
||||
env={"IFACE": "wg-fabric0"}, check=False)
|
||||
boot = subprocess.run(
|
||||
["/bin/sh", "-eu", "-c", capture + _BOOT_HELPER[boot_start:boot_end]],
|
||||
input="route|100.64.1.2/32\n", capture_output=True, text=True,
|
||||
env={"IFACE": "wg-fabric0", "DEPLOYMENT_MODE": mode, "CONF": "/dev/stdin"},
|
||||
check=False,
|
||||
)
|
||||
assert apply.returncode == boot.returncode == 0
|
||||
assert apply.stdout == boot.stdout
|
||||
args = apply.stdout.split()
|
||||
replacement_metric = args[args.index("metric") + 1] if "metric" in args else "0"
|
||||
assert replacement_metric == metric
|
||||
# The documented kernel key includes priority. Existing NM priority50 or
|
||||
# ifupdown priority0 gets replaced, not duplicated by a different key.
|
||||
route_keys = {("100.64.1.2/32", "main", metric)}
|
||||
route_keys.add((args[2], args[4], replacement_metric))
|
||||
assert len(route_keys) == 1
|
||||
Loading…
Reference in New Issue