test_signature.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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. SSHCliSignatureVendor,
  33. SSHSigSignatureVendor,
  34. X509SignatureVendor,
  35. detect_signature_format,
  36. get_signature_vendor,
  37. get_signature_vendor_for_signature,
  38. )
  39. try:
  40. import gpg
  41. except ImportError:
  42. gpg = None
  43. def get_valid_gpg_key() -> str | None:
  44. """Get a valid (non-revoked, non-expired, can-sign) GPG key from the keyring.
  45. Returns:
  46. A key fingerprint string that can be used for signing, or None if no valid key found.
  47. Raises:
  48. unittest.SkipTest: if gpg module is not available
  49. """
  50. if gpg is None:
  51. raise unittest.SkipTest("gpg module not available")
  52. with gpg.Context() as ctx:
  53. keys = list(ctx.keylist(secret=True))
  54. if not keys:
  55. return None
  56. # Find a non-revoked, non-expired key that can sign
  57. for key in keys:
  58. if not key.revoked and not key.expired and key.can_sign:
  59. return str(key.fpr)
  60. return None
  61. def get_valid_gpg_key_cli() -> str | None:
  62. """Get a valid (non-revoked, non-expired) GPG key fingerprint using CLI.
  63. Returns:
  64. A key fingerprint string, or None if no valid key found.
  65. """
  66. result = subprocess.run(
  67. ["gpg", "--list-secret-keys", "--with-colons"],
  68. capture_output=True,
  69. check=True,
  70. text=True,
  71. )
  72. # Find a valid key (field 2 should be '-' for valid, 'e' for expired, 'r' for revoked)
  73. current_key_valid = False
  74. for line in result.stdout.split("\n"):
  75. if line.startswith("sec:"):
  76. fields = line.split(":")
  77. # Only accept valid keys (field 2 is '-')
  78. current_key_valid = fields[1] == "-"
  79. elif line.startswith("fpr:") and current_key_valid:
  80. return line.split(":")[9]
  81. return None
  82. @unittest.skipIf(gpg is None, "gpg not available")
  83. class GPGSignatureVendorTests(unittest.TestCase):
  84. """Tests for GPGSignatureVendor."""
  85. def test_min_trust_level_from_config(self) -> None:
  86. """Test reading gpg.minTrustLevel from config."""
  87. config = ConfigDict()
  88. config.set((b"gpg",), b"minTrustLevel", b"marginal")
  89. vendor = GPGSignatureVendor.from_config(config=config)
  90. self.assertEqual(vendor.min_trust_level, "marginal")
  91. def test_min_trust_level_default(self) -> None:
  92. """Test default when gpg.minTrustLevel not in config."""
  93. vendor = GPGSignatureVendor()
  94. self.assertIsNone(vendor.min_trust_level)
  95. def test_available(self) -> None:
  96. """Test that available() returns boolean."""
  97. result = GPGSignatureVendor.available()
  98. self.assertIsInstance(result, bool)
  99. def test_sign_and_verify(self) -> None:
  100. """Test basic sign and verify cycle.
  101. Note: This test requires a GPG key to be configured in the test
  102. environment. It may be skipped in environments without GPG setup.
  103. """
  104. vendor = GPGSignatureVendor()
  105. test_data = b"test data to sign"
  106. key = get_valid_gpg_key()
  107. if not key:
  108. self.skipTest("No valid GPG keys available for testing")
  109. # Sign the data
  110. signature = vendor.sign(test_data)
  111. self.assertIsInstance(signature, bytes)
  112. self.assertGreater(len(signature), 0)
  113. # Verify the signature
  114. vendor.verify(test_data, signature)
  115. def test_verify_invalid_signature(self) -> None:
  116. """Test that verify raises an error for invalid signatures."""
  117. vendor = GPGSignatureVendor()
  118. test_data = b"test data"
  119. invalid_signature = b"this is not a valid signature"
  120. with self.assertRaises(gpg.errors.GPGMEError):
  121. vendor.verify(test_data, invalid_signature)
  122. def test_sign_with_keyid(self) -> None:
  123. """Test signing with a specific key ID.
  124. Note: This test requires a GPG key to be configured in the test
  125. environment. It may be skipped in environments without GPG setup.
  126. """
  127. vendor = GPGSignatureVendor()
  128. test_data = b"test data to sign"
  129. key = get_valid_gpg_key()
  130. if not key:
  131. self.skipTest("No valid GPG keys available for testing")
  132. signature = vendor.sign(test_data, keyid=key)
  133. self.assertIsInstance(signature, bytes)
  134. self.assertGreater(len(signature), 0)
  135. # Verify the signature
  136. vendor.verify(test_data, signature)
  137. class GPGCliSignatureVendorTests(unittest.TestCase):
  138. """Tests for GPGCliSignatureVendor."""
  139. def setUp(self) -> None:
  140. """Check if gpg command is available."""
  141. if shutil.which("gpg") is None:
  142. self.skipTest("gpg command not available")
  143. def test_sign_and_verify(self) -> None:
  144. """Test basic sign and verify cycle using CLI."""
  145. vendor = GPGCliSignatureVendor()
  146. test_data = b"test data to sign"
  147. try:
  148. # Sign the data
  149. signature = vendor.sign(test_data)
  150. self.assertIsInstance(signature, bytes)
  151. self.assertGreater(len(signature), 0)
  152. self.assertTrue(signature.startswith(b"-----BEGIN PGP SIGNATURE-----"))
  153. # Verify the signature
  154. vendor.verify(test_data, signature)
  155. except subprocess.CalledProcessError as e:
  156. # Skip test if no GPG key is available or configured
  157. self.skipTest(f"GPG signing failed: {e}")
  158. def test_verify_invalid_signature(self) -> None:
  159. """Test that verify raises an error for invalid signatures."""
  160. from dulwich.signature import BadSignature
  161. vendor = GPGCliSignatureVendor()
  162. test_data = b"test data"
  163. invalid_signature = b"this is not a valid signature"
  164. with self.assertRaises(BadSignature):
  165. vendor.verify(test_data, invalid_signature)
  166. def test_sign_with_keyid(self) -> None:
  167. """Test signing with a specific key ID using CLI."""
  168. vendor = GPGCliSignatureVendor()
  169. test_data = b"test data to sign"
  170. try:
  171. # Try to get a key from the keyring
  172. result = subprocess.run(
  173. ["gpg", "--list-secret-keys", "--with-colons"],
  174. capture_output=True,
  175. check=True,
  176. text=True,
  177. )
  178. # Parse output to find a key fingerprint
  179. keyid = None
  180. for line in result.stdout.split("\n"):
  181. if line.startswith("fpr:"):
  182. keyid = line.split(":")[9]
  183. break
  184. if not keyid:
  185. self.skipTest("No GPG keys available for testing")
  186. signature = vendor.sign(test_data, keyid=keyid)
  187. self.assertIsInstance(signature, bytes)
  188. self.assertGreater(len(signature), 0)
  189. # Verify the signature
  190. vendor.verify(test_data, signature)
  191. except subprocess.CalledProcessError as e:
  192. self.skipTest(f"GPG key not available: {e}")
  193. def test_verify_with_keyids(self) -> None:
  194. """Test verifying with specific trusted key IDs."""
  195. from dulwich.signature import UntrustedSignature
  196. signer = GPGCliSignatureVendor()
  197. test_data = b"test data to sign"
  198. try:
  199. valid_keyid = get_valid_gpg_key_cli()
  200. if not valid_keyid:
  201. self.skipTest("No valid GPG keys available for testing")
  202. # Sign with the specific key
  203. signature = signer.sign(test_data, keyid=valid_keyid)
  204. # Verify with the correct keyid - should succeed
  205. verifier_trusted = GPGCliSignatureVendor(keyids=[valid_keyid])
  206. verifier_trusted.verify(test_data, signature)
  207. # Verify with a different keyid - should fail
  208. fake_keyid = "0" * 40 # Fake 40-character fingerprint
  209. verifier_untrusted = GPGCliSignatureVendor(keyids=[fake_keyid])
  210. with self.assertRaises(UntrustedSignature):
  211. verifier_untrusted.verify(test_data, signature)
  212. except subprocess.CalledProcessError as e:
  213. self.skipTest(f"GPG key not available: {e}")
  214. def test_custom_gpg_command(self) -> None:
  215. """Test using a custom GPG command path."""
  216. vendor = GPGCliSignatureVendor(gpg_command="gpg")
  217. test_data = b"test data"
  218. try:
  219. signature = vendor.sign(test_data)
  220. self.assertIsInstance(signature, bytes)
  221. except subprocess.CalledProcessError as e:
  222. self.skipTest(f"GPG not available: {e}")
  223. def test_gpg_program_from_config(self) -> None:
  224. """Test reading gpg.program from config."""
  225. # Create a config with gpg.program set
  226. config = ConfigDict()
  227. config.set((b"gpg",), b"program", b"gpg2")
  228. vendor = GPGCliSignatureVendor.from_config(config=config)
  229. self.assertEqual(vendor.gpg_command, "gpg2")
  230. def test_gpg_program_explicit(self) -> None:
  231. """Test that gpg_command parameter works when passed directly."""
  232. vendor = GPGCliSignatureVendor(gpg_command="gpg2")
  233. self.assertEqual(vendor.gpg_command, "gpg2")
  234. def test_gpg_program_default(self) -> None:
  235. """Test default gpg command when no config provided."""
  236. vendor = GPGCliSignatureVendor()
  237. self.assertEqual(vendor.gpg_command, "gpg")
  238. def test_gpg_program_default_when_not_in_config(self) -> None:
  239. """Test default gpg command when config doesn't have gpg.program."""
  240. config = ConfigDict()
  241. vendor = GPGCliSignatureVendor.from_config(config=config)
  242. self.assertEqual(vendor.gpg_command, "gpg")
  243. def test_available(self) -> None:
  244. """Test that available() returns boolean."""
  245. result = GPGCliSignatureVendor.available()
  246. self.assertIsInstance(result, bool)
  247. class X509SignatureVendorTests(unittest.TestCase):
  248. """Tests for X509SignatureVendor."""
  249. def test_gpgsm_program_default(self) -> None:
  250. """Test default gpgsm command is 'gpgsm'."""
  251. vendor = X509SignatureVendor()
  252. self.assertEqual(vendor.gpgsm_command, "gpgsm")
  253. def test_gpgsm_program_from_config(self) -> None:
  254. """Test reading gpg.x509.program from config."""
  255. config = ConfigDict()
  256. config.set((b"gpg", b"x509"), b"program", b"/usr/local/bin/gpgsm")
  257. vendor = X509SignatureVendor.from_config(config=config)
  258. self.assertEqual(vendor.gpgsm_command, "/usr/local/bin/gpgsm")
  259. def test_gpgsm_program_explicit(self) -> None:
  260. """Test gpgsm_command parameter works when passed directly."""
  261. vendor = X509SignatureVendor(gpgsm_command="/custom/gpgsm")
  262. self.assertEqual(vendor.gpgsm_command, "/custom/gpgsm")
  263. def test_gpgsm_program_default_when_not_in_config(self) -> None:
  264. """Test default when gpg.x509.program not in config."""
  265. config = ConfigDict()
  266. vendor = X509SignatureVendor.from_config(config=config)
  267. self.assertEqual(vendor.gpgsm_command, "gpgsm")
  268. def test_available(self) -> None:
  269. """Test that available() returns boolean."""
  270. result = X509SignatureVendor.available()
  271. self.assertIsInstance(result, bool)
  272. @unittest.skipIf(
  273. shutil.which("gpgsm") is None, "gpgsm command not available in PATH"
  274. )
  275. def test_sign_and_verify(self) -> None:
  276. """Test basic X.509 sign and verify cycle.
  277. Note: This test requires gpgsm and an X.509 certificate to be configured.
  278. It may be skipped in environments without gpgsm/certificate setup.
  279. """
  280. vendor = X509SignatureVendor()
  281. test_data = b"test data to sign"
  282. try:
  283. # Try to sign the data
  284. signature = vendor.sign(test_data)
  285. self.assertIsInstance(signature, bytes)
  286. self.assertGreater(len(signature), 0)
  287. # Verify the signature
  288. vendor.verify(test_data, signature)
  289. except subprocess.CalledProcessError:
  290. # Skip test if no X.509 certificate is available
  291. self.skipTest("No X.509 certificate available for signing")
  292. class GetSignatureVendorTests(unittest.TestCase):
  293. """Tests for get_signature_vendor function."""
  294. def test_default_format(self) -> None:
  295. """Test that default format is openpgp."""
  296. vendor = get_signature_vendor()
  297. self.assertIsInstance(vendor, (GPGSignatureVendor, GPGCliSignatureVendor))
  298. def test_explicit_openpgp_format(self) -> None:
  299. """Test explicitly requesting openpgp format."""
  300. vendor = get_signature_vendor(format="openpgp")
  301. self.assertIsInstance(vendor, (GPGSignatureVendor, GPGCliSignatureVendor))
  302. def test_format_from_config(self) -> None:
  303. """Test reading format from config."""
  304. config = ConfigDict()
  305. config.set((b"gpg",), b"format", b"openpgp")
  306. vendor = get_signature_vendor(config=config)
  307. self.assertIsInstance(vendor, (GPGSignatureVendor, GPGCliSignatureVendor))
  308. def test_format_case_insensitive(self) -> None:
  309. """Test that format is case-insensitive."""
  310. vendor = get_signature_vendor(format="OpenPGP")
  311. self.assertIsInstance(vendor, (GPGSignatureVendor, GPGCliSignatureVendor))
  312. def test_x509_format_supported(self) -> None:
  313. """Test that x509 format is now supported."""
  314. vendor = get_signature_vendor(format="x509")
  315. self.assertIsInstance(vendor, X509SignatureVendor)
  316. def test_ssh_format_supported(self) -> None:
  317. """Test that ssh format is now supported."""
  318. vendor = get_signature_vendor(format="ssh")
  319. # Should be either SSHSigSignatureVendor or SSHCliSignatureVendor
  320. self.assertIsInstance(vendor, (SSHSigSignatureVendor, SSHCliSignatureVendor))
  321. def test_invalid_format(self) -> None:
  322. """Test that invalid format raises ValueError."""
  323. with self.assertRaises(ValueError) as cm:
  324. get_signature_vendor(format="invalid")
  325. self.assertIn("Unsupported", str(cm.exception))
  326. def test_config_passed_to_vendor(self) -> None:
  327. """Test that config is passed to the vendor."""
  328. config = ConfigDict()
  329. config.set((b"gpg",), b"program", b"gpg2")
  330. vendor = get_signature_vendor(format="openpgp", config=config)
  331. # If CLI vendor is used, check that config was passed
  332. if isinstance(vendor, GPGCliSignatureVendor):
  333. self.assertEqual(vendor.gpg_command, "gpg2")
  334. def test_ssh_format(self) -> None:
  335. """Test requesting SSH format."""
  336. vendor = get_signature_vendor(format="ssh")
  337. # Should be either SSHSigSignatureVendor or SSHCliSignatureVendor
  338. self.assertIsInstance(vendor, (SSHSigSignatureVendor, SSHCliSignatureVendor))
  339. def test_x509_format(self) -> None:
  340. """Test requesting X.509 format."""
  341. vendor = get_signature_vendor(format="x509")
  342. self.assertIsInstance(vendor, X509SignatureVendor)
  343. class SSHSigSignatureVendorTests(unittest.TestCase):
  344. """Tests for SSHSigSignatureVendor (sshsig package implementation)."""
  345. def setUp(self) -> None:
  346. """Check if sshsig package is available."""
  347. if not SSHSigSignatureVendor.available():
  348. self.skipTest("sshsig package not available")
  349. def test_verify_without_config_raises(self) -> None:
  350. """Test that verify without config or keyids raises UntrustedSignature."""
  351. from dulwich.signature import UntrustedSignature
  352. vendor = SSHSigSignatureVendor()
  353. with self.assertRaises(UntrustedSignature) as cm:
  354. vendor.verify(b"test data", b"fake signature")
  355. self.assertIn("allowedSignersFile", str(cm.exception))
  356. def test_config_parsing(self) -> None:
  357. """Test parsing SSH config options."""
  358. config = ConfigDict()
  359. config.set((b"gpg", b"ssh"), b"allowedSignersFile", b"/path/to/allowed")
  360. config.set((b"gpg", b"ssh"), b"defaultKeyCommand", b"ssh-add -L")
  361. vendor = SSHSigSignatureVendor.from_config(config=config)
  362. self.assertEqual(vendor.allowed_signers_file, "/path/to/allowed")
  363. self.assertEqual(vendor.default_key_command, "ssh-add -L")
  364. def test_available(self) -> None:
  365. """Test that available() returns boolean."""
  366. result = SSHSigSignatureVendor.available()
  367. self.assertIsInstance(result, bool)
  368. def test_verify_with_cli_generated_signature(self) -> None:
  369. """Test verifying a signature created by SSH CLI vendor."""
  370. import os
  371. import tempfile
  372. if shutil.which("ssh-keygen") is None:
  373. self.skipTest("ssh-keygen not available")
  374. # Generate a test SSH key and signature using CLI vendor
  375. with tempfile.TemporaryDirectory() as tmpdir:
  376. private_key = os.path.join(tmpdir, "test_key")
  377. public_key = private_key + ".pub"
  378. allowed_signers = os.path.join(tmpdir, "allowed_signers")
  379. # Generate Ed25519 key
  380. subprocess.run(
  381. [
  382. "ssh-keygen",
  383. "-t",
  384. "ed25519",
  385. "-f",
  386. private_key,
  387. "-N",
  388. "",
  389. "-C",
  390. "test@example.com",
  391. ],
  392. capture_output=True,
  393. check=True,
  394. )
  395. # Create allowed_signers file
  396. with open(public_key) as pub:
  397. pub_key_content = pub.read().strip()
  398. with open(allowed_signers, "w") as allowed:
  399. allowed.write(f"* {pub_key_content}\n")
  400. # Sign with CLI vendor
  401. cli_config = ConfigDict()
  402. cli_config.set(
  403. (b"gpg", b"ssh"), b"allowedSignersFile", allowed_signers.encode()
  404. )
  405. cli_vendor = SSHCliSignatureVendor.from_config(config=cli_config)
  406. test_data = b"test data for sshsig verification"
  407. signature = cli_vendor.sign(test_data, keyid=private_key)
  408. # Verify with sshsig package vendor
  409. pkg_config = ConfigDict()
  410. pkg_config.set(
  411. (b"gpg", b"ssh"), b"allowedSignersFile", allowed_signers.encode()
  412. )
  413. pkg_vendor = SSHSigSignatureVendor.from_config(config=pkg_config)
  414. # This should succeed
  415. pkg_vendor.verify(test_data, signature)
  416. def test_key_lifetime_validation(self) -> None:
  417. """Test SSH key lifetime validation (valid-after/valid-before).
  418. Note: The current version of the sshsig library does not parse options
  419. from allowed_signers files, so this test verifies the code is in place
  420. but will be skipped until the library adds support.
  421. """
  422. import io
  423. # Check if sshsig library supports parsing options
  424. import sshsig.allowed_signers
  425. test_content = 'valid-after="20260104" test@example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl'
  426. f = io.StringIO(test_content)
  427. signers = list(sshsig.allowed_signers.load_allowed_signers_file(f))
  428. if not signers or signers[0].options is None:
  429. self.skipTest(
  430. "sshsig library does not yet support parsing options from allowed_signers files"
  431. )
  432. # If we get here, the library supports options, so we can test
  433. import os
  434. import tempfile
  435. import time
  436. from dulwich.signature import UntrustedSignature
  437. if shutil.which("ssh-keygen") is None:
  438. self.skipTest("ssh-keygen not available")
  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
  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. # Read public key
  460. with open(public_key) as pub:
  461. pub_key_content = pub.read().strip()
  462. # Test 1: Key with valid-after in the future (should fail)
  463. future_time = int(time.time()) + 86400 # 1 day from now
  464. future_timestamp = time.strftime("%Y%m%d", time.gmtime(future_time))
  465. with open(allowed_signers, "w") as allowed:
  466. allowed.write(
  467. f'valid-after="{future_timestamp}" test@example.com {pub_key_content}\n'
  468. )
  469. cli_config = ConfigDict()
  470. cli_config.set(
  471. (b"gpg", b"ssh"), b"allowedSignersFile", allowed_signers.encode()
  472. )
  473. cli_vendor = SSHCliSignatureVendor.from_config(config=cli_config)
  474. test_data = b"test data for lifetime validation"
  475. signature = cli_vendor.sign(test_data, keyid=private_key)
  476. pkg_config = ConfigDict()
  477. pkg_config.set(
  478. (b"gpg", b"ssh"), b"allowedSignersFile", allowed_signers.encode()
  479. )
  480. pkg_vendor = SSHSigSignatureVendor.from_config(config=pkg_config)
  481. # Verification should fail because key is not yet valid
  482. with self.assertRaises(UntrustedSignature) as cm:
  483. pkg_vendor.verify(test_data, signature)
  484. self.assertIn("not yet valid", str(cm.exception))
  485. def test_revocation_checking(self) -> None:
  486. """Test SSH key revocation checking."""
  487. import os
  488. import tempfile
  489. from dulwich.signature import UntrustedSignature
  490. if shutil.which("ssh-keygen") is None:
  491. self.skipTest("ssh-keygen not available")
  492. with tempfile.TemporaryDirectory() as tmpdir:
  493. private_key = os.path.join(tmpdir, "test_key")
  494. public_key = private_key + ".pub"
  495. allowed_signers = os.path.join(tmpdir, "allowed_signers")
  496. revocation_file = os.path.join(tmpdir, "revoked_keys")
  497. # Generate Ed25519 key
  498. subprocess.run(
  499. [
  500. "ssh-keygen",
  501. "-t",
  502. "ed25519",
  503. "-f",
  504. private_key,
  505. "-N",
  506. "",
  507. "-C",
  508. "test@example.com",
  509. ],
  510. capture_output=True,
  511. check=True,
  512. )
  513. # Read public key
  514. with open(public_key) as pub:
  515. pub_key_content = pub.read().strip()
  516. # Create allowed_signers file
  517. with open(allowed_signers, "w") as allowed:
  518. allowed.write(f"* {pub_key_content}\n")
  519. # Sign some data
  520. cli_config = ConfigDict()
  521. cli_config.set(
  522. (b"gpg", b"ssh"), b"allowedSignersFile", allowed_signers.encode()
  523. )
  524. cli_vendor = SSHCliSignatureVendor.from_config(config=cli_config)
  525. test_data = b"test data for revocation checking"
  526. signature = cli_vendor.sign(test_data, keyid=private_key)
  527. # Test 1: Without revocation file (should succeed)
  528. pkg_config = ConfigDict()
  529. pkg_config.set(
  530. (b"gpg", b"ssh"), b"allowedSignersFile", allowed_signers.encode()
  531. )
  532. pkg_vendor = SSHSigSignatureVendor.from_config(config=pkg_config)
  533. pkg_vendor.verify(test_data, signature)
  534. # Test 2: With revocation file containing this key (should fail)
  535. with open(revocation_file, "w") as revoked:
  536. revoked.write(f"{pub_key_content}\n")
  537. pkg_config.set(
  538. (b"gpg", b"ssh"), b"revocationFile", revocation_file.encode()
  539. )
  540. pkg_vendor = SSHSigSignatureVendor.from_config(config=pkg_config)
  541. with self.assertRaises(UntrustedSignature) as cm:
  542. pkg_vendor.verify(test_data, signature)
  543. self.assertIn("revoked", str(cm.exception))
  544. class SSHCliSignatureVendorTests(unittest.TestCase):
  545. """Tests for SSHCliSignatureVendor."""
  546. def setUp(self) -> None:
  547. """Check if ssh-keygen is available."""
  548. if shutil.which("ssh-keygen") is None:
  549. self.skipTest("ssh-keygen command not available")
  550. def test_ssh_program_from_config(self) -> None:
  551. """Test reading gpg.ssh.program from config."""
  552. config = ConfigDict()
  553. config.set((b"gpg", b"ssh"), b"program", b"/usr/bin/ssh-keygen")
  554. vendor = SSHCliSignatureVendor.from_config(config=config)
  555. self.assertEqual(vendor.ssh_command, "/usr/bin/ssh-keygen")
  556. def test_ssh_program_explicit(self) -> None:
  557. """Test that ssh_command parameter works when passed directly."""
  558. vendor = SSHCliSignatureVendor(ssh_command="/usr/bin/ssh-keygen")
  559. self.assertEqual(vendor.ssh_command, "/usr/bin/ssh-keygen")
  560. def test_ssh_program_default(self) -> None:
  561. """Test default ssh-keygen command when no config provided."""
  562. vendor = SSHCliSignatureVendor()
  563. self.assertEqual(vendor.ssh_command, "ssh-keygen")
  564. def test_allowed_signers_from_config(self) -> None:
  565. """Test reading gpg.ssh.allowedSignersFile from config."""
  566. config = ConfigDict()
  567. config.set((b"gpg", b"ssh"), b"allowedSignersFile", b"/tmp/allowed_signers")
  568. vendor = SSHCliSignatureVendor.from_config(config=config)
  569. self.assertEqual(vendor.allowed_signers_file, "/tmp/allowed_signers")
  570. def test_sign_without_key_raises(self) -> None:
  571. """Test that signing without a key raises ValueError."""
  572. vendor = SSHCliSignatureVendor()
  573. with self.assertRaises(ValueError) as cm:
  574. vendor.sign(b"test data")
  575. self.assertIn("key", str(cm.exception).lower())
  576. def test_verify_without_allowed_signers_raises(self) -> None:
  577. """Test that verify without allowedSignersFile raises UntrustedSignature."""
  578. from dulwich.signature import UntrustedSignature
  579. vendor = SSHCliSignatureVendor()
  580. with self.assertRaises(UntrustedSignature) as cm:
  581. vendor.verify(b"test data", b"fake signature")
  582. self.assertIn("allowedSignersFile", str(cm.exception))
  583. def test_sign_and_verify_with_ssh_key(self) -> None:
  584. """Test sign and verify cycle with SSH key."""
  585. import os
  586. import tempfile
  587. # Generate a test SSH key
  588. with tempfile.TemporaryDirectory() as tmpdir:
  589. private_key = os.path.join(tmpdir, "test_key")
  590. public_key = private_key + ".pub"
  591. allowed_signers = os.path.join(tmpdir, "allowed_signers")
  592. # Generate Ed25519 key (no passphrase)
  593. subprocess.run(
  594. [
  595. "ssh-keygen",
  596. "-t",
  597. "ed25519",
  598. "-f",
  599. private_key,
  600. "-N",
  601. "",
  602. "-C",
  603. "test@example.com",
  604. ],
  605. capture_output=True,
  606. check=True,
  607. )
  608. # Create allowed_signers file
  609. with open(public_key) as pub:
  610. pub_key_content = pub.read().strip()
  611. with open(allowed_signers, "w") as allowed:
  612. allowed.write(f"git {pub_key_content}\n")
  613. # Create vendor with config
  614. config = ConfigDict()
  615. config.set(
  616. (b"gpg", b"ssh"), b"allowedSignersFile", allowed_signers.encode()
  617. )
  618. vendor = SSHCliSignatureVendor.from_config(config=config)
  619. # Test signing and verification
  620. test_data = b"test data to sign with SSH"
  621. signature = vendor.sign(test_data, keyid=private_key)
  622. self.assertIsInstance(signature, bytes)
  623. self.assertGreater(len(signature), 0)
  624. self.assertTrue(signature.startswith(b"-----BEGIN SSH SIGNATURE-----"))
  625. # Verify the signature
  626. vendor.verify(test_data, signature)
  627. def test_default_key_command(self) -> None:
  628. """Test gpg.ssh.defaultKeyCommand support."""
  629. import os
  630. import tempfile
  631. # Generate a test SSH key
  632. with tempfile.TemporaryDirectory() as tmpdir:
  633. private_key = os.path.join(tmpdir, "test_key")
  634. # Generate Ed25519 key (no passphrase)
  635. subprocess.run(
  636. [
  637. "ssh-keygen",
  638. "-t",
  639. "ed25519",
  640. "-f",
  641. private_key,
  642. "-N",
  643. "",
  644. "-C",
  645. "test@example.com",
  646. ],
  647. capture_output=True,
  648. check=True,
  649. )
  650. # Create config with defaultKeyCommand that echoes the key path
  651. config = ConfigDict()
  652. config.set(
  653. (b"gpg", b"ssh"), b"defaultKeyCommand", f"echo {private_key}".encode()
  654. )
  655. vendor = SSHCliSignatureVendor.from_config(config=config)
  656. test_data = b"test data"
  657. # Sign without providing keyid - should use defaultKeyCommand
  658. signature = vendor.sign(test_data)
  659. self.assertIsInstance(signature, bytes)
  660. self.assertGreater(len(signature), 0)
  661. def test_revocation_file_config(self) -> None:
  662. """Test that revocation file is read from config."""
  663. config = ConfigDict()
  664. config.set((b"gpg", b"ssh"), b"revocationFile", b"/path/to/revoked_keys")
  665. vendor = SSHCliSignatureVendor.from_config(config=config)
  666. self.assertEqual(vendor.revocation_file, "/path/to/revoked_keys")
  667. def test_available(self) -> None:
  668. """Test that available() returns boolean."""
  669. result = SSHCliSignatureVendor.available()
  670. self.assertIsInstance(result, bool)
  671. class DetectSignatureFormatTests(unittest.TestCase):
  672. """Tests for detect_signature_format function."""
  673. def test_detect_ssh_signature(self) -> None:
  674. """Test detecting SSH signature format."""
  675. ssh_sig = b"-----BEGIN SSH SIGNATURE-----\nfoo\n-----END SSH SIGNATURE-----"
  676. self.assertEqual(detect_signature_format(ssh_sig), SIGNATURE_FORMAT_SSH)
  677. def test_detect_pgp_signature(self) -> None:
  678. """Test detecting PGP signature format."""
  679. pgp_sig = b"-----BEGIN PGP SIGNATURE-----\nfoo\n-----END PGP SIGNATURE-----"
  680. self.assertEqual(detect_signature_format(pgp_sig), SIGNATURE_FORMAT_OPENPGP)
  681. def test_detect_x509_signature_pkcs7(self) -> None:
  682. """Test detecting X.509 PKCS7 signature format."""
  683. x509_sig = b"-----BEGIN PKCS7-----\nfoo\n-----END PKCS7-----"
  684. self.assertEqual(detect_signature_format(x509_sig), SIGNATURE_FORMAT_X509)
  685. def test_detect_x509_signature_signed_message(self) -> None:
  686. """Test detecting X.509 signed message format."""
  687. x509_sig = b"-----BEGIN SIGNED MESSAGE-----\nfoo\n-----END SIGNED MESSAGE-----"
  688. self.assertEqual(detect_signature_format(x509_sig), SIGNATURE_FORMAT_X509)
  689. def test_unknown_signature_format(self) -> None:
  690. """Test that unknown format raises ValueError."""
  691. with self.assertRaises(ValueError) as cm:
  692. detect_signature_format(b"not a signature")
  693. self.assertIn("Unable to detect", str(cm.exception))
  694. class GetSignatureVendorForSignatureTests(unittest.TestCase):
  695. """Tests for get_signature_vendor_for_signature function."""
  696. def test_get_vendor_for_ssh_signature(self) -> None:
  697. """Test getting vendor for SSH signature."""
  698. ssh_sig = b"-----BEGIN SSH SIGNATURE-----\nfoo\n-----END SSH SIGNATURE-----"
  699. vendor = get_signature_vendor_for_signature(ssh_sig)
  700. self.assertIsInstance(vendor, (SSHSigSignatureVendor, SSHCliSignatureVendor))
  701. def test_get_vendor_for_pgp_signature(self) -> None:
  702. """Test getting vendor for PGP signature."""
  703. pgp_sig = b"-----BEGIN PGP SIGNATURE-----\nfoo\n-----END PGP SIGNATURE-----"
  704. vendor = get_signature_vendor_for_signature(pgp_sig)
  705. self.assertIsInstance(vendor, (GPGSignatureVendor, GPGCliSignatureVendor))
  706. def test_get_vendor_for_x509_signature(self) -> None:
  707. """Test getting vendor for X.509 signature."""
  708. x509_sig = b"-----BEGIN PKCS7-----\nfoo\n-----END PKCS7-----"
  709. vendor = get_signature_vendor_for_signature(x509_sig)
  710. self.assertIsInstance(vendor, X509SignatureVendor)
  711. def test_get_vendor_with_config(self) -> None:
  712. """Test that config is passed to vendor."""
  713. config = ConfigDict()
  714. config.set((b"gpg",), b"program", b"gpg2")
  715. pgp_sig = b"-----BEGIN PGP SIGNATURE-----\nfoo\n-----END PGP SIGNATURE-----"
  716. vendor = get_signature_vendor_for_signature(pgp_sig, config=config)
  717. # If CLI vendor is used, check config was passed
  718. if isinstance(vendor, GPGCliSignatureVendor):
  719. self.assertEqual(vendor.gpg_command, "gpg2")