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.
559
for clientpath, properties in clients.items():
560
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
561
dbus_busname, str(clientpath))
562
client = bus.get_object(dbus_busname, clientpath)
563
self.run_on_one_client(client, properties)
566
class IsEnabled(Base):
567
def run(self, clients, bus=None, mandos=None):
568
client, properties = next(iter(clients.items()))
569
if self.is_enabled(client, properties):
572
def is_enabled(self, client, properties):
573
return properties["Enabled"]
577
def run_on_one_client(self, client, properties):
578
log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
579
client.__dbus_object_path__,
580
client_dbus_interface)
581
client.Approve(dbus.Boolean(True),
582
dbus_interface=client_dbus_interface)
586
def run_on_one_client(self, client, properties):
587
log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
588
client.__dbus_object_path__,
589
client_dbus_interface)
590
client.Approve(dbus.Boolean(False),
591
dbus_interface=client_dbus_interface)
595
def run(self, clients, bus, mandos):
596
for clientpath in clients.keys():
597
log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)",
598
dbus_busname, server_dbus_path,
599
server_dbus_interface, clientpath)
600
mandos.RemoveClient(clientpath)
604
"""Abstract class for commands outputting client details"""
605
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
606
"Created", "Interval", "Host", "KeyID",
607
"Fingerprint", "CheckerRunning",
608
"LastEnabled", "ApprovalPending",
609
"ApprovedByDefault", "LastApprovalRequest",
610
"ApprovalDelay", "ApprovalDuration",
611
"Checker", "ExtendedTimeout", "Expires",
615
class DumpJSON(Output):
616
def run(self, clients, bus=None, mandos=None):
617
data = {client["Name"]:
618
{key: self.dbus_boolean_to_bool(client[key])
619
for key in self.all_keywords}
620
for client in clients.values()}
621
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})
624
def dbus_boolean_to_bool(value):
625
if isinstance(value, dbus.Boolean):
630
class PrintTable(Output):
631
def __init__(self, verbose=False):
632
self.verbose = verbose
634
def run(self, clients, bus=None, mandos=None):
635
default_keywords = ("Name", "Enabled", "Timeout",
637
keywords = default_keywords
639
keywords = self.all_keywords
640
print(self.TableOfClients(clients.values(), keywords))
642
class TableOfClients(object):
645
"Enabled": "Enabled",
646
"Timeout": "Timeout",
647
"LastCheckedOK": "Last Successful Check",
648
"LastApprovalRequest": "Last Approval Request",
649
"Created": "Created",
650
"Interval": "Interval",
652
"Fingerprint": "Fingerprint",
654
"CheckerRunning": "Check Is Running",
655
"LastEnabled": "Last Enabled",
656
"ApprovalPending": "Approval Is Pending",
657
"ApprovedByDefault": "Approved By Default",
658
"ApprovalDelay": "Approval Delay",
659
"ApprovalDuration": "Approval Duration",
660
"Checker": "Checker",
661
"ExtendedTimeout": "Extended Timeout",
662
"Expires": "Expires",
663
"LastCheckerStatus": "Last Checker Status",
666
def __init__(self, clients, keywords):
667
self.clients = clients
668
self.keywords = keywords
671
return "\n".join(self.rows())
673
if sys.version_info.major == 2:
674
__unicode__ = __str__
676
return str(self).encode(
677
locale.getpreferredencoding())
680
format_string = self.row_formatting_string()
681
rows = [self.header_line(format_string)]
682
rows.extend(self.client_line(client, format_string)
683
for client in self.clients)
686
def row_formatting_string(self):
687
"Format string used to format table rows"
688
return " ".join("{{{key}:{width}}}".format(
689
width=max(len(self.tableheaders[key]),
690
*(len(self.string_from_client(client,
692
for client in self.clients)),
694
for key in self.keywords)
696
def string_from_client(self, client, key):
697
return self.valuetostring(client[key], key)
700
def valuetostring(cls, value, keyword):
701
if isinstance(value, dbus.Boolean):
702
return "Yes" if value else "No"
703
if keyword in ("Timeout", "Interval", "ApprovalDelay",
704
"ApprovalDuration", "ExtendedTimeout"):
705
return cls.milliseconds_to_string(value)
708
def header_line(self, format_string):
709
return format_string.format(**self.tableheaders)
711
def client_line(self, client, format_string):
712
return format_string.format(
713
**{key: self.string_from_client(client, key)
714
for key in self.keywords})
717
def milliseconds_to_string(ms):
718
td = datetime.timedelta(0, 0, 0, ms)
719
return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
720
.format(days="{}T".format(td.days)
722
hours=td.seconds // 3600,
723
minutes=(td.seconds % 3600) // 60,
724
seconds=td.seconds % 60))
727
class PropertySetter(Base):
728
"Abstract class for Actions for setting one client property"
730
def run_on_one_client(self, client, properties):
731
"""Set the Client's D-Bus property"""
732
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
733
client.__dbus_object_path__,
734
dbus.PROPERTIES_IFACE, client_dbus_interface,
735
self.propname, self.value_to_set
736
if not isinstance(self.value_to_set,
738
else bool(self.value_to_set))
739
client.Set(client_dbus_interface, self.propname,
741
dbus_interface=dbus.PROPERTIES_IFACE)
745
raise NotImplementedError()
748
class Enable(PropertySetter):
750
value_to_set = dbus.Boolean(True)
753
class Disable(PropertySetter):
755
value_to_set = dbus.Boolean(False)
758
class BumpTimeout(PropertySetter):
759
propname = "LastCheckedOK"
763
class StartChecker(PropertySetter):
764
propname = "CheckerRunning"
765
value_to_set = dbus.Boolean(True)
768
class StopChecker(PropertySetter):
769
propname = "CheckerRunning"
770
value_to_set = dbus.Boolean(False)
773
class ApproveByDefault(PropertySetter):
774
propname = "ApprovedByDefault"
775
value_to_set = dbus.Boolean(True)
778
class DenyByDefault(PropertySetter):
779
propname = "ApprovedByDefault"
780
value_to_set = dbus.Boolean(False)
783
class PropertySetterValue(PropertySetter):
784
"""Abstract class for PropertySetter recieving a value as
785
constructor argument instead of a class attribute."""
786
def __init__(self, value):
787
self.value_to_set = value
790
class SetChecker(PropertySetterValue):
794
class SetHost(PropertySetterValue):
798
class SetSecret(PropertySetterValue):
802
def value_to_set(self):
806
def value_to_set(self, value):
807
"""When setting, read data from supplied file object"""
808
self._vts = value.read()
812
class PropertySetterValueMilliseconds(PropertySetterValue):
813
"""Abstract class for PropertySetterValue taking a value
814
argument as a datetime.timedelta() but should store it as
818
def value_to_set(self):
822
def value_to_set(self, value):
823
"When setting, convert value from a datetime.timedelta"
824
self._vts = int(round(value.total_seconds() * 1000))
827
class SetTimeout(PropertySetterValueMilliseconds):
831
class SetExtendedTimeout(PropertySetterValueMilliseconds):
832
propname = "ExtendedTimeout"
835
class SetInterval(PropertySetterValueMilliseconds):
836
propname = "Interval"
839
class SetApprovalDelay(PropertySetterValueMilliseconds):
840
propname = "ApprovalDelay"
843
class SetApprovalDuration(PropertySetterValueMilliseconds):
844
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"
1165
1134
options = self.parser.parse_args(args)
1166
1135
check_option_syntax(self.parser, options)
1167
1136
commands = commands_from_options(options)
1168
self.assertEqual(1, len(commands))
1137
self.assertEqual(len(commands), 1)
1169
1138
command = commands[0]
1170
1139
self.assertIsInstance(command, command_cls)
1171
1140
for key, value in cmd_attrs.items():
1172
self.assertEqual(value, getattr(command, key))
1141
self.assertEqual(getattr(command, key), value)
1174
1143
def test_is_enabled_short(self):
1175
self.assert_command_from_args(["-V", "client"],
1144
self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1178
1146
def test_approve(self):
1179
self.assert_command_from_args(["--approve", "client"],
1147
self.assert_command_from_args(["--approve", "foo"],
1182
1150
def test_approve_short(self):
1183
self.assert_command_from_args(["-A", "client"],
1151
self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1186
1153
def test_deny(self):
1187
self.assert_command_from_args(["--deny", "client"],
1154
self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1190
1156
def test_deny_short(self):
1191
self.assert_command_from_args(["-D", "client"], command.Deny)
1157
self.assert_command_from_args(["-D", "foo"], DenyCmd)
1193
1159
def test_remove(self):
1194
self.assert_command_from_args(["--remove", "client"],
1160
self.assert_command_from_args(["--remove", "foo"],
1197
1163
def test_deny_before_remove(self):
1198
1164
options = self.parser.parse_args(["--deny", "--remove",
1200
1166
check_option_syntax(self.parser, options)
1201
1167
commands = commands_from_options(options)
1202
self.assertEqual(2, len(commands))
1203
self.assertIsInstance(commands[0], command.Deny)
1204
self.assertIsInstance(commands[1], command.Remove)
1168
self.assertEqual(len(commands), 2)
1169
self.assertIsInstance(commands[0], DenyCmd)
1170
self.assertIsInstance(commands[1], RemoveCmd)
1206
1172
def test_deny_before_remove_reversed(self):
1207
1173
options = self.parser.parse_args(["--remove", "--deny",
1209
1175
check_option_syntax(self.parser, options)
1210
1176
commands = commands_from_options(options)
1211
self.assertEqual(2, len(commands))
1212
self.assertIsInstance(commands[0], command.Deny)
1213
self.assertIsInstance(commands[1], command.Remove)
1177
self.assertEqual(len(commands), 2)
1178
self.assertIsInstance(commands[0], DenyCmd)
1179
self.assertIsInstance(commands[1], RemoveCmd)
1215
1181
def test_remove_short(self):
1216
self.assert_command_from_args(["-r", "client"],
1182
self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1219
1184
def test_dump_json(self):
1220
self.assert_command_from_args(["--dump-json"],
1185
self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1223
1187
def test_enable(self):
1224
self.assert_command_from_args(["--enable", "client"],
1188
self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1227
1190
def test_enable_short(self):
1228
self.assert_command_from_args(["-e", "client"],
1191
self.assert_command_from_args(["-e", "foo"], EnableCmd)
1231
1193
def test_disable(self):
1232
self.assert_command_from_args(["--disable", "client"],
1194
self.assert_command_from_args(["--disable", "foo"],
1235
1197
def test_disable_short(self):
1236
self.assert_command_from_args(["-d", "client"],
1198
self.assert_command_from_args(["-d", "foo"], DisableCmd)
1239
1200
def test_bump_timeout(self):
1240
self.assert_command_from_args(["--bump-timeout", "client"],
1241
command.BumpTimeout)
1201
self.assert_command_from_args(["--bump-timeout", "foo"],
1243
1204
def test_bump_timeout_short(self):
1244
self.assert_command_from_args(["-b", "client"],
1245
command.BumpTimeout)
1205
self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1247
1207
def test_start_checker(self):
1248
self.assert_command_from_args(["--start-checker", "client"],
1249
command.StartChecker)
1208
self.assert_command_from_args(["--start-checker", "foo"],
1251
1211
def test_stop_checker(self):
1252
self.assert_command_from_args(["--stop-checker", "client"],
1253
command.StopChecker)
1212
self.assert_command_from_args(["--stop-checker", "foo"],
1255
1215
def test_approve_by_default(self):
1256
self.assert_command_from_args(["--approve-by-default",
1258
command.ApproveByDefault)
1216
self.assert_command_from_args(["--approve-by-default", "foo"],
1217
ApproveByDefaultCmd)
1260
1219
def test_deny_by_default(self):
1261
self.assert_command_from_args(["--deny-by-default", "client"],
1262
command.DenyByDefault)
1220
self.assert_command_from_args(["--deny-by-default", "foo"],
1264
1223
def test_checker(self):
1265
self.assert_command_from_args(["--checker", ":", "client"],
1224
self.assert_command_from_args(["--checker", ":", "foo"],
1225
SetCheckerCmd, value_to_set=":")
1269
1227
def test_checker_empty(self):
1270
self.assert_command_from_args(["--checker", "", "client"],
1228
self.assert_command_from_args(["--checker", "", "foo"],
1229
SetCheckerCmd, value_to_set="")
1274
1231
def test_checker_short(self):
1275
self.assert_command_from_args(["-c", ":", "client"],
1232
self.assert_command_from_args(["-c", ":", "foo"],
1233
SetCheckerCmd, value_to_set=":")
1279
1235
def test_host(self):
1280
self.assert_command_from_args(
1281
["--host", "client.example.org", "client"],
1282
command.SetHost, value_to_set="client.example.org")
1236
self.assert_command_from_args(["--host", "foo.example.org",
1238
value_to_set="foo.example.org")
1284
1240
def test_host_short(self):
1285
self.assert_command_from_args(
1286
["-H", "client.example.org", "client"], command.SetHost,
1287
value_to_set="client.example.org")
1241
self.assert_command_from_args(["-H", "foo.example.org",
1243
value_to_set="foo.example.org")
1289
1245
def test_secret_devnull(self):
1290
1246
self.assert_command_from_args(["--secret", os.path.devnull,
1291
"client"], command.SetSecret,
1247
"foo"], SetSecretCmd,
1292
1248
value_to_set=b"")
1294
1250
def test_secret_tempfile(self):
1438
1394
LastCheckerStatus=-2)
1439
1395
self.clients = collections.OrderedDict(
1441
(self.client.__dbus_object_path__,
1442
self.client.attributes),
1443
(self.other_client.__dbus_object_path__,
1444
self.other_client.attributes),
1397
("/clients/foo", self.client.attributes),
1398
("/clients/barbar", self.other_client.attributes),
1446
self.one_client = {self.client.__dbus_object_path__:
1447
self.client.attributes}
1400
self.one_client = {"/clients/foo": self.client.attributes}
1451
class MockBus(object):
1453
1406
def get_object(client_bus_name, path):
1454
self.assertEqual(dbus_busname, client_bus_name)
1455
# Note: "self" here is the TestCmd instance, not the
1456
# MockBus instance, since this is a static method!
1457
if path == self.client.__dbus_object_path__:
1459
elif path == self.other_client.__dbus_object_path__:
1460
return self.other_client
1464
class TestBaseCommands(TestCommand):
1466
def test_IsEnabled_exits_successfully(self):
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):
1467
1425
with self.assertRaises(SystemExit) as e:
1468
command.IsEnabled().run(self.one_client)
1426
IsEnabledCmd().run(self.one_client)
1469
1427
if e.exception.code is not None:
1470
self.assertEqual(0, e.exception.code)
1428
self.assertEqual(e.exception.code, 0)
1472
1430
self.assertIsNone(e.exception.code)
1474
def test_IsEnabled_exits_with_failure(self):
1432
def test_is_enabled_run_exits_with_failure(self):
1475
1433
self.client.attributes["Enabled"] = dbus.Boolean(False)
1476
1434
with self.assertRaises(SystemExit) as e:
1477
command.IsEnabled().run(self.one_client)
1435
IsEnabledCmd().run(self.one_client)
1478
1436
if isinstance(e.exception.code, int):
1479
self.assertNotEqual(0, e.exception.code)
1437
self.assertNotEqual(e.exception.code, 0)
1481
1439
self.assertIsNotNone(e.exception.code)
1483
def test_Approve(self):
1484
command.Approve().run(self.clients, self.bus)
1442
class TestApproveCmd(TestCmd):
1443
def test_approve(self):
1444
ApproveCmd().run(self.clients, self.bus)
1485
1445
for clientpath in self.clients:
1486
1446
client = self.bus.get_object(dbus_busname, clientpath)
1487
1447
self.assertIn(("Approve", (True, client_dbus_interface)),
1490
def test_Deny(self):
1491
command.Deny().run(self.clients, self.bus)
1451
class TestDenyCmd(TestCmd):
1452
def test_deny(self):
1453
DenyCmd().run(self.clients, self.bus)
1492
1454
for clientpath in self.clients:
1493
1455
client = self.bus.get_object(dbus_busname, clientpath)
1494
1456
self.assertIn(("Approve", (False, client_dbus_interface)),
1497
def test_Remove(self):
1498
class MandosSpy(object):
1460
class TestRemoveCmd(TestCmd):
1461
def test_remove(self):
1462
class MockMandos(object):
1499
1463
def __init__(self):
1500
1464
self.calls = []
1501
1465
def RemoveClient(self, dbus_path):
1502
1466
self.calls.append(("RemoveClient", (dbus_path,)))
1503
mandos = MandosSpy()
1504
command.Remove().run(self.clients, self.bus, mandos)
1467
mandos = MockMandos()
1468
super(TestRemoveCmd, self).setUp()
1469
RemoveCmd().run(self.clients, self.bus, mandos)
1470
self.assertEqual(len(mandos.calls), 2)
1505
1471
for clientpath in self.clients:
1506
1472
self.assertIn(("RemoveClient", (clientpath,)),
1512
"KeyID": ("92ed150794387c03ce684574b1139a65"
1513
"94a34f895daaaf09fd8ea90a27cddb12"),
1514
"Host": "foo.example.org",
1517
"LastCheckedOK": "2019-02-03T00:00:00",
1518
"Created": "2019-01-02T00:00:00",
1520
"Fingerprint": ("778827225BA7DE539C5A"
1521
"7CFA59CFF7CDBD9A5920"),
1522
"CheckerRunning": False,
1523
"LastEnabled": "2019-01-03T00:00:00",
1524
"ApprovalPending": False,
1525
"ApprovedByDefault": True,
1526
"LastApprovalRequest": "",
1528
"ApprovalDuration": 1000,
1529
"Checker": "fping -q -- %(host)s",
1530
"ExtendedTimeout": 900000,
1531
"Expires": "2019-02-04T00:00:00",
1532
"LastCheckerStatus": 0,
1536
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1537
"6ab612cff5ad227247e46c2b020f441c"),
1538
"Host": "192.0.2.3",
1541
"LastCheckedOK": "2019-02-04T00:00:00",
1542
"Created": "2019-01-03T00:00:00",
1544
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1545
"F547B3A107558FCA3A27"),
1546
"CheckerRunning": True,
1547
"LastEnabled": "2019-01-04T00:00:00",
1548
"ApprovalPending": False,
1549
"ApprovedByDefault": False,
1550
"LastApprovalRequest": "2019-01-03T00:00:00",
1551
"ApprovalDelay": 30000,
1552
"ApprovalDuration": 93785000,
1554
"ExtendedTimeout": 900000,
1555
"Expires": "2019-02-05T00:00:00",
1556
"LastCheckerStatus": -2,
1560
def test_DumpJSON_normal(self):
1561
with self.capture_stdout_to_buffer() as buffer:
1562
command.DumpJSON().run(self.clients)
1563
json_data = json.loads(buffer.getvalue())
1564
self.assertDictEqual(self.expected_json, json_data)
1567
@contextlib.contextmanager
1568
def capture_stdout_to_buffer():
1569
capture_buffer = io.StringIO()
1570
old_stdout = sys.stdout
1571
sys.stdout = capture_buffer
1573
yield capture_buffer
1575
sys.stdout = old_stdout
1577
def test_DumpJSON_one_client(self):
1578
with self.capture_stdout_to_buffer() as buffer:
1579
command.DumpJSON().run(self.one_client)
1580
json_data = json.loads(buffer.getvalue())
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)
1581
1538
expected_json = {"foo": self.expected_json["foo"]}
1582
self.assertDictEqual(expected_json, json_data)
1584
def test_PrintTable_normal(self):
1585
with self.capture_stdout_to_buffer() as buffer:
1586
command.PrintTable().run(self.clients)
1539
self.assertDictEqual(json_data, expected_json)
1542
class TestPrintTableCmd(TestCmd):
1543
def test_normal(self):
1544
output = PrintTableCmd().output(self.clients.values())
1587
1545
expected_output = "\n".join((
1588
1546
"Name Enabled Timeout Last Successful Check",
1589
1547
"foo Yes 00:05:00 2019-02-03T00:00:00 ",
1590
1548
"barbar Yes 00:05:00 2019-02-04T00:00:00 ",
1592
self.assertEqual(expected_output, buffer.getvalue())
1550
self.assertEqual(output, expected_output)
1594
def test_PrintTable_verbose(self):
1595
with self.capture_stdout_to_buffer() as buffer:
1596
command.PrintTable(verbose=True).run(self.clients)
1552
def test_verbose(self):
1553
output = PrintTableCmd(verbose=True).output(
1554
self.clients.values())
1725
1682
self.command().run(clients, self.bus)
1728
class TestEnableCmd(TestPropertySetterCmd):
1729
command = command.Enable
1685
class TestEnableCmd(TestPropertyCmd):
1730
1687
propname = "Enabled"
1731
1688
values_to_set = [dbus.Boolean(True)]
1734
class TestDisableCmd(TestPropertySetterCmd):
1735
command = command.Disable
1691
class TestDisableCmd(TestPropertyCmd):
1692
command = DisableCmd
1736
1693
propname = "Enabled"
1737
1694
values_to_set = [dbus.Boolean(False)]
1740
class TestBumpTimeoutCmd(TestPropertySetterCmd):
1741
command = command.BumpTimeout
1697
class TestBumpTimeoutCmd(TestPropertyCmd):
1698
command = BumpTimeoutCmd
1742
1699
propname = "LastCheckedOK"
1743
1700
values_to_set = [""]
1746
class TestStartCheckerCmd(TestPropertySetterCmd):
1747
command = command.StartChecker
1748
propname = "CheckerRunning"
1749
values_to_set = [dbus.Boolean(True)]
1752
class TestStopCheckerCmd(TestPropertySetterCmd):
1753
command = command.StopChecker
1754
propname = "CheckerRunning"
1755
values_to_set = [dbus.Boolean(False)]
1758
class TestApproveByDefaultCmd(TestPropertySetterCmd):
1759
command = command.ApproveByDefault
1760
propname = "ApprovedByDefault"
1761
values_to_set = [dbus.Boolean(True)]
1764
class TestDenyByDefaultCmd(TestPropertySetterCmd):
1765
command = command.DenyByDefault
1766
propname = "ApprovedByDefault"
1767
values_to_set = [dbus.Boolean(False)]
1770
class TestPropertySetterValueCmd(TestPropertySetterCmd):
1771
"""Abstract class for tests of PropertySetterValueCmd classes"""
1703
class TestStartCheckerCmd(TestPropertyCmd):
1704
command = StartCheckerCmd
1705
propname = "CheckerRunning"
1706
values_to_set = [dbus.Boolean(True)]
1709
class TestStopCheckerCmd(TestPropertyCmd):
1710
command = StopCheckerCmd
1711
propname = "CheckerRunning"
1712
values_to_set = [dbus.Boolean(False)]
1715
class TestApproveByDefaultCmd(TestPropertyCmd):
1716
command = ApproveByDefaultCmd
1717
propname = "ApprovedByDefault"
1718
values_to_set = [dbus.Boolean(True)]
1721
class TestDenyByDefaultCmd(TestPropertyCmd):
1722
command = DenyByDefaultCmd
1723
propname = "ApprovedByDefault"
1724
values_to_set = [dbus.Boolean(False)]
1727
class TestPropertyValueCmd(TestPropertyCmd):
1728
"""Abstract class for tests of PropertyValueCmd classes"""
1773
1730
def runTest(self):
1774
if type(self) is TestPropertySetterValueCmd:
1731
if type(self) is TestPropertyValueCmd:
1776
return super(TestPropertySetterValueCmd, self).runTest()
1733
return super(TestPropertyValueCmd, self).runTest()
1778
1735
def run_command(self, value, clients):
1779
1736
self.command(value).run(clients, self.bus)
1782
class TestSetCheckerCmd(TestPropertySetterValueCmd):
1783
command = command.SetChecker
1739
class TestSetCheckerCmd(TestPropertyValueCmd):
1740
command = SetCheckerCmd
1784
1741
propname = "Checker"
1785
1742
values_to_set = ["", ":", "fping -q -- %s"]
1788
class TestSetHostCmd(TestPropertySetterValueCmd):
1789
command = command.SetHost
1745
class TestSetHostCmd(TestPropertyValueCmd):
1746
command = SetHostCmd
1790
1747
propname = "Host"
1791
values_to_set = ["192.0.2.3", "client.example.org"]
1794
class TestSetSecretCmd(TestPropertySetterValueCmd):
1795
command = command.SetSecret
1748
values_to_set = ["192.0.2.3", "foo.example.org"]
1751
class TestSetSecretCmd(TestPropertyValueCmd):
1752
command = SetSecretCmd
1796
1753
propname = "Secret"
1797
1754
values_to_set = [io.BytesIO(b""),
1798
1755
io.BytesIO(b"secret\0xyzzy\nbar")]
1799
values_to_get = [f.getvalue() for f in values_to_set]
1802
class TestSetTimeoutCmd(TestPropertySetterValueCmd):
1803
command = command.SetTimeout
1756
values_to_get = [b"", b"secret\0xyzzy\nbar"]
1759
class TestSetTimeoutCmd(TestPropertyValueCmd):
1760
command = SetTimeoutCmd
1804
1761
propname = "Timeout"
1805
1762
values_to_set = [datetime.timedelta(),
1806
1763
datetime.timedelta(minutes=5),
1807
1764
datetime.timedelta(seconds=1),
1808
1765
datetime.timedelta(weeks=1),
1809
1766
datetime.timedelta(weeks=52)]
1810
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1813
class TestSetExtendedTimeoutCmd(TestPropertySetterValueCmd):
1814
command = command.SetExtendedTimeout
1767
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1770
class TestSetExtendedTimeoutCmd(TestPropertyValueCmd):
1771
command = SetExtendedTimeoutCmd
1815
1772
propname = "ExtendedTimeout"
1816
1773
values_to_set = [datetime.timedelta(),
1817
1774
datetime.timedelta(minutes=5),
1818
1775
datetime.timedelta(seconds=1),
1819
1776
datetime.timedelta(weeks=1),
1820
1777
datetime.timedelta(weeks=52)]
1821
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1824
class TestSetIntervalCmd(TestPropertySetterValueCmd):
1825
command = command.SetInterval
1778
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1781
class TestSetIntervalCmd(TestPropertyValueCmd):
1782
command = SetIntervalCmd
1826
1783
propname = "Interval"
1827
1784
values_to_set = [datetime.timedelta(),
1828
1785
datetime.timedelta(minutes=5),
1829
1786
datetime.timedelta(seconds=1),
1830
1787
datetime.timedelta(weeks=1),
1831
1788
datetime.timedelta(weeks=52)]
1832
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1835
class TestSetApprovalDelayCmd(TestPropertySetterValueCmd):
1836
command = command.SetApprovalDelay
1789
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1792
class TestSetApprovalDelayCmd(TestPropertyValueCmd):
1793
command = SetApprovalDelayCmd
1837
1794
propname = "ApprovalDelay"
1838
1795
values_to_set = [datetime.timedelta(),
1839
1796
datetime.timedelta(minutes=5),
1840
1797
datetime.timedelta(seconds=1),
1841
1798
datetime.timedelta(weeks=1),
1842
1799
datetime.timedelta(weeks=52)]
1843
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1846
class TestSetApprovalDurationCmd(TestPropertySetterValueCmd):
1847
command = command.SetApprovalDuration
1800
values_to_get = [0, 300000, 1000, 604800000, 31449600000]
1803
class TestSetApprovalDurationCmd(TestPropertyValueCmd):
1804
command = SetApprovalDurationCmd
1848
1805
propname = "ApprovalDuration"
1849
1806
values_to_set = [datetime.timedelta(),
1850
1807
datetime.timedelta(minutes=5),
1851
1808
datetime.timedelta(seconds=1),
1852
1809
datetime.timedelta(weeks=1),
1853
1810
datetime.timedelta(weeks=52)]
1854
values_to_get = [dt.total_seconds()*1000 for dt in values_to_set]
1811
values_to_get = [0, 300000, 1000, 604800000, 31449600000]