diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index c84837c976..2bd410bc96 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -99,6 +99,7 @@ jobs: {"environment":"fedora-podman-rootless","installer":"rpm","family":"conformance","package":"conformance","gateway":"openshell","runner":"ubuntu-24.04","test_threads":4}, {"environment":"ubuntu-k3s","installer":"k3s","family":"conformance","package":"conformance","gateway":"tmachine","runner":"ubuntu-24.04","test_threads":4}, {"environment":"ubuntu-k3s","installer":"k3s-ha","family":"conformance","package":"conformance","gateway":"tmachine","runner":"ubuntu-24.04","test_threads":4}, + {"environment":"ubuntu-k3s-ipv6","installer":"k3s-ha","family":"conformance","package":"conformance","gateway":"tmachine","runner":"ubuntu-24.04","test_threads":4}, {"environment":"ubuntu-docker-rootful-cdi","installer":"deb","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful-cdi","installer":"rpm","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootless-cdi","installer":"rpm","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"}, @@ -115,6 +116,7 @@ jobs: {"environment":"fedora-podman-rootful","installer":"rpm","family":"features","package":"routable-host-ip","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-k3s","installer":"k3s","family":"features","package":"routable-host-ip","gateway":"tmachine","runner":"ubuntu-24.04"}, {"environment":"ubuntu-k3s","installer":"k3s-ha","family":"features","package":"routable-host-ip","gateway":"tmachine","runner":"ubuntu-24.04"}, + {"environment":"ubuntu-k3s-ipv6","installer":"k3s-ha","family":"features","package":"policy-dns-ipv6","gateway":"tmachine","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"connect-ssh-supervision","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful-keycloak","installer":"rpm","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootless-keycloak","installer":"rpm","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, diff --git a/TESTING.md b/TESTING.md index c959a505e3..0c6e21f1a3 100644 --- a/TESTING.md +++ b/TESTING.md @@ -707,6 +707,12 @@ supervisor. The address must be one the supervisor lets an IP literal reach. Rootless Podman's is link-local and always blocked, so CI runs the suite on Docker rootful, Podman rootful, and the `k3s` and `k3s-ha` installers. +The `policy-dns-ipv6` feature suite (`tests/suites/features/policy-dns-ipv6`) +checks that policy DNS answers AAAA queries with a synthetic address that +reaches only the policy endpoint's server. CI runs it on `ubuntu-k3s-ipv6`, +where the K3s installers enable `policy_dns_ipv6_egress` and set +`server.hostGatewayIP` to the node's IPv6 address. + The `connect-ssh-supervision` feature suite (`tests/suites/features/connect-ssh-supervision`) checks how `sandbox connect` supervises its `ssh` process: it reconnects after losing the SSH transport and diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index ba47285c9a..adabff4abb 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -2674,6 +2674,16 @@ version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +[[package]] +name = "policy-dns-ipv6" +version = "0.0.0" +dependencies = [ + "host-server-support", + "openshell-testkit", + "sandbox-clients-support", + "serde_json", +] + [[package]] name = "portable-atomic" version = "1.13.1" diff --git a/tests/suites/features/Cargo.toml b/tests/suites/features/Cargo.toml index 7c7fe40ae7..b7ea154446 100644 --- a/tests/suites/features/Cargo.toml +++ b/tests/suites/features/Cargo.toml @@ -3,4 +3,4 @@ [workspace] resolver = "2" -members = ["cdi", "connect-ssh-supervision", "docker-updates", "host-gateway", "keycloak-provider-refresh", "kubernetes-updates", "oci-image", "routable-host-ip"] +members = ["cdi", "connect-ssh-supervision", "docker-updates", "host-gateway", "keycloak-provider-refresh", "kubernetes-updates", "oci-image", "policy-dns-ipv6", "routable-host-ip"] diff --git a/tests/suites/features/policy-dns-ipv6/Cargo.toml b/tests/suites/features/policy-dns-ipv6/Cargo.toml new file mode 100644 index 0000000000..c7f37181c8 --- /dev/null +++ b/tests/suites/features/policy-dns-ipv6/Cargo.toml @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "policy-dns-ipv6" +description = "Features suite: policy DNS answers AAAA queries with a synthetic address pinned to the policy endpoint" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/ai-openshell/openshell" +publish = false + +[[test]] +name = "policy-dns-ipv6" +path = "tests/policy_dns_ipv6.rs" +harness = false + +[dependencies] +host-server-support = { path = "../../../support/host-server" } +sandbox-clients-support = { path = "../../../support/sandbox-clients" } +openshell-testkit = { path = "../../../testkit/testkit" } +serde_json = "1" diff --git a/tests/suites/features/policy-dns-ipv6/tests/policy_dns_ipv6.rs b/tests/suites/features/policy-dns-ipv6/tests/policy_dns_ipv6.rs new file mode 100644 index 0000000000..2a9c7cde76 --- /dev/null +++ b/tests/suites/features/policy-dns-ipv6/tests/policy_dns_ipv6.rs @@ -0,0 +1,159 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! With `policy_dns_ipv6_egress` enabled, policy DNS answers AAAA queries for +//! a policy endpoint's host with a synthetic IPv6 address, and a connection to +//! that address reaches only the endpoint's upstream. +//! +//! The environment must enable it and set `host.openshell.internal` to the +//! test host's IPv6 address, as the `k3s` installers do on `ubuntu-k3s-ipv6`. + +use std::net::IpAddr; + +use host_server_support::{HttpRecorder, TEST_HOST, allow_host, free_port}; +use sandbox_clients_support::{Request, connect, http}; +use testkit::policy; +use testkit::{Context, ResultExt as _}; + +fn main() -> std::process::ExitCode { + testkit::main() +} + +/// Sends an AAAA query for `argv[1]` to the sandbox's nameserver over UDP and +/// over TCP, without proxy variables, and prints the addresses of each answer +/// as one JSON line. +const DNS_CLIENT: &str = r#" +import json, os, random, socket, struct, sys + +for name in [n for n in os.environ if n.lower().endswith("_proxy")]: + del os.environ[name] +server = next(l.split()[1] for l in open("/etc/resolv.conf") if l.startswith("nameserver")) +family = socket.AF_INET6 if ":" in server else socket.AF_INET +qid = random.randrange(65536) +query = struct.pack("!HHHHHH", qid, 0x0100, 1, 0, 0, 0) +query += b"".join(bytes([len(p)]) + p.encode() for p in sys.argv[1].split(".")) + b"\0" +query += struct.pack("!HH", 28, 1) + +def skip_name(msg, i): + while msg[i]: + if msg[i] >= 0xC0: + return i + 2 + i += msg[i] + 1 + return i + 1 + +def addresses(msg): + _, flags, qd, an = struct.unpack("!HHHH", msg[:8]) + i = 12 + for _ in range(qd): + i = skip_name(msg, i) + 4 + found = [] + for _ in range(an): + i = skip_name(msg, i) + rtype, _, _, length = struct.unpack("!HHIH", msg[i:i + 10]) + i += 10 + if rtype == 28: + found.append(socket.inet_ntop(socket.AF_INET6, msg[i:i + length])) + i += length + return {"rcode": flags & 0xF, "addresses": found} + +with socket.socket(family, socket.SOCK_DGRAM) as udp: + udp.settimeout(5) + udp.sendto(query, (server, 53)) + udp_answer = addresses(udp.recv(4096)) +with socket.create_connection((server, 53), timeout=5) as tcp: + tcp.sendall(struct.pack("!H", len(query)) + query) + data = b"" + while len(data) < 2 or len(data) < 2 + struct.unpack("!H", data[:2])[0]: + chunk = tcp.recv(4096) + if not chunk: + break + data += chunk + tcp_answer = addresses(data[2:]) +print(json.dumps({"udp": udp_answer, "tcp": tcp_answer})) +"#; + +/// A native client gets the same synthetic AAAA answer over UDP and TCP, and +/// reaches the policy endpoint's server through it. The sandbox denies the +/// server's real address, the synthetic address on another port, and the +/// synthetic address once a policy change made its mapping stale. +#[testkit::test] +async fn aaaa_answer_reaches_only_the_pinned_upstream(cx: &mut Context) -> testkit::Result { + let server = HttpRecorder::start("pinned").await?; + let mut allowed = policy::base(); + allow_host(&mut allowed, "host_server", server.port); + let sandbox = cx.python_sandbox("dns6", allowed).create_ready().await?; + + let reply = http(&sandbox, TEST_HOST, server.port, &Request::get("/by-name")).await?; + testkit::ensure!( + reply.status() == Some(200), + "request by name failed: {reply:?}" + ); + let real_ip = server + .requests() + .first() + .and_then(|request| request.local_addr) + .ok_or_else(|| testkit::Error::msg("the host server didn't record its address"))? + .ip(); + testkit::ensure!( + real_ip.is_ipv6(), + "{TEST_HOST} reached the host server at {real_ip}, not an IPv6 address" + ); + + let answers = sandbox + .exec(["python3", "-c", DNS_CLIENT, TEST_HOST]) + .await? + .success()? + .last_json()?; + let udp = &answers["udp"]["addresses"]; + testkit::ensure!( + udp == &answers["tcp"]["addresses"] && udp.as_array().is_some_and(|a| a.len() == 1), + "expected one AAAA address, the same over UDP and TCP: {answers}" + ); + let synthetic: IpAddr = udp[0] + .as_str() + .and_then(|address| address.parse().ok()) + .ok_or_else(|| testkit::Error::msg(format!("unparsable AAAA answer: {answers}")))?; + testkit::ensure!( + synthetic != real_ip, + "the AAAA answer is the host server's real address {real_ip}" + ); + + let host_header = format!("{TEST_HOST}:{}", server.port); + let by_address = Request::get("/by-synthetic-address").header("Host", host_header.as_str()); + let synthetic = synthetic.to_string(); + let reply = http(&sandbox, &synthetic, server.port, &by_address).await?; + testkit::ensure!( + reply.status() == Some(200), + "request to the synthetic address {synthetic} failed: {reply:?}" + ); + + let other_port = free_port().await?; + for (what, host, port) in [ + ("the real address", real_ip.to_string(), server.port), + ( + "the synthetic address on another port", + synthetic.clone(), + other_port, + ), + ] { + let attempt = connect(&sandbox, &host, port).await?; + testkit::ensure!( + attempt.outcome.is_permission_denied(), + "expected a denial for {what} [{host}]:{port}; got {attempt:?}" + ); + } + + let moved = HttpRecorder::start("moved").await?; + let mut changed = policy::base(); + allow_host(&mut changed, "host_server", moved.port); + policy::set(&sandbox, &changed) + .await + .context("move the endpoint to another port")?; + let attempt = connect(&sandbox, &synthetic, server.port).await?; + testkit::ensure!( + attempt.outcome.is_permission_denied(), + "expected a denial for the stale synthetic address [{synthetic}]:{}; got {attempt:?}", + server.port + ); + Ok(()) +} diff --git a/tests/suites/unsupported.yaml b/tests/suites/unsupported.yaml index 84c914f04c..4c30ae70b3 100644 --- a/tests/suites/unsupported.yaml +++ b/tests/suites/unsupported.yaml @@ -22,7 +22,9 @@ issue: https://github.com/ai-openshell/openshell/issues/5752 environments: - ubuntu-k3s/k3s-ha + - ubuntu-k3s-ipv6/k3s-ha - test: conformance::network_egress::fail_closed_middleware_blocks_uninspectable_traffic issue: https://github.com/ai-openshell/openshell/issues/5752 environments: - ubuntu-k3s/k3s-ha + - ubuntu-k3s-ipv6/k3s-ha diff --git a/tests/support/host-server/src/http.rs b/tests/support/host-server/src/http.rs index 0845b0af5e..b93dc7fbd1 100644 --- a/tests/support/host-server/src/http.rs +++ b/tests/support/host-server/src/http.rs @@ -247,7 +247,11 @@ pub(crate) async fn read_request(stream: &mut TcpStream, buffer: &mut Vec) - loop { if let Some((mut request, length)) = parse_request(buffer) { buffer.drain(..length); - request.local_addr = stream.local_addr().ok(); + // An IPv4 client on the IPv6 socket arrives on a mapped address. + request.local_addr = stream + .local_addr() + .ok() + .map(|addr| SocketAddr::new(addr.ip().to_canonical(), addr.port())); return Some(request); } match tokio::time::timeout(READ_TIMEOUT, stream.read(&mut chunk)).await { diff --git a/tests/support/host-server/src/lib.rs b/tests/support/host-server/src/lib.rs index a481c1d5f3..7bd44ce6d8 100644 --- a/tests/support/host-server/src/lib.rs +++ b/tests/support/host-server/src/lib.rs @@ -54,10 +54,15 @@ const WAIT_INTERVAL: Duration = Duration::from_millis(100); const READ_TIMEOUT: Duration = Duration::from_secs(10); const MAX_REQUEST: usize = 1024 * 1024; +/// Listens on every IPv6 and IPv4 address, or on IPv4 only where the host +/// has no IPv6. async fn bind() -> Result<(TcpListener, u16)> { - let listener = TcpListener::bind(("0.0.0.0", 0)) - .await - .context("bind a host server")?; + let listener = match TcpListener::bind(("::", 0)).await { + Ok(listener) => listener, + Err(_) => TcpListener::bind(("0.0.0.0", 0)) + .await + .context("bind a host server")?, + }; let port = listener .local_addr() .context("read the host server's address")? diff --git a/tests/tmachine/ansible/playbooks/k3s-ipv6.yaml b/tests/tmachine/ansible/playbooks/k3s-ipv6.yaml new file mode 100644 index 0000000000..ce5a3995c6 --- /dev/null +++ b/tests/tmachine/ansible/playbooks/k3s-ipv6.yaml @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Make the K3s base a dual-stack cluster with IPv6 first. k3s.yaml left K3s +# stopped with no cluster state, so the next start creates it from this file. +--- +- name: Configure IPv6-first dual-stack K3s + hosts: all + become: true + gather_facts: false + tasks: + - name: Wait for SSH + ansible.builtin.wait_for_connection: + + # K3s takes the node's addresses from the default routes. tmachine gives + # the guest a global IPv6 address through QEMU's ipv6-net option. + - name: Wait for a global IPv6 address + ansible.builtin.setup: + gather_subset: [network] + register: k3s_ipv6_facts + until: (k3s_ipv6_facts.ansible_facts.ansible_default_ipv6.scope | default('')) == "global" + retries: 10 + delay: 2 + + - name: Write the dual-stack K3s configuration + ansible.builtin.copy: + dest: /etc/rancher/k3s/config.yaml + owner: root + group: root + mode: "0644" + content: | + cluster-cidr: fd00:42::/56,10.42.0.0/16 + service-cidr: fd00:43::/112,10.43.0.0/16 + flannel-ipv6-masq: true diff --git a/tests/tmachine/ansible/playbooks/openshell-k3s-ha.yaml b/tests/tmachine/ansible/playbooks/openshell-k3s-ha.yaml index efcc736d49..3518cc1a7f 100644 --- a/tests/tmachine/ansible/playbooks/openshell-k3s-ha.yaml +++ b/tests/tmachine/ansible/playbooks/openshell-k3s-ha.yaml @@ -64,7 +64,7 @@ ansible.builtin.lineinfile: path: /etc/hosts regexp: '\sopenshell\.openshell\.svc\.cluster\.local$' - line: "{{ k3s_gateway_address.stdout.split(':')[0] }} openshell.openshell.svc.cluster.local" + line: "{{ k3s_gateway_ip }} openshell.openshell.svc.cluster.local" - name: Read chart client TLS Secret ansible.builtin.command: @@ -103,4 +103,4 @@ apply: become: false vars: - openshell_client_gateway_endpoint: "https://openshell.openshell.svc.cluster.local:{{ k3s_gateway_address.stdout.split(':')[1] }}" + openshell_client_gateway_endpoint: "https://openshell.openshell.svc.cluster.local:{{ k3s_gateway_port }}" diff --git a/tests/tmachine/ansible/playbooks/openshell-k3s.yaml b/tests/tmachine/ansible/playbooks/openshell-k3s.yaml index 5b68bc0067..2af473db13 100644 --- a/tests/tmachine/ansible/playbooks/openshell-k3s.yaml +++ b/tests/tmachine/ansible/playbooks/openshell-k3s.yaml @@ -66,7 +66,8 @@ # address must be the one of the node the tests run on. QEMU user # networking gives every boot the same guest address (10.0.2.15), so the # value stays valid when the disk is reused. - # The node can also list an IPv6 address after it, so take the IPv4 one. + # A dual-stack node lists both addresses, the IPv6 one first on an + # IPv6-first cluster (playbooks/k3s-ipv6.yaml). Take the first. - name: Discover the K3s node address ansible.builtin.command: argv: @@ -91,10 +92,13 @@ changed_when: false failed_when: k3s_nodes.rc != 0 or k3s_nodes.stdout_lines | length != 1 - - name: Select the K3s node IPv4 address + - name: Select the K3s node address ansible.builtin.set_fact: - k3s_node_ipv4: "{{ k3s_node_address.stdout.split() | select('match', '^[0-9.]+$') | first }}" + k3s_node_ip: "{{ k3s_node_address.stdout.split()[0] }}" + k3s_ipv6: "{{ ':' in k3s_node_address.stdout.split()[0] }}" + # On an IPv6-first cluster the gateway and supervisor listen on IPv6, and + # policy DNS answers AAAA queries, so sandboxes reach the node over IPv6. - name: Write OpenShell Helm values ansible.builtin.copy: dest: /var/lib/openshell/artifacts/values.yaml @@ -104,6 +108,7 @@ image: registry: "" gateway: + listenAddress: "{{ '::' if k3s_ipv6 else '0.0.0.0' }}" image: repository: openshell/gateway tag: tmachine @@ -114,6 +119,7 @@ tag: tmachine pullPolicy: never supervisor: + listenAddress: "{{ '::' if k3s_ipv6 else '0.0.0.0' }}" image: repository: openshell/supervisor tag: tmachine @@ -124,8 +130,13 @@ auth: allowUnauthenticatedUsers: true disableTls: true - hostGatewayIP: "{{ k3s_node_ipv4 }}" + hostGatewayIP: "{{ k3s_node_ip }}" telemetryEnabled: false + {% if k3s_ipv6 %} + gatewayConfig: + openshell.drivers.kubernetes: + policy_dns_ipv6_egress: enabled + {% endif %} - name: Write OpenShell Helm values overlay ansible.builtin.copy: @@ -196,17 +207,29 @@ - get - service - openshell - - --output=jsonpath={.spec.clusterIP}:{.spec.ports[?(@.name=="grpc")].port} + - --output=jsonpath={.spec.clusterIP} {.spec.ports[?(@.name=="grpc")].port} register: k3s_gateway_address changed_when: false # Rejects headless Services (ClusterIP "None") and a missing grpc port. + # The ClusterIP is IPv6 on a cluster whose primary family is IPv6. - name: Require a gateway Service address ansible.builtin.assert: that: - - k3s_gateway_address.stdout is match('^[0-9.]+:[0-9]+$') + - k3s_gateway_address.stdout is match('^([0-9.]+|[0-9a-f:]+) [0-9]+$') fail_msg: "Unexpected gateway Service address: {{ k3s_gateway_address.stdout }}" + # A URL needs brackets around an IPv6 address, for example + # http://[fd00:43::a]:8080; without them the port can't be told apart. + - name: Record the gateway Service address + vars: + gateway_ip: "{{ k3s_gateway_address.stdout.split()[0] }}" + gateway_port: "{{ k3s_gateway_address.stdout.split()[1] }}" + ansible.builtin.set_fact: + k3s_gateway_ip: "{{ gateway_ip }}" + k3s_gateway_port: "{{ gateway_port }}" + k3s_gateway_authority: "{{ ('[' ~ gateway_ip ~ ']') if ':' in gateway_ip else gateway_ip }}:{{ gateway_port }}" + # Deployment readiness doesn't establish that the controller reconciles # Sandboxes. This checks the installed cluster; a booted guest restarts the # controller, so the test runner checks again after it boots @@ -218,6 +241,6 @@ hosts: all gather_facts: false vars: - openshell_client_gateway_endpoint: "http://{{ k3s_gateway_address.stdout }}" + openshell_client_gateway_endpoint: "http://{{ k3s_gateway_authority }}" roles: - openshell_client diff --git a/tests/tmachine/config.nix b/tests/tmachine/config.nix index ed62c23eb6..3cb4f21237 100644 --- a/tests/tmachine/config.nix +++ b/tests/tmachine/config.nix @@ -109,6 +109,12 @@ let inputs.keycloak_realm_file = "../../scripts/keycloak-realm.json"; }; }; + # A dual-stack K3s cluster with IPv6 first, for running the k3s suites + # over IPv6. + ipv6 = { + bases = [ "ubuntu-k3s" ]; + setup.playbooks = [ "ansible/playbooks/k3s-ipv6.yaml" ]; + }; # Hardware-free CDI fixtures, for the cdi suite. cdi = { bases = dockerBases ++ podmanBases; diff --git a/tests/tmachine/src/qemu/vm.rs b/tests/tmachine/src/qemu/vm.rs index 354d04c53a..000d9d1779 100644 --- a/tests/tmachine/src/qemu/vm.rs +++ b/tests/tmachine/src/qemu/vm.rs @@ -225,8 +225,14 @@ fn command( .arg("virtio-blk-pci,drive=rootfs,bootindex=1") .arg("-device") .arg("virtio-rng-pci") + // A unique local IPv6 prefix instead of user networking's default + // site-local fec0::/64. Linux ranks a site-local source below any + // global address, so on a dual-stack K3s guest it picks flannel's + // address to reach an IPv6 Service and never gets the reply. .arg("-netdev") - .arg(format!("user,id=net0,hostfwd=tcp:127.0.0.1:{ssh_port}-:22")) + .arg(format!( + "user,id=net0,ipv6-net=fd00:10::/64,hostfwd=tcp:127.0.0.1:{ssh_port}-:22" + )) .arg("-device") .arg("virtio-net-pci,netdev=net0");