/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-15 23:55:53 UTC
  • Revision ID: teddy@recompile.se-20190315235553-znbpfn7d8o84tyt6
mandos-ctl: Refactor

* mandos-ctl (main): Do some minor refactoring.

Show diffs side-by-side

added added

removed removed

Lines of Context:
61
61
 
62
62
if sys.version_info.major == 2:
63
63
    str = unicode
64
 
    import StringIO
65
 
    io.StringIO = StringIO.StringIO
66
64
 
67
65
locale.setlocale(locale.LC_ALL, "")
68
66
 
83
81
 
84
82
def main():
85
83
    parser = argparse.ArgumentParser()
 
84
 
86
85
    add_command_line_options(parser)
87
86
 
88
87
    options = parser.parse_args()
 
88
 
89
89
    check_option_syntax(parser, options)
90
90
 
91
91
    clientnames = options.client
102
102
    mandos_serv_object_manager = dbus.Interface(
103
103
        mandos_dbus_object, dbus_interface=dbus.OBJECT_MANAGER_IFACE)
104
104
 
105
 
    managed_objects = get_managed_objects(mandos_serv_object_manager)
 
105
    log.debug("D-Bus: %s:%s:%s.GetManagedObjects()", dbus_busname,
 
106
              server_dbus_path, dbus.OBJECT_MANAGER_IFACE)
 
107
    try:
 
108
        with SilenceLogger("dbus.proxies"):
 
109
            managed_objects = (mandos_serv_object_manager
 
110
                               .GetManagedObjects())
 
111
    except dbus.exceptions.DBusException as e:
 
112
        log.critical("Failed to access Mandos server through D-Bus:"
 
113
                     "\n%s", e)
 
114
        sys.exit(1)
106
115
 
107
116
    all_clients = {}
108
117
    for path, ifs_and_props in managed_objects.items():
125
134
                log.critical("Client not found on server: %r", name)
126
135
                sys.exit(1)
127
136
 
 
137
    # Run all commands on clients
128
138
    commands = commands_from_options(options)
129
 
 
130
139
    for command in commands:
131
140
        command.run(clients, bus, mandos_serv)
132
141
 
232
241
    >>> rfc3339_duration_to_delta("")
233
242
    Traceback (most recent call last):
234
243
    ...
235
 
    ValueError: Invalid RFC 3339 duration: ""
 
244
    ValueError: Invalid RFC 3339 duration: u''
236
245
    >>> # Must start with "P":
237
246
    >>> rfc3339_duration_to_delta("1D")
238
247
    Traceback (most recent call last):
239
248
    ...
240
 
    ValueError: Invalid RFC 3339 duration: "1D"
 
249
    ValueError: Invalid RFC 3339 duration: u'1D'
241
250
    >>> # Must use correct order
242
251
    >>> rfc3339_duration_to_delta("PT1S2M")
243
252
    Traceback (most recent call last):
244
253
    ...
245
 
    ValueError: Invalid RFC 3339 duration: "PT1S2M"
 
254
    ValueError: Invalid RFC 3339 duration: u'PT1S2M'
246
255
    >>> # Time needs time marker
247
256
    >>> rfc3339_duration_to_delta("P1H2S")
248
257
    Traceback (most recent call last):
249
258
    ...
250
 
    ValueError: Invalid RFC 3339 duration: "P1H2S"
 
259
    ValueError: Invalid RFC 3339 duration: u'P1H2S'
251
260
    >>> # Weeks can not be combined with anything else
252
261
    >>> rfc3339_duration_to_delta("P1D2W")
253
262
    Traceback (most recent call last):
254
263
    ...
255
 
    ValueError: Invalid RFC 3339 duration: "P1D2W"
 
264
    ValueError: Invalid RFC 3339 duration: u'P1D2W'
256
265
    >>> rfc3339_duration_to_delta("P2W2H")
257
266
    Traceback (most recent call last):
258
267
    ...
259
 
    ValueError: Invalid RFC 3339 duration: "P2W2H"
 
268
    ValueError: Invalid RFC 3339 duration: u'P2W2H'
260
269
    """
261
270
 
262
271
    # Parsing an RFC 3339 duration with regular expressions is not
333
342
                break
334
343
        else:
335
344
            # No currently valid tokens were found
336
 
            raise ValueError("Invalid RFC 3339 duration: \"{}\""
 
345
            raise ValueError("Invalid RFC 3339 duration: {!r}"
337
346
                             .format(duration))
338
347
    # End token found
339
348
    return value
425
434
 
426
435
 
427
436
def get_mandos_dbus_object(bus):
428
 
    log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
429
 
              dbus_busname, server_dbus_path)
430
 
    with if_dbus_exception_log_with_exception_and_exit(
431
 
            "Could not connect to Mandos server: %s"):
 
437
    try:
 
438
        log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
 
439
                  dbus_busname, server_dbus_path)
432
440
        mandos_dbus_object = bus.get_object(dbus_busname,
433
441
                                            server_dbus_path)
 
442
    except dbus.exceptions.DBusException:
 
443
        log.critical("Could not connect to Mandos server")
 
444
        sys.exit(1)
 
445
 
434
446
    return mandos_dbus_object
435
447
 
436
448
 
437
 
@contextlib.contextmanager
438
 
def if_dbus_exception_log_with_exception_and_exit(*args, **kwargs):
439
 
    try:
440
 
        yield
441
 
    except dbus.exceptions.DBusException as e:
442
 
        log.critical(*(args + (e,)), **kwargs)
443
 
        sys.exit(1)
444
 
 
445
 
 
446
 
def get_managed_objects(object_manager):
447
 
    log.debug("D-Bus: %s:%s:%s.GetManagedObjects()", dbus_busname,
448
 
              server_dbus_path, dbus.OBJECT_MANAGER_IFACE)
449
 
    with if_dbus_exception_log_with_exception_and_exit(
450
 
            "Failed to access Mandos server through D-Bus:\n%s"):
451
 
        with SilenceLogger("dbus.proxies"):
452
 
            managed_objects = object_manager.GetManagedObjects()
453
 
    return managed_objects
454
 
 
455
 
 
456
449
class SilenceLogger(object):
457
450
    "Simple context manager to silence a particular logger"
458
451
    def __init__(self, loggername):
460
453
 
461
454
    def __enter__(self):
462
455
        self.logger.addFilter(self.nullfilter)
 
456
        return self
463
457
 
464
458
    class NullFilter(logging.Filter):
465
459
        def filter(self, record):
476
470
    commands = []
477
471
 
478
472
    if options.is_enabled:
479
 
        commands.append(command.IsEnabled())
 
473
        commands.append(IsEnabledCmd())
480
474
 
481
475
    if options.approve:
482
 
        commands.append(command.Approve())
 
476
        commands.append(ApproveCmd())
483
477
 
484
478
    if options.deny:
485
 
        commands.append(command.Deny())
 
479
        commands.append(DenyCmd())
486
480
 
487
481
    if options.remove:
488
 
        commands.append(command.Remove())
 
482
        commands.append(RemoveCmd())
489
483
 
490
484
    if options.dump_json:
491
 
        commands.append(command.DumpJSON())
 
485
        commands.append(DumpJSONCmd())
492
486
 
493
487
    if options.enable:
494
 
        commands.append(command.Enable())
 
488
        commands.append(EnableCmd())
495
489
 
496
490
    if options.disable:
497
 
        commands.append(command.Disable())
 
491
        commands.append(DisableCmd())
498
492
 
499
493
    if options.bump_timeout:
500
 
        commands.append(command.BumpTimeout())
 
494
        commands.append(BumpTimeoutCmd())
501
495
 
502
496
    if options.start_checker:
503
 
        commands.append(command.StartChecker())
 
497
        commands.append(StartCheckerCmd())
504
498
 
505
499
    if options.stop_checker:
506
 
        commands.append(command.StopChecker())
 
500
        commands.append(StopCheckerCmd())
507
501
 
508
502
    if options.approved_by_default is not None:
509
503
        if options.approved_by_default:
510
 
            commands.append(command.ApproveByDefault())
 
504
            commands.append(ApproveByDefaultCmd())
511
505
        else:
512
 
            commands.append(command.DenyByDefault())
 
506
            commands.append(DenyByDefaultCmd())
513
507
 
514
508
    if options.checker is not None:
515
 
        commands.append(command.SetChecker(options.checker))
 
509
        commands.append(SetCheckerCmd(options.checker))
516
510
 
517
511
    if options.host is not None:
518
 
        commands.append(command.SetHost(options.host))
 
512
        commands.append(SetHostCmd(options.host))
519
513
 
520
514
    if options.secret is not None:
521
 
        commands.append(command.SetSecret(options.secret))
 
515
        commands.append(SetSecretCmd(options.secret))
522
516
 
523
517
    if options.timeout is not None:
524
 
        commands.append(command.SetTimeout(options.timeout))
 
518
        commands.append(SetTimeoutCmd(options.timeout))
525
519
 
526
520
    if options.extended_timeout:
527
521
        commands.append(
528
 
            command.SetExtendedTimeout(options.extended_timeout))
 
522
            SetExtendedTimeoutCmd(options.extended_timeout))
529
523
 
530
524
    if options.interval is not None:
531
 
        commands.append(command.SetInterval(options.interval))
 
525
        commands.append(SetIntervalCmd(options.interval))
532
526
 
533
527
    if options.approval_delay is not None:
534
 
        commands.append(
535
 
            command.SetApprovalDelay(options.approval_delay))
 
528
        commands.append(SetApprovalDelayCmd(options.approval_delay))
536
529
 
537
530
    if options.approval_duration is not None:
538
531
        commands.append(
539
 
            command.SetApprovalDuration(options.approval_duration))
 
532
            SetApprovalDurationCmd(options.approval_duration))
540
533
 
541
534
    # If no command option has been given, show table of clients,
542
535
    # optionally verbosely
543
536
    if not commands:
544
 
        commands.append(command.PrintTable(verbose=options.verbose))
 
537
        commands.append(PrintTableCmd(verbose=options.verbose))
545
538
 
546
539
    return commands
547
540
 
548
541
 
549
 
class command(object):
550
 
    """A namespace for command classes"""
551
 
 
552
 
    class Base(object):
553
 
        """Abstract base class for commands"""
554
 
        def run(self, clients, bus=None, mandos=None):
555
 
            """Normal commands should implement run_on_one_client(),
556
 
but commands which want to operate on all clients at the same time can
557
 
override this run() method instead.
558
 
"""
559
 
            for clientpath, properties in clients.items():
560
 
                log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
561
 
                          dbus_busname, str(clientpath))
562
 
                client = bus.get_object(dbus_busname, clientpath)
563
 
                self.run_on_one_client(client, properties)
564
 
 
565
 
 
566
 
    class IsEnabled(Base):
567
 
        def run(self, clients, bus=None, mandos=None):
568
 
            client, properties = next(iter(clients.items()))
569
 
            if self.is_enabled(client, properties):
570
 
                sys.exit(0)
571
 
            sys.exit(1)
572
 
        def is_enabled(self, client, properties):
573
 
            return properties["Enabled"]
574
 
 
575
 
 
576
 
    class Approve(Base):
577
 
        def run_on_one_client(self, client, properties):
578
 
            log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
579
 
                      client.__dbus_object_path__,
580
 
                      client_dbus_interface)
581
 
            client.Approve(dbus.Boolean(True),
582
 
                           dbus_interface=client_dbus_interface)
583
 
 
584
 
 
585
 
    class Deny(Base):
586
 
        def run_on_one_client(self, client, properties):
587
 
            log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
588
 
                      client.__dbus_object_path__,
589
 
                      client_dbus_interface)
590
 
            client.Approve(dbus.Boolean(False),
591
 
                           dbus_interface=client_dbus_interface)
592
 
 
593
 
 
594
 
    class Remove(Base):
595
 
        def run(self, clients, bus, mandos):
596
 
            for clientpath in clients.keys():
597
 
                log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)",
598
 
                          dbus_busname, server_dbus_path,
599
 
                          server_dbus_interface, clientpath)
600
 
                mandos.RemoveClient(clientpath)
601
 
 
602
 
 
603
 
    class Output(Base):
604
 
        """Abstract class for commands outputting client details"""
605
 
        all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
606
 
                        "Created", "Interval", "Host", "KeyID",
607
 
                        "Fingerprint", "CheckerRunning",
608
 
                        "LastEnabled", "ApprovalPending",
609
 
                        "ApprovedByDefault", "LastApprovalRequest",
610
 
                        "ApprovalDelay", "ApprovalDuration",
611
 
                        "Checker", "ExtendedTimeout", "Expires",
612
 
                        "LastCheckerStatus")
613
 
 
614
 
 
615
 
    class DumpJSON(Output):
616
 
        def run(self, clients, bus=None, mandos=None):
617
 
            data = {client["Name"]:
618
 
                    {key: self.dbus_boolean_to_bool(client[key])
619
 
                     for key in self.all_keywords}
620
 
                    for client in clients.values()}
621
 
            print(json.dumps(data, indent=4, separators=(',', ': ')))
 
542
class Command(object):
 
543
    """Abstract class for commands"""
 
544
    def run(self, clients, bus=None, mandos=None):
 
545
        """Normal commands should implement run_on_one_client(), but
 
546
        commands which want to operate on all clients at the same time
 
547
        can override this run() method instead."""
 
548
        self.mandos = mandos
 
549
        for clientpath, properties in clients.items():
 
550
            log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
 
551
                      dbus_busname, str(clientpath))
 
552
            client = bus.get_object(dbus_busname, clientpath)
 
553
            self.run_on_one_client(client, properties)
 
554
 
 
555
 
 
556
class IsEnabledCmd(Command):
 
557
    def run(self, clients, bus=None, mandos=None):
 
558
        client, properties = next(iter(clients.items()))
 
559
        if self.is_enabled(client, properties):
 
560
            sys.exit(0)
 
561
        sys.exit(1)
 
562
    def is_enabled(self, client, properties):
 
563
        return properties["Enabled"]
 
564
 
 
565
 
 
566
class ApproveCmd(Command):
 
567
    def run_on_one_client(self, client, properties):
 
568
        log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
 
569
                  client.__dbus_object_path__, client_dbus_interface)
 
570
        client.Approve(dbus.Boolean(True),
 
571
                       dbus_interface=client_dbus_interface)
 
572
 
 
573
 
 
574
class DenyCmd(Command):
 
575
    def run_on_one_client(self, client, properties):
 
576
        log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
 
577
                  client.__dbus_object_path__, client_dbus_interface)
 
578
        client.Approve(dbus.Boolean(False),
 
579
                       dbus_interface=client_dbus_interface)
 
580
 
 
581
 
 
582
class RemoveCmd(Command):
 
583
    def run_on_one_client(self, client, properties):
 
584
        log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", dbus_busname,
 
585
                  server_dbus_path, server_dbus_interface,
 
586
                  str(client.__dbus_object_path__))
 
587
        self.mandos.RemoveClient(client.__dbus_object_path__)
 
588
 
 
589
 
 
590
class OutputCmd(Command):
 
591
    """Abstract class for commands outputting client details"""
 
592
    all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
 
593
                    "Created", "Interval", "Host", "KeyID",
 
594
                    "Fingerprint", "CheckerRunning", "LastEnabled",
 
595
                    "ApprovalPending", "ApprovedByDefault",
 
596
                    "LastApprovalRequest", "ApprovalDelay",
 
597
                    "ApprovalDuration", "Checker", "ExtendedTimeout",
 
598
                    "Expires", "LastCheckerStatus")
 
599
 
 
600
    def run(self, clients, bus=None, mandos=None):
 
601
        print(self.output(clients.values()))
 
602
 
 
603
    def output(self, clients):
 
604
        raise NotImplementedError()
 
605
 
 
606
 
 
607
class DumpJSONCmd(OutputCmd):
 
608
    def output(self, clients):
 
609
        data = {client["Name"]:
 
610
                {key: self.dbus_boolean_to_bool(client[key])
 
611
                 for key in self.all_keywords}
 
612
                for client in clients}
 
613
        return json.dumps(data, indent=4, separators=(',', ': '))
 
614
 
 
615
    @staticmethod
 
616
    def dbus_boolean_to_bool(value):
 
617
        if isinstance(value, dbus.Boolean):
 
618
            value = bool(value)
 
619
        return value
 
620
 
 
621
 
 
622
class PrintTableCmd(OutputCmd):
 
623
    def __init__(self, verbose=False):
 
624
        self.verbose = verbose
 
625
 
 
626
    def output(self, clients):
 
627
        default_keywords = ("Name", "Enabled", "Timeout",
 
628
                            "LastCheckedOK")
 
629
        keywords = default_keywords
 
630
        if self.verbose:
 
631
            keywords = self.all_keywords
 
632
        return str(self.TableOfClients(clients, keywords))
 
633
 
 
634
    class TableOfClients(object):
 
635
        tableheaders = {
 
636
            "Name": "Name",
 
637
            "Enabled": "Enabled",
 
638
            "Timeout": "Timeout",
 
639
            "LastCheckedOK": "Last Successful Check",
 
640
            "LastApprovalRequest": "Last Approval Request",
 
641
            "Created": "Created",
 
642
            "Interval": "Interval",
 
643
            "Host": "Host",
 
644
            "Fingerprint": "Fingerprint",
 
645
            "KeyID": "Key ID",
 
646
            "CheckerRunning": "Check Is Running",
 
647
            "LastEnabled": "Last Enabled",
 
648
            "ApprovalPending": "Approval Is Pending",
 
649
            "ApprovedByDefault": "Approved By Default",
 
650
            "ApprovalDelay": "Approval Delay",
 
651
            "ApprovalDuration": "Approval Duration",
 
652
            "Checker": "Checker",
 
653
            "ExtendedTimeout": "Extended Timeout",
 
654
            "Expires": "Expires",
 
655
            "LastCheckerStatus": "Last Checker Status",
 
656
        }
 
657
 
 
658
        def __init__(self, clients, keywords):
 
659
            self.clients = clients
 
660
            self.keywords = keywords
 
661
 
 
662
        def __str__(self):
 
663
            return "\n".join(self.rows())
 
664
 
 
665
        if sys.version_info.major == 2:
 
666
            __unicode__ = __str__
 
667
            def __str__(self):
 
668
                return str(self).encode(locale.getpreferredencoding())
 
669
 
 
670
        def rows(self):
 
671
            format_string = self.row_formatting_string()
 
672
            rows = [self.header_line(format_string)]
 
673
            rows.extend(self.client_line(client, format_string)
 
674
                        for client in self.clients)
 
675
            return rows
 
676
 
 
677
        def row_formatting_string(self):
 
678
            "Format string used to format table rows"
 
679
            return " ".join("{{{key}:{width}}}".format(
 
680
                width=max(len(self.tableheaders[key]),
 
681
                          *(len(self.string_from_client(client, key))
 
682
                            for client in self.clients)),
 
683
                key=key)
 
684
                            for key in self.keywords)
 
685
 
 
686
        def string_from_client(self, client, key):
 
687
            return self.valuetostring(client[key], key)
 
688
 
 
689
        @classmethod
 
690
        def valuetostring(cls, value, keyword):
 
691
            if isinstance(value, dbus.Boolean):
 
692
                return "Yes" if value else "No"
 
693
            if keyword in ("Timeout", "Interval", "ApprovalDelay",
 
694
                           "ApprovalDuration", "ExtendedTimeout"):
 
695
                return cls.milliseconds_to_string(value)
 
696
            return str(value)
 
697
 
 
698
        def header_line(self, format_string):
 
699
            return format_string.format(**self.tableheaders)
 
700
 
 
701
        def client_line(self, client, format_string):
 
702
            return format_string.format(
 
703
                **{key: self.string_from_client(client, key)
 
704
                   for key in self.keywords})
622
705
 
623
706
        @staticmethod
624
 
        def dbus_boolean_to_bool(value):
625
 
            if isinstance(value, dbus.Boolean):
626
 
                value = bool(value)
627
 
            return value
628
 
 
629
 
 
630
 
    class PrintTable(Output):
631
 
        def __init__(self, verbose=False):
632
 
            self.verbose = verbose
633
 
 
634
 
        def run(self, clients, bus=None, mandos=None):
635
 
            default_keywords = ("Name", "Enabled", "Timeout",
636
 
                                "LastCheckedOK")
637
 
            keywords = default_keywords
638
 
            if self.verbose:
639
 
                keywords = self.all_keywords
640
 
            print(self.TableOfClients(clients.values(), keywords))
641
 
 
642
 
        class TableOfClients(object):
643
 
            tableheaders = {
644
 
                "Name": "Name",
645
 
                "Enabled": "Enabled",
646
 
                "Timeout": "Timeout",
647
 
                "LastCheckedOK": "Last Successful Check",
648
 
                "LastApprovalRequest": "Last Approval Request",
649
 
                "Created": "Created",
650
 
                "Interval": "Interval",
651
 
                "Host": "Host",
652
 
                "Fingerprint": "Fingerprint",
653
 
                "KeyID": "Key ID",
654
 
                "CheckerRunning": "Check Is Running",
655
 
                "LastEnabled": "Last Enabled",
656
 
                "ApprovalPending": "Approval Is Pending",
657
 
                "ApprovedByDefault": "Approved By Default",
658
 
                "ApprovalDelay": "Approval Delay",
659
 
                "ApprovalDuration": "Approval Duration",
660
 
                "Checker": "Checker",
661
 
                "ExtendedTimeout": "Extended Timeout",
662
 
                "Expires": "Expires",
663
 
                "LastCheckerStatus": "Last Checker Status",
664
 
            }
665
 
 
666
 
            def __init__(self, clients, keywords):
667
 
                self.clients = clients
668
 
                self.keywords = keywords
669
 
 
670
 
            def __str__(self):
671
 
                return "\n".join(self.rows())
672
 
 
673
 
            if sys.version_info.major == 2:
674
 
                __unicode__ = __str__
675
 
                def __str__(self):
676
 
                    return str(self).encode(
677
 
                        locale.getpreferredencoding())
678
 
 
679
 
            def rows(self):
680
 
                format_string = self.row_formatting_string()
681
 
                rows = [self.header_line(format_string)]
682
 
                rows.extend(self.client_line(client, format_string)
683
 
                            for client in self.clients)
684
 
                return rows
685
 
 
686
 
            def row_formatting_string(self):
687
 
                "Format string used to format table rows"
688
 
                return " ".join("{{{key}:{width}}}".format(
689
 
                    width=max(len(self.tableheaders[key]),
690
 
                              *(len(self.string_from_client(client,
691
 
                                                            key))
692
 
                                for client in self.clients)),
693
 
                    key=key)
694
 
                                for key in self.keywords)
695
 
 
696
 
            def string_from_client(self, client, key):
697
 
                return self.valuetostring(client[key], key)
698
 
 
699
 
            @classmethod
700
 
            def valuetostring(cls, value, keyword):
701
 
                if isinstance(value, dbus.Boolean):
702
 
                    return "Yes" if value else "No"
703
 
                if keyword in ("Timeout", "Interval", "ApprovalDelay",
704
 
                               "ApprovalDuration", "ExtendedTimeout"):
705
 
                    return cls.milliseconds_to_string(value)
706
 
                return str(value)
707
 
 
708
 
            def header_line(self, format_string):
709
 
                return format_string.format(**self.tableheaders)
710
 
 
711
 
            def client_line(self, client, format_string):
712
 
                return format_string.format(
713
 
                    **{key: self.string_from_client(client, key)
714
 
                       for key in self.keywords})
715
 
 
716
 
            @staticmethod
717
 
            def milliseconds_to_string(ms):
718
 
                td = datetime.timedelta(0, 0, 0, ms)
719
 
                return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
720
 
                        .format(days="{}T".format(td.days)
721
 
                                if td.days else "",
722
 
                                hours=td.seconds // 3600,
723
 
                                minutes=(td.seconds % 3600) // 60,
724
 
                                seconds=td.seconds % 60))
725
 
 
726
 
 
727
 
    class PropertySetter(Base):
728
 
        "Abstract class for Actions for setting one client property"
729
 
 
730
 
        def run_on_one_client(self, client, properties):
731
 
            """Set the Client's D-Bus property"""
732
 
            log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
733
 
                      client.__dbus_object_path__,
734
 
                      dbus.PROPERTIES_IFACE, client_dbus_interface,
735
 
                      self.propname, self.value_to_set
736
 
                      if not isinstance(self.value_to_set,
737
 
                                        dbus.Boolean)
738
 
                      else bool(self.value_to_set))
739
 
            client.Set(client_dbus_interface, self.propname,
740
 
                       self.value_to_set,
741
 
                       dbus_interface=dbus.PROPERTIES_IFACE)
742
 
 
743
 
        @property
744
 
        def propname(self):
745
 
            raise NotImplementedError()
746
 
 
747
 
 
748
 
    class Enable(PropertySetter):
749
 
        propname = "Enabled"
750
 
        value_to_set = dbus.Boolean(True)
751
 
 
752
 
 
753
 
    class Disable(PropertySetter):
754
 
        propname = "Enabled"
755
 
        value_to_set = dbus.Boolean(False)
756
 
 
757
 
 
758
 
    class BumpTimeout(PropertySetter):
759
 
        propname = "LastCheckedOK"
760
 
        value_to_set = ""
761
 
 
762
 
 
763
 
    class StartChecker(PropertySetter):
764
 
        propname = "CheckerRunning"
765
 
        value_to_set = dbus.Boolean(True)
766
 
 
767
 
 
768
 
    class StopChecker(PropertySetter):
769
 
        propname = "CheckerRunning"
770
 
        value_to_set = dbus.Boolean(False)
771
 
 
772
 
 
773
 
    class ApproveByDefault(PropertySetter):
774
 
        propname = "ApprovedByDefault"
775
 
        value_to_set = dbus.Boolean(True)
776
 
 
777
 
 
778
 
    class DenyByDefault(PropertySetter):
779
 
        propname = "ApprovedByDefault"
780
 
        value_to_set = dbus.Boolean(False)
781
 
 
782
 
 
783
 
    class PropertySetterValue(PropertySetter):
784
 
        """Abstract class for PropertySetter recieving a value as
785
 
constructor argument instead of a class attribute."""
786
 
        def __init__(self, value):
787
 
            self.value_to_set = value
788
 
 
789
 
 
790
 
    class SetChecker(PropertySetterValue):
791
 
        propname = "Checker"
792
 
 
793
 
 
794
 
    class SetHost(PropertySetterValue):
795
 
        propname = "Host"
796
 
 
797
 
 
798
 
    class SetSecret(PropertySetterValue):
799
 
        propname = "Secret"
800
 
 
801
 
        @property
802
 
        def value_to_set(self):
803
 
            return self._vts
804
 
 
805
 
        @value_to_set.setter
806
 
        def value_to_set(self, value):
807
 
            """When setting, read data from supplied file object"""
808
 
            self._vts = value.read()
809
 
            value.close()
810
 
 
811
 
 
812
 
    class PropertySetterValueMilliseconds(PropertySetterValue):
813
 
        """Abstract class for PropertySetterValue taking a value
814
 
argument as a datetime.timedelta() but should store it as
815
 
milliseconds."""
816
 
 
817
 
        @property
818
 
        def value_to_set(self):
819
 
            return self._vts
820
 
 
821
 
        @value_to_set.setter
822
 
        def value_to_set(self, value):
823
 
            "When setting, convert value from a datetime.timedelta"
824
 
            self._vts = int(round(value.total_seconds() * 1000))
825
 
 
826
 
 
827
 
    class SetTimeout(PropertySetterValueMilliseconds):
828
 
        propname = "Timeout"
829
 
 
830
 
 
831
 
    class SetExtendedTimeout(PropertySetterValueMilliseconds):
832
 
        propname = "ExtendedTimeout"
833
 
 
834
 
 
835
 
    class SetInterval(PropertySetterValueMilliseconds):
836
 
        propname = "Interval"
837
 
 
838
 
 
839
 
    class SetApprovalDelay(PropertySetterValueMilliseconds):
840
 
        propname = "ApprovalDelay"
841
 
 
842
 
 
843
 
    class SetApprovalDuration(PropertySetterValueMilliseconds):
844
 
        propname = "ApprovalDuration"
 
707
        def milliseconds_to_string(ms):
 
708
            td = datetime.timedelta(0, 0, 0, ms)
 
709
            return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
 
710
                    .format(days="{}T".format(td.days)
 
711
                            if td.days else "",
 
712
                            hours=td.seconds // 3600,
 
713
                            minutes=(td.seconds % 3600) // 60,
 
714
                            seconds=td.seconds % 60))
 
715
 
 
716
 
 
717
class PropertyCmd(Command):
 
718
    """Abstract class for Actions for setting one client property"""
 
719
 
 
720
    def run_on_one_client(self, client, properties):
 
721
        """Set the Client's D-Bus property"""
 
722
        log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
 
723
                  client.__dbus_object_path__,
 
724
                  dbus.PROPERTIES_IFACE, client_dbus_interface,
 
725
                  self.propname, self.value_to_set
 
726
                  if not isinstance(self.value_to_set, dbus.Boolean)
 
727
                  else bool(self.value_to_set))
 
728
        client.Set(client_dbus_interface, self.propname,
 
729
                   self.value_to_set,
 
730
                   dbus_interface=dbus.PROPERTIES_IFACE)
 
731
 
 
732
    @property
 
733
    def propname(self):
 
734
        raise NotImplementedError()
 
735
 
 
736
 
 
737
class EnableCmd(PropertyCmd):
 
738
    propname = "Enabled"
 
739
    value_to_set = dbus.Boolean(True)
 
740
 
 
741
 
 
742
class DisableCmd(PropertyCmd):
 
743
    propname = "Enabled"
 
744
    value_to_set = dbus.Boolean(False)
 
745
 
 
746
 
 
747
class BumpTimeoutCmd(PropertyCmd):
 
748
    propname = "LastCheckedOK"
 
749
    value_to_set = ""
 
750
 
 
751
 
 
752
class StartCheckerCmd(PropertyCmd):
 
753
    propname = "CheckerRunning"
 
754
    value_to_set = dbus.Boolean(True)
 
755
 
 
756
 
 
757
class StopCheckerCmd(PropertyCmd):
 
758
    propname = "CheckerRunning"
 
759
    value_to_set = dbus.Boolean(False)
 
760
 
 
761
 
 
762
class ApproveByDefaultCmd(PropertyCmd):
 
763
    propname = "ApprovedByDefault"
 
764
    value_to_set = dbus.Boolean(True)
 
765
 
 
766
 
 
767
class DenyByDefaultCmd(PropertyCmd):
 
768
    propname = "ApprovedByDefault"
 
769
    value_to_set = dbus.Boolean(False)
 
770
 
 
771
 
 
772
class PropertyValueCmd(PropertyCmd):
 
773
    """Abstract class for PropertyCmd recieving a value as argument"""
 
774
    def __init__(self, value):
 
775
        self.value_to_set = value
 
776
 
 
777
 
 
778
class SetCheckerCmd(PropertyValueCmd):
 
779
    propname = "Checker"
 
780
 
 
781
 
 
782
class SetHostCmd(PropertyValueCmd):
 
783
    propname = "Host"
 
784
 
 
785
 
 
786
class SetSecretCmd(PropertyValueCmd):
 
787
    propname = "Secret"
 
788
 
 
789
    @property
 
790
    def value_to_set(self):
 
791
        return self._vts
 
792
 
 
793
    @value_to_set.setter
 
794
    def value_to_set(self, value):
 
795
        """When setting, read data from supplied file object"""
 
796
        self._vts = value.read()
 
797
        value.close()
 
798
 
 
799
 
 
800
class MillisecondsPropertyValueArgumentCmd(PropertyValueCmd):
 
801
    """Abstract class for PropertyValueCmd taking a value argument as
 
802
a datetime.timedelta() but should store it as milliseconds."""
 
803
 
 
804
    @property
 
805
    def value_to_set(self):
 
806
        return self._vts
 
807
 
 
808
    @value_to_set.setter
 
809
    def value_to_set(self, value):
 
810
        """When setting, convert value from a datetime.timedelta"""
 
811
        self._vts = int(round(value.total_seconds() * 1000))
 
812
 
 
813
 
 
814
class SetTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
 
815
    propname = "Timeout"
 
816
 
 
817
 
 
818
class SetExtendedTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
 
819
    propname = "ExtendedTimeout"
 
820
 
 
821
 
 
822
class SetIntervalCmd(MillisecondsPropertyValueArgumentCmd):
 
823
    propname = "Interval"
 
824
 
 
825
 
 
826
class SetApprovalDelayCmd(MillisecondsPropertyValueArgumentCmd):
 
827
    propname = "ApprovalDelay"
 
828
 
 
829
 
 
830
class SetApprovalDurationCmd(MillisecondsPropertyValueArgumentCmd):
 
831
    propname = "ApprovalDuration"
845
832
 
846
833
 
847
834
 
848
 
class TestCaseWithAssertLogs(unittest.TestCase):
849
 
    """unittest.TestCase.assertLogs only exists in Python 3.4"""
850
 
 
851
 
    if not hasattr(unittest.TestCase, "assertLogs"):
852
 
        @contextlib.contextmanager
853
 
        def assertLogs(self, logger, level=logging.INFO):
854
 
            capturing_handler = self.CapturingLevelHandler(level)
855
 
            old_level = logger.level
856
 
            old_propagate = logger.propagate
857
 
            logger.addHandler(capturing_handler)
858
 
            logger.setLevel(level)
859
 
            logger.propagate = False
860
 
            try:
861
 
                yield capturing_handler.watcher
862
 
            finally:
863
 
                logger.propagate = old_propagate
864
 
                logger.removeHandler(capturing_handler)
865
 
                logger.setLevel(old_level)
866
 
            self.assertGreater(len(capturing_handler.watcher.records),
867
 
                               0)
868
 
 
869
 
        class CapturingLevelHandler(logging.Handler):
870
 
            def __init__(self, level, *args, **kwargs):
871
 
                logging.Handler.__init__(self, *args, **kwargs)
872
 
                self.watcher = self.LoggingWatcher([], [])
873
 
            def emit(self, record):
874
 
                self.watcher.records.append(record)
875
 
                self.watcher.output.append(self.format(record))
876
 
 
877
 
            LoggingWatcher = collections.namedtuple("LoggingWatcher",
878
 
                                                    ("records",
879
 
                                                     "output"))
880
 
 
881
 
 
882
 
class Test_string_to_delta(TestCaseWithAssertLogs):
883
 
    # Just test basic RFC 3339 functionality here, the doc string for
884
 
    # rfc3339_duration_to_delta() already has more comprehensive
885
 
    # tests, which is run by doctest.
886
 
 
887
 
    def test_rfc3339_zero_seconds(self):
888
 
        self.assertEqual(datetime.timedelta(),
889
 
                         string_to_delta("PT0S"))
890
 
 
891
 
    def test_rfc3339_zero_days(self):
892
 
        self.assertEqual(datetime.timedelta(), string_to_delta("P0D"))
893
 
 
894
 
    def test_rfc3339_one_second(self):
895
 
        self.assertEqual(datetime.timedelta(0, 1),
896
 
                         string_to_delta("PT1S"))
897
 
 
898
 
    def test_rfc3339_two_hours(self):
899
 
        self.assertEqual(datetime.timedelta(0, 7200),
900
 
                         string_to_delta("PT2H"))
 
835
class Test_string_to_delta(unittest.TestCase):
 
836
    def test_handles_basic_rfc3339(self):
 
837
        self.assertEqual(string_to_delta("PT0S"),
 
838
                         datetime.timedelta())
 
839
        self.assertEqual(string_to_delta("P0D"),
 
840
                         datetime.timedelta())
 
841
        self.assertEqual(string_to_delta("PT1S"),
 
842
                         datetime.timedelta(0, 1))
 
843
        self.assertEqual(string_to_delta("PT2H"),
 
844
                         datetime.timedelta(0, 7200))
901
845
 
902
846
    def test_falls_back_to_pre_1_6_1_with_warning(self):
903
 
        with self.assertLogs(log, logging.WARNING):
904
 
            value = string_to_delta("2h")
905
 
        self.assertEqual(datetime.timedelta(0, 7200), value)
 
847
        # assertLogs only exists in Python 3.4
 
848
        if hasattr(self, "assertLogs"):
 
849
            with self.assertLogs(log, logging.WARNING):
 
850
                value = string_to_delta("2h")
 
851
        else:
 
852
            class WarningFilter(logging.Filter):
 
853
                """Don't show, but record the presence of, warnings"""
 
854
                def filter(self, record):
 
855
                    is_warning = record.levelno >= logging.WARNING
 
856
                    self.found = is_warning or getattr(self, "found",
 
857
                                                       False)
 
858
                    return not is_warning
 
859
            warning_filter = WarningFilter()
 
860
            log.addFilter(warning_filter)
 
861
            try:
 
862
                value = string_to_delta("2h")
 
863
            finally:
 
864
                log.removeFilter(warning_filter)
 
865
            self.assertTrue(getattr(warning_filter, "found", False))
 
866
        self.assertEqual(value, datetime.timedelta(0, 7200))
906
867
 
907
868
 
908
869
class Test_check_option_syntax(unittest.TestCase):
946
907
    @contextlib.contextmanager
947
908
    def assertParseError(self):
948
909
        with self.assertRaises(SystemExit) as e:
949
 
            with self.redirect_stderr_to_devnull():
 
910
            with self.temporarily_suppress_stderr():
950
911
                yield
951
912
        # Exit code from argparse is guaranteed to be "2".  Reference:
952
913
        # https://docs.python.org/3/library
953
914
        # /argparse.html#exiting-methods
954
 
        self.assertEqual(2, e.exception.code)
 
915
        self.assertEqual(e.exception.code, 2)
955
916
 
956
917
    @staticmethod
957
918
    @contextlib.contextmanager
958
 
    def redirect_stderr_to_devnull():
959
 
        old_stderr = sys.stderr
960
 
        with contextlib.closing(open(os.devnull, "w")) as null:
961
 
            sys.stderr = null
962
 
            try:
963
 
                yield
964
 
            finally:
965
 
                sys.stderr = old_stderr
 
919
    def temporarily_suppress_stderr():
 
920
        null = os.open(os.path.devnull, os.O_RDWR)
 
921
        stderrcopy = os.dup(sys.stderr.fileno())
 
922
        os.dup2(null, sys.stderr.fileno())
 
923
        os.close(null)
 
924
        try:
 
925
            yield
 
926
        finally:
 
927
            # restore stderr
 
928
            os.dup2(stderrcopy, sys.stderr.fileno())
 
929
            os.close(stderrcopy)
966
930
 
967
931
    def check_option_syntax(self, options):
968
932
        check_option_syntax(self.parser, options)
969
933
 
970
 
    def test_actions_all_conflicts_with_verbose(self):
971
 
        for action, value in self.actions.items():
972
 
            options = self.parser.parse_args()
973
 
            setattr(options, action, value)
974
 
            options.all = True
975
 
            options.verbose = True
976
 
            with self.assertParseError():
977
 
                self.check_option_syntax(options)
978
 
 
979
 
    def test_actions_with_client_conflicts_with_verbose(self):
980
 
        for action, value in self.actions.items():
981
 
            options = self.parser.parse_args()
982
 
            setattr(options, action, value)
983
 
            options.verbose = True
984
 
            options.client = ["client"]
 
934
    def test_actions_conflicts_with_verbose(self):
 
935
        for action, value in self.actions.items():
 
936
            options = self.parser.parse_args()
 
937
            setattr(options, action, value)
 
938
            options.verbose = True
985
939
            with self.assertParseError():
986
940
                self.check_option_syntax(options)
987
941
 
1013
967
            options.all = True
1014
968
            self.check_option_syntax(options)
1015
969
 
1016
 
    def test_any_action_is_ok_with_one_client(self):
1017
 
        for action, value in self.actions.items():
1018
 
            options = self.parser.parse_args()
1019
 
            setattr(options, action, value)
1020
 
            options.client = ["client"]
1021
 
            self.check_option_syntax(options)
1022
 
 
1023
 
    def test_one_client_with_all_actions_except_is_enabled(self):
1024
 
        options = self.parser.parse_args()
1025
 
        for action, value in self.actions.items():
1026
 
            if action == "is_enabled":
1027
 
                continue
1028
 
            setattr(options, action, value)
1029
 
        options.client = ["client"]
1030
 
        self.check_option_syntax(options)
1031
 
 
1032
 
    def test_two_clients_with_all_actions_except_is_enabled(self):
1033
 
        options = self.parser.parse_args()
1034
 
        for action, value in self.actions.items():
1035
 
            if action == "is_enabled":
1036
 
                continue
1037
 
            setattr(options, action, value)
1038
 
        options.client = ["client1", "client2"]
1039
 
        self.check_option_syntax(options)
1040
 
 
1041
 
    def test_two_clients_are_ok_with_actions_except_is_enabled(self):
1042
 
        for action, value in self.actions.items():
1043
 
            if action == "is_enabled":
1044
 
                continue
1045
 
            options = self.parser.parse_args()
1046
 
            setattr(options, action, value)
1047
 
            options.client = ["client1", "client2"]
1048
 
            self.check_option_syntax(options)
1049
 
 
1050
970
    def test_is_enabled_fails_without_client(self):
1051
971
        options = self.parser.parse_args()
1052
972
        options.is_enabled = True
1053
973
        with self.assertParseError():
1054
974
            self.check_option_syntax(options)
1055
975
 
 
976
    def test_is_enabled_works_with_one_client(self):
 
977
        options = self.parser.parse_args()
 
978
        options.is_enabled = True
 
979
        options.client = ["foo"]
 
980
        self.check_option_syntax(options)
 
981
 
1056
982
    def test_is_enabled_fails_with_two_clients(self):
1057
983
        options = self.parser.parse_args()
1058
984
        options.is_enabled = True
1059
 
        options.client = ["client1", "client2"]
 
985
        options.client = ["foo", "barbar"]
1060
986
        with self.assertParseError():
1061
987
            self.check_option_syntax(options)
1062
988
 
1072
998
                self.check_option_syntax(options)
1073
999
 
1074
1000
 
1075
 
class Test_get_mandos_dbus_object(TestCaseWithAssertLogs):
 
1001
class Test_get_mandos_dbus_object(unittest.TestCase):
1076
1002
    def test_calls_and_returns_get_object_on_bus(self):
1077
1003
        class MockBus(object):
1078
1004
            called = False
1079
1005
            def get_object(mockbus_self, busname, dbus_path):
1080
1006
                # Note that "self" is still the testcase instance,
1081
1007
                # this MockBus instance is in "mockbus_self".
1082
 
                self.assertEqual(dbus_busname, busname)
1083
 
                self.assertEqual(server_dbus_path, dbus_path)
 
1008
                self.assertEqual(busname, dbus_busname)
 
1009
                self.assertEqual(dbus_path, server_dbus_path)
1084
1010
                mockbus_self.called = True
1085
1011
                return mockbus_self
1086
1012
 
1089
1015
        self.assertTrue(mockbus.called)
1090
1016
 
1091
1017
    def test_logs_and_exits_on_dbus_error(self):
1092
 
        class FailingBusStub(object):
 
1018
        class MockBusFailing(object):
1093
1019
            def get_object(self, busname, dbus_path):
1094
1020
                raise dbus.exceptions.DBusException("Test")
1095
1021
 
1096
 
        with self.assertLogs(log, logging.CRITICAL):
1097
 
            with self.assertRaises(SystemExit) as e:
1098
 
                bus = get_mandos_dbus_object(bus=FailingBusStub())
1099
 
 
 
1022
        # assertLogs only exists in Python 3.4
 
1023
        if hasattr(self, "assertLogs"):
 
1024
            with self.assertLogs(log, logging.CRITICAL):
 
1025
                with self.assertRaises(SystemExit) as e:
 
1026
                    bus = get_mandos_dbus_object(bus=MockBus())
 
1027
        else:
 
1028
            critical_filter = self.CriticalFilter()
 
1029
            log.addFilter(critical_filter)
 
1030
            try:
 
1031
                with self.assertRaises(SystemExit) as e:
 
1032
                    get_mandos_dbus_object(bus=MockBusFailing())
 
1033
            finally:
 
1034
                log.removeFilter(critical_filter)
 
1035
            self.assertTrue(critical_filter.found)
1100
1036
        if isinstance(e.exception.code, int):
1101
 
            self.assertNotEqual(0, e.exception.code)
 
1037
            self.assertNotEqual(e.exception.code, 0)
1102
1038
        else:
1103
1039
            self.assertIsNotNone(e.exception.code)
1104
1040
 
1105
 
 
1106
 
class Test_get_managed_objects(TestCaseWithAssertLogs):
1107
 
    def test_calls_and_returns_GetManagedObjects(self):
1108
 
        managed_objects = {"/clients/client": { "Name": "client"}}
1109
 
        class ObjectManagerStub(object):
1110
 
            def GetManagedObjects(self):
1111
 
                return managed_objects
1112
 
        retval = get_managed_objects(ObjectManagerStub())
1113
 
        self.assertDictEqual(managed_objects, retval)
1114
 
 
1115
 
    def test_logs_and_exits_on_dbus_error(self):
1116
 
        dbus_logger = logging.getLogger("dbus.proxies")
1117
 
 
1118
 
        class ObjectManagerFailingStub(object):
1119
 
            def GetManagedObjects(self):
1120
 
                dbus_logger.error("Test")
1121
 
                raise dbus.exceptions.DBusException("Test")
1122
 
 
1123
 
        class CountingHandler(logging.Handler):
1124
 
            count = 0
1125
 
            def emit(self, record):
1126
 
                self.count += 1
1127
 
 
1128
 
        counting_handler = CountingHandler()
1129
 
 
1130
 
        dbus_logger.addHandler(counting_handler)
1131
 
 
 
1041
    class CriticalFilter(logging.Filter):
 
1042
        """Don't show, but register, critical messages"""
 
1043
        found = False
 
1044
        def filter(self, record):
 
1045
            is_critical = record.levelno >= logging.CRITICAL
 
1046
            self.found = is_critical or self.found
 
1047
            return not is_critical
 
1048
 
 
1049
 
 
1050
class Test_SilenceLogger(unittest.TestCase):
 
1051
    loggername = "mandos-ctl.Test_SilenceLogger"
 
1052
    log = logging.getLogger(loggername)
 
1053
    log.propagate = False
 
1054
    log.addHandler(logging.NullHandler())
 
1055
 
 
1056
    def setUp(self):
 
1057
        self.counting_filter = self.CountingFilter()
 
1058
 
 
1059
    class CountingFilter(logging.Filter):
 
1060
        "Count number of records"
 
1061
        count = 0
 
1062
        def filter(self, record):
 
1063
            self.count += 1
 
1064
            return True
 
1065
 
 
1066
    def test_should_filter_records_only_when_active(self):
1132
1067
        try:
1133
 
            with self.assertLogs(log, logging.CRITICAL) as watcher:
1134
 
                with self.assertRaises(SystemExit) as e:
1135
 
                    get_managed_objects(ObjectManagerFailingStub())
 
1068
            with SilenceLogger(self.loggername):
 
1069
                self.log.addFilter(self.counting_filter)
 
1070
                self.log.info("Filtered log message 1")
 
1071
            self.log.info("Non-filtered message 2")
 
1072
            self.log.info("Non-filtered message 3")
1136
1073
        finally:
1137
 
            dbus_logger.removeFilter(counting_handler)
1138
 
 
1139
 
        # Make sure the dbus logger was suppressed
1140
 
        self.assertEqual(0, counting_handler.count)
1141
 
 
1142
 
        # Test that the dbus_logger still works
1143
 
        with self.assertLogs(dbus_logger, logging.ERROR):
1144
 
            dbus_logger.error("Test")
1145
 
 
1146
 
        if isinstance(e.exception.code, int):
1147
 
            self.assertNotEqual(0, e.exception.code)
1148
 
        else:
1149
 
            self.assertIsNotNone(e.exception.code)
 
1074
            self.log.removeFilter(self.counting_filter)
 
1075
        self.assertEqual(self.counting_filter.count, 2)
1150
1076
 
1151
1077
 
1152
1078
class Test_commands_from_options(unittest.TestCase):
1155
1081
        add_command_line_options(self.parser)
1156
1082
 
1157
1083
    def test_is_enabled(self):
1158
 
        self.assert_command_from_args(["--is-enabled", "client"],
1159
 
                                      command.IsEnabled)
 
1084
        self.assert_command_from_args(["--is-enabled", "foo"],
 
1085
                                      IsEnabledCmd)
1160
1086
 
1161
1087
    def assert_command_from_args(self, args, command_cls,
1162
1088
                                 **cmd_attrs):
1165
1091
        options = self.parser.parse_args(args)
1166
1092
        check_option_syntax(self.parser, options)
1167
1093
        commands = commands_from_options(options)
1168
 
        self.assertEqual(1, len(commands))
 
1094
        self.assertEqual(len(commands), 1)
1169
1095
        command = commands[0]
1170
1096
        self.assertIsInstance(command, command_cls)
1171
1097
        for key, value in cmd_attrs.items():
1172
 
            self.assertEqual(value, getattr(command, key))
 
1098
            self.assertEqual(getattr(command, key), value)
1173
1099
 
1174
1100
    def test_is_enabled_short(self):
1175
 
        self.assert_command_from_args(["-V", "client"],
1176
 
                                      command.IsEnabled)
 
1101
        self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1177
1102
 
1178
1103
    def test_approve(self):
1179
 
        self.assert_command_from_args(["--approve", "client"],
1180
 
                                      command.Approve)
 
1104
        self.assert_command_from_args(["--approve", "foo"],
 
1105
                                      ApproveCmd)
1181
1106
 
1182
1107
    def test_approve_short(self):
1183
 
        self.assert_command_from_args(["-A", "client"],
1184
 
                                      command.Approve)
 
1108
        self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1185
1109
 
1186
1110
    def test_deny(self):
1187
 
        self.assert_command_from_args(["--deny", "client"],
1188
 
                                      command.Deny)
 
1111
        self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1189
1112
 
1190
1113
    def test_deny_short(self):
1191
 
        self.assert_command_from_args(["-D", "client"], command.Deny)
 
1114
        self.assert_command_from_args(["-D", "foo"], DenyCmd)
1192
1115
 
1193
1116
    def test_remove(self):
1194
 
        self.assert_command_from_args(["--remove", "client"],
1195
 
                                      command.Remove)
 
1117
        self.assert_command_from_args(["--remove", "foo"],
 
1118
                                      RemoveCmd)
1196
1119
 
1197
1120
    def test_deny_before_remove(self):
1198
1121
        options = self.parser.parse_args(["--deny", "--remove",
1199
 
                                          "client"])
 
1122
                                          "foo"])
1200
1123
        check_option_syntax(self.parser, options)
1201
1124
        commands = commands_from_options(options)
1202
 
        self.assertEqual(2, len(commands))
1203
 
        self.assertIsInstance(commands[0], command.Deny)
1204
 
        self.assertIsInstance(commands[1], command.Remove)
 
1125
        self.assertEqual(len(commands), 2)
 
1126
        self.assertIsInstance(commands[0], DenyCmd)
 
1127
        self.assertIsInstance(commands[1], RemoveCmd)
1205
1128
 
1206
1129
    def test_deny_before_remove_reversed(self):
1207
1130
        options = self.parser.parse_args(["--remove", "--deny",
1208
1131
                                          "--all"])
1209
1132
        check_option_syntax(self.parser, options)
1210
1133
        commands = commands_from_options(options)
1211
 
        self.assertEqual(2, len(commands))
1212
 
        self.assertIsInstance(commands[0], command.Deny)
1213
 
        self.assertIsInstance(commands[1], command.Remove)
 
1134
        self.assertEqual(len(commands), 2)
 
1135
        self.assertIsInstance(commands[0], DenyCmd)
 
1136
        self.assertIsInstance(commands[1], RemoveCmd)
1214
1137
 
1215
1138
    def test_remove_short(self):
1216
 
        self.assert_command_from_args(["-r", "client"],
1217
 
                                      command.Remove)
 
1139
        self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1218
1140
 
1219
1141
    def test_dump_json(self):
1220
 
        self.assert_command_from_args(["--dump-json"],
1221
 
                                      command.DumpJSON)
 
1142
        self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1222
1143
 
1223
1144
    def test_enable(self):
1224
 
        self.assert_command_from_args(["--enable", "client"],
1225
 
                                      command.Enable)
 
1145
        self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1226
1146
 
1227
1147
    def test_enable_short(self):
1228
 
        self.assert_command_from_args(["-e", "client"],
1229
 
                                      command.Enable)
 
1148
        self.assert_command_from_args(["-e", "foo"], EnableCmd)
1230
1149
 
1231
1150
    def test_disable(self):
1232
 
        self.assert_command_from_args(["--disable", "client"],
1233
 
                                      command.Disable)
 
1151
        self.assert_command_from_args(["--disable", "foo"],
 
1152
                                      DisableCmd)
1234
1153
 
1235
1154
    def test_disable_short(self):
1236
 
        self.assert_command_from_args(["-d", "client"],
1237
 
                                      command.Disable)
 
1155
        self.assert_command_from_args(["-d", "foo"], DisableCmd)
1238
1156
 
1239
1157
    def test_bump_timeout(self):
1240
 
        self.assert_command_from_args(["--bump-timeout", "client"],
1241
 
                                      command.BumpTimeout)
 
1158
        self.assert_command_from_args(["--bump-timeout", "foo"],
 
1159
                                      BumpTimeoutCmd)
1242
1160
 
1243
1161
    def test_bump_timeout_short(self):
1244
 
        self.assert_command_from_args(["-b", "client"],
1245
 
                                      command.BumpTimeout)
 
1162
        self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1246
1163
 
1247
1164
    def test_start_checker(self):
1248
 
        self.assert_command_from_args(["--start-checker", "client"],
1249
 
                                      command.StartChecker)
 
1165
        self.assert_command_from_args(["--start-checker", "foo"],
 
1166
                                      StartCheckerCmd)
1250
1167
 
1251
1168
    def test_stop_checker(self):
1252
 
        self.assert_command_from_args(["--stop-checker", "client"],
1253
 
                                      command.StopChecker)
 
1169
        self.assert_command_from_args(["--stop-checker", "foo"],
 
1170
                                      StopCheckerCmd)
1254
1171
 
1255
1172
    def test_approve_by_default(self):
1256
 
        self.assert_command_from_args(["--approve-by-default",
1257
 
                                       "client"],
1258
 
                                      command.ApproveByDefault)
 
1173
        self.assert_command_from_args(["--approve-by-default", "foo"],
 
1174
                                      ApproveByDefaultCmd)
1259
1175
 
1260
1176
    def test_deny_by_default(self):
1261
 
        self.assert_command_from_args(["--deny-by-default", "client"],
1262
 
                                      command.DenyByDefault)
 
1177
        self.assert_command_from_args(["--deny-by-default", "foo"],
 
1178
                                      DenyByDefaultCmd)
1263
1179
 
1264
1180
    def test_checker(self):
1265
 
        self.assert_command_from_args(["--checker", ":", "client"],
1266
 
                                      command.SetChecker,
1267
 
                                      value_to_set=":")
 
1181
        self.assert_command_from_args(["--checker", ":", "foo"],
 
1182
                                      SetCheckerCmd, value_to_set=":")
1268
1183
 
1269
1184
    def test_checker_empty(self):
1270
 
        self.assert_command_from_args(["--checker", "", "client"],
1271
 
                                      command.SetChecker,
1272
 
                                      value_to_set="")
 
1185
        self.assert_command_from_args(["--checker", "", "foo"],
 
1186
                                      SetCheckerCmd, value_to_set="")
1273
1187
 
1274
1188
    def test_checker_short(self):
1275
 
        self.assert_command_from_args(["-c", ":", "client"],
1276
 
                                      command.SetChecker,
1277
 
                                      value_to_set=":")
 
1189
        self.assert_command_from_args(["-c", ":", "foo"],
 
1190
                                      SetCheckerCmd, value_to_set=":")
1278
1191
 
1279
1192
    def test_host(self):
1280
 
        self.assert_command_from_args(
1281
 
            ["--host", "client.example.org", "client"],
1282
 
            command.SetHost, value_to_set="client.example.org")
 
1193
        self.assert_command_from_args(["--host", "foo.example.org",
 
1194
                                       "foo"], SetHostCmd,
 
1195
                                      value_to_set="foo.example.org")
1283
1196
 
1284
1197
    def test_host_short(self):
1285
 
        self.assert_command_from_args(
1286
 
            ["-H", "client.example.org", "client"], command.SetHost,
1287
 
            value_to_set="client.example.org")
 
1198
        self.assert_command_from_args(["-H", "foo.example.org",
 
1199
                                       "foo"], SetHostCmd,
 
1200
                                      value_to_set="foo.example.org")
1288
1201
 
1289
1202
    def test_secret_devnull(self):
1290
1203
        self.assert_command_from_args(["--secret", os.path.devnull,
1291
 
                                       "client"], command.SetSecret,
 
1204
                                       "foo"], SetSecretCmd,
1292
1205
                                      value_to_set=b"")
1293
1206
 
1294
1207
    def test_secret_tempfile(self):
1297
1210
            f.write(value)
1298
1211
            f.seek(0)
1299
1212
            self.assert_command_from_args(["--secret", f.name,
1300
 
                                           "client"],
1301
 
                                          command.SetSecret,
 
1213
                                           "foo"], SetSecretCmd,
1302
1214
                                          value_to_set=value)
1303
1215
 
1304
1216
    def test_secret_devnull_short(self):
1305
 
        self.assert_command_from_args(["-s", os.path.devnull,
1306
 
                                       "client"], command.SetSecret,
1307
 
                                      value_to_set=b"")
 
1217
        self.assert_command_from_args(["-s", os.path.devnull, "foo"],
 
1218
                                      SetSecretCmd, value_to_set=b"")
1308
1219
 
1309
1220
    def test_secret_tempfile_short(self):
1310
1221
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
1311
1222
            value = b"secret\0xyzzy\nbar"
1312
1223
            f.write(value)
1313
1224
            f.seek(0)
1314
 
            self.assert_command_from_args(["-s", f.name, "client"],
1315
 
                                          command.SetSecret,
 
1225
            self.assert_command_from_args(["-s", f.name, "foo"],
 
1226
                                          SetSecretCmd,
1316
1227
                                          value_to_set=value)
1317
1228
 
1318
1229
    def test_timeout(self):
1319
 
        self.assert_command_from_args(["--timeout", "PT5M", "client"],
1320
 
                                      command.SetTimeout,
 
1230
        self.assert_command_from_args(["--timeout", "PT5M", "foo"],
 
1231
                                      SetTimeoutCmd,
1321
1232
                                      value_to_set=300000)
1322
1233
 
1323
1234
    def test_timeout_short(self):
1324
 
        self.assert_command_from_args(["-t", "PT5M", "client"],
1325
 
                                      command.SetTimeout,
 
1235
        self.assert_command_from_args(["-t", "PT5M", "foo"],
 
1236
                                      SetTimeoutCmd,
1326
1237
                                      value_to_set=300000)
1327
1238
 
1328
1239
    def test_extended_timeout(self):
1329
1240
        self.assert_command_from_args(["--extended-timeout", "PT15M",
1330
 
                                       "client"],
1331
 
                                      command.SetExtendedTimeout,
 
1241
                                       "foo"],
 
1242
                                      SetExtendedTimeoutCmd,
1332
1243
                                      value_to_set=900000)
1333
1244
 
1334
1245
    def test_interval(self):
1335
 
        self.assert_command_from_args(["--interval", "PT2M",
1336
 
                                       "client"], command.SetInterval,
 
1246
        self.assert_command_from_args(["--interval", "PT2M", "foo"],
 
1247
                                      SetIntervalCmd,
1337
1248
                                      value_to_set=120000)
1338
1249
 
1339
1250
    def test_interval_short(self):
1340
 
        self.assert_command_from_args(["-i", "PT2M", "client"],
1341
 
                                      command.SetInterval,
 
1251
        self.assert_command_from_args(["-i", "PT2M", "foo"],
 
1252
                                      SetIntervalCmd,
1342
1253
                                      value_to_set=120000)
1343
1254
 
1344
1255
    def test_approval_delay(self):
1345
1256
        self.assert_command_from_args(["--approval-delay", "PT30S",
1346
 
                                       "client"],
1347
 
                                      command.SetApprovalDelay,
 
1257
                                       "foo"], SetApprovalDelayCmd,
1348
1258
                                      value_to_set=30000)
1349
1259
 
1350
1260
    def test_approval_duration(self):
1351
1261
        self.assert_command_from_args(["--approval-duration", "PT1S",
1352
 
                                       "client"],
1353
 
                                      command.SetApprovalDuration,
 
1262
                                       "foo"], SetApprovalDurationCmd,
1354
1263
                                      value_to_set=1000)
1355
1264
 
1356
1265
    def test_print_table(self):
1357
 
        self.assert_command_from_args([], command.PrintTable,
 
1266
        self.assert_command_from_args([], PrintTableCmd,
1358
1267
                                      verbose=False)
1359
1268
 
1360
1269
    def test_print_table_verbose(self):
1361
 
        self.assert_command_from_args(["--verbose"],
1362
 
                                      command.PrintTable,
 
1270
        self.assert_command_from_args(["--verbose"], PrintTableCmd,
1363
1271
                                      verbose=True)
1364
1272
 
1365
1273
    def test_print_table_verbose_short(self):
1366
 
        self.assert_command_from_args(["-v"], command.PrintTable,
 
1274
        self.assert_command_from_args(["-v"], PrintTableCmd,
1367
1275
                                      verbose=True)
1368
1276
 
1369
1277
 
1370
 
class TestCommand(unittest.TestCase):
 
1278
class TestCmd(unittest.TestCase):
1371
1279
    """Abstract class for tests of command classes"""
1372
1280
 
1373
1281
    def setUp(self):
1379
1287
                self.attributes["Name"] = name
1380
1288
                self.calls = []
1381
1289
            def Set(self, interface, propname, value, dbus_interface):
1382
 
                testcase.assertEqual(client_dbus_interface, interface)
1383
 
                testcase.assertEqual(dbus.PROPERTIES_IFACE,
1384
 
                                     dbus_interface)
 
1290
                testcase.assertEqual(interface, client_dbus_interface)
 
1291
                testcase.assertEqual(dbus_interface,
 
1292
                                     dbus.PROPERTIES_IFACE)
1385
1293
                self.attributes[propname] = value
 
1294
            def Get(self, interface, propname, dbus_interface):
 
1295
                testcase.assertEqual(interface, client_dbus_interface)
 
1296
                testcase.assertEqual(dbus_interface,
 
1297
                                     dbus.PROPERTIES_IFACE)
 
1298
                return self.attributes[propname]
1386
1299
            def Approve(self, approve, dbus_interface):
1387
 
                testcase.assertEqual(client_dbus_interface,
1388
 
                                     dbus_interface)
 
1300
                testcase.assertEqual(dbus_interface,
 
1301
                                     client_dbus_interface)
1389
1302
                self.calls.append(("Approve", (approve,
1390
1303
                                               dbus_interface)))
1391
1304
        self.client = MockClient(
1438
1351
            LastCheckerStatus=-2)
1439
1352
        self.clients =  collections.OrderedDict(
1440
1353
            [
1441
 
                (self.client.__dbus_object_path__,
1442
 
                 self.client.attributes),
1443
 
                (self.other_client.__dbus_object_path__,
1444
 
                 self.other_client.attributes),
 
1354
                ("/clients/foo", self.client.attributes),
 
1355
                ("/clients/barbar", self.other_client.attributes),
1445
1356
            ])
1446
 
        self.one_client = {self.client.__dbus_object_path__:
1447
 
                           self.client.attributes}
 
1357
        self.one_client = {"/clients/foo": self.client.attributes}
1448
1358
 
1449
1359
    @property
1450
1360
    def bus(self):
1451
 
        class MockBus(object):
 
1361
        class Bus(object):
1452
1362
            @staticmethod
1453
1363
            def get_object(client_bus_name, path):
1454
 
                self.assertEqual(dbus_busname, client_bus_name)
1455
 
                # Note: "self" here is the TestCmd instance, not the
1456
 
                # MockBus instance, since this is a static method!
1457
 
                if path == self.client.__dbus_object_path__:
1458
 
                    return self.client
1459
 
                elif path == self.other_client.__dbus_object_path__:
1460
 
                    return self.other_client
1461
 
        return MockBus()
1462
 
 
1463
 
 
1464
 
class TestBaseCommands(TestCommand):
1465
 
 
1466
 
    def test_IsEnabled_exits_successfully(self):
 
1364
                self.assertEqual(client_bus_name, dbus_busname)
 
1365
                return {
 
1366
                    # Note: "self" here is the TestCmd instance, not
 
1367
                    # the Bus instance, since this is a static method!
 
1368
                    "/clients/foo": self.client,
 
1369
                    "/clients/barbar": self.other_client,
 
1370
                }[path]
 
1371
        return Bus()
 
1372
 
 
1373
 
 
1374
class TestIsEnabledCmd(TestCmd):
 
1375
    def test_is_enabled(self):
 
1376
        self.assertTrue(all(IsEnabledCmd().is_enabled(client,
 
1377
                                                      properties)
 
1378
                            for client, properties
 
1379
                            in self.clients.items()))
 
1380
 
 
1381
    def test_is_enabled_run_exits_successfully(self):
1467
1382
        with self.assertRaises(SystemExit) as e:
1468
 
            command.IsEnabled().run(self.one_client)
 
1383
            IsEnabledCmd().run(self.one_client)
1469
1384
        if e.exception.code is not None:
1470
 
            self.assertEqual(0, e.exception.code)
 
1385
            self.assertEqual(e.exception.code, 0)
1471
1386
        else:
1472
1387
            self.assertIsNone(e.exception.code)
1473
1388
 
1474
 
    def test_IsEnabled_exits_with_failure(self):
 
1389
    def test_is_enabled_run_exits_with_failure(self):
1475
1390
        self.client.attributes["Enabled"] = dbus.Boolean(False)
1476
1391
        with self.assertRaises(SystemExit) as e:
1477
 
            command.IsEnabled().run(self.one_client)
 
1392
            IsEnabledCmd().run(self.one_client)
1478
1393
        if isinstance(e.exception.code, int):
1479
 
            self.assertNotEqual(0, e.exception.code)
 
1394
            self.assertNotEqual(e.exception.code, 0)
1480
1395
        else:
1481
1396
            self.assertIsNotNone(e.exception.code)
1482
1397
 
1483
 
    def test_Approve(self):
1484
 
        command.Approve().run(self.clients, self.bus)
 
1398
 
 
1399
class TestApproveCmd(TestCmd):
 
1400
    def test_approve(self):
 
1401
        ApproveCmd().run(self.clients, self.bus)
1485
1402
        for clientpath in self.clients:
1486
1403
            client = self.bus.get_object(dbus_busname, clientpath)
1487
1404
            self.assertIn(("Approve", (True, client_dbus_interface)),
1488
1405
                          client.calls)
1489
1406
 
1490
 
    def test_Deny(self):
1491
 
        command.Deny().run(self.clients, self.bus)
 
1407
 
 
1408
class TestDenyCmd(TestCmd):
 
1409
    def test_deny(self):
 
1410
        DenyCmd().run(self.clients, self.bus)
1492
1411
        for clientpath in self.clients:
1493
1412
            client = self.bus.get_object(dbus_busname, clientpath)
1494
1413
            self.assertIn(("Approve", (False, client_dbus_interface)),
1495
1414
                          client.calls)
1496
1415
 
1497
 
    def test_Remove(self):
1498
 
        class MandosSpy(object):
 
1416
 
 
1417
class TestRemoveCmd(TestCmd):
 
1418
    def test_remove(self):
 
1419
        class MockMandos(object):
1499
1420
            def __init__(self):
1500
1421
                self.calls = []
1501
1422
            def RemoveClient(self, dbus_path):
1502
1423
                self.calls.append(("RemoveClient", (dbus_path,)))
1503
 
        mandos = MandosSpy()
1504
 
        command.Remove().run(self.clients, self.bus, mandos)
 
1424
        mandos = MockMandos()
 
1425
        super(TestRemoveCmd, self).setUp()
 
1426
        RemoveCmd().run(self.clients, self.bus, mandos)
 
1427
        self.assertEqual(len(mandos.calls), 2)
1505
1428
        for clientpath in self.clients:
1506
1429
            self.assertIn(("RemoveClient", (clientpath,)),
1507
1430
                          mandos.calls)
1508
1431
 
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
 
        with self.capture_stdout_to_buffer() as buffer:
1562
 
            command.DumpJSON().run(self.clients)
1563
 
        json_data = json.loads(buffer.getvalue())
1564
 
        self.assertDictEqual(self.expected_json, json_data)
1565
 
 
1566
 
    @staticmethod
1567
 
    @contextlib.contextmanager
1568
 
    def capture_stdout_to_buffer():
1569
 
        capture_buffer = io.StringIO()
1570
 
        old_stdout = sys.stdout
1571
 
        sys.stdout = capture_buffer
1572
 
        try:
1573
 
            yield capture_buffer
1574
 
        finally:
1575
 
            sys.stdout = old_stdout
1576
 
 
1577
 
    def test_DumpJSON_one_client(self):
1578
 
        with self.capture_stdout_to_buffer() as buffer:
1579
 
            command.DumpJSON().run(self.one_client)
1580
 
        json_data = json.loads(buffer.getvalue())
 
1432
 
 
1433
class TestDumpJSONCmd(TestCmd):
 
1434
    def setUp(self):
 
1435
        self.expected_json = {
 
1436
            "foo": {
 
1437
                "Name": "foo",
 
1438
                "KeyID": ("92ed150794387c03ce684574b1139a65"
 
1439
                          "94a34f895daaaf09fd8ea90a27cddb12"),
 
1440
                "Host": "foo.example.org",
 
1441
                "Enabled": True,
 
1442
                "Timeout": 300000,
 
1443
                "LastCheckedOK": "2019-02-03T00:00:00",
 
1444
                "Created": "2019-01-02T00:00:00",
 
1445
                "Interval": 120000,
 
1446
                "Fingerprint": ("778827225BA7DE539C5A"
 
1447
                                "7CFA59CFF7CDBD9A5920"),
 
1448
                "CheckerRunning": False,
 
1449
                "LastEnabled": "2019-01-03T00:00:00",
 
1450
                "ApprovalPending": False,
 
1451
                "ApprovedByDefault": True,
 
1452
                "LastApprovalRequest": "",
 
1453
                "ApprovalDelay": 0,
 
1454
                "ApprovalDuration": 1000,
 
1455
                "Checker": "fping -q -- %(host)s",
 
1456
                "ExtendedTimeout": 900000,
 
1457
                "Expires": "2019-02-04T00:00:00",
 
1458
                "LastCheckerStatus": 0,
 
1459
            },
 
1460
            "barbar": {
 
1461
                "Name": "barbar",
 
1462
                "KeyID": ("0558568eedd67d622f5c83b35a115f79"
 
1463
                          "6ab612cff5ad227247e46c2b020f441c"),
 
1464
                "Host": "192.0.2.3",
 
1465
                "Enabled": True,
 
1466
                "Timeout": 300000,
 
1467
                "LastCheckedOK": "2019-02-04T00:00:00",
 
1468
                "Created": "2019-01-03T00:00:00",
 
1469
                "Interval": 120000,
 
1470
                "Fingerprint": ("3E393AEAEFB84C7E89E2"
 
1471
                                "F547B3A107558FCA3A27"),
 
1472
                "CheckerRunning": True,
 
1473
                "LastEnabled": "2019-01-04T00:00:00",
 
1474
                "ApprovalPending": False,
 
1475
                "ApprovedByDefault": False,
 
1476
                "LastApprovalRequest": "2019-01-03T00:00:00",
 
1477
                "ApprovalDelay": 30000,
 
1478
                "ApprovalDuration": 93785000,
 
1479
                "Checker": ":",
 
1480
                "ExtendedTimeout": 900000,
 
1481
                "Expires": "2019-02-05T00:00:00",
 
1482
                "LastCheckerStatus": -2,
 
1483
            },
 
1484
        }
 
1485
        return super(TestDumpJSONCmd, self).setUp()
 
1486
 
 
1487
    def test_normal(self):
 
1488
        output = DumpJSONCmd().output(self.clients.values())
 
1489
        json_data = json.loads(output)
 
1490
        self.assertDictEqual(json_data, self.expected_json)
 
1491
 
 
1492
    def test_one_client(self):
 
1493
        output = DumpJSONCmd().output(self.one_client.values())
 
1494
        json_data = json.loads(output)
1581
1495
        expected_json = {"foo": self.expected_json["foo"]}
1582
 
        self.assertDictEqual(expected_json, json_data)
1583
 
 
1584
 
    def test_PrintTable_normal(self):
1585
 
        with self.capture_stdout_to_buffer() as buffer:
1586
 
            command.PrintTable().run(self.clients)
 
1496
        self.assertDictEqual(json_data, expected_json)
 
1497
 
 
1498
 
 
1499
class TestPrintTableCmd(TestCmd):
 
1500
    def test_normal(self):
 
1501
        output = PrintTableCmd().output(self.clients.values())
1587
1502
        expected_output = "\n".join((
1588
1503
            "Name   Enabled Timeout  Last Successful Check",
1589
1504
            "foo    Yes     00:05:00 2019-02-03T00:00:00  ",
1590
1505
            "barbar Yes     00:05:00 2019-02-04T00:00:00  ",
1591
 
        )) + "\n"
1592
 
        self.assertEqual(expected_output, buffer.getvalue())
 
1506
        ))
 
1507
        self.assertEqual(output, expected_output)
1593
1508
 
1594
 
    def test_PrintTable_verbose(self):
1595
 
        with self.capture_stdout_to_buffer() as buffer:
1596
 
            command.PrintTable(verbose=True).run(self.clients)
 
1509
    def test_verbose(self):
 
1510
        output = PrintTableCmd(verbose=True).output(
 
1511
            self.clients.values())
1597
1512
        columns = (
1598
1513
            (
1599
1514
                "Name   ",
1681
1596
            )
1682
1597
        )
1683
1598
        num_lines = max(len(rows) for rows in columns)
1684
 
        expected_output = ("\n".join("".join(rows[line]
1685
 
                                             for rows in columns)
1686
 
                                     for line in range(num_lines))
1687
 
                           + "\n")
1688
 
        self.assertEqual(expected_output, buffer.getvalue())
 
1599
        expected_output = "\n".join("".join(rows[line]
 
1600
                                            for rows in columns)
 
1601
                                    for line in range(num_lines))
 
1602
        self.assertEqual(output, expected_output)
1689
1603
 
1690
 
    def test_PrintTable_one_client(self):
1691
 
        with self.capture_stdout_to_buffer() as buffer:
1692
 
            command.PrintTable().run(self.one_client)
 
1604
    def test_one_client(self):
 
1605
        output = PrintTableCmd().output(self.one_client.values())
1693
1606
        expected_output = "\n".join((
1694
1607
            "Name Enabled Timeout  Last Successful Check",
1695
1608
            "foo  Yes     00:05:00 2019-02-03T00:00:00  ",
1696
 
        )) + "\n"
1697
 
        self.assertEqual(expected_output, buffer.getvalue())
1698
 
 
1699
 
 
1700
 
class TestPropertySetterCmd(TestCommand):
1701
 
    """Abstract class for tests of command.PropertySetter classes"""
 
1609
        ))
 
1610
        self.assertEqual(output, expected_output)
 
1611
 
 
1612
 
 
1613
class TestPropertyCmd(TestCmd):
 
1614
    """Abstract class for tests of PropertyCmd classes"""
1702
1615
    def runTest(self):
1703
1616
        if not hasattr(self, "command"):
1704
1617
            return
1709
1622
            for clientpath in self.clients:
1710
1623
                client = self.bus.get_object(dbus_busname, clientpath)
1711
1624
                old_value = client.attributes[self.propname]
 
1625
                self.assertNotIsInstance(old_value, self.Unique)
1712
1626
                client.attributes[self.propname] = self.Unique()
1713
1627
            self.run_command(value_to_set, self.clients)
1714
1628
            for clientpath in self.clients:
1715
1629
                client = self.bus.get_object(dbus_busname, clientpath)
1716
1630
                value = client.attributes[self.propname]
1717
1631
                self.assertNotIsInstance(value, self.Unique)
1718
 
                self.assertEqual(value_to_get, value)
 
1632
                self.assertEqual(value, value_to_get)
1719
1633
 
1720
1634
    class Unique(object):
1721
1635
        """Class for objects which exist only to be unique objects,
1725
1639
        self.command().run(clients, self.bus)
1726
1640
 
1727
1641
 
1728
 
class TestEnableCmd(TestPropertySetterCmd):
1729
 
    command = command.Enable
 
1642
class TestEnableCmd(TestPropertyCmd):
 
1643
    command = EnableCmd
1730
1644
    propname = "Enabled"
1731
1645
    values_to_set = [dbus.Boolean(True)]
1732
1646
 
1733
1647
 
1734
 
class TestDisableCmd(TestPropertySetterCmd):
1735
 
    command = command.Disable
 
1648
class TestDisableCmd(TestPropertyCmd):
 
1649
    command = DisableCmd
1736
1650
    propname = "Enabled"
1737
1651
    values_to_set = [dbus.Boolean(False)]
1738
1652
 
1739
1653
 
1740
 
class TestBumpTimeoutCmd(TestPropertySetterCmd):
1741
 
    command = command.BumpTimeout
 
1654
class TestBumpTimeoutCmd(TestPropertyCmd):
 
1655
    command = BumpTimeoutCmd
1742
1656
    propname = "LastCheckedOK"
1743
1657
    values_to_set = [""]
1744
1658
 
1745
1659
 
1746
 
class TestStartCheckerCmd(TestPropertySetterCmd):
1747
 
    command = command.StartChecker
1748
 
    propname = "CheckerRunning"
1749
 
    values_to_set = [dbus.Boolean(True)]
1750
 
 
1751
 
 
1752
 
class TestStopCheckerCmd(TestPropertySetterCmd):
1753
 
    command = command.StopChecker
1754
 
    propname = "CheckerRunning"
1755
 
    values_to_set = [dbus.Boolean(False)]
1756
 
 
1757
 
 
1758
 
class TestApproveByDefaultCmd(TestPropertySetterCmd):
1759
 
    command = command.ApproveByDefault
1760
 
    propname = "ApprovedByDefault"
1761
 
    values_to_set = [dbus.Boolean(True)]
1762
 
 
1763
 
 
1764
 
class TestDenyByDefaultCmd(TestPropertySetterCmd):
1765
 
    command = command.DenyByDefault
1766
 
    propname = "ApprovedByDefault"
1767
 
    values_to_set = [dbus.Boolean(False)]
1768
 
 
1769
 
 
1770
 
class TestPropertySetterValueCmd(TestPropertySetterCmd):
1771
 
    """Abstract class for tests of PropertySetterValueCmd classes"""
 
1660
class TestStartCheckerCmd(TestPropertyCmd):
 
1661
    command = StartCheckerCmd
 
1662
    propname = "CheckerRunning"
 
1663
    values_to_set = [dbus.Boolean(True)]
 
1664
 
 
1665
 
 
1666
class TestStopCheckerCmd(TestPropertyCmd):
 
1667
    command = StopCheckerCmd
 
1668
    propname = "CheckerRunning"
 
1669
    values_to_set = [dbus.Boolean(False)]
 
1670
 
 
1671
 
 
1672
class TestApproveByDefaultCmd(TestPropertyCmd):
 
1673
    command = ApproveByDefaultCmd
 
1674
    propname = "ApprovedByDefault"
 
1675
    values_to_set = [dbus.Boolean(True)]
 
1676
 
 
1677
 
 
1678
class TestDenyByDefaultCmd(TestPropertyCmd):
 
1679
    command = DenyByDefaultCmd
 
1680
    propname = "ApprovedByDefault"
 
1681
    values_to_set = [dbus.Boolean(False)]
 
1682
 
 
1683
 
 
1684
class TestPropertyValueCmd(TestPropertyCmd):
 
1685
    """Abstract class for tests of PropertyValueCmd classes"""
1772
1686
 
1773
1687
    def runTest(self):
1774
 
        if type(self) is TestPropertySetterValueCmd:
 
1688
        if type(self) is TestPropertyValueCmd:
1775
1689
            return
1776
 
        return super(TestPropertySetterValueCmd, self).runTest()
 
1690
        return super(TestPropertyValueCmd, self).runTest()
1777
1691
 
1778
1692
    def run_command(self, value, clients):
1779
1693
        self.command(value).run(clients, self.bus)
1780
1694
 
1781
1695
 
1782
 
class TestSetCheckerCmd(TestPropertySetterValueCmd):
1783
 
    command = command.SetChecker
 
1696
class TestSetCheckerCmd(TestPropertyValueCmd):
 
1697
    command = SetCheckerCmd
1784
1698
    propname = "Checker"
1785
1699
    values_to_set = ["", ":", "fping -q -- %s"]
1786
1700
 
1787
1701
 
1788
 
class TestSetHostCmd(TestPropertySetterValueCmd):
1789
 
    command = command.SetHost
 
1702
class TestSetHostCmd(TestPropertyValueCmd):
 
1703
    command = SetHostCmd
1790
1704
    propname = "Host"
1791
 
    values_to_set = ["192.0.2.3", "client.example.org"]
1792
 
 
1793
 
 
1794
 
class TestSetSecretCmd(TestPropertySetterValueCmd):
1795
 
    command = command.SetSecret
 
1705
    values_to_set = ["192.0.2.3", "foo.example.org"]
 
1706
 
 
1707
 
 
1708
class TestSetSecretCmd(TestPropertyValueCmd):
 
1709
    command = SetSecretCmd
1796
1710
    propname = "Secret"
1797
1711
    values_to_set = [io.BytesIO(b""),
1798
1712
                     io.BytesIO(b"secret\0xyzzy\nbar")]
1799
 
    values_to_get = [f.getvalue() for f in values_to_set]
1800
 
 
1801
 
 
1802
 
class TestSetTimeoutCmd(TestPropertySetterValueCmd):
1803
 
    command = command.SetTimeout
 
1713
    values_to_get = [b"", b"secret\0xyzzy\nbar"]
 
1714
 
 
1715
 
 
1716
class TestSetTimeoutCmd(TestPropertyValueCmd):
 
1717
    command = SetTimeoutCmd
1804
1718
    propname = "Timeout"
1805
1719
    values_to_set = [datetime.timedelta(),
1806
1720
                     datetime.timedelta(minutes=5),
1807
1721
                     datetime.timedelta(seconds=1),
1808
1722
                     datetime.timedelta(weeks=1),
1809
1723
                     datetime.timedelta(weeks=52)]
1810
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1811
 
 
1812
 
 
1813
 
class TestSetExtendedTimeoutCmd(TestPropertySetterValueCmd):
1814
 
    command = command.SetExtendedTimeout
 
1724
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1725
 
 
1726
 
 
1727
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
 
1728
    command = SetExtendedTimeoutCmd
1815
1729
    propname = "ExtendedTimeout"
1816
1730
    values_to_set = [datetime.timedelta(),
1817
1731
                     datetime.timedelta(minutes=5),
1818
1732
                     datetime.timedelta(seconds=1),
1819
1733
                     datetime.timedelta(weeks=1),
1820
1734
                     datetime.timedelta(weeks=52)]
1821
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1822
 
 
1823
 
 
1824
 
class TestSetIntervalCmd(TestPropertySetterValueCmd):
1825
 
    command = command.SetInterval
 
1735
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1736
 
 
1737
 
 
1738
class TestSetIntervalCmd(TestPropertyValueCmd):
 
1739
    command = SetIntervalCmd
1826
1740
    propname = "Interval"
1827
1741
    values_to_set = [datetime.timedelta(),
1828
1742
                     datetime.timedelta(minutes=5),
1829
1743
                     datetime.timedelta(seconds=1),
1830
1744
                     datetime.timedelta(weeks=1),
1831
1745
                     datetime.timedelta(weeks=52)]
1832
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1833
 
 
1834
 
 
1835
 
class TestSetApprovalDelayCmd(TestPropertySetterValueCmd):
1836
 
    command = command.SetApprovalDelay
 
1746
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1747
 
 
1748
 
 
1749
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
 
1750
    command = SetApprovalDelayCmd
1837
1751
    propname = "ApprovalDelay"
1838
1752
    values_to_set = [datetime.timedelta(),
1839
1753
                     datetime.timedelta(minutes=5),
1840
1754
                     datetime.timedelta(seconds=1),
1841
1755
                     datetime.timedelta(weeks=1),
1842
1756
                     datetime.timedelta(weeks=52)]
1843
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1844
 
 
1845
 
 
1846
 
class TestSetApprovalDurationCmd(TestPropertySetterValueCmd):
1847
 
    command = command.SetApprovalDuration
 
1757
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1758
 
 
1759
 
 
1760
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
 
1761
    command = SetApprovalDurationCmd
1848
1762
    propname = "ApprovalDuration"
1849
1763
    values_to_set = [datetime.timedelta(),
1850
1764
                     datetime.timedelta(minutes=5),
1851
1765
                     datetime.timedelta(seconds=1),
1852
1766
                     datetime.timedelta(weeks=1),
1853
1767
                     datetime.timedelta(weeks=52)]
1854
 
    values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
 
1768
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1855
1769
 
1856
1770
 
1857
1771