|
| 1 | +"""Cross-world federation end-to-end test: real CoreDNS + peer DNS stub. |
| 2 | +
|
| 3 | +Run with: |
| 4 | + pytest tests/integration/test_e2e_federation.py --run-e2e |
| 5 | +
|
| 6 | +Requires: |
| 7 | + - Docker daemon accessible on the host |
| 8 | + - The 'core' and 'platform' Docker networks must not already exist |
| 9 | +
|
| 10 | +What gets validated: |
| 11 | + - GatewayPortalHandler runs without error in PEERED mode |
| 12 | + - The peer's TLD forwarding stub is appended to the CoreDNS Corefile |
| 13 | + - CoreDNS reloads the new config (SIGHUP sent) without crashing |
| 14 | + - Runtime state records the peer federation output |
| 15 | +
|
| 16 | +What is intentionally NOT tested here (requires dedicated infrastructure): |
| 17 | + - nftables routing (needs a gateway container provisioned by a separate phase) |
| 18 | + - Trust anchor cert (tested via unit tests in test_gateway_portal.py) |
| 19 | + - Actual cross-world DNS resolution (needs a real peer world running) |
| 20 | +""" |
| 21 | + |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +import asyncio |
| 25 | +import time |
| 26 | +from pathlib import Path |
| 27 | + |
| 28 | +import pytest |
| 29 | + |
| 30 | +from netengine.core.state import RuntimeState |
| 31 | +from netengine.handlers.context import PhaseContext |
| 32 | +from netengine.handlers.docker_handler import DockerHandler |
| 33 | +from netengine.handlers.dns import DNSHandler |
| 34 | +from netengine.handlers.gateway_portal_handler import GatewayPortalHandler |
| 35 | +from netengine.handlers.substrate import SubstrateHandler |
| 36 | +from netengine.logging import get_logger |
| 37 | +from netengine.spec.loader import load_spec |
| 38 | +from netengine.spec.models import CrossWorldConfig, CrossWorldPeer, GatewayPortal, RealInternetConfig |
| 39 | +from netengine.spec.types import GatewayCrossWorldMode, GatewayRealInternetMode |
| 40 | + |
| 41 | +EXAMPLES_DIR = Path(__file__).parent.parent.parent / "examples" |
| 42 | + |
| 43 | + |
| 44 | +# ───────────────────────────────────────────── |
| 45 | +# Helpers (shared with test_e2e_fullstack) |
| 46 | +# ───────────────────────────────────────────── |
| 47 | + |
| 48 | + |
| 49 | +def _docker_client(): |
| 50 | + try: |
| 51 | + import docker |
| 52 | + |
| 53 | + client = docker.from_env() |
| 54 | + client.ping() |
| 55 | + return client |
| 56 | + except Exception: |
| 57 | + return None |
| 58 | + |
| 59 | + |
| 60 | +def _cleanup_docker(client) -> None: |
| 61 | + for c in client.containers.list(all=True): |
| 62 | + if c.name.startswith(("netengine_", "netengines_")): |
| 63 | + try: |
| 64 | + c.stop(timeout=5) |
| 65 | + c.remove(force=True) |
| 66 | + except Exception: |
| 67 | + pass |
| 68 | + for n in client.networks.list(): |
| 69 | + if n.name in ("core", "platform"): |
| 70 | + try: |
| 71 | + n.remove() |
| 72 | + except Exception: |
| 73 | + pass |
| 74 | + |
| 75 | + |
| 76 | +def _read_corefile_from_container(client, container_name: str) -> str: |
| 77 | + """Return the current contents of /etc/coredns/Corefile inside the container.""" |
| 78 | + container = client.containers.get(container_name) |
| 79 | + exit_code, output = container.exec_run(["cat", "/etc/coredns/Corefile"], demux=False) |
| 80 | + return (output or b"").decode("utf-8", errors="replace") |
| 81 | + |
| 82 | + |
| 83 | +# ───────────────────────────────────────────── |
| 84 | +# Federation test |
| 85 | +# ───────────────────────────────────────────── |
| 86 | + |
| 87 | + |
| 88 | +@pytest.mark.e2e |
| 89 | +@pytest.mark.asyncio |
| 90 | +async def test_e2e_cross_world_federation(tmp_path, monkeypatch): |
| 91 | + """PEERED mode: verify DNS stub for peer TLD is written to CoreDNS Corefile. |
| 92 | +
|
| 93 | + The test boots phases 0-2 (substrate + CoreDNS) then runs |
| 94 | + GatewayPortalHandler with a PEERED cross-world spec that references a |
| 95 | + simulated peer world at 192.0.2.1 (TEST-NET — not routable). |
| 96 | +
|
| 97 | + After the handler runs, the CoreDNS Corefile must contain a forwarding |
| 98 | + stub for `world-b.internal` pointing at the peer's DNS resolver. |
| 99 | + """ |
| 100 | + monkeypatch.setenv("NETENGINE_ZONE_DIR", str(tmp_path / "coredns")) |
| 101 | + |
| 102 | + client = _docker_client() |
| 103 | + if client is None: |
| 104 | + pytest.skip("Docker daemon not available") |
| 105 | + |
| 106 | + spec = load_spec(EXAMPLES_DIR / "minimal.yaml") |
| 107 | + docker_handler = DockerHandler() |
| 108 | + state = RuntimeState() |
| 109 | + ctx = PhaseContext( |
| 110 | + spec=spec, |
| 111 | + runtime_state=state, |
| 112 | + logger=get_logger("e2e.federation"), |
| 113 | + docker_client=docker_handler, |
| 114 | + mock_mode=False, |
| 115 | + zone_dir=str(tmp_path / "coredns"), |
| 116 | + ) |
| 117 | + |
| 118 | + try: |
| 119 | + # ── Bootstrap phases 0-2 ──────────────────────────────────────────── |
| 120 | + await SubstrateHandler().execute(ctx) |
| 121 | + await DNSHandler().execute(ctx) |
| 122 | + |
| 123 | + coredns = client.containers.get("netengine_coredns") |
| 124 | + assert coredns.status == "running" |
| 125 | + |
| 126 | + # ── Build gateway portal spec with PEERED cross-world mode ────────── |
| 127 | + peer = CrossWorldPeer( |
| 128 | + name="world-b", |
| 129 | + endpoint="192.0.2.1", # TEST-NET — safe, not routable |
| 130 | + mode=GatewayCrossWorldMode.PEERED, |
| 131 | + trust_anchor_cert=None, # Skip trust anchor install |
| 132 | + ) |
| 133 | + portal_spec = GatewayPortal( |
| 134 | + enabled=True, |
| 135 | + real_internet=RealInternetConfig( |
| 136 | + mode=GatewayRealInternetMode.CUSTOM # CUSTOM is a no-op; avoids gateway container |
| 137 | + ), |
| 138 | + cross_world=CrossWorldConfig( |
| 139 | + mode=GatewayCrossWorldMode.PEERED, |
| 140 | + peers=[peer], |
| 141 | + ), |
| 142 | + ) |
| 143 | + |
| 144 | + # Patch the spec's gateway_portal for this test |
| 145 | + original_portal = ctx.spec.gateway_portal |
| 146 | + object.__setattr__(ctx.spec, "gateway_portal", portal_spec) |
| 147 | + |
| 148 | + try: |
| 149 | + # ── Run gateway portal handler ─────────────────────────────────── |
| 150 | + await GatewayPortalHandler().execute(ctx) |
| 151 | + finally: |
| 152 | + object.__setattr__(ctx.spec, "gateway_portal", original_portal) |
| 153 | + |
| 154 | + # ── Assertions ─────────────────────────────────────────────────────── |
| 155 | + gp_output = ctx.runtime_state.gateway_portal_output |
| 156 | + assert gp_output is not None |
| 157 | + assert gp_output["enabled"] is True |
| 158 | + assert gp_output["cross_world_mode"] == GatewayCrossWorldMode.PEERED.value |
| 159 | + |
| 160 | + peers_out = gp_output.get("federation", {}).get("peers", []) |
| 161 | + assert len(peers_out) == 1, f"Expected 1 peer in output, got: {peers_out}" |
| 162 | + |
| 163 | + peer_out = peers_out[0] |
| 164 | + assert peer_out["name"] == "world-b" |
| 165 | + assert peer_out["dns_forwarding_configured"] is True, ( |
| 166 | + "DNS stub for world-b.internal was not written to CoreDNS Corefile. " |
| 167 | + f"Peer output: {peer_out}" |
| 168 | + ) |
| 169 | + |
| 170 | + # ── Verify Corefile content ─────────────────────────────────────────── |
| 171 | + # Brief pause for SIGHUP to propagate |
| 172 | + await asyncio.sleep(1) |
| 173 | + |
| 174 | + corefile = _read_corefile_from_container(client, "netengine_coredns") |
| 175 | + assert "world-b.internal" in corefile, ( |
| 176 | + f"Expected 'world-b.internal' stub in CoreDNS Corefile but not found.\n" |
| 177 | + f"Corefile:\n{corefile}" |
| 178 | + ) |
| 179 | + assert "192.0.2.1" in corefile, ( |
| 180 | + f"Expected peer IP '192.0.2.1' in CoreDNS Corefile.\nCorefile:\n{corefile}" |
| 181 | + ) |
| 182 | + |
| 183 | + # CoreDNS should still be running (SIGHUP did not crash it) |
| 184 | + coredns.reload() |
| 185 | + assert coredns.status == "running", ( |
| 186 | + f"CoreDNS crashed after Corefile update (status={coredns.status})" |
| 187 | + ) |
| 188 | + |
| 189 | + finally: |
| 190 | + _cleanup_docker(client) |
| 191 | + |
| 192 | + |
| 193 | +@pytest.mark.e2e |
| 194 | +@pytest.mark.asyncio |
| 195 | +async def test_e2e_federation_none_mode_no_changes(tmp_path, monkeypatch): |
| 196 | + """NONE mode: GatewayPortalHandler skips peer setup when cross_world is NONE.""" |
| 197 | + monkeypatch.setenv("NETENGINE_ZONE_DIR", str(tmp_path / "coredns")) |
| 198 | + |
| 199 | + client = _docker_client() |
| 200 | + if client is None: |
| 201 | + pytest.skip("Docker daemon not available") |
| 202 | + |
| 203 | + spec = load_spec(EXAMPLES_DIR / "minimal.yaml") |
| 204 | + docker_handler = DockerHandler() |
| 205 | + state = RuntimeState() |
| 206 | + ctx = PhaseContext( |
| 207 | + spec=spec, |
| 208 | + runtime_state=state, |
| 209 | + logger=get_logger("e2e.federation.none"), |
| 210 | + docker_client=docker_handler, |
| 211 | + mock_mode=False, |
| 212 | + zone_dir=str(tmp_path / "coredns"), |
| 213 | + ) |
| 214 | + |
| 215 | + try: |
| 216 | + await SubstrateHandler().execute(ctx) |
| 217 | + await DNSHandler().execute(ctx) |
| 218 | + |
| 219 | + corefile_before = _read_corefile_from_container(client, "netengine_coredns") |
| 220 | + |
| 221 | + # minimal.yaml has cross_world.mode: none — run portal handler as-is |
| 222 | + await GatewayPortalHandler().execute(ctx) |
| 223 | + |
| 224 | + gp_output = ctx.runtime_state.gateway_portal_output |
| 225 | + assert gp_output is not None |
| 226 | + assert gp_output["cross_world_mode"] == GatewayCrossWorldMode.NONE.value |
| 227 | + |
| 228 | + corefile_after = _read_corefile_from_container(client, "netengine_coredns") |
| 229 | + # Corefile must not have changed — no stubs should have been added |
| 230 | + assert corefile_before == corefile_after, ( |
| 231 | + "Corefile was modified even though cross_world mode is NONE" |
| 232 | + ) |
| 233 | + |
| 234 | + finally: |
| 235 | + _cleanup_docker(client) |
0 commit comments