fix(nix): share a native runtime layout across packages

This commit is contained in:
Kevin Yue committed 2026-10-07 18:17:56 +08:00
1 parent 673cf464b0
commit 0e444236d9
11 files changed
+238 -207

No files matched your search

+19
View File
@@ -7,6 +7,7 @@ on:
- "flake.nix" - "flake.nix"
- "flake.lock" - "flake.lock"
- "nix/**" - "nix/**"
- "scripts/tests/nix-desktop-authorization.sh"
- ".github/workflows/nix.yaml" - ".github/workflows/nix.yaml"
push: push:
branches: branches:
@@ -15,6 +16,7 @@ on:
- "flake.nix" - "flake.nix"
- "flake.lock" - "flake.lock"
- "nix/**" - "nix/**"
- "scripts/tests/nix-desktop-authorization.sh"
- ".github/workflows/nix.yaml" - ".github/workflows/nix.yaml"
permissions: permissions:
@@ -91,6 +93,23 @@ jobs:
- name: Verify desktop authorization runs on the host - name: Verify desktop authorization runs on the host
run: bash scripts/tests/nix-desktop-authorization.sh result 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: nixos-module:
name: nixos-module (${{ matrix.platform.system }}, ${{ matrix.nixpkgs }}) name: nixos-module (${{ matrix.platform.system }}, ${{ matrix.nixpkgs }})
strategy: strategy:
+5 -12
View File
@@ -104,18 +104,11 @@ jobs:
test -x result/bin/gpgui-helper test -x result/bin/gpgui-helper
test -x result/bin/gpgui test -x result/bin/gpgui
test ! -L result/bin/gpservice test ! -L result/bin/gpservice
head -n1 result/bin/gpclient | grep '^#!' test -x result/libexec/gpclient/gp-vpnc-script-installer
head -n1 result/bin/gpservice | grep '^#!' test -x result/libexec/gpclient/gp-hip-script-installer
package_path="$(readlink -f result)" result/bin/gpclient --version
grep -Fq "export GP_SERVICE_BINARY='$package_path/bin/gpservice'" result/bin/gpclient result/bin/gpservice --version
grep -Fq "export GP_AUTH_BINARY='$package_path/bin/gpauth'" result/bin/gpclient result/bin/gpauth --version
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
if grep -R '/usr/bin/gp' result/share; then if grep -R '/usr/bin/gp' result/share; then
echo "Desktop assets contain paths outside the Nix package" >&2 echo "Desktop assets contain paths outside the Nix package" >&2
+1 -1
View File
@@ -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 removed from the system configuration. Remove an installed replacement VPN
script from the app settings before removing the package. 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 ```bash
git submodule update --init --recursive git submodule update --init --recursive
+1 -1
View File
@@ -265,7 +265,7 @@ impl WsServer {
fn build_snapshot(vpn_state: VpnState) -> VpnEnv { fn build_snapshot(vpn_state: VpnState) -> VpnEnv {
VpnEnv { VpnEnv {
vpn_state, 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(), auth_executable: binary_paths::gpauth().to_string_lossy().into_owned(),
host_info: HostInfo { host_info: HostInfo {
host_identity: HostIdentity::collect(), host_identity: HostIdentity::collect(),
+5 -4
View File
@@ -33,10 +33,11 @@ pub fn gp_vpnc_script_installer() -> PathBuf {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub fn gp_hip_script_installer() -> PathBuf { pub fn gp_hip_script_installer() -> PathBuf {
env::var_os("GP_HIP_SCRIPT_INSTALLER_BINARY") resolve(
.filter(|value| !value.is_empty()) "GP_HIP_SCRIPT_INSTALLER_BINARY",
.map(PathBuf::from) "gp-hip-script-installer",
.unwrap_or_else(|| PathBuf::from(GP_HIP_SCRIPT_INSTALLER_BINARY)) GP_HIP_SCRIPT_INSTALLER_BINARY,
)
} }
pub fn gpauth() -> PathBuf { pub fn gpauth() -> PathBuf {
+34 -4
View File
@@ -53,8 +53,19 @@ const TOOL_DIRECTORIES: &[&str] = &[
"/sbin", "/sbin",
"/usr/local/bin", "/usr/local/bin",
"/usr/local/sbin", "/usr/local/sbin",
#[cfg(target_os = "linux")]
"/run/current-system/sw/bin",
]; ];
fn tool_directories() -> Vec<PathBuf> {
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> { pub struct CollectorCommands<'a> {
control: &'a dyn CollectionControl, control: &'a dyn CollectionControl,
} }
@@ -65,9 +76,7 @@ impl<'a> CollectorCommands<'a> {
} }
pub fn resolve(&self, name: &str) -> Option<PathBuf> { pub fn resolve(&self, name: &str) -> Option<PathBuf> {
TOOL_DIRECTORIES resolve_in_directories(name, &tool_directories(), uzers::get_effective_uid() == 0)
.iter()
.find_map(|directory| resolve_executable(&Path::new(directory).join(name), uzers::get_effective_uid() == 0))
} }
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> { pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
@@ -116,6 +125,12 @@ impl<'a> CollectorCommands<'a> {
} }
} }
fn resolve_in_directories(name: &str, directories: &[PathBuf], require_root: bool) -> Option<PathBuf> {
directories
.iter()
.find_map(|directory| resolve_executable(&directory.join(name), require_root))
}
fn resolve_executable(path: &Path, require_root: bool) -> Option<PathBuf> { fn resolve_executable(path: &Path, require_root: bool) -> Option<PathBuf> {
let resolved = fs::canonicalize(path).ok()?; let resolved = fs::canonicalize(path).ok()?;
let metadata = fs::metadata(&resolved).ok()?; let metadata = fs::metadata(&resolved).ok()?;
@@ -129,7 +144,8 @@ fn resolve_executable(path: &Path, require_root: bool) -> Option<PathBuf> {
/// Known command directories, canonicalized and restricted to trusted root /// Known command directories, canonicalized and restricted to trusted root
/// ownership when used for privileged execution. /// ownership when used for privileged execution.
pub fn command_path(require_root: bool) -> io::Result<std::ffi::OsString> { pub fn command_path(require_root: bool) -> io::Result<std::ffi::OsString> {
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()?; let resolved = fs::canonicalize(directory).ok()?;
if resolved.is_dir() && (!require_root || root_owned_path(&resolved)) { if resolved.is_dir() && (!require_root || root_owned_path(&resolved)) {
Some(resolved) Some(resolved)
@@ -152,6 +168,20 @@ fn root_owned_path(path: &Path) -> bool {
mod tests { mod tests {
use super::*; 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] #[test]
fn root_command_path_contains_only_trusted_canonical_directories() { fn root_command_path_contains_only_trusted_canonical_directories() {
let path = command_path(true).unwrap(); let path = command_path(true).unwrap();
+4 -4
View File
@@ -435,22 +435,22 @@ impl VpnBuilder {
self self
} }
fn determine_script(&self) -> Result<&str, VpnError> { fn determine_script(&self) -> Result<String, VpnError> {
match &self.script { match &self.script {
Some(script) => { Some(script) => {
if self.script_is_path && !std::path::Path::new(script).exists() { if self.script_is_path && !std::path::Path::new(script).exists() {
return Err(VpnError::new(format!("VPN script does not exist: {script}"))); return Err(VpnError::new(format!("VPN script does not exist: {script}")));
} }
check_executable(script).map_err(|e| VpnError::new(e.to_string()))?; 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"))), None => find_vpnc_script().ok_or_else(|| VpnError::new(String::from("Failed to find vpnc-script"))),
} }
} }
pub fn build(self) -> Result<Vpn, VpnError> { pub fn build(self) -> Result<Vpn, VpnError> {
let script = self.determine_script()?.to_owned(); let script = self.determine_script()?;
let script = if self.script_is_path { let script = if self.script_is_path || self.script.is_none() {
shell_quote_path(&script) shell_quote_path(&script)
} else { } else {
script script
+26 -2
View File
@@ -30,8 +30,18 @@ fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
None None
} }
pub fn find_vpnc_script() -> Option<&'static str> { pub fn find_vpnc_script() -> Option<String> {
find_executable(VPNC_SCRIPT_LOCATIONS) 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<String> {
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 /// If file exists, check if it is executable
@@ -47,3 +57,17 @@ pub fn check_executable(file: &str) -> Result<(), io::Error> {
Ok(()) 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());
}
}
+31 -170
View File
@@ -90,6 +90,23 @@
xdg-utils 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 '' rewriteVpncScriptToolPaths = lib.optionalString pkgs.stdenv.isLinux ''
substituteInPlace $out/libexec/gpclient/vpnc-script \ substituteInPlace $out/libexec/gpclient/vpnc-script \
--replace-fail /usr/bin/resolvectl ${pkgs.systemd}/bin/resolvectl \ --replace-fail /usr/bin/resolvectl ${pkgs.systemd}/bin/resolvectl \
@@ -124,7 +141,7 @@
substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \ substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \
--replace-fail /usr/bin/gpservice $out/bin/gpservice \ --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 if [ -f $out/libexec/gpclient/gp-hip-script-installer ]; then
substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \ substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \
@@ -137,26 +154,6 @@
fi 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 = '' installNixosPolkitRule = ''
chmod u+w $out/share $out/share/polkit-1 2>/dev/null || true chmod u+w $out/share $out/share/polkit-1 2>/dev/null || true
install -d $out/share/polkit-1/rules.d install -d $out/share/polkit-1/rules.d
@@ -212,9 +209,7 @@
runtimeDependencies = lib.optionals pkgs.stdenv.isLinux linuxRuntimeDependencies; runtimeDependencies = lib.optionals pkgs.stdenv.isLinux linuxRuntimeDependencies;
preFixup = lib.optionalString pkgs.stdenv.isLinux '' preFixup = nativeRuntimeWrapping;
gappsWrapperArgs+=(--prefix PATH : ${lib.makeBinPath [ pkgs.xdg-utils ]})
'';
overrideMain = overrideMain =
{ ... }: { ... }:
@@ -243,9 +238,9 @@
cp -r packaging/files/usr/libexec $out/libexec cp -r packaging/files/usr/libexec $out/libexec
'' ''
+ lib.optionalString pkgs.stdenv.isLinux '' + lib.optionalString pkgs.stdenv.isLinux ''
if [ -f $out/bin/gp-hip-script-installer ]; then for installer in gp-vpnc-script-installer gp-hip-script-installer; do
install -Dm755 $out/bin/gp-hip-script-installer $out/libexec/gpclient/gp-hip-script-installer install -Dm755 "$out/bin/$installer" "$out/libexec/gpclient/$installer"
fi done
# Copy the prebuilt gpgui binary to the output bin directory # Copy the prebuilt gpgui binary to the output bin directory
cp ${gpgui}/gpgui $out/bin/gpgui cp ${gpgui}/gpgui $out/bin/gpgui
@@ -262,7 +257,7 @@
''; '';
}; };
prebuiltFiles = pkgs.stdenv.mkDerivation { prebuilt = pkgs.stdenv.mkDerivation {
inherit pname; inherit pname;
version = releaseVersion; version = releaseVersion;
@@ -276,6 +271,7 @@
buildInputs = linuxBuildInputs; buildInputs = linuxBuildInputs;
runtimeDependencies = linuxRuntimeDependencies; runtimeDependencies = linuxRuntimeDependencies;
preFixup = nativeRuntimeWrapping;
installPhase = '' installPhase = ''
runHook preInstall runHook preInstall
@@ -292,153 +288,13 @@
install -Dm755 ${gpgui}/gpgui $out/bin/gpgui install -Dm755 ${gpgui}/gpgui $out/bin/gpgui
${rewriteVpncScriptToolPaths} ${rewriteVpncScriptToolPaths}
${rewriteSourceInstallPaths}
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}
${installNixosPolkitRule} ${installNixosPolkitRule}
runHook postInstall runHook postInstall
''; '';
}; };
in in
{ {
inherit fromSource prebuilt; inherit fromSource prebuilt;
@@ -496,6 +352,11 @@
default = fromSource; 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 = { apps.default = {
type = "app"; type = "app";
program = "${self.packages.${system}.default}/bin/gpclient"; program = "${self.packages.${system}.default}/bin/gpclient";
+97
View File
@@ -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")
'';
}
+15 -9
View File
@@ -29,13 +29,19 @@ exit 126
EOF EOF
chmod +x "$test_workspace/bin/pkexec" chmod +x "$test_workspace/bin/pkexec"
if PATH="$test_workspace/bin:$PATH" \ check_authorization() {
XDG_DATA_HOME="$test_workspace/data" \ rm -f "$test_workspace/data/gpclient/gpclient.log"
GP_TEST_SERVICE_BINARY="$package_path/bin/gpservice" \ if PATH="$test_workspace/bin:$PATH" \
"$package_path/bin/gpclient" launch-gui --minimized; then XDG_DATA_HOME="$test_workspace/data" \
echo "The desktop launcher ignored the authorization rejection" >&2 GP_TEST_SERVICE_BINARY="$package_path/bin/gpservice" \
exit 1 "$@"; then
fi 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' \ check_authorization "$package_path/bin/gpclient" launch-gui --minimized
"$test_workspace/data/gpclient/gpclient.log" check_authorization "$package_path/bin/gpclient" --lock-file "$test_workspace/client.lock" launch-gui
check_authorization "$package_path/bin/gpgui" --minimized