ps-ipc: line-delimited JSON over a named pipe whose ACL admits SYSTEM, Administrators and (with userControl) the interactive user; the caller is identified by impersonation, never by what it claims. A Unix socket stands in off Windows. ps-service (proxy-suite-service.exe): a Windows service, or --console. Keeps the configuration with revisions, runtime state and generated secrets; renders, checks with sing-box check before replacing what runs, and supervises the backends (restart with backoff, start limit, logs in a ring and a file, a Job Object on Windows). Enforces scopes, admin-only edits and secret redaction that round-trips. Fetches subscriptions and rule sets through the proxy or directly with upstream's redirect rules, on timers. ps-ctl (proxy-ctl.exe): status, restart, logs [-f], config get/set/ validate, and proxy on/off, outbounds, pin, mode, subs, rules, rulesets, tun and config. An end-to-end test runs it all offline: a sing-box Shadowsocks server, the service, proxy-ctl adding the outbound, a page fetched through the local proxy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
190 lines
7.9 KiB
Rust
190 lines
7.9 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);
|
|
}
|