XRay alone (proxy.backend = "xray"), as upstream's xray.nix and its start-time filter make it: the mixed-in listener with its login, DNS remote and local ordered by the route mode with the servers' names on local, IPIfNonMatch routing in upstream's order and modes, zapret's direct lists; urltest as prefixed tags under a leastPing balancer and observatory, a pin or first as one exit; chains by dialerProxy; Tor, SSH, WARP, AmneziaWG and whitelist-bypass as SOCKS hops. What needs sing-box is refused for it, as upstream asserts (TUN, groups, rule sets, autoProxy, selector/failover, DoT, dns.strategy and the like). The service checks it with xray run -test and runs it with its component's geodata (XRAY_LOCATION_ASSET); latency tests and autoProxy stand aside. zapret beside the TUN: winws2 gets the TUN's addresses left out in its --wf-raw-filter (with the cutoff probe's ports); Flowseal's winws, which takes no ANDed part, gets its own filter as it saves it (--wf-save) with them left out, through --wf-raw. WinDivert negates single tests only: the part is spelled positively, and compiled by WinDivert's own parser. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
624 lines
33 KiB
Rust
624 lines
33 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, cutoff) = (dir.join("direct.json"), dir.join("proxy.json"), dir.join("cutoff.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 cut = ps_core::zapret2::cutoff_rules("16509\n", "", "16509\t3.5.0.0/16\n16509\t2600:1f00::/32\n");
|
|
std::fs::write(&cutoff, serde_json::to_vec(&cut).unwrap()).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());
|
|
e.zapret2_cutoff_rule_set = Some(cutoff.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 - 3], json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
|
|
assert_eq!(rules[n - 2], json!({ "rule_set": ["zapret-cutoff"], "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", "zapret-cutoff"]);
|
|
state.route_mode = Some(RouteMode::AllBypass);
|
|
assert!(tags(&render_with(&state)).is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn helper_programs_go_direct_only_from_the_tun() {
|
|
let dir = scratch("direct-programs");
|
|
let mut cfg = base();
|
|
cfg.proxy.tun.enable = true;
|
|
let e = env(&dir);
|
|
let rules = |tun: bool| {
|
|
let sb = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun }).unwrap().sing_box.unwrap();
|
|
sb["route"]["rules"].as_array().unwrap().iter().filter(|r| r.get("process_path").is_some() && r["outbound"] == "direct").cloned().collect::<Vec<_>>()
|
|
};
|
|
// Through the local listener a helper (the service's own fetches) goes where the rules say.
|
|
assert!(rules(false).is_empty());
|
|
let under_tun = rules(true);
|
|
assert_eq!(under_tun.len(), 1);
|
|
assert_eq!(under_tun[0]["inbound"], json!(["tun-in"]));
|
|
}
|
|
|
|
/// The xray backend's config, rendered and checked by `xray run -test`.
|
|
fn render_xray(cfg: &Config, state: &State, dir: &Path) -> (Value, Vec<String>) {
|
|
let mut cfg = cfg.clone();
|
|
cfg.proxy.backend = Backend::Xray;
|
|
let r = render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &env(dir), read_file: &no_files, tun: false }).unwrap();
|
|
assert!(r.sing_box.is_none() && r.probe_exits.is_empty());
|
|
let x = r.xray.unwrap();
|
|
check_xray(&x, dir);
|
|
(x, r.warnings)
|
|
}
|
|
|
|
fn xray_rules(x: &Value) -> &Vec<Value> {
|
|
x["routing"]["rules"].as_array().unwrap()
|
|
}
|
|
|
|
fn xray_rule<'a>(x: &'a Value, tag: &str) -> Option<&'a Value> {
|
|
xray_rules(x).iter().find(|r| r["ruleTag"] == tag)
|
|
}
|
|
|
|
fn xray_tags(x: &Value) -> Vec<&str> {
|
|
x["outbounds"].as_array().unwrap().iter().map(|o| o["tag"].as_str().unwrap()).collect()
|
|
}
|
|
|
|
fn xray_dns_tags(x: &Value) -> Vec<&str> {
|
|
x["dns"]["servers"].as_array().unwrap().iter().map(|s| s["tag"].as_str().unwrap()).collect()
|
|
}
|
|
|
|
fn xray_base() -> Config {
|
|
let mut cfg = base();
|
|
cfg.proxy.outbounds[0] = outbound("nl", "trojan://pw@nl.example.com:443?sni=nl.example.com");
|
|
cfg
|
|
}
|
|
|
|
#[test]
|
|
fn xray_route_modes_change_the_final_the_lists_and_the_dns_order() {
|
|
let dir = scratch("xray-modes");
|
|
let mut cfg = xray_base();
|
|
cfg.proxy.routing.direct.domains = vec!["direct.example".into()];
|
|
cfg.proxy.routing.direct.geoips = vec!["cn".into()];
|
|
cfg.proxy.routing.block.domains = vec!["ads.example".into()];
|
|
cfg.proxy.routing.proxy.domains = vec!["proxy.example".into()];
|
|
cfg.proxy.routing.proxy.geosites = vec!["netflix".into()];
|
|
for (mode, final_ob, has_direct, remote_first) in [
|
|
(None, "nl", true, true),
|
|
(Some(RouteMode::Whitelist), "direct", true, false),
|
|
(Some(RouteMode::AllProxy), "nl", false, true),
|
|
(Some(RouteMode::AllBypass), "direct", false, false),
|
|
] {
|
|
let state = State { route_mode: mode, ..Default::default() };
|
|
let (x, _) = render_xray(&cfg, &state, &dir);
|
|
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], final_ob, "{mode:?}");
|
|
assert_eq!(xray_rule(&x, "direct-domain").is_some(), has_direct, "{mode:?}");
|
|
assert_eq!(xray_rule(&x, "direct-geoip").is_some(), has_direct, "{mode:?}");
|
|
// Block and the private-address safety stay in every mode.
|
|
assert_eq!(xray_rule(&x, "block-domain").unwrap()["outboundTag"], "block", "{mode:?}");
|
|
assert!(xray_rule(&x, "direct-private").is_some(), "{mode:?}");
|
|
let proxied = mode != Some(RouteMode::AllBypass);
|
|
assert_eq!(xray_rule(&x, "proxy-domain").is_some(), proxied, "{mode:?}");
|
|
assert_eq!(xray_rule(&x, "proxy-geosite").is_some(), proxied, "{mode:?}");
|
|
// The DNS server the mode prefers comes first.
|
|
assert_eq!(xray_dns_tags(&x)[0], if remote_first { "remote" } else { "local" }, "{mode:?}");
|
|
}
|
|
// The order of the lists: block ahead of direct, the geo lists of the proxy last.
|
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
|
let pos = |tag: &str| xray_rules(&x).iter().position(|r| r["ruleTag"] == tag).unwrap();
|
|
assert!(pos("proxy-domain") < pos("block-domain") && pos("block-domain") < pos("direct-domain"));
|
|
assert!(pos("direct-private") < pos("proxy-geosite") && pos("proxy-geosite") < pos("final-default"));
|
|
assert_eq!(xray_rule(&x, "proxy-geosite").unwrap()["domain"], json!(["geosite:netflix"]));
|
|
assert_eq!(xray_rule(&x, "direct-domain").unwrap()["domain"], json!(["domain:direct.example"]));
|
|
assert_eq!(x["routing"]["domainStrategy"], "IPIfNonMatch");
|
|
assert_eq!(x["routing"]["domainMatcher"], "hybrid");
|
|
}
|
|
|
|
#[test]
|
|
fn xray_dns_follows_routing_default_and_pins_the_proxy_servers() {
|
|
let dir = scratch("xray-dns");
|
|
let mut cfg = xray_base();
|
|
cfg.proxy.dns.remote = DnsUpstream { transport: DnsTransport::Tcp, address: "9.9.9.9".into(), port: 5353 };
|
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
|
// proxy: remote first; the copy of "local" that answers for the servers' names last.
|
|
assert_eq!(xray_dns_tags(&x), ["remote", "local", "local"]);
|
|
let servers = x["dns"]["servers"].as_array().unwrap();
|
|
assert_eq!(servers[0]["address"], "tcp://9.9.9.9");
|
|
assert_eq!(servers[0]["port"], 5353);
|
|
assert_eq!(servers[2]["domains"], json!(["full:de.example.com", "full:nl.example.com"]));
|
|
assert_eq!(servers[2]["skipFallback"], true);
|
|
assert!(servers[1].get("domains").is_none());
|
|
// The server's own queries: local direct, remote through the proxy.
|
|
assert_eq!(xray_rule(&x, "dns-upstream-direct").unwrap()["outboundTag"], "direct");
|
|
assert_eq!(xray_rule(&x, "dns-upstream-remote").unwrap()["outboundTag"], "nl");
|
|
cfg.proxy.routing.default = RouteDefault::Direct;
|
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
|
assert_eq!(xray_dns_tags(&x), ["local", "remote", "local"]);
|
|
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "direct");
|
|
// DoT has no XRay counterpart.
|
|
cfg.proxy.backend = Backend::Xray;
|
|
cfg.proxy.dns.local.transport = DnsTransport::Tls;
|
|
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("tls"), "{err}");
|
|
}
|
|
|
|
#[test]
|
|
fn xray_urltest_balances_and_a_pin_leaves_one_exit() {
|
|
let dir = scratch("xray-urltest");
|
|
let mut cfg = xray_base();
|
|
cfg.proxy.selection = Selection::Urltest;
|
|
cfg.proxy.url_test.url = "https://probe.example/204".into();
|
|
cfg.proxy.url_test.interval = "90s".into();
|
|
cfg.proxy.outbounds.push(outbound("ru", "trojan://pw@ru.example.com:443?sni=ru.example.com"));
|
|
cfg.proxy.outbounds[2].routing.domains = vec!["ru.example".into()];
|
|
cfg.proxy.selection_exclude = vec!["ru".into()];
|
|
cfg.proxy.routing.proxy.domains = vec!["proxy.example".into()];
|
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
|
assert_eq!(xray_tags(&x)[..3], ["proxy-suite-ob-nl", "proxy-suite-ob-de", "proxy-suite-ob-ru"]);
|
|
// The balancer takes what selection may pick, not the excluded outbound.
|
|
let candidates = json!(["proxy-suite-ob-nl", "proxy-suite-ob-de"]);
|
|
assert_eq!(x["routing"]["balancers"], json!([{ "tag": "proxy", "selector": candidates, "strategy": { "type": "leastPing" } }]));
|
|
assert_eq!(x["observatory"], json!({ "subjectSelector": candidates, "probeUrl": "https://probe.example/204", "probeInterval": "90s" }));
|
|
assert_eq!(xray_rule(&x, "final-default").unwrap()["balancerTag"], "proxy");
|
|
assert_eq!(xray_rule(&x, "proxy-domain").unwrap()["balancerTag"], "proxy");
|
|
assert_eq!(xray_rule(&x, "dns-upstream-remote").unwrap()["balancerTag"], "proxy");
|
|
// An outbound's own routing names it, renamed with the rest.
|
|
assert_eq!(xray_rule(&x, "custom-proxy-domain").unwrap()["outboundTag"], "proxy-suite-ob-ru");
|
|
|
|
// A pin: no balancer, no observatory, every "proxy" rule on the one exit.
|
|
let state = State { pin: Some("de".into()), ..Default::default() };
|
|
let (x, _) = render_xray(&cfg, &state, &dir);
|
|
assert!(x["routing"].get("balancers").is_none() && x.get("observatory").is_none());
|
|
for tag in ["final-default", "proxy-domain", "dns-upstream-remote"] {
|
|
let r = xray_rule(&x, tag).unwrap();
|
|
assert_eq!(r["outboundTag"], "proxy-suite-ob-de", "{tag}");
|
|
assert!(r.get("balancerTag").is_none(), "{tag}");
|
|
}
|
|
assert_eq!(xray_rule(&x, "custom-proxy-domain").unwrap()["outboundTag"], "proxy-suite-ob-ru");
|
|
|
|
// One selectable outbound is a pin of its own.
|
|
cfg.proxy.selection_exclude = vec!["ru".into(), "de".into()];
|
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
|
assert!(x["routing"].get("balancers").is_none() && x.get("observatory").is_none());
|
|
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "proxy-suite-ob-nl");
|
|
}
|
|
|
|
#[test]
|
|
fn xray_first_selection_takes_the_first_outbound_or_the_pin() {
|
|
let dir = scratch("xray-first");
|
|
let cfg = xray_base();
|
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
|
assert_eq!(xray_tags(&x), ["nl", "de", "direct", "block", "dns-out"]);
|
|
assert!(x["routing"].get("balancers").is_none() && x.get("observatory").is_none());
|
|
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "nl");
|
|
let state = State { pin: Some("de".into()), ..Default::default() };
|
|
let (x, _) = render_xray(&cfg, &state, &dir);
|
|
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "de");
|
|
// Every tag stays, so a rule naming another outbound still reaches it.
|
|
let mut cfg = cfg;
|
|
cfg.proxy.routing.rules.push(RoutingRule { outbound: "nl".into(), matches: RouteMatch { ips: vec!["203.0.113.0/24".into()], geoips: vec!["us".into()], ..Default::default() }, ..Default::default() });
|
|
cfg.proxy.routing.rules.push(RoutingRule { outbound: "direct".into(), matches: RouteMatch { domains: vec!["lan.example".into()], ..Default::default() }, ..Default::default() });
|
|
let (x, _) = render_xray(&cfg, &state, &dir);
|
|
assert_eq!(xray_rule(&x, "custom-proxy-ip").unwrap()["outboundTag"], "nl");
|
|
assert_eq!(xray_rule(&x, "custom-proxy-geoip").unwrap()["ip"], json!(["geoip:us"]));
|
|
assert_eq!(xray_rule(&x, "custom-direct-domain").unwrap()["outboundTag"], "direct");
|
|
}
|
|
|
|
#[test]
|
|
fn xray_listener_takes_a_login_and_guards_loopback() {
|
|
let dir = scratch("xray-listener");
|
|
let mut cfg = xray_base();
|
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
|
let inbound = &x["inbounds"][0];
|
|
assert_eq!(inbound["tag"], "mixed-in");
|
|
assert_eq!(inbound["protocol"], "socks");
|
|
assert_eq!(inbound["listen"], "127.0.0.1");
|
|
assert_eq!(inbound["port"], 1080);
|
|
assert_eq!(inbound["settings"]["auth"], "noauth");
|
|
assert_eq!(inbound["settings"]["udp"], true);
|
|
assert_eq!(x["inbounds"].as_array().unwrap().len(), 1);
|
|
cfg.proxy.listener.auth = ListenerAuth { username: Some("me".into()), password: Some("pw".into()), password_file: None };
|
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
|
assert_eq!(x["inbounds"][0]["settings"]["auth"], "password");
|
|
assert_eq!(x["inbounds"][0]["settings"]["accounts"], json!([{ "user": "me", "pass": "pw" }]));
|
|
// Nothing reaches this host's loopback: by address or name through the listener, or from a
|
|
// name the direct outbound resolves.
|
|
assert_eq!(xray_rule(&x, "guard-loopback-ip").unwrap()["outboundTag"], "block");
|
|
assert_eq!(xray_rule(&x, "guard-loopback-domain").unwrap()["domain"], json!(["domain:localhost"]));
|
|
let direct = x["outbounds"].as_array().unwrap().iter().find(|o| o["tag"] == "direct").unwrap();
|
|
assert_eq!(direct["settings"]["finalRules"].as_array().unwrap().last().unwrap()["action"], "block");
|
|
}
|
|
|
|
#[test]
|
|
fn xray_chains_and_helpers_are_xray_outbounds() {
|
|
let dir = scratch("xray-chain");
|
|
let mut cfg = xray_base();
|
|
cfg.proxy.outbounds.push(Outbound { detour: Some("nl".into()), ..outbound("chained", "trojan://pw@t.example.com:443?sni=t.example.com") });
|
|
cfg.proxy.outbounds.push(Outbound { tag: "raw".into(), xray_json: Some(serde_json::from_value(json!({ "protocol": "freedom", "settings": {} })).unwrap()), ..Default::default() });
|
|
cfg.tor.enable = true;
|
|
cfg.tor.as_outbound = true;
|
|
cfg.warp.enable = true;
|
|
cfg.warp.as_outbound = Some(WarpOutboundKind::Userspace);
|
|
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.whitelist_bypass.enable = true;
|
|
cfg.whitelist_bypass.joiners.insert("wl".into(), WlJoiner { platform: WlPlatform::Wbstream, link_file: None });
|
|
cfg.proxy.routing.rules.push(RoutingRule { outbound: "gone".into(), matches: RouteMatch { domains: vec!["x.example".into()], ..Default::default() }, ..Default::default() });
|
|
for urltest in [false, true] {
|
|
cfg.proxy.selection = if urltest { Selection::Urltest } else { Selection::First };
|
|
let (x, warnings) = render_xray(&cfg, &State::default(), &dir);
|
|
let prefix = if urltest { "proxy-suite-ob-" } else { "" };
|
|
let ob = |tag: &str| x["outbounds"].as_array().unwrap().iter().find(|o| o["tag"] == format!("{prefix}{tag}")).unwrap_or_else(|| panic!("no {tag}: {:?}", xray_tags(&x)));
|
|
assert_eq!(ob("chained")["streamSettings"]["sockopt"]["dialerProxy"], format!("{prefix}nl"));
|
|
// The helpers' loopback SOCKS listeners, with the hop login where the service set one.
|
|
let tor = ob("tor");
|
|
assert_eq!(tor["protocol"], "socks");
|
|
assert_eq!(tor["settings"]["address"], "127.0.0.1");
|
|
assert!(tor["settings"].get("user").is_none());
|
|
assert!(ob("ssh-proxy")["settings"].get("user").is_none());
|
|
assert_eq!(ob("warp")["settings"]["user"], "hop");
|
|
assert_eq!(ob("warp")["settings"]["pass"], "hop-pass");
|
|
assert_eq!(ob("wl")["settings"]["user"], "hop");
|
|
assert_eq!(ob("raw")["protocol"], "freedom");
|
|
// Tor is for what is routed to it: not selected on its own.
|
|
assert_eq!(xray_rule(&x, "final-default").unwrap().get("balancerTag").is_some(), urltest);
|
|
if urltest {
|
|
let selector = x["routing"]["balancers"][0]["selector"].as_array().unwrap();
|
|
assert!(!selector.contains(&json!("proxy-suite-ob-tor")), "{selector:?}");
|
|
}
|
|
assert_eq!(xray_rule(&x, "tor-onion").unwrap()["outboundTag"], format!("{prefix}tor"));
|
|
assert_eq!(xray_rule(&x, "custom-block-domain").unwrap()["outboundTag"], "block");
|
|
assert!(warnings.iter().any(|w| w.contains("'gone'")), "{warnings:?}");
|
|
}
|
|
// Endpoints are sing-box's: left out, with a word.
|
|
cfg.warp.as_outbound = Some(WarpOutboundKind::SingBox);
|
|
let (x, warnings) = render_xray(&cfg, &State::default(), &dir);
|
|
assert!(!xray_tags(&x).contains(&"warp"));
|
|
assert!(warnings.iter().any(|w| w.contains("WARP")), "{warnings:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn xray_zapret_direct_lists_go_direct() {
|
|
let dir = scratch("xray-zapret");
|
|
let cfg = xray_base();
|
|
let mut e = env(&dir);
|
|
e.zapret_direct = RouteMatch { domains: vec!["blocked.example".into()], ips: vec!["198.51.100.0/24".into()], ..Default::default() };
|
|
// zapret2's runtime rule-sets are sing-box's: pure XRay has no equivalent.
|
|
e.zapret2_direct_rule_set = Some("zapret.json".into());
|
|
let mut cfg = cfg;
|
|
cfg.proxy.backend = Backend::Xray;
|
|
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap();
|
|
let x = r.xray.unwrap();
|
|
check_xray(&x, &dir);
|
|
let domains = xray_rule(&x, "direct-domain").unwrap();
|
|
assert_eq!(domains["outboundTag"], "direct");
|
|
assert!(domains["domain"].as_array().unwrap().contains(&json!("domain:blocked.example")));
|
|
assert!(xray_rule(&x, "direct-ip").unwrap()["ip"].as_array().unwrap().contains(&json!("198.51.100.0/24")));
|
|
assert!(!x.to_string().contains("zapret.json"));
|
|
}
|
|
|
|
#[test]
|
|
fn xray_backend_refuses_what_it_cannot_do() {
|
|
let mut cfg = xray_base();
|
|
cfg.proxy.backend = Backend::Xray;
|
|
let refused = |cfg: &Config| -> Vec<String> {
|
|
ps_core::config::validate(cfg).into_iter().filter(|i| i.severity == Severity::Error).map(|i| i.path).collect()
|
|
};
|
|
assert!(refused(&cfg).is_empty(), "{:?}", refused(&cfg));
|
|
let mut c = cfg.clone();
|
|
c.proxy.selection = Selection::Selector;
|
|
assert!(refused(&c).contains(&"proxy.selection".to_owned()));
|
|
let mut c = cfg.clone();
|
|
c.proxy.tun.enable = true;
|
|
assert!(refused(&c).contains(&"proxy.tun.enable".to_owned()));
|
|
let mut c = cfg.clone();
|
|
c.proxy.dns.remote.transport = DnsTransport::Tls;
|
|
assert!(refused(&c).contains(&"proxy.dns".to_owned()));
|
|
let mut c = cfg.clone();
|
|
c.proxy.dns.strategy = Some(DomainStrategy::Ipv4Only);
|
|
assert!(refused(&c).contains(&"proxy.dns.strategy".to_owned()));
|
|
let mut c = cfg.clone();
|
|
c.debug.connection_log.enable = true;
|
|
assert!(refused(&c).contains(&"debug.connectionLog.enable".to_owned()));
|
|
// The TUN is refused at render too, whatever the validation was told.
|
|
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&scratch("xray-tun")), read_file: &no_files, tun: true });
|
|
assert!(r.unwrap_err().0.contains("TUN"));
|
|
}
|