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