from pathlib import Path
import unittest


ROOT = Path(__file__).resolve().parents[1]


class PrivateApiAuthTests(unittest.TestCase):
    def test_private_api_requires_hmac_timestamp_nonce_and_principal(self) -> None:
        init = (ROOT / "init.inc.php").read_text(encoding="utf-8")
        for contract in (
            "BEE_SERVICE_HMAC_KEY",
            "HTTP_X_RAZGAR_SERVICE",
            "HTTP_X_RAZGAR_PRINCIPAL",
            "HTTP_X_RAZGAR_TIMESTAMP",
            "HTTP_X_RAZGAR_NONCE",
            "HTTP_X_RAZGAR_SIGNATURE",
            "hash_hmac('sha256'",
            "hash_equals(",
        ):
            self.assertIn(contract, init)

    def test_replay_nonce_is_atomically_reserved_in_redis(self) -> None:
        init = (ROOT / "init.inc.php").read_text(encoding="utf-8")
        self.assertIn("bee:service-nonce:", init)
        self.assertIn("'NX'", init)
        self.assertIn("'EX'", init)

    def test_private_request_is_bound_to_test_owner_or_test_runtime(self) -> None:
        init = (ROOT / "init.inc.php").read_text(encoding="utf-8")
        self.assertIn("bee_tests", init)
        self.assertIn("$principal_id !== $test_id", init)

    def test_debug_errors_and_private_cors_are_not_public(self) -> None:
        init = (ROOT / "init.inc.php").read_text(encoding="utf-8")
        self.assertIn("ini_set('display_errors', 'Off')", init)
        self.assertNotIn('"https://test.razgar.io"', init)


if __name__ == "__main__":
    unittest.main()
