From 8d6ab4113de03fb0e4ee914021cbbd13215d506c Mon Sep 17 00:00:00 2001 From: rcourtman Date: Mon, 13 Oct 2025 14:35:06 +0000 Subject: [PATCH] fix: Handle authorized_keys removal when all keys are managed Codex caught an edge case in the authorized_keys removal logic: **Problem:** When authorized_keys contains ONLY pulse-managed keys, `grep -vF` returns exit code 1 (no lines matched the inverse filter). The previous code only executed the rewrite on exit 0, leaving managed keys in place when they should have been removed. **Solution:** - Capture grep exit code explicitly - Treat both exit 0 (lines remain) and exit 1 (all removed) as success - Only treat exit codes > 1 as actual errors - Properly handles the "remove all keys" scenario This ensures complete removal works even when the file contains nothing but Pulse-managed entries. Addresses #123 --- internal/api/config_handlers.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.go index fc8030e..98b8e84 100644 --- a/internal/api/config_handlers.go +++ b/internal/api/config_handlers.go @@ -3111,7 +3111,11 @@ if [[ $MAIN_ACTION =~ ^[Rr]$ ]]; then TMP_AUTH_KEYS=$(mktemp) if [ -f "$TMP_AUTH_KEYS" ]; then # Remove only lines with pulse-managed-key marker (preserves user keys) - if grep -vF '# pulse-managed-key' /root/.ssh/authorized_keys > "$TMP_AUTH_KEYS" 2>/dev/null; then + grep -vF '# pulse-managed-key' /root/.ssh/authorized_keys > "$TMP_AUTH_KEYS" 2>/dev/null + GREP_EXIT=$? + + # Exit 0 = lines remain, Exit 1 = all lines removed (both are success) + if [ $GREP_EXIT -eq 0 ] || [ $GREP_EXIT -eq 1 ]; then # Preserve ownership and permissions from original chmod --reference=/root/.ssh/authorized_keys "$TMP_AUTH_KEYS" 2>/dev/null || chmod 600 "$TMP_AUTH_KEYS" chown --reference=/root/.ssh/authorized_keys "$TMP_AUTH_KEYS" 2>/dev/null || true @@ -3123,7 +3127,7 @@ if [[ $MAIN_ACTION =~ ^[Rr]$ ]]; then rm -f "$TMP_AUTH_KEYS" fi else - # Cleanup temp file if grep failed + # Cleanup temp file if grep had a real error (exit > 1) rm -f "$TMP_AUTH_KEYS" fi fi