479
481
if options.is_enabled:
480
commands.append(IsEnabledCmd())
482
commands.append(command.IsEnabled())
482
484
if options.approve:
483
commands.append(ApproveCmd())
485
commands.append(command.Approve())
486
commands.append(DenyCmd())
488
commands.append(command.Deny())
488
490
if options.remove:
489
commands.append(RemoveCmd())
491
commands.append(command.Remove())
491
493
if options.dump_json:
492
commands.append(DumpJSONCmd())
494
commands.append(command.DumpJSON())
494
496
if options.enable:
495
commands.append(EnableCmd())
497
commands.append(command.Enable())
497
499
if options.disable:
498
commands.append(DisableCmd())
500
commands.append(command.Disable())
500
502
if options.bump_timeout:
501
commands.append(BumpTimeoutCmd())
503
commands.append(command.BumpTimeout())
503
505
if options.start_checker:
504
commands.append(StartCheckerCmd())
506
commands.append(command.StartChecker())
506
508
if options.stop_checker:
507
commands.append(StopCheckerCmd())
509
commands.append(command.StopChecker())
509
511
if options.approved_by_default is not None:
510
512
if options.approved_by_default:
511
commands.append(ApproveByDefaultCmd())
513
commands.append(command.ApproveByDefault())
513
commands.append(DenyByDefaultCmd())
515
commands.append(command.DenyByDefault())
515
517
if options.checker is not None:
516
commands.append(SetCheckerCmd(options.checker))
518
commands.append(command.SetChecker(options.checker))
518
520
if options.host is not None:
519
commands.append(SetHostCmd(options.host))
521
commands.append(command.SetHost(options.host))
521
523
if options.secret is not None:
522
commands.append(SetSecretCmd(options.secret))
524
commands.append(command.SetSecret(options.secret))
524
526
if options.timeout is not None:
525
commands.append(SetTimeoutCmd(options.timeout))
527
commands.append(command.SetTimeout(options.timeout))
527
529
if options.extended_timeout:
529
SetExtendedTimeoutCmd(options.extended_timeout))
531
command.SetExtendedTimeout(options.extended_timeout))
531
533
if options.interval is not None:
532
commands.append(SetIntervalCmd(options.interval))
534
commands.append(command.SetInterval(options.interval))
534
536
if options.approval_delay is not None:
535
commands.append(SetApprovalDelayCmd(options.approval_delay))
538
command.SetApprovalDelay(options.approval_delay))
537
540
if options.approval_duration is not None:
539
SetApprovalDurationCmd(options.approval_duration))
542
command.SetApprovalDuration(options.approval_duration))
541
544
# If no command option has been given, show table of clients,
542
545
# optionally verbosely
544
commands.append(PrintTableCmd(verbose=options.verbose))
547
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__
552
class command(object):
553
"""A namespace for command classes"""
556
"""Abstract base class for commands"""
557
def run(self, clients, bus=None, mandos=None):
558
"""Normal commands should implement run_on_one_client(),
559
but commands which want to operate on all clients at the same time can
560
override this run() method instead.
563
for clientpath, properties in clients.items():
564
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
565
dbus_busname, str(clientpath))
566
client = bus.get_object(dbus_busname, clientpath)
567
self.run_on_one_client(client, properties)
570
class IsEnabled(Base):
571
def run(self, clients, bus=None, mandos=None):
572
client, properties = next(iter(clients.items()))
573
if self.is_enabled(client, properties):
576
def is_enabled(self, client, properties):
577
return properties["Enabled"]
581
def run_on_one_client(self, client, properties):
582
log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
583
client.__dbus_object_path__,
584
client_dbus_interface)
585
client.Approve(dbus.Boolean(True),
586
dbus_interface=client_dbus_interface)
590
def run_on_one_client(self, client, properties):
591
log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
592
client.__dbus_object_path__,
593
client_dbus_interface)
594
client.Approve(dbus.Boolean(False),
595
dbus_interface=client_dbus_interface)
599
def run_on_one_client(self, client, properties):
600
log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)",
601
dbus_busname, server_dbus_path,
602
server_dbus_interface,
603
str(client.__dbus_object_path__))
604
self.mandos.RemoveClient(client.__dbus_object_path__)
608
"""Abstract class for commands outputting client details"""
609
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
610
"Created", "Interval", "Host", "KeyID",
611
"Fingerprint", "CheckerRunning",
612
"LastEnabled", "ApprovalPending",
613
"ApprovedByDefault", "LastApprovalRequest",
614
"ApprovalDelay", "ApprovalDuration",
615
"Checker", "ExtendedTimeout", "Expires",
619
class DumpJSON(Output):
620
def run(self, clients, bus=None, mandos=None):
621
data = {client["Name"]:
622
{key: self.dbus_boolean_to_bool(client[key])
623
for key in self.all_keywords}
624
for client in clients.values()}
625
print(json.dumps(data, indent=4, separators=(',', ': ')))
628
def dbus_boolean_to_bool(value):
629
if isinstance(value, dbus.Boolean):
634
class PrintTable(Output):
635
def __init__(self, verbose=False):
636
self.verbose = verbose
638
def run(self, clients, bus=None, mandos=None):
639
default_keywords = ("Name", "Enabled", "Timeout",
641
keywords = default_keywords
643
keywords = self.all_keywords
644
print(self.TableOfClients(clients.values(), keywords))
646
class TableOfClients(object):
649
"Enabled": "Enabled",
650
"Timeout": "Timeout",
651
"LastCheckedOK": "Last Successful Check",
652
"LastApprovalRequest": "Last Approval Request",
653
"Created": "Created",
654
"Interval": "Interval",
656
"Fingerprint": "Fingerprint",
658
"CheckerRunning": "Check Is Running",
659
"LastEnabled": "Last Enabled",
660
"ApprovalPending": "Approval Is Pending",
661
"ApprovedByDefault": "Approved By Default",
662
"ApprovalDelay": "Approval Delay",
663
"ApprovalDuration": "Approval Duration",
664
"Checker": "Checker",
665
"ExtendedTimeout": "Extended Timeout",
666
"Expires": "Expires",
667
"LastCheckerStatus": "Last Checker Status",
670
def __init__(self, clients, keywords):
671
self.clients = clients
672
self.keywords = keywords
674
674
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
675
return "\n".join(self.rows())
677
if sys.version_info.major == 2:
678
__unicode__ = __str__
680
return str(self).encode(
681
locale.getpreferredencoding())
684
format_string = self.row_formatting_string()
685
rows = [self.header_line(format_string)]
686
rows.extend(self.client_line(client, format_string)
687
for client in self.clients)
690
def row_formatting_string(self):
691
"Format string used to format table rows"
692
return " ".join("{{{key}:{width}}}".format(
693
width=max(len(self.tableheaders[key]),
694
*(len(self.string_from_client(client,
696
for client in self.clients)),
698
for key in self.keywords)
700
def string_from_client(self, client, key):
701
return self.valuetostring(client[key], key)
704
def valuetostring(cls, value, keyword):
705
if isinstance(value, dbus.Boolean):
706
return "Yes" if value else "No"
707
if keyword in ("Timeout", "Interval", "ApprovalDelay",
708
"ApprovalDuration", "ExtendedTimeout"):
709
return cls.milliseconds_to_string(value)
712
def header_line(self, format_string):
713
return format_string.format(**self.tableheaders)
715
def client_line(self, client, format_string):
716
return format_string.format(
717
**{key: self.string_from_client(client, key)
718
for key in self.keywords})
721
def milliseconds_to_string(ms):
722
td = datetime.timedelta(0, 0, 0, ms)
723
return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
724
.format(days="{}T".format(td.days)
726
hours=td.seconds // 3600,
727
minutes=(td.seconds % 3600) // 60,
728
seconds=td.seconds % 60))
731
class Property(Base):
732
"Abstract class for Actions for setting one client property"
734
def run_on_one_client(self, client, properties):
735
"""Set the Client's D-Bus property"""
736
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
737
client.__dbus_object_path__,
738
dbus.PROPERTIES_IFACE, client_dbus_interface,
739
self.propname, self.value_to_set
740
if not isinstance(self.value_to_set,
742
else bool(self.value_to_set))
743
client.Set(client_dbus_interface, self.propname,
745
dbus_interface=dbus.PROPERTIES_IFACE)
749
raise NotImplementedError()
752
class Enable(Property):
754
value_to_set = dbus.Boolean(True)
757
class Disable(Property):
759
value_to_set = dbus.Boolean(False)
762
class BumpTimeout(Property):
763
propname = "LastCheckedOK"
767
class StartChecker(Property):
768
propname = "CheckerRunning"
769
value_to_set = dbus.Boolean(True)
772
class StopChecker(Property):
773
propname = "CheckerRunning"
774
value_to_set = dbus.Boolean(False)
777
class ApproveByDefault(Property):
778
propname = "ApprovedByDefault"
779
value_to_set = dbus.Boolean(True)
782
class DenyByDefault(Property):
783
propname = "ApprovedByDefault"
784
value_to_set = dbus.Boolean(False)
787
class PropertyValue(Property):
788
"Abstract class for Property recieving a value as argument"
789
def __init__(self, value):
790
self.value_to_set = value
793
class SetChecker(PropertyValue):
797
class SetHost(PropertyValue):
801
class SetSecret(PropertyValue):
805
def value_to_set(self):
809
def value_to_set(self, value):
810
"""When setting, read data from supplied file object"""
811
self._vts = value.read()
815
class MillisecondsPropertyValueArgument(PropertyValue):
816
"""Abstract class for PropertyValue taking a value argument as
809
817
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"
820
def value_to_set(self):
824
def value_to_set(self, value):
825
"When setting, convert value from a datetime.timedelta"
826
self._vts = int(round(value.total_seconds() * 1000))
829
class SetTimeout(MillisecondsPropertyValueArgument):
833
class SetExtendedTimeout(MillisecondsPropertyValueArgument):
834
propname = "ExtendedTimeout"
837
class SetInterval(MillisecondsPropertyValueArgument):
838
propname = "Interval"
841
class SetApprovalDelay(MillisecondsPropertyValueArgument):
842
propname = "ApprovalDelay"
845
class SetApprovalDuration(MillisecondsPropertyValueArgument):
846
propname = "ApprovalDuration"
1134
1167
options = self.parser.parse_args(args)
1135
1168
check_option_syntax(self.parser, options)
1136
1169
commands = commands_from_options(options)
1137
self.assertEqual(len(commands), 1)
1170
self.assertEqual(1, len(commands))
1138
1171
command = commands[0]
1139
1172
self.assertIsInstance(command, command_cls)
1140
1173
for key, value in cmd_attrs.items():
1141
self.assertEqual(getattr(command, key), value)
1174
self.assertEqual(value, getattr(command, key))
1143
1176
def test_is_enabled_short(self):
1144
self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1177
self.assert_command_from_args(["-V", "client"],
1146
1180
def test_approve(self):
1147
self.assert_command_from_args(["--approve", "foo"],
1181
self.assert_command_from_args(["--approve", "client"],
1150
1184
def test_approve_short(self):
1151
self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1185
self.assert_command_from_args(["-A", "client"],
1153
1188
def test_deny(self):
1154
self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1189
self.assert_command_from_args(["--deny", "client"],
1156
1192
def test_deny_short(self):
1157
self.assert_command_from_args(["-D", "foo"], DenyCmd)
1193
self.assert_command_from_args(["-D", "client"], command.Deny)
1159
1195
def test_remove(self):
1160
self.assert_command_from_args(["--remove", "foo"],
1196
self.assert_command_from_args(["--remove", "client"],
1163
1199
def test_deny_before_remove(self):
1164
1200
options = self.parser.parse_args(["--deny", "--remove",
1166
1202
check_option_syntax(self.parser, options)
1167
1203
commands = commands_from_options(options)
1168
self.assertEqual(len(commands), 2)
1169
self.assertIsInstance(commands[0], DenyCmd)
1170
self.assertIsInstance(commands[1], RemoveCmd)
1204
self.assertEqual(2, len(commands))
1205
self.assertIsInstance(commands[0], command.Deny)
1206
self.assertIsInstance(commands[1], command.Remove)
1172
1208
def test_deny_before_remove_reversed(self):
1173
1209
options = self.parser.parse_args(["--remove", "--deny",
1175
1211
check_option_syntax(self.parser, options)
1176
1212
commands = commands_from_options(options)
1177
self.assertEqual(len(commands), 2)
1178
self.assertIsInstance(commands[0], DenyCmd)
1179
self.assertIsInstance(commands[1], RemoveCmd)
1213
self.assertEqual(2, len(commands))
1214
self.assertIsInstance(commands[0], command.Deny)
1215
self.assertIsInstance(commands[1], command.Remove)
1181
1217
def test_remove_short(self):
1182
self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1218
self.assert_command_from_args(["-r", "client"],
1184
1221
def test_dump_json(self):
1185
self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1222
self.assert_command_from_args(["--dump-json"],
1187
1225
def test_enable(self):
1188
self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1226
self.assert_command_from_args(["--enable", "client"],
1190
1229
def test_enable_short(self):
1191
self.assert_command_from_args(["-e", "foo"], EnableCmd)
1230
self.assert_command_from_args(["-e", "client"],
1193
1233
def test_disable(self):
1194
self.assert_command_from_args(["--disable", "foo"],
1234
self.assert_command_from_args(["--disable", "client"],
1197
1237
def test_disable_short(self):
1198
self.assert_command_from_args(["-d", "foo"], DisableCmd)
1238
self.assert_command_from_args(["-d", "client"],
1200
1241
def test_bump_timeout(self):
1201
self.assert_command_from_args(["--bump-timeout", "foo"],
1242
self.assert_command_from_args(["--bump-timeout", "client"],
1243
command.BumpTimeout)
1204
1245
def test_bump_timeout_short(self):
1205
self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1246
self.assert_command_from_args(["-b", "client"],
1247
command.BumpTimeout)
1207
1249
def test_start_checker(self):
1208
self.assert_command_from_args(["--start-checker", "foo"],
1250
self.assert_command_from_args(["--start-checker", "client"],
1251
command.StartChecker)
1211
1253
def test_stop_checker(self):
1212
self.assert_command_from_args(["--stop-checker", "foo"],
1254
self.assert_command_from_args(["--stop-checker", "client"],
1255
command.StopChecker)
1215
1257
def test_approve_by_default(self):
1216
self.assert_command_from_args(["--approve-by-default", "foo"],
1217
ApproveByDefaultCmd)
1258
self.assert_command_from_args(["--approve-by-default",
1260
command.ApproveByDefault)
1219
1262
def test_deny_by_default(self):
1220
self.assert_command_from_args(["--deny-by-default", "foo"],
1263
self.assert_command_from_args(["--deny-by-default", "client"],
1264
command.DenyByDefault)
1223
1266
def test_checker(self):
1224
self.assert_command_from_args(["--checker", ":", "foo"],
1225
SetCheckerCmd, value_to_set=":")
1267
self.assert_command_from_args(["--checker", ":", "client"],
1227
1271
def test_checker_empty(self):
1228
self.assert_command_from_args(["--checker", "", "foo"],
1229
SetCheckerCmd, value_to_set="")
1272
self.assert_command_from_args(["--checker", "", "client"],
1231
1276
def test_checker_short(self):
1232
self.assert_command_from_args(["-c", ":", "foo"],
1233
SetCheckerCmd, value_to_set=":")
1277
self.assert_command_from_args(["-c", ":", "client"],
1235
1281
def test_host(self):
1236
self.assert_command_from_args(["--host", "foo.example.org",
1238
value_to_set="foo.example.org")
1282
self.assert_command_from_args(
1283
["--host", "client.example.org", "client"],
1284
command.SetHost, value_to_set="client.example.org")
1240
1286
def test_host_short(self):
1241
self.assert_command_from_args(["-H", "foo.example.org",
1243
value_to_set="foo.example.org")
1287
self.assert_command_from_args(
1288
["-H", "client.example.org", "client"], command.SetHost,
1289
value_to_set="client.example.org")
1245
1291
def test_secret_devnull(self):
1246
1292
self.assert_command_from_args(["--secret", os.path.devnull,
1247
"foo"], SetSecretCmd,
1293
"client"], command.SetSecret,
1248
1294
value_to_set=b"")
1250
1296
def test_secret_tempfile(self):
1394
1440
LastCheckerStatus=-2)
1395
1441
self.clients = collections.OrderedDict(
1397
("/clients/foo", self.client.attributes),
1398
("/clients/barbar", self.other_client.attributes),
1443
(self.client.__dbus_object_path__,
1444
self.client.attributes),
1445
(self.other_client.__dbus_object_path__,
1446
self.other_client.attributes),
1400
self.one_client = {"/clients/foo": self.client.attributes}
1448
self.one_client = {self.client.__dbus_object_path__:
1449
self.client.attributes}
1453
class MockBus(object):
1406
1455
def get_object(client_bus_name, path):
1407
self.assertEqual(client_bus_name, dbus_busname)
1409
# Note: "self" here is the TestCmd instance, not
1410
# the Bus instance, since this is a static method!
1411
"/clients/foo": self.client,
1412
"/clients/barbar": self.other_client,
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()))
1424
def test_is_enabled_run_exits_successfully(self):
1456
self.assertEqual(dbus_busname, client_bus_name)
1457
# Note: "self" here is the TestCmd instance, not the
1458
# MockBus instance, since this is a static method!
1459
if path == self.client.__dbus_object_path__:
1461
elif path == self.other_client.__dbus_object_path__:
1462
return self.other_client
1466
class TestBaseCommands(TestCommand):
1468
def test_IsEnabled_exits_successfully(self):
1425
1469
with self.assertRaises(SystemExit) as e:
1426
IsEnabledCmd().run(self.one_client)
1470
command.IsEnabled().run(self.one_client)
1427
1471
if e.exception.code is not None:
1428
self.assertEqual(e.exception.code, 0)
1472
self.assertEqual(0, e.exception.code)
1430
1474
self.assertIsNone(e.exception.code)
1432
def test_is_enabled_run_exits_with_failure(self):
1476
def test_IsEnabled_exits_with_failure(self):
1433
1477
self.client.attributes["Enabled"] = dbus.Boolean(False)
1434
1478
with self.assertRaises(SystemExit) as e:
1435
IsEnabledCmd().run(self.one_client)
1479
command.IsEnabled().run(self.one_client)
1436
1480
if isinstance(e.exception.code, int):
1437
self.assertNotEqual(e.exception.code, 0)
1481
self.assertNotEqual(0, e.exception.code)
1439
1483
self.assertIsNotNone(e.exception.code)
1442
class TestApproveCmd(TestCmd):
1443
def test_approve(self):
1444
ApproveCmd().run(self.clients, self.bus)
1485
def test_Approve(self):
1486
command.Approve().run(self.clients, self.bus)
1445
1487
for clientpath in self.clients:
1446
1488
client = self.bus.get_object(dbus_busname, clientpath)
1447
1489
self.assertIn(("Approve", (True, client_dbus_interface)),
1451
class TestDenyCmd(TestCmd):
1452
def test_deny(self):
1453
DenyCmd().run(self.clients, self.bus)
1492
def test_Deny(self):
1493
command.Deny().run(self.clients, self.bus)
1454
1494
for clientpath in self.clients:
1455
1495
client = self.bus.get_object(dbus_busname, clientpath)
1456
1496
self.assertIn(("Approve", (False, client_dbus_interface)),
1460
class TestRemoveCmd(TestCmd):
1461
def test_remove(self):
1462
class MockMandos(object):
1499
def test_Remove(self):
1500
class MandosSpy(object):
1463
1501
def __init__(self):
1464
1502
self.calls = []
1465
1503
def RemoveClient(self, dbus_path):
1466
1504
self.calls.append(("RemoveClient", (dbus_path,)))
1467
mandos = MockMandos()
1468
super(TestRemoveCmd, self).setUp()
1469
RemoveCmd().run(self.clients, self.bus, mandos)
1470
self.assertEqual(len(mandos.calls), 2)
1505
mandos = MandosSpy()
1506
command.Remove().run(self.clients, self.bus, mandos)
1471
1507
for clientpath in self.clients:
1472
1508
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())
1532
json_data = json.loads(output)
1533
self.assertDictEqual(json_data, self.expected_json)
1535
def test_one_client(self):
1536
output = DumpJSONCmd().output(self.one_client.values())
1537
json_data = json.loads(output)
1514
"KeyID": ("92ed150794387c03ce684574b1139a65"
1515
"94a34f895daaaf09fd8ea90a27cddb12"),
1516
"Host": "foo.example.org",
1519
"LastCheckedOK": "2019-02-03T00:00:00",
1520
"Created": "2019-01-02T00:00:00",
1522
"Fingerprint": ("778827225BA7DE539C5A"
1523
"7CFA59CFF7CDBD9A5920"),
1524
"CheckerRunning": False,
1525
"LastEnabled": "2019-01-03T00:00:00",
1526
"ApprovalPending": False,
1527
"ApprovedByDefault": True,
1528
"LastApprovalRequest": "",
1530
"ApprovalDuration": 1000,
1531
"Checker": "fping -q -- %(host)s",
1532
"ExtendedTimeout": 900000,
1533
"Expires": "2019-02-04T00:00:00",
1534
"LastCheckerStatus": 0,
1538
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1539
"6ab612cff5ad227247e46c2b020f441c"),
1540
"Host": "192.0.2.3",
1543
"LastCheckedOK": "2019-02-04T00:00:00",
1544
"Created": "2019-01-03T00:00:00",
1546
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1547
"F547B3A107558FCA3A27"),
1548
"CheckerRunning": True,
1549
"LastEnabled": "2019-01-04T00:00:00",
1550
"ApprovalPending": False,
1551
"ApprovedByDefault": False,
1552
"LastApprovalRequest": "2019-01-03T00:00:00",
1553
"ApprovalDelay": 30000,
1554
"ApprovalDuration": 93785000,
1556
"ExtendedTimeout": 900000,
1557
"Expires": "2019-02-05T00:00:00",
1558
"LastCheckerStatus": -2,
1562
def test_DumpJSON_normal(self):
1563
with self.capture_stdout_to_buffer() as buffer:
1564
command.DumpJSON().run(self.clients)
1565
json_data = json.loads(buffer.getvalue())
1566
self.assertDictEqual(self.expected_json, json_data)
1569
@contextlib.contextmanager
1570
def capture_stdout_to_buffer():
1571
capture_buffer = io.StringIO()
1572
old_stdout = sys.stdout
1573
sys.stdout = capture_buffer
1575
yield capture_buffer
1577
sys.stdout = old_stdout
1579
def test_DumpJSON_one_client(self):
1580
with self.capture_stdout_to_buffer() as buffer:
1581
command.DumpJSON().run(self.one_client)
1582
json_data = json.loads(buffer.getvalue())
1538
1583
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())
1584
self.assertDictEqual(expected_json, json_data)
1586
def test_PrintTable_normal(self):
1587
with self.capture_stdout_to_buffer() as buffer:
1588
command.PrintTable().run(self.clients)
1545
1589
expected_output = "\n".join((
1546
1590
"Name Enabled Timeout Last Successful Check",
1547
1591
"foo Yes 00:05:00 2019-02-03T00:00:00 ",
1548
1592
"barbar Yes 00:05:00 2019-02-04T00:00:00 ",
1550
self.assertEqual(output, expected_output)
1594
self.assertEqual(expected_output, buffer.getvalue())
1552
def test_verbose(self):
1553
output = PrintTableCmd(verbose=True).output(
1554
self.clients.values())
1596
def test_PrintTable_verbose(self):
1597
with self.capture_stdout_to_buffer() as buffer:
1598
command.PrintTable(verbose=True).run(self.clients)