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
1114
options = self.parser.parse_args(args)
1167
1115
check_option_syntax(self.parser, options)
1168
1116
commands = commands_from_options(options)
1169
self.assertEqual(1, len(commands))
1117
self.assertEqual(len(commands), 1)
1170
1118
command = commands[0]
1171
1119
self.assertIsInstance(command, command_cls)
1172
1120
for key, value in cmd_attrs.items():
1173
self.assertEqual(value, getattr(command, key))
1121
self.assertEqual(getattr(command, key), value)
1175
1123
def test_is_enabled_short(self):
1176
self.assert_command_from_args(["-V", "client"],
1124
self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1179
1126
def test_approve(self):
1180
self.assert_command_from_args(["--approve", "client"],
1127
self.assert_command_from_args(["--approve", "foo"],
1183
1130
def test_approve_short(self):
1184
self.assert_command_from_args(["-A", "client"],
1131
self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1187
1133
def test_deny(self):
1188
self.assert_command_from_args(["--deny", "client"],
1134
self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1191
1136
def test_deny_short(self):
1192
self.assert_command_from_args(["-D", "client"], command.Deny)
1137
self.assert_command_from_args(["-D", "foo"], DenyCmd)
1194
1139
def test_remove(self):
1195
self.assert_command_from_args(["--remove", "client"],
1140
self.assert_command_from_args(["--remove", "foo"],
1198
1143
def test_deny_before_remove(self):
1199
1144
options = self.parser.parse_args(["--deny", "--remove",
1201
1146
check_option_syntax(self.parser, options)
1202
1147
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)
1148
self.assertEqual(len(commands), 2)
1149
self.assertIsInstance(commands[0], DenyCmd)
1150
self.assertIsInstance(commands[1], RemoveCmd)
1207
1152
def test_deny_before_remove_reversed(self):
1208
1153
options = self.parser.parse_args(["--remove", "--deny",
1210
1155
check_option_syntax(self.parser, options)
1211
1156
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)
1157
self.assertEqual(len(commands), 2)
1158
self.assertIsInstance(commands[0], DenyCmd)
1159
self.assertIsInstance(commands[1], RemoveCmd)
1216
1161
def test_remove_short(self):
1217
self.assert_command_from_args(["-r", "client"],
1162
self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1220
1164
def test_dump_json(self):
1221
self.assert_command_from_args(["--dump-json"],
1165
self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1224
1167
def test_enable(self):
1225
self.assert_command_from_args(["--enable", "client"],
1168
self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1228
1170
def test_enable_short(self):
1229
self.assert_command_from_args(["-e", "client"],
1171
self.assert_command_from_args(["-e", "foo"], EnableCmd)
1232
1173
def test_disable(self):
1233
self.assert_command_from_args(["--disable", "client"],
1174
self.assert_command_from_args(["--disable", "foo"],
1236
1177
def test_disable_short(self):
1237
self.assert_command_from_args(["-d", "client"],
1178
self.assert_command_from_args(["-d", "foo"], DisableCmd)
1240
1180
def test_bump_timeout(self):
1241
self.assert_command_from_args(["--bump-timeout", "client"],
1242
command.BumpTimeout)
1181
self.assert_command_from_args(["--bump-timeout", "foo"],
1244
1184
def test_bump_timeout_short(self):
1245
self.assert_command_from_args(["-b", "client"],
1246
command.BumpTimeout)
1185
self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1248
1187
def test_start_checker(self):
1249
self.assert_command_from_args(["--start-checker", "client"],
1250
command.StartChecker)
1188
self.assert_command_from_args(["--start-checker", "foo"],
1252
1191
def test_stop_checker(self):
1253
self.assert_command_from_args(["--stop-checker", "client"],
1254
command.StopChecker)
1192
self.assert_command_from_args(["--stop-checker", "foo"],
1256
1195
def test_approve_by_default(self):
1257
self.assert_command_from_args(["--approve-by-default",
1259
command.ApproveByDefault)
1196
self.assert_command_from_args(["--approve-by-default", "foo"],
1197
ApproveByDefaultCmd)
1261
1199
def test_deny_by_default(self):
1262
self.assert_command_from_args(["--deny-by-default", "client"],
1263
command.DenyByDefault)
1200
self.assert_command_from_args(["--deny-by-default", "foo"],
1265
1203
def test_checker(self):
1266
self.assert_command_from_args(["--checker", ":", "client"],
1204
self.assert_command_from_args(["--checker", ":", "foo"],
1205
SetCheckerCmd, value_to_set=":")
1270
1207
def test_checker_empty(self):
1271
self.assert_command_from_args(["--checker", "", "client"],
1208
self.assert_command_from_args(["--checker", "", "foo"],
1209
SetCheckerCmd, value_to_set="")
1275
1211
def test_checker_short(self):
1276
self.assert_command_from_args(["-c", ":", "client"],
1212
self.assert_command_from_args(["-c", ":", "foo"],
1213
SetCheckerCmd, value_to_set=":")
1280
1215
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")
1216
self.assert_command_from_args(["--host", "foo.example.org",
1218
value_to_set="foo.example.org")
1285
1220
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")
1221
self.assert_command_from_args(["-H", "foo.example.org",
1223
value_to_set="foo.example.org")
1290
1225
def test_secret_devnull(self):
1291
1226
self.assert_command_from_args(["--secret", os.path.devnull,
1292
"client"], command.SetSecret,
1227
"foo"], SetSecretCmd,
1293
1228
value_to_set=b"")
1295
1230
def test_secret_tempfile(self):
1439
1374
LastCheckerStatus=-2)
1440
1375
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),
1377
("/clients/foo", self.client.attributes),
1378
("/clients/barbar", self.other_client.attributes),
1447
self.one_client = {self.client.__dbus_object_path__:
1448
self.client.attributes}
1380
self.one_client = {"/clients/foo": self.client.attributes}
1452
class MockBus(object):
1454
1386
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):
1387
self.assertEqual(client_bus_name, dbus_busname)
1389
# Note: "self" here is the TestCmd instance, not
1390
# the Bus instance, since this is a static method!
1391
"/clients/foo": self.client,
1392
"/clients/barbar": self.other_client,
1397
class TestIsEnabledCmd(TestCmd):
1398
def test_is_enabled(self):
1399
self.assertTrue(all(IsEnabledCmd().is_enabled(client,
1401
for client, properties
1402
in self.clients.items()))
1404
def test_is_enabled_run_exits_successfully(self):
1468
1405
with self.assertRaises(SystemExit) as e:
1469
command.IsEnabled().run(self.one_client)
1406
IsEnabledCmd().run(self.one_client)
1470
1407
if e.exception.code is not None:
1471
self.assertEqual(0, e.exception.code)
1408
self.assertEqual(e.exception.code, 0)
1473
1410
self.assertIsNone(e.exception.code)
1475
def test_IsEnabled_exits_with_failure(self):
1412
def test_is_enabled_run_exits_with_failure(self):
1476
1413
self.client.attributes["Enabled"] = dbus.Boolean(False)
1477
1414
with self.assertRaises(SystemExit) as e:
1478
command.IsEnabled().run(self.one_client)
1415
IsEnabledCmd().run(self.one_client)
1479
1416
if isinstance(e.exception.code, int):
1480
self.assertNotEqual(0, e.exception.code)
1417
self.assertNotEqual(e.exception.code, 0)
1482
1419
self.assertIsNotNone(e.exception.code)
1484
def test_Approve(self):
1485
command.Approve().run(self.clients, self.bus)
1422
class TestApproveCmd(TestCmd):
1423
def test_approve(self):
1424
ApproveCmd().run(self.clients, self.bus)
1486
1425
for clientpath in self.clients:
1487
1426
client = self.bus.get_object(dbus_busname, clientpath)
1488
1427
self.assertIn(("Approve", (True, client_dbus_interface)),
1491
def test_Deny(self):
1492
command.Deny().run(self.clients, self.bus)
1431
class TestDenyCmd(TestCmd):
1432
def test_deny(self):
1433
DenyCmd().run(self.clients, self.bus)
1493
1434
for clientpath in self.clients:
1494
1435
client = self.bus.get_object(dbus_busname, clientpath)
1495
1436
self.assertIn(("Approve", (False, client_dbus_interface)),
1498
def test_Remove(self):
1499
class MandosSpy(object):
1440
class TestRemoveCmd(TestCmd):
1441
def test_remove(self):
1442
class MockMandos(object):
1500
1443
def __init__(self):
1501
1444
self.calls = []
1502
1445
def RemoveClient(self, dbus_path):
1503
1446
self.calls.append(("RemoveClient", (dbus_path,)))
1504
mandos = MandosSpy()
1505
command.Remove().run(self.clients, self.bus, mandos)
1447
mandos = MockMandos()
1448
super(TestRemoveCmd, self).setUp()
1449
RemoveCmd().run(self.clients, self.bus, mandos)
1450
self.assertEqual(len(mandos.calls), 2)
1506
1451
for clientpath in self.clients:
1507
1452
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())
1456
class TestDumpJSONCmd(TestCmd):
1458
self.expected_json = {
1461
"KeyID": ("92ed150794387c03ce684574b1139a65"
1462
"94a34f895daaaf09fd8ea90a27cddb12"),
1463
"Host": "foo.example.org",
1466
"LastCheckedOK": "2019-02-03T00:00:00",
1467
"Created": "2019-01-02T00:00:00",
1469
"Fingerprint": ("778827225BA7DE539C5A"
1470
"7CFA59CFF7CDBD9A5920"),
1471
"CheckerRunning": False,
1472
"LastEnabled": "2019-01-03T00:00:00",
1473
"ApprovalPending": False,
1474
"ApprovedByDefault": True,
1475
"LastApprovalRequest": "",
1477
"ApprovalDuration": 1000,
1478
"Checker": "fping -q -- %(host)s",
1479
"ExtendedTimeout": 900000,
1480
"Expires": "2019-02-04T00:00:00",
1481
"LastCheckerStatus": 0,
1485
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1486
"6ab612cff5ad227247e46c2b020f441c"),
1487
"Host": "192.0.2.3",
1490
"LastCheckedOK": "2019-02-04T00:00:00",
1491
"Created": "2019-01-03T00:00:00",
1493
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1494
"F547B3A107558FCA3A27"),
1495
"CheckerRunning": True,
1496
"LastEnabled": "2019-01-04T00:00:00",
1497
"ApprovalPending": False,
1498
"ApprovedByDefault": False,
1499
"LastApprovalRequest": "2019-01-03T00:00:00",
1500
"ApprovalDelay": 30000,
1501
"ApprovalDuration": 93785000,
1503
"ExtendedTimeout": 900000,
1504
"Expires": "2019-02-05T00:00:00",
1505
"LastCheckerStatus": -2,
1508
return super(TestDumpJSONCmd, self).setUp()
1510
def test_normal(self):
1511
output = DumpJSONCmd().output(self.clients.values())
1512
json_data = json.loads(output)
1513
self.assertDictEqual(json_data, self.expected_json)
1515
def test_one_client(self):
1516
output = DumpJSONCmd().output(self.one_client.values())
1517
json_data = json.loads(output)
1582
1518
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)
1519
self.assertDictEqual(json_data, expected_json)
1522
class TestPrintTableCmd(TestCmd):
1523
def test_normal(self):
1524
output = PrintTableCmd().output(self.clients.values())
1588
1525
expected_output = "\n".join((
1589
1526
"Name Enabled Timeout Last Successful Check",
1590
1527
"foo Yes 00:05:00 2019-02-03T00:00:00 ",
1591
1528
"barbar Yes 00:05:00 2019-02-04T00:00:00 ",
1593
self.assertEqual(expected_output, buffer.getvalue())
1530
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)
1532
def test_verbose(self):
1533
output = PrintTableCmd(verbose=True).output(
1534
self.clients.values())
1726
1662
self.command().run(clients, self.bus)
1729
class TestEnableCmd(TestPropertySetterCmd):
1730
command = command.Enable
1665
class TestEnableCmd(TestPropertyCmd):
1731
1667
propname = "Enabled"
1732
1668
values_to_set = [dbus.Boolean(True)]
1735
class TestDisableCmd(TestPropertySetterCmd):
1736
command = command.Disable
1671
class TestDisableCmd(TestPropertyCmd):
1672
command = DisableCmd
1737
1673
propname = "Enabled"
1738
1674
values_to_set = [dbus.Boolean(False)]
1741
class TestBumpTimeoutCmd(TestPropertySetterCmd):
1742
command = command.BumpTimeout
1677
class TestBumpTimeoutCmd(TestPropertyCmd):
1678
command = BumpTimeoutCmd
1743
1679
propname = "LastCheckedOK"
1744
1680
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"""
1683
class TestStartCheckerCmd(TestPropertyCmd):
1684
command = StartCheckerCmd
1685
propname = "CheckerRunning"
1686
values_to_set = [dbus.Boolean(True)]
1689
class TestStopCheckerCmd(TestPropertyCmd):
1690
command = StopCheckerCmd
1691
propname = "CheckerRunning"
1692
values_to_set = [dbus.Boolean(False)]
1695
class TestApproveByDefaultCmd(TestPropertyCmd):
1696
command = ApproveByDefaultCmd
1697
propname = "ApprovedByDefault"
1698
values_to_set = [dbus.Boolean(True)]
1701
class TestDenyByDefaultCmd(TestPropertyCmd):
1702
command = DenyByDefaultCmd
1703
propname = "ApprovedByDefault"
1704
values_to_set = [dbus.Boolean(False)]
1707
class TestPropertyValueCmd(TestPropertyCmd):
1708
"""Abstract class for tests of PropertyValueCmd classes"""
1774
1710
def runTest(self):
1775
if type(self) is TestPropertySetterValueCmd:
1711
if type(self) is TestPropertyValueCmd:
1777
return super(TestPropertySetterValueCmd, self).runTest()
1713
return super(TestPropertyValueCmd, self).runTest()
1779
1715
def run_command(self, value, clients):
1780
1716
self.command(value).run(clients, self.bus)
1783
class TestSetCheckerCmd(TestPropertySetterValueCmd):
1784
command = command.SetChecker
1719
class TestSetCheckerCmd(TestPropertyValueCmd):
1720
command = SetCheckerCmd
1785
1721
propname = "Checker"
1786
1722
values_to_set = ["", ":", "fping -q -- %s"]
1789
class TestSetHostCmd(TestPropertySetterValueCmd):
1790
command = command.SetHost
1725
class TestSetHostCmd(TestPropertyValueCmd):
1726
command = SetHostCmd
1791
1727
propname = "Host"
1792
values_to_set = ["192.0.2.3", "client.example.org"]
1795
class TestSetSecretCmd(TestPropertySetterValueCmd):
1796
command = command.SetSecret
1728
values_to_set = ["192.0.2.3", "foo.example.org"]
1731
class TestSetSecretCmd(TestPropertyValueCmd):
1732
command = SetSecretCmd
1797
1733
propname = "Secret"
1798
1734
values_to_set = [io.BytesIO(b""),
1799
1735
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
1736
values_to_get = [b"", b"secret\0xyzzy\nbar"]
1739
class TestSetTimeoutCmd(TestPropertyValueCmd):
1740
command = SetTimeoutCmd
1805
1741
propname = "Timeout"
1806
1742
values_to_set = [datetime.timedelta(),
1807
1743
datetime.timedelta(minutes=5),
1808
1744
datetime.timedelta(seconds=1),
1809
1745
datetime.timedelta(weeks=1),
1810
1746
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
1747
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1750
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
1751
command = SetExtendedTimeoutCmd
1816
1752
propname = "ExtendedTimeout"
1817
1753
values_to_set = [datetime.timedelta(),
1818
1754
datetime.timedelta(minutes=5),
1819
1755
datetime.timedelta(seconds=1),
1820
1756
datetime.timedelta(weeks=1),
1821
1757
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
1758
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1761
class TestSetIntervalCmd(TestPropertyValueCmd):
1762
command = SetIntervalCmd
1827
1763
propname = "Interval"
1828
1764
values_to_set = [datetime.timedelta(),
1829
1765
datetime.timedelta(minutes=5),
1830
1766
datetime.timedelta(seconds=1),
1831
1767
datetime.timedelta(weeks=1),
1832
1768
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
1769
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1772
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
1773
command = SetApprovalDelayCmd
1838
1774
propname = "ApprovalDelay"
1839
1775
values_to_set = [datetime.timedelta(),
1840
1776
datetime.timedelta(minutes=5),
1841
1777
datetime.timedelta(seconds=1),
1842
1778
datetime.timedelta(weeks=1),
1843
1779
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
1780
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1783
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
1784
command = SetApprovalDurationCmd
1849
1785
propname = "ApprovalDuration"
1850
1786
values_to_set = [datetime.timedelta(),
1851
1787
datetime.timedelta(minutes=5),
1852
1788
datetime.timedelta(seconds=1),
1853
1789
datetime.timedelta(weeks=1),
1854
1790
datetime.timedelta(weeks=52)]
1855
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1791
values_to_get = [0, 300000, 1000, 604800000, 31449600000]