diff --git a/nix/host-modules/lib/atomic-write-secret.nix b/nix/host-modules/lib/atomic-write-secret.nix index dccf7e9d..cf50e12a 100644 --- a/nix/host-modules/lib/atomic-write-secret.nix +++ b/nix/host-modules/lib/atomic-write-secret.nix @@ -26,12 +26,28 @@ atomic_write_secret() { local mode="$1" owner="$2" target="$3" tmp tmp="$(mktemp "$(dirname -- "$target")/.$(basename -- "$target").XXXXXX")" - trap 'rm -f "$tmp"' RETURN - cat > "$tmp" - chmod "$mode" "$tmp" - if [ -n "$owner" ]; then - chown "$owner" "$tmp" - fi + # The write happens in a subshell so its own EXIT trap cleans up `$tmp` + # on failure (a `RETURN` trap does not fire when `set -e` aborts the + # function mid-body) without touching an EXIT trap the calling script's + # own `script` may already have — subshell traps are local to the + # subshell. A named handler, not an inline trap string, so `local rc=$?` + # is a normal function-local assignment shellcheck can see: it only + # removes `$tmp` when `$?` is nonzero — on the ordinary path the + # subshell also exits successfully, and `$tmp` has to survive that to + # reach the `mv` below. + ( + _atomic_write_secret_cleanup() { + local rc=$? + [ "$rc" -eq 0 ] || rm -f "$tmp" + exit "$rc" + } + trap _atomic_write_secret_cleanup EXIT + cat > "$tmp" + chmod "$mode" "$tmp" + if [ -n "$owner" ]; then + chown "$owner" "$tmp" + fi + ) mv -f "$tmp" "$target" } '' diff --git a/nix/host-modules/swarm-bao.nix b/nix/host-modules/swarm-bao.nix index c517e763..459934f3 100644 --- a/nix/host-modules/swarm-bao.nix +++ b/nix/host-modules/swarm-bao.nix @@ -764,6 +764,8 @@ let forwarderSecretInContainer = "/var/lib/swarm-bao-otel-oidc/${cfg.otel.clientId}.secret"; forwarderHostSecretPath = "/var/lib/nixos-containers/${cfg.machine}${forwarderSecretInContainer}"; forwarderHostSecretDir = builtins.dirOf forwarderHostSecretPath; + + atomicWriteSecret = import ./lib/atomic-write-secret.nix { }; # The collector runs under `DynamicUser` and opens `client_secret_file` # itself, so there is no uid to hand a 0400 file to. `LoadCredential` reads # it as root before the sandbox exists and re-exposes it under a path that @@ -1797,6 +1799,8 @@ in script = '' set -euo pipefail + ${atomicWriteSecret} + # `bao`'s own message is the only thing separating a missing value # from a refused identity from an unreachable store, and this unit # retries on all three — so it reports which one rather than @@ -1837,10 +1841,7 @@ in # an argument in /proc the way `install <<<"$secret"` or an `echo` # from `path` would. install -d -m 0755 ${lib.escapeShellArg forwarderHostSecretDir} - umask 077 - printf '%s\n' "$secret" > ${lib.escapeShellArg forwarderHostSecretPath} - chown root:root ${lib.escapeShellArg forwarderHostSecretPath} - chmod 0400 ${lib.escapeShellArg forwarderHostSecretPath} + printf '%s\n' "$secret" | atomic_write_secret 0400 root:root ${lib.escapeShellArg forwarderHostSecretPath} ''; }; })