446
426
options.remove = True
429
def get_mandos_dbus_object(bus):
430
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
431
dbus_busname, server_dbus_path)
432
with if_dbus_exception_log_with_exception_and_exit(
433
"Could not connect to Mandos server: %s"):
434
mandos_dbus_object = bus.get_object(dbus_busname,
436
return mandos_dbus_object
439
@contextlib.contextmanager
440
def if_dbus_exception_log_with_exception_and_exit(*args, **kwargs):
443
except dbus.exceptions.DBusException as e:
444
log.critical(*(args + (e,)), **kwargs)
448
def get_managed_objects(object_manager):
449
log.debug("D-Bus: %s:%s:%s.GetManagedObjects()", dbus_busname,
450
server_dbus_path, dbus.OBJECT_MANAGER_IFACE)
451
with if_dbus_exception_log_with_exception_and_exit(
452
"Failed to access Mandos server through D-Bus:\n%s"):
453
with SilenceLogger("dbus.proxies"):
454
managed_objects = object_manager.GetManagedObjects()
455
return managed_objects
458
class SilenceLogger(object):
459
"Simple context manager to silence a particular logger"
460
def __init__(self, loggername):
461
self.logger = logging.getLogger(loggername)
464
self.logger.addFilter(self.nullfilter)
467
class NullFilter(logging.Filter):
468
def filter(self, record):
471
nullfilter = NullFilter()
473
def __exit__(self, exc_type, exc_val, exc_tb):
474
self.logger.removeFilter(self.nullfilter)
449
477
def commands_from_options(options):
453
481
if options.is_enabled:
454
commands.append(IsEnabledCmd())
482
commands.append(command.IsEnabled())
456
484
if options.approve:
457
commands.append(ApproveCmd())
485
commands.append(command.Approve())
460
commands.append(DenyCmd())
488
commands.append(command.Deny())
462
490
if options.remove:
463
commands.append(RemoveCmd())
491
commands.append(command.Remove())
465
493
if options.dump_json:
466
commands.append(DumpJSONCmd())
494
commands.append(command.DumpJSON())
468
496
if options.enable:
469
commands.append(EnableCmd())
497
commands.append(command.Enable())
471
499
if options.disable:
472
commands.append(DisableCmd())
500
commands.append(command.Disable())
474
502
if options.bump_timeout:
475
commands.append(BumpTimeoutCmd())
503
commands.append(command.BumpTimeout())
477
505
if options.start_checker:
478
commands.append(StartCheckerCmd())
506
commands.append(command.StartChecker())
480
508
if options.stop_checker:
481
commands.append(StopCheckerCmd())
509
commands.append(command.StopChecker())
483
511
if options.approved_by_default is not None:
484
512
if options.approved_by_default:
485
commands.append(ApproveByDefaultCmd())
513
commands.append(command.ApproveByDefault())
487
commands.append(DenyByDefaultCmd())
515
commands.append(command.DenyByDefault())
489
517
if options.checker is not None:
490
commands.append(SetCheckerCmd(options.checker))
518
commands.append(command.SetChecker(options.checker))
492
520
if options.host is not None:
493
commands.append(SetHostCmd(options.host))
521
commands.append(command.SetHost(options.host))
495
523
if options.secret is not None:
496
commands.append(SetSecretCmd(options.secret))
524
commands.append(command.SetSecret(options.secret))
498
526
if options.timeout is not None:
499
commands.append(SetTimeoutCmd(options.timeout))
527
commands.append(command.SetTimeout(options.timeout))
501
529
if options.extended_timeout:
503
SetExtendedTimeoutCmd(options.extended_timeout))
531
command.SetExtendedTimeout(options.extended_timeout))
505
533
if options.interval is not None:
506
commands.append(SetIntervalCmd(options.interval))
534
commands.append(command.SetInterval(options.interval))
508
536
if options.approval_delay is not None:
509
commands.append(SetApprovalDelayCmd(options.approval_delay))
538
command.SetApprovalDelay(options.approval_delay))
511
540
if options.approval_duration is not None:
513
SetApprovalDurationCmd(options.approval_duration))
542
command.SetApprovalDuration(options.approval_duration))
515
544
# If no command option has been given, show table of clients,
516
545
# optionally verbosely
518
commands.append(PrintTableCmd(verbose=options.verbose))
547
commands.append(command.PrintTable(verbose=options.verbose))
523
class Command(object):
524
"""Abstract class for commands"""
525
def run(self, clients, bus=None, mandos=None):
526
"""Normal commands should implement run_on_one_client(), but
527
commands which want to operate on all clients at the same time
528
can override this run() method instead."""
530
for clientpath, properties in clients.items():
531
log.debug("D-Bus: Connect to: (busname=%r, path=%r)",
532
dbus_busname, str(clientpath))
533
client = bus.get_object(dbus_busname, clientpath)
534
self.run_on_one_client(client, properties)
537
class IsEnabledCmd(Command):
538
def run(self, clients, bus=None, mandos=None):
539
client, properties = next(iter(clients.items()))
540
if self.is_enabled(client, properties):
543
def is_enabled(self, client, properties):
544
return properties["Enabled"]
547
class ApproveCmd(Command):
548
def run_on_one_client(self, client, properties):
549
log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname,
550
client.__dbus_object_path__, client_dbus_interface)
551
client.Approve(dbus.Boolean(True),
552
dbus_interface=client_dbus_interface)
555
class DenyCmd(Command):
556
def run_on_one_client(self, client, properties):
557
log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname,
558
client.__dbus_object_path__, client_dbus_interface)
559
client.Approve(dbus.Boolean(False),
560
dbus_interface=client_dbus_interface)
563
class RemoveCmd(Command):
564
def run_on_one_client(self, client, properties):
565
log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", dbus_busname,
566
server_dbus_path, server_dbus_interface,
567
str(client.__dbus_object_path__))
568
self.mandos.RemoveClient(client.__dbus_object_path__)
571
class OutputCmd(Command):
572
"""Abstract class for commands outputting client details"""
573
all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
574
"Created", "Interval", "Host", "KeyID",
575
"Fingerprint", "CheckerRunning", "LastEnabled",
576
"ApprovalPending", "ApprovedByDefault",
577
"LastApprovalRequest", "ApprovalDelay",
578
"ApprovalDuration", "Checker", "ExtendedTimeout",
579
"Expires", "LastCheckerStatus")
581
def run(self, clients, bus=None, mandos=None):
582
print(self.output(clients.values()))
584
def output(self, clients):
585
raise NotImplementedError()
588
class DumpJSONCmd(OutputCmd):
589
def output(self, clients):
590
data = {client["Name"]:
591
{key: self.dbus_boolean_to_bool(client[key])
592
for key in self.all_keywords}
593
for client in clients}
594
return json.dumps(data, indent=4, separators=(',', ': '))
597
def dbus_boolean_to_bool(value):
598
if isinstance(value, dbus.Boolean):
603
class PrintTableCmd(OutputCmd):
604
def __init__(self, verbose=False):
605
self.verbose = verbose
607
def output(self, clients):
608
default_keywords = ("Name", "Enabled", "Timeout",
610
keywords = default_keywords
612
keywords = self.all_keywords
613
return str(self.TableOfClients(clients, keywords))
615
class TableOfClients(object):
618
"Enabled": "Enabled",
619
"Timeout": "Timeout",
620
"LastCheckedOK": "Last Successful Check",
621
"LastApprovalRequest": "Last Approval Request",
622
"Created": "Created",
623
"Interval": "Interval",
625
"Fingerprint": "Fingerprint",
627
"CheckerRunning": "Check Is Running",
628
"LastEnabled": "Last Enabled",
629
"ApprovalPending": "Approval Is Pending",
630
"ApprovedByDefault": "Approved By Default",
631
"ApprovalDelay": "Approval Delay",
632
"ApprovalDuration": "Approval Duration",
633
"Checker": "Checker",
634
"ExtendedTimeout": "Extended Timeout",
635
"Expires": "Expires",
636
"LastCheckerStatus": "Last Checker Status",
639
def __init__(self, clients, keywords, tableheaders=None):
640
self.clients = clients
641
self.keywords = keywords
642
if tableheaders is not None:
643
self.tableheaders = tableheaders
646
return "\n".join(self.rows())
648
if sys.version_info.major == 2:
649
__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
650
674
def __str__(self):
651
return str(self).encode(locale.getpreferredencoding())
654
format_string = self.row_formatting_string()
655
rows = [self.header_line(format_string)]
656
rows.extend(self.client_line(client, format_string)
657
for client in self.clients)
660
def row_formatting_string(self):
661
"Format string used to format table rows"
662
return " ".join("{{{key}:{width}}}".format(
663
width=max(len(self.tableheaders[key]),
664
*(len(self.string_from_client(client, key))
665
for client in self.clients)),
667
for key in self.keywords)
669
def string_from_client(self, client, key):
670
return self.valuetostring(client[key], key)
673
def valuetostring(cls, value, keyword):
674
if isinstance(value, dbus.Boolean):
675
return "Yes" if value else "No"
676
if keyword in ("Timeout", "Interval", "ApprovalDelay",
677
"ApprovalDuration", "ExtendedTimeout"):
678
return cls.milliseconds_to_string(value)
681
def header_line(self, format_string):
682
return format_string.format(**self.tableheaders)
684
def client_line(self, client, format_string):
685
return format_string.format(
686
**{key: self.string_from_client(client, key)
687
for key in self.keywords})
690
def milliseconds_to_string(ms):
691
td = datetime.timedelta(0, 0, 0, ms)
692
return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
693
.format(days="{}T".format(td.days)
695
hours=td.seconds // 3600,
696
minutes=(td.seconds % 3600) // 60,
697
seconds=td.seconds % 60))
700
class PropertyCmd(Command):
701
"""Abstract class for Actions for setting one client property"""
703
def run_on_one_client(self, client, properties):
704
"""Set the Client's D-Bus property"""
705
log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname,
706
client.__dbus_object_path__,
707
dbus.PROPERTIES_IFACE, client_dbus_interface,
708
self.propname, self.value_to_set
709
if not isinstance(self.value_to_set, dbus.Boolean)
710
else bool(self.value_to_set))
711
client.Set(client_dbus_interface, self.propname,
713
dbus_interface=dbus.PROPERTIES_IFACE)
717
raise NotImplementedError()
720
class EnableCmd(PropertyCmd):
722
value_to_set = dbus.Boolean(True)
725
class DisableCmd(PropertyCmd):
727
value_to_set = dbus.Boolean(False)
730
class BumpTimeoutCmd(PropertyCmd):
731
propname = "LastCheckedOK"
735
class StartCheckerCmd(PropertyCmd):
736
propname = "CheckerRunning"
737
value_to_set = dbus.Boolean(True)
740
class StopCheckerCmd(PropertyCmd):
741
propname = "CheckerRunning"
742
value_to_set = dbus.Boolean(False)
745
class ApproveByDefaultCmd(PropertyCmd):
746
propname = "ApprovedByDefault"
747
value_to_set = dbus.Boolean(True)
750
class DenyByDefaultCmd(PropertyCmd):
751
propname = "ApprovedByDefault"
752
value_to_set = dbus.Boolean(False)
755
class PropertyValueCmd(PropertyCmd):
756
"""Abstract class for PropertyCmd recieving a value as argument"""
757
def __init__(self, value):
758
self.value_to_set = value
761
class SetCheckerCmd(PropertyValueCmd):
765
class SetHostCmd(PropertyValueCmd):
769
class SetSecretCmd(PropertyValueCmd):
773
def value_to_set(self):
777
def value_to_set(self, value):
778
"""When setting, read data from supplied file object"""
779
self._vts = value.read()
783
class MillisecondsPropertyValueArgumentCmd(PropertyValueCmd):
784
"""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
785
817
a datetime.timedelta() but should store it as milliseconds."""
788
def value_to_set(self):
792
def value_to_set(self, value):
793
"""When setting, convert value from a datetime.timedelta"""
794
self._vts = int(round(value.total_seconds() * 1000))
797
class SetTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
801
class SetExtendedTimeoutCmd(MillisecondsPropertyValueArgumentCmd):
802
propname = "ExtendedTimeout"
805
class SetIntervalCmd(MillisecondsPropertyValueArgumentCmd):
806
propname = "Interval"
809
class SetApprovalDelayCmd(MillisecondsPropertyValueArgumentCmd):
810
propname = "ApprovalDelay"
813
class SetApprovalDurationCmd(MillisecondsPropertyValueArgumentCmd):
814
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"
818
class Test_string_to_delta(unittest.TestCase):
819
def test_handles_basic_rfc3339(self):
820
self.assertEqual(string_to_delta("PT0S"),
821
datetime.timedelta())
822
self.assertEqual(string_to_delta("P0D"),
823
datetime.timedelta())
824
self.assertEqual(string_to_delta("PT1S"),
825
datetime.timedelta(0, 1))
826
self.assertEqual(string_to_delta("PT2H"),
827
datetime.timedelta(0, 7200))
850
class TestCaseWithAssertLogs(unittest.TestCase):
851
"""unittest.TestCase.assertLogs only exists in Python 3.4"""
853
if not hasattr(unittest.TestCase, "assertLogs"):
854
@contextlib.contextmanager
855
def assertLogs(self, logger, level=logging.INFO):
856
capturing_handler = self.CapturingLevelHandler(level)
857
old_level = logger.level
858
old_propagate = logger.propagate
859
logger.addHandler(capturing_handler)
860
logger.setLevel(level)
861
logger.propagate = False
863
yield capturing_handler.watcher
865
logger.propagate = old_propagate
866
logger.removeHandler(capturing_handler)
867
logger.setLevel(old_level)
868
self.assertGreater(len(capturing_handler.watcher.records),
871
class CapturingLevelHandler(logging.Handler):
872
def __init__(self, level, *args, **kwargs):
873
logging.Handler.__init__(self, *args, **kwargs)
874
self.watcher = self.LoggingWatcher([], [])
875
def emit(self, record):
876
self.watcher.records.append(record)
877
self.watcher.output.append(self.format(record))
879
LoggingWatcher = collections.namedtuple("LoggingWatcher",
884
class Test_string_to_delta(TestCaseWithAssertLogs):
885
# Just test basic RFC 3339 functionality here, the doc string for
886
# rfc3339_duration_to_delta() already has more comprehensive
887
# tests, which is run by doctest.
889
def test_rfc3339_zero_seconds(self):
890
self.assertEqual(datetime.timedelta(),
891
string_to_delta("PT0S"))
893
def test_rfc3339_zero_days(self):
894
self.assertEqual(datetime.timedelta(), string_to_delta("P0D"))
896
def test_rfc3339_one_second(self):
897
self.assertEqual(datetime.timedelta(0, 1),
898
string_to_delta("PT1S"))
900
def test_rfc3339_two_hours(self):
901
self.assertEqual(datetime.timedelta(0, 7200),
902
string_to_delta("PT2H"))
829
904
def test_falls_back_to_pre_1_6_1_with_warning(self):
830
# assertLogs only exists in Python 3.4
831
if hasattr(self, "assertLogs"):
832
with self.assertLogs(log, logging.WARNING):
833
value = string_to_delta("2h")
835
class WarningFilter(logging.Filter):
836
"""Don't show, but record the presence of, warnings"""
837
def filter(self, record):
838
is_warning = record.levelno >= logging.WARNING
839
self.found = is_warning or getattr(self, "found",
841
return not is_warning
842
warning_filter = WarningFilter()
843
log.addFilter(warning_filter)
845
value = string_to_delta("2h")
847
log.removeFilter(warning_filter)
848
self.assertTrue(getattr(warning_filter, "found", False))
849
self.assertEqual(value, datetime.timedelta(0, 7200))
905
with self.assertLogs(log, logging.WARNING):
906
value = string_to_delta("2h")
907
self.assertEqual(datetime.timedelta(0, 7200), value)
852
910
class Test_check_option_syntax(unittest.TestCase):
997
1167
options = self.parser.parse_args(args)
998
1168
check_option_syntax(self.parser, options)
999
1169
commands = commands_from_options(options)
1000
self.assertEqual(len(commands), 1)
1170
self.assertEqual(1, len(commands))
1001
1171
command = commands[0]
1002
1172
self.assertIsInstance(command, command_cls)
1003
1173
for key, value in cmd_attrs.items():
1004
self.assertEqual(getattr(command, key), value)
1174
self.assertEqual(value, getattr(command, key))
1006
1176
def test_is_enabled_short(self):
1007
self.assert_command_from_args(["-V", "foo"], IsEnabledCmd)
1177
self.assert_command_from_args(["-V", "foo"],
1009
1180
def test_approve(self):
1010
1181
self.assert_command_from_args(["--approve", "foo"],
1013
1184
def test_approve_short(self):
1014
self.assert_command_from_args(["-A", "foo"], ApproveCmd)
1185
self.assert_command_from_args(["-A", "foo"], command.Approve)
1016
1187
def test_deny(self):
1017
self.assert_command_from_args(["--deny", "foo"], DenyCmd)
1188
self.assert_command_from_args(["--deny", "foo"], command.Deny)
1019
1190
def test_deny_short(self):
1020
self.assert_command_from_args(["-D", "foo"], DenyCmd)
1191
self.assert_command_from_args(["-D", "foo"], command.Deny)
1022
1193
def test_remove(self):
1023
1194
self.assert_command_from_args(["--remove", "foo"],
1026
1197
def test_deny_before_remove(self):
1027
1198
options = self.parser.parse_args(["--deny", "--remove",
1029
1200
check_option_syntax(self.parser, options)
1030
1201
commands = commands_from_options(options)
1031
self.assertEqual(len(commands), 2)
1032
self.assertIsInstance(commands[0], DenyCmd)
1033
self.assertIsInstance(commands[1], RemoveCmd)
1202
self.assertEqual(2, len(commands))
1203
self.assertIsInstance(commands[0], command.Deny)
1204
self.assertIsInstance(commands[1], command.Remove)
1035
1206
def test_deny_before_remove_reversed(self):
1036
1207
options = self.parser.parse_args(["--remove", "--deny",
1038
1209
check_option_syntax(self.parser, options)
1039
1210
commands = commands_from_options(options)
1040
self.assertEqual(len(commands), 2)
1041
self.assertIsInstance(commands[0], DenyCmd)
1042
self.assertIsInstance(commands[1], RemoveCmd)
1211
self.assertEqual(2, len(commands))
1212
self.assertIsInstance(commands[0], command.Deny)
1213
self.assertIsInstance(commands[1], command.Remove)
1044
1215
def test_remove_short(self):
1045
self.assert_command_from_args(["-r", "foo"], RemoveCmd)
1216
self.assert_command_from_args(["-r", "foo"], command.Remove)
1047
1218
def test_dump_json(self):
1048
self.assert_command_from_args(["--dump-json"], DumpJSONCmd)
1219
self.assert_command_from_args(["--dump-json"],
1050
1222
def test_enable(self):
1051
self.assert_command_from_args(["--enable", "foo"], EnableCmd)
1223
self.assert_command_from_args(["--enable", "foo"],
1053
1226
def test_enable_short(self):
1054
self.assert_command_from_args(["-e", "foo"], EnableCmd)
1227
self.assert_command_from_args(["-e", "foo"], command.Enable)
1056
1229
def test_disable(self):
1057
1230
self.assert_command_from_args(["--disable", "foo"],
1060
1233
def test_disable_short(self):
1061
self.assert_command_from_args(["-d", "foo"], DisableCmd)
1234
self.assert_command_from_args(["-d", "foo"], command.Disable)
1063
1236
def test_bump_timeout(self):
1064
1237
self.assert_command_from_args(["--bump-timeout", "foo"],
1238
command.BumpTimeout)
1067
1240
def test_bump_timeout_short(self):
1068
self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd)
1241
self.assert_command_from_args(["-b", "foo"],
1242
command.BumpTimeout)
1070
1244
def test_start_checker(self):
1071
1245
self.assert_command_from_args(["--start-checker", "foo"],
1246
command.StartChecker)
1074
1248
def test_stop_checker(self):
1075
1249
self.assert_command_from_args(["--stop-checker", "foo"],
1250
command.StopChecker)
1078
1252
def test_approve_by_default(self):
1079
1253
self.assert_command_from_args(["--approve-by-default", "foo"],
1080
ApproveByDefaultCmd)
1254
command.ApproveByDefault)
1082
1256
def test_deny_by_default(self):
1083
1257
self.assert_command_from_args(["--deny-by-default", "foo"],
1258
command.DenyByDefault)
1086
1260
def test_checker(self):
1087
1261
self.assert_command_from_args(["--checker", ":", "foo"],
1088
SetCheckerCmd, value_to_set=":")
1090
1265
def test_checker_empty(self):
1091
1266
self.assert_command_from_args(["--checker", "", "foo"],
1092
SetCheckerCmd, value_to_set="")
1094
1270
def test_checker_short(self):
1095
1271
self.assert_command_from_args(["-c", ":", "foo"],
1096
SetCheckerCmd, value_to_set=":")
1098
1275
def test_host(self):
1099
1276
self.assert_command_from_args(["--host", "foo.example.org",
1277
"foo"], command.SetHost,
1101
1278
value_to_set="foo.example.org")
1103
1280
def test_host_short(self):
1104
1281
self.assert_command_from_args(["-H", "foo.example.org",
1282
"foo"], command.SetHost,
1106
1283
value_to_set="foo.example.org")
1108
1285
def test_secret_devnull(self):
1109
1286
self.assert_command_from_args(["--secret", os.path.devnull,
1110
"foo"], SetSecretCmd,
1287
"foo"], command.SetSecret,
1111
1288
value_to_set=b"")
1113
1290
def test_secret_tempfile(self):
1280
class TestIsEnabledCmd(TestCmd):
1281
def test_is_enabled(self):
1282
self.assertTrue(all(IsEnabledCmd().is_enabled(client,
1284
for client, properties
1285
in self.clients.items()))
1456
class TestBaseCommands(TestCommand):
1287
def test_is_enabled_run_exits_successfully(self):
1458
def test_IsEnabled_exits_successfully(self):
1288
1459
with self.assertRaises(SystemExit) as e:
1289
IsEnabledCmd().run(self.one_client)
1460
command.IsEnabled().run(self.one_client)
1290
1461
if e.exception.code is not None:
1291
self.assertEqual(e.exception.code, 0)
1462
self.assertEqual(0, e.exception.code)
1293
1464
self.assertIsNone(e.exception.code)
1295
def test_is_enabled_run_exits_with_failure(self):
1466
def test_IsEnabled_exits_with_failure(self):
1296
1467
self.client.attributes["Enabled"] = dbus.Boolean(False)
1297
1468
with self.assertRaises(SystemExit) as e:
1298
IsEnabledCmd().run(self.one_client)
1469
command.IsEnabled().run(self.one_client)
1299
1470
if isinstance(e.exception.code, int):
1300
self.assertNotEqual(e.exception.code, 0)
1471
self.assertNotEqual(0, e.exception.code)
1302
1473
self.assertIsNotNone(e.exception.code)
1305
class TestApproveCmd(TestCmd):
1306
def test_approve(self):
1307
ApproveCmd().run(self.clients, self.bus)
1475
def test_Approve(self):
1476
command.Approve().run(self.clients, self.bus)
1308
1477
for clientpath in self.clients:
1309
1478
client = self.bus.get_object(dbus_busname, clientpath)
1310
1479
self.assertIn(("Approve", (True, client_dbus_interface)),
1314
class TestDenyCmd(TestCmd):
1315
def test_deny(self):
1316
DenyCmd().run(self.clients, self.bus)
1482
def test_Deny(self):
1483
command.Deny().run(self.clients, self.bus)
1317
1484
for clientpath in self.clients:
1318
1485
client = self.bus.get_object(dbus_busname, clientpath)
1319
1486
self.assertIn(("Approve", (False, client_dbus_interface)),
1323
class TestRemoveCmd(TestCmd):
1324
def test_remove(self):
1489
def test_Remove(self):
1325
1490
class MockMandos(object):
1326
1491
def __init__(self):
1327
1492
self.calls = []
1328
1493
def RemoveClient(self, dbus_path):
1329
1494
self.calls.append(("RemoveClient", (dbus_path,)))
1330
1495
mandos = MockMandos()
1331
super(TestRemoveCmd, self).setUp()
1332
RemoveCmd().run(self.clients, self.bus, mandos)
1333
self.assertEqual(len(mandos.calls), 2)
1496
command.Remove().run(self.clients, self.bus, mandos)
1334
1497
for clientpath in self.clients:
1335
1498
self.assertIn(("RemoveClient", (clientpath,)),
1339
class TestDumpJSONCmd(TestCmd):
1341
self.expected_json = {
1344
"KeyID": ("92ed150794387c03ce684574b1139a65"
1345
"94a34f895daaaf09fd8ea90a27cddb12"),
1346
"Host": "foo.example.org",
1349
"LastCheckedOK": "2019-02-03T00:00:00",
1350
"Created": "2019-01-02T00:00:00",
1352
"Fingerprint": ("778827225BA7DE539C5A"
1353
"7CFA59CFF7CDBD9A5920"),
1354
"CheckerRunning": False,
1355
"LastEnabled": "2019-01-03T00:00:00",
1356
"ApprovalPending": False,
1357
"ApprovedByDefault": True,
1358
"LastApprovalRequest": "",
1360
"ApprovalDuration": 1000,
1361
"Checker": "fping -q -- %(host)s",
1362
"ExtendedTimeout": 900000,
1363
"Expires": "2019-02-04T00:00:00",
1364
"LastCheckerStatus": 0,
1368
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1369
"6ab612cff5ad227247e46c2b020f441c"),
1370
"Host": "192.0.2.3",
1373
"LastCheckedOK": "2019-02-04T00:00:00",
1374
"Created": "2019-01-03T00:00:00",
1376
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1377
"F547B3A107558FCA3A27"),
1378
"CheckerRunning": True,
1379
"LastEnabled": "2019-01-04T00:00:00",
1380
"ApprovalPending": False,
1381
"ApprovedByDefault": False,
1382
"LastApprovalRequest": "2019-01-03T00:00:00",
1383
"ApprovalDelay": 30000,
1384
"ApprovalDuration": 93785000,
1386
"ExtendedTimeout": 900000,
1387
"Expires": "2019-02-05T00:00:00",
1388
"LastCheckerStatus": -2,
1391
return super(TestDumpJSONCmd, self).setUp()
1393
def test_normal(self):
1394
output = DumpJSONCmd().output(self.clients.values())
1395
json_data = json.loads(output)
1396
self.assertDictEqual(json_data, self.expected_json)
1398
def test_one_client(self):
1399
output = DumpJSONCmd().output(self.one_client.values())
1400
json_data = json.loads(output)
1504
"KeyID": ("92ed150794387c03ce684574b1139a65"
1505
"94a34f895daaaf09fd8ea90a27cddb12"),
1506
"Host": "foo.example.org",
1509
"LastCheckedOK": "2019-02-03T00:00:00",
1510
"Created": "2019-01-02T00:00:00",
1512
"Fingerprint": ("778827225BA7DE539C5A"
1513
"7CFA59CFF7CDBD9A5920"),
1514
"CheckerRunning": False,
1515
"LastEnabled": "2019-01-03T00:00:00",
1516
"ApprovalPending": False,
1517
"ApprovedByDefault": True,
1518
"LastApprovalRequest": "",
1520
"ApprovalDuration": 1000,
1521
"Checker": "fping -q -- %(host)s",
1522
"ExtendedTimeout": 900000,
1523
"Expires": "2019-02-04T00:00:00",
1524
"LastCheckerStatus": 0,
1528
"KeyID": ("0558568eedd67d622f5c83b35a115f79"
1529
"6ab612cff5ad227247e46c2b020f441c"),
1530
"Host": "192.0.2.3",
1533
"LastCheckedOK": "2019-02-04T00:00:00",
1534
"Created": "2019-01-03T00:00:00",
1536
"Fingerprint": ("3E393AEAEFB84C7E89E2"
1537
"F547B3A107558FCA3A27"),
1538
"CheckerRunning": True,
1539
"LastEnabled": "2019-01-04T00:00:00",
1540
"ApprovalPending": False,
1541
"ApprovedByDefault": False,
1542
"LastApprovalRequest": "2019-01-03T00:00:00",
1543
"ApprovalDelay": 30000,
1544
"ApprovalDuration": 93785000,
1546
"ExtendedTimeout": 900000,
1547
"Expires": "2019-02-05T00:00:00",
1548
"LastCheckerStatus": -2,
1552
def test_DumpJSON_normal(self):
1553
with self.capture_stdout_to_buffer() as buffer:
1554
command.DumpJSON().run(self.clients)
1555
json_data = json.loads(buffer.getvalue())
1556
self.assertDictEqual(self.expected_json, json_data)
1559
@contextlib.contextmanager
1560
def capture_stdout_to_buffer():
1561
capture_buffer = io.StringIO()
1562
old_stdout = sys.stdout
1563
sys.stdout = capture_buffer
1565
yield capture_buffer
1567
sys.stdout = old_stdout
1569
def test_DumpJSON_one_client(self):
1570
with self.capture_stdout_to_buffer() as buffer:
1571
command.DumpJSON().run(self.one_client)
1572
json_data = json.loads(buffer.getvalue())
1401
1573
expected_json = {"foo": self.expected_json["foo"]}
1402
self.assertDictEqual(json_data, expected_json)
1405
class TestPrintTableCmd(TestCmd):
1406
def test_normal(self):
1407
output = PrintTableCmd().output(self.clients.values())
1574
self.assertDictEqual(expected_json, json_data)
1576
def test_PrintTable_normal(self):
1577
with self.capture_stdout_to_buffer() as buffer:
1578
command.PrintTable().run(self.clients)
1408
1579
expected_output = "\n".join((
1409
1580
"Name Enabled Timeout Last Successful Check",
1410
1581
"foo Yes 00:05:00 2019-02-03T00:00:00 ",
1411
1582
"barbar Yes 00:05:00 2019-02-04T00:00:00 ",
1413
self.assertEqual(output, expected_output)
1584
self.assertEqual(expected_output, buffer.getvalue())
1415
def test_verbose(self):
1416
output = PrintTableCmd(verbose=True).output(
1417
self.clients.values())
1586
def test_PrintTable_verbose(self):
1587
with self.capture_stdout_to_buffer() as buffer:
1588
command.PrintTable(verbose=True).run(self.clients)