/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
6402.3.1 by Jelmer Vernooij
Add safe_open class to bzr.
1
# Copyright (C) 2011 Canonical Ltd
2
#
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.
7
#
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.
12
#
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
17
"""Tests for the safe branch open code."""
18
19
from bzrlib import urlutils
20
from bzrlib.branch import (
21
    Branch,
22
    BranchReferenceFormat,
23
    )
24
from bzrlib.bzrdir import (
25
    BzrDir,
26
    BzrProber,
27
    )
28
from bzrlib.controldir import ControlDirFormat
29
from bzrlib.errors import NotBranchError
30
from bzrlib.safe_open import (
31
    BadUrl,
32
    BlacklistPolicy,
33
    BranchLoopError,
34
    BranchReferenceForbidden,
35
    safe_open,
36
    SafeBranchOpener,
37
    WhitelistPolicy,
38
    )
39
from bzrlib.tests import (
40
    TestCase,
41
    TestCaseWithTransport,
42
    )
43
from bzrlib.transport import chroot
44
45
46
class TestSafeBranchOpenerCheckAndFollowBranchReference(TestCase):
47
    """Unit tests for `SafeBranchOpener.check_and_follow_branch_reference`."""
48
49
    def setUp(self):
50
        super(TestSafeBranchOpenerCheckAndFollowBranchReference, self).setUp()
51
        SafeBranchOpener.install_hook()
52
53
    class StubbedSafeBranchOpener(SafeBranchOpener):
54
        """SafeBranchOpener that provides canned answers.
55
56
        We implement the methods we need to to be able to control all the
57
        inputs to the `follow_reference` method, which is what is
58
        being tested in this class.
59
        """
60
61
        def __init__(self, references, policy):
62
            parent_cls = TestSafeBranchOpenerCheckAndFollowBranchReference
63
            super(parent_cls.StubbedSafeBranchOpener, self).__init__(policy)
64
            self._reference_values = {}
65
            for i in range(len(references) - 1):
66
                self._reference_values[references[i]] = references[i + 1]
67
            self.follow_reference_calls = []
68
69
        def follow_reference(self, url):
70
            self.follow_reference_calls.append(url)
71
            return self._reference_values[url]
72
73
    def make_branch_opener(self, should_follow_references, references,
74
                         unsafe_urls=None):
75
        policy = BlacklistPolicy(should_follow_references, unsafe_urls)
76
        opener = self.StubbedSafeBranchOpener(references, policy)
77
        return opener
78
79
    def test_check_initial_url(self):
80
        # check_and_follow_branch_reference rejects all URLs that are not allowed.
81
        opener = self.make_branch_opener(None, [], set(['a']))
82
        self.assertRaises(
83
            BadUrl, opener.check_and_follow_branch_reference, 'a')
84
85
    def test_not_reference(self):
86
        # When branch references are forbidden, check_and_follow_branch_reference
87
        # does not raise on non-references.
88
        opener = self.make_branch_opener(False, ['a', None])
89
        self.assertEquals(
90
            'a', opener.check_and_follow_branch_reference('a'))
91
        self.assertEquals(['a'], opener.follow_reference_calls)
92
93
    def test_branch_reference_forbidden(self):
94
        # check_and_follow_branch_reference raises BranchReferenceForbidden if
95
        # branch references are forbidden and the source URL points to a
96
        # branch reference.
97
        opener = self.make_branch_opener(False, ['a', 'b'])
98
        self.assertRaises(
99
            BranchReferenceForbidden,
100
            opener.check_and_follow_branch_reference, 'a')
101
        self.assertEquals(['a'], opener.follow_reference_calls)
102
103
    def test_allowed_reference(self):
104
        # check_and_follow_branch_reference does not raise if following references
105
        # is allowed and the source URL points to a branch reference to a
106
        # permitted location.
107
        opener = self.make_branch_opener(True, ['a', 'b', None])
108
        self.assertEquals(
109
            'b', opener.check_and_follow_branch_reference('a'))
110
        self.assertEquals(['a', 'b'], opener.follow_reference_calls)
111
112
    def test_check_referenced_urls(self):
113
        # check_and_follow_branch_reference checks if the URL a reference points
114
        # to is safe.
115
        opener = self.make_branch_opener(
116
            True, ['a', 'b', None], unsafe_urls=set('b'))
117
        self.assertRaises(
118
            BadUrl, opener.check_and_follow_branch_reference, 'a')
119
        self.assertEquals(['a'], opener.follow_reference_calls)
120
121
    def test_self_referencing_branch(self):
122
        # check_and_follow_branch_reference raises BranchReferenceLoopError if
123
        # following references is allowed and the source url points to a
124
        # self-referencing branch reference.
125
        opener = self.make_branch_opener(True, ['a', 'a'])
126
        self.assertRaises(
127
            BranchLoopError, opener.check_and_follow_branch_reference, 'a')
128
        self.assertEquals(['a'], opener.follow_reference_calls)
129
130
    def test_branch_reference_loop(self):
131
        # check_and_follow_branch_reference raises BranchReferenceLoopError if
132
        # following references is allowed and the source url points to a loop
133
        # of branch references.
134
        references = ['a', 'b', 'a']
135
        opener = self.make_branch_opener(True, references)
136
        self.assertRaises(
137
            BranchLoopError, opener.check_and_follow_branch_reference, 'a')
138
        self.assertEquals(['a', 'b'], opener.follow_reference_calls)
139
140
141
class TrackingProber(BzrProber):
142
    """Subclass of BzrProber which tracks URLs it has been asked to open."""
143
144
    seen_urls = []
145
146
    @classmethod
147
    def probe_transport(klass, transport):
148
        klass.seen_urls.append(transport.base)
149
        return BzrProber.probe_transport(transport)
150
151
152
class TestSafeBranchOpenerStacking(TestCaseWithTransport):
153
154
    def setUp(self):
155
        super(TestSafeBranchOpenerStacking, self).setUp()
156
        SafeBranchOpener.install_hook()
157
158
    def make_branch_opener(self, allowed_urls, probers=None):
159
        policy = WhitelistPolicy(True, allowed_urls, True)
160
        return SafeBranchOpener(policy, probers)
161
162
    def test_probers(self):
163
        # Only the specified probers should be used
164
        b = self.make_branch('branch')
165
        opener = self.make_branch_opener([b.base], probers=[])
166
        self.assertRaises(NotBranchError, opener.open, b.base)
167
        opener = self.make_branch_opener([b.base], probers=[BzrProber])
168
        self.assertEquals(b.base, opener.open(b.base).base)
169
170
    def test_default_probers(self):
171
        # If no probers are specified to the constructor
172
        # of SafeBranchOpener, then a safe set will be used,
173
        # rather than all probers registered in bzr.
174
        self.addCleanup(ControlDirFormat.unregister_prober, TrackingProber)
175
        ControlDirFormat.register_prober(TrackingProber)
176
        # Open a location without any branches, so that all probers are
177
        # tried.
178
        # First, check that the TrackingProber tracks correctly.
179
        TrackingProber.seen_urls = []
180
        opener = self.make_branch_opener(["."], probers=[TrackingProber])
181
        self.assertRaises(NotBranchError, opener.open, ".")
182
        self.assertEquals(1, len(TrackingProber.seen_urls))
183
        TrackingProber.seen_urls = []
184
        # And make sure it's registered in such a way that BzrDir.open would
185
        # use it.
186
        self.assertRaises(NotBranchError, BzrDir.open, ".")
187
        self.assertEquals(1, len(TrackingProber.seen_urls))
188
189
    def test_allowed_url(self):
190
        # the opener does not raise an exception for branches stacked on
191
        # branches with allowed URLs.
192
        stacked_on_branch = self.make_branch('base-branch', format='1.6')
193
        stacked_branch = self.make_branch('stacked-branch', format='1.6')
194
        stacked_branch.set_stacked_on_url(stacked_on_branch.base)
195
        opener = self.make_branch_opener(
196
            [stacked_branch.base, stacked_on_branch.base])
197
        # This doesn't raise an exception.
198
        opener.open(stacked_branch.base)
199
200
    def test_nstackable_repository(self):
201
        # treats branches with UnstackableRepositoryFormats as
202
        # being not stacked.
203
        branch = self.make_branch('unstacked', format='knit')
204
        opener = self.make_branch_opener([branch.base])
205
        # This doesn't raise an exception.
206
        opener.open(branch.base)
207
208
    def test_allowed_relative_url(self):
209
        # passes on absolute urls to check_one_url, even if the
210
        # value of stacked_on_location in the config is set to a relative URL.
211
        stacked_on_branch = self.make_branch('base-branch', format='1.6')
212
        stacked_branch = self.make_branch('stacked-branch', format='1.6')
213
        stacked_branch.set_stacked_on_url('../base-branch')
214
        opener = self.make_branch_opener(
215
            [stacked_branch.base, stacked_on_branch.base])
216
        # Note that stacked_on_branch.base is not '../base-branch', it's an
217
        # absolute URL.
218
        self.assertNotEqual('../base-branch', stacked_on_branch.base)
219
        # This doesn't raise an exception.
220
        opener.open(stacked_branch.base)
221
222
    def test_allowed_relative_nested(self):
223
        # Relative URLs are resolved relative to the stacked branch.
224
        self.get_transport().mkdir('subdir')
225
        a = self.make_branch('subdir/a', format='1.6')
226
        b = self.make_branch('b', format='1.6')
227
        b.set_stacked_on_url('../subdir/a')
228
        c = self.make_branch('subdir/c', format='1.6')
229
        c.set_stacked_on_url('../../b')
230
        opener = self.make_branch_opener([c.base, b.base, a.base])
231
        # This doesn't raise an exception.
232
        opener.open(c.base)
233
234
    def test_forbidden_url(self):
235
        # raises a BadUrl exception if a branch is stacked on a
236
        # branch with a forbidden URL.
237
        stacked_on_branch = self.make_branch('base-branch', format='1.6')
238
        stacked_branch = self.make_branch('stacked-branch', format='1.6')
239
        stacked_branch.set_stacked_on_url(stacked_on_branch.base)
240
        opener = self.make_branch_opener([stacked_branch.base])
241
        self.assertRaises(BadUrl, opener.open, stacked_branch.base)
242
243
    def test_forbidden_url_nested(self):
244
        # raises a BadUrl exception if a branch is stacked on a
245
        # branch that is in turn stacked on a branch with a forbidden URL.
246
        a = self.make_branch('a', format='1.6')
247
        b = self.make_branch('b', format='1.6')
248
        b.set_stacked_on_url(a.base)
249
        c = self.make_branch('c', format='1.6')
250
        c.set_stacked_on_url(b.base)
251
        opener = self.make_branch_opener([c.base, b.base])
252
        self.assertRaises(BadUrl, opener.open, c.base)
253
254
    def test_self_stacked_branch(self):
255
        # raises StackingLoopError if a branch is stacked on
256
        # itself. This avoids infinite recursion errors.
257
        a = self.make_branch('a', format='1.6')
258
        # Bazaar 1.17 and up make it harder to create branches like this.
259
        # It's still worth testing that we don't blow up in the face of them,
260
        # so we grovel around a bit to create one anyway.
261
        a.get_config().set_user_option('stacked_on_location', a.base)
262
        opener = self.make_branch_opener([a.base])
263
        self.assertRaises(BranchLoopError, opener.open, a.base)
264
265
    def test_loop_stacked_branch(self):
266
        # raises StackingLoopError if a branch is stacked in such
267
        # a way so that it is ultimately stacked on itself. e.g. a stacked on
268
        # b stacked on a.
269
        a = self.make_branch('a', format='1.6')
270
        b = self.make_branch('b', format='1.6')
271
        a.set_stacked_on_url(b.base)
272
        b.set_stacked_on_url(a.base)
273
        opener = self.make_branch_opener([a.base, b.base])
274
        self.assertRaises(BranchLoopError, opener.open, a.base)
275
        self.assertRaises(BranchLoopError, opener.open, b.base)
276
277
    def test_custom_opener(self):
278
        # A custom function for opening a control dir can be specified.
279
        a = self.make_branch('a', format='2a')
280
        b = self.make_branch('b', format='2a')
281
        b.set_stacked_on_url(a.base)
282
283
        TrackingProber.seen_urls = []
284
        opener = self.make_branch_opener(
285
            [a.base, b.base], probers=[TrackingProber])
286
        opener.open(b.base)
287
        self.assertEquals(
288
            set(TrackingProber.seen_urls), set([b.base, a.base]))
289
290
    def test_custom_opener_with_branch_reference(self):
291
        # A custom function for opening a control dir can be specified.
292
        a = self.make_branch('a', format='2a')
293
        b_dir = self.make_bzrdir('b')
294
        b = BranchReferenceFormat().initialize(b_dir, target_branch=a)
295
        TrackingProber.seen_urls = []
296
        opener = self.make_branch_opener(
297
            [a.base, b.base], probers=[TrackingProber])
298
        opener.open(b.base)
299
        self.assertEquals(
300
            set(TrackingProber.seen_urls), set([b.base, a.base]))
301
302
303
class TestSafeOpen(TestCaseWithTransport):
304
    """Tests for `safe_open`."""
305
306
    def setUp(self):
307
        super(TestSafeOpen, self).setUp()
308
        SafeBranchOpener.install_hook()
309
310
    def test_hook_does_not_interfere(self):
311
        # The transform_fallback_location hook does not interfere with regular
312
        # stacked branch access outside of safe_open.
313
        self.make_branch('stacked')
314
        self.make_branch('stacked-on')
315
        Branch.open('stacked').set_stacked_on_url('../stacked-on')
316
        Branch.open('stacked')
317
318
    def get_chrooted_scheme(self, relpath):
319
        """Create a server that is chrooted to `relpath`.
320
321
        :return: ``(scheme, get_url)`` where ``scheme`` is the scheme of the
322
            chroot server and ``get_url`` returns URLs on said server.
323
        """
324
        transport = self.get_transport(relpath)
325
        chroot_server = chroot.ChrootServer(transport)
326
        chroot_server.start_server()
327
        self.addCleanup(chroot_server.stop_server)
328
329
        def get_url(relpath):
6402.3.2 by Jelmer Vernooij
bzrify
330
            return chroot_server.get_url() + relpath
6402.3.1 by Jelmer Vernooij
Add safe_open class to bzr.
331
332
        return urlutils.URL.from_string(chroot_server.get_url()).scheme, get_url
333
334
    def test_stacked_within_scheme(self):
335
        # A branch that is stacked on a URL of the same scheme is safe to
336
        # open.
337
        self.get_transport().mkdir('inside')
338
        self.make_branch('inside/stacked')
339
        self.make_branch('inside/stacked-on')
340
        scheme, get_chrooted_url = self.get_chrooted_scheme('inside')
341
        Branch.open(get_chrooted_url('stacked')).set_stacked_on_url(
342
            get_chrooted_url('stacked-on'))
343
        safe_open(scheme, get_chrooted_url('stacked'))
344
345
    def test_stacked_outside_scheme(self):
346
        # A branch that is stacked on a URL that is not of the same scheme is
347
        # not safe to open.
348
        self.get_transport().mkdir('inside')
349
        self.get_transport().mkdir('outside')
350
        self.make_branch('inside/stacked')
351
        self.make_branch('outside/stacked-on')
352
        scheme, get_chrooted_url = self.get_chrooted_scheme('inside')
353
        Branch.open(get_chrooted_url('stacked')).set_stacked_on_url(
354
            self.get_url('outside/stacked-on'))
355
        self.assertRaises(
356
            BadUrl, safe_open, scheme, get_chrooted_url('stacked'))