/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos-ctl

  • Committer: Teddy Hogeborn
  • Date: 2019-03-03 14:04:14 UTC
  • mto: (237.7.594 trunk)
  • mto: This revision was merged to the branch mainline in revision 382.
  • Revision ID: teddy@recompile.se-20190303140414-4jspvi9mi83f9cpl
mandos-ctl: Refactor

* mandos-ctl (Command.run): Take a "mandos" argument and save it.
  (PrintCmd.run): Take, but ignore, a "mandos" argument.
  (RemoveCmd.__init__): Remove.
  (main): Don't pass mandos_serv to RemoveCmd constructor.  Instead,
          always pass mandos_serv to command.run().

Show diffs side-by-side

added added

removed removed

Lines of Context:
42
42
import json
43
43
import unittest
44
44
import logging
45
 
import io
46
 
import tempfile
47
 
import contextlib
48
45
 
49
46
import dbus
50
47
 
271
268
    return value
272
269
 
273
270
 
 
271
class TableOfClients(object):
 
272
    tableheaders = {
 
273
        "Name": "Name",
 
274
        "Enabled": "Enabled",
 
275
        "Timeout": "Timeout",
 
276
        "LastCheckedOK": "Last Successful Check",
 
277
        "LastApprovalRequest": "Last Approval Request",
 
278
        "Created": "Created",
 
279
        "Interval": "Interval",
 
280
        "Host": "Host",
 
281
        "Fingerprint": "Fingerprint",
 
282
        "KeyID": "Key ID",
 
283
        "CheckerRunning": "Check Is Running",
 
284
        "LastEnabled": "Last Enabled",
 
285
        "ApprovalPending": "Approval Is Pending",
 
286
        "ApprovedByDefault": "Approved By Default",
 
287
        "ApprovalDelay": "Approval Delay",
 
288
        "ApprovalDuration": "Approval Duration",
 
289
        "Checker": "Checker",
 
290
        "ExtendedTimeout": "Extended Timeout",
 
291
        "Expires": "Expires",
 
292
        "LastCheckerStatus": "Last Checker Status",
 
293
    }
 
294
 
 
295
    def __init__(self, clients, keywords, tableheaders=None):
 
296
        self.clients = clients
 
297
        self.keywords = keywords
 
298
        if tableheaders is not None:
 
299
            self.tableheaders = tableheaders
 
300
 
 
301
    def __str__(self):
 
302
        return "\n".join(self.rows())
 
303
 
 
304
    if sys.version_info.major == 2:
 
305
        __unicode__ = __str__
 
306
        def __str__(self):
 
307
            return str(self).encode(locale.getpreferredencoding())
 
308
 
 
309
    def rows(self):
 
310
        format_string = self.row_formatting_string()
 
311
        rows = [self.header_line(format_string)]
 
312
        rows.extend(self.client_line(client, format_string)
 
313
                    for client in self.clients)
 
314
        return rows
 
315
 
 
316
    def row_formatting_string(self):
 
317
        "Format string used to format table rows"
 
318
        return " ".join("{{{key}:{width}}}".format(
 
319
            width=max(len(self.tableheaders[key]),
 
320
                      *(len(self.string_from_client(client, key))
 
321
                        for client in self.clients)),
 
322
            key=key)
 
323
                        for key in self.keywords)
 
324
 
 
325
    def string_from_client(self, client, key):
 
326
        return self.valuetostring(client[key], key)
 
327
 
 
328
    @staticmethod
 
329
    def valuetostring(value, keyword):
 
330
        if isinstance(value, dbus.Boolean):
 
331
            return "Yes" if value else "No"
 
332
        if keyword in ("Timeout", "Interval", "ApprovalDelay",
 
333
                       "ApprovalDuration", "ExtendedTimeout"):
 
334
            return milliseconds_to_string(value)
 
335
        return str(value)
 
336
 
 
337
    def header_line(self, format_string):
 
338
        return format_string.format(**self.tableheaders)
 
339
 
 
340
    def client_line(self, client, format_string):
 
341
        return format_string.format(
 
342
            **{key: self.string_from_client(client, key)
 
343
               for key in self.keywords})
 
344
 
 
345
 
274
346
## Classes for commands.
275
347
 
276
348
# Abstract classes first
281
353
        commands which want to operate on all clients at the same time
282
354
        can override this run() method instead."""
283
355
        self.mandos = mandos
284
 
        for client, properties in clients.items():
285
 
            self.run_on_one_client(client, properties)
 
356
        for client in clients:
 
357
            self.run_on_one_client(client)
286
358
 
287
359
class PrintCmd(Command):
288
360
    """Abstract class for commands printing client details"""
298
370
 
299
371
class PropertyCmd(Command):
300
372
    """Abstract class for Actions for setting one client property"""
301
 
    def run_on_one_client(self, client, properties):
 
373
    def run_on_one_client(self, client):
302
374
        """Set the Client's D-Bus property"""
303
375
        client.Set(client_interface, self.property, self.value_to_set,
304
376
                   dbus_interface=dbus.PROPERTIES_IFACE)
317
389
    @value_to_set.setter
318
390
    def value_to_set(self, value):
319
391
        """When setting, convert value to a datetime.timedelta"""
320
 
        self._vts = int(round(value.total_seconds() * 1000))
 
392
        self._vts = string_to_delta(value).total_seconds() * 1000
321
393
 
322
394
# Actual (non-abstract) command classes
323
395
 
324
396
class PrintTableCmd(PrintCmd):
325
397
    def __init__(self, verbose=False):
326
398
        self.verbose = verbose
327
 
 
328
399
    def output(self, clients):
329
 
        default_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
330
 
        keywords = default_keywords
331
400
        if self.verbose:
332
401
            keywords = self.all_keywords
333
 
        return str(self.TableOfClients(clients.values(), keywords))
334
 
 
335
 
    class TableOfClients(object):
336
 
        tableheaders = {
337
 
            "Name": "Name",
338
 
            "Enabled": "Enabled",
339
 
            "Timeout": "Timeout",
340
 
            "LastCheckedOK": "Last Successful Check",
341
 
            "LastApprovalRequest": "Last Approval Request",
342
 
            "Created": "Created",
343
 
            "Interval": "Interval",
344
 
            "Host": "Host",
345
 
            "Fingerprint": "Fingerprint",
346
 
            "KeyID": "Key ID",
347
 
            "CheckerRunning": "Check Is Running",
348
 
            "LastEnabled": "Last Enabled",
349
 
            "ApprovalPending": "Approval Is Pending",
350
 
            "ApprovedByDefault": "Approved By Default",
351
 
            "ApprovalDelay": "Approval Delay",
352
 
            "ApprovalDuration": "Approval Duration",
353
 
            "Checker": "Checker",
354
 
            "ExtendedTimeout": "Extended Timeout",
355
 
            "Expires": "Expires",
356
 
            "LastCheckerStatus": "Last Checker Status",
357
 
        }
358
 
 
359
 
        def __init__(self, clients, keywords, tableheaders=None):
360
 
            self.clients = clients
361
 
            self.keywords = keywords
362
 
            if tableheaders is not None:
363
 
                self.tableheaders = tableheaders
364
 
 
365
 
        def __str__(self):
366
 
            return "\n".join(self.rows())
367
 
 
368
 
        if sys.version_info.major == 2:
369
 
            __unicode__ = __str__
370
 
            def __str__(self):
371
 
                return str(self).encode(locale.getpreferredencoding())
372
 
 
373
 
        def rows(self):
374
 
            format_string = self.row_formatting_string()
375
 
            rows = [self.header_line(format_string)]
376
 
            rows.extend(self.client_line(client, format_string)
377
 
                        for client in self.clients)
378
 
            return rows
379
 
 
380
 
        def row_formatting_string(self):
381
 
            "Format string used to format table rows"
382
 
            return " ".join("{{{key}:{width}}}".format(
383
 
                width=max(len(self.tableheaders[key]),
384
 
                          *(len(self.string_from_client(client, key))
385
 
                            for client in self.clients)),
386
 
                key=key)
387
 
                            for key in self.keywords)
388
 
 
389
 
        def string_from_client(self, client, key):
390
 
            return self.valuetostring(client[key], key)
391
 
 
392
 
        @staticmethod
393
 
        def valuetostring(value, keyword):
394
 
            if isinstance(value, dbus.Boolean):
395
 
                return "Yes" if value else "No"
396
 
            if keyword in ("Timeout", "Interval", "ApprovalDelay",
397
 
                           "ApprovalDuration", "ExtendedTimeout"):
398
 
                return milliseconds_to_string(value)
399
 
            return str(value)
400
 
 
401
 
        def header_line(self, format_string):
402
 
            return format_string.format(**self.tableheaders)
403
 
 
404
 
        def client_line(self, client, format_string):
405
 
            return format_string.format(
406
 
                **{key: self.string_from_client(client, key)
407
 
                   for key in self.keywords})
408
 
 
409
 
 
 
402
        else:
 
403
            keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
 
404
        return str(TableOfClients(clients.values(), keywords))
410
405
 
411
406
class DumpJSONCmd(PrintCmd):
412
407
    def output(self, clients):
422
417
        return value
423
418
 
424
419
class IsEnabledCmd(Command):
425
 
    def run_on_one_client(self, client, properties):
426
 
        if self.is_enabled(client, properties):
 
420
    def run_on_one_client(self, client):
 
421
        if self.is_enabled(client):
427
422
            sys.exit(0)
428
423
        sys.exit(1)
429
 
    def is_enabled(self, client, properties):
430
 
        return bool(properties["Enabled"])
 
424
    def is_enabled(self, client):
 
425
        return client.Get(client_interface, "Enabled",
 
426
                          dbus_interface=dbus.PROPERTIES_IFACE)
431
427
 
432
428
class RemoveCmd(Command):
433
 
    def run_on_one_client(self, client, properties):
 
429
    def run_on_one_client(self, client):
434
430
        self.mandos.RemoveClient(client.__dbus_object_path__)
435
431
 
436
432
class ApproveCmd(Command):
437
 
    def run_on_one_client(self, client, properties):
 
433
    def run_on_one_client(self, client):
438
434
        client.Approve(dbus.Boolean(True),
439
435
                       dbus_interface=client_interface)
440
436
 
441
437
class DenyCmd(Command):
442
 
    def run_on_one_client(self, client, properties):
 
438
    def run_on_one_client(self, client):
443
439
        client.Approve(dbus.Boolean(False),
444
440
                       dbus_interface=client_interface)
445
441
 
478
474
    property = "Host"
479
475
 
480
476
class SetSecretCmd(PropertyCmd, ValueArgumentMixIn):
481
 
    @property
482
 
    def value_to_set(self):
483
 
        return self._vts
484
 
    @value_to_set.setter
485
 
    def value_to_set(self, value):
486
 
        """When setting, read data from supplied file object"""
487
 
        self._vts = value.read()
488
 
        value.close()
489
477
    property = "Secret"
490
478
 
491
479
class SetTimeoutCmd(PropertyCmd, MillisecondsValueArgumentMixIn):
506
494
                             MillisecondsValueArgumentMixIn):
507
495
    property = "ApprovalDuration"
508
496
 
509
 
def add_command_line_options(parser):
 
497
def has_actions(options):
 
498
    return any((options.enable,
 
499
                options.disable,
 
500
                options.bump_timeout,
 
501
                options.start_checker,
 
502
                options.stop_checker,
 
503
                options.is_enabled,
 
504
                options.remove,
 
505
                options.checker is not None,
 
506
                options.timeout is not None,
 
507
                options.extended_timeout is not None,
 
508
                options.interval is not None,
 
509
                options.approved_by_default is not None,
 
510
                options.approval_delay is not None,
 
511
                options.approval_duration is not None,
 
512
                options.host is not None,
 
513
                options.secret is not None,
 
514
                options.approve,
 
515
                options.deny))
 
516
 
 
517
 
 
518
def main():
 
519
    parser = argparse.ArgumentParser()
510
520
    parser.add_argument("--version", action="version",
511
521
                        version="%(prog)s {}".format(version),
512
522
                        help="show version number and exit")
537
547
                        help="Remove client")
538
548
    parser.add_argument("-c", "--checker",
539
549
                        help="Set checker command for client")
540
 
    parser.add_argument("-t", "--timeout", type=string_to_delta,
 
550
    parser.add_argument("-t", "--timeout",
541
551
                        help="Set timeout for client")
542
 
    parser.add_argument("--extended-timeout", type=string_to_delta,
 
552
    parser.add_argument("--extended-timeout",
543
553
                        help="Set extended timeout for client")
544
 
    parser.add_argument("-i", "--interval", type=string_to_delta,
 
554
    parser.add_argument("-i", "--interval",
545
555
                        help="Set checker interval for client")
546
556
    approve_deny_default = parser.add_mutually_exclusive_group()
547
557
    approve_deny_default.add_argument(
552
562
        "--deny-by-default", action="store_false",
553
563
        dest="approved_by_default",
554
564
        help="Set client to be denied by default")
555
 
    parser.add_argument("--approval-delay", type=string_to_delta,
 
565
    parser.add_argument("--approval-delay",
556
566
                        help="Set delay before client approve/deny")
557
 
    parser.add_argument("--approval-duration", type=string_to_delta,
 
567
    parser.add_argument("--approval-duration",
558
568
                        help="Set duration of one client approval")
559
569
    parser.add_argument("-H", "--host", help="Set host for client")
560
570
    parser.add_argument("-s", "--secret",
569
579
    parser.add_argument("--check", action="store_true",
570
580
                        help="Run self-test")
571
581
    parser.add_argument("client", nargs="*", help="Client name")
572
 
 
573
 
 
574
 
def commands_from_options(options):
 
582
    options = parser.parse_args()
 
583
 
 
584
    if has_actions(options) and not (options.client or options.all):
 
585
        parser.error("Options require clients names or --all.")
 
586
    if options.verbose and has_actions(options):
 
587
        parser.error("--verbose can only be used alone.")
 
588
    if options.dump_json and (options.verbose
 
589
                              or has_actions(options)):
 
590
        parser.error("--dump-json can only be used alone.")
 
591
    if options.all and not has_actions(options):
 
592
        parser.error("--all requires an action.")
 
593
    if options.is_enabled and len(options.client) > 1:
 
594
            parser.error("--is-enabled requires exactly one client")
 
595
 
 
596
    try:
 
597
        bus = dbus.SystemBus()
 
598
        mandos_dbus_objc = bus.get_object(busname, server_path)
 
599
    except dbus.exceptions.DBusException:
 
600
        log.critical("Could not connect to Mandos server")
 
601
        sys.exit(1)
 
602
 
 
603
    mandos_serv = dbus.Interface(mandos_dbus_objc,
 
604
                                 dbus_interface=server_interface)
 
605
    mandos_serv_object_manager = dbus.Interface(
 
606
        mandos_dbus_objc, dbus_interface=dbus.OBJECT_MANAGER_IFACE)
575
607
 
576
608
    commands = []
577
609
 
585
617
        commands.append(DisableCmd())
586
618
 
587
619
    if options.bump_timeout:
588
 
        commands.append(BumpTimeoutCmd())
 
620
        commands.append(BumpTimeoutCmd(options.bump_timeout))
589
621
 
590
622
    if options.start_checker:
591
623
        commands.append(StartCheckerCmd())
600
632
        commands.append(RemoveCmd())
601
633
 
602
634
    if options.checker is not None:
603
 
        commands.append(SetCheckerCmd(options.checker))
 
635
        commands.append(SetCheckerCmd())
604
636
 
605
637
    if options.timeout is not None:
606
638
        commands.append(SetTimeoutCmd(options.timeout))
610
642
            SetExtendedTimeoutCmd(options.extended_timeout))
611
643
 
612
644
    if options.interval is not None:
613
 
        commands.append(SetIntervalCmd(options.interval))
 
645
        command.append(SetIntervalCmd(options.interval))
614
646
 
615
647
    if options.approved_by_default is not None:
616
648
        if options.approved_by_default:
617
 
            commands.append(ApproveByDefaultCmd())
 
649
            command.append(ApproveByDefaultCmd())
618
650
        else:
619
 
            commands.append(DenyByDefaultCmd())
 
651
            command.append(DenyByDefaultCmd())
620
652
 
621
653
    if options.approval_delay is not None:
622
 
        commands.append(SetApprovalDelayCmd(options.approval_delay))
 
654
        command.append(SetApprovalDelayCmd(options.approval_delay))
623
655
 
624
656
    if options.approval_duration is not None:
625
 
        commands.append(
 
657
        command.append(
626
658
            SetApprovalDurationCmd(options.approval_duration))
627
659
 
628
660
    if options.host is not None:
629
 
        commands.append(SetHostCmd(options.host))
 
661
        command.append(SetHostCmd(options.host))
630
662
 
631
663
    if options.secret is not None:
632
 
        commands.append(SetSecretCmd(options.secret))
 
664
        command.append(SetSecretCmd(options.secret))
633
665
 
634
666
    if options.approve:
635
667
        commands.append(ApproveCmd())
642
674
    if not commands:
643
675
        commands.append(PrintTableCmd(verbose=options.verbose))
644
676
 
645
 
    return commands
646
 
 
647
 
 
648
 
def check_option_syntax(parser, options):
649
 
    """Apply additional restrictions on options, not expressible in
650
 
argparse"""
651
 
 
652
 
    def has_actions(options):
653
 
        return any((options.enable,
654
 
                    options.disable,
655
 
                    options.bump_timeout,
656
 
                    options.start_checker,
657
 
                    options.stop_checker,
658
 
                    options.is_enabled,
659
 
                    options.remove,
660
 
                    options.checker is not None,
661
 
                    options.timeout is not None,
662
 
                    options.extended_timeout is not None,
663
 
                    options.interval is not None,
664
 
                    options.approved_by_default is not None,
665
 
                    options.approval_delay is not None,
666
 
                    options.approval_duration is not None,
667
 
                    options.host is not None,
668
 
                    options.secret is not None,
669
 
                    options.approve,
670
 
                    options.deny))
671
 
 
672
 
    if has_actions(options) and not (options.client or options.all):
673
 
        parser.error("Options require clients names or --all.")
674
 
    if options.verbose and has_actions(options):
675
 
        parser.error("--verbose can only be used alone.")
676
 
    if options.dump_json and (options.verbose
677
 
                              or has_actions(options)):
678
 
        parser.error("--dump-json can only be used alone.")
679
 
    if options.all and not has_actions(options):
680
 
        parser.error("--all requires an action.")
681
 
    if options.is_enabled and len(options.client) > 1:
682
 
        parser.error("--is-enabled requires exactly one client")
683
 
 
684
 
 
685
 
def main():
686
 
    parser = argparse.ArgumentParser()
687
 
 
688
 
    add_command_line_options(parser)
689
 
 
690
 
    options = parser.parse_args()
691
 
 
692
 
    check_option_syntax(parser, options)
693
 
 
694
 
    clientnames = options.client
695
 
 
696
 
    try:
697
 
        bus = dbus.SystemBus()
698
 
        mandos_dbus_objc = bus.get_object(busname, server_path)
699
 
    except dbus.exceptions.DBusException:
700
 
        log.critical("Could not connect to Mandos server")
701
 
        sys.exit(1)
702
 
 
703
 
    mandos_serv = dbus.Interface(mandos_dbus_objc,
704
 
                                 dbus_interface=server_interface)
705
 
    mandos_serv_object_manager = dbus.Interface(
706
 
        mandos_dbus_objc, dbus_interface=dbus.OBJECT_MANAGER_IFACE)
707
 
 
708
677
    # Filter out log message from dbus module
709
678
    dbus_logger = logging.getLogger("dbus.proxies")
710
679
    class NullFilter(logging.Filter):
711
680
        def filter(self, record):
712
681
            return False
713
682
    dbus_filter = NullFilter()
 
683
    dbus_logger.addFilter(dbus_filter)
714
684
    try:
715
 
        dbus_logger.addFilter(dbus_filter)
716
 
        mandos_clients = {path: ifs_and_props[client_interface]
717
 
                          for path, ifs_and_props in
718
 
                          mandos_serv_object_manager
719
 
                          .GetManagedObjects().items()
720
 
                          if client_interface in ifs_and_props}
 
685
        try:
 
686
            mandos_clients = {path: ifs_and_props[client_interface]
 
687
                              for path, ifs_and_props in
 
688
                              mandos_serv_object_manager
 
689
                              .GetManagedObjects().items()
 
690
                              if client_interface in ifs_and_props}
 
691
        finally:
 
692
            # restore dbus logger
 
693
            dbus_logger.removeFilter(dbus_filter)
721
694
    except dbus.exceptions.DBusException as e:
722
695
        log.critical("Failed to access Mandos server through D-Bus:"
723
696
                     "\n%s", e)
724
697
        sys.exit(1)
725
 
    finally:
726
 
        # restore dbus logger
727
 
        dbus_logger.removeFilter(dbus_filter)
728
698
 
729
699
    # Compile dict of (clients: properties) to process
730
700
    clients = {}
731
701
 
732
 
    if not clientnames:
 
702
    if options.all or not options.client:
733
703
        clients = {bus.get_object(busname, path): properties
734
704
                   for path, properties in mandos_clients.items()}
735
705
    else:
736
 
        for name in clientnames:
 
706
        for name in options.client:
737
707
            for path, client in mandos_clients.items():
738
708
                if client["Name"] == name:
739
709
                    client_objc = bus.get_object(busname, path)
744
714
                sys.exit(1)
745
715
 
746
716
    # Run all commands on clients
747
 
    commands = commands_from_options(options)
748
717
    for command in commands:
749
718
        command.run(mandos_serv, clients)
750
719
 
764
733
 
765
734
class Test_string_to_delta(unittest.TestCase):
766
735
    def test_handles_basic_rfc3339(self):
767
 
        self.assertEqual(string_to_delta("PT0S"),
768
 
                         datetime.timedelta())
769
 
        self.assertEqual(string_to_delta("P0D"),
770
 
                         datetime.timedelta())
771
 
        self.assertEqual(string_to_delta("PT1S"),
772
 
                         datetime.timedelta(0, 1))
773
736
        self.assertEqual(string_to_delta("PT2H"),
774
737
                         datetime.timedelta(0, 7200))
775
738
    def test_falls_back_to_pre_1_6_1_with_warning(self):
794
757
            self.assertTrue(getattr(warning_filter, "found", False))
795
758
        self.assertEqual(value, datetime.timedelta(0, 7200))
796
759
 
797
 
 
798
 
class TestCmd(unittest.TestCase):
799
 
    """Abstract class for tests of command classes"""
800
 
    def setUp(self):
801
 
        testcase = self
802
 
        class MockClient(object):
803
 
            def __init__(self, name, **attributes):
804
 
                self.__dbus_object_path__ = "objpath_{}".format(name)
805
 
                self.attributes = attributes
806
 
                self.attributes["Name"] = name
807
 
                self.calls = []
808
 
            def Set(self, interface, property, value, dbus_interface):
809
 
                testcase.assertEqual(interface, client_interface)
810
 
                testcase.assertEqual(dbus_interface,
811
 
                                     dbus.PROPERTIES_IFACE)
812
 
                self.attributes[property] = value
813
 
            def Get(self, interface, property, dbus_interface):
814
 
                testcase.assertEqual(interface, client_interface)
815
 
                testcase.assertEqual(dbus_interface,
816
 
                                     dbus.PROPERTIES_IFACE)
817
 
                return self.attributes[property]
818
 
            def Approve(self, approve, dbus_interface):
819
 
                testcase.assertEqual(dbus_interface, client_interface)
820
 
                self.calls.append(("Approve", (approve,
821
 
                                               dbus_interface)))
822
 
        self.client = MockClient(
823
 
            "foo",
824
 
            KeyID=("92ed150794387c03ce684574b1139a65"
825
 
                   "94a34f895daaaf09fd8ea90a27cddb12"),
826
 
            Secret=b"secret",
827
 
            Host="foo.example.org",
828
 
            Enabled=dbus.Boolean(True),
829
 
            Timeout=300000,
830
 
            LastCheckedOK="2019-02-03T00:00:00",
831
 
            Created="2019-01-02T00:00:00",
832
 
            Interval=120000,
833
 
            Fingerprint=("778827225BA7DE539C5A"
834
 
                         "7CFA59CFF7CDBD9A5920"),
835
 
            CheckerRunning=dbus.Boolean(False),
836
 
            LastEnabled="2019-01-03T00:00:00",
837
 
            ApprovalPending=dbus.Boolean(False),
838
 
            ApprovedByDefault=dbus.Boolean(True),
839
 
            LastApprovalRequest="",
840
 
            ApprovalDelay=0,
841
 
            ApprovalDuration=1000,
842
 
            Checker="fping -q -- %(host)s",
843
 
            ExtendedTimeout=900000,
844
 
            Expires="2019-02-04T00:00:00",
845
 
            LastCheckerStatus=0)
846
 
        self.other_client = MockClient(
847
 
            "barbar",
848
 
            KeyID=("0558568eedd67d622f5c83b35a115f79"
849
 
                   "6ab612cff5ad227247e46c2b020f441c"),
850
 
            Secret=b"secretbar",
851
 
            Host="192.0.2.3",
852
 
            Enabled=dbus.Boolean(True),
853
 
            Timeout=300000,
854
 
            LastCheckedOK="2019-02-04T00:00:00",
855
 
            Created="2019-01-03T00:00:00",
856
 
            Interval=120000,
857
 
            Fingerprint=("3E393AEAEFB84C7E89E2"
858
 
                         "F547B3A107558FCA3A27"),
859
 
            CheckerRunning=dbus.Boolean(True),
860
 
            LastEnabled="2019-01-04T00:00:00",
861
 
            ApprovalPending=dbus.Boolean(False),
862
 
            ApprovedByDefault=dbus.Boolean(False),
863
 
            LastApprovalRequest="2019-01-03T00:00:00",
864
 
            ApprovalDelay=30000,
865
 
            ApprovalDuration=1000,
866
 
            Checker=":",
867
 
            ExtendedTimeout=900000,
868
 
            Expires="2019-02-05T00:00:00",
869
 
            LastCheckerStatus=-2)
870
 
        self.clients =  collections.OrderedDict(
871
 
            [
872
 
                (self.client, self.client.attributes),
873
 
                (self.other_client, self.other_client.attributes),
874
 
            ])
875
 
        self.one_client = {self.client: self.client.attributes}
876
 
 
877
 
class TestPrintTableCmd(TestCmd):
878
 
    def test_normal(self):
879
 
        output = PrintTableCmd().output(self.clients)
880
 
        expected_output = """
881
 
Name   Enabled Timeout  Last Successful Check
882
 
foo    Yes     00:05:00 2019-02-03T00:00:00  
883
 
barbar Yes     00:05:00 2019-02-04T00:00:00  
884
 
"""[1:-1]
885
 
        self.assertEqual(output, expected_output)
886
 
    def test_verbose(self):
887
 
        output = PrintTableCmd(verbose=True).output(self.clients)
888
 
        expected_output = """
889
 
Name   Enabled Timeout  Last Successful Check Created             Interval Host            Key ID                                                           Fingerprint                              Check Is Running Last Enabled        Approval Is Pending Approved By Default Last Approval Request Approval Delay Approval Duration Checker              Extended Timeout Expires             Last Checker Status
890
 
foo    Yes     00:05:00 2019-02-03T00:00:00   2019-01-02T00:00:00 00:02:00 foo.example.org 92ed150794387c03ce684574b1139a6594a34f895daaaf09fd8ea90a27cddb12 778827225BA7DE539C5A7CFA59CFF7CDBD9A5920 No               2019-01-03T00:00:00 No                  Yes                                       00:00:00       00:00:01          fping -q -- %(host)s 00:15:00         2019-02-04T00:00:00 0                  
891
 
barbar Yes     00:05:00 2019-02-04T00:00:00   2019-01-03T00:00:00 00:02:00 192.0.2.3       0558568eedd67d622f5c83b35a115f796ab612cff5ad227247e46c2b020f441c 3E393AEAEFB84C7E89E2F547B3A107558FCA3A27 Yes              2019-01-04T00:00:00 No                  No                  2019-01-03T00:00:00   00:00:30       00:00:01          :                    00:15:00         2019-02-05T00:00:00 -2                 
892
 
"""[1:-1]
893
 
        self.assertEqual(output, expected_output)
894
 
    def test_one_client(self):
895
 
        output = PrintTableCmd().output(self.one_client)
896
 
        expected_output = """
897
 
Name Enabled Timeout  Last Successful Check
898
 
foo  Yes     00:05:00 2019-02-03T00:00:00  
899
 
"""[1:-1]
900
 
        self.assertEqual(output, expected_output)
901
 
 
902
 
class TestDumpJSONCmd(TestCmd):
903
 
    def setUp(self):
904
 
        self.expected_json = {
905
 
            "foo": {
906
 
                "Name": "foo",
907
 
                "KeyID": ("92ed150794387c03ce684574b1139a65"
908
 
                          "94a34f895daaaf09fd8ea90a27cddb12"),
909
 
                "Host": "foo.example.org",
910
 
                "Enabled": True,
911
 
                "Timeout": 300000,
912
 
                "LastCheckedOK": "2019-02-03T00:00:00",
913
 
                "Created": "2019-01-02T00:00:00",
914
 
                "Interval": 120000,
915
 
                "Fingerprint": ("778827225BA7DE539C5A"
916
 
                                "7CFA59CFF7CDBD9A5920"),
917
 
                "CheckerRunning": False,
918
 
                "LastEnabled": "2019-01-03T00:00:00",
919
 
                "ApprovalPending": False,
920
 
                "ApprovedByDefault": True,
921
 
                "LastApprovalRequest": "",
922
 
                "ApprovalDelay": 0,
923
 
                "ApprovalDuration": 1000,
924
 
                "Checker": "fping -q -- %(host)s",
925
 
                "ExtendedTimeout": 900000,
926
 
                "Expires": "2019-02-04T00:00:00",
927
 
                "LastCheckerStatus": 0,
928
 
            },
929
 
            "barbar": {
930
 
                "Name": "barbar",
931
 
                "KeyID": ("0558568eedd67d622f5c83b35a115f79"
932
 
                          "6ab612cff5ad227247e46c2b020f441c"),
933
 
                "Host": "192.0.2.3",
934
 
                "Enabled": True,
935
 
                "Timeout": 300000,
936
 
                "LastCheckedOK": "2019-02-04T00:00:00",
937
 
                "Created": "2019-01-03T00:00:00",
938
 
                "Interval": 120000,
939
 
                "Fingerprint": ("3E393AEAEFB84C7E89E2"
940
 
                                "F547B3A107558FCA3A27"),
941
 
                "CheckerRunning": True,
942
 
                "LastEnabled": "2019-01-04T00:00:00",
943
 
                "ApprovalPending": False,
944
 
                "ApprovedByDefault": False,
945
 
                "LastApprovalRequest": "2019-01-03T00:00:00",
946
 
                "ApprovalDelay": 30000,
947
 
                "ApprovalDuration": 1000,
948
 
                "Checker": ":",
949
 
                "ExtendedTimeout": 900000,
950
 
                "Expires": "2019-02-05T00:00:00",
951
 
                "LastCheckerStatus": -2,
952
 
            },
 
760
class Test_TableOfClients(unittest.TestCase):
 
761
    def setUp(self):
 
762
        self.tableheaders = {
 
763
            "Attr1": "X",
 
764
            "AttrTwo": "Yy",
 
765
            "AttrThree": "Zzz",
 
766
            "Bool": "A D-BUS Boolean",
 
767
            "NonDbusBoolean": "A Non-D-BUS Boolean",
 
768
            "Integer": "An Integer",
 
769
            "Timeout": "Timedelta 1",
 
770
            "Interval": "Timedelta 2",
 
771
            "ApprovalDelay": "Timedelta 3",
 
772
            "ApprovalDuration": "Timedelta 4",
 
773
            "ExtendedTimeout": "Timedelta 5",
 
774
            "String": "A String",
953
775
        }
954
 
        return super(TestDumpJSONCmd, self).setUp()
955
 
    def test_normal(self):
956
 
        json_data = json.loads(DumpJSONCmd().output(self.clients))
957
 
        self.assertDictEqual(json_data, self.expected_json)
958
 
    def test_one_client(self):
959
 
        clients = self.one_client
960
 
        json_data = json.loads(DumpJSONCmd().output(clients))
961
 
        expected_json = {"foo": self.expected_json["foo"]}
962
 
        self.assertDictEqual(json_data, expected_json)
963
 
 
964
 
class TestIsEnabledCmd(TestCmd):
965
 
    def test_is_enabled(self):
966
 
        self.assertTrue(all(IsEnabledCmd().is_enabled(client, properties)
967
 
                            for client, properties in self.clients.items()))
968
 
    def test_is_enabled_run_exits_successfully(self):
969
 
        with self.assertRaises(SystemExit) as e:
970
 
            IsEnabledCmd().run(None, self.one_client)
971
 
        if e.exception.code is not None:
972
 
            self.assertEqual(e.exception.code, 0)
973
 
        else:
974
 
            self.assertIsNone(e.exception.code)
975
 
    def test_is_enabled_run_exits_with_failure(self):
976
 
        self.client.attributes["Enabled"] = dbus.Boolean(False)
977
 
        with self.assertRaises(SystemExit) as e:
978
 
            IsEnabledCmd().run(None, self.one_client)
979
 
        if isinstance(e.exception.code, int):
980
 
            self.assertNotEqual(e.exception.code, 0)
981
 
        else:
982
 
            self.assertIsNotNone(e.exception.code)
983
 
 
984
 
class TestRemoveCmd(TestCmd):
985
 
    def test_remove(self):
986
 
        class MockMandos(object):
987
 
            def __init__(self):
988
 
                self.calls = []
989
 
            def RemoveClient(self, dbus_path):
990
 
                self.calls.append(("RemoveClient", (dbus_path,)))
991
 
        mandos = MockMandos()
992
 
        super(TestRemoveCmd, self).setUp()
993
 
        RemoveCmd().run(mandos, self.clients)
994
 
        self.assertEqual(len(mandos.calls), 2)
995
 
        for client in self.clients:
996
 
            self.assertIn(("RemoveClient",
997
 
                           (client.__dbus_object_path__,)),
998
 
                          mandos.calls)
999
 
 
1000
 
class TestApproveCmd(TestCmd):
1001
 
    def test_approve(self):
1002
 
        ApproveCmd().run(None, self.clients)
1003
 
        for client in self.clients:
1004
 
            self.assertIn(("Approve", (True, client_interface)),
1005
 
                          client.calls)
1006
 
 
1007
 
class TestDenyCmd(TestCmd):
1008
 
    def test_deny(self):
1009
 
        DenyCmd().run(None, self.clients)
1010
 
        for client in self.clients:
1011
 
            self.assertIn(("Approve", (False, client_interface)),
1012
 
                          client.calls)
1013
 
 
1014
 
class TestEnableCmd(TestCmd):
1015
 
    def test_enable(self):
1016
 
        for client in self.clients:
1017
 
            client.attributes["Enabled"] = False
1018
 
 
1019
 
        EnableCmd().run(None, self.clients)
1020
 
 
1021
 
        for client in self.clients:
1022
 
            self.assertTrue(client.attributes["Enabled"])
1023
 
 
1024
 
class TestDisableCmd(TestCmd):
1025
 
    def test_disable(self):
1026
 
        DisableCmd().run(None, self.clients)
1027
 
 
1028
 
        for client in self.clients:
1029
 
            self.assertFalse(client.attributes["Enabled"])
1030
 
 
1031
 
class Unique(object):
1032
 
    """Class for objects which exist only to be unique objects, since
1033
 
unittest.mock.sentinel only exists in Python 3.3"""
1034
 
 
1035
 
class TestPropertyCmd(TestCmd):
1036
 
    """Abstract class for tests of PropertyCmd classes"""
1037
 
    def runTest(self):
1038
 
        if not hasattr(self, "command"):
1039
 
            return
1040
 
        values_to_get = getattr(self, "values_to_get",
1041
 
                                self.values_to_set)
1042
 
        for value_to_set, value_to_get in zip(self.values_to_set,
1043
 
                                              values_to_get):
1044
 
            for client in self.clients:
1045
 
                old_value = client.attributes[self.property]
1046
 
                self.assertNotIsInstance(old_value, Unique)
1047
 
                client.attributes[self.property] = Unique()
1048
 
            self.run_command(value_to_set, self.clients)
1049
 
            for client in self.clients:
1050
 
                value = client.attributes[self.property]
1051
 
                self.assertNotIsInstance(value, Unique)
1052
 
                self.assertEqual(value, value_to_get)
1053
 
    def run_command(self, value, clients):
1054
 
        self.command().run(None, clients)
1055
 
 
1056
 
class TestBumpTimeoutCmd(TestPropertyCmd):
1057
 
    command = BumpTimeoutCmd
1058
 
    property = "LastCheckedOK"
1059
 
    values_to_set = [""]
1060
 
 
1061
 
class TestStartCheckerCmd(TestPropertyCmd):
1062
 
    command = StartCheckerCmd
1063
 
    property = "CheckerRunning"
1064
 
    values_to_set = [dbus.Boolean(True)]
1065
 
 
1066
 
class TestStopCheckerCmd(TestPropertyCmd):
1067
 
    command = StopCheckerCmd
1068
 
    property = "CheckerRunning"
1069
 
    values_to_set = [dbus.Boolean(False)]
1070
 
 
1071
 
class TestApproveByDefaultCmd(TestPropertyCmd):
1072
 
    command = ApproveByDefaultCmd
1073
 
    property = "ApprovedByDefault"
1074
 
    values_to_set = [dbus.Boolean(True)]
1075
 
 
1076
 
class TestDenyByDefaultCmd(TestPropertyCmd):
1077
 
    command = DenyByDefaultCmd
1078
 
    property = "ApprovedByDefault"
1079
 
    values_to_set = [dbus.Boolean(False)]
1080
 
 
1081
 
class TestValueArgumentPropertyCmd(TestPropertyCmd):
1082
 
    """Abstract class for tests of PropertyCmd classes using the
1083
 
ValueArgumentMixIn"""
1084
 
    def runTest(self):
1085
 
        if type(self) is TestValueArgumentPropertyCmd:
1086
 
            return
1087
 
        return super(TestValueArgumentPropertyCmd, self).runTest()
1088
 
    def run_command(self, value, clients):
1089
 
        self.command(value).run(None, clients)
1090
 
 
1091
 
class TestSetCheckerCmd(TestValueArgumentPropertyCmd):
1092
 
    command = SetCheckerCmd
1093
 
    property = "Checker"
1094
 
    values_to_set = ["", ":", "fping -q -- %s"]
1095
 
 
1096
 
class TestSetHostCmd(TestValueArgumentPropertyCmd):
1097
 
    command = SetHostCmd
1098
 
    property = "Host"
1099
 
    values_to_set = ["192.0.2.3", "foo.example.org"]
1100
 
 
1101
 
class TestSetSecretCmd(TestValueArgumentPropertyCmd):
1102
 
    command = SetSecretCmd
1103
 
    property = "Secret"
1104
 
    values_to_set = [io.BytesIO(b""),
1105
 
                     io.BytesIO(b"secret\0xyzzy\nbar")]
1106
 
    values_to_get = [b"", b"secret\0xyzzy\nbar"]
1107
 
 
1108
 
class TestSetTimeoutCmd(TestValueArgumentPropertyCmd):
1109
 
    command = SetTimeoutCmd
1110
 
    property = "Timeout"
1111
 
    values_to_set = [datetime.timedelta(),
1112
 
                     datetime.timedelta(minutes=5),
1113
 
                     datetime.timedelta(seconds=1),
1114
 
                     datetime.timedelta(weeks=1),
1115
 
                     datetime.timedelta(weeks=52)]
1116
 
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1117
 
 
1118
 
class TestSetExtendedTimeoutCmd(TestValueArgumentPropertyCmd):
1119
 
    command = SetExtendedTimeoutCmd
1120
 
    property = "ExtendedTimeout"
1121
 
    values_to_set = [datetime.timedelta(),
1122
 
                     datetime.timedelta(minutes=5),
1123
 
                     datetime.timedelta(seconds=1),
1124
 
                     datetime.timedelta(weeks=1),
1125
 
                     datetime.timedelta(weeks=52)]
1126
 
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1127
 
 
1128
 
class TestSetIntervalCmd(TestValueArgumentPropertyCmd):
1129
 
    command = SetIntervalCmd
1130
 
    property = "Interval"
1131
 
    values_to_set = [datetime.timedelta(),
1132
 
                     datetime.timedelta(minutes=5),
1133
 
                     datetime.timedelta(seconds=1),
1134
 
                     datetime.timedelta(weeks=1),
1135
 
                     datetime.timedelta(weeks=52)]
1136
 
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1137
 
 
1138
 
class TestSetApprovalDelayCmd(TestValueArgumentPropertyCmd):
1139
 
    command = SetApprovalDelayCmd
1140
 
    property = "ApprovalDelay"
1141
 
    values_to_set = [datetime.timedelta(),
1142
 
                     datetime.timedelta(minutes=5),
1143
 
                     datetime.timedelta(seconds=1),
1144
 
                     datetime.timedelta(weeks=1),
1145
 
                     datetime.timedelta(weeks=52)]
1146
 
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1147
 
 
1148
 
class TestSetApprovalDurationCmd(TestValueArgumentPropertyCmd):
1149
 
    command = SetApprovalDurationCmd
1150
 
    property = "ApprovalDuration"
1151
 
    values_to_set = [datetime.timedelta(),
1152
 
                     datetime.timedelta(minutes=5),
1153
 
                     datetime.timedelta(seconds=1),
1154
 
                     datetime.timedelta(weeks=1),
1155
 
                     datetime.timedelta(weeks=52)]
1156
 
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1157
 
 
1158
 
class Test_command_from_options(unittest.TestCase):
1159
 
    def setUp(self):
1160
 
        self.parser = argparse.ArgumentParser()
1161
 
        add_command_line_options(self.parser)
1162
 
    def assert_command_from_args(self, args, command_cls, **cmd_attrs):
1163
 
        """Assert that parsing ARGS should result in an instance of
1164
 
COMMAND_CLS with (optionally) all supplied attributes (CMD_ATTRS)."""
1165
 
        options = self.parser.parse_args(args)
1166
 
        check_option_syntax(self.parser, options)
1167
 
        commands = commands_from_options(options)
1168
 
        self.assertEqual(len(commands), 1)
1169
 
        command = commands[0]
1170
 
        self.assertIsInstance(command, command_cls)
1171
 
        for key, value in cmd_attrs.items():
1172
 
            self.assertEqual(getattr(command, key), value)
1173
 
    def test_print_table(self):
1174
 
        self.assert_command_from_args([], PrintTableCmd,
1175
 
                                      verbose=False)
1176
 
 
1177
 
    def test_print_table_verbose(self):
1178
 
        self.assert_command_from_args(["--verbose"], PrintTableCmd,
1179
 
                                      verbose=True)
1180
 
 
1181
 
    def test_print_table_verbose_short(self):
1182
 
        self.assert_command_from_args(["-v"], PrintTableCmd,
1183
 
                                      verbose=True)
1184
 
 
1185
 
    def test_enable(self):
1186
 
        self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1187
 
 
1188
 
    def test_enable_short(self):
1189
 
        self.assert_command_from_args(["-e", "foo"], EnableCmd)
1190
 
 
1191
 
    def test_disable(self):
1192
 
        self.assert_command_from_args(["--disable", "foo"],
1193
 
                                      DisableCmd)
1194
 
 
1195
 
    def test_disable_short(self):
1196
 
        self.assert_command_from_args(["-d", "foo"], DisableCmd)
1197
 
 
1198
 
    def test_bump_timeout(self):
1199
 
        self.assert_command_from_args(["--bump-timeout", "foo"],
1200
 
                                      BumpTimeoutCmd)
1201
 
 
1202
 
    def test_bump_timeout_short(self):
1203
 
        self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1204
 
 
1205
 
    def test_start_checker(self):
1206
 
        self.assert_command_from_args(["--start-checker", "foo"],
1207
 
                                      StartCheckerCmd)
1208
 
 
1209
 
    def test_stop_checker(self):
1210
 
        self.assert_command_from_args(["--stop-checker", "foo"],
1211
 
                                      StopCheckerCmd)
1212
 
 
1213
 
    def test_remove(self):
1214
 
        self.assert_command_from_args(["--remove", "foo"],
1215
 
                                      RemoveCmd)
1216
 
 
1217
 
    def test_remove_short(self):
1218
 
        self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1219
 
 
1220
 
    def test_checker(self):
1221
 
        self.assert_command_from_args(["--checker", ":", "foo"],
1222
 
                                      SetCheckerCmd, value_to_set=":")
1223
 
 
1224
 
    def test_checker_empty(self):
1225
 
        self.assert_command_from_args(["--checker", "", "foo"],
1226
 
                                      SetCheckerCmd, value_to_set="")
1227
 
 
1228
 
    def test_checker_short(self):
1229
 
        self.assert_command_from_args(["-c", ":", "foo"],
1230
 
                                      SetCheckerCmd, value_to_set=":")
1231
 
 
1232
 
    def test_timeout(self):
1233
 
        self.assert_command_from_args(["--timeout", "PT5M", "foo"],
1234
 
                                      SetTimeoutCmd,
1235
 
                                      value_to_set=300000)
1236
 
 
1237
 
    def test_timeout_short(self):
1238
 
        self.assert_command_from_args(["-t", "PT5M", "foo"],
1239
 
                                      SetTimeoutCmd,
1240
 
                                      value_to_set=300000)
1241
 
 
1242
 
    def test_extended_timeout(self):
1243
 
        self.assert_command_from_args(["--extended-timeout", "PT15M",
1244
 
                                       "foo"],
1245
 
                                      SetExtendedTimeoutCmd,
1246
 
                                      value_to_set=900000)
1247
 
 
1248
 
    def test_interval(self):
1249
 
        self.assert_command_from_args(["--interval", "PT2M", "foo"],
1250
 
                                      SetIntervalCmd,
1251
 
                                      value_to_set=120000)
1252
 
 
1253
 
    def test_interval_short(self):
1254
 
        self.assert_command_from_args(["-i", "PT2M", "foo"],
1255
 
                                      SetIntervalCmd,
1256
 
                                      value_to_set=120000)
1257
 
 
1258
 
    def test_approve_by_default(self):
1259
 
        self.assert_command_from_args(["--approve-by-default", "foo"],
1260
 
                                      ApproveByDefaultCmd)
1261
 
 
1262
 
    def test_deny_by_default(self):
1263
 
        self.assert_command_from_args(["--deny-by-default", "foo"],
1264
 
                                      DenyByDefaultCmd)
1265
 
 
1266
 
    def test_approval_delay(self):
1267
 
        self.assert_command_from_args(["--approval-delay", "PT30S",
1268
 
                                       "foo"], SetApprovalDelayCmd,
1269
 
                                      value_to_set=30000)
1270
 
 
1271
 
    def test_approval_duration(self):
1272
 
        self.assert_command_from_args(["--approval-duration", "PT1S",
1273
 
                                       "foo"], SetApprovalDurationCmd,
1274
 
                                      value_to_set=1000)
1275
 
 
1276
 
    def test_host(self):
1277
 
        self.assert_command_from_args(["--host", "foo.example.org",
1278
 
                                       "foo"], SetHostCmd,
1279
 
                                      value_to_set="foo.example.org")
1280
 
 
1281
 
    def test_host_short(self):
1282
 
        self.assert_command_from_args(["-H", "foo.example.org",
1283
 
                                       "foo"], SetHostCmd,
1284
 
                                      value_to_set="foo.example.org")
1285
 
 
1286
 
    def test_secret_devnull(self):
1287
 
        self.assert_command_from_args(["--secret", os.path.devnull,
1288
 
                                       "foo"], SetSecretCmd,
1289
 
                                      value_to_set=b"")
1290
 
 
1291
 
    def test_secret_tempfile(self):
1292
 
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
1293
 
            value = b"secret\0xyzzy\nbar"
1294
 
            f.write(value)
1295
 
            f.seek(0)
1296
 
            self.assert_command_from_args(["--secret", f.name,
1297
 
                                           "foo"], SetSecretCmd,
1298
 
                                          value_to_set=value)
1299
 
 
1300
 
    def test_secret_devnull_short(self):
1301
 
        self.assert_command_from_args(["-s", os.path.devnull, "foo"],
1302
 
                                      SetSecretCmd, value_to_set=b"")
1303
 
 
1304
 
    def test_secret_tempfile_short(self):
1305
 
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
1306
 
            value = b"secret\0xyzzy\nbar"
1307
 
            f.write(value)
1308
 
            f.seek(0)
1309
 
            self.assert_command_from_args(["-s", f.name, "foo"],
1310
 
                                          SetSecretCmd,
1311
 
                                          value_to_set=value)
1312
 
 
1313
 
    def test_approve(self):
1314
 
        self.assert_command_from_args(["--approve", "foo"],
1315
 
                                      ApproveCmd)
1316
 
 
1317
 
    def test_approve_short(self):
1318
 
        self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1319
 
 
1320
 
    def test_deny(self):
1321
 
        self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1322
 
 
1323
 
    def test_deny_short(self):
1324
 
        self.assert_command_from_args(["-D", "foo"], DenyCmd)
1325
 
 
1326
 
    def test_dump_json(self):
1327
 
        self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1328
 
 
1329
 
    def test_is_enabled(self):
1330
 
        self.assert_command_from_args(["--is-enabled", "foo"],
1331
 
                                      IsEnabledCmd)
1332
 
 
1333
 
    def test_is_enabled_short(self):
1334
 
        self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1335
 
 
1336
 
 
1337
 
class Test_check_option_syntax(unittest.TestCase):
1338
 
    # This mostly corresponds to the definition from has_actions() in
1339
 
    # check_option_syntax()
1340
 
    actions = {
1341
 
        # The actual values set here are not that important, but we do
1342
 
        # at least stick to the correct types, even though they are
1343
 
        # never used
1344
 
        "enable": True,
1345
 
        "disable": True,
1346
 
        "bump_timeout": True,
1347
 
        "start_checker": True,
1348
 
        "stop_checker": True,
1349
 
        "is_enabled": True,
1350
 
        "remove": True,
1351
 
        "checker": "x",
1352
 
        "timeout": datetime.timedelta(),
1353
 
        "extended_timeout": datetime.timedelta(),
1354
 
        "interval": datetime.timedelta(),
1355
 
        "approved_by_default": True,
1356
 
        "approval_delay": datetime.timedelta(),
1357
 
        "approval_duration": datetime.timedelta(),
1358
 
        "host": "x",
1359
 
        "secret": io.BytesIO(b"x"),
1360
 
        "approve": True,
1361
 
        "deny": True,
1362
 
    }
1363
 
 
1364
 
    def setUp(self):
1365
 
        self.parser = argparse.ArgumentParser()
1366
 
        add_command_line_options(self.parser)
1367
 
 
1368
 
    @contextlib.contextmanager
1369
 
    def assertParseError(self):
1370
 
        with self.assertRaises(SystemExit) as e:
1371
 
            with self.temporarily_suppress_stderr():
1372
 
                yield
1373
 
        # Exit code from argparse is guaranteed to be "2".  Reference:
1374
 
        # https://docs.python.org/3/library/argparse.html#exiting-methods
1375
 
        self.assertEqual(e.exception.code, 2)
1376
 
 
1377
 
    @staticmethod
1378
 
    @contextlib.contextmanager
1379
 
    def temporarily_suppress_stderr():
1380
 
        null = os.open(os.path.devnull, os.O_RDWR)
1381
 
        stderrcopy = os.dup(sys.stderr.fileno())
1382
 
        os.dup2(null, sys.stderr.fileno())
1383
 
        os.close(null)
1384
 
        try:
1385
 
            yield
1386
 
        finally:
1387
 
            # restore stderr
1388
 
            os.dup2(stderrcopy, sys.stderr.fileno())
1389
 
            os.close(stderrcopy)
1390
 
 
1391
 
    def check_option_syntax(self, options):
1392
 
        check_option_syntax(self.parser, options)
1393
 
 
1394
 
    def test_actions_requires_client_or_all(self):
1395
 
        for action, value in self.actions.items():
1396
 
            options = self.parser.parse_args()
1397
 
            setattr(options, action, value)
1398
 
            with self.assertParseError():
1399
 
                self.check_option_syntax(options)
1400
 
 
1401
 
    def test_actions_conflicts_with_verbose(self):
1402
 
        for action, value in self.actions.items():
1403
 
            options = self.parser.parse_args()
1404
 
            setattr(options, action, value)
1405
 
            options.verbose = True
1406
 
            with self.assertParseError():
1407
 
                self.check_option_syntax(options)
1408
 
 
1409
 
    def test_dump_json_conflicts_with_verbose(self):
1410
 
        options = self.parser.parse_args()
1411
 
        options.dump_json = True
1412
 
        options.verbose = True
1413
 
        with self.assertParseError():
1414
 
            self.check_option_syntax(options)
1415
 
 
1416
 
    def test_dump_json_conflicts_with_action(self):
1417
 
        for action, value in self.actions.items():
1418
 
            options = self.parser.parse_args()
1419
 
            setattr(options, action, value)
1420
 
            options.dump_json = True
1421
 
            with self.assertParseError():
1422
 
                self.check_option_syntax(options)
1423
 
 
1424
 
    def test_all_can_not_be_alone(self):
1425
 
        options = self.parser.parse_args()
1426
 
        options.all = True
1427
 
        with self.assertParseError():
1428
 
            self.check_option_syntax(options)
1429
 
 
1430
 
    def test_all_is_ok_with_any_action(self):
1431
 
        for action, value in self.actions.items():
1432
 
            options = self.parser.parse_args()
1433
 
            setattr(options, action, value)
1434
 
            options.all = True
1435
 
            self.check_option_syntax(options)
1436
 
 
1437
 
    def test_is_enabled_fails_without_client(self):
1438
 
        options = self.parser.parse_args()
1439
 
        options.is_enabled = True
1440
 
        with self.assertParseError():
1441
 
            self.check_option_syntax(options)
1442
 
 
1443
 
    def test_is_enabled_works_with_one_client(self):
1444
 
        options = self.parser.parse_args()
1445
 
        options.is_enabled = True
1446
 
        options.client = ["foo"]
1447
 
        self.check_option_syntax(options)
1448
 
 
1449
 
    def test_is_enabled_fails_with_two_clients(self):
1450
 
        options = self.parser.parse_args()
1451
 
        options.is_enabled = True
1452
 
        options.client = ["foo", "barbar"]
1453
 
        with self.assertParseError():
1454
 
            self.check_option_syntax(options)
 
776
        self.keywords = ["Attr1", "AttrTwo"]
 
777
        self.clients = [
 
778
            {
 
779
                "Attr1": "x1",
 
780
                "AttrTwo": "y1",
 
781
                "AttrThree": "z1",
 
782
                "Bool": dbus.Boolean(False),
 
783
                "NonDbusBoolean": False,
 
784
                "Integer": 0,
 
785
                "Timeout": 0,
 
786
                "Interval": 1000,
 
787
                "ApprovalDelay": 2000,
 
788
                "ApprovalDuration": 3000,
 
789
                "ExtendedTimeout": 4000,
 
790
                "String": "",
 
791
            },
 
792
            {
 
793
                "Attr1": "x2",
 
794
                "AttrTwo": "y2",
 
795
                "AttrThree": "z2",
 
796
                "Bool": dbus.Boolean(True),
 
797
                "NonDbusBoolean": True,
 
798
                "Integer": 1,
 
799
                "Timeout": 93785000,
 
800
                "Interval": 93786000,
 
801
                "ApprovalDelay": 93787000,
 
802
                "ApprovalDuration": 93788000,
 
803
                "ExtendedTimeout": 93789000,
 
804
                "String": "A huge string which will not fit," * 10,
 
805
            },
 
806
        ]
 
807
    def test_short_header(self):
 
808
        text = str(TableOfClients(self.clients, self.keywords,
 
809
                                  self.tableheaders))
 
810
        expected_text = """
 
811
X  Yy
 
812
x1 y1
 
813
x2 y2
 
814
"""[1:-1]
 
815
        self.assertEqual(text, expected_text)
 
816
    def test_booleans(self):
 
817
        keywords = ["Bool", "NonDbusBoolean"]
 
818
        text = str(TableOfClients(self.clients, keywords,
 
819
                                  self.tableheaders))
 
820
        expected_text = """
 
821
A D-BUS Boolean A Non-D-BUS Boolean
 
822
No              False              
 
823
Yes             True               
 
824
"""[1:-1]
 
825
        self.assertEqual(text, expected_text)
 
826
    def test_milliseconds_detection(self):
 
827
        keywords = ["Integer", "Timeout", "Interval", "ApprovalDelay",
 
828
                    "ApprovalDuration", "ExtendedTimeout"]
 
829
        text = str(TableOfClients(self.clients, keywords,
 
830
                                  self.tableheaders))
 
831
        expected_text = """
 
832
An Integer Timedelta 1 Timedelta 2 Timedelta 3 Timedelta 4 Timedelta 5
 
833
0          00:00:00    00:00:01    00:00:02    00:00:03    00:00:04   
 
834
1          1T02:03:05  1T02:03:06  1T02:03:07  1T02:03:08  1T02:03:09 
 
835
"""[1:-1]
 
836
        self.assertEqual(text, expected_text)
 
837
    def test_empty_and_long_string_values(self):
 
838
        keywords = ["String"]
 
839
        text = str(TableOfClients(self.clients, keywords,
 
840
                                  self.tableheaders))
 
841
        expected_text = """
 
842
A String                                                                                                                                                                                                                                                                                                                                  
 
843
                                                                                                                                                                                                                                                                                                                                          
 
844
A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,A huge string which will not fit,
 
845
"""[1:-1]
 
846
        self.assertEqual(text, expected_text)
1455
847
 
1456
848
 
1457
849