706194
From 857713c5a9c8e0b62c06dd92e69c09eeb34b2e99 Mon Sep 17 00:00:00 2001
706194
From: Anuja More <amore@redhat.com>
706194
Date: Mon, 23 May 2022 12:26:34 +0530
706194
Subject: [PATCH] Add end to end integration tests for external IdP
706194
706194
Added tests for HBAC and SUDO rule and other
706194
test scenarios.
706194
706194
Related : https://pagure.io/freeipa/issue/8805
706194
Related: https://pagure.io/freeipa/issue/8803
706194
Related: https://pagure.io/freeipa/issue/8804
706194
706194
Signed-off-by: Anuja More <amore@redhat.com>
706194
Reviewed-By: Florence Blanc-Renaud <flo@redhat.com>
706194
Reviewed-By: Florence Blanc-Renaud <flo@redhat.com>
706194
---
706194
 ipatests/test_integration/test_idp.py | 260 ++++++++++++++++++++++----
706194
 1 file changed, 226 insertions(+), 34 deletions(-)
706194
706194
diff --git a/ipatests/test_integration/test_idp.py b/ipatests/test_integration/test_idp.py
706194
index 8f9e92e6a..2ffe6a208 100644
706194
--- a/ipatests/test_integration/test_idp.py
706194
+++ b/ipatests/test_integration/test_idp.py
706194
@@ -1,6 +1,8 @@
706194
 from __future__ import absolute_import
706194
 
706194
 import time
706194
+import pytest
706194
+import re
706194
 
706194
 import textwrap
706194
 from ipaplatform.paths import paths
706194
@@ -22,12 +24,12 @@ driver.get(verification_uri)
706194
 try:
706194
     element = WebDriverWait(driver, 90).until(
706194
         EC.presence_of_element_located((By.ID, "username")))
706194
-    driver.find_element_by_id("username").send_keys("testuser1")
706194
-    driver.find_element_by_id("password").send_keys("{passwd}")
706194
-    driver.find_element_by_id("kc-login").click()
706194
+    driver.find_element(By.ID, "username").send_keys("testuser1")
706194
+    driver.find_element(By.ID, "password").send_keys("{passwd}")
706194
+    driver.find_element(By.ID, "kc-login").click()
706194
     element = WebDriverWait(driver, 90).until(
706194
         EC.presence_of_element_located((By.ID, "kc-login")))
706194
-    driver.find_element_by_id("kc-login").click()
706194
+    driver.find_element(By.ID, "kc-login").click()
706194
     assert "Device Login Successful" in driver.page_source
706194
 finally:
706194
     now = datetime.now().strftime("%M-%S")
706194
@@ -39,18 +41,12 @@ finally:
706194
 def add_user_code(host, verification_uri):
706194
     contents = user_code_script.format(uri=verification_uri,
706194
                                        passwd=host.config.admin_password)
706194
-    host.put_file_contents("/tmp/add_user_code.py", contents)
706194
-    tasks.run_repeatedly(
706194
-        host, ['python3', '/tmp/add_user_code.py'])
706194
-
706194
-
706194
-def get_verification_uri(host, since, keycloak_server_name):
706194
-    command = textwrap.dedent("""
706194
-    journalctl -u ipa-otpd\\* --since="%s" | grep "user_code:" | awk '{ print substr($7,2,9) }'""" % since)  # noqa: E501
706194
-    user_code = host.run_command(command).stdout_text.rstrip("\r\n")
706194
-    uri = ("https://{0}:8443/auth/realms/master/device?user_code={1}".format(
706194
-        keycloak_server_name, user_code))
706194
-    return uri
706194
+    try:
706194
+        host.put_file_contents("/tmp/add_user_code.py", contents)
706194
+        tasks.run_repeatedly(
706194
+            host, ['python3', '/tmp/add_user_code.py'])
706194
+    finally:
706194
+        host.run_command(["rm", "-f", "/tmp/add_user_code.py"])
706194
 
706194
 
706194
 def kinit_idp(host, user, keycloak_server):
706194
@@ -58,11 +54,14 @@ def kinit_idp(host, user, keycloak_server):
706194
     tasks.kdestroy_all(host)
706194
     # create armor for FAST
706194
     host.run_command(["kinit", "-n", "-c", ARMOR])
706194
-    since = time.strftime('%Y-%m-%d %H:%M:%S')
706194
     cmd = ["kinit", "-T", ARMOR, user]
706194
+
706194
     with host.spawn_expect(cmd, default_timeout=100) as e:
706194
-        e.expect('Authenticate at .+: ')
706194
-        uri = get_verification_uri(host, since, keycloak_server.hostname)
706194
+        e.expect('Authenticate at (.+) and press ENTER.:')
706194
+        prompt = e.get_last_output()
706194
+        uri = re.search(r'Authenticate at (.*?) and press ENTER.:', prompt
706194
+                        ).group(1)
706194
+        time.sleep(15)
706194
         if uri:
706194
             add_user_code(keycloak_server, uri)
706194
         e.sendline('\n')
706194
@@ -74,21 +73,27 @@ def kinit_idp(host, user, keycloak_server):
706194
 
706194
 class TestIDPKeycloak(IntegrationTest):
706194
 
706194
-    num_replicas = 1
706194
+    num_replicas = 2
706194
     topology = 'line'
706194
 
706194
     @classmethod
706194
     def install(cls, mh):
706194
-        tasks.install_master(cls.master, setup_dns=True)
706194
-        tasks.install_client(cls.master, cls.replicas[0])
706194
-        content = cls.master.get_file_contents(paths.IPA_DEFAULT_CONF,
706194
-                                               encoding='utf-8')
706194
-        new_content = content + "\noidc_child_debug_level = 10"
706194
-        cls.master.put_file_contents(paths.IPA_DEFAULT_CONF, new_content)
706194
+        cls.client = cls.replicas[0]
706194
+        cls.replica = cls.replicas[1]
706194
+        tasks.install_master(cls.master)
706194
+        tasks.install_client(cls.master, cls.replicas[0],
706194
+                             extra_args=["--mkhomedir"])
706194
+        tasks.install_replica(cls.master, cls.replicas[1])
706194
+        for host in [cls.master, cls.replicas[0], cls.replicas[1]]:
706194
+            content = host.get_file_contents(paths.IPA_DEFAULT_CONF,
706194
+                                             encoding='utf-8')
706194
+            new_content = content + "\noidc_child_debug_level = 10"
706194
+            host.put_file_contents(paths.IPA_DEFAULT_CONF, new_content)
706194
         with tasks.remote_sssd_config(cls.master) as sssd_config:
706194
             sssd_config.edit_domain(
706194
                 cls.master.domain, 'krb5_auth_timeout', 1100)
706194
         tasks.clear_sssd_cache(cls.master)
706194
+        tasks.clear_sssd_cache(cls.replicas[0])
706194
         tasks.kinit_admin(cls.master)
706194
         cls.master.run_command(["ipa", "config-mod", "--user-auth-type=idp",
706194
                                 "--user-auth-type=password"])
706194
@@ -97,20 +102,207 @@ class TestIDPKeycloak(IntegrationTest):
706194
         cls.replicas[0].run_command(xvfb)
706194
 
706194
     def test_auth_keycloak_idp(self):
706194
-        keycloak_srv = self.replicas[0]
706194
-        create_quarkus.setup_keycloakserver(keycloak_srv)
706194
+        """
706194
+        Test case to check that OAuth 2.0 Device
706194
+        Authorization Grant is working as
706194
+        expected for user configured with external idp.
706194
+        """
706194
+        create_quarkus.setup_keycloakserver(self.client)
706194
         time.sleep(60)
706194
-        create_quarkus.setup_keycloak_client(keycloak_srv)
706194
+        create_quarkus.setup_keycloak_client(self.client)
706194
         tasks.kinit_admin(self.master)
706194
-        cmd = ["ipa", "idp-add", "keycloak", "--provider=keycloak",
706194
+        cmd = ["ipa", "idp-add", "keycloakidp", "--provider=keycloak",
706194
                "--client-id=ipa_oidc_client", "--org=master",
706194
-               "--base-url={0}:8443/auth".format(keycloak_srv.hostname)]
706194
+               "--base-url={0}:8443/auth".format(self.client.hostname)]
706194
         self.master.run_command(cmd, stdin_text="{0}\n{0}".format(
706194
-            keycloak_srv.config.admin_password))
706194
+            self.client.config.admin_password))
706194
         tasks.user_add(self.master, 'keycloakuser',
706194
                        extra_args=["--user-auth-type=idp",
706194
                                    "--idp-user-id=testuser1@ipa.test",
706194
-                                   "--idp=keycloak"]
706194
+                                   "--idp=keycloakidp"]
706194
                        )
706194
+        list_user = self.master.run_command(
706194
+            ["ipa", "user-find", "--idp-user-id=testuser1@ipa.test"]
706194
+        )
706194
+        assert "keycloakuser" in list_user.stdout_text
706194
+        list_by_idp = self.master.run_command(["ipa", "user-find",
706194
+                                               "--idp=keycloakidp"]
706194
+                                              )
706194
+        assert "keycloakuser" in list_by_idp.stdout_text
706194
+        list_by_user = self.master.run_command(
706194
+            ["ipa", "user-find", "--idp-user-id=testuser1@ipa.test", "--all"]
706194
+        )
706194
+        assert "keycloakidp" in list_by_user.stdout_text
706194
+        tasks.clear_sssd_cache(self.master)
706194
+        kinit_idp(self.master, 'keycloakuser', keycloak_server=self.client)
706194
+
706194
+    @pytest.fixture
706194
+    def hbac_setup_teardown(self):
706194
+        # allow sshd only on given host
706194
+        tasks.kinit_admin(self.master)
706194
+        self.master.run_command(["ipa", "hbacrule-disable", "allow_all"])
706194
+        self.master.run_command(["ipa", "hbacrule-add", "rule1"])
706194
+        self.master.run_command(["ipa", "hbacrule-add-user", "rule1",
706194
+                                 "--users=keycloakuser"]
706194
+                                )
706194
+        self.master.run_command(["ipa", "hbacrule-add-host", "rule1",
706194
+                                 "--hosts", self.replica.hostname])
706194
+        self.master.run_command(["ipa", "hbacrule-add-service", "rule1",
706194
+                                 "--hbacsvcs=sshd"]
706194
+                                )
706194
+        tasks.clear_sssd_cache(self.master)
706194
+        tasks.clear_sssd_cache(self.replica)
706194
+        yield
706194
+
706194
+        # cleanup
706194
+        tasks.kinit_admin(self.master)
706194
+        self.master.run_command(["ipa", "hbacrule-enable", "allow_all"])
706194
+        self.master.run_command(["ipa", "hbacrule-del", "rule1"])
706194
+
706194
+    def test_auth_hbac(self, hbac_setup_teardown):
706194
+        """
706194
+        Test case to check that hbacrule is working as
706194
+        expected for user configured with external idp.
706194
+        """
706194
+        kinit_idp(self.master, 'keycloakuser', keycloak_server=self.client)
706194
+        ssh_cmd = "ssh -q -K -l keycloakuser {0} whoami"
706194
+        valid_ssh = self.master.run_command(
706194
+            ssh_cmd.format(self.replica.hostname))
706194
+        assert "keycloakuser" in valid_ssh.stdout_text
706194
+        negative_ssh = self.master.run_command(
706194
+            ssh_cmd.format(self.master.hostname), raiseonerr=False
706194
+        )
706194
+        assert negative_ssh.returncode == 255
706194
+
706194
+    def test_auth_sudo_idp(self):
706194
+        """
706194
+        Test case to check that sudorule is working as
706194
+        expected for user configured with external idp.
706194
+        """
706194
+        tasks.kdestroy_all(self.master)
706194
+        tasks.kinit_admin(self.master)
706194
+        #  rule: keycloakuser are allowed to execute yum on
706194
+        #  the client machine as root.
706194
+        cmdlist = [
706194
+            ["ipa", "sudocmd-add", "/usr/bin/yum"],
706194
+            ["ipa", "sudorule-add", "sudorule"],
706194
+            ['ipa', 'sudorule-add-user', '--users=keycloakuser',
706194
+             'sudorule'],
706194
+            ['ipa', 'sudorule-add-host', '--hosts',
706194
+             self.client.hostname, 'sudorule'],
706194
+            ['ipa', 'sudorule-add-runasuser',
706194
+             '--users=root', 'sudorule'],
706194
+            ['ipa', 'sudorule-add-allow-command',
706194
+             '--sudocmds=/usr/bin/yum', 'sudorule'],
706194
+            ['ipa', 'sudorule-show', 'sudorule', '--all'],
706194
+            ['ipa', 'sudorule-add-option',
706194
+             'sudorule', '--sudooption', "!authenticate"]
706194
+        ]
706194
+        for cmd in cmdlist:
706194
+            self.master.run_command(cmd)
706194
+        tasks.clear_sssd_cache(self.master)
706194
+        tasks.clear_sssd_cache(self.client)
706194
+        try:
706194
+            cmd = 'sudo -ll -U keycloakuser'
706194
+            test = self.client.run_command(cmd).stdout_text
706194
+            assert "User keycloakuser may run the following commands" in test
706194
+            assert "/usr/bin/yum" in test
706194
+            kinit_idp(self.client, 'keycloakuser', self.client)
706194
+            test_sudo = 'su -c "sudo yum list wget" keycloakuser'
706194
+            self.client.run_command(test_sudo)
706194
+            list_fail = self.master.run_command(cmd).stdout_text
706194
+            assert "User keycloakuser is not allowed to run sudo" in list_fail
706194
+        finally:
706194
+            tasks.kinit_admin(self.master)
706194
+            self.master.run_command(['ipa', 'sudorule-del', 'sudorule'])
706194
+            self.master.run_command(["ipa", "sudocmd-del", "/usr/bin/yum"])
706194
+
706194
+    def test_auth_replica(self):
706194
+        """
706194
+        Test case to check that OAuth 2.0 Device
706194
+        Authorization is working as expected on replica.
706194
+        """
706194
+        tasks.clear_sssd_cache(self.master)
706194
+        tasks.clear_sssd_cache(self.replica)
706194
+        tasks.kinit_admin(self.replica)
706194
+        list_user = self.master.run_command(
706194
+            ["ipa", "user-find", "--idp-user-id=testuser1@ipa.test"]
706194
+        )
706194
+        assert "keycloakuser" in list_user.stdout_text
706194
+        list_by_idp = self.replica.run_command(["ipa", "user-find",
706194
+                                                "--idp=keycloakidp"]
706194
+                                               )
706194
+        assert "keycloakuser" in list_by_idp.stdout_text
706194
+        list_by_user = self.replica.run_command(
706194
+            ["ipa", "user-find", "--idp-user-id=testuser1@ipa.test", "--all"]
706194
+        )
706194
+        assert "keycloakidp" in list_by_user.stdout_text
706194
+        kinit_idp(self.replica, 'keycloakuser', keycloak_server=self.client)
706194
+
706194
+    def test_idp_with_services(self):
706194
+        """
706194
+        Test case to check that services can be configured
706194
+        auth indicator as idp.
706194
+        """
706194
         tasks.clear_sssd_cache(self.master)
706194
-        kinit_idp(self.master, 'keycloakuser', keycloak_srv)
706194
+        tasks.kinit_admin(self.master)
706194
+        domain = self.master.domain.name.upper()
706194
+        services = [
706194
+            "DNS/{0}@{1}".format(self.master.hostname, domain),
706194
+            "HTTP/{0}@{1}".format(self.client.hostname, domain),
706194
+            "dogtag/{0}@{1}".format(self.master.hostname, domain),
706194
+            "ipa-dnskeysyncd/{0}@{1}".format(self.master.hostname, domain)
706194
+        ]
706194
+        try:
706194
+            for service in services:
706194
+                test = self.master.run_command(["ipa", "service-mod", service,
706194
+                                                "--auth-ind=idp"]
706194
+                                               )
706194
+                assert "Authentication Indicators: idp" in test.stdout_text
706194
+        finally:
706194
+            for service in services:
706194
+                self.master.run_command(["ipa", "service-mod", service,
706194
+                                         "--auth-ind="])
706194
+
706194
+    def test_idp_backup_restore(self):
706194
+        """
706194
+        Test case to check that after restore data is retrieved
706194
+        with related idp configuration.
706194
+        """
706194
+        tasks.kinit_admin(self.master)
706194
+        user = "backupuser"
706194
+        cmd = ["ipa", "idp-add", "testidp", "--provider=keycloak",
706194
+               "--client-id=ipa_oidc_client", "--org=master",
706194
+               "--base-url={0}:8443/auth".format(self.client.hostname)]
706194
+        self.master.run_command(cmd, stdin_text="{0}\n{0}".format(
706194
+            self.client.config.admin_password))
706194
+
706194
+        tasks.user_add(self.master, user,
706194
+                       extra_args=["--user-auth-type=idp",
706194
+                                   "--idp-user-id=testuser1@ipa.test",
706194
+                                   "--idp=testidp"]
706194
+                       )
706194
+
706194
+        backup_path = tasks.get_backup_dir(self.master)
706194
+        # change data after backup
706194
+        self.master.run_command(['ipa', 'user-del', user])
706194
+        self.master.run_command(['ipa', 'idp-del', 'testidp'])
706194
+        dirman_password = self.master.config.dirman_password
706194
+        self.master.run_command(['ipa-restore', backup_path],
706194
+                                stdin_text=dirman_password + '\nyes')
706194
+        try:
706194
+            list_user = self.master.run_command(
706194
+                ['ipa', 'user-show', 'backupuser', '--all']
706194
+            ).stdout_text
706194
+            assert "External IdP configuration: testidp" in list_user
706194
+            assert "User authentication types: idp" in list_user
706194
+            assert ("External IdP user identifier: "
706194
+                    "testuser1@ipa.test") in list_user
706194
+            list_idp = self.master.run_command(['ipa', 'idp-find', 'testidp'])
706194
+            assert "testidp" in list_idp.stdout_text
706194
+            kinit_idp(self.master, user, self.client)
706194
+        finally:
706194
+            tasks.kdestroy_all(self.master)
706194
+            tasks.kinit_admin(self.master)
706194
+            self.master.run_command(["rm", "-rf", backup_path])
706194
+            self.master.run_command(["ipa", "idp-del", "testidp"])
706194
-- 
706194
2.36.1
706194