/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-06 22:24:59 UTC
  • mto: (237.7.594 trunk)
  • mto: This revision was merged to the branch mainline in revision 382.
  • Revision ID: teddy@recompile.se-20190306222459-7q5j7dqwtiiwglg7
mandos-ctl.xml: Fix documentation bug

* mandos-ctl.xml (SYNOPSIS): Remove duplicate "--interval" option.

Show diffs side-by-side

added added

removed removed

Lines of Context:
44
44
import logging
45
45
import io
46
46
import tempfile
47
 
import contextlib
48
47
 
49
48
import dbus
50
49
 
294
293
                    "ApprovalDuration", "Checker", "ExtendedTimeout",
295
294
                    "Expires", "LastCheckerStatus")
296
295
    def run(self, mandos, clients):
297
 
        print(self.output(clients.values()))
298
 
    def output(self, clients):
299
 
        raise NotImplementedError()
 
296
        print(self.output(clients))
300
297
 
301
298
class PropertyCmd(Command):
302
299
    """Abstract class for Actions for setting one client property"""
303
300
    def run_on_one_client(self, client, properties):
304
301
        """Set the Client's D-Bus property"""
305
 
        log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", busname,
306
 
                  client.__dbus_object_path__,
307
 
                  dbus.PROPERTIES_IFACE, client_interface,
308
 
                  self.propname, self.value_to_set
309
 
                  if not isinstance(self.value_to_set, dbus.Boolean)
310
 
                  else bool(self.value_to_set))
311
 
        client.Set(client_interface, self.propname, self.value_to_set,
 
302
        client.Set(client_interface, self.property, self.value_to_set,
312
303
                   dbus_interface=dbus.PROPERTIES_IFACE)
313
 
    @property
314
 
    def propname(self):
315
 
        raise NotImplementedError()
316
304
 
317
305
class ValueArgumentMixIn(object):
318
306
    """Mixin class for commands taking a value as argument"""
328
316
    @value_to_set.setter
329
317
    def value_to_set(self, value):
330
318
        """When setting, convert value to a datetime.timedelta"""
331
 
        self._vts = int(round(value.total_seconds() * 1000))
 
319
        self._vts = string_to_delta(value).total_seconds() * 1000
332
320
 
333
321
# Actual (non-abstract) command classes
334
322
 
341
329
        keywords = default_keywords
342
330
        if self.verbose:
343
331
            keywords = self.all_keywords
344
 
        return str(self.TableOfClients(clients, keywords))
 
332
        return str(self.TableOfClients(clients.values(), keywords))
345
333
 
346
334
    class TableOfClients(object):
347
335
        tableheaders = {
438
426
            sys.exit(0)
439
427
        sys.exit(1)
440
428
    def is_enabled(self, client, properties):
441
 
        log.debug("D-Bus: %s:%s:%s.Get(%r, %r)", busname,
442
 
                  client.__dbus_object_path__,
443
 
                  dbus.PROPERTIES_IFACE, client_interface,
444
 
                  "Enabled")
445
 
        return bool(client.Get(client_interface, "Enabled",
446
 
                               dbus_interface=dbus.PROPERTIES_IFACE))
 
429
        return bool(properties["Enabled"])
447
430
 
448
431
class RemoveCmd(Command):
449
432
    def run_on_one_client(self, client, properties):
450
 
        log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", busname,
451
 
                  server_path, server_interface,
452
 
                  str(client.__dbus_object_path__))
453
433
        self.mandos.RemoveClient(client.__dbus_object_path__)
454
434
 
455
435
class ApproveCmd(Command):
456
436
    def run_on_one_client(self, client, properties):
457
 
        log.debug("D-Bus: %s:%s.Approve(True)",
458
 
                  client.__dbus_object_path__, client_interface)
459
437
        client.Approve(dbus.Boolean(True),
460
438
                       dbus_interface=client_interface)
461
439
 
462
440
class DenyCmd(Command):
463
441
    def run_on_one_client(self, client, properties):
464
 
        log.debug("D-Bus: %s:%s.Approve(False)",
465
 
                  client.__dbus_object_path__, client_interface)
466
442
        client.Approve(dbus.Boolean(False),
467
443
                       dbus_interface=client_interface)
468
444
 
469
445
class EnableCmd(PropertyCmd):
470
 
    propname = "Enabled"
 
446
    property = "Enabled"
471
447
    value_to_set = dbus.Boolean(True)
472
448
 
473
449
class DisableCmd(PropertyCmd):
474
 
    propname = "Enabled"
 
450
    property = "Enabled"
475
451
    value_to_set = dbus.Boolean(False)
476
452
 
477
453
class BumpTimeoutCmd(PropertyCmd):
478
 
    propname = "LastCheckedOK"
 
454
    property = "LastCheckedOK"
479
455
    value_to_set = ""
480
456
 
481
457
class StartCheckerCmd(PropertyCmd):
482
 
    propname = "CheckerRunning"
 
458
    property = "CheckerRunning"
483
459
    value_to_set = dbus.Boolean(True)
484
460
 
485
461
class StopCheckerCmd(PropertyCmd):
486
 
    propname = "CheckerRunning"
 
462
    property = "CheckerRunning"
487
463
    value_to_set = dbus.Boolean(False)
488
464
 
489
465
class ApproveByDefaultCmd(PropertyCmd):
490
 
    propname = "ApprovedByDefault"
 
466
    property = "ApprovedByDefault"
491
467
    value_to_set = dbus.Boolean(True)
492
468
 
493
469
class DenyByDefaultCmd(PropertyCmd):
494
 
    propname = "ApprovedByDefault"
 
470
    property = "ApprovedByDefault"
495
471
    value_to_set = dbus.Boolean(False)
496
472
 
497
473
class SetCheckerCmd(PropertyCmd, ValueArgumentMixIn):
498
 
    propname = "Checker"
 
474
    property = "Checker"
499
475
 
500
476
class SetHostCmd(PropertyCmd, ValueArgumentMixIn):
501
 
    propname = "Host"
 
477
    property = "Host"
502
478
 
503
479
class SetSecretCmd(PropertyCmd, ValueArgumentMixIn):
504
 
    propname = "Secret"
505
480
    @property
506
481
    def value_to_set(self):
507
482
        return self._vts
510
485
        """When setting, read data from supplied file object"""
511
486
        self._vts = value.read()
512
487
        value.close()
 
488
    property = "Secret"
513
489
 
514
490
class SetTimeoutCmd(PropertyCmd, MillisecondsValueArgumentMixIn):
515
 
    propname = "Timeout"
 
491
    property = "Timeout"
516
492
 
517
493
class SetExtendedTimeoutCmd(PropertyCmd,
518
494
                            MillisecondsValueArgumentMixIn):
519
 
    propname = "ExtendedTimeout"
 
495
    property = "ExtendedTimeout"
520
496
 
521
497
class SetIntervalCmd(PropertyCmd, MillisecondsValueArgumentMixIn):
522
 
    propname = "Interval"
 
498
    property = "Interval"
523
499
 
524
500
class SetApprovalDelayCmd(PropertyCmd,
525
501
                          MillisecondsValueArgumentMixIn):
526
 
    propname = "ApprovalDelay"
 
502
    property = "ApprovalDelay"
527
503
 
528
504
class SetApprovalDurationCmd(PropertyCmd,
529
505
                             MillisecondsValueArgumentMixIn):
530
 
    propname = "ApprovalDuration"
 
506
    property = "ApprovalDuration"
 
507
 
 
508
def has_actions(options):
 
509
    return any((options.enable,
 
510
                options.disable,
 
511
                options.bump_timeout,
 
512
                options.start_checker,
 
513
                options.stop_checker,
 
514
                options.is_enabled,
 
515
                options.remove,
 
516
                options.checker is not None,
 
517
                options.timeout is not None,
 
518
                options.extended_timeout is not None,
 
519
                options.interval is not None,
 
520
                options.approved_by_default is not None,
 
521
                options.approval_delay is not None,
 
522
                options.approval_duration is not None,
 
523
                options.host is not None,
 
524
                options.secret is not None,
 
525
                options.approve,
 
526
                options.deny))
531
527
 
532
528
def add_command_line_options(parser):
533
529
    parser.add_argument("--version", action="version",
560
556
                        help="Remove client")
561
557
    parser.add_argument("-c", "--checker",
562
558
                        help="Set checker command for client")
563
 
    parser.add_argument("-t", "--timeout", type=string_to_delta,
 
559
    parser.add_argument("-t", "--timeout",
564
560
                        help="Set timeout for client")
565
 
    parser.add_argument("--extended-timeout", type=string_to_delta,
 
561
    parser.add_argument("--extended-timeout",
566
562
                        help="Set extended timeout for client")
567
 
    parser.add_argument("-i", "--interval", type=string_to_delta,
 
563
    parser.add_argument("-i", "--interval",
568
564
                        help="Set checker interval for client")
569
565
    approve_deny_default = parser.add_mutually_exclusive_group()
570
566
    approve_deny_default.add_argument(
575
571
        "--deny-by-default", action="store_false",
576
572
        dest="approved_by_default",
577
573
        help="Set client to be denied by default")
578
 
    parser.add_argument("--approval-delay", type=string_to_delta,
 
574
    parser.add_argument("--approval-delay",
579
575
                        help="Set delay before client approve/deny")
580
 
    parser.add_argument("--approval-duration", type=string_to_delta,
 
576
    parser.add_argument("--approval-duration",
581
577
                        help="Set duration of one client approval")
582
578
    parser.add_argument("-H", "--host", help="Set host for client")
583
579
    parser.add_argument("-s", "--secret",
589
585
        help="Approve any current client request")
590
586
    approve_deny.add_argument("-D", "--deny", action="store_true",
591
587
                              help="Deny any current client request")
592
 
    parser.add_argument("--debug", action="store_true",
593
 
                        help="Debug mode (show D-Bus commands)")
594
588
    parser.add_argument("--check", action="store_true",
595
589
                        help="Run self-test")
596
590
    parser.add_argument("client", nargs="*", help="Client name")
621
615
    if options.is_enabled:
622
616
        commands.append(IsEnabledCmd())
623
617
 
 
618
    if options.remove:
 
619
        commands.append(RemoveCmd())
 
620
 
624
621
    if options.checker is not None:
625
622
        commands.append(SetCheckerCmd(options.checker))
626
623
 
659
656
    if options.deny:
660
657
        commands.append(DenyCmd())
661
658
 
662
 
    if options.remove:
663
 
        commands.append(RemoveCmd())
664
 
 
665
659
    # If no command option has been given, show table of clients,
666
660
    # optionally verbosely
667
661
    if not commands:
670
664
    return commands
671
665
 
672
666
 
673
 
def check_option_syntax(parser, options):
674
 
    """Apply additional restrictions on options, not expressible in
675
 
argparse"""
676
 
 
677
 
    def has_actions(options):
678
 
        return any((options.enable,
679
 
                    options.disable,
680
 
                    options.bump_timeout,
681
 
                    options.start_checker,
682
 
                    options.stop_checker,
683
 
                    options.is_enabled,
684
 
                    options.remove,
685
 
                    options.checker is not None,
686
 
                    options.timeout is not None,
687
 
                    options.extended_timeout is not None,
688
 
                    options.interval is not None,
689
 
                    options.approved_by_default is not None,
690
 
                    options.approval_delay is not None,
691
 
                    options.approval_duration is not None,
692
 
                    options.host is not None,
693
 
                    options.secret is not None,
694
 
                    options.approve,
695
 
                    options.deny))
 
667
def main():
 
668
    parser = argparse.ArgumentParser()
 
669
 
 
670
    add_command_line_options(parser)
 
671
 
 
672
    options = parser.parse_args()
696
673
 
697
674
    if has_actions(options) and not (options.client or options.all):
698
675
        parser.error("Options require clients names or --all.")
705
682
        parser.error("--all requires an action.")
706
683
    if options.is_enabled and len(options.client) > 1:
707
684
        parser.error("--is-enabled requires exactly one client")
708
 
    if options.remove:
709
 
        options.remove = False
710
 
        if has_actions(options) and not options.deny:
711
 
            parser.error("--remove can only be combined with --deny")
712
 
        options.remove = True
713
 
 
714
 
 
715
 
def main():
716
 
    parser = argparse.ArgumentParser()
717
 
 
718
 
    add_command_line_options(parser)
719
 
 
720
 
    options = parser.parse_args()
721
 
 
722
 
    check_option_syntax(parser, options)
723
685
 
724
686
    clientnames = options.client
725
687
 
726
 
    if options.debug:
727
 
        log.setLevel(logging.DEBUG)
728
 
 
729
688
    try:
730
689
        bus = dbus.SystemBus()
731
 
        log.debug("D-Bus: Connect to: (name=%r, path=%r)", busname,
732
 
                  server_path)
733
690
        mandos_dbus_objc = bus.get_object(busname, server_path)
734
691
    except dbus.exceptions.DBusException:
735
692
        log.critical("Could not connect to Mandos server")
748
705
    dbus_filter = NullFilter()
749
706
    try:
750
707
        dbus_logger.addFilter(dbus_filter)
751
 
        log.debug("D-Bus: %s:%s:%s.GetManagedObjects()", busname,
752
 
                  server_path, dbus.OBJECT_MANAGER_IFACE)
753
708
        mandos_clients = {path: ifs_and_props[client_interface]
754
709
                          for path, ifs_and_props in
755
710
                          mandos_serv_object_manager
767
722
    clients = {}
768
723
 
769
724
    if not clientnames:
770
 
        clients = {(log.debug("D-Bus: Connect to: (name=%r, path=%r)",
771
 
                              busname, str(path)) and False) or
772
 
                   bus.get_object(busname, path): properties
 
725
        clients = {bus.get_object(busname, path): properties
773
726
                   for path, properties in mandos_clients.items()}
774
727
    else:
775
728
        for name in clientnames:
776
729
            for path, client in mandos_clients.items():
777
730
                if client["Name"] == name:
778
 
                    log.debug("D-Bus: Connect to: (name=%r, path=%r)",
779
 
                              busname, str(path))
780
731
                    client_objc = bus.get_object(busname, path)
781
732
                    clients[client_objc] = client
782
733
                    break
846
797
                self.attributes = attributes
847
798
                self.attributes["Name"] = name
848
799
                self.calls = []
849
 
            def Set(self, interface, propname, value, dbus_interface):
850
 
                testcase.assertEqual(interface, client_interface)
851
 
                testcase.assertEqual(dbus_interface,
852
 
                                     dbus.PROPERTIES_IFACE)
853
 
                self.attributes[propname] = value
854
 
            def Get(self, interface, propname, dbus_interface):
855
 
                testcase.assertEqual(interface, client_interface)
856
 
                testcase.assertEqual(dbus_interface,
857
 
                                     dbus.PROPERTIES_IFACE)
858
 
                return self.attributes[propname]
 
800
            def Set(self, interface, property, value, dbus_interface):
 
801
                testcase.assertEqual(interface, client_interface)
 
802
                testcase.assertEqual(dbus_interface,
 
803
                                     dbus.PROPERTIES_IFACE)
 
804
                self.attributes[property] = value
 
805
            def Get(self, interface, property, dbus_interface):
 
806
                testcase.assertEqual(interface, client_interface)
 
807
                testcase.assertEqual(dbus_interface,
 
808
                                     dbus.PROPERTIES_IFACE)
 
809
                return self.attributes[property]
859
810
            def Approve(self, approve, dbus_interface):
860
811
                testcase.assertEqual(dbus_interface, client_interface)
861
812
                self.calls.append(("Approve", (approve,
917
868
 
918
869
class TestPrintTableCmd(TestCmd):
919
870
    def test_normal(self):
920
 
        output = PrintTableCmd().output(self.clients.values())
 
871
        output = PrintTableCmd().output(self.clients)
921
872
        expected_output = """
922
873
Name   Enabled Timeout  Last Successful Check
923
874
foo    Yes     00:05:00 2019-02-03T00:00:00  
925
876
"""[1:-1]
926
877
        self.assertEqual(output, expected_output)
927
878
    def test_verbose(self):
928
 
        output = PrintTableCmd(verbose=True).output(
929
 
            self.clients.values())
 
879
        output = PrintTableCmd(verbose=True).output(self.clients)
930
880
        expected_output = """
931
881
Name   Enabled Timeout  Last Successful Check Created             Interval Host            Key ID                                                           Fingerprint                              Check Is Running Last Enabled        Approval Is Pending Approved By Default Last Approval Request Approval Delay Approval Duration Checker              Extended Timeout Expires             Last Checker Status
932
882
foo    Yes     00:05:00 2019-02-03T00:00:00   2019-01-02T00:00:00 00:02:00 foo.example.org 92ed150794387c03ce684574b1139a6594a34f895daaaf09fd8ea90a27cddb12 778827225BA7DE539C5A7CFA59CFF7CDBD9A5920 No               2019-01-03T00:00:00 No                  Yes                                       00:00:00       00:00:01          fping -q -- %(host)s 00:15:00         2019-02-04T00:00:00 0                  
934
884
"""[1:-1]
935
885
        self.assertEqual(output, expected_output)
936
886
    def test_one_client(self):
937
 
        output = PrintTableCmd().output(self.one_client.values())
 
887
        output = PrintTableCmd().output(self.one_client)
938
888
        expected_output = """
939
889
Name Enabled Timeout  Last Successful Check
940
890
foo  Yes     00:05:00 2019-02-03T00:00:00  
1084
1034
        for value_to_set, value_to_get in zip(self.values_to_set,
1085
1035
                                              values_to_get):
1086
1036
            for client in self.clients:
1087
 
                old_value = client.attributes[self.propname]
 
1037
                old_value = client.attributes[self.property]
1088
1038
                self.assertNotIsInstance(old_value, Unique)
1089
 
                client.attributes[self.propname] = Unique()
 
1039
                client.attributes[self.property] = Unique()
1090
1040
            self.run_command(value_to_set, self.clients)
1091
1041
            for client in self.clients:
1092
 
                value = client.attributes[self.propname]
 
1042
                value = client.attributes[self.property]
1093
1043
                self.assertNotIsInstance(value, Unique)
1094
1044
                self.assertEqual(value, value_to_get)
1095
1045
    def run_command(self, value, clients):
1097
1047
 
1098
1048
class TestBumpTimeoutCmd(TestPropertyCmd):
1099
1049
    command = BumpTimeoutCmd
1100
 
    propname = "LastCheckedOK"
 
1050
    property = "LastCheckedOK"
1101
1051
    values_to_set = [""]
1102
1052
 
1103
1053
class TestStartCheckerCmd(TestPropertyCmd):
1104
1054
    command = StartCheckerCmd
1105
 
    propname = "CheckerRunning"
 
1055
    property = "CheckerRunning"
1106
1056
    values_to_set = [dbus.Boolean(True)]
1107
1057
 
1108
1058
class TestStopCheckerCmd(TestPropertyCmd):
1109
1059
    command = StopCheckerCmd
1110
 
    propname = "CheckerRunning"
 
1060
    property = "CheckerRunning"
1111
1061
    values_to_set = [dbus.Boolean(False)]
1112
1062
 
1113
1063
class TestApproveByDefaultCmd(TestPropertyCmd):
1114
1064
    command = ApproveByDefaultCmd
1115
 
    propname = "ApprovedByDefault"
 
1065
    property = "ApprovedByDefault"
1116
1066
    values_to_set = [dbus.Boolean(True)]
1117
1067
 
1118
1068
class TestDenyByDefaultCmd(TestPropertyCmd):
1119
1069
    command = DenyByDefaultCmd
1120
 
    propname = "ApprovedByDefault"
 
1070
    property = "ApprovedByDefault"
1121
1071
    values_to_set = [dbus.Boolean(False)]
1122
1072
 
1123
1073
class TestValueArgumentPropertyCmd(TestPropertyCmd):
1132
1082
 
1133
1083
class TestSetCheckerCmd(TestValueArgumentPropertyCmd):
1134
1084
    command = SetCheckerCmd
1135
 
    propname = "Checker"
 
1085
    property = "Checker"
1136
1086
    values_to_set = ["", ":", "fping -q -- %s"]
1137
1087
 
1138
1088
class TestSetHostCmd(TestValueArgumentPropertyCmd):
1139
1089
    command = SetHostCmd
1140
 
    propname = "Host"
 
1090
    property = "Host"
1141
1091
    values_to_set = ["192.0.2.3", "foo.example.org"]
1142
1092
 
1143
1093
class TestSetSecretCmd(TestValueArgumentPropertyCmd):
1144
1094
    command = SetSecretCmd
1145
 
    propname = "Secret"
1146
 
    values_to_set = [io.BytesIO(b""),
 
1095
    property = "Secret"
 
1096
    values_to_set = [open("/dev/null", "rb"),
1147
1097
                     io.BytesIO(b"secret\0xyzzy\nbar")]
1148
1098
    values_to_get = [b"", b"secret\0xyzzy\nbar"]
1149
1099
 
1150
1100
class TestSetTimeoutCmd(TestValueArgumentPropertyCmd):
1151
1101
    command = SetTimeoutCmd
1152
 
    propname = "Timeout"
1153
 
    values_to_set = [datetime.timedelta(),
1154
 
                     datetime.timedelta(minutes=5),
1155
 
                     datetime.timedelta(seconds=1),
1156
 
                     datetime.timedelta(weeks=1),
1157
 
                     datetime.timedelta(weeks=52)]
1158
 
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1102
    property = "Timeout"
 
1103
    values_to_set = ["P0D", "PT5M", "PT1S", "PT120S", "P1Y"]
 
1104
    values_to_get = [0, 300000, 1000, 120000, 31449600000]
1159
1105
 
1160
1106
class TestSetExtendedTimeoutCmd(TestValueArgumentPropertyCmd):
1161
1107
    command = SetExtendedTimeoutCmd
1162
 
    propname = "ExtendedTimeout"
1163
 
    values_to_set = [datetime.timedelta(),
1164
 
                     datetime.timedelta(minutes=5),
1165
 
                     datetime.timedelta(seconds=1),
1166
 
                     datetime.timedelta(weeks=1),
1167
 
                     datetime.timedelta(weeks=52)]
1168
 
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1108
    property = "ExtendedTimeout"
 
1109
    values_to_set = ["P0D", "PT5M", "PT1S", "PT120S", "P1Y"]
 
1110
    values_to_get = [0, 300000, 1000, 120000, 31449600000]
1169
1111
 
1170
1112
class TestSetIntervalCmd(TestValueArgumentPropertyCmd):
1171
1113
    command = SetIntervalCmd
1172
 
    propname = "Interval"
1173
 
    values_to_set = [datetime.timedelta(),
1174
 
                     datetime.timedelta(minutes=5),
1175
 
                     datetime.timedelta(seconds=1),
1176
 
                     datetime.timedelta(weeks=1),
1177
 
                     datetime.timedelta(weeks=52)]
1178
 
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1114
    property = "Interval"
 
1115
    values_to_set = ["P0D", "PT5M", "PT1S", "PT120S", "P1Y"]
 
1116
    values_to_get = [0, 300000, 1000, 120000, 31449600000]
1179
1117
 
1180
1118
class TestSetApprovalDelayCmd(TestValueArgumentPropertyCmd):
1181
1119
    command = SetApprovalDelayCmd
1182
 
    propname = "ApprovalDelay"
1183
 
    values_to_set = [datetime.timedelta(),
1184
 
                     datetime.timedelta(minutes=5),
1185
 
                     datetime.timedelta(seconds=1),
1186
 
                     datetime.timedelta(weeks=1),
1187
 
                     datetime.timedelta(weeks=52)]
1188
 
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1120
    property = "ApprovalDelay"
 
1121
    values_to_set = ["P0D", "PT5M", "PT1S", "PT120S", "P1Y"]
 
1122
    values_to_get = [0, 300000, 1000, 120000, 31449600000]
1189
1123
 
1190
1124
class TestSetApprovalDurationCmd(TestValueArgumentPropertyCmd):
1191
1125
    command = SetApprovalDurationCmd
1192
 
    propname = "ApprovalDuration"
1193
 
    values_to_set = [datetime.timedelta(),
1194
 
                     datetime.timedelta(minutes=5),
1195
 
                     datetime.timedelta(seconds=1),
1196
 
                     datetime.timedelta(weeks=1),
1197
 
                     datetime.timedelta(weeks=52)]
1198
 
    values_to_get = [0, 300000, 1000, 604800000, 31449600000]
 
1126
    property = "ApprovalDuration"
 
1127
    values_to_set = ["P0D", "PT5M", "PT1S", "PT120S", "P1Y"]
 
1128
    values_to_get = [0, 300000, 1000, 120000, 31449600000]
1199
1129
 
1200
1130
class Test_command_from_options(unittest.TestCase):
1201
1131
    def setUp(self):
1205
1135
        """Assert that parsing ARGS should result in an instance of
1206
1136
COMMAND_CLS with (optionally) all supplied attributes (CMD_ATTRS)."""
1207
1137
        options = self.parser.parse_args(args)
1208
 
        check_option_syntax(self.parser, options)
1209
1138
        commands = commands_from_options(options)
1210
1139
        self.assertEqual(len(commands), 1)
1211
1140
        command = commands[0]
1220
1149
        self.assert_command_from_args(["--verbose"], PrintTableCmd,
1221
1150
                                      verbose=True)
1222
1151
 
1223
 
    def test_print_table_verbose_short(self):
1224
 
        self.assert_command_from_args(["-v"], PrintTableCmd,
1225
 
                                      verbose=True)
1226
 
 
1227
1152
    def test_enable(self):
1228
1153
        self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1229
1154
 
1230
 
    def test_enable_short(self):
1231
 
        self.assert_command_from_args(["-e", "foo"], EnableCmd)
1232
 
 
1233
1155
    def test_disable(self):
1234
1156
        self.assert_command_from_args(["--disable", "foo"],
1235
1157
                                      DisableCmd)
1236
1158
 
1237
 
    def test_disable_short(self):
1238
 
        self.assert_command_from_args(["-d", "foo"], DisableCmd)
1239
 
 
1240
1159
    def test_bump_timeout(self):
1241
1160
        self.assert_command_from_args(["--bump-timeout", "foo"],
1242
1161
                                      BumpTimeoutCmd)
1243
1162
 
1244
 
    def test_bump_timeout_short(self):
1245
 
        self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1246
 
 
1247
1163
    def test_start_checker(self):
1248
1164
        self.assert_command_from_args(["--start-checker", "foo"],
1249
1165
                                      StartCheckerCmd)
1256
1172
        self.assert_command_from_args(["--remove", "foo"],
1257
1173
                                      RemoveCmd)
1258
1174
 
1259
 
    def test_remove_short(self):
1260
 
        self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1261
 
 
1262
1175
    def test_checker(self):
1263
1176
        self.assert_command_from_args(["--checker", ":", "foo"],
1264
1177
                                      SetCheckerCmd, value_to_set=":")
1265
1178
 
1266
 
    def test_checker_empty(self):
1267
 
        self.assert_command_from_args(["--checker", "", "foo"],
1268
 
                                      SetCheckerCmd, value_to_set="")
1269
 
 
1270
 
    def test_checker_short(self):
1271
 
        self.assert_command_from_args(["-c", ":", "foo"],
1272
 
                                      SetCheckerCmd, value_to_set=":")
1273
 
 
1274
1179
    def test_timeout(self):
1275
1180
        self.assert_command_from_args(["--timeout", "PT5M", "foo"],
1276
1181
                                      SetTimeoutCmd,
1277
1182
                                      value_to_set=300000)
1278
1183
 
1279
 
    def test_timeout_short(self):
1280
 
        self.assert_command_from_args(["-t", "PT5M", "foo"],
1281
 
                                      SetTimeoutCmd,
1282
 
                                      value_to_set=300000)
1283
 
 
1284
1184
    def test_extended_timeout(self):
1285
1185
        self.assert_command_from_args(["--extended-timeout", "PT15M",
1286
1186
                                       "foo"],
1292
1192
                                      SetIntervalCmd,
1293
1193
                                      value_to_set=120000)
1294
1194
 
1295
 
    def test_interval_short(self):
1296
 
        self.assert_command_from_args(["-i", "PT2M", "foo"],
1297
 
                                      SetIntervalCmd,
1298
 
                                      value_to_set=120000)
1299
 
 
1300
1195
    def test_approve_by_default(self):
1301
1196
        self.assert_command_from_args(["--approve-by-default", "foo"],
1302
1197
                                      ApproveByDefaultCmd)
1320
1215
                                       "foo"], SetHostCmd,
1321
1216
                                      value_to_set="foo.example.org")
1322
1217
 
1323
 
    def test_host_short(self):
1324
 
        self.assert_command_from_args(["-H", "foo.example.org",
1325
 
                                       "foo"], SetHostCmd,
1326
 
                                      value_to_set="foo.example.org")
1327
 
 
1328
1218
    def test_secret_devnull(self):
1329
1219
        self.assert_command_from_args(["--secret", os.path.devnull,
1330
1220
                                       "foo"], SetSecretCmd,
1339
1229
                                           "foo"], SetSecretCmd,
1340
1230
                                          value_to_set=value)
1341
1231
 
1342
 
    def test_secret_devnull_short(self):
1343
 
        self.assert_command_from_args(["-s", os.path.devnull, "foo"],
1344
 
                                      SetSecretCmd, value_to_set=b"")
1345
 
 
1346
 
    def test_secret_tempfile_short(self):
1347
 
        with tempfile.NamedTemporaryFile(mode="r+b") as f:
1348
 
            value = b"secret\0xyzzy\nbar"
1349
 
            f.write(value)
1350
 
            f.seek(0)
1351
 
            self.assert_command_from_args(["-s", f.name, "foo"],
1352
 
                                          SetSecretCmd,
1353
 
                                          value_to_set=value)
1354
 
 
1355
1232
    def test_approve(self):
1356
1233
        self.assert_command_from_args(["--approve", "foo"],
1357
1234
                                      ApproveCmd)
1358
1235
 
1359
 
    def test_approve_short(self):
1360
 
        self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1361
 
 
1362
1236
    def test_deny(self):
1363
1237
        self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1364
1238
 
1365
 
    def test_deny_short(self):
1366
 
        self.assert_command_from_args(["-D", "foo"], DenyCmd)
1367
 
 
1368
1239
    def test_dump_json(self):
1369
1240
        self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1370
1241
 
1372
1243
        self.assert_command_from_args(["--is-enabled", "foo"],
1373
1244
                                      IsEnabledCmd)
1374
1245
 
1375
 
    def test_is_enabled_short(self):
1376
 
        self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1377
 
 
1378
 
    def test_deny_before_remove(self):
1379
 
        options = self.parser.parse_args(["--deny", "--remove", "foo"])
1380
 
        check_option_syntax(self.parser, options)
1381
 
        commands = commands_from_options(options)
1382
 
        self.assertEqual(len(commands), 2)
1383
 
        self.assertIsInstance(commands[0], DenyCmd)
1384
 
        self.assertIsInstance(commands[1], RemoveCmd)
1385
 
 
1386
 
    def test_deny_before_remove_reversed(self):
1387
 
        options = self.parser.parse_args(["--remove", "--deny", "--all"])
1388
 
        check_option_syntax(self.parser, options)
1389
 
        commands = commands_from_options(options)
1390
 
        self.assertEqual(len(commands), 2)
1391
 
        self.assertIsInstance(commands[0], DenyCmd)
1392
 
        self.assertIsInstance(commands[1], RemoveCmd)
1393
 
 
1394
 
 
1395
 
class Test_check_option_syntax(unittest.TestCase):
1396
 
    # This mostly corresponds to the definition from has_actions() in
1397
 
    # check_option_syntax()
1398
 
    actions = {
1399
 
        # The actual values set here are not that important, but we do
1400
 
        # at least stick to the correct types, even though they are
1401
 
        # never used
1402
 
        "enable": True,
1403
 
        "disable": True,
1404
 
        "bump_timeout": True,
1405
 
        "start_checker": True,
1406
 
        "stop_checker": True,
1407
 
        "is_enabled": True,
1408
 
        "remove": True,
1409
 
        "checker": "x",
1410
 
        "timeout": datetime.timedelta(),
1411
 
        "extended_timeout": datetime.timedelta(),
1412
 
        "interval": datetime.timedelta(),
1413
 
        "approved_by_default": True,
1414
 
        "approval_delay": datetime.timedelta(),
1415
 
        "approval_duration": datetime.timedelta(),
1416
 
        "host": "x",
1417
 
        "secret": io.BytesIO(b"x"),
1418
 
        "approve": True,
1419
 
        "deny": True,
1420
 
    }
1421
 
 
1422
 
    def setUp(self):
1423
 
        self.parser = argparse.ArgumentParser()
1424
 
        add_command_line_options(self.parser)
1425
 
 
1426
 
    @contextlib.contextmanager
1427
 
    def assertParseError(self):
1428
 
        with self.assertRaises(SystemExit) as e:
1429
 
            with self.temporarily_suppress_stderr():
1430
 
                yield
1431
 
        # Exit code from argparse is guaranteed to be "2".  Reference:
1432
 
        # https://docs.python.org/3/library/argparse.html#exiting-methods
1433
 
        self.assertEqual(e.exception.code, 2)
1434
 
 
1435
 
    @staticmethod
1436
 
    @contextlib.contextmanager
1437
 
    def temporarily_suppress_stderr():
1438
 
        null = os.open(os.path.devnull, os.O_RDWR)
1439
 
        stderrcopy = os.dup(sys.stderr.fileno())
1440
 
        os.dup2(null, sys.stderr.fileno())
1441
 
        os.close(null)
1442
 
        try:
1443
 
            yield
1444
 
        finally:
1445
 
            # restore stderr
1446
 
            os.dup2(stderrcopy, sys.stderr.fileno())
1447
 
            os.close(stderrcopy)
1448
 
 
1449
 
    def check_option_syntax(self, options):
1450
 
        check_option_syntax(self.parser, options)
1451
 
 
1452
 
    def test_actions_requires_client_or_all(self):
1453
 
        for action, value in self.actions.items():
1454
 
            options = self.parser.parse_args()
1455
 
            setattr(options, action, value)
1456
 
            with self.assertParseError():
1457
 
                self.check_option_syntax(options)
1458
 
 
1459
 
    def test_actions_conflicts_with_verbose(self):
1460
 
        for action, value in self.actions.items():
1461
 
            options = self.parser.parse_args()
1462
 
            setattr(options, action, value)
1463
 
            options.verbose = True
1464
 
            with self.assertParseError():
1465
 
                self.check_option_syntax(options)
1466
 
 
1467
 
    def test_dump_json_conflicts_with_verbose(self):
1468
 
        options = self.parser.parse_args()
1469
 
        options.dump_json = True
1470
 
        options.verbose = True
1471
 
        with self.assertParseError():
1472
 
            self.check_option_syntax(options)
1473
 
 
1474
 
    def test_dump_json_conflicts_with_action(self):
1475
 
        for action, value in self.actions.items():
1476
 
            options = self.parser.parse_args()
1477
 
            setattr(options, action, value)
1478
 
            options.dump_json = True
1479
 
            with self.assertParseError():
1480
 
                self.check_option_syntax(options)
1481
 
 
1482
 
    def test_all_can_not_be_alone(self):
1483
 
        options = self.parser.parse_args()
1484
 
        options.all = True
1485
 
        with self.assertParseError():
1486
 
            self.check_option_syntax(options)
1487
 
 
1488
 
    def test_all_is_ok_with_any_action(self):
1489
 
        for action, value in self.actions.items():
1490
 
            options = self.parser.parse_args()
1491
 
            setattr(options, action, value)
1492
 
            options.all = True
1493
 
            self.check_option_syntax(options)
1494
 
 
1495
 
    def test_is_enabled_fails_without_client(self):
1496
 
        options = self.parser.parse_args()
1497
 
        options.is_enabled = True
1498
 
        with self.assertParseError():
1499
 
            self.check_option_syntax(options)
1500
 
 
1501
 
    def test_is_enabled_works_with_one_client(self):
1502
 
        options = self.parser.parse_args()
1503
 
        options.is_enabled = True
1504
 
        options.client = ["foo"]
1505
 
        self.check_option_syntax(options)
1506
 
 
1507
 
    def test_is_enabled_fails_with_two_clients(self):
1508
 
        options = self.parser.parse_args()
1509
 
        options.is_enabled = True
1510
 
        options.client = ["foo", "barbar"]
1511
 
        with self.assertParseError():
1512
 
            self.check_option_syntax(options)
1513
 
 
1514
 
    def test_remove_can_only_be_combined_with_action_deny(self):
1515
 
        for action, value in self.actions.items():
1516
 
            if action in {"remove", "deny"}:
1517
 
                continue
1518
 
            options = self.parser.parse_args()
1519
 
            setattr(options, action, value)
1520
 
            options.all = True
1521
 
            options.remove = True
1522
 
            with self.assertParseError():
1523
 
                self.check_option_syntax(options)
1524
 
 
1525
1246
 
1526
1247
 
1527
1248
def should_only_run_tests():