fix: more fixes

This commit is contained in:
fufsob committed 2026-09-16 15:59:25 +00:00
1 parent 32341ba323
commit 65fc4a7915
23 files changed
+207 -146

No files matched your search

+4 -2
View File
@@ -102,6 +102,7 @@ let
];
nativeBuildInputs = [ pkgs.makeWrapper ];
postBuild = ''
# /run/wrappers/bin first: the store's sudo, earlier on a PATH, refuses to run without setuid.
wrapProgram "$out/bin/proxy-tui" \
--prefix PYTHONPATH : ${pythonModules} \
--prefix PATH : "${
@@ -110,7 +111,7 @@ let
pkgs.systemd
]
}" \
--suffix PATH : /run/wrappers/bin ${envFlags}
--prefix PATH : /run/wrappers/bin ${envFlags}
'';
};
guiPython = pkgs.python3.withPackages (ps: [ ps.pygobject3 ]);
@@ -184,6 +185,7 @@ let
runHook postInstall
'';
postFixup = ''
# /run/wrappers/bin first: the store's pkexec, earlier on a PATH, refuses to run without setuid.
makeWrapper ${guiPython}/bin/python3 "$out/bin/proxy-suite-gui" \
--add-flags "$out/lib/proxy-suite-gui/proxy_gui.py" \
"''${gappsWrapperArgs[@]}" \
@@ -195,7 +197,7 @@ let
pkgs.qrencode
]
}" \
--suffix PATH : /run/wrappers/bin \
--prefix PATH : /run/wrappers/bin \
--set PROXY_GUI_ICON_DIR "$out/share/proxy-suite-gui/icons" \
--set PROXY_GUI_REFRESH ${toString guiRefreshInterval} ${envFlags}
'';
+19 -4
View File
@@ -5,6 +5,7 @@ Configuration arrives through the environment the Nix wrapper sets.
import datetime
import http.client
import importlib
import json
import os
import re
@@ -625,6 +626,15 @@ def _status_tray():
print(f"awg_profiles={','.join(snapshot['awg']['profiles'])}")
def _status_tab(tab_id=""):
"""A front end's tab as JSON [rows, summary]: how the GUI reads, through pkexec, what only root can."""
model = _module("proxy_model")
tab = next((t for t in model.TABS if t.id == tab_id), None)
if tab is None:
usage(f"status --tab <{'|'.join(t.id for t in model.TABS)}>")
print(json.dumps(model.load_tab(tab, model._read_states())))
def _status_json():
snapshot = _status_snapshot()
if snapshot["proxy"]["active"]:
@@ -700,6 +710,9 @@ def cmd_status(*args):
if args[:1] == ("--tray",):
_status_tray()
return
if args[:1] == ("--tab",):
_status_tab(*args[1:2])
return
print("proxy-suite services:")
for svc in _snapshot_units():
if svc != SUBSCRIPTION_UPDATE:
@@ -814,7 +827,7 @@ def _require_outbound_inventory():
def _outbound_current():
"""What the backend dials right now, when it exposes a selector.
Empty otherwise, which is normal for selection = "first" and for XRay.
Empty otherwise, which is normal for XRay.
"""
status, body = _clash("GET", "/proxies/proxy", timeout=5)
now = body.get("now") if status == 200 and isinstance(body, dict) else None
@@ -1071,12 +1084,14 @@ def _subscription_link(*args):
_emit(_s(url), flag == "--qr")
def _proxy_export():
def _module(name):
# Not PYTHONPATH: that would reach every command `apps run` starts.
sys.path.append(env("PROXY_CTL_MODULES", os.path.dirname(os.path.abspath(__file__))))
import proxy_export
return importlib.import_module(name)
return proxy_export
def _proxy_export():
return _module("proxy_export")
def _config_export(*args, only=None):
+2 -3
View File
@@ -76,9 +76,8 @@ def _dropped(exits, keep):
def _backend_tag(tags, only, prefix=""):
"""The tag `only` has in the backend: as given, prefixed by the XRay wrapper, or the
outbound collapsed into "proxy"."""
for tag in (only, prefix + only, "proxy"):
"""The tag `only` has in the backend: as given, or prefixed by the XRay wrapper."""
for tag in (only, prefix + only):
if tag in tags:
return tag
raise ValueError(f"no outbound {only} in the running config")
+25 -6
View File
@@ -66,7 +66,7 @@ GLOBAL_SHORTCUTS = [
("w", "How is a domain routed"),
("<Shift>l", "Follow all logs"),
("o", "Output of the last command"),
("<Control>e", "Run actions as root (pkexec)"),
("<Control>e", "Read and run as root (pkexec)"),
("F5 r", "Refresh now"),
("<Control>question", "Keyboard shortcuts"),
("<Control>w", "Close the window (the tray keeps running)"),
@@ -755,7 +755,7 @@ class Window(Adw.ApplicationWindow):
self.refresh_stack.add_named(Adw.Spinner(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER), "busy")
self.busy_timer = None
header.pack_start(self.refresh_stack)
self.root_badge = Gtk.Image(icon_name="dialog-password-symbolic", tooltip_text="Actions run as root (Ctrl+E)", visible=app.elevated(), css_classes=["warning"])
self.root_badge = Gtk.Image(icon_name="dialog-password-symbolic", tooltip_text="Reads and actions run as root (Ctrl+E)", visible=app.elevated(), css_classes=["warning"])
header.pack_start(self.root_badge)
menu = Gio.Menu()
section = Gio.Menu()
@@ -764,7 +764,7 @@ class Window(Adw.ApplicationWindow):
section.append("Output of the last command", "win.last-output")
menu.append_section(None, section)
section = Gio.Menu()
section.append("Run actions as root", "app.elevated")
section.append("Read and run as root", "app.elevated")
menu.append_section(None, section)
section = Gio.Menu()
section.append("Keyboard Shortcuts", "win.shortcuts")
@@ -1027,6 +1027,7 @@ class ProxySuiteGui(Adw.Application):
self.pending = False
self.generation = 0
self.failed = None # units in failed state at the last load; None before the first
self.root_read_refused = False # pkexec for a tab read was dismissed: not asked again until Ctrl+E flips
self.timer = None
def do_startup(self):
@@ -1088,8 +1089,10 @@ class ProxySuiteGui(Adw.Application):
def on_elevated(self, action, value):
action.set_state(value)
self.root_read_refused = False
if self.window:
self.window.root_badge.set_visible(value.get_boolean())
self.reload() # tabs only root can read
def present(self, tab=None):
if self.window is None:
@@ -1129,9 +1132,9 @@ class ProxySuiteGui(Adw.Application):
if window:
window.set_busy(True)
tab = window.pages[window.stack.get_visible_child_name()].tab if window and window.stack.get_visible_child_name() else None
threading.Thread(target=self.load, args=(self.generation, tab), daemon=True).start()
threading.Thread(target=self.load, args=(self.generation, tab, self.elevated()), daemon=True).start()
def load(self, generation, tab):
def load(self, generation, tab, elevated):
model.new_load()
states = model._read_states()
snap = model.snapshot(states) if states else None
@@ -1141,9 +1144,25 @@ class ProxySuiteGui(Adw.Application):
if tab is not None:
result["visible"] = model.available_tabs(states)
result["status"] = model._safe(model.status_items, states, fallback=[("", "Status unavailable", "bad")])
result["tab"] = (tab.id, *model.load_tab(tab, states))
result["tab"] = (tab.id, *self.load_tab(tab, states, elevated))
GLib.idle_add(self.landed, generation, result)
def load_tab(self, tab, states, elevated):
"""The tab as this user reads it; what only root can read, through pkexec when actions run as root."""
rows, summary = model.load_tab(tab, states)
if not model.needs_root(summary.splitlines(), 1):
return rows, summary
if not elevated:
return rows, summary + "\nCtrl+E: read and run as root (pkexec)"
if self.root_read_refused:
return rows, summary + "\nRoot read cancelled: Ctrl+E twice to ask again."
root_rows, why = model.load_tab_as_root(tab, "pkexec")
if root_rows is None:
# ponytail: one refusal stops the asking, else the password dialog is back every refresh
self.root_read_refused = why == "authentication cancelled"
return rows, summary + f"\nAs root: {why}"
return root_rows, why
def landed(self, generation, result):
self.loading = False
if self.window:
+18 -1
View File
@@ -5,6 +5,7 @@ validation, permission errors and systemd triggers stay in one place, and its
die() cannot take a front end down.
"""
import json
import os
import re
import shlex
@@ -176,7 +177,8 @@ def outbound_rows(_):
excluded = set(inventory.get("excluded") or [])
current = ctl._outbound_current()
reputation = ctl._reputation_by_tag()
runtime = set(ctl._runtime_tags("outbound"))
# outbounds.d is root-only; the inventory says "runtime" for what the backend loaded from it.
runtime = set(ctl._runtime_tags("outbound")) | {t for t, s in sources.items() if s == "runtime"}
return [
{
"key": t,
@@ -567,6 +569,21 @@ def elevated(argv, via):
return [via, shutil.which(CTL) or CTL, *argv]
def load_tab_as_root(tab, via):
"""load_tab in proxy-ctl run through via (pkexec): (rows, summary), or None and why it did not run."""
try:
p = subprocess.run(elevated(["status", "--tab", tab.id], via), capture_output=True, text=True, stdin=subprocess.DEVNULL)
except OSError as e:
return None, f"cannot run {via}: {e}"
if p.returncode in (126, 127) and not p.stdout and not p.stderr.strip():
return None, "authentication cancelled" # pkexec: dismissed, or not allowed
try:
rows, summary = json.loads(p.stdout)
return rows, summary
except ValueError:
return None, (p.stderr.strip().splitlines() or [f"exit status {p.returncode}"])[-1]
def popen(argv, root=None):
"""proxy-ctl with its output streamed: its own process group, so stop() takes down what it spawned too.
root: "pkexec" to run it as root, asking through the desktop's polkit agent."""
+1 -1
View File
@@ -496,7 +496,7 @@ class ProxyTui(App):
self.loaded[tab_id] = (states, visible, status, rows, summary)
self.states, self.status = states, status
# A read root could do: ! retries runs, not reads, so the way out is the whole TUI under sudo.
if summary.startswith("✗") and model.needs_root(summary.splitlines(), 1):
if model.needs_root(summary.splitlines(), 1):
summary += "\n#: run proxy-tui as root (sudo)"
self.show_status()
if visible != self.shown:
+4 -5
View File
@@ -70,7 +70,7 @@ class EnvTest(unittest.TestCase):
class ClashApiTest(EnvTest):
def test_unset_api_reads_as_unreachable(self):
# selection = "first" and the XRay backend leave the API off; a bare
# The XRay backend leaves the API off; a bare
# path is not a URL, and it used to escape as a traceback out of
# `status`, `where` and `proxy outbounds`.
for value in ("", "127.0.0.1:9090"):
@@ -529,8 +529,7 @@ class OutboundTestTest(EnvTest):
"port": 18537,
"selector": "proxy-suite-test",
"url": "https://t.test/204",
# selection = "first": the backend knows the pick as "proxy".
"outbounds": {"own-vps": "proxy", "de": "de", "wg": "wg"},
"outbounds": {"own-vps": "own-vps", "de": "de", "wg": "wg"},
},
)
self.calls = []
@@ -563,10 +562,10 @@ class OutboundTestTest(EnvTest):
self.assertRegex(out, r"(?m)^ TAG +PING +DELAY +DOWNLOAD$")
self.assertRegex(out, r"(?m)^ own-vps +udp +88 ms +12\.3 Mbit/s$")
self.assertRegex(out, r"(?m)^ de +- +failed +12\.3 Mbit/s$")
self.assertTrue(any(c[1].startswith("/proxies/proxy/delay?") and "t.test" in c[1] for c in self.calls))
self.assertTrue(any(c[1].startswith("/proxies/own-vps/delay?") and "t.test" in c[1] for c in self.calls))
# Downloads switch the test selector, one outbound at a time, in order.
puts = [c for c in self.calls if c[0] == "PUT"]
self.assertEqual([c[2]["name"] for c in puts], ["proxy", "de", "wg"])
self.assertEqual([c[2]["name"] for c in puts], ["own-vps", "de", "wg"])
self.assertEqual({c[1] for c in puts}, {"/proxies/proxy-suite-test"})
def test_default_and_arguments(self):
-7
View File
@@ -135,13 +135,6 @@ class SingBoxTest(unittest.TestCase):
self.assertNotIn("via-warp", [o["tag"] for o in cfg["outbounds"]])
self.assertIn("left out via-warp: it chains through warp", warnings)
def test_collapsed_proxy(self):
base = sing_box_config()
base["outbounds"] = [{**base["outbounds"][0], "tag": "proxy"}, base["outbounds"][1], *base["outbounds"][6:]]
base["route"]["rules"] = []
cfg, _ = export.portable(base, only="vps")
self.assertEqual([o["tag"] for o in cfg["outbounds"]], ["proxy", "direct", "block"])
def test_kept_loopback_hop_leaves_no_dangling_reference(self):
"""Asking for a loopback hop drops it, so nothing may still point at it:
sing-box stops with "default outbound not found" (which `check` does not catch)."""
+28
View File
@@ -5,7 +5,9 @@ key names become GTK accelerators, and every icon the tray can ask for is drawn.
import os
import sys
import tempfile
import types
import unittest
from unittest import mock
import proxy_ctl as ctl
import proxy_gui as gui
@@ -81,6 +83,32 @@ class GuiTest(unittest.TestCase):
[("failed", ("bold", "red")), (" ok", ())],
)
def test_root_toggle_reads_too(self):
"""A tab only root can read goes through pkexec when the toggle is on, and one refusal stops the asking."""
tab = model.Tab("x", "X", model.ROW, [], list)
app = types.SimpleNamespace(root_read_refused=False)
denied = ([], "✗ Cannot read /x - join the proxy-suite group, or re-run with sudo.")
asked = []
def as_root(result):
return mock.patch.object(model, "load_tab_as_root", lambda tab, via: asked.append(via) or result)
load = lambda elevated: gui.ProxySuiteGui.load_tab(app, tab, {}, elevated)
with mock.patch.object(model, "load_tab", lambda tab, states: denied), mock.patch.object(model.os, "geteuid", lambda: 1000):
with as_root(([{"key": "a"}], "")):
self.assertIn("Ctrl+E", load(False)[1])
self.assertEqual(asked, [])
self.assertEqual(load(True), ([{"key": "a"}], ""))
self.assertEqual(asked, ["pkexec"])
with as_root((None, "authentication cancelled")):
self.assertIn("As root: authentication cancelled", load(True)[1])
self.assertIn("Ctrl+E twice", load(True)[1])
self.assertEqual(len(asked), 2)
with mock.patch.object(model, "load_tab", lambda tab, states: ([], "Nothing here yet.")), as_root(None):
app.root_read_refused = False
self.assertEqual(load(True), ([], "Nothing here yet.")) # readable: no pkexec
self.assertEqual(len(asked), 2)
def test_every_tray_icon_is_drawn(self):
here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons")
with tempfile.TemporaryDirectory() as out:
+33
View File
@@ -1,7 +1,11 @@
#!/usr/bin/env python3
"""proxy_model without a front end: the status line and the tray menu turn state into the right proxy-ctl argv."""
import contextlib
import io
import json
import os
import subprocess
import tempfile
import unittest
from unittest import mock
@@ -148,6 +152,35 @@ class ModelTest(unittest.TestCase):
self.assertEqual(probe.argv(rows[1], "example.com", {}), ["proxy", "auto", "probe", "example.com", "--via", "b-backend"])
broken = model.Tab("x", "X", model.ROW, [], lambda _: ctl.die("backend gone"))
self.assertEqual(model.load_tab(broken, {}), ([], "✗ backend gone"))
# outbounds.d is root-only: the inventory still says which are runtime, so they can be removed.
inventory["sources"] = {"a": "runtime"}
with mock.patch.object(ctl, "_outbound_current", lambda: ""), mock.patch.object(ctl, "_reputation_by_tag", lambda: {}), mock.patch.object(ctl, "_runtime_tags", lambda kind: []), mock.patch.object(ctl, "_outbound_inventory", lambda: inventory):
rows, _ = model.load_tab(tab, {})
self.assertEqual([(r["source"], r["runtime"]) for r in rows], [("runtime", True), ("-", False)])
def test_load_tab_as_root(self):
"""The GUI's root read: proxy-ctl status --tab through pkexec, and what a refusal says."""
tab = next(t for t in model.TABS if t.id == "routing")
with mock.patch.object(ctl, "_route_mode_current", lambda: "default"), mock.patch.object(ctl, "_route_mode_default", lambda: "rules"):
out = io.StringIO()
with contextlib.redirect_stdout(out):
ctl._status_tab("routing")
self.assertEqual(json.loads(out.getvalue()), list(model.load_tab(tab, {})))
with self.assertRaises(SystemExit) as e:
ctl._status_tab("nope")
self.assertIn("status --tab <services|", str(e.exception))
def ran(returncode, stdout="", stderr=""):
return mock.patch.object(model.subprocess, "run", lambda argv, **_: subprocess.CompletedProcess(argv, returncode, stdout, stderr))
with ran(0, '[[{"key": "a"}], "ok"]'):
self.assertEqual(model.load_tab_as_root(tab, "pkexec"), ([{"key": "a"}], "ok"))
with ran(126):
self.assertEqual(model.load_tab_as_root(tab, "pkexec"), (None, "authentication cancelled"))
with ran(127, stderr="pkexec must be setuid root\n"): # not a refusal: asked again next refresh
self.assertEqual(model.load_tab_as_root(tab, "pkexec"), (None, "pkexec must be setuid root"))
with ran(1, stderr="boom\nUsage: proxy-ctl status\n"):
self.assertEqual(model.load_tab_as_root(tab, "pkexec"), (None, "Usage: proxy-ctl status"))
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
def test_unreadable_is_not_empty(self):