/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to mandos-ctl

  • Committer: Teddy Hogeborn
  • Date: 2019-08-03 12:40:59 UTC
  • mfrom: (1144 trunk)
  • mto: This revision was merged to the branch mainline in revision 1145.
  • Revision ID: teddy@recompile.se-20190803124059-z12hb7q97uc74ydk
MergeĀ fromĀ trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python
2
 
# -*- mode: python; coding: utf-8; after-save-hook: (lambda () (let ((command (if (and (boundp 'tramp-file-name-structure) (string-match (car tramp-file-name-structure) (buffer-file-name))) (tramp-file-name-localname (tramp-dissect-file-name (buffer-file-name))) (buffer-file-name)))) (if (= (shell-command (format "%s --check" (shell-quote-argument command)) "*Test*") 0) (let ((w (get-buffer-window "*Test*"))) (if w (delete-window w)) (kill-buffer "*Test*")) (display-buffer "*Test*")))); -*-
 
2
# -*- after-save-hook: (lambda () (let ((command (if (fboundp 'file-local-name) (file-local-name (buffer-file-name)) (or (file-remote-p (buffer-file-name) 'localname) (buffer-file-name))))) (if (= (progn (if (get-buffer "*Test*") (kill-buffer "*Test*")) (process-file-shell-command (format "%s --check" (shell-quote-argument command)) nil "*Test*")) 0) (let ((w (get-buffer-window "*Test*"))) (if w (delete-window w))) (progn (with-current-buffer "*Test*" (compilation-mode)) (display-buffer "*Test*" '(display-buffer-in-side-window)))))); coding: utf-8 -*-
3
3
#
4
4
# Mandos Monitor - Control and monitor the Mandos server
5
5
#
78
78
 
79
79
locale.setlocale(locale.LC_ALL, "")
80
80
 
81
 
version = "1.8.3"
 
81
version = "1.8.5"
82
82
 
83
83
 
84
84
def main():
250
250
def rfc3339_duration_to_delta(duration):
251
251
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
252
252
 
253
 
    >>> rfc3339_duration_to_delta("P7D")
254
 
    datetime.timedelta(7)
255
 
    >>> rfc3339_duration_to_delta("PT60S")
256
 
    datetime.timedelta(0, 60)
257
 
    >>> rfc3339_duration_to_delta("PT60M")
258
 
    datetime.timedelta(0, 3600)
259
 
    >>> rfc3339_duration_to_delta("P60M")
260
 
    datetime.timedelta(1680)
261
 
    >>> rfc3339_duration_to_delta("PT24H")
262
 
    datetime.timedelta(1)
263
 
    >>> rfc3339_duration_to_delta("P1W")
264
 
    datetime.timedelta(7)
265
 
    >>> rfc3339_duration_to_delta("PT5M30S")
266
 
    datetime.timedelta(0, 330)
267
 
    >>> rfc3339_duration_to_delta("P1DT3M20S")
268
 
    datetime.timedelta(1, 200)
 
253
    >>> rfc3339_duration_to_delta("P7D") == datetime.timedelta(7)
 
254
    True
 
255
    >>> rfc3339_duration_to_delta("PT60S") == datetime.timedelta(0, 60)
 
256
    True
 
257
    >>> rfc3339_duration_to_delta("PT60M") == datetime.timedelta(hours=1)
 
258
    True
 
259
    >>> # 60 months
 
260
    >>> rfc3339_duration_to_delta("P60M") == datetime.timedelta(1680)
 
261
    True
 
262
    >>> rfc3339_duration_to_delta("PT24H") == datetime.timedelta(1)
 
263
    True
 
264
    >>> rfc3339_duration_to_delta("P1W") == datetime.timedelta(7)
 
265
    True
 
266
    >>> rfc3339_duration_to_delta("PT5M30S") == datetime.timedelta(0, 330)
 
267
    True
 
268
    >>> rfc3339_duration_to_delta("P1DT3M20S") == datetime.timedelta(1, 200)
 
269
    True
269
270
    >>> # Can not be empty:
270
271
    >>> rfc3339_duration_to_delta("")
271
272
    Traceback (most recent call last):
381
382
    """Parse an interval string as documented by Mandos before 1.6.1,
382
383
    and return a datetime.timedelta
383
384
 
384
 
    >>> parse_pre_1_6_1_interval('7d')
385
 
    datetime.timedelta(7)
386
 
    >>> parse_pre_1_6_1_interval('60s')
387
 
    datetime.timedelta(0, 60)
388
 
    >>> parse_pre_1_6_1_interval('60m')
389
 
    datetime.timedelta(0, 3600)
390
 
    >>> parse_pre_1_6_1_interval('24h')
391
 
    datetime.timedelta(1)
392
 
    >>> parse_pre_1_6_1_interval('1w')
393
 
    datetime.timedelta(7)
394
 
    >>> parse_pre_1_6_1_interval('5m 30s')
395
 
    datetime.timedelta(0, 330)
396
 
    >>> parse_pre_1_6_1_interval('')
397
 
    datetime.timedelta(0)
 
385
    >>> parse_pre_1_6_1_interval('7d') == datetime.timedelta(days=7)
 
386
    True
 
387
    >>> parse_pre_1_6_1_interval('60s') == datetime.timedelta(0, 60)
 
388
    True
 
389
    >>> parse_pre_1_6_1_interval('60m') == datetime.timedelta(hours=1)
 
390
    True
 
391
    >>> parse_pre_1_6_1_interval('24h') == datetime.timedelta(days=1)
 
392
    True
 
393
    >>> parse_pre_1_6_1_interval('1w') == datetime.timedelta(days=7)
 
394
    True
 
395
    >>> parse_pre_1_6_1_interval('5m 30s') == datetime.timedelta(0, 330)
 
396
    True
 
397
    >>> parse_pre_1_6_1_interval('') == datetime.timedelta(0)
 
398
    True
398
399
    >>> # Ignore unknown characters, allow any order and repetitions
399
 
    >>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m')
400
 
    datetime.timedelta(2, 480, 18000)
 
400
    >>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m') == datetime.timedelta(2, 480, 18000)
 
401
    True
401
402
 
402
403
    """
403
404
 
571
572
                        for key, subval in value.items()}
572
573
            return value
573
574
 
 
575
        def set_client_property(self, objectpath, key, value):
 
576
            if key == "Secret":
 
577
                if not isinstance(value, bytes):
 
578
                    value = value.encode("utf-8")
 
579
                value = self.dbus_python.ByteArray(value)
 
580
            return self.set_property(self.busname, objectpath,
 
581
                                     self.client_interface, key,
 
582
                                     value)
574
583
 
575
584
    class SilenceLogger(object):
576
585
        "Simple context manager to silence a particular logger"
1312
1321
                @staticmethod
1313
1322
                def get_object(busname, objectpath):
1314
1323
                    DBusObject = collections.namedtuple(
1315
 
                        "DBusObject", ("methodname",))
 
1324
                        "DBusObject", ("methodname", "Set"))
1316
1325
                    def method(*args, **kwargs):
1317
1326
                        self.assertEqual({"dbus_interface":
1318
1327
                                          "interface"},
1319
1328
                                         kwargs)
1320
1329
                        return func(*args)
1321
 
                    return DBusObject(methodname=method)
 
1330
                    def set_property(interface, key, value,
 
1331
                                     dbus_interface=None):
 
1332
                        self.assertEqual(
 
1333
                            "org.freedesktop.DBus.Properties",
 
1334
                            dbus_interface)
 
1335
                        self.assertEqual("Secret", key)
 
1336
                        return func(interface, key, value,
 
1337
                                    dbus_interface=dbus_interface)
 
1338
                    return DBusObject(methodname=method,
 
1339
                                      Set=set_property)
1322
1340
            class Boolean(object):
1323
1341
                def __init__(self, value):
1324
1342
                    self.value = bool(value)
1330
1348
                pass
1331
1349
            class Dictionary(dict):
1332
1350
                pass
 
1351
            class ByteArray(bytes):
 
1352
                pass
1333
1353
        return mock_dbus_python
1334
1354
 
1335
1355
    def call_method(self, bus, methodname, busname, objectpath,
1512
1532
        # Make sure the dbus logger was suppressed
1513
1533
        self.assertEqual(0, counting_handler.count)
1514
1534
 
 
1535
    def test_Set_Secret_sends_bytearray(self):
 
1536
        ret = [None]
 
1537
        def func(*args, **kwargs):
 
1538
            ret[0] = (args, kwargs)
 
1539
        mock_dbus_python = self.MockDBusPython_func(func)
 
1540
        bus = dbus_python_adapter.SystemBus(mock_dbus_python)
 
1541
        bus.set_client_property("objectpath", "Secret", "value")
 
1542
        expected_call = (("se.recompile.Mandos.Client", "Secret",
 
1543
                          mock_dbus_python.ByteArray(b"value")),
 
1544
                         {"dbus_interface":
 
1545
                          "org.freedesktop.DBus.Properties"})
 
1546
        self.assertEqual(expected_call, ret[0])
 
1547
        if sys.version_info.major == 2:
 
1548
            self.assertIsInstance(ret[0][0][-1],
 
1549
                                  mock_dbus_python.ByteArray)
 
1550
 
1515
1551
    def test_get_object_converts_to_correct_exception(self):
1516
1552
        bus = dbus_python_adapter.SystemBus(
1517
1553
            self.fake_dbus_python_raises_exception_on_connect)
1745
1781
        self.assert_command_from_args(["--is-enabled", "client"],
1746
1782
                                      command.IsEnabled)
1747
1783
 
1748
 
    def assert_command_from_args(self, args, command_cls,
1749
 
                                 **cmd_attrs):
 
1784
    def assert_command_from_args(self, args, command_cls, length=1,
 
1785
                                 clients=None, **cmd_attrs):
1750
1786
        """Assert that parsing ARGS should result in an instance of
1751
1787
COMMAND_CLS with (optionally) all supplied attributes (CMD_ATTRS)."""
1752
1788
        options = self.parser.parse_args(args)
1753
1789
        check_option_syntax(self.parser, options)
1754
1790
        commands = commands_from_options(options)
1755
 
        self.assertEqual(1, len(commands))
1756
 
        command = commands[0]
1757
 
        self.assertIsInstance(command, command_cls)
 
1791
        self.assertEqual(length, len(commands))
 
1792
        for command in commands:
 
1793
            if isinstance(command, command_cls):
 
1794
                break
 
1795
        else:
 
1796
            self.assertIsInstance(command, command_cls)
 
1797
        if clients is not None:
 
1798
            self.assertEqual(clients, options.client)
1758
1799
        for key, value in cmd_attrs.items():
1759
1800
            self.assertEqual(value, getattr(command, key))
1760
1801
 
 
1802
    def assert_commands_from_args(self, args, commands, clients=None):
 
1803
        for cmd in commands:
 
1804
            self.assert_command_from_args(args, cmd,
 
1805
                                          length=len(commands),
 
1806
                                          clients=clients)
 
1807
 
1761
1808
    def test_is_enabled_short(self):
1762
1809
        self.assert_command_from_args(["-V", "client"],
1763
1810
                                      command.IsEnabled)
1954
2001
                                      verbose=True)
1955
2002
 
1956
2003
 
 
2004
    def test_manual_page_example_1(self):
 
2005
        self.assert_command_from_args("",
 
2006
                                      command.PrintTable,
 
2007
                                      clients=[],
 
2008
                                      verbose=False)
 
2009
 
 
2010
    def test_manual_page_example_2(self):
 
2011
        self.assert_command_from_args(
 
2012
            "--verbose foo1.example.org foo2.example.org".split(),
 
2013
            command.PrintTable, clients=["foo1.example.org",
 
2014
                                         "foo2.example.org"],
 
2015
            verbose=True)
 
2016
 
 
2017
    def test_manual_page_example_3(self):
 
2018
        self.assert_command_from_args("--enable --all".split(),
 
2019
                                      command.Enable,
 
2020
                                      clients=[])
 
2021
 
 
2022
    def test_manual_page_example_4(self):
 
2023
        self.assert_commands_from_args(
 
2024
            ("--timeout=PT5M --interval=PT1M foo1.example.org"
 
2025
             " foo2.example.org").split(),
 
2026
            [command.SetTimeout, command.SetInterval],
 
2027
            clients=["foo1.example.org", "foo2.example.org"])
 
2028
 
 
2029
    def test_manual_page_example_5(self):
 
2030
        self.assert_command_from_args("--approve --all".split(),
 
2031
                                      command.Approve,
 
2032
                                      clients=[])
 
2033
 
 
2034
 
1957
2035
class TestCommand(unittest.TestCase):
1958
2036
    """Abstract class for tests of command classes"""
1959
2037