~ubuntu-branches/debian/sid/aptdaemon/sid

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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Provides unit tests for the APT worker."""
# Copyright (C) 2011 Sebastian Heinlein <devel@glatzor.de>
#
# Licensed under the GNU General Public License Version 2
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# Licensed under the GNU General Public License Version 2

__author__  = "Sebastian Heinlein <devel@glatzor.de>"

import glob
import os
import shutil
import stat
import sys
import unittest

import apt_pkg
from gi.repository import GObject
import dbus

import aptdaemon.test
from aptdaemon.worker import AptWorker
from aptdaemon.core import Transaction
from aptdaemon import enums, errors

REPO_PATH = os.path.join(aptdaemon.test.get_tests_dir(), "repo")


class MockQueue(object):

    """A fake TransactionQueue which only provides a limbo attribute."""

    def __init__(self):
        self.limbo = {}


class WorkerTestCase(aptdaemon.test.AptDaemonTestCase):

    """Test suite for the worker which performs the actual package
    installation and removal."""

    def setUp(self):
        self.chroot = aptdaemon.test.Chroot()
        self.chroot.setup()
        self.addCleanup(self.chroot.remove)
        self.start_dbus_daemon()
        self.dbus = dbus.bus.BusConnection(self.dbus_address)
        self.loop = GObject.MainLoop()
        self.queue = MockQueue()
        self.worker = AptWorker(chroot=self.chroot.path, load_plugins=False)
        self.worker.connect("transaction-done", lambda w,t: self.loop.quit())
        self.worker.connect("transaction-simulated",
                            lambda w,t: self.loop.quit())

    def test_update_cache(self):
        """Test updating the cache using a local repository."""
        # Add a working and a non-working repository
        self.chroot.add_trusted_key()
        path = os.path.join(self.chroot.path,
                            "etc/apt/sources.list.d/test.list")
        with open(path, "w") as part_file:
            part_file.write("deb file://%s ./" % REPO_PATH)
        self.chroot.add_repository("/does/not/exist", copy_list=False)
        # Only update the repository from the working snippet
        trans = Transaction(None, enums.ROLE_UPDATE_CACHE,
                            self.queue, os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus,
                            kwargs={"sources_list": "test.list"})
        self.worker.simulate(trans)
        self.loop.run()
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_SUCCESS,
                         "%s: %s" % (trans._error_property[0],
                                     trans._error_property[1]))
        self.worker._cache.open()
        self.assertEqual(len(self.worker._cache), 9)
        pkg = self.worker._cache["silly-base"]
        self.assertTrue(pkg.candidate.origins[0].trusted)

    def test_upgrade_system(self):
        """Test upgrading the system."""
        self.chroot.add_test_repository()
        self.chroot.install_debfile(os.path.join(REPO_PATH,
                                                 "silly-base_0.1-0_all.deb"))
        # Install the package
        trans = Transaction(None, enums.ROLE_UPGRADE_SYSTEM,
                            self.queue, os.getpid(),
                            os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus,
                            kwargs={"safe_mode": False})
        self.worker.simulate(trans)
        self.loop.run()
        self.assertEqual(trans.depends[enums.PKGS_UPGRADE],
                         ["silly-base=0.1-0update1"])
        self.assertTrue(trans.space > 0)
        self.assertTrue(trans.download == 0)
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_SUCCESS,
                         "%s: %s" % (trans._error_property[0],
                                     trans._error_property[1]))
        self.worker._cache.open()
        # Test apt history log
        with open(os.path.join(self.chroot.path, "var/log/apt/history.log")) \
                as history_file:
            history = history_file.read()
        self.assertTrue("Commandline: aptdaemon role='%s'" % trans.role in
                        history)

        self.assertEqual(self.worker._cache["silly-base"].installed.version,
                         "0.1-0update1")

    def test_check_unauth(self):
        """Test if packages from an unauthenticated repo are detected."""
        self.chroot.add_test_repository(copy_sig=False)
        # Install the package
        trans = Transaction(None, enums.ROLE_INSTALL_PACKAGES, self.queue,
                            os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus,
                            packages=[["silly-base"],[],[],[],[], []])
        self.worker.simulate(trans)
        self.loop.run()
        trans.allow_unauthenticated = False
        self.assertEqual(trans.unauthenticated, ["silly-base"])
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_FAILED)
        self.assertEqual(trans.error.code, enums.ERROR_PACKAGE_UNAUTHENTICATED)

        # Allow installation of unauthenticated packages
        trans = Transaction(None, enums.ROLE_INSTALL_PACKAGES, self.queue,
                            os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus,
                            packages=[["silly-base"],[],[],[],[], []])
        trans.allow_unauthenticated = True
        self.worker.simulate(trans)
        self.loop.run()
        self.assertEqual(trans.unauthenticated, ["silly-base"])
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_SUCCESS,
                         "%s: %s" % (trans._error_property[0],
                                     trans._error_property[1]))
        self.worker._cache.open()
        self.assertTrue(self.worker._cache["silly-base"].is_installed)

    def test_install(self):
        """Test installation of a package from a repository."""
        self.chroot.add_test_repository()
        # Install the package
        trans = Transaction(None, enums.ROLE_INSTALL_PACKAGES, self.queue,
                            os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus,
                            packages=[["silly-depend-base"],[],[],[],[], []])
        self.worker.simulate(trans)
        self.loop.run()
        self.assertEqual(trans.depends[enums.PKGS_INSTALL],
                         ["silly-base=0.1-0update1"])
        self.assertTrue(trans.space > 0)
        self.assertTrue(trans.download == 0)
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_SUCCESS,
                         "%s: %s" % (trans._error_property[0],
                                     trans._error_property[1]))
        self.worker._cache.open()
        self.assertTrue(self.worker._cache["silly-depend-base"].is_installed)

    def test_remove_obsolete(self):
        """Test the removal of obsoleted packages."""
        for pkg in ["silly-base_0.1-0_all.deb",
                    "silly-depend-base_0.1-0_all.deb"]:
            self.chroot.install_debfile(os.path.join(REPO_PATH, pkg))
        ext_states = apt_pkg.config.find_file("Dir::State::extended_states")
        with open(ext_states, "w") as ext_states_file:
            ext_states_file.write("""Package: silly-base
Architecture: all
Auto-Installed: 1""")
        trans = Transaction(None, enums.ROLE_REMOVE_PACKAGES, self.queue,
                            os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus,
                            packages=[[],[],["silly-depend-base"],[],[],[]])
        trans.remove_obsoleted_depends = True
        self.worker.simulate(trans)
        self.loop.run()
        self.assertEqual(trans.depends[enums.PKGS_REMOVE],
                         ["silly-base=0.1-0"])
        self.assertTrue(trans.space < 0)
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_SUCCESS,
                         "%s: %s" % (trans._error_property[0],
                                     trans._error_property[1]))
        self.worker._cache.open()
        self.assertFalse("silly-base" in self.worker._cache)
        self.assertFalse("silly-depend-base" in self.worker._cache)

    def test_remove(self):
        """Test the removal of packages."""
        for pkg in ["silly-base_0.1-0_all.deb", "silly-essential_0.1-0_all.deb",
                    "silly-depend-base_0.1-0_all.deb"]:
            self.chroot.install_debfile(os.path.join(REPO_PATH, pkg))
        trans = Transaction(None, enums.ROLE_REMOVE_PACKAGES, self.queue,
                            os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus,
                            packages=[[],[],["silly-base"],[],[],[]])
        self.worker.simulate(trans)
        self.loop.run()
        self.assertEqual(trans.depends[enums.PKGS_REMOVE],
                         ["silly-depend-base=0.1-0"])
        self.assertTrue(trans.space < 0)
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_SUCCESS,
                         "%s: %s" % (trans._error_property[0],
                                     trans._error_property[1]))
        self.worker._cache.open()
        try:
            installed = self.worker._cache["silly-depend-base"].is_installed
            self.assertFalse(installed)
        except KeyError:
            pass
        # Don't allow to remove essential packages
        trans = Transaction(None, enums.ROLE_REMOVE_PACKAGES, self.queue,
                            os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus,
                            packages=[[],[],["silly-essential"],[],[],[]])
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_FAILED,
                         "Allowed to remove an essential package")
        self.assertEqual(trans.error.code,
                         enums.ERROR_NOT_REMOVE_ESSENTIAL_PACKAGE,
                         "Allowed to remove an essential package")

    def test_downgrade(self):
        """Test downgrading of packages."""
        self.chroot.add_test_repository()
        pkg = os.path.join(REPO_PATH, "silly-base_0.1-0update1_all.deb")
        self.chroot.install_debfile(pkg)
        trans = Transaction(None, enums.ROLE_COMMIT_PACKAGES, self.queue,
                            os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus,
                            packages=[[],[],[],[],[],["silly-base=0.1-0"]])
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_SUCCESS,
                         "%s: %s" % (trans._error_property[0],
                                     trans._error_property[1]))
        self.worker._cache.open()
        self.assertEqual(self.worker._cache["silly-base"].installed.version,
                         "0.1-0", "Failed to downgrade.")

    def test_purge(self):
        """Test the purging of packages."""
        for pkg in ["silly-base_0.1-0_all.deb", "silly-config_0.1-0_all.deb"]:
            self.chroot.install_debfile(os.path.join(REPO_PATH, pkg))
        trans = Transaction(None, enums.ROLE_REMOVE_PACKAGES, self.queue,
                            os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus,
                            packages=[[],[],[],["silly-config"],[],[]])
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_SUCCESS,
                         "%s: %s" % (trans._error_property[0],
                                     trans._error_property[1]))
        self.assertFalse(os.path.exists(os.path.join(self.chroot.path,
                                                     "etc/silly-packages.cfg")),
                         "Configuration file wasn't removed.")

    def test_install_file(self):
        """Test the installation of a local package file."""
        # add custom lintian file
        target = os.path.join(self.chroot.path, "usr", "share", "aptdaemon")
        os.makedirs(target)
        for tags_file in glob.glob(os.path.join(aptdaemon.test.get_tests_dir(),
                                                "../data/lintian*tags*")):
            shutil.copy(tags_file, target)
        # test
        self.chroot.add_test_repository()
        pkg = os.path.join(
            REPO_PATH, "silly-depend-base-lintian-broken_0.1-0_all.deb")
        trans = Transaction(None, enums.ROLE_INSTALL_FILE, self.queue,
                            os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus,
                            kwargs={"path": os.path.join(REPO_PATH, pkg),
                                    "force": False})
        self.worker.simulate(trans)
        self.loop.run()
        self.assertEqual(trans.error.code, enums.ERROR_INVALID_PACKAGE_FILE,
                         "Lintian failed to detect a broken package")
        # Now allow to install invalid packages
        trans.kwargs["force"] = True
        self.worker.simulate(trans)
        self.loop.run()
        self.assertEqual(trans.depends[enums.PKGS_INSTALL],
                         ["silly-base=0.1-0update1"])
        self.assertTrue(trans.space > 0)
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_SUCCESS,
                         "%s: %s" % (trans._error_property[0],
                                     trans._error_property[1]))
        self.worker._cache.open()
        self.assertTrue(self.worker._cache["silly-depend-base-lintian-broken"].is_installed)

    def test_install_unknown_file(self):
        """Test the installation of a local package file which is not known
        to the cache.

        Regression test for LP #702217
        """
        pkg = os.path.join(REPO_PATH, "silly-base_0.1-0_all.deb")
        trans = Transaction(None, enums.ROLE_INSTALL_FILE, self.queue,
                            os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus,
                            kwargs={"path": os.path.join(REPO_PATH, pkg),
                                    "force": True})
        self.worker.simulate(trans)
        self.loop.run()
        self.assertEqual(trans.packages, (["silly-base"], [], [], [], [], []))
        self.assertTrue(trans.space > 0)
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_SUCCESS,
                         "%s: %s" % (trans._error_property[0],
                                     trans._error_property[1]))
        self.worker._cache.open()
        self.assertTrue(self.worker._cache["silly-base"].is_installed)

    def test_fix_broken_depends(self):
        """Test the fixing of broken dependencies."""
        for pkg in ["silly-base_0.1-0_all.deb", "silly-broken_0.1-0_all.deb"]:
            self.chroot.install_debfile(os.path.join(REPO_PATH, pkg), True)
        trans = Transaction(None, enums.ROLE_FIX_BROKEN_DEPENDS, self.queue,
                            os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test", bus=self.dbus)
        self.worker.simulate(trans)
        self.loop.run()
        self.assertEqual(trans.depends[enums.PKGS_REMOVE],
                         ["silly-broken=0.1-0"])
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_SUCCESS,
                         "%s: %s" % (trans._error_property[0],
                                     trans._error_property[1]))
        self.worker._cache.open()
        self.assertEqual(self.worker._cache.broken_count, 0)

    def test_add_license_key_unsecure(self):
        """Test if we refuse to install license key files to an unsecure
        location or binaries."""
        self.chroot.add_test_repository(copy_sig=False)
        # Should fail because of an untrusted source
        license_key = "NASTY_BLOB"
        license_key_path = "/opt/silly-license/NASTY.KEY"
        pkg_name = "silly-license"
        self.assertRaises(errors.TransactionFailed,
                          self.worker._add_license_key_to_system,
                          pkg_name, license_key, license_key_path)
        # Check if we don't allow to install executables
        with open("/bin/ls", "r") as sample_exec:
            license_key = sample_exec.read()
        pkg_name = "silly-license"
        self.assertRaises(errors.TransactionFailed,
                          self.worker._add_license_key_to_system,
                          pkg_name, license_key, license_key_path)
 
    def test_add_license_key(self):
        """Test the installation of license key files."""
        license_key = "Bli bla blub, I am a nasty BLOB!"
        license_path = "/opt/silly-license/NASTY.KEY"
        def get_license_key_mock(uid, pkg, oauth, server):
            return license_key, license_path
        self.chroot.add_test_repository()
        trans = Transaction(None, enums.ROLE_ADD_LICENSE_KEY, self.queue,
                            os.getpid(), os.getuid(), sys.argv[0],
                            "org.debian.apt.test",
                            kwargs={"pkg_name": "silly-license",
                                    "json_token": "lalelu",
                                    "server_name": "mock"},
                            bus=self.dbus)
        os.makedirs(os.path.join(aptdaemon.worker.apt_pkg.config["Dir"],
                                 "opt/silly-license/"))
        self.worker.plugins["get_license_key"] = [get_license_key_mock]
        self.worker.run(trans)
        self.loop.run()
        self.assertEqual(trans.exit, enums.EXIT_SUCCESS,
                         "%s: %s" % (trans._error_property[0],
                                     trans._error_property[1]))
         # Check the content of the installed key
        verify_path = os.path.join(aptdaemon.worker.apt_pkg.config["Dir"],
                                   license_path[1:])
        self.assertEqual(license_key, open(verify_path).read(),
                         "Content of license key doesn't match")

    def test_use_apt_auth_conf(self):
        """Test if credentials of repositories are store securely in a
        separate file.
        """
        from mock import Mock

        source_file_name = "private_source.list"
        self.worker.add_repository(Mock(), "deb",
                                   "https://user:pass@host.example.com/path",
                                   "natty", ["main"], "comment",
                                   source_file_name)
        # check if password was stripped (source file)
        source_parts = apt_pkg.config.find_dir("Dir::Etc::sourceparts")
        source_file_path = os.path.join(source_parts,
                                        source_file_name)
        with open(source_file_path) as source_file:
            source_file_content = source_file.read()
        self.assertFalse("user:pass" in source_file_content)
        # check if password was stored correctly (auth.conf)
        auth_file_path = apt_pkg.config.find_file("Dir::Etc::netrc")
        with open(auth_file_path) as auth_file:
            auth_file_content = auth_file.read()
        self.assertTrue("login user" in auth_file_content)
        self.assertTrue("password pass" in auth_file_content)
        self.assertTrue("machine host.example.com/path" in auth_file_content)
        buf = os.stat(auth_file_path)
        self.assertEqual(stat.S_IMODE(buf.st_mode), 0640)


if __name__ == "__main__":
    unittest.main()

# vim: ts=4 et sts=4