import os
import unittest
from unittest import mock

from aerix_certbot import plugin


class ValidateTokenTests(unittest.TestCase):
    def test_accepts_base64url_token(self):
        token = "aFNw3LyFeBqcBdXabhqgKhfQO4I0dPxututEsXH3umA"
        # Should not raise
        plugin.AerixAuthenticator._validate_token(token)

    def test_accepts_padded_ascii_token(self):
        token = "abcdEFGH1234567890-_="
        plugin.AerixAuthenticator._validate_token(token)

    def test_rejects_path_separators(self):
        with self.assertRaises(plugin.errors.PluginError):
            plugin.AerixAuthenticator._validate_token("valid/../../token")

    def test_rejects_absolute_path(self):
        with self.assertRaises(plugin.errors.PluginError):
            plugin.AerixAuthenticator._validate_token(os.path.join(os.sep, "token"))

    def test_rejects_whitespace(self):
        with self.assertRaises(plugin.errors.PluginError):
            plugin.AerixAuthenticator._validate_token(" token\n")

    def test_rejects_non_ascii(self):
        with self.assertRaises(plugin.errors.PluginError):
            plugin.AerixAuthenticator._validate_token("tøken")


class PerformTests(unittest.TestCase):
    def test_perform_does_not_reject_on_good_token_flag(self):
        config = mock.Mock(aerix_debug=False)
        authenticator = plugin.AerixAuthenticator(config, "aerix")

        achall = mock.Mock()
        achall.domain = "example.com"
        achall.account_key = mock.Mock()
        achall.chall.good_token = False
        achall.chall.encode.return_value = "valid-token"
        achall.validation.return_value = "valid-token.thumbprint"
        achall.response.return_value = "response"

        with mock.patch.object(
            authenticator,
            "_write_challenge_file",
            return_value="/var/lib/aerix/example.com/valid-token",
        ) as write_mock:
            responses = authenticator.perform([achall])

        write_mock.assert_called_once_with(
            plugin.AERIX_BASE_PATH,
            "example.com",
            "valid-token",
            "valid-token.thumbprint",
        )
        self.assertEqual(["response"], responses)


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