Files
nixpkgs/modules/nixos/pi-agent-wrapper.nix

103 lines
2.7 KiB
Nix
Raw Normal View History

{
cfg,
pkgs,
lib,
runner,
...
}:
with lib;
pkgs.writeShellScriptBin cfg.wrapper.commandName ''
set -euo pipefail
user_name="$(id -un)"
user_home="$(eval echo "~$user_name")"
if [ -z "$user_home" ] || [ "$user_home" = "~$user_name" ]; then
user_home="$HOME"
fi
resolve_user_policy() {
local user="$1"
USER_ROOTS=()
case "$user" in
${concatStringsSep "\n" (
mapAttrsToList (
user: userCfg: ''
${escapeShellArg user})
USER_ROOTS=(${concatStringsSep " " (map escapeShellArg userCfg.projectRoots)})
;;
''
)
cfg.hostUsers
)}
*)
return 1
;;
esac
return 0
}
if ! resolve_user_policy "$user_name"; then
echo "User '$user_name' is not allowed to use ${cfg.wrapper.commandName}" >&2
exit 1
fi
expand_home_path() {
local input="$1"
if [ "$input" = "~" ]; then
printf '%s\n' "$user_home"
elif ${pkgs.gnugrep}/bin/grep -q '^~/' <<<"$input"; then
printf '%s\n' "$user_home/''${input:2}"
elif ${pkgs.gnugrep}/bin/grep -q '^/' <<<"$input"; then
printf '%s\n' "$input"
else
printf '%s\n' "$user_home/$input"
fi
}
cwd_real="$(${pkgs.coreutils}/bin/realpath -m "$PWD")"
is_allowed_cwd=0
resolved_roots=()
skipped_roots=()
for configured_root in "''${USER_ROOTS[@]}"; do
expanded_root="$(expand_home_path "$configured_root")"
resolved_root="$(${pkgs.coreutils}/bin/realpath -m "$expanded_root")"
if [ ! -d "$resolved_root" ]; then
skipped_roots+=("$resolved_root")
continue
fi
resolved_roots+=("$resolved_root")
case "$cwd_real/" in
"$resolved_root"/*)
is_allowed_cwd=1
;;
esac
done
if [ "''${#resolved_roots[@]}" -eq 0 ]; then
echo "Denied: no valid existing project roots are configured for user '$user_name'." >&2
if [ "''${#skipped_roots[@]}" -gt 0 ]; then
echo "Configured but missing roots:" >&2
for root in "''${skipped_roots[@]}"; do
echo " - $root" >&2
done
fi
exit 1
fi
if [ "$is_allowed_cwd" -ne 1 ]; then
echo "Denied: '$cwd_real' is outside allowed project roots for user '$user_name'." >&2
echo "Allowed roots:" >&2
for root in "''${resolved_roots[@]}"; do
echo " - $root" >&2
done
exit 1
fi
exec /run/wrappers/bin/sudo --non-interactive \
${runner}/bin/${cfg.wrapper.runnerName} \
"$user_name" "$cwd_real" \
"TERM=$TERM" "LANG=$LANG" "LC_ALL=''${LC_ALL:-}" "LC_CTYPE=''${LC_CTYPE:-}" "COLORTERM=''${COLORTERM:-}" "TERM_PROGRAM=''${TERM_PROGRAM:-}" \
"$@"
''