"""Unit Tests for Cybersecurity, Redaction & Cryptographic Auth."""
from __future__ import annotations

import unittest
import time

from backend.app.audit.logger import redact_sensitive_data
from backend.app.auth.security import (
    create_access_token,
    decode_access_token,
    hash_password,
    verify_password,
)


class TestSecurity(unittest.TestCase):
    def test_log_credential_redaction(self) -> None:
        """Verify API keys, secrets, and passwords are automatically redacted from messages."""
        msg = 'Connecting with api_key="secretKey12345678" and secret="mySuperSecretApiSecretKey"'
        redacted = redact_sensitive_data(msg)
        self.assertNotIn("secretKey12345678", redacted)
        self.assertNotIn("mySuperSecretApiSecretKey", redacted)
        self.assertIn("***REDACTED***", redacted)

    def test_password_hashing_and_verification(self) -> None:
        """Verify PBKDF2 salted password hashing."""
        pwd = "SafeAdminPassword#2026"
        hashed = hash_password(pwd)
        self.assertNotEqual(pwd, hashed)
        self.assertTrue(verify_password(pwd, hashed))
        self.assertFalse(verify_password("WrongPassword123", hashed))

    def test_jwt_token_creation_and_tampering(self) -> None:
        """Verify HMAC signed token creation, decoding, and forged payload rejection."""
        token = create_access_token({"sub": "admin", "role": "admin"}, expires_delta_seconds=3600)
        decoded = decode_access_token(token)
        self.assertIsNotNone(decoded)
        self.assertEqual(decoded["sub"], "admin")
        self.assertEqual(decoded["role"], "admin")

        # Tampered token
        tampered_token = token[:-4] + "fake"
        self.assertIsNone(decode_access_token(tampered_token))

    def test_jwt_token_expiration(self) -> None:
        """Verify expired tokens are rejected."""
        # Create token expired 10 seconds ago
        token = create_access_token({"sub": "admin"}, expires_delta_seconds=-10)
        self.assertIsNone(decode_access_token(token))


if __name__ == "__main__":
    unittest.main()
