Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

fix(security): join SSH key ids to the lines delete actually pops

Juan Denis3de88b5f826a
diff --git a/backend/app/services/security_service.py b/backend/app/services/security_service.py
index 1aaec447..87df04a4 100644
--- a/backend/app/services/security_service.py
+++ b/backend/app/services/security_service.py
@@ -1042,10 +1042,16 @@ class SecurityService:
try:
keys = []
with open(auth_keys_path, 'r') as f:
- for idx, line in enumerate(f):
+ # The id must index the same sequence remove_ssh_key pops
+ # from: non-blank, non-comment lines in file order. Numbering
+ # over raw file lines shifts every id past a comment banner,
+ # so delete-by-id would remove the wrong key.
+ key_idx = -1
+ for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
+ key_idx += 1
parts = line.split()
if len(parts) >= 2:
@@ -1056,7 +1062,7 @@ class SecurityService:
fingerprint = cls._get_key_fingerprint(line)
keys.append({
- 'id': idx,
+ 'id': key_idx,
'type': key_type,
'fingerprint': fingerprint,
'comment': comment,
@@ -1102,12 +1108,21 @@ class SecurityService:
try:
os.makedirs(ssh_dir, mode=0o700, exist_ok=True)
+ existing = ''
if os.path.exists(auth_keys_path):
with open(auth_keys_path, 'r') as f:
- if key in f.read():
+ existing = f.read()
+ # Compare the key-data token, not a raw substring: a key whose
+ # text happens to be contained in a longer line is not the
+ # same key.
+ for existing_line in existing.splitlines():
+ existing_parts = existing_line.split()
+ if len(existing_parts) >= 2 and existing_parts[1] == parts[1]:
return {'success': False, 'error': 'Key already exists'}
with open(auth_keys_path, 'a') as f:
+ if existing and not existing.endswith('\n'):
+ f.write('\n')
f.write(key + '\n')
os.chmod(auth_keys_path, 0o600)
@@ -1132,22 +1147,19 @@ class SecurityService:
with open(auth_keys_path, 'r') as f:
lines = f.readlines()
- key_lines = []
- other_lines = []
- for line in lines:
- stripped = line.strip()
- if stripped and not stripped.startswith('#'):
- key_lines.append(line)
- else:
- other_lines.append(line)
+ # Same id space as get_ssh_keys: the nth non-blank, non-comment
+ # line. Delete it in place so comments/blank lines keep their
+ # position and the remaining ids stay stable.
+ key_indices = [i for i, line in enumerate(lines)
+ if line.strip() and not line.strip().startswith('#')]
- if key_id < 0 or key_id >= len(key_lines):
+ if key_id < 0 or key_id >= len(key_indices):
return {'success': False, 'error': 'Invalid key ID'}
- key_lines.pop(key_id)
+ del lines[key_indices[key_id]]
with open(auth_keys_path, 'w') as f:
- f.writelines(other_lines + key_lines)
+ f.writelines(lines)
return {'success': True, 'message': 'SSH key removed'}
diff --git a/backend/tests/test_ssh_keys_roundtrip.py b/backend/tests/test_ssh_keys_roundtrip.py
new file mode 100644
index 00000000..8e519122
--- /dev/null
+++ b/backend/tests/test_ssh_keys_roundtrip.py
@@ -0,0 +1,109 @@
+"""authorized_keys list ↔ remove round trip.
+
+get_ssh_keys numbered keys over raw file lines (comments and blanks included)
+while remove_ssh_key popped that id from a list of key lines only, so any
+comment banner in authorized_keys shifted every id and delete-by-id removed
+the wrong key — the same write/read join-key mismatch as the cron #117 bug.
+These tests pin the cycle: list → remove by the listed id → list again and
+assert the right key went away and the file kept its shape.
+"""
+
+import pytest
+
+from app.services.security_service import SecurityService
+
+
+KEY_A = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKeyAlicelicealice alice@laptop'
+KEY_B = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKeyBobbobbobbobbob bob@desktop'
+KEY_C = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABKeyCarolcarolcarol carol@ci'
+
+
+def auth_keys(tmp_path, monkeypatch):
+ """Point the service at a temp authorized_keys and stub the fingerprint
+ subprocess so no ssh-keygen is spawned."""
+ path = tmp_path / 'authorized_keys'
+ monkeypatch.setattr(SecurityService, 'SSH_DIR', str(tmp_path))
+ monkeypatch.setattr(SecurityService, 'AUTHORIZED_KEYS', str(path))
+ monkeypatch.setattr(
+ SecurityService, '_get_key_fingerprint',
+ classmethod(lambda cls, line: 'SHA256:' + line.split()[1][:8]))
+ return path
+
+
+def _write(path, *lines):
+ path.write_text('\n'.join(lines) + '\n')
+
+
+def test_ids_index_key_lines_not_file_lines(auth_keys):
+ _write(auth_keys, '# cloud-init banner', '', KEY_A, KEY_B)
+
+ result = SecurityService.get_ssh_keys()
+ assert result['success']
+ assert [k['id'] for k in result['keys']] == [0, 1]
+ assert result['keys'][0]['comment'] == 'alice@laptop'
+
+
+def test_remove_by_listed_id_removes_that_key(auth_keys):
+ _write(auth_keys, '# cloud-init banner', KEY_A, KEY_B, KEY_C)
+
+ listed = SecurityService.get_ssh_keys()['keys']
+ alice = next(k for k in listed if k['comment'] == 'alice@laptop')
+
+ assert SecurityService.remove_ssh_key(alice['id'])['success']
+
+ content = auth_keys.read_text()
+ assert 'alice@laptop' not in content
+ assert 'bob@desktop' in content
+ assert 'carol@ci' in content
+
+
+def test_remove_last_listed_key_is_valid(auth_keys):
+ # With the old raw-line ids, the banner made the last key's id exceed
+ # len(key_lines) and delete answered "Invalid key ID".
+ _write(auth_keys, '# banner one', '# banner two', KEY_A, KEY_B)
+
+ last = SecurityService.get_ssh_keys()['keys'][-1]
+ result = SecurityService.remove_ssh_key(last['id'])
+ assert result['success'], result
+ assert 'bob@desktop' not in auth_keys.read_text()
+
+
+def test_remove_preserves_comment_positions(auth_keys):
+ _write(auth_keys, '# alice below', KEY_A, '# bob below', KEY_B)
+
+ assert SecurityService.remove_ssh_key(0)['success']
+ assert auth_keys.read_text().splitlines() == [
+ '# alice below', '# bob below', KEY_B]
+
+
+def test_ids_stay_joined_across_removals(auth_keys):
+ _write(auth_keys, '# banner', KEY_A, KEY_B, KEY_C)
+
+ for victim in ('bob@desktop', 'carol@ci', 'alice@laptop'):
+ key = next(k for k in SecurityService.get_ssh_keys()['keys']
+ if k['comment'] == victim)
+ assert SecurityService.remove_ssh_key(key['id'])['success']
+ assert victim not in auth_keys.read_text()
+
+ assert SecurityService.get_ssh_keys()['keys'] == []
+
+
+def test_add_appends_cleanly_without_trailing_newline(auth_keys):
+ auth_keys.write_text(KEY_A) # no trailing newline
+
+ assert SecurityService.add_ssh_key(KEY_B)['success']
+
+ lines = auth_keys.read_text().splitlines()
+ assert lines == [KEY_A, KEY_B]
+
+
+def test_add_duplicate_matches_key_data_not_substring(auth_keys):
+ _write(auth_keys, KEY_A)
+
+ dup = SecurityService.add_ssh_key(KEY_A + ' renamed@host')
+ assert not dup['success']
+
+ # A different key must not be rejected just because its text shares a
+ # prefix with an existing line.
+ assert SecurityService.add_ssh_key(KEY_B)['success']