"""Per-account OpenSSH public keys for cloud-image guest access. Only public key material is stored. Every lookup and mutation includes the authenticated user's database ID, so an ID from another account is not an authorization bypass. The unique fingerprint is calculated from the decoded SSH wire-format blob, independent of whitespace or a trailing comment. """ from __future__ import annotations import base64 import hashlib import time from typing import Any from .cloud_init import _validate_ssh_public_key from .database import DatabaseError, DatabaseStore, pymysql class SSHKeyError(Exception): def __init__(self, message: str, status: int = 400) -> None: super().__init__(message) self.status = status def _user_id(value: int) -> int: if isinstance(value, bool) or not isinstance(value, int) or value < 1: raise ValueError("Invalid user ID") return value def _key_id(value: int) -> int: if isinstance(value, bool) or not isinstance(value, int) or value < 1: raise ValueError("Invalid SSH key ID") return value def _name(value: str) -> str: if (not isinstance(value, str) or value != value.strip() or not 1 <= len(value) <= 80 or any(ord(char) < 32 or ord(char) == 127 for char in value)): raise SSHKeyError("公钥名称须为 1 至 80 个非控制字符") return value def _public_key(value: str) -> tuple[str, str]: try: validated = _validate_ssh_public_key(value) except ValueError as exc: raise SSHKeyError(str(exc)) from exc key_type, encoded = validated.split(maxsplit=2)[:2] blob = base64.b64decode(encoded, validate=True) # Comments are operator hints, not key material. The user-chosen name is # retained instead, and the canonical form avoids charset surprises. canonical = f"{key_type} {base64.b64encode(blob).decode('ascii')}" fingerprint = "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode("ascii").rstrip("=") return canonical, fingerprint def _row(row: dict[str, Any] | None) -> dict[str, Any] | None: if row is None: return None return { "id": int(row["id"]), "name": row["name"], "public_key": row["public_key"], "fingerprint": row["fingerprint"], "created_at": int(row["created_at"]), } class DatabaseSSHKeyStore: """MariaDB-backed key library with owner-scoped SQL queries.""" def __init__(self, store: DatabaseStore) -> None: self._store = store def _connect(self): return self._store._connect() def list_for_user(self, user_id: int) -> list[dict[str, Any]]: _user_id(user_id) connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "SELECT id, name, public_key, fingerprint, created_at " "FROM user_ssh_keys WHERE user_id=%s ORDER BY created_at DESC, id DESC", (user_id,), ) return [_row(row) for row in cursor.fetchall()] except pymysql.MySQLError as exc: raise DatabaseError("无法读取 SSH 公钥") from exc finally: connection.close() def create_for_user(self, user_id: int, name: str, public_key: str, *, now: int | None = None) -> dict[str, Any]: _user_id(user_id) name = _name(name) public_key, fingerprint = _public_key(public_key) timestamp = int(time.time()) if now is None else now if isinstance(timestamp, bool) or not isinstance(timestamp, int) or timestamp < 0: raise ValueError("Invalid SSH key creation time") connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "INSERT INTO user_ssh_keys " "(user_id, name, public_key, fingerprint, created_at) " "VALUES (%s, %s, %s, %s, %s)", (user_id, name, public_key, fingerprint, timestamp), ) key_id = cursor.lastrowid connection.commit() return { "id": key_id, "name": name, "public_key": public_key, "fingerprint": fingerprint, "created_at": timestamp, } except pymysql.err.IntegrityError as exc: connection.rollback() if exc.args and exc.args[0] == 1062: raise SSHKeyError("此 SSH 公钥已添加到当前账户", 409) from exc raise DatabaseError("无法保存 SSH 公钥") from exc except pymysql.MySQLError as exc: connection.rollback() raise DatabaseError("无法保存 SSH 公钥") from exc finally: connection.close() def get_for_user(self, user_id: int, key_id: int) -> dict[str, Any] | None: _user_id(user_id) _key_id(key_id) connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "SELECT id, name, public_key, fingerprint, created_at " "FROM user_ssh_keys WHERE user_id=%s AND id=%s", (user_id, key_id), ) return _row(cursor.fetchone()) except pymysql.MySQLError as exc: raise DatabaseError("无法读取 SSH 公钥") from exc finally: connection.close() def delete_for_user(self, user_id: int, key_id: int) -> bool: _user_id(user_id) _key_id(key_id) connection = self._connect() try: with connection.cursor() as cursor: cursor.execute( "DELETE FROM user_ssh_keys WHERE user_id=%s AND id=%s", (user_id, key_id), ) deleted = cursor.rowcount > 0 connection.commit() return deleted except pymysql.MySQLError as exc: connection.rollback() raise DatabaseError("无法删除 SSH 公钥") from exc finally: connection.close()