478
479
if options.is_enabled:
479
commands.append(command.IsEnabled())
480
commands.append(IsEnabledCmd())
481
482
if options.approve:
482
commands.append(command.Approve())
483
commands.append(ApproveCmd())
485
commands.append(command.Deny())
486
commands.append(DenyCmd())
487
488
if options.remove:
488
commands.append(command.Remove())
489
commands.append(RemoveCmd())
490
491
if options.dump_json:
491
commands.append(command.DumpJSON())
492
commands.append(DumpJSONCmd())
493
494
if options.enable:
494
commands.append(command.Enable())
495
commands.append(EnableCmd())
496
497
if options.disable:
497
commands.append(command.Disable())
498
commands.append(DisableCmd())
499
500
if options.bump_timeout:
500
commands.append(command.BumpTimeout())
501
commands.append(BumpTimeoutCmd())
502
503
if options.start_checker:
503
commands.append(command.StartChecker())
504
commands.append(StartCheckerCmd())
505
506
if options.stop_checker:
506
commands.append(command.StopChecker())
507
commands.append(StopCheckerCmd())
508
509
if options.approved_by_default is not None:
509
510
if options.approved_by_default:
510
commands.append(command.ApproveByDefault())
511
commands.append(ApproveByDefaultCmd())
512
commands.append(command.DenyByDefault())
513
commands.append(DenyByDefaultCmd())
514
515
if options.checker is not None:
515
commands.append(command.SetChecker(options.checker))
516
commands.append(SetCheckerCmd(options.checker))
517
518
if options.host is not None:
518
commands.append(command.SetHost(options.host))
519
commands.append(SetHostCmd(options.host))
520
521
if options.secret is not None:
521
commands.append(command.SetSecret(options.secret))
522
commands.append(SetSecretCmd(options.secret))
523
524
if options.timeout is not None:
524
commands.append(command.SetTimeout(options.timeout))
525
commands.append(SetTimeoutCmd(options.timeout))
526
527
if options.extended_timeout:
528
command.SetExtendedTimeout(options.extended_timeout))
529
SetExtendedTimeoutCmd(options.extended_timeout))
530
531
if options.interval is not None:
531
commands.append(command.SetInterval(options.interval))
532
commands.append(SetIntervalCmd(options.interval))
533
534
if options.approval_delay is not None:
535
command.SetApprovalDelay(options.approval_delay))
535
commands.append(SetApprovalDelayCmd(options.approval_delay))
537
537
if options.approval_duration is not None:
539
command.SetApprovalDuration(options.approval_duration))
539
SetApprovalDurationCmd(options.approval_duration))
541
541
# If no command option has been given, show table of clients,
542
542
# optionally verbosely
544
commands.append(command.PrintTable(verbose=options.verbose))
544
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=(',', ': ')))
549
class Command(object):
550
"""Abstract class for commands"""
551
def run(self, clients, bus=None, mandos=None):
552
"""Normal commands should implement run_on_one_client(), but
553
commands which want to operate on all clients at the same time
554
can override this run() method instead."""
556
for clientpath, properties in clients.items():
557
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
558
dbus_busname, str(clientpath))
559
client = bus.get_object(dbus_busname, clientpath)
560
self.run_on_one_client(client, properties)
563
class IsEnabledCmd(Command):
564
def run(self, clients, bus=None, mandos=None):
565
client, properties = next(iter(clients.items()))
566
if self.is_enabled(client, properties):
569
def is_enabled(self, client, properties):
570
return properties["Enabled"]
573
class ApproveCmd(Command):
574
def run_on_one_client(self, client, properties):
575
log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
576
client.__dbus_object_path__, client_dbus_interface)
577
client.Approve(dbus.Boolean(True),
578
dbus_interface=client_dbus_interface)
581
class DenyCmd(Command):
582
def run_on_one_client(self, client, properties):
583
log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
584
client.__dbus_object_path__, client_dbus_interface)
585
client.Approve(dbus.Boolean(False),
586
dbus_interface=client_dbus_interface)
589
class RemoveCmd(Command):
590
def run_on_one_client(self, client, properties):
591
log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", dbus_busname,
592
server_dbus_path, server_dbus_interface,
593
str(client.__dbus_object_path__))
594
self.mandos.RemoveClient(client.__dbus_object_path__)
597
class OutputCmd(Command):
598
"""Abstract class for commands outputting client details"""
599
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
600
"Created", "Interval", "Host", "KeyID",
601
"Fingerprint", "CheckerRunning", "LastEnabled",
602
"ApprovalPending", "ApprovedByDefault",
603
"LastApprovalRequest", "ApprovalDelay",
604
"ApprovalDuration", "Checker", "ExtendedTimeout",
605
"Expires", "LastCheckerStatus")
607
def run(self, clients, bus=None, mandos=None):
608
print(self.output(clients.values()))
610
def output(self, clients):
611
raise NotImplementedError()
614
class DumpJSONCmd(OutputCmd):
615
def output(self, clients):
616
data = {client["Name"]:
617
{key: self.dbus_boolean_to_bool(client[key])
618
for key in self.all_keywords}
619
for client in clients}
620
return json.dumps(data, indent=4, separators=(',', ': '))
623
def dbus_boolean_to_bool(value):
624
if isinstance(value, dbus.Boolean):
629
class PrintTableCmd(OutputCmd):
630
def __init__(self, verbose=False):
631
self.verbose = verbose
633
def output(self, clients):
634
default_keywords = ("Name", "Enabled", "Timeout",
636
keywords = default_keywords
638
keywords = self.all_keywords
639
return str(self.TableOfClients(clients, keywords))
641
class TableOfClients(object):
644
"Enabled": "Enabled",
645
"Timeout": "Timeout",
646
"LastCheckedOK": "Last Successful Check",
647
"LastApprovalRequest": "Last Approval Request",
648
"Created": "Created",
649
"Interval": "Interval",
651
"Fingerprint": "Fingerprint",
653
"CheckerRunning": "Check Is Running",
654
"LastEnabled": "Last Enabled",
655
"ApprovalPending": "Approval Is Pending",
656
"ApprovedByDefault": "Approved By Default",
657
"ApprovalDelay": "Approval Delay",
658
"ApprovalDuration": "Approval Duration",
659
"Checker": "Checker",
660
"ExtendedTimeout": "Extended Timeout",
661
"Expires": "Expires",
662
"LastCheckerStatus": "Last Checker Status",
665
def __init__(self, clients, keywords):
666
self.clients = clients
667
self.keywords = keywords
670
return "\n".join(self.rows())
672
if sys.version_info.major == 2:
673
__unicode__ = __str__
675
return str(self).encode(locale.getpreferredencoding())
678
format_string = self.row_formatting_string()
679
rows = [self.header_line(format_string)]
680
rows.extend(self.client_line(client, format_string)
681
for client in self.clients)
684
def row_formatting_string(self):
685
"Format string used to format table rows"
686
return " ".join("{{{key}:{width}}}".format(
687
width=max(len(self.tableheaders[key]),
688
*(len(self.string_from_client(client, key))
689
for client in self.clients)),
691
for key in self.keywords)
693
def string_from_client(self, client, key):
694
return self.valuetostring(client[key], key)
697
def valuetostring(cls, value, keyword):
698
if isinstance(value, dbus.Boolean):
699
return "Yes" if value else "No"
700
if keyword in ("Timeout", "Interval", "ApprovalDelay",
701
"ApprovalDuration", "ExtendedTimeout"):
702
return cls.milliseconds_to_string(value)
705
def header_line(self, format_string):
706
return format_string.format(**self.tableheaders)
708
def client_line(self, client, format_string):
709
return format_string.format(
710
**{key: self.string_from_client(client, key)
711
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"
714
def milliseconds_to_string(ms):
715
td = datetime.timedelta(0, 0, 0, ms)
716
return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
717
.format(days="{}T".format(td.days)
719
hours=td.seconds // 3600,
720
minutes=(td.seconds % 3600) // 60,
721
seconds=td.seconds % 60))
724
class PropertyCmd(Command):
725
"""Abstract class for Actions for setting one client property"""
727
def run_on_one_client(self, client, properties):
728
"""Set the Client's D-Bus property"""
729
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
730
client.__dbus_object_path__,
731
dbus.PROPERTIES_IFACE, client_dbus_interface,
732
self.propname, self.value_to_set
733
if not isinstance(self.value_to_set, dbus.Boolean)
734
else bool(self.value_to_set))
735
client.Set(client_dbus_interface, self.propname,
737
dbus_interface=dbus.PROPERTIES_IFACE)
741
raise NotImplementedError()
744
class EnableCmd(PropertyCmd):
746
value_to_set = dbus.Boolean(True)
749
class DisableCmd(PropertyCmd):
751
value_to_set = dbus.Boolean(False)
754
class BumpTimeoutCmd(PropertyCmd):
755
propname = "LastCheckedOK"
759
class StartCheckerCmd(PropertyCmd):
760
propname = "CheckerRunning"
761
value_to_set = dbus.Boolean(True)
764
class StopCheckerCmd(PropertyCmd):
765
propname = "CheckerRunning"
766
value_to_set = dbus.Boolean(False)
769
class ApproveByDefaultCmd(PropertyCmd):
770
propname = "ApprovedByDefault"
771
value_to_set = dbus.Boolean(True)
774
class DenyByDefaultCmd(PropertyCmd):
775
propname = "ApprovedByDefault"
776
value_to_set = dbus.Boolean(False)
779
class PropertyValueCmd(PropertyCmd):
780
"""Abstract class for PropertyCmd recieving a value as argument"""
781
def __init__(self, value):
782
self.value_to_set = value
785
class SetCheckerCmd(PropertyValueCmd):
789
class SetHostCmd(PropertyValueCmd):
793
class SetSecretCmd(PropertyValueCmd):
797
def value_to_set(self):
801
def value_to_set(self, value):
802
"""When setting, read data from supplied file object"""
803
self._vts = value.read()
807
class MillisecondsPropertyValueArgumentCmd(PropertyValueCmd):
808
"""Abstract class for PropertyValueCmd taking a value argument as
809
a datetime.timedelta() but should store it as milliseconds."""
812
def value_to_set(self):
816
def value_to_set(self, value):
817
"""When setting, convert value from a datetime.timedelta"""
818
self._vts = int(round(value.total_seconds() * 1000))
821
class SetTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
825
class SetExtendedTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
826
propname = "ExtendedTimeout"
829
class SetIntervalCmd(MillisecondsPropertyValueArgumentCmd):
830
propname = "Interval"
833
class SetApprovalDelayCmd(MillisecondsPropertyValueArgumentCmd):
834
propname = "ApprovalDelay"
837
class SetApprovalDurationCmd(MillisecondsPropertyValueArgumentCmd):
838
propname = "ApprovalDuration"
1166
1112
options = self.parser.parse_args(args)
1167
1113
check_option_syntax(self.parser, options)
1168
1114
commands = commands_from_options(options)
1169
self.assertEqual(1, len(commands))
1115
self.assertEqual(len(commands), 1)
1170
1116
command = commands[0]
1171
1117
self.assertIsInstance(command, command_cls)
1172
1118
for key, value in cmd_attrs.items():
1173
self.assertEqual(value, getattr(command, key))
1119
self.assertEqual(getattr(command, key), value)
1175
1121
def test_is_enabled_short(self):
1176
self.assert_command_from_args(["-V", "client"],
1122
self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1179
1124
def test_approve(self):
1180
self.assert_command_from_args(["--approve", "client"],
1125
self.assert_command_from_args(["--approve", "foo"],
1183
1128
def test_approve_short(self):
1184
self.assert_command_from_args(["-A", "client"],
1129
self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1187
1131
def test_deny(self):
1188
self.assert_command_from_args(["--deny", "client"],
1132
self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1191
1134
def test_deny_short(self):
1192
self.assert_command_from_args(["-D", "client"], command.Deny)
1135
self.assert_command_from_args(["-D", "foo"], DenyCmd)
1194
1137
def test_remove(self):
1195
self.assert_command_from_args(["--remove", "client"],
1138
self.assert_command_from_args(["--remove", "foo"],
1198
1141
def test_deny_before_remove(self):
1199
1142
options = self.parser.parse_args(["--deny", "--remove",
1201
1144
check_option_syntax(self.parser, options)
1202
1145
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)
1146
self.assertEqual(len(commands), 2)
1147
self.assertIsInstance(commands[0], DenyCmd)
1148
self.assertIsInstance(commands[1], RemoveCmd)
1207
1150
def test_deny_before_remove_reversed(self):
1208
1151
options = self.parser.parse_args(["--remove", "--deny",
1210
1153
check_option_syntax(self.parser, options)
1211
1154
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)
1155
self.assertEqual(len(commands), 2)
1156
self.assertIsInstance(commands[0], DenyCmd)
1157
self.assertIsInstance(commands[1], RemoveCmd)
1216
1159
def test_remove_short(self):
1217
self.assert_command_from_args(["-r", "client"],
1160
self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1220
1162
def test_dump_json(self):
1221
self.assert_command_from_args(["--dump-json"],
1163
self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1224
1165
def test_enable(self):
1225
self.assert_command_from_args(["--enable", "client"],
1166
self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1228
1168
def test_enable_short(self):
1229
self.assert_command_from_args(["-e", "client"],
1169
self.assert_command_from_args(["-e", "foo"], EnableCmd)
1232
1171
def test_disable(self):
1233
self.assert_command_from_args(["--disable", "client"],
1172
self.assert_command_from_args(["--disable", "foo"],
1236
1175
def test_disable_short(self):
1237
self.assert_command_from_args(["-d", "client"],
1176
self.assert_command_from_args(["-d", "foo"], DisableCmd)
1240
1178
def test_bump_timeout(self):
1241
self.assert_command_from_args(["--bump-timeout", "client"],
1242
command.BumpTimeout)
1179
self.assert_command_from_args(["--bump-timeout", "foo"],
1244
1182
def test_bump_timeout_short(self):
1245
self.assert_command_from_args(["-b", "client"],
1246
command.BumpTimeout)
1183
self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1248
1185
def test_start_checker(self):
1249
self.assert_command_from_args(["--start-checker", "client"],
1250
command.StartChecker)
1186
self.assert_command_from_args(["--start-checker", "foo"],
1252
1189
def test_stop_checker(self):
1253
self.assert_command_from_args(["--stop-checker", "client"],
1254
command.StopChecker)
1190
self.assert_command_from_args(["--stop-checker", "foo"],
1256
1193
def test_approve_by_default(self):
1257
self.assert_command_from_args(["--approve-by-default",
1259
command.ApproveByDefault)
1194
self.assert_command_from_args(["--approve-by-default", "foo"],
1195
ApproveByDefaultCmd)
1261
1197
def test_deny_by_default(self):
1262
self.assert_command_from_args(["--deny-by-default", "client"],
1263
command.DenyByDefault)
1198
self.assert_command_from_args(["--deny-by-default", "foo"],
1265
1201
def test_checker(self):
1266
self.assert_command_from_args(["--checker", ":", "client"],
1202
self.assert_command_from_args(["--checker", ":", "foo"],
1203
SetCheckerCmd, value_to_set=":")
1270
1205
def test_checker_empty(self):
1271
self.assert_command_from_args(["--checker", "", "client"],
1206
self.assert_command_from_args(["--checker", "", "foo"],
1207
SetCheckerCmd, value_to_set="")
1275
1209
def test_checker_short(self):
1276
self.assert_command_from_args(["-c", ":", "client"],
1210
self.assert_command_from_args(["-c", ":", "foo"],
1211
SetCheckerCmd, value_to_set=":")
1280
1213
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")
1214
self.assert_command_from_args(["--host", "foo.example.org",
1216
value_to_set="foo.example.org")
1285
1218
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")
1219
self.assert_command_from_args(["-H", "foo.example.org",
1221
value_to_set="foo.example.org")
1290
1223
def test_secret_devnull(self):
1291
1224
self.assert_command_from_args(["--secret", os.path.devnull,
1292
"client"], command.SetSecret,
1225
"foo"], SetSecretCmd,
1293
1226
value_to_set=b"")
1295
1228
def test_secret_tempfile(self):
1439
1372
LastCheckerStatus=-2)
1440
1373
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),
1375
("/clients/foo", self.client.attributes),
1376
("/clients/barbar", self.other_client.attributes),
1447
self.one_client = {self.client.__dbus_object_path__:
1448
self.client.attributes}
1378
self.one_client = {"/clients/foo": self.client.attributes}
1452
class MockBus(object):
1454
1384
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):
1385
self.assertEqual(client_bus_name, dbus_busname)
1387
# Note: "self" here is the TestCmd instance, not
1388
# the Bus instance, since this is a static method!
1389
"/clients/foo": self.client,
1390
"/clients/barbar": self.other_client,
1395
class TestIsEnabledCmd(TestCmd):
1396
def test_is_enabled(self):
1397
self.assertTrue(all(IsEnabledCmd().is_enabled(client,
1399
for client, properties
1400
in self.clients.items()))
1402
def test_is_enabled_run_exits_successfully(self):
1468
1403
with self.assertRaises(SystemExit) as e:
1469
command.IsEnabled().run(self.one_client)
1404
IsEnabledCmd().run(self.one_client)
1470
1405
if e.exception.code is not None:
1471
self.assertEqual(0, e.exception.code)
1406
self.assertEqual(e.exception.code, 0)
1473
1408
self.assertIsNone(e.exception.code)
1475
def test_IsEnabled_exits_with_failure(self):
1410
def test_is_enabled_run_exits_with_failure(self):
1476
1411
self.client.attributes["Enabled"] = dbus.Boolean(False)
1477
1412
with self.assertRaises(SystemExit) as e:
1478
command.IsEnabled().run(self.one_client)
1413
IsEnabledCmd().run(self.one_client)
1479
1414
if isinstance(e.exception.code, int):
1480
self.assertNotEqual(0, e.exception.code)
1415
self.assertNotEqual(e.exception.code, 0)
1482
1417
self.assertIsNotNone(e.exception.code)
1484
def test_Approve(self):
1485
command.Approve().run(self.clients, self.bus)
1420
class TestApproveCmd(TestCmd):
1421
def test_approve(self):
1422
ApproveCmd().run(self.clients, self.bus)
1486
1423
for clientpath in self.clients:
1487
1424
client = self.bus.get_object(dbus_busname, clientpath)
1488
1425
self.assertIn(("Approve", (True, client_dbus_interface)),
1491
def test_Deny(self):
1492
command.Deny().run(self.clients, self.bus)
1429
class TestDenyCmd(TestCmd):
1430
def test_deny(self):
1431
DenyCmd().run(self.clients, self.bus)
1493
1432
for clientpath in self.clients:
1494
1433
client = self.bus.get_object(dbus_busname, clientpath)
1495
1434
self.assertIn(("Approve", (False, client_dbus_interface)),
1498
def test_Remove(self):
1499
class MandosSpy(object):
1438
class TestRemoveCmd(TestCmd):
1439
def test_remove(self):
1440
class MockMandos(object):
1500
1441
def __init__(self):
1501
1442
self.calls = []
1502
1443
def RemoveClient(self, dbus_path):
1503
1444
self.calls.append(("RemoveClient", (dbus_path,)))
1504
mandos = MandosSpy()
1505
command.Remove().run(self.clients, self.bus, mandos)
1445
mandos = MockMandos()
1446
super(TestRemoveCmd, self).setUp()
1447
RemoveCmd().run(self.clients, self.bus, mandos)
1448
self.assertEqual(len(mandos.calls), 2)
1506
1449
for clientpath in self.clients:
1507
1450
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())
1454
class TestDumpJSONCmd(TestCmd):
1456
self.expected_json = {
1459
"KeyID": ("92ed150794387c03ce684574b1139a65"
1460
"94a34f895daaaf09fd8ea90a27cddb12"),
1461
"Host": "foo.example.org",
1464
"LastCheckedOK": "2019-02-03T00:00:00",
1465
"Created": "2019-01-02T00:00:00",
1467
"Fingerprint": ("778827225BA7DE539C5A"
1468
"7CFA59CFF7CDBD9A5920"),
1469
"CheckerRunning": False,
1470
"LastEnabled": "2019-01-03T00:00:00",
1471
"ApprovalPending": False,
1472
"ApprovedByDefault": True,
1473
"LastApprovalRequest": "",
1475
"ApprovalDuration": 1000,
1476
"Checker": "fping -q -- %(host)s",
1477
"ExtendedTimeout": 900000,
1478
"Expires": "2019-02-04T00:00:00",
1479
"LastCheckerStatus": 0,
1483
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1484
"6ab612cff5ad227247e46c2b020f441c"),
1485
"Host": "192.0.2.3",
1488
"LastCheckedOK": "2019-02-04T00:00:00",
1489
"Created": "2019-01-03T00:00:00",
1491
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1492
"F547B3A107558FCA3A27"),
1493
"CheckerRunning": True,
1494
"LastEnabled": "2019-01-04T00:00:00",
1495
"ApprovalPending": False,
1496
"ApprovedByDefault": False,
1497
"LastApprovalRequest": "2019-01-03T00:00:00",
1498
"ApprovalDelay": 30000,
1499
"ApprovalDuration": 93785000,
1501
"ExtendedTimeout": 900000,
1502
"Expires": "2019-02-05T00:00:00",
1503
"LastCheckerStatus": -2,
1506
return super(TestDumpJSONCmd, self).setUp()
1508
def test_normal(self):
1509
output = DumpJSONCmd().output(self.clients.values())
1510
json_data = json.loads(output)
1511
self.assertDictEqual(json_data, self.expected_json)
1513
def test_one_client(self):
1514
output = DumpJSONCmd().output(self.one_client.values())
1515
json_data = json.loads(output)
1582
1516
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)
1517
self.assertDictEqual(json_data, expected_json)
1520
class TestPrintTableCmd(TestCmd):
1521
def test_normal(self):
1522
output = PrintTableCmd().output(self.clients.values())
1588
1523
expected_output = "\n".join((
1589
1524
"Name Enabled Timeout Last Successful Check",
1590
1525
"foo Yes 00:05:00 2019-02-03T00:00:00 ",
1591
1526
"barbar Yes 00:05:00 2019-02-04T00:00:00 ",
1593
self.assertEqual(expected_output, buffer.getvalue())
1528
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)
1530
def test_verbose(self):
1531
output = PrintTableCmd(verbose=True).output(
1532
self.clients.values())
1726
1660
self.command().run(clients, self.bus)
1729
class TestEnableCmd(TestPropertySetterCmd):
1730
command = command.Enable
1663
class TestEnableCmd(TestPropertyCmd):
1731
1665
propname = "Enabled"
1732
1666
values_to_set = [dbus.Boolean(True)]
1735
class TestDisableCmd(TestPropertySetterCmd):
1736
command = command.Disable
1669
class TestDisableCmd(TestPropertyCmd):
1670
command = DisableCmd
1737
1671
propname = "Enabled"
1738
1672
values_to_set = [dbus.Boolean(False)]
1741
class TestBumpTimeoutCmd(TestPropertySetterCmd):
1742
command = command.BumpTimeout
1675
class TestBumpTimeoutCmd(TestPropertyCmd):
1676
command = BumpTimeoutCmd
1743
1677
propname = "LastCheckedOK"
1744
1678
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"""
1681
class TestStartCheckerCmd(TestPropertyCmd):
1682
command = StartCheckerCmd
1683
propname = "CheckerRunning"
1684
values_to_set = [dbus.Boolean(True)]
1687
class TestStopCheckerCmd(TestPropertyCmd):
1688
command = StopCheckerCmd
1689
propname = "CheckerRunning"
1690
values_to_set = [dbus.Boolean(False)]
1693
class TestApproveByDefaultCmd(TestPropertyCmd):
1694
command = ApproveByDefaultCmd
1695
propname = "ApprovedByDefault"
1696
values_to_set = [dbus.Boolean(True)]
1699
class TestDenyByDefaultCmd(TestPropertyCmd):
1700
command = DenyByDefaultCmd
1701
propname = "ApprovedByDefault"
1702
values_to_set = [dbus.Boolean(False)]
1705
class TestPropertyValueCmd(TestPropertyCmd):
1706
"""Abstract class for tests of PropertyValueCmd classes"""
1774
1708
def runTest(self):
1775
if type(self) is TestPropertySetterValueCmd:
1709
if type(self) is TestPropertyValueCmd:
1777
return super(TestPropertySetterValueCmd, self).runTest()
1711
return super(TestPropertyValueCmd, self).runTest()
1779
1713
def run_command(self, value, clients):
1780
1714
self.command(value).run(clients, self.bus)
1783
class TestSetCheckerCmd(TestPropertySetterValueCmd):
1784
command = command.SetChecker
1717
class TestSetCheckerCmd(TestPropertyValueCmd):
1718
command = SetCheckerCmd
1785
1719
propname = "Checker"
1786
1720
values_to_set = ["", ":", "fping -q -- %s"]
1789
class TestSetHostCmd(TestPropertySetterValueCmd):
1790
command = command.SetHost
1723
class TestSetHostCmd(TestPropertyValueCmd):
1724
command = SetHostCmd
1791
1725
propname = "Host"
1792
values_to_set = ["192.0.2.3", "client.example.org"]
1795
class TestSetSecretCmd(TestPropertySetterValueCmd):
1796
command = command.SetSecret
1726
values_to_set = ["192.0.2.3", "foo.example.org"]
1729
class TestSetSecretCmd(TestPropertyValueCmd):
1730
command = SetSecretCmd
1797
1731
propname = "Secret"
1798
1732
values_to_set = [io.BytesIO(b""),
1799
1733
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
1734
values_to_get = [b"", b"secret\0xyzzy\nbar"]
1737
class TestSetTimeoutCmd(TestPropertyValueCmd):
1738
command = SetTimeoutCmd
1805
1739
propname = "Timeout"
1806
1740
values_to_set = [datetime.timedelta(),
1807
1741
datetime.timedelta(minutes=5),
1808
1742
datetime.timedelta(seconds=1),
1809
1743
datetime.timedelta(weeks=1),
1810
1744
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
1745
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1748
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
1749
command = SetExtendedTimeoutCmd
1816
1750
propname = "ExtendedTimeout"
1817
1751
values_to_set = [datetime.timedelta(),
1818
1752
datetime.timedelta(minutes=5),
1819
1753
datetime.timedelta(seconds=1),
1820
1754
datetime.timedelta(weeks=1),
1821
1755
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
1756
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1759
class TestSetIntervalCmd(TestPropertyValueCmd):
1760
command = SetIntervalCmd
1827
1761
propname = "Interval"
1828
1762
values_to_set = [datetime.timedelta(),
1829
1763
datetime.timedelta(minutes=5),
1830
1764
datetime.timedelta(seconds=1),
1831
1765
datetime.timedelta(weeks=1),
1832
1766
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
1767
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1770
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
1771
command = SetApprovalDelayCmd
1838
1772
propname = "ApprovalDelay"
1839
1773
values_to_set = [datetime.timedelta(),
1840
1774
datetime.timedelta(minutes=5),
1841
1775
datetime.timedelta(seconds=1),
1842
1776
datetime.timedelta(weeks=1),
1843
1777
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
1778
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1781
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
1782
command = SetApprovalDurationCmd
1849
1783
propname = "ApprovalDuration"
1850
1784
values_to_set = [datetime.timedelta(),
1851
1785
datetime.timedelta(minutes=5),
1852
1786
datetime.timedelta(seconds=1),
1853
1787
datetime.timedelta(weeks=1),
1854
1788
datetime.timedelta(weeks=52)]
1855
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1789
values_to_get = [0, 300000, 1000, 604800000, 31449600000]