From 0e444236d999d1780aff0b98c3e8a0dce440a305 Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Wed, 7 Oct 2026 18:17:56 +0800 Subject: [PATCH] fix(nix): share a native runtime layout across packages --- .github/workflows/nix.yaml | 19 ++ .github/workflows/update-flake-hashes.yaml | 17 +- README.md | 2 +- apps/gpservice/src/ws_server.rs | 2 +- crates/common/src/binary_paths.rs | 9 +- crates/gpapi/src/process/collection.rs | 38 +++- crates/openconnect/src/vpn.rs | 8 +- crates/openconnect/src/vpn_utils.rs | 28 ++- flake.nix | 201 ++++----------------- nix/tests/native-runtime.nix | 97 ++++++++++ scripts/tests/nix-desktop-authorization.sh | 24 ++- 11 files changed, 238 insertions(+), 207 deletions(-) create mode 100644 nix/tests/native-runtime.nix diff --git a/.github/workflows/nix.yaml b/.github/workflows/nix.yaml index 2e08e2c..0da0578 100644 --- a/.github/workflows/nix.yaml +++ b/.github/workflows/nix.yaml @@ -7,6 +7,7 @@ on: - "flake.nix" - "flake.lock" - "nix/**" + - "scripts/tests/nix-desktop-authorization.sh" - ".github/workflows/nix.yaml" push: branches: @@ -15,6 +16,7 @@ on: - "flake.nix" - "flake.lock" - "nix/**" + - "scripts/tests/nix-desktop-authorization.sh" - ".github/workflows/nix.yaml" permissions: @@ -91,6 +93,23 @@ jobs: - name: Verify desktop authorization runs on the host run: bash scripts/tests/nix-desktop-authorization.sh result + native-runtime: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + package: [prebuilt, source] + steps: + - uses: actions/checkout@v6 + with: + submodules: recursive + - uses: cachix/install-nix-action@v31 + - name: Test native runtime in NixOS + run: | + nix build "git+file://$PWD?submodules=1#checks.x86_64-linux.native-runtime-${{ matrix.package }}" \ + --extra-experimental-features "nix-command flakes" \ + --print-build-logs + nixos-module: name: nixos-module (${{ matrix.platform.system }}, ${{ matrix.nixpkgs }}) strategy: diff --git a/.github/workflows/update-flake-hashes.yaml b/.github/workflows/update-flake-hashes.yaml index 6a398ec..93845b3 100644 --- a/.github/workflows/update-flake-hashes.yaml +++ b/.github/workflows/update-flake-hashes.yaml @@ -104,18 +104,11 @@ jobs: test -x result/bin/gpgui-helper test -x result/bin/gpgui test ! -L result/bin/gpservice - head -n1 result/bin/gpclient | grep '^#!' - head -n1 result/bin/gpservice | grep '^#!' - package_path="$(readlink -f result)" - grep -Fq "export GP_SERVICE_BINARY='$package_path/bin/gpservice'" result/bin/gpclient - grep -Fq "export GP_AUTH_BINARY='$package_path/bin/gpauth'" result/bin/gpclient - gui_binary="$(sed -n "s/^export GP_GUI_BINARY='\(.*\)'$/\1/p" result/bin/gpclient)" - test -x "$gui_binary" - grep -q 'exec .*/bin/gpservice' result/bin/gpservice - if grep -Fq -e '@gpservice_public@' -e '@gpauth_public@' -e '@gpservice_fhs@' -e "\$out/bin/gpservice" result/bin/gpclient result/bin/gpservice; then - echo "Unresolved launch wrapper placeholders" >&2 - exit 1 - fi + test -x result/libexec/gpclient/gp-vpnc-script-installer + test -x result/libexec/gpclient/gp-hip-script-installer + result/bin/gpclient --version + result/bin/gpservice --version + result/bin/gpauth --version if grep -R '/usr/bin/gp' result/share; then echo "Desktop assets contain paths outside the Nix package" >&2 diff --git a/README.md b/README.md index a4bedb3..bda451e 100644 --- a/README.md +++ b/README.md @@ -306,7 +306,7 @@ NixOS does not run an imperative package-uninstall hook when a package is removed from the system configuration. Remove an installed replacement VPN script from the app settings before removing the package. -The `prebuilt` package and NixOS module use the published release pinned in `flake.nix`. The `fromSource` package builds the current flake checkout, including its Git submodules: +The `prebuilt` package and NixOS module use the published release pinned in `flake.nix`. Both `prebuilt` and `fromSource` run natively on the host with packaged dependencies and installer paths. The `fromSource` package builds the current flake checkout, including its Git submodules: ```bash git submodule update --init --recursive diff --git a/apps/gpservice/src/ws_server.rs b/apps/gpservice/src/ws_server.rs index 157c3eb..882db28 100644 --- a/apps/gpservice/src/ws_server.rs +++ b/apps/gpservice/src/ws_server.rs @@ -265,7 +265,7 @@ impl WsServer { fn build_snapshot(vpn_state: VpnState) -> VpnEnv { VpnEnv { vpn_state, - vpnc_script: find_vpnc_script().map(ToOwned::to_owned), + vpnc_script: find_vpnc_script(), auth_executable: binary_paths::gpauth().to_string_lossy().into_owned(), host_info: HostInfo { host_identity: HostIdentity::collect(), diff --git a/crates/common/src/binary_paths.rs b/crates/common/src/binary_paths.rs index 2b1760e..f36dc3a 100644 --- a/crates/common/src/binary_paths.rs +++ b/crates/common/src/binary_paths.rs @@ -33,10 +33,11 @@ pub fn gp_vpnc_script_installer() -> PathBuf { #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] pub fn gp_hip_script_installer() -> PathBuf { - env::var_os("GP_HIP_SCRIPT_INSTALLER_BINARY") - .filter(|value| !value.is_empty()) - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(GP_HIP_SCRIPT_INSTALLER_BINARY)) + resolve( + "GP_HIP_SCRIPT_INSTALLER_BINARY", + "gp-hip-script-installer", + GP_HIP_SCRIPT_INSTALLER_BINARY, + ) } pub fn gpauth() -> PathBuf { diff --git a/crates/gpapi/src/process/collection.rs b/crates/gpapi/src/process/collection.rs index 5c861a5..9d90b65 100644 --- a/crates/gpapi/src/process/collection.rs +++ b/crates/gpapi/src/process/collection.rs @@ -53,8 +53,19 @@ const TOOL_DIRECTORIES: &[&str] = &[ "/sbin", "/usr/local/bin", "/usr/local/sbin", + #[cfg(target_os = "linux")] + "/run/current-system/sw/bin", ]; +fn tool_directories() -> Vec { + let configured = std::env::var_os("GP_COMMAND_PATH").unwrap_or_default(); + let mut directories: Vec<_> = std::env::split_paths(&configured) + .filter(|path| path.is_absolute()) + .collect(); + directories.extend(TOOL_DIRECTORIES.iter().map(PathBuf::from)); + directories +} + pub struct CollectorCommands<'a> { control: &'a dyn CollectionControl, } @@ -65,9 +76,7 @@ impl<'a> CollectorCommands<'a> { } pub fn resolve(&self, name: &str) -> Option { - TOOL_DIRECTORIES - .iter() - .find_map(|directory| resolve_executable(&Path::new(directory).join(name), uzers::get_effective_uid() == 0)) + resolve_in_directories(name, &tool_directories(), uzers::get_effective_uid() == 0) } pub fn run(&self, name: &str, args: &[&str]) -> io::Result> { @@ -116,6 +125,12 @@ impl<'a> CollectorCommands<'a> { } } +fn resolve_in_directories(name: &str, directories: &[PathBuf], require_root: bool) -> Option { + directories + .iter() + .find_map(|directory| resolve_executable(&directory.join(name), require_root)) +} + fn resolve_executable(path: &Path, require_root: bool) -> Option { let resolved = fs::canonicalize(path).ok()?; let metadata = fs::metadata(&resolved).ok()?; @@ -129,7 +144,8 @@ fn resolve_executable(path: &Path, require_root: bool) -> Option { /// Known command directories, canonicalized and restricted to trusted root /// ownership when used for privileged execution. pub fn command_path(require_root: bool) -> io::Result { - let directories = TOOL_DIRECTORIES.iter().filter_map(|directory| { + let configured = tool_directories(); + let directories = configured.iter().filter_map(|directory| { let resolved = fs::canonicalize(directory).ok()?; if resolved.is_dir() && (!require_root || root_owned_path(&resolved)) { Some(resolved) @@ -152,6 +168,20 @@ fn root_owned_path(path: &Path) -> bool { mod tests { use super::*; + #[test] + fn configured_directories_resolve_tools_without_using_the_process_path() { + let dir = tempfile::tempdir().unwrap(); + let tool = dir.path().join("configured-tool"); + fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap(); + fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap(); + assert_eq!( + resolve_in_directories("configured-tool", &[dir.path().to_owned()], false), + Some(fs::canonicalize(&tool).unwrap()) + ); + fs::set_permissions(&tool, fs::Permissions::from_mode(0o777)).unwrap(); + assert!(resolve_in_directories("configured-tool", &[dir.path().to_owned()], true).is_none()); + } + #[test] fn root_command_path_contains_only_trusted_canonical_directories() { let path = command_path(true).unwrap(); diff --git a/crates/openconnect/src/vpn.rs b/crates/openconnect/src/vpn.rs index 31bf461..4266e50 100644 --- a/crates/openconnect/src/vpn.rs +++ b/crates/openconnect/src/vpn.rs @@ -435,22 +435,22 @@ impl VpnBuilder { self } - fn determine_script(&self) -> Result<&str, VpnError> { + fn determine_script(&self) -> Result { match &self.script { Some(script) => { if self.script_is_path && !std::path::Path::new(script).exists() { return Err(VpnError::new(format!("VPN script does not exist: {script}"))); } check_executable(script).map_err(|e| VpnError::new(e.to_string()))?; - Ok(script) + Ok(script.clone()) } None => find_vpnc_script().ok_or_else(|| VpnError::new(String::from("Failed to find vpnc-script"))), } } pub fn build(self) -> Result { - let script = self.determine_script()?.to_owned(); - let script = if self.script_is_path { + let script = self.determine_script()?; + let script = if self.script_is_path || self.script.is_none() { shell_quote_path(&script) } else { script diff --git a/crates/openconnect/src/vpn_utils.rs b/crates/openconnect/src/vpn_utils.rs index ae4d112..1336e7b 100644 --- a/crates/openconnect/src/vpn_utils.rs +++ b/crates/openconnect/src/vpn_utils.rs @@ -30,8 +30,18 @@ fn find_executable(locations: &[&'static str]) -> Option<&'static str> { None } -pub fn find_vpnc_script() -> Option<&'static str> { - find_executable(VPNC_SCRIPT_LOCATIONS) +pub fn find_vpnc_script() -> Option { + if let Some(path) = std::env::var_os("GP_VPNC_SCRIPT").filter(|path| !path.is_empty()) { + return configured_script(Path::new(&path)); + } + find_executable(VPNC_SCRIPT_LOCATIONS).map(str::to_owned) +} + +fn configured_script(path: &Path) -> Option { + if path.is_absolute() && path.is_file() && path.is_executable() { + return path.to_str().map(str::to_owned); + } + None } /// If file exists, check if it is executable @@ -47,3 +57,17 @@ pub fn check_executable(file: &str) -> Result<(), io::Error> { Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn configured_script_requires_an_absolute_executable_path() { + assert_eq!(configured_script(Path::new("/bin/sh")), Some("/bin/sh".to_owned())); + assert!(configured_script(Path::new("bin/sh")).is_none()); + assert!(configured_script(Path::new("/missing-openconnect-vpnc-script")).is_none()); + assert!(configured_script(Path::new("/etc/passwd")).is_none()); + assert!(configured_script(Path::new("/tmp")).is_none()); + } +} diff --git a/flake.nix b/flake.nix index 0c49aa2..3ab62a6 100644 --- a/flake.nix +++ b/flake.nix @@ -90,6 +90,23 @@ xdg-utils ]; + runtimeTools = with pkgs; [ coreutils iproute2 systemd procps util-linux nettools xdg-utils ]; + + nativeRuntimeWrapping = lib.optionalString pkgs.stdenv.isLinux '' + gappsWrapperArgs+=( + --prefix PATH : "/run/wrappers/bin:${lib.makeBinPath runtimeTools}" + --set GP_COMMAND_PATH "${lib.makeBinPath runtimeTools}" + --set GP_VPNC_SCRIPT "$out/libexec/gpclient/vpnc-script" + --set GP_CLIENT_BINARY "$out/bin/gpclient" + --set GP_SERVICE_BINARY "$out/bin/gpservice" + --set GP_AUTH_BINARY "$out/bin/gpauth" + --set GP_GUI_BINARY "$out/bin/gpgui" + --set GP_GUI_HELPER_BINARY "$out/bin/gpgui-helper" + --set GP_VPNC_SCRIPT_INSTALLER_BINARY "$out/libexec/gpclient/gp-vpnc-script-installer" + --set GP_HIP_SCRIPT_INSTALLER_BINARY "$out/libexec/gpclient/gp-hip-script-installer" + ) + ''; + rewriteVpncScriptToolPaths = lib.optionalString pkgs.stdenv.isLinux '' substituteInPlace $out/libexec/gpclient/vpnc-script \ --replace-fail /usr/bin/resolvectl ${pkgs.systemd}/bin/resolvectl \ @@ -124,7 +141,7 @@ substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \ --replace-fail /usr/bin/gpservice $out/bin/gpservice \ - --replace-fail /usr/libexec/gpclient/gp-vpnc-script-installer $out/bin/gp-vpnc-script-installer + --replace-fail /usr/libexec/gpclient/gp-vpnc-script-installer $out/libexec/gpclient/gp-vpnc-script-installer if [ -f $out/libexec/gpclient/gp-hip-script-installer ]; then substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \ @@ -137,26 +154,6 @@ fi ''; - rewriteHostInstallPaths = '' - substituteInPlace $out/share/applications/gpgui.desktop \ - --replace-fail /usr/bin/gpclient $out/bin/gpclient - - substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \ - --replace-fail /usr/bin/gpservice $out/bin/gpservice - - for installer in gp-vpnc-script-installer gp-hip-script-installer; do - if [ -x "${prebuiltFiles}/libexec/gpclient/$installer" ]; then - substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \ - --replace-fail "/usr/libexec/gpclient/$installer" "${prebuiltFiles}/libexec/gpclient/$installer" - fi - done - - if [ -f $out/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down ]; then - substituteInPlace $out/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down \ - --replace-fail /usr/bin/gpclient $out/bin/gpclient - fi - ''; - installNixosPolkitRule = '' chmod u+w $out/share $out/share/polkit-1 2>/dev/null || true install -d $out/share/polkit-1/rules.d @@ -212,9 +209,7 @@ runtimeDependencies = lib.optionals pkgs.stdenv.isLinux linuxRuntimeDependencies; - preFixup = lib.optionalString pkgs.stdenv.isLinux '' - gappsWrapperArgs+=(--prefix PATH : ${lib.makeBinPath [ pkgs.xdg-utils ]}) - ''; + preFixup = nativeRuntimeWrapping; overrideMain = { ... }: @@ -243,9 +238,9 @@ cp -r packaging/files/usr/libexec $out/libexec '' + lib.optionalString pkgs.stdenv.isLinux '' - if [ -f $out/bin/gp-hip-script-installer ]; then - install -Dm755 $out/bin/gp-hip-script-installer $out/libexec/gpclient/gp-hip-script-installer - fi + for installer in gp-vpnc-script-installer gp-hip-script-installer; do + install -Dm755 "$out/bin/$installer" "$out/libexec/gpclient/$installer" + done # Copy the prebuilt gpgui binary to the output bin directory cp ${gpgui}/gpgui $out/bin/gpgui @@ -262,7 +257,7 @@ ''; }; - prebuiltFiles = pkgs.stdenv.mkDerivation { + prebuilt = pkgs.stdenv.mkDerivation { inherit pname; version = releaseVersion; @@ -276,6 +271,7 @@ buildInputs = linuxBuildInputs; runtimeDependencies = linuxRuntimeDependencies; + preFixup = nativeRuntimeWrapping; installPhase = '' runHook preInstall @@ -292,153 +288,13 @@ install -Dm755 ${gpgui}/gpgui $out/bin/gpgui ${rewriteVpncScriptToolPaths} - - runHook postInstall - ''; - }; - - hostGuiLauncher = pkgs.writeShellScript "gpgui-host-launcher" '' - set -eu - - if [ "''${1:-}" = "--version" ]; then - exec ${prebuiltFiles}/bin/gpgui "$@" - fi - - systemd_run_args=( - --user - --pipe - --wait - --quiet - --collect - --service-type=exec - ) - - while IFS= read -r -d "" env_entry; do - env_name="''${env_entry%%=*}" - case "$env_name" in - *[!A-Za-z0-9_]* | [0-9]* | PATH | GP_VPNC_SCRIPT_INSTALLER_BINARY | GP_HIP_SCRIPT_INSTALLER_BINARY | INVOCATION_ID | JOURNAL_STREAM | LISTEN_* | NOTIFY_SOCKET | SYSTEMD_EXEC_PID) - continue - ;; - esac - systemd_run_args+=("--setenv=$env_name") - done < <(${pkgs.coreutils}/bin/env --null) - - gui_path="/run/wrappers/bin:''${PATH:-}" - systemd_run_args+=("--setenv=PATH=$gui_path") - for helper in \ - GP_VPNC_SCRIPT_INSTALLER_BINARY=gp-vpnc-script-installer \ - GP_HIP_SCRIPT_INSTALLER_BINARY=gp-hip-script-installer; do - helper_path="${prebuiltFiles}/libexec/gpclient/''${helper#*=}" - if [ -x "$helper_path" ]; then - systemd_run_args+=("--setenv=''${helper%%=*}=$helper_path") - fi - done - - exec ${pkgs.systemd}/bin/systemd-run \ - "''${systemd_run_args[@]}" \ - ${prebuiltFiles}/bin/gpgui \ - "$@" - ''; - - prebuiltCommand = - { - binaryName, - extraProfile ? "", - }: - pkgs.buildFHSEnv { - name = binaryName; - targetPkgs = pkgs: [ prebuiltFiles ] ++ linuxBuildInputs ++ linuxRuntimeDependencies; - runScript = "/usr/bin/${binaryName}"; - profile = '' - export PATH=/run/wrappers/bin:$PATH - for helper in \ - GP_VPNC_SCRIPT_INSTALLER_BINARY=gp-vpnc-script-installer \ - GP_HIP_SCRIPT_INSTALLER_BINARY=gp-hip-script-installer; do - helper_path="${prebuiltFiles}/libexec/gpclient/''${helper#*=}" - if [ -x "$helper_path" ]; then - export "''${helper%%=*}=$helper_path" - fi - done - ${extraProfile} - ''; - extraBwrapArgs = [ - "--bind-try" - "/run/wrappers" - "/run/wrappers" - "--ro-bind-try" - "/etc/gpgui" - "/etc/gpgui" - ]; - }; - - prebuiltCommands = { - gpclient = prebuiltCommand { binaryName = "gpclient"; }; - gpservice = prebuiltCommand { - binaryName = "gpservice"; - extraProfile = '' - export GP_GUI_BINARY='${hostGuiLauncher}' - ''; - }; - gpauth = prebuiltCommand { binaryName = "gpauth"; }; - gpgui = prebuiltCommand { binaryName = "gpgui"; }; - gpgui-helper = prebuiltCommand { binaryName = "gpgui-helper"; }; - }; - - prebuilt = pkgs.stdenv.mkDerivation { - inherit pname; - version = releaseVersion; - - dontUnpack = true; - - installPhase = '' - runHook preInstall - - mkdir -p $out/bin - cat > $out/bin/gpclient <<'EOF' - #!${pkgs.runtimeShell} - set -eu - - export GP_SERVICE_BINARY='@gpservice_public@' - export GP_AUTH_BINARY='@gpauth_public@' - export GP_GUI_BINARY='${hostGuiLauncher}' - if [ "''${1:-}" = "launch-gui" ]; then - # Authorization must run before entering Bubblewrap, which disables setuid elevation. - export PATH=/run/wrappers/bin:$PATH - exec '${prebuiltFiles}/bin/gpclient' "$@" - fi - exec '${prebuiltCommands.gpclient}/bin/gpclient' "$@" - EOF - substituteInPlace $out/bin/gpclient \ - --replace-fail '@gpservice_public@' "$out/bin/gpservice" \ - --replace-fail '@gpauth_public@' "$out/bin/gpauth" - chmod +x $out/bin/gpclient - - cat > $out/bin/gpservice <<'EOF' - #!${pkgs.runtimeShell} - set -eu - exec '@gpservice_fhs@' "$@" - EOF - substituteInPlace $out/bin/gpservice \ - --replace-fail '@gpservice_fhs@' '${prebuiltCommands.gpservice}/bin/gpservice' - chmod +x $out/bin/gpservice - - ln -s ${prebuiltCommands.gpauth}/bin/gpauth $out/bin/gpauth - ln -s ${prebuiltCommands.gpgui}/bin/gpgui $out/bin/gpgui - ln -s ${prebuiltCommands."gpgui-helper"}/bin/gpgui-helper $out/bin/gpgui-helper - - cp -r ${prebuiltFiles}/libexec $out/libexec - cp -r ${prebuiltFiles}/share $out/share - - if [ -d ${prebuiltFiles}/lib ]; then - cp -r ${prebuiltFiles}/lib $out/lib - fi - - ${rewriteHostInstallPaths} + ${rewriteSourceInstallPaths} ${installNixosPolkitRule} runHook postInstall ''; }; + in { inherit fromSource prebuilt; @@ -496,6 +352,11 @@ default = fromSource; }; + checks = lib.optionalAttrs (system == "x86_64-linux") { + native-runtime-prebuilt = import ./nix/tests/native-runtime.nix { inherit pkgs; package = prebuilt; }; + native-runtime-source = import ./nix/tests/native-runtime.nix { inherit pkgs; package = fromSource; }; + }; + apps.default = { type = "app"; program = "${self.packages.${system}.default}/bin/gpclient"; diff --git a/nix/tests/native-runtime.nix b/nix/tests/native-runtime.nix new file mode 100644 index 0000000..9ed8bc5 --- /dev/null +++ b/nix/tests/native-runtime.nix @@ -0,0 +1,97 @@ +{ pkgs, package }: +let + guiProbe = pkgs.writeScript "gpgui-runtime-probe" '' + #!${pkgs.python3}/bin/python3 + import os + import pathlib + import sys + + if "--version" in sys.argv: + print("gpgui ${package.version}") + sys.exit(0) + + assert "--service-credential-on-stdin" in sys.argv + assert os.geteuid() == 1000 + assert "NoNewPrivs:\t0" in pathlib.Path("/proc/self/status").read_text() + for name in ("GP_CLIENT_BINARY", "GP_SERVICE_BINARY", "GP_AUTH_BINARY", + "GP_VPNC_SCRIPT_INSTALLER_BINARY", "GP_HIP_SCRIPT_INSTALLER_BINARY", + "GP_VPNC_SCRIPT"): + assert os.access(os.environ[name], os.X_OK), name + header = sys.stdin.buffer.read(2) + assert len(header) == 2 + length = int.from_bytes(header, "big") + assert 0 < length <= 510 + assert len(sys.stdin.buffer.read(length)) == length + pathlib.Path("/tmp/gp-gui-ready").write_text(str(os.getpid())) + sys.stdin.buffer.read() + ''; + testPackage = package.overrideAttrs (old: { + postInstall = (old.postInstall or "") + '' + install -m755 ${guiProbe} $out/bin/gpgui + ''; + }); + hostCollector = pkgs.writeShellScriptBin "clamscan" '' + echo 'ClamAV 1.4.0/27123/Mon Oct 7 00:00:00 2026' + ''; +in +pkgs.testers.runNixOSTest { + name = "gp-native-runtime-${package.pname}"; + nodes.machine = { + environment.systemPackages = [ testPackage hostCollector ]; + users.users.alice = { isNormalUser = true; uid = 1000; }; + security.polkit.enable = true; + security.polkit.extraConfig = '' + polkit.addRule(function(action, subject) { + if (subject.user == "alice" && ( + action.id == "com.yuezk.gpgui.service" || + action.id == "com.yuezk.gpgui.manage-vpnc-script" || + action.id == "com.yuezk.gpgui.manage-root-hip-script" + )) return polkit.Result.YES; + }); + ''; + virtualisation.memorySize = 4096; + }; + testScript = '' + import base64 + import json + import shlex + + machine.start() + machine.wait_for_unit("polkit.service") + package = "${testPackage}" + + def as_alice(command): + return machine.succeed("su - alice -c " + shlex.quote(command)) + + # Exercise real host pkexec, private credential pipes and launcher cancellation. + command = package + "/bin/gpclient --lock-file /tmp/gp-client.lock launch-gui" + as_alice(command + " > /tmp/gp-client-output 2>&1 & echo $! > /tmp/gp-client-pid") + machine.wait_until_succeeds("test -s /tmp/gp-gui-ready") + service_pid = machine.succeed("cut -d: -f1 /var/run/gpservice.lock").strip() + machine.succeed("test $(stat -c %u /proc/" + service_pid + ") = 0") + as_alice("kill -TERM $(cat /tmp/gp-client-pid)") + machine.wait_until_succeeds("test ! -e /proc/" + service_pid) + machine.wait_until_succeeds("! kill -0 $(cat /tmp/gp-gui-ready)") + + # The optional collector lives in the NixOS system profile, outside the package's tool closure. + report = machine.succeed(package + "/bin/gpclient hip --client-version 6.3.3-619 " + "--client-os linux --cookie fixture --md5 0123456789abcdef0123456789abcdef") + assert "ClamAV" in report, report + + script = base64.b64encode(b"#!/bin/sh\nexit 0\n").decode() + hip_request = json.dumps({"originalPath": "/home/alice/hip.sh", "contentsBase64": script}) + hip_installer = package + "/libexec/gpclient/gp-hip-script-installer" + approval = json.loads(as_alice("printf %s " + shlex.quote(hip_request) + + " | pkexec " + hip_installer + " install")) + assert approval["ownerUid"] == 1000 + as_alice("pkexec " + hip_installer + " revoke " + shlex.quote(approval["approvalId"])) + + vpn_request = json.dumps({"metadata": {"source": "file", "value": "/home/alice/vpnc.sh"}, + "contents": script}) + vpn_installer = package + "/libexec/gpclient/gp-vpnc-script-installer" + as_alice("printf %s " + shlex.quote(vpn_request) + " | pkexec " + vpn_installer + " install") + machine.succeed("test -x /var/lib/gpclient/scripts/vpnc-script") + as_alice("pkexec " + vpn_installer + " remove") + machine.succeed("test ! -e /var/lib/gpclient/scripts/vpnc-script") + ''; +} diff --git a/scripts/tests/nix-desktop-authorization.sh b/scripts/tests/nix-desktop-authorization.sh index 8e89a1b..d556072 100644 --- a/scripts/tests/nix-desktop-authorization.sh +++ b/scripts/tests/nix-desktop-authorization.sh @@ -29,13 +29,19 @@ exit 126 EOF chmod +x "$test_workspace/bin/pkexec" -if PATH="$test_workspace/bin:$PATH" \ - XDG_DATA_HOME="$test_workspace/data" \ - GP_TEST_SERVICE_BINARY="$package_path/bin/gpservice" \ - "$package_path/bin/gpclient" launch-gui --minimized; then - echo "The desktop launcher ignored the authorization rejection" >&2 - exit 1 -fi +check_authorization() { + rm -f "$test_workspace/data/gpclient/gpclient.log" + if PATH="$test_workspace/bin:$PATH" \ + XDG_DATA_HOME="$test_workspace/data" \ + GP_TEST_SERVICE_BINARY="$package_path/bin/gpservice" \ + "$@"; then + echo "The desktop launcher ignored the authorization rejection" >&2 + exit 1 + fi + grep -Fx 'Authorization reached the host without NoNewPrivs' \ + "$test_workspace/data/gpclient/gpclient.log" +} -grep -Fx 'Authorization reached the host without NoNewPrivs' \ - "$test_workspace/data/gpclient/gpclient.log" +check_authorization "$package_path/bin/gpclient" launch-gui --minimized +check_authorization "$package_path/bin/gpclient" --lock-file "$test_workspace/client.lock" launch-gui +check_authorization "$package_path/bin/gpgui" --minimized