Files
proxy-suite-flake/windows/crates/ps-ctl/tests/e2e.rs
T
faumarayandClaude Opus 5.5 2c4cdee7d3 windows: AmneziaWG outbounds, and WARP through wireproxy
- ps_core::awg: upstream's scripts/amneziawg_config.py, ported: a profile
  from a .conf, an AmneziaVPN vpn:// link (qCompress'd JSON or the compact
  .conf form, containers and DNS placeholders as upstream reads them) or
  declarative settings (with obfuscationFile's secrets); AWG 3's MTU
  default, the endpoint override, upstream's checks (no wg-quick hooks
  unless allowed, no control characters, one [Interface]); and the
  wireproxy configuration. Checked against links made by upstream's own
  encoder, output byte for byte.
- wireproxy-awg for Windows, built from upstream's tag (pinned to its
  commit) with upstream's patches, by tools/build-wireproxy-awg.sh; in
  the release as a bundled component. Go joins the dev shell.
- The service runs one per "userspace" AmneziaWG outbound and WARP
  device, on its loopback port with the hop login, its configuration
  below the protected state root; "singBox" profiles reach the renderer.
  wireproxy goes direct under the TUN.
- End to end on Linux (an_amneziawg_tunnel): sing-box as the WireGuard
  server, the service's wireproxy as the client; a page through its
  listener and through the proxy's outbound, named inside the tunnel.
- What is still to come and said: AmneziaWG as a system-wide VPN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:32:43 +03:00

441 lines
20 KiB
Rust

//! The whole stack, offline: a sing-box Shadowsocks server and a small web server on
//! loopback, the service in console mode with a fresh state directory, proxy-ctl adding the
//! server as an outbound, and a page fetched through the local proxy.
//!
//! Needs sing-box on PATH (the dev shell has it); skipped otherwise. Unix only: the Windows
//! side of the transport is a named pipe.
#![cfg(unix)]
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
const KEY: &str = "a2tra2tra2tra2tra2traw=="; // base64 of 16 'k's
fn free_port() -> u16 {
TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
struct Kill(Child);
impl Drop for Kill {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
fn service_binary() -> PathBuf {
let ctl = PathBuf::from(env!("CARGO_BIN_EXE_proxy-ctl"));
let dir = ctl.parent().unwrap();
let status = Command::new(env!("CARGO"))
.args(["build", "-q", "-p", "ps-service", "--bin", "proxy-suite-service"])
.status()
.unwrap();
assert!(status.success());
dir.join("proxy-suite-service")
}
fn ctl(socket: &Path, args: &[&str]) -> (bool, String) {
let out = Command::new(env!("CARGO_BIN_EXE_proxy-ctl")).arg("--socket").arg(socket).args(args).output().unwrap();
(out.status.success(), format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
}
/// GET http://<host>:<port>/ through a SOCKS5 proxy, with the name resolved by the proxy.
fn socks_get(proxy: u16, host: &str, port: u16) -> std::io::Result<String> {
let mut s = TcpStream::connect(("127.0.0.1", proxy))?;
s.set_read_timeout(Some(Duration::from_secs(10)))?;
s.write_all(&[5, 1, 0])?;
let mut buf = [0u8; 2];
s.read_exact(&mut buf)?;
let mut req = vec![5, 1, 0, 3, host.len() as u8];
req.extend_from_slice(host.as_bytes());
req.extend_from_slice(&port.to_be_bytes());
s.write_all(&req)?;
let mut reply = [0u8; 10];
s.read_exact(&mut reply)?;
if reply[1] != 0 {
return Err(std::io::Error::other(format!("SOCKS reply {}", reply[1])));
}
s.write_all(format!("GET / HTTP/1.0\r\nHost: {host}\r\n\r\n").as_bytes())?;
let mut body = String::new();
s.read_to_string(&mut body)?;
Ok(body)
}
fn wait_for(what: &str, timeout: Duration, mut check: impl FnMut() -> bool) {
let start = Instant::now();
while start.elapsed() < timeout {
if check() {
return;
}
std::thread::sleep(Duration::from_millis(250));
}
panic!("timed out waiting for {what}");
}
#[test]
fn a_page_through_the_whole_stack() {
if Command::new("sing-box").arg("version").output().is_err() {
eprintln!("sing-box is not on PATH: skipping");
return;
}
let dir = std::env::temp_dir().join(format!("ps-e2e-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (ss_port, web_port, proxy_port, clash_port, test_port) = (free_port(), free_port(), free_port(), free_port(), free_port());
// The web server.
let web = TcpListener::bind(("127.0.0.1", web_port)).unwrap();
std::thread::spawn(move || {
for mut s in web.incoming().flatten() {
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf);
let _ = s.write_all(b"HTTP/1.0 200 OK\r\nContent-Length: 19\r\n\r\nhello-through-proxy");
}
});
// The Shadowsocks server, which knows web.test as loopback.
let server_cfg = serde_json::json!({
"log": { "level": "warn" },
"dns": { "servers": [{ "type": "hosts", "tag": "hosts", "predefined": { "web.test": ["127.0.0.1"] } }] },
"inbounds": [{ "type": "shadowsocks", "tag": "ss-in", "listen": "127.0.0.1", "listen_port": ss_port,
"method": "2022-blake3-aes-128-gcm", "password": KEY }],
"outbounds": [{ "type": "direct", "tag": "direct" }],
"route": { "default_domain_resolver": "hosts", "final": "direct" },
});
std::fs::write(dir.join("server.json"), server_cfg.to_string()).unwrap();
let _server = Kill(Command::new("sing-box").args(["run", "-c"]).arg(dir.join("server.json")).stderr(Stdio::null()).spawn().unwrap());
// The service, with no outbound yet and nothing to download.
let state = dir.join("state");
std::fs::create_dir_all(&state).unwrap();
let config = serde_json::json!({
"proxy": {
"enable": true,
"listener": { "port": proxy_port },
"singBox": { "clashApiPort": clash_port, "testPort": test_port },
"routing": { "directRu": false },
},
});
std::fs::write(state.join("config.json"), config.to_string()).unwrap();
let socket = dir.join("api.sock");
let _service = Kill(
Command::new(service_binary())
.args(["--console", "--state-dir"])
.arg(&state)
.arg("--socket")
.arg(&socket)
.stderr(std::fs::File::create(dir.join("service.log")).unwrap())
.spawn()
.unwrap(),
);
wait_for("the service's API", Duration::from_secs(10), || ctl(&socket, &["status"]).0);
// proxy-ctl adds the server; the service renders, checks and starts sing-box.
let link = format!("ss://2022-blake3-aes-128-gcm:{}@127.0.0.1:{ss_port}#Test%20Server", KEY.replace('=', "%3D"));
let (ok, out) = ctl(&socket, &["proxy", "outbounds", "add", &link]);
assert!(ok, "{out}");
assert!(out.contains("added Test-Server"), "{out}");
let start = Instant::now();
while !ctl(&socket, &["status"]).1.contains("proxy: active") {
if start.elapsed() > Duration::from_secs(15) {
panic!(
"the proxy did not come up\nstatus:\n{}\nlogs:\n{}\nservice:\n{}",
ctl(&socket, &["status"]).1,
ctl(&socket, &["logs", "-n", "60"]).1,
std::fs::read_to_string(dir.join("service.log")).unwrap_or_default()
);
}
std::thread::sleep(Duration::from_millis(250));
}
let body = (0..20)
.find_map(|_| {
std::thread::sleep(Duration::from_millis(300));
socks_get(proxy_port, "web.test", web_port).ok()
})
.unwrap_or_else(|| {
panic!(
"no page through the proxy\nservice log:\n{}\nunit log:\n{}",
std::fs::read_to_string(dir.join("service.log")).unwrap_or_default(),
ctl(&socket, &["logs", "-n", "50"]).1
)
});
assert!(body.ends_with("hello-through-proxy"), "{body}");
// The inventory, a pin, and a route mode that sends everything direct, where web.test
// does not resolve.
let (_, list) = ctl(&socket, &["proxy", "outbounds"]);
assert!(list.contains("Test-Server") && list.contains("static"), "{list}");
assert!(ctl(&socket, &["proxy", "pin", "Test-Server"]).0);
assert!(ctl(&socket, &["status"]).1.contains("pinned to Test-Server"));
assert!(ctl(&socket, &["proxy", "mode", "all-bypass"]).0);
std::thread::sleep(Duration::from_secs(2));
assert!(socks_get(proxy_port, "web.test", web_port).map_or(true, |b| !b.ends_with("hello-through-proxy")));
assert!(ctl(&socket, &["proxy", "mode", "default"]).0);
// A bad edit is refused and changes nothing.
let (ok, out) = ctl(&socket, &["proxy", "rules", "add", "nowhere-real", "example.com"]);
assert!(!ok && out.contains("is not an outbound"), "{out}");
assert!(!ctl(&socket, &["proxy", "rules"]).1.contains("nowhere-real"));
// A good one goes in.
let (ok, out) = ctl(&socket, &["proxy", "rules", "add", "Test-Server", "example.com", "geoip:us", "process:Telegram.exe"]);
assert!(ok, "{out}");
assert!(ctl(&socket, &["proxy", "rules"]).1.contains("process:Telegram.exe"));
let _ = std::fs::remove_dir_all(&dir);
}
/// A program on PATH, by its full path (sshd will not run by a bare name).
fn on_path(name: &str) -> Option<PathBuf> {
std::env::var_os("PATH").and_then(|p| std::env::split_paths(&p).map(|d| d.join(name)).find(|f| f.is_file()))
}
/// The SSH tunnel, offline: an sshd of the test's own on loopback, the service running
/// OpenSSH's `-D` listener to it and sing-box's SSH outbound, a page fetched through each.
#[test]
fn an_ssh_tunnel() {
let (Some(sshd), Some(keygen), true) = (on_path("sshd"), on_path("ssh-keygen"), Command::new("sing-box").arg("version").output().is_ok()) else {
eprintln!("sshd, ssh-keygen or sing-box is not on PATH: skipping");
return;
};
let dir = std::env::temp_dir().join(format!("ps-e2e-ssh-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (ssh_port, web_port, socks_port, proxy_port, clash_port, test_port) = (free_port(), free_port(), free_port(), free_port(), free_port(), free_port());
// On every address: sing-box's outbound is reached by this machine's name (below).
let web = TcpListener::bind(("0.0.0.0", web_port)).unwrap();
std::thread::spawn(move || {
for mut s in web.incoming().flatten() {
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf);
let _ = s.write_all(b"HTTP/1.0 200 OK\r\nContent-Length: 15\r\n\r\nhello-over-ssh!");
}
});
for key in ["hostkey", "id"] {
assert!(Command::new(&keygen).args(["-q", "-t", "ed25519", "-N", "", "-f"]).arg(dir.join(key)).status().unwrap().success());
}
std::fs::copy(dir.join("id.pub"), dir.join("authorized_keys")).unwrap();
let host_key = std::fs::read_to_string(dir.join("hostkey.pub")).unwrap().split_whitespace().take(2).collect::<Vec<_>>().join(" ");
std::fs::write(
dir.join("sshd_config"),
format!(
"Port {ssh_port}\nListenAddress 127.0.0.1\nHostKey {d}/hostkey\nPidFile {d}/sshd.pid\nAuthorizedKeysFile {d}/authorized_keys\n\
UsePAM no\nStrictModes no\nPasswordAuthentication no\nKbdInteractiveAuthentication no\nAllowTcpForwarding yes\n",
d = dir.display()
),
)
.unwrap();
let _sshd = Kill(Command::new(&sshd).args(["-D", "-e", "-f"]).arg(dir.join("sshd_config")).stderr(std::fs::File::create(dir.join("sshd.log")).unwrap()).spawn().unwrap());
let state = dir.join("state");
std::fs::create_dir_all(&state).unwrap();
let user = std::env::var("USER").unwrap_or_else(|_| "root".into());
let config = serde_json::json!({
"proxy": {
"enable": true,
"listener": { "port": proxy_port },
"singBox": { "clashApiPort": clash_port, "testPort": test_port },
"routing": { "directRu": false },
},
"sshProxy": {
"enable": true,
"server": { "host": "127.0.0.1", "port": ssh_port, "user": user },
"identityFile": dir.join("id").to_string_lossy(),
"hostKey": [host_key],
"listener": { "port": socks_port },
"asOutbound": true,
},
});
std::fs::write(state.join("config.json"), config.to_string()).unwrap();
let socket = dir.join("api.sock");
let _service = Kill(
Command::new(service_binary())
.args(["--console", "--state-dir"])
.arg(&state)
.arg("--socket")
.arg(&socket)
.stderr(std::fs::File::create(dir.join("service.log")).unwrap())
.spawn()
.unwrap(),
);
wait_for("the service's API", Duration::from_secs(10), || ctl(&socket, &["status"]).0);
let diagnose = || {
format!(
"status:\n{}\nlogs:\n{}\nsshd:\n{}\nrendered:\n{}",
ctl(&socket, &["status"]).1,
ctl(&socket, &["logs", "-n", "40"]).1,
std::fs::read_to_string(dir.join("sshd.log")).unwrap_or_default(),
ctl(&socket, &["proxy", "config"]).1
)
};
// OpenSSH's listener, as other programs use it.
let body = (0..40).find_map(|_| {
std::thread::sleep(Duration::from_millis(250));
socks_get(socks_port, "127.0.0.1", web_port).ok()
});
assert!(body.as_deref().is_some_and(|b| b.ends_with("hello-over-ssh!")), "no page through ssh -D\n{}", diagnose());
// sing-box's own SSH outbound. The proxy refuses loopback destinations (a guard), so the
// page is asked for by this machine's name, which the SSH server resolves for itself.
let host = std::fs::read_to_string("/proc/sys/kernel/hostname").unwrap_or_default().trim().to_owned();
assert!(ctl(&socket, &["proxy", "pin", "ssh-proxy"]).0, "{}", diagnose());
let body = (0..40).find_map(|_| {
std::thread::sleep(Duration::from_millis(250));
socks_get(proxy_port, &host, web_port).ok().filter(|b| b.ends_with("hello-over-ssh!"))
});
assert!(body.is_some(), "no page through sing-box's SSH outbound\n{}", diagnose());
// Two logins with the copied key: OpenSSH's, then sing-box's.
let logins = std::fs::read_to_string(dir.join("sshd.log")).unwrap_or_default().matches("Accepted publickey").count();
assert_eq!(logins, 2, "{}", diagnose());
let _ = std::fs::remove_dir_all(&dir);
}
/// GET http://<host>:<port>/ through a SOCKS5 proxy that wants a login (RFC 1929).
fn socks_get_login(proxy: u16, login: (&str, &str), host: &str, port: u16) -> std::io::Result<String> {
let mut s = TcpStream::connect(("127.0.0.1", proxy))?;
s.set_read_timeout(Some(Duration::from_secs(10)))?;
s.write_all(&[5, 1, 2])?;
let mut buf = [0u8; 2];
s.read_exact(&mut buf)?;
let (u, p) = login;
let mut auth = vec![1, u.len() as u8];
auth.extend_from_slice(u.as_bytes());
auth.push(p.len() as u8);
auth.extend_from_slice(p.as_bytes());
s.write_all(&auth)?;
s.read_exact(&mut buf)?;
if buf[1] != 0 {
return Err(std::io::Error::other("SOCKS login refused"));
}
let ip: std::net::Ipv4Addr = host.parse().map_err(std::io::Error::other)?;
let mut req = vec![5, 1, 0, 1];
req.extend_from_slice(&ip.octets());
req.extend_from_slice(&port.to_be_bytes());
s.write_all(&req)?;
let mut reply = [0u8; 10];
s.read_exact(&mut reply)?;
if reply[1] != 0 {
return Err(std::io::Error::other(format!("SOCKS reply {}", reply[1])));
}
s.write_all(format!("GET / HTTP/1.0\r\nHost: {host}\r\n\r\n").as_bytes())?;
let mut body = String::new();
s.read_to_string(&mut body)?;
Ok(body)
}
fn wg_keypair() -> (String, String) {
let out = Command::new("sing-box").args(["generate", "wg-keypair"]).output().unwrap();
let text = String::from_utf8_lossy(&out.stdout).into_owned();
let field = |name: &str| text.lines().find_map(|l| l.strip_prefix(name)).unwrap_or_else(|| panic!("{text}")).trim().to_owned();
(field("PrivateKey:"), field("PublicKey:"))
}
/// AmneziaWG of the "userspace" kind, offline: sing-box as the WireGuard server on loopback
/// (answering for web.test, and taking 10.66.0.1 to this machine), the service running
/// wireproxy-awg as its client, a page through wireproxy's listener and through the proxy.
#[test]
fn an_amneziawg_tunnel() {
if Command::new("sing-box").arg("version").output().is_err() || on_path("wireproxy").is_none() {
eprintln!("sing-box or wireproxy (tools/build-wireproxy-awg.sh OUT linux) is not on PATH: skipping");
return;
}
let dir = std::env::temp_dir().join(format!("ps-e2e-awg-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (wg_port, web_port, proxy_port, clash_port, test_port) = (free_port(), free_port(), free_port(), free_port(), free_port());
let web = TcpListener::bind(("127.0.0.1", web_port)).unwrap();
std::thread::spawn(move || {
for mut s in web.incoming().flatten() {
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf);
let _ = s.write_all(b"HTTP/1.0 200 OK\r\nContent-Length: 16\r\n\r\nhello-through-wg");
}
});
let (srv_priv, srv_pub) = wg_keypair();
let (cli_priv, cli_pub) = wg_keypair();
let server = serde_json::json!({
"log": { "level": "warn" },
// web.test is the server's own tunnel address, which it takes to this machine's
// loopback (a tunnel's packet to 127.0.0.1 itself would be dropped as martian).
"dns": { "servers": [{ "type": "hosts", "tag": "hosts", "predefined": { "web.test": ["10.66.0.1"] } }] },
"endpoints": [{ "type": "wireguard", "tag": "wg-in", "address": ["10.66.0.1/32"], "private_key": srv_priv,
"listen_port": wg_port, "peers": [{ "public_key": cli_pub, "allowed_ips": ["10.66.0.2/32"] }] }],
"outbounds": [{ "type": "direct", "tag": "direct" }],
"route": {
"default_domain_resolver": "hosts",
"rules": [
{ "port": 53, "action": "hijack-dns" },
{ "ip_cidr": ["10.66.0.1/32"], "action": "route", "outbound": "direct", "override_address": "127.0.0.1" },
],
"final": "direct",
},
});
std::fs::write(dir.join("server.json"), server.to_string()).unwrap();
let _server = Kill(Command::new("sing-box").args(["run", "-c"]).arg(dir.join("server.json")).stderr(std::fs::File::create(dir.join("server.log")).unwrap()).spawn().unwrap());
let profile = format!(
"[Interface]\nPrivateKey = {cli_priv}\nAddress = 10.66.0.2/32\nDNS = 10.66.0.1\n\n[Peer]\nPublicKey = {srv_pub}\nAllowedIPs = 0.0.0.0/0\nEndpoint = 127.0.0.1:{wg_port}\nPersistentKeepalive = 25\n"
);
let state = dir.join("state");
std::fs::create_dir_all(&state).unwrap();
let config = serde_json::json!({
"proxy": {
"enable": true,
"listener": { "port": proxy_port },
"singBox": { "clashApiPort": clash_port, "testPort": test_port },
"routing": { "directRu": false },
},
"amneziaWg": { "enable": true, "profiles": { "vpn": { "config": profile, "asOutbound": "userspace" } } },
});
std::fs::write(state.join("config.json"), config.to_string()).unwrap();
let socket = dir.join("api.sock");
let _service = Kill(
Command::new(service_binary())
.args(["--console", "--state-dir"])
.arg(&state)
.arg("--socket")
.arg(&socket)
.stderr(std::fs::File::create(dir.join("service.log")).unwrap())
.spawn()
.unwrap(),
);
wait_for("the service's API", Duration::from_secs(10), || ctl(&socket, &["status"]).0);
let diagnose = || {
format!(
"status:\n{}\nlogs:\n{}\nserver:\n{}",
ctl(&socket, &["status"]).1,
ctl(&socket, &["logs", "-n", "40"]).1,
std::fs::read_to_string(dir.join("server.log")).unwrap_or_default()
)
};
// wireproxy's own listener, with the login the service gave it.
let conf = state.join("run").join("awg").join("vpn.conf");
wait_for("wireproxy's configuration", Duration::from_secs(10), || conf.is_file());
let text = std::fs::read_to_string(&conf).unwrap();
let field = |name: &str| text.lines().find_map(|l| l.strip_prefix(name)).unwrap().trim().to_owned();
let (user, password) = (field("Username ="), field("Password ="));
let port: u16 = field("BindAddress =").rsplit(':').next().unwrap().parse().unwrap();
let body = (0..40).find_map(|_| {
std::thread::sleep(Duration::from_millis(250));
socks_get_login(port, (&user, &password), "10.66.0.1", web_port).ok().filter(|b| b.ends_with("hello-through-wg"))
});
assert!(body.is_some(), "no page through wireproxy\n{}", diagnose());
// The proxy's outbound "vpn", a name resolved inside the tunnel.
assert!(ctl(&socket, &["proxy", "pin", "vpn"]).0, "{}", diagnose());
let body = (0..40).find_map(|_| {
std::thread::sleep(Duration::from_millis(250));
socks_get(proxy_port, "web.test", web_port).ok().filter(|b| b.ends_with("hello-through-wg"))
});
assert!(body.is_some(), "no page through the proxy's AmneziaWG outbound\n{}", diagnose());
let _ = std::fs::remove_dir_all(&dir);
}