/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos-ctl

  • Committer: Teddy Hogeborn
  • Date: 2019-03-12 21:11:32 UTC
  • mto: This revision was merged to the branch mainline in revision 382.
  • Revision ID: teddy@recompile.se-20190312211132-q6mxkrybruj3irbn
mandos-ctl: Refactor

* mandos-ctl (Test_check_option_syntax): Reorder methods into logical
                                         order.
  (Test_command_from_options): Rename to "Test_commands_from_options",
                               and reorder methods to match order in
                               commands_from_options().

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