/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 00:23:20 UTC
  • Revision ID: teddy@recompile.se-20190316002320-ajpmbdl4jup156en
mandos-ctl: Refactor

* mandos-ctl (get_mandos_dbus_object, get_managed_objects): Factor out
                                             D-Bus exception catching.
                       
  (if_dbus_exception_log_with_exception_and_exit): New.

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
 
854
 
class TestCaseWithAssertLogs(unittest.TestCase):
855
 
    """unittest.TestCase.assertLogs only exists in Python 3.4"""
856
 
 
857
 
    if not hasattr(unittest.TestCase, "assertLogs"):
858
 
        @contextlib.contextmanager
859
 
        def assertLogs(self, logger, level=logging.INFO):
860
 
            capturing_handler = self.CapturingLevelHandler(level)
861
 
            old_level = logger.level
862
 
            old_propagate = logger.propagate
863
 
            logger.addHandler(capturing_handler)
864
 
            logger.setLevel(level)
865
 
            logger.propagate = False
866
 
            try:
867
 
                yield capturing_handler.watcher
868
 
            finally:
869
 
                logger.propagate = old_propagate
870
 
                logger.removeHandler(capturing_handler)
871
 
                logger.setLevel(old_level)
872
 
            self.assertGreater(len(capturing_handler.watcher.records),
873
 
                               0)
874
 
 
875
 
        class CapturingLevelHandler(logging.Handler):
876
 
            def __init__(self, level, *args, **kwargs):
877
 
                logging.Handler.__init__(self, *args, **kwargs)
878
 
                self.watcher = self.LoggingWatcher([], [])
879
 
            def emit(self, record):
880
 
                self.watcher.records.append(record)
881
 
                self.watcher.output.append(self.format(record))
882
 
 
883
 
            LoggingWatcher = collections.namedtuple("LoggingWatcher",
884
 
                                                    ("records",
885
 
                                                     "output"))
886
 
 
887
 
 
888
 
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):
 
842
class Test_string_to_delta(unittest.TestCase):
 
843
    def test_handles_basic_rfc3339(self):
894
844
        self.assertEqual(string_to_delta("PT0S"),
895
845
                         datetime.timedelta())
896
 
 
897
 
    def test_rfc3339_zero_days(self):
898
846
        self.assertEqual(string_to_delta("P0D"),
899
847
                         datetime.timedelta())
900
 
 
901
 
    def test_rfc3339_one_second(self):
902
848
        self.assertEqual(string_to_delta("PT1S"),
903
849
                         datetime.timedelta(0, 1))
904
 
 
905
 
    def test_rfc3339_two_hours(self):
906
850
        self.assertEqual(string_to_delta("PT2H"),
907
851
                         datetime.timedelta(0, 7200))
908
852
 
909
853
    def test_falls_back_to_pre_1_6_1_with_warning(self):
910
 
        with self.assertLogs(log, logging.WARNING):
911
 
            value = string_to_delta("2h")
 
854
        # assertLogs only exists in Python 3.4
 
855
        if hasattr(self, "assertLogs"):
 
856
            with self.assertLogs(log, logging.WARNING):
 
857
                value = string_to_delta("2h")
 
858
        else:
 
859
            class WarningFilter(logging.Filter):
 
860
                """Don't show, but record the presence of, warnings"""
 
861
                def filter(self, record):
 
862
                    is_warning = record.levelno >= logging.WARNING
 
863
                    self.found = is_warning or getattr(self, "found",
 
864
                                                       False)
 
865
                    return not is_warning
 
866
            warning_filter = WarningFilter()
 
867
            log.addFilter(warning_filter)
 
868
            try:
 
869
                value = string_to_delta("2h")
 
870
            finally:
 
871
                log.removeFilter(warning_filter)
 
872
            self.assertTrue(getattr(warning_filter, "found", False))
912
873
        self.assertEqual(value, datetime.timedelta(0, 7200))
913
874
 
914
875
 
953
914
    @contextlib.contextmanager
954
915
    def assertParseError(self):
955
916
        with self.assertRaises(SystemExit) as e:
956
 
            with self.redirect_stderr_to_devnull():
 
917
            with self.temporarily_suppress_stderr():
957
918
                yield
958
919
        # Exit code from argparse is guaranteed to be "2".  Reference:
959
920
        # https://docs.python.org/3/library
962
923
 
963
924
    @staticmethod
964
925
    @contextlib.contextmanager
965
 
    def redirect_stderr_to_devnull():
 
926
    def temporarily_suppress_stderr():
966
927
        null = os.open(os.path.devnull, os.O_RDWR)
967
928
        stderrcopy = os.dup(sys.stderr.fileno())
968
929
        os.dup2(null, sys.stderr.fileno())
977
938
    def check_option_syntax(self, options):
978
939
        check_option_syntax(self.parser, options)
979
940
 
980
 
    def test_actions_all_conflicts_with_verbose(self):
981
 
        for action, value in self.actions.items():
982
 
            options = self.parser.parse_args()
983
 
            setattr(options, action, value)
984
 
            options.all = True
985
 
            options.verbose = True
986
 
            with self.assertParseError():
987
 
                self.check_option_syntax(options)
988
 
 
989
 
    def test_actions_with_client_conflicts_with_verbose(self):
990
 
        for action, value in self.actions.items():
991
 
            options = self.parser.parse_args()
992
 
            setattr(options, action, value)
993
 
            options.verbose = True
994
 
            options.client = ["foo"]
 
941
    def test_actions_conflicts_with_verbose(self):
 
942
        for action, value in self.actions.items():
 
943
            options = self.parser.parse_args()
 
944
            setattr(options, action, value)
 
945
            options.verbose = True
995
946
            with self.assertParseError():
996
947
                self.check_option_syntax(options)
997
948
 
1023
974
            options.all = True
1024
975
            self.check_option_syntax(options)
1025
976
 
1026
 
    def test_any_action_is_ok_with_one_client(self):
1027
 
        for action, value in self.actions.items():
1028
 
            options = self.parser.parse_args()
1029
 
            setattr(options, action, value)
1030
 
            options.client = ["foo"]
 
977
    def test_is_enabled_fails_without_client(self):
 
978
        options = self.parser.parse_args()
 
979
        options.is_enabled = True
 
980
        with self.assertParseError():
1031
981
            self.check_option_syntax(options)
1032
982
 
1033
 
    def test_one_client_with_all_actions_except_is_enabled(self):
 
983
    def test_is_enabled_works_with_one_client(self):
1034
984
        options = self.parser.parse_args()
1035
 
        for action, value in self.actions.items():
1036
 
            if action == "is_enabled":
1037
 
                continue
1038
 
            setattr(options, action, value)
 
985
        options.is_enabled = True
1039
986
        options.client = ["foo"]
1040
987
        self.check_option_syntax(options)
1041
988
 
1042
 
    def test_two_clients_with_all_actions_except_is_enabled(self):
1043
 
        options = self.parser.parse_args()
1044
 
        for action, value in self.actions.items():
1045
 
            if action == "is_enabled":
1046
 
                continue
1047
 
            setattr(options, action, value)
1048
 
        options.client = ["foo", "barbar"]
1049
 
        self.check_option_syntax(options)
1050
 
 
1051
 
    def test_two_clients_are_ok_with_actions_except_is_enabled(self):
1052
 
        for action, value in self.actions.items():
1053
 
            if action == "is_enabled":
1054
 
                continue
1055
 
            options = self.parser.parse_args()
1056
 
            setattr(options, action, value)
1057
 
            options.client = ["foo", "barbar"]
1058
 
            self.check_option_syntax(options)
1059
 
 
1060
 
    def test_is_enabled_fails_without_client(self):
1061
 
        options = self.parser.parse_args()
1062
 
        options.is_enabled = True
1063
 
        with self.assertParseError():
1064
 
            self.check_option_syntax(options)
1065
 
 
1066
989
    def test_is_enabled_fails_with_two_clients(self):
1067
990
        options = self.parser.parse_args()
1068
991
        options.is_enabled = True
1082
1005
                self.check_option_syntax(options)
1083
1006
 
1084
1007
 
1085
 
class Test_get_mandos_dbus_object(TestCaseWithAssertLogs):
 
1008
class Test_get_mandos_dbus_object(unittest.TestCase):
1086
1009
    def test_calls_and_returns_get_object_on_bus(self):
1087
1010
        class MockBus(object):
1088
1011
            called = False
1103
1026
            def get_object(self, busname, dbus_path):
1104
1027
                raise dbus.exceptions.DBusException("Test")
1105
1028
 
1106
 
        with self.assertLogs(log, logging.CRITICAL):
1107
 
            with self.assertRaises(SystemExit) as e:
1108
 
                bus = get_mandos_dbus_object(bus=MockBusFailing())
1109
 
 
 
1029
        # assertLogs only exists in Python 3.4
 
1030
        if hasattr(self, "assertLogs"):
 
1031
            with self.assertLogs(log, logging.CRITICAL):
 
1032
                with self.assertRaises(SystemExit) as e:
 
1033
                    bus = get_mandos_dbus_object(bus=MockBus())
 
1034
        else:
 
1035
            critical_filter = self.CriticalFilter()
 
1036
            log.addFilter(critical_filter)
 
1037
            try:
 
1038
                with self.assertRaises(SystemExit) as e:
 
1039
                    get_mandos_dbus_object(bus=MockBusFailing())
 
1040
            finally:
 
1041
                log.removeFilter(critical_filter)
 
1042
            self.assertTrue(critical_filter.found)
1110
1043
        if isinstance(e.exception.code, int):
1111
1044
            self.assertNotEqual(e.exception.code, 0)
1112
1045
        else:
1113
1046
            self.assertIsNotNone(e.exception.code)
1114
1047
 
1115
 
 
1116
 
class Test_get_managed_objects(TestCaseWithAssertLogs):
 
1048
    class CriticalFilter(logging.Filter):
 
1049
        """Don't show, but register, critical messages"""
 
1050
        found = False
 
1051
        def filter(self, record):
 
1052
            is_critical = record.levelno >= logging.CRITICAL
 
1053
            self.found = is_critical or self.found
 
1054
            return not is_critical
 
1055
 
 
1056
 
 
1057
class Test_get_managed_objects(unittest.TestCase):
1117
1058
    def test_calls_and_returns_GetManagedObjects(self):
1118
1059
        managed_objects = {"/clients/foo": { "Name": "foo"}}
1119
1060
        class MockObjectManager(object):
1120
 
            def GetManagedObjects(self):
 
1061
            @staticmethod
 
1062
            def GetManagedObjects():
1121
1063
                return managed_objects
1122
1064
        retval = get_managed_objects(MockObjectManager())
1123
1065
        self.assertDictEqual(managed_objects, retval)
1124
1066
 
1125
1067
    def test_logs_and_exits_on_dbus_error(self):
1126
 
        dbus_logger = logging.getLogger("dbus.proxies")
1127
 
 
1128
1068
        class MockObjectManagerFailing(object):
1129
 
            def GetManagedObjects(self):
1130
 
                dbus_logger.error("Test")
 
1069
            @staticmethod
 
1070
            def GetManagedObjects():
1131
1071
                raise dbus.exceptions.DBusException("Test")
1132
1072
 
1133
 
        class CountingHandler(logging.Handler):
1134
 
            count = 0
1135
 
            def emit(self, record):
1136
 
                self.count += 1
1137
 
 
1138
 
        counting_handler = CountingHandler()
1139
 
 
1140
 
        dbus_logger.addHandler(counting_handler)
1141
 
 
1142
 
        try:
1143
 
            with self.assertLogs(log, logging.CRITICAL) as watcher:
 
1073
        if hasattr(self, "assertLogs"):
 
1074
            with self.assertLogs(log, logging.CRITICAL):
 
1075
                with self.assertRaises(SystemExit):
 
1076
                    get_managed_objects(MockObjectManagerFailing())
 
1077
        else:
 
1078
            critical_filter = self.CriticalFilter()
 
1079
            log.addFilter(critical_filter)
 
1080
            try:
1144
1081
                with self.assertRaises(SystemExit) as e:
1145
1082
                    get_managed_objects(MockObjectManagerFailing())
1146
 
        finally:
1147
 
            dbus_logger.removeFilter(counting_handler)
1148
 
 
1149
 
        # Make sure the dbus logger was suppressed
1150
 
        self.assertEqual(counting_handler.count, 0)
1151
 
 
1152
 
        # Test that the dbus_logger still works
1153
 
        with self.assertLogs(dbus_logger, logging.ERROR):
1154
 
            dbus_logger.error("Test")
1155
 
 
 
1083
            finally:
 
1084
                log.removeFilter(critical_filter)
 
1085
            self.assertTrue(critical_filter.found)
1156
1086
        if isinstance(e.exception.code, int):
1157
1087
            self.assertNotEqual(e.exception.code, 0)
1158
1088
        else:
1159
1089
            self.assertIsNotNone(e.exception.code)
1160
1090
 
 
1091
    class CriticalFilter(logging.Filter):
 
1092
        """Don't show, but register, critical messages"""
 
1093
        found = False
 
1094
        def filter(self, record):
 
1095
            is_critical = record.levelno >= logging.CRITICAL
 
1096
            self.found = is_critical or self.found
 
1097
            return not is_critical
 
1098
 
 
1099
 
 
1100
class Test_SilenceLogger(unittest.TestCase):
 
1101
    loggername = "mandos-ctl.Test_SilenceLogger"
 
1102
    log = logging.getLogger(loggername)
 
1103
    log.propagate = False
 
1104
    log.addHandler(logging.NullHandler())
 
1105
 
 
1106
    def setUp(self):
 
1107
        self.counting_filter = self.CountingFilter()
 
1108
 
 
1109
    class CountingFilter(logging.Filter):
 
1110
        "Count number of records"
 
1111
        count = 0
 
1112
        def filter(self, record):
 
1113
            self.count += 1
 
1114
            return True
 
1115
 
 
1116
    def test_should_filter_records_only_when_active(self):
 
1117
        try:
 
1118
            with SilenceLogger(self.loggername):
 
1119
                self.log.addFilter(self.counting_filter)
 
1120
                self.log.info("Filtered log message 1")
 
1121
            self.log.info("Non-filtered message 2")
 
1122
            self.log.info("Non-filtered message 3")
 
1123
        finally:
 
1124
            self.log.removeFilter(self.counting_filter)
 
1125
        self.assertEqual(self.counting_filter.count, 2)
 
1126
 
1161
1127
 
1162
1128
class Test_commands_from_options(unittest.TestCase):
1163
1129
    def setUp(self):
1166
1132
 
1167
1133
    def test_is_enabled(self):
1168
1134
        self.assert_command_from_args(["--is-enabled", "foo"],
1169
 
                                      command.IsEnabled)
 
1135
                                      IsEnabledCmd)
1170
1136
 
1171
1137
    def assert_command_from_args(self, args, command_cls,
1172
1138
                                 **cmd_attrs):
1182
1148
            self.assertEqual(getattr(command, key), value)
1183
1149
 
1184
1150
    def test_is_enabled_short(self):
1185
 
        self.assert_command_from_args(["-V", "foo"],
1186
 
                                      command.IsEnabled)
 
1151
        self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1187
1152
 
1188
1153
    def test_approve(self):
1189
1154
        self.assert_command_from_args(["--approve", "foo"],
1190
 
                                      command.Approve)
 
1155
                                      ApproveCmd)
1191
1156
 
1192
1157
    def test_approve_short(self):
1193
 
        self.assert_command_from_args(["-A", "foo"], command.Approve)
 
1158
        self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1194
1159
 
1195
1160
    def test_deny(self):
1196
 
        self.assert_command_from_args(["--deny", "foo"], command.Deny)
 
1161
        self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1197
1162
 
1198
1163
    def test_deny_short(self):
1199
 
        self.assert_command_from_args(["-D", "foo"], command.Deny)
 
1164
        self.assert_command_from_args(["-D", "foo"], DenyCmd)
1200
1165
 
1201
1166
    def test_remove(self):
1202
1167
        self.assert_command_from_args(["--remove", "foo"],
1203
 
                                      command.Remove)
 
1168
                                      RemoveCmd)
1204
1169
 
1205
1170
    def test_deny_before_remove(self):
1206
1171
        options = self.parser.parse_args(["--deny", "--remove",
1208
1173
        check_option_syntax(self.parser, options)
1209
1174
        commands = commands_from_options(options)
1210
1175
        self.assertEqual(len(commands), 2)
1211
 
        self.assertIsInstance(commands[0], command.Deny)
1212
 
        self.assertIsInstance(commands[1], command.Remove)
 
1176
        self.assertIsInstance(commands[0], DenyCmd)
 
1177
        self.assertIsInstance(commands[1], RemoveCmd)
1213
1178
 
1214
1179
    def test_deny_before_remove_reversed(self):
1215
1180
        options = self.parser.parse_args(["--remove", "--deny",
1217
1182
        check_option_syntax(self.parser, options)
1218
1183
        commands = commands_from_options(options)
1219
1184
        self.assertEqual(len(commands), 2)
1220
 
        self.assertIsInstance(commands[0], command.Deny)
1221
 
        self.assertIsInstance(commands[1], command.Remove)
 
1185
        self.assertIsInstance(commands[0], DenyCmd)
 
1186
        self.assertIsInstance(commands[1], RemoveCmd)
1222
1187
 
1223
1188
    def test_remove_short(self):
1224
 
        self.assert_command_from_args(["-r", "foo"], command.Remove)
 
1189
        self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1225
1190
 
1226
1191
    def test_dump_json(self):
1227
 
        self.assert_command_from_args(["--dump-json"],
1228
 
                                      command.DumpJSON)
 
1192
        self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1229
1193
 
1230
1194
    def test_enable(self):
1231
 
        self.assert_command_from_args(["--enable", "foo"],
1232
 
                                      command.Enable)
 
1195
        self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1233
1196
 
1234
1197
    def test_enable_short(self):
1235
 
        self.assert_command_from_args(["-e", "foo"], command.Enable)
 
1198
        self.assert_command_from_args(["-e", "foo"], EnableCmd)
1236
1199
 
1237
1200
    def test_disable(self):
1238
1201
        self.assert_command_from_args(["--disable", "foo"],
1239
 
                                      command.Disable)
 
1202
                                      DisableCmd)
1240
1203
 
1241
1204
    def test_disable_short(self):
1242
 
        self.assert_command_from_args(["-d", "foo"], command.Disable)
 
1205
        self.assert_command_from_args(["-d", "foo"], DisableCmd)
1243
1206
 
1244
1207
    def test_bump_timeout(self):
1245
1208
        self.assert_command_from_args(["--bump-timeout", "foo"],
1246
 
                                      command.BumpTimeout)
 
1209
                                      BumpTimeoutCmd)
1247
1210
 
1248
1211
    def test_bump_timeout_short(self):
1249
 
        self.assert_command_from_args(["-b", "foo"],
1250
 
                                      command.BumpTimeout)
 
1212
        self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1251
1213
 
1252
1214
    def test_start_checker(self):
1253
1215
        self.assert_command_from_args(["--start-checker", "foo"],
1254
 
                                      command.StartChecker)
 
1216
                                      StartCheckerCmd)
1255
1217
 
1256
1218
    def test_stop_checker(self):
1257
1219
        self.assert_command_from_args(["--stop-checker", "foo"],
1258
 
                                      command.StopChecker)
 
1220
                                      StopCheckerCmd)
1259
1221
 
1260
1222
    def test_approve_by_default(self):
1261
1223
        self.assert_command_from_args(["--approve-by-default", "foo"],
1262
 
                                      command.ApproveByDefault)
 
1224
                                      ApproveByDefaultCmd)
1263
1225
 
1264
1226
    def test_deny_by_default(self):
1265
1227
        self.assert_command_from_args(["--deny-by-default", "foo"],
1266
 
                                      command.DenyByDefault)
 
1228
                                      DenyByDefaultCmd)
1267
1229
 
1268
1230
    def test_checker(self):
1269
1231
        self.assert_command_from_args(["--checker", ":", "foo"],
1270
 
                                      command.SetChecker,
1271
 
                                      value_to_set=":")
 
1232
                                      SetCheckerCmd, value_to_set=":")
1272
1233
 
1273
1234
    def test_checker_empty(self):
1274
1235
        self.assert_command_from_args(["--checker", "", "foo"],
1275
 
                                      command.SetChecker,
1276
 
                                      value_to_set="")
 
1236
                                      SetCheckerCmd, value_to_set="")
1277
1237
 
1278
1238
    def test_checker_short(self):
1279
1239
        self.assert_command_from_args(["-c", ":", "foo"],
1280
 
                                      command.SetChecker,
1281
 
                                      value_to_set=":")
 
1240
                                      SetCheckerCmd, value_to_set=":")
1282
1241
 
1283
1242
    def test_host(self):
1284
1243
        self.assert_command_from_args(["--host", "foo.example.org",
1285
 
                                       "foo"], command.SetHost,
 
1244
                                       "foo"], SetHostCmd,
1286
1245
                                      value_to_set="foo.example.org")
1287
1246
 
1288
1247
    def test_host_short(self):
1289
1248
        self.assert_command_from_args(["-H", "foo.example.org",
1290
 
                                       "foo"], command.SetHost,
 
1249
                                       "foo"], SetHostCmd,
1291
1250
                                      value_to_set="foo.example.org")
1292
1251
 
1293
1252
    def test_secret_devnull(self):
1294
1253
        self.assert_command_from_args(["--secret", os.path.devnull,
1295
 
                                       "foo"], command.SetSecret,
 
1254
                                       "foo"], SetSecretCmd,
1296
1255
                                      value_to_set=b"")
1297
1256
 
1298
1257
    def test_secret_tempfile(self):
1301
1260
            f.write(value)
1302
1261
            f.seek(0)
1303
1262
            self.assert_command_from_args(["--secret", f.name,
1304
 
                                           "foo"], command.SetSecret,
 
1263
                                           "foo"], SetSecretCmd,
1305
1264
                                          value_to_set=value)
1306
1265
 
1307
1266
    def test_secret_devnull_short(self):
1308
1267
        self.assert_command_from_args(["-s", os.path.devnull, "foo"],
1309
 
                                      command.SetSecret,
1310
 
                                      value_to_set=b"")
 
1268
                                      SetSecretCmd, value_to_set=b"")
1311
1269
 
1312
1270
    def test_secret_tempfile_short(self):
1313
1271
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
1315
1273
            f.write(value)
1316
1274
            f.seek(0)
1317
1275
            self.assert_command_from_args(["-s", f.name, "foo"],
1318
 
                                          command.SetSecret,
 
1276
                                          SetSecretCmd,
1319
1277
                                          value_to_set=value)
1320
1278
 
1321
1279
    def test_timeout(self):
1322
1280
        self.assert_command_from_args(["--timeout", "PT5M", "foo"],
1323
 
                                      command.SetTimeout,
 
1281
                                      SetTimeoutCmd,
1324
1282
                                      value_to_set=300000)
1325
1283
 
1326
1284
    def test_timeout_short(self):
1327
1285
        self.assert_command_from_args(["-t", "PT5M", "foo"],
1328
 
                                      command.SetTimeout,
 
1286
                                      SetTimeoutCmd,
1329
1287
                                      value_to_set=300000)
1330
1288
 
1331
1289
    def test_extended_timeout(self):
1332
1290
        self.assert_command_from_args(["--extended-timeout", "PT15M",
1333
1291
                                       "foo"],
1334
 
                                      command.SetExtendedTimeout,
 
1292
                                      SetExtendedTimeoutCmd,
1335
1293
                                      value_to_set=900000)
1336
1294
 
1337
1295
    def test_interval(self):
1338
1296
        self.assert_command_from_args(["--interval", "PT2M", "foo"],
1339
 
                                      command.SetInterval,
 
1297
                                      SetIntervalCmd,
1340
1298
                                      value_to_set=120000)
1341
1299
 
1342
1300
    def test_interval_short(self):
1343
1301
        self.assert_command_from_args(["-i", "PT2M", "foo"],
1344
 
                                      command.SetInterval,
 
1302
                                      SetIntervalCmd,
1345
1303
                                      value_to_set=120000)
1346
1304
 
1347
1305
    def test_approval_delay(self):
1348
1306
        self.assert_command_from_args(["--approval-delay", "PT30S",
1349
 
                                       "foo"],
1350
 
                                      command.SetApprovalDelay,
 
1307
                                       "foo"], SetApprovalDelayCmd,
1351
1308
                                      value_to_set=30000)
1352
1309
 
1353
1310
    def test_approval_duration(self):
1354
1311
        self.assert_command_from_args(["--approval-duration", "PT1S",
1355
 
                                       "foo"],
1356
 
                                      command.SetApprovalDuration,
 
1312
                                       "foo"], SetApprovalDurationCmd,
1357
1313
                                      value_to_set=1000)
1358
1314
 
1359
1315
    def test_print_table(self):
1360
 
        self.assert_command_from_args([], command.PrintTable,
 
1316
        self.assert_command_from_args([], PrintTableCmd,
1361
1317
                                      verbose=False)
1362
1318
 
1363
1319
    def test_print_table_verbose(self):
1364
 
        self.assert_command_from_args(["--verbose"],
1365
 
                                      command.PrintTable,
 
1320
        self.assert_command_from_args(["--verbose"], PrintTableCmd,
1366
1321
                                      verbose=True)
1367
1322
 
1368
1323
    def test_print_table_verbose_short(self):
1369
 
        self.assert_command_from_args(["-v"], command.PrintTable,
 
1324
        self.assert_command_from_args(["-v"], PrintTableCmd,
1370
1325
                                      verbose=True)
1371
1326
 
1372
1327
 
1373
 
class TestCommand(unittest.TestCase):
 
1328
class TestCmd(unittest.TestCase):
1374
1329
    """Abstract class for tests of command classes"""
1375
1330
 
1376
1331
    def setUp(self):
1386
1341
                testcase.assertEqual(dbus_interface,
1387
1342
                                     dbus.PROPERTIES_IFACE)
1388
1343
                self.attributes[propname] = value
 
1344
            def Get(self, interface, propname, dbus_interface):
 
1345
                testcase.assertEqual(interface, client_dbus_interface)
 
1346
                testcase.assertEqual(dbus_interface,
 
1347
                                     dbus.PROPERTIES_IFACE)
 
1348
                return self.attributes[propname]
1389
1349
            def Approve(self, approve, dbus_interface):
1390
1350
                testcase.assertEqual(dbus_interface,
1391
1351
                                     client_dbus_interface)
1461
1421
        return Bus()
1462
1422
 
1463
1423
 
1464
 
class TestBaseCommands(TestCommand):
 
1424
class TestIsEnabledCmd(TestCmd):
 
1425
    def test_is_enabled(self):
 
1426
        self.assertTrue(all(IsEnabledCmd().is_enabled(client,
 
1427
                                                      properties)
 
1428
                            for client, properties
 
1429
                            in self.clients.items()))
1465
1430
 
1466
 
    def test_IsEnabled_exits_successfully(self):
 
1431
    def test_is_enabled_run_exits_successfully(self):
1467
1432
        with self.assertRaises(SystemExit) as e:
1468
 
            command.IsEnabled().run(self.one_client)
 
1433
            IsEnabledCmd().run(self.one_client)
1469
1434
        if e.exception.code is not None:
1470
1435
            self.assertEqual(e.exception.code, 0)
1471
1436
        else:
1472
1437
            self.assertIsNone(e.exception.code)
1473
1438
 
1474
 
    def test_IsEnabled_exits_with_failure(self):
 
1439
    def test_is_enabled_run_exits_with_failure(self):
1475
1440
        self.client.attributes["Enabled"] = dbus.Boolean(False)
1476
1441
        with self.assertRaises(SystemExit) as e:
1477
 
            command.IsEnabled().run(self.one_client)
 
1442
            IsEnabledCmd().run(self.one_client)
1478
1443
        if isinstance(e.exception.code, int):
1479
1444
            self.assertNotEqual(e.exception.code, 0)
1480
1445
        else:
1481
1446
            self.assertIsNotNone(e.exception.code)
1482
1447
 
1483
 
    def test_Approve(self):
1484
 
        command.Approve().run(self.clients, self.bus)
 
1448
 
 
1449
class TestApproveCmd(TestCmd):
 
1450
    def test_approve(self):
 
1451
        ApproveCmd().run(self.clients, self.bus)
1485
1452
        for clientpath in self.clients:
1486
1453
            client = self.bus.get_object(dbus_busname, clientpath)
1487
1454
            self.assertIn(("Approve", (True, client_dbus_interface)),
1488
1455
                          client.calls)
1489
1456
 
1490
 
    def test_Deny(self):
1491
 
        command.Deny().run(self.clients, self.bus)
 
1457
 
 
1458
class TestDenyCmd(TestCmd):
 
1459
    def test_deny(self):
 
1460
        DenyCmd().run(self.clients, self.bus)
1492
1461
        for clientpath in self.clients:
1493
1462
            client = self.bus.get_object(dbus_busname, clientpath)
1494
1463
            self.assertIn(("Approve", (False, client_dbus_interface)),
1495
1464
                          client.calls)
1496
1465
 
1497
 
    def test_Remove(self):
 
1466
 
 
1467
class TestRemoveCmd(TestCmd):
 
1468
    def test_remove(self):
1498
1469
        class MockMandos(object):
1499
1470
            def __init__(self):
1500
1471
                self.calls = []
1501
1472
            def RemoveClient(self, dbus_path):
1502
1473
                self.calls.append(("RemoveClient", (dbus_path,)))
1503
1474
        mandos = MockMandos()
1504
 
        command.Remove().run(self.clients, self.bus, mandos)
 
1475
        super(TestRemoveCmd, self).setUp()
 
1476
        RemoveCmd().run(self.clients, self.bus, mandos)
 
1477
        self.assertEqual(len(mandos.calls), 2)
1505
1478
        for clientpath in self.clients:
1506
1479
            self.assertIn(("RemoveClient", (clientpath,)),
1507
1480
                          mandos.calls)
1508
1481
 
1509
 
    expected_json = {
1510
 
        "foo": {
1511
 
            "Name": "foo",
1512
 
            "KeyID": ("92ed150794387c03ce684574b1139a65"
1513
 
                      "94a34f895daaaf09fd8ea90a27cddb12"),
1514
 
            "Host": "foo.example.org",
1515
 
            "Enabled": True,
1516
 
            "Timeout": 300000,
1517
 
            "LastCheckedOK": "2019-02-03T00:00:00",
1518
 
            "Created": "2019-01-02T00:00:00",
1519
 
            "Interval": 120000,
1520
 
            "Fingerprint": ("778827225BA7DE539C5A"
1521
 
                            "7CFA59CFF7CDBD9A5920"),
1522
 
            "CheckerRunning": False,
1523
 
            "LastEnabled": "2019-01-03T00:00:00",
1524
 
            "ApprovalPending": False,
1525
 
            "ApprovedByDefault": True,
1526
 
            "LastApprovalRequest": "",
1527
 
            "ApprovalDelay": 0,
1528
 
            "ApprovalDuration": 1000,
1529
 
            "Checker": "fping -q -- %(host)s",
1530
 
            "ExtendedTimeout": 900000,
1531
 
            "Expires": "2019-02-04T00:00:00",
1532
 
            "LastCheckerStatus": 0,
1533
 
        },
1534
 
        "barbar": {
1535
 
            "Name": "barbar",
1536
 
            "KeyID": ("0558568eedd67d622f5c83b35a115f79"
1537
 
                      "6ab612cff5ad227247e46c2b020f441c"),
1538
 
            "Host": "192.0.2.3",
1539
 
            "Enabled": True,
1540
 
            "Timeout": 300000,
1541
 
            "LastCheckedOK": "2019-02-04T00:00:00",
1542
 
            "Created": "2019-01-03T00:00:00",
1543
 
            "Interval": 120000,
1544
 
            "Fingerprint": ("3E393AEAEFB84C7E89E2"
1545
 
                            "F547B3A107558FCA3A27"),
1546
 
            "CheckerRunning": True,
1547
 
            "LastEnabled": "2019-01-04T00:00:00",
1548
 
            "ApprovalPending": False,
1549
 
            "ApprovedByDefault": False,
1550
 
            "LastApprovalRequest": "2019-01-03T00:00:00",
1551
 
            "ApprovalDelay": 30000,
1552
 
            "ApprovalDuration": 93785000,
1553
 
            "Checker": ":",
1554
 
            "ExtendedTimeout": 900000,
1555
 
            "Expires": "2019-02-05T00:00:00",
1556
 
            "LastCheckerStatus": -2,
1557
 
        },
1558
 
    }
1559
 
 
1560
 
    def test_DumpJSON_normal(self):
1561
 
        output = command.DumpJSON().output(self.clients.values())
 
1482
 
 
1483
class TestDumpJSONCmd(TestCmd):
 
1484
    def setUp(self):
 
1485
        self.expected_json = {
 
1486
            "foo": {
 
1487
                "Name": "foo",
 
1488
                "KeyID": ("92ed150794387c03ce684574b1139a65"
 
1489
                          "94a34f895daaaf09fd8ea90a27cddb12"),
 
1490
                "Host": "foo.example.org",
 
1491
                "Enabled": True,
 
1492
                "Timeout": 300000,
 
1493
                "LastCheckedOK": "2019-02-03T00:00:00",
 
1494
                "Created": "2019-01-02T00:00:00",
 
1495
                "Interval": 120000,
 
1496
                "Fingerprint": ("778827225BA7DE539C5A"
 
1497
                                "7CFA59CFF7CDBD9A5920"),
 
1498
                "CheckerRunning": False,
 
1499
                "LastEnabled": "2019-01-03T00:00:00",
 
1500
                "ApprovalPending": False,
 
1501
                "ApprovedByDefault": True,
 
1502
                "LastApprovalRequest": "",
 
1503
                "ApprovalDelay": 0,
 
1504
                "ApprovalDuration": 1000,
 
1505
                "Checker": "fping -q -- %(host)s",
 
1506
                "ExtendedTimeout": 900000,
 
1507
                "Expires": "2019-02-04T00:00:00",
 
1508
                "LastCheckerStatus": 0,
 
1509
            },
 
1510
            "barbar": {
 
1511
                "Name": "barbar",
 
1512
                "KeyID": ("0558568eedd67d622f5c83b35a115f79"
 
1513
                          "6ab612cff5ad227247e46c2b020f441c"),
 
1514
                "Host": "192.0.2.3",
 
1515
                "Enabled": True,
 
1516
                "Timeout": 300000,
 
1517
                "LastCheckedOK": "2019-02-04T00:00:00",
 
1518
                "Created": "2019-01-03T00:00:00",
 
1519
                "Interval": 120000,
 
1520
                "Fingerprint": ("3E393AEAEFB84C7E89E2"
 
1521
                                "F547B3A107558FCA3A27"),
 
1522
                "CheckerRunning": True,
 
1523
                "LastEnabled": "2019-01-04T00:00:00",
 
1524
                "ApprovalPending": False,
 
1525
                "ApprovedByDefault": False,
 
1526
                "LastApprovalRequest": "2019-01-03T00:00:00",
 
1527
                "ApprovalDelay": 30000,
 
1528
                "ApprovalDuration": 93785000,
 
1529
                "Checker": ":",
 
1530
                "ExtendedTimeout": 900000,
 
1531
                "Expires": "2019-02-05T00:00:00",
 
1532
                "LastCheckerStatus": -2,
 
1533
            },
 
1534
        }
 
1535
        return super(TestDumpJSONCmd, self).setUp()
 
1536
 
 
1537
    def test_normal(self):
 
1538
        output = DumpJSONCmd().output(self.clients.values())
1562
1539
        json_data = json.loads(output)
1563
1540
        self.assertDictEqual(json_data, self.expected_json)
1564
1541
 
1565
 
    def test_DumpJSON_one_client(self):
1566
 
        output = command.DumpJSON().output(self.one_client.values())
 
1542
    def test_one_client(self):
 
1543
        output = DumpJSONCmd().output(self.one_client.values())
1567
1544
        json_data = json.loads(output)
1568
1545
        expected_json = {"foo": self.expected_json["foo"]}
1569
1546
        self.assertDictEqual(json_data, expected_json)
1570
1547
 
1571
 
    def test_PrintTable_normal(self):
1572
 
        output = command.PrintTable().output(self.clients.values())
 
1548
 
 
1549
class TestPrintTableCmd(TestCmd):
 
1550
    def test_normal(self):
 
1551
        output = PrintTableCmd().output(self.clients.values())
1573
1552
        expected_output = "\n".join((
1574
1553
            "Name   Enabled Timeout  Last Successful Check",
1575
1554
            "foo    Yes     00:05:00 2019-02-03T00:00:00  ",
1577
1556
        ))
1578
1557
        self.assertEqual(output, expected_output)
1579
1558
 
1580
 
    def test_PrintTable_verbose(self):
1581
 
        output = command.PrintTable(verbose=True).output(
 
1559
    def test_verbose(self):
 
1560
        output = PrintTableCmd(verbose=True).output(
1582
1561
            self.clients.values())
1583
1562
        columns = (
1584
1563
            (
1672
1651
                                    for line in range(num_lines))
1673
1652
        self.assertEqual(output, expected_output)
1674
1653
 
1675
 
    def test_PrintTable_one_client(self):
1676
 
        output = command.PrintTable().output(self.one_client.values())
 
1654
    def test_one_client(self):
 
1655
        output = PrintTableCmd().output(self.one_client.values())
1677
1656
        expected_output = "\n".join((
1678
1657
            "Name Enabled Timeout  Last Successful Check",
1679
1658
            "foo  Yes     00:05:00 2019-02-03T00:00:00  ",
1681
1660
        self.assertEqual(output, expected_output)
1682
1661
 
1683
1662
 
1684
 
class TestPropertyCmd(TestCommand):
1685
 
    """Abstract class for tests of command.Property classes"""
 
1663
class TestPropertyCmd(TestCmd):
 
1664
    """Abstract class for tests of PropertyCmd classes"""
1686
1665
    def runTest(self):
1687
1666
        if not hasattr(self, "command"):
1688
1667
            return
1693
1672
            for clientpath in self.clients:
1694
1673
                client = self.bus.get_object(dbus_busname, clientpath)
1695
1674
                old_value = client.attributes[self.propname]
 
1675
                self.assertNotIsInstance(old_value, self.Unique)
1696
1676
                client.attributes[self.propname] = self.Unique()
1697
1677
            self.run_command(value_to_set, self.clients)
1698
1678
            for clientpath in self.clients:
1710
1690
 
1711
1691
 
1712
1692
class TestEnableCmd(TestPropertyCmd):
1713
 
    command = command.Enable
 
1693
    command = EnableCmd
1714
1694
    propname = "Enabled"
1715
1695
    values_to_set = [dbus.Boolean(True)]
1716
1696
 
1717
1697
 
1718
1698
class TestDisableCmd(TestPropertyCmd):
1719
 
    command = command.Disable
 
1699
    command = DisableCmd
1720
1700
    propname = "Enabled"
1721
1701
    values_to_set = [dbus.Boolean(False)]
1722
1702
 
1723
1703
 
1724
1704
class TestBumpTimeoutCmd(TestPropertyCmd):
1725
 
    command = command.BumpTimeout
 
1705
    command = BumpTimeoutCmd
1726
1706
    propname = "LastCheckedOK"
1727
1707
    values_to_set = [""]
1728
1708
 
1729
1709
 
1730
1710
class TestStartCheckerCmd(TestPropertyCmd):
1731
 
    command = command.StartChecker
 
1711
    command = StartCheckerCmd
1732
1712
    propname = "CheckerRunning"
1733
1713
    values_to_set = [dbus.Boolean(True)]
1734
1714
 
1735
1715
 
1736
1716
class TestStopCheckerCmd(TestPropertyCmd):
1737
 
    command = command.StopChecker
 
1717
    command = StopCheckerCmd
1738
1718
    propname = "CheckerRunning"
1739
1719
    values_to_set = [dbus.Boolean(False)]
1740
1720
 
1741
1721
 
1742
1722
class TestApproveByDefaultCmd(TestPropertyCmd):
1743
 
    command = command.ApproveByDefault
 
1723
    command = ApproveByDefaultCmd
1744
1724
    propname = "ApprovedByDefault"
1745
1725
    values_to_set = [dbus.Boolean(True)]
1746
1726
 
1747
1727
 
1748
1728
class TestDenyByDefaultCmd(TestPropertyCmd):
1749
 
    command = command.DenyByDefault
 
1729
    command = DenyByDefaultCmd
1750
1730
    propname = "ApprovedByDefault"
1751
1731
    values_to_set = [dbus.Boolean(False)]
1752
1732
 
1764
1744
 
1765
1745
 
1766
1746
class TestSetCheckerCmd(TestPropertyValueCmd):
1767
 
    command = command.SetChecker
 
1747
    command = SetCheckerCmd
1768
1748
    propname = "Checker"
1769
1749
    values_to_set = ["", ":", "fping -q -- %s"]
1770
1750
 
1771
1751
 
1772
1752
class TestSetHostCmd(TestPropertyValueCmd):
1773
 
    command = command.SetHost
 
1753
    command = SetHostCmd
1774
1754
    propname = "Host"
1775
1755
    values_to_set = ["192.0.2.3", "foo.example.org"]
1776
1756
 
1777
1757
 
1778
1758
class TestSetSecretCmd(TestPropertyValueCmd):
1779
 
    command = command.SetSecret
 
1759
    command = SetSecretCmd
1780
1760
    propname = "Secret"
1781
1761
    values_to_set = [io.BytesIO(b""),
1782
1762
                     io.BytesIO(b"secret\0xyzzy\nbar")]
1784
1764
 
1785
1765
 
1786
1766
class TestSetTimeoutCmd(TestPropertyValueCmd):
1787
 
    command = command.SetTimeout
 
1767
    command = SetTimeoutCmd
1788
1768
    propname = "Timeout"
1789
1769
    values_to_set = [datetime.timedelta(),
1790
1770
                     datetime.timedelta(minutes=5),
1795
1775
 
1796
1776
 
1797
1777
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
1798
 
    command = command.SetExtendedTimeout
 
1778
    command = SetExtendedTimeoutCmd
1799
1779
    propname = "ExtendedTimeout"
1800
1780
    values_to_set = [datetime.timedelta(),
1801
1781
                     datetime.timedelta(minutes=5),
1806
1786
 
1807
1787
 
1808
1788
class TestSetIntervalCmd(TestPropertyValueCmd):
1809
 
    command = command.SetInterval
 
1789
    command = SetIntervalCmd
1810
1790
    propname = "Interval"
1811
1791
    values_to_set = [datetime.timedelta(),
1812
1792
                     datetime.timedelta(minutes=5),
1817
1797
 
1818
1798
 
1819
1799
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
1820
 
    command = command.SetApprovalDelay
 
1800
    command = SetApprovalDelayCmd
1821
1801
    propname = "ApprovalDelay"
1822
1802
    values_to_set = [datetime.timedelta(),
1823
1803
                     datetime.timedelta(minutes=5),
1828
1808
 
1829
1809
 
1830
1810
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
1831
 
    command = command.SetApprovalDuration
 
1811
    command = SetApprovalDurationCmd
1832
1812
    propname = "ApprovalDuration"
1833
1813
    values_to_set = [datetime.timedelta(),
1834
1814
                     datetime.timedelta(minutes=5),