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
This commit is contained in:
rcourtman 2025-10-13 14:35:06 +00:00
parent e0d7cc7f58
commit 8d6ab4113d

View file

@ -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