Add per-user SSH public key library for cloud VMs
parent
4474610ea9
commit
62c7b51c3e
@ -0,0 +1,168 @@
|
||||
"""Owner-isolated MariaDB SSH public key records, using a SQL test adapter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import sqlite3
|
||||
import struct
|
||||
|
||||
import pytest
|
||||
|
||||
from virsh_panel.ssh_keys import DatabaseSSHKeyStore, SSHKeyError
|
||||
|
||||
|
||||
def _valid_key(seed: bytes = b"a", comment: str = "operator@example") -> str:
|
||||
blob = struct.pack("!I", 11) + b"ssh-ed25519" + struct.pack("!I", 32) + seed * 32
|
||||
return "ssh-ed25519 " + base64.b64encode(blob).decode("ascii") + " " + comment
|
||||
|
||||
|
||||
class _Cursor:
|
||||
def __init__(self, connection: sqlite3.Connection) -> None:
|
||||
self._cursor = connection.cursor()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *_exc):
|
||||
self._cursor.close()
|
||||
|
||||
def execute(self, statement, parameters=()):
|
||||
try:
|
||||
self._cursor.execute(statement.replace("%s", "?"), parameters)
|
||||
except sqlite3.IntegrityError as exc:
|
||||
import pymysql
|
||||
|
||||
raise pymysql.err.IntegrityError(1062, str(exc)) from exc
|
||||
return self
|
||||
|
||||
def fetchone(self):
|
||||
row = self._cursor.fetchone()
|
||||
return None if row is None else dict(row)
|
||||
|
||||
def fetchall(self):
|
||||
return [dict(row) for row in self._cursor.fetchall()]
|
||||
|
||||
@property
|
||||
def lastrowid(self):
|
||||
return self._cursor.lastrowid
|
||||
|
||||
@property
|
||||
def rowcount(self):
|
||||
return self._cursor.rowcount
|
||||
|
||||
|
||||
class _Connection:
|
||||
def __init__(self) -> None:
|
||||
self.raw = sqlite3.connect(":memory:")
|
||||
self.raw.row_factory = sqlite3.Row
|
||||
self.raw.execute("PRAGMA foreign_keys=ON")
|
||||
self.raw.executescript("""
|
||||
CREATE TABLE users (id INTEGER PRIMARY KEY);
|
||||
INSERT INTO users (id) VALUES (1), (2);
|
||||
CREATE TABLE user_ssh_keys (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
public_key TEXT NOT NULL,
|
||||
fingerprint TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
UNIQUE (user_id, fingerprint)
|
||||
);
|
||||
""")
|
||||
|
||||
def cursor(self):
|
||||
return _Cursor(self.raw)
|
||||
|
||||
def commit(self):
|
||||
self.raw.commit()
|
||||
|
||||
def rollback(self):
|
||||
self.raw.rollback()
|
||||
|
||||
def close(self):
|
||||
# A single in-memory database must outlive individual store calls.
|
||||
pass
|
||||
|
||||
|
||||
class _Store:
|
||||
def __init__(self) -> None:
|
||||
self.connection = _Connection()
|
||||
|
||||
def _connect(self):
|
||||
return self.connection
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def key_store():
|
||||
store = _Store()
|
||||
yield DatabaseSSHKeyStore(store), store.connection.raw
|
||||
store.connection.raw.close()
|
||||
|
||||
|
||||
def test_keys_are_strictly_isolated_by_user_on_all_operations(key_store):
|
||||
repository, database = key_store
|
||||
first = repository.create_for_user(1, "生产环境", _valid_key(), now=100)
|
||||
second = repository.create_for_user(2, "另一用户", _valid_key(), now=101)
|
||||
assert first["id"] != second["id"]
|
||||
assert first["fingerprint"] == second["fingerprint"]
|
||||
assert first["public_key"] == _valid_key().rsplit(" ", 1)[0]
|
||||
blob = base64.b64decode(first["public_key"].split()[1])
|
||||
assert first["fingerprint"] == (
|
||||
"SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=")
|
||||
)
|
||||
assert repository.list_for_user(1) == [first]
|
||||
assert repository.list_for_user(2) == [second]
|
||||
assert repository.get_for_user(1, second["id"]) is None
|
||||
assert repository.get_for_user(2, first["id"]) is None
|
||||
assert repository.delete_for_user(2, first["id"]) is False
|
||||
assert repository.get_for_user(1, first["id"]) == first
|
||||
assert repository.delete_for_user(1, first["id"]) is True
|
||||
assert repository.delete_for_user(1, first["id"]) is False
|
||||
assert repository.list_for_user(1) == []
|
||||
assert repository.list_for_user(2) == [second]
|
||||
database.execute("DELETE FROM users WHERE id=2")
|
||||
database.commit()
|
||||
assert database.execute("SELECT COUNT(*) FROM user_ssh_keys").fetchone()[0] == 0
|
||||
|
||||
|
||||
def test_same_wire_key_cannot_be_saved_twice_per_user_even_with_new_comment(key_store):
|
||||
repository, _database = key_store
|
||||
repository.create_for_user(1, "第一把", _valid_key(comment="first"))
|
||||
with pytest.raises(SSHKeyError) as duplicate:
|
||||
repository.create_for_user(1, "第二把", _valid_key(comment="second"))
|
||||
assert duplicate.value.status == 409
|
||||
assert len(repository.list_for_user(1)) == 1
|
||||
# Unique constraint is owner-scoped, not a global ban on shared keys.
|
||||
assert repository.create_for_user(2, "允许跨用户重复", _valid_key(comment="second"))["id"] > 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid_key", [
|
||||
"-----BEGIN OPENSSH PRIVATE KEY-----\nAAAA\n-----END OPENSSH PRIVATE KEY-----",
|
||||
"ssh-ed25519 not-base64",
|
||||
"ssh-rsa " + _valid_key().split()[1],
|
||||
_valid_key() + "\nssh-ed25519 another-key",
|
||||
"",
|
||||
])
|
||||
def test_private_or_invalid_public_keys_are_rejected_without_writes(key_store, invalid_key):
|
||||
repository, _database = key_store
|
||||
with pytest.raises(SSHKeyError) as invalid:
|
||||
repository.create_for_user(1, "键", invalid_key)
|
||||
assert invalid.value.status == 400
|
||||
assert repository.list_for_user(1) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid_name", ["", " ", " leading", "trailing ", "bad\nname", "x" * 81])
|
||||
def test_key_name_must_be_safe_and_bounded(key_store, invalid_name):
|
||||
repository, _database = key_store
|
||||
with pytest.raises(SSHKeyError):
|
||||
repository.create_for_user(1, invalid_name, _valid_key())
|
||||
assert repository.list_for_user(1) == []
|
||||
|
||||
|
||||
def test_list_is_newest_first_and_exposes_no_owner_id(key_store):
|
||||
repository, _database = key_store
|
||||
first = repository.create_for_user(1, "first", _valid_key(b"a"), now=100)
|
||||
second = repository.create_for_user(1, "second", _valid_key(b"b"), now=200)
|
||||
assert repository.list_for_user(1) == [second, first]
|
||||
assert "user_id" not in second
|
||||
@ -0,0 +1,165 @@
|
||||
"""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()
|
||||
Loading…
Reference in New Issue