Blame SOURCES/0028-TESTS-Add-integration-tests-for-the-KCM-responder.patch

ecf709
From ad820beebae89c886f1ba4f0d2ddac4ca36857b7 Mon Sep 17 00:00:00 2001
ecf709
From: Jakub Hrozek <jhrozek@redhat.com>
ecf709
Date: Tue, 13 Dec 2016 17:17:16 +0100
ecf709
Subject: [PATCH 28/36] TESTS: Add integration tests for the KCM responder
ecf709
MIME-Version: 1.0
ecf709
Content-Type: text/plain; charset=UTF-8
ecf709
Content-Transfer-Encoding: 8bit
ecf709
ecf709
Reviewed-by: Michal Židek <mzidek@redhat.com>
ecf709
Reviewed-by: Simo Sorce <simo@redhat.com>
ecf709
Reviewed-by: Lukáš Slebodník <lslebodn@redhat.com>
ecf709
---
ecf709
 contrib/ci/configure.sh     |   7 +
ecf709
 contrib/ci/deps.sh          |   6 +
ecf709
 src/tests/intg/Makefile.am  |   4 +
ecf709
 src/tests/intg/kdc.py       | 175 +++++++++++++++++++++
ecf709
 src/tests/intg/krb5utils.py | 156 +++++++++++++++++++
ecf709
 src/tests/intg/test_kcm.py  | 361 ++++++++++++++++++++++++++++++++++++++++++++
ecf709
 6 files changed, 709 insertions(+)
ecf709
 create mode 100644 src/tests/intg/kdc.py
ecf709
 create mode 100644 src/tests/intg/krb5utils.py
ecf709
 create mode 100644 src/tests/intg/test_kcm.py
ecf709
ecf709
diff --git a/contrib/ci/configure.sh b/contrib/ci/configure.sh
ecf709
index 8e779cfe634a7555e0e8e3b52f42c07e62980fbc..7590743c2aa5fe31bcdf1a3e92a3f482dbec699b 100644
ecf709
--- a/contrib/ci/configure.sh
ecf709
+++ b/contrib/ci/configure.sh
ecf709
@@ -38,6 +38,13 @@ if [[ "$DISTRO_BRANCH" == -redhat-redhatenterprise*-6.*- ||
ecf709
         "--disable-cifs-idmap-plugin"
ecf709
         "--with-syslog=syslog"
ecf709
         "--without-python3-bindings"
ecf709
+        "--without-kcm"
ecf709
+    )
ecf709
+fi
ecf709
+
ecf709
+if [[ "$DISTRO_BRANCH" == -redhat-fedora-2[0-2]* ]]; then
ecf709
+    CONFIGURE_ARG_LIST+=(
ecf709
+        "--without-kcm"
ecf709
     )
ecf709
 fi
ecf709
 
ecf709
diff --git a/contrib/ci/deps.sh b/contrib/ci/deps.sh
ecf709
index c525e62e8c1d5b9fa042dee4ad03790dbceba242..4467e117c3a896a7f01ef7cb9e94fe28c2ea2838 100644
ecf709
--- a/contrib/ci/deps.sh
ecf709
+++ b/contrib/ci/deps.sh
ecf709
@@ -47,6 +47,8 @@ if [[ "$DISTRO_BRANCH" == -redhat-* ]]; then
ecf709
         uid_wrapper
ecf709
         python-requests
ecf709
         curl-devel
ecf709
+        krb5-server
ecf709
+        krb5-workstation
ecf709
     )
ecf709
     _DEPS_LIST_SPEC=`
ecf709
         sed -e 's/@PACKAGE_VERSION@/0/g' \
ecf709
@@ -122,6 +124,10 @@ if [[ "$DISTRO_BRANCH" == -debian-* ]]; then
ecf709
         libhttp-parser-dev
ecf709
         libjansson-dev
ecf709
         libcurl4-openssl-dev
ecf709
+        krb5-kdc
ecf709
+        krb5-admin-server
ecf709
+        krb5-user
ecf709
+        uuid-dev
ecf709
     )
ecf709
     DEPS_INTGCHECK_SATISFIED=true
ecf709
 fi
ecf709
diff --git a/src/tests/intg/Makefile.am b/src/tests/intg/Makefile.am
ecf709
index 1d36fa0d2d50307fbc871f5b2a6f0cb1cc95db81..8526beace09b15c99aa27ac98d5038d1980f6a71 100644
ecf709
--- a/src/tests/intg/Makefile.am
ecf709
+++ b/src/tests/intg/Makefile.am
ecf709
@@ -26,6 +26,9 @@ dist_noinst_DATA = \
ecf709
     files_ops.py \
ecf709
     test_files_ops.py \
ecf709
     test_files_provider.py \
ecf709
+    kdc.py \
ecf709
+    krb5utils.py \
ecf709
+    test_kcm.py \
ecf709
     $(NULL)
ecf709
 
ecf709
 config.py: config.py.m4
ecf709
@@ -80,5 +83,6 @@ intgcheck-installed: config.py passwd group
ecf709
 	NSS_WRAPPER_MODULE_FN_PREFIX="sss" \
ecf709
 	UID_WRAPPER=1 \
ecf709
 	UID_WRAPPER_ROOT=1 \
ecf709
+	NON_WRAPPED_UID=$$(echo $$UID) \
ecf709
 	    fakeroot $(PYTHON2) $(PYTEST) -v --tb=native $(INTGCHECK_PYTEST_ARGS) .
ecf709
 	rm -f $(DESTDIR)$(logpath)/*
ecf709
diff --git a/src/tests/intg/kdc.py b/src/tests/intg/kdc.py
ecf709
new file mode 100644
ecf709
index 0000000000000000000000000000000000000000..dec33a979916c0979561afb22dc39d6eb8894ff3
ecf709
--- /dev/null
ecf709
+++ b/src/tests/intg/kdc.py
ecf709
@@ -0,0 +1,175 @@
ecf709
+#
ecf709
+# MIT Kerberos server class
ecf709
+#
ecf709
+# Copyright (c) 2016 Red Hat, Inc.
ecf709
+#
ecf709
+# This is free software; you can redistribute it and/or modify it
ecf709
+# under the terms of the GNU General Public License as published by
ecf709
+# the Free Software Foundation; version 2 only
ecf709
+#
ecf709
+# This program is distributed in the hope that it will be useful, but
ecf709
+# WITHOUT ANY WARRANTY; without even the implied warranty of
ecf709
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
ecf709
+# General Public License for more details.
ecf709
+#
ecf709
+# You should have received a copy of the GNU General Public License
ecf709
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
ecf709
+#
ecf709
+import os
ecf709
+import signal
ecf709
+import shutil
ecf709
+import subprocess
ecf709
+
ecf709
+from util import *
ecf709
+
ecf709
+
ecf709
+class KDC(object):
ecf709
+    """
ecf709
+    MIT Kerberos KDC instance
ecf709
+    """
ecf709
+
ecf709
+    def __init__(self, basedir, realm,
ecf709
+                 includedir=None,
ecf709
+                 kdc_port=10088,
ecf709
+                 kadmin_port=10749,
ecf709
+                 master_key='master'):
ecf709
+        self.basedir = basedir
ecf709
+        self.realm = realm
ecf709
+        self.kdc_port = kdc_port
ecf709
+        self.kadmin_port = kadmin_port
ecf709
+        self.master_key = master_key
ecf709
+
ecf709
+        self.kdc_basedir = self.basedir + "/var/krb5kdc"
ecf709
+        self.includedir = includedir or (self.kdc_basedir + "/include")
ecf709
+        self.kdc_logdir = self.kdc_basedir + "/log"
ecf709
+        self.kdc_conf_path = self.kdc_basedir + "/kdc.conf"
ecf709
+        self.krb5_conf_path = self.kdc_basedir + "/krb5.conf"
ecf709
+
ecf709
+        self.kdc_pid_file = self.kdc_basedir + "/kdc.pid"
ecf709
+
ecf709
+        self.acl_file = self.kdc_basedir + "/kadm5.acl"
ecf709
+
ecf709
+        self.admin_princ = "admin/admin@" + self.realm
ecf709
+
ecf709
+    def start_kdc(self, extra_args=[]):
ecf709
+        args = ["krb5kdc", '-P', self.kdc_pid_file] + extra_args
ecf709
+        return self._run_in_env(args, self.get_krb5_env())
ecf709
+
ecf709
+    def stop_kdc(self):
ecf709
+        try:
ecf709
+            with open(self.kdc_pid_file, "r") as pid_file:
ecf709
+                os.kill(int(pid_file.read()), signal.SIGTERM)
ecf709
+        except IOError as ioex:
ecf709
+            if ioex.errno == 2:
ecf709
+                pass
ecf709
+            else:
ecf709
+                raise ioex
ecf709
+
ecf709
+    def teardown(self):
ecf709
+        self.stop_kdc()
ecf709
+        shutil.rmtree(self.kdc_basedir)
ecf709
+
ecf709
+    def set_up(self):
ecf709
+        self._create_config()
ecf709
+        self._create_acl()
ecf709
+        self._create_kdb()
ecf709
+
ecf709
+    def get_krb5_env(self):
ecf709
+        my_env = os.environ
ecf709
+        my_env['KRB5_CONFIG'] = self.krb5_conf_path
ecf709
+        my_env['KRB5_KDC_PROFILE'] = self.kdc_conf_path
ecf709
+        return my_env
ecf709
+
ecf709
+    def add_config(self, include_files):
ecf709
+        for name, contents in include_files.items():
ecf709
+            include_fpath = os.path.join(self.includedir, name)
ecf709
+            with open(include_fpath, 'w') as include_file:
ecf709
+                include_file.write(contents)
ecf709
+
ecf709
+    def add_principal(self, princ, password=None):
ecf709
+        args = ["kadmin.local", "-q"]
ecf709
+        if password is None:
ecf709
+            args += ["addprinc -randkey %s" % (princ)]
ecf709
+        else:
ecf709
+            args += ["addprinc -pw %s %s" % (password, princ)]
ecf709
+        return self._run_in_env(args, self.get_krb5_env())
ecf709
+
ecf709
+    def _run_in_env(self, args, env):
ecf709
+        cmd = subprocess.Popen(args, env=env)
ecf709
+        out, err = cmd.communicate()
ecf709
+        return cmd.returncode, out, err
ecf709
+
ecf709
+    def _create_config(self):
ecf709
+        try:
ecf709
+            os.makedirs(self.kdc_basedir)
ecf709
+            os.makedirs(self.kdc_logdir)
ecf709
+            os.makedirs(self.includedir)
ecf709
+        except OSError as osex:
ecf709
+            if osex.errno == 17:
ecf709
+                pass
ecf709
+
ecf709
+        kdc_conf = self._format_kdc_conf()
ecf709
+        with open(self.kdc_conf_path, 'w') as kdc_conf_file:
ecf709
+            kdc_conf_file.write(kdc_conf)
ecf709
+
ecf709
+        krb5_conf = self._format_krb5_conf()
ecf709
+        with open(self.krb5_conf_path, 'w') as krb5_conf_file:
ecf709
+            krb5_conf_file.write(krb5_conf)
ecf709
+
ecf709
+    def _create_acl(self):
ecf709
+        with open(self.acl_file, 'w') as acl_fobject:
ecf709
+            acl_fobject.write(self.admin_princ)
ecf709
+
ecf709
+    def _create_kdb(self):
ecf709
+        self._run_in_env(
ecf709
+            ['kdb5_util', 'create', '-W', '-s', '-P', self.master_key],
ecf709
+            self.get_krb5_env()
ecf709
+        )
ecf709
+
ecf709
+    def _format_kdc_conf(self):
ecf709
+        database_path = self.kdc_basedir + "/principal"
ecf709
+        key_stash = self.kdc_basedir + "/stash." + self.realm
ecf709
+
ecf709
+        kdc_logfile = "FILE:" + self.kdc_logdir + "/krb5kdc.log"
ecf709
+        kadmin_logfile = "FILE:" + self.kdc_logdir + "/kadmin.log"
ecf709
+        libkrb5_logfile = "FILE:" + self.kdc_logdir + "/libkrb5.log"
ecf709
+
ecf709
+        kdc_conf = unindent("""
ecf709
+        [kdcdefaults]
ecf709
+        kdc_ports = {self.kdc_port}
ecf709
+        kdc_tcp_ports = {self.kdc_port}
ecf709
+
ecf709
+        [realms]
ecf709
+            {self.realm} = {{
ecf709
+                kadmind_port = {self.kadmin_port}
ecf709
+                database_name = {database_path}
ecf709
+                key_stash_file = {key_stash}
ecf709
+                acl_file = {self.acl_file}
ecf709
+            }}
ecf709
+
ecf709
+        [logging]
ecf709
+            kdc = {kdc_logfile}
ecf709
+            admin_server = {kadmin_logfile}
ecf709
+            default = {libkrb5_logfile}
ecf709
+        """).format(**locals())
ecf709
+        return kdc_conf
ecf709
+
ecf709
+    def _format_krb5_conf(self):
ecf709
+        kdc_uri = "localhost:%d" % self.kdc_port
ecf709
+        kadmin_uri = "localhost:%d" % self.kadmin_port
ecf709
+
ecf709
+        krb5_conf = unindent("""
ecf709
+        includedir {self.includedir}
ecf709
+
ecf709
+        [libdefaults]
ecf709
+        default_realm = {self.realm}
ecf709
+        dns_lookup_kdc = false
ecf709
+        dns_lookup_realm = false
ecf709
+
ecf709
+        [realms]
ecf709
+            {self.realm} = {{
ecf709
+                kdc = {kdc_uri}
ecf709
+                admin_server = {kadmin_uri}
ecf709
+            }}
ecf709
+        """).format(**locals())
ecf709
+        return krb5_conf
ecf709
diff --git a/src/tests/intg/krb5utils.py b/src/tests/intg/krb5utils.py
ecf709
new file mode 100644
ecf709
index 0000000000000000000000000000000000000000..775cffd0bbfa011f2d8ffc1169dccfef96d78fab
ecf709
--- /dev/null
ecf709
+++ b/src/tests/intg/krb5utils.py
ecf709
@@ -0,0 +1,156 @@
ecf709
+#
ecf709
+# MIT Kerberos server class
ecf709
+#
ecf709
+# Copyright (c) 2016 Red Hat, Inc.
ecf709
+#
ecf709
+# This is free software; you can redistribute it and/or modify it
ecf709
+# under the terms of the GNU General Public License as published by
ecf709
+# the Free Software Foundation; version 2 only
ecf709
+#
ecf709
+# This program is distributed in the hope that it will be useful, but
ecf709
+# WITHOUT ANY WARRANTY; without even the implied warranty of
ecf709
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
ecf709
+# General Public License for more details.
ecf709
+#
ecf709
+# You should have received a copy of the GNU General Public License
ecf709
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
ecf709
+#
ecf709
+import os
ecf709
+import subprocess
ecf709
+
ecf709
+
ecf709
+class NoPrincipals(Exception):
ecf709
+    def __init__(self):
ecf709
+        Exception.__init__(self, 'No principals in the collection')
ecf709
+
ecf709
+
ecf709
+class PrincNotFound(Exception):
ecf709
+    def __init__(self, principal):
ecf709
+        Exception.__init__(self, 'Principal %s not found' % principal)
ecf709
+
ecf709
+
ecf709
+class Krb5Utils(object):
ecf709
+    """
ecf709
+    Helper class to test Kerberos command line utilities
ecf709
+    """
ecf709
+    def __init__(self, krb5_conf_path):
ecf709
+        self.krb5_conf_path = krb5_conf_path
ecf709
+
ecf709
+    def _run_in_env(self, args, stdin=None, extra_env=None):
ecf709
+        my_env = os.environ
ecf709
+        my_env['KRB5_CONFIG'] = self.krb5_conf_path
ecf709
+
ecf709
+        if 'KRB5CCNAME' in my_env:
ecf709
+            del my_env['KRB5CCNAME']
ecf709
+        if extra_env is not None:
ecf709
+            my_env.update(extra_env)
ecf709
+
ecf709
+        cmd = subprocess.Popen(args,
ecf709
+                               env=my_env,
ecf709
+                               stdin=subprocess.PIPE,
ecf709
+                               stdout=subprocess.PIPE,
ecf709
+                               stderr=subprocess.PIPE)
ecf709
+        out, err = cmd.communicate(stdin)
ecf709
+        return cmd.returncode, out.decode('utf-8'), err.decode('utf-8')
ecf709
+
ecf709
+    def kinit(self, principal, password, env=None):
ecf709
+        args = ["kinit", principal]
ecf709
+        return self._run_in_env(args, password.encode('utf-8'), env)
ecf709
+
ecf709
+    def kvno(self, principal, env=None):
ecf709
+        args = ["kvno", principal]
ecf709
+        return self._run_in_env(args, env)
ecf709
+
ecf709
+    def kdestroy(self, all_ccaches=False, env=None):
ecf709
+        args = ["kdestroy"]
ecf709
+        if all_ccaches is True:
ecf709
+            args += ["-A"]
ecf709
+        retval, _, _ = self._run_in_env(args, env)
ecf709
+        return retval
ecf709
+
ecf709
+    def kswitch(self, principal, env=None):
ecf709
+        args = ["kswitch", '-p', principal]
ecf709
+        retval, _, _ = self._run_in_env(args, env)
ecf709
+        return retval
ecf709
+
ecf709
+    def _check_klist_l(self, line, exp_principal, exp_cache):
ecf709
+        try:
ecf709
+            princ, cache = line.split()
ecf709
+        except ValueError:
ecf709
+            return False
ecf709
+
ecf709
+        if exp_cache is not None and cache != exp_cache:
ecf709
+            return False
ecf709
+
ecf709
+        if exp_principal != princ:
ecf709
+            return False
ecf709
+
ecf709
+        return True
ecf709
+
ecf709
+    def num_princs(self, env=None):
ecf709
+        args = ["klist", "-l"]
ecf709
+        retval, out, err = self._run_in_env(args, extra_env=env)
ecf709
+        if retval != 0:
ecf709
+            return 0
ecf709
+
ecf709
+        outlines = [l for l in out.split('\n') if len(l) > 1]
ecf709
+        return len(outlines) - 2
ecf709
+
ecf709
+    def list_princs(self, env=None):
ecf709
+        args = ["klist", "-l"]
ecf709
+        retval, out, err = self._run_in_env(args, extra_env=env)
ecf709
+        if retval == 1:
ecf709
+            raise NoPrincipals
ecf709
+        elif retval != 0:
ecf709
+            raise Exception("klist failed: %d: %s\n", retval, err)
ecf709
+
ecf709
+        outlines = out.split('\n')
ecf709
+        if len(outlines) < 2:
ecf709
+            raise Exception("Not enough output from klist -l")
ecf709
+
ecf709
+        return [l for l in outlines[2:] if len(l) > 0]
ecf709
+
ecf709
+    def has_principal(self, exp_principal, exp_cache=None, env=None):
ecf709
+        try:
ecf709
+            princlist = self.list_princs(env)
ecf709
+        except NoPrincipals:
ecf709
+            return False
ecf709
+
ecf709
+        for line in princlist:
ecf709
+            matches = self._check_klist_l(line, exp_principal, exp_cache)
ecf709
+            if matches is True:
ecf709
+                return True
ecf709
+
ecf709
+        return False
ecf709
+
ecf709
+    def default_principal(self, env=None):
ecf709
+        principals = self.list_princs(env)
ecf709
+        return principals[0].split()[0]
ecf709
+
ecf709
+    def _parse_klist_a(self, out):
ecf709
+        dflprinc = None
ecf709
+        thisrealm = None
ecf709
+        ccache_dict = dict()
ecf709
+
ecf709
+        for line in [l for l in out.split('\n') if len(l) > 0]:
ecf709
+            if line.startswith("Default principal"):
ecf709
+                dflprinc = line.split()[2]
ecf709
+                thisrealm = '@' + dflprinc.split('@')[1]
ecf709
+            elif thisrealm is not None and line.endswith(thisrealm):
ecf709
+                svc = line.split()[-1]
ecf709
+                if dflprinc in ccache_dict:
ecf709
+                    ccache_dict[dflprinc].append(svc)
ecf709
+                else:
ecf709
+                    ccache_dict[dflprinc] = [svc]
ecf709
+
ecf709
+        return ccache_dict
ecf709
+
ecf709
+    def list_all_princs(self, env=None):
ecf709
+        args = ["klist", "-A"]
ecf709
+        retval, out, err = self._run_in_env(args, extra_env=env)
ecf709
+        if retval == 1:
ecf709
+            raise NoPrincipals
ecf709
+        elif retval != 0:
ecf709
+            raise Exception("klist -A failed: %d: %s\n", retval, err)
ecf709
+
ecf709
+        return self._parse_klist_a(out)
ecf709
diff --git a/src/tests/intg/test_kcm.py b/src/tests/intg/test_kcm.py
ecf709
new file mode 100644
ecf709
index 0000000000000000000000000000000000000000..ad1e4923bfe339cb040464757431d2ef3bf57ce1
ecf709
--- /dev/null
ecf709
+++ b/src/tests/intg/test_kcm.py
ecf709
@@ -0,0 +1,361 @@
ecf709
+#
ecf709
+# KCM responder integration tests
ecf709
+#
ecf709
+# Copyright (c) 2016 Red Hat, Inc.
ecf709
+#
ecf709
+# This is free software; you can redistribute it and/or modify it
ecf709
+# under the terms of the GNU General Public License as published by
ecf709
+# the Free Software Foundation; version 2 only
ecf709
+#
ecf709
+# This program is distributed in the hope that it will be useful, but
ecf709
+# WITHOUT ANY WARRANTY; without even the implied warranty of
ecf709
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
ecf709
+# General Public License for more details.
ecf709
+#
ecf709
+# You should have received a copy of the GNU General Public License
ecf709
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
ecf709
+#
ecf709
+import os
ecf709
+import os.path
ecf709
+import stat
ecf709
+import subprocess
ecf709
+import pytest
ecf709
+import socket
ecf709
+import time
ecf709
+import signal
ecf709
+
ecf709
+import kdc
ecf709
+import krb5utils
ecf709
+import config
ecf709
+from util import unindent, run_shell
ecf709
+
ecf709
+class KcmTestEnv(object):
ecf709
+    def __init__(self, k5kdc, k5util):
ecf709
+        self.k5kdc = k5kdc
ecf709
+        self.k5util = k5util
ecf709
+        self.counter = 0
ecf709
+
ecf709
+    def my_uid(self):
ecf709
+        s_myuid = os.environ['NON_WRAPPED_UID']
ecf709
+        return int(s_myuid)
ecf709
+
ecf709
+    def ccname(self, my_uid=None):
ecf709
+        if my_uid is None:
ecf709
+            my_uid = self.my_uid()
ecf709
+
ecf709
+        return "KCM:%d" % my_uid
ecf709
+
ecf709
+
ecf709
+@pytest.fixture(scope="module")
ecf709
+def kdc_instance(request):
ecf709
+    """Kerberos server instance fixture"""
ecf709
+    kdc_instance = kdc.KDC(config.PREFIX, "KCMTEST")
ecf709
+    try:
ecf709
+        kdc_instance.set_up()
ecf709
+        kdc_instance.start_kdc()
ecf709
+    except:
ecf709
+        kdc_instance.teardown()
ecf709
+        raise
ecf709
+    request.addfinalizer(kdc_instance.teardown)
ecf709
+    return kdc_instance
ecf709
+
ecf709
+
ecf709
+def create_conf_fixture(request, contents):
ecf709
+    """Generate sssd.conf and add teardown for removing it"""
ecf709
+    with open(config.CONF_PATH, "w") as conf:
ecf709
+        conf.write(contents)
ecf709
+    os.chmod(config.CONF_PATH, stat.S_IRUSR | stat.S_IWUSR)
ecf709
+    request.addfinalizer(lambda: os.unlink(config.CONF_PATH))
ecf709
+
ecf709
+
ecf709
+def create_sssd_kcm_fixture(sock_path, request):
ecf709
+    if subprocess.call(['sssd', "--genconf"]) != 0:
ecf709
+        raise Exception("failed to regenerate confdb")
ecf709
+
ecf709
+    resp_path = os.path.join(config.LIBEXEC_PATH, "sssd", "sssd_kcm")
ecf709
+    if not os.access(resp_path, os.X_OK):
ecf709
+        # It would be cleaner to use pytest.mark.skipif on the package level
ecf709
+        # but upstream insists on supporting RHEL-6..
ecf709
+        pytest.skip("No KCM responder, skipping")
ecf709
+
ecf709
+    kcm_pid = os.fork()
ecf709
+    assert kcm_pid >= 0
ecf709
+
ecf709
+    if kcm_pid == 0:
ecf709
+        if subprocess.call([resp_path, "--uid=0", "--gid=0"]) != 0:
ecf709
+            print("sssd_kcm failed to start")
ecf709
+            sys.exit(99)
ecf709
+    else:
ecf709
+        abs_sock_path = os.path.join(config.RUNSTATEDIR, sock_path)
ecf709
+        sck = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
ecf709
+        for _ in range(1, 10):
ecf709
+            try:
ecf709
+                sck.connect(abs_sock_path)
ecf709
+            except:
ecf709
+                time.sleep(0.1)
ecf709
+            else:
ecf709
+                break
ecf709
+        sck.close()
ecf709
+        assert os.path.exists(abs_sock_path)
ecf709
+
ecf709
+    def kcm_teardown():
ecf709
+        if kcm_pid == 0:
ecf709
+            return
ecf709
+        os.kill(kcm_pid, signal.SIGTERM)
ecf709
+
ecf709
+    request.addfinalizer(kcm_teardown)
ecf709
+    return kcm_pid
ecf709
+
ecf709
+
ecf709
+@pytest.fixture
ecf709
+def setup_for_kcm(request, kdc_instance):
ecf709
+    """
ecf709
+    Just set up the local provider for tests and enable the KCM
ecf709
+    responder
ecf709
+    """
ecf709
+    kcm_path = os.path.join(config.RUNSTATEDIR, "kcm.socket")
ecf709
+
ecf709
+    sssd_conf = unindent("""\
ecf709
+        [sssd]
ecf709
+        domains = local
ecf709
+        services = nss
ecf709
+
ecf709
+        [domain/local]
ecf709
+        id_provider = local
ecf709
+
ecf709
+        [kcm]
ecf709
+        socket_path = {kcm_path}
ecf709
+    """).format(**locals())
ecf709
+
ecf709
+    kcm_socket_include = unindent("""
ecf709
+    [libdefaults]
ecf709
+    default_ccache_name = KCM:
ecf709
+    kcm_socket = {kcm_path}
ecf709
+    """).format(**locals())
ecf709
+    kdc_instance.add_config({'kcm_socket': kcm_socket_include})
ecf709
+
ecf709
+    create_conf_fixture(request, sssd_conf)
ecf709
+    create_sssd_kcm_fixture(kcm_path, request)
ecf709
+
ecf709
+    k5util = krb5utils.Krb5Utils(kdc_instance.krb5_conf_path)
ecf709
+
ecf709
+    return KcmTestEnv(kdc_instance, k5util)
ecf709
+
ecf709
+
ecf709
+def test_kcm_init_list_destroy(setup_for_kcm):
ecf709
+    """
ecf709
+    Test that kinit, kdestroy and klist work with KCM
ecf709
+    """
ecf709
+    testenv = setup_for_kcm
ecf709
+    testenv.k5kdc.add_principal("kcmtest", "Secret123")
ecf709
+
ecf709
+    ok = testenv.k5util.has_principal("kcmtest@KCMTEST")
ecf709
+    assert ok is False
ecf709
+    nprincs = testenv.k5util.num_princs()
ecf709
+    assert nprincs == 0
ecf709
+
ecf709
+    out, _, _ = testenv.k5util.kinit("kcmtest", "Secret123")
ecf709
+    assert out == 0
ecf709
+    nprincs = testenv.k5util.num_princs()
ecf709
+    assert nprincs == 1
ecf709
+
ecf709
+    exp_ccname = testenv.ccname()
ecf709
+    ok = testenv.k5util.has_principal("kcmtest@KCMTEST", exp_ccname)
ecf709
+    assert ok is True
ecf709
+
ecf709
+    out = testenv.k5util.kdestroy()
ecf709
+    assert out == 0
ecf709
+
ecf709
+    ok = testenv.k5util.has_principal("kcmtest@KCMTEST")
ecf709
+    assert ok is False
ecf709
+    nprincs = testenv.k5util.num_princs()
ecf709
+    assert nprincs == 0
ecf709
+
ecf709
+
ecf709
+def test_kcm_overwrite(setup_for_kcm):
ecf709
+    """
ecf709
+    That that reusing a ccache reinitializes the cache and doesn't
ecf709
+    add the same principal twice
ecf709
+    """
ecf709
+    testenv = setup_for_kcm
ecf709
+    testenv.k5kdc.add_principal("kcmtest", "Secret123")
ecf709
+    exp_ccache = {'kcmtest@KCMTEST': ['krbtgt/KCMTEST@KCMTEST']}
ecf709
+
ecf709
+    assert testenv.k5util.num_princs() == 0
ecf709
+
ecf709
+    out, _, _ = testenv.k5util.kinit("kcmtest", "Secret123")
ecf709
+    assert out == 0
ecf709
+    assert exp_ccache == testenv.k5util.list_all_princs()
ecf709
+
ecf709
+    out, _, _ = testenv.k5util.kinit("kcmtest", "Secret123")
ecf709
+    assert out == 0
ecf709
+    assert exp_ccache == testenv.k5util.list_all_princs()
ecf709
+
ecf709
+
ecf709
+def test_collection_init_list_destroy(setup_for_kcm):
ecf709
+    """
ecf709
+    Test that multiple principals and service tickets can be stored
ecf709
+    in a collection.
ecf709
+    """
ecf709
+    testenv = setup_for_kcm
ecf709
+    testenv.k5kdc.add_principal("alice", "alicepw")
ecf709
+    testenv.k5kdc.add_principal("bob", "bobpw")
ecf709
+    testenv.k5kdc.add_principal("carol", "carolpw")
ecf709
+    testenv.k5kdc.add_principal("host/somehostname")
ecf709
+
ecf709
+    assert testenv.k5util.num_princs() == 0
ecf709
+
ecf709
+    out, _, _ = testenv.k5util.kinit("alice", "alicepw")
ecf709
+    assert out == 0
ecf709
+    assert testenv.k5util.default_principal() == 'alice@KCMTEST'
ecf709
+    cc_coll = testenv.k5util.list_all_princs()
ecf709
+    assert len(cc_coll) == 1
ecf709
+    assert cc_coll['alice@KCMTEST'] == ['krbtgt/KCMTEST@KCMTEST']
ecf709
+    assert 'bob@KCMTEST' not in cc_coll
ecf709
+    assert 'carol@KCMTEST' not in cc_coll
ecf709
+
ecf709
+    out, _, _ = testenv.k5util.kinit("bob", "bobpw")
ecf709
+    assert out == 0
ecf709
+    assert testenv.k5util.default_principal() == 'bob@KCMTEST'
ecf709
+    cc_coll = testenv.k5util.list_all_princs()
ecf709
+    assert len(cc_coll) == 2
ecf709
+    assert cc_coll['alice@KCMTEST'] == ['krbtgt/KCMTEST@KCMTEST']
ecf709
+    assert cc_coll['bob@KCMTEST'] == ['krbtgt/KCMTEST@KCMTEST']
ecf709
+    assert 'carol@KCMTEST' not in cc_coll
ecf709
+
ecf709
+    out, _, _ = testenv.k5util.kinit("carol", "carolpw")
ecf709
+    assert out == 0
ecf709
+    assert testenv.k5util.default_principal() == 'carol@KCMTEST'
ecf709
+    cc_coll = testenv.k5util.list_all_princs()
ecf709
+    assert len(cc_coll) == 3
ecf709
+    assert cc_coll['alice@KCMTEST'] == ['krbtgt/KCMTEST@KCMTEST']
ecf709
+    assert cc_coll['bob@KCMTEST'] == ['krbtgt/KCMTEST@KCMTEST']
ecf709
+    assert cc_coll['carol@KCMTEST'] == ['krbtgt/KCMTEST@KCMTEST']
ecf709
+
ecf709
+    out, _, _ = testenv.k5util.kvno('host/somehostname')
ecf709
+    assert out == 0
ecf709
+    cc_coll = testenv.k5util.list_all_princs()
ecf709
+    assert len(cc_coll) == 3
ecf709
+    assert set(cc_coll['carol@KCMTEST']) == set(['krbtgt/KCMTEST@KCMTEST',
ecf709
+                                                 'host/somehostname@KCMTEST'])
ecf709
+
ecf709
+    out = testenv.k5util.kdestroy()
ecf709
+    assert out == 0
ecf709
+    assert testenv.k5util.default_principal() == 'bob@KCMTEST'
ecf709
+    cc_coll = testenv.k5util.list_all_princs()
ecf709
+    assert len(cc_coll) == 2
ecf709
+    assert cc_coll['alice@KCMTEST'] == ['krbtgt/KCMTEST@KCMTEST']
ecf709
+    assert cc_coll['bob@KCMTEST'] == ['krbtgt/KCMTEST@KCMTEST']
ecf709
+    assert 'carol@KCMTEST' not in cc_coll
ecf709
+
ecf709
+    # FIXME - a bug in libkrb5?
ecf709
+    #out = testenv.k5util.kdestroy(all_ccaches=True)
ecf709
+    #assert out == 0
ecf709
+    #cc_coll = testenv.k5util.list_all_princs()
ecf709
+    #assert len(cc_coll) == 0
ecf709
+
ecf709
+
ecf709
+def test_kswitch(setup_for_kcm):
ecf709
+    """
ecf709
+    Test switching between principals
ecf709
+    """
ecf709
+    testenv = setup_for_kcm
ecf709
+    testenv.k5kdc.add_principal("alice", "alicepw")
ecf709
+    testenv.k5kdc.add_principal("bob", "bobpw")
ecf709
+    testenv.k5kdc.add_principal("host/somehostname")
ecf709
+    testenv.k5kdc.add_principal("host/differenthostname")
ecf709
+
ecf709
+    out, _, _ = testenv.k5util.kinit("alice", "alicepw")
ecf709
+    assert out == 0
ecf709
+    assert testenv.k5util.default_principal() == 'alice@KCMTEST'
ecf709
+
ecf709
+    out, _, _ = testenv.k5util.kinit("bob", "bobpw")
ecf709
+    assert out == 0
ecf709
+    assert testenv.k5util.default_principal() == 'bob@KCMTEST'
ecf709
+
ecf709
+    cc_coll = testenv.k5util.list_all_princs()
ecf709
+    assert len(cc_coll) == 2
ecf709
+    assert cc_coll['alice@KCMTEST'] == ['krbtgt/KCMTEST@KCMTEST']
ecf709
+    assert cc_coll['bob@KCMTEST'] == ['krbtgt/KCMTEST@KCMTEST']
ecf709
+
ecf709
+    out = testenv.k5util.kswitch("alice@KCMTEST")
ecf709
+    assert testenv.k5util.default_principal() == 'alice@KCMTEST'
ecf709
+    out, _, _ = testenv.k5util.kvno('host/somehostname')
ecf709
+    assert out == 0
ecf709
+    cc_coll = testenv.k5util.list_all_princs()
ecf709
+    assert len(cc_coll) == 2
ecf709
+    assert set(cc_coll['alice@KCMTEST']) == set(['krbtgt/KCMTEST@KCMTEST',
ecf709
+                                                 'host/somehostname@KCMTEST'])
ecf709
+    assert cc_coll['bob@KCMTEST'] == ['krbtgt/KCMTEST@KCMTEST']
ecf709
+
ecf709
+    out = testenv.k5util.kswitch("bob@KCMTEST")
ecf709
+    assert testenv.k5util.default_principal() == 'bob@KCMTEST'
ecf709
+    out, _, _ = testenv.k5util.kvno('host/differenthostname')
ecf709
+    assert out == 0
ecf709
+    cc_coll = testenv.k5util.list_all_princs()
ecf709
+    assert len(cc_coll) == 2
ecf709
+    assert set(cc_coll['alice@KCMTEST']) == set(['krbtgt/KCMTEST@KCMTEST',
ecf709
+                                                 'host/somehostname@KCMTEST'])
ecf709
+    assert set(cc_coll['bob@KCMTEST']) == set([
ecf709
+                                    'krbtgt/KCMTEST@KCMTEST',
ecf709
+                                    'host/differenthostname@KCMTEST'])
ecf709
+
ecf709
+
ecf709
+def test_subsidiaries(setup_for_kcm):
ecf709
+    """
ecf709
+    Test that subsidiary caches are usable and KCM: without specifying UID
ecf709
+    can be used to identify the collection
ecf709
+    """
ecf709
+    testenv = setup_for_kcm
ecf709
+    testenv.k5kdc.add_principal("alice", "alicepw")
ecf709
+    testenv.k5kdc.add_principal("bob", "bobpw")
ecf709
+    testenv.k5kdc.add_principal("host/somehostname")
ecf709
+    testenv.k5kdc.add_principal("host/differenthostname")
ecf709
+
ecf709
+    out, _, _ = testenv.k5util.kinit("alice", "alicepw")
ecf709
+    assert out == 0
ecf709
+    out, _, _ = testenv.k5util.kvno('host/somehostname')
ecf709
+
ecf709
+    out, _, _ = testenv.k5util.kinit("bob", "bobpw")
ecf709
+    assert out == 0
ecf709
+    out, _, _ = testenv.k5util.kvno('host/differenthostname')
ecf709
+
ecf709
+    exp_cc_coll = dict()
ecf709
+    exp_cc_coll['alice@KCMTEST'] = 'host/somehostname@KCMTEST'
ecf709
+    exp_cc_coll['bob@KCMTEST'] = 'host/differenthostname@KCMTEST'
ecf709
+
ecf709
+    klist_l = testenv.k5util.list_princs()
ecf709
+    princ_ccache = dict()
ecf709
+    for line in klist_l:
ecf709
+        princ, subsidiary = line.split()
ecf709
+        princ_ccache[princ] = subsidiary
ecf709
+
ecf709
+    for princ, subsidiary in princ_ccache.items():
ecf709
+        env = {'KRB5CCNAME': subsidiary}
ecf709
+        cc_coll = testenv.k5util.list_all_princs(env=env)
ecf709
+        assert len(cc_coll) == 1
ecf709
+        assert princ in cc_coll
ecf709
+        assert exp_cc_coll[princ] in cc_coll[princ]
ecf709
+
ecf709
+    cc_coll = testenv.k5util.list_all_princs(env={'KRB5CCNAME': 'KCM:'})
ecf709
+    assert len(cc_coll) == 2
ecf709
+    assert set(cc_coll['alice@KCMTEST']) == set(['krbtgt/KCMTEST@KCMTEST',
ecf709
+                                                 'host/somehostname@KCMTEST'])
ecf709
+    assert set(cc_coll['bob@KCMTEST']) == set([
ecf709
+                                            'krbtgt/KCMTEST@KCMTEST',
ecf709
+                                            'host/differenthostname@KCMTEST'])
ecf709
+
ecf709
+
ecf709
+def test_kdestroy_nocache(setup_for_kcm):
ecf709
+    """
ecf709
+    Destroying a non-existing ccache should not throw an error
ecf709
+    """
ecf709
+    testenv = setup_for_kcm
ecf709
+    testenv.k5kdc.add_principal("alice", "alicepw")
ecf709
+    out, _, _ = testenv.k5util.kinit("alice", "alicepw")
ecf709
+    assert out == 0
ecf709
+
ecf709
+    testenv.k5util.kdestroy()
ecf709
+    assert out == 0
ecf709
+    out = testenv.k5util.kdestroy()
ecf709
+    assert out == 0
ecf709
-- 
ecf709
2.9.3
ecf709