/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-03-16 04:38:35 UTC
  • Revision ID: teddy@recompile.se-20190316043835-xlmz9xse3bh1u5u6
mandos-ctl: Refactor tests

* mandos-ctl (Test_get_managed_objects): Remove some useless
                                         "@staticmethod"s.

Show diffs side-by-side

added added

removed removed

Lines of Context:
125
125
                log.critical("Client not found on server: %r", name)
126
126
                sys.exit(1)
127
127
 
 
128
    # Run all commands on clients
128
129
    commands = commands_from_options(options)
129
 
 
130
130
    for command in commands:
131
131
        command.run(clients, bus, mandos_serv)
132
132
 
232
232
    >>> rfc3339_duration_to_delta("")
233
233
    Traceback (most recent call last):
234
234
    ...
235
 
    ValueError: Invalid RFC 3339 duration: ""
 
235
    ValueError: Invalid RFC 3339 duration: u''
236
236
    >>> # Must start with "P":
237
237
    >>> rfc3339_duration_to_delta("1D")
238
238
    Traceback (most recent call last):
239
239
    ...
240
 
    ValueError: Invalid RFC 3339 duration: "1D"
 
240
    ValueError: Invalid RFC 3339 duration: u'1D'
241
241
    >>> # Must use correct order
242
242
    >>> rfc3339_duration_to_delta("PT1S2M")
243
243
    Traceback (most recent call last):
244
244
    ...
245
 
    ValueError: Invalid RFC 3339 duration: "PT1S2M"
 
245
    ValueError: Invalid RFC 3339 duration: u'PT1S2M'
246
246
    >>> # Time needs time marker
247
247
    >>> rfc3339_duration_to_delta("P1H2S")
248
248
    Traceback (most recent call last):
249
249
    ...
250
 
    ValueError: Invalid RFC 3339 duration: "P1H2S"
 
250
    ValueError: Invalid RFC 3339 duration: u'P1H2S'
251
251
    >>> # Weeks can not be combined with anything else
252
252
    >>> rfc3339_duration_to_delta("P1D2W")
253
253
    Traceback (most recent call last):
254
254
    ...
255
 
    ValueError: Invalid RFC 3339 duration: "P1D2W"
 
255
    ValueError: Invalid RFC 3339 duration: u'P1D2W'
256
256
    >>> rfc3339_duration_to_delta("P2W2H")
257
257
    Traceback (most recent call last):
258
258
    ...
259
 
    ValueError: Invalid RFC 3339 duration: "P2W2H"
 
259
    ValueError: Invalid RFC 3339 duration: u'P2W2H'
260
260
    """
261
261
 
262
262
    # Parsing an RFC 3339 duration with regular expressions is not
333
333
                break
334
334
        else:
335
335
            # No currently valid tokens were found
336
 
            raise ValueError("Invalid RFC 3339 duration: \"{}\""
 
336
            raise ValueError("Invalid RFC 3339 duration: {!r}"
337
337
                             .format(duration))
338
338
    # End token found
339
339
    return value
477
477
    commands = []
478
478
 
479
479
    if options.is_enabled:
480
 
        commands.append(command.IsEnabled())
 
480
        commands.append(IsEnabledCmd())
481
481
 
482
482
    if options.approve:
483
 
        commands.append(command.Approve())
 
483
        commands.append(ApproveCmd())
484
484
 
485
485
    if options.deny:
486
 
        commands.append(command.Deny())
 
486
        commands.append(DenyCmd())
487
487
 
488
488
    if options.remove:
489
 
        commands.append(command.Remove())
 
489
        commands.append(RemoveCmd())
490
490
 
491
491
    if options.dump_json:
492
 
        commands.append(command.DumpJSON())
 
492
        commands.append(DumpJSONCmd())
493
493
 
494
494
    if options.enable:
495
 
        commands.append(command.Enable())
 
495
        commands.append(EnableCmd())
496
496
 
497
497
    if options.disable:
498
 
        commands.append(command.Disable())
 
498
        commands.append(DisableCmd())
499
499
 
500
500
    if options.bump_timeout:
501
 
        commands.append(command.BumpTimeout())
 
501
        commands.append(BumpTimeoutCmd())
502
502
 
503
503
    if options.start_checker:
504
 
        commands.append(command.StartChecker())
 
504
        commands.append(StartCheckerCmd())
505
505
 
506
506
    if options.stop_checker:
507
 
        commands.append(command.StopChecker())
 
507
        commands.append(StopCheckerCmd())
508
508
 
509
509
    if options.approved_by_default is not None:
510
510
        if options.approved_by_default:
511
 
            commands.append(command.ApproveByDefault())
 
511
            commands.append(ApproveByDefaultCmd())
512
512
        else:
513
 
            commands.append(command.DenyByDefault())
 
513
            commands.append(DenyByDefaultCmd())
514
514
 
515
515
    if options.checker is not None:
516
 
        commands.append(command.SetChecker(options.checker))
 
516
        commands.append(SetCheckerCmd(options.checker))
517
517
 
518
518
    if options.host is not None:
519
 
        commands.append(command.SetHost(options.host))
 
519
        commands.append(SetHostCmd(options.host))
520
520
 
521
521
    if options.secret is not None:
522
 
        commands.append(command.SetSecret(options.secret))
 
522
        commands.append(SetSecretCmd(options.secret))
523
523
 
524
524
    if options.timeout is not None:
525
 
        commands.append(command.SetTimeout(options.timeout))
 
525
        commands.append(SetTimeoutCmd(options.timeout))
526
526
 
527
527
    if options.extended_timeout:
528
528
        commands.append(
529
 
            command.SetExtendedTimeout(options.extended_timeout))
 
529
            SetExtendedTimeoutCmd(options.extended_timeout))
530
530
 
531
531
    if options.interval is not None:
532
 
        commands.append(command.SetInterval(options.interval))
 
532
        commands.append(SetIntervalCmd(options.interval))
533
533
 
534
534
    if options.approval_delay is not None:
535
 
        commands.append(
536
 
            command.SetApprovalDelay(options.approval_delay))
 
535
        commands.append(SetApprovalDelayCmd(options.approval_delay))
537
536
 
538
537
    if options.approval_duration is not None:
539
538
        commands.append(
540
 
            command.SetApprovalDuration(options.approval_duration))
 
539
            SetApprovalDurationCmd(options.approval_duration))
541
540
 
542
541
    # If no command option has been given, show table of clients,
543
542
    # optionally verbosely
544
543
    if not commands:
545
 
        commands.append(command.PrintTable(verbose=options.verbose))
 
544
        commands.append(PrintTableCmd(verbose=options.verbose))
546
545
 
547
546
    return commands
548
547
 
549
548
 
550
 
class command(object):
551
 
    """A namespace for command classes"""
552
 
 
553
 
    class Base(object):
554
 
        """Abstract base class for commands"""
555
 
        def run(self, clients, bus=None, mandos=None):
556
 
            """Normal commands should implement run_on_one_client(),
557
 
but commands which want to operate on all clients at the same time can
558
 
override this run() method instead.
559
 
"""
560
 
            self.mandos = mandos
561
 
            for clientpath, properties in clients.items():
562
 
                log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
563
 
                          dbus_busname, str(clientpath))
564
 
                client = bus.get_object(dbus_busname, clientpath)
565
 
                self.run_on_one_client(client, properties)
566
 
 
567
 
 
568
 
    class IsEnabled(Base):
569
 
        def run(self, clients, bus=None, mandos=None):
570
 
            client, properties = next(iter(clients.items()))
571
 
            if self.is_enabled(client, properties):
572
 
                sys.exit(0)
573
 
            sys.exit(1)
574
 
        def is_enabled(self, client, properties):
575
 
            return properties["Enabled"]
576
 
 
577
 
 
578
 
    class Approve(Base):
579
 
        def run_on_one_client(self, client, properties):
580
 
            log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
581
 
                      client.__dbus_object_path__,
582
 
                      client_dbus_interface)
583
 
            client.Approve(dbus.Boolean(True),
584
 
                           dbus_interface=client_dbus_interface)
585
 
 
586
 
 
587
 
    class Deny(Base):
588
 
        def run_on_one_client(self, client, properties):
589
 
            log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
590
 
                      client.__dbus_object_path__,
591
 
                      client_dbus_interface)
592
 
            client.Approve(dbus.Boolean(False),
593
 
                           dbus_interface=client_dbus_interface)
594
 
 
595
 
 
596
 
    class Remove(Base):
597
 
        def run_on_one_client(self, client, properties):
598
 
            log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)",
599
 
                      dbus_busname, server_dbus_path,
600
 
                      server_dbus_interface,
601
 
                      str(client.__dbus_object_path__))
602
 
            self.mandos.RemoveClient(client.__dbus_object_path__)
603
 
 
604
 
 
605
 
    class Output(Base):
606
 
        """Abstract class for commands outputting client details"""
607
 
        all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
608
 
                        "Created", "Interval", "Host", "KeyID",
609
 
                        "Fingerprint", "CheckerRunning",
610
 
                        "LastEnabled", "ApprovalPending",
611
 
                        "ApprovedByDefault", "LastApprovalRequest",
612
 
                        "ApprovalDelay", "ApprovalDuration",
613
 
                        "Checker", "ExtendedTimeout", "Expires",
614
 
                        "LastCheckerStatus")
615
 
 
616
 
        def run(self, clients, bus=None, mandos=None):
617
 
            print(self.output(clients.values()))
618
 
 
619
 
        def output(self, clients):
620
 
            raise NotImplementedError()
621
 
 
622
 
 
623
 
    class DumpJSON(Output):
624
 
        def output(self, clients):
625
 
            data = {client["Name"]:
626
 
                    {key: self.dbus_boolean_to_bool(client[key])
627
 
                     for key in self.all_keywords}
628
 
                    for client in clients}
629
 
            return json.dumps(data, indent=4, separators=(',', ': '))
 
549
class Command(object):
 
550
    """Abstract class for commands"""
 
551
    def run(self, clients, bus=None, mandos=None):
 
552
        """Normal commands should implement run_on_one_client(), but
 
553
        commands which want to operate on all clients at the same time
 
554
        can override this run() method instead."""
 
555
        self.mandos = mandos
 
556
        for clientpath, properties in clients.items():
 
557
            log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
 
558
                      dbus_busname, str(clientpath))
 
559
            client = bus.get_object(dbus_busname, clientpath)
 
560
            self.run_on_one_client(client, properties)
 
561
 
 
562
 
 
563
class IsEnabledCmd(Command):
 
564
    def run(self, clients, bus=None, mandos=None):
 
565
        client, properties = next(iter(clients.items()))
 
566
        if self.is_enabled(client, properties):
 
567
            sys.exit(0)
 
568
        sys.exit(1)
 
569
    def is_enabled(self, client, properties):
 
570
        return properties["Enabled"]
 
571
 
 
572
 
 
573
class ApproveCmd(Command):
 
574
    def run_on_one_client(self, client, properties):
 
575
        log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
 
576
                  client.__dbus_object_path__, client_dbus_interface)
 
577
        client.Approve(dbus.Boolean(True),
 
578
                       dbus_interface=client_dbus_interface)
 
579
 
 
580
 
 
581
class DenyCmd(Command):
 
582
    def run_on_one_client(self, client, properties):
 
583
        log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
 
584
                  client.__dbus_object_path__, client_dbus_interface)
 
585
        client.Approve(dbus.Boolean(False),
 
586
                       dbus_interface=client_dbus_interface)
 
587
 
 
588
 
 
589
class RemoveCmd(Command):
 
590
    def run_on_one_client(self, client, properties):
 
591
        log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", dbus_busname,
 
592
                  server_dbus_path, server_dbus_interface,
 
593
                  str(client.__dbus_object_path__))
 
594
        self.mandos.RemoveClient(client.__dbus_object_path__)
 
595
 
 
596
 
 
597
class OutputCmd(Command):
 
598
    """Abstract class for commands outputting client details"""
 
599
    all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
 
600
                    "Created", "Interval", "Host", "KeyID",
 
601
                    "Fingerprint", "CheckerRunning", "LastEnabled",
 
602
                    "ApprovalPending", "ApprovedByDefault",
 
603
                    "LastApprovalRequest", "ApprovalDelay",
 
604
                    "ApprovalDuration", "Checker", "ExtendedTimeout",
 
605
                    "Expires", "LastCheckerStatus")
 
606
 
 
607
    def run(self, clients, bus=None, mandos=None):
 
608
        print(self.output(clients.values()))
 
609
 
 
610
    def output(self, clients):
 
611
        raise NotImplementedError()
 
612
 
 
613
 
 
614
class DumpJSONCmd(OutputCmd):
 
615
    def output(self, clients):
 
616
        data = {client["Name"]:
 
617
                {key: self.dbus_boolean_to_bool(client[key])
 
618
                 for key in self.all_keywords}
 
619
                for client in clients}
 
620
        return json.dumps(data, indent=4, separators=(',', ': '))
 
621
 
 
622
    @staticmethod
 
623
    def dbus_boolean_to_bool(value):
 
624
        if isinstance(value, dbus.Boolean):
 
625
            value = bool(value)
 
626
        return value
 
627
 
 
628
 
 
629
class PrintTableCmd(OutputCmd):
 
630
    def __init__(self, verbose=False):
 
631
        self.verbose = verbose
 
632
 
 
633
    def output(self, clients):
 
634
        default_keywords = ("Name", "Enabled", "Timeout",
 
635
                            "LastCheckedOK")
 
636
        keywords = default_keywords
 
637
        if self.verbose:
 
638
            keywords = self.all_keywords
 
639
        return str(self.TableOfClients(clients, keywords))
 
640
 
 
641
    class TableOfClients(object):
 
642
        tableheaders = {
 
643
            "Name": "Name",
 
644
            "Enabled": "Enabled",
 
645
            "Timeout": "Timeout",
 
646
            "LastCheckedOK": "Last Successful Check",
 
647
            "LastApprovalRequest": "Last Approval Request",
 
648
            "Created": "Created",
 
649
            "Interval": "Interval",
 
650
            "Host": "Host",
 
651
            "Fingerprint": "Fingerprint",
 
652
            "KeyID": "Key ID",
 
653
            "CheckerRunning": "Check Is Running",
 
654
            "LastEnabled": "Last Enabled",
 
655
            "ApprovalPending": "Approval Is Pending",
 
656
            "ApprovedByDefault": "Approved By Default",
 
657
            "ApprovalDelay": "Approval Delay",
 
658
            "ApprovalDuration": "Approval Duration",
 
659
            "Checker": "Checker",
 
660
            "ExtendedTimeout": "Extended Timeout",
 
661
            "Expires": "Expires",
 
662
            "LastCheckerStatus": "Last Checker Status",
 
663
        }
 
664
 
 
665
        def __init__(self, clients, keywords):
 
666
            self.clients = clients
 
667
            self.keywords = keywords
 
668
 
 
669
        def __str__(self):
 
670
            return "\n".join(self.rows())
 
671
 
 
672
        if sys.version_info.major == 2:
 
673
            __unicode__ = __str__
 
674
            def __str__(self):
 
675
                return str(self).encode(locale.getpreferredencoding())
 
676
 
 
677
        def rows(self):
 
678
            format_string = self.row_formatting_string()
 
679
            rows = [self.header_line(format_string)]
 
680
            rows.extend(self.client_line(client, format_string)
 
681
                        for client in self.clients)
 
682
            return rows
 
683
 
 
684
        def row_formatting_string(self):
 
685
            "Format string used to format table rows"
 
686
            return " ".join("{{{key}:{width}}}".format(
 
687
                width=max(len(self.tableheaders[key]),
 
688
                          *(len(self.string_from_client(client, key))
 
689
                            for client in self.clients)),
 
690
                key=key)
 
691
                            for key in self.keywords)
 
692
 
 
693
        def string_from_client(self, client, key):
 
694
            return self.valuetostring(client[key], key)
 
695
 
 
696
        @classmethod
 
697
        def valuetostring(cls, value, keyword):
 
698
            if isinstance(value, dbus.Boolean):
 
699
                return "Yes" if value else "No"
 
700
            if keyword in ("Timeout", "Interval", "ApprovalDelay",
 
701
                           "ApprovalDuration", "ExtendedTimeout"):
 
702
                return cls.milliseconds_to_string(value)
 
703
            return str(value)
 
704
 
 
705
        def header_line(self, format_string):
 
706
            return format_string.format(**self.tableheaders)
 
707
 
 
708
        def client_line(self, client, format_string):
 
709
            return format_string.format(
 
710
                **{key: self.string_from_client(client, key)
 
711
                   for key in self.keywords})
630
712
 
631
713
        @staticmethod
632
 
        def dbus_boolean_to_bool(value):
633
 
            if isinstance(value, dbus.Boolean):
634
 
                value = bool(value)
635
 
            return value
636
 
 
637
 
 
638
 
    class PrintTable(Output):
639
 
        def __init__(self, verbose=False):
640
 
            self.verbose = verbose
641
 
 
642
 
        def output(self, clients):
643
 
            default_keywords = ("Name", "Enabled", "Timeout",
644
 
                                "LastCheckedOK")
645
 
            keywords = default_keywords
646
 
            if self.verbose:
647
 
                keywords = self.all_keywords
648
 
            return str(self.TableOfClients(clients, keywords))
649
 
 
650
 
        class TableOfClients(object):
651
 
            tableheaders = {
652
 
                "Name": "Name",
653
 
                "Enabled": "Enabled",
654
 
                "Timeout": "Timeout",
655
 
                "LastCheckedOK": "Last Successful Check",
656
 
                "LastApprovalRequest": "Last Approval Request",
657
 
                "Created": "Created",
658
 
                "Interval": "Interval",
659
 
                "Host": "Host",
660
 
                "Fingerprint": "Fingerprint",
661
 
                "KeyID": "Key ID",
662
 
                "CheckerRunning": "Check Is Running",
663
 
                "LastEnabled": "Last Enabled",
664
 
                "ApprovalPending": "Approval Is Pending",
665
 
                "ApprovedByDefault": "Approved By Default",
666
 
                "ApprovalDelay": "Approval Delay",
667
 
                "ApprovalDuration": "Approval Duration",
668
 
                "Checker": "Checker",
669
 
                "ExtendedTimeout": "Extended Timeout",
670
 
                "Expires": "Expires",
671
 
                "LastCheckerStatus": "Last Checker Status",
672
 
            }
673
 
 
674
 
            def __init__(self, clients, keywords):
675
 
                self.clients = clients
676
 
                self.keywords = keywords
677
 
 
678
 
            def __str__(self):
679
 
                return "\n".join(self.rows())
680
 
 
681
 
            if sys.version_info.major == 2:
682
 
                __unicode__ = __str__
683
 
                def __str__(self):
684
 
                    return str(self).encode(
685
 
                        locale.getpreferredencoding())
686
 
 
687
 
            def rows(self):
688
 
                format_string = self.row_formatting_string()
689
 
                rows = [self.header_line(format_string)]
690
 
                rows.extend(self.client_line(client, format_string)
691
 
                            for client in self.clients)
692
 
                return rows
693
 
 
694
 
            def row_formatting_string(self):
695
 
                "Format string used to format table rows"
696
 
                return " ".join("{{{key}:{width}}}".format(
697
 
                    width=max(len(self.tableheaders[key]),
698
 
                              *(len(self.string_from_client(client,
699
 
                                                            key))
700
 
                                for client in self.clients)),
701
 
                    key=key)
702
 
                                for key in self.keywords)
703
 
 
704
 
            def string_from_client(self, client, key):
705
 
                return self.valuetostring(client[key], key)
706
 
 
707
 
            @classmethod
708
 
            def valuetostring(cls, value, keyword):
709
 
                if isinstance(value, dbus.Boolean):
710
 
                    return "Yes" if value else "No"
711
 
                if keyword in ("Timeout", "Interval", "ApprovalDelay",
712
 
                               "ApprovalDuration", "ExtendedTimeout"):
713
 
                    return cls.milliseconds_to_string(value)
714
 
                return str(value)
715
 
 
716
 
            def header_line(self, format_string):
717
 
                return format_string.format(**self.tableheaders)
718
 
 
719
 
            def client_line(self, client, format_string):
720
 
                return format_string.format(
721
 
                    **{key: self.string_from_client(client, key)
722
 
                       for key in self.keywords})
723
 
 
724
 
            @staticmethod
725
 
            def milliseconds_to_string(ms):
726
 
                td = datetime.timedelta(0, 0, 0, ms)
727
 
                return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
728
 
                        .format(days="{}T".format(td.days)
729
 
                                if td.days else "",
730
 
                                hours=td.seconds // 3600,
731
 
                                minutes=(td.seconds % 3600) // 60,
732
 
                                seconds=td.seconds % 60))
733
 
 
734
 
 
735
 
    class Property(Base):
736
 
        "Abstract class for Actions for setting one client property"
737
 
 
738
 
        def run_on_one_client(self, client, properties):
739
 
            """Set the Client's D-Bus property"""
740
 
            log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
741
 
                      client.__dbus_object_path__,
742
 
                      dbus.PROPERTIES_IFACE, client_dbus_interface,
743
 
                      self.propname, self.value_to_set
744
 
                      if not isinstance(self.value_to_set,
745
 
                                        dbus.Boolean)
746
 
                      else bool(self.value_to_set))
747
 
            client.Set(client_dbus_interface, self.propname,
748
 
                       self.value_to_set,
749
 
                       dbus_interface=dbus.PROPERTIES_IFACE)
750
 
 
751
 
        @property
752
 
        def propname(self):
753
 
            raise NotImplementedError()
754
 
 
755
 
 
756
 
    class Enable(Property):
757
 
        propname = "Enabled"
758
 
        value_to_set = dbus.Boolean(True)
759
 
 
760
 
 
761
 
    class Disable(Property):
762
 
        propname = "Enabled"
763
 
        value_to_set = dbus.Boolean(False)
764
 
 
765
 
 
766
 
    class BumpTimeout(Property):
767
 
        propname = "LastCheckedOK"
768
 
        value_to_set = ""
769
 
 
770
 
 
771
 
    class StartChecker(Property):
772
 
        propname = "CheckerRunning"
773
 
        value_to_set = dbus.Boolean(True)
774
 
 
775
 
 
776
 
    class StopChecker(Property):
777
 
        propname = "CheckerRunning"
778
 
        value_to_set = dbus.Boolean(False)
779
 
 
780
 
 
781
 
    class ApproveByDefault(Property):
782
 
        propname = "ApprovedByDefault"
783
 
        value_to_set = dbus.Boolean(True)
784
 
 
785
 
 
786
 
    class DenyByDefault(Property):
787
 
        propname = "ApprovedByDefault"
788
 
        value_to_set = dbus.Boolean(False)
789
 
 
790
 
 
791
 
    class PropertyValue(Property):
792
 
        "Abstract class for Property recieving a value as argument"
793
 
        def __init__(self, value):
794
 
            self.value_to_set = value
795
 
 
796
 
 
797
 
    class SetChecker(PropertyValue):
798
 
        propname = "Checker"
799
 
 
800
 
 
801
 
    class SetHost(PropertyValue):
802
 
        propname = "Host"
803
 
 
804
 
 
805
 
    class SetSecret(PropertyValue):
806
 
        propname = "Secret"
807
 
 
808
 
        @property
809
 
        def value_to_set(self):
810
 
            return self._vts
811
 
 
812
 
        @value_to_set.setter
813
 
        def value_to_set(self, value):
814
 
            """When setting, read data from supplied file object"""
815
 
            self._vts = value.read()
816
 
            value.close()
817
 
 
818
 
 
819
 
    class MillisecondsPropertyValueArgument(PropertyValue):
820
 
        """Abstract class for PropertyValue taking a value argument as
 
714
        def milliseconds_to_string(ms):
 
715
            td = datetime.timedelta(0, 0, 0, ms)
 
716
            return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
 
717
                    .format(days="{}T".format(td.days)
 
718
                            if td.days else "",
 
719
                            hours=td.seconds // 3600,
 
720
                            minutes=(td.seconds % 3600) // 60,
 
721
                            seconds=td.seconds % 60))
 
722
 
 
723
 
 
724
class PropertyCmd(Command):
 
725
    """Abstract class for Actions for setting one client property"""
 
726
 
 
727
    def run_on_one_client(self, client, properties):
 
728
        """Set the Client's D-Bus property"""
 
729
        log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
 
730
                  client.__dbus_object_path__,
 
731
                  dbus.PROPERTIES_IFACE, client_dbus_interface,
 
732
                  self.propname, self.value_to_set
 
733
                  if not isinstance(self.value_to_set, dbus.Boolean)
 
734
                  else bool(self.value_to_set))
 
735
        client.Set(client_dbus_interface, self.propname,
 
736
                   self.value_to_set,
 
737
                   dbus_interface=dbus.PROPERTIES_IFACE)
 
738
 
 
739
    @property
 
740
    def propname(self):
 
741
        raise NotImplementedError()
 
742
 
 
743
 
 
744
class EnableCmd(PropertyCmd):
 
745
    propname = "Enabled"
 
746
    value_to_set = dbus.Boolean(True)
 
747
 
 
748
 
 
749
class DisableCmd(PropertyCmd):
 
750
    propname = "Enabled"
 
751
    value_to_set = dbus.Boolean(False)
 
752
 
 
753
 
 
754
class BumpTimeoutCmd(PropertyCmd):
 
755
    propname = "LastCheckedOK"
 
756
    value_to_set = ""
 
757
 
 
758
 
 
759
class StartCheckerCmd(PropertyCmd):
 
760
    propname = "CheckerRunning"
 
761
    value_to_set = dbus.Boolean(True)
 
762
 
 
763
 
 
764
class StopCheckerCmd(PropertyCmd):
 
765
    propname = "CheckerRunning"
 
766
    value_to_set = dbus.Boolean(False)
 
767
 
 
768
 
 
769
class ApproveByDefaultCmd(PropertyCmd):
 
770
    propname = "ApprovedByDefault"
 
771
    value_to_set = dbus.Boolean(True)
 
772
 
 
773
 
 
774
class DenyByDefaultCmd(PropertyCmd):
 
775
    propname = "ApprovedByDefault"
 
776
    value_to_set = dbus.Boolean(False)
 
777
 
 
778
 
 
779
class PropertyValueCmd(PropertyCmd):
 
780
    """Abstract class for PropertyCmd recieving a value as argument"""
 
781
    def __init__(self, value):
 
782
        self.value_to_set = value
 
783
 
 
784
 
 
785
class SetCheckerCmd(PropertyValueCmd):
 
786
    propname = "Checker"
 
787
 
 
788
 
 
789
class SetHostCmd(PropertyValueCmd):
 
790
    propname = "Host"
 
791
 
 
792
 
 
793
class SetSecretCmd(PropertyValueCmd):
 
794
    propname = "Secret"
 
795
 
 
796
    @property
 
797
    def value_to_set(self):
 
798
        return self._vts
 
799
 
 
800
    @value_to_set.setter
 
801
    def value_to_set(self, value):
 
802
        """When setting, read data from supplied file object"""
 
803
        self._vts = value.read()
 
804
        value.close()
 
805
 
 
806
 
 
807
class MillisecondsPropertyValueArgumentCmd(PropertyValueCmd):
 
808
    """Abstract class for PropertyValueCmd taking a value argument as
821
809
a datetime.timedelta() but should store it as milliseconds."""
822
810
 
823
 
        @property
824
 
        def value_to_set(self):
825
 
            return self._vts
826
 
 
827
 
        @value_to_set.setter
828
 
        def value_to_set(self, value):
829
 
            "When setting, convert value from a datetime.timedelta"
830
 
            self._vts = int(round(value.total_seconds() * 1000))
831
 
 
832
 
 
833
 
    class SetTimeout(MillisecondsPropertyValueArgument):
834
 
        propname = "Timeout"
835
 
 
836
 
 
837
 
    class SetExtendedTimeout(MillisecondsPropertyValueArgument):
838
 
        propname = "ExtendedTimeout"
839
 
 
840
 
 
841
 
    class SetInterval(MillisecondsPropertyValueArgument):
842
 
        propname = "Interval"
843
 
 
844
 
 
845
 
    class SetApprovalDelay(MillisecondsPropertyValueArgument):
846
 
        propname = "ApprovalDelay"
847
 
 
848
 
 
849
 
    class SetApprovalDuration(MillisecondsPropertyValueArgument):
850
 
        propname = "ApprovalDuration"
 
811
    @property
 
812
    def value_to_set(self):
 
813
        return self._vts
 
814
 
 
815
    @value_to_set.setter
 
816
    def value_to_set(self, value):
 
817
        """When setting, convert value from a datetime.timedelta"""
 
818
        self._vts = int(round(value.total_seconds() * 1000))
 
819
 
 
820
 
 
821
class SetTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
 
822
    propname = "Timeout"
 
823
 
 
824
 
 
825
class SetExtendedTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
 
826
    propname = "ExtendedTimeout"
 
827
 
 
828
 
 
829
class SetIntervalCmd(MillisecondsPropertyValueArgumentCmd):
 
830
    propname = "Interval"
 
831
 
 
832
 
 
833
class SetApprovalDelayCmd(MillisecondsPropertyValueArgumentCmd):
 
834
    propname = "ApprovalDelay"
 
835
 
 
836
 
 
837
class SetApprovalDurationCmd(MillisecondsPropertyValueArgumentCmd):
 
838
    propname = "ApprovalDuration"
851
839
 
852
840
 
853
841
 
884
872
                                                    ("records",
885
873
                                                     "output"))
886
874
 
887
 
 
888
875
class Test_string_to_delta(TestCaseWithAssertLogs):
889
 
    # Just test basic RFC 3339 functionality here, the doc string for
890
 
    # rfc3339_duration_to_delta() already has more comprehensive
891
 
    # tests, which is run by doctest.
892
 
 
893
 
    def test_rfc3339_zero_seconds(self):
894
 
        self.assertEqual(datetime.timedelta(),
895
 
                         string_to_delta("PT0S"))
896
 
 
897
 
    def test_rfc3339_zero_days(self):
898
 
        self.assertEqual(datetime.timedelta(), string_to_delta("P0D"))
899
 
 
900
 
    def test_rfc3339_one_second(self):
901
 
        self.assertEqual(datetime.timedelta(0, 1),
902
 
                         string_to_delta("PT1S"))
903
 
 
904
 
    def test_rfc3339_two_hours(self):
905
 
        self.assertEqual(datetime.timedelta(0, 7200),
906
 
                         string_to_delta("PT2H"))
 
876
    def test_handles_basic_rfc3339(self):
 
877
        self.assertEqual(string_to_delta("PT0S"),
 
878
                         datetime.timedelta())
 
879
        self.assertEqual(string_to_delta("P0D"),
 
880
                         datetime.timedelta())
 
881
        self.assertEqual(string_to_delta("PT1S"),
 
882
                         datetime.timedelta(0, 1))
 
883
        self.assertEqual(string_to_delta("PT2H"),
 
884
                         datetime.timedelta(0, 7200))
907
885
 
908
886
    def test_falls_back_to_pre_1_6_1_with_warning(self):
909
887
        with self.assertLogs(log, logging.WARNING):
910
888
            value = string_to_delta("2h")
911
 
        self.assertEqual(datetime.timedelta(0, 7200), value)
 
889
        self.assertEqual(value, datetime.timedelta(0, 7200))
912
890
 
913
891
 
914
892
class Test_check_option_syntax(unittest.TestCase):
952
930
    @contextlib.contextmanager
953
931
    def assertParseError(self):
954
932
        with self.assertRaises(SystemExit) as e:
955
 
            with self.redirect_stderr_to_devnull():
 
933
            with self.temporarily_suppress_stderr():
956
934
                yield
957
935
        # Exit code from argparse is guaranteed to be "2".  Reference:
958
936
        # https://docs.python.org/3/library
959
937
        # /argparse.html#exiting-methods
960
 
        self.assertEqual(2, e.exception.code)
 
938
        self.assertEqual(e.exception.code, 2)
961
939
 
962
940
    @staticmethod
963
941
    @contextlib.contextmanager
964
 
    def redirect_stderr_to_devnull():
 
942
    def temporarily_suppress_stderr():
965
943
        null = os.open(os.path.devnull, os.O_RDWR)
966
944
        stderrcopy = os.dup(sys.stderr.fileno())
967
945
        os.dup2(null, sys.stderr.fileno())
976
954
    def check_option_syntax(self, options):
977
955
        check_option_syntax(self.parser, options)
978
956
 
979
 
    def test_actions_all_conflicts_with_verbose(self):
980
 
        for action, value in self.actions.items():
981
 
            options = self.parser.parse_args()
982
 
            setattr(options, action, value)
983
 
            options.all = True
984
 
            options.verbose = True
985
 
            with self.assertParseError():
986
 
                self.check_option_syntax(options)
987
 
 
988
 
    def test_actions_with_client_conflicts_with_verbose(self):
989
 
        for action, value in self.actions.items():
990
 
            options = self.parser.parse_args()
991
 
            setattr(options, action, value)
992
 
            options.verbose = True
993
 
            options.client = ["foo"]
 
957
    def test_actions_conflicts_with_verbose(self):
 
958
        for action, value in self.actions.items():
 
959
            options = self.parser.parse_args()
 
960
            setattr(options, action, value)
 
961
            options.verbose = True
994
962
            with self.assertParseError():
995
963
                self.check_option_syntax(options)
996
964
 
1022
990
            options.all = True
1023
991
            self.check_option_syntax(options)
1024
992
 
1025
 
    def test_any_action_is_ok_with_one_client(self):
1026
 
        for action, value in self.actions.items():
1027
 
            options = self.parser.parse_args()
1028
 
            setattr(options, action, value)
1029
 
            options.client = ["foo"]
 
993
    def test_is_enabled_fails_without_client(self):
 
994
        options = self.parser.parse_args()
 
995
        options.is_enabled = True
 
996
        with self.assertParseError():
1030
997
            self.check_option_syntax(options)
1031
998
 
1032
 
    def test_one_client_with_all_actions_except_is_enabled(self):
 
999
    def test_is_enabled_works_with_one_client(self):
1033
1000
        options = self.parser.parse_args()
1034
 
        for action, value in self.actions.items():
1035
 
            if action == "is_enabled":
1036
 
                continue
1037
 
            setattr(options, action, value)
 
1001
        options.is_enabled = True
1038
1002
        options.client = ["foo"]
1039
1003
        self.check_option_syntax(options)
1040
1004
 
1041
 
    def test_two_clients_with_all_actions_except_is_enabled(self):
1042
 
        options = self.parser.parse_args()
1043
 
        for action, value in self.actions.items():
1044
 
            if action == "is_enabled":
1045
 
                continue
1046
 
            setattr(options, action, value)
1047
 
        options.client = ["foo", "barbar"]
1048
 
        self.check_option_syntax(options)
1049
 
 
1050
 
    def test_two_clients_are_ok_with_actions_except_is_enabled(self):
1051
 
        for action, value in self.actions.items():
1052
 
            if action == "is_enabled":
1053
 
                continue
1054
 
            options = self.parser.parse_args()
1055
 
            setattr(options, action, value)
1056
 
            options.client = ["foo", "barbar"]
1057
 
            self.check_option_syntax(options)
1058
 
 
1059
 
    def test_is_enabled_fails_without_client(self):
1060
 
        options = self.parser.parse_args()
1061
 
        options.is_enabled = True
1062
 
        with self.assertParseError():
1063
 
            self.check_option_syntax(options)
1064
 
 
1065
1005
    def test_is_enabled_fails_with_two_clients(self):
1066
1006
        options = self.parser.parse_args()
1067
1007
        options.is_enabled = True
1088
1028
            def get_object(mockbus_self, busname, dbus_path):
1089
1029
                # Note that "self" is still the testcase instance,
1090
1030
                # this MockBus instance is in "mockbus_self".
1091
 
                self.assertEqual(dbus_busname, busname)
1092
 
                self.assertEqual(server_dbus_path, dbus_path)
 
1031
                self.assertEqual(busname, dbus_busname)
 
1032
                self.assertEqual(dbus_path, server_dbus_path)
1093
1033
                mockbus_self.called = True
1094
1034
                return mockbus_self
1095
1035
 
1107
1047
                bus = get_mandos_dbus_object(bus=MockBusFailing())
1108
1048
 
1109
1049
        if isinstance(e.exception.code, int):
1110
 
            self.assertNotEqual(0, e.exception.code)
 
1050
            self.assertNotEqual(e.exception.code, 0)
1111
1051
        else:
1112
1052
            self.assertIsNotNone(e.exception.code)
1113
1053
 
1144
1084
                    get_managed_objects(MockObjectManagerFailing())
1145
1085
        finally:
1146
1086
            dbus_logger.removeFilter(counting_handler)
1147
 
 
1148
 
        # Make sure the dbus logger was suppressed
1149
 
        self.assertEqual(0, counting_handler.count)
 
1087
        self.assertEqual(counting_handler.count, 0)
1150
1088
 
1151
1089
        # Test that the dbus_logger still works
1152
1090
        with self.assertLogs(dbus_logger, logging.ERROR):
1153
1091
            dbus_logger.error("Test")
1154
1092
 
1155
1093
        if isinstance(e.exception.code, int):
1156
 
            self.assertNotEqual(0, e.exception.code)
 
1094
            self.assertNotEqual(e.exception.code, 0)
1157
1095
        else:
1158
1096
            self.assertIsNotNone(e.exception.code)
1159
1097
 
1165
1103
 
1166
1104
    def test_is_enabled(self):
1167
1105
        self.assert_command_from_args(["--is-enabled", "foo"],
1168
 
                                      command.IsEnabled)
 
1106
                                      IsEnabledCmd)
1169
1107
 
1170
1108
    def assert_command_from_args(self, args, command_cls,
1171
1109
                                 **cmd_attrs):
1174
1112
        options = self.parser.parse_args(args)
1175
1113
        check_option_syntax(self.parser, options)
1176
1114
        commands = commands_from_options(options)
1177
 
        self.assertEqual(1, len(commands))
 
1115
        self.assertEqual(len(commands), 1)
1178
1116
        command = commands[0]
1179
1117
        self.assertIsInstance(command, command_cls)
1180
1118
        for key, value in cmd_attrs.items():
1181
 
            self.assertEqual(value, getattr(command, key))
 
1119
            self.assertEqual(getattr(command, key), value)
1182
1120
 
1183
1121
    def test_is_enabled_short(self):
1184
 
        self.assert_command_from_args(["-V", "foo"],
1185
 
                                      command.IsEnabled)
 
1122
        self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1186
1123
 
1187
1124
    def test_approve(self):
1188
1125
        self.assert_command_from_args(["--approve", "foo"],
1189
 
                                      command.Approve)
 
1126
                                      ApproveCmd)
1190
1127
 
1191
1128
    def test_approve_short(self):
1192
 
        self.assert_command_from_args(["-A", "foo"], command.Approve)
 
1129
        self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1193
1130
 
1194
1131
    def test_deny(self):
1195
 
        self.assert_command_from_args(["--deny", "foo"], command.Deny)
 
1132
        self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1196
1133
 
1197
1134
    def test_deny_short(self):
1198
 
        self.assert_command_from_args(["-D", "foo"], command.Deny)
 
1135
        self.assert_command_from_args(["-D", "foo"], DenyCmd)
1199
1136
 
1200
1137
    def test_remove(self):
1201
1138
        self.assert_command_from_args(["--remove", "foo"],
1202
 
                                      command.Remove)
 
1139
                                      RemoveCmd)
1203
1140
 
1204
1141
    def test_deny_before_remove(self):
1205
1142
        options = self.parser.parse_args(["--deny", "--remove",
1206
1143
                                          "foo"])
1207
1144
        check_option_syntax(self.parser, options)
1208
1145
        commands = commands_from_options(options)
1209
 
        self.assertEqual(2, len(commands))
1210
 
        self.assertIsInstance(commands[0], command.Deny)
1211
 
        self.assertIsInstance(commands[1], command.Remove)
 
1146
        self.assertEqual(len(commands), 2)
 
1147
        self.assertIsInstance(commands[0], DenyCmd)
 
1148
        self.assertIsInstance(commands[1], RemoveCmd)
1212
1149
 
1213
1150
    def test_deny_before_remove_reversed(self):
1214
1151
        options = self.parser.parse_args(["--remove", "--deny",
1215
1152
                                          "--all"])
1216
1153
        check_option_syntax(self.parser, options)
1217
1154
        commands = commands_from_options(options)
1218
 
        self.assertEqual(2, len(commands))
1219
 
        self.assertIsInstance(commands[0], command.Deny)
1220
 
        self.assertIsInstance(commands[1], command.Remove)
 
1155
        self.assertEqual(len(commands), 2)
 
1156
        self.assertIsInstance(commands[0], DenyCmd)
 
1157
        self.assertIsInstance(commands[1], RemoveCmd)
1221
1158
 
1222
1159
    def test_remove_short(self):
1223
 
        self.assert_command_from_args(["-r", "foo"], command.Remove)
 
1160
        self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1224
1161
 
1225
1162
    def test_dump_json(self):
1226
 
        self.assert_command_from_args(["--dump-json"],
1227
 
                                      command.DumpJSON)
 
1163
        self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1228
1164
 
1229
1165
    def test_enable(self):
1230
 
        self.assert_command_from_args(["--enable", "foo"],
1231
 
                                      command.Enable)
 
1166
        self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1232
1167
 
1233
1168
    def test_enable_short(self):
1234
 
        self.assert_command_from_args(["-e", "foo"], command.Enable)
 
1169
        self.assert_command_from_args(["-e", "foo"], EnableCmd)
1235
1170
 
1236
1171
    def test_disable(self):
1237
1172
        self.assert_command_from_args(["--disable", "foo"],
1238
 
                                      command.Disable)
 
1173
                                      DisableCmd)
1239
1174
 
1240
1175
    def test_disable_short(self):
1241
 
        self.assert_command_from_args(["-d", "foo"], command.Disable)
 
1176
        self.assert_command_from_args(["-d", "foo"], DisableCmd)
1242
1177
 
1243
1178
    def test_bump_timeout(self):
1244
1179
        self.assert_command_from_args(["--bump-timeout", "foo"],
1245
 
                                      command.BumpTimeout)
 
1180
                                      BumpTimeoutCmd)
1246
1181
 
1247
1182
    def test_bump_timeout_short(self):
1248
 
        self.assert_command_from_args(["-b", "foo"],
1249
 
                                      command.BumpTimeout)
 
1183
        self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1250
1184
 
1251
1185
    def test_start_checker(self):
1252
1186
        self.assert_command_from_args(["--start-checker", "foo"],
1253
 
                                      command.StartChecker)
 
1187
                                      StartCheckerCmd)
1254
1188
 
1255
1189
    def test_stop_checker(self):
1256
1190
        self.assert_command_from_args(["--stop-checker", "foo"],
1257
 
                                      command.StopChecker)
 
1191
                                      StopCheckerCmd)
1258
1192
 
1259
1193
    def test_approve_by_default(self):
1260
1194
        self.assert_command_from_args(["--approve-by-default", "foo"],
1261
 
                                      command.ApproveByDefault)
 
1195
                                      ApproveByDefaultCmd)
1262
1196
 
1263
1197
    def test_deny_by_default(self):
1264
1198
        self.assert_command_from_args(["--deny-by-default", "foo"],
1265
 
                                      command.DenyByDefault)
 
1199
                                      DenyByDefaultCmd)
1266
1200
 
1267
1201
    def test_checker(self):
1268
1202
        self.assert_command_from_args(["--checker", ":", "foo"],
1269
 
                                      command.SetChecker,
1270
 
                                      value_to_set=":")
 
1203
                                      SetCheckerCmd, value_to_set=":")
1271
1204
 
1272
1205
    def test_checker_empty(self):
1273
1206
        self.assert_command_from_args(["--checker", "", "foo"],
1274
 
                                      command.SetChecker,
1275
 
                                      value_to_set="")
 
1207
                                      SetCheckerCmd, value_to_set="")
1276
1208
 
1277
1209
    def test_checker_short(self):
1278
1210
        self.assert_command_from_args(["-c", ":", "foo"],
1279
 
                                      command.SetChecker,
1280
 
                                      value_to_set=":")
 
1211
                                      SetCheckerCmd, value_to_set=":")
1281
1212
 
1282
1213
    def test_host(self):
1283
1214
        self.assert_command_from_args(["--host", "foo.example.org",
1284
 
                                       "foo"], command.SetHost,
 
1215
                                       "foo"], SetHostCmd,
1285
1216
                                      value_to_set="foo.example.org")
1286
1217
 
1287
1218
    def test_host_short(self):
1288
1219
        self.assert_command_from_args(["-H", "foo.example.org",
1289
 
                                       "foo"], command.SetHost,
 
1220
                                       "foo"], SetHostCmd,
1290
1221
                                      value_to_set="foo.example.org")
1291
1222
 
1292
1223
    def test_secret_devnull(self):
1293
1224
        self.assert_command_from_args(["--secret", os.path.devnull,
1294
 
                                       "foo"], command.SetSecret,
 
1225
                                       "foo"], SetSecretCmd,
1295
1226
                                      value_to_set=b"")
1296
1227
 
1297
1228
    def test_secret_tempfile(self):
1300
1231
            f.write(value)
1301
1232
            f.seek(0)
1302
1233
            self.assert_command_from_args(["--secret", f.name,
1303
 
                                           "foo"], command.SetSecret,
 
1234
                                           "foo"], SetSecretCmd,
1304
1235
                                          value_to_set=value)
1305
1236
 
1306
1237
    def test_secret_devnull_short(self):
1307
1238
        self.assert_command_from_args(["-s", os.path.devnull, "foo"],
1308
 
                                      command.SetSecret,
1309
 
                                      value_to_set=b"")
 
1239
                                      SetSecretCmd, value_to_set=b"")
1310
1240
 
1311
1241
    def test_secret_tempfile_short(self):
1312
1242
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
1314
1244
            f.write(value)
1315
1245
            f.seek(0)
1316
1246
            self.assert_command_from_args(["-s", f.name, "foo"],
1317
 
                                          command.SetSecret,
 
1247
                                          SetSecretCmd,
1318
1248
                                          value_to_set=value)
1319
1249
 
1320
1250
    def test_timeout(self):
1321
1251
        self.assert_command_from_args(["--timeout", "PT5M", "foo"],
1322
 
                                      command.SetTimeout,
 
1252
                                      SetTimeoutCmd,
1323
1253
                                      value_to_set=300000)
1324
1254
 
1325
1255
    def test_timeout_short(self):
1326
1256
        self.assert_command_from_args(["-t", "PT5M", "foo"],
1327
 
                                      command.SetTimeout,
 
1257
                                      SetTimeoutCmd,
1328
1258
                                      value_to_set=300000)
1329
1259
 
1330
1260
    def test_extended_timeout(self):
1331
1261
        self.assert_command_from_args(["--extended-timeout", "PT15M",
1332
1262
                                       "foo"],
1333
 
                                      command.SetExtendedTimeout,
 
1263
                                      SetExtendedTimeoutCmd,
1334
1264
                                      value_to_set=900000)
1335
1265
 
1336
1266
    def test_interval(self):
1337
1267
        self.assert_command_from_args(["--interval", "PT2M", "foo"],
1338
 
                                      command.SetInterval,
 
1268
                                      SetIntervalCmd,
1339
1269
                                      value_to_set=120000)
1340
1270
 
1341
1271
    def test_interval_short(self):
1342
1272
        self.assert_command_from_args(["-i", "PT2M", "foo"],
1343
 
                                      command.SetInterval,
 
1273
                                      SetIntervalCmd,
1344
1274
                                      value_to_set=120000)
1345
1275
 
1346
1276
    def test_approval_delay(self):
1347
1277
        self.assert_command_from_args(["--approval-delay", "PT30S",
1348
 
                                       "foo"],
1349
 
                                      command.SetApprovalDelay,
 
1278
                                       "foo"], SetApprovalDelayCmd,
1350
1279
                                      value_to_set=30000)
1351
1280
 
1352
1281
    def test_approval_duration(self):
1353
1282
        self.assert_command_from_args(["--approval-duration", "PT1S",
1354
 
                                       "foo"],
1355
 
                                      command.SetApprovalDuration,
 
1283
                                       "foo"], SetApprovalDurationCmd,
1356
1284
                                      value_to_set=1000)
1357
1285
 
1358
1286
    def test_print_table(self):
1359
 
        self.assert_command_from_args([], command.PrintTable,
 
1287
        self.assert_command_from_args([], PrintTableCmd,
1360
1288
                                      verbose=False)
1361
1289
 
1362
1290
    def test_print_table_verbose(self):
1363
 
        self.assert_command_from_args(["--verbose"],
1364
 
                                      command.PrintTable,
 
1291
        self.assert_command_from_args(["--verbose"], PrintTableCmd,
1365
1292
                                      verbose=True)
1366
1293
 
1367
1294
    def test_print_table_verbose_short(self):
1368
 
        self.assert_command_from_args(["-v"], command.PrintTable,
 
1295
        self.assert_command_from_args(["-v"], PrintTableCmd,
1369
1296
                                      verbose=True)
1370
1297
 
1371
1298
 
1372
 
class TestCommand(unittest.TestCase):
 
1299
class TestCmd(unittest.TestCase):
1373
1300
    """Abstract class for tests of command classes"""
1374
1301
 
1375
1302
    def setUp(self):
1381
1308
                self.attributes["Name"] = name
1382
1309
                self.calls = []
1383
1310
            def Set(self, interface, propname, value, dbus_interface):
1384
 
                testcase.assertEqual(client_dbus_interface, interface)
1385
 
                testcase.assertEqual(dbus.PROPERTIES_IFACE,
1386
 
                                     dbus_interface)
 
1311
                testcase.assertEqual(interface, client_dbus_interface)
 
1312
                testcase.assertEqual(dbus_interface,
 
1313
                                     dbus.PROPERTIES_IFACE)
1387
1314
                self.attributes[propname] = value
 
1315
            def Get(self, interface, propname, dbus_interface):
 
1316
                testcase.assertEqual(interface, client_dbus_interface)
 
1317
                testcase.assertEqual(dbus_interface,
 
1318
                                     dbus.PROPERTIES_IFACE)
 
1319
                return self.attributes[propname]
1388
1320
            def Approve(self, approve, dbus_interface):
1389
 
                testcase.assertEqual(client_dbus_interface,
1390
 
                                     dbus_interface)
 
1321
                testcase.assertEqual(dbus_interface,
 
1322
                                     client_dbus_interface)
1391
1323
                self.calls.append(("Approve", (approve,
1392
1324
                                               dbus_interface)))
1393
1325
        self.client = MockClient(
1450
1382
        class Bus(object):
1451
1383
            @staticmethod
1452
1384
            def get_object(client_bus_name, path):
1453
 
                self.assertEqual(dbus_busname, client_bus_name)
 
1385
                self.assertEqual(client_bus_name, dbus_busname)
1454
1386
                return {
1455
1387
                    # Note: "self" here is the TestCmd instance, not
1456
1388
                    # the Bus instance, since this is a static method!
1460
1392
        return Bus()
1461
1393
 
1462
1394
 
1463
 
class TestBaseCommands(TestCommand):
 
1395
class TestIsEnabledCmd(TestCmd):
 
1396
    def test_is_enabled(self):
 
1397
        self.assertTrue(all(IsEnabledCmd().is_enabled(client,
 
1398
                                                      properties)
 
1399
                            for client, properties
 
1400
                            in self.clients.items()))
1464
1401
 
1465
 
    def test_IsEnabled_exits_successfully(self):
 
1402
    def test_is_enabled_run_exits_successfully(self):
1466
1403
        with self.assertRaises(SystemExit) as e:
1467
 
            command.IsEnabled().run(self.one_client)
 
1404
            IsEnabledCmd().run(self.one_client)
1468
1405
        if e.exception.code is not None:
1469
 
            self.assertEqual(0, e.exception.code)
 
1406
            self.assertEqual(e.exception.code, 0)
1470
1407
        else:
1471
1408
            self.assertIsNone(e.exception.code)
1472
1409
 
1473
 
    def test_IsEnabled_exits_with_failure(self):
 
1410
    def test_is_enabled_run_exits_with_failure(self):
1474
1411
        self.client.attributes["Enabled"] = dbus.Boolean(False)
1475
1412
        with self.assertRaises(SystemExit) as e:
1476
 
            command.IsEnabled().run(self.one_client)
 
1413
            IsEnabledCmd().run(self.one_client)
1477
1414
        if isinstance(e.exception.code, int):
1478
 
            self.assertNotEqual(0, e.exception.code)
 
1415
            self.assertNotEqual(e.exception.code, 0)
1479
1416
        else:
1480
1417
            self.assertIsNotNone(e.exception.code)
1481
1418
 
1482
 
    def test_Approve(self):
1483
 
        command.Approve().run(self.clients, self.bus)
 
1419
 
 
1420
class TestApproveCmd(TestCmd):
 
1421
    def test_approve(self):
 
1422
        ApproveCmd().run(self.clients, self.bus)
1484
1423
        for clientpath in self.clients:
1485
1424
            client = self.bus.get_object(dbus_busname, clientpath)
1486
1425
            self.assertIn(("Approve", (True, client_dbus_interface)),
1487
1426
                          client.calls)
1488
1427
 
1489
 
    def test_Deny(self):
1490
 
        command.Deny().run(self.clients, self.bus)
 
1428
 
 
1429
class TestDenyCmd(TestCmd):
 
1430
    def test_deny(self):
 
1431
        DenyCmd().run(self.clients, self.bus)
1491
1432
        for clientpath in self.clients:
1492
1433
            client = self.bus.get_object(dbus_busname, clientpath)
1493
1434
            self.assertIn(("Approve", (False, client_dbus_interface)),
1494
1435
                          client.calls)
1495
1436
 
1496
 
    def test_Remove(self):
 
1437
 
 
1438
class TestRemoveCmd(TestCmd):
 
1439
    def test_remove(self):
1497
1440
        class MockMandos(object):
1498
1441
            def __init__(self):
1499
1442
                self.calls = []
1500
1443
            def RemoveClient(self, dbus_path):
1501
1444
                self.calls.append(("RemoveClient", (dbus_path,)))
1502
1445
        mandos = MockMandos()
1503
 
        command.Remove().run(self.clients, self.bus, mandos)
 
1446
        super(TestRemoveCmd, self).setUp()
 
1447
        RemoveCmd().run(self.clients, self.bus, mandos)
 
1448
        self.assertEqual(len(mandos.calls), 2)
1504
1449
        for clientpath in self.clients:
1505
1450
            self.assertIn(("RemoveClient", (clientpath,)),
1506
1451
                          mandos.calls)
1507
1452
 
1508
 
    expected_json = {
1509
 
        "foo": {
1510
 
            "Name": "foo",
1511
 
            "KeyID": ("92ed150794387c03ce684574b1139a65"
1512
 
                      "94a34f895daaaf09fd8ea90a27cddb12"),
1513
 
            "Host": "foo.example.org",
1514
 
            "Enabled": True,
1515
 
            "Timeout": 300000,
1516
 
            "LastCheckedOK": "2019-02-03T00:00:00",
1517
 
            "Created": "2019-01-02T00:00:00",
1518
 
            "Interval": 120000,
1519
 
            "Fingerprint": ("778827225BA7DE539C5A"
1520
 
                            "7CFA59CFF7CDBD9A5920"),
1521
 
            "CheckerRunning": False,
1522
 
            "LastEnabled": "2019-01-03T00:00:00",
1523
 
            "ApprovalPending": False,
1524
 
            "ApprovedByDefault": True,
1525
 
            "LastApprovalRequest": "",
1526
 
            "ApprovalDelay": 0,
1527
 
            "ApprovalDuration": 1000,
1528
 
            "Checker": "fping -q -- %(host)s",
1529
 
            "ExtendedTimeout": 900000,
1530
 
            "Expires": "2019-02-04T00:00:00",
1531
 
            "LastCheckerStatus": 0,
1532
 
        },
1533
 
        "barbar": {
1534
 
            "Name": "barbar",
1535
 
            "KeyID": ("0558568eedd67d622f5c83b35a115f79"
1536
 
                      "6ab612cff5ad227247e46c2b020f441c"),
1537
 
            "Host": "192.0.2.3",
1538
 
            "Enabled": True,
1539
 
            "Timeout": 300000,
1540
 
            "LastCheckedOK": "2019-02-04T00:00:00",
1541
 
            "Created": "2019-01-03T00:00:00",
1542
 
            "Interval": 120000,
1543
 
            "Fingerprint": ("3E393AEAEFB84C7E89E2"
1544
 
                            "F547B3A107558FCA3A27"),
1545
 
            "CheckerRunning": True,
1546
 
            "LastEnabled": "2019-01-04T00:00:00",
1547
 
            "ApprovalPending": False,
1548
 
            "ApprovedByDefault": False,
1549
 
            "LastApprovalRequest": "2019-01-03T00:00:00",
1550
 
            "ApprovalDelay": 30000,
1551
 
            "ApprovalDuration": 93785000,
1552
 
            "Checker": ":",
1553
 
            "ExtendedTimeout": 900000,
1554
 
            "Expires": "2019-02-05T00:00:00",
1555
 
            "LastCheckerStatus": -2,
1556
 
        },
1557
 
    }
1558
 
 
1559
 
    def test_DumpJSON_normal(self):
1560
 
        output = command.DumpJSON().output(self.clients.values())
 
1453
 
 
1454
class TestDumpJSONCmd(TestCmd):
 
1455
    def setUp(self):
 
1456
        self.expected_json = {
 
1457
            "foo": {
 
1458
                "Name": "foo",
 
1459
                "KeyID": ("92ed150794387c03ce684574b1139a65"
 
1460
                          "94a34f895daaaf09fd8ea90a27cddb12"),
 
1461
                "Host": "foo.example.org",
 
1462
                "Enabled": True,
 
1463
                "Timeout": 300000,
 
1464
                "LastCheckedOK": "2019-02-03T00:00:00",
 
1465
                "Created": "2019-01-02T00:00:00",
 
1466
                "Interval": 120000,
 
1467
                "Fingerprint": ("778827225BA7DE539C5A"
 
1468
                                "7CFA59CFF7CDBD9A5920"),
 
1469
                "CheckerRunning": False,
 
1470
                "LastEnabled": "2019-01-03T00:00:00",
 
1471
                "ApprovalPending": False,
 
1472
                "ApprovedByDefault": True,
 
1473
                "LastApprovalRequest": "",
 
1474
                "ApprovalDelay": 0,
 
1475
                "ApprovalDuration": 1000,
 
1476
                "Checker": "fping -q -- %(host)s",
 
1477
                "ExtendedTimeout": 900000,
 
1478
                "Expires": "2019-02-04T00:00:00",
 
1479
                "LastCheckerStatus": 0,
 
1480
            },
 
1481
            "barbar": {
 
1482
                "Name": "barbar",
 
1483
                "KeyID": ("0558568eedd67d622f5c83b35a115f79"
 
1484
                          "6ab612cff5ad227247e46c2b020f441c"),
 
1485
                "Host": "192.0.2.3",
 
1486
                "Enabled": True,
 
1487
                "Timeout": 300000,
 
1488
                "LastCheckedOK": "2019-02-04T00:00:00",
 
1489
                "Created": "2019-01-03T00:00:00",
 
1490
                "Interval": 120000,
 
1491
                "Fingerprint": ("3E393AEAEFB84C7E89E2"
 
1492
                                "F547B3A107558FCA3A27"),
 
1493
                "CheckerRunning": True,
 
1494
                "LastEnabled": "2019-01-04T00:00:00",
 
1495
                "ApprovalPending": False,
 
1496
                "ApprovedByDefault": False,
 
1497
                "LastApprovalRequest": "2019-01-03T00:00:00",
 
1498
                "ApprovalDelay": 30000,
 
1499
                "ApprovalDuration": 93785000,
 
1500
                "Checker": ":",
 
1501
                "ExtendedTimeout": 900000,
 
1502
                "Expires": "2019-02-05T00:00:00",
 
1503
                "LastCheckerStatus": -2,
 
1504
            },
 
1505
        }
 
1506
        return super(TestDumpJSONCmd, self).setUp()
 
1507
 
 
1508
    def test_normal(self):
 
1509
        output = DumpJSONCmd().output(self.clients.values())
1561
1510
        json_data = json.loads(output)
1562
 
        self.assertDictEqual(self.expected_json, json_data)
 
1511
        self.assertDictEqual(json_data, self.expected_json)
1563
1512
 
1564
 
    def test_DumpJSON_one_client(self):
1565
 
        output = command.DumpJSON().output(self.one_client.values())
 
1513
    def test_one_client(self):
 
1514
        output = DumpJSONCmd().output(self.one_client.values())
1566
1515
        json_data = json.loads(output)
1567
1516
        expected_json = {"foo": self.expected_json["foo"]}
1568
 
        self.assertDictEqual(expected_json, json_data)
1569
 
 
1570
 
    def test_PrintTable_normal(self):
1571
 
        output = command.PrintTable().output(self.clients.values())
 
1517
        self.assertDictEqual(json_data, expected_json)
 
1518
 
 
1519
 
 
1520
class TestPrintTableCmd(TestCmd):
 
1521
    def test_normal(self):
 
1522
        output = PrintTableCmd().output(self.clients.values())
1572
1523
        expected_output = "\n".join((
1573
1524
            "Name   Enabled Timeout  Last Successful Check",
1574
1525
            "foo    Yes     00:05:00 2019-02-03T00:00:00  ",
1575
1526
            "barbar Yes     00:05:00 2019-02-04T00:00:00  ",
1576
1527
        ))
1577
 
        self.assertEqual(expected_output, output)
 
1528
        self.assertEqual(output, expected_output)
1578
1529
 
1579
 
    def test_PrintTable_verbose(self):
1580
 
        output = command.PrintTable(verbose=True).output(
 
1530
    def test_verbose(self):
 
1531
        output = PrintTableCmd(verbose=True).output(
1581
1532
            self.clients.values())
1582
1533
        columns = (
1583
1534
            (
1669
1620
        expected_output = "\n".join("".join(rows[line]
1670
1621
                                            for rows in columns)
1671
1622
                                    for line in range(num_lines))
1672
 
        self.assertEqual(expected_output, output)
 
1623
        self.assertEqual(output, expected_output)
1673
1624
 
1674
 
    def test_PrintTable_one_client(self):
1675
 
        output = command.PrintTable().output(self.one_client.values())
 
1625
    def test_one_client(self):
 
1626
        output = PrintTableCmd().output(self.one_client.values())
1676
1627
        expected_output = "\n".join((
1677
1628
            "Name Enabled Timeout  Last Successful Check",
1678
1629
            "foo  Yes     00:05:00 2019-02-03T00:00:00  ",
1679
1630
        ))
1680
 
        self.assertEqual(expected_output, output)
1681
 
 
1682
 
 
1683
 
class TestPropertyCmd(TestCommand):
1684
 
    """Abstract class for tests of command.Property classes"""
 
1631
        self.assertEqual(output, expected_output)
 
1632
 
 
1633
 
 
1634
class TestPropertyCmd(TestCmd):
 
1635
    """Abstract class for tests of PropertyCmd classes"""
1685
1636
    def runTest(self):
1686
1637
        if not hasattr(self, "command"):
1687
1638
            return
1692
1643
            for clientpath in self.clients:
1693
1644
                client = self.bus.get_object(dbus_busname, clientpath)
1694
1645
                old_value = client.attributes[self.propname]
 
1646
                self.assertNotIsInstance(old_value, self.Unique)
1695
1647
                client.attributes[self.propname] = self.Unique()
1696
1648
            self.run_command(value_to_set, self.clients)
1697
1649
            for clientpath in self.clients:
1698
1650
                client = self.bus.get_object(dbus_busname, clientpath)
1699
1651
                value = client.attributes[self.propname]
1700
1652
                self.assertNotIsInstance(value, self.Unique)
1701
 
                self.assertEqual(value_to_get, value)
 
1653
                self.assertEqual(value, value_to_get)
1702
1654
 
1703
1655
    class Unique(object):
1704
1656
        """Class for objects which exist only to be unique objects,
1709
1661
 
1710
1662
 
1711
1663
class TestEnableCmd(TestPropertyCmd):
1712
 
    command = command.Enable
 
1664
    command = EnableCmd
1713
1665
    propname = "Enabled"
1714
1666
    values_to_set = [dbus.Boolean(True)]
1715
1667
 
1716
1668
 
1717
1669
class TestDisableCmd(TestPropertyCmd):
1718
 
    command = command.Disable
 
1670
    command = DisableCmd
1719
1671
    propname = "Enabled"
1720
1672
    values_to_set = [dbus.Boolean(False)]
1721
1673
 
1722
1674
 
1723
1675
class TestBumpTimeoutCmd(TestPropertyCmd):
1724
 
    command = command.BumpTimeout
 
1676
    command = BumpTimeoutCmd
1725
1677
    propname = "LastCheckedOK"
1726
1678
    values_to_set = [""]
1727
1679
 
1728
1680
 
1729
1681
class TestStartCheckerCmd(TestPropertyCmd):
1730
 
    command = command.StartChecker
 
1682
    command = StartCheckerCmd
1731
1683
    propname = "CheckerRunning"
1732
1684
    values_to_set = [dbus.Boolean(True)]
1733
1685
 
1734
1686
 
1735
1687
class TestStopCheckerCmd(TestPropertyCmd):
1736
 
    command = command.StopChecker
 
1688
    command = StopCheckerCmd
1737
1689
    propname = "CheckerRunning"
1738
1690
    values_to_set = [dbus.Boolean(False)]
1739
1691
 
1740
1692
 
1741
1693
class TestApproveByDefaultCmd(TestPropertyCmd):
1742
 
    command = command.ApproveByDefault
 
1694
    command = ApproveByDefaultCmd
1743
1695
    propname = "ApprovedByDefault"
1744
1696
    values_to_set = [dbus.Boolean(True)]
1745
1697
 
1746
1698
 
1747
1699
class TestDenyByDefaultCmd(TestPropertyCmd):
1748
 
    command = command.DenyByDefault
 
1700
    command = DenyByDefaultCmd
1749
1701
    propname = "ApprovedByDefault"
1750
1702
    values_to_set = [dbus.Boolean(False)]
1751
1703
 
1763
1715
 
1764
1716
 
1765
1717
class TestSetCheckerCmd(TestPropertyValueCmd):
1766
 
    command = command.SetChecker
 
1718
    command = SetCheckerCmd
1767
1719
    propname = "Checker"
1768
1720
    values_to_set = ["", ":", "fping -q -- %s"]
1769
1721
 
1770
1722
 
1771
1723
class TestSetHostCmd(TestPropertyValueCmd):
1772
 
    command = command.SetHost
 
1724
    command = SetHostCmd
1773
1725
    propname = "Host"
1774
1726
    values_to_set = ["192.0.2.3", "foo.example.org"]
1775
1727
 
1776
1728
 
1777
1729
class TestSetSecretCmd(TestPropertyValueCmd):
1778
 
    command = command.SetSecret
 
1730
    command = SetSecretCmd
1779
1731
    propname = "Secret"
1780
1732
    values_to_set = [io.BytesIO(b""),
1781
1733
                     io.BytesIO(b"secret\0xyzzy\nbar")]
1783
1735
 
1784
1736
 
1785
1737
class TestSetTimeoutCmd(TestPropertyValueCmd):
1786
 
    command = command.SetTimeout
 
1738
    command = SetTimeoutCmd
1787
1739
    propname = "Timeout"
1788
1740
    values_to_set = [datetime.timedelta(),
1789
1741
                     datetime.timedelta(minutes=5),
1794
1746
 
1795
1747
 
1796
1748
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
1797
 
    command = command.SetExtendedTimeout
 
1749
    command = SetExtendedTimeoutCmd
1798
1750
    propname = "ExtendedTimeout"
1799
1751
    values_to_set = [datetime.timedelta(),
1800
1752
                     datetime.timedelta(minutes=5),
1805
1757
 
1806
1758
 
1807
1759
class TestSetIntervalCmd(TestPropertyValueCmd):
1808
 
    command = command.SetInterval
 
1760
    command = SetIntervalCmd
1809
1761
    propname = "Interval"
1810
1762
    values_to_set = [datetime.timedelta(),
1811
1763
                     datetime.timedelta(minutes=5),
1816
1768
 
1817
1769
 
1818
1770
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
1819
 
    command = command.SetApprovalDelay
 
1771
    command = SetApprovalDelayCmd
1820
1772
    propname = "ApprovalDelay"
1821
1773
    values_to_set = [datetime.timedelta(),
1822
1774
                     datetime.timedelta(minutes=5),
1827
1779
 
1828
1780
 
1829
1781
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
1830
 
    command = command.SetApprovalDuration
 
1782
    command = SetApprovalDurationCmd
1831
1783
    propname = "ApprovalDuration"
1832
1784
    values_to_set = [datetime.timedelta(),
1833
1785
                     datetime.timedelta(minutes=5),