Browse Source

Fix SSH key update on device re-registration

Previously, when a device re-registered, the new SSH key was ignored
and old credentials were returned. Now the key is updated in config
and authorized_keys is synced.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
root 2 weeks ago
parent
commit
5985797bd7
1 changed files with 19 additions and 2 deletions
  1. 19 2
      backend/app/api/v1/registration.py

+ 19 - 2
backend/app/api/v1/registration.py

@@ -77,13 +77,30 @@ async def register_device(
     device = result.scalar_one_or_none()
 
     if device:
-        # Return existing credentials
+        # Update SSH key if provided (device may have regenerated keys)
+        ssh_key_updated = False
+        if data.ssh_public_key:
+            new_key = data.ssh_public_key.strip()
+            old_key = (device.config or {}).get("ssh_public_key", "").strip()
+            if new_key != old_key:
+                # Update config with new key (preserve other settings)
+                new_config = {**(device.config or {}), "ssh_public_key": new_key}
+                device.config = new_config
+                ssh_key_updated = True
+                print(f"[REGISTRATION] Updated SSH key for device={mac_address}")
+
+        # Re-generate credentials if missing
         if not device.device_token or not device.device_password:
-            # Re-generate if missing
             device.device_token = _generate_token()
             device.device_password = _generate_password()
+
+        if ssh_key_updated or not device.device_token:
             await db.commit()
 
+        # Sync SSH keys if updated
+        if ssh_key_updated:
+            asyncio.create_task(sync_authorized_keys())
+
         return RegistrationResponse(
             device_token=device.device_token,
             device_password=device.device_password,