test_signature.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. # test_signature.py -- tests for signature.py
  2. # Copyright (C) 2025 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Tests for signature vendors."""
  22. import shutil
  23. import subprocess
  24. import unittest
  25. from dulwich.config import ConfigDict
  26. from dulwich.signature import GPGCliSignatureVendor, GPGSignatureVendor, SignatureVendor
  27. try:
  28. import gpg
  29. except ImportError:
  30. gpg = None
  31. class SignatureVendorTests(unittest.TestCase):
  32. """Tests for SignatureVendor base class."""
  33. def test_sign_not_implemented(self) -> None:
  34. """Test that sign raises NotImplementedError."""
  35. vendor = SignatureVendor()
  36. with self.assertRaises(NotImplementedError):
  37. vendor.sign(b"test data")
  38. def test_verify_not_implemented(self) -> None:
  39. """Test that verify raises NotImplementedError."""
  40. vendor = SignatureVendor()
  41. with self.assertRaises(NotImplementedError):
  42. vendor.verify(b"test data", b"fake signature")
  43. @unittest.skipIf(gpg is None, "gpg not available")
  44. class GPGSignatureVendorTests(unittest.TestCase):
  45. """Tests for GPGSignatureVendor."""
  46. def test_sign_and_verify(self) -> None:
  47. """Test basic sign and verify cycle.
  48. Note: This test requires a GPG key to be configured in the test
  49. environment. It may be skipped in environments without GPG setup.
  50. """
  51. vendor = GPGSignatureVendor()
  52. test_data = b"test data to sign"
  53. try:
  54. # Sign the data
  55. signature = vendor.sign(test_data)
  56. self.assertIsInstance(signature, bytes)
  57. self.assertGreater(len(signature), 0)
  58. # Verify the signature
  59. vendor.verify(test_data, signature)
  60. except gpg.errors.GPGMEError as e:
  61. # Skip test if no GPG key is available
  62. self.skipTest(f"GPG key not available: {e}")
  63. def test_verify_invalid_signature(self) -> None:
  64. """Test that verify raises an error for invalid signatures."""
  65. vendor = GPGSignatureVendor()
  66. test_data = b"test data"
  67. invalid_signature = b"this is not a valid signature"
  68. with self.assertRaises(gpg.errors.GPGMEError):
  69. vendor.verify(test_data, invalid_signature)
  70. def test_sign_with_keyid(self) -> None:
  71. """Test signing with a specific key ID.
  72. Note: This test requires a GPG key to be configured in the test
  73. environment. It may be skipped in environments without GPG setup.
  74. """
  75. vendor = GPGSignatureVendor()
  76. test_data = b"test data to sign"
  77. try:
  78. # Try to get a key from the keyring
  79. with gpg.Context() as ctx:
  80. keys = list(ctx.keylist(secret=True))
  81. if not keys:
  82. self.skipTest("No GPG keys available for testing")
  83. key = keys[0]
  84. signature = vendor.sign(test_data, keyid=key.fpr)
  85. self.assertIsInstance(signature, bytes)
  86. self.assertGreater(len(signature), 0)
  87. # Verify the signature
  88. vendor.verify(test_data, signature)
  89. except gpg.errors.GPGMEError as e:
  90. self.skipTest(f"GPG key not available: {e}")
  91. class GPGCliSignatureVendorTests(unittest.TestCase):
  92. """Tests for GPGCliSignatureVendor."""
  93. def setUp(self) -> None:
  94. """Check if gpg command is available."""
  95. if shutil.which("gpg") is None:
  96. self.skipTest("gpg command not available")
  97. def test_sign_and_verify(self) -> None:
  98. """Test basic sign and verify cycle using CLI."""
  99. vendor = GPGCliSignatureVendor()
  100. test_data = b"test data to sign"
  101. try:
  102. # Sign the data
  103. signature = vendor.sign(test_data)
  104. self.assertIsInstance(signature, bytes)
  105. self.assertGreater(len(signature), 0)
  106. self.assertTrue(signature.startswith(b"-----BEGIN PGP SIGNATURE-----"))
  107. # Verify the signature
  108. vendor.verify(test_data, signature)
  109. except subprocess.CalledProcessError as e:
  110. # Skip test if no GPG key is available or configured
  111. self.skipTest(f"GPG signing failed: {e}")
  112. def test_verify_invalid_signature(self) -> None:
  113. """Test that verify raises an error for invalid signatures."""
  114. vendor = GPGCliSignatureVendor()
  115. test_data = b"test data"
  116. invalid_signature = b"this is not a valid signature"
  117. with self.assertRaises(subprocess.CalledProcessError):
  118. vendor.verify(test_data, invalid_signature)
  119. def test_sign_with_keyid(self) -> None:
  120. """Test signing with a specific key ID using CLI."""
  121. vendor = GPGCliSignatureVendor()
  122. test_data = b"test data to sign"
  123. try:
  124. # Try to get a key from the keyring
  125. result = subprocess.run(
  126. ["gpg", "--list-secret-keys", "--with-colons"],
  127. capture_output=True,
  128. check=True,
  129. text=True,
  130. )
  131. # Parse output to find a key fingerprint
  132. keyid = None
  133. for line in result.stdout.split("\n"):
  134. if line.startswith("fpr:"):
  135. keyid = line.split(":")[9]
  136. break
  137. if not keyid:
  138. self.skipTest("No GPG keys available for testing")
  139. signature = vendor.sign(test_data, keyid=keyid)
  140. self.assertIsInstance(signature, bytes)
  141. self.assertGreater(len(signature), 0)
  142. # Verify the signature
  143. vendor.verify(test_data, signature)
  144. except subprocess.CalledProcessError as e:
  145. self.skipTest(f"GPG key not available: {e}")
  146. def test_verify_with_keyids(self) -> None:
  147. """Test verifying with specific trusted key IDs."""
  148. vendor = GPGCliSignatureVendor()
  149. test_data = b"test data to sign"
  150. try:
  151. # Sign without specifying a key (use default)
  152. signature = vendor.sign(test_data)
  153. # Get the primary key fingerprint from the keyring
  154. result = subprocess.run(
  155. ["gpg", "--list-secret-keys", "--with-colons"],
  156. capture_output=True,
  157. check=True,
  158. text=True,
  159. )
  160. primary_keyid = None
  161. for line in result.stdout.split("\n"):
  162. if line.startswith("fpr:"):
  163. primary_keyid = line.split(":")[9]
  164. break
  165. if not primary_keyid:
  166. self.skipTest("No GPG keys available for testing")
  167. # Verify with the correct primary keyid - should succeed
  168. # (GPG shows primary key fingerprint even if signed by subkey)
  169. vendor.verify(test_data, signature, keyids=[primary_keyid])
  170. # Verify with a different keyid - should fail
  171. fake_keyid = "0" * 40 # Fake 40-character fingerprint
  172. with self.assertRaises(ValueError):
  173. vendor.verify(test_data, signature, keyids=[fake_keyid])
  174. except subprocess.CalledProcessError as e:
  175. self.skipTest(f"GPG key not available: {e}")
  176. def test_custom_gpg_command(self) -> None:
  177. """Test using a custom GPG command path."""
  178. vendor = GPGCliSignatureVendor(gpg_command="gpg")
  179. test_data = b"test data"
  180. try:
  181. signature = vendor.sign(test_data)
  182. self.assertIsInstance(signature, bytes)
  183. except subprocess.CalledProcessError as e:
  184. self.skipTest(f"GPG not available: {e}")
  185. def test_gpg_program_from_config(self) -> None:
  186. """Test reading gpg.program from config."""
  187. # Create a config with gpg.program set
  188. config = ConfigDict()
  189. config.set((b"gpg",), b"program", b"gpg2")
  190. vendor = GPGCliSignatureVendor(config=config)
  191. self.assertEqual(vendor.gpg_command, "gpg2")
  192. def test_gpg_program_override(self) -> None:
  193. """Test that gpg_command parameter overrides config."""
  194. config = ConfigDict()
  195. config.set((b"gpg",), b"program", b"gpg2")
  196. vendor = GPGCliSignatureVendor(config=config, gpg_command="gpg")
  197. self.assertEqual(vendor.gpg_command, "gpg")
  198. def test_gpg_program_default(self) -> None:
  199. """Test default gpg command when no config provided."""
  200. vendor = GPGCliSignatureVendor()
  201. self.assertEqual(vendor.gpg_command, "gpg")
  202. def test_gpg_program_default_when_not_in_config(self) -> None:
  203. """Test default gpg command when config doesn't have gpg.program."""
  204. config = ConfigDict()
  205. vendor = GPGCliSignatureVendor(config=config)
  206. self.assertEqual(vendor.gpg_command, "gpg")