From 8a4ba2db6a4a86d8c004ca6ca92435cdccbcaccd Mon Sep 17 00:00:00 2001 From: FUFSoB Date: Fri, 18 Sep 2026 21:39:18 +0500 Subject: [PATCH] refactor: remove duplication --- deploy/installer.nix | 7 +- deploy/net-rescue.nix | 7 +- deploy/script.nix | 16 + deploy/server-module.nix | 2 +- modules/proxy-suite/amnezia-wg-inbounds.nix | 21 +- modules/proxy-suite/amnezia-wg.nix | 23 +- modules/proxy-suite/assembly.nix | 62 +++ modules/proxy-suite/awg-common.nix | 27 ++ .../config-templates/proxy-inbounds.nix | 12 +- modules/proxy-suite/core.nix | 56 +-- modules/proxy-suite/derived.nix | 29 +- modules/proxy-suite/hosts/common.nix | 57 +++ modules/proxy-suite/hosts/home-manager.nix | 28 +- modules/proxy-suite/hosts/nix-on-droid.nix | 29 +- modules/proxy-suite/hosts/nixos.nix | 52 +-- modules/proxy-suite/hosts/system-manager.nix | 70 ++- modules/proxy-suite/lib/scripts-dir.nix | 14 + modules/proxy-suite/options/default.nix | 1 - modules/proxy-suite/options/inbounds.nix | 7 +- modules/proxy-suite/options/lib.nix | 47 ++ .../proxy-suite/options/per-app-routing.nix | 7 +- modules/proxy-suite/options/proxy-routing.nix | 8 +- modules/proxy-suite/options/removed.nix | 13 +- modules/proxy-suite/options/ssh-proxy.nix | 8 +- modules/proxy-suite/options/tg-ws-proxy.nix | 8 +- modules/proxy-suite/options/tray.nix | 19 - modules/proxy-suite/options/types.nix | 9 +- .../proxy-suite/options/types/amnezia-wg.nix | 175 ++----- .../proxy-suite/options/types/inbounds.nix | 8 +- .../proxy-suite/options/types/outbounds.nix | 8 +- modules/proxy-suite/options/zapret.nix | 14 +- modules/proxy-suite/options/zapret2.nix | 7 +- modules/proxy-suite/service-assertions.nix | 439 +++++++----------- modules/proxy-suite/service/context.nix | 184 ++------ .../proxy-suite/service/control-scripts.nix | 10 +- modules/proxy-suite/service/control.nix | 150 +++--- modules/proxy-suite/service/default.nix | 76 +-- .../proxy-suite/service/per-app-routing.nix | 164 ++----- .../per-app-routing/backend-scripts.nix | 32 +- .../service/per-app-routing/profiles.nix | 26 +- .../service/proxy-inbounds-scripts.nix | 51 +- .../proxy-suite/service/routing-scripts.nix | 28 +- .../script-blocks/hybrid-runtime-helpers.nix | 16 +- .../service/script-blocks/subscriptions.nix | 31 +- modules/proxy-suite/service/scripts.nix | 197 +++----- modules/proxy-suite/service/start-scripts.nix | 196 ++++---- modules/proxy-suite/service/units.nix | 53 ++- modules/proxy-suite/tor.nix | 18 +- modules/proxy-suite/warp.nix | 15 +- modules/proxy-suite/wg-tunnel.nix | 5 +- modules/proxy-suite/zapret.nix | 36 +- modules/proxy-suite/zapret/common.nix | 42 ++ modules/proxy-suite/zapret/packages.nix | 12 +- modules/proxy-suite/zapret2.nix | 42 +- nix/checks.nix | 4 +- nix/checks/amnezia-wg-outbound.nix | 27 +- nix/checks/amnezia-wg.nix | 61 ++- nix/checks/chaining-dns.nix | 6 +- nix/checks/core-proxy.nix | 4 + nix/checks/core-proxy/fixtures.nix | 10 +- nix/checks/core-proxy/routing-dns.nix | 69 +-- nix/checks/core-proxy/service-defaults.nix | 24 +- nix/checks/global-proxy-modes.nix | 17 +- nix/checks/hybrid-backend.nix | 2 + nix/checks/hybrid-backend/fixtures.nix | 26 +- nix/checks/lib.nix | 150 +++--- nix/checks/local-proxy-auth.nix | 10 +- nix/checks/module-suite.nix | 29 +- nix/checks/parsers.nix | 57 --- nix/checks/per-app-routing-proxychains.nix | 27 +- nix/checks/per-app-routing-tproxy.nix | 7 +- nix/checks/per-app-routing-tun.nix | 26 +- .../per-app-routing-validation-resources.nix | 104 ++--- nix/checks/per-app-routing-validation.nix | 6 +- nix/checks/per-app-routing-zapret.nix | 12 +- nix/checks/per-app-routing.nix | 10 +- nix/checks/proxy-inbounds.nix | 300 +++--------- nix/checks/python-tests.nix | 117 +++++ nix/checks/repo.nix | 109 +---- nix/checks/route-mode.nix | 20 +- nix/checks/server-module.nix | 86 ++-- nix/checks/ssh-proxy.nix | 328 ++++--------- nix/checks/subscriptions-runtime.nix | 28 +- nix/checks/subscriptions-runtime/fixtures.nix | 14 +- nix/checks/subscriptions-validation.nix | 7 +- nix/checks/subscriptions.nix | 3 + nix/checks/tg-ws-proxy.nix | 18 +- nix/checks/tg-ws-proxy/fixtures.nix | 6 +- nix/checks/tor.nix | 80 ++-- nix/checks/user-control.nix | 11 +- nix/checks/warp.nix | 25 +- nix/checks/xray-backend-features.nix | 2 + nix/checks/xray-backend-features/fixtures.nix | 27 +- nix/checks/xray-backend-runtime.nix | 3 + nix/checks/xray-backend-runtime/fixtures.nix | 14 +- nix/checks/xray-backend-runtime/tun.nix | 1 + nix/checks/xray-backend.nix | 3 + nix/checks/xray-backends.nix | 3 + nix/checks/zapret-hostlist-routing.nix | 1 + nix/checks/zapret.nix | 2 + nix/readme-doc.nix | 47 +- pkgs/proxy-ctl.nix | 87 +--- pkgs/proxy-ctl/proxy_ctl.py | 49 +- pkgs/proxy-ctl/proxy_supervisor.py | 86 ++-- pkgs/proxy-ctl/test_proxy_supervisor.py | 32 +- scripts/patch-zapret-config.py | 158 +++---- scripts/proxy_parsing.py | 108 +++-- scripts/proxy_url_parsers.py | 56 +-- scripts/test-patch-zapret-config.py | 91 ++++ 109 files changed, 2206 insertions(+), 3078 deletions(-) create mode 100644 deploy/script.nix create mode 100644 modules/proxy-suite/assembly.nix create mode 100644 modules/proxy-suite/awg-common.nix create mode 100644 modules/proxy-suite/lib/scripts-dir.nix create mode 100644 modules/proxy-suite/options/lib.nix delete mode 100644 modules/proxy-suite/options/tray.nix create mode 100644 modules/proxy-suite/zapret/common.nix delete mode 100644 nix/checks/parsers.nix create mode 100644 nix/checks/python-tests.nix create mode 100644 scripts/test-patch-zapret-config.py diff --git a/deploy/installer.nix b/deploy/installer.nix index 8db0eab..780d701 100644 --- a/deploy/installer.nix +++ b/deploy/installer.nix @@ -27,8 +27,9 @@ xkcdpass, }: -writeShellApplication { +import ./script.nix { inherit lib writeShellApplication; } { name = "proxy-suite-install"; + script = ./installer.sh; runtimeInputs = [ coreutils curl @@ -56,8 +57,4 @@ writeShellApplication { PSI_FLAKE_SRC = "${flakeSource}"; PSI_STATE_VERSION = stateVersion; }; - text = lib.concatStringsSep "\n" [ - (builtins.readFile ./net-lib.sh) - (builtins.readFile ./installer.sh) - ]; } diff --git a/deploy/net-rescue.nix b/deploy/net-rescue.nix index 3e4e1a5..92b5c89 100644 --- a/deploy/net-rescue.nix +++ b/deploy/net-rescue.nix @@ -14,8 +14,9 @@ systemd, }: -writeShellApplication { +import ./script.nix { inherit lib writeShellApplication; } { name = "proxy-suite-net"; + script = ./net-rescue.sh; runtimeInputs = [ coreutils curl @@ -27,8 +28,4 @@ writeShellApplication { iputils systemd ]; - text = lib.concatStringsSep "\n" [ - (builtins.readFile ./net-lib.sh) - (builtins.readFile ./net-rescue.sh) - ]; } diff --git a/deploy/script.nix b/deploy/script.nix new file mode 100644 index 0000000..9d9ca42 --- /dev/null +++ b/deploy/script.nix @@ -0,0 +1,16 @@ +# The console helpers are net-lib.sh plus one front end, wrapped with the tools they call. +{ lib, writeShellApplication }: + +{ + name, + script, + runtimeInputs, + runtimeEnv ? { }, +}: +writeShellApplication { + inherit name runtimeInputs runtimeEnv; + text = lib.concatStringsSep "\n" [ + (builtins.readFile ./net-lib.sh) + (builtins.readFile script) + ]; +} diff --git a/deploy/server-module.nix b/deploy/server-module.nix index 648487a..00f9092 100644 --- a/deploy/server-module.nix +++ b/deploy/server-module.nix @@ -321,7 +321,7 @@ in services.getty.helpLine = '' - proxy-suite server ''${certName}. Share links (as ''${cfg.adminUser}): + proxy-suite server ${certName}. Share links (as ${cfg.adminUser}): proxy-ctl inbounds link vless-reality --qr (or vless-tls, vless-ws) '' + lib.optionalString cfg.onion.enable " proxy-ctl inbounds link vless-reality --onion --qr (through Tor)\n" diff --git a/modules/proxy-suite/amnezia-wg-inbounds.nix b/modules/proxy-suite/amnezia-wg-inbounds.nix index c8ad8e6..2240039 100644 --- a/modules/proxy-suite/amnezia-wg-inbounds.nix +++ b/modules/proxy-suite/amnezia-wg-inbounds.nix @@ -23,13 +23,10 @@ let lanListeners = builtins.filter (listener: listener.mode == "lan") listeners; lanIPv6 = lib.any (listener: listener.subnet6 != null) lanListeners; - scriptsDir = builtins.path { - name = "proxy-suite-scripts"; - path = ../../scripts; - }; + scriptsDir = import ./lib/scripts-dir.nix { inherit lib; }; python3 = "${pkgs.python3}/bin/python3"; awg = "${awgCfg.toolsPackage}/bin/awg"; - awgQuick = "${awgCfg.toolsPackage}/bin/awg-quick"; + awgCommon = import ./awg-common.nix { inherit lib pkgs awgCfg; }; # Diverted packets are delivered locally; only "lan" listeners forward. sysctl = @@ -128,9 +125,7 @@ let set -Eeuo pipefail trap ${stop} ERR - ${lib.optionalString (awgCfg.kernelModulePackage != null) '' - ${pkgs.kmod}/bin/modprobe amneziawg 2>/dev/null || true - ''} + ${awgCommon.modprobe} ${stop} @@ -139,15 +134,7 @@ let > "$RUNTIME_DIRECTORY/interfaces" while read -r _interface implementation config; do - # The 3.1 kernel module drops RandomTrailers packets with ranged H1-H3; userspace does not. - if [[ "$implementation" == userspace ]]; then - WG_QUICK_FORCE_USERSPACE_IMPLEMENTATION=1 \ - WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \ - ${awgQuick} up "$config" - else - WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \ - ${awgQuick} up "$config" - fi + ${awgCommon.awgQuickUp "$implementation" "\"$config\""} done < "$RUNTIME_DIRECTORY/interfaces" ${lib.concatStrings ( diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix index 10eebda..d7ce2d3 100644 --- a/modules/proxy-suite/amnezia-wg.nix +++ b/modules/proxy-suite/amnezia-wg.nix @@ -81,12 +81,8 @@ let // source profile ) ); - configTool = "${ - builtins.path { - name = "proxy-suite-scripts"; - path = ../../scripts; - } - }/amneziawg_config.py"; + configTool = "${import ./lib/scripts-dir.nix { inherit lib; }}/amneziawg_config.py"; + awgCommon = import ./awg-common.nix { inherit lib pkgs awgCfg; }; runtimeDir = name: "/run/${serviceName name}"; runtimeConfig = name: profile: "${runtimeDir name}/${profile.interfaceName}.conf"; # Keep proxy backend sockets (proxyMark) out of AWG's default-route table. @@ -204,22 +200,11 @@ let } trap cleanup ERR - ${lib.optionalString (awgCfg.kernelModulePackage != null) '' - ${pkgs.kmod}/bin/modprobe amneziawg 2>/dev/null || true - ''} + ${awgCommon.modprobe} read -r implementation probe _ < <(${pkgs.python3}/bin/python3 ${configTool} \ --inspect ${lib.escapeShellArg configPath}) - # The 3.1 kernel module dropped RandomTrailers packets with ranged H1-H3 (seen on 20260812); - # userspace carries the fix. - if [[ "$implementation" == userspace ]]; then - WG_QUICK_FORCE_USERSPACE_IMPLEMENTATION=1 \ - WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \ - ${awgCfg.toolsPackage}/bin/awg-quick up ${lib.escapeShellArg configPath} - else - WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \ - ${awgCfg.toolsPackage}/bin/awg-quick up ${lib.escapeShellArg configPath} - fi + ${awgCommon.awgQuickUp "$implementation" (lib.escapeShellArg configPath)} ${mkHandshakeHelpers profile} # A handshake is retried every 5 seconds: each retry after the first gets a new port. diff --git a/modules/proxy-suite/assembly.nix b/modules/proxy-suite/assembly.nix new file mode 100644 index 0000000..a5b292d --- /dev/null +++ b/modules/proxy-suite/assembly.nix @@ -0,0 +1,62 @@ +# Routing rules → generated configs → nftables rule files → service context: the wiring the +# host-neutral module does at evaluation time, in one place so the docs generator and the +# checks assemble it exactly as the running system does. +{ + lib, + pkgs, + cfg, + packages, + zapret, +}: +let + rules = import ./rules.nix { + inherit + lib + pkgs + cfg + zapret + ; + }; + configs = import ./config.nix { + inherit + lib + pkgs + cfg + rules + ; + }; + nftr = import ./nftables.nix { inherit lib pkgs cfg; }; + context = import ./service/context.nix { + inherit + lib + pkgs + packages + cfg + ; + inherit (configs) + tproxyFile + tunFile + perAppTunFile + routeModeRulesFile + proxyInboundsFile + proxyInboundsSpecFile + ; + inherit (nftr) + perAppTunChainFile + perAppTproxyRulesFile + perAppZapretRulesFile + nftablesRulesFile + ip + nft + ; + }; +in +{ + inherit + rules + configs + nftr + context + ; + inherit (context) derived; +} diff --git a/modules/proxy-suite/awg-common.nix b/modules/proxy-suite/awg-common.nix new file mode 100644 index 0000000..0328c74 --- /dev/null +++ b/modules/proxy-suite/awg-common.nix @@ -0,0 +1,27 @@ +# Shared AmneziaWG plumbing: bringing an interface up the way both the client profiles +# (./amnezia-wg.nix) and the server listeners (./amnezia-wg-inbounds.nix) need it. +{ + lib, + pkgs, + awgCfg, +}: +{ + # The kernel module is optional; userspace works without it. + modprobe = lib.optionalString (awgCfg.kernelModulePackage != null) '' + ${pkgs.kmod}/bin/modprobe amneziawg 2>/dev/null || true + ''; + + # `implementation` is a shell word holding "userspace" or "kernel", `config` the .conf path. + # The 3.1 kernel module dropped RandomTrailers packets with ranged H1-H3 (seen on 20260812); + # userspace carries the fix, so a profile that needs it asks for userspace by name. + awgQuickUp = implementation: config: '' + if [[ "${implementation}" == userspace ]]; then + WG_QUICK_FORCE_USERSPACE_IMPLEMENTATION=1 \ + WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \ + ${awgCfg.toolsPackage}/bin/awg-quick up ${config} + else + WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \ + ${awgCfg.toolsPackage}/bin/awg-quick up ${config} + fi + ''; +} diff --git a/modules/proxy-suite/config-templates/proxy-inbounds.nix b/modules/proxy-suite/config-templates/proxy-inbounds.nix index a5e723f..1f5c434 100644 --- a/modules/proxy-suite/config-templates/proxy-inbounds.nix +++ b/modules/proxy-suite/config-templates/proxy-inbounds.nix @@ -14,17 +14,7 @@ let proxyInboundsResolveInSingBox ; - localProxyAddress = - if - builtins.elem proxyCfg.listener.address [ - "0.0.0.0" - "::" - "" - ] - then - "127.0.0.1" - else - proxyCfg.listener.address; + localProxyAddress = derived.localProxy.host; # The client stack's SOCKS listener; credentials are injected at start. localProxyOutbound = lib.optional proxyInboundsNeedLocalProxy { diff --git a/modules/proxy-suite/core.nix b/modules/proxy-suite/core.nix index 604dbc0..0ed44e6 100644 --- a/modules/proxy-suite/core.nix +++ b/modules/proxy-suite/core.nix @@ -18,8 +18,16 @@ let cfg = config.services.proxy-suite; packages = import ../../pkgs/default.nix { inherit pkgs; }; - nftr = import ./nftables.nix { inherit lib pkgs cfg; }; - derived = import ./derived.nix { inherit lib cfg; }; + assembly = import ./assembly.nix { + inherit + lib + pkgs + cfg + packages + zapret + ; + }; + inherit (assembly) nftr derived; in { imports = [ @@ -44,48 +52,10 @@ in } (lib.mkIf cfg.enable ( - let - rules = import ./rules.nix { - inherit - lib - pkgs - cfg - zapret - ; - }; - configs = import ./config.nix { - inherit - lib - pkgs - cfg - rules - ; - }; - in lib.mkMerge [ (import ./service { - inherit - lib - pkgs - packages - cfg - ; - inherit (configs) - tproxyFile - tunFile - perAppTunFile - routeModeRulesFile - proxyInboundsFile - proxyInboundsSpecFile - ; - inherit (nftr) - nftablesRulesFile - perAppTproxyRulesFile - perAppZapretRulesFile - perAppTunChainFile - ip - nft - ; + inherit lib pkgs cfg; + inherit (assembly) context; }) (lib.mkIf @@ -176,7 +146,7 @@ in cfg derived ; - inherit (configs) proxyInboundsSpecFile; + inherit (assembly.configs) proxyInboundsSpecFile; inherit (nftr) reservedIpBlock ip nft; } )) diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index dc8f149..c43133a 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -18,7 +18,6 @@ let singBoxEnabled = proxyEnabled && proxyCfg.backend != "xray"; xrayEnabled = proxyEnabled && proxyCfg.backend != "sing-box"; hybridEnabled = proxyEnabled && proxyCfg.backend == "hybrid"; - pureSingBoxEnabled = proxyEnabled && proxyCfg.backend == "sing-box"; pureXrayEnabled = proxyEnabled && proxyCfg.backend == "xray"; activeBackend = if proxyEnabled then proxyCfg.backend else null; perAppRoutingCfg = cfg.perAppRouting; @@ -36,6 +35,29 @@ let # Only sing-box dials SSH natively; XRay and standalone tunnels use the OpenSSH unit. sshProxyNativeOutbound = sshProxyOutboundEnabled && !pureXrayEnabled; sshProxyUnitEnabled = sshProxyCfg.enable && !sshProxyNativeOutbound; + # The local proxy as the other services dial it: a wildcard listener is reached on loopback. + # (The secret itself stays with whoever needs it on disk: derived.nix has no pkgs.) + localProxy = + let + auth = proxyCfg.listener.auth; + host = + if + builtins.elem proxyCfg.listener.address [ + "0.0.0.0" + "::" + "" + ] + then + "127.0.0.1" + else + proxyCfg.listener.address; + in + { + inherit auth host; + hostPart = if lib.hasInfix ":" host then "[${host}]" else host; + authEnabled = auth.username != null && (auth.password != null || auth.passwordFile != null); + }; + warpCfg = cfg.warp // { # Without a configFile, proxy-suite-warp registers with wgcf into its state dir. autoRegister = cfg.warp.enable && cfg.warp.configFile == null; @@ -402,13 +424,13 @@ in { inherit proxyCfg + localProxy singBoxCfg xrayCfg proxyEnabled singBoxEnabled xrayEnabled hybridEnabled - pureSingBoxEnabled pureXrayEnabled activeBackend perAppRoutingCfg @@ -426,12 +448,10 @@ in userControlEnabled userControlAllows sshProxyCfg - sshProxyOutboundTag sshProxyOutboundEnabled sshProxyNativeOutbound sshProxyUnitEnabled warpCfg - warpOutboundTag warpOutboundEnabled torCfg torOutboundTag @@ -464,7 +484,6 @@ in outboundTags effectiveOutboundTags subscriptionTags - hasStaticOutbounds hasSubscriptions hasAvailableOutbounds collapseNamedOutbounds diff --git a/modules/proxy-suite/hosts/common.nix b/modules/proxy-suite/hosts/common.nix index 8d1a0d8..db54c3f 100644 --- a/modules/proxy-suite/hosts/common.nix +++ b/modules/proxy-suite/hosts/common.nix @@ -13,6 +13,63 @@ rec { ); forward = forwardWith lib.id; + # The unit and package forwarding NixOS and system-manager do identically. + systemdForward = internal: { + systemd.services = forward internal.services; + systemd.timers = forward internal.timers; + systemd.paths = forward internal.paths; + systemd.tmpfiles.rules = forward internal.tmpfiles; + + environment.systemPackages = lib.mkMerge [ + (forwardWith lib.mkBefore internal.earlyPackages) + (forward internal.packages) + ]; + }; + + # One system user per daemon, each in a group of its own, plus the userControl group. + systemUsersAndGroups = cfg: { + users.users = lib.genAttrs cfg.internal.systemUsers (name: { + isSystemUser = true; + group = name; + description = "proxy-suite daemons"; + }); + users.groups = lib.genAttrs (cfg.internal.systemUsers ++ cfg.internal.groups) (_: { }); + }; + + firewallPortForward = internal: { + networking.firewall = { + allowedTCPPorts = forward internal.firewall.allowedTCPPorts; + allowedUDPPorts = forward internal.firewall.allowedUDPPorts; + }; + }; + + # The rootless adapters (home-manager, nix-on-droid) render the same unit set for a user + # manager: system and user services together, timers and paths, each filtered to enabled. + userUnitsFor = + { + lib, + pkgs, + host, + internal, + hostPath ? null, + }: + let + units = import ./user-units.nix ( + { + inherit lib pkgs; + inherit (host) runtimeDir; + stateDir = builtins.dirOf host.stateDir; + } + // lib.optionalAttrs (hostPath != null) { inherit hostPath; } + ); + enabled = lib.filterAttrs (_: unit: unit.enable); + in + { + services = lib.mapAttrs units.toService (enabled (internal.services // internal.userServices)); + timers = lib.mapAttrs units.toTimer (enabled internal.timers); + paths = lib.mapAttrs units.toPath (enabled internal.paths); + }; + # Scripts share one store name per block, and journald names a unit's output # after its ExecStart basename; tag each unit with its own name instead. unitsWithOwnSyslogIdentifier = lib.mkOption { diff --git a/modules/proxy-suite/hosts/home-manager.nix b/modules/proxy-suite/hosts/home-manager.nix index 9be2ea3..2bdc921 100644 --- a/modules/proxy-suite/hosts/home-manager.nix +++ b/modules/proxy-suite/hosts/home-manager.nix @@ -13,18 +13,14 @@ let host = cfg.host; internal = cfg.internal; - inherit - (import ./user-units.nix { - inherit lib pkgs; - inherit (host) runtimeDir; - stateDir = dirOf host.stateDir; - }) - toService - toTimer - toPath - ; - - enabled = lib.filterAttrs (_: unit: unit.enable); + userUnits = (import ./common.nix { inherit lib; }).userUnitsFor { + inherit + lib + pkgs + host + internal + ; + }; in { config = lib.mkMerge [ @@ -44,11 +40,9 @@ in (lib.mkIf cfg.enable ( lib.mkMerge [ { - systemd.user.services = lib.mapAttrs toService ( - enabled (internal.services // internal.userServices) - ); - systemd.user.timers = lib.mapAttrs toTimer (enabled internal.timers); - systemd.user.paths = lib.mapAttrs toPath (enabled internal.paths); + systemd.user.services = userUnits.services; + systemd.user.timers = userUnits.timers; + systemd.user.paths = userUnits.paths; home.packages = lib.mkMerge [ (lib.mkBefore internal.earlyPackages) diff --git a/modules/proxy-suite/hosts/nix-on-droid.nix b/modules/proxy-suite/hosts/nix-on-droid.nix index 7b9b865..22a7e40 100644 --- a/modules/proxy-suite/hosts/nix-on-droid.nix +++ b/modules/proxy-suite/hosts/nix-on-droid.nix @@ -15,30 +15,21 @@ let internal = cfg.internal; home = config.user.home; - inherit - (import ./user-units.nix { - inherit lib pkgs; - inherit (host) runtimeDir; - stateDir = dirOf host.stateDir; - hostPath = "${home}/.nix-profile/bin"; - }) - toService - toTimer - toPath - ; - - enabled = lib.filterAttrs (_: unit: unit.enable); + userUnits = (import ./common.nix { inherit lib; }).userUnitsFor { + inherit + lib + pkgs + host + internal + ; + hostPath = "${home}/.nix-profile/bin"; + }; supervisorDir = "${host.runtimeDir}/proxy-suite-supervisor"; # Outside the store, so proxy-suitectl stays the same from one generation to the next. manifestLink = "${host.stateDir}/supervisor/manifest.json"; manifest = pkgs.writeText "proxy-suite-units.json" ( - builtins.toJSON { - services = lib.mapAttrs toService (enabled (internal.services // internal.userServices)); - timers = lib.mapAttrs toTimer (enabled internal.timers); - paths = lib.mapAttrs toPath (enabled internal.paths); - inherit (internal) tmpfiles; - } + builtins.toJSON (userUnits // { inherit (internal) tmpfiles; }) ); suitectl = import ../../../pkgs/proxy-suite-supervisor.nix { inherit lib pkgs; } { diff --git a/modules/proxy-suite/hosts/nixos.nix b/modules/proxy-suite/hosts/nixos.nix index c536ea3..76c96ce 100644 --- a/modules/proxy-suite/hosts/nixos.nix +++ b/modules/proxy-suite/hosts/nixos.nix @@ -12,6 +12,8 @@ let inherit (import ./common.nix { inherit lib; }) forwardWith forward + systemdForward + systemUsersAndGroups unitsWithOwnSyslogIdentifier ; in @@ -32,39 +34,29 @@ in }; } - (lib.mkIf cfg.enable { - systemd.services = forward internal.services; - systemd.user.services = forward internal.userServices; - systemd.timers = forward internal.timers; - systemd.paths = forward internal.paths; - systemd.tmpfiles.rules = forward internal.tmpfiles; + (lib.mkIf cfg.enable ( + lib.mkMerge [ + (systemdForward internal) + (systemUsersAndGroups cfg) + { + systemd.user.services = forward internal.userServices; - environment.systemPackages = lib.mkMerge [ - (forwardWith lib.mkBefore internal.earlyPackages) - (forward internal.packages) - ]; + security.polkit.enable = lib.mkIf cfg.internal.polkit.enable true; + security.polkit.extraConfig = forwardWith lib.mkAfter internal.polkit.rules; - users.users = lib.genAttrs cfg.internal.systemUsers (name: { - isSystemUser = true; - group = name; - description = "proxy-suite daemons"; - }); - users.groups = lib.genAttrs (cfg.internal.systemUsers ++ cfg.internal.groups) (_: { }); + networking.nftables.enable = lib.mkIf cfg.internal.nftables (lib.mkDefault true); + networking.firewall = { + allowedTCPPorts = forward internal.firewall.allowedTCPPorts; + allowedUDPPorts = forward internal.firewall.allowedUDPPorts; + extraReversePathFilterRules = forward internal.firewall.extraReversePathFilterRules; + trustedInterfaces = forward internal.firewall.trustedInterfaces; + }; - security.polkit.enable = lib.mkIf cfg.internal.polkit.enable true; - security.polkit.extraConfig = forwardWith lib.mkAfter internal.polkit.rules; - - networking.nftables.enable = lib.mkIf cfg.internal.nftables (lib.mkDefault true); - networking.firewall = { - allowedTCPPorts = forward internal.firewall.allowedTCPPorts; - allowedUDPPorts = forward internal.firewall.allowedUDPPorts; - extraReversePathFilterRules = forward internal.firewall.extraReversePathFilterRules; - trustedInterfaces = forward internal.firewall.trustedInterfaces; - }; - - boot.extraModulePackages = forward internal.kernelModulePackages; - boot.kernel.sysctl = lib.mapAttrs (_: lib.mkDefault) cfg.internal.sysctl; - }) + boot.extraModulePackages = forward internal.kernelModulePackages; + boot.kernel.sysctl = lib.mapAttrs (_: lib.mkDefault) cfg.internal.sysctl; + } + ] + )) # Off by default since nixpkgs 26.11, and always there before, where the option does # not exist. diff --git a/modules/proxy-suite/hosts/system-manager.nix b/modules/proxy-suite/hosts/system-manager.nix index 4dd96a6..12d54a9 100644 --- a/modules/proxy-suite/hosts/system-manager.nix +++ b/modules/proxy-suite/hosts/system-manager.nix @@ -14,8 +14,10 @@ let cfg = config.services.proxy-suite; internal = options.services.proxy-suite.internal; inherit (import ./common.nix { inherit lib; }) - forwardWith forward + systemdForward + systemUsersAndGroups + firewallPortForward unitsWithOwnSyslogIdentifier ; @@ -72,47 +74,33 @@ in }; } - (lib.mkIf cfg.enable { - assertions = [ + (lib.mkIf cfg.enable ( + lib.mkMerge [ + (systemdForward internal) + (systemUsersAndGroups cfg) + # Only reported: system-manager leaves the host firewall alone. The routing modes load + # their own nftables tables, and the distribution's loose reverse-path filter already + # lets AmneziaWG replies in. + (firewallPortForward internal) { - assertion = cfg.internal.kernelModulePackages == [ ]; - message = "proxy-suite: system-manager cannot load kernel modules from Nix; leave amneziaWg.kernelModulePackage at null"; + assertions = [ + { + assertion = cfg.internal.kernelModulePackages == [ ]; + message = "proxy-suite: system-manager cannot load kernel modules from Nix; leave amneziaWg.kernelModulePackage at null"; + } + ]; + + environment.etc = lib.mkMerge [ + userServiceFiles + # Read by polkit 0.106 and later; the distribution runs the daemon. The rules + # go through the host's setuid pkexec: nothing here needs a wrapper. + (lib.mkIf cfg.internal.polkit.enable { + "polkit-1/rules.d/50-proxy-suite.rules".text = cfg.internal.polkit.rules; + }) + ]; + } - ]; - - systemd.services = forward internal.services; - systemd.timers = forward internal.timers; - systemd.paths = forward internal.paths; - systemd.tmpfiles.rules = forward internal.tmpfiles; - - environment.systemPackages = lib.mkMerge [ - (forwardWith lib.mkBefore internal.earlyPackages) - (forward internal.packages) - ]; - - environment.etc = lib.mkMerge [ - userServiceFiles - # Read by polkit 0.106 and later; the distribution runs the daemon. The rules - # go through the host's setuid pkexec: nothing here needs a wrapper. - (lib.mkIf cfg.internal.polkit.enable { - "polkit-1/rules.d/50-proxy-suite.rules".text = cfg.internal.polkit.rules; - }) - ]; - - users.users = lib.genAttrs cfg.internal.systemUsers (name: { - isSystemUser = true; - group = name; - description = "proxy-suite daemons"; - }); - users.groups = lib.genAttrs (cfg.internal.systemUsers ++ cfg.internal.groups) (_: { }); - - # Only reported: system-manager leaves the host firewall alone. The routing modes - # load their own nftables tables, and the distribution's loose reverse-path filter - # already lets AmneziaWG replies in. - networking.firewall = { - allowedTCPPorts = forward internal.firewall.allowedTCPPorts; - allowedUDPPorts = forward internal.firewall.allowedUDPPorts; - }; - }) + ] + )) ]; } diff --git a/modules/proxy-suite/lib/scripts-dir.nix b/modules/proxy-suite/lib/scripts-dir.nix new file mode 100644 index 0000000..28399c8 --- /dev/null +++ b/modules/proxy-suite/lib/scripts-dir.nix @@ -0,0 +1,14 @@ +# The runtime helper scripts (../../../scripts), as one filtered store path shared by every +# module that shells out to them. Unfiltered, the unit tests and any stale __pycache__ land +# in every host's closure and move its store hash. +{ lib }: +builtins.path { + name = "proxy-suite-scripts"; + path = ../../../scripts; + filter = + path: _type: + let + base = baseNameOf path; + in + !(lib.hasPrefix "test-" base) && base != "__pycache__"; +} diff --git a/modules/proxy-suite/options/default.nix b/modules/proxy-suite/options/default.nix index ab3171b..ccca645 100644 --- a/modules/proxy-suite/options/default.nix +++ b/modules/proxy-suite/options/default.nix @@ -19,7 +19,6 @@ ./tg-ws-proxy.nix ./geodata.nix ./gui.nix - ./tray.nix ./tui.nix ./user-control.nix ./host.nix diff --git a/modules/proxy-suite/options/inbounds.nix b/modules/proxy-suite/options/inbounds.nix index cc02b08..a47ce03 100644 --- a/modules/proxy-suite/options/inbounds.nix +++ b/modules/proxy-suite/options/inbounds.nix @@ -9,12 +9,7 @@ let types ; t = import ./types.nix { inherit lib; }; - bool = - default: description: - mkOption { - type = types.bool; - inherit default description; - }; + inherit (import ./lib.nix { inherit lib; }) bool; in { options.services.proxy-suite.inbounds = { diff --git a/modules/proxy-suite/options/lib.nix b/modules/proxy-suite/options/lib.nix new file mode 100644 index 0000000..eeb5bef --- /dev/null +++ b/modules/proxy-suite/options/lib.nix @@ -0,0 +1,47 @@ +# The option shapes this module declares over and over, in one place. +{ lib }: +let + inherit (lib) mkOption types; +in +{ + list = + description: example: + mkOption { + type = types.listOf types.str; + default = [ ]; + inherit description example; + }; + nullStr = + description: example: + mkOption { + type = types.nullOr types.str; + default = null; + inherit description example; + }; + bool = + default: description: + mkOption { + type = types.bool; + inherit default description; + }; + int = + default: description: + mkOption { + type = types.int; + inherit default description; + }; + positiveInt = + default: description: + mkOption { + type = types.ints.positive; + inherit default description; + }; + # An option path under services.proxy-suite, for the compatibility modules. + path = + path: + [ + "services" + "proxy-suite" + ] + ++ lib.splitString "." path; +} diff --git a/modules/proxy-suite/options/per-app-routing.nix b/modules/proxy-suite/options/per-app-routing.nix index 2ef0374..fbf5d50 100644 --- a/modules/proxy-suite/options/per-app-routing.nix +++ b/modules/proxy-suite/options/per-app-routing.nix @@ -3,12 +3,7 @@ let inherit (lib) mkEnableOption mkOption types; t = import ./types.nix { inherit lib; }; - int = - default: description: - mkOption { - type = types.int; - inherit default description; - }; + inherit (import ./lib.nix { inherit lib; }) int; localSubnets = description: mkOption { diff --git a/modules/proxy-suite/options/proxy-routing.nix b/modules/proxy-suite/options/proxy-routing.nix index c7652b1..392afa1 100644 --- a/modules/proxy-suite/options/proxy-routing.nix +++ b/modules/proxy-suite/options/proxy-routing.nix @@ -3,13 +3,7 @@ let inherit (lib) mkOption types; t = import ./types.nix { inherit lib; }; - list = - description: example: - mkOption { - type = types.listOf types.str; - default = [ ]; - inherit description example; - }; + inherit (import ./lib.nix { inherit lib; }) list; in { options.services.proxy-suite.proxy.routing = { diff --git a/modules/proxy-suite/options/removed.nix b/modules/proxy-suite/options/removed.nix index dc8a561..fb39508 100644 --- a/modules/proxy-suite/options/removed.nix +++ b/modules/proxy-suite/options/removed.nix @@ -1,13 +1,7 @@ { lib, ... }: let - p = - path: - [ - "services" - "proxy-suite" - ] - ++ lib.splitString "." path; + p = (import ./lib.nix { inherit lib; }).path; rm = path: replacement: lib.mkRemovedOptionModule (p path) replacement; # Top-level zapret options that moved under the engine namespace; the value is # the leaf name they carry there. @@ -24,6 +18,11 @@ let in { imports = [ + # The tray indicator became Proxy Suite GUI, which has the tray icon built in. + (lib.mkRenamedOptionModule (p "tray.enable") (p "gui.enable")) + (lib.mkRenamedOptionModule (p "tray.autostart") (p "gui.autostart")) + (lib.mkRenamedOptionModule (p "tray.pollInterval") (p "gui.refreshInterval")) + # These were aliases; they are removal notices now, so there is one # compatibility policy instead of two. (rm "proxyInbounds" "Use services.proxy-suite.inbounds.") diff --git a/modules/proxy-suite/options/ssh-proxy.nix b/modules/proxy-suite/options/ssh-proxy.nix index a71c9ae..8b8a2d7 100644 --- a/modules/proxy-suite/options/ssh-proxy.nix +++ b/modules/proxy-suite/options/ssh-proxy.nix @@ -3,13 +3,7 @@ let inherit (lib) mkEnableOption mkOption types; token = types.nullOr (types.strMatching "[^[:space:]]+"); - path = - description: example: - mkOption { - type = types.nullOr types.str; - default = null; - inherit description example; - }; + path = (import ./lib.nix { inherit lib; }).nullStr; in { options.services.proxy-suite.sshProxy = { diff --git a/modules/proxy-suite/options/tg-ws-proxy.nix b/modules/proxy-suite/options/tg-ws-proxy.nix index 05a946c..369bdfe 100644 --- a/modules/proxy-suite/options/tg-ws-proxy.nix +++ b/modules/proxy-suite/options/tg-ws-proxy.nix @@ -2,13 +2,7 @@ let inherit (lib) mkEnableOption mkOption types; - domains = - description: example: - mkOption { - type = types.listOf types.str; - default = [ ]; - inherit description example; - }; + domains = (import ./lib.nix { inherit lib; }).list; in { options.services.proxy-suite.tgWsProxy = { diff --git a/modules/proxy-suite/options/tray.nix b/modules/proxy-suite/options/tray.nix deleted file mode 100644 index 836cebe..0000000 --- a/modules/proxy-suite/options/tray.nix +++ /dev/null @@ -1,19 +0,0 @@ -{ lib, ... }: - -let - p = - path: - [ - "services" - "proxy-suite" - ] - ++ lib.splitString "." path; -in -{ - # The tray indicator became Proxy Suite GUI, which has the tray icon built in. - imports = [ - (lib.mkRenamedOptionModule (p "tray.enable") (p "gui.enable")) - (lib.mkRenamedOptionModule (p "tray.autostart") (p "gui.autostart")) - (lib.mkRenamedOptionModule (p "tray.pollInterval") (p "gui.refreshInterval")) - ]; -} diff --git a/modules/proxy-suite/options/types.nix b/modules/proxy-suite/options/types.nix index 5fbaadf..4936582 100644 --- a/modules/proxy-suite/options/types.nix +++ b/modules/proxy-suite/options/types.nix @@ -2,14 +2,7 @@ let inherit (lib) mkOption types; - - list = - description: example: - mkOption { - type = types.listOf types.str; - default = [ ]; - inherit description example; - }; + inherit (import ./lib.nix { inherit lib; }) list; routingFields = { domains = list "Domain suffixes to match." [ "youtube.com" ]; diff --git a/modules/proxy-suite/options/types/amnezia-wg.nix b/modules/proxy-suite/options/types/amnezia-wg.nix index 22032a5..9d84b24 100644 --- a/modules/proxy-suite/options/types/amnezia-wg.nix +++ b/modules/proxy-suite/options/types/amnezia-wg.nix @@ -54,139 +54,50 @@ let }; }; - obfuscationType = types.submodule { - options = { - jc = mkOption { - type = optionalUnsigned; - default = null; - description = "Junk packet count (Jc)."; - }; - jmin = mkOption { - type = optionalUnsigned; - default = null; - description = "Minimum junk packet size (Jmin)."; - }; - jmax = mkOption { - type = optionalUnsigned; - default = null; - description = "Maximum junk packet size (Jmax)."; - }; - s1 = mkOption { - type = optionalUnsigned; - default = null; - description = "Handshake-init padding (S1)."; - }; - s2 = mkOption { - type = optionalUnsigned; - default = null; - description = "Handshake-response padding (S2)."; - }; - s3 = mkOption { - type = optionalUnsigned; - default = null; - description = "Cookie-reply padding (S3)."; - }; - s4 = mkOption { - type = optionalUnsigned; - default = null; - description = "Transport-message padding (S4)."; - }; - h1 = mkOption { - type = optionalRange; - default = null; - description = "Handshake-init header or range (H1)."; - }; - h2 = mkOption { - type = optionalRange; - default = null; - description = "Handshake-response header or range (H2)."; - }; - h3 = mkOption { - type = optionalRange; - default = null; - description = "Cookie-reply header or range (H3)."; - }; - h4 = mkOption { - type = optionalRange; - default = null; - description = "Transport-message header or range (H4)."; - }; - i1 = mkOption { - type = optionalString; - default = null; - description = "First custom signature packet (I1)."; - }; - i2 = mkOption { - type = optionalString; - default = null; - description = "Second custom signature packet (I2)."; - }; - i3 = mkOption { - type = optionalString; - default = null; - description = "Third custom signature packet (I3)."; - }; - i4 = mkOption { - type = optionalString; - default = null; - description = "Fourth custom signature packet (I4)."; - }; - i5 = mkOption { - type = optionalString; - default = null; - description = "Fifth custom signature packet (I5)."; - }; - headerProtectionKey = mkOption { - type = optionalString; - default = null; - description = "Inline AWG 3 header-protection key. Prefer headerProtectionKeyFile."; - }; - headerProtectionKeyFile = mkOption { - type = optionalString; - default = null; - description = "Runtime path containing the AWG 3 header-protection key."; - }; - contentPaddingAddition = mkOption { - type = optionalRange; - default = null; - description = "AWG 3 content-padding addition or range."; - }; - rekeyAfterTime = mkOption { - type = optionalRange; - default = null; - description = "AWG 3 rekey interval or range."; - }; - rekeyTimeout = mkOption { - type = optionalRange; - default = null; - description = "AWG 3 rekey timeout or range."; - }; - rejectAfterTime = mkOption { - type = optionalRange; - default = null; - description = "AWG 3 reject-after interval or range."; - }; - keepaliveTimeout = mkOption { - type = optionalRange; - default = null; - description = "AWG 3 keepalive timeout or range."; - }; - maxHandshakeAttempts = mkOption { - type = optionalRange; - default = null; - description = "AWG 3 maximum handshake attempts or range."; - }; - randomTrailers = mkOption { - type = types.nullOr types.bool; - default = null; - description = "AWG 3 random transport trailers (RandomTrailers)."; - }; - disableCookies = mkOption { - type = types.nullOr types.bool; - default = null; - description = "AWG 3 cookie suppression (DisableCookies)."; - }; + # Every AWG obfuscation field is an optional scalar with a one-line description, so they + # are declared as tables per value type rather than 27 near-identical mkOption blocks. + optional = + type: description: + mkOption { + inherit type description; + default = null; }; + obfuscationType = types.submodule { + options = + lib.mapAttrs (_: optional optionalUnsigned) { + jc = "Junk packet count (Jc)."; + jmin = "Minimum junk packet size (Jmin)."; + jmax = "Maximum junk packet size (Jmax)."; + s1 = "Handshake-init padding (S1)."; + s2 = "Handshake-response padding (S2)."; + s3 = "Cookie-reply padding (S3)."; + s4 = "Transport-message padding (S4)."; + } + // lib.mapAttrs (_: optional optionalRange) { + h1 = "Handshake-init header or range (H1)."; + h2 = "Handshake-response header or range (H2)."; + h3 = "Cookie-reply header or range (H3)."; + h4 = "Transport-message header or range (H4)."; + contentPaddingAddition = "AWG 3 content-padding addition or range."; + rekeyAfterTime = "AWG 3 rekey interval or range."; + rekeyTimeout = "AWG 3 rekey timeout or range."; + rejectAfterTime = "AWG 3 reject-after interval or range."; + keepaliveTimeout = "AWG 3 keepalive timeout or range."; + maxHandshakeAttempts = "AWG 3 maximum handshake attempts or range."; + } + // lib.mapAttrs (_: optional optionalString) { + i1 = "First custom signature packet (I1)."; + i2 = "Second custom signature packet (I2)."; + i3 = "Third custom signature packet (I3)."; + i4 = "Fourth custom signature packet (I4)."; + i5 = "Fifth custom signature packet (I5)."; + headerProtectionKey = "Inline AWG 3 header-protection key. Prefer headerProtectionKeyFile."; + headerProtectionKeyFile = "Runtime path containing the AWG 3 header-protection key."; + } + // lib.mapAttrs (_: optional (types.nullOr types.bool)) { + randomTrailers = "AWG 3 random transport trailers (RandomTrailers)."; + disableCookies = "AWG 3 cookie suppression (DisableCookies)."; + }; }; settingsType = types.submodule { diff --git a/modules/proxy-suite/options/types/inbounds.nix b/modules/proxy-suite/options/types/inbounds.nix index 5b22fda..f4c778c 100644 --- a/modules/proxy-suite/options/types/inbounds.nix +++ b/modules/proxy-suite/options/types/inbounds.nix @@ -3,13 +3,7 @@ let inherit (lib) mkOption types; inherit (import ./amnezia-wg.nix { inherit lib; }) obfuscationType; - nullStr = - description: example: - mkOption { - type = types.nullOr types.str; - default = null; - inherit description example; - }; + inherit (import ../lib.nix { inherit lib; }) nullStr; userType = types.submodule { options = { diff --git a/modules/proxy-suite/options/types/outbounds.nix b/modules/proxy-suite/options/types/outbounds.nix index c0759dc..7759d83 100644 --- a/modules/proxy-suite/options/types/outbounds.nix +++ b/modules/proxy-suite/options/types/outbounds.nix @@ -2,13 +2,7 @@ let inherit (lib) mkOption types; - nullStr = - description: example: - mkOption { - type = types.nullOr types.str; - default = null; - inherit description example; - }; + inherit (import ../lib.nix { inherit lib; }) nullStr; nullAttrs = description: example: mkOption { diff --git a/modules/proxy-suite/options/zapret.nix b/modules/proxy-suite/options/zapret.nix index 82c8f2d..1061927 100644 --- a/modules/proxy-suite/options/zapret.nix +++ b/modules/proxy-suite/options/zapret.nix @@ -3,19 +3,7 @@ let inherit (lib) mkEnableOption mkOption types; t = import ./types.nix { inherit lib; }; - list = - description: example: - mkOption { - type = types.listOf types.str; - default = [ ]; - inherit description example; - }; - bool = - default: description: - mkOption { - type = types.bool; - inherit default description; - }; + inherit (import ./lib.nix { inherit lib; }) list bool; in { options.services.proxy-suite.zapret = { diff --git a/modules/proxy-suite/options/zapret2.nix b/modules/proxy-suite/options/zapret2.nix index 8f66f3f..3666bc3 100644 --- a/modules/proxy-suite/options/zapret2.nix +++ b/modules/proxy-suite/options/zapret2.nix @@ -2,12 +2,7 @@ let inherit (lib) mkEnableOption mkOption types; - int = - default: description: - mkOption { - type = types.ints.positive; - inherit default description; - }; + int = (import ./lib.nix { inherit lib; }).positiveInt; fromSource = what: "null uses the ${what} of strategySource."; in { diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index 6911767..e015529 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -38,9 +38,10 @@ let requireEnabled = featureEnabled: dependencyEnabled: message: mkAssertion (!featureEnabled || dependencyEnabled) message; - requireAvailable = - featureUsed: dependencyEnabled: message: - mkAssertion (!featureUsed || dependencyEnabled) message; + # The shape of nearly every dependency assertion: " requires = true". + requires = + used: dependency: usedLabel: dependencyLabel: + mkAssertion (!used || dependency) "proxy-suite: ${usedLabel} requires ${dependencyLabel} = true"; uniqueValues = condition: values: message: mkAssertion (!condition || builtins.length values == builtins.length (lib.unique values)) message; @@ -55,6 +56,13 @@ let forbiddenValues = condition: value: disallowed: message: mkAssertion (!(condition && builtins.elem value disallowed)) message; + # Two values that must not coincide; the message names the config that conflicts them. + distinct = + condition: left: right: message: + notEqualWhen condition left right "proxy-suite: ${message}"; + positive = + condition: value: label: + mkAssertion (!condition || value > 0) "proxy-suite: ${label} must be greater than zero"; # Every loopback listener proxy-suite opens with a fixed port of its own, which # the autoProxy prober's range must stay clear of. @@ -238,54 +246,49 @@ let ) ]; + # Each case reads " requires = true", with option paths as labels. perAppRoutingAssertions = [ - (requireAvailable (perAppRoutingCfg.profiles != [ ]) perAppRoutingCfg.enable - "proxy-suite: perAppRouting.profiles requires perAppRouting.enable = true" + (requires ( + perAppRoutingCfg.profiles != [ ] + ) perAppRoutingCfg.enable "perAppRouting.profiles" "perAppRouting.enable") + (requires perAppRoutingCfg.proxychains.enable perAppRoutingCfg.enable + "perAppRouting.proxychains.enable" + "perAppRouting.enable" ) - (requireEnabled perAppRoutingCfg.proxychains.enable perAppRoutingCfg.enable - "proxy-suite: perAppRouting.proxychains.enable requires perAppRouting.enable = true" - ) - (requireEnabled perAppRoutingCfg.proxychains.enable proxyEnabled - "proxy-suite: perAppRouting.proxychains.enable requires proxy.enable = true" + (requires perAppRoutingCfg.proxychains.enable proxyEnabled "perAppRouting.proxychains.enable" + "proxy.enable" ) (uniqueValues true effectivePerAppRoutingProfileNames "proxy-suite: perAppRouting profile names must be unique" ) - (requireAvailable hasProxychainsProfiles perAppRoutingCfg.proxychains.enable - "proxy-suite: route=proxychains in perAppRouting.profiles requires perAppRouting.proxychains.enable = true" + (requires hasProxychainsProfiles perAppRoutingCfg.proxychains.enable + "route=proxychains in perAppRouting.profiles" + "perAppRouting.proxychains.enable" ) - (requireAvailable hasProxychainsProfiles proxyEnabled - "proxy-suite: route=proxychains in perAppRouting.profiles requires proxy.enable = true" + (requires hasProxychainsProfiles proxyEnabled "route=proxychains in perAppRouting.profiles" + "proxy.enable" ) - (requireEnabled perAppRoutingTun.enable perAppRoutingCfg.enable - "proxy-suite: perAppRouting.tun.enable requires perAppRouting.enable = true" + (requires perAppRoutingTun.enable perAppRoutingCfg.enable "perAppRouting.tun.enable" + "perAppRouting.enable" ) - (requireEnabled perAppRoutingTun.enable proxyEnabled - "proxy-suite: perAppRouting.tun.enable requires proxy.enable = true" + (requires perAppRoutingTun.enable proxyEnabled "perAppRouting.tun.enable" "proxy.enable") + (requires hasTunProfiles perAppRoutingTun.enable "route=tun in perAppRouting.profiles" + "perAppRouting.tun.enable" ) - (requireAvailable hasTunProfiles perAppRoutingTun.enable - "proxy-suite: route=tun in perAppRouting.profiles requires perAppRouting.tun.enable = true" + (requires hasTunProfiles proxyEnabled "route=tun in perAppRouting.profiles" "proxy.enable") + (requires perAppRoutingTproxy.enable perAppRoutingCfg.enable "perAppRouting.tproxy.enable" + "perAppRouting.enable" ) - (requireAvailable hasTunProfiles proxyEnabled - "proxy-suite: route=tun in perAppRouting.profiles requires proxy.enable = true" + (requires perAppRoutingTproxy.enable proxyEnabled "perAppRouting.tproxy.enable" "proxy.enable") + (requires hasTproxyProfiles perAppRoutingTproxy.enable "route=tproxy in perAppRouting.profiles" + "perAppRouting.tproxy.enable" ) - (requireEnabled perAppRoutingTproxy.enable perAppRoutingCfg.enable - "proxy-suite: perAppRouting.tproxy.enable requires perAppRouting.enable = true" + (requires hasTproxyProfiles proxyEnabled "route=tproxy in perAppRouting.profiles" "proxy.enable") + (requires perAppZapretCfg.enable perAppRoutingCfg.enable "perAppRouting.zapret.enable" + "perAppRouting.enable" ) - (requireEnabled perAppRoutingTproxy.enable proxyEnabled - "proxy-suite: perAppRouting.tproxy.enable requires proxy.enable = true" - ) - (requireAvailable hasTproxyProfiles perAppRoutingTproxy.enable - "proxy-suite: route=tproxy in perAppRouting.profiles requires perAppRouting.tproxy.enable = true" - ) - (requireAvailable hasTproxyProfiles proxyEnabled - "proxy-suite: route=tproxy in perAppRouting.profiles requires proxy.enable = true" - ) - (requireEnabled perAppZapretCfg.enable perAppRoutingCfg.enable - "proxy-suite: perAppRouting.zapret.enable requires perAppRouting.enable = true" - ) - (requireAvailable hasZapretProfiles perAppZapretCfg.enable - "proxy-suite: route=zapret in perAppRouting.profiles requires perAppRouting.zapret.enable = true" + (requires hasZapretProfiles perAppZapretCfg.enable "route=zapret in perAppRouting.profiles" + "perAppRouting.zapret.enable" ) ]; @@ -528,7 +531,7 @@ let (mkAssertion ( !proxyInboundsEnabled || !l.reality.enable || l.reality.serverNames != [ ] ) "${prefix}: reality.serverNames must not be empty") - (requireAvailable (proxyInboundsEnabled && l.reality.enable && proxyInboundsCfg.shareLinks) + (requireEnabled (proxyInboundsEnabled && l.reality.enable && proxyInboundsCfg.shareLinks) (l.reality.publicKey != null) "${prefix}: reality.publicKey is required to generate share links. Run `xray x25519` to print it alongside the private key, or set inbounds.shareLinks = false." ) @@ -692,254 +695,132 @@ let globalTunAutoRouteTable = constants.tunAutoRouteTableIndex; globalZapretQnum = constants.zapretGlobalQnum.${zapretEngine}; - collisionAssertions = map (item: notEqualWhen item.condition item.left item.right item.message) [ - { - condition = globalTun.enable && perAppRoutingTun.enable; - left = globalTun.interface; - right = perAppRoutingTun.interface; - message = "proxy-suite: proxy.tun.interface and perAppRouting.tun.interface must differ"; - } - { - condition = globalTun.enable && perAppRoutingTun.enable; - left = globalTun.address; - right = perAppRoutingTun.address; - message = "proxy-suite: proxy.tun.address and perAppRouting.tun.address must differ"; - } - { - condition = globalTun.enable && perAppRoutingTun.enable; - left = perAppRoutingTun.routeTable; - right = globalTunAutoRouteTable; - message = "proxy-suite: perAppRouting.tun.routeTable must differ from the global TUN auto-route table ${toString globalTunAutoRouteTable}"; - } - { - condition = perAppRoutingTun.enable && globalTproxy.enable; - left = perAppRoutingTun.fwmark; - right = globalTproxy.fwmark; - message = "proxy-suite: perAppRouting.tun.fwmark must differ from proxy.tproxy.fwmark when global TProxy is enabled"; - } - { - condition = perAppRoutingTun.enable && globalTproxy.enable; - left = perAppRoutingTun.fwmark; - right = globalTproxy.proxyMark; - message = "proxy-suite: perAppRouting.tun.fwmark must differ from proxy.tproxy.proxyMark when global TProxy is enabled"; - } - { - condition = perAppRoutingTun.enable && globalTproxy.enable; - left = perAppRoutingTun.routeTable; - right = globalTproxy.routeTable; - message = "proxy-suite: perAppRouting.tun.routeTable must differ from proxy.tproxy.routeTable when global TProxy is enabled"; - } - { - condition = perAppZapretCfg.enable && zapretCfg.enable; - left = perAppZapretCfg.qnum; - right = globalZapretQnum; - message = "proxy-suite: perAppRouting.zapret.qnum must differ from the global zapret instance's NFQUEUE ${toString globalZapretQnum}"; - } - { - condition = perAppRoutingTproxy.enable; - left = perAppRoutingTproxy.fwmark; - right = globalTproxy.fwmark; - message = "proxy-suite: perAppRouting.tproxy.fwmark must differ from proxy.tproxy.fwmark"; - } - { - condition = perAppRoutingTproxy.enable; - left = perAppRoutingTproxy.fwmark; - right = globalTproxy.proxyMark; - message = "proxy-suite: perAppRouting.tproxy.fwmark must differ from proxy.tproxy.proxyMark"; - } - { - condition = perAppRoutingTproxy.enable; - left = perAppRoutingTproxy.routeTable; - right = globalTproxy.routeTable; - message = "proxy-suite: perAppRouting.tproxy.routeTable must differ from proxy.tproxy.routeTable"; - } - { - condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable; - left = perAppRoutingTun.fwmark; - right = perAppRoutingTproxy.fwmark; - message = "proxy-suite: perAppRouting.tun.fwmark and perAppRouting.tproxy.fwmark must differ"; - } - { - condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable; - left = perAppRoutingTun.routeTable; - right = perAppRoutingTproxy.routeTable; - message = "proxy-suite: perAppRouting.tun.routeTable and perAppRouting.tproxy.routeTable must differ"; - } - { - condition = perAppZapretCfg.enable; - left = perAppZapretCfg.filterMark; - right = globalTproxy.fwmark; - message = "proxy-suite: perAppRouting.zapret.filterMark must differ from proxy.tproxy.fwmark"; - } - { - condition = perAppZapretCfg.enable; - left = perAppZapretCfg.filterMark; - right = globalTproxy.proxyMark; - message = "proxy-suite: perAppRouting.zapret.filterMark must differ from proxy.tproxy.proxyMark"; - } - { - condition = perAppRoutingTun.enable && perAppZapretCfg.enable; - left = perAppRoutingTun.fwmark; - right = perAppZapretCfg.filterMark; - message = "proxy-suite: perAppRouting.tun.fwmark and perAppRouting.zapret.filterMark must differ"; - } - { - condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable; - left = perAppRoutingTproxy.fwmark; - right = perAppZapretCfg.filterMark; - message = "proxy-suite: perAppRouting.tproxy.fwmark and perAppRouting.zapret.filterMark must differ"; - } - { - condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable; - left = tgWsProxyCfg.fwmark; - right = globalTproxy.fwmark; - message = "proxy-suite: tgWsProxy.fwmark must differ from proxy.tproxy.fwmark"; - } - { - condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable; - left = tgWsProxyCfg.fwmark; - right = globalTproxy.proxyMark; - message = "proxy-suite: tgWsProxy.fwmark must differ from proxy.tproxy.proxyMark"; - } - { - condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTun.enable; - left = tgWsProxyCfg.fwmark; - right = perAppRoutingTun.fwmark; - message = "proxy-suite: tgWsProxy.fwmark must differ from perAppRouting.tun.fwmark"; - } - { - condition = - tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTproxy.enable; - left = tgWsProxyCfg.fwmark; - right = perAppRoutingTproxy.fwmark; - message = "proxy-suite: tgWsProxy.fwmark must differ from perAppRouting.tproxy.fwmark"; - } - { - condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable; - left = tgWsProxyCfg.fwmark; - right = perAppZapretCfg.filterMark; - message = "proxy-suite: tgWsProxy.fwmark must differ from perAppRouting.zapret.filterMark"; - } - ]; + collisionAssertions = + let + bothTun = globalTun.enable && perAppRoutingTun.enable; + perAppTunWithTproxy = perAppRoutingTun.enable && globalTproxy.enable; + bothPerApp = perAppRoutingTun.enable && perAppRoutingTproxy.enable; + tgWsBypass = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy; + in + [ + (distinct bothTun globalTun.interface perAppRoutingTun.interface + "proxy.tun.interface and perAppRouting.tun.interface must differ" + ) + (distinct bothTun globalTun.address perAppRoutingTun.address + "proxy.tun.address and perAppRouting.tun.address must differ" + ) + (distinct bothTun perAppRoutingTun.routeTable globalTunAutoRouteTable + "perAppRouting.tun.routeTable must differ from the global TUN auto-route table ${toString globalTunAutoRouteTable}" + ) + (distinct perAppTunWithTproxy perAppRoutingTun.fwmark globalTproxy.fwmark + "perAppRouting.tun.fwmark must differ from proxy.tproxy.fwmark when global TProxy is enabled" + ) + (distinct perAppTunWithTproxy perAppRoutingTun.fwmark globalTproxy.proxyMark + "perAppRouting.tun.fwmark must differ from proxy.tproxy.proxyMark when global TProxy is enabled" + ) + (distinct perAppTunWithTproxy perAppRoutingTun.routeTable globalTproxy.routeTable + "perAppRouting.tun.routeTable must differ from proxy.tproxy.routeTable when global TProxy is enabled" + ) + (distinct (perAppZapretCfg.enable && zapretCfg.enable) perAppZapretCfg.qnum globalZapretQnum + "perAppRouting.zapret.qnum must differ from the global zapret instance's NFQUEUE ${toString globalZapretQnum}" + ) + (distinct perAppRoutingTproxy.enable perAppRoutingTproxy.fwmark globalTproxy.fwmark + "perAppRouting.tproxy.fwmark must differ from proxy.tproxy.fwmark" + ) + (distinct perAppRoutingTproxy.enable perAppRoutingTproxy.fwmark globalTproxy.proxyMark + "perAppRouting.tproxy.fwmark must differ from proxy.tproxy.proxyMark" + ) + (distinct perAppRoutingTproxy.enable perAppRoutingTproxy.routeTable globalTproxy.routeTable + "perAppRouting.tproxy.routeTable must differ from proxy.tproxy.routeTable" + ) + (distinct bothPerApp perAppRoutingTun.fwmark perAppRoutingTproxy.fwmark + "perAppRouting.tun.fwmark and perAppRouting.tproxy.fwmark must differ" + ) + (distinct bothPerApp perAppRoutingTun.routeTable perAppRoutingTproxy.routeTable + "perAppRouting.tun.routeTable and perAppRouting.tproxy.routeTable must differ" + ) + (distinct perAppZapretCfg.enable perAppZapretCfg.filterMark globalTproxy.fwmark + "perAppRouting.zapret.filterMark must differ from proxy.tproxy.fwmark" + ) + (distinct perAppZapretCfg.enable perAppZapretCfg.filterMark globalTproxy.proxyMark + "perAppRouting.zapret.filterMark must differ from proxy.tproxy.proxyMark" + ) + (distinct (perAppRoutingTun.enable && perAppZapretCfg.enable) perAppRoutingTun.fwmark + perAppZapretCfg.filterMark + "perAppRouting.tun.fwmark and perAppRouting.zapret.filterMark must differ" + ) + (distinct (perAppRoutingTproxy.enable && perAppZapretCfg.enable) perAppRoutingTproxy.fwmark + perAppZapretCfg.filterMark + "perAppRouting.tproxy.fwmark and perAppRouting.zapret.filterMark must differ" + ) + (distinct ( + tgWsBypass && globalTproxy.enable + ) tgWsProxyCfg.fwmark globalTproxy.fwmark "tgWsProxy.fwmark must differ from proxy.tproxy.fwmark") + (distinct (tgWsBypass && globalTproxy.enable) tgWsProxyCfg.fwmark globalTproxy.proxyMark + "tgWsProxy.fwmark must differ from proxy.tproxy.proxyMark" + ) + (distinct (tgWsBypass && perAppRoutingTun.enable) tgWsProxyCfg.fwmark perAppRoutingTun.fwmark + "tgWsProxy.fwmark must differ from perAppRouting.tun.fwmark" + ) + (distinct (tgWsBypass && perAppRoutingTproxy.enable) tgWsProxyCfg.fwmark perAppRoutingTproxy.fwmark + "tgWsProxy.fwmark must differ from perAppRouting.tproxy.fwmark" + ) + (distinct (tgWsBypass && perAppZapretCfg.enable) tgWsProxyCfg.fwmark perAppZapretCfg.filterMark + "tgWsProxy.fwmark must differ from perAppRouting.zapret.filterMark" + ) + ]; perAppZapretDesyncMarks = [ 67108864 134217728 ]; - positiveNumberAssertions = - map (item: mkAssertion (!item.condition || item.value > 0) item.message) - [ - { - condition = globalTun.enable; - value = globalTun.mtu; - message = "proxy-suite: proxy.tun.mtu must be greater than zero"; - } - { - condition = perAppRoutingTun.enable; - value = perAppRoutingTun.mtu; - message = "proxy-suite: perAppRouting.tun.mtu must be greater than zero"; - } - { - condition = globalTproxy.enable; - value = globalTproxy.fwmark; - message = "proxy-suite: proxy.tproxy.fwmark must be greater than zero"; - } - { - condition = globalTproxy.enable; - value = globalTproxy.proxyMark; - message = "proxy-suite: proxy.tproxy.proxyMark must be greater than zero"; - } - { - condition = globalTproxy.enable; - value = globalTproxy.routeTable; - message = "proxy-suite: proxy.tproxy.routeTable must be greater than zero"; - } - { - condition = perAppRoutingTun.enable; - value = perAppRoutingTun.fwmark; - message = "proxy-suite: perAppRouting.tun.fwmark must be greater than zero"; - } - { - condition = perAppRoutingTun.enable; - value = perAppRoutingTun.routeTable; - message = "proxy-suite: perAppRouting.tun.routeTable must be greater than zero"; - } - { - condition = perAppRoutingTproxy.enable; - value = perAppRoutingTproxy.fwmark; - message = "proxy-suite: perAppRouting.tproxy.fwmark must be greater than zero"; - } - { - condition = perAppRoutingTproxy.enable; - value = perAppRoutingTproxy.routeTable; - message = "proxy-suite: perAppRouting.tproxy.routeTable must be greater than zero"; - } - { - condition = perAppZapretCfg.enable; - value = perAppZapretCfg.filterMark; - message = "proxy-suite: perAppRouting.zapret.filterMark must be greater than zero"; - } - { - condition = perAppZapretCfg.enable; - value = perAppZapretCfg.qnum; - message = "proxy-suite: perAppRouting.zapret.qnum must be greater than zero"; - } - { - condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy; - value = tgWsProxyCfg.fwmark; - message = "proxy-suite: tgWsProxy.fwmark must be greater than zero"; - } - ]; + positiveNumberAssertions = [ + (positive globalTun.enable globalTun.mtu "proxy.tun.mtu") + (positive perAppRoutingTun.enable perAppRoutingTun.mtu "perAppRouting.tun.mtu") + (positive globalTproxy.enable globalTproxy.fwmark "proxy.tproxy.fwmark") + (positive globalTproxy.enable globalTproxy.proxyMark "proxy.tproxy.proxyMark") + (positive globalTproxy.enable globalTproxy.routeTable "proxy.tproxy.routeTable") + (positive perAppRoutingTun.enable perAppRoutingTun.fwmark "perAppRouting.tun.fwmark") + (positive perAppRoutingTun.enable perAppRoutingTun.routeTable "perAppRouting.tun.routeTable") + (positive perAppRoutingTproxy.enable perAppRoutingTproxy.fwmark "perAppRouting.tproxy.fwmark") + (positive perAppRoutingTproxy.enable perAppRoutingTproxy.routeTable + "perAppRouting.tproxy.routeTable" + ) + (positive perAppZapretCfg.enable perAppZapretCfg.filterMark "perAppRouting.zapret.filterMark") + (positive perAppZapretCfg.enable perAppZapretCfg.qnum "perAppRouting.zapret.qnum") + (positive ( + tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy + ) tgWsProxyCfg.fwmark "tgWsProxy.fwmark") + ]; forbiddenValueAssertions = - map (item: forbiddenValues item.condition item.value item.disallowed item.message) - [ - { - condition = perAppZapretCfg.enable; - value = perAppZapretCfg.filterMark; - disallowed = [ - 536870912 - 1073741824 - ]; - message = "proxy-suite: perAppRouting.zapret.filterMark must not use zapret internal desync mark bits"; - } - { - condition = perAppZapretCfg.enable; - value = globalTproxy.fwmark; - disallowed = perAppZapretDesyncMarks; - message = "proxy-suite: proxy.tproxy.fwmark must not use per-app-zapret internal desync mark bits"; - } - { - condition = perAppZapretCfg.enable; - value = globalTproxy.proxyMark; - disallowed = perAppZapretDesyncMarks; - message = "proxy-suite: proxy.tproxy.proxyMark must not use per-app-zapret internal desync mark bits"; - } - { - condition = perAppRoutingTun.enable && perAppZapretCfg.enable; - value = perAppRoutingTun.fwmark; - disallowed = perAppZapretDesyncMarks; - message = "proxy-suite: perAppRouting.tun.fwmark must not use per-app-zapret internal desync mark bits"; - } - { - condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable; - value = perAppRoutingTproxy.fwmark; - disallowed = perAppZapretDesyncMarks; - message = "proxy-suite: perAppRouting.tproxy.fwmark must not use per-app-zapret internal desync mark bits"; - } - { - condition = perAppZapretCfg.enable; - value = perAppZapretCfg.filterMark; - disallowed = perAppZapretDesyncMarks; - message = "proxy-suite: perAppRouting.zapret.filterMark must not use per-app-zapret internal desync mark bits"; - } - { - condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable; - value = tgWsProxyCfg.fwmark; - disallowed = perAppZapretDesyncMarks; - message = "proxy-suite: tgWsProxy.fwmark must not use per-app-zapret internal desync mark bits"; - } + let + # zapret's own desync marks: v1's pair, and the bits nfqws2 sets for per-app zapret. + zapretInternalMarks = [ + 536870912 + 1073741824 ]; + noDesyncBits = + condition: value: label: + forbiddenValues condition value perAppZapretDesyncMarks + "proxy-suite: ${label} must not use per-app-zapret internal desync mark bits"; + tgWsBypass = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy; + in + [ + (forbiddenValues perAppZapretCfg.enable perAppZapretCfg.filterMark zapretInternalMarks + "proxy-suite: perAppRouting.zapret.filterMark must not use zapret internal desync mark bits" + ) + (noDesyncBits perAppZapretCfg.enable globalTproxy.fwmark "proxy.tproxy.fwmark") + (noDesyncBits perAppZapretCfg.enable globalTproxy.proxyMark "proxy.tproxy.proxyMark") + (noDesyncBits ( + perAppRoutingTun.enable && perAppZapretCfg.enable + ) perAppRoutingTun.fwmark "perAppRouting.tun.fwmark") + (noDesyncBits ( + perAppRoutingTproxy.enable && perAppZapretCfg.enable + ) perAppRoutingTproxy.fwmark "perAppRouting.tproxy.fwmark") + (noDesyncBits perAppZapretCfg.enable perAppZapretCfg.filterMark "perAppRouting.zapret.filterMark") + (noDesyncBits (tgWsBypass && perAppZapretCfg.enable) tgWsProxyCfg.fwmark "tgWsProxy.fwmark") + ]; torCfg = cfg.tor; torOnionListeners = diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index 508aafe..b35bc59 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -13,54 +13,15 @@ perAppTunChainFile, perAppTproxyRulesFile, perAppZapretRulesFile, + nftablesRulesFile, ip, nft, }: let derived = import ../derived.nix { inherit lib cfg; }; - constants = derived.constants; - inherit (derived) - singBoxCfg - proxyCfg - xrayCfg - proxyEnabled - singBoxEnabled - xrayEnabled - hybridEnabled - pureXrayEnabled - activeBackend - perAppRoutingCfg - globalTun - globalTproxy - perAppRoutingTun - perAppRoutingTproxy - perAppZapretCfg - zapretEngine - zapretCutoffEnabled - zapretCutoffProxyFallback - userControlCfg - selectionMode - builtinTags - outboundTags - subscriptionTags - invalidRoutingTargets - collapseNamedOutbounds - sshProxyCfg - sshProxyOutboundEnabled - sshProxyUnitEnabled - warpCfg - torCfg - awgOutbounds - proxyInboundsCfg - proxyInboundsEnabled - proxyInboundsAwg - proxyInboundsNeedLocalProxy - torOnionEnabled - proxyInboundsGuardPrivate - proxyInboundViaOutbounds - userControlAllows - ; + # Only what this file itself needs; the rest reaches the sub-modules through ctx. + inherit (derived) singBoxCfg xrayCfg userControlCfg; # Tool paths – defined once here and passed into sub-modules as needed. jq = "${pkgs.jq}/bin/jq"; @@ -81,10 +42,7 @@ let ) ); - proxySuiteScriptsDir = builtins.path { - name = "proxy-suite-scripts"; - path = ../../../scripts; - }; + proxySuiteScriptsDir = import ../lib/scripts-dir.nix { inherit lib; }; parserScriptsPythonPath = proxySuiteScriptsDir; buildOutboundPy = "${proxySuiteScriptsDir}/build-outbound.py"; buildInboundPy = "${proxySuiteScriptsDir}/build-inbound.py"; @@ -94,36 +52,38 @@ let polkit = import ./polkit.nix { inherit userControlCfg; }; - scripts = import ./scripts.nix { + # One context for the service layer: everything derived.nix computes, the tool paths and + # generated files above, and the shell-snippet builders. Sub-modules take it whole and + # `inherit` the names they use, so adding a value needs no plumbing in between. + ctx = derived // { inherit lib pkgs - singBoxCfg - proxyCfg - sshProxyCfg - warpCfg - torCfg - awgOutbounds - xrayEnabled - hybridEnabled - pureXrayEnabled - activeBackend - perAppRoutingCfg - userControlCfg - selectionMode - collapseNamedOutbounds - constants - zapretCutoffProxyFallback + packages + cfg + builders + polkit ; inherit jq python3 singBox xray + grepBin + awk + sleepBin + headBin + seqBin + findBin + awgBin + ; + inherit + proxySuiteScriptsDir parserScriptsPythonPath buildOutboundPy buildInboundPy fetchSubscriptionPy + amneziaWgProfileNamesFile ; inherit tproxyFile @@ -132,102 +92,28 @@ let routeModeRulesFile proxyInboundsFile proxyInboundsSpecFile + perAppTunChainFile + perAppTproxyRulesFile + perAppZapretRulesFile + nftablesRulesFile + ip + nft ; - inherit - proxyInboundsCfg - proxyInboundsAwg - awgBin - proxyInboundsNeedLocalProxy - torOnionEnabled - proxyInboundsGuardPrivate - proxyInboundViaOutbounds - userControlAllows - builders - ; + # Filled in below; lazily, so the sub-modules can read each other's results. + inherit scripts perAppRouting; }; - perAppRouting = import ./per-app-routing.nix { - inherit - lib - pkgs - cfg - singBoxCfg - proxyCfg - perAppRoutingCfg - perAppRoutingTun - perAppRoutingTproxy - constants - ; - perAppZapretCfg = perAppZapretCfg; - inherit perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile; - inherit ip nft; - inherit - awk - grepBin - findBin - headBin - seqBin - sleepBin - ; - }; - - control = import ./control.nix { - inherit - packages - singBoxCfg - proxyCfg - perAppRoutingCfg - perAppRoutingTun - perAppRoutingTproxy - perAppZapretCfg - zapretEngine - zapretCutoffEnabled - constants - selectionMode - userControlCfg - ; - inherit (scripts) subscriptionTagsFile subscriptionCacheDir; - inherit (scripts) routeModeStateFile; - inherit proxyInboundsEnabled; - inherit (scripts) proxyInboundsLinksFile proxyInboundsSubscriptionsFile; - proxyInboundsSubscriptionsBaseUrl = proxyInboundsCfg.subscriptions.baseUrl; - proxyInboundsXray = "${proxyInboundsCfg.package}/bin/xray"; - inherit amneziaWgProfileNamesFile; - guiRefreshInterval = cfg.gui.refreshInterval; - inherit (perAppRouting) - perAppRoutingProfilesFile - proxychainsConfigFile - proxychainsQuietArg - ; - }; + scripts = import ./scripts.nix { inherit ctx; }; + perAppRouting = import ./per-app-routing.nix { inherit ctx; }; + control = import ./control.nix { inherit ctx; }; in { inherit + ctx derived - singBoxCfg - proxyCfg - xrayCfg - proxyEnabled - singBoxEnabled - xrayEnabled - hybridEnabled - pureXrayEnabled - activeBackend - perAppRoutingCfg - globalTun - globalTproxy - perAppRoutingTun - perAppRoutingTproxy - perAppZapretCfg - userControlCfg - builtinTags - outboundTags - subscriptionTags - invalidRoutingTargets polkit scripts perAppRouting control - amneziaWgProfileNamesFile ; } diff --git a/modules/proxy-suite/service/control-scripts.nix b/modules/proxy-suite/service/control-scripts.nix index cea9346..a8261ed 100644 --- a/modules/proxy-suite/service/control-scripts.nix +++ b/modules/proxy-suite/service/control-scripts.nix @@ -52,15 +52,7 @@ let mode="''${1:-}" case "$mode" in - default) - ;; - whitelist) - ;; - blacklist) - ;; - all-proxy) - ;; - all-bypass) + default | whitelist | blacklist | all-proxy | all-bypass) ;; *) echo "proxy-suite: route mode must be default, whitelist, blacklist, all-proxy, or all-bypass" >&2 diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 9fc9cc2..59bffa3 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -1,75 +1,97 @@ # Builds proxy-ctl from global proxy-suite state and per-app routing metadata. -{ - packages, - singBoxCfg, - proxyCfg, - perAppRoutingCfg, - perAppRoutingTun, - perAppRoutingTproxy, - perAppZapretCfg, - zapretEngine, - zapretCutoffEnabled, - constants, - selectionMode, - userControlCfg, - subscriptionTagsFile, - subscriptionCacheDir, - perAppRoutingProfilesFile, - proxychainsConfigFile, - proxychainsQuietArg, - routeModeStateFile, - amneziaWgProfileNamesFile, - proxyInboundsEnabled, - proxyInboundsLinksFile, - proxyInboundsSubscriptionsFile, - proxyInboundsSubscriptionsBaseUrl, - proxyInboundsXray, - guiRefreshInterval, -}: +{ ctx }: + +let + inherit (ctx) + lib + localProxy + packages + cfg + singBoxCfg + proxyCfg + perAppRoutingCfg + perAppRoutingTun + perAppRoutingTproxy + perAppZapretCfg + zapretEngine + zapretCutoffEnabled + constants + selectionMode + userControlCfg + proxyInboundsCfg + proxyInboundsEnabled + amneziaWgProfileNamesFile + ; + inherit (ctx.scripts) + subscriptionTagsFile + subscriptionCacheDir + routeModeStateFile + proxyInboundsLinksFile + proxyInboundsSubscriptionsFile + ; + inherit (ctx.perAppRouting) + perAppRoutingProfilesFile + proxychainsConfigFile + proxychainsQuietArg + ; + proxyInboundsSubscriptionsBaseUrl = proxyInboundsCfg.subscriptions.baseUrl; + proxyInboundsXray = "${proxyInboundsCfg.package}/bin/xray"; + guiRefreshInterval = cfg.gui.refreshInterval; + # proxy_ctl.py reads these as "1"/"0" strings. + flag = enabled: if enabled then "1" else "0"; +in { proxyCtl = packages.mkProxyCtl { - clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}"; - selection = selectionMode; inherit + guiRefreshInterval subscriptionTagsFile - subscriptionCacheDir perAppRoutingProfilesFile proxychainsConfigFile - proxychainsQuietArg - routeModeStateFile amneziaWgProfileNamesFile - guiRefreshInterval ; - defaultRouteMode = if (proxyCfg.routing.default == "proxy") then "blacklist" else "whitelist"; - perAppRoutingEnabled = if perAppRoutingCfg.enable then "1" else "0"; - perAppRoutingProxychainsEnabled = if perAppRoutingCfg.proxychains.enable then "1" else "0"; - perAppRoutingTunEnabled = if perAppRoutingTun.enable then "1" else "0"; - perAppRoutingTproxyEnabled = if perAppRoutingTproxy.enable then "1" else "0"; - perAppRoutingZapretEnabled = if perAppZapretCfg.enable then "1" else "0"; - zapretAutoEnabled = if zapretEngine == "zapret2" then "1" else "0"; - zapretStateDir = constants.zapret2StateDir; - zapretCutoffEnabled = if zapretCutoffEnabled then "1" else "0"; - outboundInventoryFile = constants.outboundInventoryFile; - runtimeOutboundsDir = constants.runtimeOutboundsDir; - runtimeSubscriptionsDir = constants.runtimeSubscriptionsDir; - userControlGroup = userControlCfg.group; - inboundsEnabled = if proxyInboundsEnabled then "1" else "0"; - inboundsLinksFile = proxyInboundsLinksFile; - inboundsStatsFile = constants.inboundStatsFile; - inboundsXray = proxyInboundsXray; - inboundsApi = "127.0.0.1:${toString constants.inboundStatsApiPort}"; - inboundsSubscriptionsFile = proxyInboundsSubscriptionsFile; - inboundsSubscriptionsBaseUrl = - if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl; - autoProxyEnabled = if proxyCfg.autoProxy.enable then "1" else "0"; - autoProxyStateDir = constants.autoProxyStateDir; - torControlSocket = constants.torControlSocket; - inherit (constants) stateDir runtimeDir serviceManager; - privileged = if constants.privileged then "1" else "0"; - supervisorCtl = if constants.serviceManager == "supervisor" then constants.systemctl else ""; - singBox = "${singBoxCfg.package}/bin/sing-box"; - localProxyUrl = "http://${ - if proxyCfg.listener.address == "0.0.0.0" then "127.0.0.1" else proxyCfg.listener.address - }:${toString proxyCfg.listener.port}"; + env = { + CLASH_API = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}"; + SELECTION = selectionMode; + SUB_TAGS_FILE = toString subscriptionTagsFile; + SUB_CACHE_DIR = subscriptionCacheDir; + PER_APP_ROUTING_ENABLED = flag perAppRoutingCfg.enable; + PER_APP_ROUTING_PROXYCHAINS_ENABLED = flag perAppRoutingCfg.proxychains.enable; + PER_APP_ROUTING_TUN_ENABLED = flag perAppRoutingTun.enable; + PER_APP_ROUTING_TPROXY_ENABLED = flag perAppRoutingTproxy.enable; + PER_APP_ROUTING_ZAPRET_ENABLED = flag perAppZapretCfg.enable; + PER_APP_ROUTING_PROFILES_FILE = toString perAppRoutingProfilesFile; + PROXYCHAINS_CONFIG = toString proxychainsConfigFile; + PROXYCHAINS_QUIET_ARG = lib.removeSuffix " " proxychainsQuietArg; + ROUTE_MODE_STATE_FILE = routeModeStateFile; + DEFAULT_ROUTE_MODE = if proxyCfg.routing.default == "proxy" then "blacklist" else "whitelist"; + AWG_PROFILES_FILE = toString amneziaWgProfileNamesFile; + INBOUNDS_ENABLED = flag proxyInboundsEnabled; + INBOUNDS_LINKS_FILE = proxyInboundsLinksFile; + INBOUNDS_STATS_FILE = constants.inboundStatsFile; + INBOUNDS_XRAY = proxyInboundsXray; + INBOUNDS_API = "127.0.0.1:${toString constants.inboundStatsApiPort}"; + INBOUNDS_SUBS_FILE = proxyInboundsSubscriptionsFile; + INBOUNDS_SUB_BASE_URL = + if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl; + ZAPRET_AUTO_ENABLED = flag (zapretEngine == "zapret2"); + ZAPRET_STATE_DIR = constants.zapret2StateDir; + ZAPRET_CUTOFF_ENABLED = flag zapretCutoffEnabled; + OUTBOUND_INVENTORY_FILE = constants.outboundInventoryFile; + RUNTIME_OUTBOUNDS_DIR = constants.runtimeOutboundsDir; + RUNTIME_SUBS_DIR = constants.runtimeSubscriptionsDir; + USER_CONTROL_GROUP = userControlCfg.group; + LOCAL_PROXY_URL = "http://${localProxy.hostPart}:${toString proxyCfg.listener.port}"; + AUTOPROXY_ENABLED = flag proxyCfg.autoProxy.enable; + AUTOPROXY_STATE_DIR = constants.autoProxyStateDir; + TOR_CONTROL_SOCKET = constants.torControlSocket; + SING_BOX = "${singBoxCfg.package}/bin/sing-box"; + STATE_DIR = constants.stateDir; + RUNTIME_DIR = constants.runtimeDir; + SERVICE_MANAGER = constants.serviceManager; + PRIVILEGED = flag constants.privileged; + } + // lib.optionalAttrs (constants.serviceManager == "supervisor") { + SUPERVISOR_CTL = constants.systemctl; + }; }; } diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index d3dff99..b3ab810 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -3,43 +3,11 @@ { lib, pkgs, - packages, cfg, - tproxyFile, - tunFile, - perAppTunFile, - routeModeRulesFile, - proxyInboundsFile, - proxyInboundsSpecFile, - nftablesRulesFile, - perAppTproxyRulesFile, - perAppZapretRulesFile, - perAppTunChainFile, - ip, - nft, + context, }: let - context = import ./context.nix { - inherit - lib - pkgs - packages - cfg - tproxyFile - tunFile - perAppTunFile - routeModeRulesFile - proxyInboundsFile - proxyInboundsSpecFile - perAppTunChainFile - perAppTproxyRulesFile - perAppZapretRulesFile - ip - nft - ; - }; - builders = import ./builders.nix { inherit lib pkgs; }; inherit (builders) mkNamedUnits; @@ -79,46 +47,12 @@ let builtinTags ; constants = derived.constants; - routingScripts = import ./routing-scripts.nix { - inherit - lib - pkgs - builders - ip - nft - nftablesRulesFile - constants - globalTun - globalTproxy - perAppRoutingTun - ; - inherit (proxyCfg) ipv6; - }; + routingScripts = import ./routing-scripts.nix { inherit (context) ctx; }; serviceUnits = import ./units.nix { - inherit - lib - builders - proxyCfg - proxyEnabled - hybridEnabled - pureXrayEnabled - globalTun - globalTproxy - perAppRoutingTun - perAppRoutingTproxy - perAppZapretEnabled - sshProxyOutboundEnabled - sshProxyUnitEnabled - torOutboundEnabled - torOnionEnabled - proxyInboundsEnabled - proxyInboundsNeedLocalProxy - scripts - perAppRouting - routingScripts - ; - inherit (cfg) geodata; + ctx = context.ctx // { + inherit routingScripts; + }; }; inherit (serviceUnits) localProxyAuthEnabled diff --git a/modules/proxy-suite/service/per-app-routing.nix b/modules/proxy-suite/service/per-app-routing.nix index 0929179..9efba4f 100644 --- a/modules/proxy-suite/service/per-app-routing.nix +++ b/modules/proxy-suite/service/per-app-routing.nix @@ -1,135 +1,47 @@ # App routing backend infrastructure (TUN, TProxy, zapret). -{ - lib, - pkgs, - cfg, - singBoxCfg, - proxyCfg, - perAppRoutingCfg, - perAppRoutingTun, - perAppRoutingTproxy, - constants, - perAppZapretCfg, - perAppTunChainFile, - perAppTproxyRulesFile, - perAppZapretRulesFile, - ip, - nft, - awk, - grepBin, - findBin, - headBin, - seqBin, - sleepBin, -}: +{ ctx }: let - builders = import ./builders.nix { inherit lib pkgs; }; - inherit (builders) mkAnchorService; - - perAppTunSliceName = "proxy-suite-per-app-tun.slice"; - perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice"; - perAppZapretSliceName = "proxy-suite-per-app-zapret.slice"; - - profiles = import ./per-app-routing/profiles.nix { - inherit (constants) runtimeDir; - inherit - lib - pkgs - proxyCfg - perAppRoutingCfg - perAppRoutingTun - perAppRoutingTproxy - perAppZapretCfg - ; - }; - inherit (profiles) - effectivePerAppRoutingProfiles - effectivePerAppRoutingProfileNames - perAppRoutingProfilesFile - proxychainsConfigFile - proxychainsQuietArg - hasProxychainsProfiles - hasTunProfiles - hasTproxyProfiles - hasZapretProfiles + inherit (ctx) + builders + nft + awk + grepBin + findBin + headBin + perAppRoutingTun + perAppRoutingTproxy + perAppZapretCfg ; - backendScripts = import ./per-app-routing/backend-scripts.nix { - inherit - lib - pkgs - builders - perAppRoutingTun - perAppRoutingTproxy - constants - perAppTunChainFile - perAppTproxyRulesFile - ip - nft - seqBin - sleepBin - ; - inherit (proxyCfg) ipv6; + slices = { + perAppTunSliceName = "proxy-suite-per-app-tun.slice"; + perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice"; + perAppZapretSliceName = "proxy-suite-per-app-zapret.slice"; }; - inherit (backendScripts) - perAppTunUpScript - perAppTunDownScript - perAppTproxyUpScript - perAppTproxyDownScript - ; - - userRules = import ./per-app-routing/user-rules.nix { - inherit - lib - pkgs - perAppRoutingTun - perAppRoutingTproxy - perAppZapretCfg - perAppTunSliceName - perAppTproxySliceName - perAppZapretSliceName - nft - awk - grepBin - findBin - headBin - ; - }; - inherit (userRules) - perAppTunUserRuleStart - perAppTunUserRuleStop - perAppTproxyUserRuleStart - perAppTproxyUserRuleStop - perAppZapretUserRuleStart - perAppZapretUserRuleStop - ; + # user-rules.nix is also imported by the checks, so it keeps an explicit argument list. + userRules = import ./per-app-routing/user-rules.nix ( + { + inherit (ctx) lib pkgs; + inherit + perAppRoutingTun + perAppRoutingTproxy + perAppZapretCfg + nft + awk + grepBin + findBin + headBin + ; + } + // slices + ); in -{ - inherit - perAppTunSliceName - perAppTproxySliceName - perAppZapretSliceName - perAppTunUpScript - perAppTunDownScript - perAppTproxyUpScript - perAppTproxyDownScript - perAppTunUserRuleStart - perAppTunUserRuleStop - perAppTproxyUserRuleStart - perAppTproxyUserRuleStop - perAppZapretUserRuleStart - perAppZapretUserRuleStop - mkAnchorService - effectivePerAppRoutingProfiles - effectivePerAppRoutingProfileNames - perAppRoutingProfilesFile - proxychainsConfigFile - proxychainsQuietArg - hasProxychainsProfiles - hasTunProfiles - hasTproxyProfiles - hasZapretProfiles - ; +slices +// import ./per-app-routing/profiles.nix { inherit ctx; } +// import ./per-app-routing/backend-scripts.nix { inherit ctx; } +// userRules +// { + inherit (builders) mkAnchorService; } diff --git a/modules/proxy-suite/service/per-app-routing/backend-scripts.nix b/modules/proxy-suite/service/per-app-routing/backend-scripts.nix index fa9dee0..01cd239 100644 --- a/modules/proxy-suite/service/per-app-routing/backend-scripts.nix +++ b/modules/proxy-suite/service/per-app-routing/backend-scripts.nix @@ -1,21 +1,23 @@ # Per-app TUN and TProxy backend lifecycle scripts. -{ - lib, - pkgs, - builders, - perAppRoutingTun, - perAppRoutingTproxy, - ipv6, - constants, - perAppTunChainFile, - perAppTproxyRulesFile, - ip, - nft, - seqBin, - sleepBin, -}: +{ ctx }: let + inherit (ctx) + lib + pkgs + builders + perAppRoutingTun + perAppRoutingTproxy + proxyCfg + constants + perAppTunChainFile + perAppTproxyRulesFile + ip + nft + seqBin + sleepBin + ; + inherit (proxyCfg) ipv6; inherit (constants) perAppTunIPv6Address perAppTunIPv6RoutePrefix diff --git a/modules/proxy-suite/service/per-app-routing/profiles.nix b/modules/proxy-suite/service/per-app-routing/profiles.nix index af72d63..271efbe 100644 --- a/modules/proxy-suite/service/per-app-routing/profiles.nix +++ b/modules/proxy-suite/service/per-app-routing/profiles.nix @@ -1,16 +1,18 @@ # Per-app routing profile expansion and proxychains config. -{ - lib, - pkgs, - proxyCfg, - perAppRoutingCfg, - perAppRoutingTun, - perAppRoutingTproxy, - perAppZapretCfg, - runtimeDir, -}: +{ ctx }: let + inherit (ctx) + lib + pkgs + proxyCfg + perAppRoutingCfg + perAppRoutingTun + perAppRoutingTproxy + perAppZapretCfg + constants + ; + inherit (constants) runtimeDir; perAppRoutingProfileNames = map (profile: profile.name) perAppRoutingCfg.profiles; defaultPerAppRoutingProfiles = lib.optionals perAppRoutingCfg.createDefaultProfiles ( [ @@ -46,9 +48,7 @@ let effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles; localProxyAuth = proxyCfg.listener.auth; - localProxyAuthEnabled = - localProxyAuth.username != null - && (localProxyAuth.password != null || localProxyAuth.passwordFile != null); + localProxyAuthEnabled = ctx.localProxy.authEnabled; perAppRoutingProfilesFile = pkgs.writeText "proxy-suite-per-app" ( builtins.toJSON effectivePerAppRoutingProfiles diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix index ba8c0ca..d35bc42 100644 --- a/modules/proxy-suite/service/proxy-inbounds-scripts.nix +++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix @@ -1,32 +1,33 @@ # Start script of the inbound service: renders the listeners with their secrets into the # template and runs XRay. -{ - lib, - pkgs, - proxyCfg, - proxyInboundsCfg, - proxyInboundsAwg, - awgBin, - proxyInboundsNeedLocalProxy, - torOnionEnabled, - proxyInboundViaOutbounds, - userControlCfg, - userControlAllows, - localProxyAuth, - localProxyAuthEnabled, - localProxyAuthPasswordSource, - jq, - python3, - parserScriptsPythonPath, - buildInboundPy, - buildOutboundPy, - proxyInboundsFile, - proxyInboundsSpecFile, - builders, - constants, -}: +{ ctx }: let + inherit (ctx) + lib + pkgs + proxyCfg + proxyInboundsCfg + proxyInboundsAwg + awgBin + proxyInboundsNeedLocalProxy + torOnionEnabled + proxyInboundViaOutbounds + userControlCfg + userControlAllows + localProxyAuth + localProxyAuthEnabled + localProxyAuthPasswordSource + jq + python3 + parserScriptsPythonPath + buildInboundPy + buildOutboundPy + proxyInboundsFile + proxyInboundsSpecFile + builders + constants + ; runtimeDir = "${constants.runtimeDir}/proxy-suite-inbounds"; linksFile = "${runtimeDir}/links.json"; subscriptionsFile = "${runtimeDir}/subscriptions.json"; diff --git a/modules/proxy-suite/service/routing-scripts.nix b/modules/proxy-suite/service/routing-scripts.nix index 10ba3db..eb90726 100644 --- a/modules/proxy-suite/service/routing-scripts.nix +++ b/modules/proxy-suite/service/routing-scripts.nix @@ -1,18 +1,20 @@ -{ - lib, - pkgs, - builders, - ip, - nft, - nftablesRulesFile, - constants, - globalTun, - globalTproxy, - perAppRoutingTun, - ipv6, -}: +{ ctx }: let + inherit (ctx) + lib + pkgs + builders + ip + nft + nftablesRulesFile + constants + globalTun + globalTproxy + perAppRoutingTun + proxyCfg + ; + inherit (proxyCfg) ipv6; inherit (constants) tunAutoRouteTableIndex tunAutoRouteRulePriority diff --git a/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix index c170805..aad9997 100644 --- a/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix +++ b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix @@ -1,9 +1,13 @@ -{ - lib, - jq, - hybridEnabled, - xraySidecarRoutingMark, -}: +{ ctx }: + +let + inherit (ctx) + lib + jq + hybridEnabled + xraySidecarRoutingMark + ; +in routingMark: xraySidecarBasePort: xrayDnsBridgePort: diff --git a/modules/proxy-suite/service/script-blocks/subscriptions.nix b/modules/proxy-suite/service/script-blocks/subscriptions.nix index 7c2e532..e8b3326 100644 --- a/modules/proxy-suite/service/script-blocks/subscriptions.nix +++ b/modules/proxy-suite/service/script-blocks/subscriptions.nix @@ -3,23 +3,24 @@ # Everything is emitted as shell functions taking a tag and a file holding the # subscription URL, so a subscription declared in Nix and one added at runtime # under `subscriptions.d/` go through exactly the same code. -{ - lib, - pkgs, - proxyCfg, - hybridEnabled, - mainBackend, - backend, - stateDir, - runtimeSubscriptionsDir, - jq, - python3, - parserScriptsPythonPath, - fetchSubscriptionPy, - routingMarkJq, -}: +{ ctx }: let + inherit (ctx) + lib + pkgs + proxyCfg + hybridEnabled + mainBackend + backend + constants + jq + python3 + parserScriptsPythonPath + fetchSubscriptionPy + routingMarkJq + ; + inherit (constants) stateDir runtimeSubscriptionsDir; subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend; subscriptionBackendArg = "--backend ${subscriptionBackend}"; subscriptionCacheDir = "${stateDir}/subscriptions/${backend}"; diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 5d28615..88cbbad 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -1,49 +1,36 @@ # Assembles proxy backend startup and control scripts. -{ - lib, - pkgs, - singBoxCfg, - proxyCfg, - sshProxyCfg, - warpCfg, - torCfg, - awgOutbounds, - xrayEnabled, - hybridEnabled, - pureXrayEnabled, - activeBackend, - perAppRoutingCfg, - userControlCfg, - selectionMode, - collapseNamedOutbounds, - constants, - zapretCutoffProxyFallback, - jq, - python3, - singBox, - xray, - parserScriptsPythonPath, - buildOutboundPy, - fetchSubscriptionPy, - tproxyFile, - tunFile, - perAppTunFile, - routeModeRulesFile, - proxyInboundsCfg, - proxyInboundsAwg, - awgBin, - proxyInboundsNeedLocalProxy, - torOnionEnabled, - proxyInboundsGuardPrivate, - proxyInboundViaOutbounds, - userControlAllows, - buildInboundPy, - proxyInboundsFile, - proxyInboundsSpecFile, - builders, -}: +{ ctx }: let + inherit (ctx) + lib + pkgs + singBoxCfg + proxyCfg + activeBackend + xrayEnabled + hybridEnabled + pureXrayEnabled + perAppRoutingCfg + userControlCfg + userControlAllows + selectionMode + constants + zapretCutoffProxyFallback + jq + python3 + singBox + xray + proxyInboundsCfg + proxyInboundsGuardPrivate + routeModeRulesFile + tproxyFile + tunFile + perAppTunFile + proxyInboundsFile + proxyInboundsSpecFile + builders + ; globalTproxy = proxyCfg.tproxy; backend = if activeBackend == null then "sing-box" else activeBackend; mainBackend = if pureXrayEnabled then "xray" else "sing-box"; @@ -81,23 +68,43 @@ let else " | .routing_mark = ${toString routingMark}"; - subscriptionScripts = import ./script-blocks/subscriptions.nix { - inherit (constants) stateDir; + # ctx plus this layer's own values; the script blocks read what they need off it. Lazy, so + # a block may use a sibling's output (start-scripts uses the subscription helpers). + sctx = ctx // { inherit - lib - pkgs - proxyCfg - hybridEnabled - mainBackend backend - runtimeSubscriptionsDir - jq - python3 - parserScriptsPythonPath - fetchSubscriptionPy + mainBackend + backendArg + backendBin + globalTproxy + localProxyAuth + localProxyAuthEnabled + localProxyAuthPasswordSource + routeModeStateFile + xrayLoglevelFile + runtimeProxychainsConfig + xraySidecarRoutingMark routingMarkJq + pinnedOutboundFile + runtimeOutboundsDir + runtimeSubscriptionsDir + outboundInventoryFile + clashApi ; + inherit (subscriptionScripts) + subscriptionCacheDir + subscriptionCacheHelpersBlock + mkSubscriptionLoadHelperBlock + mkSubscriptionBlock + runtimeSubscriptionsBlock + mkSubscriptionFetchBlock + runtimeSubscriptionsFetchBlock + ; + inherit (outboundScripts) mkOutboundScript; + inherit hybridRuntimeHelpersBlock backendJqFilterFile; }; + + subscriptionScripts = import ./script-blocks/subscriptions.nix { ctx = sctx; }; inherit (subscriptionScripts) subscriptionCacheDir subscriptionCacheHelpersBlock @@ -110,7 +117,7 @@ let ; outboundScripts = import ./script-blocks/outbounds.nix { - inherit + inherit (sctx) lib pkgs singBoxCfg @@ -140,14 +147,7 @@ let }; inherit (outboundScripts) mkOutboundScript; - hybridRuntimeHelpersBlock = import ./script-blocks/hybrid-runtime-helpers.nix { - inherit - lib - jq - hybridEnabled - xraySidecarRoutingMark - ; - }; + hybridRuntimeHelpersBlock = import ./script-blocks/hybrid-runtime-helpers.nix { ctx = sctx; }; backendJqFilter = import ./script-blocks/backend-jq-filter.nix { inherit @@ -160,69 +160,10 @@ let }; backendJqFilterFile = pkgs.writeText "proxy-suite-core" backendJqFilter; - startScripts = import ./start-scripts.nix { - inherit - lib - pkgs - proxyCfg - perAppRoutingCfg - userControlCfg - userControlAllows - globalTproxy - xrayEnabled - hybridEnabled - pureXrayEnabled - constants - zapretCutoffProxyFallback - jq - singBox - xray - backendBin - routeModeStateFile - routeModeRulesFile - xrayLoglevelFile - runtimeProxychainsConfig - localProxyAuth - localProxyAuthEnabled - localProxyAuthPasswordSource - backendJqFilterFile - hybridRuntimeHelpersBlock - subscriptionCacheHelpersBlock - mkOutboundScript - tproxyFile - tunFile - perAppTunFile - ; - }; + startScripts = import ./start-scripts.nix { ctx = sctx; }; inherit (startScripts) startSocks startTun startPerAppTun; - proxyInboundsScripts = import ./proxy-inbounds-scripts.nix { - inherit - lib - pkgs - proxyCfg - proxyInboundsCfg - proxyInboundsAwg - awgBin - proxyInboundsNeedLocalProxy - torOnionEnabled - proxyInboundViaOutbounds - userControlCfg - userControlAllows - localProxyAuth - localProxyAuthEnabled - localProxyAuthPasswordSource - jq - python3 - parserScriptsPythonPath - buildInboundPy - buildOutboundPy - proxyInboundsFile - proxyInboundsSpecFile - builders - constants - ; - }; + proxyInboundsScripts = import ./proxy-inbounds-scripts.nix { ctx = sctx; }; inherit (proxyInboundsScripts) startInbounds collectInboundStats; proxyInboundsLinksFile = proxyInboundsScripts.linksFile; proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile; @@ -271,11 +212,5 @@ in subscriptionUpdateScript subscriptionTagsFile subscriptionCacheDir - runtimeProxychainsConfig - pinnedOutboundFile - runtimeOutboundsDir - runtimeSubscriptionsDir - outboundInventoryFile - clashApi ; } diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix index a2b62a2..3b893f3 100644 --- a/modules/proxy-suite/service/start-scripts.nix +++ b/modules/proxy-suite/service/start-scripts.nix @@ -1,38 +1,39 @@ # Backend startup script derivations. -{ - lib, - pkgs, - proxyCfg, - perAppRoutingCfg, - userControlCfg, - userControlAllows, - globalTproxy, - xrayEnabled, - hybridEnabled, - pureXrayEnabled, - constants, - zapretCutoffProxyFallback, - jq, - singBox, - xray, - backendBin, - routeModeStateFile, - routeModeRulesFile, - xrayLoglevelFile, - runtimeProxychainsConfig, - localProxyAuth, - localProxyAuthEnabled, - localProxyAuthPasswordSource, - backendJqFilterFile, - hybridRuntimeHelpersBlock, - subscriptionCacheHelpersBlock, - mkOutboundScript, - tproxyFile, - tunFile, - perAppTunFile, -}: +{ ctx }: let + inherit (ctx) + lib + pkgs + proxyCfg + perAppRoutingCfg + userControlCfg + userControlAllows + globalTproxy + xrayEnabled + hybridEnabled + pureXrayEnabled + constants + zapretCutoffProxyFallback + jq + singBox + xray + backendBin + routeModeStateFile + routeModeRulesFile + xrayLoglevelFile + runtimeProxychainsConfig + localProxyAuth + localProxyAuthEnabled + localProxyAuthPasswordSource + backendJqFilterFile + hybridRuntimeHelpersBlock + subscriptionCacheHelpersBlock + mkOutboundScript + tproxyFile + tunFile + perAppTunFile + ; inherit (constants) autoProxyStateDir outboundTestPort @@ -60,62 +61,89 @@ let + .proxyGeo ''; + # Every route mode is the same four assignments over one jq program on the rule buckets. + routeModeArms = [ + { + mode = "blacklist"; + final = "proxy"; + dns = "remote"; + rules = '' + .common + + (.custom | map(.entries) | add // []) + + .proxyPrimary + + .direct + + .safetyDirect + ${routeModeBlacklistTail} + ''; + } + { + mode = "whitelist"; + final = "direct"; + dns = "local"; + rules = '' + .common + + (.custom | map(.entries) | add // []) + + .proxyPrimary + + .direct + + .safetyDirect + ${routeModeBlacklistTail} + ''; + } + { + # Only the proxy and block lists are kept: everything else follows the final action. + mode = "all-proxy"; + final = "proxy"; + dns = "remote"; + clearDns = true; + rules = '' + .common + + (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // []) + + .proxyPrimary + + .safetyDirect + ${routeModeBlacklistTail} + ''; + } + { + mode = "all-bypass"; + final = "direct"; + dns = "local"; + clearDns = true; + rules = '' + .common + + (.custom | map(select(.category == "block") | .entries) | add // []) + + .safetyDirect + + .block + ''; + } + ]; + + # Written out line by line: the block lands inside a `case`, where the indentation of an + # interpolated multi-line value would otherwise be lost. + mkRouteModeArm = + arm: + lib.concatStringsSep "\n" ( + [ + " ${arm.mode})" + " ROUTE_FINAL=\"${arm.final}\"" + " DNS_FINAL=\"${arm.dns}\"" + " ROUTE_MODE_ACTIVE=true" + ] + ++ lib.optional (arm.clearDns or false) " CLEAR_DNS_RULES=true" + ++ [ " ROUTE_RULES_JSON=$(${jq} -c '" ] + ++ map (line: if line == "" then "" else " ${line}") ( + lib.splitString "\n" (lib.removeSuffix "\n" arm.rules) + ) + ++ [ + " ' \"${routeModeRulesFile}\")" + " ;;" + ] + ); + routeModeCaseBlock = '' if [ -r "$ROUTE_MODE_STATE_FILE" ]; then ROUTE_MODE="$(tr -d '\r\n[:space:]' < "$ROUTE_MODE_STATE_FILE" 2>/dev/null || true)" fi - case "$ROUTE_MODE" in - blacklist) - ROUTE_FINAL="proxy" - DNS_FINAL="remote" - ROUTE_MODE_ACTIVE=true - ROUTE_RULES_JSON=$(${jq} -c ' - .common - + (.custom | map(.entries) | add // []) - + .proxyPrimary - + .direct - + .safetyDirect - ${routeModeBlacklistTail} - ' "${routeModeRulesFile}") - ;; - whitelist) - ROUTE_FINAL="direct" - DNS_FINAL="local" - ROUTE_MODE_ACTIVE=true - ROUTE_RULES_JSON=$(${jq} -c ' - .common - + (.custom | map(.entries) | add // []) - + .proxyPrimary - + .direct - + .safetyDirect - ${routeModeBlacklistTail} - ' "${routeModeRulesFile}") - ;; - all-proxy) - ROUTE_FINAL="proxy" - DNS_FINAL="remote" - ROUTE_MODE_ACTIVE=true - CLEAR_DNS_RULES=true - ROUTE_RULES_JSON=$(${jq} -c ' - .common - + (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // []) - + .proxyPrimary - + .safetyDirect - ${routeModeBlacklistTail} - ' "${routeModeRulesFile}") - ;; - all-bypass) - ROUTE_FINAL="direct" - DNS_FINAL="local" - ROUTE_MODE_ACTIVE=true - CLEAR_DNS_RULES=true - ROUTE_RULES_JSON=$(${jq} -c ' - .common - + (.custom | map(select(.category == "block") | .entries) | add // []) - + .safetyDirect - + .block - ' "${routeModeRulesFile}") - ;; + case "$ROUTE_MODE" in${lib.concatMapStrings (arm: "\n" + mkRouteModeArm arm) routeModeArms} *) ROUTE_MODE="" ;; diff --git a/modules/proxy-suite/service/units.nix b/modules/proxy-suite/service/units.nix index fd5e97c..bc25053 100644 --- a/modules/proxy-suite/service/units.nix +++ b/modules/proxy-suite/service/units.nix @@ -1,29 +1,31 @@ # Systemd unit definitions for proxy-suite services and timers. -{ - lib, - builders, - proxyCfg, - proxyEnabled, - hybridEnabled, - pureXrayEnabled, - globalTun, - globalTproxy, - perAppRoutingTun, - perAppRoutingTproxy, - perAppZapretEnabled, - sshProxyOutboundEnabled, - sshProxyUnitEnabled, - torOutboundEnabled, - torOnionEnabled, - proxyInboundsEnabled, - proxyInboundsNeedLocalProxy, - scripts, - perAppRouting, - routingScripts, - geodata, -}: +{ ctx }: let + inherit (ctx) + lib + builders + proxyCfg + proxyEnabled + hybridEnabled + pureXrayEnabled + globalTun + globalTproxy + perAppRoutingTun + perAppRoutingTproxy + perAppZapretEnabled + sshProxyOutboundEnabled + sshProxyUnitEnabled + torOutboundEnabled + torOnionEnabled + proxyInboundsEnabled + proxyInboundsNeedLocalProxy + scripts + perAppRouting + routingScripts + cfg + ; + inherit (cfg) geodata; inherit (builders) mkAnchorService mkRestartingService @@ -58,9 +60,7 @@ let else "sing-box"; - localProxyAuthEnabled = - proxyCfg.listener.auth.username != null - && (proxyCfg.listener.auth.password != null || proxyCfg.listener.auth.passwordFile != null); + localProxyAuthEnabled = ctx.localProxy.authEnabled; # XRay finds geoip.dat/geosite.dat through this; sing-box ignores it. xrayAssetEnv = lib.optionalAttrs (geodata.xray.assets != null) { @@ -336,7 +336,6 @@ let in { inherit - serviceNames localProxyAuthEnabled systemServiceEntries userServiceEntries diff --git a/modules/proxy-suite/tor.nix b/modules/proxy-suite/tor.nix index f3c1b8b..193b27f 100644 --- a/modules/proxy-suite/tor.nix +++ b/modules/proxy-suite/tor.nix @@ -12,20 +12,10 @@ let inherit (derived.constants) unprivilegedServiceConfig; inherit (cfg.host) privileged; + inherit (derived.localProxy) auth; listener = cfg.proxy.listener; - auth = listener.auth; - # Tor dials the local proxy by address: a wildcard listener is reached on loopback. - proxyHost = - if - builtins.elem listener.address [ - "0.0.0.0" - "::" - ] - then - "127.0.0.1" - else - listener.address; - proxyHostPart = if lib.hasInfix ":" proxyHost then "[${proxyHost}]" else proxyHost; + proxyHost = derived.localProxy.host; + proxyHostPart = derived.localProxy.hostPart; passwordSource = if auth.passwordFile != null then auth.passwordFile @@ -34,7 +24,7 @@ let else null; viaProxy = t.upstream == "proxy"; - withProxyAuth = viaProxy && auth.username != null && passwordSource != null; + withProxyAuth = viaProxy && derived.localProxy.authEnabled; bridgesEnabled = t.bridges.lines != [ ] || t.bridges.file != null; # The control socket's directory: members of userControl.group may use it for diff --git a/modules/proxy-suite/warp.nix b/modules/proxy-suite/warp.nix index be13131..d5f7363 100644 --- a/modules/proxy-suite/warp.nix +++ b/modules/proxy-suite/warp.nix @@ -10,19 +10,8 @@ let w = derived.warpCfg; inherit (derived.constants) unprivilegedServiceConfig; + inherit (derived.localProxy) auth host hostPart; listener = cfg.proxy.listener; - auth = listener.auth; - host = - if - builtins.elem listener.address [ - "0.0.0.0" - "::" - ] - then - "127.0.0.1" - else - listener.address; - hostPart = if lib.hasInfix ":" host then "[${host}]" else host; passwordSource = if auth.passwordFile != null then auth.passwordFile @@ -30,7 +19,7 @@ let pkgs.writeText "proxy-suite-warp" auth.password else null; - withProxyAuth = auth.username != null && passwordSource != null; + withProxyAuth = derived.localProxy.authEnabled; userinfo = lib.optionalString withProxyAuth '' userinfo=$(${pkgs.jq}/bin/jq -rn --arg u ${lib.escapeShellArg auth.username} \ --rawfile p "$CREDENTIALS_DIRECTORY/proxy-password" '"\($u | @uri):\($p | rtrimstr("\n") | @uri)@"') diff --git a/modules/proxy-suite/wg-tunnel.nix b/modules/proxy-suite/wg-tunnel.nix index 025d900..3985885 100644 --- a/modules/proxy-suite/wg-tunnel.nix +++ b/modules/proxy-suite/wg-tunnel.nix @@ -10,10 +10,7 @@ let inherit (derived.constants) serviceUser runAsServiceUser ifPrivileged; - scriptsDir = builtins.path { - name = "proxy-suite-scripts"; - path = ../../scripts; - }; + scriptsDir = import ./lib/scripts-dir.nix { inherit lib; }; # sing-box's "local" server has no upstream on hosts behind systemd-resolved, so the tunnel # resolves the peer hostname like the main config, with proxy.dns.local. Destinations are diff --git a/modules/proxy-suite/zapret.nix b/modules/proxy-suite/zapret.nix index 620436a..6420081 100644 --- a/modules/proxy-suite/zapret.nix +++ b/modules/proxy-suite/zapret.nix @@ -14,10 +14,21 @@ let zapretCfg = cfg.zapret; perAppZapretCfg = cfg.perAppRouting.zapret; - # Global AmneziaWG profiles only: an outbound one leaves the host's routes alone. - awgServiceNames = map (name: "proxy-suite-awg-${name}.service") ( - builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles) - ); + inherit + (import ./zapret/common.nix { + inherit + lib + pkgs + cfg + nft + perAppZapretRulesFile + ; + }) + awgServiceNames + perAppConflicts + perAppZapretMarkUpScript + perAppZapretMarkDownScript + ; zapretPackages = import ./zapret/packages.nix { inherit lib @@ -47,17 +58,6 @@ let fi ''; - perAppZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-zapret" '' - set -euo pipefail - ${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true - ${nft} -f ${perAppZapretRulesFile} - ''; - - perAppZapretMarkDownScript = pkgs.writeShellScript "proxy-suite-zapret" '' - set -euo pipefail - ${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true - ''; - exemptStart = '' set -euo pipefail '' @@ -108,11 +108,7 @@ in description = "proxy-suite per-app-routing zapret backend"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; - conflicts = [ - "proxy-suite-tproxy.service" - "proxy-suite-tun.service" - ] - ++ awgServiceNames; + conflicts = perAppConflicts ++ awgServiceNames; preStart = zapretCommonPreStart perAppZapretPackage; runtimeDirectory = "proxy-suite-per-app-zapret"; execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start"; diff --git a/modules/proxy-suite/zapret/common.nix b/modules/proxy-suite/zapret/common.nix new file mode 100644 index 0000000..9891b53 --- /dev/null +++ b/modules/proxy-suite/zapret/common.nix @@ -0,0 +1,42 @@ +# What both zapret engines need the same way: which units they must not run beside, the +# interfaces to keep out of NFQUEUE, and the per-app mark table's nft hooks. +{ + lib, + pkgs, + cfg, + nft ? null, + perAppZapretRulesFile ? null, + # zapret v1 names its scripts proxy-suite-zapret, zapret2 proxy-suite-zapret2. + scriptName ? "proxy-suite-zapret", +}: +let + dropMarkTable = "${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true"; +in +{ + # Global AmneziaWG profiles only: an outbound one leaves the host's routes alone. + awgServiceNames = map (name: "proxy-suite-awg-${name}.service") ( + builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles) + ); + + tunInterfaces = lib.unique ( + lib.optional (cfg.proxy.enable && cfg.proxy.tun.enable) cfg.proxy.tun.interface + ++ lib.optional (cfg.proxy.enable && cfg.perAppRouting.tun.enable) cfg.perAppRouting.tun.interface + ); + + # The transparent backends steer the same packets; a per-app zapret instance replaces them. + perAppConflicts = [ + "proxy-suite-tproxy.service" + "proxy-suite-tun.service" + ]; + + perAppZapretMarkUpScript = pkgs.writeShellScript scriptName '' + set -euo pipefail + ${dropMarkTable} + ${nft} -f ${perAppZapretRulesFile} + ''; + + perAppZapretMarkDownScript = pkgs.writeShellScript scriptName '' + set -euo pipefail + ${dropMarkTable} + ''; +} diff --git a/modules/proxy-suite/zapret/packages.nix b/modules/proxy-suite/zapret/packages.nix index c48504c..d6ee6ae 100644 --- a/modules/proxy-suite/zapret/packages.nix +++ b/modules/proxy-suite/zapret/packages.nix @@ -9,10 +9,7 @@ let zapretCfg = cfg.zapret; perAppZapretCfg = cfg.perAppRouting.zapret; - tunInterfaces = lib.unique ( - lib.optional (cfg.proxy.enable && cfg.proxy.tun.enable) cfg.proxy.tun.interface - ++ lib.optional (cfg.proxy.enable && cfg.perAppRouting.tun.enable) cfg.perAppRouting.tun.interface - ); + inherit (import ./common.nix { inherit lib pkgs cfg; }) tunInterfaces; zapretDomainGroups = import ../zapret-domain-groups.nix { inherit lib zapret; }; runtimeDeps = lib.attrValues { @@ -84,12 +81,7 @@ let ); selectedConfigName = lib.strings.sanitizeDerivationName zapretCfg.zapret-discord-youtube.configName; - patchConfigScriptSrc = "${ - builtins.path { - name = "proxy-suite-scripts"; - path = ../../../scripts; - } - }/patch-zapret-config.py"; + patchConfigScriptSrc = "${import ../lib/scripts-dir.nix { inherit lib; }}/patch-zapret-config.py"; patchConfigScript = "${pkgs.python3}/bin/python3 ${patchConfigScriptSrc}"; packageBuilder = import ./package-builder.nix { diff --git a/modules/proxy-suite/zapret2.nix b/modules/proxy-suite/zapret2.nix index e784aa0..fb69818 100644 --- a/modules/proxy-suite/zapret2.nix +++ b/modules/proxy-suite/zapret2.nix @@ -17,10 +17,23 @@ let perAppZapretCfg = cfg.perAppRouting.zapret; cutoffCfg = zapretCfg.zapret2.cutoff; inherit (import ./derived.nix { inherit lib cfg; }) constants userControlAllows; - # Global AmneziaWG profiles only: an outbound one leaves the host's routes alone. - awgServiceNames = map (name: "proxy-suite-awg-${name}.service") ( - builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles) - ); + inherit + (import ./zapret/common.nix { + inherit + lib + pkgs + cfg + nft + perAppZapretRulesFile + ; + scriptName = "proxy-suite-zapret2"; + }) + awgServiceNames + tunInterfaces + perAppConflicts + perAppZapretMarkUpScript + perAppZapretMarkDownScript + ; runtime = import ./zapret2/runtime.nix { inherit @@ -32,11 +45,6 @@ let ; }; - tunInterfaces = lib.unique ( - lib.optional (cfg.proxy.enable && cfg.proxy.tun.enable) cfg.proxy.tun.interface - ++ lib.optional (cfg.proxy.enable && cfg.perAppRouting.tun.enable) cfg.perAppRouting.tun.interface - ); - globalRuntime = runtime.mkRuntime { name = "proxy-suite-zapret2"; qnum = constants.zapretGlobalQnum.zapret2; @@ -91,16 +99,6 @@ let ; }; - perAppZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-zapret2" '' - set -euo pipefail - ${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true - ${nft} -f ${perAppZapretRulesFile} - ''; - - perAppZapretMarkDownScript = pkgs.writeShellScript "proxy-suite-zapret2" '' - set -euo pipefail - ${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true - ''; in { services.proxy-suite.internal.earlyPackages = [ runtime.package ]; @@ -138,11 +136,7 @@ in description = "proxy-suite per-app-routing zapret2 backend"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; - conflicts = [ - "proxy-suite-tproxy.service" - "proxy-suite-tun.service" - ] - ++ awgServiceNames; + conflicts = perAppConflicts ++ awgServiceNames; preStart = mkPreStart; runtimeDirectory = "proxy-suite-per-app-zapret"; stateDirectory = "proxy-suite"; diff --git a/nix/checks.nix b/nix/checks.nix index 57b7960..4c6bf47 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -20,7 +20,7 @@ let } ); }; - parserChecks = import ./checks/parsers.nix { inherit pkgs; }; + pythonChecks = import ./checks/python-tests.nix { inherit pkgs; }; checkLib = import ./checks/lib.nix { inherit pkgs @@ -67,5 +67,5 @@ moduleSuiteChecks proxy-inbounds-runtime = proxyInboundsRuntime; amneziawg-inbounds-runtime = amneziaWgInboundsRuntime; } -// parserChecks +// pythonChecks // repoChecks diff --git a/nix/checks/amnezia-wg-outbound.nix b/nix/checks/amnezia-wg-outbound.nix index 32408e7..84cab8c 100644 --- a/nix/checks/amnezia-wg-outbound.nix +++ b/nix/checks/amnezia-wg-outbound.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkBadProxySuiteFixture, @@ -9,6 +10,7 @@ }: let + inherit (checkLib) mkProxySuite; generated = import ./read-generated.nix; inherit (pkgs.lib) hasInfix; @@ -57,21 +59,16 @@ let plainTunnel = generated.readDerivation services.proxy-suite-awg-plain.serviceConfig.ExecStart; dnsServer = dnsServerByTag (mkTProxyConfig singBox) "awg-dns-de"; - warpInterface = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy.enable = true; - amneziaWg.enable = true; - warp = { - enable = true; - configFile = "/run/secrets/wgcf-profile.conf"; - asOutbound = "interface"; - }; - }; - } - ]; + warpInterface = mkProxySuite { + enable = true; + proxy.enable = true; + amneziaWg.enable = true; + warp = { + enable = true; + configFile = "/run/secrets/wgcf-profile.conf"; + asOutbound = "interface"; + }; + }; in { assertions = [ diff --git a/nix/checks/amnezia-wg.nix b/nix/checks/amnezia-wg.nix index c03cbf1..2ff36da 100644 --- a/nix/checks/amnezia-wg.nix +++ b/nix/checks/amnezia-wg.nix @@ -1,25 +1,23 @@ { + checkLib, pkgs, evalProxySuite, mkBadProxySuiteFixture, mkFailingAssertions, + rejectsProxySuite, mkProxyCtlDerived, }: let + inherit (checkLib) mkProxySuite; generated = import ./read-generated.nix; - defaultPackages = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - amneziaWg = { - enable = true; - profiles.home.configFile = "/run/secrets/awg.conf"; - }; - }; - } - ]; + defaultPackages = mkProxySuite { + enable = true; + amneziaWg = { + enable = true; + profiles.home.configFile = "/run/secrets/awg.conf"; + }; + }; awgOnly = evalProxySuite [ { system.stateVersion = "26.05"; @@ -108,21 +106,16 @@ let fakeKernelModule = pkgs.runCommand "fake-amneziawg-module" { } '' mkdir -p "$out/lib/modules" ''; - overrideFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - amneziaWg = { - enable = true; - toolsPackage = fakeTools; - userspacePackage = fakeUserspace; - kernelModulePackage = fakeKernelModule; - profiles.home.configFile = "/run/secrets/client.conf"; - }; - }; - } - ]; + overrideFixture = mkProxySuite { + enable = true; + amneziaWg = { + enable = true; + toolsPackage = fakeTools; + userspacePackage = fakeUserspace; + kernelModulePackage = fakeKernelModule; + profiles.home.configFile = "/run/secrets/client.conf"; + }; + }; withGlobalTun = evalProxySuite [ { @@ -340,7 +333,11 @@ in }; }; } - { + ] + # An AmneziaWG profile and a global proxy mode both autostarting. Message-matched: with + # `proxy.tun.autostart` (removed) this case used to fail on the option name instead. + ++ [ + (rejectsProxySuite "at most one AmneziaWG, TUN, or TProxy global mode may autostart" { enable = true; proxy = { enable = true; @@ -351,10 +348,8 @@ in url = "http://proxy.example.com:8080"; } ]; - tun = { - enable = true; - autostart = true; - }; + tun.enable = true; + autostart = "tun"; }; amneziaWg = { enable = true; @@ -364,6 +359,6 @@ in configFile = "/run/home.conf"; }; }; - } + }) ]; } diff --git a/nix/checks/chaining-dns.nix b/nix/checks/chaining-dns.nix index 6d09c8b..6377731 100644 --- a/nix/checks/chaining-dns.nix +++ b/nix/checks/chaining-dns.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -9,11 +10,8 @@ }: let + inherit (checkLib) startScript; generated = import ./read-generated.nix; - startScript = - fixture: - generated.readDerivation - fixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart; chained = evalProxySuite [ baseModule diff --git a/nix/checks/core-proxy.nix b/nix/checks/core-proxy.nix index 0c4079f..10a0c47 100644 --- a/nix/checks/core-proxy.nix +++ b/nix/checks/core-proxy.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -12,6 +13,7 @@ let fixtures = import ./core-proxy/fixtures.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -40,6 +42,7 @@ let ; routingDnsChecks = import ./core-proxy/routing-dns.nix { + inherit checkLib; inherit hasRuleSet dnsHasRuleSet @@ -57,6 +60,7 @@ let ; }; serviceDefaultChecks = import ./core-proxy/service-defaults.nix { + inherit checkLib; inherit pkgs minimal diff --git a/nix/checks/core-proxy/fixtures.nix b/nix/checks/core-proxy/fixtures.nix index 523307e..9591693 100644 --- a/nix/checks/core-proxy/fixtures.nix +++ b/nix/checks/core-proxy/fixtures.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -8,6 +9,7 @@ }: let + inherit (checkLib) startScript; generated = import ../read-generated.nix; customSingBoxPackage = pkgs.writeShellScriptBin "sing-box" '' @@ -20,9 +22,7 @@ let } ]; customSingBoxPackageBin = "${builtins.unsafeDiscardStringContext (toString customSingBoxPackage)}/bin/sing-box"; - customSingBoxPackageStartScript = generated.readDerivation ( - customSingBoxPackageFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + customSingBoxPackageStartScript = startScript customSingBoxPackageFixture; routingOrFixture = evalProxySuite [ { @@ -125,9 +125,7 @@ let }; } ]; - urlTestCustomStartScript = generated.readDerivation ( - urlTestCustomFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + urlTestCustomStartScript = startScript urlTestCustomFixture; noProxyBackendDefaultFixture = evalProxySuite [ { diff --git a/nix/checks/core-proxy/routing-dns.nix b/nix/checks/core-proxy/routing-dns.nix index e32d97a..b49f106 100644 --- a/nix/checks/core-proxy/routing-dns.nix +++ b/nix/checks/core-proxy/routing-dns.nix @@ -1,4 +1,5 @@ { + checkLib, hasRuleSet, dnsHasRuleSet, dnsServerByTag, @@ -14,25 +15,16 @@ routingOrGeoIPRules, }: +let + inherit (checkLib) ok; +in { assertions = [ # -- routing rule entries with domains and geoips preserve both matchers, and the named outbound -- - ( - assert builtins.length routingOrDomainRules == 1; - true - ) - ( - assert builtins.length routingOrGeoIPRules == 1; - true - ) - ( - assert (builtins.head routingOrDomainRules).outbound == "primary"; - true - ) - ( - assert (builtins.head routingOrGeoIPRules).outbound == "primary"; - true - ) + (ok (builtins.length routingOrDomainRules == 1)) + (ok (builtins.length routingOrGeoIPRules == 1)) + (ok ((builtins.head routingOrDomainRules).outbound == "primary")) + (ok ((builtins.head routingOrGeoIPRules).outbound == "primary")) # -- default RU direct route and DNS rules are generated -- ( @@ -50,34 +42,13 @@ assert remoteDns.detour == "proxy"; true ) - ( - assert hasRuleSet ruDefaultRules "direct" "geosite-category-ru"; - true - ) - ( - assert hasRuleSet ruDefaultRules "direct" "geoip-ru"; - true - ) - ( - assert dnsHasRuleSet ruDefaultConfig.dns.rules "geosite-category-ru"; - true - ) - ( - assert !(hasRuleSet ruDisabledRules "direct" "geosite-category-ru"); - true - ) - ( - assert !(hasRuleSet ruDisabledRules "direct" "geoip-ru"); - true - ) - ( - assert !(dnsHasRuleSet ruDisabledConfig.dns.rules "geosite-category-ru"); - true - ) - ( - assert dnsHasRuleSet ruExplicitConfig.dns.rules "geosite-category-ru"; - true - ) + (ok (hasRuleSet ruDefaultRules "direct" "geosite-category-ru")) + (ok (hasRuleSet ruDefaultRules "direct" "geoip-ru")) + (ok (dnsHasRuleSet ruDefaultConfig.dns.rules "geosite-category-ru")) + (ok (!(hasRuleSet ruDisabledRules "direct" "geosite-category-ru"))) + (ok (!(hasRuleSet ruDisabledRules "direct" "geoip-ru"))) + (ok (!(dnsHasRuleSet ruDisabledConfig.dns.rules "geosite-category-ru"))) + (ok (dnsHasRuleSet ruExplicitConfig.dns.rules "geosite-category-ru")) # -- DNS overrides map to sing-box server entries -- ( @@ -102,13 +73,7 @@ ) # -- block route geosite and geoip sets are emitted -- - ( - assert hasRuleSet blockGeoRules "block" "geosite-category-ads-all"; - true - ) - ( - assert hasRuleSet blockGeoRules "block" "geoip-cn"; - true - ) + (ok (hasRuleSet blockGeoRules "block" "geosite-category-ads-all")) + (ok (hasRuleSet blockGeoRules "block" "geoip-cn")) ]; } diff --git a/nix/checks/core-proxy/service-defaults.nix b/nix/checks/core-proxy/service-defaults.nix index 08dc8cb..614fbc5 100644 --- a/nix/checks/core-proxy/service-defaults.nix +++ b/nix/checks/core-proxy/service-defaults.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, minimal, customSingBoxPackageBin, @@ -9,27 +10,18 @@ noProxyBackendDefaultFixture, }: +let + inherit (checkLib) ok; +in { assertions = [ # -- sing-box package override propagates into generated service scripts -- - ( - assert pkgs.lib.hasInfix customSingBoxPackageBin customSingBoxPackageStartScript; - true - ) + (ok (pkgs.lib.hasInfix customSingBoxPackageBin customSingBoxPackageStartScript)) # -- proxy defaults and urltest settings are applied -- - ( - assert proxyDirectConfig.dns.final == "local"; - true - ) - ( - assert ruDefaultConfig.dns.final == "remote"; - true - ) - ( - assert ruDefaultConfig.route.default_domain_resolver == "local"; - true - ) + (ok (proxyDirectConfig.dns.final == "local")) + (ok (ruDefaultConfig.dns.final == "remote")) + (ok (ruDefaultConfig.route.default_domain_resolver == "local")) ( assert builtins.match ".*telegram\\.org.*" urlTestCustomStartScript != null; assert builtins.match ".*1m.*" urlTestCustomStartScript != null; diff --git a/nix/checks/global-proxy-modes.nix b/nix/checks/global-proxy-modes.nix index 90f4499..271c985 100644 --- a/nix/checks/global-proxy-modes.nix +++ b/nix/checks/global-proxy-modes.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -12,6 +13,7 @@ }: let + inherit (checkLib) ok; fixtures = import ./global-proxy-modes/fixtures.nix { inherit evalProxySuite @@ -49,10 +51,7 @@ let in { assertions = [ - ( - assert tproxyWithFirewall.config.networking.firewall.enable; - true - ) + (ok (tproxyWithFirewall.config.networking.firewall.enable)) ( assert tproxyManualFixture.config.services.proxy-suite.proxy.autostart == null; assert tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".wantedBy == [ ]; @@ -140,10 +139,7 @@ in assert tunDefaultConfig.route.auto_detect_interface == true; true ) - ( - assert tunManualFixture.config.networking.nftables.enable; - true - ) + (ok (tunManualFixture.config.networking.nftables.enable)) ( assert tunServiceConfig.ExecStartPre == tunServiceConfig.ExecStopPost; assert pkgs.lib.hasInfix "delete table inet sing-box" tunCleanupScript; @@ -169,10 +165,7 @@ in assert !(localDns ? detour); true ) - ( - assert tunDefaultConfig.route.default_domain_resolver == "local"; - true - ) + (ok (tunDefaultConfig.route.default_domain_resolver == "local")) ( assert builtins.elem "network-online.target" tunManualFixture.config.systemd.services."proxy-suite-tun".after; diff --git a/nix/checks/hybrid-backend.nix b/nix/checks/hybrid-backend.nix index 28bdc1a..144d66d 100644 --- a/nix/checks/hybrid-backend.nix +++ b/nix/checks/hybrid-backend.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkTProxyConfig, @@ -9,6 +10,7 @@ let fixtures = import ./hybrid-backend/fixtures.nix { + inherit checkLib; inherit pkgs evalProxySuite diff --git a/nix/checks/hybrid-backend/fixtures.nix b/nix/checks/hybrid-backend/fixtures.nix index 3caaa6b..62a5c4f 100644 --- a/nix/checks/hybrid-backend/fixtures.nix +++ b/nix/checks/hybrid-backend/fixtures.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkTProxyConfig, @@ -7,6 +8,7 @@ }: let + inherit (checkLib) startScript unitScript; generated = import ../read-generated.nix; hybridModule = { @@ -36,15 +38,9 @@ let hybridFixture = evalProxySuite [ hybridModule ]; hybridTproxyConfig = mkTProxyConfig hybridFixture; hybridTunConfig = mkTunConfig hybridFixture; - hybridStartScript = generated.readDerivation ( - hybridFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); - hybridTunStartScript = generated.readDerivation ( - hybridFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStart - ); - hybridPerAppTunStartScript = generated.readDerivation ( - hybridFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStart - ); + hybridStartScript = startScript hybridFixture; + hybridTunStartScript = unitScript hybridFixture "proxy-suite-tun"; + hybridPerAppTunStartScript = unitScript hybridFixture "proxy-suite-per-app-tun"; hybridBackendJqFilter = import ../../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix { @@ -75,9 +71,7 @@ let }; } ]; - hybridXrayRawStartScript = generated.readDerivation ( - hybridXrayRawFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + hybridXrayRawStartScript = startScript hybridXrayRawFixture; hybridSubscriptionFixture = evalProxySuite [ { @@ -98,12 +92,8 @@ let }; } ]; - hybridSubscriptionStartScript = generated.readDerivation ( - hybridSubscriptionFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); - hybridSubscriptionUpdateScript = generated.readDerivation ( - hybridSubscriptionFixture.config.systemd.services."proxy-suite-subscription-update".serviceConfig.ExecStart - ); + hybridSubscriptionStartScript = startScript hybridSubscriptionFixture; + hybridSubscriptionUpdateScript = unitScript hybridSubscriptionFixture "proxy-suite-subscription-update"; in { inherit diff --git a/nix/checks/lib.nix b/nix/checks/lib.nix index a6a8fb2..f5ce4a1 100644 --- a/nix/checks/lib.nix +++ b/nix/checks/lib.nix @@ -17,85 +17,54 @@ let }; forceEval = value: builtins.tryEval (builtins.deepSeq value true); rg = "${pkgs.ripgrep}/bin/rg"; - mkRouting = + # The module's own wiring, so a check sees exactly what a running system generates. + mkAssembly = fixture: - let - cfg = fixture.config.services.proxy-suite; - in - import ../../modules/proxy-suite/rules.nix { + import ../../modules/proxy-suite/assembly.nix { lib = pkgs.lib; - inherit pkgs cfg zapret; + inherit pkgs zapret; + cfg = fixture.config.services.proxy-suite; + packages = import ../../pkgs/default.nix { inherit pkgs; }; }; + mkRouting = fixture: (mkAssembly fixture).rules; mkRoutingRules = fixture: (mkRouting fixture).routingRules; mkRouteModeRules = fixture: (mkRouting fixture).routeModeRules; mkProxyConfig = fixture: configAttr: - let - cfg = fixture.config.services.proxy-suite; - rules = mkRouting fixture; - configs = import ../../modules/proxy-suite/config.nix { - lib = pkgs.lib; - inherit pkgs cfg rules; - }; - in builtins.fromJSON ( - builtins.unsafeDiscardStringContext (generated.readDerivation configs.${configAttr}) + builtins.unsafeDiscardStringContext ( + generated.readDerivation (mkAssembly fixture).configs.${configAttr} + ) ); mkTProxyConfig = fixture: mkProxyConfig fixture "tproxyFile"; mkTunConfig = fixture: mkProxyConfig fixture "tunFile"; mkPerAppTunConfig = fixture: mkProxyConfig fixture "perAppTunFile"; mkInboundsConfig = fixture: mkProxyConfig fixture "proxyInboundsFile"; mkInboundsSpec = fixture: mkProxyConfig fixture "proxyInboundsSpecFile"; - mkTProxyNftRules = - fixture: - let - cfg = fixture.config.services.proxy-suite; - nftr = import ../../modules/proxy-suite/nftables.nix { - lib = pkgs.lib; - inherit pkgs cfg; - }; - in - generated.readDerivation nftr.nftablesRulesFile; - mkPerAppZapretNftRules = - fixture: - let - cfg = fixture.config.services.proxy-suite; - nftr = import ../../modules/proxy-suite/nftables.nix { - lib = pkgs.lib; - inherit pkgs cfg; - }; - in - generated.readDerivation nftr.perAppZapretRulesFile; - mkPerAppUserRules = - fixture: - let - cfg = fixture.config.services.proxy-suite; - derived = import ../../modules/proxy-suite/derived.nix { - lib = pkgs.lib; - inherit cfg; - }; - nftr = import ../../modules/proxy-suite/nftables.nix { - lib = pkgs.lib; - inherit pkgs cfg; - }; - in - import ../../modules/proxy-suite/service/per-app-routing/user-rules.nix { - lib = pkgs.lib; - inherit pkgs; - inherit (derived) - perAppRoutingTun - perAppRoutingTproxy - perAppZapretCfg - ; - perAppTunSliceName = "proxy-suite-per-app-tun.slice"; - perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice"; - perAppZapretSliceName = "proxy-suite-per-app-zapret.slice"; - inherit (nftr) nft; - awk = "${pkgs.gawk}/bin/awk"; - grepBin = "${pkgs.gnugrep}/bin/grep"; - findBin = "${pkgs.findutils}/bin/find"; - headBin = "${pkgs.coreutils}/bin/head"; - }; + mkNftRules = fixture: attr: generated.readDerivation (mkAssembly fixture).nftr.${attr}; + mkTProxyNftRules = fixture: mkNftRules fixture "nftablesRulesFile"; + mkPerAppZapretNftRules = fixture: mkNftRules fixture "perAppZapretRulesFile"; + mkPerAppUserRules = fixture: (mkAssembly fixture).context.perAppRouting; + # One assertion as a list element: `ok (x == y)` where the check lists want a true. + ok = + condition: + assert condition; + true; + # A fixture from nothing but proxy-suite settings, the shape most checks want. + mkProxySuite = + proxySuiteConfig: + evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = proxySuiteConfig; + } + ]; + # The text of the program a unit starts, without import-from-derivation. + unitScript = + fixture: unit: + generated.readDerivation fixture.config.systemd.services.${unit}.serviceConfig.ExecStart; + # The local proxy's start script, which most checks read their expectations out of. + startScript = fixture: unitScript fixture "proxy-suite-socks"; hasDirectDomain = rules: domain: builtins.any ( @@ -143,11 +112,6 @@ let builtins.head ( builtins.filter (line: pkgs.lib.hasPrefix prefix line) (pkgs.lib.splitString "\n" text) ); - lineContaining = - text: infix: - builtins.head ( - builtins.filter (line: pkgs.lib.hasInfix infix line) (pkgs.lib.splitString "\n" text) - ); shellValueByPrefix = text: prefix: let @@ -210,6 +174,42 @@ let assert (evaluate case).success == false; true ) cases; + # The messages of the assertions a config fails. Only the failing ones are forced, so an + # unrelated module's lazily-broken message (nixpkgs has some) never gets in the way. A + # fixture that does not evaluate at all reports that instead, so it cannot pass silently. + failedAssertions = + modules: + let + messages = map (a: a.message) ( + builtins.filter (a: !a.assertion) (evalProxySuite modules).config.assertions + ); + forced = builtins.tryEval (builtins.deepSeq messages messages); + in + if forced.success then forced.value else [ "the fixture does not evaluate" ]; + # A bad config must fail *for the stated reason*: without the message, a case that stops + # evaluating for an unrelated reason (a renamed option, say) passes while testing nothing. + # Forcing the assertions rather than a whole system toplevel is also ~30x cheaper. + rejectsRaw = + expected: modules: + let + messages = failedAssertions modules; + in + if builtins.any (message: pkgs.lib.hasInfix expected message) messages then + true + else + throw ( + "proxy-suite checks: expected a failure mentioning ${builtins.toJSON expected}, got: " + + builtins.concatStringsSep " | " messages + ); + rejects = expected: modules: rejectsRaw expected ([ baseModule ] ++ modules); + rejectsProxySuite = + expected: proxySuiteConfig: + rejectsRaw expected [ + { + system.stateVersion = "26.05"; + services.proxy-suite = proxySuiteConfig; + } + ]; mkProxyCtlDerived = fixture: let @@ -235,6 +235,7 @@ in rg evalProxySuite forceEval + mkAssembly mkRouting mkRoutingRules mkRouteModeRules @@ -246,6 +247,10 @@ in mkTProxyNftRules mkPerAppZapretNftRules mkPerAppUserRules + ok + mkProxySuite + unitScript + startScript hasDirectDomain hasDirectIP hasRuleSet @@ -256,13 +261,16 @@ in packagePathMatches packageByPattern lineByPrefix - lineContaining shellValueByPrefix baseModule mkBadFixture mkBadFixtureRaw mkBadProxySuiteFixture mkFailingAssertions + failedAssertions + rejects + rejectsRaw + rejectsProxySuite mkProxyCtlDerived system nixpkgs diff --git a/nix/checks/local-proxy-auth.nix b/nix/checks/local-proxy-auth.nix index e54e1c1..1f29075 100644 --- a/nix/checks/local-proxy-auth.nix +++ b/nix/checks/local-proxy-auth.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -10,6 +11,7 @@ }: let + inherit (checkLib) startScript; generated = import ./read-generated.nix; localProxyAuthFixture = evalProxySuite [ @@ -21,9 +23,7 @@ let }; } ]; - localProxyAuthStartScript = generated.readDerivation ( - localProxyAuthFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + localProxyAuthStartScript = startScript localProxyAuthFixture; localProxyAuthBackendJqFilter = import ../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix { @@ -57,9 +57,7 @@ let _localProxyAuthPasswordFile = mkProxyCtlDerived localProxyAuthPasswordFileFixture; localProxyAuthPasswordFileWrapper = _localProxyAuthPasswordFile.wrapper; localProxyAuthPasswordFileScript = _localProxyAuthPasswordFile.script; - localProxyAuthPasswordFileStartScript = generated.readDerivation ( - localProxyAuthPasswordFileFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + localProxyAuthPasswordFileStartScript = startScript localProxyAuthPasswordFileFixture; invalidLocalProxyAuthAssertions = mkFailingAssertions mkBadFixture [ # Auth requires both username and a password source. diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index 056adea..e11f4cf 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -5,6 +5,7 @@ let inherit (checkLib) + ok mkRouting evalProxySuite mkRoutingRules @@ -25,13 +26,14 @@ let mkZapretBaseFor mkZapretBase packagePathMatches - packageByPattern shellValueByPrefix baseModule mkBadFixture mkBadFixtureRaw mkBadProxySuiteFixture mkFailingAssertions + rejects + rejectsProxySuite mkProxyCtlDerived ; @@ -47,6 +49,7 @@ let minimalSocksService = minimal.config.systemd.services."proxy-suite-socks"; coreProxyChecks = import ./core-proxy.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -62,6 +65,7 @@ let inherit (coreProxyChecks) ruDefaultConfig; routeModeChecks = import ./route-mode.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -74,6 +78,7 @@ let }; subscriptionChecks = import ./subscriptions.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -93,6 +98,7 @@ let }; localProxyAuthChecks = import ./local-proxy-auth.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -106,6 +112,7 @@ let }; sshProxyChecks = import ./ssh-proxy.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -117,6 +124,7 @@ let }; warpChecks = import ./warp.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -126,6 +134,7 @@ let }; torChecks = import ./tor.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -141,6 +150,7 @@ let }; proxyInboundsChecks = import ./proxy-inbounds.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -151,6 +161,7 @@ let }; perAppRoutingChecks = import ./per-app-routing.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -164,6 +175,7 @@ let mkZapretBaseFor mkBadFixture mkFailingAssertions + rejects minimalProxyCtlScript ; }; @@ -172,6 +184,7 @@ let inherit mkBadProxySuiteFixture mkFailingAssertions; }; chainingDnsChecks = import ./chaining-dns.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -184,7 +197,9 @@ let }; amneziaWgChecks = import ./amnezia-wg.nix { + inherit checkLib; inherit + rejectsProxySuite pkgs evalProxySuite mkBadProxySuiteFixture @@ -194,6 +209,7 @@ let }; amneziaWgOutboundChecks = import ./amnezia-wg-outbound.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -206,6 +222,7 @@ let }; globalProxyModeChecks = import ./global-proxy-modes.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -221,6 +238,7 @@ let }; zapretChecks = import ./zapret.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -246,6 +264,7 @@ let }; tgWsProxyChecks = import ./tg-ws-proxy.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -262,11 +281,12 @@ let }; serverModuleChecks = import ./server-module.nix { - inherit pkgs mkInboundsSpec; + inherit checkLib pkgs mkInboundsSpec; inherit (checkLib) system nixpkgs proxySuiteModule; }; xrayBackendChecks = import ./xray-backends.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -283,10 +303,7 @@ let validated = builtins.all (x: x) ( [ - ( - assert minimal.config.services.proxy-suite.proxy.listener.address == "127.0.0.1"; - true - ) + (ok (minimal.config.services.proxy-suite.proxy.listener.address == "127.0.0.1")) ] ++ coreProxyChecks.assertions ++ localProxyAuthChecks.assertions diff --git a/nix/checks/parsers.nix b/nix/checks/parsers.nix deleted file mode 100644 index 17049b6..0000000 --- a/nix/checks/parsers.nix +++ /dev/null @@ -1,57 +0,0 @@ -{ pkgs }: - -{ - build-outbound-parser = - pkgs.runCommand "build-outbound-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; } - '' - export PYTHONDONTWRITEBYTECODE=1 - export PYTHONPATH=${../../scripts}:$PYTHONPATH - python ${../../scripts/test-build-outbound.py} - touch "$out" - ''; - - build-inbound-renderer = - pkgs.runCommand "build-inbound-renderer-check" { nativeBuildInputs = [ pkgs.python3 ]; } - '' - export PYTHONDONTWRITEBYTECODE=1 - export PYTHONPATH=${../../scripts}:$PYTHONPATH - python ${../../scripts/test-build-inbound.py} - touch "$out" - ''; - - fetch-subscription-parser = - pkgs.runCommand "fetch-subscription-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; } - '' - export PYTHONDONTWRITEBYTECODE=1 - export PYTHONPATH=${../../scripts}:$PYTHONPATH - python ${../../scripts/test-fetch-subscription.py} - touch "$out" - ''; - - warp-outbound-parser = - pkgs.runCommand "warp-outbound-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; } - '' - export PYTHONDONTWRITEBYTECODE=1 - export PYTHONPATH=${../../scripts}:$PYTHONPATH - python ${../../scripts/test-warp-outbound.py} - touch "$out" - ''; - - amneziawg-config-parser = - pkgs.runCommand "amneziawg-config-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; } - '' - export PYTHONDONTWRITEBYTECODE=1 - export PYTHONPATH=${../../scripts}:$PYTHONPATH - python ${../../scripts/test-amneziawg-config.py} - touch "$out" - ''; - - awg-inbound-state = - pkgs.runCommand "awg-inbound-state-check" { nativeBuildInputs = [ pkgs.python3 ]; } - '' - export PYTHONDONTWRITEBYTECODE=1 - export PYTHONPATH=${../../scripts}:$PYTHONPATH - python ${../../scripts/test-awg-inbound.py} - touch "$out" - ''; -} diff --git a/nix/checks/per-app-routing-proxychains.nix b/nix/checks/per-app-routing-proxychains.nix index f06addd..cba4664 100644 --- a/nix/checks/per-app-routing-proxychains.nix +++ b/nix/checks/per-app-routing-proxychains.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -7,6 +8,7 @@ }: let + inherit (checkLib) ok; generated = import ./read-generated.nix; perAppRoutingProxychainsFixture = evalProxySuite [ @@ -67,20 +69,14 @@ in { assertions = [ # -- perAppRouting: proxychains/direct profile config is accepted -- - ( - assert perAppRoutingProxychainsFixture.config.services.proxy-suite.perAppRouting.enable; - true - ) + (ok (perAppRoutingProxychainsFixture.config.services.proxy-suite.perAppRouting.enable)) ( assert builtins.length perAppRoutingProxychainsFixture.config.services.proxy-suite.perAppRouting.profiles == 2; true ) - ( - assert builtins.length perAppRoutingProxychainsProfiles == 2; - true - ) + (ok (builtins.length perAppRoutingProxychainsProfiles == 2)) # -- perAppRouting: createDefaultProfiles injects curated proxychains profile -- ( @@ -91,10 +87,7 @@ in ) # -- perAppRouting: createDefaultProfiles = false injects no curated profiles -- - ( - assert builtins.length perAppRoutingNoDefaultProfiles == 0; - true - ) + (ok (builtins.length perAppRoutingNoDefaultProfiles == 0)) # -- perAppRouting: proxy-ctl script embeds wrap/apps commands -- ( @@ -115,15 +108,9 @@ in ) # -- proxy-ctl: restart skips services that are not present in zapret-only or tg-only builds -- - ( - assert pkgs.lib.hasInfix "proxy-suite-tg-ws-proxy" minimalProxyCtlScript; - true - ) + (ok (pkgs.lib.hasInfix "proxy-suite-tg-ws-proxy" minimalProxyCtlScript)) # -- perAppRouting: generated proxy-ctl script dispatches through proxychains4 -- - ( - assert pkgs.lib.hasInfix "export PROXYCHAINS_QUIET_ARG=-q" perAppRoutingProxychainsScript; - true - ) + (ok (pkgs.lib.hasInfix "export PROXYCHAINS_QUIET_ARG=-q" perAppRoutingProxychainsScript)) ]; } diff --git a/nix/checks/per-app-routing-tproxy.nix b/nix/checks/per-app-routing-tproxy.nix index d7502fa..455989e 100644 --- a/nix/checks/per-app-routing-tproxy.nix +++ b/nix/checks/per-app-routing-tproxy.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -7,6 +8,7 @@ }: let + inherit (checkLib) ok; generated = import ./read-generated.nix; perAppRoutingTproxyFixture = evalProxySuite [ @@ -51,10 +53,7 @@ in ) # -- perAppRouting: generated proxy-ctl script dispatches tproxy profiles through systemd slices -- - ( - assert pkgs.lib.hasInfix "PER_APP_ROUTING_TPROXY_ENABLED" perAppRoutingTproxyScript; - true - ) + (ok (pkgs.lib.hasInfix "PER_APP_ROUTING_TPROXY_ENABLED" perAppRoutingTproxyScript)) # -- perAppRouting: app TProxy service and helper units are created -- ( diff --git a/nix/checks/per-app-routing-tun.nix b/nix/checks/per-app-routing-tun.nix index ee23222..d4e19b6 100644 --- a/nix/checks/per-app-routing-tun.nix +++ b/nix/checks/per-app-routing-tun.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -9,6 +10,7 @@ }: let + inherit (checkLib) ok; generated = import ./read-generated.nix; perAppRoutingTunFixture = evalProxySuite [ @@ -79,10 +81,7 @@ in ) # -- perAppRouting: generated proxy-ctl script dispatches tun profiles through systemd slices -- - ( - assert pkgs.lib.hasInfix "PER_APP_ROUTING_TUN_ENABLED" perAppRoutingTunScript; - true - ) + (ok (pkgs.lib.hasInfix "PER_APP_ROUTING_TUN_ENABLED" perAppRoutingTunScript)) # -- perAppRouting: user mark script installs fwmark + conntrack mark rules -- ( @@ -122,10 +121,7 @@ in ) # -- perAppRouting: app TUN uses local domain resolver and avoids global auto-routing -- - ( - assert perAppRoutingTunConfig.route.default_domain_resolver == "local"; - true - ) + (ok (perAppRoutingTunConfig.route.default_domain_resolver == "local")) # -- perAppRouting: app TUN does not set outbound routing marks when TProxy is disabled -- ( @@ -165,12 +161,11 @@ in # -- perAppRouting: wrapped apps' replies to incoming connections skip the mark (and the # user rule appended after it), so they leave directly -- - ( - assert pkgs.lib.hasInfix "ct direction reply return" ( + (ok ( + pkgs.lib.hasInfix "ct direction reply return" ( builtins.head (pkgs.lib.splitString "ct mark 16 meta mark set 16" perAppRoutingTunNftRules) - ); - true - ) + ) + )) # -- perAppRouting: wrapped apps' DNS reaches the app TUN even when the resolver sits on # a local or reserved address, and their local IPv6 still leaves directly -- @@ -191,9 +186,6 @@ in ) # -- perAppRouting: app TUN enables nftables -- - ( - assert perAppRoutingTunFixture.config.networking.nftables.enable; - true - ) + (ok (perAppRoutingTunFixture.config.networking.nftables.enable)) ]; } diff --git a/nix/checks/per-app-routing-validation-resources.nix b/nix/checks/per-app-routing-validation-resources.nix index 54f095a..6ccf96e 100644 --- a/nix/checks/per-app-routing-validation-resources.nix +++ b/nix/checks/per-app-routing-validation-resources.nix @@ -1,102 +1,102 @@ -{ - mkBadFixture, - mkFailingAssertions, -}: +# Marks and route tables per-app routing must not share with the global backends. Each case +# names the assertion it expects, so a case that stops evaluating for another reason fails. +{ rejects }: { - assertions = mkFailingAssertions mkBadFixture [ - # app TUN fwmark must not collide with global TProxy proxyMark. - [ - { - services.proxy-suite = { - proxy.tproxy.proxyMark = 7; - proxy.tun.perApp = { - enable = true; - fwmark = 7; - }; - perAppRouting.enable = true; - }; - } - ] - - # app TProxy fwmark must not collide with global TProxy proxyMark. - [ + assertions = [ + (rejects "perAppRouting.tun.fwmark must differ from proxy.tproxy.proxyMark" [ { services.proxy-suite = { proxy.tproxy = { + enable = true; + proxyMark = 7; + }; + perAppRouting = { + enable = true; + tun = { + enable = true; + fwmark = 7; + }; + }; + }; + } + ]) + (rejects "perAppRouting.tproxy.fwmark must differ from proxy.tproxy.proxyMark" [ + { + services.proxy-suite = { + proxy.tproxy = { + enable = true; proxyMark = 8; - perApp = { + }; + perAppRouting = { + enable = true; + tproxy = { enable = true; fwmark = 8; }; }; - perAppRouting.enable = true; }; } - ] - - # app TUN and TProxy backends must use distinct marks and route tables. - [ + ]) + (rejects "perAppRouting.tun.fwmark and perAppRouting.tproxy.fwmark must differ" [ { - services.proxy-suite = { - proxy.tun.perApp = { + services.proxy-suite.perAppRouting = { + enable = true; + tun = { enable = true; fwmark = 11; }; - proxy.tproxy.perApp = { + tproxy = { enable = true; fwmark = 11; }; - perAppRouting.enable = true; }; } - ] - [ + ]) + (rejects "perAppRouting.tun.routeTable and perAppRouting.tproxy.routeTable must differ" [ { - services.proxy-suite = { - proxy.tun.perApp = { + services.proxy-suite.perAppRouting = { + enable = true; + tun = { enable = true; routeTable = 100; }; - proxy.tproxy.perApp = { + tproxy = { enable = true; routeTable = 100; }; - perAppRouting.enable = true; }; } - ] - - # per-app zapret marks must not collide with TUN/TProxy marks. - [ + ]) + (rejects "perAppRouting.tun.fwmark and perAppRouting.zapret.filterMark must differ" [ { - services.proxy-suite = { - proxy.tun.perApp = { + services.proxy-suite.perAppRouting = { + enable = true; + tun = { enable = true; fwmark = 12; }; - zapret.perApp = { + zapret = { enable = true; filterMark = 12; }; - perAppRouting.enable = true; }; } - ] - [ + ]) + (rejects "perAppRouting.tproxy.fwmark and perAppRouting.zapret.filterMark must differ" [ { - services.proxy-suite = { - proxy.tproxy.perApp = { + services.proxy-suite.perAppRouting = { + enable = true; + tproxy = { enable = true; fwmark = 13; }; - zapret.perApp = { + zapret = { enable = true; filterMark = 13; }; - perAppRouting.enable = true; }; } - ] + ]) ]; } diff --git a/nix/checks/per-app-routing-validation.nix b/nix/checks/per-app-routing-validation.nix index bb4f88c..62490b9 100644 --- a/nix/checks/per-app-routing-validation.nix +++ b/nix/checks/per-app-routing-validation.nix @@ -1,15 +1,15 @@ { + checkLib, mkBadFixture, mkFailingAssertions, + rejects, }: let profileChecks = import ./per-app-routing-validation-profiles.nix { inherit mkBadFixture mkFailingAssertions; }; - resourceChecks = import ./per-app-routing-validation-resources.nix { - inherit mkBadFixture mkFailingAssertions; - }; + resourceChecks = import ./per-app-routing-validation-resources.nix { inherit rejects; }; in { assertions = profileChecks.assertions ++ resourceChecks.assertions; diff --git a/nix/checks/per-app-routing-zapret.nix b/nix/checks/per-app-routing-zapret.nix index a0a0949..2339b34 100644 --- a/nix/checks/per-app-routing-zapret.nix +++ b/nix/checks/per-app-routing-zapret.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -10,6 +11,7 @@ }: let + inherit (checkLib) ok; generated = import ./read-generated.nix; perAppRoutingZapretFixture = evalProxySuite [ @@ -168,10 +170,7 @@ in ) # -- perAppRouting: generated proxy-ctl script dispatches zapret profiles through systemd slices -- - ( - assert pkgs.lib.hasInfix "PER_APP_ROUTING_ZAPRET_ENABLED" perAppRoutingZapretScript; - true - ) + (ok (pkgs.lib.hasInfix "PER_APP_ROUTING_ZAPRET_ENABLED" perAppRoutingZapretScript)) # -- perAppRouting: app zapret service and helper units are created -- ( @@ -213,10 +212,7 @@ in ) # -- perAppRouting: app zapret startup installs nftables backend -- - ( - assert pkgs.lib.hasInfix "proxy_suite_per_app_zapret_mark" perAppRoutingZapretStartScript; - true - ) + (ok (pkgs.lib.hasInfix "proxy_suite_per_app_zapret_mark" perAppRoutingZapretStartScript)) ]; diff --git a/nix/checks/per-app-routing.nix b/nix/checks/per-app-routing.nix index ef8eddf..1e8d4c6 100644 --- a/nix/checks/per-app-routing.nix +++ b/nix/checks/per-app-routing.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -11,11 +12,13 @@ mkZapretBaseFor, mkBadFixture, mkFailingAssertions, + rejects, minimalProxyCtlScript, }: let tunChecks = import ./per-app-routing-tun.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -27,6 +30,7 @@ let ; }; tproxyChecks = import ./per-app-routing-tproxy.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -36,6 +40,7 @@ let ; }; zapretChecks = import ./per-app-routing-zapret.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -48,9 +53,11 @@ let ; }; validationChecks = import ./per-app-routing-validation.nix { - inherit mkBadFixture mkFailingAssertions; + inherit checkLib; + inherit mkBadFixture mkFailingAssertions rejects; }; userControlChecks = import ./user-control.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -58,6 +65,7 @@ let ; }; proxychainsChecks = import ./per-app-routing-proxychains.nix { + inherit checkLib; inherit pkgs evalProxySuite diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index 5d14163..919b1d6 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -7,6 +8,7 @@ }: let + inherit (checkLib) ok; inherit (pkgs) lib; realityListener = { @@ -515,29 +517,14 @@ let assertions = [ # Listeners are rendered at start time. - ( - assert relayConfig.inbounds == [ ]; - true - ) + (ok (relayConfig.inbounds == [ ])) # AsIs when relayed through sing-box; IPOnDemand when XRay dials (see the template). - ( - assert relayConfig.routing.domainStrategy == "AsIs"; - true - ) - ( - assert exitConfig.routing.domainStrategy == "IPOnDemand"; - true - ) + (ok (relayConfig.routing.domainStrategy == "AsIs")) + (ok (exitConfig.routing.domainStrategy == "IPOnDemand")) - ( - assert hasOutbound relayConfig "proxy"; - true - ) - ( - assert (ruleByTag relayConfig "inbound-final").outboundTag == "proxy"; - true - ) + (ok (hasOutbound relayConfig "proxy")) + (ok ((ruleByTag relayConfig "inbound-final").outboundTag == "proxy")) ( assert (builtins.head (builtins.filter (ob: ob.tag == "proxy") relayConfig.outbounds)).protocol == "socks"; @@ -556,36 +543,15 @@ let ) # A pure exit node needs no proxy outbound at all. - ( - assert !hasOutbound exitConfig "proxy"; - true - ) - ( - assert (ruleByTag exitConfig "inbound-final").outboundTag == "direct"; - true - ) + (ok (!hasOutbound exitConfig "proxy")) + (ok ((ruleByTag exitConfig "inbound-final").outboundTag == "direct")) # Safety rules come first. - ( - assert builtins.head (ruleTags relayConfig) == "inbound-block-private"; - true - ) - ( - assert (ruleByTag relayConfig "inbound-block-private").outboundTag == "block"; - true - ) - ( - assert (ruleByTag relayConfig "inbound-block-ru-domain").domain == [ "geosite:category-ru" ]; - true - ) - ( - assert (ruleByTag relayConfig "inbound-block-ru-ip").ip == [ "geoip:ru" ]; - true - ) - ( - assert !builtins.elem "inbound-block-private" (ruleTags unguardedConfig); - true - ) + (ok (builtins.head (ruleTags relayConfig) == "inbound-block-private")) + (ok ((ruleByTag relayConfig "inbound-block-private").outboundTag == "block")) + (ok ((ruleByTag relayConfig "inbound-block-ru-domain").domain == [ "geosite:category-ru" ])) + (ok ((ruleByTag relayConfig "inbound-block-ru-ip").ip == [ "geoip:ru" ])) + (ok (!builtins.elem "inbound-block-private" (ruleTags unguardedConfig))) # serverAddress is exempt after blockPrivate, before the country blocks. ( assert @@ -596,10 +562,7 @@ let ]; true ) - ( - assert (ruleByTag namedConfig "inbound-server-address-direct").domain == [ "full:vpn.example.ru" ]; - true - ) + (ok ((ruleByTag namedConfig "inbound-server-address-direct").domain == [ "full:vpn.example.ru" ])) # Names that resolve private are refused where XRay dials them itself. ( assert @@ -612,64 +575,25 @@ let true ) # Only the listener ports, not every service on this host. - ( - assert (ruleByTag namedConfig "inbound-server-address-direct").port == "443"; - true - ) - ( - assert (ruleByTag blockedConfig "inbound-proxy-domain").inboundTag == [ "open" ]; - true - ) - ( - assert (ruleByTag blockedConfig "inbound-server-address-direct").inboundTag == [ "open" ]; - true - ) + (ok ((ruleByTag namedConfig "inbound-server-address-direct").port == "443")) + (ok ((ruleByTag blockedConfig "inbound-proxy-domain").inboundTag == [ "open" ])) + (ok ((ruleByTag blockedConfig "inbound-server-address-direct").inboundTag == [ "open" ])) # No address to exempt when it is detected at runtime instead. - ( - assert !builtins.elem "inbound-server-address-direct" (ruleTags relayConfig); - true - ) - ( - assert (ruleByTag ipNamedConfig "inbound-server-address-direct").ip == [ "82.146.44.102" ]; - true - ) - ( - assert !builtins.elem "inbound-block-ru-domain" (ruleTags unguardedConfig); - true - ) + (ok (!builtins.elem "inbound-server-address-direct" (ruleTags relayConfig))) + (ok ((ruleByTag ipNamedConfig "inbound-server-address-direct").ip == [ "82.146.44.102" ])) + (ok (!builtins.elem "inbound-block-ru-domain" (ruleTags unguardedConfig))) # A per-listener via becomes its own rule; listeners on the default do not. - ( - assert builtins.elem "inbound-via-local-exit" (ruleTags mixedConfig); - true - ) - ( - assert !builtins.elem "inbound-via-relayed" (ruleTags mixedConfig); - true - ) - ( - assert (ruleByTag mixedConfig "inbound-via-local-exit").inboundTag == [ "local-exit" ]; - true - ) - ( - assert (ruleByTag mixedConfig "inbound-via-local-exit").outboundTag == "direct"; - true - ) + (ok (builtins.elem "inbound-via-local-exit" (ruleTags mixedConfig))) + (ok (!builtins.elem "inbound-via-relayed" (ruleTags mixedConfig))) + (ok ((ruleByTag mixedConfig "inbound-via-local-exit").inboundTag == [ "local-exit" ])) + (ok ((ruleByTag mixedConfig "inbound-via-local-exit").outboundTag == "direct")) # The pinned listener gets its own rule; the default one rides the final rule. - ( - assert (ruleByTag pinnedConfig "inbound-via-through-de").outboundTag == "de-vps"; - true - ) - ( - assert (ruleByTag pinnedConfig "inbound-final").outboundTag == "nl-vps"; - true - ) + (ok ((ruleByTag pinnedConfig "inbound-via-through-de").outboundTag == "de-vps")) + (ok ((ruleByTag pinnedConfig "inbound-final").outboundTag == "nl-vps")) # Pinned outbounds are injected at start and need no local proxy. - ( - assert !hasOutbound pinnedConfig "proxy"; - true - ) + (ok (!hasOutbound pinnedConfig "proxy")) ( assert outboundTags pinnedConfig == [ @@ -690,46 +614,19 @@ let ) # The final rule always comes last. - ( - assert lib.last (ruleTags relayConfig) == "inbound-final"; - true - ) - ( - assert lib.last (ruleTags mixedConfig) == "inbound-final"; - true - ) + (ok (lib.last (ruleTags relayConfig) == "inbound-final")) + (ok (lib.last (ruleTags mixedConfig) == "inbound-final")) # Without zapret running there is nothing to route around it. - ( - assert !builtins.elem "inbound-zapret-direct-domain" (ruleTags relayConfig); - true - ) + (ok (!builtins.elem "inbound-zapret-direct-domain" (ruleTags relayConfig))) # The spec carries secret paths, never their contents. - ( - assert builtins.length relaySpec.listeners == 1; - true - ) - ( - assert (builtins.head relaySpec.listeners).tag == "vless-in"; - true - ) - ( - assert (builtins.head relaySpec.listeners).listen == "::"; - true - ) - ( - assert (builtins.head (builtins.head relaySpec.listeners).users).uuidFile == "/run/secrets/uuid"; - true - ) - ( - assert (builtins.head relaySpec.listeners).reality.privateKeyFile == "/run/secrets/reality-key"; - true - ) - ( - assert relaySpec.shareLinks; - true - ) + (ok (builtins.length relaySpec.listeners == 1)) + (ok ((builtins.head relaySpec.listeners).tag == "vless-in")) + (ok ((builtins.head relaySpec.listeners).listen == "::")) + (ok ((builtins.head (builtins.head relaySpec.listeners).users).uuidFile == "/run/secrets/uuid")) + (ok ((builtins.head relaySpec.listeners).reality.privateKeyFile == "/run/secrets/reality-key")) + (ok (relaySpec.shareLinks)) # Firewall: TCP for every listener, UDP only where the protocol uses it. ( @@ -748,33 +645,15 @@ let ]; true ) - ( - assert wsListener.port == 10002 && wsListener.sharePort == 443; - true - ) - ( - assert noFirewallFixture.config.networking.firewall.allowedTCPPorts == [ ]; - true - ) + (ok (wsListener.port == 10002 && wsListener.sharePort == 443)) + (ok (noFirewallFixture.config.networking.firewall.allowedTCPPorts == [ ])) # The unit exists, and only waits on the client stack when it relays. - ( - assert (service relayFixture).wantedBy == [ "multi-user.target" ]; - true - ) - ( - assert builtins.elem "proxy-suite-socks.service" (service relayFixture).after; - true - ) - ( - assert !builtins.elem "proxy-suite-socks.service" (service exitFixture).after; - true - ) + (ok ((service relayFixture).wantedBy == [ "multi-user.target" ])) + (ok (builtins.elem "proxy-suite-socks.service" (service relayFixture).after)) + (ok (!builtins.elem "proxy-suite-socks.service" (service exitFixture).after)) # Not `requires`: direct-routed listeners keep serving if the client is down. - ( - assert (service relayFixture).requires == [ ]; - true - ) + (ok ((service relayFixture).requires == [ ])) # A stop collects what XRay counted since the last timer run. ( assert @@ -793,44 +672,20 @@ let ) # AmneziaWG: the spec carries each listener's loopback inbound, in listener order. - ( - assert (awgSpecListener "home").amneziaWg.internalPort == 18700; - true - ) - ( - assert (awgSpecListener "roam").amneziaWg.internalPort == 18701; - true - ) - ( - assert (awgSpecListener "home").amneziaWg.internalListen == "::"; - true - ) - ( - assert (awgSpecListener "roam").amneziaWg.internalListen == "127.0.0.1"; - true - ) - ( - assert (awgSpecListener "home").amneziaWg.fwmark == 2; - true - ) - ( - assert (awgSpecListener "home").amneziaWg.interfaceName == "awgi-home"; - true - ) + (ok ((awgSpecListener "home").amneziaWg.internalPort == 18700)) + (ok ((awgSpecListener "roam").amneziaWg.internalPort == 18701)) + (ok ((awgSpecListener "home").amneziaWg.internalListen == "::")) + (ok ((awgSpecListener "roam").amneziaWg.internalListen == "127.0.0.1")) + (ok ((awgSpecListener "home").amneziaWg.fwmark == 2)) + (ok ((awgSpecListener "home").amneziaWg.interfaceName == "awgi-home")) ( assert (awgSpecListener "roam").amneziaWg.stateFile == "/var/lib/proxy-suite/awg-inbounds/roam/state.json"; true ) - ( - assert !((awgSpecListener "vless-in") ? amneziaWg); - true - ) + (ok (!((awgSpecListener "vless-in") ? amneziaWg))) # UDP only, and the interfaces past the host firewall. - ( - assert awgFixture.config.networking.firewall.allowedTCPPorts == [ 443 ]; - true - ) + (ok (awgFixture.config.networking.firewall.allowedTCPPorts == [ 443 ])) ( assert lib.sort lib.lessThan awgFixture.config.networking.firewall.allowedUDPPorts == [ @@ -844,38 +699,21 @@ let assert builtins.elem "awgi-roam" awgFixture.config.networking.firewall.trustedInterfaces; true ) - ( - assert lib.hasInfix ''iifname "awgi-home" accept'' - awgFixture.config.networking.firewall.extraReversePathFilterRules; - true - ) + (ok ( + lib.hasInfix ''iifname "awgi-home" accept'' awgFixture.config.networking.firewall.extraReversePathFilterRules + )) # The interfaces come up before XRay renders their links. - ( - assert builtins.elem "proxy-suite-inbounds-awg.service" (service awgFixture).after; - true - ) - ( - assert builtins.elem "proxy-suite-inbounds-awg.service" (service awgFixture).wants; - true - ) - ( - assert !(relayFixture.config.systemd.services ? "proxy-suite-inbounds-awg"); - true - ) + (ok (builtins.elem "proxy-suite-inbounds-awg.service" (service awgFixture).after)) + (ok (builtins.elem "proxy-suite-inbounds-awg.service" (service awgFixture).wants)) + (ok (!(relayFixture.config.systemd.services ? "proxy-suite-inbounds-awg"))) ( assert lib.hasInfix "rule add pref 8990 fwmark 20 table 103" (awgStartScript awgFixture); assert lib.hasInfix "awg_inbound.py prepare" (awgStartScript awgFixture); true ) # IPv6 routing only where a listener has IPv6. - ( - assert lib.hasInfix "-6 rule add pref 8990" (awgStartScript awgFixture); - true - ) - ( - assert !lib.hasInfix "-6 rule add pref 8990" (awgStartScript awgProxyFixture); - true - ) + (ok (lib.hasInfix "-6 rule add pref 8990" (awgStartScript awgFixture))) + (ok (!lib.hasInfix "-6 rule add pref 8990" (awgStartScript awgProxyFixture))) # Transparent sockets only where there is something to divert. ( assert lib.hasInfix "net_admin" (readInboundsStart awgFixture); @@ -883,18 +721,9 @@ let true ) # Forwarding only for "lan" listeners. - ( - assert awgFixture.config.boot.kernel.sysctl."net.ipv4.ip_forward" == 1; - true - ) - ( - assert awgFixture.config.boot.kernel.sysctl."net.ipv6.conf.all.forwarding" == 1; - true - ) - ( - assert !(awgProxyFixture.config.services.proxy-suite.internal.sysctl ? "net.ipv4.ip_forward"); - true - ) + (ok (awgFixture.config.boot.kernel.sysctl."net.ipv4.ip_forward" == 1)) + (ok (awgFixture.config.boot.kernel.sysctl."net.ipv6.conf.all.forwarding" == 1)) + (ok (!(awgProxyFixture.config.services.proxy-suite.internal.sysctl ? "net.ipv4.ip_forward"))) # "lan" clients reach private networks and each other natively, "proxy" clients nothing but via. ( let @@ -914,10 +743,7 @@ let assert !lib.hasInfix "10.67.0.0/24 oifname" rules; true ) - ( - assert !lib.hasInfix "masquerade" (awgRules awgProxyFixture); - true - ) + (ok (!lib.hasInfix "masquerade" (awgRules awgProxyFixture))) ] ++ failing; diff --git a/nix/checks/python-tests.nix b/nix/checks/python-tests.nix new file mode 100644 index 0000000..d6cd5b7 --- /dev/null +++ b/nix/checks/python-tests.nix @@ -0,0 +1,117 @@ +# The Python unit tests, as Nix checks. Every entry is the same runCommand: the test file, the +# interpreter (with the packages it imports) and the env it needs. +{ pkgs }: + +let + scripts = ../../scripts; + proxyCtl = ../../pkgs/proxy-ctl; + + mkPythonCheck = + name: + { + file, + drv ? name, + python ? pkgs.python3, + env ? { }, + extraInputs ? [ ], + buildInputs ? [ ], + }: + pkgs.runCommand "${drv}-check" + { + nativeBuildInputs = [ python ] ++ extraInputs; + inherit buildInputs; + } + '' + export PYTHONDONTWRITEBYTECODE=1 + ${pkgs.lib.concatStringsSep "\n" ( + pkgs.lib.mapAttrsToList (variable: value: "export ${variable}=${value}") env + )} + python ${file} + touch "$out" + ''; + + withPath = path: { PYTHONPATH = "${path}:$PYTHONPATH"; }; + singBox = { + SING_BOX = "${pkgs.sing-box}/bin/sing-box"; + }; +in +pkgs.lib.mapAttrs mkPythonCheck { + # The runtime helpers the module's start scripts call: share-link parsing, inbound and + # AmneziaWG rendering, subscription fetching. + build-outbound-parser = { + file = "${scripts}/test-build-outbound.py"; + env = withPath scripts; + }; + build-inbound-renderer = { + file = "${scripts}/test-build-inbound.py"; + env = withPath scripts; + }; + fetch-subscription-parser = { + file = "${scripts}/test-fetch-subscription.py"; + env = withPath scripts; + }; + warp-outbound-parser = { + file = "${scripts}/test-warp-outbound.py"; + env = withPath scripts; + }; + amneziawg-config-parser = { + file = "${scripts}/test-amneziawg-config.py"; + env = withPath scripts; + }; + awg-inbound-state = { + file = "${scripts}/test-awg-inbound.py"; + env = withPath scripts; + }; + # The NFQWS_OPT rewrites the zapret v1 package build applies. + patch-zapret-config = { + file = "${scripts}/test-patch-zapret-config.py"; + env = withPath scripts; + }; + + # 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 = { + drv = "proxy-suite-proxy-ctl-unit"; + file = "${proxyCtl}/test_proxy_ctl.py"; + env = singBox; + }; + # proxy-suitectl, nix-on-droid's service manager: real processes restarted, timed and stopped. + proxy-suite-supervisor-unit = { + file = "${proxyCtl}/test_proxy_supervisor.py"; + env.HOME = "\"$TMPDIR\""; + }; + # proxy_export: the running config made portable, and sing-box still accepts it. + proxy-export-unit = { + drv = "proxy-suite-proxy-export-unit"; + file = "${proxyCtl}/test_proxy_export.py"; + env = singBox // { + PYTHONPATH = "${proxyCtl}"; + }; + }; + # proxy-tui driven headless: keys turn into the right proxy-ctl argv. + proxy-tui-unit = { + drv = "proxy-suite-proxy-tui-unit"; + file = "${proxyCtl}/test_proxy_tui.py"; + python = pkgs.python3.withPackages (ps: [ ps.textual ]); + env.PYTHONPATH = "${proxyCtl}"; + }; + # proxy_model: the status strip, tab loads and the tray menu tree, without a UI toolkit. + proxy-model-unit = { + drv = "proxy-suite-proxy-model-unit"; + file = "${proxyCtl}/test_proxy_model.py"; + env.PYTHONPATH = "${proxyCtl}"; + }; + # proxy_gui and proxy_sni import against GTK4/libadwaita, the D-Bus interfaces parse, and the + # tray menu serializes to dbusmenu's layout type. No display needed. + proxy-gui-smoke = { + drv = "proxy-suite-proxy-gui-smoke"; + file = "${proxyCtl}/test_proxy_gui.py"; + python = pkgs.python3.withPackages (ps: [ ps.pygobject3 ]); + extraInputs = [ pkgs.gobject-introspection ]; + buildInputs = [ + pkgs.gtk4 + pkgs.libadwaita + ]; + env.PYTHONPATH = "${proxyCtl}"; + }; +} diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index 9f3f411..1ca5899 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -8,6 +8,22 @@ controlModuleSource, }: +let + # Every proxy-ctl CLI check runs against the same disabled-feature defaults; only the + # files and the feature under test differ. + perAppRoutingOff = '' + PER_APP_ROUTING_ENABLED="0" \ + PER_APP_ROUTING_PROXYCHAINS_ENABLED="0" \ + PER_APP_ROUTING_TUN_ENABLED="0" \ + PER_APP_ROUTING_TPROXY_ENABLED="0" \ + PER_APP_ROUTING_ZAPRET_ENABLED="0" \ + PER_APP_ROUTING_PROFILES_FILE="$PWD/profiles.json" \ + PROXYCHAINS_CONFIG="$PWD/proxychains.conf" \ + PROXYCHAINS_QUIET_ARG="" \ + ROUTE_MODE_STATE_FILE="$PWD/route-mode" \ + DEFAULT_ROUTE_MODE="blacklist" \ + ''; +in { no-secrets = pkgs.runCommand "proxy-suite-no-secrets-check" { } '' repo_root=${../../.} @@ -65,17 +81,7 @@ SUB_CACHE_DIR="$PWD/cache" \ CLASH_API="http://127.0.0.1:9090" \ SELECTION="first" \ - PER_APP_ROUTING_ENABLED="0" \ - PER_APP_ROUTING_PROXYCHAINS_ENABLED="0" \ - PER_APP_ROUTING_TUN_ENABLED="0" \ - PER_APP_ROUTING_TPROXY_ENABLED="0" \ - PER_APP_ROUTING_ZAPRET_ENABLED="0" \ - PER_APP_ROUTING_PROFILES_FILE="$PWD/profiles.json" \ - PROXYCHAINS_CONFIG="$PWD/proxychains.conf" \ - PROXYCHAINS_QUIET_ARG="" \ - ROUTE_MODE_STATE_FILE="$PWD/route-mode" \ - DEFAULT_ROUTE_MODE="blacklist" \ - python3 "$proxy_ctl" proxy subs list > output + ${perAppRoutingOff} python3 "$proxy_ctl" proxy subs list > output # The old spelling still dispatches. env SUB_TAGS_FILE="$PWD/tags.json" SUB_CACHE_DIR="$PWD/cache" \ python3 "$proxy_ctl" subscription list | cmp - output @@ -137,17 +143,7 @@ USER_CONTROL_GROUP="proxy-suite" \ CLASH_API="http://127.0.0.1:1" \ SELECTION="urltest" \ - PER_APP_ROUTING_ENABLED="0" \ - PER_APP_ROUTING_PROXYCHAINS_ENABLED="0" \ - PER_APP_ROUTING_TUN_ENABLED="0" \ - PER_APP_ROUTING_TPROXY_ENABLED="0" \ - PER_APP_ROUTING_ZAPRET_ENABLED="0" \ - PER_APP_ROUTING_PROFILES_FILE="$PWD/profiles.json" \ - PROXYCHAINS_CONFIG="$PWD/proxychains.conf" \ - PROXYCHAINS_QUIET_ARG="" \ - ROUTE_MODE_STATE_FILE="$PWD/route-mode" \ - DEFAULT_ROUTE_MODE="blacklist" \ - python3 "$proxy_ctl" "$@" + ${perAppRoutingOff} python3 "$proxy_ctl" "$@" } # Listing works from the inventory alone, with no Clash API answering. @@ -453,75 +449,6 @@ 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 SING_BOX=${pkgs.sing-box}/bin/sing-box - export PYTHONDONTWRITEBYTECODE=1 - python ${../../pkgs/proxy-ctl}/test_proxy_ctl.py - touch "$out" - ''; - - # proxy-suitectl, nix-on-droid's service manager: real processes restarted, timed and stopped. - proxy-suite-supervisor-unit = - pkgs.runCommand "proxy-suite-supervisor-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } - '' - export PYTHONDONTWRITEBYTECODE=1 HOME="$TMPDIR" - python ${../../pkgs/proxy-ctl}/test_proxy_supervisor.py - touch "$out" - ''; - - # proxy_export: the running config made portable, and sing-box still accepts it. - proxy-export-unit = - pkgs.runCommand "proxy-suite-proxy-export-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } - '' - export SING_BOX=${pkgs.sing-box}/bin/sing-box - export PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=${../../pkgs/proxy-ctl} - python ${../../pkgs/proxy-ctl}/test_proxy_export.py - touch "$out" - ''; - - # proxy-tui driven headless: keys turn into the right proxy-ctl argv. - proxy-tui-unit = - pkgs.runCommand "proxy-suite-proxy-tui-unit-check" - { nativeBuildInputs = [ (pkgs.python3.withPackages (ps: [ ps.textual ])) ]; } - '' - export PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=${../../pkgs/proxy-ctl} - python ${../../pkgs/proxy-ctl}/test_proxy_tui.py - touch "$out" - ''; - - # proxy_model: the status strip, tab loads and the tray menu tree, without a UI toolkit. - proxy-model-unit = - pkgs.runCommand "proxy-suite-proxy-model-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } - '' - export PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=${../../pkgs/proxy-ctl} - python ${../../pkgs/proxy-ctl}/test_proxy_model.py - touch "$out" - ''; - - # proxy_gui and proxy_sni import against GTK4/libadwaita, the D-Bus interfaces parse, - # and the tray menu serializes to dbusmenu's layout type. No display needed. - proxy-gui-smoke = - pkgs.runCommand "proxy-suite-proxy-gui-smoke-check" - { - nativeBuildInputs = [ - (pkgs.python3.withPackages (ps: [ ps.pygobject3 ])) - pkgs.gobject-introspection - ]; - buildInputs = [ - pkgs.gtk4 - pkgs.libadwaita - ]; - } - '' - export PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=${../../pkgs/proxy-ctl} - python ${../../pkgs/proxy-ctl}/test_proxy_gui.py - touch "$out" - ''; - # autoProxy slowness routing: sampler and judge. autoproxy-slowness = pkgs.runCommand "proxy-suite-autoproxy-slowness-check" { nativeBuildInputs = [ pkgs.jq ]; } diff --git a/nix/checks/route-mode.nix b/nix/checks/route-mode.nix index e1c6cc0..276938c 100644 --- a/nix/checks/route-mode.nix +++ b/nix/checks/route-mode.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -9,6 +10,7 @@ }: let + inherit (checkLib) ok startScript; generated = import ./read-generated.nix; routeModeFixture = evalProxySuite [ @@ -38,9 +40,7 @@ let }; } ]; - routeModeStartScript = generated.readDerivation ( - routeModeFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + routeModeStartScript = startScript routeModeFixture; routeModeBackendJqFilter = import ../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix { @@ -81,11 +81,9 @@ in ) # proxy-ctl help/status exposes default plus the explicit route modes. - ( - assert pkgs.lib.hasInfix "proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]" - minimalProxyCtlScript; - true - ) + (ok ( + pkgs.lib.hasInfix "proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]" minimalProxyCtlScript + )) # The socks start script includes every override branch and uses volatile state. ( @@ -118,9 +116,9 @@ in in assert !(setterSvc.serviceConfig ? RuntimeDirectory); assert pkgs.lib.hasInfix "/run/proxy-suite/route-mode" routeModeSetterScript; - assert pkgs.lib.hasInfix "default)" routeModeSetterScript; - assert pkgs.lib.hasInfix "all-proxy)" routeModeSetterScript; - assert pkgs.lib.hasInfix "all-bypass)" routeModeSetterScript; + # One case arm lists every mode the setter accepts. + assert pkgs.lib.hasInfix "default | whitelist | blacklist | all-proxy | all-bypass)" + routeModeSetterScript; true ) diff --git a/nix/checks/server-module.nix b/nix/checks/server-module.nix index c54bca0..9b44196 100644 --- a/nix/checks/server-module.nix +++ b/nix/checks/server-module.nix @@ -1,6 +1,7 @@ # nixosModules.server as the installer writes it: once for an IP certificate, once for # a domain. { + checkLib, pkgs, system, nixpkgs, @@ -9,6 +10,7 @@ }: let + inherit (checkLib) ok; inherit (pkgs) lib; serverModule = import ../../deploy/server-module.nix { inherit proxySuiteModule; }; @@ -66,14 +68,8 @@ let in { assertions = [ - ( - assert failedAssertions ipServer == [ ]; - true - ) - ( - assert failedAssertions domainServer == [ ]; - true - ) + (ok (failedAssertions ipServer == [ ])) + (ok (failedAssertions domainServer == [ ])) ( assert @@ -95,14 +91,8 @@ in (listener ipSpec "vless-tls").tls.certificateFile == "/var/lib/acme/203.0.113.10/fullchain.pem"; true ) - ( - assert (listener domainSpec "vless-ws").tls.keyFile == "/var/lib/acme/vpn.example.com/key.pem"; - true - ) - ( - assert (listener ipSpec "vless-ws").transport.path == "/3f9a1c07b2e4"; - true - ) + (ok ((listener domainSpec "vless-ws").tls.keyFile == "/var/lib/acme/vpn.example.com/key.pem")) + (ok ((listener ipSpec "vless-ws").transport.path == "/3f9a1c07b2e4")) ( assert (lib.head (listener ipSpec "vless-tls").users).uuidFile == "/var/lib/proxy-suite-server/uuid"; @@ -110,28 +100,13 @@ in ) # IP certificates exist only in the short-lived profile. - ( - assert ipCert.profile == "shortlived" && domainCert.profile == null; - true - ) - ( - assert ipCert.group == "proxy-suite-daemon"; - true - ) - ( - assert ipServer.config.services.proxy-suite.inbounds.serverAddress == "203.0.113.10"; - true - ) - ( - assert domainServer.config.services.proxy-suite.inbounds.serverAddress == "vpn.example.com"; - true - ) + (ok (ipCert.profile == "shortlived" && domainCert.profile == null)) + (ok (ipCert.group == "proxy-suite-daemon")) + (ok (ipServer.config.services.proxy-suite.inbounds.serverAddress == "203.0.113.10")) + (ok (domainServer.config.services.proxy-suite.inbounds.serverAddress == "vpn.example.com")) # A /32 with a gateway outside it only works on-link. - ( - assert (uplink ipServer).address == [ "203.0.113.10/32" ]; - true - ) + (ok ((uplink ipServer).address == [ "203.0.113.10/32" ])) ( assert (uplink ipServer).routes == [ @@ -142,31 +117,21 @@ in ]; true ) - ( - assert (uplink domainServer).networkConfig.DHCP == "yes" && (uplink domainServer).address == [ ]; - true - ) + (ok ((uplink domainServer).networkConfig.DHCP == "yes" && (uplink domainServer).address == [ ])) - ( - assert lib.all (p: builtins.elem p ipServer.config.networking.firewall.allowedTCPPorts) [ + (ok ( + lib.all (p: builtins.elem p ipServer.config.networking.firewall.allowedTCPPorts) [ 80 443 8443 2053 22 - ]; - true - ) - ( - assert ipServer.config.services.openssh.settings.PermitRootLogin == "no"; - true - ) + ] + )) + (ok (ipServer.config.services.openssh.settings.PermitRootLogin == "no")) # onion.enable: every listener behind the onion service, and nothing opened for it. - ( - assert failedAssertions onionServer == [ ]; - true - ) + (ok (failedAssertions onionServer == [ ])) ( assert lib.sort (a: b: a < b) onionSpec.onionListeners == [ @@ -181,11 +146,9 @@ in !(ipServer.config.systemd.services ? proxy-suite-tor) && (ipSpec.onionListeners or [ ]) == [ ]; true ) - ( - assert builtins.elem "proxy-suite-tor.service" - onionServer.config.systemd.services.proxy-suite-inbounds.after; - true - ) + (ok ( + builtins.elem "proxy-suite-tor.service" onionServer.config.systemd.services.proxy-suite-inbounds.after + )) ( assert onionServer.config.networking.firewall.allowedTCPPorts @@ -198,5 +161,12 @@ in && !(lib.hasInfix "--onion" ipServer.config.services.getty.helpLine); true ) + # The console banner names the server and the admin account, interpolated: an escaped + # ''${...} used to reach the login screen verbatim. + ( + assert lib.hasInfix "proxy-suite server 203.0.113.10." ipServer.config.services.getty.helpLine; + assert !(lib.hasInfix "\${" ipServer.config.services.getty.helpLine); + true + ) ]; } diff --git a/nix/checks/ssh-proxy.nix b/nix/checks/ssh-proxy.nix index d39b6ac..7d369a1 100644 --- a/nix/checks/ssh-proxy.nix +++ b/nix/checks/ssh-proxy.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -8,6 +9,7 @@ }: let + inherit (checkLib) ok mkProxySuite startScript; generated = import ./read-generated.nix; testHostKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; @@ -22,29 +24,22 @@ let builtins.unsafeDiscardStringContext "${pkgs.writeText "proxy-suite-core" (builtins.toJSON value)}"; # SingBox dials SSH natively: no unit, no local SOCKS listener. - sshNativeSingBox = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - sshProxy = { - enable = true; - server.user = "root"; - server.host = "ssh.example.com"; - asOutbound = true; - identityFile = "/run/secrets/ssh-key"; - hostKey = [ testHostKey ]; - }; - proxy = { - enable = true; - backend = "sing-box"; - }; - }; - } - ]; - sshNativeSingBoxStart = generated.readDerivation ( - sshNativeSingBox.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + sshNativeSingBox = mkProxySuite { + enable = true; + sshProxy = { + enable = true; + server.user = "root"; + server.host = "ssh.example.com"; + asOutbound = true; + identityFile = "/run/secrets/ssh-key"; + hostKey = [ testHostKey ]; + }; + proxy = { + enable = true; + backend = "sing-box"; + }; + }; + sshNativeSingBoxStart = startScript sshNativeSingBox; expectedNativeSingBoxOutbound = expectedOutboundFile { type = "ssh"; tag = "ssh-proxy"; @@ -56,29 +51,22 @@ let }; # hostKeyFile keys are injected at start, not baked into the JSON. - sshHostKeyFile = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - sshProxy = { - enable = true; - server.user = "root"; - server.host = "ssh.example.com"; - server.port = 2222; - asOutbound = true; - hostKeyFile = "/run/secrets/ssh-known-hosts"; - }; - proxy = { - enable = true; - backend = "sing-box"; - }; - }; - } - ]; - sshHostKeyFileStart = generated.readDerivation ( - sshHostKeyFile.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + sshHostKeyFile = mkProxySuite { + enable = true; + sshProxy = { + enable = true; + server.user = "root"; + server.host = "ssh.example.com"; + server.port = 2222; + asOutbound = true; + hostKeyFile = "/run/secrets/ssh-known-hosts"; + }; + proxy = { + enable = true; + backend = "sing-box"; + }; + }; + sshHostKeyFileStart = startScript sshHostKeyFile; # asOutbound = false: a standalone tunnel, so the OpenSSH unit exists even on SingBox. sshStandalone = evalProxySuite [ @@ -114,38 +102,27 @@ let ]; standaloneService = sshStandalone.config.systemd.services."proxy-suite-ssh-proxy"; standaloneStartScript = generated.readDerivation standaloneService.serviceConfig.ExecStart; - sshStandaloneStart = generated.readDerivation ( - sshStandalone.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + sshStandaloneStart = startScript sshStandalone; unchanged = evalProxySuite [ baseModule ]; - unchangedStart = generated.readDerivation ( - unchanged.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + unchangedStart = startScript unchanged; # XRay keeps the unit and proxies through its listener, domainStrategy on sockopt. - sshXray = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - sshProxy = { - enable = true; - server.user = "proxy"; - server.host = "ssh.example.com"; - asOutbound = true; - domainStrategy = "prefer_ipv4"; - }; - proxy = { - enable = true; - backend = "xray"; - }; - }; - } - ]; - sshXrayStart = generated.readDerivation ( - sshXray.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + sshXray = mkProxySuite { + enable = true; + sshProxy = { + enable = true; + server.user = "proxy"; + server.host = "ssh.example.com"; + asOutbound = true; + domainStrategy = "prefer_ipv4"; + }; + proxy = { + enable = true; + backend = "xray"; + }; + }; + sshXrayStart = startScript sshXray; xrayService = sshXray.config.systemd.services."proxy-suite-ssh-proxy"; xrayStartScript = generated.readDerivation xrayService.serviceConfig.ExecStart; expectedXrayOutbound = expectedOutboundFile { @@ -161,28 +138,21 @@ let }; }; - sshHybrid = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - sshProxy = { - enable = true; - server.user = "proxy"; - server.host = "ssh.example.com"; - asOutbound = true; - hostKey = [ testHostKey ]; - }; - proxy = { - enable = true; - backend = "hybrid"; - }; - }; - } - ]; - sshHybridStart = generated.readDerivation ( - sshHybrid.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + sshHybrid = mkProxySuite { + enable = true; + sshProxy = { + enable = true; + server.user = "proxy"; + server.host = "ssh.example.com"; + asOutbound = true; + hostKey = [ testHostKey ]; + }; + proxy = { + enable = true; + backend = "hybrid"; + }; + }; + sshHybridStart = startScript sshHybrid; expectedHybridOutbound = expectedOutboundFile { type = "ssh"; tag = "ssh-proxy"; @@ -219,9 +189,7 @@ let }; } ]; - sshSelectorStart = generated.readDerivation ( - sshSelector.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + sshSelectorStart = startScript sshSelector; sshUrltest = evalProxySuite [ { @@ -248,9 +216,7 @@ let }; } ]; - sshUrltestStart = generated.readDerivation ( - sshUrltest.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + sshUrltestStart = startScript sshUrltest; sshRouting = evalProxySuite [ { @@ -339,15 +305,9 @@ let ]; assertions = [ - ( - assert sshNativeSingBox.config.services.proxy-suite.proxy.outbounds == [ ]; - true - ) + (ok (sshNativeSingBox.config.services.proxy-suite.proxy.outbounds == [ ])) # No OpenSSH unit and no ordering against one: sing-box dials SSH in-process. - ( - assert !(sshNativeSingBox.config.systemd.services ? "proxy-suite-ssh-proxy"); - true - ) + (ok (!(sshNativeSingBox.config.systemd.services ? "proxy-suite-ssh-proxy"))) ( assert sshNativeSingBox.config.systemd.services."proxy-suite-socks".after == [ @@ -372,24 +332,12 @@ let true ) # The global local-resolve route rule is gone; the native outbound resolves. - ( - assert !(pkgs.lib.hasInfix "\"resolve\"" sshNativeSingBoxStart); - true - ) + (ok (!(pkgs.lib.hasInfix "\"resolve\"" sshNativeSingBoxStart))) # Non-default port has to be looked up as "[host]:port" in known_hosts. - ( - assert pkgs.lib.hasInfix "ssh-keygen -F '[ssh.example.com]:2222'" sshHostKeyFileStart; - true - ) - ( - assert pkgs.lib.hasInfix "'.host_key = \$hk'" sshHostKeyFileStart; - true - ) - ( - assert pkgs.lib.hasInfix "/run/secrets/ssh-known-hosts" sshHostKeyFileStart; - true - ) + (ok (pkgs.lib.hasInfix "ssh-keygen -F '[ssh.example.com]:2222'" sshHostKeyFileStart)) + (ok (pkgs.lib.hasInfix "'.host_key = \$hk'" sshHostKeyFileStart)) + (ok (pkgs.lib.hasInfix "/run/secrets/ssh-known-hosts" sshHostKeyFileStart)) # The keys must not be baked into the store-resident outbound JSON. ( assert @@ -400,56 +348,21 @@ let ) # Standalone tunnel: unit is created, but nothing is wired as an outbound. - ( - assert sshStandalone.config.systemd.services ? "proxy-suite-ssh-proxy"; - true - ) - ( - assert !(pkgs.lib.hasInfix "ssh-proxy" sshStandaloneStart); - true - ) - ( - assert standaloneService.serviceConfig.User == "proxy"; - true - ) - ( - assert !(standaloneService.serviceConfig ? SocketMark); - true - ) + (ok (sshStandalone.config.systemd.services ? "proxy-suite-ssh-proxy")) + (ok (!(pkgs.lib.hasInfix "ssh-proxy" sshStandaloneStart))) + (ok (standaloneService.serviceConfig.User == "proxy")) + (ok (!(standaloneService.serviceConfig ? SocketMark))) # Hardening: a half-open tunnel must be detected and always restarted. - ( - assert standaloneService.serviceConfig.Restart == "always"; - true - ) - ( - assert standaloneService.serviceConfig.LimitNOFILE == 65536; - true - ) - ( - assert standaloneService.startLimitIntervalSec == 0; - true - ) - ( - assert pkgs.lib.hasInfix "ServerAliveInterval=15" standaloneStartScript; - true - ) - ( - assert pkgs.lib.hasInfix "ServerAliveCountMax=3" standaloneStartScript; - true - ) - ( - assert pkgs.lib.hasInfix "ConnectTimeout=10" standaloneStartScript; - true - ) - ( - assert pkgs.lib.hasInfix "IPQoS=throughput" standaloneStartScript; - true - ) - ( - assert pkgs.lib.hasInfix ''UserKnownHostsFile="$CREDENTIALS_DIRECTORY/known_hosts"'' - standaloneStartScript; - true - ) + (ok (standaloneService.serviceConfig.Restart == "always")) + (ok (standaloneService.serviceConfig.LimitNOFILE == 65536)) + (ok (standaloneService.startLimitIntervalSec == 0)) + (ok (pkgs.lib.hasInfix "ServerAliveInterval=15" standaloneStartScript)) + (ok (pkgs.lib.hasInfix "ServerAliveCountMax=3" standaloneStartScript)) + (ok (pkgs.lib.hasInfix "ConnectTimeout=10" standaloneStartScript)) + (ok (pkgs.lib.hasInfix "IPQoS=throughput" standaloneStartScript)) + (ok ( + pkgs.lib.hasInfix ''UserKnownHostsFile="$CREDENTIALS_DIRECTORY/known_hosts"'' standaloneStartScript + )) # Secrets reach the unprivileged user as credentials. ( assert @@ -460,20 +373,11 @@ let true ) - ( - assert !(unchanged.config.systemd.services ? "proxy-suite-ssh-proxy"); - true - ) - ( - assert !(pkgs.lib.hasInfix "ssh-proxy" unchangedStart); - true - ) + (ok (!(unchanged.config.systemd.services ? "proxy-suite-ssh-proxy"))) + (ok (!(pkgs.lib.hasInfix "ssh-proxy" unchangedStart))) # XRay keeps the unit and orders the backend behind it. - ( - assert sshXray.config.systemd.services ? "proxy-suite-ssh-proxy"; - true - ) + (ok (sshXray.config.systemd.services ? "proxy-suite-ssh-proxy")) ( assert sshXray.config.systemd.services."proxy-suite-socks".after == [ @@ -490,50 +394,20 @@ let ]; true ) - ( - assert xrayService.serviceConfig.Restart == "always"; - true - ) - ( - assert pkgs.lib.hasInfix "ServerAliveInterval=15" xrayStartScript; - true - ) + (ok (xrayService.serviceConfig.Restart == "always")) + (ok (pkgs.lib.hasInfix "ServerAliveInterval=15" xrayStartScript)) # prefer_ipv4 maps onto XRay's "IPv4 first, fall back to IPv6". - ( - assert pkgs.lib.hasInfix expectedXrayOutbound sshXrayStart; - true - ) + (ok (pkgs.lib.hasInfix expectedXrayOutbound sshXrayStart)) # Hybrid routes the tunnel through sing-box, so it gets the native shape. - ( - assert !(sshHybrid.config.systemd.services ? "proxy-suite-ssh-proxy"); - true - ) - ( - assert pkgs.lib.hasInfix "_proxy_suite_add_sing_box_ob" sshHybridStart; - true - ) - ( - assert pkgs.lib.hasInfix expectedHybridOutbound sshHybridStart; - true - ) + (ok (!(sshHybrid.config.systemd.services ? "proxy-suite-ssh-proxy"))) + (ok (pkgs.lib.hasInfix "_proxy_suite_add_sing_box_ob" sshHybridStart)) + (ok (pkgs.lib.hasInfix expectedHybridOutbound sshHybridStart)) - ( - assert pkgs.lib.hasInfix "selector" sshSelectorStart; - true - ) - ( - assert pkgs.lib.hasInfix "ssh-proxy" sshSelectorStart; - true - ) - ( - assert pkgs.lib.hasInfix "# outbound: ssh-proxy (OpenSSH SOCKS5 listener)" sshUrltestStart; - true - ) - ( - assert builtins.any (rule: (rule.outbound or null) == "ssh-proxy") (mkRoutingRules sshRouting); - true - ) + (ok (pkgs.lib.hasInfix "selector" sshSelectorStart)) + (ok (pkgs.lib.hasInfix "ssh-proxy" sshSelectorStart)) + (ok (pkgs.lib.hasInfix "# outbound: ssh-proxy (OpenSSH SOCKS5 listener)" sshUrltestStart)) + (ok (builtins.any (rule: (rule.outbound or null) == "ssh-proxy") (mkRoutingRules sshRouting))) ] ++ invalidAssertions; in diff --git a/nix/checks/subscriptions-runtime.nix b/nix/checks/subscriptions-runtime.nix index 3d8e620..99033f0 100644 --- a/nix/checks/subscriptions-runtime.nix +++ b/nix/checks/subscriptions-runtime.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkProxyCtlDerived, @@ -6,7 +7,9 @@ }: let + inherit (checkLib) ok; fixtures = import ./subscriptions-runtime/fixtures.nix { + inherit checkLib; inherit evalProxySuite mkProxyCtlDerived @@ -28,10 +31,7 @@ in { assertions = [ # Basic config is accepted. - ( - assert subscriptionOnlyFixture.config.services.proxy-suite.proxy.subscriptions != [ ]; - true - ) + (ok (subscriptionOnlyFixture.config.services.proxy-suite.proxy.subscriptions != [ ])) # Wrapper exposes tags through a JSON file, not shell word splitting. ( @@ -42,14 +42,8 @@ in ) # Update service and timer are created when subscriptions are configured. - ( - assert subscriptionOnlyFixture.config.systemd.services ? "proxy-suite-subscription-update"; - true - ) - ( - assert subscriptionOnlyFixture.config.systemd.timers ? "proxy-suite-subscription-update"; - true - ) + (ok (subscriptionOnlyFixture.config.systemd.services ? "proxy-suite-subscription-update")) + (ok (subscriptionOnlyFixture.config.systemd.timers ? "proxy-suite-subscription-update")) # A oneshot left active would swallow every later timer run. ( assert @@ -176,14 +170,8 @@ in # The update service and timer exist whenever the proxy does, because a # subscription can be added at runtime after the rebuild. - ( - assert minimal.config.systemd.services ? "proxy-suite-subscription-update"; - true - ) - ( - assert minimal.config.systemd.timers ? "proxy-suite-subscription-update"; - true - ) + (ok (minimal.config.systemd.services ? "proxy-suite-subscription-update")) + (ok (minimal.config.systemd.timers ? "proxy-suite-subscription-update")) # Runtime spool dirs are root-only unless userControl grants outbounds (see user-control.nix). ( diff --git a/nix/checks/subscriptions-runtime/fixtures.nix b/nix/checks/subscriptions-runtime/fixtures.nix index 88bf8ca..4df4fd7 100644 --- a/nix/checks/subscriptions-runtime/fixtures.nix +++ b/nix/checks/subscriptions-runtime/fixtures.nix @@ -1,9 +1,11 @@ { + checkLib, evalProxySuite, mkProxyCtlDerived, }: let + inherit (checkLib) startScript unitScript; generated = import ../read-generated.nix; subscriptionOnlyFixture = evalProxySuite [ @@ -60,9 +62,7 @@ let }; } ]; - subscriptionWithStaticStartScript = generated.readDerivation ( - subscriptionWithStaticFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + subscriptionWithStaticStartScript = startScript subscriptionWithStaticFixture; subscriptionFirstSelectionFixture = evalProxySuite [ { @@ -83,9 +83,7 @@ let }; } ]; - subscriptionFirstSelectionStartScript = generated.readDerivation ( - subscriptionFirstSelectionFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + subscriptionFirstSelectionStartScript = startScript subscriptionFirstSelectionFixture; subscriptionPerAppTunFixture = evalProxySuite [ { @@ -109,9 +107,7 @@ let }; } ]; - subscriptionPerAppTunUpdateScript = generated.readDerivation ( - subscriptionPerAppTunFixture.config.systemd.services."proxy-suite-subscription-update".serviceConfig.ExecStart - ); + subscriptionPerAppTunUpdateScript = unitScript subscriptionPerAppTunFixture "proxy-suite-subscription-update"; in { inherit diff --git a/nix/checks/subscriptions-validation.nix b/nix/checks/subscriptions-validation.nix index 0b77c54..01658f2 100644 --- a/nix/checks/subscriptions-validation.nix +++ b/nix/checks/subscriptions-validation.nix @@ -1,10 +1,12 @@ { + checkLib, evalProxySuite, mkBadFixtureRaw, mkFailingAssertions, }: let + inherit (checkLib) ok; proxyWithSubscriptions = subscriptions: { system.stateVersion = "26.05"; services.proxy-suite = { @@ -71,9 +73,6 @@ in ]) ++ [ # urlFile form is accepted. - ( - assert subscriptionUrlFileFixture.config.services.proxy-suite.proxy.subscriptions != [ ]; - true - ) + (ok (subscriptionUrlFileFixture.config.services.proxy-suite.proxy.subscriptions != [ ])) ]; } diff --git a/nix/checks/subscriptions.nix b/nix/checks/subscriptions.nix index 7f24ef4..925afcd 100644 --- a/nix/checks/subscriptions.nix +++ b/nix/checks/subscriptions.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkBadFixtureRaw, @@ -9,6 +10,7 @@ let runtimeChecks = import ./subscriptions-runtime.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -17,6 +19,7 @@ let ; }; validationChecks = import ./subscriptions-validation.nix { + inherit checkLib; inherit evalProxySuite mkBadFixtureRaw diff --git a/nix/checks/tg-ws-proxy.nix b/nix/checks/tg-ws-proxy.nix index 368af7c..e2e66da 100644 --- a/nix/checks/tg-ws-proxy.nix +++ b/nix/checks/tg-ws-proxy.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -13,7 +14,9 @@ }: let + inherit (checkLib) ok; fixtures = import ./tg-ws-proxy/fixtures.nix { + inherit checkLib; inherit evalProxySuite baseModule @@ -38,18 +41,9 @@ let in { assertions = [ - ( - assert tgSecretFile.config.services.proxy-suite.tgWsProxy.listener.address == "127.0.0.1"; - true - ) - ( - assert minimal.config.services.proxy-suite.tgWsProxy.listener.address == "127.0.0.1"; - true - ) - ( - assert minimal.config.services.proxy-suite.tgWsProxy.dcIps == { }; - true - ) + (ok (tgSecretFile.config.services.proxy-suite.tgWsProxy.listener.address == "127.0.0.1")) + (ok (minimal.config.services.proxy-suite.tgWsProxy.listener.address == "127.0.0.1")) + (ok (minimal.config.services.proxy-suite.tgWsProxy.dcIps == { })) # Upstream runtime flags are exposed as typed module options. ( diff --git a/nix/checks/tg-ws-proxy/fixtures.nix b/nix/checks/tg-ws-proxy/fixtures.nix index a501dd3..6a4abcd 100644 --- a/nix/checks/tg-ws-proxy/fixtures.nix +++ b/nix/checks/tg-ws-proxy/fixtures.nix @@ -1,4 +1,5 @@ { + checkLib, evalProxySuite, baseModule, mkRoutingRules, @@ -8,6 +9,7 @@ }: let + inherit (checkLib) unitScript; generated = import ../read-generated.nix; tgSecretFile = evalProxySuite [ @@ -47,9 +49,7 @@ let }; } ]; - tgAllOptionsStartScript = generated.readDerivation ( - tgAllOptions.config.systemd.services."proxy-suite-tg-ws-proxy".serviceConfig.ExecStart - ); + tgAllOptionsStartScript = unitScript tgAllOptions "proxy-suite-tg-ws-proxy"; tgWithGlobalTun = evalProxySuite [ baseModule diff --git a/nix/checks/tor.nix b/nix/checks/tor.nix index 36a7b50..a6e53cc 100644 --- a/nix/checks/tor.nix +++ b/nix/checks/tor.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkBadProxySuiteFixture, @@ -12,6 +13,7 @@ }: let + inherit (checkLib) ok mkProxySuite; generated = import ./read-generated.nix; inherit (pkgs) lib; inherit (lib) hasInfix; @@ -108,32 +110,27 @@ let viaProxyStart = torStartOf viaProxy; viaProxyTor = (services viaProxy).proxy-suite-tor; - onion = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { + onion = mkProxySuite { + enable = true; + tor = { + enable = true; + onionService = { enable = true; - tor = { - enable = true; - onionService = { - enable = true; - secretKeyFile = "/run/secrets/hs_ed25519_secret_key"; - }; - }; - inbounds = { - enable = true; - serverAddress = "vpn.example.com"; - routing.via = "direct"; - listeners.plain = listener; - listeners.shared = listener // { - port = 10444; - address = "127.0.0.1"; - sharePort = 443; - }; - }; + secretKeyFile = "/run/secrets/hs_ed25519_secret_key"; }; - } - ]; + }; + inbounds = { + enable = true; + serverAddress = "vpn.example.com"; + routing.via = "direct"; + listeners.plain = listener; + listeners.shared = listener // { + port = 10444; + address = "127.0.0.1"; + sharePort = 443; + }; + }; + }; # An exit node: its clients' .onion names still reach Tor, through the local proxy. exitInbounds = { inbounds = { @@ -326,8 +323,8 @@ in !(lib.any (r: r.ruleTag or "" == "inbound-tor-onion") (mkInboundsConfig onion).routing.rules); true ) - ( - assert lib.all (f: failedAssertions f == [ ]) [ + (ok ( + lib.all (f: failedAssertions f == [ ]) [ singBox xray hybrid @@ -335,25 +332,17 @@ in bridges viaProxy onion - ]; - true - ) + ] + )) # Every backend dials Tor's SOCKS listener as the "tor" outbound. - ( - assert hasInfix ''{"server":"127.0.0.1","server_port":18530,"tag":"tor","type":"socks"}'' - singBoxStart; - true - ) - ( - assert hasInfix ''{"protocol":"socks","settings":{"address":"127.0.0.1","port":18530},"tag":"tor"}'' - xrayStart; - true - ) - ( - assert hasInfix ''"tag":"tor","type":"socks"'' hybridStart; - true - ) + (ok ( + hasInfix ''{"server":"127.0.0.1","server_port":18530,"tag":"tor","type":"socks"}'' singBoxStart + )) + (ok ( + hasInfix ''{"protocol":"socks","settings":{"address":"127.0.0.1","port":18530},"tag":"tor"}'' xrayStart + )) + (ok (hasInfix ''"tag":"tor","type":"socks"'' hybridStart)) # Only rules and detours reach it: never selected, tested, or used as an autoProxy exit. ( assert @@ -522,10 +511,7 @@ in && builtins.elem "proxy-suite-tor.service" onionInbounds.wants; true ) - ( - assert !(onion.config.systemd.services ? proxy-suite-socks); - true - ) + (ok (!(onion.config.systemd.services ? proxy-suite-socks))) ] ++ invalidAssertions; } diff --git a/nix/checks/user-control.nix b/nix/checks/user-control.nix index 09149fa..aec11b9 100644 --- a/nix/checks/user-control.nix +++ b/nix/checks/user-control.nix @@ -1,10 +1,12 @@ { + checkLib, pkgs, evalProxySuite, baseModule, }: let + inherit (checkLib) ok; inherit (pkgs.lib) hasInfix; mkFixture = @@ -136,11 +138,10 @@ in ) # -- userControl: scopes without enable is refused, not silently ignored -- - ( - assert builtins.any ( + (ok ( + builtins.any ( a: !a.assertion && hasInfix "userControl.scopes is set" a.message - ) scopesWithoutEnableFixture.config.assertions; - true - ) + ) scopesWithoutEnableFixture.config.assertions + )) ]; } diff --git a/nix/checks/warp.nix b/nix/checks/warp.nix index 91c3598..3a3dc7b 100644 --- a/nix/checks/warp.nix +++ b/nix/checks/warp.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkBadProxySuiteFixture, @@ -6,6 +7,7 @@ }: let + inherit (checkLib) mkProxySuite; generated = import ./read-generated.nix; inherit (pkgs.lib) hasInfix escapeShellArg; @@ -67,20 +69,15 @@ let autoRegister = registerOf auto; generatorRegister = registerOf generator; - amneziaWg = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - amneziaWg.enable = true; - warp = { - enable = true; - configFile = profile; - asAmneziaWg = true; - }; - }; - } - ]; + amneziaWg = mkProxySuite { + enable = true; + amneziaWg.enable = true; + warp = { + enable = true; + configFile = profile; + asAmneziaWg = true; + }; + }; invalidAssertions = mkFailingAssertions mkBadProxySuiteFixture [ # Enabled but used for nothing. diff --git a/nix/checks/xray-backend-features.nix b/nix/checks/xray-backend-features.nix index 37fdc64..bc7bfba 100644 --- a/nix/checks/xray-backend-features.nix +++ b/nix/checks/xray-backend-features.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkTProxyConfig, @@ -9,6 +10,7 @@ let fixtures = import ./xray-backend-features/fixtures.nix { + inherit checkLib; inherit pkgs evalProxySuite diff --git a/nix/checks/xray-backend-features/fixtures.nix b/nix/checks/xray-backend-features/fixtures.nix index efde02b..8eec604 100644 --- a/nix/checks/xray-backend-features/fixtures.nix +++ b/nix/checks/xray-backend-features/fixtures.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkTProxyConfig, @@ -7,6 +8,7 @@ }: let + inherit (checkLib) mkProxySuite startScript; generated = import ../read-generated.nix; rawOutboundJson = (import ../../../modules/proxy-suite/service/script-blocks/outbounds.nix { @@ -75,23 +77,16 @@ let }; } ]; - xraySubscriptionStartScript = generated.readDerivation ( - xraySubscriptionFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); + xraySubscriptionStartScript = startScript xraySubscriptionFixture; - xrayRawStreamFixture = evalProxySuite [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - backend = "xray"; - outbounds = [ xrayRawStreamDefinition ]; - }; - }; - } - ]; + xrayRawStreamFixture = mkProxySuite { + enable = true; + proxy = { + enable = true; + backend = "xray"; + outbounds = [ xrayRawStreamDefinition ]; + }; + }; xrayRawStreamOutbound = rawOutboundJson (builtins.head xrayRawStreamFixture.config.services.proxy-suite.proxy.outbounds) "proxy" diff --git a/nix/checks/xray-backend-runtime.nix b/nix/checks/xray-backend-runtime.nix index 7acfdc3..295f704 100644 --- a/nix/checks/xray-backend-runtime.nix +++ b/nix/checks/xray-backend-runtime.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkTProxyConfig, @@ -10,6 +11,7 @@ let fixtures = import ./xray-backend-runtime/fixtures.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -100,6 +102,7 @@ let ; }; tunChecks = import ./xray-backend-runtime/tun.nix { + inherit checkLib; inherit pkgs checkConstants diff --git a/nix/checks/xray-backend-runtime/fixtures.nix b/nix/checks/xray-backend-runtime/fixtures.nix index 900065b..c27bed7 100644 --- a/nix/checks/xray-backend-runtime/fixtures.nix +++ b/nix/checks/xray-backend-runtime/fixtures.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkTProxyConfig, @@ -8,6 +9,7 @@ }: let + inherit (checkLib) startScript unitScript; generated = import ../read-generated.nix; xrayModule = { @@ -49,18 +51,12 @@ let xrayTproxyConfig = mkTProxyConfig xrayFixture; xrayTunConfig = mkTunConfig xrayFixture; xrayPerAppTunConfig = mkPerAppTunConfig xrayFixture; - xrayStartScript = generated.readDerivation ( - xrayFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart - ); - xrayTunStartScript = generated.readDerivation ( - xrayFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStart - ); + xrayStartScript = startScript xrayFixture; + xrayTunStartScript = unitScript xrayFixture "proxy-suite-tun"; xrayTunUpScript = generated.readDerivation ( xrayFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStartPost ); - xrayPerAppTunStartScript = generated.readDerivation ( - xrayFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStart - ); + xrayPerAppTunStartScript = unitScript xrayFixture "proxy-suite-per-app-tun"; xrayPerAppTunUpScript = generated.readDerivation ( xrayFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStartPost ); diff --git a/nix/checks/xray-backend-runtime/tun.nix b/nix/checks/xray-backend-runtime/tun.nix index 4104c43..d4c0e2e 100644 --- a/nix/checks/xray-backend-runtime/tun.nix +++ b/nix/checks/xray-backend-runtime/tun.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, checkConstants, xrayTunConfig, diff --git a/nix/checks/xray-backend.nix b/nix/checks/xray-backend.nix index e96002e..5430aa6 100644 --- a/nix/checks/xray-backend.nix +++ b/nix/checks/xray-backend.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkTProxyConfig, @@ -13,6 +14,7 @@ let runtimeChecks = import ./xray-backend-runtime.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -24,6 +26,7 @@ let ; }; featureChecks = import ./xray-backend-features.nix { + inherit checkLib; inherit pkgs evalProxySuite diff --git a/nix/checks/xray-backends.nix b/nix/checks/xray-backends.nix index 2241a11..61e6809 100644 --- a/nix/checks/xray-backends.nix +++ b/nix/checks/xray-backends.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, mkTProxyConfig, @@ -13,6 +14,7 @@ let xrayChecks = import ./xray-backend.nix { + inherit checkLib; inherit pkgs evalProxySuite @@ -27,6 +29,7 @@ let ; }; hybridChecks = import ./hybrid-backend.nix { + inherit checkLib; inherit pkgs evalProxySuite diff --git a/nix/checks/zapret-hostlist-routing.nix b/nix/checks/zapret-hostlist-routing.nix index b7d9691..2c00f5d 100644 --- a/nix/checks/zapret-hostlist-routing.nix +++ b/nix/checks/zapret-hostlist-routing.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, diff --git a/nix/checks/zapret.nix b/nix/checks/zapret.nix index 61273eb..1c21719 100644 --- a/nix/checks/zapret.nix +++ b/nix/checks/zapret.nix @@ -1,4 +1,5 @@ { + checkLib, pkgs, evalProxySuite, baseModule, @@ -40,6 +41,7 @@ let ; zapretHostlistRoutingChecks = import ./zapret-hostlist-routing.nix { + inherit checkLib; inherit pkgs evalProxySuite diff --git a/nix/readme-doc.nix b/nix/readme-doc.nix index 92a1e01..484f966 100644 --- a/nix/readme-doc.nix +++ b/nix/readme-doc.nix @@ -19,41 +19,18 @@ let ]; }; cfg = eval.config.services.proxy-suite; - rules = import ../modules/proxy-suite/rules.nix { - lib = pkgs.lib; - inherit pkgs cfg zapret; - }; - configs = import ../modules/proxy-suite/config.nix { - lib = pkgs.lib; - inherit pkgs cfg rules; - }; - nftr = import ../modules/proxy-suite/nftables.nix { - lib = pkgs.lib; - inherit pkgs cfg; - }; - context = import ../modules/proxy-suite/service/context.nix { - lib = pkgs.lib; - inherit - pkgs - packages - cfg - ; - inherit (configs) - tproxyFile - tunFile - perAppTunFile - routeModeRulesFile - proxyInboundsFile - proxyInboundsSpecFile - ; - inherit (nftr) - perAppTunChainFile - perAppTproxyRulesFile - perAppZapretRulesFile - ip - nft - ; - }; + inherit + (import ../modules/proxy-suite/assembly.nix { + lib = pkgs.lib; + inherit + pkgs + packages + cfg + zapret + ; + }) + context + ; in pkgs.runCommand "proxy-suite-README.md" { nativeBuildInputs = [ pkgs.python3 ]; } '' src=${../README.md} diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index 6a82a25..46febb0 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -4,47 +4,16 @@ }: { - clashApi, - selection, + # NAME -> value, exported into proxy-ctl and both front ends. The module builds it + # (modules/proxy-suite/service/control.nix); proxy_ctl.py reads every name with env(). + env, + guiRefreshInterval ? 3, + # These four are also passed as derivations: the checks read the files' contents through + # passthru.proxySuiteCheck, which toString in env would lose. subscriptionTagsFile, - subscriptionCacheDir, - perAppRoutingEnabled, - perAppRoutingProxychainsEnabled, - perAppRoutingTunEnabled, - perAppRoutingTproxyEnabled, - perAppRoutingZapretEnabled, perAppRoutingProfilesFile, proxychainsConfigFile, - proxychainsQuietArg, - routeModeStateFile, - defaultRouteMode, amneziaWgProfileNamesFile, - inboundsEnabled, - inboundsLinksFile, - inboundsStatsFile, - inboundsXray, - inboundsApi, - inboundsSubscriptionsFile, - inboundsSubscriptionsBaseUrl, - zapretAutoEnabled, - zapretStateDir, - zapretCutoffEnabled, - outboundInventoryFile, - runtimeOutboundsDir, - runtimeSubscriptionsDir, - userControlGroup, - localProxyUrl, - autoProxyEnabled, - autoProxyStateDir, - torControlSocket ? "", - singBox, - stateDir ? "/var/lib/proxy-suite", - runtimeDir ? "/run", - serviceManager ? "systemd", - privileged ? "1", - # proxy-suitectl, when serviceManager is "supervisor". - supervisorCtl ? "", - guiRefreshInterval ? 3, }: let @@ -52,49 +21,7 @@ let unwrapped = pkgs.writeScriptBin "proxy-ctl" ( "#!${pkgs.python3}/bin/python3\n" + builtins.readFile ./proxy-ctl/proxy_ctl.py ); - wrapperEnv = { - CLASH_API = clashApi; - SELECTION = selection; - SUB_TAGS_FILE = toString subscriptionTagsFile; - SUB_CACHE_DIR = subscriptionCacheDir; - PER_APP_ROUTING_ENABLED = perAppRoutingEnabled; - PER_APP_ROUTING_PROXYCHAINS_ENABLED = perAppRoutingProxychainsEnabled; - PER_APP_ROUTING_TUN_ENABLED = perAppRoutingTunEnabled; - PER_APP_ROUTING_TPROXY_ENABLED = perAppRoutingTproxyEnabled; - PER_APP_ROUTING_ZAPRET_ENABLED = perAppRoutingZapretEnabled; - PER_APP_ROUTING_PROFILES_FILE = toString perAppRoutingProfilesFile; - PROXYCHAINS_CONFIG = toString proxychainsConfigFile; - PROXYCHAINS_QUIET_ARG = lib.removeSuffix " " proxychainsQuietArg; - ROUTE_MODE_STATE_FILE = routeModeStateFile; - DEFAULT_ROUTE_MODE = defaultRouteMode; - AWG_PROFILES_FILE = toString amneziaWgProfileNamesFile; - INBOUNDS_ENABLED = inboundsEnabled; - INBOUNDS_LINKS_FILE = inboundsLinksFile; - INBOUNDS_STATS_FILE = inboundsStatsFile; - INBOUNDS_XRAY = inboundsXray; - INBOUNDS_API = inboundsApi; - INBOUNDS_SUBS_FILE = inboundsSubscriptionsFile; - INBOUNDS_SUB_BASE_URL = inboundsSubscriptionsBaseUrl; - ZAPRET_AUTO_ENABLED = zapretAutoEnabled; - ZAPRET_STATE_DIR = zapretStateDir; - ZAPRET_CUTOFF_ENABLED = zapretCutoffEnabled; - OUTBOUND_INVENTORY_FILE = outboundInventoryFile; - RUNTIME_OUTBOUNDS_DIR = runtimeOutboundsDir; - RUNTIME_SUBS_DIR = runtimeSubscriptionsDir; - USER_CONTROL_GROUP = userControlGroup; - LOCAL_PROXY_URL = localProxyUrl; - AUTOPROXY_ENABLED = autoProxyEnabled; - AUTOPROXY_STATE_DIR = autoProxyStateDir; - TOR_CONTROL_SOCKET = torControlSocket; - SING_BOX = singBox; - STATE_DIR = stateDir; - RUNTIME_DIR = runtimeDir; - SERVICE_MANAGER = serviceManager; - PRIVILEGED = privileged; - } - // lib.optionalAttrs (supervisorCtl != "") { - SUPERVISOR_CTL = supervisorCtl; - }; + wrapperEnv = env; envFlags = lib.concatStringsSep " " ( lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") wrapperEnv ); diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index e11b24e..9b397f1 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -162,6 +162,21 @@ def read_json(path): return json.load(f) +def require_enabled(variable, feature): + """Refuses when the module did not build this feature in.""" + if env(variable) != "1": + die(f"{feature} is not enabled in this configuration.") + + +def read_json_or(path, fallback): + """The JSON at path, or fallback when it is missing, unreadable or not JSON.""" + try: + value = read_json(path) + except (OSError, ValueError): + return fallback + return value if isinstance(value, type(fallback)) else fallback + + def read_text(path): with open(path, encoding="utf-8", errors="replace") as f: return f.read() @@ -396,10 +411,7 @@ def _emit(text, qr): def _json_list(path): - try: - return [_s(x) for x in read_json(path)] - except (OSError, ValueError, TypeError): - return [] + return [_s(x) for x in read_json_or(path, [])] def _sub_tags(): @@ -948,14 +960,7 @@ def _outbound_inventory(): Empty until the proxy has started once. """ - path = env("OUTBOUND_INVENTORY_FILE") - if not readable(path): - return {} - try: - inventory = read_json(path) - except (OSError, ValueError): - return {} - return inventory if isinstance(inventory, dict) else {} + return read_json_or(env("OUTBOUND_INVENTORY_FILE"), {}) def _outbound_tags(): @@ -2032,10 +2037,7 @@ def cmd_proxy_probe(*args): def _backend_tags(): """User outbound tag -> the backend's tag, which probe exits and their reputation are keyed by.""" - try: - return read_json(_runtime_file("outbound-test.json")).get("outbounds") or {} - except (OSError, ValueError, AttributeError): - return {} + return read_json_or(_runtime_file("outbound-test.json"), {}).get("outbounds") or {} def _backend_tag(tag, backend=None): @@ -2061,8 +2063,7 @@ def _autoproxy_dir(): def _require_autoproxy(): - if env("AUTOPROXY_ENABLED") != "1": - die("proxy.autoProxy is not enabled in this configuration.") + require_enabled("AUTOPROXY_ENABLED", "proxy.autoProxy") def _autoproxy_unreadable(path): @@ -2089,11 +2090,7 @@ def _require_autoproxy_readable(path): def _autoproxy_state(path): - try: - state = read_json(os.path.join(path, "state.json")) - except (OSError, ValueError): - return {} - return state if isinstance(state, dict) else {} + return read_json_or(os.path.join(path, "state.json"), {}) def cmd_proxy_auto(verb="list", *args): @@ -2729,8 +2726,7 @@ def _per_app_profiles(): def _ensure_app_routing(): - if env("PER_APP_ROUTING_ENABLED") != "1": - die("perAppRouting is not enabled in this configuration.") + require_enabled("PER_APP_ROUTING_ENABLED", "perAppRouting") def _check_no_global_proxy(route): @@ -3081,8 +3077,7 @@ def _inbound_subscriptions(*args): def cmd_inbounds(verb="list", *args): - if env("INBOUNDS_ENABLED") != "1": - die("inbounds is not enabled in this configuration.") + require_enabled("INBOUNDS_ENABLED", "inbounds") if verb == "list": state = svc_state("proxy-suite-inbounds") row = " {:<24} {:<16} {:<14} {:<8} {}" diff --git a/pkgs/proxy-ctl/proxy_supervisor.py b/pkgs/proxy-ctl/proxy_supervisor.py index 0f78129..1c34046 100644 --- a/pkgs/proxy-ctl/proxy_supervisor.py +++ b/pkgs/proxy-ctl/proxy_supervisor.py @@ -188,38 +188,45 @@ class Unit: self.done.notify_all() -class Timer: +class Activator: + """A .timer or .path unit: it is active or not, and it starts one service.""" + + section = "" + suffix = "" + def __init__(self, name, definition): self.name = name self.definition = definition self.active = False + + @property + def config(self): + return self.definition.get(self.section) or {} + + def target(self): + return self.config.get("Unit") or self.name.replace(self.suffix, ".service") + + +class Timer(Activator): + section = "Timer" + suffix = ".timer" + + def __init__(self, name, definition): + super().__init__(name, definition) self.activated = None self.fired = set() self.last = None self.jitter = 0.0 - @property - def config(self): - return self.definition.get("Timer") or {} - def target(self): - return (self.definition.get("Timer") or {}).get("Unit") or self.name.replace(".timer", ".service") +class PathWatch(Activator): + section = "Path" + suffix = ".path" - -class PathWatch: def __init__(self, name, definition): - self.name = name - self.definition = definition - self.active = False + super().__init__(name, definition) self.seen = {} - @property - def config(self): - return self.definition.get("Path") or {} - - def target(self): - return self.config.get("Unit") or self.name.replace(".path", ".service") - def signature(path): try: @@ -570,24 +577,34 @@ class Supervisor: # timers and paths - def start_timer(self, name): - name = full_name(name, "timer") + def _activator(self, registry, kind, cls, name): + """The unit's Timer/PathWatch, made or replaced when its definition changed.""" + name = full_name(name, kind) definition = self.definition(name) if definition is None: - return 5 + return None + current = registry.get(name) + if current is None or current.definition is not definition: + current = registry[name] = cls(name, definition) + return current + + def start_timer(self, name): with self.guard: - timer = self.timers.get(name) - if timer is None or timer.definition is not definition: - timer = self.timers[name] = Timer(name, definition) + timer = self._activator(self.timers, "timer", Timer, name) + if timer is None: + return 5 if not timer.active: timer.active, timer.activated, timer.fired = True, time.time(), set() timer.jitter = self.jitter(timer) return 0 def stop_timer(self, name): - timer = self.timers.get(full_name(name, "timer")) - if timer: - timer.active = False + return self._stop_activator(self.timers, "timer", name) + + def _stop_activator(self, registry, kind, name): + unit = registry.get(full_name(name, kind)) + if unit: + unit.active = False return 0 @staticmethod @@ -611,24 +628,17 @@ class Supervisor: return at + timer.jitter, {base for base, when in candidates if when <= at} def start_path(self, name): - name = full_name(name, "path") - definition = self.definition(name) - if definition is None: - return 5 with self.guard: - watch = self.paths.get(name) - if watch is None or watch.definition is not definition: - watch = self.paths[name] = PathWatch(name, definition) + watch = self._activator(self.paths, "path", PathWatch, name) + if watch is None: + return 5 if not watch.active: watch.active = True watch.seen = {p: signature(p) for key in ("PathChanged", "PathModified") for p in as_list(watch.config.get(key))} return 0 def stop_path(self, name): - watch = self.paths.get(full_name(name, "path")) - if watch: - watch.active = False - return 0 + return self._stop_activator(self.paths, "path", name) def in_background(self, fn, *args): threading.Thread(target=fn, args=args, daemon=True).start() diff --git a/pkgs/proxy-ctl/test_proxy_supervisor.py b/pkgs/proxy-ctl/test_proxy_supervisor.py index 834cb6b..aa49240 100644 --- a/pkgs/proxy-ctl/test_proxy_supervisor.py +++ b/pkgs/proxy-ctl/test_proxy_supervisor.py @@ -81,6 +81,10 @@ class SupervisorTest(unittest.TestCase): "Unit": {"Description": "timer job"}, "Service": {"Type": "oneshot", "ExecStart": sh(f"echo tick >> {out}/ticks")}, }, + "proxy-suite-watched": { + "Unit": {"Description": "path job"}, + "Service": {"Type": "oneshot", "ExecStart": sh(f"echo changed >> {out}/watched")}, + }, "proxy-suite-pin@": { "Unit": {"Description": "template"}, "Service": {"Type": "oneshot", "ExecStart": sh(f"echo '%I' >> {out}/pins")}, @@ -93,7 +97,13 @@ class SupervisorTest(unittest.TestCase): "Install": {"WantedBy": ["timers.target"]}, }, }, - "paths": {}, + "paths": { + "proxy-suite-watched": { + "Unit": {"Description": "watch a file"}, + "Path": {"PathChanged": [os.path.join(self.tmp, "trigger")]}, + "Install": {"WantedBy": ["paths.target"]}, + }, + }, "tmpfiles": [f"d {self.run_dir} 0700 - - -"], } with open(self.manifest + ".tmp", "w") as f: @@ -168,5 +178,25 @@ class SupervisorTest(unittest.TestCase): self.assertEqual(self.read("once"), ["ran"]) + def test_path_unit_starts_its_service_when_the_file_changes(self): + trigger = os.path.join(self.tmp, "trigger") + # boot brings up the .path unit with the rest of paths.target. + self.assertEqual(self.ctl("boot")[0], 0) + # A .path unit is active itself, and quiet until the file it watches appears. + self.assertEqual(self.ctl("is-active", "--quiet", "proxy-suite-watched.path")[0], 0) + self.assertEqual(self.read("watched"), []) + + with open(trigger, "w") as f: + f.write("one") + wait_for(lambda: self.read("watched") == ["changed"]) + + # Stopped, further changes are ignored. + self.assertEqual(self.ctl("stop", "proxy-suite-watched.path")[0], 0) + with open(trigger, "w") as f: + f.write("two") + time.sleep(1) + self.assertEqual(self.read("watched"), ["changed"]) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/patch-zapret-config.py b/scripts/patch-zapret-config.py index 5188996..76d4397 100644 --- a/scripts/patch-zapret-config.py +++ b/scripts/patch-zapret-config.py @@ -13,14 +13,18 @@ BUILTIN_ACTIVATION_FALLBACKS = { } -def _hostlist_remove_pattern(stem: str) -> str: +def _remove_pattern(option: str, stem: str) -> str: + """Matches --hostlist=/--ipset= pointing at one of the config's own list files.""" escaped = re.escape(stem) - return rf'\s+--hostlist=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)' + return rf'\s+--{option}=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)' + + +def _hostlist_remove_pattern(stem: str) -> str: + return _remove_pattern("hostlist", stem) def _ipset_remove_pattern(stem: str) -> str: - escaped = re.escape(stem) - return rf'\s+--ipset=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)' + return _remove_pattern("ipset", stem) def _mk_family(match_stems: list[str], remove_stems: list[str]) -> dict: @@ -117,40 +121,28 @@ def add_standard_excludes(line: str, standard_excludes: list[str]) -> str: def _render_args( line: str, - hostlist_path: str, + option: str, + list_path: str, standard_excludes: list[str], *, - preset_family: str | None = None, + family_patterns: dict | None = None, + family: str | None = None, ) -> str: + """The line with its own list arguments dropped and list_path put in their place. + + `option` is "hostlist" or "ipset": the other kind is always removed, and the named + family's own patterns are removed instead of every argument when cloning a preset. + """ + other = "ipset" if option == "hostlist" else "hostlist" rendered = strip_trailing_new(line) - if preset_family is not None: - for pattern in FAMILY_PATTERNS[preset_family]["remove"]: + if family is not None: + for pattern in family_patterns[family]["remove"]: rendered = re.sub(pattern, "", rendered) else: - rendered = re.sub(r'\s+--hostlist=(?:"[^"]+"|\S+)', "", rendered) - rendered = re.sub(r'\s+--ipset=(?:"[^"]+"|\S+)', "", rendered) + rendered = re.sub(rf'\s+--{option}=(?:"[^"]+"|\S+)', "", rendered) + rendered = re.sub(rf'\s+--{other}=(?:"[^"]+"|\S+)', "", rendered) rendered = normalize_spaces(rendered) - rendered = f'{rendered} --hostlist="{hostlist_path}"' - rendered = add_standard_excludes(rendered, standard_excludes) - return f"{normalize_spaces(rendered)} --new" - - -def _render_ipset_args( - line: str, - ipset_path: str, - standard_excludes: list[str], - *, - ipset_family: str | None = None, -) -> str: - rendered = strip_trailing_new(line) - if ipset_family is not None: - for pattern in IPSET_PATTERNS[ipset_family]["remove"]: - rendered = re.sub(pattern, "", rendered) - else: - rendered = re.sub(r'\s+--ipset=(?:"[^"]+"|\S+)', "", rendered) - rendered = re.sub(r'\s+--hostlist=(?:"[^"]+"|\S+)', "", rendered) - rendered = normalize_spaces(rendered) - rendered = f'{rendered} --ipset="{ipset_path}"' + rendered = f'{normalize_spaces(rendered)} --{option}="{list_path}"' rendered = add_standard_excludes(rendered, standard_excludes) return f"{normalize_spaces(rendered)} --new" @@ -159,30 +151,12 @@ def render_protocol_clone(line: str) -> str: return f"{normalize_spaces(strip_trailing_new(line))} --new" -def render_preset_clone( - line: str, - family: str, - hostlist_path: str, - standard_excludes: list[str], -) -> str: - return _render_args(line, hostlist_path, standard_excludes, preset_family=family) - - def render_custom_args( fragment: str, hostlist_path: str, standard_excludes: list[str], ) -> str: - return _render_args(fragment, hostlist_path, standard_excludes) - - -def render_ipset_clone( - line: str, - family: str, - ipset_path: str, - standard_excludes: list[str], -) -> str: - return _render_ipset_args(line, ipset_path, standard_excludes, ipset_family=family) + return _render_args(fragment, "hostlist", hostlist_path, standard_excludes) def render_custom_ipset_args( @@ -190,7 +164,21 @@ def render_custom_ipset_args( ipset_path: str, standard_excludes: list[str], ) -> str: - return _render_ipset_args(fragment, ipset_path, standard_excludes) + return _render_args(fragment, "ipset", ipset_path, standard_excludes) + + +def _clone_lines( + existing_lines: list[str], patterns: dict, family: str, what: str, render +) -> list[str]: + """Every line of the config carrying the family's marker, rendered anew.""" + if family not in patterns: + raise ValueError(f"{what} '{family}' is unknown") + matches = [ + line for line in existing_lines if any(m in line for m in patterns[family]["match"]) + ] + if not matches: + raise ValueError(f"{what} '{family}' is not present in the selected zapret config") + return [render(line) for line in matches] def clone_family_lines( @@ -199,19 +187,21 @@ def clone_family_lines( hostlist_path: str, standard_excludes: list[str], ) -> list[str]: - matches = [ - line - for line in existing_lines - if any(marker in line for marker in FAMILY_PATTERNS[family]["match"]) - ] - if not matches: - raise ValueError( - f"Preset family '{family}' is not present in the selected zapret config" - ) - return [ - render_preset_clone(line, family, hostlist_path, standard_excludes) - for line in matches - ] + """The preset family's rules, pointed at this entry's own hostlist.""" + return _clone_lines( + existing_lines, + FAMILY_PATTERNS, + family, + "Preset family", + lambda line: _render_args( + line, + "hostlist", + hostlist_path, + standard_excludes, + family_patterns=FAMILY_PATTERNS, + family=family, + ), + ) def clone_ipset_lines( @@ -220,32 +210,26 @@ def clone_ipset_lines( ipset_path: str, standard_excludes: list[str], ) -> list[str]: - matches = [ - line - for line in existing_lines - if any(marker in line for marker in IPSET_PATTERNS[family]["match"]) - ] - if not matches: - raise ValueError( - f"IP set family '{family}' is not present in the selected zapret config" - ) - return [ - render_ipset_clone(line, family, ipset_path, standard_excludes) - for line in matches - ] + return _clone_lines( + existing_lines, + IPSET_PATTERNS, + family, + "IP set family", + lambda line: _render_args( + line, + "ipset", + ipset_path, + standard_excludes, + family_patterns=IPSET_PATTERNS, + family=family, + ), + ) def clone_protocol_lines(existing_lines: list[str], family: str) -> list[str]: - matches = [ - line - for line in existing_lines - if any(marker in line for marker in PROTOCOL_PATTERNS[family]["match"]) - ] - if not matches: - raise ValueError( - f"Protocol family '{family}' is not present in the selected zapret config" - ) - return [render_protocol_clone(line) for line in matches] + return _clone_lines( + existing_lines, PROTOCOL_PATTERNS, family, "Protocol family", render_protocol_clone + ) def activate_builtin_hostlists( diff --git a/scripts/proxy_parsing.py b/scripts/proxy_parsing.py index 56bbdbd..8a388d5 100644 --- a/scripts/proxy_parsing.py +++ b/scripts/proxy_parsing.py @@ -286,6 +286,46 @@ def _subscription_tag(line: str, tag_prefix: str, index: int, seen_tags: set[str return _unique_tag(make_tag(tag_prefix, _remark_from_line(line), index), seen_tags) +def _walk_subscription( + lines: list[str], + tag_prefix: str, + routing_mark: int | None, + backends: list[str], + links: dict[str, str] | None, + keep, +) -> None: + """Parses every supported line, trying each backend in turn, and hands the result to keep. + + A line no backend accepts is reported with every backend's complaint and skipped. + """ + seen_tags: set[str] = set() + + for index, line in enumerate(lines): + scheme = detect_scheme(line) + if scheme not in PARSERS: + continue + + tag = _subscription_tag(line, tag_prefix, index, seen_tags) + errors = [] + for backend in backends: + try: + outbound = build_outbound(line, tag, routing_mark, backend) + except Exception as exc: + errors.append(f"{backend}: {exc}" if len(backends) > 1 else str(exc)) + continue + + seen_tags.add(tag) + keep(backend, outbound) + if links is not None: + links[tag] = line + break + else: + print( + f"warning: skipping entry {index} ({scheme}): " + "; ".join(errors), + file=sys.stderr, + ) + + def parse_subscription( lines: list[str], tag_prefix: str, @@ -294,66 +334,24 @@ def parse_subscription( links: dict[str, str] | None = None, ) -> list[dict]: """links, when given, collects tag -> the line it came from, to share it back.""" - outbounds = [] - seen_tags: set[str] = set() - - for index, line in enumerate(lines): - scheme = detect_scheme(line) - if scheme not in PARSERS: - continue - - tag = _subscription_tag(line, tag_prefix, index, seen_tags) - - try: - outbound = build_outbound(line, tag, routing_mark, backend) - except Exception as exc: - print(f"warning: skipping entry {index} ({scheme}): {exc}", file=sys.stderr) - continue - - seen_tags.add(tag) - outbounds.append(outbound) - if links is not None: - links[tag] = line - + outbounds: list[dict] = [] + _walk_subscription( + lines, tag_prefix, routing_mark, [backend], links, lambda _, ob: outbounds.append(ob) + ) return outbounds def parse_hybrid_subscription( lines: list[str], tag_prefix: str, routing_mark: int | None = None, links: dict[str, str] | None = None ) -> dict[str, list[dict]]: + """Each line goes to whichever backend can dial it, sing-box first.""" outbounds: dict[str, list[dict]] = {"singBox": [], "xray": []} - seen_tags: set[str] = set() - - for index, line in enumerate(lines): - scheme = detect_scheme(line) - if scheme not in PARSERS: - continue - - tag = _subscription_tag(line, tag_prefix, index, seen_tags) - - try: - outbound = build_outbound(line, tag, routing_mark, "sing-box") - outbounds["singBox"].append(outbound) - seen_tags.add(tag) - if links is not None: - links[tag] = line - continue - except Exception as sing_box_exc: - sing_box_error = sing_box_exc - - try: - outbound = build_outbound(line, tag, routing_mark, "xray") - except Exception as xray_exc: - print( - f"warning: skipping entry {index} ({scheme}): " - f"sing-box: {sing_box_error}; xray: {xray_exc}", - file=sys.stderr, - ) - continue - - outbounds["xray"].append(outbound) - seen_tags.add(tag) - if links is not None: - links[tag] = line - + _walk_subscription( + lines, + tag_prefix, + routing_mark, + ["sing-box", "xray"], + links, + lambda backend, ob: outbounds["singBox" if backend == "sing-box" else "xray"].append(ob), + ) return outbounds diff --git a/scripts/proxy_url_parsers.py b/scripts/proxy_url_parsers.py index d72c553..561e0e7 100644 --- a/scripts/proxy_url_parsers.py +++ b/scripts/proxy_url_parsers.py @@ -209,6 +209,15 @@ def _mk_auth(userinfo: str) -> "tuple[str | None, str | None]": return urllib.parse.unquote(username), urllib.parse.unquote(password) if separator else None +def _set_auth(ob: dict, userinfo: str) -> None: + """Copies userinfo onto the outbound, password only when it is there.""" + username, password = _mk_auth(userinfo) + if username is not None: + ob["username"] = username + if password is not None: + ob["password"] = password + + def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict: userinfo, host, port, params = _parse_url_parts(url, "vless") security = _param(params, "security", "none") @@ -478,52 +487,37 @@ def parse_naive(url: str, tag: str) -> dict: "server_port": _port(port), "tls": {"enabled": True, "server_name": params.get("sni") or host}, } - username, password = _mk_auth(userinfo) - if username is not None: - ob["username"] = username - if password is not None: - ob["password"] = password + _set_auth(ob, userinfo) if scheme == "naive+quic": ob["quic"] = True return ob -def parse_socks(url: str, tag: str) -> dict: - scheme = url.split("://")[0].lower() - version = "4" if scheme.startswith("socks4") else "5" - userinfo, host, port, _ = _parse_url_parts(url, scheme) - - ob: dict = {"type": "socks", "tag": tag, "version": version} - username, password = _mk_auth(userinfo) - if username is not None: - ob["username"] = username - if password is not None: - ob["password"] = password - ob["server"] = host - ob["server_port"] = _port(port) - - return ob - - -def parse_http_proxy(url: str, tag: str) -> dict: +def _parse_plain_proxy(url: str, tag: str, kind: str) -> dict: + """socks:// and http(s)://: host, port and optional credentials, nothing else.""" scheme = url.split("://")[0].lower() userinfo, host, port, _ = _parse_url_parts(url, scheme) - ob: dict = {"type": "http", "tag": tag} - username, password = _mk_auth(userinfo) - if username is not None: - ob["username"] = username - if password is not None: - ob["password"] = password + ob: dict = {"type": kind, "tag": tag} + if kind == "socks": + ob["version"] = "4" if scheme.startswith("socks4") else "5" + _set_auth(ob, userinfo) ob["server"] = host ob["server_port"] = _port(port) - - if scheme == "https": + if kind == "http" and scheme == "https": ob["tls"] = {"enabled": True, "server_name": host} return ob +def parse_socks(url: str, tag: str) -> dict: + return _parse_plain_proxy(url, tag, "socks") + + +def parse_http_proxy(url: str, tag: str) -> dict: + return _parse_plain_proxy(url, tag, "http") + + PARSERS = { "vless": parse_vless, "vmess": parse_vmess, diff --git a/scripts/test-patch-zapret-config.py b/scripts/test-patch-zapret-config.py new file mode 100644 index 0000000..a34eb03 --- /dev/null +++ b/scripts/test-patch-zapret-config.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""patch-zapret-config.py: the NFQWS_OPT rewrites, on strings only.""" + +import importlib.util +import unittest +from pathlib import Path + +spec = importlib.util.spec_from_file_location( + "patch_zapret_config", Path(__file__).with_name("patch-zapret-config.py") +) +patch = importlib.util.module_from_spec(spec) +spec.loader.exec_module(patch) + +HOSTLISTS = "/opt/zapret/hostlists" +EXCLUDES = [ + f'--hostlist-exclude="{HOSTLISTS}/list-exclude.txt"', + f'--ipset-exclude="{HOSTLISTS}/ipset-exclude.txt"', +] +GENERAL = ( + f'--filter-tcp=443 --hostlist="{HOSTLISTS}/list-general.txt" ' + "--dpi-desync=fake --dpi-desync-ttl=6 --new" +) +IPSET_ALL = f'--filter-udp=443 --ipset="{HOSTLISTS}/ipset-all.txt" --dpi-desync=fake --new' +DISCORD = "--filter-l7=discord,stun --dpi-desync=fake --new" + + +class CloneTests(unittest.TestCase): + def test_family_clone_repoints_the_hostlist_and_keeps_the_strategy(self): + (line,) = patch.clone_family_lines([GENERAL], "general", "/run/mine.txt", EXCLUDES) + self.assertIn('--hostlist="/run/mine.txt"', line) + self.assertNotIn("list-general.txt", line) + self.assertIn("--dpi-desync=fake", line) + self.assertIn("--dpi-desync-ttl=6", line) + self.assertTrue(line.endswith("--new")) + self.assertEqual(line.count("--new"), 1) + for exclude in EXCLUDES: + self.assertIn(exclude, line) + + def test_ipset_clone_repoints_the_ipset(self): + (line,) = patch.clone_ipset_lines([IPSET_ALL], "all", "/run/mine-ips.txt", EXCLUDES) + self.assertIn('--ipset="/run/mine-ips.txt"', line) + self.assertNotIn("ipset-all.txt", line) + self.assertNotIn("--hostlist=", line) + self.assertTrue(line.endswith("--new")) + + def test_protocol_clone_keeps_the_line_as_is(self): + (line,) = patch.clone_protocol_lines([DISCORD], "discord-voice") + self.assertEqual(line, DISCORD) + + def test_a_missing_family_is_an_error(self): + for call in ( + lambda: patch.clone_family_lines([IPSET_ALL], "google", "/run/x.txt", EXCLUDES), + lambda: patch.clone_ipset_lines([GENERAL], "all", "/run/x.txt", EXCLUDES), + lambda: patch.clone_protocol_lines([GENERAL], "discord-voice"), + ): + with self.assertRaises(ValueError): + call() + + def test_custom_args_get_one_hostlist_and_one_ipset_form(self): + fragment = "--filter-tcp=80 --dpi-desync=split2" + host = patch.render_custom_args(fragment, "/run/mine.txt", EXCLUDES) + ips = patch.render_custom_ipset_args(fragment, "/run/mine-ips.txt", EXCLUDES) + self.assertIn('--hostlist="/run/mine.txt"', host) + self.assertNotIn("--ipset=", host) + self.assertIn('--ipset="/run/mine-ips.txt"', ips) + self.assertNotIn("--hostlist=", ips) + + def test_builtin_activation_only_adds_missing_lists(self): + instagram = f'--filter-tcp=443 --hostlist="{HOSTLISTS}/list-instagram.txt" --new' + added = patch.activate_builtin_hostlists( + [GENERAL, instagram], Path(HOSTLISTS), EXCLUDES + ) + joined = "\n".join(added) + self.assertNotIn("list-instagram.txt", joined) + self.assertIn("list-soundcloud.txt", joined) + self.assertIn("list-twitter.txt", joined) + + +class BlockTests(unittest.TestCase): + def test_locate_nfqws_block(self): + lines = ['OTHER=1', 'NFQWS_OPT="', GENERAL, '"', "TAIL=2"] + start, end = patch.locate_nfqws_block(lines) + self.assertEqual((start, end), (1, 3)) + + def test_a_config_without_the_block_is_an_error(self): + with self.assertRaises(ValueError): + patch.locate_nfqws_block(["OTHER=1"]) + + +if __name__ == "__main__": + unittest.main()