test_nacl.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # -*- coding: utf-8 -*-
  2. """
  3. Tests for the nacl execution module
  4. """
  5. # Import Python libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. # Import Salt libs
  8. import salt.utils.stringutils
  9. # Import Salt Testing libs
  10. from tests.support.mixins import LoaderModuleMockMixin
  11. from tests.support.unit import TestCase, skipIf
  12. try:
  13. import libnacl.secret # pylint: disable=unused-import
  14. import libnacl.sealed # pylint: disable=unused-import
  15. import salt.modules.nacl as nacl
  16. HAS_LIBNACL = True
  17. except (ImportError, OSError, AttributeError):
  18. HAS_LIBNACL = False
  19. @skipIf(not HAS_LIBNACL, "skipping test_nacl, libnacl is unavailable")
  20. class NaclTest(TestCase, LoaderModuleMockMixin):
  21. """
  22. Test the nacl runner
  23. """
  24. def setup_loader_modules(self):
  25. self.unencrypted_data = salt.utils.stringutils.to_bytes("hello")
  26. self.opts = salt.config.DEFAULT_MINION_OPTS.copy()
  27. utils = salt.loader.utils(self.opts)
  28. funcs = salt.loader.minion_mods(self.opts, utils=utils, whitelist=["nacl"])
  29. return {
  30. nacl: {"__opts__": self.opts, "__utils__": utils, "__salt__": funcs},
  31. }
  32. def setUp(self):
  33. # Generate the keys
  34. ret = nacl.keygen()
  35. self.assertIn("pk", ret)
  36. self.assertIn("sk", ret)
  37. self.pk = ret["pk"]
  38. self.sk = ret["sk"]
  39. def test_keygen(self):
  40. """
  41. Test keygen
  42. """
  43. self.assertEqual(len(self.pk), 44)
  44. self.assertEqual(len(self.sk), 44)
  45. def test_enc_dec(self):
  46. """
  47. Generate keys, encrypt, then decrypt.
  48. """
  49. # Encrypt with pk
  50. encrypted_data = nacl.enc(data=self.unencrypted_data, pk=self.pk)
  51. # Decrypt with sk
  52. decrypted_data = nacl.dec(data=encrypted_data, sk=self.sk)
  53. self.assertEqual(self.unencrypted_data, decrypted_data)
  54. def test_sealedbox_enc_dec(self):
  55. """
  56. Generate keys, encrypt, then decrypt.
  57. """
  58. # Encrypt with pk
  59. encrypted_data = nacl.sealedbox_encrypt(data=self.unencrypted_data, pk=self.pk)
  60. # Decrypt with sk
  61. decrypted_data = nacl.sealedbox_decrypt(data=encrypted_data, sk=self.sk)
  62. self.assertEqual(self.unencrypted_data, decrypted_data)
  63. def test_secretbox_enc_dec(self):
  64. """
  65. Generate keys, encrypt, then decrypt.
  66. """
  67. # Encrypt with sk
  68. encrypted_data = nacl.secretbox_encrypt(data=self.unencrypted_data, sk=self.sk)
  69. # Decrypt with sk
  70. decrypted_data = nacl.secretbox_decrypt(data=encrypted_data, sk=self.sk)
  71. self.assertEqual(self.unencrypted_data, decrypted_data)