//! The API: who may do what, and doing it. use ps_core::config::{Config, Issue, Scope, Severity, privileged_changes, validate}; use ps_core::render::RouteMode; use ps_ipc::transport::{Conn, Server}; use ps_ipc::{Peer, Request, Response}; use serde_json::{Value, json}; use crate::service::{self, Shared}; /// What stands in for a secret a caller may not read. Sent back unchanged, it keeps the /// value it hides. pub const REDACTED: &str = "\u{2022}\u{2022}\u{2022}redacted\u{2022}\u{2022}\u{2022}"; /// Option paths holding secrets (`*`: any key or list entry). const SECRET_PATHS: [&str; 19] = [ "proxy.outbounds.*.url", "proxy.outbounds.*.singBoxJson", "proxy.outbounds.*.xrayJson", "proxy.subscriptions.*.url", "proxy.listener.auth.password", "amneziaWg.profiles.*.config", "amneziaWg.profiles.*.vpn", "amneziaWg.profiles.*.settings.privateKey", "amneziaWg.profiles.*.settings.peers.*.presharedKey", "amneziaWg.profiles.*.settings.obfuscation.headerProtectionKey", "warp.config", "warp.devices.*.config", "tgWsProxy.secret", "inbounds.users.*.uuid", "inbounds.users.*.password", "inbounds.listeners.*.serverPassword", "inbounds.listeners.*.reality.privateKey", "inbounds.listeners.*.hysteria.salamander.password", "inbounds.listeners.*.xrayJson", ]; fn redact_at(value: &mut Value, path: &[&str]) { let Some((head, rest)) = path.split_first() else { if !value.is_null() { *value = REDACTED.into(); } return; }; match value { Value::Object(map) => { if *head == "*" { map.values_mut().for_each(|v| redact_at(v, rest)); } else if let Some(v) = map.get_mut(*head) { redact_at(v, rest); } } Value::Array(list) if *head == "*" => list.iter_mut().for_each(|v| redact_at(v, rest)), _ => {} } } pub fn redact(config: &Config) -> Value { let mut v = serde_json::to_value(config).expect("the config serializes"); for p in SECRET_PATHS { redact_at(&mut v, &p.split('.').collect::>()); } v } /// The entry of `old` a list entry of `new` stands for: by its tag or name, else its index. fn counterpart<'a>(old: &'a [Value], new: &Value, index: usize) -> Option<&'a Value> { for key in ["tag", "name"] { if let Some(id) = new.get(key).filter(|v| v.is_string()) { return old.iter().find(|o| o.get(key) == Some(id)); } } old.get(index) } fn unredact_at(new: &mut Value, old: Option<&Value>, path: &[&str]) { let Some((head, rest)) = path.split_first() else { if new.as_str() == Some(REDACTED) { *new = old.cloned().unwrap_or(Value::Null); } return; }; match new { Value::Object(map) => { let old_map = old.and_then(Value::as_object); if *head == "*" { for (k, v) in map.iter_mut() { unredact_at(v, old_map.and_then(|m| m.get(k)), rest); } } else if let Some(v) = map.get_mut(*head) { unredact_at(v, old_map.and_then(|m| m.get(*head)), rest); } } Value::Array(list) if *head == "*" => { let old_list = old.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]); for (i, v) in list.iter_mut().enumerate() { let o = counterpart(old_list, v, i).cloned(); unredact_at(v, o.as_ref(), rest); } } _ => {} } } /// `new` with every placeholder replaced by the value it hid in `old`. pub fn unredact(new: &mut Value, old: &Config) { let old = serde_json::to_value(old).expect("the config serializes"); for p in SECRET_PATHS { unredact_at(new, Some(&old), &p.split('.').collect::>()); } } /// Whether `peer` may use `scope`, under `cfg.userControl`. fn allowed(cfg: &Config, peer: &Peer, scope: Option) -> Result<(), String> { if peer.admin { return Ok(()); } let Some(scope) = scope else { return Ok(()) }; let uc = &cfg.user_control; if !uc.enable { return Err("this needs an administrator (userControl is off)".into()); } if uc.scopes.is_empty() || uc.scopes.contains(&scope) { Ok(()) } else { Err(format!("this needs the {scope:?} scope, which userControl does not give").to_lowercase()) } } fn scope_of(req: &Request) -> Option { match req { Request::ConfigSet { .. } => Some(Scope::Config), Request::Pin { .. } | Request::Mode { .. } | Request::RuleSetsUpdate => Some(Scope::Routing), Request::Disable { .. } | Request::SubsUpdate { .. } | Request::Test { .. } => Some(Scope::Outbounds), // Backend logs name the sites visited (at info), and errors may quote what was dialled. Request::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets), Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services), _ => None, } } fn has_secrets(cfg: &Config, peer: &Peer) -> bool { allowed(cfg, peer, Some(Scope::Secrets)).is_ok() } fn issues_json(issues: &[Issue]) -> Value { serde_json::to_value(issues).unwrap() } /// Serves the API until the process ends. pub async fn serve(mut server: Server, shared: Shared) { loop { match server.accept().await { Ok(conn) => { let shared = shared.clone(); tokio::spawn(async move { connection(conn, shared).await }); } Err(e) => { tracing::warn!("accepting a client: {e}"); tokio::time::sleep(std::time::Duration::from_millis(200)).await; } } } } async fn connection(mut conn: Conn, shared: Shared) { loop { let req: Request = match conn.read_json().await { Ok(Some(r)) => r, Ok(None) => return, Err(e) => { let _ = conn.write_json(&Response::err(format!("bad request: {e}"))).await; return; } }; let peer = conn.peer(); // Every request, streamed or not, is authorized here before anything is done for it. let denied = { let s = shared.lock().await; allowed(s.cfg(), &peer, scope_of(&req)).err() }; if let Some(e) = denied { if conn.write_json(&Response::err(e)).await.is_err() { return; } continue; } if let Request::Logs { unit, lines, follow: true } = &req { follow_logs(&mut conn, &shared, unit.clone(), *lines).await; return; } let resp = handle(req, &peer, &shared).await; if conn.write_json(&resp).await.is_err() { return; } } } async fn follow_logs(conn: &mut Conn, shared: &Shared, unit: Option, lines: usize) { let (backlog, mut feed) = { let s = shared.lock().await; (s.sup.tail(unit.as_deref(), lines), s.sup.subscribe()) }; for line in backlog { if conn.write_json(&Response::partial(json!(line))).await.is_err() { return; } } loop { match feed.recv().await { Ok(line) if unit.as_ref().is_none_or(|u| *u == line.unit) => { if conn.write_json(&Response::partial(json!(line))).await.is_err() { return; } } Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {} Err(_) => return, } } } /// Does what `req` asks; the caller has authorized it (`connection`). pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response { match req { Request::Status => Response::ok(shared.lock().await.status()), Request::ConfigGet => { let s = shared.lock().await; let config = if has_secrets(s.cfg(), peer) { serde_json::to_value(s.cfg()).unwrap() } else { redact(s.cfg()) }; Response::ok(json!({ "config": config, "revision": s.store.revision, "redacted": !has_secrets(s.cfg(), peer) })) } Request::ConfigValidate { config } => match serde_json::from_value::(config) { Ok(cfg) => Response::ok(json!({ "issues": issues_json(&validate(&cfg)) })), Err(e) => Response::err(format!("not a configuration: {e}")), }, Request::ConfigSet { mut config, base } => { let mut s = shared.lock().await; if let Some(base) = base && base != s.store.revision { return Response::err(format!("the configuration changed since revision {base} (now {}): read it again", s.store.revision)); } unredact(&mut config, s.cfg()); let new: Config = match serde_json::from_value(config) { Ok(c) => c, Err(e) => return Response::err(format!("not a configuration: {e}")), }; let issues = validate(&new); if issues.iter().any(|i| i.severity == Severity::Error) { return Response { ok: false, error: Some("the configuration has errors".into()), data: json!({ "issues": issues_json(&issues) }), more: false }; } if !peer.admin { let privileged = privileged_changes(s.cfg(), &new); if !privileged.is_empty() { return Response { ok: false, error: Some(format!("only an administrator may change {}", privileged.join(", "))), data: json!({ "privileged": privileged }), more: false, }; } } let subs_before: Vec = s.cfg().proxy.subscriptions.iter().map(|x| x.tag.clone()).collect(); if let Err(e) = s.store.save_config(new) { return Response::err(format!("cannot save the configuration: {e}")); } tracing::info!("configuration revision {} set by {}", s.store.revision, peer.user); let new_subs: Vec = s.cfg().proxy.subscriptions.iter().map(|x| x.tag.clone()).filter(|t| !subs_before.contains(t)).collect(); let applied = s.apply().await; let revision = s.store.revision; drop(s); // A new subscription is fetched at once, as upstream fetches on first start. for tag in new_subs { let shared = shared.clone(); tokio::spawn(async move { service::update_subscriptions(&shared, Some(&tag)).await }); } { let shared = shared.clone(); tokio::spawn(async move { service::update_rule_sets(&shared, true).await }); } { let shared = shared.clone(); tokio::spawn(async move { service::register_warp(&shared).await }); } Response::ok(json!({ "revision": revision, "issues": issues_json(&issues), "applied": applied.as_ref().map(|_| true).unwrap_or(false), "error": applied.err().map(|e| e.to_string()), })) } Request::StateGet => Response::ok(serde_json::to_value(&shared.lock().await.store.state).unwrap()), Request::Pin { tag, group } => { let mut s = shared.lock().await; match group { Some(g) => match tag { Some(t) => { s.store.state.group_pins.insert(g, t); } None => { s.store.state.group_pins.remove(&g); } }, None => s.store.state.pin = tag, } finish_state(&mut s).await } Request::Disable { tag, disabled } => { let mut s = shared.lock().await; s.store.state.disabled.retain(|t| *t != tag); if disabled { s.store.state.disabled.push(tag); } finish_state(&mut s).await } Request::Mode { mode } => { let mut s = shared.lock().await; s.store.state.route_mode = match mode.as_deref() { None | Some("default") => None, Some(m) => match serde_json::from_value::(json!(m)) { Ok(m) => Some(m), Err(_) => return Response::err(format!("unknown mode '{m}': default, whitelist, blacklist, all-proxy or all-bypass")), }, }; finish_state(&mut s).await } Request::Outbounds => { let s = shared.lock().await; let secrets = has_secrets(s.cfg(), peer); match &s.last { Some(r) => { let mut inv = serde_json::to_value(&r.inventory).unwrap(); if !secrets { inv["links"] = json!({}); } Response::ok(json!({ "inventory": inv, "warnings": r.warnings })) } None => Response::err(s.last_error.clone().unwrap_or_else(|| "the proxy is not running".into())), } } Request::RenderedConfig => { let s = shared.lock().await; match &s.last { Some(r) => Response::ok(json!({ "sing-box": r.sing_box, "xray": r.xray })), None => Response::err("nothing rendered yet"), } } Request::Restart { units } => { let mut s = shared.lock().await; let names = if units.is_empty() { s.sup.names() } else { units }; let mut missing = Vec::new(); for n in &names { if !s.sup.restart(n) { missing.push(n.clone()); } } if missing.is_empty() { Response::ok(json!({ "restarted": names })) } else { Response::err(format!("no such unit: {}", missing.join(", "))) } } Request::Start { unit } | Request::Stop { unit } if unit != service::SOCKS_UNIT && unit != "proxy-suite-tun" => { Response::err(format!("unit '{unit}' cannot be started or stopped on its own")) } Request::Start { unit } => { let mut s = shared.lock().await; if unit == "proxy-suite-tun" { if !s.cfg().proxy.tun.enable { return Response::err("the global TUN is off in the configuration (proxy.tun.enable)"); } s.tun = true; } s.proxy_on = true; applied(s.apply().await) } Request::Stop { unit } => { let mut s = shared.lock().await; if unit == "proxy-suite-tun" { s.tun = false; } else { s.proxy_on = false; } applied(s.apply().await) } Request::Logs { unit, lines, .. } => { let s = shared.lock().await; Response::ok(json!(s.sup.tail(unit.as_deref(), lines))) } Request::SubsUpdate { tag } => { let results = service::update_subscriptions(shared, tag.as_deref()).await; Response::ok(json!(results.into_iter().map(|(t, r)| match r { Ok(n) => json!({ "tag": t, "links": n }), Err(e) => json!({ "tag": t, "error": e }), }).collect::>())) } Request::RuleSetsUpdate => { let results = service::update_rule_sets(shared, false).await; Response::ok(json!(results.into_iter().map(|(t, r)| match r { Ok(()) => json!({ "tag": t }), Err(e) => json!({ "tag": t, "error": e }), }).collect::>())) } Request::Test { tags } => { let (clash, tags, url) = { let s = shared.lock().await; let Some(r) = &s.last else { return Response::err("the proxy is not running") }; let tags = if tags.is_empty() { r.inventory.exits.clone() } else { tags }; ( crate::clash::Clash::new(s.cfg().proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret), tags, s.cfg().proxy.url_test.url.clone(), ) }; let mut out = Vec::new(); for t in tags { out.push(match clash.delay(&t, &url, 5000).await { Ok(ms) => json!({ "tag": t, "delay": ms }), Err(e) => json!({ "tag": t, "error": e.to_string() }), }); } Response::ok(json!(out)) } Request::Components => { let s = shared.lock().await; let bin = s.paths().bin(); let list: Vec = ps_core::components::manifest() .components .iter() .map(|(name, c)| { json!({ "name": name, "version": c.version, "installed": crate::install::installed_version(&bin, name), "license": c.license, "homepage": c.homepage, "bundled": c.bundled, }) }) .collect(); Response::ok(json!(list)) } Request::ZapretPresets => { let s = shared.lock().await; let bats: Vec = std::fs::read_dir(s.paths().bin().join("zapret")) .into_iter() .flatten() .filter_map(|e| e.ok()?.file_name().into_string().ok()) .collect(); Response::ok(json!({ "presets": ps_core::zapret::presets(&bats), "current": s.cfg().zapret.discord_youtube.config_name, })) } Request::TgLinks => { let s = shared.lock().await; match crate::tg::secret(s.cfg(), s.paths()) { Ok(secret) => Response::ok(json!({ "links": crate::tg::links(s.cfg(), &secret) })), Err(e) => Response::err(format!("tg-ws-proxy's secret: {e:#}")), } } Request::ComponentsInstall { names } => { // Programs the service runs as SYSTEM: an administrator's call, whatever the scopes. if !peer.admin { return Response::err("installing components needs an administrator"); } let manifest = ps_core::components::manifest(); let wanted: Vec = if names.is_empty() { manifest.components.iter().filter(|(_, c)| !c.bundled).map(|(n, _)| n.clone()).collect() } else { names }; let (bin, cache, routes) = { let s = shared.lock().await; (s.paths().bin(), s.paths().root.join("downloads"), s.fetch_routes(true)) }; let mut results = Vec::new(); for name in wanted { let Some(comp) = manifest.components.get(&name) else { results.push(json!({ "name": name, "error": "no such component" })); continue; }; // What runs from it must let go of its files first. shared.lock().await.sup.stop_all().await; let r = crate::install::install(&bin, &name, comp, &routes, &cache).await; results.push(match r { Ok(()) => json!({ "name": name, "version": comp.version }), Err(e) => json!({ "name": name, "error": format!("{e:#}") }), }); } let _ = shared.lock().await.apply().await; Response::ok(json!(results)) } } } fn applied(r: anyhow::Result<()>) -> Response { match r { Ok(()) => Response::ok(Value::Null), Err(e) => Response::err(e.to_string()), } } async fn finish_state(s: &mut tokio::sync::MutexGuard<'_, service::Service>) -> Response { if let Err(e) = s.store.save_state() { return Response::err(format!("cannot save the state: {e}")); } applied(s.apply().await) } #[cfg(test)] mod tests { use super::*; use ps_core::config::Outbound; #[test] fn redaction_round_trips_by_tag() { let mut cfg = Config::default(); cfg.proxy.outbounds = vec![ Outbound { tag: "a".into(), url: Some("hy2://secret-a@a:443".into()), ..Default::default() }, Outbound { tag: "b".into(), url: Some("hy2://secret-b@b:443".into()), ..Default::default() }, ]; cfg.proxy.listener.auth.password = Some("pw".into()); let mut shown = redact(&cfg); assert_eq!(shown["proxy"]["outbounds"][0]["url"], REDACTED); assert_eq!(shown["proxy"]["listener"]["auth"]["password"], REDACTED); // The client reorders and adds one; the hidden values follow their tags. let list = shown["proxy"]["outbounds"].as_array_mut().unwrap(); list.swap(0, 1); list.push(json!({ "tag": "c", "url": "hy2://new@c:443" })); unredact(&mut shown, &cfg); let back: Config = serde_json::from_value(shown).unwrap(); assert_eq!(back.proxy.outbounds[0].url.as_deref(), Some("hy2://secret-b@b:443")); assert_eq!(back.proxy.outbounds[1].url.as_deref(), Some("hy2://secret-a@a:443")); assert_eq!(back.proxy.outbounds[2].url.as_deref(), Some("hy2://new@c:443")); assert_eq!(back.proxy.listener.auth.password.as_deref(), Some("pw")); } #[test] fn following_logs_needs_the_secrets_scope_too() { assert_eq!(scope_of(&Request::Logs { unit: None, lines: 10, follow: true }), Some(Scope::Secrets)); assert_eq!(scope_of(&Request::Logs { unit: None, lines: 10, follow: false }), Some(Scope::Secrets)); } #[test] fn scopes_follow_user_control() { let mut cfg = Config::default(); let user = Peer { admin: false, user: "u".into() }; assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_ok()); cfg.user_control.scopes = vec![Scope::Routing]; assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_ok()); assert!(allowed(&cfg, &user, Some(Scope::Config)).is_err()); cfg.user_control.enable = false; assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_err()); assert!(allowed(&cfg, &Peer { admin: true, user: "a".into() }, Some(Scope::Config)).is_ok()); } }