"""T1.7 凭据加密工具单测——Fernet 往返 + 掩码（ARCH §4.7）。

绝不在响应/日志回显明文 Key。
"""

from __future__ import annotations

import pytest
from cryptography.fernet import Fernet
from ww_api.security.credentials import (
    CredentialKeyError,
    decrypt_api_key,
    encrypt_api_key,
    mask_api_key,
)

KEY = Fernet.generate_key().decode()


def test_encrypt_decrypt_round_trip() -> None:
    # Arrange
    plaintext = "sk-abc123def456"
    # Act
    blob = encrypt_api_key(plaintext, key=KEY)
    # Assert
    assert isinstance(blob, bytes)
    assert plaintext.encode() not in blob  # 密文不含明文
    assert decrypt_api_key(blob, key=KEY) == plaintext


def test_encrypt_is_non_deterministic() -> None:
    # Fernet 含随机 IV——两次加密产物不同，但都能解回
    a = encrypt_api_key("sk-secret", key=KEY)
    b = encrypt_api_key("sk-secret", key=KEY)
    assert a != b
    assert decrypt_api_key(a, key=KEY) == decrypt_api_key(b, key=KEY) == "sk-secret"


def test_missing_key_fails_fast() -> None:
    with pytest.raises(CredentialKeyError):
        encrypt_api_key("sk-x", key="")


def test_invalid_key_fails_fast() -> None:
    with pytest.raises(CredentialKeyError):
        encrypt_api_key("sk-x", key="not-a-valid-fernet-key")


def test_mask_shows_only_last_four() -> None:
    assert mask_api_key("sk-abcdefgh1234") == "sk-…1234"


def test_mask_short_key_fully_hidden() -> None:
    # 极短 key 不泄露任何字符
    assert mask_api_key("ab") == "sk-…••••"


def test_mask_empty_key() -> None:
    assert mask_api_key("") == "sk-…••••"
