Files
proxy-suite-flake/windows/crates/ps-ctl/tests/e2e.rs
T
faumarayandClaude Opus 5.5 fb6c5962d0 windows: zapret's hostlistRules, and the SSH tunnel
- hostlistRules (zapret-discord-youtube): a group of sites with its own
  strategy, as upstream's patch-zapret-config.py makes them: the
  preset's profiles for the rule's family (or another preset's, with
  configName; Discord's voice profile with it), pointed at the rule's own
  list with the standard excludes, or the rule's nfqwsArgs; ahead of the
  preset's own. WinDivert's filter takes the ports they add. Rules with
  enableDirectSync join the direct list. Names of zapret's own lists, and
  the instagram/soundcloud/twitter families (not in Flowseal's Windows
  release), are refused. Every preset with sample rules checked by
  winws.exe --dry-run (tools/winws-dry-run.sh); one without the profile
  a rule copies is refused, as upstream refuses it.
- The SSH tunnel (sshProxy): Windows' own OpenSSH (System32) as ssh -N -D,
  with upstream's options and only the configured key offered
  (IdentitiesOnly: an agent's keys used up the server's tries); the key
  copied below the protected state root, as Windows' OpenSSH wants it and
  sing-box's SSH outbound reads it; the server's keys from hostKey,
  hostKeyFile or knownHostsFile. End to end on Linux against an sshd of
  the test's own: a page through each, two logins with the copied key.
- The dev shell has OpenSSH, for that test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 07:37:29 +03:00

298 lines
13 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);
}