1
# Copyright (C) 2005 by Canonical Ltd
 
 
3
# This program is free software; you can redistribute it and/or modify
 
 
4
# it under the terms of the GNU General Public License as published by
 
 
5
# the Free Software Foundation; either version 2 of the License, or
 
 
6
# (at your option) any later version.
 
 
8
# This program is distributed in the hope that it will be useful,
 
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 
11
# GNU General Public License for more details.
 
 
13
# You should have received a copy of the GNU General Public License
 
 
14
# along with this program; if not, write to the Free Software
 
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 
17
"""Testament - a summary of a revision for signing.
 
 
19
A testament can be defined as "something that serves as tangible 
 
 
20
proof or evidence."  In bzr we use them to allow people to certify
 
 
21
particular revisions as authentic.  
 
 
23
The goal is that if two revisions are semantically equal, then they will
 
 
24
have a byte-for-byte equal testament.  We can define different versions of
 
 
25
"semantically equal" by using different testament classes; e.g. one that
 
 
26
includes or ignores file-ids.
 
 
28
We sign a testament rather than the revision XML itself for several reasons.
 
 
29
The most important is that the form in which the revision is stored
 
 
30
internally is designed for that purpose, and contains information which need
 
 
31
not be attested to by the signer.  For example the inventory contains the
 
 
32
last-changed revision for a file, but this is not necessarily something the
 
 
35
Having unnecessary fields signed makes the signatures brittle when the same
 
 
36
revision is stored in different branches or when the format is upgraded.
 
 
38
Handling upgrades is another motivation for using testaments separate from
 
 
39
the stored revision.  We would like to be able to compare a signature
 
 
40
generated from an old-format tree to newer tree, or vice versa.  This could
 
 
41
be done by comparing the revisions but that makes it unclear about exactly
 
 
42
what is being compared or not.
 
 
44
Different signing keys might indicate different levels of trust; we can in
 
 
45
the future extend this to allow signatures indicating not just that a
 
 
46
particular version is authentic but that it has other properties.
 
 
48
The signature can be applied to either the full testament or to just a
 
 
54
* timestamps are given as integers to avoid rounding errors
 
 
55
* parents given in lexicographical order
 
 
56
* indented-text form similar to log; intended to be human readable
 
 
57
* paths are given with forward slashes
 
 
58
* files are named using paths for ease of comparison/debugging
 
 
59
* the testament uses unix line-endings (\n)
 
 
62
# XXX: At the moment, clients trust that the graph described in a weave
 
 
63
# is accurate, but that's not covered by the testament.  Perhaps the best
 
 
64
# fix is when verifying a revision to make sure that every file mentioned 
 
 
65
# in the revision has compatible ancestry links.
 
 
67
# TODO: perhaps write timestamp in a more readable form
 
 
69
# TODO: Perhaps these should just be different formats in which inventories/
 
 
70
# revisions can be serialized.
 
 
75
from bzrlib.osutils import contains_whitespace, contains_linebreaks
 
 
78
class Testament(object):
 
 
79
    """Reduced summary of a revision.
 
 
83
      - produced from a revision
 
 
85
      - loaded from a stream
 
 
86
      - compared to a revision
 
 
89
    long_header = 'bazaar-ng testament version 1\n'
 
 
90
    short_header = 'bazaar-ng testament short form 1\n'
 
 
93
    def from_revision(cls, repository, revision_id):
 
 
94
        """Produce a new testament from a historical revision"""
 
 
95
        rev = repository.get_revision(revision_id)
 
 
96
        inventory = repository.get_inventory(revision_id)
 
 
97
        return cls(rev, inventory)
 
 
99
    def __init__(self, rev, inventory):
 
 
100
        """Create a new testament for rev using inventory."""
 
 
101
        self.revision_id = str(rev.revision_id)
 
 
102
        self.committer = rev.committer
 
 
103
        self.timezone = rev.timezone or 0
 
 
104
        self.timestamp = rev.timestamp
 
 
105
        self.message = rev.message
 
 
106
        self.parent_ids = rev.parent_ids[:]
 
 
107
        self.inventory = inventory
 
 
108
        self.revprops = copy(rev.properties)
 
 
109
        assert not contains_whitespace(self.revision_id)
 
 
110
        assert not contains_linebreaks(self.committer)
 
 
112
    def as_text_lines(self):
 
 
113
        """Yield text form as a sequence of lines.
 
 
115
        The result is returned in utf-8, because it should be signed or
 
 
116
        hashed in that encoding.
 
 
121
        a('revision-id: %s\n' % self.revision_id)
 
 
122
        a('committer: %s\n' % self.committer)
 
 
123
        a('timestamp: %d\n' % self.timestamp)
 
 
124
        a('timezone: %d\n' % self.timezone)
 
 
125
        # inventory length contains the root, which is not shown here
 
 
127
        for parent_id in sorted(self.parent_ids):
 
 
128
            assert not contains_whitespace(parent_id)
 
 
129
            a('  %s\n' % parent_id)
 
 
131
        for l in self.message.splitlines():
 
 
134
        entries = self.inventory.iter_entries()
 
 
136
        for path, ie in entries:
 
 
137
            a(self._entry_to_line(path, ie))
 
 
138
        r.extend(self._revprops_to_lines())
 
 
141
                assert isinstance(l, basestring), \
 
 
142
                    '%r of type %s is not a plain string' % (l, type(l))
 
 
143
        return [line.encode('utf-8') for line in r]
 
 
145
    def _escape_path(self, path):
 
 
146
        assert not contains_linebreaks(path)
 
 
147
        return unicode(path.replace('\\', '/').replace(' ', '\ '))
 
 
149
    def _entry_to_line(self, path, ie):
 
 
150
        """Turn an inventory entry into a testament line"""
 
 
151
        assert not contains_whitespace(ie.file_id)
 
 
155
        if ie.kind == 'file':
 
 
156
            # TODO: avoid switching on kind
 
 
158
            content = ie.text_sha1
 
 
160
        elif ie.kind == 'symlink':
 
 
161
            assert ie.symlink_target
 
 
162
            content = self._escape_path(ie.symlink_target)
 
 
165
        l = u'  %s %s %s%s%s\n' % (ie.kind, self._escape_path(path),
 
 
167
                                   content_spacer, content)
 
 
171
        return ''.join(self.as_text_lines())
 
 
173
    def as_short_text(self):
 
 
174
        """Return short digest-based testament."""
 
 
175
        return (self.short_header + 
 
 
178
                % (self.revision_id, self.as_sha1()))
 
 
180
    def _revprops_to_lines(self):
 
 
181
        """Pack up revision properties."""
 
 
182
        if not self.revprops:
 
 
184
        r = ['properties:\n']
 
 
185
        for name, value in sorted(self.revprops.items()):
 
 
186
            assert isinstance(name, str)
 
 
187
            assert not contains_whitespace(name)
 
 
188
            r.append('  %s:\n' % name)
 
 
189
            for line in value.splitlines():
 
 
190
                r.append(u'    %s\n' % line)
 
 
195
        map(s.update, self.as_text_lines())
 
 
199
class StrictTestament(Testament):
 
 
200
    """This testament format is for use as a checksum in changesets"""
 
 
202
    long_header = 'bazaar-ng testament version 2.1\n'
 
 
203
    short_header = 'bazaar-ng testament short form 2.1\n'
 
 
204
    def _entry_to_line(self, path, ie):
 
 
205
        l = Testament._entry_to_line(self, path, ie)[:-1]
 
 
206
        l += ' ' + ie.revision
 
 
207
        l += {True: ' yes\n', False: ' no\n'}[ie.executable]