478
472
if options.is_enabled:
479
commands.append(command.IsEnabled())
473
commands.append(IsEnabledCmd())
481
475
if options.approve:
482
commands.append(command.Approve())
476
commands.append(ApproveCmd())
485
commands.append(command.Deny())
479
commands.append(DenyCmd())
487
481
if options.remove:
488
commands.append(command.Remove())
482
commands.append(RemoveCmd())
490
484
if options.dump_json:
491
commands.append(command.DumpJSON())
485
commands.append(DumpJSONCmd())
493
487
if options.enable:
494
commands.append(command.Enable())
488
commands.append(EnableCmd())
496
490
if options.disable:
497
commands.append(command.Disable())
491
commands.append(DisableCmd())
499
493
if options.bump_timeout:
500
commands.append(command.BumpTimeout())
494
commands.append(BumpTimeoutCmd())
502
496
if options.start_checker:
503
commands.append(command.StartChecker())
497
commands.append(StartCheckerCmd())
505
499
if options.stop_checker:
506
commands.append(command.StopChecker())
500
commands.append(StopCheckerCmd())
508
502
if options.approved_by_default is not None:
509
503
if options.approved_by_default:
510
commands.append(command.ApproveByDefault())
504
commands.append(ApproveByDefaultCmd())
512
commands.append(command.DenyByDefault())
506
commands.append(DenyByDefaultCmd())
514
508
if options.checker is not None:
515
commands.append(command.SetChecker(options.checker))
509
commands.append(SetCheckerCmd(options.checker))
517
511
if options.host is not None:
518
commands.append(command.SetHost(options.host))
512
commands.append(SetHostCmd(options.host))
520
514
if options.secret is not None:
521
commands.append(command.SetSecret(options.secret))
515
commands.append(SetSecretCmd(options.secret))
523
517
if options.timeout is not None:
524
commands.append(command.SetTimeout(options.timeout))
518
commands.append(SetTimeoutCmd(options.timeout))
526
520
if options.extended_timeout:
528
command.SetExtendedTimeout(options.extended_timeout))
522
SetExtendedTimeoutCmd(options.extended_timeout))
530
524
if options.interval is not None:
531
commands.append(command.SetInterval(options.interval))
525
commands.append(SetIntervalCmd(options.interval))
533
527
if options.approval_delay is not None:
535
command.SetApprovalDelay(options.approval_delay))
528
commands.append(SetApprovalDelayCmd(options.approval_delay))
537
530
if options.approval_duration is not None:
539
command.SetApprovalDuration(options.approval_duration))
532
SetApprovalDurationCmd(options.approval_duration))
541
534
# If no command option has been given, show table of clients,
542
535
# optionally verbosely
544
commands.append(command.PrintTable(verbose=options.verbose))
537
commands.append(PrintTableCmd(verbose=options.verbose))
549
class command(object):
550
"""A namespace for command classes"""
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.
559
for clientpath, properties in clients.items():
560
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
561
dbus_busname, str(clientpath))
562
client = bus.get_object(dbus_busname, clientpath)
563
self.run_on_one_client(client, properties)
566
class IsEnabled(Base):
567
def run(self, clients, bus=None, mandos=None):
568
client, properties = next(iter(clients.items()))
569
if self.is_enabled(client, properties):
572
def is_enabled(self, client, properties):
573
return properties["Enabled"]
577
def run_on_one_client(self, client, properties):
578
log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
579
client.__dbus_object_path__,
580
client_dbus_interface)
581
client.Approve(dbus.Boolean(True),
582
dbus_interface=client_dbus_interface)
586
def run_on_one_client(self, client, properties):
587
log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
588
client.__dbus_object_path__,
589
client_dbus_interface)
590
client.Approve(dbus.Boolean(False),
591
dbus_interface=client_dbus_interface)
595
def run(self, clients, bus, mandos):
596
for clientpath in clients.keys():
597
log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)",
598
dbus_busname, server_dbus_path,
599
server_dbus_interface, clientpath)
600
mandos.RemoveClient(clientpath)
604
"""Abstract class for commands outputting client details"""
605
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
606
"Created", "Interval", "Host", "KeyID",
607
"Fingerprint", "CheckerRunning",
608
"LastEnabled", "ApprovalPending",
609
"ApprovedByDefault", "LastApprovalRequest",
610
"ApprovalDelay", "ApprovalDuration",
611
"Checker", "ExtendedTimeout", "Expires",
615
class DumpJSON(Output):
616
def run(self, clients, bus=None, mandos=None):
617
data = {client["Name"]:
618
{key: self.dbus_boolean_to_bool(client[key])
619
for key in self.all_keywords}
620
for client in clients.values()}
621
print(json.dumps(data, indent=4, separators=(',', ': ')))
542
class Command(object):
543
"""Abstract class for commands"""
544
def run(self, clients, bus=None, mandos=None):
545
"""Normal commands should implement run_on_one_client(), but
546
commands which want to operate on all clients at the same time
547
can override this run() method instead."""
549
for clientpath, properties in clients.items():
550
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
551
dbus_busname, str(clientpath))
552
client = bus.get_object(dbus_busname, clientpath)
553
self.run_on_one_client(client, properties)
556
class IsEnabledCmd(Command):
557
def run(self, clients, bus=None, mandos=None):
558
client, properties = next(iter(clients.items()))
559
if self.is_enabled(client, properties):
562
def is_enabled(self, client, properties):
563
return properties["Enabled"]
566
class ApproveCmd(Command):
567
def run_on_one_client(self, client, properties):
568
log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
569
client.__dbus_object_path__, client_dbus_interface)
570
client.Approve(dbus.Boolean(True),
571
dbus_interface=client_dbus_interface)
574
class DenyCmd(Command):
575
def run_on_one_client(self, client, properties):
576
log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
577
client.__dbus_object_path__, client_dbus_interface)
578
client.Approve(dbus.Boolean(False),
579
dbus_interface=client_dbus_interface)
582
class RemoveCmd(Command):
583
def run_on_one_client(self, client, properties):
584
log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", dbus_busname,
585
server_dbus_path, server_dbus_interface,
586
str(client.__dbus_object_path__))
587
self.mandos.RemoveClient(client.__dbus_object_path__)
590
class OutputCmd(Command):
591
"""Abstract class for commands outputting client details"""
592
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
593
"Created", "Interval", "Host", "KeyID",
594
"Fingerprint", "CheckerRunning", "LastEnabled",
595
"ApprovalPending", "ApprovedByDefault",
596
"LastApprovalRequest", "ApprovalDelay",
597
"ApprovalDuration", "Checker", "ExtendedTimeout",
598
"Expires", "LastCheckerStatus")
600
def run(self, clients, bus=None, mandos=None):
601
print(self.output(clients.values()))
603
def output(self, clients):
604
raise NotImplementedError()
607
class DumpJSONCmd(OutputCmd):
608
def output(self, clients):
609
data = {client["Name"]:
610
{key: self.dbus_boolean_to_bool(client[key])
611
for key in self.all_keywords}
612
for client in clients}
613
return json.dumps(data, indent=4, separators=(',', ': '))
616
def dbus_boolean_to_bool(value):
617
if isinstance(value, dbus.Boolean):
622
class PrintTableCmd(OutputCmd):
623
def __init__(self, verbose=False):
624
self.verbose = verbose
626
def output(self, clients):
627
default_keywords = ("Name", "Enabled", "Timeout",
629
keywords = default_keywords
631
keywords = self.all_keywords
632
return str(self.TableOfClients(clients, keywords))
634
class TableOfClients(object):
637
"Enabled": "Enabled",
638
"Timeout": "Timeout",
639
"LastCheckedOK": "Last Successful Check",
640
"LastApprovalRequest": "Last Approval Request",
641
"Created": "Created",
642
"Interval": "Interval",
644
"Fingerprint": "Fingerprint",
646
"CheckerRunning": "Check Is Running",
647
"LastEnabled": "Last Enabled",
648
"ApprovalPending": "Approval Is Pending",
649
"ApprovedByDefault": "Approved By Default",
650
"ApprovalDelay": "Approval Delay",
651
"ApprovalDuration": "Approval Duration",
652
"Checker": "Checker",
653
"ExtendedTimeout": "Extended Timeout",
654
"Expires": "Expires",
655
"LastCheckerStatus": "Last Checker Status",
658
def __init__(self, clients, keywords):
659
self.clients = clients
660
self.keywords = keywords
663
return "\n".join(self.rows())
665
if sys.version_info.major == 2:
666
__unicode__ = __str__
668
return str(self).encode(locale.getpreferredencoding())
671
format_string = self.row_formatting_string()
672
rows = [self.header_line(format_string)]
673
rows.extend(self.client_line(client, format_string)
674
for client in self.clients)
677
def row_formatting_string(self):
678
"Format string used to format table rows"
679
return " ".join("{{{key}:{width}}}".format(
680
width=max(len(self.tableheaders[key]),
681
*(len(self.string_from_client(client, key))
682
for client in self.clients)),
684
for key in self.keywords)
686
def string_from_client(self, client, key):
687
return self.valuetostring(client[key], key)
690
def valuetostring(cls, value, keyword):
691
if isinstance(value, dbus.Boolean):
692
return "Yes" if value else "No"
693
if keyword in ("Timeout", "Interval", "ApprovalDelay",
694
"ApprovalDuration", "ExtendedTimeout"):
695
return cls.milliseconds_to_string(value)
698
def header_line(self, format_string):
699
return format_string.format(**self.tableheaders)
701
def client_line(self, client, format_string):
702
return format_string.format(
703
**{key: self.string_from_client(client, key)
704
for key in self.keywords})
624
def dbus_boolean_to_bool(value):
625
if isinstance(value, dbus.Boolean):
630
class PrintTable(Output):
631
def __init__(self, verbose=False):
632
self.verbose = verbose
634
def run(self, clients, bus=None, mandos=None):
635
default_keywords = ("Name", "Enabled", "Timeout",
637
keywords = default_keywords
639
keywords = self.all_keywords
640
print(self.TableOfClients(clients.values(), keywords))
642
class TableOfClients(object):
645
"Enabled": "Enabled",
646
"Timeout": "Timeout",
647
"LastCheckedOK": "Last Successful Check",
648
"LastApprovalRequest": "Last Approval Request",
649
"Created": "Created",
650
"Interval": "Interval",
652
"Fingerprint": "Fingerprint",
654
"CheckerRunning": "Check Is Running",
655
"LastEnabled": "Last Enabled",
656
"ApprovalPending": "Approval Is Pending",
657
"ApprovedByDefault": "Approved By Default",
658
"ApprovalDelay": "Approval Delay",
659
"ApprovalDuration": "Approval Duration",
660
"Checker": "Checker",
661
"ExtendedTimeout": "Extended Timeout",
662
"Expires": "Expires",
663
"LastCheckerStatus": "Last Checker Status",
666
def __init__(self, clients, keywords):
667
self.clients = clients
668
self.keywords = keywords
671
return "\n".join(self.rows())
673
if sys.version_info.major == 2:
674
__unicode__ = __str__
676
return str(self).encode(
677
locale.getpreferredencoding())
680
format_string = self.row_formatting_string()
681
rows = [self.header_line(format_string)]
682
rows.extend(self.client_line(client, format_string)
683
for client in self.clients)
686
def row_formatting_string(self):
687
"Format string used to format table rows"
688
return " ".join("{{{key}:{width}}}".format(
689
width=max(len(self.tableheaders[key]),
690
*(len(self.string_from_client(client,
692
for client in self.clients)),
694
for key in self.keywords)
696
def string_from_client(self, client, key):
697
return self.valuetostring(client[key], key)
700
def valuetostring(cls, value, keyword):
701
if isinstance(value, dbus.Boolean):
702
return "Yes" if value else "No"
703
if keyword in ("Timeout", "Interval", "ApprovalDelay",
704
"ApprovalDuration", "ExtendedTimeout"):
705
return cls.milliseconds_to_string(value)
708
def header_line(self, format_string):
709
return format_string.format(**self.tableheaders)
711
def client_line(self, client, format_string):
712
return format_string.format(
713
**{key: self.string_from_client(client, key)
714
for key in self.keywords})
717
def milliseconds_to_string(ms):
718
td = datetime.timedelta(0, 0, 0, ms)
719
return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
720
.format(days="{}T".format(td.days)
722
hours=td.seconds // 3600,
723
minutes=(td.seconds % 3600) // 60,
724
seconds=td.seconds % 60))
727
class PropertySetter(Base):
728
"Abstract class for Actions for setting one client property"
730
def run_on_one_client(self, client, properties):
731
"""Set the Client's D-Bus property"""
732
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
733
client.__dbus_object_path__,
734
dbus.PROPERTIES_IFACE, client_dbus_interface,
735
self.propname, self.value_to_set
736
if not isinstance(self.value_to_set,
738
else bool(self.value_to_set))
739
client.Set(client_dbus_interface, self.propname,
741
dbus_interface=dbus.PROPERTIES_IFACE)
745
raise NotImplementedError()
748
class Enable(PropertySetter):
750
value_to_set = dbus.Boolean(True)
753
class Disable(PropertySetter):
755
value_to_set = dbus.Boolean(False)
758
class BumpTimeout(PropertySetter):
759
propname = "LastCheckedOK"
763
class StartChecker(PropertySetter):
764
propname = "CheckerRunning"
765
value_to_set = dbus.Boolean(True)
768
class StopChecker(PropertySetter):
769
propname = "CheckerRunning"
770
value_to_set = dbus.Boolean(False)
773
class ApproveByDefault(PropertySetter):
774
propname = "ApprovedByDefault"
775
value_to_set = dbus.Boolean(True)
778
class DenyByDefault(PropertySetter):
779
propname = "ApprovedByDefault"
780
value_to_set = dbus.Boolean(False)
783
class PropertySetterValue(PropertySetter):
784
"""Abstract class for PropertySetter recieving a value as
785
constructor argument instead of a class attribute."""
786
def __init__(self, value):
787
self.value_to_set = value
790
class SetChecker(PropertySetterValue):
794
class SetHost(PropertySetterValue):
798
class SetSecret(PropertySetterValue):
802
def value_to_set(self):
806
def value_to_set(self, value):
807
"""When setting, read data from supplied file object"""
808
self._vts = value.read()
812
class PropertySetterValueMilliseconds(PropertySetterValue):
813
"""Abstract class for PropertySetterValue taking a value
814
argument as a datetime.timedelta() but should store it as
818
def value_to_set(self):
822
def value_to_set(self, value):
823
"When setting, convert value from a datetime.timedelta"
824
self._vts = int(round(value.total_seconds() * 1000))
827
class SetTimeout(PropertySetterValueMilliseconds):
831
class SetExtendedTimeout(PropertySetterValueMilliseconds):
832
propname = "ExtendedTimeout"
835
class SetInterval(PropertySetterValueMilliseconds):
836
propname = "Interval"
839
class SetApprovalDelay(PropertySetterValueMilliseconds):
840
propname = "ApprovalDelay"
843
class SetApprovalDuration(PropertySetterValueMilliseconds):
844
propname = "ApprovalDuration"
707
def milliseconds_to_string(ms):
708
td = datetime.timedelta(0, 0, 0, ms)
709
return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
710
.format(days="{}T".format(td.days)
712
hours=td.seconds // 3600,
713
minutes=(td.seconds % 3600) // 60,
714
seconds=td.seconds % 60))
717
class PropertyCmd(Command):
718
"""Abstract class for Actions for setting one client property"""
720
def run_on_one_client(self, client, properties):
721
"""Set the Client's D-Bus property"""
722
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
723
client.__dbus_object_path__,
724
dbus.PROPERTIES_IFACE, client_dbus_interface,
725
self.propname, self.value_to_set
726
if not isinstance(self.value_to_set, dbus.Boolean)
727
else bool(self.value_to_set))
728
client.Set(client_dbus_interface, self.propname,
730
dbus_interface=dbus.PROPERTIES_IFACE)
734
raise NotImplementedError()
737
class EnableCmd(PropertyCmd):
739
value_to_set = dbus.Boolean(True)
742
class DisableCmd(PropertyCmd):
744
value_to_set = dbus.Boolean(False)
747
class BumpTimeoutCmd(PropertyCmd):
748
propname = "LastCheckedOK"
752
class StartCheckerCmd(PropertyCmd):
753
propname = "CheckerRunning"
754
value_to_set = dbus.Boolean(True)
757
class StopCheckerCmd(PropertyCmd):
758
propname = "CheckerRunning"
759
value_to_set = dbus.Boolean(False)
762
class ApproveByDefaultCmd(PropertyCmd):
763
propname = "ApprovedByDefault"
764
value_to_set = dbus.Boolean(True)
767
class DenyByDefaultCmd(PropertyCmd):
768
propname = "ApprovedByDefault"
769
value_to_set = dbus.Boolean(False)
772
class PropertyValueCmd(PropertyCmd):
773
"""Abstract class for PropertyCmd recieving a value as argument"""
774
def __init__(self, value):
775
self.value_to_set = value
778
class SetCheckerCmd(PropertyValueCmd):
782
class SetHostCmd(PropertyValueCmd):
786
class SetSecretCmd(PropertyValueCmd):
790
def value_to_set(self):
794
def value_to_set(self, value):
795
"""When setting, read data from supplied file object"""
796
self._vts = value.read()
800
class MillisecondsPropertyValueArgumentCmd(PropertyValueCmd):
801
"""Abstract class for PropertyValueCmd taking a value argument as
802
a datetime.timedelta() but should store it as milliseconds."""
805
def value_to_set(self):
809
def value_to_set(self, value):
810
"""When setting, convert value from a datetime.timedelta"""
811
self._vts = int(round(value.total_seconds() * 1000))
814
class SetTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
818
class SetExtendedTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
819
propname = "ExtendedTimeout"
822
class SetIntervalCmd(MillisecondsPropertyValueArgumentCmd):
823
propname = "Interval"
826
class SetApprovalDelayCmd(MillisecondsPropertyValueArgumentCmd):
827
propname = "ApprovalDelay"
830
class SetApprovalDurationCmd(MillisecondsPropertyValueArgumentCmd):
831
propname = "ApprovalDuration"
848
class TestCaseWithAssertLogs(unittest.TestCase):
849
"""unittest.TestCase.assertLogs only exists in Python 3.4"""
851
if not hasattr(unittest.TestCase, "assertLogs"):
852
@contextlib.contextmanager
853
def assertLogs(self, logger, level=logging.INFO):
854
capturing_handler = self.CapturingLevelHandler(level)
855
old_level = logger.level
856
old_propagate = logger.propagate
857
logger.addHandler(capturing_handler)
858
logger.setLevel(level)
859
logger.propagate = False
861
yield capturing_handler.watcher
863
logger.propagate = old_propagate
864
logger.removeHandler(capturing_handler)
865
logger.setLevel(old_level)
866
self.assertGreater(len(capturing_handler.watcher.records),
869
class CapturingLevelHandler(logging.Handler):
870
def __init__(self, level, *args, **kwargs):
871
logging.Handler.__init__(self, *args, **kwargs)
872
self.watcher = self.LoggingWatcher([], [])
873
def emit(self, record):
874
self.watcher.records.append(record)
875
self.watcher.output.append(self.format(record))
877
LoggingWatcher = collections.namedtuple("LoggingWatcher",
882
class Test_string_to_delta(TestCaseWithAssertLogs):
883
# Just test basic RFC 3339 functionality here, the doc string for
884
# rfc3339_duration_to_delta() already has more comprehensive
885
# tests, which is run by doctest.
887
def test_rfc3339_zero_seconds(self):
888
self.assertEqual(datetime.timedelta(),
889
string_to_delta("PT0S"))
891
def test_rfc3339_zero_days(self):
892
self.assertEqual(datetime.timedelta(), string_to_delta("P0D"))
894
def test_rfc3339_one_second(self):
895
self.assertEqual(datetime.timedelta(0, 1),
896
string_to_delta("PT1S"))
898
def test_rfc3339_two_hours(self):
899
self.assertEqual(datetime.timedelta(0, 7200),
900
string_to_delta("PT2H"))
835
class Test_string_to_delta(unittest.TestCase):
836
def test_handles_basic_rfc3339(self):
837
self.assertEqual(string_to_delta("PT0S"),
838
datetime.timedelta())
839
self.assertEqual(string_to_delta("P0D"),
840
datetime.timedelta())
841
self.assertEqual(string_to_delta("PT1S"),
842
datetime.timedelta(0, 1))
843
self.assertEqual(string_to_delta("PT2H"),
844
datetime.timedelta(0, 7200))
902
846
def test_falls_back_to_pre_1_6_1_with_warning(self):
903
with self.assertLogs(log, logging.WARNING):
904
value = string_to_delta("2h")
905
self.assertEqual(datetime.timedelta(0, 7200), value)
847
# assertLogs only exists in Python 3.4
848
if hasattr(self, "assertLogs"):
849
with self.assertLogs(log, logging.WARNING):
850
value = string_to_delta("2h")
852
class WarningFilter(logging.Filter):
853
"""Don't show, but record the presence of, warnings"""
854
def filter(self, record):
855
is_warning = record.levelno >= logging.WARNING
856
self.found = is_warning or getattr(self, "found",
858
return not is_warning
859
warning_filter = WarningFilter()
860
log.addFilter(warning_filter)
862
value = string_to_delta("2h")
864
log.removeFilter(warning_filter)
865
self.assertTrue(getattr(warning_filter, "found", False))
866
self.assertEqual(value, datetime.timedelta(0, 7200))
908
869
class Test_check_option_syntax(unittest.TestCase):
1165
1091
options = self.parser.parse_args(args)
1166
1092
check_option_syntax(self.parser, options)
1167
1093
commands = commands_from_options(options)
1168
self.assertEqual(1, len(commands))
1094
self.assertEqual(len(commands), 1)
1169
1095
command = commands[0]
1170
1096
self.assertIsInstance(command, command_cls)
1171
1097
for key, value in cmd_attrs.items():
1172
self.assertEqual(value, getattr(command, key))
1098
self.assertEqual(getattr(command, key), value)
1174
1100
def test_is_enabled_short(self):
1175
self.assert_command_from_args(["-V", "client"],
1101
self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1178
1103
def test_approve(self):
1179
self.assert_command_from_args(["--approve", "client"],
1104
self.assert_command_from_args(["--approve", "foo"],
1182
1107
def test_approve_short(self):
1183
self.assert_command_from_args(["-A", "client"],
1108
self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1186
1110
def test_deny(self):
1187
self.assert_command_from_args(["--deny", "client"],
1111
self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1190
1113
def test_deny_short(self):
1191
self.assert_command_from_args(["-D", "client"], command.Deny)
1114
self.assert_command_from_args(["-D", "foo"], DenyCmd)
1193
1116
def test_remove(self):
1194
self.assert_command_from_args(["--remove", "client"],
1117
self.assert_command_from_args(["--remove", "foo"],
1197
1120
def test_deny_before_remove(self):
1198
1121
options = self.parser.parse_args(["--deny", "--remove",
1200
1123
check_option_syntax(self.parser, options)
1201
1124
commands = commands_from_options(options)
1202
self.assertEqual(2, len(commands))
1203
self.assertIsInstance(commands[0], command.Deny)
1204
self.assertIsInstance(commands[1], command.Remove)
1125
self.assertEqual(len(commands), 2)
1126
self.assertIsInstance(commands[0], DenyCmd)
1127
self.assertIsInstance(commands[1], RemoveCmd)
1206
1129
def test_deny_before_remove_reversed(self):
1207
1130
options = self.parser.parse_args(["--remove", "--deny",
1209
1132
check_option_syntax(self.parser, options)
1210
1133
commands = commands_from_options(options)
1211
self.assertEqual(2, len(commands))
1212
self.assertIsInstance(commands[0], command.Deny)
1213
self.assertIsInstance(commands[1], command.Remove)
1134
self.assertEqual(len(commands), 2)
1135
self.assertIsInstance(commands[0], DenyCmd)
1136
self.assertIsInstance(commands[1], RemoveCmd)
1215
1138
def test_remove_short(self):
1216
self.assert_command_from_args(["-r", "client"],
1139
self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1219
1141
def test_dump_json(self):
1220
self.assert_command_from_args(["--dump-json"],
1142
self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1223
1144
def test_enable(self):
1224
self.assert_command_from_args(["--enable", "client"],
1145
self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1227
1147
def test_enable_short(self):
1228
self.assert_command_from_args(["-e", "client"],
1148
self.assert_command_from_args(["-e", "foo"], EnableCmd)
1231
1150
def test_disable(self):
1232
self.assert_command_from_args(["--disable", "client"],
1151
self.assert_command_from_args(["--disable", "foo"],
1235
1154
def test_disable_short(self):
1236
self.assert_command_from_args(["-d", "client"],
1155
self.assert_command_from_args(["-d", "foo"], DisableCmd)
1239
1157
def test_bump_timeout(self):
1240
self.assert_command_from_args(["--bump-timeout", "client"],
1241
command.BumpTimeout)
1158
self.assert_command_from_args(["--bump-timeout", "foo"],
1243
1161
def test_bump_timeout_short(self):
1244
self.assert_command_from_args(["-b", "client"],
1245
command.BumpTimeout)
1162
self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1247
1164
def test_start_checker(self):
1248
self.assert_command_from_args(["--start-checker", "client"],
1249
command.StartChecker)
1165
self.assert_command_from_args(["--start-checker", "foo"],
1251
1168
def test_stop_checker(self):
1252
self.assert_command_from_args(["--stop-checker", "client"],
1253
command.StopChecker)
1169
self.assert_command_from_args(["--stop-checker", "foo"],
1255
1172
def test_approve_by_default(self):
1256
self.assert_command_from_args(["--approve-by-default",
1258
command.ApproveByDefault)
1173
self.assert_command_from_args(["--approve-by-default", "foo"],
1174
ApproveByDefaultCmd)
1260
1176
def test_deny_by_default(self):
1261
self.assert_command_from_args(["--deny-by-default", "client"],
1262
command.DenyByDefault)
1177
self.assert_command_from_args(["--deny-by-default", "foo"],
1264
1180
def test_checker(self):
1265
self.assert_command_from_args(["--checker", ":", "client"],
1181
self.assert_command_from_args(["--checker", ":", "foo"],
1182
SetCheckerCmd, value_to_set=":")
1269
1184
def test_checker_empty(self):
1270
self.assert_command_from_args(["--checker", "", "client"],
1185
self.assert_command_from_args(["--checker", "", "foo"],
1186
SetCheckerCmd, value_to_set="")
1274
1188
def test_checker_short(self):
1275
self.assert_command_from_args(["-c", ":", "client"],
1189
self.assert_command_from_args(["-c", ":", "foo"],
1190
SetCheckerCmd, value_to_set=":")
1279
1192
def test_host(self):
1280
self.assert_command_from_args(
1281
["--host", "client.example.org", "client"],
1282
command.SetHost, value_to_set="client.example.org")
1193
self.assert_command_from_args(["--host", "foo.example.org",
1195
value_to_set="foo.example.org")
1284
1197
def test_host_short(self):
1285
self.assert_command_from_args(
1286
["-H", "client.example.org", "client"], command.SetHost,
1287
value_to_set="client.example.org")
1198
self.assert_command_from_args(["-H", "foo.example.org",
1200
value_to_set="foo.example.org")
1289
1202
def test_secret_devnull(self):
1290
1203
self.assert_command_from_args(["--secret", os.path.devnull,
1291
"client"], command.SetSecret,
1204
"foo"], SetSecretCmd,
1292
1205
value_to_set=b"")
1294
1207
def test_secret_tempfile(self):
1438
1351
LastCheckerStatus=-2)
1439
1352
self.clients = collections.OrderedDict(
1441
(self.client.__dbus_object_path__,
1442
self.client.attributes),
1443
(self.other_client.__dbus_object_path__,
1444
self.other_client.attributes),
1354
("/clients/foo", self.client.attributes),
1355
("/clients/barbar", self.other_client.attributes),
1446
self.one_client = {self.client.__dbus_object_path__:
1447
self.client.attributes}
1357
self.one_client = {"/clients/foo": self.client.attributes}
1451
class MockBus(object):
1453
1363
def get_object(client_bus_name, path):
1454
self.assertEqual(dbus_busname, client_bus_name)
1455
# Note: "self" here is the TestCmd instance, not the
1456
# MockBus instance, since this is a static method!
1457
if path == self.client.__dbus_object_path__:
1459
elif path == self.other_client.__dbus_object_path__:
1460
return self.other_client
1464
class TestBaseCommands(TestCommand):
1466
def test_IsEnabled_exits_successfully(self):
1364
self.assertEqual(client_bus_name, dbus_busname)
1366
# Note: "self" here is the TestCmd instance, not
1367
# the Bus instance, since this is a static method!
1368
"/clients/foo": self.client,
1369
"/clients/barbar": self.other_client,
1374
class TestIsEnabledCmd(TestCmd):
1375
def test_is_enabled(self):
1376
self.assertTrue(all(IsEnabledCmd().is_enabled(client,
1378
for client, properties
1379
in self.clients.items()))
1381
def test_is_enabled_run_exits_successfully(self):
1467
1382
with self.assertRaises(SystemExit) as e:
1468
command.IsEnabled().run(self.one_client)
1383
IsEnabledCmd().run(self.one_client)
1469
1384
if e.exception.code is not None:
1470
self.assertEqual(0, e.exception.code)
1385
self.assertEqual(e.exception.code, 0)
1472
1387
self.assertIsNone(e.exception.code)
1474
def test_IsEnabled_exits_with_failure(self):
1389
def test_is_enabled_run_exits_with_failure(self):
1475
1390
self.client.attributes["Enabled"] = dbus.Boolean(False)
1476
1391
with self.assertRaises(SystemExit) as e:
1477
command.IsEnabled().run(self.one_client)
1392
IsEnabledCmd().run(self.one_client)
1478
1393
if isinstance(e.exception.code, int):
1479
self.assertNotEqual(0, e.exception.code)
1394
self.assertNotEqual(e.exception.code, 0)
1481
1396
self.assertIsNotNone(e.exception.code)
1483
def test_Approve(self):
1484
command.Approve().run(self.clients, self.bus)
1399
class TestApproveCmd(TestCmd):
1400
def test_approve(self):
1401
ApproveCmd().run(self.clients, self.bus)
1485
1402
for clientpath in self.clients:
1486
1403
client = self.bus.get_object(dbus_busname, clientpath)
1487
1404
self.assertIn(("Approve", (True, client_dbus_interface)),
1490
def test_Deny(self):
1491
command.Deny().run(self.clients, self.bus)
1408
class TestDenyCmd(TestCmd):
1409
def test_deny(self):
1410
DenyCmd().run(self.clients, self.bus)
1492
1411
for clientpath in self.clients:
1493
1412
client = self.bus.get_object(dbus_busname, clientpath)
1494
1413
self.assertIn(("Approve", (False, client_dbus_interface)),
1497
def test_Remove(self):
1498
class MandosSpy(object):
1417
class TestRemoveCmd(TestCmd):
1418
def test_remove(self):
1419
class MockMandos(object):
1499
1420
def __init__(self):
1500
1421
self.calls = []
1501
1422
def RemoveClient(self, dbus_path):
1502
1423
self.calls.append(("RemoveClient", (dbus_path,)))
1503
mandos = MandosSpy()
1504
command.Remove().run(self.clients, self.bus, mandos)
1424
mandos = MockMandos()
1425
super(TestRemoveCmd, self).setUp()
1426
RemoveCmd().run(self.clients, self.bus, mandos)
1427
self.assertEqual(len(mandos.calls), 2)
1505
1428
for clientpath in self.clients:
1506
1429
self.assertIn(("RemoveClient", (clientpath,)),
1512
"KeyID": ("92ed150794387c03ce684574b1139a65"
1513
"94a34f895daaaf09fd8ea90a27cddb12"),
1514
"Host": "foo.example.org",
1517
"LastCheckedOK": "2019-02-03T00:00:00",
1518
"Created": "2019-01-02T00:00:00",
1520
"Fingerprint": ("778827225BA7DE539C5A"
1521
"7CFA59CFF7CDBD9A5920"),
1522
"CheckerRunning": False,
1523
"LastEnabled": "2019-01-03T00:00:00",
1524
"ApprovalPending": False,
1525
"ApprovedByDefault": True,
1526
"LastApprovalRequest": "",
1528
"ApprovalDuration": 1000,
1529
"Checker": "fping -q -- %(host)s",
1530
"ExtendedTimeout": 900000,
1531
"Expires": "2019-02-04T00:00:00",
1532
"LastCheckerStatus": 0,
1536
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1537
"6ab612cff5ad227247e46c2b020f441c"),
1538
"Host": "192.0.2.3",
1541
"LastCheckedOK": "2019-02-04T00:00:00",
1542
"Created": "2019-01-03T00:00:00",
1544
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1545
"F547B3A107558FCA3A27"),
1546
"CheckerRunning": True,
1547
"LastEnabled": "2019-01-04T00:00:00",
1548
"ApprovalPending": False,
1549
"ApprovedByDefault": False,
1550
"LastApprovalRequest": "2019-01-03T00:00:00",
1551
"ApprovalDelay": 30000,
1552
"ApprovalDuration": 93785000,
1554
"ExtendedTimeout": 900000,
1555
"Expires": "2019-02-05T00:00:00",
1556
"LastCheckerStatus": -2,
1560
def test_DumpJSON_normal(self):
1561
with self.capture_stdout_to_buffer() as buffer:
1562
command.DumpJSON().run(self.clients)
1563
json_data = json.loads(buffer.getvalue())
1564
self.assertDictEqual(self.expected_json, json_data)
1567
@contextlib.contextmanager
1568
def capture_stdout_to_buffer():
1569
capture_buffer = io.StringIO()
1570
old_stdout = sys.stdout
1571
sys.stdout = capture_buffer
1573
yield capture_buffer
1575
sys.stdout = old_stdout
1577
def test_DumpJSON_one_client(self):
1578
with self.capture_stdout_to_buffer() as buffer:
1579
command.DumpJSON().run(self.one_client)
1580
json_data = json.loads(buffer.getvalue())
1433
class TestDumpJSONCmd(TestCmd):
1435
self.expected_json = {
1438
"KeyID": ("92ed150794387c03ce684574b1139a65"
1439
"94a34f895daaaf09fd8ea90a27cddb12"),
1440
"Host": "foo.example.org",
1443
"LastCheckedOK": "2019-02-03T00:00:00",
1444
"Created": "2019-01-02T00:00:00",
1446
"Fingerprint": ("778827225BA7DE539C5A"
1447
"7CFA59CFF7CDBD9A5920"),
1448
"CheckerRunning": False,
1449
"LastEnabled": "2019-01-03T00:00:00",
1450
"ApprovalPending": False,
1451
"ApprovedByDefault": True,
1452
"LastApprovalRequest": "",
1454
"ApprovalDuration": 1000,
1455
"Checker": "fping -q -- %(host)s",
1456
"ExtendedTimeout": 900000,
1457
"Expires": "2019-02-04T00:00:00",
1458
"LastCheckerStatus": 0,
1462
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1463
"6ab612cff5ad227247e46c2b020f441c"),
1464
"Host": "192.0.2.3",
1467
"LastCheckedOK": "2019-02-04T00:00:00",
1468
"Created": "2019-01-03T00:00:00",
1470
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1471
"F547B3A107558FCA3A27"),
1472
"CheckerRunning": True,
1473
"LastEnabled": "2019-01-04T00:00:00",
1474
"ApprovalPending": False,
1475
"ApprovedByDefault": False,
1476
"LastApprovalRequest": "2019-01-03T00:00:00",
1477
"ApprovalDelay": 30000,
1478
"ApprovalDuration": 93785000,
1480
"ExtendedTimeout": 900000,
1481
"Expires": "2019-02-05T00:00:00",
1482
"LastCheckerStatus": -2,
1485
return super(TestDumpJSONCmd, self).setUp()
1487
def test_normal(self):
1488
output = DumpJSONCmd().output(self.clients.values())
1489
json_data = json.loads(output)
1490
self.assertDictEqual(json_data, self.expected_json)
1492
def test_one_client(self):
1493
output = DumpJSONCmd().output(self.one_client.values())
1494
json_data = json.loads(output)
1581
1495
expected_json = {"foo": self.expected_json["foo"]}
1582
self.assertDictEqual(expected_json, json_data)
1584
def test_PrintTable_normal(self):
1585
with self.capture_stdout_to_buffer() as buffer:
1586
command.PrintTable().run(self.clients)
1496
self.assertDictEqual(json_data, expected_json)
1499
class TestPrintTableCmd(TestCmd):
1500
def test_normal(self):
1501
output = PrintTableCmd().output(self.clients.values())
1587
1502
expected_output = "\n".join((
1588
1503
"Name Enabled Timeout Last Successful Check",
1589
1504
"foo Yes 00:05:00 2019-02-03T00:00:00 ",
1590
1505
"barbar Yes 00:05:00 2019-02-04T00:00:00 ",
1592
self.assertEqual(expected_output, buffer.getvalue())
1507
self.assertEqual(output, expected_output)
1594
def test_PrintTable_verbose(self):
1595
with self.capture_stdout_to_buffer() as buffer:
1596
command.PrintTable(verbose=True).run(self.clients)
1509
def test_verbose(self):
1510
output = PrintTableCmd(verbose=True).output(
1511
self.clients.values())
1725
1639
self.command().run(clients, self.bus)
1728
class TestEnableCmd(TestPropertySetterCmd):
1729
command = command.Enable
1642
class TestEnableCmd(TestPropertyCmd):
1730
1644
propname = "Enabled"
1731
1645
values_to_set = [dbus.Boolean(True)]
1734
class TestDisableCmd(TestPropertySetterCmd):
1735
command = command.Disable
1648
class TestDisableCmd(TestPropertyCmd):
1649
command = DisableCmd
1736
1650
propname = "Enabled"
1737
1651
values_to_set = [dbus.Boolean(False)]
1740
class TestBumpTimeoutCmd(TestPropertySetterCmd):
1741
command = command.BumpTimeout
1654
class TestBumpTimeoutCmd(TestPropertyCmd):
1655
command = BumpTimeoutCmd
1742
1656
propname = "LastCheckedOK"
1743
1657
values_to_set = [""]
1746
class TestStartCheckerCmd(TestPropertySetterCmd):
1747
command = command.StartChecker
1748
propname = "CheckerRunning"
1749
values_to_set = [dbus.Boolean(True)]
1752
class TestStopCheckerCmd(TestPropertySetterCmd):
1753
command = command.StopChecker
1754
propname = "CheckerRunning"
1755
values_to_set = [dbus.Boolean(False)]
1758
class TestApproveByDefaultCmd(TestPropertySetterCmd):
1759
command = command.ApproveByDefault
1760
propname = "ApprovedByDefault"
1761
values_to_set = [dbus.Boolean(True)]
1764
class TestDenyByDefaultCmd(TestPropertySetterCmd):
1765
command = command.DenyByDefault
1766
propname = "ApprovedByDefault"
1767
values_to_set = [dbus.Boolean(False)]
1770
class TestPropertySetterValueCmd(TestPropertySetterCmd):
1771
"""Abstract class for tests of PropertySetterValueCmd classes"""
1660
class TestStartCheckerCmd(TestPropertyCmd):
1661
command = StartCheckerCmd
1662
propname = "CheckerRunning"
1663
values_to_set = [dbus.Boolean(True)]
1666
class TestStopCheckerCmd(TestPropertyCmd):
1667
command = StopCheckerCmd
1668
propname = "CheckerRunning"
1669
values_to_set = [dbus.Boolean(False)]
1672
class TestApproveByDefaultCmd(TestPropertyCmd):
1673
command = ApproveByDefaultCmd
1674
propname = "ApprovedByDefault"
1675
values_to_set = [dbus.Boolean(True)]
1678
class TestDenyByDefaultCmd(TestPropertyCmd):
1679
command = DenyByDefaultCmd
1680
propname = "ApprovedByDefault"
1681
values_to_set = [dbus.Boolean(False)]
1684
class TestPropertyValueCmd(TestPropertyCmd):
1685
"""Abstract class for tests of PropertyValueCmd classes"""
1773
1687
def runTest(self):
1774
if type(self) is TestPropertySetterValueCmd:
1688
if type(self) is TestPropertyValueCmd:
1776
return super(TestPropertySetterValueCmd, self).runTest()
1690
return super(TestPropertyValueCmd, self).runTest()
1778
1692
def run_command(self, value, clients):
1779
1693
self.command(value).run(clients, self.bus)
1782
class TestSetCheckerCmd(TestPropertySetterValueCmd):
1783
command = command.SetChecker
1696
class TestSetCheckerCmd(TestPropertyValueCmd):
1697
command = SetCheckerCmd
1784
1698
propname = "Checker"
1785
1699
values_to_set = ["", ":", "fping -q -- %s"]
1788
class TestSetHostCmd(TestPropertySetterValueCmd):
1789
command = command.SetHost
1702
class TestSetHostCmd(TestPropertyValueCmd):
1703
command = SetHostCmd
1790
1704
propname = "Host"
1791
values_to_set = ["192.0.2.3", "client.example.org"]
1794
class TestSetSecretCmd(TestPropertySetterValueCmd):
1795
command = command.SetSecret
1705
values_to_set = ["192.0.2.3", "foo.example.org"]
1708
class TestSetSecretCmd(TestPropertyValueCmd):
1709
command = SetSecretCmd
1796
1710
propname = "Secret"
1797
1711
values_to_set = [io.BytesIO(b""),
1798
1712
io.BytesIO(b"secret\0xyzzy\nbar")]
1799
values_to_get = [f.getvalue() for f in values_to_set]
1802
class TestSetTimeoutCmd(TestPropertySetterValueCmd):
1803
command = command.SetTimeout
1713
values_to_get = [b"", b"secret\0xyzzy\nbar"]
1716
class TestSetTimeoutCmd(TestPropertyValueCmd):
1717
command = SetTimeoutCmd
1804
1718
propname = "Timeout"
1805
1719
values_to_set = [datetime.timedelta(),
1806
1720
datetime.timedelta(minutes=5),
1807
1721
datetime.timedelta(seconds=1),
1808
1722
datetime.timedelta(weeks=1),
1809
1723
datetime.timedelta(weeks=52)]
1810
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1813
class TestSetExtendedTimeoutCmd(TestPropertySetterValueCmd):
1814
command = command.SetExtendedTimeout
1724
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1727
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
1728
command = SetExtendedTimeoutCmd
1815
1729
propname = "ExtendedTimeout"
1816
1730
values_to_set = [datetime.timedelta(),
1817
1731
datetime.timedelta(minutes=5),
1818
1732
datetime.timedelta(seconds=1),
1819
1733
datetime.timedelta(weeks=1),
1820
1734
datetime.timedelta(weeks=52)]
1821
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1824
class TestSetIntervalCmd(TestPropertySetterValueCmd):
1825
command = command.SetInterval
1735
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1738
class TestSetIntervalCmd(TestPropertyValueCmd):
1739
command = SetIntervalCmd
1826
1740
propname = "Interval"
1827
1741
values_to_set = [datetime.timedelta(),
1828
1742
datetime.timedelta(minutes=5),
1829
1743
datetime.timedelta(seconds=1),
1830
1744
datetime.timedelta(weeks=1),
1831
1745
datetime.timedelta(weeks=52)]
1832
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1835
class TestSetApprovalDelayCmd(TestPropertySetterValueCmd):
1836
command = command.SetApprovalDelay
1746
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1749
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
1750
command = SetApprovalDelayCmd
1837
1751
propname = "ApprovalDelay"
1838
1752
values_to_set = [datetime.timedelta(),
1839
1753
datetime.timedelta(minutes=5),
1840
1754
datetime.timedelta(seconds=1),
1841
1755
datetime.timedelta(weeks=1),
1842
1756
datetime.timedelta(weeks=52)]
1843
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1846
class TestSetApprovalDurationCmd(TestPropertySetterValueCmd):
1847
command = command.SetApprovalDuration
1757
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1760
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
1761
command = SetApprovalDurationCmd
1848
1762
propname = "ApprovalDuration"
1849
1763
values_to_set = [datetime.timedelta(),
1850
1764
datetime.timedelta(minutes=5),
1851
1765
datetime.timedelta(seconds=1),
1852
1766
datetime.timedelta(weeks=1),
1853
1767
datetime.timedelta(weeks=52)]
1854
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1768
values_to_get = [0, 300000, 1000, 604800000, 31449600000]