Testing
Source files: 147 · checked against Etemenanki 46c12e4 · katana v6.1.0
Etemenanki/Cargo.tomlEtemenanki/protocols/Cargo.tomlEtemenanki/supervisor/Cargo.tomlEtemenanki/app/Cargo.tomlEtemenanki/ffi/Cargo.tomlEtemenanki/reality/Cargo.tomlEtemenanki/concepts/src/runtime.rsEtemenanki/concepts/src/buffer.rsEtemenanki/concepts/src/client.rsEtemenanki/concepts/src/link.rsEtemenanki/concepts/tests/runtime.rsEtemenanki/concepts/tests/client.rsEtemenanki/environment/src/lib.rsEtemenanki/environment/tests/integration.rsEtemenanki/environment/tests/integration/udp.rsEtemenanki/environment/tests/unit/dial/socket.rsEtemenanki/protocols/src/lib.rsEtemenanki/protocols/src/core/mod.rsEtemenanki/protocols/src/core/harness.rsEtemenanki/protocols/tests/pipeline.rsEtemenanki/protocols/tests/pipeline/core.rsEtemenanki/protocols/tests/pipeline/trojan.rsEtemenanki/protocols/tests/pipeline/vless.rsEtemenanki/protocols/tests/pipeline/vmess.rsEtemenanki/protocols/tests/pipeline/shadowsocks.rsEtemenanki/protocols/tests/pipeline/transports.rsEtemenanki/protocols/tests/pipeline/socks.rsEtemenanki/protocols/tests/pipeline/hysteria.rsEtemenanki/protocols/tests/pipeline/hysteria_options.rsEtemenanki/protocols/tests/pipeline/wireguard.rsEtemenanki/protocols/tests/pipeline/tun.rsEtemenanki/protocols/tests/pipeline/anytls.rsEtemenanki/protocols/tests/pipeline/reality.rsEtemenanki/protocols/tests/support/mod.rsEtemenanki/protocols/tests/support/pipeline.rsEtemenanki/protocols/tests/support/wireguard.rsEtemenanki/protocols/tests/support/udp_range.rsEtemenanki/protocols/tests/unit/core/mod.rsEtemenanki/protocols/src/transports/mod.rsEtemenanki/protocols/tests/unit/transports/support.rsEtemenanki/protocols/tests/unit/transports/accept.rsEtemenanki/protocols/tests/unit/transports/grpc_stream.rsEtemenanki/protocols/tests/unit/transports/coalesce.rsEtemenanki/protocols/tests/unit/transports/tls_platform_roots.rsEtemenanki/protocols/tests/unit/trojan/core.rsEtemenanki/protocols/src/socks/server.rsEtemenanki/protocols/tests/unit/socks/server.rsEtemenanki/protocols/tests/unit/socks/protocol.rsEtemenanki/protocols/src/wireguard/device.rsEtemenanki/protocols/tests/unit/wireguard/device.rsEtemenanki/protocols/tests/unit/sss/transform/chain.rsEtemenanki/protocols/tests/unit/sss/transform/vectors.tsvEtemenanki/protocols/tests/unit/sss/transform/vectors.pyEtemenanki/protocols/benches/vmess_users.rsEtemenanki/reality/src/lib.rsEtemenanki/reality/src/tls13/mod.rsEtemenanki/reality/tests/server.rsEtemenanki/reality/tests/client.rsEtemenanki/reality/tests/support/dest.rsEtemenanki/reality/tests/unit/support/mod.rsEtemenanki/reality/tests/unit/tls13/rfc8448.rsEtemenanki/reality/tests/unit/tls13/schedule.rsEtemenanki/reality/tests/unit/tls13/record.rsEtemenanki/reality/tests/unit/tls13/messages.rsEtemenanki/reality/tests/unit/keys.rsEtemenanki/reality/tests/unit/auth.rsEtemenanki/reality/tests/unit/server/handshake.rsEtemenanki/reality/tests/unit/server/accept.rsEtemenanki/reality/tests/unit/client/hello.rsEtemenanki/reality/tests/unit/client/handshake.rsEtemenanki/reality/tests/unit/stream.rsEtemenanki/reality/tests/unit/camouflage.rsEtemenanki/subscribe/src/lib.rsEtemenanki/subscribe/tests/unit/subscribe.rsEtemenanki/supervisor/tests/hot_swap.rsEtemenanki/supervisor/tests/socket_policy.rsEtemenanki/supervisor/tests/tracking.rsEtemenanki/supervisor/tests/guard.rsEtemenanki/supervisor/tests/handoff.rsEtemenanki/supervisor/tests/anytls.rsEtemenanki/supervisor/tests/sss.rsEtemenanki/supervisor/tests/ping.rsEtemenanki/supervisor/tests/support/mod.rsEtemenanki/supervisor/tests/unit/plan.rsEtemenanki/supervisor/tests/unit/validate.rsEtemenanki/supervisor/tests/unit/session.rsEtemenanki/supervisor/tests/unit/track.rsEtemenanki/supervisor/tests/unit/usage.rsEtemenanki/supervisor/tests/unit/guard.rsEtemenanki/supervisor/tests/unit/supervisor.rsEtemenanki/supervisor/tests/unit/serve.rsEtemenanki/supervisor/tests/unit/router.rsEtemenanki/supervisor/tests/unit/plane.rsEtemenanki/supervisor/tests/unit/balancer.rsEtemenanki/supervisor/tests/unit/dns_outbound.rsEtemenanki/supervisor/tests/unit/ping.rsEtemenanki/supervisor/benches/tracking.rsEtemenanki/webclient/tests/tracking.rsEtemenanki/ffi/tests/proxy.rsEtemenanki/ffi/tests/inspect.rsEtemenanki/ffi/tests/convert.rsEtemenanki/app/src/main.rsEtemenanki/app/tests/integration.rsEtemenanki/app/tests/support/mod.rsEtemenanki/app/tests/support/runs.rsEtemenanki/app/tests/integration/e2e_xray.rsEtemenanki/app/tests/integration/e2e_xray_vmess.rsEtemenanki/app/tests/integration/e2e_xray_mux.rsEtemenanki/app/tests/integration/e2e_unix.rsEtemenanki/app/tests/integration/e2e_hysteria.rsEtemenanki/app/tests/integration/e2e_hysteria_inbound.rsEtemenanki/app/tests/integration/e2e_hysteria_options.rsEtemenanki/app/tests/integration/e2e_wg.rsEtemenanki/app/tests/integration/e2e_tun.rsEtemenanki/app/tests/integration/e2e_reload.rsEtemenanki/app/tests/integration/e2e_api.rsEtemenanki/app/tests/integration/e2e_xray_reality.rsEtemenanki/app/tests/integration/e2e_xray_wrapped.rsEtemenanki/app/tests/integration/e2e_singbox_anytls.rsEtemenanki/app/tests/integration/e2e_sss.rsEtemenanki/app/tests/unit/config.rsEtemenanki/app/tests/unit/lower.rsEtemenanki/app/tests/unit/subscribe.rsEtemenanki/app/tests/unit/api.rsEtemenanki/app/tests/unit/transport.rskatana/Cargo.tomlkatana/src/main.rskatana/src/api/mod.rskatana/src/runtime.rskatana/src/manager/mod.rskatana/src/manager/node.rskatana/src/lower/mod.rskatana/tests/integration.rskatana/tests/support/mod.rskatana/tests/integration/xray_interop.rskatana/tests/integration/sniff.rskatana/tests/integration/hysteria_interop.rskatana/tests/unit/e2e.rskatana/tests/unit/runtime.rskatana/tests/unit/rule.rskatana/tests/unit/lower/inbound.rskatana/tests/unit/lower/outbound.rskatana/tests/unit/lower/spec.rskatana/tests/unit/api/newv2board.rskatana/tests/unit/api/helium.rskatana/tests/unit/api/http.rskatana/tests/unit/manager/node.rs
Both repositories test in layers. The lowest layer calls a sans-I/O core or codec by hand and inspects the effects and bytes it produces. The next drives the per-connection runtimes with toy protocols over in-memory pipes. Above that, each protocol’s server core runs against its own client codec over loopback sockets, and the supervisor’s own suites run a real Supervisor on loopback and reconfigure it while connections are live. At the top, the real etemenanki-app and katana binaries run as child processes, and the interop tests among them run against independent implementations (Xray, the official Hysteria 2 client and server, and sing-box) that the tests build from the reference trees with Go. The REALITY crate, etemenanki-reality, has suites of its own that stand a local OpenSSL server in for the cover site.
This page is for contributors who add or change code in either repository. It describes where each kind of test lives, the harness each layer offers, how to run a subset or a benchmark, the gates a change must pass, and the tests a new protocol, a supervisor change or a pipeline change is expected to bring. The per-component pages list the individual tests that pin their behaviour; this page covers how the tests are built.
Layout
Section titled “Layout”Unit tests live in tests/unit/ and compile into their module
Section titled “Unit tests live in tests/unit/ and compile into their module”Unit tests do not live in the file under test. The test body lives under <crate>/tests/unit/, and the module under test mounts it with a #[path] attribute:
#[cfg(test)]#[path = "../../tests/unit/trojan/core.rs"]mod tests;The file brings the parent module into scope with use super::*;, usually on its first line. Because it compiles as a child module of the code under test, it reaches everything the module can see, including private items and the module’s private use imports (the Trojan test takes Validator, Arc and io from super::*), without any of them becoming pub. Cargo auto-discovers only tests/*.rs and tests/<dir>/main.rs as integration targets, and there is no main.rs under tests/unit/, so these files are compiled only through their #[path] mount.
| Rule | Example |
|---|---|
In etemenanki-protocols the path usually mirrors the module |
protocols/src/vless/codec.rs mounts tests/unit/vless/codec.rs; protocols/src/hysteria/server/inbound.rs mounts tests/unit/hysteria/server/inbound.rs |
| The transports flatten their third level into one file name | protocols/src/transports/tls/config.rs mounts tests/unit/transports/tls_config.rs; transports/grpc/framing.rs mounts tests/unit/transports/grpc_framing.rs; transports/grpc/stream.rs mounts tests/unit/transports/grpc_stream.rs |
| Helpers several unit-test files share are a module of their own | protocols/src/transports/mod.rs mounts tests/unit/transports/support.rs as pub(crate) mod test_support under cfg(test). accept.rs and grpc_stream.rs take Recorded from it, a pipe end that keeps every write it is handed, and writes_carrying, which counts the writes that carry a given message, to check how h2’s writes reach the socket |
A mod.rs in protocols mounts a mod.rs |
protocols/src/core/mod.rs mounts tests/unit/core/mod.rs |
etemenanki-reality mirrors its modules too, and shares its fixtures through cfg(test) modules |
reality/src/server/handshake.rs mounts tests/unit/server/handshake.rs; reality/src/lib.rs mounts tests/unit/support/mod.rs as test_support (ClientHello builders, a sans-I/O TestClient, the Lcg generator of the mutation tests, and tests/support/dest.rs as dest); reality/src/tls13/mod.rs mounts the RFC 8448 vectors, tests/unit/tls13/rfc8448.rs, for the tests of every part |
The supervisor, the app and etemenanki-subscribe keep tests/unit/ flat, one file per module under test |
supervisor/src/topology/spec_plan/plan.rs mounts tests/unit/plan.rs; supervisor/src/build/validate.rs mounts tests/unit/validate.rs; supervisor/src/topology/outbound/dns.rs mounts tests/unit/dns_outbound.rs; app/src/lower.rs mounts tests/unit/lower.rs; subscribe/src/lib.rs mounts tests/unit/subscribe.rs |
| katana mirrors its module directories | src/lower/inbound.rs mounts tests/unit/lower/inbound.rs; src/lower/mod.rs mounts tests/unit/lower/spec.rs; src/api/mod.rs mounts tests/unit/api/http.rs |
A binary crate can mount a suite from main.rs |
katana’s src/main.rs mounts tests/unit/e2e.rs as mod e2e |
The only exceptions are three files in etemenanki-concepts: concepts/src/buffer.rs, concepts/src/wake.rs and concepts/src/relay.rs keep a small inline mod tests. New tests go in tests/unit/.
Code written for another platform is tested on the host where it can be. protocols/src/transports/tls/platform_roots.rs compiles bundled (the iOS roots) and native (the Windows and macOS store, read through rustls-native-certs) under cfg(test) on every host as well, so tests/unit/transports/tls_platform_roots.rs checks that every root webpki-root-certs bundles converts to an OpenSSL certificate (every_bundled_root_parses), and that every certificate the host’s own store lists does too (every_native_root_converts).
environment/src/lib.rs, reality/src/lib.rs and protocols/src/lib.rs deny clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing and clippy::arithmetic_side_effects for the crate, then allow all four under cfg_attr(test, …). subscribe/src/lib.rs does the same with clippy::unwrap_used, clippy::expect_used and clippy::panic. Mounted unit tests are part of the crate under cfg(test), so the allowance is what lets them unwrap() and index freely. Integration targets are separate crates and never see the deny. Test support that ships in the library, such as CoreHarness, is not under cfg(test), so it obeys the lints: that is why it uses get(..).unwrap_or_default() and saturating_add rather than indexing and +. katana has no crate-wide deny.
Integration targets
Section titled “Integration targets”An integration entry point is a single file under tests/ that declares its submodules, so the scenarios of one kind link into one test binary instead of one binary per file.
| Package | Entry point | Modules | What it proves |
|---|---|---|---|
etemenanki-concepts |
tests/runtime.rs |
none | ProxyServerRuntime driven by toy cores: relaying, backpressure, deadlines, datagram transports, held bytes |
etemenanki-concepts |
tests/client.rs |
server_side |
ProxyClientRuntime driven by toy codecs, alone and as the outbound of a server runtime |
etemenanki-environment |
tests/integration.rs |
tcp, udp, quic (feature quic) |
The dialers against real loopback peers |
etemenanki-reality |
tests/server.rs, tests/client.rs |
dest in each, tests/support/dest.rs mounted with #[path] |
The REALITY server seen from outside: a client that is not one of its own gets the cover site, byte for byte and on the cover site’s timing. The real client against the real server over an in-memory pipe, and a client pinning another key relayed to the cover site, whose real certificate it refuses |
etemenanki-protocols |
tests/pipeline.rs |
pipeline::{anytls, core, dns_secure, http, hysteria, hysteria_options, reality, shadowsocks, socks, transports, trojan, tun, vless, vmess, wireguard} |
Every server core against its client codec over loopback; every transport, the REALITY transport included; DNS over TLS and HTTPS; Hysteria 2’s agreed rates and port hopping; the AnyTLS core behind TLS and its pooled client; the WireGuard connector against an in-process peer |
etemenanki-supervisor |
tests/hot_swap.rs, tests/tracking.rs, tests/socket_policy.rs, tests/guard.rs, tests/handoff.rs, tests/anytls.rs, tests/sss.rs, tests/ping.rs |
support in each |
A real Supervisor on loopback: applies against live connections and closing the flows a route change moved, flow and session accounting, the host socket policy, the device limit, the IP ban, the gRPC failure count, a WebSocket client named by a trusted proxy’s header, connections handed over on a handoff socket, AnyTLS and sss between two supervisors, and delay tests through a named outbound |
etemenanki-webclient |
tests/tracking.rs |
none | The REST API’s endpoints that go to a running supervisor: connections, traffic, a route switch that closes what it moved, and delay tests |
etemenanki-ffi |
tests/proxy.rs, tests/inspect.rs, tests/convert.rs |
none | A proxy run through the mobile library, with a stand-in TUN device; the calls that need no running proxy: reading a subscribe file, checking a config and its route view; and converting a provider’s subscription or share links into a subscribe file |
etemenanki-app |
tests/integration.rs |
20 e2e_* modules |
The real binary: interop with Xray (REALITY, Vision with its UDP, and wrapped Shadowsocks, SOCKS and HTTP included), Hysteria (Hysteria 2’s rates and port hopping included) and sing-box (AnyTLS), sss between two apps, routing, sniffing, DNS, balancers, Unix sockets, WireGuard, TUN, reloads, the REST API |
katana |
tests/integration.rs |
xray_interop, sniff, hysteria_interop |
The real binary against a fake panel, driven by real Xray and Hysteria clients |
In tests/pipeline.rs, mod hysteria and mod hysteria_options sit behind #[cfg(feature = "hysteria")], mod reality behind #[cfg(feature = "reality")], and mod tun behind #[cfg(all(feature = "tun", unix))]: its device is one end of a socketpair, which has no counterpart on Windows. mod anytls needs no feature. In environment/tests/integration.rs, mod quic sits behind #[cfg(feature = "quic")]. All three ffi targets are #![cfg(unix)], as the ffi crate itself is, and so is supervisor/tests/handoff.rs, because handoff sockets are Unix only. The shared helpers of etemenanki-protocols, the supervisor, etemenanki-app and katana live in tests/support/, declared by each entry point as mod support;. protocols/tests/support/mod.rs, support/wireguard.rs and supervisor/tests/support/mod.rs carry #![allow(dead_code)], because no single target uses every helper. The app’s support mounts protocols/tests/support/udp_range.rs with a #[path] attribute, so the Hysteria 2 option tests of both crates use the same port-range forwarder (PortRange, described below). etemenanki-reality’s two targets each mount tests/support/dest.rs as mod dest, and its unit tests reach the same file through test_support: an OpenSSL TLS 1.3 server with a fresh 2048-bit RSA certificate for one name, listening on 127.0.0.2, that acknowledges the SNI, answers what a client writes with dest: and the same bytes, and drops a connection idle past the timeout it was started with. The concepts, environment, webclient and ffi targets have no shared support module.
katana’s in-process end-to-end suite is not an integration target. tests/unit/e2e.rs is mounted into the binary crate from src/main.rs, so it runs with the unit tests and has crate-private access to NodeManager, PanelClient and the config structs. Its fixtures are pub(crate), and tests/unit/runtime.rs, mounted from src/runtime.rs, imports them from crate::e2e to drive reloads against running nodes.
The layers at a glance
Section titled “The layers at a glance”| Layer | Where | I/O | What a failure there usually means |
|---|---|---|---|
| Codec and parser unit tests | protocols/tests/unit/<proto>/{protocol,codec}.rs |
None | Wrong bytes on the wire, or a malformed field accepted |
| Core unit tests | protocols/tests/unit/<proto>/core.rs through CoreHarness |
None | Wrong effects: an early Open, a missing deadline, a lost half-close |
| Runtime tests | concepts/tests/{runtime,client}.rs |
tokio::io::duplex, some UDP on loopback |
The driver breaks the event contract, backpressure or deadlines |
| Pipeline tests | protocols/tests/pipeline/*.rs |
Loopback TCP and UDP | Server core and client codec disagree, or a transport breaks |
| REALITY crate | reality/tests/unit/**, reality/tests/{server,client}.rs |
None for the sans-I/O handshake; duplex pipes or loopback TCP with a local OpenSSL cover site |
The TLS 1.3 subset or the handshake departs from RFC 8446 or from XTLS’s, or a probe can tell the server from its cover site |
| Supervisor unit tests | supervisor/tests/unit/*.rs |
Mostly none; paused clock for grace timers and pacing | plan or validate decides wrongly, or sessions, pacing or usage accounting break their rules |
| Supervisor end to end | supervisor/tests/{hot_swap,tracking,socket_policy,guard,handoff,anytls,sss,ping}.rs |
A real Supervisor on loopback |
An apply disturbs connections it should leave alone, metering and billing miscount, or a guard admits a client it should turn away |
| webclient and ffi host tests | webclient/tests/tracking.rs, ffi/tests/{proxy,inspect,convert}.rs |
In-process | An endpoint or a mobile entry point misreports or misbehaves |
| App unit tests | app/tests/unit/{config,lower,subscribe,api,transport}.rs |
Mostly none | Config accepted that should fail closed, or lowered into the wrong spec |
| App end to end | app/tests/integration/e2e_*.rs |
Child processes on loopback | The binary as an operator runs it does not work, or disagrees with Xray, Hysteria or sing-box |
| katana unit tests | katana/tests/unit/{lower,api,manager}/*.rs, rule.rs, runtime.rs |
Mostly none | A panel answer parsed or lowered into the wrong spec, reload decisions wrong |
| katana in-process e2e | katana/tests/unit/e2e.rs, katana/tests/unit/runtime.rs |
Loopback, in-process fake panels | The node manager: sync, reporting, user refresh, speed limits, Hysteria 2 rates, the device limit and IP ban, audit, bootstrap retries, reloads |
| katana integration | katana/tests/integration/*.rs |
Child processes on loopback | The binary against an independent client and a panel |
Runtime tests: toy cores and codecs
Section titled “Runtime tests: toy cores and codecs”concepts/tests/runtime.rs and concepts/tests/client.rs never use a real protocol. They define small protocols whose whole wire format fits in a comment, so a failure points at the runtime rather than at a codec. etemenanki-concepts enables tokio’s test-util in its dev-dependencies for the paused-clock tests.
Server-side toy cores
Section titled “Server-side toy cores”| Core | Transport | Wire format | Used for |
|---|---|---|---|
TinyMux |
Byte stream | [kind][key][len:u16][payload], payload XOR 0x55; kinds OPEN 1, DATA 2, CLOSE 3, FIN 4 from the client, CONNECTED 5, CONNECT_FAILED 6, EOF 7 to it |
Several keys over one connection: relaying, stalls, half-close, deadlines, FrameTooLarge |
TinyUdp |
Byte stream | [len:u16][port:u16][payload]; len == 0 finishes; len == 0xFFFE sends to an IPv6 peer through an IPv4 socket to provoke SendFailed |
Key = Single with a datagram outbound |
TinyHub |
UDP socket (over_datagrams) |
[port:u16][payload] per packet; port 0 finishes; port 0xFFFF provokes TransportSendFailed |
Key = SocketAddr: one outbound per peer, replies through stage_to |
TinySessions over TinyQuic |
Single-peer DatagramLink (Addr = ()) over two mpsc channels, refusing packets above max |
[session:u32][port:u16][payload] |
The QUIC-datagram shape: one peer, many sessions, a refused packet reported as NOTICE |
Sniffing |
Byte stream | The first 8 bytes are the target name | Effect::ForwardHeld and the held-buffer pin rule |
The core’s constants are chosen for the test: TinyMux has STAGING_RESERVE = HDR + 64 (with HDR = 4), TinyUdp 4, TinyHub 2, TinySessions 6, Sniffing 0.
The dialers are plain closures, because Connector has a blanket implementation for FnMut(Target) -> Future:
dialer(dials)pops a pre-madeDuplexStreamfor everyOpenand refuses the target"fail"withConnectionRefused("refused by test").mux_harness(far_caps)builds the client pipe (4096 bytes) and one far-end duplex per entry offar_caps. A small capacity is how a test makes one outbound stall:stalled_outbound_holds_uplink_but_not_other_downlinkgives key 1 an 8-byte pipe.gated_dialer(targets, links)records each target and completes the dial only when the test fires aoneshot, so a test can hold a dial open while more bytes arrive.udp_connectorandudp_echobind real UDP sockets on127.0.0.1.
core_is_driven_without_any_io is the one test with no runtime at all: it calls TinyMux::handle with an EffectList and a WriteBuffer::<256> and asserts on the effects. It is the pattern CoreHarness generalises.
Client-side toy codecs
Section titled “Client-side toy codecs”| Codec | Traits | Wire format | Used for |
|---|---|---|---|
TinyCodec |
ProxyCoreEncodeHandshake, ProxyCoreEncode |
Header [0xC0][len:u8][target], then [kind][len:u16][payload ^ 0x55] with kind 1 data and 2 close; seal takes at most MAX_FRAME = 32 bytes |
Framing across calls, EOF, dial failure, backpressure |
TwoRoundCodec |
same | SOCKS-shaped: [0x05] then [0x05, 0x00], [0x01][target] then [0x00] |
Handshake::AwaitReply and a refused method |
Scripted |
all three, including ProxyCoreEncodeDatagram |
Returns whatever Handshake, Reply and Opened the test set |
Contract violations: every such test wraps the read in a 1 s timeout and expects an error, never a spin |
TinyUdpCodec |
ProxyCoreEncodeHandshake, ProxyCoreEncodeDatagram |
TinyCodec framing with [port:u16] before each payload |
Datagrams over a stream upstream |
The server_side module runs a server runtime whose connector is a ProxyClientConnector wrapping TinyCodec, with a Passthrough core that answers + on Connected and - on ConnectFailed. It pins that Connected is reported only after the upstream accepted the header (server_runtime_relays_through_a_client_runtime_in_one_task uses a 4-byte upstream pipe to make the header wait), and that a dial failure or a refused upstream handshake becomes ConnectFailed (upstream_dial_failure_is_connect_failed_not_connected, refused_upstream_handshake_is_connect_failed_not_connected).
Choosing BUF_SIZE in a test
Section titled “Choosing BUF_SIZE in a test”Both runtimes assert their buffer against the core or codec at construction:
assert!( BUF_SIZE > Core::STAGING_RESERVE, "BUF_SIZE must exceed the core's STAGING_RESERVE or nothing is ever read");ProxyClientRuntime::new has the same check against Codec::STAGING_RESERVE. A test that picks a tiny buffer to force a condition therefore panics at construction if it goes too far. frame_larger_than_the_buffer_is_an_error uses BUF_SIZE = 128 with a 504-byte frame to reach RuntimeError::FrameTooLarge legitimately.
BUF_SIZE is a cap: the read buffer starts at 2 KiB and doubles toward it, and the staging buffer starts empty (see The server runtime). Below 2 KiB a test’s buffer is allocated whole, so a test of growth needs a BUF_SIZE above 2 KiB and a frame between the two sizes. a_frame_past_the_first_read_buffer_is_relayed_whole_both_ways (BUF_SIZE = 16384, a 10,000-byte frame up and 12,000 bytes down) and a_datagram_past_the_first_read_buffer_is_delivered_whole (a 4000-byte datagram over a datagram transport) pin growth; a_frame_past_the_grown_buffer_is_still_an_error (BUF_SIZE = 8192, a 9000-byte frame) pins that a buffer grown to its cap still ends in FrameTooLarge. The buffers’ own rules (doubling, make_room, grow_to, a staging buffer that holds nothing until the first stage and never grows past N) are pinned by the inline tests in concepts/src/buffer.rs.
Core tests: CoreHarness
Section titled “Core tests: CoreHarness”CoreHarness drives a server core by hand: it delivers events, collects the effects the core pushes and the bytes it stages, and does no I/O. It lives in the library, not under cfg(test), so both the crate’s own unit tests and downstream crates can use it.
pub const HARNESS_STAGING: usize = 64 * 1024;
pub struct CoreHarness<C: ProxyCoreDecode> { pub core: C, /* private: effects, staging, packets */}
impl<C: ProxyCoreDecode> CoreHarness<C> { pub fn new(core: C) -> Self; pub fn over_datagrams(core: C) -> Self; pub fn event(&mut self, event: Event<'_, C>) -> Result<(usize, Vec<Effect<C>>), C::Error>; pub fn transport(&mut self, data: &mut [u8]) -> Result<(usize, Vec<Effect<C>>), C::Error>; pub fn feed(&mut self, data: &mut [u8]) -> Result<(usize, Vec<Effect<C>>), C::Error>; pub fn outbound( &mut self, key: C::Key, data: &mut [u8], ) -> Result<(usize, Vec<Effect<C>>), C::Error>; pub fn staged(&mut self) -> Vec<u8>; pub fn staged_packets(&mut self) -> Vec<(Vec<u8>, C::TransportAddr)>; pub fn held(&self, range: std::ops::Range<usize>) -> Vec<u8>;}| Method | Behaviour |
|---|---|
new |
Stands in for a stream transport. The staging area is a WriteBuffer<HARNESS_STAGING>, 64 KiB. |
over_datagrams |
Also keeps a PacketList, so the core’s stage_to and put_to work. Use it for cores whose TransportAddr is a peer address. |
event |
Calls core.handle once with a fresh Effects sink, returns the consumed count and every effect pushed, in order. |
transport |
event(Event::Transport(data)): one call, exactly as written. |
feed |
What the runtime does: calls again on the unconsumed tail while the core makes progress, stops when a call consumes 0. Effect::Forward and Effect::SendTo ranges are rebased so they are absolute in data. |
outbound |
event(Event::Outbound { key, data }). |
staged |
Takes everything staged toward the transport so far and clears it. |
staged_packets |
Takes the staged packets, each with its peer, in order. Empty under new. |
held |
Resolves a ForwardHeld range against core.held(), as the runtime would. |
The choice between transport and feed is deliberate. transport tests what a core does with exactly the bytes it was given, which is how header_split_across_events_opens_once_complete (protocols/tests/unit/trojan/core.rs) checks that 30 bytes of a Trojan header consume 0 and arm only the handshake deadline. feed tests the loop the runtime runs, which is what a multi-frame input needs.
Most core test files define two helpers on top of the harness: a constructor such as core(sniff: bool) -> CoreHarness<TrojanCore<()>>, and moves(fx), which drops Effect::SetDeadline so the assertions stay about behaviour. When the deadline is the point, assert on it directly against the named constants: HANDSHAKE_TIMEOUT (10 s), RELAY_IDLE_TIMEOUT (300 s) from protocols/src/core/mod.rs, and SNIFF_TIMEOUT (300 ms) from protocols/src/sniff/mod.rs. A deadline test delivers Event::Deadline through event; no clock is involved.
protocols/tests/unit/core/mod.rs tests the shared pieces the cores compose (Timing, SniffPrefix, Passthrough, PassthroughCore). Most of its tests skip the harness and use a with_sink helper that builds an Effects over a WriteBuffer::<256> and returns the drained effects and staged bytes; the three tests of a sniffing PassthroughCore use CoreHarness.
Pipeline tests: server core against client codec
Section titled “Pipeline tests: server core against client codec”protocols/tests/pipeline.rs puts each protocol’s two halves on opposite ends of a loopback TCP connection: the server core inside a ProxyServerRuntime, the client codec inside a ProxyClientRuntime, and an echo server as the destination. Neither side knows it is talking to its own sibling, so a divergence between them shows as corrupted or missing bytes.
sequenceDiagram participant T as Test participant C as ProxyClientRuntime with codec participant L as serve_runtime listener participant S as ProxyServerRuntime with core participant E as tcp_echo T->>C: client(codec, server addr) C->>L: TCP connect to 127.0.0.1 L->>S: spawn one runtime per accept, make_core() T->>C: write_all(payload) C->>S: handshake header, then sealed frames S->>E: Effect::Open, FreedomConnector dials S->>E: Effect::Forward of decoded bytes E-->>S: echoed bytes S-->>C: frames staged by the core C-->>T: read_exact returns the payload T->>C: shutdown() C-->>T: read_to_end is empty
Helpers in tests/support/pipeline.rs
Section titled “Helpers in tests/support/pipeline.rs”pub struct FreedomConnector;
impl Connector<Flow<()>> for FreedomConnector { type Stream = TcpStream; type Datagram = UdpOutbound; type Future = DialFuture<TcpStream, UdpOutbound>; fn connect(&mut self, flow: Flow<()>) -> Self::Future;}
pub struct TcpConnector;
impl Connector<Destination> for TcpConnector { type Stream = TcpStream; type Datagram = NoDatagram; type Future = DialFuture<TcpStream, NoDatagram>; fn connect(&mut self, dest: Destination) -> Self::Future;}
pub async fn serve_runtime<const BUF: usize, Core, F>(make_core: F) -> SocketAddrwhere Core: ProxyCoreDecode<Target = Flow<()>, TransportAddr = ()> + Send + 'static, Core::Error: fmt::Display, F: Fn() -> Core + Send + Sync + 'static;
pub async fn serve_runtime_over<const BUF: usize, Core, F>( transport: InboundTransport, make_core: F,) -> SocketAddrwhere Core: ProxyCoreDecode<Target = Flow<()>, TransportAddr = ()> + Send + 'static, Core::Error: fmt::Display, F: Fn() -> Core + Send + Sync + 'static;
pub fn client<const BUF: usize, Codec>( codec: Codec, addr: SocketAddr,) -> ProxyClientRuntime<BUF, Codec, TcpConnector>where Codec: ProxyCoreEncodeHandshake<Target = Destination>, Codec::Error: std::error::Error + Send + Sync + 'static;| Helper | Behaviour |
|---|---|
FreedomConnector |
Dials a flow’s destination directly. A UDP flow binds a fresh socket on 127.0.0.1:0; a TCP flow connects, and a TCP flow to a domain fails with Unsupported, so pipeline tests address echo servers by IP. |
TcpConnector |
Dials the proxy under test by address over plain TCP. A domain address fails with Unsupported. |
serve_runtime |
Binds 127.0.0.1:0, then for every accepted connection spawns ProxyServerRuntime::<BUF, Core, _, _>::new(stream, make_core(), FreedomConnector). A runtime that ends with an error prints server runtime ended with … to stderr; the test itself sees the error as bytes that never arrive. |
serve_runtime_over |
The same behind an inbound transport: each accepted connection first goes through transport.accept (a TLS handshake, say), and the runtime runs over the stream it yields. A transport that fails prints transport accept ended with …. |
client |
ProxyClientRuntime::new(codec, &mut TcpConnector, tcp_dest(addr)). The result is AsyncRead + AsyncWrite for a stream codec and a DatagramLink<Addr = Destination> for a datagram codec. |
tests/support/mod.rs adds tcp_echo() and udp_echo() (loopback echo servers on port 0), tcp_dest(addr) and udp_dest(addr) to build a Destination, and self_signed_pem(), a 2048-bit RSA certificate for CN=localhost with a localhost SubjectAltName, valid for 365 days, for TLS transports and DoT/DoH.
The BUF parameter is the core’s own constant, not a guess: TrojanCore::<()>::BUF_SIZE (16 KiB), VlessCore (16 KiB), VMessCore (32 KiB), ShadowsocksCore (20 KiB), Ss2022Core (MAX_RECORD_LEN, 65,569 bytes), HttpCore::<()>::BUF_SIZE (MAX_HEAD, 64 KiB), AnyTlsCore (16 KiB), PassthroughCore (8 KiB). Using the production size keeps the test on the same buffer arithmetic the supervisor runs. SOCKS has no core constant, and its pipeline tests give the client runtime a fixed 16 KiB.
Protocols that do not fit the pattern
Section titled “Protocols that do not fit the pattern”- SOCKS has its own driver rather than a core.
pipeline/socks.rsbuilds each server withserve_inbound(config, sniff), which takes a wholeSocksServerConfig<()>, binds127.0.0.1:0and runsSocksInbound::serve(stream, local_ip, Some(peer.ip()), FreedomConnector)per accepted connection.new_server(auth)andnew_server_with(auth, sniff)pass itconfig(auth): UDP enabled,udp_bindunset, and withauthone account,alice/secret. A TCP test that needs anotherudp_bindpasses its own config toserve_inbound; the Unix-socket test builds itsSocksInbounddirectly. The UDP tests use the kernel’s client,SocksUdpLink::associate; the tests of the association’s source check add a second sender beside it or drive the relay by hand, as described below. - Hysteria 2 runs over QUIC, so
pipeline/hysteria.rsbinds a UDP socket, opens an endpoint on it withHy2Inbound::open, and runsHy2Inbound::run(endpoint, make_connector, token)on a task, handing every connection a clone of the connector (serve). TheNewServerguard aborts that task when it drops, a hard stop: cancelling the token would wait for the clients to leave. It is compiled only with thehysteriafeature, and its helpers (serve,NewServer,client_config) arepub(super)so thatpipeline/hysteria_options.rsreuses them; see Hysteria 2 rates and port hopping. - TUN (
pipeline/tun.rs, featuretun, Unix only) replaces the device with a socketpair: the test injects IP packets it builds withetherparse, reads what the stack answers, and captures the flows the inbound opens with a recording connector. It needs no privilege, and runs onflavor = "multi_thread".an_ipv6_connect_to_an_unreachable_egress_is_refused_at_the_handshakechecks that an IPv6 SYN the gate calls unreachable is refused before the stack answers it, and one it does not is accepted. One test,the_client_sees_fin_after_the_outbound_closes_with_data_in_flight, is#[ignore]until ipstack#89 is fixed upstream. - WireGuard is an outbound, so
pipeline/wireguard.rspoints aWgConnectorat the in-process peer described below and drives a TCP and a UDP flow through it. Two more tests pin what the tunnel does with traffic it cannot deliver:a_stalled_tcp_flow_blocks_its_writer(a flow to a remote that stops reading holds up its writer, a sibling flow still echoes, and the writer resumes once the remote reads again) andan_oversized_datagram_does_not_wedge_the_association(a datagram too big to ever send is dropped, and the next one still echoes). - Transports (
pipeline/transports.rs) serve an echo behind everyInboundTransportkind and dial it with the matchingTransportConnector, including a pinned CA, WebSocket early data and many gRPC streams on one connection. - AnyTLS (
pipeline/anytls.rs) runs its server core behindserve_runtime_overwith a TLS transport. Its client is not a codec but aConnectorwith a session pool,AnyTlsConnector, so the server tests drive the core with a minimal client the file writes from the frame primitives: streams in sequence on one session, UDP over UDP-over-TCP in both request modes, a padding scheme the server pushes, a refused destination, and the session ending over a wrong password or a forbidden frame. Theclientsubmodule then runsAnyTlsConnectoragainst the real server, counting the sessions it dials, and its paused-clock tests (idle sessions closed after the timeout, the newest idle ones kept, a version 2 server that never answers a SYN given up on) run their sessions overtokio::io::duplexpipes instead of sockets, because a paused clock and real sockets do not mix. See AnyTLS. - REALITY (
pipeline/reality.rs, featurereality) puts anInboundTransport::Realityon127.0.0.2in front of a local OpenSSL site standing in for the cover site: a TLS client that is not a REALITY client gets the cover site’s certificate and answer through theDisposition::Camouflagerelay the transport hands back, an unreachable cover site fails the accept, and a bad setting is refused without the error repeating it. See REALITY transport. - sss has no pipeline module. Its codecs, gate and core are unit-tested under
protocols/tests/unit/sss/, wheretransform/chain.rsreplays 1344 byte-exact vectors fromtransform/vectors.tsv, whichvectors.pyregenerates from the specification’s reference model (sss transforms). Its two halves meet insupervisor/tests/sss.rsand the app’se2e_sss.
The SOCKS association tests
Section titled “The SOCKS association tests”Over TCP, a SOCKS5 UDP association hears one client: the IP its control connection came from, compared in canonical form, pinned to one port by the first datagram it forwards, or up front by a request that names that IP with a port (see SOCKS). SocksUdpLink always names an all-zero source, so the tests that need a chosen source, or a second sender, work below it with helpers from pipeline/socks.rs:
| Helper | Behaviour |
|---|---|
associate_raw(control, source) |
Sends a no-authentication greeting and a UDP ASSOCIATE naming source over any AsyncRead + AsyncWrite stream, and returns the server’s Reply. It waits at most 5 s for each read of the reply. |
send_via(socket, relay, target, payload) |
Sends one relay packet for target from a plain UdpSocket. |
recv_via(socket, relay) |
Returns the payload of the next relay packet within 5 s, and asserts it came from relay. |
recording_echo() |
A UDP echo on 127.0.0.1 that reports every payload on an unbounded channel before echoing it; forwarded(&mut seen) drains the channel, so a test asserts exactly what the relay passed on. |
assert_closed(control) |
Expects the server to close the control connection within 5 s, as it does after a refusal. |
A test that sends an unwanted datagram queues it ahead of the client’s, so the relay, which drains its socket in order, meets it first. NOT_ALLOWED is 0x02, the reply to an association the relay cannot hold to its client.
| Test | Pins |
|---|---|
udp_association_ignores_another_ip |
A stranger on 127.0.0.2 that sends before the client’s first datagram, and again after it, is never forwarded, and hears no answer in the 200 ms the test waits |
udp_association_ignores_another_port_once_pinned |
After the first datagram, a second socket on 127.0.0.1 is not forwarded |
udp_association_holds_to_the_port_the_request_names |
A request naming the client socket’s own address and port holds the association to it before any datagram: a neighbour that sends first is not forwarded |
udp_association_sets_aside_a_source_it_cannot_hold_to |
A request naming [::1]:0 for an IPv4 client is granted, and the client relays |
udp_association_is_not_widened_by_the_request |
A request naming a socket on 127.0.0.2 does not admit it; the control connection’s peer still relays |
udp_association_over_a_unix_socket_needs_its_exact_source |
Over a Unix socket, a request naming 0.0.0.0:0 gets 0x02 and a closed connection; one naming the client’s exact address and port relays and shuts out a neighbour |
udp_association_refuses_a_relay_that_cannot_hear_the_client |
With udp_bind = ::1, an IPv4 client’s association gets 0x02 and a closed connection |
udp_link_ignores_datagrams_not_from_the_relay |
The client side: a hand-written server grants the association, then an intruder answers the client’s first datagram ahead of the relay; the link returns only the relay’s reply |
udp_link_on_a_dual_stack_socket_hears_an_ipv4_relay |
SocksUdpLink on a socket bound to [::]:0 accepts the IPv4 relay’s replies, which arrive from its IPv4-mapped address |
The Unix test creates a UnixStream::pair() per association, keeps one end as the control connection and serves the other with serve(stream, None, None, FreedomConnector): no local IP and no peer, under a config with udp_bind set to 127.0.0.1. The tests that bind 127.0.0.2 or a dual-stack socket (udp_association_ignores_another_ip, udp_association_is_not_widened_by_the_request, udp_link_on_a_dual_stack_socket_hears_an_ipv4_relay) are #[cfg(target_os = "linux")], and the Unix test is #[cfg(unix)]. All of 127.0.0.0/8 is loopback on Linux, which is what lets a second sender take 127.0.0.2 without any setup.
The rule itself is also tested without sockets. protocols/tests/unit/socks/server.rs, mounted from protocols/src/socks/server.rs, calls ExpectedSender::new(peer, declared, hub), admits and pin directly: the first pin holds, an IPv4-mapped peer is the IPv4 one, the declared sources a client may send (a loopback of the other family, a LAN address behind NAT, a port with no address, a domain, another host) are set aside, a Unix-socket request must name a non-zero IP address and port, and a relay bound in a family the client cannot reach is an error, while an unspecified IPv6 hub hears both. endpoint_sees_through_ipv4_mapping_and_ignores_flow_info in protocols/tests/unit/socks/protocol.rs pins the comparison both ends use.
Hysteria 2 rates and port hopping
Section titled “Hysteria 2 rates and port hopping”pipeline/hysteria_options.rs builds servers with ServerConfig::new and its own bandwidth and ignore_client_bandwidth, connects this kernel’s client with Hy2Conn::connect, and measures what arrives. upload and download move a fixed number of bytes to a TCP sink or from a TCP source and return the rate the far end saw, from its first byte to its last; assert_near accepts 0.8 to 1.2 times the target.
tests/support/udp_range.rs stands in for a firewall’s port-range rule. PortRange::forward(server, count, path) opens count UDP ports on 127.0.0.1 that all forward to one server, and sends each answer back by the port the client used, as DNAT and its connection tracking do. Path adds a delay each way and a share of packets dropped each way. used() counts the ports that carried a packet from the client, sources() the distinct addresses it sent from, and port_union() renders the ports as upstream writes a port set.
| Test | Pins |
|---|---|
each_end_sends_at_the_rate_the_two_agreed |
A server taking 16 and sending at most 24 Mbit/s, and a client sending at most 40 and taking 32: the server answers its 16, the client sends at 16 and the server at 24 |
ignoring_client_bandwidth_leaves_both_ends_on_congestion_control |
With ignore_client_bandwidth the server answers auto, neither end has a fixed rate, and both directions run far above the declared 8 Mbit/s |
a_client_that_declares_nothing_gets_no_fixed_rate_either_way |
A client with no rates never sends with Brutal, and the server stays on congestion control toward it |
a_client_hops_across_a_forwarded_port_range_with_obfuscation |
A client hopping every 80 to 160 ms across four forwarded ports, under Salamander, keeps a stream and a UDP association echoing for about two seconds and uses at least two ports |
a_fixed_rate_holds_through_a_lossy_path |
A 24 Mbit/s download through 15 ms of delay and 3% downstream loss arrives at 0.75 to 1.2 times its rate, and the connection stays alive |
The app’s e2e_hysteria_options runs the same scenarios against upstream Hysteria in both roles; see What the e2e modules cover. Congestion control and Port hopping describe what these tests measure.
Payload sizes
Section titled “Payload sizes”The stream-core TCP pipeline tests push more than one buffer’s worth through the tunnel, so the relay loops, the staging buffer wraps and backpressure engages: 70 000 bytes for Trojan, VLESS, Shadowsocks and Shadowsocks 2022, 100 000 for VMess, HTTP, SOCKS and PassthroughCore. The transport tests echo 200 000 bytes. The Hysteria 2 TCP tests use short messages and check stream sharing instead.
The UDP tests send a short datagram, then a larger one: 1500 bytes for Trojan and VLESS, 1400 for SOCKS, 4000 for VMess, and 4096 for Hysteria 2, which is above any QUIC datagram size on loopback so both directions fragment. The SOCKS, Trojan, VLESS, VMess and Hysteria 2 UDP tests also assert that the first reply is attributed to the echo server’s address, not only that the bytes match.
The in-process WireGuard peer
Section titled “The in-process WireGuard peer”protocols/tests/support/wireguard.rs runs a complete WireGuard peer inside the test process: a boringtun Tunn bridged to a smoltcp interface that echoes TCP and UDP, plus a TCP sink whose reads the test switches on, TCP servers that close, reset or flood, and a switch that silences the whole peer. No kernel interface, no privilege and no network access are needed.
pub const SERVER_TUN_IP: Ipv4Addr = Ipv4Addr::new(10, 0, 0, 1);pub const CLIENT_TUN_IP: Ipv4Addr = Ipv4Addr::new(10, 0, 0, 2);pub const ECHO_PORT: u16 = 5555;pub const SINK_PORT: u16 = 5556;pub const CLOSE_PORT: u16 = 5557;pub const RESET_PORT: u16 = 5558;pub const FLOOD_PORT: u16 = 5559;
pub async fn spawn_echo_peer( server_priv: [u8; 32], client_pub: [u8; 32], sink_reads: Arc<AtomicBool>, silent: Arc<AtomicBool>,) -> SocketAddr;
pub struct Peer { pub endpoint: SocketAddr, pub client_private: [u8; 32], pub server_public: [u8; 32], pub sink_reads: Arc<AtomicBool>, pub silent: Arc<AtomicBool>,}
pub async fn spawn_peer() -> Peer;sequenceDiagram participant W as WgConnector under test participant U as peer UDP socket participant N as boringtun Tunn participant D as TestDevice rx and tx queues participant S as smoltcp sockets on 10.0.0.1 W->>U: encrypted packet U->>N: decapsulate after zeroing bytes 1 to 3 N->>D: WriteToTunnelV4 pushes to rx D->>S: iface.poll delivers the IP packet S->>S: TCP or UDP echo copies data back, the sink answers nothing S->>D: emitted packets queue on tx D->>N: encapsulate each packet N->>U: WriteToNetwork U->>W: encrypted reply to the last peer address
The loop in spawn_echo_peer does, in order: iface.poll, service the TCP echo listeners, the TCP sink, the close, reset and flood servers and the UDP echo, encrypt everything smoltcp emitted (or discard it while silent), then wait on whichever comes first of a received packet, a 200 ms update_timers tick, or smoltcp’s poll_delay. Details a test author runs into:
| Detail | Value or behaviour |
|---|---|
| Keys | spawn_peer uses the fixed private keys [0x11; 32] (client) and [0x22; 32] (peer) |
| Tunnel address | The peer is SERVER_TUN_IP/24; the client config uses CLIENT_TUN_IP |
| Device MTU | MTU = 1420 |
| Scratch buffers | SCRATCH = 64 KiB for encapsulation and receive |
| Concurrent TCP connections | LISTENERS = 4 echo sockets on ECHO_PORT, each re-armed once its connection closes |
| TCP sink | One socket on SINK_PORT with 64 KiB receive and 64 KiB send buffers. It reads nothing until sink_reads is set, so its receive window closes and the tunnel stops draining a writer to it; once set, it discards whatever arrives. It is re-armed once its connection closes |
| Sink switch | spawn_peer creates sink_reads unset and hands it out as Peer::sink_reads; the peer notices a change within one timer tick (200 ms) |
| Other TCP servers | CLOSE_PORT sends GREETING and closes; RESET_PORT sends PARTIAL, waits for it to be acknowledged and then resets; FLOOD_PORT keeps its 64 KiB send buffer full for as long as the connection lives |
| Silence | While Peer::silent is set, the peer drops every datagram it receives and sends nothing, timer packets included, like a peer that vanished |
| Socket buffers | 64 KiB per TCP direction; UDP 16 packets and 64 KiB per direction |
| Reserved bytes | Bytes 1 to 3 of every received packet longer than 3 bytes are zeroed before decapsulation, so a client configured with reserved bytes still completes the handshake |
| Reply address | The peer answers the address of the last packet it received; before the first packet arrives it sends nothing |
The pipeline’s WireGuard tests dial this peer, and so do the connection-lifetime tests in protocols/tests/unit/wireguard/device.rs, which mount the file as mod peer with a #[path] attribute. The protocols crate’s test support is not part of its library, so app/tests/integration/e2e_wg.rs carries its own copy of the peer: one TCP listener, no UDP echo, no sink, the same keys, MTU and reserved-byte handling. app_socks_to_wireguard_outbound_tcp spawns the real binary with a SOCKS inbound routed to a WireGuard outbound and echoes through that peer.
a_stalled_tcp_flow_blocks_its_writer uses the sink to pin backpressure through the tunnel. It opens a flow to SINK_PORT and writes 1 KiB chunks, each with a 1 s timeout, until one write has to wait. The sink’s 64 KiB window, the client socket’s 64 KiB, the driver’s 256-chunk channel and the one chunk the driver holds come to 385 KiB, and the test fails if the flow accepts more than 512 KiB before its writer waits. A second flow through the same tunnel must then echo within 10 s. After the test sets sink_reads, the write that was waiting must complete within 10 s, and 1024 more chunks within 20 s. an_oversized_datagram_does_not_wedge_the_association sends a 70 000-byte datagram, larger than the 64 KiB send ring the driver gives an association, then a short one, and expects the short one back within 10 s.
The driver’s uplink queue is also tested without a tunnel, in protocols/tests/unit/wireguard/device.rs (mounted from protocols/src/wireguard/device.rs): a_held_item_keeps_the_channel_unread checks that while the driver holds a chunk the socket has no room for, it does not read the channel behind it, so the producer’s try_send fails with Full; the_uplink_finishes_only_after_its_last_item checks that the uplink reports finished only once everything the application sent has been handed on. a_full_downlink_channel_wakes_the_driver_once_it_has_room drives RoomWaits directly, and a_stalled_reader_does_not_keep_the_driver_busy counts the driver’s passes while a reader stalls under a flooding remote. The same file starts devices against the in-process peer, with Lifetimes chosen per test, to pin how the driver ends tunnel TCP connections: an orphan whose remote went silent is aborted after its linger, a reader that leaves a sending remote resets it at once, a remote that vanishes under an idle connection is given up on after the timeout, and keep-alive probes keep a live idle one past it. Session revival is pinned on a paused clock against Revival alone (an_expired_session_in_use_is_revived_every_retry_interval), and end to end by a_tunnel_revives_after_its_peer_was_gone_past_the_handshake_budget, which silences the peer until the session expires. That test is #[ignore]: a session expires only after 90 s of unanswered handshakes, so it takes about 105 s.
REALITY crate tests
Section titled “REALITY crate tests”etemenanki-reality (REALITY overview) is a TLS 1.3 of its own, so most of its tests check it against fixed references rather than against itself. None needs Go or the network: the cover site is the local OpenSSL server of tests/support/dest.rs.
| Level | Where | What it pins |
|---|---|---|
| Reference vectors | tests/unit/tls13/schedule.rs, record.rs, messages.rs; tests/unit/keys.rs; tests/unit/auth.rs |
The key schedule, the protected records and the handshake messages against RFC 8448’s simple 1-RTT handshake, and SHA-384 and ChaCha20-Poly1305, which RFC 8448 does not cover, against OpenSSL’s own HKDF and one-shot AEAD; X25519 against RFC 7748’s key pairs; the auth key and the sealed ClientHello against vectors made with Python’s cryptography, and the temporary certificate against Go’s x509 output, byte for byte |
| Sans-I/O handshakes | tests/unit/server/handshake.rs, tests/unit/client/hello.rs, tests/unit/client/handshake.rs |
Whole handshakes between the server’s pure steps and the support’s TestClient, for every suite, group and flight shape: a reason for each refusal, both key-share rules, the cover site’s ServerHello kept with only the key share replaced, the flight padded to the cover site’s record lengths. The client’s own hello, 200 times over, parses and keeps both key shares. The client refuses a tampered flight, and a server that sends a Finished without the REALITY certificate and its CertificateVerify (a_server_that_proves_no_reality_key_is_never_accepted) |
| Malformed input | tests/unit/tls13/messages.rs, tests/unit/server/handshake.rs |
Every truncation of a ClientHello, then 20,000 copies with one to four bytes changed by the Lcg generator, and 20,000 one-byte mutations of a ServerHello, each parsed or refused without a panic (every_truncation_and_mutation_is_handled_without_panicking, server_hello_mutations_never_panic); a fuzzed Finished never panics either |
| Over sockets and pipes | tests/unit/server/accept.rs, tests/unit/stream.rs, tests/unit/camouflage.rs, tests/server.rs, tests/client.rs |
server::accept on 127.0.0.2 against the local cover site: a client of its own gets a connection with the cover site’s record lengths; a client of another server, with an unknown shortId, or without a required hybrid share meets the cover site; one that never finishes is closed at the handshake timeout. RealityStream over duplex pipes, and the camouflage relay, whose idle end is tested on a paused clock |
Supervisor tests
Section titled “Supervisor tests”The supervisor’s unit tests are pure where the code is. tests/unit/plan.rs and tests/unit/validate.rs build specs and check the steps plan lists and the ApplyError validate returns, with no socket and no task. plan.rs plans each bind of an inbound on its own: an inbound with a handoff socket binds both listeners (an_inbound_with_a_handoff_socket_binds_both_listeners), adding or removing one keeps the TCP listener (adding_or_removing_a_handoff_socket_keeps_the_tcp_listener), a moved one or one with another mode or group is bound anew (a_changed_handoff_socket_is_bound_anew), a removed inbound stops its handoff socket too (a_removed_inbound_stops_its_handoff_socket_too), and one passed to another inbound is kept (a_handoff_socket_passed_to_another_inbound_is_kept). validate.rs pins the handoff rules: beside a stream inbound’s TCP listener only (a_handoff_socket_stands_beside_a_stream_inbounds_tcp_listener), never an inbound’s own bind (a_handoff_bind_is_no_inbounds_own), an absolute path of at most 107 bytes (a_handoff_socket_is_an_absolute_path_a_unix_socket_can_take), a mode of permission bits alone (a_handoff_sockets_mode_is_permission_bits_alone), and one bind per socket path (two_binds_may_not_share_a_socket_path). It also holds every protocol that takes a transport to the same transport rules (every_protocol_meets_the_same_transport_rules), keeps REALITY under VLESS on both sides (reality_is_vless_only, a_reality_outbound_is_vless_only) and a wrapped SOCKS inbound off UDP (socks_relays_udp_over_plain_tcp_only), and checks the AnyTLS rules, a TLS shape on both sides among them (an_anytls_outbound_needs_tls_and_a_password). tests/unit/serve.rs pins that a REALITY connection relayed to the cover site gives its handshake permit back, keeps its live one until the relay ends, tells the ban guard nothing, and ends when its session is closed (a_camouflaged_connection_gives_its_handshake_permit_back). tests/unit/session.rs, track.rs and usage.rs drive the session registry, the pacer and the usage ledger directly; the grace-timer and pacing tests run on #[tokio::test(start_paused = true)], so they assert durations without waiting for them. tests/unit/usage.rs → every_byte_is_taken_exactly_once is a proptest property: random sequences of session opens, transfers, closes, user removals, sampler ticks and takes must report every byte exactly once. tests/unit/session.rs also pins the device limit: a session from one IP too many is refused and closed, an IP frees its slot when its last session ends, and the limit is per user, an absent one admitting any number of IPs. tests/unit/guard.rs drives the guard on a paused clock: an IP is banned at the failure limit and until the ban ends, failures outside the window start a new count, a success clears the count but not a ban, an IPv6 client is counted and banned by its /64 and a success anywhere in that /64 clears its count, an IPv4-mapped address counts as its IPv4 address (an_ipv6_client_is_counted_and_banned_by_its_64, a_success_anywhere_in_the_64_clears_its_count, an_ipv4_mapped_address_counts_as_its_ipv4), a sweep drops what no longer counts, nothing is counted without a ban policy, and a carrier is closed after failed streams in a row. tests/unit/supervisor.rs checks that the speed limits a commit publishes list only the users whose limit changed, and that a listener added beside a kept one gets the kept one’s admission caps, and an inbound with none kept gets caps of its own (an_inbounds_listeners_share_one_set_of_caps). tests/unit/plane.rs → reroutes_compares_where_a_flow_goes_now_with_what_carries_it opens a flow on one blackhole outbound and asks planes built around it whether they reroute it: a plane routing to another tag does, while one with a new version of the same tag, or a balancer that has the flow’s outbound among its members, does not, and a port-53 flow follows the DNS service when the plane has one. tests/unit/ping.rs takes the delay test’s pieces apart with no socket: a URL with the scheme’s default port, a bracketed IPv6 host and a query (a_url_is_taken_apart_with_the_schemes_default_port), the URLs refused (only_http_and_https_urls_with_a_host_are_tested: another scheme, no scheme, credentials), and response heads: the status, whether the connection stays under HTTP/1.1 and HTTP/1.0, a partial head waiting, a 100 Continue skipped, an answer that is not HTTP refused, and the bytes after a head left for the next read. The dev-dependencies carry tokio’s test-util, proptest, criterion and socket2 for these.
The eight end-to-end targets start a real Supervisor on loopback ports and talk to it with minimal clients from tests/support/mod.rs:
| Helper | Behaviour |
|---|---|
start_on(pick, build), start_built(builder, pick, build) |
Start a supervisor on the spec build makes for ports pick chooses, choosing again (up to five times) when ApplyError::Bind says a port was taken between choosing and binding |
base_spec, socks_inbound, http_inbound, vless_inbound, accounts, vless_users, tcp_bind |
Spec pieces |
tcp_echo, udp_echo, echo, closed |
Echo targets, one round trip, and a check that a stream has been closed |
socks_connect, socks_associate, socks_udp_roundtrip, http_connect |
Minimal client sides for the SOCKS and HTTP inbounds |
Mux |
The client end of a VLESS mux session, built from the kernel’s own frame encoders, counting what it sent and received |
QUIET, SOON |
400 ms, how long a test waits for something that should not happen; 5 s, how long it waits for something that should |
| Target | Tests | Proves |
|---|---|---|
hot_swap.rs |
18 | What an apply does to live connections: an unchanged inbound keeps them, a route change reaches the next UDP packet and the next mux sub-flow but not an open TCP flow, close_rerouted then closes only the flows the new routing sends to another outbound while a flow whose rule still names its outbound keeps transferring (close_rerouted_closes_only_the_flows_a_route_change_moves), a changed outbound keeps its old flows unless drained with Close, a drain with CloseAfter closes them once the grace passes, a drain with Close ends a UDP sub-link but not its association, an unchanged Hysteria 2 outbound keeps its QUIC connection, a protocol change on the same port keeps the socket, a refused spec changes nothing, removing a user or an inbound closes only their sessions, a speed-limit change keeps the user’s sessions, a Hysteria 2 obfuscation change needs allow_disruptive, changing a large user set leaves a one-worker runtime free (changing_a_large_user_set_leaves_the_runtime_worker_free), and shutdown neither waits out grace timers nor a stalled Hysteria 2 handshake |
tracking.rs |
7 | What flows and sessions count, killing one mux sub-flow, SOCKS UDP charging, a Hysteria 2 session billing its QUIC connection’s bytes, Hysteria 2 password users, and the usage sink: a batch per interval, the last at shutdown, and a slow sink that does not stall the data plane |
socket_policy.rs |
3 | The host socket policy: direct flows and a SOCKS upstream are dialed on sockets the hook saw, and a refusing hook fails the dial |
guard.rs |
8 | Who a client is: a_proxy_header_names_the_client_and_a_bare_connection_is_its_own, a_users_sessions_come_from_no_more_ips_than_their_device_limit, an_ip_failing_to_authenticate_is_turned_away_and_others_are_not, a_grpc_connection_whose_streams_keep_failing_is_closed, and, over a WebSocket client whose upgrade carries the header a proxy would add, a_trusted_proxys_forwarded_header_names_the_websocket_client, a_forwarded_header_from_anyone_untrusted_is_ignored, the_device_limit_counts_the_forwarded_client and a_forwarded_client_failing_to_authenticate_is_banned_and_others_are_not |
handoff.rs |
10 | Connections a relay on the same host hands over, sent as a real sendmsg with SCM_RIGHTS: served with the client the PROXY header names, a LOCAL header leaving the socket’s own peer, beside the TCP listener (a_handed_over_connection_is_served_with_the_client_its_header_names); no descriptor, two, a UDP, Unix or listening socket, bytes after the header, one byte after a header of the full MAX_V2_LEN, and a malformed or short header each answered 0x01, with the connection still the relay’s and working (a_malformed_handoff_is_refused_and_the_connection_stays_the_relays); the client the header names banned after failed authentications (a_handed_over_client_failing_to_authenticate_is_banned); TLS, gRPC and VMess over a handed-over socket (tls_grpc_and_vmess_run_over_a_handed_over_connection); a reload adding, moving, changing the mode of and removing the socket while every connection lives on (a_reload_adds_moves_and_removes_a_handoff_socket_and_keeps_the_tcp_listener); the directory and socket modes and group, a stale socket taken over, and any other file at the path refusing the start (a_handoff_socket_takes_over_a_stale_file_and_is_set_up_as_asked); a refused apply leaving a running handoff socket at its path with its old mode, whether a later bind refuses it (a_refused_apply_keeps_a_running_handoff_socket_at_its_path) or the regroup’s own chown does (a_regroup_whose_chown_is_refused_keeps_the_running_handoff_socket, skipped as root or in group 0); two Unix inbounds in one directory, at paths that differ in their last byte or with one a dot-file beside the other, each served at its own path by its own inbound (unix_binds_whose_staging_names_could_meet_are_each_served_at_their_path); and a running Unix socket named as a dot-file left in place by a refused apply (a_refused_apply_leaves_a_running_socket_that_looks_staged_in_place). The refusal tests list the directory afterwards, so a staged file left behind fails them. Its socket paths sit under std::env::temp_dir(), in a directory named for the process and the test |
anytls.rs |
6 | AnyTLS through a supervisor, with a client written from the frame primitives: the streams of one session count exactly toward its user (streams_of_one_session_count_exactly_toward_its_user), a wrong password counts toward the IP ban, removing the user ends the session and every stream, and a padding-scheme change leaves live sessions on the scheme they started with; then one supervisor’s AnyTLS outbound carries TCP and UDP to another’s AnyTLS inbound, and with a wrong password carries nothing |
sss.rs |
6 | sss between two supervisors: an sss outbound carries TCP and UDP to an sss inbound under transform chains, the user is charged sss bytes rather than what the transforms put on the wire (the_user_is_charged_sss_bytes_not_what_the_transforms_send), mismatched chains carry nothing, a probe is drained in silence or handed to the fallback, and validation refuses bad limits |
ping.rs |
4 | Supervisor::http_ping against local HTTP servers, under a routing that sends everything to block: the delay is the second of two requests on one connection, and the test is no tracked flow (the_delay_is_the_second_request_on_the_first_ones_connection); a site that answers Connection: close leaves the first request’s time, with unified false; a blackhole outbound, a site that never answers (a Timeout within the timeout plus a second), an unknown tag and an ftp:// URL each fail with their own PingError (failures_say_why_and_never_outlast_the_timeout); and HTTPS to a server that does not speak TLS fails as Tls |
One hot_swap.rs test creates a TUN device and needs CAP_NET_ADMIN: when the supervisor cannot create one it prints skipping: cannot create a tun device here: <error> and returns. None of the supervisor’s tests need Go: its Hysteria 2 peers are the kernel’s own client and server.
App end-to-end tests
Section titled “App end-to-end tests”app/tests/integration.rs spawns the real etemenanki-app binary. Cargo builds the binary before an integration target of the same package and exposes its path as CARGO_BIN_EXE_etemenanki-app; the tests never look in target/ themselves.
Support in app/tests/support/mod.rs
Section titled “Support in app/tests/support/mod.rs”pub struct Proc(Child);
impl Drop for Proc { fn drop(&mut self); }
impl Proc { pub fn id(&self) -> u32; #[cfg(unix)] pub fn terminate(mut self); #[cfg(not(unix))] pub fn terminate(self);}
pub fn spawn_app(dir: &Path, config: &str) -> Proc;pub fn spawn_xray(bin: &Path, dir: &Path, config: &str) -> Proc;pub fn spawn_hysteria(bin: &Path, dir: &Path, config: &str) -> Proc;pub fn spawn_hysteria_client(bin: &Path, dir: &Path, config: &str) -> Proc;pub fn spawn_singbox(bin: &Path, dir: &Path, config: &str) -> Proc;
pub static XRAY_BIN: LazyLock<Option<PathBuf>>;pub static HYSTERIA_BIN: LazyLock<Option<PathBuf>>;pub static SINGBOX_BIN: LazyLock<Option<PathBuf>>;
pub const SPARE_LOOPBACK: Ipv4Addr;
pub fn free_port() -> u16;pub fn free_port_on(ip: Ipv4Addr) -> u16;pub fn free_udp_port() -> u16;pub async fn wait_port(port: u16) -> io::Result<()>;pub async fn wait_addr(addr: SocketAddr) -> io::Result<()>;pub async fn wait_udp_port(port: u16) -> io::Result<()>;pub fn test_dir(name: &str) -> PathBuf;| Helper | Behaviour |
|---|---|
Proc |
Owns a child process. Drop kills it and waits, so a failed assertion never leaves a listener running into the next test. terminate sends SIGTERM through kill -TERM, waits up to 10 s for exit, and leaves the rest to Drop; use it when what the process does on the way out is under test (e2e_unix checks the socket file is removed, e2e_tun that the routed address stops answering). Off Unix there is no SIGTERM to send, and terminate leaves the child to Drop. |
spawn_app |
Runs the binary with -c <config> in dir, stdout and stderr discarded. |
test_dir |
<run>/<name>, created if missing, where <run> is the test process’s own directory, CARGO_TARGET_TMPDIR/runs/<pid>/, or <pid>.<n> when that id is taken (app/tests/support/runs.rs), so concurrent cargo test runs in one checkout never share one. Configs and certificates go here, and the upstream binaries are built here. The process holds an exclusive lock on runs/<id>.lock until it exits, and a run starting removes every run whose lock it can take, its directory first and the lock last; claims take turns under runs/.claim.lock. Nothing is removed while its run lives, so a helper may hand a directory to a process it spawns and keep nothing alive for it. The last run’s directories, and a failing config among them, stay until the next app test run starts in the same checkout. |
SPARE_LOOPBACK |
127.0.0.2, where no server of the app tests listens unless a test puts one there. free_port hands its port back before the process meant for it binds it, so on 127.0.0.1 another test’s server may take it next. A test that asserts nothing answers on a port it released listens on the spare address instead: the node of a_switch_sends_new_flows_of_the_group_through_the_new_target and the upstream client’s SOCKS listener in a_wrong_credential_never_gets_a_proxy. The AnyTLS servers of e2e_singbox_anytls and the stand-in cover site of e2e_xray_reality listen there too. Linux routes all of 127.0.0.0/8 to loopback. |
free_port, free_port_on |
free_port_on(ip) binds TCP port 0 on ip and returns the port after closing the socket; free_port is free_port_on(127.0.0.1). |
free_udp_port |
The same for UDP. TCP and UDP port spaces are independent, so a QUIC listener must use this one. |
wait_port, wait_addr |
wait_addr(addr) connects to addr every 50 ms for up to 20 s; wait_port is wait_addr(127.0.0.1:<port>). |
wait_udp_port |
Binds the port every 50 ms for up to 20 s and returns once the bind fails with AddrInUse, because a UDP listener cannot be probed by connecting. Any other bind error is returned at once. |
socks5_roundtrip, socks5_roundtrip_over, socks5_roundtrip_domain, socks5_connect, Socks5Udp |
A hand-written SOCKS5 client (no authentication, IPv4 or domain targets), independent of the kernel’s own codec. socks5_roundtrip_over runs over an already-open stream such as a Unix socket, and socks5_connect returns the stream after the CONNECT for a test that moves its own bytes. Socks5Udp keeps the control connection open for the association’s lifetime and returns each reply with the address the SOCKS header attributes it to. |
udp_echo, tagged |
A UDP echo whose reply is prefixed with the echo server’s own port, so a test can tell which peer received a packet apart from which peer the reply was attributed to. |
self_signed_pem, self_signed_pem_san, write_certs, write_certs_san, pinned_hash |
Certificates. The Xray tests pin the CN-only certificate by SHA-256 (pinnedPeerCertSha256); the Hysteria tests need a SubjectAltName because rustls rejects a CN-only leaf. |
real_client_hello |
A ClientHello produced by OpenSSL for a given SNI, for sniffing tests. |
fake_dns |
A UDP DNS server that answers an A query for one name with 127.0.0.1 and everything else with NXDOMAIN. |
udp_range |
protocols/tests/support/udp_range.rs, mounted with #[path]: the port-range forwarder of Hysteria 2 rates and port hopping. |
Upstream binaries built with Go
Section titled “Upstream binaries built with Go”The interop tests run the reference implementations, built from the Xray-core, hysteria and sing-box submodules of the Etemenanki repository. Xray-core is at its v26.10.17 release and sing-box at v1.14.3. Each binary is built once per test binary, on first use, through a LazyLock. The build writes it into the run’s own directory, and install then renames it to its place under CARGO_TARGET_TMPDIR: a rename swaps the file whole, so a process another run already started keeps the file it started from. When the rename fails, the run uses its own copy:
| Static | Command | Working directory | Output |
|---|---|---|---|
XRAY_BIN |
go build -o <run>/xray ./main |
Xray-core |
CARGO_TARGET_TMPDIR/xray |
HYSTERIA_BIN |
go build -o <run>/hysteria . |
hysteria/app (the repository is a Go workspace; main sits at the root of the app module) |
CARGO_TARGET_TMPDIR/hysteria |
SINGBOX_BIN |
go build -o <run>/sing-box ./cmd/sing-box |
sing-box (the default build, whose protocol set includes AnyTLS) |
CARGO_TARGET_TMPDIR/sing-box |
Xray-core v26.10.17 declares Go 1.27 in its go.mod. An older go fetches that toolchain itself when GOTOOLCHAIN is auto, which needs network access; otherwise the build fails and every Xray test skips. katana’s support builds only Xray and Hysteria.
flowchart TD
A["first use of XRAY_BIN, HYSTERIA_BIN or SINGBOX_BIN"] --> K{"katana only: sibling source dir exists?"}
K -- no --> S["print SKIP line, value is None"]
K -- yes --> G{"go version succeeds?"}
G -- no --> S
G -- yes --> B["go build: the app into its run directory, katana into CARGO_TARGET_TMPDIR/name"]
B -- fails --> S
B -- succeeds --> I["app only: rename into CARGO_TARGET_TMPDIR/name, or keep the run's copy"]
I --> R["Some(path): the test runs"]
S --> P["each test returns early and passes"]
A test, or the shared helper it calls, starts with let Some(xray) = XRAY_BIN.as_ref() else { return; }; (run_app_client and run_app_server in e2e_xray.rs; app_client and singbox_client in e2e_singbox_anytls.rs do the same with SINGBOX_BIN), returns when XRAY_BIN.is_none() (e2e_xray_reality.rs), or uses ? inside a helper that returns Option (start in e2e_xray_mux.rs). A machine without Go, or with the submodules not checked out, therefore runs the suite green without exercising any interop. In the app’s support, a submodule directory that does not exist at all makes the build return None without printing a SKIP line. go build also needs the Go modules the reference trees depend on, from the module cache or the network, and a failed build is a skip too. Before trusting a green run, install Go and run git submodule update --init in the Etemenanki repository.
What the e2e modules cover
Section titled “What the e2e modules cover”| Module | Upstream | Proves |
|---|---|---|
e2e_xray |
Xray | VLESS over WebSocket and gRPC, each plain and with TLS, and over TCP with TLS, in both roles (app as client, app as server) |
e2e_xray_vmess |
Xray | VMess over gRPC with TLS (app as server), and WebSocket early data without TLS in both roles |
e2e_xray_mux |
Xray | mux.cool against VLESS, VMess and Trojan servers, concurrent sub-streams, XUDP, reply attribution |
e2e_xray_reality |
Xray | VLESS over REALITY in both roles, with a local OpenSSL server on 127.0.0.2 as the cover site: an Xray client through the app’s inbound and the app’s client to an Xray server, exact bytes each way; an Xray client with a wrong shortId or public key, and the app’s client with a wrong key, never get through; a plain TLS probe of the app’s inbound gets the cover site’s own certificate; flow = "xtls-rprx-vision" in both roles; an inner TLS 1.3 session through the tunnel, which makes both ends switch to the raw socket (vision_splices_inner_tls_xray_client_to_our_server, vision_splices_inner_tls_our_client_to_xray_server); and SOCKS UDP under Vision, which rides XUDP, to two UDP echoes in turn with each reply attributed to its peer: from the app’s client to the app’s server (our_vision_client_carries_udp_to_our_server, which needs no Go), to an Xray server (our_vision_client_carries_udp_to_an_xray_server), and from Xray’s client to the app’s server (xray_vision_client_carries_udp_to_our_server). See VLESS Vision |
e2e_xray_wrapped |
Xray | Shadowsocks over gRPC, Shadowsocks over WebSocket with TLS, Shadowsocks 2022 with a user over gRPC with TLS, and SOCKS5 and HTTP over TLS with credentials, each in both roles |
e2e_singbox_anytls |
sing-box | AnyTLS in both roles: TCP echoes of 43 bytes to 300,000 bytes, then two flows at once, which takes a second session, and UDP over UDP-over-TCP, under the default padding scheme and under a custom one the server pushes. The AnyTLS servers listen on 127.0.0.2 |
e2e_hysteria |
Hysteria server | This kernel’s Hysteria 2 client: several proxy streams after one authentication, a private CA, a refused password, half-close (the upstream server ends a stream its client half-closed, so a target that answers only after end of file is never relayed back, and the stream ends cleanly with no reply), Salamander, UDP fragmentation, and the app’s SOCKS entry into a hysteria2 outbound |
e2e_hysteria_inbound |
Hysteria client | This kernel’s Hysteria 2 inbound: TCP and UDP, large datagrams fragmented both ways, obfuscation, username and password credentials, a wrong credential, and a reload that keeps the inbound serving on its UDP port (a_reload_keeps_the_inbound_serving_on_its_udp_port) |
e2e_hysteria_options |
Hysteria client and server | Hysteria 2’s rates and port hopping against upstream: a real client and this kernel’s inbound send at the rates they agreed, keep their rate through loss and hop across a forwarded range; this kernel’s client and a real server agree on rates while hopping; a real server with ignoreClientBandwidth answers auto; and the app on both ends, configured from TOML alone, agrees on rates and hops, a test that needs no Go. Each sender is measured across a path with 15 ms of delay each way |
e2e_sniff |
Xray client | A sniffed HTTP Host or TLS SNI routes an IP-addressed flow by a domain rule, and turning sniffing off stops it |
e2e_udp_route, e2e_route_context, e2e_dns, e2e_balancer, e2e_unix |
none | Routing per UDP packet, inbound_tag, source_cidr and network matchers, the DNS backend, balancer failover, Unix-socket listeners; the app’s own SOCKS inbound produces the traffic, so these run without Go |
e2e_reload |
none | What a reload does to open connections: an_open_connection_keeps_transferring_across_a_reload, and a_reload_that_removes_a_user_closes_only_their_connections. Each test waits until a new connection shows the new config took effect before it looks at the open one. |
e2e_api |
none | The REST API, observed on traffic: a_switch_sends_new_flows_of_the_group_through_the_new_target, the_api_follows_the_api_section_across_reloads, and, on Linux only, a_config_without_api_binds_nothing_new |
e2e_sss |
none | sss between two app processes configured from TOML, over plain TCP, WebSocket and TLS, carrying TCP and UDP with different chains each way, and a probe that is not sss handed to the server’s fallback. No other implementation speaks sss; the transforms’ match with the reference model is the vector test in protocols. Needs no Go |
e2e_wg |
in-process peer | The WireGuard outbound through the real binary |
e2e_tun |
kernel TUN device | A tun inbound answers a routed connect, and the route disappears with the process |
sequenceDiagram participant T as Test participant X as xray server participant A as etemenanki-app participant E as tcp_echo T->>T: XRAY_BIN built on first use T->>X: spawn_xray with xray.json in test_dir T->>A: spawn_app with app.toml T->>X: wait_port(xray_port) T->>A: wait_port(socks_port) T->>A: SOCKS5 CONNECT to echo, then payload A->>X: VLESS over ws, gRPC or TLS X->>E: freedom E-->>T: echo returns along the same path T->>T: assert exact bytes within 15 s
Privileged and live tests
Section titled “Privileged and live tests”e2e_tun compiles only on Linux (#![cfg(all(unix, target_os = "linux"))]), and its one test, a_routed_connect_is_answered_while_the_app_runs, needs CAP_NET_ADMIN. Its can_create_a_device opens a TUN device itself first; on PermissionDenied it prints SKIP: cannot create a tun device: … and returns, and on any other error it panics. The module comment gives the command to run it with privilege: sudo -E cargo test -p etemenanki-app --test integration e2e_tun.
e2e_wg::wireguard_outbound_live_env_tcp is #[ignore] and talks to a real WireGuard peer over the network. It reads ETEMENANKI_WG_PRIVATE_KEY, ETEMENANKI_WG_PEER_PUBLIC_KEY, ETEMENANKI_WG_ENDPOINT and ETEMENANKI_WG_ADDRESS (required), and ETEMENANKI_WG_MTU, ETEMENANKI_WG_KEEPALIVE, ETEMENANKI_WG_RESERVED (exactly three comma-separated bytes), ETEMENANKI_WG_TEST_TARGET (an IPv4 socket address) and ETEMENANKI_WG_TEST_HOST (optional). A missing required variable panics with missing <name>; run this ignored test with real WG settings. It passes when an HTTP request through the tunnel gets a response starting with HTTP/ within 20 s.
webclient, ffi and subscribe tests
Section titled “webclient, ffi and subscribe tests”webclient/tests/tracking.rsruns a real supervisor with a SOCKS inbound and drives the REST router in-process withtower::ServiceExt::oneshot, no socket in between. ANoConfigstub implementsConfigControland answers every config call with an error, because the config side is not what these tests are about. Five tests list live sessions and flows, delete one flow alone, delete by selector, and stream the traffic and connection events. The other two run onswitchable, a supervisor with ablockoutbound besidedirectand aSpecControlwhose route switch points the spec’s default route at the target and whose reload applies that spec:a_route_switch_closes_what_it_moved_only_when_askedswitches withoutcloseand the live flow keeps echoing with noclosedin the report, then switches withcloseto the outbound the flow is already on (closed0) and toblock(closed1, the flow closed);delay_tests_a_named_outbound_and_says_why_it_failedgets200withstatus,handshake_ms,delay_msandunifiedfrom a local site throughdirect,502withkindhttporconnectthroughblock,504withkindtimeoutfrom a silent listener undertimeout=200,404for an unknown tag, and400for anftp://URL and for an unknown query field.ffi/tests/proxy.rsruns the mobile library as an app would. The TUN device is one end of a datagramsocketpair(UnixDatagram): one packet per read and write, as a real TUN descriptor delivers. The test calls it the way the bindings do: synchronous methods from the test’s thread, and async ones throughfutures::executor::block_on, an executor that is not tokio. ARecorderimplementsPlatform. Its seven tests carry TCP and UDP from the device to the outbound, refuse a server inbound, serve only a local SOCKS inbound, switch routes and reload as the REST API does (a switch closes nothing unless asked), close the connection a reload moved to another outbound, and that one only once (close_rerouted_closes_what_a_reload_moved), time a delay test through a named outbound and report an unknown one as a result with anerrorrather than a failed call (http_ping_times_the_second_request_through_the_named_outbound), and return a panic as an error instead of unwinding across the boundary.ffi/tests/inspect.rscovers the calls that need no running proxy, each against what the engine itself does with the same files. Its nine tests runinspect_subscribeonsubscribe/example-subscribe.toml(whose REALITY node with the Vision flow, AnyTLS node and sss node it checks by protocol, transport, TLS and flow) and on small files of their own (a system resolver is reported, a file without[dns]has noresolve_ipv6, an unparsable file is a config error, rule groups match the engine’s own rules), runcheck_configon a client config, a server inbound and an unknown subscribe key, and check the picksroute_viewreports. Likeproxy.rs, it is#![cfg(unix)].ffi/tests/convert.rscoversconvert_subscriptionandwithout_geo, and checks every file they produce withcheck_config, asProxy::startwould. Its seven tests convert a mihomo profile of three nodes (every node kept, a node whose entry leaves UDP off reported as changed in a line that cites no source file, and the routes taken from the conversion template, never from the profile’s own groups and rules), read share links plain or as base64 into the same file, convert the links the apps write for an AnyTLS node, a VLESS node over REALITY with and without Vision, and sss nodes, one at a time and together (anytls_reality_and_vision_links_are_written,sss_links_are_written), take an Etemenanki subscribe file unchanged, refuse input with no node the engine can run withFfiError::Config, and check thatwithout_geokeeps every route group and every matcher butgeositeandgeoip, on the example file and on a converted one. It is#![cfg(unix)]too.subscribe/tests/unit/subscribe.rs, mounted fromsubscribe/src/lib.rs, parses the subscribe schema.
Benchmarks
Section titled “Benchmarks”Two criterion benches ship with the workspace. They are compiled by the clippy gate’s --all-targets but run only on request:
cargo bench -p etemenanki-supervisor --bench trackingcargo bench -p etemenanki-protocols --bench vmess_users| Bench | Measures |
|---|---|
supervisor/benches/tracking.rs |
A usage take and the reconcile that feeds it, over a ledger of 50,000 active users; the per-byte cost a metered flow adds to a relay (256 MiB in 16 KiB reads, untracked against metered); and the same with 16 flows per worker on one outbound version relaying 1 GiB together, in 1 KiB and 16 KiB reads |
protocols/benches/vmess_users.rs |
Matching a VMess auth id against configured user lists of 1,000, 10,000, 100,000 and 1,000,000 users, in two groups: an auth id no user owns, which leaves the validator as it was; and the last user’s auth id, from an address that user has already matched from, so the address hint names it first. The second group’s id has been seen, so the replay check refuses it after the match, which again leaves the validator as it was |
The figures they print are lab numbers from the machine that runs them.
katana tests
Section titled “katana tests”katana is a binary crate. All of its unit tests, including the in-process end-to-end suite, compile into the katana binary’s test harness; the integration target spawns the built binary as CARGO_BIN_EXE_katana. katana’s dev-dependencies enable tokio’s test-util and a vendored openssl for certificate generation. Metering, speed limits and connection deadlines are the supervisor’s, and are tested in its suites.
Unit tests
Section titled “Unit tests”| File | Mounted in | Covers |
|---|---|---|
tests/unit/api/newv2board.rs, tests/unit/api/helium.rs |
src/api/… |
Panel response parsing and push body shape; for newV2board, a user’s device_limit given as a number, null or left out (a_users_device_limit_may_be_a_number_null_or_absent), a rebuilt client keeping the block routes of the client it replaces until it reads the node config itself (a_rebuilt_client_keeps_the_routes_it_has_not_read); for parse_node_config in src/api/newv2board.rs, which converts a UniProxy answer into the contract’s node config, each node type’s body read into its node (parse_v2ray_ws_tls, where a WebSocket path left out is / and an empty Host is none, parse_trojan_fixed, shadowsocks_reads_its_transport, parse_anytls_keeps_the_padding_scheme, parse_socks_and_http_read_their_transport_over_tls, the_new_node_type_names_parse), the bodies helium’s node API v1 sent for each of them, a REALITY node’s tls_settings, read on a REALITY node only and decoded as the kernel reads them (parse_v2ray_reality_takes_its_tls_settings), a panel’s protocol tag checked against the node’s type (the_panels_protocol_tag_must_match_the_node), an sss node refused when its client is built (an_sss_node_is_refused), and each refusal, its reason in the error’s own message: REALITY settings that are wrong, refused without repeating a key or shortId, and REALITY over WebSocket or on VMess (a_reality_node_with_bad_settings_is_refused_without_repeating_them), a flow other than Vision, a flow off VLESS and Vision without REALITY (only_vision_and_only_on_vless), a cipher the kernel does not know, a Shadowsocks 2022 key that is not base64 or too short, and an obfs (shadowsocks_ciphers_and_keys, which also reads every legacy cipher by each name the kernel knows it by, and a 2022 key as the kernel reads one), httpupgrade, splithttp, xhttp and any other transport (a_transport_katana_cannot_serve_is_refused), a TCP header other than none, on REALITY too, while none, null, one without a type or with type null, and "none" in any case are bare TCP (a_tcp_header_other_than_none_is_refused), a server_port outside 1 to 65535 (a_port_outside_one_to_65535_is_refused), and a body that is not a UniProxy config, with a value of the wrong type never quoted (a_malformed_body_is_refused_without_quoting_it); and a Hysteria 2 node completed with [node.hysteria]’s UDP relay, masquerade and rate overrides, the panel’s obfuscation held to the rules the local block’s are (a_hysteria_node_is_completed_with_the_local_block); for helium’s node API v2, the node named in the request path (the_node_is_named_in_the_path), the config answer reaching lowering as Helium wrote it, and one that breaks a rule of the contract refused with the rule in the error’s own message and no key in it (the_node_config_is_the_contracts_as_helium_wrote_it), every protocol Helium writes read into a node (every_protocol_helium_writes_is_read), users held to the answer’s limits, an answer without them refused, and the local speed override winning (users_are_held_to_the_answers_limits, an_answer_without_limits_is_refused, the_local_speed_override_wins), the report body in the crate’s wire form, with a uid outside i32 or a negative count left out (the_report_body_is_the_crates_wire_form, an_out_of_range_uid_or_a_negative_count_is_left_out), the audit rules being the local list alone (the_audit_rules_are_the_local_list), and every local key the panel describes refused by name (local_keys_the_panel_describes_are_refused) |
tests/unit/api/http.rs |
src/api/mod.rs |
The panel HTTP client: against a TLS panel the test starts on loopback, which asks every client for a certificate and answers whether it was given one, a client built with enable_mtls on presents one and a client built with it off presents none (a_panel_that_asks_is_given_the_certificate_under_mtls_only); and against a panel that compresses its answer for a client that accepts gzip and answers 406 Not Acceptable to one that does not, the client is answered, keeps the weak ETag W/"7" as it came, and reads the decompressed JSON (a_panel_answer_is_asked_for_and_read_gzip_compressed) |
tests/unit/lower/inbound.rs |
src/lower/inbound.rs |
A contract node lowered into an InboundSpec: VLESS (a_vless_node_lowers_vless), the VMess clock check, on unless the node turns it off (vmess_checks_the_clock_unless_the_node_turns_it_off), a REALITY node lowered to its server spec, with Vision or without (a_reality_node_lowers_to_its_server_spec), Shadowsocks 2022 and each user’s key (ss2022_builds), Shadowsocks, legacy or 2022, on the panel’s transport (shadowsocks_rides_the_panels_transport), each legacy cipher the kernel’s of the same name (every_legacy_cipher_lowers_to_the_kernels), AnyTLS over TLS with its padding scheme (an_anytls_node_is_tls_with_its_padding_scheme), SOCKS and HTTP over TLS on any transport, relaying no UDP (socks_and_http_nodes_are_tls_and_relay_no_udp), their users’ credentials taken from the UUID (anytls_socks_and_http_users_are_their_uuid), and an sss node’s chains, limits and defaults, a chain it cannot parse refused, and its users’ UUIDs (an_sss_node_lowers_its_chains_and_limits, an_sss_node_defaults_to_identity_and_draining, an_sss_node_refuses_a_chain_it_cannot_parse, sss_users_are_their_uuid); this host’s settings judged and refused by name: an ACME cert mode, a TLS node without its files and reject_unknown_sni (acme_cert_mode_rejected, tls_without_cert_file_errors, reject_unknown_sni_is_refused_rather_than_ignored), and, for a Hysteria 2 node api::hysteria::local reads from [node.hysteria], the block’s refusals (obfuscation, the UDP idle timeout, a masquerade that says authenticated), the certificate it needs, its credential kind and congestion control (hysteria_refuses_an_unknown_congestion_control among them), and a panel’s masquerade the kernel cannot answer with refused before the certificate is read (a_panels_masquerade_the_kernel_cannot_answer_with_is_refused); bind_host (the_default_listen_ip_binds_both_families_where_the_host_can, any_other_listen_ip_binds_as_written); the real-IP keys: lowered for a WebSocket node only (a_websocket_node_takes_its_client_from_a_trusted_proxys_header), half a setting or a typo in one refused (half_a_real_ip_setting_or_a_typo_in_one_is_refused); and the handoff keys: a stream node’s socket named for its port (a_stream_node_takes_handed_over_connections_on_a_socket_named_for_its_port), and for its address too when listen_ip is one address, so nodes on one port and different addresses get different paths (a_node_on_one_address_names_its_handoff_socket_for_it), none for a Hysteria 2 node (a_hysteria_node_takes_no_handed_over_connections), a setting the relay could not use refused, a handoff_dir too long for the node’s longest socket name among them (a_handoff_setting_the_relay_could_not_use_is_refused), and a group found in /etc/group text by its whole name only (a_group_is_found_by_its_whole_name) |
tests/unit/lower/outbound.rs |
src/lower/outbound.rs |
The process-wide [[outbound]] entries lowered into specs, including WireGuard’s endpoint_address_family, a bracketed IPv6 literal read as the server’s address and kept in a WireGuard endpoint (a_bracketed_ipv6_server_is_an_address, a_wireguard_endpoint_takes_a_bracketed_ipv6_server), and a malformed UUID refused without echoing it (a_malformed_uuid_is_refused_without_echoing_it) |
tests/unit/lower/spec.rs |
src/lower/mod.rs |
A user held to their own speed limit, which the panel clients have already replaced with the local speed_limit where one is set (a_user_is_held_to_their_speed_limit), a shared credential admitting only its first user, audit rules routed first to one blackhole per rule id, the reserved audit# tag, the device limit and IP ban only under enable_device_limit while the gRPC failure count holds either way, 0 turning the IP ban and the gRPC close off (zero_turns_the_ip_ban_and_the_grpc_close_off), a large user list lowered without a quadratic duplicate check (lowering_a_large_list_is_not_quadratic), and the node check refusing half a real-IP setting whatever the node type (the_node_check_refuses_a_half_real_ip_setting) or a handoff setting the relay could not use (the_node_check_refuses_a_handoff_setting_the_relay_could_not_use), every node kind added in 4.9.0 and 4.10.0, legacy Shadowsocks over WebSocket and TLS, Shadowsocks 2022, and a Hysteria 2 node as helium describes it, lowered to a spec the supervisor’s own validation accepts (the_new_node_kinds_pass_the_supervisors_validation), a node’s Hysteria 2 UDP relay and masquerade reaching the listener whatever [node.hysteria] says, and a UniProxy node’s read from [node.hysteria] by api::hysteria::uniproxy (the_nodes_hysteria_udp_and_masquerade_reach_the_spec), and the check of a helium node, which builds no inbound, judging its [node.hysteria] congestion (a_helium_nodes_check_judges_its_congestion_control) |
tests/unit/manager/node.rs |
src/manager/node.rs |
Lowering off the runtime: a task ticking beside it on a one-worker runtime keeps ticking (lowering_leaves_the_runtime_worker_free); turning the VMess clock check off changes the spec (turning_the_vmess_clock_check_off_changes_the_spec); a spec equal to the running one comes back unchanged unless forced (a_spec_equal_to_the_running_one_is_unchanged_unless_forced); which node changes drop every connection (only_a_disruptive_change_drops_every_connection): an AnyTLS padding scheme, a Hysteria 2 node’s rates and its UDP idle timeout do not, while relaying UDP or not, the obfuscation password, the port, the masquerade, the transport and sss’s chains do; and, on a node the test starts on a loopback port with a panel it cannot reach, a reload of the real-IP keys alone or of the handoff keys alone applied at once (a_reload_of_the_real_ip_keys_alone_applies_at_once, a_reload_of_the_handoff_keys_alone_applies_at_once, which also checks the socket file appears and is gone once the key is dropped and the supervisor shut down), and a reload of enable_mtls alone giving the node a new panel client, where an edit to nothing the client is built from keeps it (a_reload_of_enable_mtls_alone_rebuilds_the_client) |
tests/unit/rule.rs |
src/rule.rs |
Audit rule updates: the same ids and pattern sources are not a change (update_skips_identical_ruleset) |
tests/unit/runtime.rs |
src/runtime.rs |
Reload identity and apply_reload decisions against running nodes (see Reload tests), the warning for a WireGuard outbound several nodes route to, the real-IP and handoff keys parsed with a typo in them refused (the_real_ip_keys_parse_and_a_typo_in_them_is_refused, the_handoff_keys_parse_and_a_typo_in_them_is_refused), and enable_mtls on unless a node turns it off (enable_mtls_is_on_unless_turned_off) |
katana has no paused-clock test at 6.1.0; the pacing and grace tests it relies on are the supervisor’s (supervisor/tests/unit/track.rs, session.rs). The kernel’s own deadlines are pinned the same way: deadline_event_lets_the_core_time_out and deadline_is_armed_against_the_tokio_clock in concepts/tests/runtime.rs, and the gRPC liveness and accept tests in protocols/tests/unit/transports/. The second of those exists because a deadline armed from std::time::Instant ignores the paused clock; the test advances tokio’s clock by an hour first and checks that a 5 s idle deadline neither fires early nor never.
The in-process end-to-end suite
Section titled “The in-process end-to-end suite”tests/unit/e2e.rs builds a node the way the runtime does, minus the process: a PanelClient pointed at a fake panel, a NodeManager, and a static-update channel the test holds. NodeManager::run first brings the node up (panel config, users, the supervisor and its listener), retrying until it is up or its token is cancelled, then serves.
impl NodeManager { pub fn new(api: PanelClient, cfg: NodeConfig, globals: Arc<Globals>) -> Arc<Self>;
pub async fn run( self: Arc<Self>, shutdown: CancellationToken, mut static_rx: mpsc::Receiver<StaticUpdate>, );}The suite’s spawn_node(cfg, globals) builds the PanelClient, the NodeManager and the channel, and spawns run; most tests pass Arc::default() for the process-wide Globals, which leaves the [[outbound]] entries and [dns] at their defaults.
The fake panel is an HTTP/1.1 server on 127.0.0.1:0 written in the test. read_request parses each request into a Request { path, if_none_match, authorization, body }, and the panel matches on the path: a path containing /UniProxy/config gets the node config body, /UniProxy/user the current user body, and /UniProxy/push has its body captured and gets {}. Any other path gets {}. The constructors build on each other:
| Constructor | Adds |
|---|---|
fake_panel(node_port, uuid) |
One user, uid 1001, and a plain-TCP V2ray node on node_port |
fake_panel_dynamic(node_port, user_body) |
Serves the user body from an Arc<Mutex<String>>, so a test can change the user set between phases |
fake_panel_with_config(config_body, user_body) |
Also takes the node config body |
fake_panel_quirky(config_body, user_body, quirks) |
Behaves like a real panel on a bad day, set by Quirks, and also returns an Arc<AtomicUsize> counting node config requests |
fake_helium |
A separate fake of helium’s node API v2 for node 1 (/api/node/v2/1/config, /users and /report, with ETags), serving the config and users bodies it is given: it refuses with 403 Forbidden a request without the node’s bearer token or with a query string, and records every report body in a HeliumSeen |
Quirks has two fields. config_failures answers the first N node config requests with 500 Internal Server Error: a panel that is not up yet when the node starts. etags tags every config and user answer with an ETag and answers a request whose If-None-Match matches it with 304 Not Modified, as Xboard does. wait_config_requests(requests, n) waits until the panel has been asked for the node config n times.
The default config body is {"server_port":…,"network":"tcp","tls":0}: the V2ray nodes in this suite run plain TCP only, and the transports are left to the integration tests. The Hysteria 2 tests set [node.hysteria].port locally, which makes the node skip the panel’s node config (users still come from the panel), except a_panel_described_hysteria_node_serves_obfuscated_traffic and the rate tests, which leave the port at 0 and serve their own body through fake_panel_with_config. The rate tests build their node with rated_hy2_node(config_body, local, up, down), which applies local to [node.hysteria] and connects a client declaring up and down Mbit/s; the device-limit and IP-ban tests build theirs with limited_node(uuid, limit, ban_after), a node under enable_device_limit whose one user has the device limit limit. The helium tests describe their node in a node API v2 config body: helium_node_cfg(panel_addr) is test_node_cfg with panel_type = "helium" and no node_type, helium_users_body(users) writes a users answer with no limits from the helium-node-api crate’s own users::Users, helium_node serves a plain-TCP VMess node with one user, uid 1001, from fake_helium, and free_tcp_port picks the node’s port.
test_node_cfg sets update_periodic = 1, so the node polls the panel and pushes traffic every second. Clients are the kernel’s own: a VMess or VLESS ProxyClientRuntime over TCP (vmess_client, vless_client), for Hysteria 2 nodes Hy2Conn::connect with VerifyMode::Insecure, and for the sss node an SssStream runtime dialed through SssConnector, which wraps the TCP connection in the node’s transform chains.
The fixtures that tests/unit/runtime.rs shares are pub(crate):
| Helper | Behaviour |
|---|---|
roundtrip(reader, writer, payload, limit) |
Writes payload on an open connection and expects the exact echo within limit |
vmess_roundtrip, vless_roundtrip |
The same on a fresh VMess or VLESS connection |
wait_relays(node, uuid, echo) |
Retries a 2 s vmess_roundtrip every 100 ms until the node relays, and panics after 10 s: a node still coming up refuses or drops connections until it is up |
tcp_echo, fake_panel, test_node_cfg, wait_bound |
The echo target, the newV2board panel, a node config for a panel address, and waiting for a TCP bind |
SPARE_LOOPBACK is 127.0.0.2. Every other listener in the suite is on 127.0.0.1, so a port on the spare address that a test releases can only be taken by the node meant to take it, whatever range the host hands out port 0 from.
| Test | Pins |
|---|---|
vmess_traffic_is_metered_and_reported |
A VMess echo relays exactly, and the panel’s push bodies attribute its traffic to uid 1001 |
unchanged_user_survives_user_refresh |
Adding a user leaves a live connection of an unchanged user working; removing that user drops it |
proxy_outbound_relays_and_meters |
A node whose default outbound is a VLESS client to an in-test VLESS server relays and meters |
route_change_drops_connections |
A StaticUpdate::Config with a different [node.route] drops the open connection |
a_users_speed_limit_paces_their_traffic |
A user whose panel speed_limit is 8 Mbps moves 3 MB (1.5 MB each way) in no less than 1.5 s |
a_node_comes_up_once_the_panel_answers |
With config_failures: 2, the node keeps asking, binds only after at least three config requests, and relays |
a_node_whose_port_is_taken_comes_up_once_it_is_free |
A listener holds the node’s port on SPARE_LOOPBACK; once the test releases it, the node comes up |
a_node_that_never_bootstraps_still_stops |
With every config request failing, a cancelled node task ends within 2 s instead of retrying on |
a_node_on_0_0_0_0_serves_ipv4_and_ipv6_clients, a_hysteria_node_on_0_0_0_0_serves_ipv4_and_ipv6_clients |
listen_ip = "0.0.0.0" serves clients on both 127.0.0.1 and ::1; skipped where IPv6 sockets do not take IPv4 |
a_hysteria_node_relays_and_meters |
A Hysteria 2 node relays and meters |
a_hysteria_node_refuses_an_unknown_credential |
A credential the panel never issued does not proxy |
a_retired_user_stops_while_the_rest_keep_their_connections |
Retiring user B cuts B off while A’s existing QUIC connection keeps working |
a_panel_described_hysteria_node_serves_obfuscated_traffic |
Port and Salamander settings taken from the panel’s node config reach the listener |
repeated_user_refreshes_never_disturb_a_live_connection |
Repeated cycles, each flipping the user set, leave one QUIC connection alive and relaying after every cycle |
a_panel_that_sets_rates_has_the_node_send_at_the_agreed_one |
A panel with up_mbps 24, down_mbps 16 and ignore_client_bandwidth false: the node answers 16, and sends to a client declaring 32 at 24 |
a_panel_silent_on_ignoring_client_bandwidth_keeps_the_node_on_auto |
A panel that sends rates but no ignore_client_bandwidth leaves the node answering auto, with no fixed rate either way |
the_local_hysteria_block_overrides_the_panels_rates |
[node.hysteria] turning off the panel’s ignore_client_bandwidth, with no down_mbps anywhere, has the node answer unlimited, so the client sends at its own 20 Mbit/s |
a_users_clients_come_from_no_more_ips_than_their_device_limit |
Under enable_device_limit, a user with a device limit of 1 is served on a second connection from the same IP, refused from a second IP, and served from the second IP once the first device’s connection has closed |
an_ip_failing_to_authenticate_is_banned_and_others_are_served |
With ban_max_failures = 3, an IP refused three times is then refused even with the right id, while another IP is still served |
a_helium_node_without_enable_device_limit_reports_no_addresses |
Against fake_helium, a node without enable_device_limit reports its traffic with an empty ips list in every report |
an_sss_node_relays_through_its_chains_and_meters |
A helium node whose node API v2 config (served by fake_helium) describes an sss node with a transform chain each way echoes 50,000 bytes for a real sss client, and the reports attribute at least that many bytes each way to uid 1001 |
These tests use the real clock and poll for results, because the node’s own timers are what is under test.
Reload tests against running nodes
Section titled “Reload tests against running nodes”tests/unit/runtime.rs is mounted from src/runtime.rs, so it calls the private identity, display_id and apply_reload directly. Its Runtime struct holds what run holds for its nodes (cfg, root and the node handles) around one node:
| Method | Behaviour |
|---|---|
start(node_cfg) |
Spawns one node and records a Config with that node |
reload(new) |
Calls apply_reload with the new Config and a log reload that does nothing |
stop() |
Cancels the root token and awaits every node task |
A test tells a respawn from an in-place reconfiguration by comparing the node handle’s static_tx with a clone taken before the reload (same_channel). The identity tests only compare identities and need no node.
| Test | Pins |
|---|---|
a_newv2board_node_is_also_the_type_it_asks_for |
For NewV2board, the node type it asks the panel for is part of the identity |
a_node_is_logged_by_its_panel_node_not_its_key |
display_id renders the panel node, never the key |
a_newv2board_type_edit_respawns_the_node |
Turning enable_vless off on a NewV2board node respawns it; the new node serves VMess and refuses VLESS |
a_reload_with_a_node_that_does_not_build_changes_nothing |
A reload with a node_type typo and a route edit in the same entry keeps the running node, applies neither edit, and leaves a live connection relaying |
an_sspanel_node_is_refused_at_test_and_at_start |
A config with panel_type = "SSpanel" is refused by test_config and by build_node with panel_type "SSpanel" is not supported, and spawn_node starts nothing |
a_reload_to_sspanel_changes_nothing |
A reload that moves the running node to panel_type = "SSpanel" is refused whole: the node is neither removed nor replaced, the recorded config stays, and the node still relays VMess |
a_client_edit_takes_effect_without_dropping_connections |
Setting rule_list_path to a file whose rule names the echo target by domain reconfigures in place: new flows there are refused within 10 s, and a connection already open keeps relaying |
a_wireguard_outbound_several_nodes_route_to_is_reported |
The warning for one WireGuard outbound that several nodes route to |
enable_mtls_is_on_unless_turned_off |
A node that never names enable_mtls has it on, enable_mtls = false turns it off, and turning it off does not make the entry another node |
Integration tests against FakePanel
Section titled “Integration tests against FakePanel”tests/support/mod.rs repeats the core of the app’s support (Proc without terminate, spawn_xray, spawn_hysteria_client, free_port, free_udp_port, wait_port, test_dir, socks5_roundtrip, certificates and pinning) and adds a reusable panel. It has no per-run directories: its test_dir is CARGO_TARGET_TMPDIR/<name>, and it builds Xray and Hysteria straight to CARGO_TARGET_TMPDIR/xray and CARGO_TARGET_TMPDIR/hysteria.
pub struct FakePanel { pub addr: SocketAddr, /* private: pushes */}
impl FakePanel { pub async fn spawn(config_body: String, user_body: String) -> Self; pub fn reported_totals(&self, uid: i64) -> (i64, i64); pub async fn wait_for_traffic(&self, uid: i64, timeout: Duration) -> (i64, i64);}
pub fn spawn_katana(dir: &Path, config: &str) -> Proc;pub fn users_body(users: &[(i64, &str)]) -> String;pub fn v2ray_config_body(port: u16, network: &str, tls: bool, vless: bool) -> String;pub fn hysteria_config_body(port: u16) -> String;pub fn trojan_config_body(port: u16) -> String;pub async fn wait_udp_bound(port: u16);FakePanel serves the same three UniProxy paths as the in-process fake, with fixed bodies. wait_for_traffic returns as soon as either total for the uid is above 0, or with whatever it has when the timeout elapses; the caller asserts on the result.
The Xray and Hysteria builds point at the sibling Etemenanki checkout (../Etemenanki/Xray-core, ../Etemenanki/hysteria), derived from CARGO_MANIFEST_DIR; a standalone katana clone prints SKIP: … not found and passes.
sequenceDiagram participant T as Test participant P as FakePanel participant K as katana binary participant X as xray client participant E as tcp_echo T->>P: FakePanel::spawn(config body, users body) T->>K: spawn_katana with katana.toml K->>P: request node config and users K->>K: bind the node port T->>K: wait_port(node_port) T->>X: spawn_xray, wait_port(socks_port) T->>X: socks5_roundtrip(echo, payload) X->>K: VMess, VLESS or Trojan over the chosen transport K->>E: direct outbound E-->>T: echoed bytes K->>P: push traffic every update_periodic of 1 s T->>P: wait_for_traffic(UID, 15 s) T->>T: assert up and down are both above 0
| Module | Tests |
|---|---|
xray_interop |
The matrix vmess_tcp_plain, vmess_ws_plain, vmess_grpc_plain, vmess_tcp_tls, vless_ws_tls, vless_grpc_tls, trojan_tcp_tls, and with Xray’s mux enabled vmess_tcp_plain_mux, vless_ws_tls_mux, trojan_tcp_tls_mux. Each asserts the exact echo and that the panel received traffic for uid 1001. TLS cells verify katana’s self-signed leaf by pin, not by disabling verification. |
sniff |
a_sniffed_host_reaches_a_domain_rule and disable_sniffing_stops_the_domain_rule_matching: a node whose route drops everything except a domain rule. |
hysteria_interop |
a_real_client_proxies_through_a_katana_hysteria_node: the official client, driven through its SOCKS5 front end, authenticates with the bare UUID and relays, then relays a second time through the same client, which rides a new stream of the same QUIC connection. It does not assert the traffic report. |
katana takes the kernel crates, the supervisor included, from a private Cargo registry at the version in its Cargo.lock. Its tests therefore exercise the published kernel, not the Etemenanki working tree: a kernel change reaches katana’s suite only after it is released and katana’s lockfile is bumped.
Invariants of the suites
Section titled “Invariants of the suites”| Invariant | Mechanism | Where |
|---|---|---|
| No test needs internet access, except one ignored test (building the upstream binaries may fetch Go modules, and a Go toolchain new enough for Xray-core) | Every peer and destination is an in-test server, a child process listening on loopback, or the in-process WireGuard peer; REALITY’s cover site is a local OpenSSL server | All suites; the exception is wireguard_outbound_live_env_tcp |
| Interop and privileged tests never fail for lack of Go, a submodule or privilege | XRAY_BIN/HYSTERIA_BIN/SINGBOX_BIN are None and each test returns early; can_create_a_device returns false on PermissionDenied; the supervisor’s TUN test returns on a bind failure |
app/tests/support/mod.rs, katana/tests/support/mod.rs, e2e_tun.rs, supervisor/tests/hot_swap.rs |
| A failing test leaves no process behind | Proc kills and reaps its child in Drop |
Both support modules |
| Two app test runs at once in one checkout never share a directory | Each test process claims CARGO_TARGET_TMPDIR/runs/<pid>/ under an exclusive lock it holds until it exits |
app/tests/support/runs.rs |
| Minutes-long deadlines and grace periods are tested without waiting for them | start_paused = true; the kernel and the supervisor arm their timers on tokio’s clock |
deadline_is_armed_against_the_tokio_clock, revoking_under_close_after_ends_the_session_once_the_grace_passes |
| A supervisor test that loses a port race retries instead of failing | start_on picks new ports on ApplyError::Bind |
supervisor/tests/support/mod.rs |
| A buggy core or codec fails a runtime test instead of hanging it | Contract violations surface as RuntimeError or io::Error; the tests bound the wait with tokio::time::timeout |
a_held_range_past_the_buffer_is_rejected, handshake_step_without_progress_is_rejected, zero_length_frame_is_rejected |
| The two halves of a protocol are tested against each other and, where one exists, against an independent implementation | Pipeline tests (for sss, the supervisor and app suites), then Xray, Hysteria and sing-box interop | protocols/tests/pipeline/, supervisor/tests/sss.rs, app/tests/integration/, katana/tests/integration/ |
Running tests
Section titled “Running tests”# Everything the gate runs (protocols gets hysteria, tun and reality from the supervisor)cargo test --workspace
# One crate's unit tests onlycargo test -p etemenanki-protocols --libcargo test -p etemenanki-supervisor --libcargo test -p etemenanki-app --lib
# The REALITY crate: its unit tests and its two targetscargo test -p etemenanki-reality
# One protocol's unit tests (module path filter)cargo test -p etemenanki-protocols --lib trojan::
# The runtime and client-runtime testscargo test -p etemenanki-concepts --test runtimecargo test -p etemenanki-concepts --test client
# One protocol's pipeline testscargo test -p etemenanki-protocols --test pipeline pipeline::trojancargo test -p etemenanki-protocols --features hysteria --test pipeline pipeline::hysteriacargo test -p etemenanki-protocols --features tun --test pipeline pipeline::tuncargo test -p etemenanki-protocols --features reality --test pipeline pipeline::reality
# The supervisor's end-to-end targetscargo test -p etemenanki-supervisor --test hot_swapcargo test -p etemenanki-supervisor --test trackingcargo test -p etemenanki-supervisor --test socket_policycargo test -p etemenanki-supervisor --test guardcargo test -p etemenanki-supervisor --test handoffcargo test -p etemenanki-supervisor --test anytlscargo test -p etemenanki-supervisor --test ssscargo test -p etemenanki-supervisor --test ping
# The REST API, the mobile library and the subscribe schemacargo test -p etemenanki-webclientcargo test -p etemenanki-fficargo test -p etemenanki-subscribe
# Dialers, including QUIC, which no workspace member enablescargo test -p etemenanki-environment --features quic --test integration
# App end-to-end, one module, with SKIP lines visiblecargo test -p etemenanki-app --test integration e2e_xray -- --nocapturecargo test -p etemenanki-app --test integration e2e_singbox_anytls -- --nocapture
# The privileged and the live testssudo -E cargo test -p etemenanki-app --test integration e2e_tuncargo test -p etemenanki-app --test integration wireguard_outbound_live_env_tcp -- --ignored
# Benchmarkscargo bench -p etemenanki-supervisor --bench trackingcargo bench -p etemenanki-protocols --bench vmess_users# Everything the gate runscargo test --locked
# Unit tests and the in-process e2e (all in the binary's harness)cargo test --locked --bin katanacargo test --locked --bin katana e2e::cargo test --locked --bin katana lower::cargo test --locked --bin katana rule::tests::cargo test --locked --bin katana runtime::tests::cargo test --locked --bin katana manager::node::tests::
# Integration tests against FakePanel, one modulecargo test --locked --test integration xray_interop -- --nocapturecargo test --locked --test integration hysteria_interop -- --nocaptureA filter matches a substring of the full test path. The paths follow the module layout:
| Kind | Example path |
|---|---|
| Mounted unit test | trojan::core::tests::header_split_across_events_opens_once_complete |
| Supervisor unit test | topology::spec_plan::plan::tests::a_route_change_alone_rebuilds_only_the_route_table |
| Pipeline test | pipeline::trojan::new_server_vs_new_client_tcp |
| Supervisor end-to-end test | removing_a_user_closes_only_their_sessions_and_refuses_them_after, in the hot_swap target |
| App integration test | e2e_xray::app_client_ws_xray_server_plain |
| katana in-process e2e | e2e::vmess_traffic_is_metered_and_reported |
| katana reload test | runtime::tests::a_newv2board_type_edit_respawns_the_node |
| katana integration test | xray_interop::vmess_ws_plain |
Validation gates
Section titled “Validation gates”A change lands only after the full gate passes in every repository it touches. The CI workflows build release binaries and run none of these, so the gates are run locally.
cargo fmt --all -- --checkcargo test --workspacecargo clippy --workspace --all-targets --all-features -- -D warnings# before a release, additionally:cargo check --workspace --lockedcargo fmt --all -- --checkcargo test --lockedcargo clippy --all-targets --all-features -- -D warnings# before a release, additionally:cargo metadata --locked --no-deps --format-version 1cargo check --locked--all-targets in the clippy gate lints the integration test crates, the ffi/bindgen binary and both criterion benches too, and --all-features turns on quic, so the QUIC dialer tests are at least compiled and linted even though cargo test --workspace does not run them. The panicking-form lints are clippy lints: cargo test compiles an unwrap() in library code without complaint, and only the clippy gate rejects it. Protocol, transport, WireGuard, SOCKS and TLS changes should also run the interop suites with Go present and --nocapture, and confirm no SKIP line appears; for a change to reality/ or to REALITY or Vision in protocols, that means e2e_xray_reality. The supervisor’s suites and the REALITY crate’s own need no Go.
Limits and timeouts in the harnesses
Section titled “Limits and timeouts in the harnesses”| Constant or value | Where | Value |
|---|---|---|
HARNESS_STAGING |
protocols/src/core/harness.rs |
64 KiB staging per CoreHarness |
MTU, SCRATCH, LISTENERS |
protocols/tests/support/wireguard.rs |
1420, 64 KiB, 4 |
ECHO_PORT, SINK_PORT |
same | 5555 (TCP and UDP echo), 5556 (TCP sink) |
| Stalled-flow bound | protocols/tests/pipeline/wireguard.rs |
At most 512 KiB accepted before a write to the stalled sink waits longer than 1 s |
| WireGuard peer timer | same | update_timers every 200 ms |
QUIET, SOON |
supervisor/tests/support/mod.rs |
400 ms, 5 s |
start_on retries |
same | Up to 5 new port picks on ApplyError::Bind |
wait_port |
app and katana support | 20 s, polling every 50 ms |
wait_addr |
app/tests/support/mod.rs |
20 s, polling every 50 ms |
wait_udp_port |
app/tests/support/mod.rs |
20 s, polling every 50 ms |
wait_udp_bound |
katana/tests/support/mod.rs |
400 tries 50 ms apart (20 s), then panics |
wait_bound, wait_udp_bound |
katana/tests/unit/e2e.rs |
200 tries 50 ms apart (10 s), then panics |
wait_config_requests |
katana/tests/unit/e2e.rs |
200 tries 50 ms apart (10 s), then panics |
wait_relays |
katana/tests/unit/e2e.rs |
10 s deadline, 2 s per round trip, 100 ms between tries, then panics |
roundtrip, vmess_roundtrip, vless_roundtrip |
katana/tests/unit/e2e.rs, katana/tests/unit/runtime.rs |
The caller’s limit: 10 s where the echo must arrive, 2 s where it must fail |
Proc::terminate |
app/tests/support/mod.rs |
10 s after SIGTERM, then SIGKILL from Drop |
| Round-trip timeouts | e2e_xray, e2e_xray_vmess, e2e_xray_mux, e2e_xray_wrapped, e2e_wg |
15 s per SOCKS round trip; some e2e_xray_mux cases allow 20 s or 30 s |
| Round-trip timeouts | e2e_xray_reality |
20 s where the echo must arrive; 12 s for the wrong-key and wrong-shortId cases, which pass when the round trip fails or times out; 10 s for the UDP association and for each datagram’s reply in the Vision UDP tests |
| Round-trip timeouts | e2e_singbox_anytls, e2e_sss |
20 s per TCP round trip and 10 s per UDP step in e2e_singbox_anytls; 10 s per round trip in e2e_sss |
FakePanel::wait_for_traffic |
katana integration | Polls every 100 ms up to the caller’s timeout (15 s in xray_interop) |
update_periodic in test configs |
katana e2e and integration | 1 s |
| Contract-violation reads | concepts/tests/client.rs |
1 s timeout; hitting it means the runtime spun or hung |
assert_near |
protocols/tests/pipeline/hysteria_options.rs; app/tests/integration/e2e_hysteria_options.rs |
A measured rate within 0.8 to 1.2 times the target; 0.75 to 1.25 in the app’s tests |
long_path |
app/tests/integration/e2e_hysteria_options.rs |
15 ms of delay each way through the forwarded port range |
Adding tests
Section titled “Adding tests”When you add a protocol
Section titled “When you add a protocol”-
Wire format. In
protocols/tests/unit/<proto>/protocol.rs, mounted fromsrc/<proto>/protocol.rs: encode and decode round trips, and one negative test per fixed field (version, reserved bytes, length, command or type) proving a wrong value is an error rather than a silently accepted header. Truncated input must ask for more, and a length beyond the protocol’s limit must fail. Test only what the parser does; do not assume the peer is a correct implementation. -
Client codec. In
tests/unit/<proto>/codec.rs:sealandopenwith no I/O, a frame split across calls returningOpened::NeedMore, andfinish. Thecodec_is_driven_without_any_iotest inconcepts/tests/client.rsis the template. -
Server core. In
tests/unit/<proto>/core.rs, throughCoreHarness: a header split across events opens only once complete; a wrong credential fails withPermissionDenied; an IP target with sniffing on holds the prefix and opens on a host or onSNIFF_TIMEOUT; a domain target is never sniffed; the relay half-closes each way and finishes on the second;ConnectFailedends the connection the way the protocol requires;Event::Deadlinebefore establishment fails with the handshake timeout; for UDP, a partial packet frame waits for the rest.protocols/tests/unit/trojan/core.rshas one test for each. -
Pipeline. A new
protocols/tests/pipeline/<proto>.rs, declared intests/pipeline.rs(behind a#[cfg(feature = …)]if the protocol is feature-gated). At leastnew_server_vs_new_client_tcpwith a payload larger than the core’sBUF_SIZEfollowed byshutdownand an emptyread_to_end, andnew_server_vs_new_client_udpwith a 1500-byte datagram and an assertion on the reply’s source. A UDP relay also needs a negative test that a datagram from a source outside the association is not relayed, as the SOCKS association tests do withrecording_echo. Useserve_runtime::<{ YourCore::<()>::BUF_SIZE }, _, _>rather than a hand-picked size, orserve_runtime_overwhen the protocol always runs behind a transport, as AnyTLS runs behind TLS. -
Supervisor and app. A spec rule the protocol needs goes in
supervisor/src/build/validate.rs, with a test insupervisor/tests/unit/validate.rsfor each refusal. A protocol that rides a stream transport joinsInboundProtocolSpec::transport(), the one list from which validation applies the shared transport rules, REALITY’s refusal under anything but VLESS included. The app’s lowering gets tests inapp/tests/unit/lower.rs(andtransport.rsfor stream settings): a minimal config lowers, every required setting is enforced, an unknown setting is refused, and an unsupported transport or security combination fails closed with a message naming the fix. Assert on a distinctive part of the error text. -
Interop. If Xray, Hysteria or sing-box implements the protocol, an
e2e_*test in each direction the app supports, driven throughsocks5_roundtripand asserting the exact echo. If mux.cool or XUDP applies, add a cell toe2e_xray_mux. -
katana, if it serves the protocol. The node in
helium-node-api’s contract first; where a UniProxy panel describes it, a test inkatana/tests/unit/api/newv2board.rsthatparse_node_configreads its body into the node and refuses what katana cannot serve; then lowering tests inkatana/tests/unit/lower/inbound.rsfor the node and each user’s credential, a check that the spec katana builds passes the supervisor’s own validation, asthe_new_node_kinds_pass_the_supervisors_validation(katana/tests/unit/lower/spec.rs) does for the node kinds of 4.9.0 and 4.10.0, and a cell in thexray_interopmatrix that also asserts the traffic report. -
Gates. The full gate with Go installed and
--nocaptureon the interop modules, checking that nothing printedSKIP.
When you change the runtime or the event contract
Section titled “When you change the runtime or the event contract”- Pin the behaviour with a toy core in
concepts/tests/runtime.rs, or a toy codec inconcepts/tests/client.rs, not with a real protocol. ExtendTinyMuxorScriptedwhen an existing toy can express the case; add a new toy when it cannot, and document its wire format in a doc comment. - Backpressure changes need a test where one side stalls: a small far-end pipe, as in
stalled_outbound_holds_uplink_but_not_other_downlink, or a small upstream, as inbackpressure_from_the_wire_reaches_the_writer. Assert both that the stalled direction waits and that unrelated directions keep moving. Any new queue or buffer on the path needs a cap and a test in which a blocked consumer stops the producer, asa_stalled_tcp_flow_blocks_its_writeranda_held_item_keeps_the_channel_unreaddo for the WireGuard driver, anda_stalled_stream_stalls_the_writer_instead_of_growing_the_buffer(protocols/tests/unit/transports/coalesce.rs) does for the buffer under h2’s writes. - Deadline changes need a
start_pausedtest overduplex. Keep real sockets out of paused tests: tokio auto-advances a paused clock whenever the runtime has no work, including while a task waits on a real socket, so timers can fire before the socket delivers. - A new
RuntimeErrorvariant or a new contract check needs a test that provokes it and bounds the wait withtokio::time::timeout, so a regression hangs for a second instead of forever. - Datagram paths need the truncation and refusal cases:
datagram_outbound_is_never_truncated_by_staging_backpressure,a_refused_datagram_send_keeps_the_key_alive,a_refused_transport_packet_is_reported_not_fatal. Bytes the peer waits for need a test over a wire that holds writes until a flush, as a WebSocket sink and sss’s transform chains do:a_packet_reaches_a_wire_that_holds_writes_until_flushed(concepts/tests/client.rs) puts aBufWriterunder the client runtime’s datagrams, andthe_sniffed_prefix_reaches_an_upstream_that_buffers(protocols/tests/unit/socks/server.rs) one under the SOCKS driver’s upstream. - Then run the whole
pipelinetarget with--features hysteria,tun,reality, the supervisor’s targets and the app’s e2e modules: every inbound except SOCKS runs inside the server runtime.
When you change the supervisor
Section titled “When you change the supervisor”- An apply. A plan change needs a unit test in
supervisor/tests/unit/plan.rsfor the steps it lists, and a test insupervisor/tests/hot_swap.rsthat holds a live connection across the apply and checks what happens to it and to the next one. A refusal belongs invalidate.rswith its own test. - Sessions, pacing and usage. Grace timers and speed limits are tested on a paused clock (
tests/unit/session.rs,tests/unit/track.rs). A change to how bytes are counted or taken keepsevery_byte_is_taken_exactly_oncepassing, and adds a case tosupervisor/tests/tracking.rsthat checks exact counts over real sockets. - Sockets the supervisor opens. A new kind of outbound socket needs a
socket_policy.rstest that the hook saw it. - Route changes and live flows. A change to what counts as the same way out for
close_reroutedneeds a case intests/unit/plane.rsagainstPlane::reroutes, and one inhot_swap.rsover real flows that checks both a flow that is closed and one that keeps transferring. - Handed-over connections. A change to the handoff socket needs a case in
supervisor/tests/handoff.rsthat hands a real socket over withsendmsgandSCM_RIGHTS, and, for anything it refuses, a check that the relay still holds a working connection. A change to how a Unix or handoff socket is bound needs a refused apply too: the running socket still reachable at its path, and nothing left in its directory. - Who a client is. A change to the IP ban or the gRPC failure count needs a unit test in
tests/unit/guard.rson a paused clock, and one to the device limit a unit test intests/unit/session.rs(a_session_from_one_ip_too_many_is_refused_and_closedand its neighbours). Each also needs an end-to-end case insupervisor/tests/guard.rswith a real client on loopback. A change to the real-IP header needs a unit test ofreal_ip_sourceintests/unit/serve.rs(a_trusted_proxys_header_names_the_client_and_no_one_elses_does), a test intests/unit/validate.rsfor each refusal, and an end-to-end case insupervisor/tests/guard.rsthat sends the header from a trusted and from an untrusted address.
When you change katana
Section titled “When you change katana”- Lowering: a test in
tests/unit/lower/for each node field that reaches the spec, and for each refusal of this host’s settings. A refusal of what a UniProxy answer asks for is the newV2board client’s: test it intests/unit/api/newv2board.rsand assert the reason in the error’s own message, the one a node logs. - Speed limits, metering and usage are the supervisor’s: test them there (see When you change the supervisor), and in katana only end to end, as
a_users_speed_limit_paces_their_trafficdoes. - Node lifecycle and user sync: an in-process test in
tests/unit/e2e.rsusingfake_panel_dynamicto change the user set while a connection is open. - Bootstrap, retries and conditional requests: an in-process test against
fake_panel_quirky, withQuirks { config_failures }for a panel that is not up yet andQuirks { etags }for one that answers304 Not Modified, usingwait_config_requeststo know how far the node got. - Reload and node identity: a test in
tests/unit/runtime.rsthrough theRuntimeharness. An identity change needs anidentityassertion and a respawn test; any other edit needs a test that it takes effect in the running node, and that it keeps open connections when nothing a listener is built from changed. - Logging of credentials: when a test feeds a malformed credential, assert the error does not echo it, as
a_malformed_uuid_is_refused_without_echoing_itintests/unit/lower/outbound.rsdoes. - A new panel field or node type: the field in
helium-node-api’s contract, a parsing test intests/unit/api/(for newV2board, the conversion and every refusal), a check intests/unit/lower/spec.rsthat the node lowers to a spec the supervisor accepts, a case inonly_a_disruptive_change_drops_every_connectionif a change to the field must not drop connections, and a config body helper intests/support/mod.rsif the integration tests need it.