summaryrefslogtreecommitdiff
path: root/tests/commands/utils_tests.py
blob: 63863db828b8ea853dcc5e8532a8ce7545f83e91 (plain)
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
# encoding=utf-8
# Copyright © 2017-2018 Dylan Baker
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import tempfile
import os
import shutil
import unittest
from unittest import mock

import gpg

from alot import crypto
from alot import errors
from alot.commands import utils
from alot.db.envelope import Envelope

from .. import utilities

MOD_CLEAN = utilities.ModuleCleanup()

# A useful single fingerprint for tests that only care about one key. This
# key will not be ambiguous
FPR = "F74091D4133F87D56B5D343C1974EC55FBC2D660"

# Some additional keys, these keys may be ambigiuos
EXTRA_FPRS = [
    "DD19862809A7573A74058FF255937AFBB156245D",
    "2071E9C8DB4EF5466F4D233CF730DF92C4566CE7",
]

DEVNULL = open('/dev/null', 'w')
MOD_CLEAN.add_cleanup(DEVNULL.close)


@MOD_CLEAN.wrap_setup
def setUpModule():
    home = tempfile.mkdtemp()
    MOD_CLEAN.add_cleanup(shutil.rmtree, home)
    mock_home = mock.patch.dict(os.environ, {'GNUPGHOME': home})
    mock_home.start()
    MOD_CLEAN.add_cleanup(mock_home.stop)

    with gpg.core.Context(armor=True) as ctx:
        # Add the public and private keys. They have no password
        search_dir = os.path.join(
            os.path.dirname(__file__), '../static/gpg-keys')
        for each in os.listdir(search_dir):
            if os.path.splitext(each)[1] == '.gpg':
                with open(os.path.join(search_dir, each)) as f:
                    ctx.op_import(f)


@MOD_CLEAN.wrap_teardown
def tearDownModule():
    pass


class TestGetKeys(unittest.TestCase):

    # pylint: disable=protected-access

    @utilities.async_test
    async def test_get_keys(self):
        """Test that getting keys works when all keys are present."""
        expected = crypto.get_key(FPR, validate=True, encrypt=True,
                                  signed_only=False)
        ui = utilities.make_ui()
        ids = [FPR]
        actual = await utils._get_keys(ui, ids)
        self.assertIn(FPR, actual)
        self.assertEqual(actual[FPR].fpr, expected.fpr)

    @utilities.async_test
    async def test_get_keys_missing(self):
        """Test that getting keys works when some keys are missing."""
        expected = crypto.get_key(FPR, validate=True, encrypt=True,
                                  signed_only=False)
        ui = utilities.make_ui()
        ids = [FPR, "6F6B15509CF8E59E6E469F327F438280EF8D349F"]
        actual = await utils._get_keys(ui, ids)
        self.assertIn(FPR, actual)
        self.assertEqual(actual[FPR].fpr, expected.fpr)

    @utilities.async_test
    async def test_get_keys_signed_only(self):
        """Test gettings keys when signed only is required."""
        ui = utilities.make_ui()
        ids = [FPR]
        actual = await utils._get_keys(ui, ids, signed_only=True)
        self.assertEqual(actual, {})

    @utilities.async_test
    async def test_get_keys_ambiguous(self):
        """Test gettings keys when when the key is ambiguous."""
        key = crypto.get_key(
            FPR, validate=True, encrypt=True, signed_only=False)
        ui = utilities.make_ui()

        # Creat a ui.choice object that can satisfy asyncio, but can also be
        # queried for calls as a mock
        async def choice(*args, **kwargs):
            return None
        ui.choice = mock.Mock(wraps=choice)

        ids = [FPR]
        with mock.patch('alot.commands.utils.crypto.get_key',
                        mock.Mock(side_effect=errors.GPGProblem(
                            'test', errors.GPGCode.AMBIGUOUS_NAME))):
            with mock.patch('alot.commands.utils.crypto.list_keys',
                            mock.Mock(return_value=[key])):
                await utils._get_keys(ui, ids, signed_only=False)
        ui.choice.assert_called_once()


class _Account(object):
    def __init__(self, encrypt_to_self=True, gpg_key=None):
        self.encrypt_to_self = encrypt_to_self
        self.gpg_key = gpg_key


class TestSetEncrypt(unittest.TestCase):

    @utilities.async_test
    async def test_get_keys_from_to(self):
        ui = utilities.make_ui()
        envelope = Envelope()
        envelope['To'] = 'ambig@example.com, test@example.com'
        await utils.update_keys(ui, envelope)
        self.assertTrue(envelope.encrypt)
        self.assertCountEqual(
            [f.fpr for f in envelope.encrypt_keys.values()],
            [crypto.get_key(FPR).fpr, crypto.get_key(EXTRA_FPRS[0]).fpr])

    @utilities.async_test
    async def test_get_keys_from_cc(self):
        ui = utilities.make_ui()
        envelope = Envelope()
        envelope['Cc'] = 'ambig@example.com, test@example.com'
        await utils.update_keys(ui, envelope)
        self.assertTrue(envelope.encrypt)
        self.assertCountEqual(
            [f.fpr for f in envelope.encrypt_keys.values()],
            [crypto.get_key(FPR).fpr, crypto.get_key(EXTRA_FPRS[0]).fpr])

    @utilities.async_test
    async def test_get_partial_keys(self):
        ui = utilities.make_ui()
        envelope = Envelope()
        envelope['Cc'] = 'foo@example.com, test@example.com'
        await utils.update_keys(ui, envelope)
        self.assertTrue(envelope.encrypt)
        self.assertCountEqual(
            [f.fpr for f in envelope.encrypt_keys.values()],
            [crypto.get_key(FPR).fpr])

    @utilities.async_test
    async def test_get_no_keys(self):
        ui = utilities.make_ui()
        envelope = Envelope()
        envelope['To'] = 'foo@example.com'
        await utils.update_keys(ui, envelope)
        self.assertFalse(envelope.encrypt)
        self.assertEqual(envelope.encrypt_keys, {})

    @utilities.async_test
    async def test_encrypt_to_self_true(self):
        ui = utilities.make_ui()
        envelope = Envelope()
        envelope['From'] = 'test@example.com'
        envelope['To'] = 'ambig@example.com'
        gpg_key = crypto.get_key(FPR)
        account = _Account(encrypt_to_self=True, gpg_key=gpg_key)
        envelope.account = account
        await utils.update_keys(ui, envelope)
        self.assertTrue(envelope.encrypt)
        self.assertIn(FPR, envelope.encrypt_keys)
        self.assertEqual(gpg_key, envelope.encrypt_keys[FPR])

    @utilities.async_test
    async def test_encrypt_to_self_false(self):
        ui = utilities.make_ui()
        envelope = Envelope()
        envelope['From'] = 'test@example.com'
        envelope['To'] = 'ambig@example.com'
        gpg_key = crypto.get_key(FPR)
        account = _Account(encrypt_to_self=False, gpg_key=gpg_key)
        envelope.account = account
        await utils.update_keys(ui, envelope)
        self.assertTrue(envelope.encrypt)
        self.assertNotIn(FPR, envelope.encrypt_keys)