Add SSH connection validation for settings
This commit is contained in:
@@ -9,8 +9,11 @@ import paramiko
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from media_library_viewer_api.clients.ssh import RemoteSSHClient
|
||||
from media_library_viewer_api.config import get_settings
|
||||
from media_library_viewer_api.dependencies import get_monitoring_poller, get_settings_store
|
||||
from media_library_viewer_api.services.db_maintenance import remove_sqlite_database
|
||||
from media_library_viewer_api.services.known_hosts import ensure_known_host
|
||||
from media_library_viewer_api.services.media_index import MediaIndex
|
||||
from media_library_viewer_api.services.settings_store import SettingsStore
|
||||
|
||||
@@ -49,6 +52,106 @@ def get_machines(store: SettingsStore = Depends(get_settings_store)) -> list[dic
|
||||
return store.list_machines()
|
||||
|
||||
|
||||
def _resolve_ssh_client(
|
||||
machine: MonitoringMachineInput,
|
||||
store: SettingsStore,
|
||||
) -> tuple[RemoteSSHClient, str, int]:
|
||||
host = machine.host.strip()
|
||||
username = machine.username.strip()
|
||||
port = int(machine.port or 22)
|
||||
if not host or not username:
|
||||
raise HTTPException(status_code=400, detail="SSH machine is missing host or username")
|
||||
|
||||
private_key = machine.ssh_private_key
|
||||
passphrase = machine.ssh_private_key_passphrase
|
||||
if machine.ssh_key_id:
|
||||
ssh_key = store.get_ssh_key(machine.ssh_key_id)
|
||||
if ssh_key:
|
||||
private_key = str(ssh_key.get("private_key") or private_key)
|
||||
passphrase = str(ssh_key.get("passphrase") or passphrase)
|
||||
|
||||
key_filename = ""
|
||||
if machine.key_directory and machine.key_name:
|
||||
key_filename = f"{machine.key_directory}/{machine.key_name}"
|
||||
|
||||
settings = get_settings()
|
||||
client = RemoteSSHClient(
|
||||
host=host,
|
||||
username=username,
|
||||
port=port,
|
||||
key_filename=key_filename or None,
|
||||
private_key=private_key or None,
|
||||
private_key_passphrase=passphrase or None,
|
||||
password=machine.password or None,
|
||||
known_hosts_path=str(settings.ssh_known_hosts_file),
|
||||
)
|
||||
return client, host, port
|
||||
|
||||
|
||||
@router.post("/machines/test-ssh")
|
||||
def test_machine_ssh(
|
||||
machine: MonitoringMachineInput,
|
||||
store: SettingsStore = Depends(get_settings_store),
|
||||
) -> dict[str, Any]:
|
||||
if str(machine.mode or "").strip().lower() != "ssh":
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="SSH validation only applies to SSH machines")
|
||||
|
||||
client, host, port = _resolve_ssh_client(machine, store)
|
||||
settings = get_settings()
|
||||
try:
|
||||
known_hosts_updated = ensure_known_host(host, port, settings.ssh_known_hosts_file, strict=True)
|
||||
except RuntimeError as exc:
|
||||
message = str(exc)
|
||||
lowered = message.lower()
|
||||
if "protocol banner" in lowered:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=(
|
||||
f"SSH banner not received from {host}:{port}; the backend could not record the host key. "
|
||||
"Confirm the SSH service, host, and port are reachable."
|
||||
),
|
||||
) from exc
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=message) from exc
|
||||
|
||||
try:
|
||||
client.connect()
|
||||
except Exception as exc:
|
||||
message = str(exc)
|
||||
lowered = message.lower()
|
||||
if "protocol banner" in lowered:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=(
|
||||
f"SSH banner not received from {host}:{port}; the backend recorded the host key, "
|
||||
"but SSH auth could not be validated. Confirm the SSH service is running."
|
||||
),
|
||||
) from exc
|
||||
if "no authentication methods available" in lowered or "authentication failed" in lowered:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=(
|
||||
f"SSH banner received from {host}:{port}, but authentication failed. "
|
||||
"Check the selected SSH key, passphrase, username, or password."
|
||||
),
|
||||
) from exc
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"SSH validation failed for {host}:{port}: {message}",
|
||||
) from exc
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
return {
|
||||
"status": "ok",
|
||||
"message": (
|
||||
f"SSH connection succeeded for {host}:{port}; host key {'was recorded' if known_hosts_updated else 'was already trusted'} and authentication worked."
|
||||
),
|
||||
"host": host,
|
||||
"port": port,
|
||||
"known_hosts_updated": known_hosts_updated,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/machines", status_code=status.HTTP_201_CREATED)
|
||||
def post_machine(
|
||||
machine: MonitoringMachineInput,
|
||||
|
||||
Reference in New Issue
Block a user