"""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