479
479
if options.is_enabled:
480
commands.append(IsEnabledCmd())
480
commands.append(command.IsEnabled())
482
482
if options.approve:
483
commands.append(ApproveCmd())
483
commands.append(command.Approve())
486
commands.append(DenyCmd())
486
commands.append(command.Deny())
488
488
if options.remove:
489
commands.append(RemoveCmd())
489
commands.append(command.Remove())
491
491
if options.dump_json:
492
commands.append(DumpJSONCmd())
492
commands.append(command.DumpJSON())
494
494
if options.enable:
495
commands.append(EnableCmd())
495
commands.append(command.Enable())
497
497
if options.disable:
498
commands.append(DisableCmd())
498
commands.append(command.Disable())
500
500
if options.bump_timeout:
501
commands.append(BumpTimeoutCmd())
501
commands.append(command.BumpTimeout())
503
503
if options.start_checker:
504
commands.append(StartCheckerCmd())
504
commands.append(command.StartChecker())
506
506
if options.stop_checker:
507
commands.append(StopCheckerCmd())
507
commands.append(command.StopChecker())
509
509
if options.approved_by_default is not None:
510
510
if options.approved_by_default:
511
commands.append(ApproveByDefaultCmd())
511
commands.append(command.ApproveByDefault())
513
commands.append(DenyByDefaultCmd())
513
commands.append(command.DenyByDefault())
515
515
if options.checker is not None:
516
commands.append(SetCheckerCmd(options.checker))
516
commands.append(command.SetChecker(options.checker))
518
518
if options.host is not None:
519
commands.append(SetHostCmd(options.host))
519
commands.append(command.SetHost(options.host))
521
521
if options.secret is not None:
522
commands.append(SetSecretCmd(options.secret))
522
commands.append(command.SetSecret(options.secret))
524
524
if options.timeout is not None:
525
commands.append(SetTimeoutCmd(options.timeout))
525
commands.append(command.SetTimeout(options.timeout))
527
527
if options.extended_timeout:
529
SetExtendedTimeoutCmd(options.extended_timeout))
529
command.SetExtendedTimeout(options.extended_timeout))
531
531
if options.interval is not None:
532
commands.append(SetIntervalCmd(options.interval))
532
commands.append(command.SetInterval(options.interval))
534
534
if options.approval_delay is not None:
535
commands.append(SetApprovalDelayCmd(options.approval_delay))
536
command.SetApprovalDelay(options.approval_delay))
537
538
if options.approval_duration is not None:
539
SetApprovalDurationCmd(options.approval_duration))
540
command.SetApprovalDuration(options.approval_duration))
541
542
# If no command option has been given, show table of clients,
542
543
# optionally verbosely
544
commands.append(PrintTableCmd(verbose=options.verbose))
545
commands.append(command.PrintTable(verbose=options.verbose))
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__
550
class command(object):
551
"""A namespace for command classes"""
554
"""Abstract base class for commands"""
555
def run(self, clients, bus=None, mandos=None):
556
"""Normal commands should implement run_on_one_client(),
557
but commands which want to operate on all clients at the same time can
558
override this run() method instead.
561
for clientpath, properties in clients.items():
562
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
563
dbus_busname, str(clientpath))
564
client = bus.get_object(dbus_busname, clientpath)
565
self.run_on_one_client(client, properties)
568
class IsEnabled(Base):
569
def run(self, clients, bus=None, mandos=None):
570
client, properties = next(iter(clients.items()))
571
if self.is_enabled(client, properties):
574
def is_enabled(self, client, properties):
575
return properties["Enabled"]
579
def run_on_one_client(self, client, properties):
580
log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
581
client.__dbus_object_path__,
582
client_dbus_interface)
583
client.Approve(dbus.Boolean(True),
584
dbus_interface=client_dbus_interface)
588
def run_on_one_client(self, client, properties):
589
log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
590
client.__dbus_object_path__,
591
client_dbus_interface)
592
client.Approve(dbus.Boolean(False),
593
dbus_interface=client_dbus_interface)
597
def run_on_one_client(self, client, properties):
598
log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)",
599
dbus_busname, server_dbus_path,
600
server_dbus_interface,
601
str(client.__dbus_object_path__))
602
self.mandos.RemoveClient(client.__dbus_object_path__)
606
"""Abstract class for commands outputting client details"""
607
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
608
"Created", "Interval", "Host", "KeyID",
609
"Fingerprint", "CheckerRunning",
610
"LastEnabled", "ApprovalPending",
611
"ApprovedByDefault", "LastApprovalRequest",
612
"ApprovalDelay", "ApprovalDuration",
613
"Checker", "ExtendedTimeout", "Expires",
616
def run(self, clients, bus=None, mandos=None):
617
print(self.output(clients.values()))
619
def output(self, clients):
620
raise NotImplementedError()
623
class DumpJSON(Output):
624
def output(self, clients):
625
data = {client["Name"]:
626
{key: self.dbus_boolean_to_bool(client[key])
627
for key in self.all_keywords}
628
for client in clients}
629
return json.dumps(data, indent=4, separators=(',', ': '))
632
def dbus_boolean_to_bool(value):
633
if isinstance(value, dbus.Boolean):
638
class PrintTable(Output):
639
def __init__(self, verbose=False):
640
self.verbose = verbose
642
def output(self, clients):
643
default_keywords = ("Name", "Enabled", "Timeout",
645
keywords = default_keywords
647
keywords = self.all_keywords
648
return str(self.TableOfClients(clients, keywords))
650
class TableOfClients(object):
653
"Enabled": "Enabled",
654
"Timeout": "Timeout",
655
"LastCheckedOK": "Last Successful Check",
656
"LastApprovalRequest": "Last Approval Request",
657
"Created": "Created",
658
"Interval": "Interval",
660
"Fingerprint": "Fingerprint",
662
"CheckerRunning": "Check Is Running",
663
"LastEnabled": "Last Enabled",
664
"ApprovalPending": "Approval Is Pending",
665
"ApprovedByDefault": "Approved By Default",
666
"ApprovalDelay": "Approval Delay",
667
"ApprovalDuration": "Approval Duration",
668
"Checker": "Checker",
669
"ExtendedTimeout": "Extended Timeout",
670
"Expires": "Expires",
671
"LastCheckerStatus": "Last Checker Status",
674
def __init__(self, clients, keywords):
675
self.clients = clients
676
self.keywords = keywords
674
678
def __str__(self):
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})
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
679
return "\n".join(self.rows())
681
if sys.version_info.major == 2:
682
__unicode__ = __str__
684
return str(self).encode(
685
locale.getpreferredencoding())
688
format_string = self.row_formatting_string()
689
rows = [self.header_line(format_string)]
690
rows.extend(self.client_line(client, format_string)
691
for client in self.clients)
694
def row_formatting_string(self):
695
"Format string used to format table rows"
696
return " ".join("{{{key}:{width}}}".format(
697
width=max(len(self.tableheaders[key]),
698
*(len(self.string_from_client(client,
700
for client in self.clients)),
702
for key in self.keywords)
704
def string_from_client(self, client, key):
705
return self.valuetostring(client[key], key)
708
def valuetostring(cls, value, keyword):
709
if isinstance(value, dbus.Boolean):
710
return "Yes" if value else "No"
711
if keyword in ("Timeout", "Interval", "ApprovalDelay",
712
"ApprovalDuration", "ExtendedTimeout"):
713
return cls.milliseconds_to_string(value)
716
def header_line(self, format_string):
717
return format_string.format(**self.tableheaders)
719
def client_line(self, client, format_string):
720
return format_string.format(
721
**{key: self.string_from_client(client, key)
722
for key in self.keywords})
725
def milliseconds_to_string(ms):
726
td = datetime.timedelta(0, 0, 0, ms)
727
return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
728
.format(days="{}T".format(td.days)
730
hours=td.seconds // 3600,
731
minutes=(td.seconds % 3600) // 60,
732
seconds=td.seconds % 60))
735
class Property(Base):
736
"Abstract class for Actions for setting one client property"
738
def run_on_one_client(self, client, properties):
739
"""Set the Client's D-Bus property"""
740
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
741
client.__dbus_object_path__,
742
dbus.PROPERTIES_IFACE, client_dbus_interface,
743
self.propname, self.value_to_set
744
if not isinstance(self.value_to_set,
746
else bool(self.value_to_set))
747
client.Set(client_dbus_interface, self.propname,
749
dbus_interface=dbus.PROPERTIES_IFACE)
753
raise NotImplementedError()
756
class Enable(Property):
758
value_to_set = dbus.Boolean(True)
761
class Disable(Property):
763
value_to_set = dbus.Boolean(False)
766
class BumpTimeout(Property):
767
propname = "LastCheckedOK"
771
class StartChecker(Property):
772
propname = "CheckerRunning"
773
value_to_set = dbus.Boolean(True)
776
class StopChecker(Property):
777
propname = "CheckerRunning"
778
value_to_set = dbus.Boolean(False)
781
class ApproveByDefault(Property):
782
propname = "ApprovedByDefault"
783
value_to_set = dbus.Boolean(True)
786
class DenyByDefault(Property):
787
propname = "ApprovedByDefault"
788
value_to_set = dbus.Boolean(False)
791
class PropertyValue(Property):
792
"Abstract class for Property recieving a value as argument"
793
def __init__(self, value):
794
self.value_to_set = value
797
class SetChecker(PropertyValue):
801
class SetHost(PropertyValue):
805
class SetSecret(PropertyValue):
809
def value_to_set(self):
813
def value_to_set(self, value):
814
"""When setting, read data from supplied file object"""
815
self._vts = value.read()
819
class MillisecondsPropertyValueArgument(PropertyValue):
820
"""Abstract class for PropertyValue taking a value argument as
809
821
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"
824
def value_to_set(self):
828
def value_to_set(self, value):
829
"When setting, convert value from a datetime.timedelta"
830
self._vts = int(round(value.total_seconds() * 1000))
833
class SetTimeout(MillisecondsPropertyValueArgument):
837
class SetExtendedTimeout(MillisecondsPropertyValueArgument):
838
propname = "ExtendedTimeout"
841
class SetInterval(MillisecondsPropertyValueArgument):
842
propname = "Interval"
845
class SetApprovalDelay(MillisecondsPropertyValueArgument):
846
propname = "ApprovalDelay"
849
class SetApprovalDuration(MillisecondsPropertyValueArgument):
850
propname = "ApprovalDuration"
1134
1171
options = self.parser.parse_args(args)
1135
1172
check_option_syntax(self.parser, options)
1136
1173
commands = commands_from_options(options)
1137
self.assertEqual(len(commands), 1)
1174
self.assertEqual(1, len(commands))
1138
1175
command = commands[0]
1139
1176
self.assertIsInstance(command, command_cls)
1140
1177
for key, value in cmd_attrs.items():
1141
self.assertEqual(getattr(command, key), value)
1178
self.assertEqual(value, getattr(command, key))
1143
1180
def test_is_enabled_short(self):
1144
self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1181
self.assert_command_from_args(["-V", "foo"],
1146
1184
def test_approve(self):
1147
1185
self.assert_command_from_args(["--approve", "foo"],
1150
1188
def test_approve_short(self):
1151
self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1189
self.assert_command_from_args(["-A", "foo"], command.Approve)
1153
1191
def test_deny(self):
1154
self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1192
self.assert_command_from_args(["--deny", "foo"], command.Deny)
1156
1194
def test_deny_short(self):
1157
self.assert_command_from_args(["-D", "foo"], DenyCmd)
1195
self.assert_command_from_args(["-D", "foo"], command.Deny)
1159
1197
def test_remove(self):
1160
1198
self.assert_command_from_args(["--remove", "foo"],
1163
1201
def test_deny_before_remove(self):
1164
1202
options = self.parser.parse_args(["--deny", "--remove",
1166
1204
check_option_syntax(self.parser, options)
1167
1205
commands = commands_from_options(options)
1168
self.assertEqual(len(commands), 2)
1169
self.assertIsInstance(commands[0], DenyCmd)
1170
self.assertIsInstance(commands[1], RemoveCmd)
1206
self.assertEqual(2, len(commands))
1207
self.assertIsInstance(commands[0], command.Deny)
1208
self.assertIsInstance(commands[1], command.Remove)
1172
1210
def test_deny_before_remove_reversed(self):
1173
1211
options = self.parser.parse_args(["--remove", "--deny",
1175
1213
check_option_syntax(self.parser, options)
1176
1214
commands = commands_from_options(options)
1177
self.assertEqual(len(commands), 2)
1178
self.assertIsInstance(commands[0], DenyCmd)
1179
self.assertIsInstance(commands[1], RemoveCmd)
1215
self.assertEqual(2, len(commands))
1216
self.assertIsInstance(commands[0], command.Deny)
1217
self.assertIsInstance(commands[1], command.Remove)
1181
1219
def test_remove_short(self):
1182
self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1220
self.assert_command_from_args(["-r", "foo"], command.Remove)
1184
1222
def test_dump_json(self):
1185
self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1223
self.assert_command_from_args(["--dump-json"],
1187
1226
def test_enable(self):
1188
self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1227
self.assert_command_from_args(["--enable", "foo"],
1190
1230
def test_enable_short(self):
1191
self.assert_command_from_args(["-e", "foo"], EnableCmd)
1231
self.assert_command_from_args(["-e", "foo"], command.Enable)
1193
1233
def test_disable(self):
1194
1234
self.assert_command_from_args(["--disable", "foo"],
1197
1237
def test_disable_short(self):
1198
self.assert_command_from_args(["-d", "foo"], DisableCmd)
1238
self.assert_command_from_args(["-d", "foo"], command.Disable)
1200
1240
def test_bump_timeout(self):
1201
1241
self.assert_command_from_args(["--bump-timeout", "foo"],
1242
command.BumpTimeout)
1204
1244
def test_bump_timeout_short(self):
1205
self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1245
self.assert_command_from_args(["-b", "foo"],
1246
command.BumpTimeout)
1207
1248
def test_start_checker(self):
1208
1249
self.assert_command_from_args(["--start-checker", "foo"],
1250
command.StartChecker)
1211
1252
def test_stop_checker(self):
1212
1253
self.assert_command_from_args(["--stop-checker", "foo"],
1254
command.StopChecker)
1215
1256
def test_approve_by_default(self):
1216
1257
self.assert_command_from_args(["--approve-by-default", "foo"],
1217
ApproveByDefaultCmd)
1258
command.ApproveByDefault)
1219
1260
def test_deny_by_default(self):
1220
1261
self.assert_command_from_args(["--deny-by-default", "foo"],
1262
command.DenyByDefault)
1223
1264
def test_checker(self):
1224
1265
self.assert_command_from_args(["--checker", ":", "foo"],
1225
SetCheckerCmd, value_to_set=":")
1227
1269
def test_checker_empty(self):
1228
1270
self.assert_command_from_args(["--checker", "", "foo"],
1229
SetCheckerCmd, value_to_set="")
1231
1274
def test_checker_short(self):
1232
1275
self.assert_command_from_args(["-c", ":", "foo"],
1233
SetCheckerCmd, value_to_set=":")
1235
1279
def test_host(self):
1236
1280
self.assert_command_from_args(["--host", "foo.example.org",
1281
"foo"], command.SetHost,
1238
1282
value_to_set="foo.example.org")
1240
1284
def test_host_short(self):
1241
1285
self.assert_command_from_args(["-H", "foo.example.org",
1286
"foo"], command.SetHost,
1243
1287
value_to_set="foo.example.org")
1245
1289
def test_secret_devnull(self):
1246
1290
self.assert_command_from_args(["--secret", os.path.devnull,
1247
"foo"], SetSecretCmd,
1291
"foo"], command.SetSecret,
1248
1292
value_to_set=b"")
1250
1294
def test_secret_tempfile(self):
1417
class TestIsEnabledCmd(TestCmd):
1418
def test_is_enabled(self):
1419
self.assertTrue(all(IsEnabledCmd().is_enabled(client,
1421
for client, properties
1422
in self.clients.items()))
1460
class TestBaseCommands(TestCommand):
1424
def test_is_enabled_run_exits_successfully(self):
1462
def test_IsEnabled_exits_successfully(self):
1425
1463
with self.assertRaises(SystemExit) as e:
1426
IsEnabledCmd().run(self.one_client)
1464
command.IsEnabled().run(self.one_client)
1427
1465
if e.exception.code is not None:
1428
self.assertEqual(e.exception.code, 0)
1466
self.assertEqual(0, e.exception.code)
1430
1468
self.assertIsNone(e.exception.code)
1432
def test_is_enabled_run_exits_with_failure(self):
1470
def test_IsEnabled_exits_with_failure(self):
1433
1471
self.client.attributes["Enabled"] = dbus.Boolean(False)
1434
1472
with self.assertRaises(SystemExit) as e:
1435
IsEnabledCmd().run(self.one_client)
1473
command.IsEnabled().run(self.one_client)
1436
1474
if isinstance(e.exception.code, int):
1437
self.assertNotEqual(e.exception.code, 0)
1475
self.assertNotEqual(0, e.exception.code)
1439
1477
self.assertIsNotNone(e.exception.code)
1442
class TestApproveCmd(TestCmd):
1443
def test_approve(self):
1444
ApproveCmd().run(self.clients, self.bus)
1479
def test_Approve(self):
1480
command.Approve().run(self.clients, self.bus)
1445
1481
for clientpath in self.clients:
1446
1482
client = self.bus.get_object(dbus_busname, clientpath)
1447
1483
self.assertIn(("Approve", (True, client_dbus_interface)),
1451
class TestDenyCmd(TestCmd):
1452
def test_deny(self):
1453
DenyCmd().run(self.clients, self.bus)
1486
def test_Deny(self):
1487
command.Deny().run(self.clients, self.bus)
1454
1488
for clientpath in self.clients:
1455
1489
client = self.bus.get_object(dbus_busname, clientpath)
1456
1490
self.assertIn(("Approve", (False, client_dbus_interface)),
1460
class TestRemoveCmd(TestCmd):
1461
def test_remove(self):
1493
def test_Remove(self):
1462
1494
class MockMandos(object):
1463
1495
def __init__(self):
1464
1496
self.calls = []
1465
1497
def RemoveClient(self, dbus_path):
1466
1498
self.calls.append(("RemoveClient", (dbus_path,)))
1467
1499
mandos = MockMandos()
1468
super(TestRemoveCmd, self).setUp()
1469
RemoveCmd().run(self.clients, self.bus, mandos)
1470
self.assertEqual(len(mandos.calls), 2)
1500
command.Remove().run(self.clients, self.bus, mandos)
1471
1501
for clientpath in self.clients:
1472
1502
self.assertIn(("RemoveClient", (clientpath,)),
1476
class TestDumpJSONCmd(TestCmd):
1478
self.expected_json = {
1481
"KeyID": ("92ed150794387c03ce684574b1139a65"
1482
"94a34f895daaaf09fd8ea90a27cddb12"),
1483
"Host": "foo.example.org",
1486
"LastCheckedOK": "2019-02-03T00:00:00",
1487
"Created": "2019-01-02T00:00:00",
1489
"Fingerprint": ("778827225BA7DE539C5A"
1490
"7CFA59CFF7CDBD9A5920"),
1491
"CheckerRunning": False,
1492
"LastEnabled": "2019-01-03T00:00:00",
1493
"ApprovalPending": False,
1494
"ApprovedByDefault": True,
1495
"LastApprovalRequest": "",
1497
"ApprovalDuration": 1000,
1498
"Checker": "fping -q -- %(host)s",
1499
"ExtendedTimeout": 900000,
1500
"Expires": "2019-02-04T00:00:00",
1501
"LastCheckerStatus": 0,
1505
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1506
"6ab612cff5ad227247e46c2b020f441c"),
1507
"Host": "192.0.2.3",
1510
"LastCheckedOK": "2019-02-04T00:00:00",
1511
"Created": "2019-01-03T00:00:00",
1513
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1514
"F547B3A107558FCA3A27"),
1515
"CheckerRunning": True,
1516
"LastEnabled": "2019-01-04T00:00:00",
1517
"ApprovalPending": False,
1518
"ApprovedByDefault": False,
1519
"LastApprovalRequest": "2019-01-03T00:00:00",
1520
"ApprovalDelay": 30000,
1521
"ApprovalDuration": 93785000,
1523
"ExtendedTimeout": 900000,
1524
"Expires": "2019-02-05T00:00:00",
1525
"LastCheckerStatus": -2,
1528
return super(TestDumpJSONCmd, self).setUp()
1530
def test_normal(self):
1531
output = DumpJSONCmd().output(self.clients.values())
1508
"KeyID": ("92ed150794387c03ce684574b1139a65"
1509
"94a34f895daaaf09fd8ea90a27cddb12"),
1510
"Host": "foo.example.org",
1513
"LastCheckedOK": "2019-02-03T00:00:00",
1514
"Created": "2019-01-02T00:00:00",
1516
"Fingerprint": ("778827225BA7DE539C5A"
1517
"7CFA59CFF7CDBD9A5920"),
1518
"CheckerRunning": False,
1519
"LastEnabled": "2019-01-03T00:00:00",
1520
"ApprovalPending": False,
1521
"ApprovedByDefault": True,
1522
"LastApprovalRequest": "",
1524
"ApprovalDuration": 1000,
1525
"Checker": "fping -q -- %(host)s",
1526
"ExtendedTimeout": 900000,
1527
"Expires": "2019-02-04T00:00:00",
1528
"LastCheckerStatus": 0,
1532
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1533
"6ab612cff5ad227247e46c2b020f441c"),
1534
"Host": "192.0.2.3",
1537
"LastCheckedOK": "2019-02-04T00:00:00",
1538
"Created": "2019-01-03T00:00:00",
1540
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1541
"F547B3A107558FCA3A27"),
1542
"CheckerRunning": True,
1543
"LastEnabled": "2019-01-04T00:00:00",
1544
"ApprovalPending": False,
1545
"ApprovedByDefault": False,
1546
"LastApprovalRequest": "2019-01-03T00:00:00",
1547
"ApprovalDelay": 30000,
1548
"ApprovalDuration": 93785000,
1550
"ExtendedTimeout": 900000,
1551
"Expires": "2019-02-05T00:00:00",
1552
"LastCheckerStatus": -2,
1556
def test_DumpJSON_normal(self):
1557
output = command.DumpJSON().output(self.clients.values())
1532
1558
json_data = json.loads(output)
1533
self.assertDictEqual(json_data, self.expected_json)
1559
self.assertDictEqual(self.expected_json, json_data)
1535
def test_one_client(self):
1536
output = DumpJSONCmd().output(self.one_client.values())
1561
def test_DumpJSON_one_client(self):
1562
output = command.DumpJSON().output(self.one_client.values())
1537
1563
json_data = json.loads(output)
1538
1564
expected_json = {"foo": self.expected_json["foo"]}
1539
self.assertDictEqual(json_data, expected_json)
1542
class TestPrintTableCmd(TestCmd):
1543
def test_normal(self):
1544
output = PrintTableCmd().output(self.clients.values())
1565
self.assertDictEqual(expected_json, json_data)
1567
def test_PrintTable_normal(self):
1568
output = command.PrintTable().output(self.clients.values())
1545
1569
expected_output = "\n".join((
1546
1570
"Name Enabled Timeout Last Successful Check",
1547
1571
"foo Yes 00:05:00 2019-02-03T00:00:00 ",
1548
1572
"barbar Yes 00:05:00 2019-02-04T00:00:00 ",
1550
self.assertEqual(output, expected_output)
1574
self.assertEqual(expected_output, output)
1552
def test_verbose(self):
1553
output = PrintTableCmd(verbose=True).output(
1576
def test_PrintTable_verbose(self):
1577
output = command.PrintTable(verbose=True).output(
1554
1578
self.clients.values())