//! 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::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: &PathBuf) -> 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 { Err(format!("{path}: not found")) } fn check_sing_box(config: &Value, dir: &PathBuf) { 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: &PathBuf) { 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")); }