fix: rewrite proxy-ctl to python
This commit is contained in:
14 files changed
+2243
-1986
No files matched your search
@@ -98,7 +98,6 @@ in
|
||||
|
||||
# -- perAppRouting: proxy-ctl script embeds wrap/apps commands --
|
||||
(
|
||||
assert pkgs.lib.hasInfix "help | -h | --help)" perAppRoutingProxychainsScript;
|
||||
assert pkgs.lib.hasInfix "Usage: proxy-ctl <group>" perAppRoutingProxychainsScript;
|
||||
assert pkgs.lib.hasInfix "local proxy backend" perAppRoutingProxychainsScript;
|
||||
assert pkgs.lib.hasInfix "restart active services"
|
||||
@@ -118,8 +117,6 @@ in
|
||||
|
||||
# -- proxy-ctl: restart skips services that are not present in zapret-only or tg-only builds --
|
||||
(
|
||||
assert pkgs.lib.hasInfix "if _svc_exists proxy-suite-socks; then" minimalProxyCtlScript;
|
||||
assert pkgs.lib.hasInfix "_svc_exists \"$svc\" && _svc_active \"$svc\"" minimalProxyCtlScript;
|
||||
assert pkgs.lib.hasInfix "proxy-suite-tg-ws-proxy" minimalProxyCtlScript;
|
||||
true
|
||||
)
|
||||
@@ -127,9 +124,6 @@ in
|
||||
# -- perAppRouting: generated proxy-ctl script dispatches through proxychains4 --
|
||||
(
|
||||
assert pkgs.lib.hasInfix "export PROXYCHAINS_QUIET_ARG=-q" perAppRoutingProxychainsScript;
|
||||
assert pkgs.lib.hasInfix
|
||||
"exec proxychains4 $PROXYCHAINS_QUIET_ARG -f \"$PROXYCHAINS_CONFIG\" \"$@\""
|
||||
perAppRoutingProxychainsScript;
|
||||
true
|
||||
)
|
||||
];
|
||||
|
||||
@@ -46,10 +46,6 @@ in
|
||||
# -- perAppRouting: generated proxy-ctl script dispatches tproxy profiles through systemd slices --
|
||||
(
|
||||
assert pkgs.lib.hasInfix "PER_APP_ROUTING_TPROXY_ENABLED" perAppRoutingTproxyScript;
|
||||
assert pkgs.lib.hasInfix
|
||||
''_wrap_slice "proxy-suite-per-app-tproxy" "$profile" "$PER_APP_ROUTING_TPROXY_ENABLED"''
|
||||
perAppRoutingTproxyScript;
|
||||
assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingTproxyScript;
|
||||
true
|
||||
)
|
||||
|
||||
|
||||
@@ -74,15 +74,6 @@ in
|
||||
# -- perAppRouting: generated proxy-ctl script dispatches tun profiles through systemd slices --
|
||||
(
|
||||
assert pkgs.lib.hasInfix "PER_APP_ROUTING_TUN_ENABLED" perAppRoutingTunScript;
|
||||
assert pkgs.lib.hasInfix "systemd-run --user --scope --quiet --collect --same-dir"
|
||||
perAppRoutingTunScript;
|
||||
assert pkgs.lib.hasInfix "_check_no_global_proxy tun" perAppRoutingTunScript;
|
||||
assert pkgs.lib.hasInfix
|
||||
''_wrap_slice "proxy-suite-per-app-tun" "$profile" "$PER_APP_ROUTING_TUN_ENABLED"''
|
||||
perAppRoutingTunScript;
|
||||
assert pkgs.lib.hasInfix "$slice_base-user@$uid.service" perAppRoutingTunScript;
|
||||
assert pkgs.lib.hasInfix "cleanup_slice()" perAppRoutingTunScript;
|
||||
assert pkgs.lib.hasInfix "trap cleanup_slice EXIT" perAppRoutingTunScript;
|
||||
true
|
||||
)
|
||||
|
||||
|
||||
@@ -170,10 +170,6 @@ in
|
||||
# -- perAppRouting: generated proxy-ctl script dispatches zapret profiles through systemd slices --
|
||||
(
|
||||
assert pkgs.lib.hasInfix "PER_APP_ROUTING_ZAPRET_ENABLED" perAppRoutingZapretScript;
|
||||
assert pkgs.lib.hasInfix
|
||||
''_wrap_slice "proxy-suite-per-app-zapret" "$profile" "$PER_APP_ROUTING_ZAPRET_ENABLED"''
|
||||
perAppRoutingZapretScript;
|
||||
assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingZapretScript;
|
||||
true
|
||||
)
|
||||
|
||||
|
||||
+43
-316
@@ -46,16 +46,14 @@
|
||||
pkgs.runCommand "proxy-suite-proxy-ctl-subscription-list-check"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
pkgs.bash
|
||||
pkgs.python3
|
||||
pkgs.coreutils
|
||||
pkgs.gawk
|
||||
pkgs.jq
|
||||
];
|
||||
}
|
||||
''
|
||||
proxy_ctl="$TMPDIR/proxy-ctl"
|
||||
cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl"
|
||||
chmod +x "$proxy_ctl"
|
||||
proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py}
|
||||
|
||||
mkdir -p cache
|
||||
printf '%s\n' '["plain","hybrid","bad"]' > tags.json
|
||||
@@ -78,10 +76,10 @@
|
||||
PROXYCHAINS_QUIET_ARG="" \
|
||||
ROUTE_MODE_STATE_FILE="$PWD/route-mode" \
|
||||
DEFAULT_ROUTE_MODE="blacklist" \
|
||||
bash "$proxy_ctl" proxy subs list > output
|
||||
python3 "$proxy_ctl" proxy subs list > output
|
||||
# The old spelling still dispatches.
|
||||
env SUB_TAGS_FILE="$PWD/tags.json" SUB_CACHE_DIR="$PWD/cache" \
|
||||
bash "$proxy_ctl" subscription list | cmp - output
|
||||
python3 "$proxy_ctl" subscription list | cmp - output
|
||||
|
||||
awk '$1 == "plain" { found = 1; if ($NF != "2") exit 1 } END { exit found ? 0 : 1 }' output
|
||||
awk '$1 == "hybrid" { found = 1; if ($NF != "3") exit 1 } END { exit found ? 0 : 1 }' output
|
||||
@@ -94,7 +92,7 @@
|
||||
pkgs.runCommand "proxy-suite-proxy-ctl-outbounds-check"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
pkgs.bash
|
||||
pkgs.python3
|
||||
pkgs.coreutils
|
||||
pkgs.curl
|
||||
pkgs.gawk
|
||||
@@ -103,9 +101,7 @@
|
||||
];
|
||||
}
|
||||
''
|
||||
proxy_ctl="$TMPDIR/proxy-ctl"
|
||||
cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl"
|
||||
chmod +x "$proxy_ctl"
|
||||
proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py}
|
||||
|
||||
# systemd is not in the sandbox. The reload stub stands in for the start
|
||||
# script, which is what actually republishes the inventory.
|
||||
@@ -149,7 +145,7 @@
|
||||
PROXYCHAINS_QUIET_ARG="" \
|
||||
ROUTE_MODE_STATE_FILE="$PWD/route-mode" \
|
||||
DEFAULT_ROUTE_MODE="blacklist" \
|
||||
bash "$proxy_ctl" "$@"
|
||||
python3 "$proxy_ctl" "$@"
|
||||
}
|
||||
|
||||
# Listing works from the inventory alone, with no Clash API answering.
|
||||
@@ -213,15 +209,14 @@
|
||||
pkgs.runCommand "proxy-suite-proxy-ctl-zapret-auto-check"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
pkgs.bash
|
||||
pkgs.python3
|
||||
pkgs.coreutils
|
||||
pkgs.gawk
|
||||
pkgs.gnugrep
|
||||
];
|
||||
}
|
||||
''
|
||||
proxy_ctl="$TMPDIR/proxy-ctl"
|
||||
cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl"
|
||||
proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py}
|
||||
|
||||
state="$PWD/state"
|
||||
mkdir -p "$state"
|
||||
@@ -230,7 +225,7 @@
|
||||
: > "$state/zapret-hosts-user-exclude.txt"
|
||||
|
||||
run() {
|
||||
env ZAPRET_AUTO_ENABLED=1 ZAPRET_STATE_DIR="$state" bash "$proxy_ctl" zapret auto "$@"
|
||||
env ZAPRET_AUTO_ENABLED=1 ZAPRET_STATE_DIR="$state" python3 "$proxy_ctl" zapret auto "$@"
|
||||
}
|
||||
|
||||
run list | grep -qx blocked.example
|
||||
@@ -266,14 +261,14 @@
|
||||
printf 'AS12389\n' > "$state/cutoff/egress"
|
||||
printf '24940\n14061\n' > "$state/cutoff/asn.txt"
|
||||
printf '24940\t300.ya.ru\n' > "$state/cutoff/sni.txt"
|
||||
cutoff=$(env ZAPRET_CUTOFF_ENABLED=1 ZAPRET_STATE_DIR="$state" bash "$proxy_ctl" zapret cutoff)
|
||||
cutoff=$(env ZAPRET_CUTOFF_ENABLED=1 ZAPRET_STATE_DIR="$state" python3 "$proxy_ctl" zapret cutoff)
|
||||
printf '%s\n' "$cutoff" | grep -q 'from AS12389$'
|
||||
printf '%s\n' "$cutoff" | grep -qx 'Cutoff: 2 network(s)'
|
||||
printf '%s\n' "$cutoff" | grep -qE '^ AS24940 +300\.ya\.ru$'
|
||||
printf '%s\n' "$cutoff" | grep -qE '^ AS14061 +no name - proxy fallback$'
|
||||
|
||||
# Without the zapret2 engine there is nothing to inspect.
|
||||
! env ZAPRET_AUTO_ENABLED=0 ZAPRET_STATE_DIR="$state" bash "$proxy_ctl" zapret auto list
|
||||
! env ZAPRET_AUTO_ENABLED=0 ZAPRET_STATE_DIR="$state" python3 "$proxy_ctl" zapret auto list
|
||||
|
||||
touch "$out"
|
||||
'';
|
||||
@@ -282,7 +277,7 @@
|
||||
pkgs.runCommand "proxy-suite-proxy-ctl-complete-check"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
pkgs.bash
|
||||
pkgs.python3
|
||||
pkgs.coreutils
|
||||
pkgs.gawk
|
||||
pkgs.gnugrep
|
||||
@@ -290,8 +285,7 @@
|
||||
];
|
||||
}
|
||||
''
|
||||
proxy_ctl="$TMPDIR/proxy-ctl"
|
||||
cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl"
|
||||
proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py}
|
||||
|
||||
printf '%s\n' '["home","work"]' > awg.json
|
||||
jq -n '[{name:"torrent",route:"direct"}]' > profiles.json
|
||||
@@ -301,11 +295,11 @@
|
||||
env AWG_PROFILES_FILE="$PWD/awg.json" \
|
||||
PER_APP_ROUTING_PROFILES_FILE="$PWD/profiles.json" \
|
||||
OUTBOUND_INVENTORY_FILE="$PWD/inventory.json" \
|
||||
bash "$proxy_ctl" __complete "$@"
|
||||
python3 "$proxy_ctl" __complete "$@"
|
||||
}
|
||||
|
||||
# Every group the help lists must complete, or the table has drifted.
|
||||
bash "$proxy_ctl" help | awk '/^ [a-z]/ { print $1 }' | sort -u > groups
|
||||
python3 "$proxy_ctl" help | awk '/^ [a-z]/ { print $1 }' | sort -u > groups
|
||||
run > top
|
||||
while read -r group; do
|
||||
grep -qx "$group" top || { echo "help lists $group, completion does not" >&2; exit 1; }
|
||||
@@ -330,7 +324,12 @@
|
||||
|
||||
# A shell completing must never die, however unreadable the state is.
|
||||
run inbounds link | cmp - /dev/null
|
||||
env AWG_PROFILES_FILE=/nonexistent bash "$proxy_ctl" __complete awg on
|
||||
env AWG_PROFILES_FILE=/nonexistent python3 "$proxy_ctl" __complete awg on
|
||||
|
||||
# Every shell's completion file at least parses.
|
||||
bash -n ${../../pkgs/proxy-ctl/completions/proxy-ctl.bash}
|
||||
${pkgs.zsh}/bin/zsh -n ${../../pkgs/proxy-ctl/completions/_proxy-ctl}
|
||||
HOME="$TMPDIR" ${pkgs.fish}/bin/fish --no-execute ${../../pkgs/proxy-ctl/completions/proxy-ctl.fish}
|
||||
|
||||
touch "$out"
|
||||
'';
|
||||
@@ -339,15 +338,14 @@
|
||||
pkgs.runCommand "proxy-suite-proxy-ctl-where-check"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
pkgs.bash
|
||||
pkgs.python3
|
||||
pkgs.coreutils
|
||||
pkgs.gnugrep
|
||||
pkgs.jq
|
||||
];
|
||||
}
|
||||
''
|
||||
proxy_ctl="$TMPDIR/proxy-ctl"
|
||||
cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl"
|
||||
proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py}
|
||||
|
||||
mkdir -p ap zap
|
||||
jq -n '{domains:{"spotify.com":{exit:"community-de",host:"open.spotify.com",at:0}}}' > ap/state.json
|
||||
@@ -358,7 +356,7 @@
|
||||
run() {
|
||||
env AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$PWD/ap" \
|
||||
ZAPRET_AUTO_ENABLED=1 ZAPRET_STATE_DIR="$PWD/zap" \
|
||||
bash "$proxy_ctl" where "$@"
|
||||
python3 "$proxy_ctl" where "$@"
|
||||
}
|
||||
|
||||
# Piping into `grep -q` would race the script against SIGPIPE.
|
||||
@@ -382,248 +380,19 @@
|
||||
# A URL is accepted where a hostname is.
|
||||
verdict https://open.spotify.com/track/x '^ domain *open.spotify.com$'
|
||||
|
||||
! bash "$proxy_ctl" where 2>/dev/null
|
||||
! python3 "$proxy_ctl" where 2>/dev/null
|
||||
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
# The verdict table, fed tuples measured on a real censored network.
|
||||
proxy-ctl-proxy-probe =
|
||||
pkgs.runCommand "proxy-suite-proxy-ctl-proxy-probe-check"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
pkgs.bash
|
||||
pkgs.coreutils
|
||||
pkgs.gnugrep
|
||||
pkgs.jq
|
||||
];
|
||||
}
|
||||
''
|
||||
cat > "$TMPDIR/test.sh" <<'EOF'
|
||||
set -euo pipefail
|
||||
. ${../../pkgs/proxy-ctl-lib.sh}
|
||||
|
||||
expect() {
|
||||
local want="$1" direct="$2" via="$3" got
|
||||
got="$(_probe_verdict "$direct" "$via")"
|
||||
if [ "$got" != "$want" ]; then
|
||||
echo "FAIL: expected $want, got $got" >&2
|
||||
echo " direct=$direct" >&2
|
||||
echo " proxy =$via" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Origin refuses direct, accepts the proxy: chatgpt.com/robots.txt.
|
||||
expect destination '0|0.146175|403|6633|' '0|0.230116|200|4302|'
|
||||
|
||||
# The same through a redirect: claude.ai/robots.txt.
|
||||
expect destination \
|
||||
'0|0.141625|302|143|https://claude.com/app-unavailable-in-region' \
|
||||
'0|0.181276|200|281|'
|
||||
|
||||
# TLS never completed: censorship, zapret's job.
|
||||
expect censor '35|0.000000|000|0|' '0|0.119348|200|6258|'
|
||||
|
||||
# Handshake, then silence: the post-handshake throttle.
|
||||
expect censor '0|0.125029|000|0|' '0|0.143772|200|32881|'
|
||||
|
||||
# Direct works. Nothing to do, whoever else also works.
|
||||
expect ok '0|0.099546|200|2678|' '0|0.146822|200|2678|'
|
||||
|
||||
# robots.txt legitimately absent is not a failure.
|
||||
expect ok '0|0.161330|404|559|' '0|0.214667|404|559|'
|
||||
|
||||
# An ordinary redirect must not read as a block.
|
||||
expect ok \
|
||||
'0|0.10|301|0|https://www.example.com/robots.txt' \
|
||||
'0|0.20|301|0|https://www.example.com/robots.txt'
|
||||
|
||||
# Refused everywhere: not an egress problem.
|
||||
expect both-fail '0|0.10|403|100|' '0|0.20|403|100|'
|
||||
|
||||
# Nothing reaches it at all - a dead name, not a blocked one.
|
||||
expect unreachable '6|0.000000|000|0|' '35|0.000000|000|0|'
|
||||
|
||||
# --- redirect chains ---
|
||||
# spotify.com: the block is four same-site hops in.
|
||||
curl() {
|
||||
local url
|
||||
for url; do :; done
|
||||
echo x >> "$TMPDIR/curl-calls"
|
||||
case "$url" in
|
||||
https://spotify.test/) printf '0|0.1|301|0|https://www.spotify.test/' ;;
|
||||
https://www.spotify.test/) printf '0|0.1|301|0|https://open.spotify.test/' ;;
|
||||
https://open.spotify.test/) printf '0|0.1|302|93|https://accounts.spotify.test/login' ;;
|
||||
https://accounts.spotify.test/login)
|
||||
printf '0|0.1|301|0|https://www.spotify.test/int/why-not-available/' ;;
|
||||
https://redir.test/) printf '0|0.1|301|0|https://elsewhere.example/' ;;
|
||||
https://loop.test/) printf '0|0.1|301|0|https://loop.test/' ;;
|
||||
*) printf '0|0.1|200|10|' ;;
|
||||
esac
|
||||
}
|
||||
test "$(_probe_exit_verdict "$(_probe_fetch spotify.test / --noproxy '*')")" = blocked
|
||||
# Leaving the site ends the walk.
|
||||
test "$(_probe_exit_verdict "$(_probe_fetch redir.test / --noproxy '*')")" = ok
|
||||
# A redirect loop inside the site still stops.
|
||||
: > "$TMPDIR/curl-calls"
|
||||
_probe_fetch loop.test / --noproxy '*' > /dev/null
|
||||
test "$(wc -l < "$TMPDIR/curl-calls")" -le 6
|
||||
unset -f curl
|
||||
|
||||
# --- which path decides: the apex, robots.txt only breaks ties ---
|
||||
_svc_active() { return 0; }
|
||||
# No listener index: only this host and the local proxy.
|
||||
PROBE_EXITS_FILE=/nonexistent
|
||||
|
||||
# A curl that cannot start is an error, not a dead site.
|
||||
! (PROBE_CURL=/nonexistent cmd_proxy_probe --json x.test) 2> "$TMPDIR/curl-err"
|
||||
grep -q 'Cannot run /nonexistent' "$TMPDIR/curl-err"
|
||||
|
||||
probe_with() {
|
||||
# $1 apex-direct $2 apex-proxy $3 robots-direct $4 robots-proxy
|
||||
_probe_fetch() {
|
||||
case "$2" in
|
||||
/) [ "$3" = --noproxy ] && printf '%s' "$APEX_DIRECT" || printf '%s' "$APEX_PROXY" ;;
|
||||
*) [ "$3" = --noproxy ] && printf '%s' "$ROBOTS_DIRECT" || printf '%s' "$ROBOTS_PROXY" ;;
|
||||
esac
|
||||
}
|
||||
APEX_DIRECT="$1" APEX_PROXY="$2" ROBOTS_DIRECT="$3" ROBOTS_PROXY="$4" \
|
||||
cmd_proxy_probe --json example.test
|
||||
}
|
||||
|
||||
# last.fm: apex geo-blocked, robots.txt served everywhere.
|
||||
out="$(probe_with '0|0.11|403|424|' '0|0.17|200|59809|' '0|0.11|200|400|' '0|0.17|200|400|')"
|
||||
grep -q '"verdict":"destination"' <<<"$out"
|
||||
grep -q '"url":"https://example.test/"' <<<"$out"
|
||||
|
||||
# chatgpt.com: apex 403 everywhere, robots.txt separates.
|
||||
out="$(probe_with '0|0.14|403|6633|' '0|0.23|403|8442|' '0|0.14|403|6633|' '0|0.23|200|4302|')"
|
||||
grep -q '"verdict":"destination"' <<<"$out"
|
||||
grep -q '"url":"https://example.test/robots.txt"' <<<"$out"
|
||||
|
||||
# A working apex is never second-guessed by the fallback path.
|
||||
# set -e: proxy-ctl runs under it, and $() does not inherit it.
|
||||
out="$(set -e; probe_with '0|0.10|200|500|' '0|0.20|200|500|' '0|0.10|403|10|' '0|0.20|200|10|')"
|
||||
grep -q '"verdict":"ok"' <<<"$out"
|
||||
|
||||
# --- walking more than two exits ---
|
||||
# Direct and the first proxy share a WAF; only the third exit gets through.
|
||||
printf '%s' '[{"i":0,"tag":"direct","port":18540},
|
||||
{"i":1,"tag":"fi","port":18541},{"i":2,"tag":"de","port":18542}]' \
|
||||
> "$TMPDIR/exits.json"
|
||||
PROBE_EXITS_FILE="$TMPDIR/exits.json"
|
||||
_probe_fetch() {
|
||||
# every exit, direct included, goes through its pinned listener
|
||||
case "$4" in
|
||||
*:18540 | *:18541) printf '0|0.10|403|919|' ;;
|
||||
*:18542) printf '0|0.10|200|500|' ;;
|
||||
esac
|
||||
}
|
||||
out="$(cmd_proxy_probe --json sekai.test)"
|
||||
jq -e '.verdict == "destination" and .exit == "de"' <<<"$out" > /dev/null
|
||||
|
||||
# --keep-going tries every exit but keeps the first that worked.
|
||||
out="$(cmd_proxy_probe --json --keep-going --exits de,fi sekai.test)"
|
||||
jq -e '.exit == "de" and [.exits[].tag] == ["direct", "de", "fi", "direct", "de", "fi"]' \
|
||||
<<<"$out" > /dev/null
|
||||
|
||||
# --exits restricts and orders the walk; direct is always tried first.
|
||||
out="$(cmd_proxy_probe --json --exits de sekai.test)"
|
||||
jq -e '[.exits[].tag] == ["direct", "de"]' <<<"$out" > /dev/null
|
||||
|
||||
# An empty list probes direct only (every exit shares one network).
|
||||
out="$(cmd_proxy_probe --json --exits "" sekai.test)"
|
||||
jq -e '([.exits[].tag] | unique) == ["direct"] and .exit == null' <<<"$out" > /dev/null
|
||||
|
||||
# --via: can this exit carry what direct reaches?
|
||||
out="$(cmd_proxy_probe --json --via de sekai.test)"
|
||||
jq -e '.verdict == "ok" and ([.exits[].tag] | unique) == ["de", "direct"]' <<<"$out" > /dev/null
|
||||
out="$(cmd_proxy_probe --json --via fi sekai.test)"
|
||||
jq -e '.verdict == "blocked"' <<<"$out" > /dev/null
|
||||
! (cmd_proxy_probe --json --via nowhere sekai.test) 2> /dev/null
|
||||
# A given path is probed as is, for that probe only.
|
||||
out="$(cmd_proxy_probe --json --via de sekai.test/robots.txt)"
|
||||
jq -e '.url == "https://sekai.test/robots.txt" and ([.exits[].path] | unique) == ["/robots.txt"]' \
|
||||
<<<"$out" > /dev/null
|
||||
out="$(cmd_proxy_probe --json --via fi sekai.test)"
|
||||
jq -e '([.exits[].path] | unique) == ["/", "/robots.txt"]' <<<"$out" > /dev/null
|
||||
|
||||
# Refused a front page direct gets: not a stand-in (www.reddit.com).
|
||||
_probe_fetch() {
|
||||
case "$4:$2" in
|
||||
*:18541:/) printf '0|0.10|403|190240|' ;;
|
||||
*) printf '0|0.10|200|500|' ;;
|
||||
esac
|
||||
}
|
||||
out="$(cmd_proxy_probe --json --via fi geo.test)"
|
||||
jq -e '.verdict == "blocked"' <<<"$out" > /dev/null
|
||||
# i.pximg.net: the front page is 400 everywhere, so robots.txt decides.
|
||||
_probe_fetch() {
|
||||
case "$2" in
|
||||
/) printf '0|0.10|400|0|' ;;
|
||||
*) printf '0|0.10|200|43|' ;;
|
||||
esac
|
||||
}
|
||||
out="$(cmd_proxy_probe --json --via fi cdn.test)"
|
||||
jq -e '.verdict == "ok"' <<<"$out" > /dev/null
|
||||
|
||||
# --- proxy-ctl proxy auto learn ---
|
||||
learn_dir="$TMPDIR/learn"
|
||||
mkdir -p "$learn_dir"
|
||||
systemctl() {
|
||||
# stands in for the requests-only run
|
||||
printf '%s' '{"domains":{"last.fm":{"verdict":"destination","exit":"primary","host":"www.last.fm"}},
|
||||
"hosts":{"www.last.fm":{"domain":"last.fm","verdict":"destination","exit":"primary"}}}' \
|
||||
> "$learn_dir/state.json"
|
||||
}
|
||||
! (AUTOPROXY_ENABLED=0 cmd_proxy_learn www.last.fm) 2> /dev/null
|
||||
# It lands in a root-owned file and then in a URL: hostnames only.
|
||||
! (AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn 'x;rm -rf /') 2> /dev/null
|
||||
! (AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn '-evil.test/path') 2> /dev/null
|
||||
out="$(AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn www.last.fm)"
|
||||
test "$(cat "$learn_dir/requests")" = www.last.fm
|
||||
grep -q 'last.fm: destination - routed via primary' <<<"$out"
|
||||
|
||||
# A verdict that routes nothing is kept for its host and reported.
|
||||
systemctl() {
|
||||
printf '%s' '{"domains":{},
|
||||
"hosts":{"api.example.test":{"domain":"example.test","verdict":"ok","exit":null}}}' \
|
||||
> "$learn_dir/state.json"
|
||||
}
|
||||
out="$(AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn api.example.test)"
|
||||
grep -q 'api.example.test: ok - nothing to route' <<<"$out"
|
||||
|
||||
# A failed run is reported in plain words, and the request is not lost.
|
||||
systemctl() { return 1; }
|
||||
: > "$learn_dir/requests"
|
||||
! (AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn www.last.fm) 2> "$TMPDIR/learn-err"
|
||||
grep -q 'still queued' "$TMPDIR/learn-err"
|
||||
grep -qx www.last.fm "$learn_dir/requests"
|
||||
|
||||
# --- queue and learned ----------------------------------------------
|
||||
systemctl() { return 0; }
|
||||
printf '%s' '{"domains":{"spotify.com":{"verdict":"destination","exit":"primary","host":"www.spotify.com","at":0}},
|
||||
"hosts":{"www.spotify.com":{"domain":"spotify.com","verdict":"destination","exit":"primary"},
|
||||
"gew1-spclient.spotify.com":{"domain":"spotify.com","verdict":"ok","exit":null}},
|
||||
"backlog":{"a.example":{"domain":"example","hits":2},"b.example":{"domain":"example","hits":9}}}' \
|
||||
> "$learn_dir/state.json"
|
||||
q="$(AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_queue)"
|
||||
grep -qx ' www.last.fm' <<<"$q"
|
||||
# Most-dialled first.
|
||||
test "$(grep -oE '[ab]\.example' <<<"$q" | head -n 1)" = b.example
|
||||
l="$(AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learned)"
|
||||
grep -q 'spotify.com .*-> primary' <<<"$l"
|
||||
grep -q 'ok=1' <<<"$l"
|
||||
# An unreadable state directory asks for sudo.
|
||||
chmod 000 "$learn_dir"
|
||||
! (AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_queue) 2> "$TMPDIR/q-err"
|
||||
chmod 755 "$learn_dir"
|
||||
grep -q 'enable userControl, or run with sudo' "$TMPDIR/q-err"
|
||||
EOF
|
||||
bash "$TMPDIR/test.sh"
|
||||
touch "$out"
|
||||
'';
|
||||
# proxy_ctl.py's function-level tests: the probe verdict table and exit walk,
|
||||
# autoProxy learn/queue, inbound stats and subscriptions, apps run.
|
||||
proxy-ctl-unit =
|
||||
pkgs.runCommand "proxy-suite-proxy-ctl-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } ''
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
python ${../../pkgs/proxy-ctl}/test_proxy_ctl.py
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
# autoProxy slowness routing: sampler and judge.
|
||||
autoproxy-slowness =
|
||||
@@ -685,17 +454,11 @@
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
# Per-user inbound traffic: collection and `proxy-ctl inbounds stats`.
|
||||
# Per-user inbound traffic collection; `proxy-ctl inbounds stats` is in proxy-ctl-unit.
|
||||
inbound-stats =
|
||||
pkgs.runCommand "proxy-suite-inbound-stats-check"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
pkgs.bash
|
||||
pkgs.coreutils
|
||||
pkgs.gawk
|
||||
pkgs.gnugrep
|
||||
pkgs.jq
|
||||
];
|
||||
nativeBuildInputs = [ pkgs.jq ];
|
||||
}
|
||||
''
|
||||
add=${../../modules/proxy-suite/inbound-stats-add.jq}
|
||||
@@ -716,40 +479,6 @@
|
||||
old="$(jq -c '.days["2024-01-01"] = {fufsob: {up: 1}}' <<<"$s")"
|
||||
jq -e '.days["2024-01-01"] == null' <<<"$(a '{}' "$old")" > /dev/null
|
||||
|
||||
jq -c '.days["2026-09-10"] = {fufsob: {down: 1073741824, up: 1048576}}' <<<"$s" > "$TMPDIR/stats.json"
|
||||
cat > "$TMPDIR/test.sh" <<'EOF'
|
||||
set -euo pipefail
|
||||
. ${../../pkgs/proxy-ctl-lib.sh}
|
||||
id() { echo 1000; }
|
||||
date() { echo 2026-09-10; }
|
||||
export INBOUNDS_STATS_FILE="$TMPDIR/stats.json"
|
||||
out="$(_inbound_stats 2)"
|
||||
printf '%s\n' "$out"
|
||||
# Newest day first, sizes readable, then totals over the period.
|
||||
test "$(grep -oE '^ 2026-09-1[01]' <<<"$out" | head -n 1)" = " 2026-09-11"
|
||||
grep -qE '^ 2026-09-11 +fufsob +5\.7 MiB +4 KiB$' <<<"$out"
|
||||
grep -qE '^ 2026-09-11 +phone +0 B +0 B$' <<<"$out"
|
||||
grep -qE '^ 2026-09-10 +fufsob +1\.0 GiB +1\.0 MiB$' <<<"$out"
|
||||
grep -qE '^ fufsob +1\.0 GiB +1\.0 MiB$' <<<"$out"
|
||||
! (_inbound_stats 0) 2> /dev/null
|
||||
# Nothing collected yet says so, rather than printing an empty table.
|
||||
! (INBOUNDS_STATS_FILE="$TMPDIR/none.json" _inbound_stats 7) 2> "$TMPDIR/err"
|
||||
grep -q 'No traffic recorded yet' "$TMPDIR/err"
|
||||
|
||||
# --- proxy-ctl inbounds sub -----------------------------------------
|
||||
printf '%s' '[{"user":"fufsob","token":"aaa"},{"user":"teri","token":"bbb"}]' > "$TMPDIR/subs.json"
|
||||
export INBOUNDS_SUBS_FILE="$TMPDIR/subs.json"
|
||||
test "$(INBOUNDS_SUB_BASE_URL=https://vpn.example/sub/ _inbound_subscriptions teri)" = https://vpn.example/sub/bbb
|
||||
# Without a user: names only, never a token.
|
||||
out="$(INBOUNDS_SUB_BASE_URL=https://vpn.example/sub _inbound_subscriptions 2> /dev/null)"
|
||||
test "$(wc -l <<<"$out")" = 2
|
||||
! grep -qE 'aaa|bbb' <<<"$out"
|
||||
! (_inbound_subscriptions nobody) 2> /dev/null
|
||||
# Without a base URL: the file path, and no QR code.
|
||||
test "$(INBOUNDS_SUB_BASE_URL= _inbound_subscriptions fufsob 2> /dev/null)" = "$TMPDIR/subs/aaa"
|
||||
! (INBOUNDS_SUB_BASE_URL= _inbound_subscriptions fufsob --qr) 2> /dev/null
|
||||
EOF
|
||||
bash "$TMPDIR/test.sh"
|
||||
touch "$out"
|
||||
'';
|
||||
|
||||
@@ -757,16 +486,14 @@
|
||||
pkgs.runCommand "proxy-suite-proxy-ctl-amneziawg-check"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
pkgs.bash
|
||||
pkgs.python3
|
||||
pkgs.coreutils
|
||||
pkgs.gnugrep
|
||||
pkgs.jq
|
||||
];
|
||||
}
|
||||
''
|
||||
proxy_ctl="$TMPDIR/proxy-ctl"
|
||||
cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl"
|
||||
chmod +x "$proxy_ctl"
|
||||
proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py}
|
||||
|
||||
mkdir -p bin
|
||||
cat > bin/systemctl <<'SH'
|
||||
@@ -797,17 +524,17 @@
|
||||
export SYSTEMCTL_LOG="$PWD/systemctl.log"
|
||||
export AWG_PROFILES_FILE="$PWD/awg-profiles.json"
|
||||
|
||||
bash "$proxy_ctl" awg list > list-output
|
||||
python3 "$proxy_ctl" awg list > list-output
|
||||
grep -q 'home.*active' list-output
|
||||
grep -q 'work.*inactive' list-output
|
||||
bash "$proxy_ctl" awg on work
|
||||
bash "$proxy_ctl" awg off home
|
||||
bash "$proxy_ctl" awg restart home
|
||||
python3 "$proxy_ctl" awg on work
|
||||
python3 "$proxy_ctl" awg off home
|
||||
python3 "$proxy_ctl" awg restart home
|
||||
grep -q '^start proxy-suite-awg-work$' "$SYSTEMCTL_LOG"
|
||||
grep -q '^stop proxy-suite-awg-home$' "$SYSTEMCTL_LOG"
|
||||
grep -q '^restart proxy-suite-awg-home$' "$SYSTEMCTL_LOG"
|
||||
|
||||
if bash "$proxy_ctl" awg on missing 2> error-output; then
|
||||
if python3 "$proxy_ctl" awg on missing 2> error-output; then
|
||||
exit 1
|
||||
fi
|
||||
grep -q 'Unknown AmneziaWG profile' error-output
|
||||
|
||||
@@ -82,12 +82,6 @@ in
|
||||
(
|
||||
assert pkgs.lib.hasInfix "proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]"
|
||||
minimalProxyCtlScript;
|
||||
assert pkgs.lib.hasInfix ''printf 'route_mode=%s\n' "$(_route_mode_current)"''
|
||||
minimalProxyCtlScript;
|
||||
assert pkgs.lib.hasInfix ''printf 'default_route_mode=%s\n' "$(_route_mode_default)"''
|
||||
minimalProxyCtlScript;
|
||||
assert pkgs.lib.hasInfix ''systemctl start "proxy-suite-route-mode@''${action}.service"''
|
||||
minimalProxyCtlScript;
|
||||
true
|
||||
)
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+7
-7
@@ -38,8 +38,9 @@
|
||||
}:
|
||||
|
||||
let
|
||||
unwrapped = pkgs.writeShellScriptBin "proxy-ctl" (
|
||||
builtins.readFile ./proxy-ctl-lib.sh + "\n" + builtins.readFile ./proxy-ctl.sh
|
||||
# Not writePython3Bin: its flake8 pass would gate the build on style.
|
||||
unwrapped = pkgs.writeScriptBin "proxy-ctl" (
|
||||
"#!${pkgs.python3}/bin/python3\n" + builtins.readFile ./proxy-ctl/proxy_ctl.py
|
||||
);
|
||||
wrapperEnv = {
|
||||
CLASH_API = clashApi;
|
||||
@@ -93,8 +94,11 @@ pkgs.symlinkJoin {
|
||||
# curl. The newest Chrome profile the package ships, since the set varies by
|
||||
# version; the build fails if there is none.
|
||||
postBuild = ''
|
||||
install -Dm644 ${./proxy-ctl-completion.bash} \
|
||||
install -Dm644 ${./proxy-ctl/completions/proxy-ctl.bash} \
|
||||
"$out/share/bash-completion/completions/proxy-ctl"
|
||||
install -Dm644 ${./proxy-ctl/completions/_proxy-ctl} "$out/share/zsh/site-functions/_proxy-ctl"
|
||||
install -Dm644 ${./proxy-ctl/completions/proxy-ctl.fish} \
|
||||
"$out/share/fish/vendor_completions.d/proxy-ctl.fish"
|
||||
probe_curl=$(ls ${pkgs.curl-impersonate}/bin/curl_chrome[0-9]* | grep -E '/curl_chrome[0-9]+$' | sort -V | tail -n 1)
|
||||
[ -x "$probe_curl" ]
|
||||
wrapProgram "$out/bin/proxy-ctl" \
|
||||
@@ -103,12 +107,8 @@ pkgs.symlinkJoin {
|
||||
lib.makeBinPath [
|
||||
# curl-impersonate's curl_chrome* wrappers are `#!/usr/bin/env bash`.
|
||||
pkgs.bash
|
||||
pkgs.coreutils
|
||||
pkgs.curl
|
||||
pkgs.fzf
|
||||
pkgs.gawk
|
||||
pkgs.gnugrep
|
||||
pkgs.jq
|
||||
pkgs.proxychains-ng
|
||||
pkgs.qrencode
|
||||
pkgs.systemd
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
set -euo pipefail
|
||||
|
||||
PROXYCHAINS_QUIET_ARG="${PROXYCHAINS_QUIET_ARG:-}"
|
||||
SUB_TAGS=()
|
||||
AWG_PROFILES=()
|
||||
if [ -f "${SUB_TAGS_FILE:-}" ]; then
|
||||
mapfile -t SUB_TAGS < <(jq -r '.[]' "$SUB_TAGS_FILE")
|
||||
fi
|
||||
if [ -f "${AWG_PROFILES_FILE:-}" ]; then
|
||||
mapfile -t AWG_PROFILES < <(jq -r '.[]' "$AWG_PROFILES_FILE")
|
||||
fi
|
||||
|
||||
# Old spellings: still accepted, not in the help.
|
||||
case "${1:-}" in
|
||||
tun | tproxy | outbounds | select) set -- proxy "$@" ;;
|
||||
route-mode) shift; set -- proxy mode "$@" ;;
|
||||
subscription) shift; set -- proxy subs "$@" ;;
|
||||
wrap) shift; set -- apps run "$@" ;;
|
||||
esac
|
||||
|
||||
cmd="${1:-status}"
|
||||
shift || true
|
||||
|
||||
case "$cmd" in
|
||||
help | -h | --help) _help ;;
|
||||
status) cmd_status "$@" ;;
|
||||
restart) cmd_restart ;;
|
||||
logs)
|
||||
if [ "$#" -gt 0 ]; then exec journalctl -fu "$@"; fi
|
||||
# journalctl takes unit globs, so the default needs no unit list of its own.
|
||||
exec journalctl -f -u 'proxy-suite-*' -u zapret-discord-youtube
|
||||
;;
|
||||
proxy) cmd_proxy "$@" ;;
|
||||
zapret) cmd_zapret "$@" ;;
|
||||
awg) cmd_awg "$@" ;;
|
||||
ssh) _toggle proxy-suite-ssh-proxy ssh "$@" ;;
|
||||
apps) cmd_apps "$@" ;;
|
||||
inbounds) cmd_inbounds "$@" ;;
|
||||
where) cmd_where "$@" ;;
|
||||
__complete) cmd_complete "$@" ;;
|
||||
*)
|
||||
_help >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,5 @@
|
||||
#compdef proxy-ctl
|
||||
# proxy-ctl knows its own verbs, tags, profiles and units: ask it.
|
||||
local -a candidates
|
||||
candidates=(${(f)"$(proxy-ctl __complete ${(Q)words[2,CURRENT-1]} 2>/dev/null)"})
|
||||
compadd -a candidates
|
||||
File renamed without changes.
@@ -0,0 +1,2 @@
|
||||
# proxy-ctl knows its own verbs, tags, profiles and units: ask it.
|
||||
complete -c proxy-ctl -f -a '(proxy-ctl __complete (commandline -xpc)[2..] 2>/dev/null)'
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,410 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import contextlib
|
||||
import datetime
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import proxy_ctl as ctl
|
||||
|
||||
|
||||
def run(fn, *args):
|
||||
"""(exit status, stdout, stderr) of a proxy-ctl function."""
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
status = 0
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
try:
|
||||
fn(*args)
|
||||
except SystemExit as e:
|
||||
status = e.code
|
||||
return status, out.getvalue(), err.getvalue()
|
||||
|
||||
|
||||
def ok(fn, *args):
|
||||
status, out, err = run(fn, *args)
|
||||
assert status == 0, (status, out, err)
|
||||
return out
|
||||
|
||||
|
||||
class EnvTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.dir = self.tmp.name
|
||||
patcher = mock.patch.dict(os.environ, {}, clear=False)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
|
||||
def path(self, name):
|
||||
return os.path.join(self.dir, name)
|
||||
|
||||
def write(self, name, content):
|
||||
path = self.path(name)
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
f.write(content if isinstance(content, str) else json.dumps(content))
|
||||
return path
|
||||
|
||||
def patch(self, name, value):
|
||||
patcher = mock.patch.object(ctl, name, value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
|
||||
# The verdict table, fed tuples measured on a real censored network.
|
||||
class ProbeVerdictTest(unittest.TestCase):
|
||||
def expect(self, want, direct, via):
|
||||
self.assertEqual(ctl._probe_verdict(direct, via), want, (direct, via))
|
||||
|
||||
def test_table(self):
|
||||
# Origin refuses direct, accepts the proxy: chatgpt.com/robots.txt.
|
||||
self.expect("destination", "0|0.146175|403|6633|", "0|0.230116|200|4302|")
|
||||
# The same through a redirect: claude.ai/robots.txt.
|
||||
self.expect("destination", "0|0.141625|302|143|https://claude.com/app-unavailable-in-region", "0|0.181276|200|281|")
|
||||
# TLS never completed: censorship, zapret's job.
|
||||
self.expect("censor", "35|0.000000|000|0|", "0|0.119348|200|6258|")
|
||||
# Handshake, then silence: the post-handshake throttle.
|
||||
self.expect("censor", "0|0.125029|000|0|", "0|0.143772|200|32881|")
|
||||
# Direct works. Nothing to do, whoever else also works.
|
||||
self.expect("ok", "0|0.099546|200|2678|", "0|0.146822|200|2678|")
|
||||
# robots.txt legitimately absent is not a failure.
|
||||
self.expect("ok", "0|0.161330|404|559|", "0|0.214667|404|559|")
|
||||
# An ordinary redirect must not read as a block.
|
||||
self.expect("ok", "0|0.10|301|0|https://www.example.com/robots.txt", "0|0.20|301|0|https://www.example.com/robots.txt")
|
||||
# Refused everywhere: not an egress problem.
|
||||
self.expect("both-fail", "0|0.10|403|100|", "0|0.20|403|100|")
|
||||
# Nothing reaches it at all - a dead name, not a blocked one.
|
||||
self.expect("unreachable", "6|0.000000|000|0|", "35|0.000000|000|0|")
|
||||
|
||||
|
||||
class ProbeFetchTest(EnvTest):
|
||||
def test_redirect_chains(self):
|
||||
calls = []
|
||||
table = {
|
||||
"https://spotify.test/": "0|0.1|301|0|https://www.spotify.test/",
|
||||
"https://www.spotify.test/": "0|0.1|301|0|https://open.spotify.test/",
|
||||
"https://open.spotify.test/": "0|0.1|302|93|https://accounts.spotify.test/login",
|
||||
"https://accounts.spotify.test/login": "0|0.1|301|0|https://www.spotify.test/int/why-not-available/",
|
||||
"https://redir.test/": "0|0.1|301|0|https://elsewhere.example/",
|
||||
"https://loop.test/": "0|0.1|301|0|https://loop.test/",
|
||||
}
|
||||
|
||||
def curl(argv):
|
||||
calls.append(argv[-1])
|
||||
return 0, table.get(argv[-1], "0|0.1|200|10|")
|
||||
|
||||
self.patch("run_curl", curl)
|
||||
# spotify.com: the block is four same-site hops in.
|
||||
self.assertEqual(ctl._probe_exit_verdict(ctl._probe_fetch("spotify.test", "/", "--noproxy", "*")), "blocked")
|
||||
# Leaving the site ends the walk.
|
||||
self.assertEqual(ctl._probe_exit_verdict(ctl._probe_fetch("redir.test", "/", "--noproxy", "*")), "ok")
|
||||
# A redirect loop inside the site still stops.
|
||||
calls.clear()
|
||||
ctl._probe_fetch("loop.test", "/", "--noproxy", "*")
|
||||
self.assertLessEqual(len(calls), 6)
|
||||
|
||||
def test_curl_that_cannot_start(self):
|
||||
# An error, not a dead site.
|
||||
os.environ.update(PROBE_CURL="/nonexistent", PROBE_EXITS_FILE="/nonexistent")
|
||||
self.patch("svc_active", lambda unit: True)
|
||||
status, _, err = run(ctl.cmd_proxy_probe, "--json", "x.test")
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn("Cannot run /nonexistent", err)
|
||||
|
||||
|
||||
class ProbeWalkTest(EnvTest):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.patch("svc_active", lambda unit: True)
|
||||
os.environ["PROBE_EXITS_FILE"] = "/nonexistent"
|
||||
|
||||
def probe(self, *args):
|
||||
return json.loads(ok(ctl.cmd_proxy_probe, "--json", *args))
|
||||
|
||||
def probe_with(self, apex_direct, apex_proxy, robots_direct, robots_proxy):
|
||||
"""No listener index: only this host and the local proxy."""
|
||||
|
||||
def fetch(domain, path, flag, url):
|
||||
if path == "/":
|
||||
return apex_direct if flag == "--noproxy" else apex_proxy
|
||||
return robots_direct if flag == "--noproxy" else robots_proxy
|
||||
|
||||
self.patch("_probe_fetch", fetch)
|
||||
return self.probe("example.test")
|
||||
|
||||
# --- which path decides: the apex, robots.txt only breaks ties ---
|
||||
def test_apex_decides(self):
|
||||
# last.fm: apex geo-blocked, robots.txt served everywhere.
|
||||
out = self.probe_with("0|0.11|403|424|", "0|0.17|200|59809|", "0|0.11|200|400|", "0|0.17|200|400|")
|
||||
self.assertEqual((out["verdict"], out["url"]), ("destination", "https://example.test/"))
|
||||
|
||||
def test_robots_breaks_ties(self):
|
||||
# chatgpt.com: apex 403 everywhere, robots.txt separates.
|
||||
out = self.probe_with("0|0.14|403|6633|", "0|0.23|403|8442|", "0|0.14|403|6633|", "0|0.23|200|4302|")
|
||||
self.assertEqual((out["verdict"], out["url"]), ("destination", "https://example.test/robots.txt"))
|
||||
|
||||
def test_working_apex_is_not_second_guessed(self):
|
||||
out = self.probe_with("0|0.10|200|500|", "0|0.20|200|500|", "0|0.10|403|10|", "0|0.20|200|10|")
|
||||
self.assertEqual(out["verdict"], "ok")
|
||||
|
||||
# --- walking more than two exits ---
|
||||
def use_exits(self, fetch):
|
||||
os.environ["PROBE_EXITS_FILE"] = self.write(
|
||||
"exits.json",
|
||||
[{"i": 0, "tag": "direct", "port": 18540}, {"i": 1, "tag": "fi", "port": 18541}, {"i": 2, "tag": "de", "port": 18542}],
|
||||
)
|
||||
self.patch("_probe_fetch", fetch)
|
||||
|
||||
def test_multi_exit(self):
|
||||
# Direct and the first proxy share a WAF; only the third exit gets through.
|
||||
# Every exit, direct included, goes through its pinned listener.
|
||||
self.use_exits(lambda domain, path, flag, url: "0|0.10|200|500|" if url.endswith(":18542") else "0|0.10|403|919|")
|
||||
out = self.probe("sekai.test")
|
||||
self.assertEqual((out["verdict"], out["exit"]), ("destination", "de"))
|
||||
|
||||
# --keep-going tries every exit but keeps the first that worked.
|
||||
out = self.probe("--keep-going", "--exits", "de,fi", "sekai.test")
|
||||
self.assertEqual(out["exit"], "de")
|
||||
self.assertEqual([e["tag"] for e in out["exits"]], ["direct", "de", "fi", "direct", "de", "fi"])
|
||||
|
||||
# --exits restricts and orders the walk; direct is always tried first.
|
||||
out = self.probe("--exits", "de", "sekai.test")
|
||||
self.assertEqual([e["tag"] for e in out["exits"]], ["direct", "de"])
|
||||
|
||||
# An empty list probes direct only (every exit shares one network).
|
||||
out = self.probe("--exits", "", "sekai.test")
|
||||
self.assertEqual({e["tag"] for e in out["exits"]}, {"direct"})
|
||||
self.assertIsNone(out["exit"])
|
||||
|
||||
# --via: can this exit carry what direct reaches?
|
||||
out = self.probe("--via", "de", "sekai.test")
|
||||
self.assertEqual(out["verdict"], "ok")
|
||||
self.assertEqual({e["tag"] for e in out["exits"]}, {"de", "direct"})
|
||||
self.assertEqual(self.probe("--via", "fi", "sekai.test")["verdict"], "blocked")
|
||||
self.assertNotEqual(run(ctl.cmd_proxy_probe, "--json", "--via", "nowhere", "sekai.test")[0], 0)
|
||||
|
||||
# A given path is probed as is, for that probe only.
|
||||
out = self.probe("--via", "de", "sekai.test/robots.txt")
|
||||
self.assertEqual(out["url"], "https://sekai.test/robots.txt")
|
||||
self.assertEqual({e["path"] for e in out["exits"]}, {"/robots.txt"})
|
||||
out = self.probe("--via", "fi", "sekai.test")
|
||||
self.assertEqual({e["path"] for e in out["exits"]}, {"/", "/robots.txt"})
|
||||
|
||||
def test_via_refused_front_page(self):
|
||||
# Refused a front page direct gets: not a stand-in (www.reddit.com).
|
||||
self.use_exits(lambda domain, path, flag, url: "0|0.10|403|190240|" if url.endswith(":18541") and path == "/" else "0|0.10|200|500|")
|
||||
self.assertEqual(self.probe("--via", "fi", "geo.test")["verdict"], "blocked")
|
||||
|
||||
def test_via_robots_decides(self):
|
||||
# i.pximg.net: the front page is 400 everywhere, so robots.txt decides.
|
||||
self.use_exits(lambda domain, path, flag, url: "0|0.10|400|0|" if path == "/" else "0|0.10|200|43|")
|
||||
self.assertEqual(self.probe("--via", "fi", "cdn.test")["verdict"], "ok")
|
||||
|
||||
def test_text_output(self):
|
||||
self.use_exits(lambda domain, path, flag, url: "0|0.10|200|500|" if url.endswith(":18542") else "0|0.10|403|919|")
|
||||
out = ok(ctl.cmd_proxy_probe, "sekai.test")
|
||||
self.assertRegex(out, r"(?m)^ de +/ +TLS 0\.10s, 200, 500 bytes +ok <- chosen$")
|
||||
self.assertIn('pin: proxy.routing.rules = [ { outbound = "de"; domains = [ "sekai.test" ]; } ]', out)
|
||||
|
||||
|
||||
class AutoProxyTest(EnvTest):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
os.environ.update(AUTOPROXY_ENABLED="1", AUTOPROXY_STATE_DIR=self.dir)
|
||||
|
||||
def state_on_start(self, state):
|
||||
def systemctl(*args, **kw):
|
||||
if args[:1] == ("start",):
|
||||
self.write("state.json", state)
|
||||
return 0, ""
|
||||
|
||||
self.patch("systemctl", systemctl)
|
||||
|
||||
def test_learn(self):
|
||||
self.state_on_start(
|
||||
{
|
||||
"domains": {"last.fm": {"verdict": "destination", "exit": "primary", "host": "www.last.fm"}},
|
||||
"hosts": {"www.last.fm": {"domain": "last.fm", "verdict": "destination", "exit": "primary"}},
|
||||
}
|
||||
)
|
||||
with mock.patch.dict(os.environ, AUTOPROXY_ENABLED="0"):
|
||||
self.assertNotEqual(run(ctl.cmd_proxy_learn, "www.last.fm")[0], 0)
|
||||
# It lands in a root-owned file and then in a URL: hostnames only.
|
||||
self.assertNotEqual(run(ctl.cmd_proxy_learn, "x;rm -rf /")[0], 0)
|
||||
self.assertNotEqual(run(ctl.cmd_proxy_learn, "-evil.test/path")[0], 0)
|
||||
out = ok(ctl.cmd_proxy_learn, "www.last.fm")
|
||||
self.assertEqual(ctl.read_text(self.path("requests")), "www.last.fm\n")
|
||||
self.assertIn("last.fm: destination - routed via primary", out)
|
||||
|
||||
def test_learn_nothing_to_route(self):
|
||||
# A verdict that routes nothing is kept for its host and reported.
|
||||
self.state_on_start({"domains": {}, "hosts": {"api.example.test": {"domain": "example.test", "verdict": "ok", "exit": None}}})
|
||||
self.assertIn("api.example.test: ok - nothing to route", ok(ctl.cmd_proxy_learn, "api.example.test"))
|
||||
|
||||
def test_learn_failed_run(self):
|
||||
# A failed run is reported in plain words, and the request is not lost.
|
||||
self.patch("systemctl", lambda *args, **kw: (1, ""))
|
||||
status, _, err = run(ctl.cmd_proxy_learn, "www.last.fm")
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn("still queued", err)
|
||||
self.assertIn("www.last.fm\n", ctl.read_text(self.path("requests")))
|
||||
|
||||
def test_queue_and_learned(self):
|
||||
self.patch("systemctl", lambda *args, **kw: (0, ""))
|
||||
self.write("requests", "www.last.fm\n")
|
||||
self.write(
|
||||
"state.json",
|
||||
{
|
||||
"domains": {"spotify.com": {"verdict": "destination", "exit": "primary", "host": "www.spotify.com", "at": 0}},
|
||||
"hosts": {
|
||||
"www.spotify.com": {"domain": "spotify.com", "verdict": "destination", "exit": "primary"},
|
||||
"gew1-spclient.spotify.com": {"domain": "spotify.com", "verdict": "ok", "exit": None},
|
||||
},
|
||||
"backlog": {"a.example": {"domain": "example", "hits": 2}, "b.example": {"domain": "example", "hits": 9}},
|
||||
},
|
||||
)
|
||||
q = ok(ctl.cmd_proxy_queue)
|
||||
self.assertIn("\n www.last.fm\n", q)
|
||||
# Most-dialled first.
|
||||
self.assertLess(q.index("b.example"), q.index("a.example"))
|
||||
learned = ok(ctl.cmd_proxy_learned)
|
||||
self.assertRegex(learned, r"spotify.com .*-> primary")
|
||||
self.assertIn("ok=1", learned)
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
|
||||
def test_unreadable_state_asks_for_sudo(self):
|
||||
os.chmod(self.dir, 0)
|
||||
try:
|
||||
status, _, err = run(ctl.cmd_proxy_queue)
|
||||
finally:
|
||||
os.chmod(self.dir, 0o755)
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn("enable userControl, or run with sudo", err)
|
||||
|
||||
|
||||
class InboundsTest(EnvTest):
|
||||
def test_stats(self):
|
||||
self.patch("systemctl", lambda *args, **kw: (0, ""))
|
||||
self.patch("_today", lambda: datetime.date(2026, 9, 11))
|
||||
os.environ["INBOUNDS_STATS_FILE"] = self.write(
|
||||
"stats.json",
|
||||
{
|
||||
"days": {
|
||||
"2026-09-11": {"fufsob": {"down": 6000000, "up": 4000}, "phone": {"up": 0}},
|
||||
"2026-09-10": {"fufsob": {"down": 1073741824, "up": 1048576}},
|
||||
"2026-09-01": {"fufsob": {"down": 1, "up": 1}},
|
||||
}
|
||||
},
|
||||
)
|
||||
out = ok(ctl._inbound_stats, "2")
|
||||
# Newest day first, sizes readable, then totals over the period.
|
||||
self.assertLess(out.index(" 2026-09-11"), out.index(" 2026-09-10"))
|
||||
self.assertNotIn("2026-09-01", out)
|
||||
self.assertRegex(out, r"(?m)^ 2026-09-11 +fufsob +5\.7 MiB +4 KiB$")
|
||||
self.assertRegex(out, r"(?m)^ 2026-09-11 +phone +0 B +0 B$")
|
||||
self.assertRegex(out, r"(?m)^ 2026-09-10 +fufsob +1\.0 GiB +1\.0 MiB$")
|
||||
self.assertRegex(out, r"(?m)^ fufsob +1\.0 GiB +1\.0 MiB$")
|
||||
self.assertNotEqual(run(ctl._inbound_stats, "0")[0], 0)
|
||||
# Nothing collected yet says so, rather than printing an empty table.
|
||||
os.environ["INBOUNDS_STATS_FILE"] = self.path("none.json")
|
||||
status, _, err = run(ctl._inbound_stats, "7")
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn("No traffic recorded yet", err)
|
||||
|
||||
def test_subscriptions(self):
|
||||
os.environ["INBOUNDS_SUBS_FILE"] = self.write("subs.json", [{"user": "fufsob", "token": "aaa"}, {"user": "teri", "token": "bbb"}])
|
||||
os.environ["INBOUNDS_SUB_BASE_URL"] = "https://vpn.example/sub/"
|
||||
self.assertEqual(ok(ctl._inbound_subscriptions, "teri"), "https://vpn.example/sub/bbb\n")
|
||||
# Without a user: names only, never a token.
|
||||
out = ok(ctl._inbound_subscriptions)
|
||||
self.assertEqual(out, " fufsob\n teri\n")
|
||||
self.assertNotEqual(run(ctl._inbound_subscriptions, "nobody")[0], 0)
|
||||
# Without a base URL: the file path, and no QR code.
|
||||
os.environ["INBOUNDS_SUB_BASE_URL"] = ""
|
||||
self.assertEqual(ok(ctl._inbound_subscriptions, "fufsob"), self.path("subs") + "/aaa\n")
|
||||
self.assertNotEqual(run(ctl._inbound_subscriptions, "fufsob", "--qr")[0], 0)
|
||||
|
||||
|
||||
class AppsRunTest(EnvTest):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.calls = []
|
||||
self.active = set()
|
||||
self.execed = None
|
||||
os.environ.update(
|
||||
PER_APP_ROUTING_ENABLED="1",
|
||||
PER_APP_ROUTING_PROXYCHAINS_ENABLED="1",
|
||||
PER_APP_ROUTING_TUN_ENABLED="1",
|
||||
PER_APP_ROUTING_TPROXY_ENABLED="1",
|
||||
PER_APP_ROUTING_ZAPRET_ENABLED="1",
|
||||
PROXYCHAINS_QUIET_ARG="-q",
|
||||
PROXYCHAINS_CONFIG=self.write("proxychains.conf", ""),
|
||||
PER_APP_ROUTING_PROFILES_FILE=self.write(
|
||||
"profiles.json",
|
||||
[{"name": n, "route": n} for n in ("direct", "proxychains", "tun", "tproxy", "zapret")],
|
||||
),
|
||||
)
|
||||
|
||||
def systemctl(*args, **kw):
|
||||
self.calls.append(args)
|
||||
if args[:2] == ("is-active", "--quiet"):
|
||||
return (0 if args[2] in self.active else 3), ""
|
||||
return 0, ""
|
||||
|
||||
def exec_(argv):
|
||||
self.execed = argv
|
||||
raise SystemExit(0)
|
||||
|
||||
self.patch("systemctl", systemctl)
|
||||
self.patch("_exec", exec_)
|
||||
self.patch("_run_foreground", lambda argv: self.calls.append(tuple(argv)) or self.scope_status)
|
||||
self.scope_status = 0
|
||||
self.addCleanup(lambda: ctl.signal.signal(ctl.signal.SIGTERM, ctl.signal.SIG_DFL))
|
||||
|
||||
def test_direct_and_proxychains_exec(self):
|
||||
run(ctl.cmd_apps, "run", "direct", "--", "firefox", "-P")
|
||||
self.assertEqual(self.execed, ["firefox", "-P"])
|
||||
run(ctl.cmd_apps, "run", "proxychains", "--", "curl", "x")
|
||||
self.assertEqual(self.execed, ["proxychains4", "-q", "-f", os.environ["PROXYCHAINS_CONFIG"], "curl", "x"])
|
||||
os.environ["PROXYCHAINS_CONFIG"] = self.path("missing.conf")
|
||||
self.assertIn("Proxychains config is not readable", run(ctl.cmd_apps, "run", "proxychains", "--", "curl")[2])
|
||||
|
||||
def test_slice_routes(self):
|
||||
for route in ("tun", "tproxy", "zapret"):
|
||||
self.calls.clear()
|
||||
status, _, _ = run(ctl.cmd_apps, "run", route, "--", "curl", "x")
|
||||
self.assertEqual(status, 0)
|
||||
base = f"proxy-suite-per-app-{route}"
|
||||
scope = next(c for c in self.calls if c[0] == "systemd-run")
|
||||
self.assertIn(f"--unit={base}-{route}-{os.getpid()}", scope)
|
||||
self.assertIn(f"--slice={base}", scope)
|
||||
self.assertEqual(scope[-2:], ("curl", "x"))
|
||||
self.assertIn(("start", f"{base}-user@{os.getuid()}.service"), self.calls)
|
||||
# Nothing else runs in the slice, so it is torn down afterwards.
|
||||
self.assertIn(("stop", f"{base}.service"), self.calls)
|
||||
self.assertIn(("--user", "stop", f"{base}-anchor.service"), self.calls)
|
||||
|
||||
def test_cleanup_when_scope_fails(self):
|
||||
self.scope_status = 3
|
||||
status, _, _ = run(ctl.cmd_apps, "run", "tun", "--", "false")
|
||||
self.assertEqual(status, 3)
|
||||
self.assertIn(("stop", "proxy-suite-per-app-tun.service"), self.calls)
|
||||
|
||||
def test_global_proxy_refused(self):
|
||||
self.active = {"proxy-suite-tun.service"}
|
||||
status, _, err = run(ctl.cmd_apps, "run", "tproxy", "--", "curl")
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn("Global proxy-suite-tun.service is active", err)
|
||||
self.assertFalse(any(c[0] == "systemd-run" for c in self.calls))
|
||||
|
||||
def test_disabled_route(self):
|
||||
os.environ["PER_APP_ROUTING_ZAPRET_ENABLED"] = "0"
|
||||
self.assertIn("perAppRouting.zapret.enable is false", run(ctl.cmd_apps, "run", "zapret", "--", "curl")[2])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user