#!/usr/bin/python3
#
# Univention Keycloak tests
#
# Like what you see? Join us!
# https://www.univention.com/about-us/careers/vacancies/
#
# Copyright 2022 Univention GmbH
#
# https://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <https://www.gnu.org/licenses/>.

import importlib
import json
import os.path
import subprocess
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Union

import pytest
from keycloak import KeycloakAdmin, KeycloakOpenID
from keycloak.connection import ConnectionManager
from keycloak.exceptions import KeycloakError, KeycloakGetError
from univention.config_registry import ConfigRegistry
from univention.udm import UDM
import uuid
import base64

os.environ["UCS_TEST_SELENIUM_IGNORE_CERTS"] = "1"
test_lib = os.environ.get('UCS_TEST_LIB', 'univention.testing.apptest')
try:
	test_lib = importlib.import_module(test_lib)
except ImportError:
	print('Could not import {}. Maybe set $UCS_TEST_LIB'.format(test_lib))
	sys.exit(1)

SESSION_ID = ''


@dataclass(unsafe_hash=True)
class Config:
	hostname: str
	domain: str
	url: str = None
	username: str = 'Administrator'
	password: Union[str, Path] = 'univention'
	client_id: str = 'foo-cli'

	def __post_init__(self):
		self.url = f'https://ucs-sso-ng.{self.domain}'

		if isinstance(self.password, Path) or Path(self.password).is_file():
			with open(self.password, 'r') as fd:
				self.password = fd.read().strip()


@pytest.fixture(scope='session')
def kc_config() -> Config:
	# load UCR
	ucr = ConfigRegistry()
	ucr.load()

	yield Config(
		hostname=ucr.get('hostname'),
		domain=ucr.get('domainname'),
	)


@pytest.fixture
def kc_admin(kc_config) -> KeycloakAdmin:
	yield KeycloakAdmin(
		server_url=kc_config.url,
		username=kc_config.username,
		password=kc_config.password,
		realm_name='ucs',
		user_realm_name='master',
		verify=True,
	)


@pytest.fixture
def oidc_client(kc_admin) -> str:
	"""
	Creates OIDC client in Keycloak

	:param kc_admin:  KeycloakAdmin configuration object
	:return: ID of created client - it is generated by Keycloak and differs from what we passed as clientId in payload
	"""

	client_id = 'foo-cli'
	args = ['univention-keycloak', 'oidc/rp', 'create', '--app-url=', client_id]
	subprocess.call(args)

	kc_client_id = kc_admin.get_client_id(client_id)
	if not kc_client_id:
		raise RuntimeError(f'Failed to create {client_id} OIDC client')

	yield kc_client_id

	try:
		kc_admin.delete_client(kc_client_id)
	except KeycloakGetError:
		pass


def test_create_oidc_client(oidc_client, kc_config):
	assert oidc_client


def test_delete_oidc_client(oidc_client, kc_admin, kc_config):
	kc_admin.delete_client(oidc_client)
	assert not kc_admin.get_client_id(oidc_client)


def __build_keycloak_admin_connection(kc_username, kc_password, is_file=False):
	# load UCR
	ucr = ConfigRegistry()
	ucr.load()
	hostname = ucr.get("hostname")
	domain = ucr.get("domainname")

	kc_user = kc_username
	kc_pass = kc_password
	if is_file:
		pwdfile = kc_password
		with open(pwdfile, 'r') as fd:
			kc_pass = fd.read().strip()

	# derived composite vars #
	if hostname and not hostname == "unassigned-hostname":
		server_fqdn_with_subdomain = "https://ucs-sso-ng.{}".format(domain)
	else:
		server_fqdn_with_subdomain = "https://ucs-sso-ng.{}".format(domain)

	kc_admin_auth_url = "{}".format(server_fqdn_with_subdomain)

	# log into default realm in case UCS realm doesn't exist yet #
	kc_admin = KeycloakAdmin(server_url=kc_admin_auth_url, username=kc_user, password=kc_pass, realm_name="master", user_realm_name="master", verify=True)
	global SESSION_ID
	SESSION_ID = kc_admin.get_user_id(username=kc_user)
	return kc_admin


def __build_keycloak_openID_connection():
	# load UCR
	ucr = ConfigRegistry()
	ucr.load()
	hostname = ucr.get("hostname")
	domain = ucr.get("domainname")

	# derived composite vars #
	if hostname and not hostname == "unassigned-hostname":
		server_fqdn_with_subdomain = "https://ucs-sso-ng.{}".format(domain)
	else:
		server_fqdn_with_subdomain = "https://ucs-sso-ng.{}".format(domain)

	kc_admin_auth_url = "{}".format(server_fqdn_with_subdomain)

	# log into default realm in case UCS realm doesn't exist yet #
	kc_client = KeycloakOpenID(server_url=kc_admin_auth_url, client_id="admin-cli", realm_name="ucs", client_secret_key="secret")
	return kc_client


def _test_keycloak_admin_login(username="Administrator", password="univention"):
	print("test keycloak admin login")
	kc_admin = __build_keycloak_admin_connection(username, password)

	assert kc_admin.realm_name == "master", kc_admin.realm_name
	assert isinstance(kc_admin.connection, ConnectionManager), type(kc_admin.connection)
	assert kc_admin.client_id == "admin-cli", kc_admin.client_id
	assert kc_admin.client_secret_key is None, kc_admin.client_secret_key
	print("Admin login successfully")
	_logout_keycloak_client(kc_admin)


def _test_keycloak_admin_login_fail(username="nonExistUser", password="univention"):
	print("test keycloak admin login")
	try:
		kc_admin = __build_keycloak_admin_connection(username, password)
		assert True, "Non existing user should not be able to log in."
	except KeycloakError:
		print("Login as a non Admin/existing user fail.")


def _test_keycloak_user_login(username="Administrator", password="univention"):
	print("test keycloak user login")
	oID_client = __build_keycloak_openID_connection()

	token = oID_client.token(username, password)
	userinfo = oID_client.userinfo(token['access_token'])
	assert userinfo["preferred_username"] == username.lower(), "Wrong user login"
	oID_client.logout(token['refresh_token'])
	print("User OpenID log in successfully")


def _test_keycloak_user_login_fail(username="nonExistUser", password="univention"):
	print("test keycloak user login fail")
	oID_client = __build_keycloak_openID_connection()
	try:
		token = oID_client.token(username, password)
		assert True, "Login shouldn't be possible"
	except KeycloakError:
		print("Login as a non existing user fail.")


def _create_users():
	print("Creating users ...")
	# Create ldap users -> 1 domain admin, 1 normal user
	user_client = UDM.admin().version(2).get("users/user")

	# load UCR
	ucr = ConfigRegistry()
	ucr.load()
	domain = ucr.get("domainname")
	domain_split = domain.split(".")
	dn = "dc={},dc={}".format(domain_split[0], domain_split[1])

	obj = user_client.new()
	obj.props.username = 'userAdminTest'
	obj.props.lastname = 'test test'
	obj.props.password = 'univention'
	obj.props.primaryGroup = 'cn=Domain Admins,cn=groups,{}'.format(dn)
	obj.props.unixhome = '/home/userAdminTest'
	obj.save()

	obj = user_client.new()
	obj.props.username = 'userUserTest'
	obj.props.lastname = 'test test'
	obj.props.password = 'univention'
	obj.props.unixhome = '/home/userUserTest'
	obj.save()


def _delete_users():
	print("Deleting users ...")
	# Delete previous created ldap users -> 1 domain admin, 1 normal user
	user_client = UDM.admin().version(2).get("users/user")

	# load UCR
	ucr = ConfigRegistry()
	ucr.load()
	domain = ucr.get("domainname")
	domain_split = domain.split(".")
	dn = "cn=users,dc={},dc={}".format(domain_split[0], domain_split[1])

	obj = user_client.get("uid=userAdminTest,{}".format(dn))
	obj.delete()

	obj = user_client.get("uid=userUserTest,{}".format(dn))
	obj.delete()


def __activate_idp_keycloak():
	# load UCR
	ucr = ConfigRegistry()
	ucr.load()
	hostname = ucr.get("hostname")
	domain = ucr.get("domainname")

	subprocess.call(["ucr", "set", "umc/saml/idp-server=https://ucs-sso-ng.{}/realms/ucs/protocol/saml/descriptor".format(domain)])
	subprocess.call(["udm", "portals/entry", "modify", "--dn", "cn=login-saml,cn=entry,cn=portals,cn=univention, {}".format(ucr.get("ldap/base")), "--set", "activated=TRUE"])
	subprocess.call(["systemctl", "restart", "slapd"])


def _logout(chrome):
	chrome.click_element('#header-button-menu')
	time.sleep(4)
	chrome.click_element('#loginButton')
	time.sleep(1)


def _do_sso_login(chrome, username="administrator", password="univention"):
	chrome.goto_portal()
	chrome.click_portal_tile(u'Login (Single sign-on)')
	time.sleep(2)

	chrome.enter_input('username', username)
	chrome.enter_input('password', password)
	chrome.click_element('#kc-login')
	time.sleep(10)


def _user_login(chrome, username="administrator", password="univention", logout=True):
	_do_sso_login(chrome, username, password)
	if logout:
		_logout(chrome)


def _incorrect_login(chrome, username="administrator", password="univention"):

	_do_sso_login(chrome, username, password)
	try:
		# should not work
		_logout(chrome)
		raise AssertionError
	except AssertionError:
		pass


def _test_sso(chrome):
	__activate_idp_keycloak()
	chrome.goto_portal()

	_user_login(chrome, "userAdminTest", "univention")
	# login as user
	_user_login(chrome, "userUserTest", "univention")

	# wrong login
	_incorrect_login(chrome, "nonExistUser", "Password")


def test_keycloak(chrome):
	# login as admin
	pwdfile = "/etc/keycloak.secret"
	with open(pwdfile, 'r') as fd:
		password = fd.read().strip()

	_test_keycloak_admin_login("admin", password)
	_test_keycloak_user_login()
	_create_users()
	_test_keycloak_admin_login("useradmintest", "univention")
	_test_keycloak_user_login("userusertest", "univention")

	_test_keycloak_admin_login_fail()
	_test_keycloak_user_login_fail()

	with chrome.capture('keycloak_sso'):
		_test_sso(chrome)

	_delete_users()


def _create_dummy_realm(kc_admin):
	print("Creating dummy realm for ad-hoc federation test...")
	# load UCR
	ucr = ConfigRegistry()
	ucr.load()
	hostname = ucr.get("hostname")
	domain = ucr.get("domainname")
	locales_ucr = ucr.get("locale").split()
	locales_format = [locale[:locale.index("_")] for locale in locales_ucr]
	default_locale_ucr = ucr.get("locale/default")
	default_locale = default_locale_ucr[:default_locale_ucr.index("_")]

	# derived composite vars #
	if hostname and not hostname == "unassigned-hostname":
		server_fdnq_with_subdomain = "https://ucs-sso-ng.{}".format(domain)
		server_fdnq_without_subdomain = "https://ucs-sso-ng.{}".format(domain)
	else:
		server_fdnq_with_subdomain = "https://ucs-sso-ng.{}".format(domain)
		server_fdnq_without_subdomain = "https://ucs-sso-ng.{}".format(domain)

	# client config #
	client_id_location = "/realms/dummy"
	valid_redirect_urls = [server_fdnq_with_subdomain + "/realms/ucs/broker/saml/endpoint"]

	# set locale languages #
	realm_payload = {
		"id": "dummy",
		"realm": "dummy",
		"enabled": True,
		"internationalizationEnabled": True,
		"supportedLocales": locales_format,
		"defaultLocale": default_locale,
		"adminTheme": "keycloak",
		"accountTheme": "keycloak",
		"emailTheme": "keycloak",
		"loginTheme": "UCS",
		"browserSecurityHeaders": {
			"contentSecurityPolicyReportOnly": "",
			"xContentTypeOptions": "nosniff",
			"xRobotsTag": "none",
			"xFrameOptions": "",
			"contentSecurityPolicy": "frame-src 'self'; frame-ancestors 'self' {}/univention; object-src 'none';".format(server_fdnq_without_subdomain),
			"xXSSProtection": "1; mode=block",
			"strictTransportSecurity": "max-age=31536000; includeSubDomains"
		}
	}
	kc_admin.create_realm(payload=realm_payload, skip_exists=True)

	kc_admin.realm_name = "dummy"
	# create client #
	client_id = server_fdnq_with_subdomain + client_id_location
	print("Client ID: {}".format(client_id))

	client_payload = {
		"clientId": client_id,
		"surrogateAuthRequired": False,
		"enabled": True,
		"alwaysDisplayInConsole": False,
		"clientAuthenticatorType": "client-secret",
		"redirectUris": valid_redirect_urls,
		"webOrigins": [],
		"notBefore": 0,
		"bearerOnly": False,
		"consentRequired": False,
		"standardFlowEnabled": True,
		"implicitFlowEnabled": False,
		"directAccessGrantsEnabled": True,
		"serviceAccountsEnabled": False,
		"publicClient": True,
		"frontchannelLogout": True,
		"protocol": "saml",
		"attributes": {
			"saml.multivalued.roles": "false",
			"saml.force.post.binding": "true",
			"oauth2.device.authorization.grant.enabled": "false",
			"backchannel.logout.revoke.offline.tokens": "false",
			"saml.server.signature.keyinfo.ext": "false",
			"use.refresh.tokens": "true",
			"oidc.ciba.grant.enabled": "false",
			"backchannel.logout.session.required": "true",
			"client_credentials.use_refresh_token": "false",
			"saml.signature.algorithm": "RSA_SHA256",
			"saml.client.signature": "false",
			"require.pushed.authorization.requests": "false",
			"id.token.as.detached.signature": "false",
			"saml.assertion.signature": "true",
			"saml_single_logout_service_url_post": "",
			"saml.encrypt": "false",
			"saml_assertion_consumer_url_post": "",
			"saml.server.signature": "true",
			"exclude.session.state.from.auth.response": "false",
			"saml.artifact.binding.identifier": "JOtItQNol3ThXjMMWI3gcbW92sU=",
			"saml.artifact.binding": "false",
			"saml_single_logout_service_url_redirect": "",
			"saml_force_name_id_format": "false",
			"tls.client.certificate.bound.access.tokens": "false",
			"acr.loa.map": "{}",
			"saml.authnstatement": "true",
			"display.on.consent.screen": "false",
			"saml.assertion.lifespan": "300",
			"token.response.type.bearer.lower-case": "false",
			"saml.onetimeuse.condition": "false",
			"saml_signature_canonicalization_method": "http://www.w3.org/2001/10/xml-exc-c14n#"
		},
		"authenticationFlowBindingOverrides": {},
		"fullScopeAllowed": True,
		"nodeReRegistrationTimeout": -1,
		"protocolMappers": [
			{
				"config": {
					"attribute.name": "sAMAccountName",
					"attribute.nameformat": "Unspecified",
					"friendly.name": "uid",
					"user.attribute": "uid"
				},
				"consentRequired": "false",
				"name": "userid_mapper",
				"protocol": "saml",
				"protocolMapper": "saml-user-attribute-mapper"
			},
			{
				"config": {
					"attribute.name": "objectGUID",
					"attribute.nameformat": "Unspecified",
					"friendly.name": "uuid_remote",
					"user.attribute": "uuid_remote"
				},
				"consentRequired": "false",
				"name": "objectGUID_mapper",
				"protocol": "saml",
				"protocolMapper": "saml-user-attribute-mapper"
			},
			{
				"config": {
					"attribute.name": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname",
					"attribute.nameformat": "Unspecified",
					"friendly.name": "lastName",
					"user.attribute": "lastName"
				},
				"consentRequired": "false",
				"name": "lastname_mapper",
				"protocol": "saml",
				"protocolMapper": "saml-user-attribute-mapper"
			},
			{
				"config": {
					"attribute.name": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname",
					"attribute.nameformat": "Unspecified",
					"friendly.name": "firstName",
					"user.attribute": "firstName"
				},
				"consentRequired": "false",
				"name": "firstname_mapper",
				"protocol": "saml",
				"protocolMapper": "saml-user-attribute-mapper"
			},
			{
				"config": {
					"attribute.name": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
					"attribute.nameformat": "Unspecified",
					"friendly.name": "email",
					"user.attribute": "email"
				},
				"consentRequired": "false",
				"name": "email_mapper",
				"protocol": "saml",
				"protocolMapper": "saml-user-attribute-mapper"
			}
		],
		"defaultClientScopes": [
			"role_list"
		],
		"optionalClientScopes": [],
		"access": {
			"view": True,
			"configure": True,
			"manage": True
		}
	}
	kc_admin.create_client(payload=client_payload, skip_exists=True)


def _create_dummy_users(kc_admin):
	print("Creating users in dummy realm for ad-hoc federation test...")
	# Add user and set password
	new_user = kc_admin.create_user({"email": "test@univention.de",
		"username": "test_user1",
		"enabled": True,
		"firstName": "Test",
		"lastName": "Example",
		"credentials": [{"value": "univention", "type": "password", }],
		"attributes": {
			"uid": ["test_user1"],
			"uuid_remote": [base64.b64encode(uuid.UUID('60722945-2fb8-49e4-b5d0-c2838a390365').bytes_le).decode('utf-8')]
		}})

	new_user = kc_admin.create_user({"email": "test2@univention.de",
		"username": "test_user2",
		"enabled": True,
		"firstName": "Test",
		"lastName": "Example",
		"credentials": [{"value": "univention", "type": "password", }],
		"attributes": {
			"uid": ["test_user2"],
			"uuid_remote": [base64.b64encode(uuid.UUID('60722945-2fb8-49e4-b5d0-c2838a390365').bytes_le).decode('utf-8')]
		}})


def _create_idp(kc_admin):
	print("Creating federation and setting up the ad-hoc federation test...")
	kc_admin.realm_name = "ucs"
	# load UCR
	ucr = ConfigRegistry()
	ucr.load()
	hostname = ucr.get("hostname")
	domain = ucr.get("domainname")

	payload_authflow = {
		"newName": "Univention-Authenticator ad-hoc federation flow"
	}

	list_flows = kc_admin.get_authentication_flows()
	flow_fbl = list(filter(lambda flow: flow["alias"] == 'first broker login', list_flows))[0]

	print(flow_fbl)
	kc_admin.copy_authentication_flow(payload=json.dumps(payload_authflow), flow_alias='first broker login')

	payload_exec_flow = {
		'provider': "univention-authenticator"
	}
	kc_admin.create_authentication_flow_execution(payload=json.dumps(payload_exec_flow), flow_alias='Univention-Authenticator ad-hoc federation flow')

	execution_list = kc_admin.get_authentication_flow_executions("Univention-Authenticator ad-hoc federation flow")
	ua_execution = list(filter(lambda flow: flow["displayName"] == 'Univention Authenticator', execution_list))[0]
	print(ua_execution)

	payload_exec_flow = {
		"id": ua_execution["id"],
		"requirement": "REQUIRED",
		"displayName": "Univention Authenticator",
		"requirementChoices": [
			"REQUIRED",
			"DISABLED"
		],
		"configurable": "true",
		"providerId": "univention-authenticator",
		"level": 0,
		"index": 2
	}
	try:
		kc_admin.update_authentication_flow_executions(payload=json.dumps(payload_exec_flow), flow_alias='Univention-Authenticator ad-hoc federation flow')
	except KeycloakError as e:
		print(e)
		if e.response_code != 202:  # FIXME: function expected 204 response it gets 202
			raise e

	# config_id from 'authenticationConfig' in get_authentication_flow_executions
	config_ua = {
		"config": {
			"udm_endpoint": "http://{}.{}/univention/udm".format(hostname, domain),
			"udm_user": "Administrator",
			"udm_password": "univention"
		},
		"alias": "localhost config"
	}

	subprocess.call(["univention-keycloak", "saml/idp/cert", "get", "--output", "/root/sign.cert"])
	with open("/root/sign.cert", 'r') as fd:
		certificate = fd.read()

	data_raw = kc_admin.raw_post("admin/realms/{}/authentication/executions/{}/config".format(kc_admin.realm_name, ua_execution["id"]), json.dumps(config_ua))
	print("Response code from config Univention-Authenticator: ", data_raw.status_code)
	payload_idp = {
		"alias": "saml",
		"providerId": "saml",
		"enabled": True,
		"updateProfileFirstLoginMode": "on",
		"trustEmail": False,
		"storeToken": False,
		"addReadTokenRoleOnCreate": False,
		"authenticateByDefault": False,
		"linkOnly": False,
		"firstBrokerLoginFlowAlias": "Univention-Authenticator ad-hoc federation flow",
		"config": {
			"allowCreate": "true",
			"nameIDPolicyFormat": "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified",
			"principalAttribute": "sAMAccountName",
			"principalType": "ATTRIBUTE",
			"syncMode": "IMPORT",
			"postBindingAuthnRequest": "true",
			"postBindingLogout": "false",
			"postBindingResponse": "true",
			"authnContextComparisonType": "exact",
			"entityId": "https://ucs-sso-ng.{}/realms/dummy".format(domain),
			"singleSignOnServiceUrl": "https://ucs-sso-ng.{}/realms/dummy/protocol/saml".format(domain),
			"xmlSigKeyInfoKeyNameTransformer": "KEY_ID",
			"signatureAlgorithm": "RSA_SHA256",
			"signingCertificate": certificate,
			"validateSignature": "false",
			"wantAuthnRequestsSigned": "true",
			"useJwksUrl": "true"
		}
	}

	kc_admin.create_idp(payload_idp)

	list_idps = kc_admin.get_idps()
	new_idp = list(filter(lambda idp: idp["alias"] == 'saml', list_idps))[0]
	print(new_idp)
	idp_mapper_payload = {
		"id": new_idp["internalId"],
		"name": "email_importer",
		"identityProviderAlias": "saml",
		"identityProviderMapper": "saml-user-attribute-idp-mapper",
		"config": {
			"syncMode": "IMPORT",
			"user.attribute": "email",
			"attributes": "[]",
			"attribute.name": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"
		}
	}
	kc_admin.add_mapper_to_idp(idp_alias="saml", payload=idp_mapper_payload)

	idp_mapper_payload = {
		"config": {
			"attributes": "[]",
			"syncMode": "IMPORT",
			"target": "LOCAL",
			"template": "external-${ALIAS}-${ATTRIBUTE.sAMAccountName}"
		},
		"identityProviderAlias": "saml",
		"identityProviderMapper": "saml-username-idp-mapper",
		"name": "uid_importer"
	}
	kc_admin.add_mapper_to_idp(idp_alias="saml", payload=idp_mapper_payload)

	idp_mapper_payload = {
		"id": new_idp["internalId"],
		"name": "firstname_importer",
		"identityProviderAlias": "saml",
		"identityProviderMapper": "saml-user-attribute-idp-mapper",
		"config": {
			"syncMode": "IMPORT",
			"user.attribute": "firstName",
			"attributes": "[]",
			"attribute.name": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"
		}
	}
	kc_admin.add_mapper_to_idp(idp_alias="saml", payload=idp_mapper_payload)

	idp_mapper_payload = {
		"id": new_idp["internalId"],
		"name": "lastname_importer",
		"identityProviderAlias": "saml",
		"identityProviderMapper": "saml-user-attribute-idp-mapper",
		"config": {
			"syncMode": "IMPORT",
			"user.attribute": "lastName",
			"attributes": "[]",
			"attribute.name": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"
		}
	}
	kc_admin.add_mapper_to_idp(idp_alias="saml", payload=idp_mapper_payload)

	idp_mapper_payload = {
		"id": new_idp["internalId"],
		"name": "univentionObjectId_importer",
		"identityProviderAlias": "saml",
		"identityProviderMapper": "saml-user-attribute-idp-mapper",
		"config": {
			"syncMode": "IMPORT",
			"user.attribute": "objectGUID",
			"attributes": "[]",
			"attribute.name": "objectGUID"
		}
	}
	kc_admin.add_mapper_to_idp(idp_alias="saml", payload=idp_mapper_payload)

	idp_mapper_customer = {
		"identityProviderAlias": "saml",
		"config": {
			"syncMode": "IMPORT",
			"attributes": "[]",
			"attribute": "univentionSourceIAM",
			"attribute.value": "Dummy realm"
		},
		"name": "univentionSourceIAM_importer",
		"identityProviderMapper": "hardcoded-attribute-idp-mapper"
	}
	kc_admin.add_mapper_to_idp(idp_alias="saml", payload=idp_mapper_customer)


def _sso_adhoc_federation(chrome):
	print("Perform a SSO using the ad-hoc federation test...")
	__activate_idp_keycloak()

	chrome.goto_portal()
	chrome.click_portal_tile(u'Login (Single sign-on)')
	time.sleep(2)

	chrome.click_element('#social-saml')
	time.sleep(5)

	chrome.enter_input('username', "test_user1")
	chrome.enter_input('password', "univention")
	chrome.click_element('#kc-login')
	time.sleep(10)

	_logout(chrome)


def _check_federated_user(kc_admin):
	print("Checking new users created by the ad-hoc federation test...")
	# Check for shadow federated user
	user_client = UDM.admin().version(2).get("users/user")
	# load UCR
	ucr = ConfigRegistry()
	ucr.load()
	domain = ucr.get("domainname")
	domain_split = domain.split(".")
	dn = "cn=users,dc={},dc={}".format(domain_split[0], domain_split[1])

	obj = user_client.get("uid=external-saml-test_user1,{}".format(dn))
	assert obj.props.username == 'external-saml-test_user1', "Wrong federated user username in UDM. %s" % obj.props.username
	assert obj.props.lastname == 'Example', "Wrong federated user lastname in UDM. %s" % obj.props.lastname
	assert obj.props.firstname == 'Test', "Wrong federated user firstname in UDM. %s" % obj.props.firstname
	assert obj.props.description == 'Shadow copy of user', "Wrong federated user description in UDM. %s" % obj.props.description

	kc_admin.realm_name = "ucs"
	user_id = kc_admin.get_user_id(username="external-saml-test_user1")
	kc_user = kc_admin.get_user(user_id=user_id)
	assert kc_user["username"] == "external-saml-test_user1", "Wrong federated user username in Keycloak - UCS realm. %s" % kc_user["username"]
	assert kc_user["email"] == "test@univention.de", "Wrong federated user email in Keycloak - UCS realm. %s" % kc_user["email"]
	assert kc_user["firstName"] == "Test", "Wrong federated user firstName in Keycloak - UCS realm. %s" % kc_user["firstName"]
	assert kc_user["lastName"] == "Example", "Wrong federated user lastName in Keycloak - UCS realm. %s" % kc_user["lastName"]


def _delete_adhoc_users(kc_admin):
	print("Deleting federated users ...")
	# Delete previous created ldap users -> 1 domain admin, 1 normal user
	user_client = UDM.admin().version(2).get("users/user")

	# load UCR
	ucr = ConfigRegistry()
	ucr.load()
	domain = ucr.get("domainname")
	domain_split = domain.split(".")
	dn = "cn=users,dc={},dc={}".format(domain_split[0], domain_split[1])

	obj = user_client.get("uid=external-saml-test_user1,{}".format(dn))
	obj.delete()

	kc_admin.realm_name = "ucs"
	user_id = kc_admin.get_user_id("external-saml-test_user1")
	kc_admin.delete_user(user_id)

	kc_admin.delete_idp(idp_alias="saml")
	kc_admin.delete_realm(realm_name="dummy")

	# function not present in our version, workaround
	flow_id = [x for x in kc_admin.get_authentication_flows() if x["alias"] == "Univention-Authenticator ad-hoc federation flow"][0]["id"]
	params_path = {"realm-name": kc_admin.realm_name, "id": flow_id}
	data_raw = kc_admin.raw_delete("admin/realms/{realm-name}/authentication/flows/{id}".format(**params_path))
	print("Response code from config Univention-Authenticator: ", data_raw.status_code)


def test_adhoc_federation(chrome):
	# Connect as admin
	pwdfile = "/etc/keycloak.secret"
	with open(pwdfile, 'r') as fd:
		password = fd.read().strip()

	kc_admin = __build_keycloak_admin_connection("admin", password)

	# Create dummy realm
	# Create client in realm
	_create_dummy_realm(kc_admin)

	# Create 2 dummy user with uid attribute
	_create_dummy_users(kc_admin)

	# Create IdP federation
	_create_idp(kc_admin)

	# Close session
	_logout_keycloak_client(kc_admin)

	# Try SSO log in
	with chrome.capture("keycloak_sso_adhoc"):
		_sso_adhoc_federation(chrome)

	kc_admin = __build_keycloak_admin_connection("admin", password)  # Workaround to session timing out
	# Check user in ldap
	_check_federated_user(kc_admin)

	# Delete kc user and ldap user
	_delete_adhoc_users(kc_admin)

	_logout_keycloak_client(kc_admin)


def _logout_keycloak_client(kc_admin):
	params_path = {"realm-name": "master", "id": SESSION_ID}
	data_raw = kc_admin.raw_post(
		"admin/realms/{realm-name}/users/{id}/logout".format(**params_path), data=""
	)
	print(data_raw)


if __name__ == '__main__':
	test_lib.run_test_file(__file__)
