From ff3caf1db67c4f83c7d293f46e25aa10bc07dab5 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Mon, 16 Nov 2026 10:25:23 -0600 Subject: [PATCH] feat(nixos): keyring auto-unlock after out-of-session daemon restarts (code#10724) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit At graphical login, pam_exec stashes the login password in the kernel user keyring (RAM-only, never on disk). A systemd user .path unit watches the gnome-keyring-daemon control socket and runs keyring-auto-unlock on every daemon (re)start: if the default collection is locked and a cached password exists, it feeds the cache to gnome-keyring-daemon --unlock. Degradation is always to the previous behavior (no login since boot or stale cache = stays locked). Fixes the orphaned draft's critical D-Bus bug: bus name org.freedesktop.secrets vs interfaces org.freedesktop.Secret.* — the draft used the plural for both, so the unlocker silently exited 0 without ever reaching the daemon. Test harness rewritten per task 17508 experiments; isolated test proves addressing, stash round-trip, real unlock attempt with no silent success, no-cache degradation, already-unlocked no-op (ALL PASS, shellcheck clean). --- nixos/hosts/default.nix | 9 ++ .../services/keyring-auto-unlock/default.nix | 120 ++++++++++++++ .../keyring-auto-unlock.sh | 76 +++++++++ .../keyring-auto-unlock.test.sh | 150 ++++++++++++++++++ .../keyring-password-stash.sh | 61 +++++++ nixos/users/user/default.nix | 3 + 6 files changed, 419 insertions(+) create mode 100644 nixos/services/keyring-auto-unlock/default.nix create mode 100755 nixos/services/keyring-auto-unlock/keyring-auto-unlock.sh create mode 100755 nixos/services/keyring-auto-unlock/keyring-auto-unlock.test.sh create mode 100755 nixos/services/keyring-auto-unlock/keyring-password-stash.sh diff --git a/nixos/hosts/default.nix b/nixos/hosts/default.nix index 4d152ad986..7c28e51f01 100644 --- a/nixos/hosts/default.nix +++ b/nixos/hosts/default.nix @@ -31,6 +31,7 @@ in "services/openai-cred-watchdog" "services/opencode-go-seating-guard" "services/opencode-watchdog" + "services/keyring-auto-unlock" # "microvm" # "server" "networking/dhcp-nat" @@ -126,6 +127,14 @@ in if m == null then "" else builtins.head m; }; } + { + # Keyring auto-unlock (code#10724): re-unlock the GNOME login + # keyring after out-of-session daemon restarts. Caches the + # login password in the kernel user keyring at graphical login + # (RAM-only, never disk) and replays it via a .path-triggered + # user oneshot when the daemon control socket changes. + services.keyring-auto-unlock.enable = true; + } { # Laptop backups (code#1516, dezren39/nix#976): the dashboard # backup (local + R2 + Drive) and the repo-archive restic job, diff --git a/nixos/services/keyring-auto-unlock/default.nix b/nixos/services/keyring-auto-unlock/default.nix new file mode 100644 index 0000000000..9c98ede096 --- /dev/null +++ b/nixos/services/keyring-auto-unlock/default.nix @@ -0,0 +1,120 @@ +# keyring-auto-unlock — re-unlock gnome-keyring after daemon restarts (code#10724). +# +# Problem: the login keyring unlocks via PAM at graphical login, but a +# gnome-keyring-daemon restart outside a login session (e.g. the +# 2026-11-16 ~05:38 recovery restart) leaves it LOCKED until a human +# unlocks it at the screen — blocking every Secret Service consumer +# (agy's login lives there) with no prompter to answer. +# +# Mechanism (no password ever touches disk): +# 1. At graphical login, pam_exec (expose_authtok) in the sddm/login +# PAM stacks pipes the typed password into keyring-password-stash, +# which keeps it in the kernel user keyring (RAM-only, UID-scoped; +# reboot clears it, the next login re-stashes it). +# 2. A systemd user .path unit watches the daemon control socket and +# runs keyring-auto-unlock (oneshot) on every (re)start. If the +# default collection is locked and a cached password exists, the +# script feeds it to `gnome-keyring-daemon --unlock` and retries +# while the daemon initializes. +# +# Degradation is always to today's behavior: no cache (no login since +# boot) or a stale cache (password changed) leaves the keyring locked, +# exactly as now; the next graphical login refreshes the cache. The +# legacy capital-`Login` collection (pre-existing, locked, empty +# labels) is intentionally untouched — the default `login` keyring is +# what PAM and agy use. +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.services.keyring-auto-unlock; + + # This nixpkgs pin predates writers.writeShellApplication, so wrap + # writeBashBin outputs with makeWrapper for runtime PATH. (The + # sources are shellcheck-clean; re-check after edits with: + # shellcheck -S warning nixos/services/keyring-auto-unlock/*.sh) + mkWrappedBin = + name: src: deps: + pkgs.runCommand "${name}-wrapped" { nativeBuildInputs = [ pkgs.makeWrapper ]; } '' + mkdir -p $out/bin + makeWrapper ${pkgs.writers.writeBashBin name (builtins.readFile src)}/bin/${name} \ + $out/bin/${name} \ + --prefix PATH : ${lib.makeBinPath deps} + ''; + + stashPkg = mkWrappedBin "keyring-password-stash" ./keyring-password-stash.sh [ + pkgs.keyutils + pkgs.util-linux + ]; + + unlockPkg = mkWrappedBin "keyring-auto-unlock" ./keyring-auto-unlock.sh [ + pkgs.keyutils + pkgs.systemd + pkgs.gnome-keyring + ]; + + # pam_exec invocation: flags first, store-path command last (the + # command is everything after the last recognized flag). `optional` + # so a stash failure can never fail a login; the stash script itself + # also exits 0 unconditionally for the same reason. + stashRule = { + enable = true; + control = "optional"; + modulePath = "${pkgs.linux-pam}/lib/security/pam_exec.so"; + order = cfg.pamOrder; + args = [ + "expose_authtok" + "quiet" + "${stashPkg}/bin/keyring-password-stash" + ]; + }; +in +{ + options.services.keyring-auto-unlock = { + enable = lib.mkEnableOption "re-unlock of the GNOME login keyring after out-of-session daemon restarts (code#10724)"; + + user = lib.mkOption { + type = lib.types.str; + default = "user"; + description = "The user whose login password is cached and whose keyring is re-unlocked."; + }; + + pamOrder = lib.mkOption { + type = lib.types.int; + default = 12400; + description = "PAM auth order for the stash rule: after pam_unix/keyring auth (so authtok exists), before final unix sufficient."; + }; + }; + + config = lib.mkIf cfg.enable { + security.pam.services.sddm.rules.auth.keyring_stash = stashRule; + security.pam.services.login.rules.auth.keyring_stash = stashRule; + + home-manager.users.${cfg.user} = { + # keyctl on the user PATH: the test script and manual cache + # inspection use it directly (the packaged scripts carry their + # own wrapped PATH and do not rely on this). + home.packages = [ pkgs.keyutils ]; + + systemd.user.services.keyring-auto-unlock = { + Unit.Description = "Re-unlock GNOME login keyring from login-cached password after daemon restart (code#10724)"; + Service = { + Type = "oneshot"; + ExecStart = "${unlockPkg}/bin/keyring-auto-unlock"; + }; + }; + + systemd.user.paths.keyring-auto-unlock = { + Unit.Description = "Watch gnome-keyring-daemon control socket for restarts (code#10724)"; + Path = { + PathChanged = "%t/keyring/control"; + Unit = "keyring-auto-unlock.service"; + }; + Install.WantedBy = [ "default.target" ]; + }; + }; + }; +} diff --git a/nixos/services/keyring-auto-unlock/keyring-auto-unlock.sh b/nixos/services/keyring-auto-unlock/keyring-auto-unlock.sh new file mode 100755 index 0000000000..d3c7ac2fea --- /dev/null +++ b/nixos/services/keyring-auto-unlock/keyring-auto-unlock.sh @@ -0,0 +1,76 @@ +# keyring-auto-unlock — re-unlock gnome-keyring after daemon restarts (code#10724). +# +# Triggered by the keyring-auto-unlock.path unit whenever the daemon's +# control socket changes (i.e. the daemon (re)started), and safe to run +# any time: it exits 0 without doing anything when the default +# collection is already unlocked or when no cached password exists +# (e.g. no graphical login has happened since boot — the pre-login +# state keeps today's behavior, per the repo doctrine that +# boot-independent services must use file-based secrets). +# +# The password comes from the kernel user keyring entry written by +# keyring-password-stash at graphical login — never from disk. +# Nothing secret is printed: stdout/stderr carry fixed strings only. +# +# Command line: none. Env: KEYRING_CACHE_KEY overrides the kernel key +# name (tests use a scratch key); KEYRING_UNLOCK_ATTEMPTS overrides +# the unlock retry count (tests use a small number). +set -euo pipefail + +KEYRING_CACHE_KEY="${KEYRING_CACHE_KEY:-keyring:login-unlock}" +KEYRING_UNLOCK_ATTEMPTS="${KEYRING_UNLOCK_ATTEMPTS:-30}" + +if [ $# -ne 0 ]; then + echo "usage: keyring-auto-unlock (no arguments)" >&2 + exit 2 +fi + +# D-Bus addressing (verified against a live daemon, task 17508): +# the well-known bus NAME is org.freedesktop.secrets (plural), the +# object path is /org/freedesktop/secrets, but the INTERFACES are +# org.freedesktop.Secret.Service / .Collection (singular "Secret"). +# Confusing the name with the interface prefix makes every call fail +# and the unlocker exit 0 silently — the draft bug this fixes. +NAME="org.freedesktop.secrets" +IFACE="org.freedesktop.Secret" +SERVICE_PATH="/org/freedesktop/secrets" + +# Resolve the default collection (the "login" keyring PAM manages). +collection="$(busctl --user call "${NAME}" "${SERVICE_PATH}" \ + "${IFACE}.Service" ReadAlias s default 2>/dev/null | sed -n 's/^o "\(.*\)"$/\1/p')" || collection="" +if [ -z "${collection}" ]; then + echo "keyring-auto-unlock: Secret Service not reachable; daemon may still be starting" >&2 + exit 0 +fi + +locked="$(busctl --user get-property "${NAME}" "${collection}" \ + "${IFACE}.Collection" Locked 2>/dev/null | awk '{print $2}')" || locked="" +if [ "${locked}" != "true" ]; then + exit 0 +fi + +key_id="$(keyctl search @u user "${KEYRING_CACHE_KEY}" 2>/dev/null)" || key_id="" +if [ -z "${key_id}" ]; then + echo "keyring-auto-unlock: collection locked and no cached password (login since boot?); leaving locked" >&2 + exit 0 +fi + +# The daemon may still be initializing (control socket exists before +# the bus name is claimable), so retry the unlock for a while. +attempt=0 +while [ "${attempt}" -lt "${KEYRING_UNLOCK_ATTEMPTS}" ]; do + if keyctl pipe "${key_id}" 2>/dev/null | gnome-keyring-daemon --unlock >/dev/null 2>&1; then + sleep 1 + locked="$(busctl --user get-property "${NAME}" "${collection}" \ + "${IFACE}.Collection" Locked 2>/dev/null | awk '{print $2}')" || locked="true" + if [ "${locked}" != "true" ]; then + echo "keyring-auto-unlock: default collection re-unlocked after daemon restart" + exit 0 + fi + fi + attempt=$((attempt + 1)) + sleep 1 +done + +echo "keyring-auto-unlock: unlock attempted but collection still locked (cached password may predate a password change; next graphical login refreshes it)" >&2 +exit 1 diff --git a/nixos/services/keyring-auto-unlock/keyring-auto-unlock.test.sh b/nixos/services/keyring-auto-unlock/keyring-auto-unlock.test.sh new file mode 100755 index 0000000000..d3ac8e7c1c --- /dev/null +++ b/nixos/services/keyring-auto-unlock/keyring-auto-unlock.test.sh @@ -0,0 +1,150 @@ +#!/usr/bin/env bash +# keyring-auto-unlock.test.sh — isolated acceptance for code#10724. +# +# Spins a fully isolated Secret Service (private bus via +# dbus-run-session, scratch HOME + XDG_RUNTIME_DIR, scratch kernel-key +# name) and proves every leg of the mechanism that a headless session +# can prove: +# 1. addressing: the default collection resolves over the real +# Secret Service bus name/interface and reports Locked=true in +# the fresh state (a restarted daemon presenting a locked +# default collection is the reported bug state). The draft bug +# (interface org.freedesktop.secrets.* instead of +# org.freedesktop.Secret.*) made this resolution return empty. +# 2. stash: the packaged keyring-password-stash caches the password +# in the kernel user keyring, byte-exact, and replaces it on a +# second run; empty input caches nothing. +# 3. real attempt, no silent success: with the collection locked +# and a cache present, the packaged keyring-auto-unlock feeds +# the cache to gnome-keyring-daemon --unlock and reports +# still-locked (exit 1) when the daemon does not unlock — the +# draft exited 0 silently here without ever reaching the daemon. +# (In this scratch HOME there is no login.keyring file for +# --unlock to decrypt; on the deployed system the file exists +# from the real PAM login, which is the state --unlock acts on.) +# 4. no cache: with the cache dropped, the unlocker degrades to +# today's behavior — exit 0, keyring left locked, named reason. +# 5. already unlocked: with the default alias pointed at the +# (always-unlocked) session collection, the unlocker is a +# silent no-op, exit 0. +# +# Boundary, established by experiment on 2026-11-16 (task 17508): a +# headless session cannot mint a login.keyring file — the daemon's +# --login/--start/--unlock paths create none without a real PAM +# session, and Secret Service CreateCollection requires an +# interactive prompter. The file-backed unlock leg is therefore +# exercised on the deployed system (post-switch live check recorded +# on issue #10724), not here. Nothing in this test touches the live +# daemon, the live collections, or the real cache key; the scratch +# kernel key is unlinked on exit (trap). +# +# Usage: keyring-auto-unlock.test.sh (no arguments). Needs the +# deployed package paths (post-switch): /run/current-system/sw/bin, +# and keyctl on PATH (the module installs keyutils for the user). +# Env knobs (tests/CI only): STASH_BIN, UNLOCK_BIN. +set -euo pipefail + +if [ $# -ne 0 ]; then + echo "usage: keyring-auto-unlock.test.sh (no arguments)" >&2 + exit 2 +fi + +STASH_BIN="${STASH_BIN:-/run/current-system/sw/bin/keyring-password-stash}" +UNLOCK_BIN="${UNLOCK_BIN:-/run/current-system/sw/bin/keyring-auto-unlock}" +TEST_KEY="keyring-auto-unlock-test-v1" +TEST_PW="correct horse battery staple $(date +%s)" + +command -v dbus-run-session >/dev/null || { echo "need dbus-run-session"; exit 2; } +command -v keyctl >/dev/null || { echo "need keyctl (keyutils)"; exit 2; } +[ -x "${STASH_BIN}" ] || { echo "missing ${STASH_BIN} (switch first?)"; exit 2; } +[ -x "${UNLOCK_BIN}" ] || { echo "missing ${UNLOCK_BIN} (switch first?)"; exit 2; } + +export KEYRING_CACHE_KEY="${TEST_KEY}" +export KEYRING_UNLOCK_ATTEMPTS=3 +cleanup_key() { keyctl unlink "$(keyctl search @u user "${TEST_KEY}" 2>/dev/null)" @u 2>/dev/null || true; } +cleanup_key + +T="$(mktemp -d "${TMPDIR:-/tmp}/kringtest.XXXXXX")" +mkdir -p "${T}/home" "${T}/run" +trap 'cleanup_key; rm -rf "${T}"' EXIT + +cat >"${T}/body.sh" <<'BODY' +set -euo pipefail +NAME="org.freedesktop.secrets" +IFACE="org.freedesktop.Secret" +SP="/org/freedesktop/secrets" + +default_col() { + busctl --user call "${NAME}" "${SP}" "${IFACE}.Service" ReadAlias s default 2>/dev/null | sed -n 's/^o "\(.*\)"$/\1/p' +} +locked_of() { + busctl --user get-property "${NAME}" "$1" "${IFACE}.Collection" Locked 2>/dev/null | awk '{print $2}' +} + +start_daemon() { + gnome-keyring-daemon --foreground --components=secrets &>"${T}/daemon-$1.log" & + echo $! >"${T}/daemon.pid" + for _ in $(seq 1 50); do + [ -S "${XDG_RUNTIME_DIR}/keyring/control" ] && break + sleep 0.2 + done + for _ in $(seq 1 50); do + busctl --user list 2>/dev/null | grep -q "^org.freedesktop.secrets" && break + sleep 0.2 + done + [ -S "${XDG_RUNTIME_DIR}/keyring/control" ] || { echo "daemon $1 never created control socket" >&2; return 1; } +} + +stop_daemon() { + kill -9 "$(cat "${T}/daemon.pid")" 2>/dev/null || true + sleep 1 + rm -f "${XDG_RUNTIME_DIR}/keyring/control" +} + +echo "--- 1. addressing: fresh daemon, default collection locked" +start_daemon 1 +COL="$(default_col)" +[ -n "${COL}" ] || { echo "FAIL: default collection did not resolve (D-Bus addressing broken)"; exit 1; } +[ "$(locked_of "${COL}")" = "true" ] || { echo "FAIL: expected locked default collection in fresh state"; exit 1; } +echo "ok: default collection ${COL} resolves and is locked" + +echo "--- 2. stash caches the password byte-exact and replaces it" +printf "%s\n" "${TEST_PW}" | KEYRING_STASH_USER="$(id -un)" "${STASH_BIN}" >/dev/null +KID="$(keyctl search @u user "${KEYRING_CACHE_KEY}" 2>/dev/null)" || KID="" +[ -n "${KID}" ] || { echo "FAIL: stash did not create kernel key"; exit 1; } +[ "$(keyctl pipe "${KID}")" = "${TEST_PW}" ] || { echo "FAIL: cached value mismatch"; exit 1; } +printf "%s\n" "${TEST_PW}-v2" | KEYRING_STASH_USER="$(id -un)" "${STASH_BIN}" >/dev/null +[ "$(keyctl pipe "$(keyctl search @u user "${KEYRING_CACHE_KEY}")")" = "${TEST_PW}-v2" ] || { echo "FAIL: stash did not replace cached value"; exit 1; } +printf "%s\n" "${TEST_PW}" | KEYRING_STASH_USER="$(id -un)" "${STASH_BIN}" >/dev/null +echo "ok: stash round-trip + replace" + +echo "--- 3. unlocker attempts against the locked collection (no silent success)" +if "${UNLOCK_BIN}" >"${T}/unlock3.out" 2>"${T}/unlock3.err"; then + echo "FAIL: unlocker exited 0 although the collection stayed locked (silent no-op regression)" + exit 1 +fi +grep -q "still locked" "${T}/unlock3.err" || { echo "FAIL: unlocker did not report the still-locked outcome"; cat "${T}/unlock3.err"; exit 1; } +[ "$(locked_of "${COL}")" = "true" ] || { echo "FAIL: collection state changed unexpectedly"; exit 1; } +echo "ok: unlocker reached the daemon, attempted, and reported still-locked" + +echo "--- 4. no cache: graceful degradation, exit 0" +keyctl unlink "$(keyctl search @u user "${KEYRING_CACHE_KEY}")" @u +"${UNLOCK_BIN}" >"${T}/unlock4.out" 2>"${T}/unlock4.err" +grep -q "no cached password" "${T}/unlock4.err" || { echo "FAIL: no-cache path did not name its reason"; cat "${T}/unlock4.err"; exit 1; } +echo "ok: no-cache degradation" + +echo "--- 5. already unlocked: silent no-op" +busctl --user call "${NAME}" "${SP}" "${IFACE}.Service" SetAlias so default /org/freedesktop/secrets/collection/session >/dev/null +OUT="$("${UNLOCK_BIN}" 2>&1)" +[ -z "${OUT}" ] || { echo "FAIL: unlocker spoke on the already-unlocked path: ${OUT}"; exit 1; } +busctl --user call "${NAME}" "${SP}" "${IFACE}.Service" SetAlias so default "${COL}" >/dev/null +echo "ok: already-unlocked no-op" + +stop_daemon +echo "ALL PASS" +BODY + +env HOME="${T}/home" XDG_RUNTIME_DIR="${T}/run" \ + TEST_PW="${TEST_PW}" TEST_KEY="${TEST_KEY}" T="${T}" \ + STASH_BIN="${STASH_BIN}" UNLOCK_BIN="${UNLOCK_BIN}" \ + dbus-run-session -- bash "${T}/body.sh" diff --git a/nixos/services/keyring-auto-unlock/keyring-password-stash.sh b/nixos/services/keyring-auto-unlock/keyring-password-stash.sh new file mode 100755 index 0000000000..e65d319b00 --- /dev/null +++ b/nixos/services/keyring-auto-unlock/keyring-password-stash.sh @@ -0,0 +1,61 @@ +# keyring-password-stash — PAM auth helper (code#10724). +# +# Called by pam_exec (expose_authtok) from the graphical-login PAM stack. +# Reads the just-typed login password from stdin and stashes it in the +# kernel user keyring, where keyring-auto-unlock can reach it after an +# out-of-session gnome-keyring-daemon restart. The password is NEVER +# written to disk: kernel keyrings are RAM-only, UID-scoped, and die +# with the user (reboot clears them; the next graphical login +# re-stashes). This satisfies the issue's "does NOT store the keyring +# password in plaintext" constraint — there is no file to steal, only +# a live in-memory key readable by this UID. +# +# Command line: none. Reads stdin (PAM authtok + one trailing newline), +# configured via env: KEYRING_CACHE_KEY (default below), +# KEYRING_STASH_USER (default below). +# Exits 0 always: a stash failure must never fail a login (the PAM +# rule is `optional`, and this is belt-and-braces). +KEYRING_CACHE_KEY="${KEYRING_CACHE_KEY:-keyring:login-unlock}" +# pam_exec exports PAM_USER for the authenticating user; honor an +# explicit override (tests) the same way. +KEYRING_STASH_USER="${KEYRING_STASH_USER:-${PAM_USER:-user}}" + +if [ $# -ne 0 ]; then + echo "usage: keyring-password-stash (no arguments; reads password from stdin)" >&2 + exit 2 +fi + +# Run a command as the target user when we are root (PAM auth runs as +# root); otherwise run it directly (tests, manual runs). +as_target() { + if [ "$(id -u)" -eq 0 ]; then + runuser -u "${KEYRING_STASH_USER}" -- "$@" + else + "$@" + fi +} + +# PAM appends a single trailing newline to the authtok; command +# substitution already strips all trailing newlines, the extra trim is +# explicit documentation. Empty input (fingerprint login, autologin, +# no password) means there is nothing to cache — exit quietly. +password="$(cat)" +password="${password%$'\n'}" +if [ -z "${password}" ]; then + exit 0 +fi + +# Replace any previous entry (e.g. from an earlier login) so a changed +# password cannot linger beside the current one. +old_id="$(as_target keyctl search @u user "${KEYRING_CACHE_KEY}" 2>/dev/null)" || old_id="" +if [ -n "${old_id}" ]; then + as_target keyctl unlink "${old_id}" @u 2>/dev/null || true +fi + +if ! printf '%s' "${password}" | as_target keyctl padd user "${KEYRING_CACHE_KEY}" @u >/dev/null 2>&1; then + echo "keyring-password-stash: failed to cache login password in kernel keyring" >&2 +fi + +# Drop the secret from this shell's memory as far as bash allows. +password="" +exit 0 diff --git a/nixos/users/user/default.nix b/nixos/users/user/default.nix index b94df81b47..f46be0a183 100644 --- a/nixos/users/user/default.nix +++ b/nixos/users/user/default.nix @@ -27,6 +27,9 @@ # Linger does NOT unlock the GNOME keyring: keyring-held credentials still # need a graphical login, so boot-independent services must use file-based # secrets (sops / Bitwarden), never the keyring or the interactive gh token. + # Post-login daemon restarts now self-heal via + # services.keyring-auto-unlock (code#10724); the pre-login window above + # is unchanged by design. linger = true; hashedPasswordFile = config.sops.secrets."users/user/passwordHash".path; description = "user";