/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-17 18:17:02 UTC
  • mto: This revision was merged to the branch mainline in revision 382.
  • Revision ID: teddy@recompile.se-20190317181702-tf6uvnb0gnyw9z8v
mandos-ctl: Refactor tests

* mandos-ctl (Test_check_option_syntax.redirect_stderr_to_devnull):
  Override file objects instead of raw file descriptors.

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
129
128
    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: u''
 
235
    ValueError: Invalid RFC 3339 duration: ""
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: u'1D'
 
240
    ValueError: Invalid RFC 3339 duration: "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: u'PT1S2M'
 
245
    ValueError: Invalid RFC 3339 duration: "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: u'P1H2S'
 
250
    ValueError: Invalid RFC 3339 duration: "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: u'P1D2W'
 
255
    ValueError: Invalid RFC 3339 duration: "P1D2W"
256
256
    >>> rfc3339_duration_to_delta("P2W2H")
257
257
    Traceback (most recent call last):
258
258
    ...
259
 
    ValueError: Invalid RFC 3339 duration: u'P2W2H'
 
259
    ValueError: Invalid RFC 3339 duration: "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: {!r}"
 
336
            raise ValueError("Invalid RFC 3339 duration: \"{}\""
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(IsEnabledCmd())
 
480
        commands.append(command.IsEnabled())
481
481
 
482
482
    if options.approve:
483
 
        commands.append(ApproveCmd())
 
483
        commands.append(command.Approve())
484
484
 
485
485
    if options.deny:
486
 
        commands.append(DenyCmd())
 
486
        commands.append(command.Deny())
487
487
 
488
488
    if options.remove:
489
 
        commands.append(RemoveCmd())
 
489
        commands.append(command.Remove())
490
490
 
491
491
    if options.dump_json:
492
 
        commands.append(DumpJSONCmd())
 
492
        commands.append(command.DumpJSON())
493
493
 
494
494
    if options.enable:
495
 
        commands.append(EnableCmd())
 
495
        commands.append(command.Enable())
496
496
 
497
497
    if options.disable:
498
 
        commands.append(DisableCmd())
 
498
        commands.append(command.Disable())
499
499
 
500
500
    if options.bump_timeout:
501
 
        commands.append(BumpTimeoutCmd())
 
501
        commands.append(command.BumpTimeout())
502
502
 
503
503
    if options.start_checker:
504
 
        commands.append(StartCheckerCmd())
 
504
        commands.append(command.StartChecker())
505
505
 
506
506
    if options.stop_checker:
507
 
        commands.append(StopCheckerCmd())
 
507
        commands.append(command.StopChecker())
508
508
 
509
509
    if options.approved_by_default is not None:
510
510
        if options.approved_by_default:
511
 
            commands.append(ApproveByDefaultCmd())
 
511
            commands.append(command.ApproveByDefault())
512
512
        else:
513
 
            commands.append(DenyByDefaultCmd())
 
513
            commands.append(command.DenyByDefault())
514
514
 
515
515
    if options.checker is not None:
516
 
        commands.append(SetCheckerCmd(options.checker))
 
516
        commands.append(command.SetChecker(options.checker))
517
517
 
518
518
    if options.host is not None:
519
 
        commands.append(SetHostCmd(options.host))
 
519
        commands.append(command.SetHost(options.host))
520
520
 
521
521
    if options.secret is not None:
522
 
        commands.append(SetSecretCmd(options.secret))
 
522
        commands.append(command.SetSecret(options.secret))
523
523
 
524
524
    if options.timeout is not None:
525
 
        commands.append(SetTimeoutCmd(options.timeout))
 
525
        commands.append(command.SetTimeout(options.timeout))
526
526
 
527
527
    if options.extended_timeout:
528
528
        commands.append(
529
 
            SetExtendedTimeoutCmd(options.extended_timeout))
 
529
            command.SetExtendedTimeout(options.extended_timeout))
530
530
 
531
531
    if options.interval is not None:
532
 
        commands.append(SetIntervalCmd(options.interval))
 
532
        commands.append(command.SetInterval(options.interval))
533
533
 
534
534
    if options.approval_delay is not None:
535
 
        commands.append(SetApprovalDelayCmd(options.approval_delay))
 
535
        commands.append(
 
536
            command.SetApprovalDelay(options.approval_delay))
536
537
 
537
538
    if options.approval_duration is not None:
538
539
        commands.append(
539
 
            SetApprovalDurationCmd(options.approval_duration))
 
540
            command.SetApprovalDuration(options.approval_duration))
540
541
 
541
542
    # If no command option has been given, show table of clients,
542
543
    # optionally verbosely
543
544
    if not commands:
544
 
        commands.append(PrintTableCmd(verbose=options.verbose))
 
545
        commands.append(command.PrintTable(verbose=options.verbose))
545
546
 
546
547
    return commands
547
548
 
548
549
 
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__
 
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=(',', ': '))
 
630
 
 
631
        @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
 
674
678
            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})
712
 
 
713
 
        @staticmethod
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
 
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
809
821
a datetime.timedelta() but should store it as milliseconds."""
810
822
 
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"
 
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"
839
851
 
840
852
 
841
853
 
872
884
                                                    ("records",
873
885
                                                     "output"))
874
886
 
 
887
 
875
888
class Test_string_to_delta(TestCaseWithAssertLogs):
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))
 
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"))
885
907
 
886
908
    def test_falls_back_to_pre_1_6_1_with_warning(self):
887
909
        with self.assertLogs(log, logging.WARNING):
888
910
            value = string_to_delta("2h")
889
 
        self.assertEqual(value, datetime.timedelta(0, 7200))
 
911
        self.assertEqual(datetime.timedelta(0, 7200), value)
890
912
 
891
913
 
892
914
class Test_check_option_syntax(unittest.TestCase):
930
952
    @contextlib.contextmanager
931
953
    def assertParseError(self):
932
954
        with self.assertRaises(SystemExit) as e:
933
 
            with self.temporarily_suppress_stderr():
 
955
            with self.redirect_stderr_to_devnull():
934
956
                yield
935
957
        # Exit code from argparse is guaranteed to be "2".  Reference:
936
958
        # https://docs.python.org/3/library
937
959
        # /argparse.html#exiting-methods
938
 
        self.assertEqual(e.exception.code, 2)
 
960
        self.assertEqual(2, e.exception.code)
939
961
 
940
962
    @staticmethod
941
963
    @contextlib.contextmanager
942
 
    def temporarily_suppress_stderr():
943
 
        null = os.open(os.path.devnull, os.O_RDWR)
944
 
        stderrcopy = os.dup(sys.stderr.fileno())
945
 
        os.dup2(null, sys.stderr.fileno())
946
 
        os.close(null)
947
 
        try:
948
 
            yield
949
 
        finally:
950
 
            # restore stderr
951
 
            os.dup2(stderrcopy, sys.stderr.fileno())
952
 
            os.close(stderrcopy)
 
964
    def redirect_stderr_to_devnull():
 
965
        old_stderr = sys.stderr
 
966
        with contextlib.closing(open(os.devnull, "w")) as null:
 
967
            sys.stderr = null
 
968
            try:
 
969
                yield
 
970
            finally:
 
971
                sys.stderr = old_stderr
953
972
 
954
973
    def check_option_syntax(self, options):
955
974
        check_option_syntax(self.parser, options)
1007
1026
            options.client = ["foo"]
1008
1027
            self.check_option_syntax(options)
1009
1028
 
1010
 
    def test_actions_except_is_enabled_are_ok_with_two_clients(self):
 
1029
    def test_one_client_with_all_actions_except_is_enabled(self):
 
1030
        options = self.parser.parse_args()
 
1031
        for action, value in self.actions.items():
 
1032
            if action == "is_enabled":
 
1033
                continue
 
1034
            setattr(options, action, value)
 
1035
        options.client = ["foo"]
 
1036
        self.check_option_syntax(options)
 
1037
 
 
1038
    def test_two_clients_with_all_actions_except_is_enabled(self):
 
1039
        options = self.parser.parse_args()
 
1040
        for action, value in self.actions.items():
 
1041
            if action == "is_enabled":
 
1042
                continue
 
1043
            setattr(options, action, value)
 
1044
        options.client = ["foo", "barbar"]
 
1045
        self.check_option_syntax(options)
 
1046
 
 
1047
    def test_two_clients_are_ok_with_actions_except_is_enabled(self):
1011
1048
        for action, value in self.actions.items():
1012
1049
            if action == "is_enabled":
1013
1050
                continue
1048
1085
            def get_object(mockbus_self, busname, dbus_path):
1049
1086
                # Note that "self" is still the testcase instance,
1050
1087
                # this MockBus instance is in "mockbus_self".
1051
 
                self.assertEqual(busname, dbus_busname)
1052
 
                self.assertEqual(dbus_path, server_dbus_path)
 
1088
                self.assertEqual(dbus_busname, busname)
 
1089
                self.assertEqual(server_dbus_path, dbus_path)
1053
1090
                mockbus_self.called = True
1054
1091
                return mockbus_self
1055
1092
 
1067
1104
                bus = get_mandos_dbus_object(bus=MockBusFailing())
1068
1105
 
1069
1106
        if isinstance(e.exception.code, int):
1070
 
            self.assertNotEqual(e.exception.code, 0)
 
1107
            self.assertNotEqual(0, e.exception.code)
1071
1108
        else:
1072
1109
            self.assertIsNotNone(e.exception.code)
1073
1110
 
1106
1143
            dbus_logger.removeFilter(counting_handler)
1107
1144
 
1108
1145
        # Make sure the dbus logger was suppressed
1109
 
        self.assertEqual(counting_handler.count, 0)
 
1146
        self.assertEqual(0, counting_handler.count)
1110
1147
 
1111
1148
        # Test that the dbus_logger still works
1112
1149
        with self.assertLogs(dbus_logger, logging.ERROR):
1113
1150
            dbus_logger.error("Test")
1114
1151
 
1115
1152
        if isinstance(e.exception.code, int):
1116
 
            self.assertNotEqual(e.exception.code, 0)
 
1153
            self.assertNotEqual(0, e.exception.code)
1117
1154
        else:
1118
1155
            self.assertIsNotNone(e.exception.code)
1119
1156
 
1125
1162
 
1126
1163
    def test_is_enabled(self):
1127
1164
        self.assert_command_from_args(["--is-enabled", "foo"],
1128
 
                                      IsEnabledCmd)
 
1165
                                      command.IsEnabled)
1129
1166
 
1130
1167
    def assert_command_from_args(self, args, command_cls,
1131
1168
                                 **cmd_attrs):
1134
1171
        options = self.parser.parse_args(args)
1135
1172
        check_option_syntax(self.parser, options)
1136
1173
        commands = commands_from_options(options)
1137
 
        self.assertEqual(len(commands), 1)
 
1174
        self.assertEqual(1, len(commands))
1138
1175
        command = commands[0]
1139
1176
        self.assertIsInstance(command, command_cls)
1140
1177
        for key, value in cmd_attrs.items():
1141
 
            self.assertEqual(getattr(command, key), value)
 
1178
            self.assertEqual(value, getattr(command, key))
1142
1179
 
1143
1180
    def test_is_enabled_short(self):
1144
 
        self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
 
1181
        self.assert_command_from_args(["-V", "foo"],
 
1182
                                      command.IsEnabled)
1145
1183
 
1146
1184
    def test_approve(self):
1147
1185
        self.assert_command_from_args(["--approve", "foo"],
1148
 
                                      ApproveCmd)
 
1186
                                      command.Approve)
1149
1187
 
1150
1188
    def test_approve_short(self):
1151
 
        self.assert_command_from_args(["-A", "foo"], ApproveCmd)
 
1189
        self.assert_command_from_args(["-A", "foo"], command.Approve)
1152
1190
 
1153
1191
    def test_deny(self):
1154
 
        self.assert_command_from_args(["--deny", "foo"], DenyCmd)
 
1192
        self.assert_command_from_args(["--deny", "foo"], command.Deny)
1155
1193
 
1156
1194
    def test_deny_short(self):
1157
 
        self.assert_command_from_args(["-D", "foo"], DenyCmd)
 
1195
        self.assert_command_from_args(["-D", "foo"], command.Deny)
1158
1196
 
1159
1197
    def test_remove(self):
1160
1198
        self.assert_command_from_args(["--remove", "foo"],
1161
 
                                      RemoveCmd)
 
1199
                                      command.Remove)
1162
1200
 
1163
1201
    def test_deny_before_remove(self):
1164
1202
        options = self.parser.parse_args(["--deny", "--remove",
1165
1203
                                          "foo"])
1166
1204
        check_option_syntax(self.parser, options)
1167
1205
        commands = commands_from_options(options)
1168
 
        self.assertEqual(len(commands), 2)
1169
 
        self.assertIsInstance(commands[0], DenyCmd)
1170
 
        self.assertIsInstance(commands[1], RemoveCmd)
 
1206
        self.assertEqual(2, len(commands))
 
1207
        self.assertIsInstance(commands[0], command.Deny)
 
1208
        self.assertIsInstance(commands[1], command.Remove)
1171
1209
 
1172
1210
    def test_deny_before_remove_reversed(self):
1173
1211
        options = self.parser.parse_args(["--remove", "--deny",
1174
1212
                                          "--all"])
1175
1213
        check_option_syntax(self.parser, options)
1176
1214
        commands = commands_from_options(options)
1177
 
        self.assertEqual(len(commands), 2)
1178
 
        self.assertIsInstance(commands[0], DenyCmd)
1179
 
        self.assertIsInstance(commands[1], RemoveCmd)
 
1215
        self.assertEqual(2, len(commands))
 
1216
        self.assertIsInstance(commands[0], command.Deny)
 
1217
        self.assertIsInstance(commands[1], command.Remove)
1180
1218
 
1181
1219
    def test_remove_short(self):
1182
 
        self.assert_command_from_args(["-r", "foo"], RemoveCmd)
 
1220
        self.assert_command_from_args(["-r", "foo"], command.Remove)
1183
1221
 
1184
1222
    def test_dump_json(self):
1185
 
        self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
 
1223
        self.assert_command_from_args(["--dump-json"],
 
1224
                                      command.DumpJSON)
1186
1225
 
1187
1226
    def test_enable(self):
1188
 
        self.assert_command_from_args(["--enable", "foo"], EnableCmd)
 
1227
        self.assert_command_from_args(["--enable", "foo"],
 
1228
                                      command.Enable)
1189
1229
 
1190
1230
    def test_enable_short(self):
1191
 
        self.assert_command_from_args(["-e", "foo"], EnableCmd)
 
1231
        self.assert_command_from_args(["-e", "foo"], command.Enable)
1192
1232
 
1193
1233
    def test_disable(self):
1194
1234
        self.assert_command_from_args(["--disable", "foo"],
1195
 
                                      DisableCmd)
 
1235
                                      command.Disable)
1196
1236
 
1197
1237
    def test_disable_short(self):
1198
 
        self.assert_command_from_args(["-d", "foo"], DisableCmd)
 
1238
        self.assert_command_from_args(["-d", "foo"], command.Disable)
1199
1239
 
1200
1240
    def test_bump_timeout(self):
1201
1241
        self.assert_command_from_args(["--bump-timeout", "foo"],
1202
 
                                      BumpTimeoutCmd)
 
1242
                                      command.BumpTimeout)
1203
1243
 
1204
1244
    def test_bump_timeout_short(self):
1205
 
        self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
 
1245
        self.assert_command_from_args(["-b", "foo"],
 
1246
                                      command.BumpTimeout)
1206
1247
 
1207
1248
    def test_start_checker(self):
1208
1249
        self.assert_command_from_args(["--start-checker", "foo"],
1209
 
                                      StartCheckerCmd)
 
1250
                                      command.StartChecker)
1210
1251
 
1211
1252
    def test_stop_checker(self):
1212
1253
        self.assert_command_from_args(["--stop-checker", "foo"],
1213
 
                                      StopCheckerCmd)
 
1254
                                      command.StopChecker)
1214
1255
 
1215
1256
    def test_approve_by_default(self):
1216
1257
        self.assert_command_from_args(["--approve-by-default", "foo"],
1217
 
                                      ApproveByDefaultCmd)
 
1258
                                      command.ApproveByDefault)
1218
1259
 
1219
1260
    def test_deny_by_default(self):
1220
1261
        self.assert_command_from_args(["--deny-by-default", "foo"],
1221
 
                                      DenyByDefaultCmd)
 
1262
                                      command.DenyByDefault)
1222
1263
 
1223
1264
    def test_checker(self):
1224
1265
        self.assert_command_from_args(["--checker", ":", "foo"],
1225
 
                                      SetCheckerCmd, value_to_set=":")
 
1266
                                      command.SetChecker,
 
1267
                                      value_to_set=":")
1226
1268
 
1227
1269
    def test_checker_empty(self):
1228
1270
        self.assert_command_from_args(["--checker", "", "foo"],
1229
 
                                      SetCheckerCmd, value_to_set="")
 
1271
                                      command.SetChecker,
 
1272
                                      value_to_set="")
1230
1273
 
1231
1274
    def test_checker_short(self):
1232
1275
        self.assert_command_from_args(["-c", ":", "foo"],
1233
 
                                      SetCheckerCmd, value_to_set=":")
 
1276
                                      command.SetChecker,
 
1277
                                      value_to_set=":")
1234
1278
 
1235
1279
    def test_host(self):
1236
1280
        self.assert_command_from_args(["--host", "foo.example.org",
1237
 
                                       "foo"], SetHostCmd,
 
1281
                                       "foo"], command.SetHost,
1238
1282
                                      value_to_set="foo.example.org")
1239
1283
 
1240
1284
    def test_host_short(self):
1241
1285
        self.assert_command_from_args(["-H", "foo.example.org",
1242
 
                                       "foo"], SetHostCmd,
 
1286
                                       "foo"], command.SetHost,
1243
1287
                                      value_to_set="foo.example.org")
1244
1288
 
1245
1289
    def test_secret_devnull(self):
1246
1290
        self.assert_command_from_args(["--secret", os.path.devnull,
1247
 
                                       "foo"], SetSecretCmd,
 
1291
                                       "foo"], command.SetSecret,
1248
1292
                                      value_to_set=b"")
1249
1293
 
1250
1294
    def test_secret_tempfile(self):
1253
1297
            f.write(value)
1254
1298
            f.seek(0)
1255
1299
            self.assert_command_from_args(["--secret", f.name,
1256
 
                                           "foo"], SetSecretCmd,
 
1300
                                           "foo"], command.SetSecret,
1257
1301
                                          value_to_set=value)
1258
1302
 
1259
1303
    def test_secret_devnull_short(self):
1260
1304
        self.assert_command_from_args(["-s", os.path.devnull, "foo"],
1261
 
                                      SetSecretCmd, value_to_set=b"")
 
1305
                                      command.SetSecret,
 
1306
                                      value_to_set=b"")
1262
1307
 
1263
1308
    def test_secret_tempfile_short(self):
1264
1309
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
1266
1311
            f.write(value)
1267
1312
            f.seek(0)
1268
1313
            self.assert_command_from_args(["-s", f.name, "foo"],
1269
 
                                          SetSecretCmd,
 
1314
                                          command.SetSecret,
1270
1315
                                          value_to_set=value)
1271
1316
 
1272
1317
    def test_timeout(self):
1273
1318
        self.assert_command_from_args(["--timeout", "PT5M", "foo"],
1274
 
                                      SetTimeoutCmd,
 
1319
                                      command.SetTimeout,
1275
1320
                                      value_to_set=300000)
1276
1321
 
1277
1322
    def test_timeout_short(self):
1278
1323
        self.assert_command_from_args(["-t", "PT5M", "foo"],
1279
 
                                      SetTimeoutCmd,
 
1324
                                      command.SetTimeout,
1280
1325
                                      value_to_set=300000)
1281
1326
 
1282
1327
    def test_extended_timeout(self):
1283
1328
        self.assert_command_from_args(["--extended-timeout", "PT15M",
1284
1329
                                       "foo"],
1285
 
                                      SetExtendedTimeoutCmd,
 
1330
                                      command.SetExtendedTimeout,
1286
1331
                                      value_to_set=900000)
1287
1332
 
1288
1333
    def test_interval(self):
1289
1334
        self.assert_command_from_args(["--interval", "PT2M", "foo"],
1290
 
                                      SetIntervalCmd,
 
1335
                                      command.SetInterval,
1291
1336
                                      value_to_set=120000)
1292
1337
 
1293
1338
    def test_interval_short(self):
1294
1339
        self.assert_command_from_args(["-i", "PT2M", "foo"],
1295
 
                                      SetIntervalCmd,
 
1340
                                      command.SetInterval,
1296
1341
                                      value_to_set=120000)
1297
1342
 
1298
1343
    def test_approval_delay(self):
1299
1344
        self.assert_command_from_args(["--approval-delay", "PT30S",
1300
 
                                       "foo"], SetApprovalDelayCmd,
 
1345
                                       "foo"],
 
1346
                                      command.SetApprovalDelay,
1301
1347
                                      value_to_set=30000)
1302
1348
 
1303
1349
    def test_approval_duration(self):
1304
1350
        self.assert_command_from_args(["--approval-duration", "PT1S",
1305
 
                                       "foo"], SetApprovalDurationCmd,
 
1351
                                       "foo"],
 
1352
                                      command.SetApprovalDuration,
1306
1353
                                      value_to_set=1000)
1307
1354
 
1308
1355
    def test_print_table(self):
1309
 
        self.assert_command_from_args([], PrintTableCmd,
 
1356
        self.assert_command_from_args([], command.PrintTable,
1310
1357
                                      verbose=False)
1311
1358
 
1312
1359
    def test_print_table_verbose(self):
1313
 
        self.assert_command_from_args(["--verbose"], PrintTableCmd,
 
1360
        self.assert_command_from_args(["--verbose"],
 
1361
                                      command.PrintTable,
1314
1362
                                      verbose=True)
1315
1363
 
1316
1364
    def test_print_table_verbose_short(self):
1317
 
        self.assert_command_from_args(["-v"], PrintTableCmd,
 
1365
        self.assert_command_from_args(["-v"], command.PrintTable,
1318
1366
                                      verbose=True)
1319
1367
 
1320
1368
 
1321
 
class TestCmd(unittest.TestCase):
 
1369
class TestCommand(unittest.TestCase):
1322
1370
    """Abstract class for tests of command classes"""
1323
1371
 
1324
1372
    def setUp(self):
1330
1378
                self.attributes["Name"] = name
1331
1379
                self.calls = []
1332
1380
            def Set(self, interface, propname, value, dbus_interface):
1333
 
                testcase.assertEqual(interface, client_dbus_interface)
1334
 
                testcase.assertEqual(dbus_interface,
1335
 
                                     dbus.PROPERTIES_IFACE)
 
1381
                testcase.assertEqual(client_dbus_interface, interface)
 
1382
                testcase.assertEqual(dbus.PROPERTIES_IFACE,
 
1383
                                     dbus_interface)
1336
1384
                self.attributes[propname] = value
1337
 
            def Get(self, interface, propname, dbus_interface):
1338
 
                testcase.assertEqual(interface, client_dbus_interface)
1339
 
                testcase.assertEqual(dbus_interface,
1340
 
                                     dbus.PROPERTIES_IFACE)
1341
 
                return self.attributes[propname]
1342
1385
            def Approve(self, approve, dbus_interface):
1343
 
                testcase.assertEqual(dbus_interface,
1344
 
                                     client_dbus_interface)
 
1386
                testcase.assertEqual(client_dbus_interface,
 
1387
                                     dbus_interface)
1345
1388
                self.calls.append(("Approve", (approve,
1346
1389
                                               dbus_interface)))
1347
1390
        self.client = MockClient(
1404
1447
        class Bus(object):
1405
1448
            @staticmethod
1406
1449
            def get_object(client_bus_name, path):
1407
 
                self.assertEqual(client_bus_name, dbus_busname)
 
1450
                self.assertEqual(dbus_busname, client_bus_name)
1408
1451
                return {
1409
1452
                    # Note: "self" here is the TestCmd instance, not
1410
1453
                    # the Bus instance, since this is a static method!
1414
1457
        return Bus()
1415
1458
 
1416
1459
 
1417
 
class TestIsEnabledCmd(TestCmd):
1418
 
    def test_is_enabled(self):
1419
 
        self.assertTrue(all(IsEnabledCmd().is_enabled(client,
1420
 
                                                      properties)
1421
 
                            for client, properties
1422
 
                            in self.clients.items()))
 
1460
class TestBaseCommands(TestCommand):
1423
1461
 
1424
 
    def test_is_enabled_run_exits_successfully(self):
 
1462
    def test_IsEnabled_exits_successfully(self):
1425
1463
        with self.assertRaises(SystemExit) as e:
1426
 
            IsEnabledCmd().run(self.one_client)
 
1464
            command.IsEnabled().run(self.one_client)
1427
1465
        if e.exception.code is not None:
1428
 
            self.assertEqual(e.exception.code, 0)
 
1466
            self.assertEqual(0, e.exception.code)
1429
1467
        else:
1430
1468
            self.assertIsNone(e.exception.code)
1431
1469
 
1432
 
    def test_is_enabled_run_exits_with_failure(self):
 
1470
    def test_IsEnabled_exits_with_failure(self):
1433
1471
        self.client.attributes["Enabled"] = dbus.Boolean(False)
1434
1472
        with self.assertRaises(SystemExit) as e:
1435
 
            IsEnabledCmd().run(self.one_client)
 
1473
            command.IsEnabled().run(self.one_client)
1436
1474
        if isinstance(e.exception.code, int):
1437
 
            self.assertNotEqual(e.exception.code, 0)
 
1475
            self.assertNotEqual(0, e.exception.code)
1438
1476
        else:
1439
1477
            self.assertIsNotNone(e.exception.code)
1440
1478
 
1441
 
 
1442
 
class TestApproveCmd(TestCmd):
1443
 
    def test_approve(self):
1444
 
        ApproveCmd().run(self.clients, self.bus)
 
1479
    def test_Approve(self):
 
1480
        command.Approve().run(self.clients, self.bus)
1445
1481
        for clientpath in self.clients:
1446
1482
            client = self.bus.get_object(dbus_busname, clientpath)
1447
1483
            self.assertIn(("Approve", (True, client_dbus_interface)),
1448
1484
                          client.calls)
1449
1485
 
1450
 
 
1451
 
class TestDenyCmd(TestCmd):
1452
 
    def test_deny(self):
1453
 
        DenyCmd().run(self.clients, self.bus)
 
1486
    def test_Deny(self):
 
1487
        command.Deny().run(self.clients, self.bus)
1454
1488
        for clientpath in self.clients:
1455
1489
            client = self.bus.get_object(dbus_busname, clientpath)
1456
1490
            self.assertIn(("Approve", (False, client_dbus_interface)),
1457
1491
                          client.calls)
1458
1492
 
1459
 
 
1460
 
class TestRemoveCmd(TestCmd):
1461
 
    def test_remove(self):
 
1493
    def test_Remove(self):
1462
1494
        class MockMandos(object):
1463
1495
            def __init__(self):
1464
1496
                self.calls = []
1465
1497
            def RemoveClient(self, dbus_path):
1466
1498
                self.calls.append(("RemoveClient", (dbus_path,)))
1467
1499
        mandos = MockMandos()
1468
 
        super(TestRemoveCmd, self).setUp()
1469
 
        RemoveCmd().run(self.clients, self.bus, mandos)
1470
 
        self.assertEqual(len(mandos.calls), 2)
 
1500
        command.Remove().run(self.clients, self.bus, mandos)
1471
1501
        for clientpath in self.clients:
1472
1502
            self.assertIn(("RemoveClient", (clientpath,)),
1473
1503
                          mandos.calls)
1474
1504
 
1475
 
 
1476
 
class TestDumpJSONCmd(TestCmd):
1477
 
    def setUp(self):
1478
 
        self.expected_json = {
1479
 
            "foo": {
1480
 
                "Name": "foo",
1481
 
                "KeyID": ("92ed150794387c03ce684574b1139a65"
1482
 
                          "94a34f895daaaf09fd8ea90a27cddb12"),
1483
 
                "Host": "foo.example.org",
1484
 
                "Enabled": True,
1485
 
                "Timeout": 300000,
1486
 
                "LastCheckedOK": "2019-02-03T00:00:00",
1487
 
                "Created": "2019-01-02T00:00:00",
1488
 
                "Interval": 120000,
1489
 
                "Fingerprint": ("778827225BA7DE539C5A"
1490
 
                                "7CFA59CFF7CDBD9A5920"),
1491
 
                "CheckerRunning": False,
1492
 
                "LastEnabled": "2019-01-03T00:00:00",
1493
 
                "ApprovalPending": False,
1494
 
                "ApprovedByDefault": True,
1495
 
                "LastApprovalRequest": "",
1496
 
                "ApprovalDelay": 0,
1497
 
                "ApprovalDuration": 1000,
1498
 
                "Checker": "fping -q -- %(host)s",
1499
 
                "ExtendedTimeout": 900000,
1500
 
                "Expires": "2019-02-04T00:00:00",
1501
 
                "LastCheckerStatus": 0,
1502
 
            },
1503
 
            "barbar": {
1504
 
                "Name": "barbar",
1505
 
                "KeyID": ("0558568eedd67d622f5c83b35a115f79"
1506
 
                          "6ab612cff5ad227247e46c2b020f441c"),
1507
 
                "Host": "192.0.2.3",
1508
 
                "Enabled": True,
1509
 
                "Timeout": 300000,
1510
 
                "LastCheckedOK": "2019-02-04T00:00:00",
1511
 
                "Created": "2019-01-03T00:00:00",
1512
 
                "Interval": 120000,
1513
 
                "Fingerprint": ("3E393AEAEFB84C7E89E2"
1514
 
                                "F547B3A107558FCA3A27"),
1515
 
                "CheckerRunning": True,
1516
 
                "LastEnabled": "2019-01-04T00:00:00",
1517
 
                "ApprovalPending": False,
1518
 
                "ApprovedByDefault": False,
1519
 
                "LastApprovalRequest": "2019-01-03T00:00:00",
1520
 
                "ApprovalDelay": 30000,
1521
 
                "ApprovalDuration": 93785000,
1522
 
                "Checker": ":",
1523
 
                "ExtendedTimeout": 900000,
1524
 
                "Expires": "2019-02-05T00:00:00",
1525
 
                "LastCheckerStatus": -2,
1526
 
            },
1527
 
        }
1528
 
        return super(TestDumpJSONCmd, self).setUp()
1529
 
 
1530
 
    def test_normal(self):
1531
 
        output = DumpJSONCmd().output(self.clients.values())
 
1505
    expected_json = {
 
1506
        "foo": {
 
1507
            "Name": "foo",
 
1508
            "KeyID": ("92ed150794387c03ce684574b1139a65"
 
1509
                      "94a34f895daaaf09fd8ea90a27cddb12"),
 
1510
            "Host": "foo.example.org",
 
1511
            "Enabled": True,
 
1512
            "Timeout": 300000,
 
1513
            "LastCheckedOK": "2019-02-03T00:00:00",
 
1514
            "Created": "2019-01-02T00:00:00",
 
1515
            "Interval": 120000,
 
1516
            "Fingerprint": ("778827225BA7DE539C5A"
 
1517
                            "7CFA59CFF7CDBD9A5920"),
 
1518
            "CheckerRunning": False,
 
1519
            "LastEnabled": "2019-01-03T00:00:00",
 
1520
            "ApprovalPending": False,
 
1521
            "ApprovedByDefault": True,
 
1522
            "LastApprovalRequest": "",
 
1523
            "ApprovalDelay": 0,
 
1524
            "ApprovalDuration": 1000,
 
1525
            "Checker": "fping -q -- %(host)s",
 
1526
            "ExtendedTimeout": 900000,
 
1527
            "Expires": "2019-02-04T00:00:00",
 
1528
            "LastCheckerStatus": 0,
 
1529
        },
 
1530
        "barbar": {
 
1531
            "Name": "barbar",
 
1532
            "KeyID": ("0558568eedd67d622f5c83b35a115f79"
 
1533
                      "6ab612cff5ad227247e46c2b020f441c"),
 
1534
            "Host": "192.0.2.3",
 
1535
            "Enabled": True,
 
1536
            "Timeout": 300000,
 
1537
            "LastCheckedOK": "2019-02-04T00:00:00",
 
1538
            "Created": "2019-01-03T00:00:00",
 
1539
            "Interval": 120000,
 
1540
            "Fingerprint": ("3E393AEAEFB84C7E89E2"
 
1541
                            "F547B3A107558FCA3A27"),
 
1542
            "CheckerRunning": True,
 
1543
            "LastEnabled": "2019-01-04T00:00:00",
 
1544
            "ApprovalPending": False,
 
1545
            "ApprovedByDefault": False,
 
1546
            "LastApprovalRequest": "2019-01-03T00:00:00",
 
1547
            "ApprovalDelay": 30000,
 
1548
            "ApprovalDuration": 93785000,
 
1549
            "Checker": ":",
 
1550
            "ExtendedTimeout": 900000,
 
1551
            "Expires": "2019-02-05T00:00:00",
 
1552
            "LastCheckerStatus": -2,
 
1553
        },
 
1554
    }
 
1555
 
 
1556
    def test_DumpJSON_normal(self):
 
1557
        output = command.DumpJSON().output(self.clients.values())
1532
1558
        json_data = json.loads(output)
1533
 
        self.assertDictEqual(json_data, self.expected_json)
 
1559
        self.assertDictEqual(self.expected_json, json_data)
1534
1560
 
1535
 
    def test_one_client(self):
1536
 
        output = DumpJSONCmd().output(self.one_client.values())
 
1561
    def test_DumpJSON_one_client(self):
 
1562
        output = command.DumpJSON().output(self.one_client.values())
1537
1563
        json_data = json.loads(output)
1538
1564
        expected_json = {"foo": self.expected_json["foo"]}
1539
 
        self.assertDictEqual(json_data, expected_json)
1540
 
 
1541
 
 
1542
 
class TestPrintTableCmd(TestCmd):
1543
 
    def test_normal(self):
1544
 
        output = PrintTableCmd().output(self.clients.values())
 
1565
        self.assertDictEqual(expected_json, json_data)
 
1566
 
 
1567
    def test_PrintTable_normal(self):
 
1568
        output = command.PrintTable().output(self.clients.values())
1545
1569
        expected_output = "\n".join((
1546
1570
            "Name   Enabled Timeout  Last Successful Check",
1547
1571
            "foo    Yes     00:05:00 2019-02-03T00:00:00  ",
1548
1572
            "barbar Yes     00:05:00 2019-02-04T00:00:00  ",
1549
1573
        ))
1550
 
        self.assertEqual(output, expected_output)
 
1574
        self.assertEqual(expected_output, output)
1551
1575
 
1552
 
    def test_verbose(self):
1553
 
        output = PrintTableCmd(verbose=True).output(
 
1576
    def test_PrintTable_verbose(self):
 
1577
        output = command.PrintTable(verbose=True).output(
1554
1578
            self.clients.values())
1555
1579
        columns = (
1556
1580
            (
1642
1666
        expected_output = "\n".join("".join(rows[line]
1643
1667
                                            for rows in columns)
1644
1668
                                    for line in range(num_lines))
1645
 
        self.assertEqual(output, expected_output)
 
1669
        self.assertEqual(expected_output, output)
1646
1670
 
1647
 
    def test_one_client(self):
1648
 
        output = PrintTableCmd().output(self.one_client.values())
 
1671
    def test_PrintTable_one_client(self):
 
1672
        output = command.PrintTable().output(self.one_client.values())
1649
1673
        expected_output = "\n".join((
1650
1674
            "Name Enabled Timeout  Last Successful Check",
1651
1675
            "foo  Yes     00:05:00 2019-02-03T00:00:00  ",
1652
1676
        ))
1653
 
        self.assertEqual(output, expected_output)
1654
 
 
1655
 
 
1656
 
class TestPropertyCmd(TestCmd):
1657
 
    """Abstract class for tests of PropertyCmd classes"""
 
1677
        self.assertEqual(expected_output, output)
 
1678
 
 
1679
 
 
1680
class TestPropertyCmd(TestCommand):
 
1681
    """Abstract class for tests of command.Property classes"""
1658
1682
    def runTest(self):
1659
1683
        if not hasattr(self, "command"):
1660
1684
            return
1665
1689
            for clientpath in self.clients:
1666
1690
                client = self.bus.get_object(dbus_busname, clientpath)
1667
1691
                old_value = client.attributes[self.propname]
1668
 
                self.assertNotIsInstance(old_value, self.Unique)
1669
1692
                client.attributes[self.propname] = self.Unique()
1670
1693
            self.run_command(value_to_set, self.clients)
1671
1694
            for clientpath in self.clients:
1672
1695
                client = self.bus.get_object(dbus_busname, clientpath)
1673
1696
                value = client.attributes[self.propname]
1674
1697
                self.assertNotIsInstance(value, self.Unique)
1675
 
                self.assertEqual(value, value_to_get)
 
1698
                self.assertEqual(value_to_get, value)
1676
1699
 
1677
1700
    class Unique(object):
1678
1701
        """Class for objects which exist only to be unique objects,
1683
1706
 
1684
1707
 
1685
1708
class TestEnableCmd(TestPropertyCmd):
1686
 
    command = EnableCmd
 
1709
    command = command.Enable
1687
1710
    propname = "Enabled"
1688
1711
    values_to_set = [dbus.Boolean(True)]
1689
1712
 
1690
1713
 
1691
1714
class TestDisableCmd(TestPropertyCmd):
1692
 
    command = DisableCmd
 
1715
    command = command.Disable
1693
1716
    propname = "Enabled"
1694
1717
    values_to_set = [dbus.Boolean(False)]
1695
1718
 
1696
1719
 
1697
1720
class TestBumpTimeoutCmd(TestPropertyCmd):
1698
 
    command = BumpTimeoutCmd
 
1721
    command = command.BumpTimeout
1699
1722
    propname = "LastCheckedOK"
1700
1723
    values_to_set = [""]
1701
1724
 
1702
1725
 
1703
1726
class TestStartCheckerCmd(TestPropertyCmd):
1704
 
    command = StartCheckerCmd
 
1727
    command = command.StartChecker
1705
1728
    propname = "CheckerRunning"
1706
1729
    values_to_set = [dbus.Boolean(True)]
1707
1730
 
1708
1731
 
1709
1732
class TestStopCheckerCmd(TestPropertyCmd):
1710
 
    command = StopCheckerCmd
 
1733
    command = command.StopChecker
1711
1734
    propname = "CheckerRunning"
1712
1735
    values_to_set = [dbus.Boolean(False)]
1713
1736
 
1714
1737
 
1715
1738
class TestApproveByDefaultCmd(TestPropertyCmd):
1716
 
    command = ApproveByDefaultCmd
 
1739
    command = command.ApproveByDefault
1717
1740
    propname = "ApprovedByDefault"
1718
1741
    values_to_set = [dbus.Boolean(True)]
1719
1742
 
1720
1743
 
1721
1744
class TestDenyByDefaultCmd(TestPropertyCmd):
1722
 
    command = DenyByDefaultCmd
 
1745
    command = command.DenyByDefault
1723
1746
    propname = "ApprovedByDefault"
1724
1747
    values_to_set = [dbus.Boolean(False)]
1725
1748
 
1737
1760
 
1738
1761
 
1739
1762
class TestSetCheckerCmd(TestPropertyValueCmd):
1740
 
    command = SetCheckerCmd
 
1763
    command = command.SetChecker
1741
1764
    propname = "Checker"
1742
1765
    values_to_set = ["", ":", "fping -q -- %s"]
1743
1766
 
1744
1767
 
1745
1768
class TestSetHostCmd(TestPropertyValueCmd):
1746
 
    command = SetHostCmd
 
1769
    command = command.SetHost
1747
1770
    propname = "Host"
1748
1771
    values_to_set = ["192.0.2.3", "foo.example.org"]
1749
1772
 
1750
1773
 
1751
1774
class TestSetSecretCmd(TestPropertyValueCmd):
1752
 
    command = SetSecretCmd
 
1775
    command = command.SetSecret
1753
1776
    propname = "Secret"
1754
1777
    values_to_set = [io.BytesIO(b""),
1755
1778
                     io.BytesIO(b"secret\0xyzzy\nbar")]
1757
1780
 
1758
1781
 
1759
1782
class TestSetTimeoutCmd(TestPropertyValueCmd):
1760
 
    command = SetTimeoutCmd
 
1783
    command = command.SetTimeout
1761
1784
    propname = "Timeout"
1762
1785
    values_to_set = [datetime.timedelta(),
1763
1786
                     datetime.timedelta(minutes=5),
1768
1791
 
1769
1792
 
1770
1793
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
1771
 
    command = SetExtendedTimeoutCmd
 
1794
    command = command.SetExtendedTimeout
1772
1795
    propname = "ExtendedTimeout"
1773
1796
    values_to_set = [datetime.timedelta(),
1774
1797
                     datetime.timedelta(minutes=5),
1779
1802
 
1780
1803
 
1781
1804
class TestSetIntervalCmd(TestPropertyValueCmd):
1782
 
    command = SetIntervalCmd
 
1805
    command = command.SetInterval
1783
1806
    propname = "Interval"
1784
1807
    values_to_set = [datetime.timedelta(),
1785
1808
                     datetime.timedelta(minutes=5),
1790
1813
 
1791
1814
 
1792
1815
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
1793
 
    command = SetApprovalDelayCmd
 
1816
    command = command.SetApprovalDelay
1794
1817
    propname = "ApprovalDelay"
1795
1818
    values_to_set = [datetime.timedelta(),
1796
1819
                     datetime.timedelta(minutes=5),
1801
1824
 
1802
1825
 
1803
1826
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
1804
 
    command = SetApprovalDurationCmd
 
1827
    command = command.SetApprovalDuration
1805
1828
    propname = "ApprovalDuration"
1806
1829
    values_to_set = [datetime.timedelta(),
1807
1830
                     datetime.timedelta(minutes=5),