478
476
if options.is_enabled:
479
commands.append(command.IsEnabled())
477
commands.append(IsEnabledCmd())
481
479
if options.approve:
482
commands.append(command.Approve())
480
commands.append(ApproveCmd())
485
commands.append(command.Deny())
483
commands.append(DenyCmd())
487
485
if options.remove:
488
commands.append(command.Remove())
486
commands.append(RemoveCmd())
490
488
if options.dump_json:
491
commands.append(command.DumpJSON())
489
commands.append(DumpJSONCmd())
493
491
if options.enable:
494
commands.append(command.Enable())
492
commands.append(EnableCmd())
496
494
if options.disable:
497
commands.append(command.Disable())
495
commands.append(DisableCmd())
499
497
if options.bump_timeout:
500
commands.append(command.BumpTimeout())
498
commands.append(BumpTimeoutCmd())
502
500
if options.start_checker:
503
commands.append(command.StartChecker())
501
commands.append(StartCheckerCmd())
505
503
if options.stop_checker:
506
commands.append(command.StopChecker())
504
commands.append(StopCheckerCmd())
508
506
if options.approved_by_default is not None:
509
507
if options.approved_by_default:
510
commands.append(command.ApproveByDefault())
508
commands.append(ApproveByDefaultCmd())
512
commands.append(command.DenyByDefault())
510
commands.append(DenyByDefaultCmd())
514
512
if options.checker is not None:
515
commands.append(command.SetChecker(options.checker))
513
commands.append(SetCheckerCmd(options.checker))
517
515
if options.host is not None:
518
commands.append(command.SetHost(options.host))
516
commands.append(SetHostCmd(options.host))
520
518
if options.secret is not None:
521
commands.append(command.SetSecret(options.secret))
519
commands.append(SetSecretCmd(options.secret))
523
521
if options.timeout is not None:
524
commands.append(command.SetTimeout(options.timeout))
522
commands.append(SetTimeoutCmd(options.timeout))
526
524
if options.extended_timeout:
528
command.SetExtendedTimeout(options.extended_timeout))
526
SetExtendedTimeoutCmd(options.extended_timeout))
530
528
if options.interval is not None:
531
commands.append(command.SetInterval(options.interval))
529
commands.append(SetIntervalCmd(options.interval))
533
531
if options.approval_delay is not None:
535
command.SetApprovalDelay(options.approval_delay))
532
commands.append(SetApprovalDelayCmd(options.approval_delay))
537
534
if options.approval_duration is not None:
539
command.SetApprovalDuration(options.approval_duration))
536
SetApprovalDurationCmd(options.approval_duration))
541
538
# If no command option has been given, show table of clients,
542
539
# optionally verbosely
544
commands.append(command.PrintTable(verbose=options.verbose))
541
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.
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)
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):
573
def is_enabled(self, client, properties):
574
return properties["Enabled"]
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)
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)
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__)
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",
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=(',', ': ')))
546
class Command(object):
547
"""Abstract class for commands"""
548
def run(self, clients, bus=None, mandos=None):
549
"""Normal commands should implement run_on_one_client(), but
550
commands which want to operate on all clients at the same time
551
can override this run() method instead."""
553
for clientpath, properties in clients.items():
554
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
555
dbus_busname, str(clientpath))
556
client = bus.get_object(dbus_busname, clientpath)
557
self.run_on_one_client(client, properties)
560
class IsEnabledCmd(Command):
561
def run(self, clients, bus=None, mandos=None):
562
client, properties = next(iter(clients.items()))
563
if self.is_enabled(client, properties):
566
def is_enabled(self, client, properties):
567
return properties["Enabled"]
570
class ApproveCmd(Command):
571
def run_on_one_client(self, client, properties):
572
log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
573
client.__dbus_object_path__, client_dbus_interface)
574
client.Approve(dbus.Boolean(True),
575
dbus_interface=client_dbus_interface)
578
class DenyCmd(Command):
579
def run_on_one_client(self, client, properties):
580
log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
581
client.__dbus_object_path__, client_dbus_interface)
582
client.Approve(dbus.Boolean(False),
583
dbus_interface=client_dbus_interface)
586
class RemoveCmd(Command):
587
def run_on_one_client(self, client, properties):
588
log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", dbus_busname,
589
server_dbus_path, server_dbus_interface,
590
str(client.__dbus_object_path__))
591
self.mandos.RemoveClient(client.__dbus_object_path__)
594
class OutputCmd(Command):
595
"""Abstract class for commands outputting client details"""
596
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
597
"Created", "Interval", "Host", "KeyID",
598
"Fingerprint", "CheckerRunning", "LastEnabled",
599
"ApprovalPending", "ApprovedByDefault",
600
"LastApprovalRequest", "ApprovalDelay",
601
"ApprovalDuration", "Checker", "ExtendedTimeout",
602
"Expires", "LastCheckerStatus")
604
def run(self, clients, bus=None, mandos=None):
605
print(self.output(clients.values()))
607
def output(self, clients):
608
raise NotImplementedError()
611
class DumpJSONCmd(OutputCmd):
612
def output(self, clients):
613
data = {client["Name"]:
614
{key: self.dbus_boolean_to_bool(client[key])
615
for key in self.all_keywords}
616
for client in clients}
617
return json.dumps(data, indent=4, separators=(',', ': '))
620
def dbus_boolean_to_bool(value):
621
if isinstance(value, dbus.Boolean):
626
class PrintTableCmd(OutputCmd):
627
def __init__(self, verbose=False):
628
self.verbose = verbose
630
def output(self, clients):
631
default_keywords = ("Name", "Enabled", "Timeout",
633
keywords = default_keywords
635
keywords = self.all_keywords
636
return str(self.TableOfClients(clients, keywords))
638
class TableOfClients(object):
641
"Enabled": "Enabled",
642
"Timeout": "Timeout",
643
"LastCheckedOK": "Last Successful Check",
644
"LastApprovalRequest": "Last Approval Request",
645
"Created": "Created",
646
"Interval": "Interval",
648
"Fingerprint": "Fingerprint",
650
"CheckerRunning": "Check Is Running",
651
"LastEnabled": "Last Enabled",
652
"ApprovalPending": "Approval Is Pending",
653
"ApprovedByDefault": "Approved By Default",
654
"ApprovalDelay": "Approval Delay",
655
"ApprovalDuration": "Approval Duration",
656
"Checker": "Checker",
657
"ExtendedTimeout": "Extended Timeout",
658
"Expires": "Expires",
659
"LastCheckerStatus": "Last Checker Status",
662
def __init__(self, clients, keywords):
663
self.clients = clients
664
self.keywords = keywords
667
return "\n".join(self.rows())
669
if sys.version_info.major == 2:
670
__unicode__ = __str__
672
return str(self).encode(locale.getpreferredencoding())
675
format_string = self.row_formatting_string()
676
rows = [self.header_line(format_string)]
677
rows.extend(self.client_line(client, format_string)
678
for client in self.clients)
681
def row_formatting_string(self):
682
"Format string used to format table rows"
683
return " ".join("{{{key}:{width}}}".format(
684
width=max(len(self.tableheaders[key]),
685
*(len(self.string_from_client(client, key))
686
for client in self.clients)),
688
for key in self.keywords)
690
def string_from_client(self, client, key):
691
return self.valuetostring(client[key], key)
694
def valuetostring(cls, value, keyword):
695
if isinstance(value, dbus.Boolean):
696
return "Yes" if value else "No"
697
if keyword in ("Timeout", "Interval", "ApprovalDelay",
698
"ApprovalDuration", "ExtendedTimeout"):
699
return cls.milliseconds_to_string(value)
702
def header_line(self, format_string):
703
return format_string.format(**self.tableheaders)
705
def client_line(self, client, format_string):
706
return format_string.format(
707
**{key: self.string_from_client(client, key)
708
for key in self.keywords})
625
def dbus_boolean_to_bool(value):
626
if isinstance(value, dbus.Boolean):
631
class PrintTable(Output):
632
def __init__(self, verbose=False):
633
self.verbose = verbose
635
def run(self, clients, bus=None, mandos=None):
636
default_keywords = ("Name", "Enabled", "Timeout",
638
keywords = default_keywords
640
keywords = self.all_keywords
641
print(self.TableOfClients(clients.values(), keywords))
643
class TableOfClients(object):
646
"Enabled": "Enabled",
647
"Timeout": "Timeout",
648
"LastCheckedOK": "Last Successful Check",
649
"LastApprovalRequest": "Last Approval Request",
650
"Created": "Created",
651
"Interval": "Interval",
653
"Fingerprint": "Fingerprint",
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",
667
def __init__(self, clients, keywords):
668
self.clients = clients
669
self.keywords = keywords
672
return "\n".join(self.rows())
674
if sys.version_info.major == 2:
675
__unicode__ = __str__
677
return str(self).encode(
678
locale.getpreferredencoding())
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)
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,
693
for client in self.clients)),
695
for key in self.keywords)
697
def string_from_client(self, client, key):
698
return self.valuetostring(client[key], key)
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)
709
def header_line(self, format_string):
710
return format_string.format(**self.tableheaders)
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})
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)
723
hours=td.seconds // 3600,
724
minutes=(td.seconds % 3600) // 60,
725
seconds=td.seconds % 60))
728
class PropertySetter(Base):
729
"Abstract class for Actions for setting one client property"
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,
739
else bool(self.value_to_set))
740
client.Set(client_dbus_interface, self.propname,
742
dbus_interface=dbus.PROPERTIES_IFACE)
746
raise NotImplementedError()
749
class Enable(PropertySetter):
751
value_to_set = dbus.Boolean(True)
754
class Disable(PropertySetter):
756
value_to_set = dbus.Boolean(False)
759
class BumpTimeout(PropertySetter):
760
propname = "LastCheckedOK"
764
class StartChecker(PropertySetter):
765
propname = "CheckerRunning"
766
value_to_set = dbus.Boolean(True)
769
class StopChecker(PropertySetter):
770
propname = "CheckerRunning"
771
value_to_set = dbus.Boolean(False)
774
class ApproveByDefault(PropertySetter):
775
propname = "ApprovedByDefault"
776
value_to_set = dbus.Boolean(True)
779
class DenyByDefault(PropertySetter):
780
propname = "ApprovedByDefault"
781
value_to_set = dbus.Boolean(False)
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
791
class SetChecker(PropertySetterValue):
795
class SetHost(PropertySetterValue):
799
class SetSecret(PropertySetterValue):
803
def value_to_set(self):
807
def value_to_set(self, value):
808
"""When setting, read data from supplied file object"""
809
self._vts = value.read()
813
class PropertySetterValueMilliseconds(PropertySetterValue):
814
"""Abstract class for PropertySetterValue taking a value
815
argument as a datetime.timedelta() but should store it as
819
def value_to_set(self):
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))
828
class SetTimeout(PropertySetterValueMilliseconds):
832
class SetExtendedTimeout(PropertySetterValueMilliseconds):
833
propname = "ExtendedTimeout"
836
class SetInterval(PropertySetterValueMilliseconds):
837
propname = "Interval"
840
class SetApprovalDelay(PropertySetterValueMilliseconds):
841
propname = "ApprovalDelay"
844
class SetApprovalDuration(PropertySetterValueMilliseconds):
845
propname = "ApprovalDuration"
711
def milliseconds_to_string(ms):
712
td = datetime.timedelta(0, 0, 0, ms)
713
return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
714
.format(days="{}T".format(td.days)
716
hours=td.seconds // 3600,
717
minutes=(td.seconds % 3600) // 60,
718
seconds=td.seconds % 60))
721
class PropertyCmd(Command):
722
"""Abstract class for Actions for setting one client property"""
724
def run_on_one_client(self, client, properties):
725
"""Set the Client's D-Bus property"""
726
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
727
client.__dbus_object_path__,
728
dbus.PROPERTIES_IFACE, client_dbus_interface,
729
self.propname, self.value_to_set
730
if not isinstance(self.value_to_set, dbus.Boolean)
731
else bool(self.value_to_set))
732
client.Set(client_dbus_interface, self.propname,
734
dbus_interface=dbus.PROPERTIES_IFACE)
738
raise NotImplementedError()
741
class EnableCmd(PropertyCmd):
743
value_to_set = dbus.Boolean(True)
746
class DisableCmd(PropertyCmd):
748
value_to_set = dbus.Boolean(False)
751
class BumpTimeoutCmd(PropertyCmd):
752
propname = "LastCheckedOK"
756
class StartCheckerCmd(PropertyCmd):
757
propname = "CheckerRunning"
758
value_to_set = dbus.Boolean(True)
761
class StopCheckerCmd(PropertyCmd):
762
propname = "CheckerRunning"
763
value_to_set = dbus.Boolean(False)
766
class ApproveByDefaultCmd(PropertyCmd):
767
propname = "ApprovedByDefault"
768
value_to_set = dbus.Boolean(True)
771
class DenyByDefaultCmd(PropertyCmd):
772
propname = "ApprovedByDefault"
773
value_to_set = dbus.Boolean(False)
776
class PropertyValueCmd(PropertyCmd):
777
"""Abstract class for PropertyCmd recieving a value as argument"""
778
def __init__(self, value):
779
self.value_to_set = value
782
class SetCheckerCmd(PropertyValueCmd):
786
class SetHostCmd(PropertyValueCmd):
790
class SetSecretCmd(PropertyValueCmd):
794
def value_to_set(self):
798
def value_to_set(self, value):
799
"""When setting, read data from supplied file object"""
800
self._vts = value.read()
804
class MillisecondsPropertyValueArgumentCmd(PropertyValueCmd):
805
"""Abstract class for PropertyValueCmd taking a value argument as
806
a datetime.timedelta() but should store it as milliseconds."""
809
def value_to_set(self):
813
def value_to_set(self, value):
814
"""When setting, convert value from a datetime.timedelta"""
815
self._vts = int(round(value.total_seconds() * 1000))
818
class SetTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
822
class SetExtendedTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
823
propname = "ExtendedTimeout"
826
class SetIntervalCmd(MillisecondsPropertyValueArgumentCmd):
827
propname = "Interval"
830
class SetApprovalDelayCmd(MillisecondsPropertyValueArgumentCmd):
831
propname = "ApprovalDelay"
834
class SetApprovalDurationCmd(MillisecondsPropertyValueArgumentCmd):
835
propname = "ApprovalDuration"
849
class TestCaseWithAssertLogs(unittest.TestCase):
850
"""unittest.TestCase.assertLogs only exists in Python 3.4"""
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
862
yield capturing_handler.watcher
864
logger.propagate = old_propagate
865
logger.removeHandler(capturing_handler)
866
logger.setLevel(old_level)
867
self.assertGreater(len(capturing_handler.watcher.records),
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))
878
LoggingWatcher = collections.namedtuple("LoggingWatcher",
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.
888
def test_rfc3339_zero_seconds(self):
889
self.assertEqual(datetime.timedelta(),
890
string_to_delta("PT0S"))
892
def test_rfc3339_zero_days(self):
893
self.assertEqual(datetime.timedelta(), string_to_delta("P0D"))
895
def test_rfc3339_one_second(self):
896
self.assertEqual(datetime.timedelta(0, 1),
897
string_to_delta("PT1S"))
899
def test_rfc3339_two_hours(self):
900
self.assertEqual(datetime.timedelta(0, 7200),
901
string_to_delta("PT2H"))
839
class Test_string_to_delta(unittest.TestCase):
840
def test_handles_basic_rfc3339(self):
841
self.assertEqual(string_to_delta("PT0S"),
842
datetime.timedelta())
843
self.assertEqual(string_to_delta("P0D"),
844
datetime.timedelta())
845
self.assertEqual(string_to_delta("PT1S"),
846
datetime.timedelta(0, 1))
847
self.assertEqual(string_to_delta("PT2H"),
848
datetime.timedelta(0, 7200))
903
850
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)
851
# assertLogs only exists in Python 3.4
852
if hasattr(self, "assertLogs"):
853
with self.assertLogs(log, logging.WARNING):
854
value = string_to_delta("2h")
856
class WarningFilter(logging.Filter):
857
"""Don't show, but record the presence of, warnings"""
858
def filter(self, record):
859
is_warning = record.levelno >= logging.WARNING
860
self.found = is_warning or getattr(self, "found",
862
return not is_warning
863
warning_filter = WarningFilter()
864
log.addFilter(warning_filter)
866
value = string_to_delta("2h")
868
log.removeFilter(warning_filter)
869
self.assertTrue(getattr(warning_filter, "found", False))
870
self.assertEqual(value, datetime.timedelta(0, 7200))
909
873
class Test_check_option_syntax(unittest.TestCase):
1166
1138
options = self.parser.parse_args(args)
1167
1139
check_option_syntax(self.parser, options)
1168
1140
commands = commands_from_options(options)
1169
self.assertEqual(1, len(commands))
1141
self.assertEqual(len(commands), 1)
1170
1142
command = commands[0]
1171
1143
self.assertIsInstance(command, command_cls)
1172
1144
for key, value in cmd_attrs.items():
1173
self.assertEqual(value, getattr(command, key))
1145
self.assertEqual(getattr(command, key), value)
1175
1147
def test_is_enabled_short(self):
1176
self.assert_command_from_args(["-V", "client"],
1148
self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1179
1150
def test_approve(self):
1180
self.assert_command_from_args(["--approve", "client"],
1151
self.assert_command_from_args(["--approve", "foo"],
1183
1154
def test_approve_short(self):
1184
self.assert_command_from_args(["-A", "client"],
1155
self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1187
1157
def test_deny(self):
1188
self.assert_command_from_args(["--deny", "client"],
1158
self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1191
1160
def test_deny_short(self):
1192
self.assert_command_from_args(["-D", "client"], command.Deny)
1161
self.assert_command_from_args(["-D", "foo"], DenyCmd)
1194
1163
def test_remove(self):
1195
self.assert_command_from_args(["--remove", "client"],
1164
self.assert_command_from_args(["--remove", "foo"],
1198
1167
def test_deny_before_remove(self):
1199
1168
options = self.parser.parse_args(["--deny", "--remove",
1201
1170
check_option_syntax(self.parser, options)
1202
1171
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)
1172
self.assertEqual(len(commands), 2)
1173
self.assertIsInstance(commands[0], DenyCmd)
1174
self.assertIsInstance(commands[1], RemoveCmd)
1207
1176
def test_deny_before_remove_reversed(self):
1208
1177
options = self.parser.parse_args(["--remove", "--deny",
1210
1179
check_option_syntax(self.parser, options)
1211
1180
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)
1181
self.assertEqual(len(commands), 2)
1182
self.assertIsInstance(commands[0], DenyCmd)
1183
self.assertIsInstance(commands[1], RemoveCmd)
1216
1185
def test_remove_short(self):
1217
self.assert_command_from_args(["-r", "client"],
1186
self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1220
1188
def test_dump_json(self):
1221
self.assert_command_from_args(["--dump-json"],
1189
self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1224
1191
def test_enable(self):
1225
self.assert_command_from_args(["--enable", "client"],
1192
self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1228
1194
def test_enable_short(self):
1229
self.assert_command_from_args(["-e", "client"],
1195
self.assert_command_from_args(["-e", "foo"], EnableCmd)
1232
1197
def test_disable(self):
1233
self.assert_command_from_args(["--disable", "client"],
1198
self.assert_command_from_args(["--disable", "foo"],
1236
1201
def test_disable_short(self):
1237
self.assert_command_from_args(["-d", "client"],
1202
self.assert_command_from_args(["-d", "foo"], DisableCmd)
1240
1204
def test_bump_timeout(self):
1241
self.assert_command_from_args(["--bump-timeout", "client"],
1242
command.BumpTimeout)
1205
self.assert_command_from_args(["--bump-timeout", "foo"],
1244
1208
def test_bump_timeout_short(self):
1245
self.assert_command_from_args(["-b", "client"],
1246
command.BumpTimeout)
1209
self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1248
1211
def test_start_checker(self):
1249
self.assert_command_from_args(["--start-checker", "client"],
1250
command.StartChecker)
1212
self.assert_command_from_args(["--start-checker", "foo"],
1252
1215
def test_stop_checker(self):
1253
self.assert_command_from_args(["--stop-checker", "client"],
1254
command.StopChecker)
1216
self.assert_command_from_args(["--stop-checker", "foo"],
1256
1219
def test_approve_by_default(self):
1257
self.assert_command_from_args(["--approve-by-default",
1259
command.ApproveByDefault)
1220
self.assert_command_from_args(["--approve-by-default", "foo"],
1221
ApproveByDefaultCmd)
1261
1223
def test_deny_by_default(self):
1262
self.assert_command_from_args(["--deny-by-default", "client"],
1263
command.DenyByDefault)
1224
self.assert_command_from_args(["--deny-by-default", "foo"],
1265
1227
def test_checker(self):
1266
self.assert_command_from_args(["--checker", ":", "client"],
1228
self.assert_command_from_args(["--checker", ":", "foo"],
1229
SetCheckerCmd, value_to_set=":")
1270
1231
def test_checker_empty(self):
1271
self.assert_command_from_args(["--checker", "", "client"],
1232
self.assert_command_from_args(["--checker", "", "foo"],
1233
SetCheckerCmd, value_to_set="")
1275
1235
def test_checker_short(self):
1276
self.assert_command_from_args(["-c", ":", "client"],
1236
self.assert_command_from_args(["-c", ":", "foo"],
1237
SetCheckerCmd, value_to_set=":")
1280
1239
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")
1240
self.assert_command_from_args(["--host", "foo.example.org",
1242
value_to_set="foo.example.org")
1285
1244
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")
1245
self.assert_command_from_args(["-H", "foo.example.org",
1247
value_to_set="foo.example.org")
1290
1249
def test_secret_devnull(self):
1291
1250
self.assert_command_from_args(["--secret", os.path.devnull,
1292
"client"], command.SetSecret,
1251
"foo"], SetSecretCmd,
1293
1252
value_to_set=b"")
1295
1254
def test_secret_tempfile(self):
1439
1398
LastCheckerStatus=-2)
1440
1399
self.clients = collections.OrderedDict(
1442
(self.client.__dbus_object_path__,
1443
self.client.attributes),
1444
(self.other_client.__dbus_object_path__,
1445
self.other_client.attributes),
1401
("/clients/foo", self.client.attributes),
1402
("/clients/barbar", self.other_client.attributes),
1447
self.one_client = {self.client.__dbus_object_path__:
1448
self.client.attributes}
1404
self.one_client = {"/clients/foo": self.client.attributes}
1452
class MockBus(object):
1454
1410
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__:
1460
elif path == self.other_client.__dbus_object_path__:
1461
return self.other_client
1465
class TestBaseCommands(TestCommand):
1467
def test_IsEnabled_exits_successfully(self):
1411
self.assertEqual(client_bus_name, dbus_busname)
1413
# Note: "self" here is the TestCmd instance, not
1414
# the Bus instance, since this is a static method!
1415
"/clients/foo": self.client,
1416
"/clients/barbar": self.other_client,
1421
class TestIsEnabledCmd(TestCmd):
1422
def test_is_enabled(self):
1423
self.assertTrue(all(IsEnabledCmd().is_enabled(client,
1425
for client, properties
1426
in self.clients.items()))
1428
def test_is_enabled_run_exits_successfully(self):
1468
1429
with self.assertRaises(SystemExit) as e:
1469
command.IsEnabled().run(self.one_client)
1430
IsEnabledCmd().run(self.one_client)
1470
1431
if e.exception.code is not None:
1471
self.assertEqual(0, e.exception.code)
1432
self.assertEqual(e.exception.code, 0)
1473
1434
self.assertIsNone(e.exception.code)
1475
def test_IsEnabled_exits_with_failure(self):
1436
def test_is_enabled_run_exits_with_failure(self):
1476
1437
self.client.attributes["Enabled"] = dbus.Boolean(False)
1477
1438
with self.assertRaises(SystemExit) as e:
1478
command.IsEnabled().run(self.one_client)
1439
IsEnabledCmd().run(self.one_client)
1479
1440
if isinstance(e.exception.code, int):
1480
self.assertNotEqual(0, e.exception.code)
1441
self.assertNotEqual(e.exception.code, 0)
1482
1443
self.assertIsNotNone(e.exception.code)
1484
def test_Approve(self):
1485
command.Approve().run(self.clients, self.bus)
1446
class TestApproveCmd(TestCmd):
1447
def test_approve(self):
1448
ApproveCmd().run(self.clients, self.bus)
1486
1449
for clientpath in self.clients:
1487
1450
client = self.bus.get_object(dbus_busname, clientpath)
1488
1451
self.assertIn(("Approve", (True, client_dbus_interface)),
1491
def test_Deny(self):
1492
command.Deny().run(self.clients, self.bus)
1455
class TestDenyCmd(TestCmd):
1456
def test_deny(self):
1457
DenyCmd().run(self.clients, self.bus)
1493
1458
for clientpath in self.clients:
1494
1459
client = self.bus.get_object(dbus_busname, clientpath)
1495
1460
self.assertIn(("Approve", (False, client_dbus_interface)),
1498
def test_Remove(self):
1499
class MandosSpy(object):
1464
class TestRemoveCmd(TestCmd):
1465
def test_remove(self):
1466
class MockMandos(object):
1500
1467
def __init__(self):
1501
1468
self.calls = []
1502
1469
def RemoveClient(self, dbus_path):
1503
1470
self.calls.append(("RemoveClient", (dbus_path,)))
1504
mandos = MandosSpy()
1505
command.Remove().run(self.clients, self.bus, mandos)
1471
mandos = MockMandos()
1472
super(TestRemoveCmd, self).setUp()
1473
RemoveCmd().run(self.clients, self.bus, mandos)
1474
self.assertEqual(len(mandos.calls), 2)
1506
1475
for clientpath in self.clients:
1507
1476
self.assertIn(("RemoveClient", (clientpath,)),
1513
"KeyID": ("92ed150794387c03ce684574b1139a65"
1514
"94a34f895daaaf09fd8ea90a27cddb12"),
1515
"Host": "foo.example.org",
1518
"LastCheckedOK": "2019-02-03T00:00:00",
1519
"Created": "2019-01-02T00:00:00",
1521
"Fingerprint": ("778827225BA7DE539C5A"
1522
"7CFA59CFF7CDBD9A5920"),
1523
"CheckerRunning": False,
1524
"LastEnabled": "2019-01-03T00:00:00",
1525
"ApprovalPending": False,
1526
"ApprovedByDefault": True,
1527
"LastApprovalRequest": "",
1529
"ApprovalDuration": 1000,
1530
"Checker": "fping -q -- %(host)s",
1531
"ExtendedTimeout": 900000,
1532
"Expires": "2019-02-04T00:00:00",
1533
"LastCheckerStatus": 0,
1537
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1538
"6ab612cff5ad227247e46c2b020f441c"),
1539
"Host": "192.0.2.3",
1542
"LastCheckedOK": "2019-02-04T00:00:00",
1543
"Created": "2019-01-03T00:00:00",
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,
1555
"ExtendedTimeout": 900000,
1556
"Expires": "2019-02-05T00:00:00",
1557
"LastCheckerStatus": -2,
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)
1568
@contextlib.contextmanager
1569
def capture_stdout_to_buffer():
1570
capture_buffer = io.StringIO()
1571
old_stdout = sys.stdout
1572
sys.stdout = capture_buffer
1574
yield capture_buffer
1576
sys.stdout = old_stdout
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())
1480
class TestDumpJSONCmd(TestCmd):
1482
self.expected_json = {
1485
"KeyID": ("92ed150794387c03ce684574b1139a65"
1486
"94a34f895daaaf09fd8ea90a27cddb12"),
1487
"Host": "foo.example.org",
1490
"LastCheckedOK": "2019-02-03T00:00:00",
1491
"Created": "2019-01-02T00:00:00",
1493
"Fingerprint": ("778827225BA7DE539C5A"
1494
"7CFA59CFF7CDBD9A5920"),
1495
"CheckerRunning": False,
1496
"LastEnabled": "2019-01-03T00:00:00",
1497
"ApprovalPending": False,
1498
"ApprovedByDefault": True,
1499
"LastApprovalRequest": "",
1501
"ApprovalDuration": 1000,
1502
"Checker": "fping -q -- %(host)s",
1503
"ExtendedTimeout": 900000,
1504
"Expires": "2019-02-04T00:00:00",
1505
"LastCheckerStatus": 0,
1509
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1510
"6ab612cff5ad227247e46c2b020f441c"),
1511
"Host": "192.0.2.3",
1514
"LastCheckedOK": "2019-02-04T00:00:00",
1515
"Created": "2019-01-03T00:00:00",
1517
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1518
"F547B3A107558FCA3A27"),
1519
"CheckerRunning": True,
1520
"LastEnabled": "2019-01-04T00:00:00",
1521
"ApprovalPending": False,
1522
"ApprovedByDefault": False,
1523
"LastApprovalRequest": "2019-01-03T00:00:00",
1524
"ApprovalDelay": 30000,
1525
"ApprovalDuration": 93785000,
1527
"ExtendedTimeout": 900000,
1528
"Expires": "2019-02-05T00:00:00",
1529
"LastCheckerStatus": -2,
1532
return super(TestDumpJSONCmd, self).setUp()
1534
def test_normal(self):
1535
output = DumpJSONCmd().output(self.clients.values())
1536
json_data = json.loads(output)
1537
self.assertDictEqual(json_data, self.expected_json)
1539
def test_one_client(self):
1540
output = DumpJSONCmd().output(self.one_client.values())
1541
json_data = json.loads(output)
1582
1542
expected_json = {"foo": self.expected_json["foo"]}
1583
self.assertDictEqual(expected_json, json_data)
1585
def test_PrintTable_normal(self):
1586
with self.capture_stdout_to_buffer() as buffer:
1587
command.PrintTable().run(self.clients)
1543
self.assertDictEqual(json_data, expected_json)
1546
class TestPrintTableCmd(TestCmd):
1547
def test_normal(self):
1548
output = PrintTableCmd().output(self.clients.values())
1588
1549
expected_output = "\n".join((
1589
1550
"Name Enabled Timeout Last Successful Check",
1590
1551
"foo Yes 00:05:00 2019-02-03T00:00:00 ",
1591
1552
"barbar Yes 00:05:00 2019-02-04T00:00:00 ",
1593
self.assertEqual(expected_output, buffer.getvalue())
1554
self.assertEqual(output, expected_output)
1595
def test_PrintTable_verbose(self):
1596
with self.capture_stdout_to_buffer() as buffer:
1597
command.PrintTable(verbose=True).run(self.clients)
1556
def test_verbose(self):
1557
output = PrintTableCmd(verbose=True).output(
1558
self.clients.values())
1726
1686
self.command().run(clients, self.bus)
1729
class TestEnableCmd(TestPropertySetterCmd):
1730
command = command.Enable
1689
class TestEnableCmd(TestPropertyCmd):
1731
1691
propname = "Enabled"
1732
1692
values_to_set = [dbus.Boolean(True)]
1735
class TestDisableCmd(TestPropertySetterCmd):
1736
command = command.Disable
1695
class TestDisableCmd(TestPropertyCmd):
1696
command = DisableCmd
1737
1697
propname = "Enabled"
1738
1698
values_to_set = [dbus.Boolean(False)]
1741
class TestBumpTimeoutCmd(TestPropertySetterCmd):
1742
command = command.BumpTimeout
1701
class TestBumpTimeoutCmd(TestPropertyCmd):
1702
command = BumpTimeoutCmd
1743
1703
propname = "LastCheckedOK"
1744
1704
values_to_set = [""]
1747
class TestStartCheckerCmd(TestPropertySetterCmd):
1748
command = command.StartChecker
1749
propname = "CheckerRunning"
1750
values_to_set = [dbus.Boolean(True)]
1753
class TestStopCheckerCmd(TestPropertySetterCmd):
1754
command = command.StopChecker
1755
propname = "CheckerRunning"
1756
values_to_set = [dbus.Boolean(False)]
1759
class TestApproveByDefaultCmd(TestPropertySetterCmd):
1760
command = command.ApproveByDefault
1761
propname = "ApprovedByDefault"
1762
values_to_set = [dbus.Boolean(True)]
1765
class TestDenyByDefaultCmd(TestPropertySetterCmd):
1766
command = command.DenyByDefault
1767
propname = "ApprovedByDefault"
1768
values_to_set = [dbus.Boolean(False)]
1771
class TestPropertySetterValueCmd(TestPropertySetterCmd):
1772
"""Abstract class for tests of PropertySetterValueCmd classes"""
1707
class TestStartCheckerCmd(TestPropertyCmd):
1708
command = StartCheckerCmd
1709
propname = "CheckerRunning"
1710
values_to_set = [dbus.Boolean(True)]
1713
class TestStopCheckerCmd(TestPropertyCmd):
1714
command = StopCheckerCmd
1715
propname = "CheckerRunning"
1716
values_to_set = [dbus.Boolean(False)]
1719
class TestApproveByDefaultCmd(TestPropertyCmd):
1720
command = ApproveByDefaultCmd
1721
propname = "ApprovedByDefault"
1722
values_to_set = [dbus.Boolean(True)]
1725
class TestDenyByDefaultCmd(TestPropertyCmd):
1726
command = DenyByDefaultCmd
1727
propname = "ApprovedByDefault"
1728
values_to_set = [dbus.Boolean(False)]
1731
class TestPropertyValueCmd(TestPropertyCmd):
1732
"""Abstract class for tests of PropertyValueCmd classes"""
1774
1734
def runTest(self):
1775
if type(self) is TestPropertySetterValueCmd:
1735
if type(self) is TestPropertyValueCmd:
1777
return super(TestPropertySetterValueCmd, self).runTest()
1737
return super(TestPropertyValueCmd, self).runTest()
1779
1739
def run_command(self, value, clients):
1780
1740
self.command(value).run(clients, self.bus)
1783
class TestSetCheckerCmd(TestPropertySetterValueCmd):
1784
command = command.SetChecker
1743
class TestSetCheckerCmd(TestPropertyValueCmd):
1744
command = SetCheckerCmd
1785
1745
propname = "Checker"
1786
1746
values_to_set = ["", ":", "fping -q -- %s"]
1789
class TestSetHostCmd(TestPropertySetterValueCmd):
1790
command = command.SetHost
1749
class TestSetHostCmd(TestPropertyValueCmd):
1750
command = SetHostCmd
1791
1751
propname = "Host"
1792
values_to_set = ["192.0.2.3", "client.example.org"]
1795
class TestSetSecretCmd(TestPropertySetterValueCmd):
1796
command = command.SetSecret
1752
values_to_set = ["192.0.2.3", "foo.example.org"]
1755
class TestSetSecretCmd(TestPropertyValueCmd):
1756
command = SetSecretCmd
1797
1757
propname = "Secret"
1798
1758
values_to_set = [io.BytesIO(b""),
1799
1759
io.BytesIO(b"secret\0xyzzy\nbar")]
1800
values_to_get = [f.getvalue() for f in values_to_set]
1803
class TestSetTimeoutCmd(TestPropertySetterValueCmd):
1804
command = command.SetTimeout
1760
values_to_get = [b"", b"secret\0xyzzy\nbar"]
1763
class TestSetTimeoutCmd(TestPropertyValueCmd):
1764
command = SetTimeoutCmd
1805
1765
propname = "Timeout"
1806
1766
values_to_set = [datetime.timedelta(),
1807
1767
datetime.timedelta(minutes=5),
1808
1768
datetime.timedelta(seconds=1),
1809
1769
datetime.timedelta(weeks=1),
1810
1770
datetime.timedelta(weeks=52)]
1811
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1814
class TestSetExtendedTimeoutCmd(TestPropertySetterValueCmd):
1815
command = command.SetExtendedTimeout
1771
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1774
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
1775
command = SetExtendedTimeoutCmd
1816
1776
propname = "ExtendedTimeout"
1817
1777
values_to_set = [datetime.timedelta(),
1818
1778
datetime.timedelta(minutes=5),
1819
1779
datetime.timedelta(seconds=1),
1820
1780
datetime.timedelta(weeks=1),
1821
1781
datetime.timedelta(weeks=52)]
1822
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1825
class TestSetIntervalCmd(TestPropertySetterValueCmd):
1826
command = command.SetInterval
1782
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1785
class TestSetIntervalCmd(TestPropertyValueCmd):
1786
command = SetIntervalCmd
1827
1787
propname = "Interval"
1828
1788
values_to_set = [datetime.timedelta(),
1829
1789
datetime.timedelta(minutes=5),
1830
1790
datetime.timedelta(seconds=1),
1831
1791
datetime.timedelta(weeks=1),
1832
1792
datetime.timedelta(weeks=52)]
1833
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1836
class TestSetApprovalDelayCmd(TestPropertySetterValueCmd):
1837
command = command.SetApprovalDelay
1793
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1796
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
1797
command = SetApprovalDelayCmd
1838
1798
propname = "ApprovalDelay"
1839
1799
values_to_set = [datetime.timedelta(),
1840
1800
datetime.timedelta(minutes=5),
1841
1801
datetime.timedelta(seconds=1),
1842
1802
datetime.timedelta(weeks=1),
1843
1803
datetime.timedelta(weeks=52)]
1844
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1847
class TestSetApprovalDurationCmd(TestPropertySetterValueCmd):
1848
command = command.SetApprovalDuration
1804
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1807
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
1808
command = SetApprovalDurationCmd
1849
1809
propname = "ApprovalDuration"
1850
1810
values_to_set = [datetime.timedelta(),
1851
1811
datetime.timedelta(minutes=5),
1852
1812
datetime.timedelta(seconds=1),
1853
1813
datetime.timedelta(weeks=1),
1854
1814
datetime.timedelta(weeks=52)]
1855
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1815
values_to_get = [0, 300000, 1000, 604800000, 31449600000]