Files
proxy-suite-flake/windows/crates/ps-core/tests/render.rs
T
faumarayandClaude Opus 5.5 514ffb97ca windows: zapret2's verdicts route the proxy; options kept to what they are
As upstream's direct-sync: from zapret2's lists and the detector's
verdicts, two rule-sets sing-box reloads, rebuilt every ten seconds and
before it starts: what zapret2 cannot fix (every strategy failed for a
site, or an address leaves connections unanswered) through the proxy
(zapret2.proxyFallback), after the explicit rules and autoProxy's; what
it fixes direct, so it sees it (directSync), unless learned from
transfers cut short. all-bypass and all-proxy as upstream.

The options file winws2 reads (one a line) refuses an option holding a
control character, which would read as more options than it is; and
zapret2.ports.extraTcp/extraUdp, which join its options as written, are
ports or ranges within 1-65535 (validated, and filtered again).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:16:48 +03:00

318 lines
16 KiB
Rust

//! Rendered configs, checked by the backends themselves: `sing-box check` and
//! `xray run -test`, when they are on PATH (the dev shell has both).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use ps_core::config::*;
use ps_core::render::{Env, Input, RouteMode, State, render};
use serde_json::{Value, json};
const PBK: &str = "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc";
const WGCF: &str = "[Interface]\nPrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\nAddress = 172.16.0.2/32, 2606:4700:110:8a36::2/128\nMTU = 1280\n\n[Peer]\nPublicKey = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = engage.cloudflareclient.com:2408\n";
fn have(bin: &str) -> bool {
Command::new(bin).arg("version").output().is_ok()
}
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("ps-core-render-{}-{name}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn env(dir: &Path) -> Env {
let empty = dir.join("empty.json");
std::fs::write(&empty, r#"{"version":1,"rules":[]}"#).unwrap();
let mut warp = BTreeMap::new();
warp.insert("warp".to_owned(), WGCF.to_owned());
Env {
empty_rule_set: empty.to_string_lossy().into(),
cache_dir: dir.to_string_lossy().into(),
clash_secret: Some("s3cret".into()),
hop_login: Some(("hop".into(), "hop-pass".into())),
warp_profiles: warp,
direct_processes: vec![r"C:\ProgramData\ProxySuite\bin\tor\tor.exe".into()],
groups_watched: false,
sidecar_secret: "0b1c2d3e-4f50-6172-8394-a5b6c7d8e9f0".into(),
windows: true,
..Default::default()
}
}
fn no_files(path: &str) -> Result<String, String> {
Err(format!("{path}: not found"))
}
fn check_sing_box(config: &Value, dir: &Path) {
if !have("sing-box") {
eprintln!("sing-box not on PATH: skipping the check");
return;
}
let path = dir.join("sing-box.json");
std::fs::write(&path, serde_json::to_string_pretty(config).unwrap()).unwrap();
let out = Command::new("sing-box").args(["check", "-c"]).arg(&path).output().unwrap();
assert!(
out.status.success(),
"sing-box check failed:\n{}\n{}",
String::from_utf8_lossy(&out.stderr),
serde_json::to_string_pretty(config).unwrap()
);
}
fn check_xray(config: &Value, dir: &Path) {
if !have("xray") {
return;
}
let path = dir.join("xray.json");
std::fs::write(&path, serde_json::to_string_pretty(config).unwrap()).unwrap();
let out = Command::new("xray").args(["run", "-test", "-c"]).arg(&path).output().unwrap();
assert!(
out.status.success(),
"xray -test failed:\n{}{}\n{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
serde_json::to_string_pretty(config).unwrap()
);
}
fn outbound(tag: &str, url: &str) -> Outbound {
Outbound { tag: tag.into(), url: Some(url.into()), ..Default::default() }
}
fn base() -> Config {
let mut cfg = Config::default();
cfg.proxy.enable = true;
cfg.proxy.outbounds = vec![
outbound("nl", "hy2://pw@nl.example.com:443?sni=nl.example.com"),
outbound("de", &format!("vless://00000000-0000-0000-0000-000000000000@de.example.com:443?security=reality&pbk={PBK}&sid=ab&sni=www.microsoft.com&fp=chrome&flow=xtls-rprx-vision")),
];
cfg
}
#[test]
fn a_minimal_proxy_checks() {
let dir = scratch("minimal");
let cfg = base();
let r = render(&Input {
cfg: &cfg,
state: &State::default(),
subscriptions: &BTreeMap::new(),
env: &env(&dir),
read_file: &no_files,
tun: false,
})
.unwrap();
let sb = r.sing_box.unwrap();
assert_eq!(sb["outbounds"][0], json!({ "type": "selector", "tag": "proxy", "outbounds": ["nl"], "default": "nl" }));
assert_eq!(sb["route"]["final"], "proxy");
assert_eq!(r.inventory.top, ["nl", "de"]);
check_sing_box(&sb, &dir);
}
#[test]
fn everything_at_once_checks() {
let dir = scratch("full");
let mut cfg = base();
let p = &mut cfg.proxy;
p.selection = Selection::Urltest;
p.listener.auth = ListenerAuth { username: Some("me".into()), password: Some("pw".into()), password_file: None };
p.outbounds.push(Outbound { detour: Some("nl".into()), ..outbound("chained", "trojan://pw@t.example.com:443?sni=t.example.com") });
p.outbounds.push(outbound("broken", "vless://uuid@x.example.com:70000"));
p.outbounds[1].routing.geosites = vec!["netflix".into()];
p.subscriptions.push(Subscription { tag: "sub".into(), url: Some("https://sub.example.com/x".into()), ..Default::default() });
p.groups.insert("eu".into(), Group { outbounds: vec!["de".into()], subscriptions: vec!["sub".into()], ..Default::default() });
p.groups.insert("fast".into(), Group { match_: vec!["sub-*".into()], strategy: GroupStrategy::Urltest, ..Default::default() });
p.routing.rules.push(RoutingRule {
outbound: "eu".into(),
matches: RouteMatch { domains: vec!["example.org".into()], ips: vec!["203.0.113.0/24".into()], ..Default::default() },
process_names: vec!["Telegram.exe".into()],
..Default::default()
});
p.routing.rules.push(RoutingRule { name: Some("early".into()), priority: Some(10), outbound: "direct".into(), matches: RouteMatch { domains: vec!["bank.example".into()], ..Default::default() }, ..Default::default() });
p.routing.rules.push(RoutingRule { outbound: "gone".into(), matches: RouteMatch { domains: vec!["x.example".into()], ..Default::default() }, ..Default::default() });
p.routing.block.geosites = vec!["category-ads-all".into()];
p.routing.rule_sets.insert("antifilter".into(), RuleSet { url: "https://example.com/antifilter.srs".into(), format: None, detour: RuleSetDetour::Proxy });
p.routing.proxy.rule_sets = vec!["antifilter".into()];
p.tun.enable = true;
p.dns.fake_ip.enable = true;
p.dns.strategy = Some(DomainStrategy::Ipv4Only);
cfg.per_app_routing.enable = true;
cfg.per_app_routing.profiles.push(PerAppProfile { name: "games".into(), outbound: "direct".into(), process_names: vec!["steam.exe".into()], ..Default::default() });
cfg.tor.enable = true;
cfg.tor.as_outbound = true;
cfg.warp.enable = true;
cfg.warp.as_outbound = Some(WarpOutboundKind::SingBox);
cfg.ssh_proxy.enable = true;
cfg.ssh_proxy.as_outbound = true;
cfg.ssh_proxy.server = SshServer { user: Some("root".into()), host: Some("ssh.example.com".into()), port: 22 };
cfg.ssh_proxy.host_key = vec!["ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl".into()];
cfg.whitelist_bypass.enable = true;
cfg.whitelist_bypass.joiners.insert("wl".into(), WlJoiner { platform: WlPlatform::Wbstream, link_file: None });
let mut subs = BTreeMap::new();
subs.insert("sub".to_owned(), vec![
"hy2://pw@a.example.com:443#A".to_owned(),
"hy2://pw@b.example.com:443#B".to_owned(),
"hy2://pw@127.0.0.1:443#Loop".to_owned(),
]);
let mut state = State::default();
state.disabled.push("sub-B".into());
let r = render(&Input { cfg: &cfg, state: &state, subscriptions: &subs, env: &env(&dir), read_file: &no_files, tun: true }).unwrap();
let sb = r.sing_box.unwrap();
let tags: Vec<&str> = sb["outbounds"].as_array().unwrap().iter().map(|o| o["tag"].as_str().unwrap()).collect();
assert!(tags.contains(&"chained") && !tags.contains(&"broken"), "{tags:?}");
assert!(r.warnings.iter().any(|w| w.contains("'broken'")), "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.contains("'gone'")), "{:?}", r.warnings);
let gone = sb["route"]["rules"].as_array().unwrap().iter().find(|r| r["domain_suffix"] == json!(["x.example"])).unwrap();
assert_eq!(gone["outbound"], "block");
assert_eq!(sb["endpoints"][0]["tag"], "warp");
assert_eq!(r.inventory.detours["chained"], "nl");
assert!(r.inventory.excluded.contains(&"tor".to_owned()));
assert!(r.inventory.disabled.contains(&"sub-B".to_owned()));
// The early rule sorts ahead of the configuration's own.
let rules = sb["route"]["rules"].as_array().unwrap();
let early = rules.iter().position(|r| r["domain_suffix"] == json!(["bank.example"])).unwrap();
let eu = rules.iter().position(|r| r["domain_suffix"] == json!(["example.org"])).unwrap();
assert!(early < eu);
assert_eq!(sb["inbounds"].as_array().unwrap().last().unwrap()["type"], "tun");
check_sing_box(&sb, &dir);
}
#[test]
fn hybrid_hands_xhttp_to_the_sidecar() {
let dir = scratch("hybrid");
let mut cfg = base();
cfg.proxy.backend = Backend::Hybrid;
cfg.proxy.outbounds.push(outbound("xh", "vless://00000000-0000-0000-0000-000000000000@x.example.com:443?security=tls&sni=x.example.com&type=xhttp&path=%2Fx&mode=packet-up"));
cfg.proxy.xray.xhttp_xmux = Some(BTreeMap::from([("maxConnections".to_owned(), json!(3))]));
cfg.proxy.selection = Selection::Selector;
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap();
let sb = r.sing_box.unwrap();
let hop = sb["outbounds"].as_array().unwrap().iter().find(|o| o["tag"] == "xh").unwrap();
assert_eq!(hop["type"], "vless");
assert_eq!(r.inventory.runs_on["xh"], "xray");
let xray = r.xray.unwrap();
assert_eq!(xray["outbounds"][0]["streamSettings"]["xhttpSettings"]["extra"]["xmux"]["maxConnections"], 3);
check_sing_box(&sb, &dir);
check_xray(&xray, &dir);
}
#[test]
fn route_modes_change_the_final_and_the_lists() {
let dir = scratch("modes");
let mut cfg = base();
cfg.proxy.routing.direct.domains = vec!["direct.example".into()];
cfg.proxy.routing.block.domains = vec!["ads.example".into()];
for (mode, final_ob, has_direct) in [
(None, "proxy", true),
(Some(RouteMode::Whitelist), "direct", true),
(Some(RouteMode::AllProxy), "proxy", false),
(Some(RouteMode::AllBypass), "direct", false),
] {
let state = State { route_mode: mode, ..Default::default() };
let r = render(&Input { cfg: &cfg, state: &state, subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap();
let sb = r.sing_box.unwrap();
assert_eq!(sb["route"]["final"], final_ob, "{mode:?}");
let rules = sb["route"]["rules"].as_array().unwrap();
assert_eq!(rules.iter().any(|r| r["domain_suffix"] == json!(["direct.example"])), has_direct, "{mode:?}");
assert!(rules.iter().any(|r| r["domain_suffix"] == json!(["ads.example"])), "{mode:?}");
check_sing_box(&sb, &dir);
}
}
#[test]
fn no_outbounds_is_an_error() {
let dir = scratch("none");
let mut cfg = Config::default();
cfg.proxy.enable = true;
let err = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap_err();
assert!(err.0.contains("no proxy outbounds"));
}
#[test]
fn auto_proxy_adds_probe_listeners_and_learned_rules() {
let dir = scratch("autoproxy");
let mut cfg = base();
cfg.proxy.auto_proxy.enable = true;
cfg.proxy.auto_proxy.max_exits = 2;
let rules_dir = dir.join("rules");
std::fs::create_dir_all(&rules_dir).unwrap();
std::fs::write(rules_dir.join("rs-1.json"), r#"{"version":1,"rules":[{"domain_suffix":["blocked.example"]}]}"#).unwrap();
let mut e = env(&dir);
e.autoproxy_rules_dir = Some(rules_dir.to_string_lossy().into());
e.windows = false;
let mut state = State::default();
let render_with = |state: &State| {
render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap()
};
let r = render_with(&state);
// direct, then the first exit: maxExits 2.
assert_eq!(r.probe_exits.iter().map(|x| (x.tag.as_str(), x.port)).collect::<Vec<_>>(), [("direct", 18540), ("nl", 18541)]);
let sb = r.sing_box.unwrap();
let probe_in: Vec<&Value> = sb["inbounds"].as_array().unwrap().iter().filter(|i| i["tag"].as_str().unwrap().starts_with("probe-in-")).collect();
assert_eq!(probe_in.len(), 2);
assert_eq!(probe_in[1]["users"], json!([{ "username": "hop", "password": "hop-pass" }]));
let rules = sb["route"]["rules"].as_array().unwrap();
let guard = rules.iter().position(|r| r["domain"] == json!(["localhost"])).unwrap();
let pin = rules.iter().position(|r| r["inbound"] == json!(["probe-in-1"])).unwrap();
assert!(pin > guard, "the probes stay behind the loopback guard");
assert_eq!(rules.last().unwrap(), &json!({ "rule_set": ["autoproxy-1"], "outbound": "nl" }));
assert!(sb["dns"]["rules"].as_array().unwrap().contains(&json!({ "rule_set": ["autoproxy-1"], "server": "remote" })));
check_sing_box(&sb, &dir);
// all-bypass: everything direct, learned routes too.
state.route_mode = Some(RouteMode::AllBypass);
let sb = render_with(&state).sing_box.unwrap();
assert!(!sb["route"]["rules"].as_array().unwrap().iter().any(|r| r["rule_set"] == json!(["autoproxy-1"]) && r.get("outbound").is_some()));
}
#[test]
fn auto_proxy_never_routes_what_it_excludes() {
let dir = scratch("autoproxy-exclude");
let mut cfg = base();
cfg.proxy.auto_proxy.enable = true;
cfg.proxy.auto_proxy.max_exits = 2;
cfg.proxy.auto_proxy.exclude = vec!["intranet.example.com".into()];
let rules_dir = dir.join("rules");
std::fs::create_dir_all(&rules_dir).unwrap();
std::fs::write(rules_dir.join("rs-1.json"), r#"{"version":1,"rules":[{"domain_suffix":["example.com"]}]}"#).unwrap();
let mut e = env(&dir);
e.autoproxy_rules_dir = Some(rules_dir.to_string_lossy().into());
e.windows = false;
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap();
let sb = r.sing_box.unwrap();
assert_eq!(
sb["route"]["rules"].as_array().unwrap().last().unwrap(),
&json!({ "type": "logical", "mode": "and", "rules": [{ "rule_set": ["autoproxy-1"] }, { "domain_suffix": ["intranet.example.com"], "invert": true }], "outbound": "nl" })
);
check_sing_box(&sb, &dir);
}
#[test]
fn zapret2s_rule_sets_follow_autoproxy_and_the_mode() {
let dir = scratch("zapret2-sync");
let (direct, proxy) = (dir.join("direct.json"), dir.join("proxy.json"));
std::fs::write(&direct, r#"{"version":1,"rules":[{"domain_suffix":["fixed.example"]}]}"#).unwrap();
std::fs::write(&proxy, r#"{"version":1,"rules":[{"domain_suffix":["unfixable.example"]}]}"#).unwrap();
let cfg = base();
let mut e = env(&dir);
e.windows = false;
e.zapret2_direct_rule_set = Some(direct.to_string_lossy().into());
e.zapret2_proxy_rule_set = Some(proxy.to_string_lossy().into());
let render_with = |state: &State| render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap().sing_box.unwrap();
let sb = render_with(&State::default());
let rules = sb["route"]["rules"].as_array().unwrap();
let n = rules.len();
assert_eq!(rules[n - 2], json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
assert_eq!(rules[n - 1], json!({ "rule_set": ["zapret-hosts"], "outbound": "direct" }));
check_sing_box(&sb, &dir);
// all-proxy keeps no direct lists; all-bypass sends everything direct.
let mut state = State { route_mode: Some(RouteMode::AllProxy), ..Default::default() };
let tags = |sb: &Value| sb["route"]["rules"].as_array().unwrap().iter().filter_map(|r| r["rule_set"][0].as_str().map(str::to_owned)).collect::<Vec<_>>();
assert_eq!(tags(&render_with(&state)), ["zapret-unfixable"]);
state.route_mode = Some(RouteMode::AllBypass);
assert!(tags(&render_with(&state)).is_empty());
}