Add verified user registration, SMTP, approval and VM ownership
parent
17f0226581
commit
92241d1cee
@ -0,0 +1,79 @@
|
||||
"""Database sessions bind to immutable user IDs, not reusable usernames."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from virsh_panel.auth import DatabaseSessionStore, SessionStore
|
||||
|
||||
|
||||
class _Records:
|
||||
def __init__(self):
|
||||
self.values = {}
|
||||
|
||||
def get(self, record_type, record_key):
|
||||
return self.values.get((record_type, record_key))
|
||||
|
||||
def set(self, record_type, record_key, value):
|
||||
self.values[(record_type, record_key)] = value
|
||||
|
||||
def delete(self, record_type, record_key):
|
||||
self.values.pop((record_type, record_key), None)
|
||||
|
||||
|
||||
def test_database_session_round_trips_immutable_user_id():
|
||||
records = _Records()
|
||||
sessions = DatabaseSessionStore(records)
|
||||
created = sessions.issue("operator", user_id=47)
|
||||
assert created.user_id == 47
|
||||
key = sessions._key(created.token)
|
||||
payload = json.loads(records.get("session", key))
|
||||
assert payload["user_id"] == 47
|
||||
assert created.token not in records.get("session", key)
|
||||
restored = DatabaseSessionStore(records).get(created.token)
|
||||
assert restored == created
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid_id", [None, 0, -1, True, "47", 47.0])
|
||||
def test_database_session_issue_refuses_missing_or_invalid_user_id(invalid_id):
|
||||
sessions = DatabaseSessionStore(_Records())
|
||||
with pytest.raises(ValueError, match="positive user ID"):
|
||||
sessions.issue("operator", user_id=invalid_id)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid_id", [None, 0, -1, True, "47", 47.0])
|
||||
def test_database_session_get_rejects_legacy_or_invalid_id(invalid_id):
|
||||
records = _Records()
|
||||
sessions = DatabaseSessionStore(records)
|
||||
token = "legacy-token"
|
||||
payload = {
|
||||
"username": "operator", "csrf_token": "csrf-token",
|
||||
"expires_at": time.time() + 100,
|
||||
}
|
||||
if invalid_id is not None:
|
||||
payload["user_id"] = invalid_id
|
||||
records.set("session", sessions._key(token), json.dumps(payload))
|
||||
assert sessions.get(token) is None
|
||||
|
||||
|
||||
def test_database_session_expired_token_is_removed():
|
||||
records = _Records()
|
||||
sessions = DatabaseSessionStore(records)
|
||||
token = "expired-token"
|
||||
key = sessions._key(token)
|
||||
records.set("session", key, json.dumps({
|
||||
"username": "operator", "user_id": 47,
|
||||
"csrf_token": "csrf-token", "expires_at": time.time() - 1,
|
||||
}))
|
||||
assert sessions.get(token) is None
|
||||
assert records.get("session", key) is None
|
||||
|
||||
|
||||
def test_injected_memory_sessions_keep_username_only_compatibility():
|
||||
sessions = SessionStore()
|
||||
created = sessions.issue("test-admin")
|
||||
assert created.user_id is None
|
||||
assert sessions.get(created.token) == created
|
||||
@ -0,0 +1,305 @@
|
||||
"""Production database-mode registration and authorization HTTP boundary."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
|
||||
try:
|
||||
import libvirt # noqa: F401
|
||||
except ModuleNotFoundError:
|
||||
stub = types.ModuleType("libvirt")
|
||||
stub.libvirtError = type("libvirtError", (Exception,), {})
|
||||
sys.modules["libvirt"] = stub
|
||||
|
||||
from tests.test_database_http import MemoryStore # noqa: E402
|
||||
from virsh_panel import app as app_module # noqa: E402
|
||||
from virsh_panel.config import Settings # noqa: E402
|
||||
from virsh_panel.database import DatabasePanelState, DatabaseTemplateStore # noqa: E402
|
||||
from virsh_panel.libvirt_service import VMError # noqa: E402
|
||||
from virsh_panel.metrics import host_scope # noqa: E402
|
||||
|
||||
|
||||
ORIGIN = "https://panel.example.test"
|
||||
PASSWORD = "correct-horse-battery-staple"
|
||||
CREATE_VM = {
|
||||
"name": "tenant-vm", "vcpu": 2, "memory_mib": 2048,
|
||||
"disk_gib": 20, "network": "bridge:br0", "iso": "AlmaLinux-10.iso",
|
||||
}
|
||||
|
||||
|
||||
class _Manager:
|
||||
profile = {
|
||||
"host": "vmhost.example.test", "port": 22,
|
||||
"fingerprint": "SHA256:configured-host", "key_locked": False,
|
||||
"region": "东京", "storage_pool": "/home/kvm", "iso_pool": "/home/iso",
|
||||
"default_network": "bridge:br0", "ssh_target": "vp-managed",
|
||||
"ssh_config_file": "/fake/config", "ssh_known_hosts_file": "/fake/known_hosts",
|
||||
}
|
||||
|
||||
def current(self):
|
||||
return self.profile
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
class _Service:
|
||||
def __init__(self):
|
||||
self.vms = {}
|
||||
self.console_calls = []
|
||||
|
||||
def create_vm(self, spec):
|
||||
vm = {
|
||||
"uuid": spec["vm_uuid"], "name": spec["name"], "state": "running",
|
||||
"vcpu": spec["vcpu"], "memory_mib": spec["memory_mib"],
|
||||
"disks": [], "autostart": True,
|
||||
}
|
||||
self.vms[vm["uuid"]] = vm
|
||||
return vm
|
||||
|
||||
def list_vms(self):
|
||||
return list(self.vms.values())
|
||||
|
||||
def get_vm(self, vm_id):
|
||||
if vm_id not in self.vms:
|
||||
raise VMError("虚拟机不存在", 404)
|
||||
return self.vms[vm_id]
|
||||
|
||||
def action(self, vm_id, _action):
|
||||
return self.get_vm(vm_id)
|
||||
|
||||
def delete_vm(self, vm_id, _delete_disks):
|
||||
self.get_vm(vm_id)
|
||||
del self.vms[vm_id]
|
||||
return {"uuid": vm_id, "deleted": True, "deleted_disks": []}
|
||||
|
||||
def console_port(self, vm_id):
|
||||
self.console_calls.append(vm_id)
|
||||
self.get_vm(vm_id)
|
||||
return 5907
|
||||
|
||||
|
||||
class _NoMetrics:
|
||||
def __init__(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
def start(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
def _login(client: TestClient, username: str):
|
||||
response = client.post("/api/v1/login", json={
|
||||
"username": username, "password": PASSWORD,
|
||||
})
|
||||
assert response.status_code == 200
|
||||
return {"X-CSRF-Token": response.json()["csrf_token"]}
|
||||
|
||||
|
||||
def _register(client: TestClient, address: str, username: str):
|
||||
code = client.post("/api/v1/register/code", json={"email": address})
|
||||
assert code.status_code == 200 and code.json() == {"sent": True}
|
||||
response = client.post("/api/v1/register", json={
|
||||
"username": username, "email": address,
|
||||
"password": PASSWORD, "code": "123456",
|
||||
})
|
||||
assert response.status_code == 201
|
||||
assert response.json() == {"registered": True, "approved": False}
|
||||
|
||||
|
||||
def test_registration_smtp_approval_and_per_user_vm_isolation(monkeypatch, tmp_path):
|
||||
store = MemoryStore()
|
||||
service = _Service()
|
||||
sent = []
|
||||
monkeypatch.setattr(app_module, "make_components", lambda directory, *_: (
|
||||
DatabasePanelState(directory, store, store.users), _Manager(),
|
||||
DatabaseTemplateStore(store), store,
|
||||
))
|
||||
monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics)
|
||||
monkeypatch.setattr(
|
||||
app_module, "send_verification_code",
|
||||
lambda config, email, code: sent.append((config.host, email, code)),
|
||||
)
|
||||
settings = Settings(
|
||||
data_dir=tmp_path / "data",
|
||||
static_dir=Path(__file__).resolve().parents[1] / "static",
|
||||
)
|
||||
app = app_module.create_app(settings, service_factory=lambda _profile: service)
|
||||
token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip()
|
||||
|
||||
with TestClient(app, base_url=ORIGIN) as admin:
|
||||
configured = admin.post("/api/v1/database/setup", json={
|
||||
"host": "127.0.0.1", "port": 3306, "database": "virsh_panel",
|
||||
"username": "panel", "password": "database-password", "setup_token": token,
|
||||
})
|
||||
assert configured.status_code == 200
|
||||
initial = admin.post("/api/v1/setup/admin", json={
|
||||
"token": token, "username": "firstuser", "password": PASSWORD,
|
||||
})
|
||||
assert initial.status_code == 200
|
||||
admin_headers = {"X-CSRF-Token": initial.json()["csrf_token"]}
|
||||
assert admin.get("/api/v1/session").json()["admin"] is False
|
||||
assert admin.get("/api/v1/smtp/settings").status_code == 403
|
||||
# The operator promotes the initial account manually in MariaDB.
|
||||
store.users.promote("firstuser")
|
||||
assert admin.get("/api/v1/session").json()["admin"] is True
|
||||
smtp = admin.put("/api/v1/smtp/settings", json={
|
||||
"host": "smtp.example.test", "port": 587, "tls_mode": "starttls",
|
||||
"from_address": "panel@example.test", "username": "mailer",
|
||||
"password": "smtp-secret-password",
|
||||
}, headers=admin_headers)
|
||||
assert smtp.status_code == 200
|
||||
assert "smtp-secret-password" not in smtp.text
|
||||
|
||||
original_sender = app_module.send_verification_code
|
||||
|
||||
def fail_delivery(_config, _email, _code):
|
||||
raise app_module.SMTPError("模拟 SMTP 发送失败", 502)
|
||||
|
||||
monkeypatch.setattr(app_module, "send_verification_code", fail_delivery)
|
||||
with TestClient(app, base_url=ORIGIN) as visitor:
|
||||
failed_send = visitor.post("/api/v1/register/code", json={
|
||||
"email": "delivery-fail@example.test",
|
||||
})
|
||||
assert failed_send.status_code == 200
|
||||
assert failed_send.json() == {"sent": True}
|
||||
# A failed background delivery must remove the challenge so the
|
||||
# user is not trapped behind the resend cooldown.
|
||||
assert store.get("test_code", "delivery-fail@example.test") is None
|
||||
monkeypatch.setattr(app_module, "send_verification_code", original_sender)
|
||||
with TestClient(app, base_url=ORIGIN) as visitor:
|
||||
retried = visitor.post("/api/v1/register/code", json={
|
||||
"email": "delivery-fail@example.test",
|
||||
})
|
||||
assert retried.status_code == failed_send.status_code
|
||||
assert retried.json() == failed_send.json()
|
||||
assert store.get("test_code", "delivery-fail@example.test") == "123456"
|
||||
sent.clear()
|
||||
|
||||
with TestClient(app, base_url=ORIGIN) as first:
|
||||
_register(first, "one@example.test", "tenantone")
|
||||
assert sent == [("smtp.example.test", "one@example.test", "123456")]
|
||||
first_headers = _login(first, "tenantone")
|
||||
assert first.get("/api/v1/session").json()["approved"] is False
|
||||
assert first.post("/api/v1/vms", json=CREATE_VM,
|
||||
headers=first_headers).status_code == 403
|
||||
for protected in (
|
||||
"/api/v1/host", "/api/v1/update/settings",
|
||||
"/api/v1/smtp/settings", "/api/v1/users/pending",
|
||||
):
|
||||
assert first.get(protected).status_code == 403
|
||||
pending = admin.get("/api/v1/users/pending")
|
||||
assert pending.status_code == 200
|
||||
items = pending.json()["items"]
|
||||
assert len(items) == 1 and items[0]["username"] == "tenantone"
|
||||
assert "password_hash" not in items[0]
|
||||
approve = admin.post(f"/api/v1/users/{items[0]['id']}/approve",
|
||||
headers=admin_headers)
|
||||
assert approve.status_code == 200
|
||||
assert first.get("/api/v1/session").json()["approved"] is True
|
||||
own = first.post("/api/v1/vms", json=CREATE_VM, headers=first_headers)
|
||||
assert own.status_code == 201
|
||||
own_id = own.json()["uuid"]
|
||||
|
||||
with TestClient(app, base_url=ORIGIN) as second:
|
||||
_register(second, "two@example.test", "tenanttwo")
|
||||
second_headers = _login(second, "tenanttwo")
|
||||
second_id = store.users.get_by_username("tenanttwo")["id"]
|
||||
assert admin.post(f"/api/v1/users/{second_id}/approve",
|
||||
headers=admin_headers).status_code == 200
|
||||
other = second.post("/api/v1/vms", json={**CREATE_VM, "name": "other-vm"},
|
||||
headers=second_headers)
|
||||
assert other.status_code == 201
|
||||
other_id = other.json()["uuid"]
|
||||
|
||||
assert [vm["uuid"] for vm in first.get("/api/v1/vms").json()["items"]] == [own_id]
|
||||
assert [vm["uuid"] for vm in second.get("/api/v1/vms").json()["items"]] == [other_id]
|
||||
assert len(admin.get("/api/v1/vms").json()["items"]) == 2
|
||||
assert first.get(f"/api/v1/vms/{other_id}").status_code == 404
|
||||
assert first.post(f"/api/v1/vms/{other_id}/credential",
|
||||
headers=first_headers).status_code == 404
|
||||
assert first.get(f"/api/v1/vms/{other_id}/metrics").status_code == 404
|
||||
assert first.post(f"/api/v1/vms/{other_id}/actions", json={
|
||||
"action": "reboot",
|
||||
}, headers=first_headers).status_code == 404
|
||||
assert first.delete(f"/api/v1/vms/{other_id}",
|
||||
headers=first_headers).status_code == 404
|
||||
assert first.get(f"/api/v1/vms/{own_id}").status_code == 200
|
||||
assert first.get("/api/v1/host").status_code == 403
|
||||
assert first.put("/api/v1/update/settings", json={
|
||||
"repository_url": "https://g.luoli.live/root/virt.git", "branch": "main",
|
||||
"access_token": "forbidden",
|
||||
}, headers=first_headers).status_code == 403
|
||||
assert first.put("/api/v1/smtp/settings", json={
|
||||
"host": "evil.example.test", "port": 587, "tls_mode": "starttls",
|
||||
"from_address": "evil@example.test",
|
||||
}, headers=first_headers).status_code == 403
|
||||
assert first.post(f"/api/v1/users/{second_id}/approve",
|
||||
headers=first_headers).status_code == 403
|
||||
|
||||
cookie = first.cookies.get("virsh_panel_session")
|
||||
with pytest.raises(WebSocketDisconnect) as denied:
|
||||
with first.websocket_connect(
|
||||
f"wss://panel.example.test/api/v1/vms/{other_id}/console",
|
||||
headers={
|
||||
"host": "panel.example.test", "origin": ORIGIN,
|
||||
"cookie": f"virsh_panel_session={cookie}",
|
||||
},
|
||||
):
|
||||
pass
|
||||
assert denied.value.code == 4404
|
||||
assert service.console_calls == []
|
||||
|
||||
monkeypatch.setattr(app_module, "CONSOLE_ACCESS_CHECK_SECONDS", 0.05)
|
||||
|
||||
async def held_console(_websocket, **_kwargs):
|
||||
# If the watchdog fails to close promptly, the relay
|
||||
# closes with 1011 after a bounded fallback delay.
|
||||
await asyncio.sleep(1)
|
||||
raise app_module.ConsoleRelayError("test relay timeout")
|
||||
|
||||
monkeypatch.setattr(app_module, "relay_console", held_console)
|
||||
own_console = f"wss://panel.example.test/api/v1/vms/{own_id}/console"
|
||||
own_cookie = first.cookies.get("virsh_panel_session")
|
||||
with first.websocket_connect(own_console, headers={
|
||||
"host": "panel.example.test", "origin": ORIGIN,
|
||||
"cookie": f"virsh_panel_session={own_cookie}",
|
||||
}) as console:
|
||||
assert first.post("/api/v1/logout", headers=first_headers).status_code == 200
|
||||
with pytest.raises(WebSocketDisconnect) as revoked:
|
||||
console.receive_text()
|
||||
assert revoked.value.code == 4403
|
||||
|
||||
first_headers = _login(first, "tenantone")
|
||||
own_cookie = first.cookies.get("virsh_panel_session")
|
||||
with first.websocket_connect(own_console, headers={
|
||||
"host": "panel.example.test", "origin": ORIGIN,
|
||||
"cookie": f"virsh_panel_session={own_cookie}",
|
||||
}) as console:
|
||||
store.users.delete_vm_owner(host_scope(_Manager.profile), own_id)
|
||||
with pytest.raises(WebSocketDisconnect) as ownership_revoked:
|
||||
console.receive_text()
|
||||
assert ownership_revoked.value.code == 4403
|
||||
|
||||
# A deleted username may later be reused. Its old bearer
|
||||
# cookie must not acquire the replacement account's role.
|
||||
old_account = store.users.get_by_username("tenantone")
|
||||
store.delete("test_user", "tenantone")
|
||||
replacement = {**old_account, "id": old_account["id"] + 1000,
|
||||
"admin": True}
|
||||
store.set("test_user", "tenantone", json.dumps(replacement))
|
||||
assert first.get("/api/v1/session").json()["authenticated"] is False
|
||||
assert first.get("/api/v1/smtp/settings").status_code == 401
|
||||
assert first.post("/api/v1/vms", json=CREATE_VM,
|
||||
headers=first_headers).status_code == 401
|
||||
@ -0,0 +1,201 @@
|
||||
"""SMTP settings safety and registration mail transport tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import smtplib
|
||||
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
|
||||
from virsh_panel.database import DatabaseStore
|
||||
from virsh_panel.smtp_service import (
|
||||
SMTPConfig, SMTPError, SMTPSettingsStore, send_verification_code, validate_email,
|
||||
)
|
||||
|
||||
|
||||
def _settings(**overrides):
|
||||
values = {
|
||||
"host": "smtp.example.com", "port": 587, "tls_mode": "starttls",
|
||||
"from_address": "no-reply@example.com", "username": "account@example.com",
|
||||
"password": "app-password-secret",
|
||||
}
|
||||
values.update(overrides)
|
||||
return values
|
||||
|
||||
|
||||
class EncryptedRecords:
|
||||
def __init__(self):
|
||||
self.cipher = DatabaseStore.__new__(DatabaseStore)
|
||||
self.cipher._cipher = AESGCM(b"s" * 32)
|
||||
self.data = {}
|
||||
|
||||
def get(self, kind, key):
|
||||
encrypted = self.data.get((kind, key))
|
||||
return None if encrypted is None else self.cipher._decrypt(kind, key, encrypted)
|
||||
|
||||
def set(self, kind, key, value):
|
||||
self.data[(kind, key)] = self.cipher._encrypt(kind, key, value)
|
||||
|
||||
|
||||
def test_smtp_settings_are_encrypted_and_password_never_returns_in_status():
|
||||
records = EncryptedRecords()
|
||||
settings = SMTPSettingsStore(records)
|
||||
assert settings.public_status() == {"configured": False}
|
||||
|
||||
config = settings.save(_settings())
|
||||
assert config.password == "app-password-secret"
|
||||
ciphertext = records.data[("smtp", "current")]
|
||||
assert b"app-password-secret" not in ciphertext
|
||||
assert b"smtp.example.com" not in ciphertext
|
||||
|
||||
status = settings.public_status()
|
||||
assert status == {
|
||||
"configured": True, "host": "smtp.example.com", "port": 587,
|
||||
"tls_mode": "starttls", "from_address": "no-reply@example.com",
|
||||
"username": "account@example.com", "password_configured": True,
|
||||
}
|
||||
assert "app-password-secret" not in repr(config)
|
||||
assert "password" not in status
|
||||
|
||||
|
||||
def test_smtp_update_keeps_existing_password_only_for_same_account():
|
||||
settings = SMTPSettingsStore(EncryptedRecords())
|
||||
settings.save(_settings())
|
||||
assert settings.save(_settings(host="new.example.com", password="")).password == "app-password-secret"
|
||||
with pytest.raises(SMTPError, match="必须同时填写"):
|
||||
settings.save(_settings(username="other@example.com", password=""))
|
||||
assert settings.get().host == "new.example.com"
|
||||
assert settings.get().username == "account@example.com"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [
|
||||
_settings(host="smtp.example.com\r\nX-Injected: yes"),
|
||||
_settings(port=True),
|
||||
_settings(port=0),
|
||||
_settings(tls_mode="invalid"),
|
||||
_settings(tls_mode=[]),
|
||||
_settings(from_address="Sender <sender@example.com>"),
|
||||
_settings(username="x", password="", tls_mode="starttls"),
|
||||
_settings(tls_mode="none"),
|
||||
])
|
||||
def test_invalid_smtp_settings_are_rejected(value):
|
||||
with pytest.raises(SMTPError):
|
||||
SMTPConfig.from_mapping(value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("address", [
|
||||
"user@example.com\r\nBcc: victim@example.com", "Name <user@example.com>",
|
||||
"user..name@example.com", "user@", "@example.com", " user@example.com",
|
||||
])
|
||||
def test_invalid_mailbox_is_rejected(address):
|
||||
with pytest.raises(SMTPError, match="邮箱地址格式无效"):
|
||||
validate_email(address)
|
||||
|
||||
|
||||
def test_address_keeps_local_part_and_canonicalizes_domain():
|
||||
assert validate_email("User+tag@EXAMPLE.COM") == "User+tag@example.com"
|
||||
|
||||
|
||||
class FakeSMTP:
|
||||
events = []
|
||||
sent = None
|
||||
refused = {}
|
||||
|
||||
def __init__(self, host, port, **kwargs):
|
||||
self.events.append(("connect", host, port, kwargs))
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *_args):
|
||||
self.events.append("quit")
|
||||
|
||||
def ehlo(self):
|
||||
self.events.append("ehlo")
|
||||
|
||||
def starttls(self, **kwargs):
|
||||
assert "context" in kwargs
|
||||
self.events.append("starttls")
|
||||
|
||||
def login(self, username, password):
|
||||
self.events.append(("login", username, password))
|
||||
|
||||
def send_message(self, message):
|
||||
self.events.append("send")
|
||||
self.sent = message
|
||||
return self.refused
|
||||
|
||||
|
||||
def test_starttls_happens_before_login_and_sends_six_digit_code(monkeypatch):
|
||||
FakeSMTP.events = []
|
||||
FakeSMTP.refused = {}
|
||||
instances = []
|
||||
|
||||
def make_client(*args, **kwargs):
|
||||
client = FakeSMTP(*args, **kwargs)
|
||||
instances.append(client)
|
||||
return client
|
||||
|
||||
monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", make_client)
|
||||
send_verification_code(SMTPConfig.from_mapping(_settings()), "user@example.com", "012345")
|
||||
|
||||
assert FakeSMTP.events[0][0:3] == ("connect", "smtp.example.com", 587)
|
||||
assert FakeSMTP.events[0][3]["timeout"] == 10
|
||||
assert FakeSMTP.events[1:] == [
|
||||
"ehlo", "starttls", "ehlo",
|
||||
("login", "account@example.com", "app-password-secret"), "send", "quit",
|
||||
]
|
||||
message = instances[0].sent
|
||||
assert message["To"] == "user@example.com"
|
||||
assert message["From"] == "no-reply@example.com"
|
||||
assert "012345" in message.get_content()
|
||||
|
||||
|
||||
def test_ssl_and_unauthenticated_local_relay(monkeypatch):
|
||||
FakeSMTP.events = []
|
||||
FakeSMTP.refused = {}
|
||||
monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP_SSL", FakeSMTP)
|
||||
send_verification_code(
|
||||
SMTPConfig.from_mapping(_settings(port=465, tls_mode="ssl")),
|
||||
"user@example.com", "123456",
|
||||
)
|
||||
assert FakeSMTP.events[0][0:3] == ("connect", "smtp.example.com", 465)
|
||||
assert "context" in FakeSMTP.events[0][3]
|
||||
assert "starttls" not in FakeSMTP.events
|
||||
|
||||
FakeSMTP.events = []
|
||||
monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", FakeSMTP)
|
||||
send_verification_code(
|
||||
SMTPConfig.from_mapping(_settings(port=25, tls_mode="none", username="", password="")),
|
||||
"user@example.com", "123456",
|
||||
)
|
||||
assert not any(isinstance(event, tuple) and event[0] == "login"
|
||||
for event in FakeSMTP.events)
|
||||
|
||||
|
||||
def test_smtp_transport_failure_is_redacted(monkeypatch):
|
||||
class FailingSMTP(FakeSMTP):
|
||||
def login(self, *_args):
|
||||
raise smtplib.SMTPAuthenticationError(535, b"secret server reply")
|
||||
|
||||
monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", FailingSMTP)
|
||||
with pytest.raises(SMTPError) as failure:
|
||||
send_verification_code(
|
||||
SMTPConfig.from_mapping(_settings()), "user@example.com", "123456",
|
||||
)
|
||||
assert failure.value.status == 502
|
||||
assert "secret" not in str(failure.value)
|
||||
assert "app-password" not in str(failure.value)
|
||||
|
||||
|
||||
def test_refused_recipient_and_bad_code_do_not_leak_details(monkeypatch):
|
||||
FakeSMTP.events = []
|
||||
FakeSMTP.refused = {"user@example.com": (550, "mailbox secret")}
|
||||
monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", FakeSMTP)
|
||||
config = SMTPConfig.from_mapping(_settings())
|
||||
with pytest.raises(SMTPError) as failure:
|
||||
send_verification_code(config, "user@example.com", "123456")
|
||||
assert failure.value.status == 502
|
||||
assert "secret" not in str(failure.value)
|
||||
with pytest.raises(SMTPError, match="验证码格式无效"):
|
||||
send_verification_code(config, "user@example.com", "00000\n")
|
||||
@ -0,0 +1,240 @@
|
||||
"""Exercise SQL-backed registration and ownership without a MariaDB daemon."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from virsh_panel.auth import verify_password
|
||||
from virsh_panel.users import DatabaseUserStore, UserError, normalize_email
|
||||
|
||||
|
||||
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=()):
|
||||
sql = statement.replace("%s", "?").replace(" FOR UPDATE", "")
|
||||
try:
|
||||
self._cursor.execute(sql, 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):
|
||||
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 AUTOINCREMENT,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
email TEXT UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
admin INTEGER NOT NULL DEFAULT 0,
|
||||
approved INTEGER NOT NULL DEFAULT 0,
|
||||
email_verified INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE registration_codes (
|
||||
email TEXT PRIMARY KEY,
|
||||
code_hash TEXT NOT NULL,
|
||||
sent_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
failed_attempts INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE vm_ownership (
|
||||
host_scope TEXT NOT NULL,
|
||||
vm_uuid TEXT NOT NULL,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (host_scope, vm_uuid)
|
||||
);
|
||||
""")
|
||||
|
||||
def cursor(self):
|
||||
return _Cursor(self.raw)
|
||||
|
||||
def commit(self):
|
||||
self.raw.commit()
|
||||
|
||||
def rollback(self):
|
||||
self.raw.rollback()
|
||||
|
||||
def close(self):
|
||||
# DatabaseUserStore opens a new wrapper per method. This one fake
|
||||
# keeps a shared in-memory database alive across the test.
|
||||
pass
|
||||
|
||||
|
||||
class _Store:
|
||||
def __init__(self):
|
||||
self.connection = _Connection()
|
||||
|
||||
def _connect(self):
|
||||
return self.connection
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def users():
|
||||
store = _Store()
|
||||
yield DatabaseUserStore(store, b"x" * 32), store.connection.raw
|
||||
store.connection.raw.close()
|
||||
|
||||
|
||||
def test_initial_user_is_not_admin_but_is_approved(users):
|
||||
repository, _database = users
|
||||
assert repository.has_users() is False
|
||||
first = repository.create_initial_user("first", "initial-long-password", now=100)
|
||||
assert first["admin"] is False
|
||||
assert first["approved"] is True
|
||||
assert first["email_verified"] is True
|
||||
assert first["email"] is None
|
||||
assert verify_password("initial-long-password", first["password_hash"])
|
||||
assert repository.has_users() is True
|
||||
assert repository.get_by_username("first") == first
|
||||
assert repository.get_by_id(first["id"]) == first
|
||||
with pytest.raises(UserError) as repeated:
|
||||
repository.create_initial_user("second", "another-long-password", now=101)
|
||||
assert repeated.value.status == 409
|
||||
|
||||
|
||||
def test_registration_code_is_keyed_rate_limited_and_one_time(users):
|
||||
repository, database = users
|
||||
assert repository.issue_registration_code("User@Example.COM", "123456", now=100)
|
||||
code_hash = database.execute(
|
||||
"SELECT code_hash FROM registration_codes WHERE email=?", ("user@example.com",)
|
||||
).fetchone()[0]
|
||||
assert len(code_hash) == 64
|
||||
assert code_hash != "123456"
|
||||
with pytest.raises(UserError) as cooldown:
|
||||
repository.issue_registration_code("user@example.com", "654321", now=120)
|
||||
assert cooldown.value.status == 429
|
||||
with pytest.raises(UserError):
|
||||
repository.register_with_code("registered", "user@example.com", "long-user-password", "000000", now=130)
|
||||
assert database.execute(
|
||||
"SELECT failed_attempts FROM registration_codes WHERE email=?", ("user@example.com",)
|
||||
).fetchone()[0] == 1
|
||||
created = repository.register_with_code(
|
||||
"registered", "USER@EXAMPLE.COM", "long-user-password", "123456", now=140,
|
||||
)
|
||||
assert created["email"] == "user@example.com"
|
||||
assert created["email_verified"] is True
|
||||
assert created["admin"] is False
|
||||
assert created["approved"] is False
|
||||
assert verify_password("long-user-password", created["password_hash"])
|
||||
assert repository.issue_registration_code("user@example.com", "222222", now=300) is False
|
||||
with pytest.raises(UserError):
|
||||
repository.register_with_code(
|
||||
"duplicate", "user@example.com", "long-user-password", "123456", now=145,
|
||||
)
|
||||
|
||||
|
||||
def test_code_expires_and_five_failures_consume_challenge(users):
|
||||
repository, database = users
|
||||
repository.issue_registration_code("fail@example.com", "999999", now=100)
|
||||
for attempt in range(5):
|
||||
with pytest.raises(UserError):
|
||||
repository.register_with_code(
|
||||
"wrong", "fail@example.com", "long-user-password", "000000", now=110 + attempt,
|
||||
)
|
||||
assert database.execute("SELECT COUNT(*) FROM registration_codes").fetchone()[0] == 0
|
||||
with pytest.raises(UserError):
|
||||
repository.register_with_code(
|
||||
"wrong", "fail@example.com", "long-user-password", "999999", now=116,
|
||||
)
|
||||
repository.issue_registration_code("expired@example.com", "111111", now=200)
|
||||
with pytest.raises(UserError):
|
||||
repository.register_with_code(
|
||||
"expired", "expired@example.com", "long-user-password", "111111", now=800,
|
||||
)
|
||||
assert database.execute(
|
||||
"SELECT COUNT(*) FROM registration_codes WHERE email='expired@example.com'"
|
||||
).fetchone()[0] == 0
|
||||
|
||||
|
||||
def test_failed_smtp_delivery_can_revoke_only_matching_code(users):
|
||||
repository, database = users
|
||||
repository.issue_registration_code("retry@example.com", "111111", now=100)
|
||||
assert repository.revoke_registration_code("retry@example.com", "222222") is False
|
||||
assert repository.revoke_registration_code("retry@example.com", "111111") is True
|
||||
assert database.execute("SELECT COUNT(*) FROM registration_codes").fetchone()[0] == 0
|
||||
assert repository.issue_registration_code("retry@example.com", "333333", now=101)
|
||||
|
||||
|
||||
def test_approval_and_manual_admin_flag_are_distinct(users):
|
||||
repository, database = users
|
||||
repository.issue_registration_code("awaiting@example.com", "123456", now=100)
|
||||
account = repository.register_with_code(
|
||||
"awaiting", "awaiting@example.com", "long-user-password", "123456", now=120,
|
||||
)
|
||||
pending = repository.list_pending_users()
|
||||
assert len(pending) == 1 and pending[0]["username"] == "awaiting"
|
||||
assert "password_hash" not in pending[0]
|
||||
approved = repository.approve_user(account["id"])
|
||||
assert approved["approved"] is True and approved["admin"] is False
|
||||
assert repository.list_pending_users() == []
|
||||
database.execute("UPDATE users SET admin=1 WHERE id=?", (account["id"],))
|
||||
database.commit()
|
||||
assert repository.get_by_username("awaiting")["admin"] is True
|
||||
assert repository.approve_user(999999) is None
|
||||
|
||||
|
||||
def test_vm_ownership_is_scoped_to_host_and_user(users):
|
||||
repository, _database = users
|
||||
first = repository.create_initial_user("first", "initial-long-password", now=100)
|
||||
repository.issue_registration_code("other@example.com", "123456", now=101)
|
||||
other = repository.register_with_code(
|
||||
"other", "other@example.com", "long-user-password", "123456", now=102,
|
||||
)
|
||||
host = "a" * 64
|
||||
second_host = "b" * 64
|
||||
vm_id = str(uuid.uuid4())
|
||||
assert repository.owner_of_vm(host, vm_id) is None
|
||||
repository.assign_vm(host, vm_id, first["id"], now=103)
|
||||
repository.assign_vm(host, vm_id, first["id"], now=103)
|
||||
assert repository.owns_vm(host, vm_id, first["id"]) is True
|
||||
assert repository.owns_vm(host, vm_id, other["id"]) is False
|
||||
assert repository.list_owned_vm_ids(host, first["id"]) == {vm_id}
|
||||
assert repository.list_owned_vm_ids(second_host, first["id"]) == set()
|
||||
with pytest.raises(UserError) as conflict:
|
||||
repository.assign_vm(host, vm_id, other["id"], now=104)
|
||||
assert conflict.value.status == 409
|
||||
repository.delete_vm_owner(host, vm_id)
|
||||
assert repository.owner_of_vm(host, vm_id) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("address", [
|
||||
"evil@example.com\r\nBcc: victim@example.com", "not-an-email", "x@localhost",
|
||||
"a..b@example.com", "x@example..com", "ñ@example.com",
|
||||
])
|
||||
def test_email_validation_rejects_unsafe_addresses(address):
|
||||
with pytest.raises(UserError):
|
||||
normalize_email(address)
|
||||
@ -0,0 +1,215 @@
|
||||
"""Validated SMTP settings and registration verification mail delivery.
|
||||
|
||||
The settings store deliberately uses the panel's encrypted record store. The
|
||||
module never logs SMTP server responses because those can contain addresses or
|
||||
authentication details supplied by a remote server.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import smtplib
|
||||
import ssl
|
||||
from dataclasses import dataclass, field
|
||||
from email.message import EmailMessage
|
||||
from typing import Any, Mapping, Protocol
|
||||
|
||||
|
||||
_DNS_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\Z")
|
||||
_LOCAL_PART = re.compile(r"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*\Z")
|
||||
_SIX_DIGITS = re.compile(r"[0-9]{6}\Z")
|
||||
_SMTP_RECORD_TYPE = "smtp"
|
||||
_SMTP_RECORD_KEY = "current"
|
||||
|
||||
|
||||
class SMTPError(Exception):
|
||||
"""Safe user-facing SMTP configuration or delivery failure."""
|
||||
|
||||
def __init__(self, message: str, status: int = 422) -> None:
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
|
||||
|
||||
def _validate_host(host: str) -> str:
|
||||
if (not isinstance(host, str) or not host or len(host) > 253
|
||||
or host != host.strip()):
|
||||
raise SMTPError("SMTP 服务器地址格式无效")
|
||||
try:
|
||||
ipaddress.ip_address(host)
|
||||
return host
|
||||
except ValueError:
|
||||
pass
|
||||
if not all(_DNS_LABEL.fullmatch(label) for label in host.split(".")):
|
||||
raise SMTPError("SMTP 服务器地址必须是 IP 或 DNS 名称")
|
||||
return host.lower()
|
||||
|
||||
|
||||
def validate_email(address: str) -> str:
|
||||
"""Accept a bare ASCII mailbox address, never a display name or header."""
|
||||
|
||||
if (not isinstance(address, str) or len(address) > 254
|
||||
or address != address.strip() or address.count("@") != 1):
|
||||
raise SMTPError("邮箱地址格式无效")
|
||||
local, domain = address.rsplit("@", 1)
|
||||
if (not local or len(local) > 64 or not _LOCAL_PART.fullmatch(local)
|
||||
or not domain or len(domain) > 253
|
||||
or not all(_DNS_LABEL.fullmatch(label) for label in domain.split("."))):
|
||||
raise SMTPError("邮箱地址格式无效")
|
||||
return f"{local}@{domain.lower()}"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SMTPConfig:
|
||||
host: str
|
||||
port: int
|
||||
tls_mode: str
|
||||
from_address: str
|
||||
username: str = ""
|
||||
password: str = field(default="", repr=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "host", _validate_host(self.host))
|
||||
if (isinstance(self.port, bool) or not isinstance(self.port, int)
|
||||
or not 1 <= self.port <= 65535):
|
||||
raise SMTPError("SMTP 端口必须介于 1 到 65535")
|
||||
if (not isinstance(self.tls_mode, str)
|
||||
or self.tls_mode not in {"ssl", "starttls", "none"}):
|
||||
raise SMTPError("SMTP 加密方式无效")
|
||||
object.__setattr__(self, "from_address", validate_email(self.from_address))
|
||||
if (not isinstance(self.username, str) or len(self.username) > 256
|
||||
or self.username != self.username.strip()
|
||||
or any(ord(char) < 32 or ord(char) == 127 for char in self.username)):
|
||||
raise SMTPError("SMTP 用户名格式无效")
|
||||
if not isinstance(self.password, str) or len(self.password) > 2048:
|
||||
raise SMTPError("SMTP 密码格式无效")
|
||||
if bool(self.username) != bool(self.password):
|
||||
raise SMTPError("SMTP 用户名和密码必须同时填写")
|
||||
if self.username and self.tls_mode == "none":
|
||||
raise SMTPError("SMTP 账号认证必须启用 SSL 或 STARTTLS")
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, values: Mapping[str, Any]) -> SMTPConfig:
|
||||
if not isinstance(values, Mapping):
|
||||
raise SMTPError("SMTP 配置格式无效")
|
||||
return cls(
|
||||
host=values.get("host"),
|
||||
port=values.get("port"),
|
||||
tls_mode=values.get("tls_mode"),
|
||||
from_address=values.get("from_address"),
|
||||
username=values.get("username", ""),
|
||||
password=values.get("password", ""),
|
||||
)
|
||||
|
||||
def as_record(self) -> dict[str, str | int]:
|
||||
"""Full value for the *encrypted* database record only."""
|
||||
|
||||
return {
|
||||
"host": self.host,
|
||||
"port": self.port,
|
||||
"tls_mode": self.tls_mode,
|
||||
"from_address": self.from_address,
|
||||
"username": self.username,
|
||||
"password": self.password,
|
||||
}
|
||||
|
||||
def public_status(self) -> dict[str, str | int | bool]:
|
||||
"""Admin-only status; intentionally never includes the SMTP password."""
|
||||
|
||||
return {
|
||||
"configured": True,
|
||||
"host": self.host,
|
||||
"port": self.port,
|
||||
"tls_mode": self.tls_mode,
|
||||
"from_address": self.from_address,
|
||||
"username": self.username,
|
||||
"password_configured": bool(self.password),
|
||||
}
|
||||
|
||||
|
||||
class _RecordStore(Protocol):
|
||||
def get(self, record_type: str, record_key: str) -> str | None: ...
|
||||
def set(self, record_type: str, record_key: str, value: str) -> None: ...
|
||||
|
||||
|
||||
class SMTPSettingsStore:
|
||||
"""One SMTP configuration in the panel's AES-GCM-encrypted record table."""
|
||||
|
||||
def __init__(self, records: _RecordStore) -> None:
|
||||
self._records = records
|
||||
|
||||
def get(self) -> SMTPConfig | None:
|
||||
raw = self._records.get(_SMTP_RECORD_TYPE, _SMTP_RECORD_KEY)
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
return SMTPConfig.from_mapping(payload)
|
||||
except (ValueError, TypeError, SMTPError):
|
||||
raise SMTPError("已保存的 SMTP 配置无效,请重新保存", status=503) from None
|
||||
|
||||
def save(self, values: Mapping[str, Any]) -> SMTPConfig:
|
||||
if not isinstance(values, Mapping):
|
||||
raise SMTPError("SMTP 配置格式无效")
|
||||
candidate = dict(values)
|
||||
if candidate.get("password") in (None, ""):
|
||||
current = self.get()
|
||||
if current is not None and candidate.get("username", "") == current.username:
|
||||
candidate["password"] = current.password
|
||||
else:
|
||||
candidate["password"] = ""
|
||||
config = SMTPConfig.from_mapping(candidate)
|
||||
self._records.set(
|
||||
_SMTP_RECORD_TYPE, _SMTP_RECORD_KEY,
|
||||
json.dumps(config.as_record(), ensure_ascii=False, separators=(",", ":")),
|
||||
)
|
||||
return config
|
||||
|
||||
def public_status(self) -> dict[str, str | int | bool]:
|
||||
config = self.get()
|
||||
return {"configured": False} if config is None else config.public_status()
|
||||
|
||||
|
||||
def send_verification_code(config: SMTPConfig, recipient_email: str, code: str, *,
|
||||
timeout: int | float = 10) -> None:
|
||||
"""Send one six-digit registration code; all transport errors are redacted."""
|
||||
|
||||
recipient = validate_email(recipient_email)
|
||||
if not isinstance(code, str) or not _SIX_DIGITS.fullmatch(code):
|
||||
raise SMTPError("验证码格式无效")
|
||||
if (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
|
||||
or not 0 < timeout <= 30):
|
||||
raise SMTPError("SMTP 连接超时设置无效")
|
||||
|
||||
message = EmailMessage()
|
||||
message["From"] = config.from_address
|
||||
message["To"] = recipient
|
||||
message["Subject"] = "Virsh Panel 注册验证码"
|
||||
message["Auto-Submitted"] = "auto-generated"
|
||||
message.set_content(
|
||||
f"您的注册验证码是:{code}\n\n验证码在 10 分钟内有效,请勿转发给他人。\n"
|
||||
"如果不是您本人操作,请忽略这封邮件。\n",
|
||||
charset="utf-8",
|
||||
)
|
||||
|
||||
try:
|
||||
context = ssl.create_default_context()
|
||||
if config.tls_mode == "ssl":
|
||||
client = smtplib.SMTP_SSL(
|
||||
config.host, config.port, timeout=timeout, context=context,
|
||||
)
|
||||
else:
|
||||
client = smtplib.SMTP(config.host, config.port, timeout=timeout)
|
||||
with client:
|
||||
client.ehlo()
|
||||
if config.tls_mode == "starttls":
|
||||
client.starttls(context=context)
|
||||
client.ehlo()
|
||||
if config.username:
|
||||
client.login(config.username, config.password)
|
||||
refused = client.send_message(message)
|
||||
if refused:
|
||||
raise SMTPError("验证码发送失败,请检查 SMTP 配置后重试", status=502)
|
||||
except (smtplib.SMTPException, OSError):
|
||||
raise SMTPError("验证码发送失败,请检查 SMTP 配置后重试", status=502) from None
|
||||
@ -0,0 +1,478 @@
|
||||
"""MariaDB user accounts, registration codes, and VM ownership.
|
||||
|
||||
The panel's public registration code is only six digits, so its stored
|
||||
fingerprint is keyed with the database master key. A stolen database alone
|
||||
cannot check guesses offline. Every SQL value is passed as a parameter.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from .auth import hash_password
|
||||
from .database import DatabaseError, DatabaseStore, pymysql
|
||||
from .panel_state import _USERNAME
|
||||
|
||||
|
||||
_DOMAIN_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\Z")
|
||||
_LOCAL_PART = re.compile(r"[A-Za-z0-9_+%-](?:[A-Za-z0-9._+%-]{0,62}[A-Za-z0-9_+%-])?\Z")
|
||||
_CODE = re.compile(r"[0-9]{6}\Z")
|
||||
_HOST_SCOPE = re.compile(r"[0-9a-f]{64}\Z")
|
||||
_MAX_CODE_ATTEMPTS = 5
|
||||
|
||||
|
||||
class UserError(Exception):
|
||||
def __init__(self, message: str, status: int = 400) -> None:
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
|
||||
|
||||
def normalize_email(email: str) -> str:
|
||||
"""Reject addresses that cannot be safely used in SMTP headers."""
|
||||
if not isinstance(email, str) or not 3 <= len(email) <= 254 or email != email.strip():
|
||||
raise UserError("邮箱地址格式无效")
|
||||
try:
|
||||
email.encode("ascii")
|
||||
except UnicodeEncodeError as exc:
|
||||
raise UserError("邮箱地址格式无效") from exc
|
||||
if email.count("@") != 1:
|
||||
raise UserError("邮箱地址格式无效")
|
||||
local, domain = email.split("@")
|
||||
if (len(local) > 64 or len(domain) > 253 or ".." in email
|
||||
or not _LOCAL_PART.fullmatch(local)
|
||||
or not all(_DOMAIN_LABEL.fullmatch(label) for label in domain.split("."))
|
||||
or "." not in domain):
|
||||
raise UserError("邮箱地址格式无效")
|
||||
return email.lower()
|
||||
|
||||
|
||||
def _validate_username(username: str) -> str:
|
||||
if not isinstance(username, str) or not _USERNAME.fullmatch(username):
|
||||
raise UserError("用户名应为 3 至 32 位字母、数字、点、下划线或连字符")
|
||||
return username
|
||||
|
||||
|
||||
def _validate_password(password: str) -> str:
|
||||
if not isinstance(password, str) or not 12 <= len(password) <= 1024:
|
||||
raise UserError("密码长度须在 12 至 1024 位之间")
|
||||
return password
|
||||
|
||||
|
||||
def _validate_clock(now: int | None) -> int:
|
||||
value = int(time.time()) if now is None else now
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
||||
raise ValueError("Invalid registration time")
|
||||
return value
|
||||
|
||||
|
||||
def _vm_identity(host_scope: str, vm_uuid: str) -> tuple[str, str]:
|
||||
if not isinstance(host_scope, str) or not _HOST_SCOPE.fullmatch(host_scope):
|
||||
raise ValueError("Invalid host scope")
|
||||
try:
|
||||
canonical_uuid = str(uuid.UUID(vm_uuid))
|
||||
except (ValueError, TypeError, AttributeError) as exc:
|
||||
raise ValueError("Invalid VM UUID") from exc
|
||||
return host_scope, canonical_uuid
|
||||
|
||||
|
||||
def _user_row(row: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
if row is None:
|
||||
return None
|
||||
return {
|
||||
"id": int(row["id"]),
|
||||
"username": row["username"],
|
||||
"email": row["email"],
|
||||
"password_hash": row["password_hash"],
|
||||
"admin": bool(row["admin"]),
|
||||
"approved": bool(row["approved"]),
|
||||
"email_verified": bool(row["email_verified"]),
|
||||
"created_at": int(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
class DatabaseUserStore:
|
||||
"""Users are plain SQL rows; password hashes and code digests are one-way."""
|
||||
|
||||
def __init__(self, store: DatabaseStore, code_key: bytes) -> None:
|
||||
if not isinstance(code_key, bytes) or len(code_key) != 32:
|
||||
raise ValueError("Registration code key must be 32 bytes")
|
||||
self._store = store
|
||||
self._code_key = code_key
|
||||
|
||||
def _connect(self):
|
||||
return self._store._connect()
|
||||
|
||||
def _code_digest(self, email: str, code: str) -> str:
|
||||
message = b"virsh-panel-registration-v1\x00" + email.encode("ascii") + b"\x00" + code.encode("ascii")
|
||||
return hmac.new(self._code_key, message, hashlib.sha256).hexdigest()
|
||||
|
||||
@staticmethod
|
||||
def generate_code() -> str:
|
||||
return f"{secrets.randbelow(1_000_000):06d}"
|
||||
|
||||
def has_users(self) -> bool:
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("SELECT id FROM users LIMIT 1")
|
||||
return cursor.fetchone() is not None
|
||||
except pymysql.MySQLError as exc:
|
||||
raise DatabaseError("无法读取用户数据") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def get_by_username(self, username: str) -> dict[str, Any] | None:
|
||||
if not isinstance(username, str) or not _USERNAME.fullmatch(username):
|
||||
return None
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"SELECT id, username, email, password_hash, admin, approved, "
|
||||
"email_verified, created_at "
|
||||
"FROM users WHERE username=%s", (username,),
|
||||
)
|
||||
return _user_row(cursor.fetchone())
|
||||
except pymysql.MySQLError as exc:
|
||||
raise DatabaseError("无法读取用户数据") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def get_by_id(self, user_id: int) -> dict[str, Any] | None:
|
||||
if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1:
|
||||
return None
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"SELECT id, username, email, password_hash, admin, approved, "
|
||||
"email_verified, created_at "
|
||||
"FROM users WHERE id=%s", (user_id,),
|
||||
)
|
||||
return _user_row(cursor.fetchone())
|
||||
except pymysql.MySQLError as exc:
|
||||
raise DatabaseError("无法读取用户数据") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def create_initial_user(self, username: str, password: str,
|
||||
email: str | None = None, *, now: int | None = None) -> dict[str, Any]:
|
||||
"""Insert the first account as a regular user, never as admin.
|
||||
|
||||
The setup-token file lock held by DatabasePanelState serializes this
|
||||
check/insert across web workers on the same panel server.
|
||||
"""
|
||||
username = _validate_username(username)
|
||||
password_hash = hash_password(_validate_password(password))
|
||||
email = normalize_email(email) if email is not None else None
|
||||
timestamp = _validate_clock(now)
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("SELECT id FROM users LIMIT 1 FOR UPDATE")
|
||||
if cursor.fetchone() is not None:
|
||||
raise UserError("初始用户已创建", 409)
|
||||
cursor.execute(
|
||||
"INSERT INTO users (username, email, password_hash, admin, "
|
||||
"approved, email_verified, created_at) VALUES (%s, %s, %s, 0, 1, 1, %s)",
|
||||
(username, email, password_hash, timestamp),
|
||||
)
|
||||
user_id = cursor.lastrowid
|
||||
connection.commit()
|
||||
return {
|
||||
"id": user_id, "username": username, "email": email,
|
||||
"password_hash": password_hash, "admin": False, "approved": True,
|
||||
"email_verified": True, "created_at": timestamp,
|
||||
}
|
||||
except UserError:
|
||||
connection.rollback()
|
||||
raise
|
||||
except pymysql.err.IntegrityError as exc:
|
||||
connection.rollback()
|
||||
if exc.args and exc.args[0] == 1062:
|
||||
raise UserError("用户名或邮箱已存在", 409) from exc
|
||||
raise DatabaseError("无法创建初始用户") from exc
|
||||
except pymysql.MySQLError as exc:
|
||||
connection.rollback()
|
||||
raise DatabaseError("无法创建初始用户") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def issue_registration_code(self, email: str, code: str, *, now: int | None = None,
|
||||
ttl_seconds: int = 600,
|
||||
cooldown_seconds: int = 60) -> bool:
|
||||
"""Store a code and enforce resend cooldown; False means email already used.
|
||||
|
||||
The caller should return the same public response for existing and new
|
||||
email addresses, and send email only when this method returns True.
|
||||
"""
|
||||
email = normalize_email(email)
|
||||
if not isinstance(code, str) or not _CODE.fullmatch(code):
|
||||
raise ValueError("Invalid registration code")
|
||||
if (isinstance(ttl_seconds, bool) or not isinstance(ttl_seconds, int)
|
||||
or not 60 <= ttl_seconds <= 3600
|
||||
or isinstance(cooldown_seconds, bool) or not isinstance(cooldown_seconds, int)
|
||||
or not 1 <= cooldown_seconds <= ttl_seconds):
|
||||
raise ValueError("Invalid code lifetime or cooldown")
|
||||
timestamp = _validate_clock(now)
|
||||
digest = self._code_digest(email, code)
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("SELECT id FROM users WHERE email=%s", (email,))
|
||||
if cursor.fetchone() is not None:
|
||||
connection.rollback()
|
||||
return False
|
||||
cursor.execute(
|
||||
"SELECT sent_at FROM registration_codes WHERE email=%s FOR UPDATE",
|
||||
(email,),
|
||||
)
|
||||
existing = cursor.fetchone()
|
||||
if existing is not None and timestamp - int(existing["sent_at"]) < cooldown_seconds:
|
||||
raise UserError("验证码发送过于频繁,请稍后重试", 429)
|
||||
if existing is None:
|
||||
cursor.execute(
|
||||
"INSERT INTO registration_codes "
|
||||
"(email, code_hash, sent_at, expires_at, failed_attempts) "
|
||||
"VALUES (%s, %s, %s, %s, 0)",
|
||||
(email, digest, timestamp, timestamp + ttl_seconds),
|
||||
)
|
||||
else:
|
||||
cursor.execute(
|
||||
"UPDATE registration_codes SET code_hash=%s, sent_at=%s, "
|
||||
"expires_at=%s, failed_attempts=0 WHERE email=%s",
|
||||
(digest, timestamp, timestamp + ttl_seconds, email),
|
||||
)
|
||||
connection.commit()
|
||||
return True
|
||||
except UserError:
|
||||
connection.rollback()
|
||||
raise
|
||||
except pymysql.err.IntegrityError as exc:
|
||||
connection.rollback()
|
||||
if exc.args and exc.args[0] == 1062:
|
||||
raise UserError("验证码发送过于频繁,请稍后重试", 429) from exc
|
||||
raise DatabaseError("无法保存注册验证码") from exc
|
||||
except pymysql.MySQLError as exc:
|
||||
connection.rollback()
|
||||
raise DatabaseError("无法保存注册验证码") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def revoke_registration_code(self, email: str, code: str) -> bool:
|
||||
"""Remove only the still-current challenge after SMTP delivery fails."""
|
||||
email = normalize_email(email)
|
||||
if not isinstance(code, str) or not _CODE.fullmatch(code):
|
||||
raise ValueError("Invalid registration code")
|
||||
digest = self._code_digest(email, code)
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"SELECT code_hash FROM registration_codes WHERE email=%s FOR UPDATE",
|
||||
(email,),
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
if row is None or not hmac.compare_digest(row["code_hash"], digest):
|
||||
connection.rollback()
|
||||
return False
|
||||
cursor.execute(
|
||||
"DELETE FROM registration_codes WHERE email=%s AND code_hash=%s",
|
||||
(email, digest),
|
||||
)
|
||||
connection.commit()
|
||||
return True
|
||||
except pymysql.MySQLError as exc:
|
||||
connection.rollback()
|
||||
raise DatabaseError("无法撤销注册验证码") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def register_with_code(self, username: str, email: str, password: str,
|
||||
code: str, *, now: int | None = None) -> dict[str, Any]:
|
||||
username = _validate_username(username)
|
||||
email = normalize_email(email)
|
||||
password = _validate_password(password)
|
||||
if not isinstance(code, str) or not _CODE.fullmatch(code):
|
||||
raise UserError("验证码格式无效")
|
||||
timestamp = _validate_clock(now)
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"SELECT code_hash, expires_at, failed_attempts "
|
||||
"FROM registration_codes WHERE email=%s FOR UPDATE", (email,),
|
||||
)
|
||||
challenge = cursor.fetchone()
|
||||
if challenge is None:
|
||||
raise UserError("验证码无效或已过期")
|
||||
if timestamp >= int(challenge["expires_at"]):
|
||||
cursor.execute("DELETE FROM registration_codes WHERE email=%s", (email,))
|
||||
connection.commit()
|
||||
raise UserError("验证码无效或已过期")
|
||||
digest = self._code_digest(email, code)
|
||||
if not hmac.compare_digest(digest, challenge["code_hash"]):
|
||||
attempts = int(challenge["failed_attempts"]) + 1
|
||||
if attempts >= _MAX_CODE_ATTEMPTS:
|
||||
cursor.execute("DELETE FROM registration_codes WHERE email=%s", (email,))
|
||||
else:
|
||||
cursor.execute(
|
||||
"UPDATE registration_codes SET failed_attempts=%s WHERE email=%s",
|
||||
(attempts, email),
|
||||
)
|
||||
connection.commit()
|
||||
raise UserError("验证码无效或已过期")
|
||||
password_hash = hash_password(password)
|
||||
cursor.execute(
|
||||
"INSERT INTO users (username, email, password_hash, admin, "
|
||||
"approved, email_verified, created_at) VALUES (%s, %s, %s, 0, 0, 1, %s)",
|
||||
(username, email, password_hash, timestamp),
|
||||
)
|
||||
user_id = cursor.lastrowid
|
||||
cursor.execute("DELETE FROM registration_codes WHERE email=%s", (email,))
|
||||
connection.commit()
|
||||
return {
|
||||
"id": user_id, "username": username, "email": email,
|
||||
"password_hash": password_hash, "admin": False, "approved": False,
|
||||
"email_verified": True, "created_at": timestamp,
|
||||
}
|
||||
except UserError:
|
||||
connection.rollback()
|
||||
raise
|
||||
except pymysql.err.IntegrityError as exc:
|
||||
connection.rollback()
|
||||
if exc.args and exc.args[0] == 1062:
|
||||
raise UserError("用户名或邮箱已存在", 409) from exc
|
||||
raise DatabaseError("无法创建用户") from exc
|
||||
except pymysql.MySQLError as exc:
|
||||
connection.rollback()
|
||||
raise DatabaseError("无法创建用户") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def list_pending_users(self) -> list[dict[str, Any]]:
|
||||
"""Return registered accounts awaiting operator approval, no hashes."""
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"SELECT id, username, email, admin, approved, email_verified, "
|
||||
"created_at FROM users WHERE approved=0 ORDER BY created_at ASC, id ASC"
|
||||
)
|
||||
rows = cursor.fetchall()
|
||||
return [{
|
||||
"id": int(row["id"]), "username": row["username"],
|
||||
"email": row["email"], "admin": bool(row["admin"]),
|
||||
"approved": bool(row["approved"]),
|
||||
"email_verified": bool(row["email_verified"]),
|
||||
"created_at": int(row["created_at"]),
|
||||
} for row in rows]
|
||||
except pymysql.MySQLError as exc:
|
||||
raise DatabaseError("无法读取待审核用户") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def approve_user(self, user_id: int) -> dict[str, Any] | None:
|
||||
"""Approve an account; only the admin-authorized HTTP route may call this."""
|
||||
if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1:
|
||||
raise ValueError("Invalid user ID")
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("UPDATE users SET approved=1 WHERE id=%s", (user_id,))
|
||||
connection.commit()
|
||||
except pymysql.MySQLError as exc:
|
||||
connection.rollback()
|
||||
raise DatabaseError("无法审核用户") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
return self.get_by_id(user_id)
|
||||
|
||||
def assign_vm(self, host_scope: str, vm_uuid: str, user_id: int,
|
||||
*, now: int | None = None) -> None:
|
||||
host_scope, vm_uuid = _vm_identity(host_scope, vm_uuid)
|
||||
if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1:
|
||||
raise ValueError("Invalid user ID")
|
||||
timestamp = _validate_clock(now)
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"INSERT INTO vm_ownership (host_scope, vm_uuid, user_id, created_at) "
|
||||
"VALUES (%s, %s, %s, %s)",
|
||||
(host_scope, vm_uuid, user_id, timestamp),
|
||||
)
|
||||
connection.commit()
|
||||
except pymysql.err.IntegrityError as exc:
|
||||
connection.rollback()
|
||||
if exc.args and exc.args[0] == 1062:
|
||||
if self.owner_of_vm(host_scope, vm_uuid) == user_id:
|
||||
return
|
||||
raise UserError("此虚拟机已归属于其他用户", 409) from exc
|
||||
raise DatabaseError("无法记录虚拟机归属") from exc
|
||||
except pymysql.MySQLError as exc:
|
||||
connection.rollback()
|
||||
raise DatabaseError("无法记录虚拟机归属") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def owner_of_vm(self, host_scope: str, vm_uuid: str) -> int | None:
|
||||
host_scope, vm_uuid = _vm_identity(host_scope, vm_uuid)
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"SELECT user_id FROM vm_ownership WHERE host_scope=%s AND vm_uuid=%s",
|
||||
(host_scope, vm_uuid),
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return None if row is None else int(row["user_id"])
|
||||
except pymysql.MySQLError as exc:
|
||||
raise DatabaseError("无法读取虚拟机归属") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def owns_vm(self, host_scope: str, vm_uuid: str, user_id: int) -> bool:
|
||||
if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1:
|
||||
return False
|
||||
return self.owner_of_vm(host_scope, vm_uuid) == user_id
|
||||
|
||||
def list_owned_vm_ids(self, host_scope: str, user_id: int) -> set[str]:
|
||||
if not isinstance(host_scope, str) or not _HOST_SCOPE.fullmatch(host_scope):
|
||||
raise ValueError("Invalid host scope")
|
||||
if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1:
|
||||
raise ValueError("Invalid user ID")
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"SELECT vm_uuid FROM vm_ownership WHERE host_scope=%s AND user_id=%s",
|
||||
(host_scope, user_id),
|
||||
)
|
||||
return {row["vm_uuid"] for row in cursor.fetchall()}
|
||||
except pymysql.MySQLError as exc:
|
||||
raise DatabaseError("无法读取虚拟机归属") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def delete_vm_owner(self, host_scope: str, vm_uuid: str) -> None:
|
||||
host_scope, vm_uuid = _vm_identity(host_scope, vm_uuid)
|
||||
connection = self._connect()
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
"DELETE FROM vm_ownership WHERE host_scope=%s AND vm_uuid=%s",
|
||||
(host_scope, vm_uuid),
|
||||
)
|
||||
connection.commit()
|
||||
except pymysql.MySQLError as exc:
|
||||
connection.rollback()
|
||||
raise DatabaseError("无法删除虚拟机归属") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
Loading…
Reference in New Issue