diff --git a/cli/administration/inventory/mesh/__main__.py b/cli/administration/inventory/mesh/__main__.py index fef0042882..c5c9a28c8c 100755 --- a/cli/administration/inventory/mesh/__main__.py +++ b/cli/administration/inventory/mesh/__main__.py @@ -19,6 +19,7 @@ from .inventory import groups_of, specs_of from .plan import plan_mesh from .write import ( DEFAULT_APPLICATION_ID, + existing_addresses, existing_public_keys, prune_foreign_meshes, write_mesh, @@ -157,6 +158,12 @@ def main(argv: list[str] | None = None) -> int: held, controller=(args.controller if spec.name == args.controller_mesh else None), endpoints=parse_endpoints(args.endpoint), + addresses=existing_addresses( + host_vars_dir, + all_hosts, + spec.name, + args.application_id, + ), ) keyed_here.update({member.host: member.public_key for member in mesh.members}) written = write_mesh( diff --git a/cli/administration/inventory/mesh/plan.py b/cli/administration/inventory/mesh/plan.py index e606268840..88d67ec6f4 100644 --- a/cli/administration/inventory/mesh/plan.py +++ b/cli/administration/inventory/mesh/plan.py @@ -68,6 +68,60 @@ def _address(subnet: str, offset: int) -> str: return str(address) +def _offset_of(subnet: str, address: str) -> int | None: + """The spoke offset ``address`` occupies in ``subnet``, or None. + + None covers everything that must not be reused: an unparseable value, an + address from a subnet the spec no longer declares, and the hub's own + offset, which belongs to whichever host holds the hub group today. + """ + network = ipaddress.ip_network(subnet, strict=True) + try: + candidate = ipaddress.ip_address(address) + except ValueError: + return None + if candidate not in network: + return None + offset = int(candidate) - int(network.network_address) + return offset if offset > SPOKE_OFFSET else None + + +def _spoke_offsets( + subnet: str, spokes: list[str], stored: dict[str, str] +) -> dict[str, int]: + """Keep every spoke on the address it already holds. + + Deriving the offset from a spoke's position renumbers every later member + the moment a host that sorts earlier joins. `wg syncconf` carries keys and + peers onto a live interface but never its address, so a renumbered member + keeps answering on the old address while the rest of the mesh and the + inventory have already moved to the new one. + + Args: + subnet: the mesh subnet offsets are taken in. + spokes: every spoke of the mesh, in the order they were resolved. + stored: hostname to the address it already holds on this mesh. + """ + taken = {HUB_OFFSET} + offsets: dict[str, int] = {} + for host in spokes: + offset = _offset_of(subnet, stored.get(host, "")) + if offset is None or offset in taken: + continue + offsets[host] = offset + taken.add(offset) + + cursor = SPOKE_OFFSET + 1 + for host in spokes: + if host in offsets: + continue + while cursor in taken: + cursor += 1 + offsets[host] = cursor + taken.add(cursor) + return offsets + + def plan_mesh( spec: MeshSpec, groups: dict[str, list[str]], @@ -76,6 +130,7 @@ def plan_mesh( rotate: bool = False, controller: str | None = None, endpoints: dict[str, str] | None = None, + addresses: dict[str, str] | None = None, ) -> Mesh: """Resolve ``spec`` into a mesh whose members are addressed and keyed. @@ -94,10 +149,13 @@ def plan_mesh( endpoints: hostname to the underlay address its peers dial. A host left out keeps its hostname, which is what every peer already resolves and routes to wherever inventory names are real names. + addresses: hostname to the mesh address it already holds. Kept across + a rotation too: rotation replaces identities, not addresses. """ held = {} if rotate else dict(existing_public_keys or {}) underlay = dict(endpoints or {}) hub, spokes = members_of(spec, groups, controller) + offsets = _spoke_offsets(spec.subnet, spokes, dict(addresses or {})) def member(host: str, offset: int, is_hub: bool) -> MeshMember: address = _address(spec.subnet, offset) @@ -122,8 +180,5 @@ def plan_mesh( ) members = [member(hub, HUB_OFFSET, True)] - members.extend( - member(host, SPOKE_OFFSET + index, False) - for index, host in enumerate(spokes, start=1) - ) + members.extend(member(host, offsets[host], False) for host in spokes) return Mesh(spec=spec, members=tuple(members)) diff --git a/cli/administration/inventory/mesh/write.py b/cli/administration/inventory/mesh/write.py index 7a0a134ba5..f119f354bf 100644 --- a/cli/administration/inventory/mesh/write.py +++ b/cli/administration/inventory/mesh/write.py @@ -122,6 +122,33 @@ def existing_public_keys( return found +def existing_addresses( + host_vars_dir: Path, + hosts: list[str], + mesh_name: str, + application_id: str = DEFAULT_APPLICATION_ID, +) -> dict[str, str]: + """The addresses already issued to ``hosts`` on ``mesh_name``. + + Per mesh rather than per host, unlike the key: a member holds one address + on each plane it belongs to, so only its own entry on this mesh counts. An + entry naming another host is a leftover of the mirror and is ignored for + the same reason it is ignored when reading keys. + """ + found: dict[str, str] = {} + for host in hosts: + path = host_vars_path(host_vars_dir, host) + if not path.exists(): + continue + entry = _mesh_entry(load_document(path), mesh_name, application_id) + if not isinstance(entry, dict) or entry.get("host") != host: + continue + address = entry.get("address") + if isinstance(address, str) and address.strip(): + found[host] = address.strip() + return found + + def prune_foreign_meshes( host_vars_dir: Path, hosts: list[str], diff --git a/docs/requirements/037-svc-net-wireguard-swarm.md b/docs/requirements/037-svc-net-wireguard-swarm.md index ee262a257a..b861eb4150 100644 --- a/docs/requirements/037-svc-net-wireguard-swarm.md +++ b/docs/requirements/037-svc-net-wireguard-swarm.md @@ -82,6 +82,7 @@ Swarm mode only, and there only when the run's `vpn` axis asks for it. The role - [x] The tool takes the host set as input and writes every affected inventory in one invocation, so no deploy can observe a mesh in which one host has been rotated and another has not. - [x] Each host's inventory carries one WireGuard private key identifying it on every mesh it belongs to, and the public key of every peer it is configured to reach; no host's inventory contains another host's private key. - [x] Every generated private key is vault-encrypted in the inventory, matching the treatment of every other platform credential. +- [x] A member keeps the mesh address it already holds when the cluster grows or the keys rotate: `wg syncconf` carries keys and peers onto a live interface and never its address, so a renumbered member would answer on the old address while the inventory had already moved to the new one. - [x] Re-running the tool without a rotation request leaves an existing mesh byte-identical, so a deploy that changes nothing changes nothing. - [ ] The SWARM VPN is established between `swarm-mgr-01`, both workers and the controller, and the DATA VPN between `swarm-mgr-01`, `nfs-server` and `swarm-bkp-01`, with membership derived from the `default.env` topology rather than restated. - [ ] A worker reaches the NFS export over the mesh, routed by the Manager, and the same mount fails when the Manager's tunnel is down. diff --git a/tests/unit/python/cli/administration/inventory/mesh/test_cli.py b/tests/unit/python/cli/administration/inventory/mesh/test_cli.py index 7912139e59..404247b98f 100644 --- a/tests/unit/python/cli/administration/inventory/mesh/test_cli.py +++ b/tests/unit/python/cli/administration/inventory/mesh/test_cli.py @@ -8,6 +8,7 @@ import unittest from pathlib import Path from cli.administration.inventory.mesh.__main__ import main +from utils.cache.yaml import load_yaml_any from .test_write import ( BACKUP_INVENTORY, @@ -18,6 +19,7 @@ from .test_write import ( ) CONTROLLER = "deploy-controller" +SWARM_HOSTS = ("swarm-mgr-01", "swarm-wrk-01", "swarm-wrk-02") class TestMeshCli(unittest.TestCase): @@ -126,6 +128,45 @@ class TestMeshCli(unittest.TestCase): self.assertEqual(1, len(set(own))) self.assertIn(own[0], spoke_peers) + def _address(self, host: str, mesh_name: str) -> str: + document = load_yaml_any(str(self.host_vars / f"{host}.yml")) + return document["applications"]["svc-net-wireguard"]["meshes"][mesh_name][ + "address" + ] + + def test_growing_the_cluster_leaves_every_member_on_its_address(self): + """A node added later must not renumber the nodes already up. + + `wg syncconf` never moves a live interface's address, so a renumbered + member answers on the old one while the inventory has moved to the + new one -- and the next pass cannot reach it. + """ + self.assertEqual(main(self._argv()), 0) + before = {host: self._address(host, "swarm") for host in SWARM_HOSTS} + + (self.host_vars / "alpha-wrk-00.yml").write_text("---\n", encoding="utf-8") + self.cluster.write_text( + CLUSTER_INVENTORY.replace( + " swarm-wrk-01: {}", + " alpha-wrk-00: {}\n swarm-wrk-01: {}", + ), + encoding="utf-8", + ) + self.assertEqual(main(self._argv()), 0) + + for host, address in before.items(): + with self.subTest(host=host): + self.assertEqual(self._address(host, "swarm"), address) + self.assertNotIn(self._address("alpha-wrk-00", "swarm"), set(before.values())) + + def test_a_rotation_leaves_every_member_on_its_address(self): + self.assertEqual(main(self._argv()), 0) + before = {host: self._address(host, "swarm") for host in SWARM_HOSTS} + self.assertEqual(main(self._argv("--rotate")), 0) + for host, address in before.items(): + with self.subTest(host=host): + self.assertEqual(self._address(host, "swarm"), address) + def test_a_rerun_is_a_no_op(self): self.assertEqual(main(self._argv()), 0) before = {host: self._text(host) for host in HOSTS} diff --git a/tests/unit/python/cli/administration/inventory/mesh/test_plan.py b/tests/unit/python/cli/administration/inventory/mesh/test_plan.py index d2c715b338..8ba3f23f02 100644 --- a/tests/unit/python/cli/administration/inventory/mesh/test_plan.py +++ b/tests/unit/python/cli/administration/inventory/mesh/test_plan.py @@ -96,6 +96,61 @@ class TestAddressing(unittest.TestCase): self.assertEqual(swarm & data, set()) +class TestAddressPersistence(unittest.TestCase): + """A member keeps the address it already answers on. + + `wg syncconf` carries keys and peers onto a live interface and never its + address, so a member whose address is recomputed keeps answering on the + old one while the rest of the mesh and the inventory have moved to the + new one. The deploy then loses exactly the hosts that were already up. + """ + + def _held(self, spec, groups) -> dict[str, str]: + return {m.host: m.address for m in plan_mesh(spec, groups).members} + + def test_a_member_that_sorts_first_does_not_renumber_the_others(self): + before = self._held(SWARM, GROUPS) + grown = dict(GROUPS) + grown["svc-swarm-node"] = ["alpha-wrk-00", *GROUPS["svc-swarm-node"]] + + mesh = plan_mesh(SWARM, grown, addresses=before) + after = {m.host: m.address for m in mesh.members} + for host, address in before.items(): + with self.subTest(host=host): + self.assertEqual(after[host], address) + self.assertNotIn(after["alpha-wrk-00"], set(before.values())) + + def test_rotation_replaces_identities_and_keeps_addresses(self): + before = self._held(SWARM, GROUPS) + mesh = plan_mesh(SWARM, GROUPS, rotate=True, addresses=before) + self.assertEqual({m.host: m.address for m in mesh.members}, before) + + def test_a_stored_address_outside_the_subnet_is_replaced(self): + mesh = plan_mesh(SWARM, GROUPS, addresses={"swarm-wrk-01": "10.99.0.50"}) + address = mesh.member("swarm-wrk-01").address + self.assertTrue(address.startswith("10.100.0.")) + + def test_a_spoke_never_adopts_the_hub_address(self): + """The mirror leaves every host holding the hub's entry. + + A spoke that reused what it found there would bring up an interface + claiming the hub's address and blackhole the mesh it belongs to. + """ + hub = plan_mesh(SWARM, GROUPS).hub.address + mesh = plan_mesh(SWARM, GROUPS, addresses={"swarm-wrk-01": hub}) + self.assertNotEqual(mesh.member("swarm-wrk-01").address, hub) + + def test_two_members_claiming_one_address_do_not_both_keep_it(self): + taken = plan_mesh(SWARM, GROUPS).member("swarm-wrk-01").address + mesh = plan_mesh( + SWARM, + GROUPS, + addresses={"swarm-wrk-01": taken, "swarm-wrk-02": taken}, + ) + addresses = [m.address for m in mesh.members] + self.assertEqual(len(addresses), len(set(addresses))) + + class TestPeering(unittest.TestCase): def test_the_hub_peers_with_every_spoke(self): mesh = plan_mesh(SWARM, GROUPS) diff --git a/tests/unit/python/cli/administration/inventory/mesh/test_write.py b/tests/unit/python/cli/administration/inventory/mesh/test_write.py index 6f56e8a1c6..b332ea8ffe 100644 --- a/tests/unit/python/cli/administration/inventory/mesh/test_write.py +++ b/tests/unit/python/cli/administration/inventory/mesh/test_write.py @@ -14,6 +14,7 @@ from pathlib import Path from cli.administration.inventory.mesh.inventory import groups_of, specs_of from cli.administration.inventory.mesh.plan import plan_mesh from cli.administration.inventory.mesh.write import ( + existing_addresses, existing_public_keys, private_key_name, prune_foreign_meshes, @@ -97,6 +98,16 @@ class MeshOnDisk(unittest.TestCase): .get("meshes", {}) ) + def _entry(self, host: str, mesh_name: str) -> dict: + """The mesh block as the role will read it back off disk.""" + document = load_yaml_any(str(self.host_vars / f"{host}.yml")) + return ( + document.get("applications", {}) + .get("svc-net-wireguard", {}) + .get("meshes", {}) + .get(mesh_name, {}) + ) + def _write_all(self, *, rotate: bool = False) -> None: for spec in self.specs: mesh = plan_mesh( @@ -178,15 +189,22 @@ class TestMeshShapeOnDisk(MeshOnDisk, unittest.TestCase): with no route to the NFS server, and the mount fails while every tunnel still reports a healthy handshake -- so the symptom points at storage rather than at routing. + + Asserted against the serialized entry, not against a second plan: the + role reads the file, so a writer that stored the mesh subnet in place + of the routed range would satisfy a re-planned comparison. """ self._write_all() for spec in self.specs: mesh = plan_mesh(spec, self.groups) + self.assertEqual(spec.routed_range, "10.100.0.0/16") for spoke in mesh.spokes: with self.subTest(mesh=spec.name, spoke=spoke.host): - peers = mesh.peers_of(spoke.host) - self.assertEqual([p.host for p in peers], [mesh.hub.host]) - self.assertEqual(spec.routed_range, "10.100.0.0/16") + peers = self._entry(spoke.host, spec.name)["peers"] + self.assertEqual([p["host"] for p in peers], [mesh.hub.host]) + self.assertEqual( + [p["allowed_ips"] for p in peers], [spec.routed_range] + ) def test_the_hub_pins_each_spoke_to_a_single_address(self): """The inverse of the spoke rule. @@ -194,12 +212,44 @@ class TestMeshShapeOnDisk(MeshOnDisk, unittest.TestCase): A hub that routed the pool to one spoke would blackhole every other member behind it. """ + self._write_all() + for spec in self.specs: + hub = plan_mesh(spec, self.groups).hub.host + for peer in self._entry(hub, spec.name)["peers"]: + with self.subTest(mesh=spec.name, peer=peer["host"]): + self.assertFalse(peer["is_hub"]) + self.assertEqual(peer["allowed_ips"], peer["address"] + "/32") + + +class TestStoredAddresses(MeshOnDisk, unittest.TestCase): + """What the planner is allowed to treat as an address already in use.""" + + def test_every_written_address_is_read_back(self): self._write_all() for spec in self.specs: mesh = plan_mesh(spec, self.groups) - for peer in mesh.peers_of(mesh.hub.host): - with self.subTest(mesh=spec.name, peer=peer.host): - self.assertFalse(peer.is_hub) + with self.subTest(mesh=spec.name): + self.assertEqual( + existing_addresses(self.host_vars, list(HOSTS), spec.name), + {m.host: m.address for m in mesh.members}, + ) + + def test_a_host_with_no_entry_is_absent_rather_than_empty(self): + self._write_all() + stored = existing_addresses(self.host_vars, list(HOSTS), "data") + self.assertNotIn("swarm-wrk-01", stored) + + def test_a_mirrored_entry_is_not_read_as_the_hosts_own_address(self): + """The mirror hands every node the hub's entry. + + Reusing what it finds there would put the hub's address on a worker, + which is the same failure the key reader already guards against. + """ + self._write_all() + hub_text = self._text("swarm-mgr-01") + (self.host_vars / "swarm-wrk-01.yml").write_text(hub_text, encoding="utf-8") + stored = existing_addresses(self.host_vars, list(HOSTS), "swarm") + self.assertNotIn("swarm-wrk-01", stored) class TestIdempotence(MeshOnDisk, unittest.TestCase):