test_signature.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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 (
  27. SIGNATURE_FORMAT_OPENPGP,
  28. SIGNATURE_FORMAT_SSH,
  29. SIGNATURE_FORMAT_X509,
  30. GPGCliSignatureVendor,
  31. GPGSignatureVendor,
  32. SignatureVendor,
  33. SSHCliSignatureVendor,
  34. SSHSigSignatureVendor,
  35. X509SignatureVendor,
  36. detect_signature_format,
  37. get_signature_vendor,
  38. get_signature_vendor_for_signature,
  39. )
  40. try:
  41. import gpg
  42. except ImportError:
  43. gpg = None
  44. class SignatureVendorTests(unittest.TestCase):
  45. """Tests for SignatureVendor base class."""
  46. def test_sign_not_implemented(self) -> None:
  47. """Test that sign raises NotImplementedError."""
  48. vendor = SignatureVendor()
  49. with self.assertRaises(NotImplementedError):
  50. vendor.sign(b"test data")
  51. def test_verify_not_implemented(self) -> None:
  52. """Test that verify raises NotImplementedError."""
  53. vendor = SignatureVendor()
  54. with self.assertRaises(NotImplementedError):
  55. vendor.verify(b"test data", b"fake signature")
  56. @unittest.skipIf(gpg is None, "gpg not available")
  57. class GPGSignatureVendorTests(unittest.TestCase):
  58. """Tests for GPGSignatureVendor."""
  59. def test_min_trust_level_from_config(self) -> None:
  60. """Test reading gpg.minTrustLevel from config."""
  61. config = ConfigDict()
  62. config.set((b"gpg",), b"minTrustLevel", b"marginal")
  63. vendor = GPGSignatureVendor(config=config)
  64. self.assertEqual(vendor.min_trust_level, "marginal")
  65. def test_min_trust_level_default(self) -> None:
  66. """Test default when gpg.minTrustLevel not in config."""
  67. vendor = GPGSignatureVendor()
  68. self.assertIsNone(vendor.min_trust_level)
  69. def test_sign_and_verify(self) -> None:
  70. """Test basic sign and verify cycle.
  71. Note: This test requires a GPG key to be configured in the test
  72. environment. It may be skipped in environments without GPG setup.
  73. """
  74. vendor = GPGSignatureVendor()
  75. test_data = b"test data to sign"
  76. try:
  77. # Sign the data
  78. signature = vendor.sign(test_data)
  79. self.assertIsInstance(signature, bytes)
  80. self.assertGreater(len(signature), 0)
  81. # Verify the signature
  82. vendor.verify(test_data, signature)
  83. except gpg.errors.GPGMEError as e:
  84. # Skip test if no GPG key is available
  85. self.skipTest(f"GPG key not available: {e}")
  86. def test_verify_invalid_signature(self) -> None:
  87. """Test that verify raises an error for invalid signatures."""
  88. vendor = GPGSignatureVendor()
  89. test_data = b"test data"
  90. invalid_signature = b"this is not a valid signature"
  91. with self.assertRaises(gpg.errors.GPGMEError):
  92. vendor.verify(test_data, invalid_signature)
  93. def test_sign_with_keyid(self) -> None:
  94. """Test signing with a specific key ID.
  95. Note: This test requires a GPG key to be configured in the test
  96. environment. It may be skipped in environments without GPG setup.
  97. """
  98. vendor = GPGSignatureVendor()
  99. test_data = b"test data to sign"
  100. try:
  101. # Try to get a key from the keyring
  102. with gpg.Context() as ctx:
  103. keys = list(ctx.keylist(secret=True))
  104. if not keys:
  105. self.skipTest("No GPG keys available for testing")
  106. key = keys[0]
  107. signature = vendor.sign(test_data, keyid=key.fpr)
  108. self.assertIsInstance(signature, bytes)
  109. self.assertGreater(len(signature), 0)
  110. # Verify the signature
  111. vendor.verify(test_data, signature)
  112. except gpg.errors.GPGMEError as e:
  113. self.skipTest(f"GPG key not available: {e}")
  114. class GPGCliSignatureVendorTests(unittest.TestCase):
  115. """Tests for GPGCliSignatureVendor."""
  116. def setUp(self) -> None:
  117. """Check if gpg command is available."""
  118. if shutil.which("gpg") is None:
  119. self.skipTest("gpg command not available")
  120. def test_sign_and_verify(self) -> None:
  121. """Test basic sign and verify cycle using CLI."""
  122. vendor = GPGCliSignatureVendor()
  123. test_data = b"test data to sign"
  124. try:
  125. # Sign the data
  126. signature = vendor.sign(test_data)
  127. self.assertIsInstance(signature, bytes)
  128. self.assertGreater(len(signature), 0)
  129. self.assertTrue(signature.startswith(b"-----BEGIN PGP SIGNATURE-----"))
  130. # Verify the signature
  131. vendor.verify(test_data, signature)
  132. except subprocess.CalledProcessError as e:
  133. # Skip test if no GPG key is available or configured
  134. self.skipTest(f"GPG signing failed: {e}")
  135. def test_verify_invalid_signature(self) -> None:
  136. """Test that verify raises an error for invalid signatures."""
  137. vendor = GPGCliSignatureVendor()
  138. test_data = b"test data"
  139. invalid_signature = b"this is not a valid signature"
  140. with self.assertRaises(subprocess.CalledProcessError):
  141. vendor.verify(test_data, invalid_signature)
  142. def test_sign_with_keyid(self) -> None:
  143. """Test signing with a specific key ID using CLI."""
  144. vendor = GPGCliSignatureVendor()
  145. test_data = b"test data to sign"
  146. try:
  147. # Try to get a key from the keyring
  148. result = subprocess.run(
  149. ["gpg", "--list-secret-keys", "--with-colons"],
  150. capture_output=True,
  151. check=True,
  152. text=True,
  153. )
  154. # Parse output to find a key fingerprint
  155. keyid = None
  156. for line in result.stdout.split("\n"):
  157. if line.startswith("fpr:"):
  158. keyid = line.split(":")[9]
  159. break
  160. if not keyid:
  161. self.skipTest("No GPG keys available for testing")
  162. signature = vendor.sign(test_data, keyid=keyid)
  163. self.assertIsInstance(signature, bytes)
  164. self.assertGreater(len(signature), 0)
  165. # Verify the signature
  166. vendor.verify(test_data, signature)
  167. except subprocess.CalledProcessError as e:
  168. self.skipTest(f"GPG key not available: {e}")
  169. def test_verify_with_keyids(self) -> None:
  170. """Test verifying with specific trusted key IDs."""
  171. vendor = GPGCliSignatureVendor()
  172. test_data = b"test data to sign"
  173. try:
  174. # Sign without specifying a key (use default)
  175. signature = vendor.sign(test_data)
  176. # Get the primary key fingerprint from the keyring
  177. result = subprocess.run(
  178. ["gpg", "--list-secret-keys", "--with-colons"],
  179. capture_output=True,
  180. check=True,
  181. text=True,
  182. )
  183. primary_keyid = None
  184. for line in result.stdout.split("\n"):
  185. if line.startswith("fpr:"):
  186. primary_keyid = line.split(":")[9]
  187. break
  188. if not primary_keyid:
  189. self.skipTest("No GPG keys available for testing")
  190. # Verify with the correct primary keyid - should succeed
  191. # (GPG shows primary key fingerprint even if signed by subkey)
  192. vendor.verify(test_data, signature, keyids=[primary_keyid])
  193. # Verify with a different keyid - should fail
  194. fake_keyid = "0" * 40 # Fake 40-character fingerprint
  195. with self.assertRaises(ValueError):
  196. vendor.verify(test_data, signature, keyids=[fake_keyid])
  197. except subprocess.CalledProcessError as e:
  198. self.skipTest(f"GPG key not available: {e}")
  199. def test_custom_gpg_command(self) -> None:
  200. """Test using a custom GPG command path."""
  201. vendor = GPGCliSignatureVendor(gpg_command="gpg")
  202. test_data = b"test data"
  203. try:
  204. signature = vendor.sign(test_data)
  205. self.assertIsInstance(signature, bytes)
  206. except subprocess.CalledProcessError as e:
  207. self.skipTest(f"GPG not available: {e}")
  208. def test_gpg_program_from_config(self) -> None:
  209. """Test reading gpg.program from config."""
  210. # Create a config with gpg.program set
  211. config = ConfigDict()
  212. config.set((b"gpg",), b"program", b"gpg2")
  213. vendor = GPGCliSignatureVendor(config=config)
  214. self.assertEqual(vendor.gpg_command, "gpg2")
  215. def test_gpg_program_override(self) -> None:
  216. """Test that gpg_command parameter overrides config."""
  217. config = ConfigDict()
  218. config.set((b"gpg",), b"program", b"gpg2")
  219. vendor = GPGCliSignatureVendor(config=config, gpg_command="gpg")
  220. self.assertEqual(vendor.gpg_command, "gpg")
  221. def test_gpg_program_default(self) -> None:
  222. """Test default gpg command when no config provided."""
  223. vendor = GPGCliSignatureVendor()
  224. self.assertEqual(vendor.gpg_command, "gpg")
  225. def test_gpg_program_default_when_not_in_config(self) -> None:
  226. """Test default gpg command when config doesn't have gpg.program."""
  227. config = ConfigDict()
  228. vendor = GPGCliSignatureVendor(config=config)
  229. self.assertEqual(vendor.gpg_command, "gpg")
  230. class X509SignatureVendorTests(unittest.TestCase):
  231. """Tests for X509SignatureVendor."""
  232. def test_gpgsm_program_default(self) -> None:
  233. """Test default gpgsm command is 'gpgsm'."""
  234. vendor = X509SignatureVendor()
  235. self.assertEqual(vendor.gpgsm_command, "gpgsm")
  236. def test_gpgsm_program_from_config(self) -> None:
  237. """Test reading gpg.x509.program from config."""
  238. config = ConfigDict()
  239. config.set((b"gpg", b"x509"), b"program", b"/usr/local/bin/gpgsm")
  240. vendor = X509SignatureVendor(config=config)
  241. self.assertEqual(vendor.gpgsm_command, "/usr/local/bin/gpgsm")
  242. def test_gpgsm_program_override(self) -> None:
  243. """Test gpgsm_command parameter overrides config."""
  244. config = ConfigDict()
  245. config.set((b"gpg", b"x509"), b"program", b"/usr/local/bin/gpgsm")
  246. vendor = X509SignatureVendor(config=config, gpgsm_command="/custom/gpgsm")
  247. self.assertEqual(vendor.gpgsm_command, "/custom/gpgsm")
  248. def test_gpgsm_program_default_when_not_in_config(self) -> None:
  249. """Test default when gpg.x509.program not in config."""
  250. config = ConfigDict()
  251. vendor = X509SignatureVendor(config=config)
  252. self.assertEqual(vendor.gpgsm_command, "gpgsm")
  253. @unittest.skipIf(
  254. shutil.which("gpgsm") is None, "gpgsm command not available in PATH"
  255. )
  256. def test_sign_and_verify(self) -> None:
  257. """Test basic X.509 sign and verify cycle.
  258. Note: This test requires gpgsm and an X.509 certificate to be configured.
  259. It may be skipped in environments without gpgsm/certificate setup.
  260. """
  261. vendor = X509SignatureVendor()
  262. test_data = b"test data to sign"
  263. try:
  264. # Try to sign the data
  265. signature = vendor.sign(test_data)
  266. self.assertIsInstance(signature, bytes)
  267. self.assertGreater(len(signature), 0)
  268. # Verify the signature
  269. vendor.verify(test_data, signature)
  270. except subprocess.CalledProcessError:
  271. # Skip test if no X.509 certificate is available
  272. self.skipTest("No X.509 certificate available for signing")
  273. class GetSignatureVendorTests(unittest.TestCase):
  274. """Tests for get_signature_vendor function."""
  275. def test_default_format(self) -> None:
  276. """Test that default format is openpgp."""
  277. vendor = get_signature_vendor()
  278. self.assertIsInstance(vendor, (GPGSignatureVendor, GPGCliSignatureVendor))
  279. def test_explicit_openpgp_format(self) -> None:
  280. """Test explicitly requesting openpgp format."""
  281. vendor = get_signature_vendor(format="openpgp")
  282. self.assertIsInstance(vendor, (GPGSignatureVendor, GPGCliSignatureVendor))
  283. def test_format_from_config(self) -> None:
  284. """Test reading format from config."""
  285. config = ConfigDict()
  286. config.set((b"gpg",), b"format", b"openpgp")
  287. vendor = get_signature_vendor(config=config)
  288. self.assertIsInstance(vendor, (GPGSignatureVendor, GPGCliSignatureVendor))
  289. def test_format_case_insensitive(self) -> None:
  290. """Test that format is case-insensitive."""
  291. vendor = get_signature_vendor(format="OpenPGP")
  292. self.assertIsInstance(vendor, (GPGSignatureVendor, GPGCliSignatureVendor))
  293. def test_x509_format_supported(self) -> None:
  294. """Test that x509 format is now supported."""
  295. vendor = get_signature_vendor(format="x509")
  296. self.assertIsInstance(vendor, X509SignatureVendor)
  297. def test_ssh_format_supported(self) -> None:
  298. """Test that ssh format is now supported."""
  299. vendor = get_signature_vendor(format="ssh")
  300. # Should be either SSHSigSignatureVendor or SSHCliSignatureVendor
  301. self.assertIsInstance(vendor, (SSHSigSignatureVendor, SSHCliSignatureVendor))
  302. def test_invalid_format(self) -> None:
  303. """Test that invalid format raises ValueError."""
  304. with self.assertRaises(ValueError) as cm:
  305. get_signature_vendor(format="invalid")
  306. self.assertIn("Unsupported", str(cm.exception))
  307. def test_config_passed_to_vendor(self) -> None:
  308. """Test that config is passed to the vendor."""
  309. config = ConfigDict()
  310. config.set((b"gpg",), b"program", b"gpg2")
  311. vendor = get_signature_vendor(format="openpgp", config=config)
  312. # If CLI vendor is used, check that config was passed
  313. if isinstance(vendor, GPGCliSignatureVendor):
  314. self.assertEqual(vendor.gpg_command, "gpg2")
  315. def test_ssh_format(self) -> None:
  316. """Test requesting SSH format."""
  317. vendor = get_signature_vendor(format="ssh")
  318. # Should be either SSHSigSignatureVendor or SSHCliSignatureVendor
  319. self.assertIsInstance(vendor, (SSHSigSignatureVendor, SSHCliSignatureVendor))
  320. def test_x509_format(self) -> None:
  321. """Test requesting X.509 format."""
  322. vendor = get_signature_vendor(format="x509")
  323. self.assertIsInstance(vendor, X509SignatureVendor)
  324. class SSHSigSignatureVendorTests(unittest.TestCase):
  325. """Tests for SSHSigSignatureVendor (sshsig package implementation)."""
  326. def test_sign_not_supported(self) -> None:
  327. """Test that sign raises NotImplementedError with helpful message."""
  328. vendor = SSHSigSignatureVendor()
  329. with self.assertRaises(NotImplementedError) as cm:
  330. vendor.sign(b"test data", keyid="dummy")
  331. self.assertIn("SSHCliSignatureVendor", str(cm.exception))
  332. def test_verify_without_config_raises(self) -> None:
  333. """Test that verify without config or keyids raises ValueError."""
  334. vendor = SSHSigSignatureVendor()
  335. with self.assertRaises(ValueError) as cm:
  336. vendor.verify(b"test data", b"fake signature")
  337. self.assertIn("allowedSignersFile", str(cm.exception))
  338. def test_config_parsing(self) -> None:
  339. """Test parsing SSH config options."""
  340. config = ConfigDict()
  341. config.set((b"gpg", b"ssh"), b"allowedSignersFile", b"/path/to/allowed")
  342. config.set((b"gpg", b"ssh"), b"defaultKeyCommand", b"ssh-add -L")
  343. vendor = SSHSigSignatureVendor(config=config)
  344. self.assertEqual(vendor.allowed_signers_file, "/path/to/allowed")
  345. self.assertEqual(vendor.default_key_command, "ssh-add -L")
  346. def test_verify_with_cli_generated_signature(self) -> None:
  347. """Test verifying a signature created by SSH CLI vendor."""
  348. import os
  349. import tempfile
  350. if shutil.which("ssh-keygen") is None:
  351. self.skipTest("ssh-keygen not available")
  352. # Generate a test SSH key and signature using CLI vendor
  353. with tempfile.TemporaryDirectory() as tmpdir:
  354. private_key = os.path.join(tmpdir, "test_key")
  355. public_key = private_key + ".pub"
  356. allowed_signers = os.path.join(tmpdir, "allowed_signers")
  357. # Generate Ed25519 key
  358. subprocess.run(
  359. [
  360. "ssh-keygen",
  361. "-t",
  362. "ed25519",
  363. "-f",
  364. private_key,
  365. "-N",
  366. "",
  367. "-C",
  368. "test@example.com",
  369. ],
  370. capture_output=True,
  371. check=True,
  372. )
  373. # Create allowed_signers file
  374. with open(public_key) as pub:
  375. pub_key_content = pub.read().strip()
  376. with open(allowed_signers, "w") as allowed:
  377. allowed.write(f"* {pub_key_content}\n")
  378. # Sign with CLI vendor
  379. cli_config = ConfigDict()
  380. cli_config.set(
  381. (b"gpg", b"ssh"), b"allowedSignersFile", allowed_signers.encode()
  382. )
  383. cli_vendor = SSHCliSignatureVendor(config=cli_config)
  384. test_data = b"test data for sshsig verification"
  385. signature = cli_vendor.sign(test_data, keyid=private_key)
  386. # Verify with sshsig package vendor
  387. pkg_config = ConfigDict()
  388. pkg_config.set(
  389. (b"gpg", b"ssh"), b"allowedSignersFile", allowed_signers.encode()
  390. )
  391. pkg_vendor = SSHSigSignatureVendor(config=pkg_config)
  392. # This should succeed
  393. pkg_vendor.verify(test_data, signature)
  394. class SSHCliSignatureVendorTests(unittest.TestCase):
  395. """Tests for SSHCliSignatureVendor."""
  396. def setUp(self) -> None:
  397. """Check if ssh-keygen is available."""
  398. if shutil.which("ssh-keygen") is None:
  399. self.skipTest("ssh-keygen command not available")
  400. def test_ssh_program_from_config(self) -> None:
  401. """Test reading gpg.ssh.program from config."""
  402. config = ConfigDict()
  403. config.set((b"gpg", b"ssh"), b"program", b"/usr/bin/ssh-keygen")
  404. vendor = SSHCliSignatureVendor(config=config)
  405. self.assertEqual(vendor.ssh_command, "/usr/bin/ssh-keygen")
  406. def test_ssh_program_override(self) -> None:
  407. """Test that ssh_command parameter overrides config."""
  408. config = ConfigDict()
  409. config.set((b"gpg", b"ssh"), b"program", b"/usr/bin/ssh-keygen")
  410. vendor = SSHCliSignatureVendor(config=config, ssh_command="ssh-keygen")
  411. self.assertEqual(vendor.ssh_command, "ssh-keygen")
  412. def test_ssh_program_default(self) -> None:
  413. """Test default ssh-keygen command when no config provided."""
  414. vendor = SSHCliSignatureVendor()
  415. self.assertEqual(vendor.ssh_command, "ssh-keygen")
  416. def test_allowed_signers_from_config(self) -> None:
  417. """Test reading gpg.ssh.allowedSignersFile from config."""
  418. config = ConfigDict()
  419. config.set((b"gpg", b"ssh"), b"allowedSignersFile", b"/tmp/allowed_signers")
  420. vendor = SSHCliSignatureVendor(config=config)
  421. self.assertEqual(vendor.allowed_signers_file, "/tmp/allowed_signers")
  422. def test_sign_without_key_raises(self) -> None:
  423. """Test that signing without a key raises ValueError."""
  424. vendor = SSHCliSignatureVendor()
  425. with self.assertRaises(ValueError) as cm:
  426. vendor.sign(b"test data")
  427. self.assertIn("key", str(cm.exception).lower())
  428. def test_verify_without_allowed_signers_raises(self) -> None:
  429. """Test that verify without allowedSignersFile raises ValueError."""
  430. vendor = SSHCliSignatureVendor()
  431. with self.assertRaises(ValueError) as cm:
  432. vendor.verify(b"test data", b"fake signature")
  433. self.assertIn("allowedSignersFile", str(cm.exception))
  434. def test_sign_and_verify_with_ssh_key(self) -> None:
  435. """Test sign and verify cycle with SSH key."""
  436. import os
  437. import tempfile
  438. # Generate a test SSH key
  439. with tempfile.TemporaryDirectory() as tmpdir:
  440. private_key = os.path.join(tmpdir, "test_key")
  441. public_key = private_key + ".pub"
  442. allowed_signers = os.path.join(tmpdir, "allowed_signers")
  443. # Generate Ed25519 key (no passphrase)
  444. subprocess.run(
  445. [
  446. "ssh-keygen",
  447. "-t",
  448. "ed25519",
  449. "-f",
  450. private_key,
  451. "-N",
  452. "",
  453. "-C",
  454. "test@example.com",
  455. ],
  456. capture_output=True,
  457. check=True,
  458. )
  459. # Create allowed_signers file
  460. with open(public_key) as pub:
  461. pub_key_content = pub.read().strip()
  462. with open(allowed_signers, "w") as allowed:
  463. allowed.write(f"git {pub_key_content}\n")
  464. # Create vendor with config
  465. config = ConfigDict()
  466. config.set(
  467. (b"gpg", b"ssh"), b"allowedSignersFile", allowed_signers.encode()
  468. )
  469. vendor = SSHCliSignatureVendor(config=config)
  470. # Test signing and verification
  471. test_data = b"test data to sign with SSH"
  472. signature = vendor.sign(test_data, keyid=private_key)
  473. self.assertIsInstance(signature, bytes)
  474. self.assertGreater(len(signature), 0)
  475. self.assertTrue(signature.startswith(b"-----BEGIN SSH SIGNATURE-----"))
  476. # Verify the signature
  477. vendor.verify(test_data, signature)
  478. class DetectSignatureFormatTests(unittest.TestCase):
  479. """Tests for detect_signature_format function."""
  480. def test_detect_ssh_signature(self) -> None:
  481. """Test detecting SSH signature format."""
  482. ssh_sig = b"-----BEGIN SSH SIGNATURE-----\nfoo\n-----END SSH SIGNATURE-----"
  483. self.assertEqual(detect_signature_format(ssh_sig), SIGNATURE_FORMAT_SSH)
  484. def test_detect_pgp_signature(self) -> None:
  485. """Test detecting PGP signature format."""
  486. pgp_sig = b"-----BEGIN PGP SIGNATURE-----\nfoo\n-----END PGP SIGNATURE-----"
  487. self.assertEqual(detect_signature_format(pgp_sig), SIGNATURE_FORMAT_OPENPGP)
  488. def test_detect_x509_signature_pkcs7(self) -> None:
  489. """Test detecting X.509 PKCS7 signature format."""
  490. x509_sig = b"-----BEGIN PKCS7-----\nfoo\n-----END PKCS7-----"
  491. self.assertEqual(detect_signature_format(x509_sig), SIGNATURE_FORMAT_X509)
  492. def test_detect_x509_signature_signed_message(self) -> None:
  493. """Test detecting X.509 signed message format."""
  494. x509_sig = b"-----BEGIN SIGNED MESSAGE-----\nfoo\n-----END SIGNED MESSAGE-----"
  495. self.assertEqual(detect_signature_format(x509_sig), SIGNATURE_FORMAT_X509)
  496. def test_unknown_signature_format(self) -> None:
  497. """Test that unknown format raises ValueError."""
  498. with self.assertRaises(ValueError) as cm:
  499. detect_signature_format(b"not a signature")
  500. self.assertIn("Unable to detect", str(cm.exception))
  501. class GetSignatureVendorForSignatureTests(unittest.TestCase):
  502. """Tests for get_signature_vendor_for_signature function."""
  503. def test_get_vendor_for_ssh_signature(self) -> None:
  504. """Test getting vendor for SSH signature."""
  505. ssh_sig = b"-----BEGIN SSH SIGNATURE-----\nfoo\n-----END SSH SIGNATURE-----"
  506. vendor = get_signature_vendor_for_signature(ssh_sig)
  507. self.assertIsInstance(vendor, (SSHSigSignatureVendor, SSHCliSignatureVendor))
  508. def test_get_vendor_for_pgp_signature(self) -> None:
  509. """Test getting vendor for PGP signature."""
  510. pgp_sig = b"-----BEGIN PGP SIGNATURE-----\nfoo\n-----END PGP SIGNATURE-----"
  511. vendor = get_signature_vendor_for_signature(pgp_sig)
  512. self.assertIsInstance(vendor, (GPGSignatureVendor, GPGCliSignatureVendor))
  513. def test_get_vendor_for_x509_signature(self) -> None:
  514. """Test getting vendor for X.509 signature."""
  515. x509_sig = b"-----BEGIN PKCS7-----\nfoo\n-----END PKCS7-----"
  516. vendor = get_signature_vendor_for_signature(x509_sig)
  517. self.assertIsInstance(vendor, X509SignatureVendor)
  518. def test_get_vendor_with_config(self) -> None:
  519. """Test that config is passed to vendor."""
  520. config = ConfigDict()
  521. config.set((b"gpg",), b"program", b"gpg2")
  522. pgp_sig = b"-----BEGIN PGP SIGNATURE-----\nfoo\n-----END PGP SIGNATURE-----"
  523. vendor = get_signature_vendor_for_signature(pgp_sig, config=config)
  524. # If CLI vendor is used, check config was passed
  525. if isinstance(vendor, GPGCliSignatureVendor):
  526. self.assertEqual(vendor.gpg_command, "gpg2")