windows: the service, its API and proxy-ctl
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>
This commit is contained in:
1 parent
918cdc9a75
commit
41c8ed4406
25 files changed
+5411
-7
No files matched your search
@@ -0,0 +1,488 @@
|
||||
//! 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::<Vec<_>>());
|
||||
}
|
||||
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::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `peer` may use `scope`, under `cfg.userControl`.
|
||||
fn allowed(cfg: &Config, peer: &Peer, scope: Option<Scope>) -> 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<Scope> {
|
||||
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),
|
||||
Request::RenderedConfig => 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();
|
||||
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<String>, 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
|
||||
{
|
||||
let s = shared.lock().await;
|
||||
if let Err(e) = allowed(s.cfg(), peer, scope_of(&req)) {
|
||||
return Response::err(e);
|
||||
}
|
||||
}
|
||||
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>(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 {
|
||||
if 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<String> = 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<String> =
|
||||
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 });
|
||||
}
|
||||
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::<RouteMode>(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::<Vec<_>>()))
|
||||
}
|
||||
|
||||
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::<Vec<_>>()))
|
||||
}
|
||||
|
||||
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 | Request::ComponentsInstall { .. } => Response::err("the component manager is not there yet"),
|
||||
}
|
||||
}
|
||||
|
||||
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 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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user