~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/gpg.py

  • Committer: Martin Packman
  • Date: 2012-01-05 09:50:04 UTC
  • mfrom: (6424 +trunk)
  • mto: This revision was merged to the branch mainline in revision 6426.
  • Revision ID: martin.packman@canonical.com-20120105095004-mia9xb7y0efmto0v
Merge bzr.dev to resolve conflicts in bzrlib.builtins

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
"""GPG signing and checking logic."""
19
19
 
 
20
from __future__ import absolute_import
 
21
 
20
22
import os
21
23
import sys
22
24
from StringIO import StringIO
27
29
import subprocess
28
30
 
29
31
from bzrlib import (
 
32
    config,
30
33
    errors,
31
34
    trace,
32
35
    ui,
33
36
    )
 
37
from bzrlib.i18n import (
 
38
    gettext, 
 
39
    ngettext,
 
40
    )
34
41
""")
35
42
 
36
 
class i18n:
37
 
    """this class is ready to use bzrlib.i18n but bzrlib.i18n is not ready to
38
 
    use so here is a stub until it is"""
39
 
    @staticmethod
40
 
    def gettext(string):
41
 
        return string
42
 
        
43
 
    @staticmethod
44
 
    def ngettext(single, plural, number):
45
 
        if number == 1:
46
 
            return single
47
 
        else:
48
 
            return plural
49
 
 
50
43
#verification results
51
44
SIGNATURE_VALID = 0
52
45
SIGNATURE_KEY_MISSING = 1
115
108
        all_verifiable = True
116
109
        for rev_id in revisions:
117
110
            verification_result, uid =\
118
 
                                repository.verify_revision(rev_id,self)
 
111
                repository.verify_revision_signature(rev_id,self)
119
112
            result.append([rev_id, verification_result, uid])
120
113
            count[verification_result] += 1
121
114
            if verification_result != SIGNATURE_VALID:
123
116
        return (count, result, all_verifiable)
124
117
 
125
118
    def valid_commits_message(self, count):
126
 
        return i18n.gettext(u"{0} commits with valid signatures").format(
127
 
                                        count[SIGNATURE_VALID])            
 
119
        return gettext(u"{0} commits with valid signatures").format(
 
120
                                        count[SIGNATURE_VALID])
128
121
 
129
122
    def unknown_key_message(self, count):
130
 
        return i18n.ngettext(u"{0} commit with unknown key",
 
123
        return ngettext(u"{0} commit with unknown key",
131
124
                             u"{0} commits with unknown keys",
132
125
                             count[SIGNATURE_KEY_MISSING]).format(
133
126
                                        count[SIGNATURE_KEY_MISSING])
134
127
 
135
128
    def commit_not_valid_message(self, count):
136
 
        return i18n.ngettext(u"{0} commit not valid",
 
129
        return ngettext(u"{0} commit not valid",
137
130
                             u"{0} commits not valid",
138
131
                             count[SIGNATURE_NOT_VALID]).format(
139
132
                                            count[SIGNATURE_NOT_VALID])
140
133
 
141
134
    def commit_not_signed_message(self, count):
142
 
        return i18n.ngettext(u"{0} commit not signed",
 
135
        return ngettext(u"{0} commit not signed",
143
136
                             u"{0} commits not signed",
144
137
                             count[SIGNATURE_NOT_SIGNED]).format(
145
138
                                        count[SIGNATURE_NOT_SIGNED])
146
139
 
147
140
    def expired_commit_message(self, count):
148
 
        return i18n.ngettext(u"{0} commit with key now expired",
149
 
                             u"{0} commits with key now expired",
150
 
                             count[SIGNATURE_EXPIRED]).format(
 
141
        return ngettext(u"{0} commit with key now expired",
 
142
                        u"{0} commits with key now expired",
 
143
                        count[SIGNATURE_EXPIRED]).format(
151
144
                                        count[SIGNATURE_EXPIRED])
152
145
 
153
146
 
169
162
 
170
163
    acceptable_keys = None
171
164
 
 
165
    def __init__(self, config_stack):
 
166
        self._config_stack = config_stack
 
167
        try:
 
168
            import gpgme
 
169
            self.context = gpgme.Context()
 
170
        except ImportError, error:
 
171
            pass # can't use verify()
 
172
 
172
173
    @staticmethod
173
174
    def verify_signatures_available():
174
175
        """
183
184
            return False
184
185
 
185
186
    def _command_line(self):
186
 
        
187
 
        return [self._config.gpg_signing_command(), '--clearsign', '-u',
188
 
                                                self._config.gpg_signing_key()]
189
 
 
190
 
    def __init__(self, config):
191
 
        self._config = config
192
 
        try:
193
 
            import gpgme
194
 
            self.context = gpgme.Context()
195
 
        except ImportError, error:
196
 
            pass # can't use verify()
 
187
        key = self._config_stack.get('gpg_signing_key')
 
188
        if key is None or key == 'default':
 
189
            # 'default' or not setting gpg_signing_key at all means we should
 
190
            # use the user email address
 
191
            key = config.extract_email_address(self._config_stack.get('email'))
 
192
        return [self._config_stack.get('gpg_signing_command'), '--clearsign',
 
193
                '-u', key]
197
194
 
198
195
    def sign(self, content):
199
196
        if isinstance(content, unicode):
246
243
 
247
244
        signature = StringIO(content)
248
245
        plain_output = StringIO()
249
 
        
250
246
        try:
251
247
            result = self.context.verify(signature, None, plain_output)
252
248
        except gpgme.GpgmeError,error:
256
252
        # test_verify_invalid()
257
253
        if len(result) == 0:
258
254
            return SIGNATURE_NOT_VALID, None
259
 
        # User has specified a list of acceptable keys, check our result is in it.
260
 
        # test_verify_unacceptable_key()
 
255
        # User has specified a list of acceptable keys, check our result is in
 
256
        # it.  test_verify_unacceptable_key()
261
257
        fingerprint = result[0].fpr
262
258
        if self.acceptable_keys is not None:
263
 
            if not fingerprint in self.acceptable_keys:                
 
259
            if not fingerprint in self.acceptable_keys:
264
260
                return SIGNATURE_KEY_MISSING, fingerprint[-8:]
265
261
        # Check the signature actually matches the testament.
266
262
        # test_verify_bad_testament()
267
263
        if testament != plain_output.getvalue():
268
 
            return SIGNATURE_NOT_VALID, None 
 
264
            return SIGNATURE_NOT_VALID, None
269
265
        # Yay gpgme set the valid bit.
270
266
        # Can't write a test for this one as you can't set a key to be
271
267
        # trusted using gpgme.
282
278
        # test_verify_unknown_key()
283
279
        if result[0].summary & gpgme.SIGSUM_KEY_MISSING:
284
280
            return SIGNATURE_KEY_MISSING, fingerprint[-8:]
285
 
        # Summary isn't set if sig is valid but key is untrusted
286
 
        # but if user has explicity set the key as acceptable we can validate it.
 
281
        # Summary isn't set if sig is valid but key is untrusted but if user
 
282
        # has explicity set the key as acceptable we can validate it.
287
283
        if result[0].summary == 0 and self.acceptable_keys is not None:
288
284
            if fingerprint in self.acceptable_keys:
289
285
                # test_verify_untrusted_but_accepted()
290
 
                return SIGNATURE_VALID, None 
 
286
                return SIGNATURE_VALID, None
291
287
        # test_verify_valid_but_untrusted()
292
288
        if result[0].summary == 0 and self.acceptable_keys is None:
293
289
            return SIGNATURE_NOT_VALID, None
311
307
                                                 "verification result")
312
308
 
313
309
    def set_acceptable_keys(self, command_line_input):
314
 
        """sets the acceptable keys for verifying with this GPGStrategy
 
310
        """Set the acceptable keys for verifying with this GPGStrategy.
315
311
        
316
312
        :param command_line_input: comma separated list of patterns from
317
313
                                command line
318
314
        :return: nothing
319
315
        """
320
316
        key_patterns = None
321
 
        acceptable_keys_config = self._config.acceptable_keys()
 
317
        acceptable_keys_config = self._config_stack.get('acceptable_keys')
322
318
        try:
323
319
            if isinstance(acceptable_keys_config, unicode):
324
320
                acceptable_keys_config = str(acceptable_keys_config)
325
321
        except UnicodeEncodeError:
326
 
            #gpg Context.keylist(pattern) does not like unicode
327
 
            raise errors.BzrCommandError('Only ASCII permitted in option names')
 
322
            # gpg Context.keylist(pattern) does not like unicode
 
323
            raise errors.BzrCommandError(
 
324
                gettext('Only ASCII permitted in option names'))
328
325
 
329
326
        if acceptable_keys_config is not None:
330
327
            key_patterns = acceptable_keys_config
331
 
        if command_line_input is not None: #command line overrides config
 
328
        if command_line_input is not None: # command line overrides config
332
329
            key_patterns = command_line_input
333
330
        if key_patterns is not None:
334
331
            patterns = key_patterns.split(",")
342
339
                    self.acceptable_keys.append(key.subkeys[0].fpr)
343
340
                    trace.mutter("Added acceptable key: " + key.subkeys[0].fpr)
344
341
                if not found_key:
345
 
                    trace.note(i18n.gettext(
346
 
                            "No GnuPG key results for pattern: {}"
 
342
                    trace.note(gettext(
 
343
                            "No GnuPG key results for pattern: {0}"
347
344
                                ).format(pattern))
348
345
 
349
346
    def do_verifications(self, revisions, repository,
368
365
        all_verifiable = True
369
366
        for rev_id in revisions:
370
367
            verification_result, uid =\
371
 
                                repository.verify_revision(rev_id,self)
 
368
                repository.verify_revision_signature(rev_id, self)
372
369
            result.append([rev_id, verification_result, uid])
373
370
            count[verification_result] += 1
374
371
            if verification_result != SIGNATURE_VALID:
386
383
                signers[uid] += 1
387
384
        result = []
388
385
        for uid, number in signers.items():
389
 
             result.append( i18n.ngettext(u"{0} signed {1} commit", 
 
386
             result.append( ngettext(u"{0} signed {1} commit",
390
387
                             u"{0} signed {1} commits",
391
388
                             number).format(uid, number) )
392
389
        return result
403
400
                signers[authors] += 1
404
401
        result = []
405
402
        for authors, number in signers.items():
406
 
            result.append( i18n.ngettext(u"{0} commit by author {1}", 
 
403
            result.append( ngettext(u"{0} commit by author {1}",
407
404
                                 u"{0} commits by author {1}",
408
405
                                 number).format(number, authors) )
409
406
        return result
419
416
                signers[authors] += 1
420
417
        result = []
421
418
        for authors, number in signers.items():
422
 
            result.append( i18n.ngettext(u"{0} commit by author {1}", 
 
419
            result.append( ngettext(u"{0} commit by author {1}",
423
420
                                 u"{0} commits by author {1}",
424
421
                                 number).format(number, authors) )
425
422
        return result
433
430
                signers[fingerprint] += 1
434
431
        result = []
435
432
        for fingerprint, number in signers.items():
436
 
            result.append( i18n.ngettext(u"Unknown key {0} signed {1} commit", 
 
433
            result.append( ngettext(u"Unknown key {0} signed {1} commit",
437
434
                                 u"Unknown key {0} signed {1} commits",
438
435
                                 number).format(fingerprint, number) )
439
436
        return result
451
448
                fingerprint_to_authors[fingerprint] = authors
452
449
        result = []
453
450
        for fingerprint, number in signers.items():
454
 
            result.append( i18n.ngettext(u"{0} commit by author {1} with "\
455
 
                                          "key {2} now expired", 
456
 
                                 u"{0} commits by author {1} with key {2} now "\
457
 
                                  "expired",
458
 
                                 number).format(number,
459
 
                            fingerprint_to_authors[fingerprint], fingerprint) )
 
451
            result.append(
 
452
                ngettext(u"{0} commit by author {1} with key {2} now expired",
 
453
                         u"{0} commits by author {1} with key {2} now expired",
 
454
                         number).format(
 
455
                    number, fingerprint_to_authors[fingerprint], fingerprint) )
460
456
        return result
461
457
 
462
458
    def valid_commits_message(self, count):
463
459
        """returns message for number of commits"""
464
 
        return i18n.gettext(u"{0} commits with valid signatures").format(
 
460
        return gettext(u"{0} commits with valid signatures").format(
465
461
                                        count[SIGNATURE_VALID])
466
462
 
467
463
    def unknown_key_message(self, count):
468
464
        """returns message for number of commits"""
469
 
        return i18n.ngettext(u"{0} commit with unknown key",
470
 
                             u"{0} commits with unknown keys",
471
 
                             count[SIGNATURE_KEY_MISSING]).format(
 
465
        return ngettext(u"{0} commit with unknown key",
 
466
                        u"{0} commits with unknown keys",
 
467
                        count[SIGNATURE_KEY_MISSING]).format(
472
468
                                        count[SIGNATURE_KEY_MISSING])
473
469
 
474
470
    def commit_not_valid_message(self, count):
475
471
        """returns message for number of commits"""
476
 
        return i18n.ngettext(u"{0} commit not valid",
477
 
                             u"{0} commits not valid",
478
 
                             count[SIGNATURE_NOT_VALID]).format(
 
472
        return ngettext(u"{0} commit not valid",
 
473
                        u"{0} commits not valid",
 
474
                        count[SIGNATURE_NOT_VALID]).format(
479
475
                                            count[SIGNATURE_NOT_VALID])
480
476
 
481
477
    def commit_not_signed_message(self, count):
482
478
        """returns message for number of commits"""
483
 
        return i18n.ngettext(u"{0} commit not signed",
484
 
                             u"{0} commits not signed",
485
 
                             count[SIGNATURE_NOT_SIGNED]).format(
 
479
        return ngettext(u"{0} commit not signed",
 
480
                        u"{0} commits not signed",
 
481
                        count[SIGNATURE_NOT_SIGNED]).format(
486
482
                                        count[SIGNATURE_NOT_SIGNED])
487
483
 
488
484
    def expired_commit_message(self, count):
489
485
        """returns message for number of commits"""
490
 
        return i18n.ngettext(u"{0} commit with key now expired",
491
 
                             u"{0} commits with key now expired",
492
 
                             count[SIGNATURE_EXPIRED]).format(
493
 
                                        count[SIGNATURE_EXPIRED])
 
486
        return ngettext(u"{0} commit with key now expired",
 
487
                        u"{0} commits with key now expired",
 
488
                        count[SIGNATURE_EXPIRED]).format(
 
489
                                    count[SIGNATURE_EXPIRED])