1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
|
# test/test_crypto.py
# Part of ‘dput’, a Debian package upload toolkit.
#
# This is free software, and you are welcome to redistribute it under
# certain conditions; see the end of this file for copyright
# information, grant of license, and disclaimer of warranty.
""" Unit tests for ‘crypto’ module. """
import doctest
import functools
import operator
import sys
import textwrap
import unittest.mock
import gpg
import gpg.results
import testscenarios
import testtools
import dput.crypto
from .helper import (
patch_system_interfaces,
set_fake_file_scenario,
setup_fake_file_fixtures,
)
def make_gpg_signature_scenarios():
""" Make a collection of scenarios for `gpg.result.Signature` instances.
:return: A sequence of tuples (name, scenario) of scenarios
for use with `testscenarios` test cases.
Each scenario is a mapping of attributes to be applied to the
test case.
"""
scenarios = [
('signature-good validity-unknown', {
'verify_result': unittest.mock.MagicMock(
gpg.results.VerifyResult,
file_name=None,
signatures=[
unittest.mock.MagicMock(
gpg.results.Signature,
fpr="BADBEEF2FACEDCADF00DBEEFDECAFBAD",
status=gpg.errors.NO_ERROR,
summary=functools.reduce(
operator.ior, [gpg.constants.SIGSUM_GREEN]),
validity=gpg.constants.VALIDITY_UNKNOWN,
),
],
),
'expected_character': "good",
'expected_description': (
"Good signature from F00DBEEFDECAFBAD"),
}),
('signature-good validity-never', {
'verify_result': unittest.mock.MagicMock(
gpg.results.VerifyResult,
file_name=None,
signatures=[
unittest.mock.MagicMock(
gpg.results.Signature,
fpr="BADBEEF2FACEDCADF00DBEEFDECAFBAD",
status=gpg.errors.NO_ERROR,
summary=functools.reduce(
operator.ior, [gpg.constants.SIGSUM_GREEN]),
validity=gpg.constants.VALIDITY_NEVER,
),
],
),
'expected_character': "good",
'expected_description': (
"Good signature from F00DBEEFDECAFBAD"),
}),
('signature-good validity-full key-expired', {
'verify_result': unittest.mock.MagicMock(
gpg.results.VerifyResult,
file_name=None,
signatures=[
unittest.mock.MagicMock(
gpg.results.Signature,
fpr="BADBEEF2FACEDCADF00DBEEFDECAFBAD",
status=gpg.errors.NO_ERROR,
summary=functools.reduce(operator.ior, [
gpg.constants.SIGSUM_GREEN,
gpg.constants.SIGSUM_KEY_EXPIRED,
]),
validity=gpg.constants.VALIDITY_FULL,
),
],
),
'expected_character': "good",
'expected_description': (
"Good signature from F00DBEEFDECAFBAD"),
}),
('signature-good validity-full', {
'verify_result': unittest.mock.MagicMock(
gpg.results.VerifyResult,
file_name=None,
signatures=[
unittest.mock.MagicMock(
gpg.results.Signature,
fpr="BADBEEF2FACEDCADF00DBEEFDECAFBAD",
status=gpg.errors.NO_ERROR,
summary=functools.reduce(operator.ior, [
gpg.constants.SIGSUM_VALID,
gpg.constants.SIGSUM_GREEN,
]),
validity=gpg.constants.VALIDITY_FULL,
),
],
),
'expected_character': "valid",
'expected_description': (
"Valid signature from F00DBEEFDECAFBAD"),
}),
('signature-bad', {
'verify_result': unittest.mock.MagicMock(
gpg.results.VerifyResult,
file_name=None,
signatures=[
unittest.mock.MagicMock(
gpg.results.Signature,
fpr="BADBEEF2FACEDCADF00DBEEFDECAFBAD",
status=gpg.errors.BAD_SIGNATURE,
summary=functools.reduce(
operator.ior, [gpg.constants.SIGSUM_RED]),
validity=gpg.constants.VALIDITY_FULL,
),
],
),
'expected_character': "bad",
'expected_description': (
"Bad signature from F00DBEEFDECAFBAD"),
}),
('signature-key-missing', {
'verify_result': unittest.mock.MagicMock(
gpg.results.VerifyResult,
file_name=None,
signatures=[
unittest.mock.MagicMock(
gpg.results.Signature,
fpr="BADBEEF2FACEDCADF00DBEEFDECAFBAD",
status=gpg.errors.NO_PUBKEY,
summary=functools.reduce(
operator.ior,
[gpg.constants.SIGSUM_KEY_MISSING]),
validity=gpg.constants.VALIDITY_UNKNOWN,
),
],
),
'expected_character': dput.crypto.SignatureVerifyError,
'expected_description': (
"Error checking signature from F00DBEEFDECAFBAD:"
" SignatureVerifyError: {:d}".format(
gpg.constants.SIGSUM_KEY_MISSING)
),
}),
]
return scenarios
class characterise_signature_TestCase(
testscenarios.WithScenarios,
testtools.TestCase):
""" Test cases for function `characterise_signature`. """
scenarios = make_gpg_signature_scenarios()
def test_gives_expected_character(self):
""" Should give the expected character for signature. """
test_args = {
'signature': self.verify_result.signatures[0],
}
if (
isinstance(self.expected_character, type)
and issubclass(self.expected_character, Exception)
):
self.assertRaises(
self.expected_character,
dput.crypto.characterise_signature,
**test_args)
else:
result = dput.crypto.characterise_signature(**test_args)
self.assertEqual(result, self.expected_character)
class describe_signature_TestCase(
testscenarios.WithScenarios,
testtools.TestCase):
""" Test cases for function `describe_signature`. """
scenarios = make_gpg_signature_scenarios()
def test_gives_expected_description(self):
""" Should return expected description for signature. """
test_args = {
'signature': self.verify_result.signatures[0],
}
result = dput.crypto.describe_signature(**test_args)
self.assertEqual(result, self.expected_description)
def make_gpg_verify_scenarios():
""" Make a collection of scenarios for ‘Context.verify’ method.
:return: A collection of scenarios for tests.
The collection is a mapping from scenario name to a dictionary of
scenario attributes.
"""
signatures_by_name = {
name: scenario['verify_result']
for (name, scenario) in make_gpg_signature_scenarios()}
scenarios_by_name = {
'goodsig': {
'result': [
None,
signatures_by_name['signature-good validity-unknown'],
],
},
'validsig': {
'result': [
None,
signatures_by_name['signature-good validity-full'],
],
},
'badsig': {
'exception': gpg.errors.GPGMEError(
gpg._gpgme.gpgme_err_make(
gpg.errors.SOURCE_GPGME, gpg.errors.BAD_SIGNATURE),
"Bad signature"),
},
'errsig': {
'exception': gpg.errors.GPGMEError(
gpg._gpgme.gpgme_err_make(
gpg.errors.SOURCE_GPGME, gpg.errors.SIG_EXPIRED),
"Signature expired"),
},
'nodata': {
'exception': gpg.errors.GPGMEError(
gpg._gpgme.gpgme_err_make(
gpg.errors.SOURCE_GPGME, gpg.errors.NO_DATA),
"No data"),
},
'bogus': {
'exception': ValueError,
},
}
scenarios = {
'default': scenarios_by_name['goodsig'],
}
scenarios.update(
(name, scenario)
for (name, scenario) in scenarios_by_name.items())
return scenarios
def setup_gpg_verify_fixtures(testcase):
""" Set up fixtures for GPG interaction behaviour. """
scenarios = make_gpg_verify_scenarios()
testcase.gpg_verify_scenarios = scenarios
class check_file_signature_TestCase(testtools.TestCase):
""" Test cases for `check_file_signature` function. """
def setUp(self):
""" Set up test fixtures. """
super().setUp()
patch_system_interfaces(self)
setup_fake_file_fixtures(self)
set_fake_file_scenario(self, 'exist-minimal')
self.set_test_args()
self.patch_gpg_context()
setup_gpg_verify_fixtures(self)
self.set_gpg_verify_scenario('default')
def set_test_args(self):
""" Set the arguments for the test call to the function. """
self.test_args = dict(
infile=self.file_double.fake_file,
)
def patch_gpg_context(self):
""" Patch the ‘gpg.Context’ class for this test case. """
class_patcher = unittest.mock.patch.object(gpg, 'Context')
class_patcher.start()
self.addCleanup(class_patcher.stop)
def set_gpg_verify_scenario(self, name):
""" Set the status scenario for the ‘Context.verify’ call. """
scenario = self.gpg_verify_scenarios[name]
mock_class = gpg.Context
self.mock_gpg_context = mock_class.return_value
mock_func = self.mock_gpg_context.verify
if 'exception' in scenario:
mock_func.side_effect = scenario['exception']
else:
mock_func.return_value = scenario['result']
def assert_stderr_contains_gpg_error(self, code):
""" Assert the `stderr` content contains the GPG message. """
expected_output = textwrap.dedent("""\
gpg: {path}: error {code}: ...
""").format(
path=self.file_double.path, code=code)
self.assertThat(
sys.stderr.getvalue(),
testtools.matchers.DocTestMatches(
expected_output, doctest.ELLIPSIS))
def test_calls_gpg_verify_with_expected_args(self):
""" Should call `gpg.Context.verify` with expected args. """
dput.crypto.check_file_signature(**self.test_args)
gpg.Context.return_value.verify.assert_called_with(
self.file_double.fake_file)
def test_calls_sys_exit_if_gnupg_reports_bad_signature(self):
""" Should call `sys.exit` if GnuPG reports bad signature. """
self.set_gpg_verify_scenario('badsig')
with testtools.ExpectedException(gpg.errors.GPGMEError):
dput.crypto.check_file_signature(**self.test_args)
self.assert_stderr_contains_gpg_error(gpg.errors.BAD_SIGNATURE)
def test_calls_sys_exit_if_gnupg_reports_sig_expired(self):
""" Should call `sys.exit` if GnuPG reports signature expired. """
self.set_gpg_verify_scenario('errsig')
with testtools.ExpectedException(gpg.errors.GPGMEError):
dput.crypto.check_file_signature(**self.test_args)
self.assert_stderr_contains_gpg_error(gpg.errors.SIG_EXPIRED)
def test_calls_sys_exit_if_gnupg_reports_nodata(self):
""" Should call `sys.exit` if GnuPG reports no data. """
self.set_gpg_verify_scenario('nodata')
with testtools.ExpectedException(gpg.errors.GPGMEError):
dput.crypto.check_file_signature(**self.test_args)
self.assert_stderr_contains_gpg_error(gpg.errors.NO_DATA)
def test_outputs_message_if_gnupg_reports_goodsig(self):
""" Should output a message if GnuPG reports a good signature. """
self.set_gpg_verify_scenario('goodsig')
dput.crypto.check_file_signature(**self.test_args)
expected_output = textwrap.dedent("""\
gpg: {path}: Good signature from ...
""").format(path=self.file_double.path)
self.assertThat(
sys.stderr.getvalue(),
testtools.matchers.DocTestMatches(
expected_output, doctest.ELLIPSIS))
def test_outputs_message_if_gnupg_reports_validsig(self):
""" Should output a message if GnuPG reports a valid signature. """
self.set_gpg_verify_scenario('validsig')
dput.crypto.check_file_signature(**self.test_args)
expected_output = textwrap.dedent("""\
gpg: {path}: Valid signature from ...
""").format(path=self.file_double.path)
self.assertThat(
sys.stderr.getvalue(),
testtools.matchers.DocTestMatches(
expected_output, doctest.ELLIPSIS))
# Copyright © 2015–2024 Ben Finney <bignose@debian.org>
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 3 of that license or any later version.
# No warranty expressed or implied. See the file ‘LICENSE.GPL-3’ for details.
# Local variables:
# coding: utf-8
# mode: python
# End:
# vim: fileencoding=utf-8 filetype=python :
|