"""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 "), _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..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")