You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2785 lines
99 KiB

  1. """Test the keycloak admin object."""
  2. import copy
  3. import uuid
  4. from typing import Tuple
  5. import freezegun
  6. import pytest
  7. from dateutil import parser as datetime_parser
  8. import keycloak
  9. from keycloak import KeycloakAdmin, KeycloakOpenID, KeycloakOpenIDConnection
  10. from keycloak.connection import ConnectionManager
  11. from keycloak.exceptions import (
  12. KeycloakAuthenticationError,
  13. KeycloakDeleteError,
  14. KeycloakGetError,
  15. KeycloakPostError,
  16. KeycloakPutError,
  17. )
  18. def test_keycloak_version():
  19. """Test version."""
  20. assert keycloak.__version__, keycloak.__version__
  21. def test_keycloak_admin_init(env):
  22. """Test keycloak admin init.
  23. :param env: Environment fixture
  24. :type env: KeycloakTestEnv
  25. """
  26. admin = KeycloakAdmin(
  27. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  28. username=env.KEYCLOAK_ADMIN,
  29. password=env.KEYCLOAK_ADMIN_PASSWORD,
  30. )
  31. assert admin.server_url == f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}", admin.server_url
  32. assert admin.realm_name == "master", admin.realm_name
  33. assert isinstance(admin.connection, ConnectionManager), type(admin.connection)
  34. assert admin.client_id == "admin-cli", admin.client_id
  35. assert admin.client_secret_key is None, admin.client_secret_key
  36. assert admin.verify, admin.verify
  37. assert admin.username == env.KEYCLOAK_ADMIN, admin.username
  38. assert admin.password == env.KEYCLOAK_ADMIN_PASSWORD, admin.password
  39. assert admin.totp is None, admin.totp
  40. assert admin.token is not None, admin.token
  41. assert admin.user_realm_name is None, admin.user_realm_name
  42. assert admin.custom_headers is None, admin.custom_headers
  43. assert admin.token
  44. admin = KeycloakAdmin(
  45. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  46. username=env.KEYCLOAK_ADMIN,
  47. password=env.KEYCLOAK_ADMIN_PASSWORD,
  48. realm_name=None,
  49. user_realm_name="master",
  50. )
  51. assert admin.token
  52. admin = KeycloakAdmin(
  53. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  54. username=env.KEYCLOAK_ADMIN,
  55. password=env.KEYCLOAK_ADMIN_PASSWORD,
  56. realm_name=None,
  57. user_realm_name=None,
  58. )
  59. assert admin.token
  60. token = admin.token
  61. admin = KeycloakAdmin(
  62. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  63. token=token,
  64. realm_name=None,
  65. user_realm_name=None,
  66. )
  67. assert admin.token == token
  68. admin.create_realm(payload={"realm": "authz", "enabled": True})
  69. admin.realm_name = "authz"
  70. admin.create_client(
  71. payload={
  72. "name": "authz-client",
  73. "clientId": "authz-client",
  74. "authorizationServicesEnabled": True,
  75. "serviceAccountsEnabled": True,
  76. "clientAuthenticatorType": "client-secret",
  77. "directAccessGrantsEnabled": False,
  78. "enabled": True,
  79. "implicitFlowEnabled": False,
  80. "publicClient": False,
  81. }
  82. )
  83. secret = admin.generate_client_secrets(client_id=admin.get_client_id("authz-client"))
  84. assert KeycloakAdmin(
  85. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  86. user_realm_name="authz",
  87. client_id="authz-client",
  88. client_secret_key=secret["value"],
  89. ).token
  90. admin.delete_realm(realm_name="authz")
  91. assert (
  92. KeycloakAdmin(
  93. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  94. username=None,
  95. password=None,
  96. client_secret_key=None,
  97. custom_headers={"custom": "header"},
  98. ).token
  99. is None
  100. )
  101. keycloak_connection = KeycloakOpenIDConnection(
  102. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  103. username=env.KEYCLOAK_ADMIN,
  104. password=env.KEYCLOAK_ADMIN_PASSWORD,
  105. realm_name="master",
  106. client_id="admin-cli",
  107. verify=True,
  108. )
  109. keycloak_admin = KeycloakAdmin(connection=keycloak_connection)
  110. assert keycloak_admin.token
  111. def test_realms(admin: KeycloakAdmin):
  112. """Test realms.
  113. :param admin: Keycloak Admin client
  114. :type admin: KeycloakAdmin
  115. """
  116. # Get realms
  117. realms = admin.get_realms()
  118. assert len(realms) == 1, realms
  119. assert "master" == realms[0]["realm"]
  120. # Create a test realm
  121. res = admin.create_realm(payload={"realm": "test"})
  122. assert res == b"", res
  123. # Create the same realm, should fail
  124. with pytest.raises(KeycloakPostError) as err:
  125. res = admin.create_realm(payload={"realm": "test"})
  126. assert err.match('409: b\'{"errorMessage":"Conflict detected. See logs for details"}\'')
  127. # Create the same realm, skip_exists true
  128. res = admin.create_realm(payload={"realm": "test"}, skip_exists=True)
  129. assert res == {"msg": "Already exists"}, res
  130. # Get a single realm
  131. res = admin.get_realm(realm_name="test")
  132. assert res["realm"] == "test"
  133. # Get non-existing realm
  134. with pytest.raises(KeycloakGetError) as err:
  135. admin.get_realm(realm_name="non-existent")
  136. assert err.match('404: b\'{"error":"Realm not found."}\'')
  137. # Update realm
  138. res = admin.update_realm(realm_name="test", payload={"accountTheme": "test"})
  139. assert res == dict(), res
  140. # Check that the update worked
  141. res = admin.get_realm(realm_name="test")
  142. assert res["realm"] == "test"
  143. assert res["accountTheme"] == "test"
  144. # Update wrong payload
  145. with pytest.raises(KeycloakPutError) as err:
  146. admin.update_realm(realm_name="test", payload={"wrong": "payload"})
  147. assert err.match('400: b\'{"error":"Unrecognized field')
  148. # Check that get realms returns both realms
  149. realms = admin.get_realms()
  150. realm_names = [x["realm"] for x in realms]
  151. assert len(realms) == 2, realms
  152. assert "master" in realm_names, realm_names
  153. assert "test" in realm_names, realm_names
  154. # Delete the realm
  155. res = admin.delete_realm(realm_name="test")
  156. assert res == dict(), res
  157. # Check that the realm does not exist anymore
  158. with pytest.raises(KeycloakGetError) as err:
  159. admin.get_realm(realm_name="test")
  160. assert err.match('404: b\'{"error":"Realm not found."}\'')
  161. # Delete non-existing realm
  162. with pytest.raises(KeycloakDeleteError) as err:
  163. admin.delete_realm(realm_name="non-existent")
  164. assert err.match('404: b\'{"error":"Realm not found."}\'')
  165. def test_import_export_realms(admin: KeycloakAdmin, realm: str):
  166. """Test import and export of realms.
  167. :param admin: Keycloak Admin client
  168. :type admin: KeycloakAdmin
  169. :param realm: Keycloak realm
  170. :type realm: str
  171. """
  172. admin.realm_name = realm
  173. realm_export = admin.export_realm(export_clients=True, export_groups_and_role=True)
  174. assert realm_export != dict(), realm_export
  175. admin.delete_realm(realm_name=realm)
  176. admin.realm_name = "master"
  177. res = admin.import_realm(payload=realm_export)
  178. assert res == b"", res
  179. # Test bad import
  180. with pytest.raises(KeycloakPostError) as err:
  181. admin.import_realm(payload=dict())
  182. assert err.match('500: b\'{"error":"unknown_error"}\'')
  183. def test_users(admin: KeycloakAdmin, realm: str):
  184. """Test users.
  185. :param admin: Keycloak Admin client
  186. :type admin: KeycloakAdmin
  187. :param realm: Keycloak realm
  188. :type realm: str
  189. """
  190. admin.realm_name = realm
  191. # Check no users present
  192. users = admin.get_users()
  193. assert users == list(), users
  194. # Test create user
  195. user_id = admin.create_user(payload={"username": "test", "email": "test@test.test"})
  196. assert user_id is not None, user_id
  197. # Test create the same user
  198. with pytest.raises(KeycloakPostError) as err:
  199. admin.create_user(payload={"username": "test", "email": "test@test.test"})
  200. assert err.match('409: b\'{"errorMessage":"User exists with same username"}\'')
  201. # Test create the same user, exists_ok true
  202. user_id_2 = admin.create_user(
  203. payload={"username": "test", "email": "test@test.test"}, exist_ok=True
  204. )
  205. assert user_id == user_id_2
  206. # Test get user
  207. user = admin.get_user(user_id=user_id)
  208. assert user["username"] == "test", user["username"]
  209. assert user["email"] == "test@test.test", user["email"]
  210. # Test update user
  211. res = admin.update_user(user_id=user_id, payload={"firstName": "Test"})
  212. assert res == dict(), res
  213. user = admin.get_user(user_id=user_id)
  214. assert user["firstName"] == "Test"
  215. # Test update user fail
  216. with pytest.raises(KeycloakPutError) as err:
  217. admin.update_user(user_id=user_id, payload={"wrong": "payload"})
  218. assert err.match('400: b\'{"error":"Unrecognized field')
  219. # Test get users again
  220. users = admin.get_users()
  221. usernames = [x["username"] for x in users]
  222. assert "test" in usernames
  223. # Test users counts
  224. count = admin.users_count()
  225. assert count == 1, count
  226. # Test users count with query
  227. count = admin.users_count(query={"username": "notpresent"})
  228. assert count == 0
  229. # Test user groups
  230. groups = admin.get_user_groups(user_id=user["id"])
  231. assert len(groups) == 0
  232. # Test user groups bad id
  233. with pytest.raises(KeycloakGetError) as err:
  234. admin.get_user_groups(user_id="does-not-exist")
  235. assert err.match('404: b\'{"error":"User not found"}\'')
  236. # Test logout
  237. res = admin.user_logout(user_id=user["id"])
  238. assert res == dict(), res
  239. # Test logout fail
  240. with pytest.raises(KeycloakPostError) as err:
  241. admin.user_logout(user_id="non-existent-id")
  242. assert err.match('404: b\'{"error":"User not found"}\'')
  243. # Test consents
  244. res = admin.user_consents(user_id=user["id"])
  245. assert len(res) == 0, res
  246. # Test consents fail
  247. with pytest.raises(KeycloakGetError) as err:
  248. admin.user_consents(user_id="non-existent-id")
  249. assert err.match('404: b\'{"error":"User not found"}\'')
  250. # Test delete user
  251. res = admin.delete_user(user_id=user_id)
  252. assert res == dict(), res
  253. with pytest.raises(KeycloakGetError) as err:
  254. admin.get_user(user_id=user_id)
  255. err.match('404: b\'{"error":"User not found"}\'')
  256. # Test delete fail
  257. with pytest.raises(KeycloakDeleteError) as err:
  258. admin.delete_user(user_id="non-existent-id")
  259. assert err.match('404: b\'{"error":"User not found"}\'')
  260. def test_users_pagination(admin: KeycloakAdmin, realm: str):
  261. """Test user pagination.
  262. :param admin: Keycloak Admin client
  263. :type admin: KeycloakAdmin
  264. :param realm: Keycloak realm
  265. :type realm: str
  266. """
  267. admin.realm_name = realm
  268. for ind in range(admin.PAGE_SIZE + 50):
  269. username = f"user_{ind}"
  270. admin.create_user(payload={"username": username, "email": f"{username}@test.test"})
  271. users = admin.get_users()
  272. assert len(users) == admin.PAGE_SIZE + 50, len(users)
  273. users = admin.get_users(query={"first": 100})
  274. assert len(users) == 50, len(users)
  275. users = admin.get_users(query={"max": 20})
  276. assert len(users) == 20, len(users)
  277. def test_user_groups_pagination(admin: KeycloakAdmin, realm: str):
  278. """Test user groups pagination.
  279. :param admin: Keycloak Admin client
  280. :type admin: KeycloakAdmin
  281. :param realm: Keycloak realm
  282. :type realm: str
  283. """
  284. admin.realm_name = realm
  285. user_id = admin.create_user(
  286. payload={"username": "username_1", "email": "username_1@test.test"}
  287. )
  288. for ind in range(admin.PAGE_SIZE + 50):
  289. group_name = f"group_{ind}"
  290. group_id = admin.create_group(payload={"name": group_name})
  291. admin.group_user_add(user_id=user_id, group_id=group_id)
  292. groups = admin.get_user_groups(user_id=user_id)
  293. assert len(groups) == admin.PAGE_SIZE + 50, len(groups)
  294. groups = admin.get_user_groups(user_id=user_id, query={"first": 100, "max": -1, "search": ""})
  295. assert len(groups) == 50, len(groups)
  296. groups = admin.get_user_groups(user_id=user_id, query={"max": 20, "first": -1, "search": ""})
  297. assert len(groups) == 20, len(groups)
  298. def test_idps(admin: KeycloakAdmin, realm: str):
  299. """Test IDPs.
  300. :param admin: Keycloak Admin client
  301. :type admin: KeycloakAdmin
  302. :param realm: Keycloak realm
  303. :type realm: str
  304. """
  305. admin.realm_name = realm
  306. # Create IDP
  307. res = admin.create_idp(
  308. payload=dict(
  309. providerId="github", alias="github", config=dict(clientId="test", clientSecret="test")
  310. )
  311. )
  312. assert res == b"", res
  313. # Test create idp fail
  314. with pytest.raises(KeycloakPostError) as err:
  315. admin.create_idp(payload={"providerId": "does-not-exist", "alias": "something"})
  316. assert err.match("Invalid identity provider id"), err
  317. # Test listing
  318. idps = admin.get_idps()
  319. assert len(idps) == 1
  320. assert "github" == idps[0]["alias"]
  321. # Test get idp
  322. idp = admin.get_idp("github")
  323. assert "github" == idp["alias"]
  324. assert idp.get("config")
  325. assert "test" == idp["config"]["clientId"]
  326. assert "**********" == idp["config"]["clientSecret"]
  327. # Test get idp fail
  328. with pytest.raises(KeycloakGetError) as err:
  329. admin.get_idp("does-not-exist")
  330. assert err.match('404: b\'{"error":"HTTP 404 Not Found"}\'')
  331. # Test IdP update
  332. res = admin.update_idp(idp_alias="github", payload=idps[0])
  333. assert res == {}, res
  334. # Test adding a mapper
  335. res = admin.add_mapper_to_idp(
  336. idp_alias="github",
  337. payload={
  338. "identityProviderAlias": "github",
  339. "identityProviderMapper": "github-user-attribute-mapper",
  340. "name": "test",
  341. },
  342. )
  343. assert res == b"", res
  344. # Test mapper fail
  345. with pytest.raises(KeycloakPostError) as err:
  346. admin.add_mapper_to_idp(idp_alias="does-no-texist", payload=dict())
  347. assert err.match('404: b\'{"error":"HTTP 404 Not Found"}\'')
  348. # Test IdP mappers listing
  349. idp_mappers = admin.get_idp_mappers(idp_alias="github")
  350. assert len(idp_mappers) == 1
  351. # Test IdP mapper update
  352. res = admin.update_mapper_in_idp(
  353. idp_alias="github",
  354. mapper_id=idp_mappers[0]["id"],
  355. # For an obscure reason, keycloak expect all fields
  356. payload={
  357. "id": idp_mappers[0]["id"],
  358. "identityProviderAlias": "github-alias",
  359. "identityProviderMapper": "github-user-attribute-mapper",
  360. "name": "test",
  361. "config": idp_mappers[0]["config"],
  362. },
  363. )
  364. assert res == dict(), res
  365. # Test delete
  366. res = admin.delete_idp(idp_alias="github")
  367. assert res == dict(), res
  368. # Test delete fail
  369. with pytest.raises(KeycloakDeleteError) as err:
  370. admin.delete_idp(idp_alias="does-not-exist")
  371. assert err.match('404: b\'{"error":"HTTP 404 Not Found"}\'')
  372. def test_user_credentials(admin: KeycloakAdmin, user: str):
  373. """Test user credentials.
  374. :param admin: Keycloak Admin client
  375. :type admin: KeycloakAdmin
  376. :param user: Keycloak user
  377. :type user: str
  378. """
  379. res = admin.set_user_password(user_id=user, password="booya", temporary=True)
  380. assert res == dict(), res
  381. # Test user password set fail
  382. with pytest.raises(KeycloakPutError) as err:
  383. admin.set_user_password(user_id="does-not-exist", password="")
  384. assert err.match('404: b\'{"error":"User not found"}\'')
  385. credentials = admin.get_credentials(user_id=user)
  386. assert len(credentials) == 1
  387. assert credentials[0]["type"] == "password", credentials
  388. # Test get credentials fail
  389. with pytest.raises(KeycloakGetError) as err:
  390. admin.get_credentials(user_id="does-not-exist")
  391. assert err.match('404: b\'{"error":"User not found"}\'')
  392. res = admin.delete_credential(user_id=user, credential_id=credentials[0]["id"])
  393. assert res == dict(), res
  394. # Test delete fail
  395. with pytest.raises(KeycloakDeleteError) as err:
  396. admin.delete_credential(user_id=user, credential_id="does-not-exist")
  397. assert err.match('404: b\'{"error":"Credential not found"}\'')
  398. def test_social_logins(admin: KeycloakAdmin, user: str):
  399. """Test social logins.
  400. :param admin: Keycloak Admin client
  401. :type admin: KeycloakAdmin
  402. :param user: Keycloak user
  403. :type user: str
  404. """
  405. res = admin.add_user_social_login(
  406. user_id=user, provider_id="gitlab", provider_userid="test", provider_username="test"
  407. )
  408. assert res == dict(), res
  409. admin.add_user_social_login(
  410. user_id=user, provider_id="github", provider_userid="test", provider_username="test"
  411. )
  412. assert res == dict(), res
  413. # Test add social login fail
  414. with pytest.raises(KeycloakPostError) as err:
  415. admin.add_user_social_login(
  416. user_id="does-not-exist",
  417. provider_id="does-not-exist",
  418. provider_userid="test",
  419. provider_username="test",
  420. )
  421. assert err.match('404: b\'{"error":"User not found"}\'')
  422. res = admin.get_user_social_logins(user_id=user)
  423. assert res == list(), res
  424. # Test get social logins fail
  425. with pytest.raises(KeycloakGetError) as err:
  426. admin.get_user_social_logins(user_id="does-not-exist")
  427. assert err.match('404: b\'{"error":"User not found"}\'')
  428. res = admin.delete_user_social_login(user_id=user, provider_id="gitlab")
  429. assert res == {}, res
  430. res = admin.delete_user_social_login(user_id=user, provider_id="github")
  431. assert res == {}, res
  432. with pytest.raises(KeycloakDeleteError) as err:
  433. admin.delete_user_social_login(user_id=user, provider_id="instagram")
  434. assert err.match('404: b\'{"error":"Link not found"}\''), err
  435. def test_server_info(admin: KeycloakAdmin):
  436. """Test server info.
  437. :param admin: Keycloak Admin client
  438. :type admin: KeycloakAdmin
  439. """
  440. info = admin.get_server_info()
  441. assert set(info.keys()).issubset(
  442. {
  443. "systemInfo",
  444. "memoryInfo",
  445. "profileInfo",
  446. "themes",
  447. "socialProviders",
  448. "identityProviders",
  449. "providers",
  450. "protocolMapperTypes",
  451. "builtinProtocolMappers",
  452. "clientInstallations",
  453. "componentTypes",
  454. "passwordPolicies",
  455. "enums",
  456. "cryptoInfo",
  457. "features",
  458. }
  459. ), info.keys()
  460. def test_groups(admin: KeycloakAdmin, user: str):
  461. """Test groups.
  462. :param admin: Keycloak Admin client
  463. :type admin: KeycloakAdmin
  464. :param user: Keycloak user
  465. :type user: str
  466. """
  467. # Test get groups
  468. groups = admin.get_groups()
  469. assert len(groups) == 0
  470. # Test create group
  471. group_id = admin.create_group(payload={"name": "main-group"})
  472. assert group_id is not None, group_id
  473. # Test create subgroups
  474. subgroup_id_1 = admin.create_group(payload={"name": "subgroup-1"}, parent=group_id)
  475. subgroup_id_2 = admin.create_group(payload={"name": "subgroup-2"}, parent=group_id)
  476. # Test create group fail
  477. with pytest.raises(KeycloakPostError) as err:
  478. admin.create_group(payload={"name": "subgroup-1"}, parent=group_id)
  479. assert err.match("409"), err
  480. # Test skip exists OK
  481. subgroup_id_1_eq = admin.create_group(
  482. payload={"name": "subgroup-1"}, parent=group_id, skip_exists=True
  483. )
  484. assert subgroup_id_1_eq is None
  485. # Test get groups again
  486. groups = admin.get_groups()
  487. assert len(groups) == 1, groups
  488. assert len(groups[0]["subGroups"]) == 2, groups["subGroups"]
  489. assert groups[0]["id"] == group_id
  490. assert {x["id"] for x in groups[0]["subGroups"]} == {subgroup_id_1, subgroup_id_2}
  491. # Test get groups query
  492. groups = admin.get_groups(query={"max": 10})
  493. assert len(groups) == 1, groups
  494. assert len(groups[0]["subGroups"]) == 2, groups["subGroups"]
  495. assert groups[0]["id"] == group_id
  496. assert {x["id"] for x in groups[0]["subGroups"]} == {subgroup_id_1, subgroup_id_2}
  497. # Test get group
  498. res = admin.get_group(group_id=subgroup_id_1)
  499. assert res["id"] == subgroup_id_1, res
  500. assert res["name"] == "subgroup-1"
  501. assert res["path"] == "/main-group/subgroup-1"
  502. # Test get group fail
  503. with pytest.raises(KeycloakGetError) as err:
  504. admin.get_group(group_id="does-not-exist")
  505. assert err.match('404: b\'{"error":"Could not find group by id"}\''), err
  506. # Create 1 more subgroup
  507. subsubgroup_id_1 = admin.create_group(payload={"name": "subsubgroup-1"}, parent=subgroup_id_2)
  508. main_group = admin.get_group(group_id=group_id)
  509. # Test nested searches
  510. res = admin.get_subgroups(group=main_group, path="/main-group/subgroup-2/subsubgroup-1")
  511. assert res is not None, res
  512. assert res["id"] == subsubgroup_id_1
  513. # Test empty search
  514. res = admin.get_subgroups(group=main_group, path="/none")
  515. assert res is None, res
  516. # Test get group by path
  517. res = admin.get_group_by_path(path="/main-group/subgroup-1")
  518. assert res is not None, res
  519. assert res["id"] == subgroup_id_1, res
  520. with pytest.raises(KeycloakGetError) as err:
  521. admin.get_group_by_path(path="/main-group/subgroup-2/subsubgroup-1/test")
  522. assert err.match('404: b\'{"error":"Group path does not exist"}\'')
  523. res = admin.get_group_by_path(path="/main-group/subgroup-2/subsubgroup-1")
  524. assert res is not None, res
  525. assert res["id"] == subsubgroup_id_1
  526. res = admin.get_group_by_path(path="/main-group")
  527. assert res is not None, res
  528. assert res["id"] == group_id, res
  529. # Test group members
  530. res = admin.get_group_members(group_id=subgroup_id_2)
  531. assert len(res) == 0, res
  532. # Test fail group members
  533. with pytest.raises(KeycloakGetError) as err:
  534. admin.get_group_members(group_id="does-not-exist")
  535. assert err.match('404: b\'{"error":"Could not find group by id"}\'')
  536. res = admin.group_user_add(user_id=user, group_id=subgroup_id_2)
  537. assert res == dict(), res
  538. res = admin.get_group_members(group_id=subgroup_id_2)
  539. assert len(res) == 1, res
  540. assert res[0]["id"] == user
  541. # Test get group members query
  542. res = admin.get_group_members(group_id=subgroup_id_2, query={"max": 10})
  543. assert len(res) == 1, res
  544. assert res[0]["id"] == user
  545. with pytest.raises(KeycloakDeleteError) as err:
  546. admin.group_user_remove(user_id="does-not-exist", group_id=subgroup_id_2)
  547. assert err.match('404: b\'{"error":"User not found"}\''), err
  548. res = admin.group_user_remove(user_id=user, group_id=subgroup_id_2)
  549. assert res == dict(), res
  550. # Test set permissions
  551. res = admin.group_set_permissions(group_id=subgroup_id_2, enabled=True)
  552. assert res["enabled"], res
  553. res = admin.group_set_permissions(group_id=subgroup_id_2, enabled=False)
  554. assert not res["enabled"], res
  555. with pytest.raises(KeycloakPutError) as err:
  556. admin.group_set_permissions(group_id=subgroup_id_2, enabled="blah")
  557. assert err.match('b\'{"error":"unknown_error"}\''), err
  558. # Test update group
  559. res = admin.update_group(group_id=subgroup_id_2, payload={"name": "new-subgroup-2"})
  560. assert res == dict(), res
  561. assert admin.get_group(group_id=subgroup_id_2)["name"] == "new-subgroup-2"
  562. # test update fail
  563. with pytest.raises(KeycloakPutError) as err:
  564. admin.update_group(group_id="does-not-exist", payload=dict())
  565. assert err.match('404: b\'{"error":"Could not find group by id"}\''), err
  566. # Test delete
  567. res = admin.delete_group(group_id=group_id)
  568. assert res == dict(), res
  569. assert len(admin.get_groups()) == 0
  570. # Test delete fail
  571. with pytest.raises(KeycloakDeleteError) as err:
  572. admin.delete_group(group_id="does-not-exist")
  573. assert err.match('404: b\'{"error":"Could not find group by id"}\''), err
  574. def test_clients(admin: KeycloakAdmin, realm: str):
  575. """Test clients.
  576. :param admin: Keycloak Admin client
  577. :type admin: KeycloakAdmin
  578. :param realm: Keycloak realm
  579. :type realm: str
  580. """
  581. admin.realm_name = realm
  582. # Test get clients
  583. clients = admin.get_clients()
  584. assert len(clients) == 6, clients
  585. assert {x["name"] for x in clients} == set(
  586. [
  587. "${client_admin-cli}",
  588. "${client_security-admin-console}",
  589. "${client_account-console}",
  590. "${client_broker}",
  591. "${client_account}",
  592. "${client_realm-management}",
  593. ]
  594. ), clients
  595. # Test create client
  596. client_id = admin.create_client(payload={"name": "test-client", "clientId": "test-client"})
  597. assert client_id, client_id
  598. with pytest.raises(KeycloakPostError) as err:
  599. admin.create_client(payload={"name": "test-client", "clientId": "test-client"})
  600. assert err.match('409: b\'{"errorMessage":"Client test-client already exists"}\''), err
  601. client_id_2 = admin.create_client(
  602. payload={"name": "test-client", "clientId": "test-client"}, skip_exists=True
  603. )
  604. assert client_id == client_id_2, client_id_2
  605. # Test get client
  606. res = admin.get_client(client_id=client_id)
  607. assert res["clientId"] == "test-client", res
  608. assert res["name"] == "test-client", res
  609. assert res["id"] == client_id, res
  610. with pytest.raises(KeycloakGetError) as err:
  611. admin.get_client(client_id="does-not-exist")
  612. assert err.match('404: b\'{"error":"Could not find client"}\'')
  613. assert len(admin.get_clients()) == 7
  614. # Test get client id
  615. assert admin.get_client_id(client_id="test-client") == client_id
  616. assert admin.get_client_id(client_id="does-not-exist") is None
  617. # Test update client
  618. res = admin.update_client(client_id=client_id, payload={"name": "test-client-change"})
  619. assert res == dict(), res
  620. with pytest.raises(KeycloakPutError) as err:
  621. admin.update_client(client_id="does-not-exist", payload={"name": "test-client-change"})
  622. assert err.match('404: b\'{"error":"Could not find client"}\'')
  623. # Test client mappers
  624. res = admin.get_mappers_from_client(client_id=client_id)
  625. assert len(res) == 0
  626. with pytest.raises(KeycloakPostError) as err:
  627. admin.add_mapper_to_client(client_id="does-not-exist", payload=dict())
  628. assert err.match('404: b\'{"error":"Could not find client"}\'')
  629. res = admin.add_mapper_to_client(
  630. client_id=client_id,
  631. payload={
  632. "name": "test-mapper",
  633. "protocol": "openid-connect",
  634. "protocolMapper": "oidc-usermodel-attribute-mapper",
  635. },
  636. )
  637. assert res == b""
  638. assert len(admin.get_mappers_from_client(client_id=client_id)) == 1
  639. mapper = admin.get_mappers_from_client(client_id=client_id)[0]
  640. with pytest.raises(KeycloakPutError) as err:
  641. admin.update_client_mapper(client_id=client_id, mapper_id="does-not-exist", payload=dict())
  642. assert err.match('404: b\'{"error":"Model not found"}\'')
  643. mapper["config"]["user.attribute"] = "test"
  644. res = admin.update_client_mapper(client_id=client_id, mapper_id=mapper["id"], payload=mapper)
  645. assert res == dict()
  646. res = admin.remove_client_mapper(client_id=client_id, client_mapper_id=mapper["id"])
  647. assert res == dict()
  648. with pytest.raises(KeycloakDeleteError) as err:
  649. admin.remove_client_mapper(client_id=client_id, client_mapper_id=mapper["id"])
  650. assert err.match('404: b\'{"error":"Model not found"}\'')
  651. # Test client sessions
  652. with pytest.raises(KeycloakGetError) as err:
  653. admin.get_client_all_sessions(client_id="does-not-exist")
  654. assert err.match('404: b\'{"error":"Could not find client"}\'')
  655. assert admin.get_client_all_sessions(client_id=client_id) == list()
  656. assert admin.get_client_sessions_stats() == list()
  657. # Test authz
  658. auth_client_id = admin.create_client(
  659. payload={
  660. "name": "authz-client",
  661. "clientId": "authz-client",
  662. "authorizationServicesEnabled": True,
  663. "serviceAccountsEnabled": True,
  664. }
  665. )
  666. res = admin.get_client_authz_settings(client_id=auth_client_id)
  667. assert res["allowRemoteResourceManagement"]
  668. assert res["decisionStrategy"] == "UNANIMOUS"
  669. assert len(res["policies"]) >= 0
  670. with pytest.raises(KeycloakGetError) as err:
  671. admin.get_client_authz_settings(client_id=client_id)
  672. assert err.match('404: b\'{"error":"HTTP 404 Not Found"}\'')
  673. # Authz resources
  674. res = admin.get_client_authz_resources(client_id=auth_client_id)
  675. assert len(res) == 1
  676. assert res[0]["name"] == "Default Resource"
  677. with pytest.raises(KeycloakGetError) as err:
  678. admin.get_client_authz_resources(client_id=client_id)
  679. assert err.match('404: b\'{"error":"HTTP 404 Not Found"}\'')
  680. res = admin.create_client_authz_resource(
  681. client_id=auth_client_id, payload={"name": "test-resource"}
  682. )
  683. assert res["name"] == "test-resource", res
  684. test_resource_id = res["_id"]
  685. res = admin.get_client_authz_resource(client_id=auth_client_id, resource_id=test_resource_id)
  686. assert res["_id"] == test_resource_id, res
  687. assert res["name"] == "test-resource", res
  688. with pytest.raises(KeycloakPostError) as err:
  689. admin.create_client_authz_resource(
  690. client_id=auth_client_id, payload={"name": "test-resource"}
  691. )
  692. assert err.match('409: b\'{"error":"invalid_request"')
  693. assert admin.create_client_authz_resource(
  694. client_id=auth_client_id, payload={"name": "test-resource"}, skip_exists=True
  695. ) == {"msg": "Already exists"}
  696. res = admin.get_client_authz_resources(client_id=auth_client_id)
  697. assert len(res) == 2
  698. assert {x["name"] for x in res} == {"Default Resource", "test-resource"}
  699. res = admin.create_client_authz_resource(
  700. client_id=auth_client_id, payload={"name": "temp-resource"}
  701. )
  702. assert res["name"] == "temp-resource", res
  703. temp_resource_id: str = res["_id"]
  704. # Test update authz resources
  705. admin.update_client_authz_resource(
  706. client_id=auth_client_id,
  707. resource_id=temp_resource_id,
  708. payload={"name": "temp-updated-resource"},
  709. )
  710. res = admin.get_client_authz_resource(client_id=auth_client_id, resource_id=temp_resource_id)
  711. assert res["name"] == "temp-updated-resource", res
  712. with pytest.raises(KeycloakPutError) as err:
  713. admin.update_client_authz_resource(
  714. client_id=auth_client_id,
  715. resource_id="invalid_resource_id",
  716. payload={"name": "temp-updated-resource"},
  717. )
  718. assert err.match("404: b''"), err
  719. admin.delete_client_authz_resource(client_id=auth_client_id, resource_id=temp_resource_id)
  720. with pytest.raises(KeycloakGetError) as err:
  721. admin.get_client_authz_resource(client_id=auth_client_id, resource_id=temp_resource_id)
  722. assert err.match("404: b''")
  723. # Authz policies
  724. res = admin.get_client_authz_policies(client_id=auth_client_id)
  725. assert len(res) == 1, res
  726. assert res[0]["name"] == "Default Policy"
  727. with pytest.raises(KeycloakGetError) as err:
  728. admin.get_client_authz_policies(client_id="does-not-exist")
  729. assert err.match('404: b\'{"error":"Could not find client"}\'')
  730. role_id = admin.get_realm_role(role_name="offline_access")["id"]
  731. res = admin.create_client_authz_role_based_policy(
  732. client_id=auth_client_id,
  733. payload={"name": "test-authz-rb-policy", "roles": [{"id": role_id}]},
  734. )
  735. assert res["name"] == "test-authz-rb-policy", res
  736. with pytest.raises(KeycloakPostError) as err:
  737. admin.create_client_authz_role_based_policy(
  738. client_id=auth_client_id,
  739. payload={"name": "test-authz-rb-policy", "roles": [{"id": role_id}]},
  740. )
  741. assert err.match('409: b\'{"error":"Policy with name')
  742. assert admin.create_client_authz_role_based_policy(
  743. client_id=auth_client_id,
  744. payload={"name": "test-authz-rb-policy", "roles": [{"id": role_id}]},
  745. skip_exists=True,
  746. ) == {"msg": "Already exists"}
  747. assert len(admin.get_client_authz_policies(client_id=auth_client_id)) == 2
  748. res = admin.create_client_authz_role_based_policy(
  749. client_id=auth_client_id,
  750. payload={"name": "test-authz-rb-policy-delete", "roles": [{"id": role_id}]},
  751. )
  752. res2 = admin.get_client_authz_policy(client_id=auth_client_id, policy_id=res["id"])
  753. assert res["id"] == res2["id"]
  754. admin.delete_client_authz_policy(client_id=auth_client_id, policy_id=res["id"])
  755. with pytest.raises(KeycloakGetError) as err:
  756. admin.get_client_authz_policy(client_id=auth_client_id, policy_id=res["id"])
  757. assert err.match("404: b''")
  758. res = admin.create_client_authz_policy(
  759. client_id=auth_client_id,
  760. payload={
  761. "name": "test-authz-policy",
  762. "type": "time",
  763. "config": {"hourEnd": "18", "hour": "9"},
  764. },
  765. )
  766. assert res["name"] == "test-authz-policy", res
  767. with pytest.raises(KeycloakPostError) as err:
  768. admin.create_client_authz_policy(
  769. client_id=auth_client_id,
  770. payload={
  771. "name": "test-authz-policy",
  772. "type": "time",
  773. "config": {"hourEnd": "18", "hour": "9"},
  774. },
  775. )
  776. assert err.match('409: b\'{"error":"Policy with name')
  777. assert admin.create_client_authz_policy(
  778. client_id=auth_client_id,
  779. payload={
  780. "name": "test-authz-policy",
  781. "type": "time",
  782. "config": {"hourEnd": "18", "hour": "9"},
  783. },
  784. skip_exists=True,
  785. ) == {"msg": "Already exists"}
  786. assert len(admin.get_client_authz_policies(client_id=auth_client_id)) == 3
  787. # Test authz permissions
  788. res = admin.get_client_authz_permissions(client_id=auth_client_id)
  789. assert len(res) == 1, res
  790. assert res[0]["name"] == "Default Permission"
  791. with pytest.raises(KeycloakGetError) as err:
  792. admin.get_client_authz_permissions(client_id="does-not-exist")
  793. assert err.match('404: b\'{"error":"Could not find client"}\'')
  794. res = admin.create_client_authz_resource_based_permission(
  795. client_id=auth_client_id,
  796. payload={"name": "test-permission-rb", "resources": [test_resource_id]},
  797. )
  798. assert res, res
  799. assert res["name"] == "test-permission-rb"
  800. assert res["resources"] == [test_resource_id]
  801. with pytest.raises(KeycloakPostError) as err:
  802. admin.create_client_authz_resource_based_permission(
  803. client_id=auth_client_id,
  804. payload={"name": "test-permission-rb", "resources": [test_resource_id]},
  805. )
  806. assert err.match('409: b\'{"error":"Policy with name')
  807. assert admin.create_client_authz_resource_based_permission(
  808. client_id=auth_client_id,
  809. payload={"name": "test-permission-rb", "resources": [test_resource_id]},
  810. skip_exists=True,
  811. ) == {"msg": "Already exists"}
  812. assert len(admin.get_client_authz_permissions(client_id=auth_client_id)) == 2
  813. # Test authz scopes
  814. res = admin.get_client_authz_scopes(client_id=auth_client_id)
  815. assert len(res) == 0, res
  816. with pytest.raises(KeycloakGetError) as err:
  817. admin.get_client_authz_scopes(client_id=client_id)
  818. assert err.match('404: b\'{"error":"HTTP 404 Not Found"}\'')
  819. res = admin.create_client_authz_scopes(
  820. client_id=auth_client_id, payload={"name": "test-authz-scope"}
  821. )
  822. assert res["name"] == "test-authz-scope", res
  823. test_scope_id = res["id"]
  824. with pytest.raises(KeycloakPostError) as err:
  825. admin.create_client_authz_scopes(
  826. client_id="invalid_client_id", payload={"name": "test-authz-scope"}
  827. )
  828. assert err.match('404: b\'{"error":"Could not find client"')
  829. assert admin.create_client_authz_scopes(
  830. client_id=auth_client_id, payload={"name": "test-authz-scope"}
  831. )
  832. res = admin.get_client_authz_scopes(client_id=auth_client_id)
  833. assert len(res) == 1
  834. assert {x["name"] for x in res} == {"test-authz-scope"}
  835. res = admin.create_client_authz_scope_based_permission(
  836. client_id=auth_client_id,
  837. payload={
  838. "name": "test-permission-sb",
  839. "resources": [test_resource_id],
  840. "scopes": [test_scope_id],
  841. },
  842. )
  843. assert res, res
  844. assert res["name"] == "test-permission-sb"
  845. assert res["resources"] == [test_resource_id]
  846. assert res["scopes"] == [test_scope_id]
  847. with pytest.raises(KeycloakPostError) as err:
  848. admin.create_client_authz_scope_based_permission(
  849. client_id=auth_client_id,
  850. payload={
  851. "name": "test-permission-sb",
  852. "resources": [test_resource_id],
  853. "scopes": [test_scope_id],
  854. },
  855. )
  856. assert err.match('409: b\'{"error":"Policy with name')
  857. assert admin.create_client_authz_scope_based_permission(
  858. client_id=auth_client_id,
  859. payload={
  860. "name": "test-permission-sb",
  861. "resources": [test_resource_id],
  862. "scopes": [test_scope_id],
  863. },
  864. skip_exists=True,
  865. ) == {"msg": "Already exists"}
  866. assert len(admin.get_client_authz_permissions(client_id=auth_client_id)) == 3
  867. # Test service account user
  868. res = admin.get_client_service_account_user(client_id=auth_client_id)
  869. assert res["username"] == "service-account-authz-client", res
  870. with pytest.raises(KeycloakGetError) as err:
  871. admin.get_client_service_account_user(client_id=client_id)
  872. assert err.match('400: b\'{"error":"unknown_error"}\'')
  873. # Test delete client
  874. res = admin.delete_client(client_id=auth_client_id)
  875. assert res == dict(), res
  876. with pytest.raises(KeycloakDeleteError) as err:
  877. admin.delete_client(client_id=auth_client_id)
  878. assert err.match('404: b\'{"error":"Could not find client"}\'')
  879. # Test client credentials
  880. admin.create_client(
  881. payload={
  882. "name": "test-confidential",
  883. "enabled": True,
  884. "protocol": "openid-connect",
  885. "publicClient": False,
  886. "redirectUris": ["http://localhost/*"],
  887. "webOrigins": ["+"],
  888. "clientId": "test-confidential",
  889. "secret": "test-secret",
  890. "clientAuthenticatorType": "client-secret",
  891. }
  892. )
  893. with pytest.raises(KeycloakGetError) as err:
  894. admin.get_client_secrets(client_id="does-not-exist")
  895. assert err.match('404: b\'{"error":"Could not find client"}\'')
  896. secrets = admin.get_client_secrets(
  897. client_id=admin.get_client_id(client_id="test-confidential")
  898. )
  899. assert secrets == {"type": "secret", "value": "test-secret"}
  900. with pytest.raises(KeycloakPostError) as err:
  901. admin.generate_client_secrets(client_id="does-not-exist")
  902. assert err.match('404: b\'{"error":"Could not find client"}\'')
  903. res = admin.generate_client_secrets(
  904. client_id=admin.get_client_id(client_id="test-confidential")
  905. )
  906. assert res
  907. assert (
  908. admin.get_client_secrets(client_id=admin.get_client_id(client_id="test-confidential"))
  909. == res
  910. )
  911. def test_realm_roles(admin: KeycloakAdmin, realm: str):
  912. """Test realm roles.
  913. :param admin: Keycloak Admin client
  914. :type admin: KeycloakAdmin
  915. :param realm: Keycloak realm
  916. :type realm: str
  917. """
  918. admin.realm_name = realm
  919. # Test get realm roles
  920. roles = admin.get_realm_roles()
  921. assert len(roles) == 3, roles
  922. role_names = [x["name"] for x in roles]
  923. assert "uma_authorization" in role_names, role_names
  924. assert "offline_access" in role_names, role_names
  925. # Test get realm roles with search text
  926. searched_roles = admin.get_realm_roles(search_text="uma_a")
  927. searched_role_names = [x["name"] for x in searched_roles]
  928. assert "uma_authorization" in searched_role_names, searched_role_names
  929. assert "offline_access" not in searched_role_names, searched_role_names
  930. # Test empty members
  931. with pytest.raises(KeycloakGetError) as err:
  932. admin.get_realm_role_members(role_name="does-not-exist")
  933. assert err.match('404: b\'{"error":"Could not find role"}\'')
  934. members = admin.get_realm_role_members(role_name="offline_access")
  935. assert members == list(), members
  936. # Test create realm role
  937. role_id = admin.create_realm_role(payload={"name": "test-realm-role"}, skip_exists=True)
  938. assert role_id, role_id
  939. with pytest.raises(KeycloakPostError) as err:
  940. admin.create_realm_role(payload={"name": "test-realm-role"})
  941. assert err.match('409: b\'{"errorMessage":"Role with name test-realm-role already exists"}\'')
  942. role_id_2 = admin.create_realm_role(payload={"name": "test-realm-role"}, skip_exists=True)
  943. assert role_id == role_id_2
  944. # Test update realm role
  945. res = admin.update_realm_role(
  946. role_name="test-realm-role", payload={"name": "test-realm-role-update"}
  947. )
  948. assert res == dict(), res
  949. with pytest.raises(KeycloakPutError) as err:
  950. admin.update_realm_role(
  951. role_name="test-realm-role", payload={"name": "test-realm-role-update"}
  952. )
  953. assert err.match('404: b\'{"error":"Could not find role"}\''), err
  954. # Test realm role user assignment
  955. user_id = admin.create_user(payload={"username": "role-testing", "email": "test@test.test"})
  956. with pytest.raises(KeycloakPostError) as err:
  957. admin.assign_realm_roles(user_id=user_id, roles=["bad"])
  958. assert err.match('b\'{"error":"unknown_error"}\''), err
  959. res = admin.assign_realm_roles(
  960. user_id=user_id,
  961. roles=[
  962. admin.get_realm_role(role_name="offline_access"),
  963. admin.get_realm_role(role_name="test-realm-role-update"),
  964. ],
  965. )
  966. assert res == dict(), res
  967. assert admin.get_user(user_id=user_id)["username"] in [
  968. x["username"] for x in admin.get_realm_role_members(role_name="offline_access")
  969. ]
  970. assert admin.get_user(user_id=user_id)["username"] in [
  971. x["username"] for x in admin.get_realm_role_members(role_name="test-realm-role-update")
  972. ]
  973. roles = admin.get_realm_roles_of_user(user_id=user_id)
  974. assert len(roles) == 3
  975. assert "offline_access" in [x["name"] for x in roles]
  976. assert "test-realm-role-update" in [x["name"] for x in roles]
  977. with pytest.raises(KeycloakDeleteError) as err:
  978. admin.delete_realm_roles_of_user(user_id=user_id, roles=["bad"])
  979. assert err.match('b\'{"error":"unknown_error"}\''), err
  980. res = admin.delete_realm_roles_of_user(
  981. user_id=user_id, roles=[admin.get_realm_role(role_name="offline_access")]
  982. )
  983. assert res == dict(), res
  984. assert admin.get_realm_role_members(role_name="offline_access") == list()
  985. roles = admin.get_realm_roles_of_user(user_id=user_id)
  986. assert len(roles) == 2
  987. assert "offline_access" not in [x["name"] for x in roles]
  988. assert "test-realm-role-update" in [x["name"] for x in roles]
  989. roles = admin.get_available_realm_roles_of_user(user_id=user_id)
  990. assert len(roles) == 2
  991. assert "offline_access" in [x["name"] for x in roles]
  992. assert "uma_authorization" in [x["name"] for x in roles]
  993. # Test realm role group assignment
  994. group_id = admin.create_group(payload={"name": "test-group"})
  995. with pytest.raises(KeycloakPostError) as err:
  996. admin.assign_group_realm_roles(group_id=group_id, roles=["bad"])
  997. assert err.match('b\'{"error":"unknown_error"}\''), err
  998. res = admin.assign_group_realm_roles(
  999. group_id=group_id,
  1000. roles=[
  1001. admin.get_realm_role(role_name="offline_access"),
  1002. admin.get_realm_role(role_name="test-realm-role-update"),
  1003. ],
  1004. )
  1005. assert res == dict(), res
  1006. roles = admin.get_group_realm_roles(group_id=group_id)
  1007. assert len(roles) == 2
  1008. assert "offline_access" in [x["name"] for x in roles]
  1009. assert "test-realm-role-update" in [x["name"] for x in roles]
  1010. with pytest.raises(KeycloakDeleteError) as err:
  1011. admin.delete_group_realm_roles(group_id=group_id, roles=["bad"])
  1012. assert err.match('b\'{"error":"unknown_error"}\''), err
  1013. res = admin.delete_group_realm_roles(
  1014. group_id=group_id, roles=[admin.get_realm_role(role_name="offline_access")]
  1015. )
  1016. assert res == dict(), res
  1017. roles = admin.get_group_realm_roles(group_id=group_id)
  1018. assert len(roles) == 1
  1019. assert "test-realm-role-update" in [x["name"] for x in roles]
  1020. # Test composite realm roles
  1021. composite_role = admin.create_realm_role(payload={"name": "test-composite-role"})
  1022. with pytest.raises(KeycloakPostError) as err:
  1023. admin.add_composite_realm_roles_to_role(role_name=composite_role, roles=["bad"])
  1024. assert err.match('b\'{"error":"unknown_error"}\''), err
  1025. res = admin.add_composite_realm_roles_to_role(
  1026. role_name=composite_role, roles=[admin.get_realm_role(role_name="test-realm-role-update")]
  1027. )
  1028. assert res == dict(), res
  1029. res = admin.get_composite_realm_roles_of_role(role_name=composite_role)
  1030. assert len(res) == 1
  1031. assert "test-realm-role-update" in res[0]["name"]
  1032. with pytest.raises(KeycloakGetError) as err:
  1033. admin.get_composite_realm_roles_of_role(role_name="bad")
  1034. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1035. res = admin.get_composite_realm_roles_of_user(user_id=user_id)
  1036. assert len(res) == 4
  1037. assert "offline_access" in {x["name"] for x in res}
  1038. assert "test-realm-role-update" in {x["name"] for x in res}
  1039. assert "uma_authorization" in {x["name"] for x in res}
  1040. with pytest.raises(KeycloakGetError) as err:
  1041. admin.get_composite_realm_roles_of_user(user_id="bad")
  1042. assert err.match('b\'{"error":"User not found"}\''), err
  1043. with pytest.raises(KeycloakDeleteError) as err:
  1044. admin.remove_composite_realm_roles_to_role(role_name=composite_role, roles=["bad"])
  1045. assert err.match('b\'{"error":"unknown_error"}\''), err
  1046. res = admin.remove_composite_realm_roles_to_role(
  1047. role_name=composite_role, roles=[admin.get_realm_role(role_name="test-realm-role-update")]
  1048. )
  1049. assert res == dict(), res
  1050. res = admin.get_composite_realm_roles_of_role(role_name=composite_role)
  1051. assert len(res) == 0
  1052. # Test delete realm role
  1053. res = admin.delete_realm_role(role_name=composite_role)
  1054. assert res == dict(), res
  1055. with pytest.raises(KeycloakDeleteError) as err:
  1056. admin.delete_realm_role(role_name=composite_role)
  1057. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1058. @pytest.mark.parametrize(
  1059. "testcase, arg_brief_repr, includes_attributes",
  1060. [
  1061. ("brief True", {"brief_representation": True}, False),
  1062. ("brief False", {"brief_representation": False}, True),
  1063. ("default", {}, False),
  1064. ],
  1065. )
  1066. def test_role_attributes(
  1067. admin: KeycloakAdmin,
  1068. realm: str,
  1069. client: str,
  1070. arg_brief_repr: dict,
  1071. includes_attributes: bool,
  1072. testcase: str,
  1073. ):
  1074. """Test getting role attributes for bulk calls.
  1075. :param admin: Keycloak admin
  1076. :type admin: KeycloakAdmin
  1077. :param realm: Keycloak realm
  1078. :type realm: str
  1079. :param client: Keycloak client
  1080. :type client: str
  1081. :param arg_brief_repr: Brief representation
  1082. :type arg_brief_repr: dict
  1083. :param includes_attributes: Indicator whether to include attributes
  1084. :type includes_attributes: bool
  1085. :param testcase: Test case
  1086. :type testcase: str
  1087. """
  1088. # setup
  1089. attribute_role = "test-realm-role-w-attr"
  1090. test_attrs = {"attr1": ["val1"], "attr2": ["val2-1", "val2-2"]}
  1091. role_id = admin.create_realm_role(
  1092. payload={"name": attribute_role, "attributes": test_attrs}, skip_exists=True
  1093. )
  1094. assert role_id, role_id
  1095. cli_role_id = admin.create_client_role(
  1096. client, payload={"name": attribute_role, "attributes": test_attrs}, skip_exists=True
  1097. )
  1098. assert cli_role_id, cli_role_id
  1099. if not includes_attributes:
  1100. test_attrs = None
  1101. # tests
  1102. roles = admin.get_realm_roles(**arg_brief_repr)
  1103. roles_filtered = [role for role in roles if role["name"] == role_id]
  1104. assert roles_filtered, roles_filtered
  1105. role = roles_filtered[0]
  1106. assert role.get("attributes") == test_attrs, testcase
  1107. roles = admin.get_client_roles(client, **arg_brief_repr)
  1108. roles_filtered = [role for role in roles if role["name"] == cli_role_id]
  1109. assert roles_filtered, roles_filtered
  1110. role = roles_filtered[0]
  1111. assert role.get("attributes") == test_attrs, testcase
  1112. # cleanup
  1113. res = admin.delete_realm_role(role_name=attribute_role)
  1114. assert res == dict(), res
  1115. res = admin.delete_client_role(client, role_name=attribute_role)
  1116. assert res == dict(), res
  1117. def test_client_scope_realm_roles(admin: KeycloakAdmin, realm: str):
  1118. """Test client realm roles.
  1119. :param admin: Keycloak admin
  1120. :type admin: KeycloakAdmin
  1121. :param realm: Keycloak realm
  1122. :type realm: str
  1123. """
  1124. admin.realm_name = realm
  1125. # Test get realm roles
  1126. roles = admin.get_realm_roles()
  1127. assert len(roles) == 3, roles
  1128. role_names = [x["name"] for x in roles]
  1129. assert "uma_authorization" in role_names, role_names
  1130. assert "offline_access" in role_names, role_names
  1131. # create realm role for test
  1132. role_id = admin.create_realm_role(payload={"name": "test-realm-role"}, skip_exists=True)
  1133. assert role_id, role_id
  1134. # Test realm role client assignment
  1135. client_id = admin.create_client(
  1136. payload={"name": "role-testing-client", "clientId": "role-testing-client"}
  1137. )
  1138. with pytest.raises(KeycloakPostError) as err:
  1139. admin.assign_realm_roles_to_client_scope(client_id=client_id, roles=["bad"])
  1140. assert err.match('b\'{"error":"unknown_error"}\''), err
  1141. res = admin.assign_realm_roles_to_client_scope(
  1142. client_id=client_id,
  1143. roles=[
  1144. admin.get_realm_role(role_name="offline_access"),
  1145. admin.get_realm_role(role_name="test-realm-role"),
  1146. ],
  1147. )
  1148. assert res == dict(), res
  1149. roles = admin.get_realm_roles_of_client_scope(client_id=client_id)
  1150. assert len(roles) == 2
  1151. client_role_names = [x["name"] for x in roles]
  1152. assert "offline_access" in client_role_names, client_role_names
  1153. assert "test-realm-role" in client_role_names, client_role_names
  1154. assert "uma_authorization" not in client_role_names, client_role_names
  1155. # Test remove realm role of client
  1156. with pytest.raises(KeycloakDeleteError) as err:
  1157. admin.delete_realm_roles_of_client_scope(client_id=client_id, roles=["bad"])
  1158. assert err.match('b\'{"error":"unknown_error"}\''), err
  1159. res = admin.delete_realm_roles_of_client_scope(
  1160. client_id=client_id, roles=[admin.get_realm_role(role_name="offline_access")]
  1161. )
  1162. assert res == dict(), res
  1163. roles = admin.get_realm_roles_of_client_scope(client_id=client_id)
  1164. assert len(roles) == 1
  1165. assert "test-realm-role" in [x["name"] for x in roles]
  1166. res = admin.delete_realm_roles_of_client_scope(
  1167. client_id=client_id, roles=[admin.get_realm_role(role_name="test-realm-role")]
  1168. )
  1169. assert res == dict(), res
  1170. roles = admin.get_realm_roles_of_client_scope(client_id=client_id)
  1171. assert len(roles) == 0
  1172. def test_client_scope_client_roles(admin: KeycloakAdmin, realm: str, client: str):
  1173. """Test client assignment of other client roles.
  1174. :param admin: Keycloak admin
  1175. :type admin: KeycloakAdmin
  1176. :param realm: Keycloak realm
  1177. :type realm: str
  1178. :param client: Keycloak client
  1179. :type client: str
  1180. """
  1181. admin.realm_name = realm
  1182. client_id = admin.create_client(
  1183. payload={"name": "role-testing-client", "clientId": "role-testing-client"}
  1184. )
  1185. # Test get client roles
  1186. roles = admin.get_client_roles_of_client_scope(client_id, client)
  1187. assert len(roles) == 0, roles
  1188. # create client role for test
  1189. client_role_id = admin.create_client_role(
  1190. client_role_id=client, payload={"name": "client-role-test"}, skip_exists=True
  1191. )
  1192. assert client_role_id, client_role_id
  1193. # Test client role assignment to other client
  1194. with pytest.raises(KeycloakPostError) as err:
  1195. admin.assign_client_roles_to_client_scope(
  1196. client_id=client_id, client_roles_owner_id=client, roles=["bad"]
  1197. )
  1198. assert err.match('b\'{"error":"unknown_error"}\''), err
  1199. res = admin.assign_client_roles_to_client_scope(
  1200. client_id=client_id,
  1201. client_roles_owner_id=client,
  1202. roles=[admin.get_client_role(client_id=client, role_name="client-role-test")],
  1203. )
  1204. assert res == dict(), res
  1205. roles = admin.get_client_roles_of_client_scope(
  1206. client_id=client_id, client_roles_owner_id=client
  1207. )
  1208. assert len(roles) == 1
  1209. client_role_names = [x["name"] for x in roles]
  1210. assert "client-role-test" in client_role_names, client_role_names
  1211. # Test remove realm role of client
  1212. with pytest.raises(KeycloakDeleteError) as err:
  1213. admin.delete_client_roles_of_client_scope(
  1214. client_id=client_id, client_roles_owner_id=client, roles=["bad"]
  1215. )
  1216. assert err.match('b\'{"error":"unknown_error"}\''), err
  1217. res = admin.delete_client_roles_of_client_scope(
  1218. client_id=client_id,
  1219. client_roles_owner_id=client,
  1220. roles=[admin.get_client_role(client_id=client, role_name="client-role-test")],
  1221. )
  1222. assert res == dict(), res
  1223. roles = admin.get_client_roles_of_client_scope(
  1224. client_id=client_id, client_roles_owner_id=client
  1225. )
  1226. assert len(roles) == 0
  1227. def test_client_default_client_scopes(admin: KeycloakAdmin, realm: str, client: str):
  1228. """Test client assignment of default client scopes.
  1229. :param admin: Keycloak admin
  1230. :type admin: KeycloakAdmin
  1231. :param realm: Keycloak realm
  1232. :type realm: str
  1233. :param client: Keycloak client
  1234. :type client: str
  1235. """
  1236. admin.realm_name = realm
  1237. client_id = admin.create_client(
  1238. payload={"name": "role-testing-client", "clientId": "role-testing-client"}
  1239. )
  1240. # Test get client default scopes
  1241. # keycloak default roles: web-origins, acr, profile, roles, email
  1242. default_client_scopes = admin.get_client_default_client_scopes(client_id)
  1243. assert len(default_client_scopes) == 5, default_client_scopes
  1244. # Test add a client scope to client default scopes
  1245. default_client_scope = "test-client-default-scope"
  1246. new_client_scope = {
  1247. "name": default_client_scope,
  1248. "description": f"Test Client Scope: {default_client_scope}",
  1249. "protocol": "openid-connect",
  1250. "attributes": {},
  1251. }
  1252. new_client_scope_id = admin.create_client_scope(new_client_scope, skip_exists=False)
  1253. new_default_client_scope_data = {
  1254. "realm": realm,
  1255. "client": client_id,
  1256. "clientScopeId": new_client_scope_id,
  1257. }
  1258. admin.add_client_default_client_scope(
  1259. client_id, new_client_scope_id, new_default_client_scope_data
  1260. )
  1261. default_client_scopes = admin.get_client_default_client_scopes(client_id)
  1262. assert len(default_client_scopes) == 6, default_client_scopes
  1263. # Test remove a client default scope
  1264. admin.delete_client_default_client_scope(client_id, new_client_scope_id)
  1265. default_client_scopes = admin.get_client_default_client_scopes(client_id)
  1266. assert len(default_client_scopes) == 5, default_client_scopes
  1267. def test_client_optional_client_scopes(admin: KeycloakAdmin, realm: str, client: str):
  1268. """Test client assignment of optional client scopes.
  1269. :param admin: Keycloak admin
  1270. :type admin: KeycloakAdmin
  1271. :param realm: Keycloak realm
  1272. :type realm: str
  1273. :param client: Keycloak client
  1274. :type client: str
  1275. """
  1276. admin.realm_name = realm
  1277. client_id = admin.create_client(
  1278. payload={"name": "role-testing-client", "clientId": "role-testing-client"}
  1279. )
  1280. # Test get client optional scopes
  1281. # keycloak optional roles: microprofile-jwt, offline_access, address, phone
  1282. optional_client_scopes = admin.get_client_optional_client_scopes(client_id)
  1283. assert len(optional_client_scopes) == 4, optional_client_scopes
  1284. # Test add a client scope to client optional scopes
  1285. optional_client_scope = "test-client-optional-scope"
  1286. new_client_scope = {
  1287. "name": optional_client_scope,
  1288. "description": f"Test Client Scope: {optional_client_scope}",
  1289. "protocol": "openid-connect",
  1290. "attributes": {},
  1291. }
  1292. new_client_scope_id = admin.create_client_scope(new_client_scope, skip_exists=False)
  1293. new_optional_client_scope_data = {
  1294. "realm": realm,
  1295. "client": client_id,
  1296. "clientScopeId": new_client_scope_id,
  1297. }
  1298. admin.add_client_optional_client_scope(
  1299. client_id, new_client_scope_id, new_optional_client_scope_data
  1300. )
  1301. optional_client_scopes = admin.get_client_optional_client_scopes(client_id)
  1302. assert len(optional_client_scopes) == 5, optional_client_scopes
  1303. # Test remove a client optional scope
  1304. admin.delete_client_optional_client_scope(client_id, new_client_scope_id)
  1305. optional_client_scopes = admin.get_client_optional_client_scopes(client_id)
  1306. assert len(optional_client_scopes) == 4, optional_client_scopes
  1307. def test_client_roles(admin: KeycloakAdmin, client: str):
  1308. """Test client roles.
  1309. :param admin: Keycloak Admin client
  1310. :type admin: KeycloakAdmin
  1311. :param client: Keycloak client
  1312. :type client: str
  1313. """
  1314. # Test get client roles
  1315. res = admin.get_client_roles(client_id=client)
  1316. assert len(res) == 0
  1317. with pytest.raises(KeycloakGetError) as err:
  1318. admin.get_client_roles(client_id="bad")
  1319. assert err.match('404: b\'{"error":"Could not find client"}\'')
  1320. # Test create client role
  1321. client_role_id = admin.create_client_role(
  1322. client_role_id=client, payload={"name": "client-role-test"}, skip_exists=True
  1323. )
  1324. with pytest.raises(KeycloakPostError) as err:
  1325. admin.create_client_role(client_role_id=client, payload={"name": "client-role-test"})
  1326. assert err.match('409: b\'{"errorMessage":"Role with name client-role-test already exists"}\'')
  1327. client_role_id_2 = admin.create_client_role(
  1328. client_role_id=client, payload={"name": "client-role-test"}, skip_exists=True
  1329. )
  1330. assert client_role_id == client_role_id_2
  1331. # Test get client role
  1332. res = admin.get_client_role(client_id=client, role_name="client-role-test")
  1333. assert res["name"] == client_role_id
  1334. with pytest.raises(KeycloakGetError) as err:
  1335. admin.get_client_role(client_id=client, role_name="bad")
  1336. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1337. res_ = admin.get_client_role_id(client_id=client, role_name="client-role-test")
  1338. assert res_ == res["id"]
  1339. with pytest.raises(KeycloakGetError) as err:
  1340. admin.get_client_role_id(client_id=client, role_name="bad")
  1341. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1342. assert len(admin.get_client_roles(client_id=client)) == 1
  1343. # Test update client role
  1344. res = admin.update_client_role(
  1345. client_role_id=client,
  1346. role_name="client-role-test",
  1347. payload={"name": "client-role-test-update"},
  1348. )
  1349. assert res == dict()
  1350. with pytest.raises(KeycloakPutError) as err:
  1351. res = admin.update_client_role(
  1352. client_role_id=client,
  1353. role_name="client-role-test",
  1354. payload={"name": "client-role-test-update"},
  1355. )
  1356. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1357. # Test user with client role
  1358. res = admin.get_client_role_members(client_id=client, role_name="client-role-test-update")
  1359. assert len(res) == 0
  1360. with pytest.raises(KeycloakGetError) as err:
  1361. admin.get_client_role_members(client_id=client, role_name="bad")
  1362. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1363. user_id = admin.create_user(payload={"username": "test", "email": "test@test.test"})
  1364. with pytest.raises(KeycloakPostError) as err:
  1365. admin.assign_client_role(user_id=user_id, client_id=client, roles=["bad"])
  1366. assert err.match('b\'{"error":"unknown_error"}\''), err
  1367. res = admin.assign_client_role(
  1368. user_id=user_id,
  1369. client_id=client,
  1370. roles=[admin.get_client_role(client_id=client, role_name="client-role-test-update")],
  1371. )
  1372. assert res == dict()
  1373. assert (
  1374. len(admin.get_client_role_members(client_id=client, role_name="client-role-test-update"))
  1375. == 1
  1376. )
  1377. roles = admin.get_client_roles_of_user(user_id=user_id, client_id=client)
  1378. assert len(roles) == 1, roles
  1379. with pytest.raises(KeycloakGetError) as err:
  1380. admin.get_client_roles_of_user(user_id=user_id, client_id="bad")
  1381. assert err.match('404: b\'{"error":"Client not found"}\'')
  1382. roles = admin.get_composite_client_roles_of_user(user_id=user_id, client_id=client)
  1383. assert len(roles) == 1, roles
  1384. with pytest.raises(KeycloakGetError) as err:
  1385. admin.get_composite_client_roles_of_user(user_id=user_id, client_id="bad")
  1386. assert err.match('404: b\'{"error":"Client not found"}\'')
  1387. roles = admin.get_available_client_roles_of_user(user_id=user_id, client_id=client)
  1388. assert len(roles) == 0, roles
  1389. with pytest.raises(KeycloakGetError) as err:
  1390. admin.get_composite_client_roles_of_user(user_id=user_id, client_id="bad")
  1391. assert err.match('404: b\'{"error":"Client not found"}\'')
  1392. with pytest.raises(KeycloakDeleteError) as err:
  1393. admin.delete_client_roles_of_user(user_id=user_id, client_id=client, roles=["bad"])
  1394. assert err.match('b\'{"error":"unknown_error"}\''), err
  1395. admin.delete_client_roles_of_user(
  1396. user_id=user_id,
  1397. client_id=client,
  1398. roles=[admin.get_client_role(client_id=client, role_name="client-role-test-update")],
  1399. )
  1400. assert len(admin.get_client_roles_of_user(user_id=user_id, client_id=client)) == 0
  1401. # Test groups and client roles
  1402. res = admin.get_client_role_groups(client_id=client, role_name="client-role-test-update")
  1403. assert len(res) == 0
  1404. with pytest.raises(KeycloakGetError) as err:
  1405. admin.get_client_role_groups(client_id=client, role_name="bad")
  1406. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1407. group_id = admin.create_group(payload={"name": "test-group"})
  1408. res = admin.get_group_client_roles(group_id=group_id, client_id=client)
  1409. assert len(res) == 0
  1410. with pytest.raises(KeycloakGetError) as err:
  1411. admin.get_group_client_roles(group_id=group_id, client_id="bad")
  1412. assert err.match('404: b\'{"error":"Client not found"}\'')
  1413. with pytest.raises(KeycloakPostError) as err:
  1414. admin.assign_group_client_roles(group_id=group_id, client_id=client, roles=["bad"])
  1415. assert err.match('b\'{"error":"unknown_error"}\''), err
  1416. res = admin.assign_group_client_roles(
  1417. group_id=group_id,
  1418. client_id=client,
  1419. roles=[admin.get_client_role(client_id=client, role_name="client-role-test-update")],
  1420. )
  1421. assert res == dict()
  1422. assert (
  1423. len(admin.get_client_role_groups(client_id=client, role_name="client-role-test-update"))
  1424. == 1
  1425. )
  1426. assert len(admin.get_group_client_roles(group_id=group_id, client_id=client)) == 1
  1427. with pytest.raises(KeycloakDeleteError) as err:
  1428. admin.delete_group_client_roles(group_id=group_id, client_id=client, roles=["bad"])
  1429. assert err.match('b\'{"error":"unknown_error"}\''), err
  1430. res = admin.delete_group_client_roles(
  1431. group_id=group_id,
  1432. client_id=client,
  1433. roles=[admin.get_client_role(client_id=client, role_name="client-role-test-update")],
  1434. )
  1435. assert res == dict()
  1436. # Test composite client roles
  1437. with pytest.raises(KeycloakPostError) as err:
  1438. admin.add_composite_client_roles_to_role(
  1439. client_role_id=client, role_name="client-role-test-update", roles=["bad"]
  1440. )
  1441. assert err.match('b\'{"error":"unknown_error"}\''), err
  1442. res = admin.add_composite_client_roles_to_role(
  1443. client_role_id=client,
  1444. role_name="client-role-test-update",
  1445. roles=[admin.get_realm_role(role_name="offline_access")],
  1446. )
  1447. assert res == dict()
  1448. assert admin.get_client_role(client_id=client, role_name="client-role-test-update")[
  1449. "composite"
  1450. ]
  1451. # Test delete of client role
  1452. res = admin.delete_client_role(client_role_id=client, role_name="client-role-test-update")
  1453. assert res == dict()
  1454. with pytest.raises(KeycloakDeleteError) as err:
  1455. admin.delete_client_role(client_role_id=client, role_name="client-role-test-update")
  1456. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1457. def test_enable_token_exchange(admin: KeycloakAdmin, realm: str):
  1458. """Test enable token exchange.
  1459. :param admin: Keycloak Admin client
  1460. :type admin: KeycloakAdmin
  1461. :param realm: Keycloak realm
  1462. :type realm: str
  1463. :raises AssertionError: In case of bad configuration
  1464. """
  1465. # Test enabling token exchange between two confidential clients
  1466. admin.realm_name = realm
  1467. # Create test clients
  1468. source_client_id = admin.create_client(
  1469. payload={"name": "Source Client", "clientId": "source-client"}
  1470. )
  1471. target_client_id = admin.create_client(
  1472. payload={"name": "Target Client", "clientId": "target-client"}
  1473. )
  1474. for c in admin.get_clients():
  1475. if c["clientId"] == "realm-management":
  1476. realm_management_id = c["id"]
  1477. break
  1478. else:
  1479. raise AssertionError("Missing realm management client")
  1480. # Enable permissions on the Superset client
  1481. admin.update_client_management_permissions(
  1482. payload={"enabled": True}, client_id=target_client_id
  1483. )
  1484. # Fetch various IDs and strings needed when creating the permission
  1485. token_exchange_permission_id = admin.get_client_management_permissions(
  1486. client_id=target_client_id
  1487. )["scopePermissions"]["token-exchange"]
  1488. scopes = admin.get_client_authz_policy_scopes(
  1489. client_id=realm_management_id, policy_id=token_exchange_permission_id
  1490. )
  1491. for s in scopes:
  1492. if s["name"] == "token-exchange":
  1493. token_exchange_scope_id = s["id"]
  1494. break
  1495. else:
  1496. raise AssertionError("Missing token-exchange scope")
  1497. resources = admin.get_client_authz_policy_resources(
  1498. client_id=realm_management_id, policy_id=token_exchange_permission_id
  1499. )
  1500. for r in resources:
  1501. if r["name"] == f"client.resource.{target_client_id}":
  1502. token_exchange_resource_id = r["_id"]
  1503. break
  1504. else:
  1505. raise AssertionError("Missing client resource")
  1506. # Create a client policy for source client
  1507. policy_name = "Exchange source client token with target client token"
  1508. client_policy_id = admin.create_client_authz_client_policy(
  1509. payload={
  1510. "type": "client",
  1511. "logic": "POSITIVE",
  1512. "decisionStrategy": "UNANIMOUS",
  1513. "name": policy_name,
  1514. "clients": [source_client_id],
  1515. },
  1516. client_id=realm_management_id,
  1517. )["id"]
  1518. policies = admin.get_client_authz_client_policies(client_id=realm_management_id)
  1519. for policy in policies:
  1520. if policy["name"] == policy_name:
  1521. assert policy["clients"] == [source_client_id]
  1522. break
  1523. else:
  1524. raise AssertionError("Missing client policy")
  1525. # Update permissions on the target client to reference this policy
  1526. permission_name = admin.get_client_authz_scope_permission(
  1527. client_id=realm_management_id, scope_id=token_exchange_permission_id
  1528. )["name"]
  1529. admin.update_client_authz_scope_permission(
  1530. payload={
  1531. "id": token_exchange_permission_id,
  1532. "name": permission_name,
  1533. "type": "scope",
  1534. "logic": "POSITIVE",
  1535. "decisionStrategy": "UNANIMOUS",
  1536. "resources": [token_exchange_resource_id],
  1537. "scopes": [token_exchange_scope_id],
  1538. "policies": [client_policy_id],
  1539. },
  1540. client_id=realm_management_id,
  1541. scope_id=token_exchange_permission_id,
  1542. )
  1543. def test_email(admin: KeycloakAdmin, user: str):
  1544. """Test email.
  1545. :param admin: Keycloak Admin client
  1546. :type admin: KeycloakAdmin
  1547. :param user: Keycloak user
  1548. :type user: str
  1549. """
  1550. # Emails will fail as we don't have SMTP test setup
  1551. with pytest.raises(KeycloakPutError) as err:
  1552. admin.send_update_account(user_id=user, payload=dict())
  1553. assert err.match('b\'{"error":"unknown_error"}\''), err
  1554. admin.update_user(user_id=user, payload={"enabled": True})
  1555. with pytest.raises(KeycloakPutError) as err:
  1556. admin.send_verify_email(user_id=user)
  1557. assert err.match('500: b\'{"errorMessage":"Failed to send execute actions email"}\'')
  1558. def test_get_sessions(admin: KeycloakAdmin):
  1559. """Test get sessions.
  1560. :param admin: Keycloak Admin client
  1561. :type admin: KeycloakAdmin
  1562. """
  1563. sessions = admin.get_sessions(user_id=admin.get_user_id(username=admin.username))
  1564. assert len(sessions) >= 1
  1565. with pytest.raises(KeycloakGetError) as err:
  1566. admin.get_sessions(user_id="bad")
  1567. assert err.match('404: b\'{"error":"User not found"}\'')
  1568. def test_get_client_installation_provider(admin: KeycloakAdmin, client: str):
  1569. """Test get client installation provider.
  1570. :param admin: Keycloak Admin client
  1571. :type admin: KeycloakAdmin
  1572. :param client: Keycloak client
  1573. :type client: str
  1574. """
  1575. with pytest.raises(KeycloakGetError) as err:
  1576. admin.get_client_installation_provider(client_id=client, provider_id="bad")
  1577. assert err.match('404: b\'{"error":"Unknown Provider"}\'')
  1578. installation = admin.get_client_installation_provider(
  1579. client_id=client, provider_id="keycloak-oidc-keycloak-json"
  1580. )
  1581. assert set(installation.keys()) == {
  1582. "auth-server-url",
  1583. "confidential-port",
  1584. "credentials",
  1585. "realm",
  1586. "resource",
  1587. "ssl-required",
  1588. }
  1589. def test_auth_flows(admin: KeycloakAdmin, realm: str):
  1590. """Test auth flows.
  1591. :param admin: Keycloak Admin client
  1592. :type admin: KeycloakAdmin
  1593. :param realm: Keycloak realm
  1594. :type realm: str
  1595. """
  1596. admin.realm_name = realm
  1597. res = admin.get_authentication_flows()
  1598. default_flows = len(res)
  1599. assert {x["alias"] for x in res}.issubset(
  1600. {
  1601. "reset credentials",
  1602. "browser",
  1603. "registration",
  1604. "http challenge",
  1605. "docker auth",
  1606. "direct grant",
  1607. "first broker login",
  1608. "clients",
  1609. }
  1610. )
  1611. assert set(res[0].keys()) == {
  1612. "alias",
  1613. "authenticationExecutions",
  1614. "builtIn",
  1615. "description",
  1616. "id",
  1617. "providerId",
  1618. "topLevel",
  1619. }
  1620. with pytest.raises(KeycloakGetError) as err:
  1621. admin.get_authentication_flow_for_id(flow_id="bad")
  1622. assert err.match('404: b\'{"error":"Could not find flow with id"}\'')
  1623. browser_flow_id = [x for x in res if x["alias"] == "browser"][0]["id"]
  1624. res = admin.get_authentication_flow_for_id(flow_id=browser_flow_id)
  1625. assert res["alias"] == "browser"
  1626. # Test copying
  1627. with pytest.raises(KeycloakPostError) as err:
  1628. admin.copy_authentication_flow(payload=dict(), flow_alias="bad")
  1629. assert err.match("404: b''")
  1630. res = admin.copy_authentication_flow(payload={"newName": "test-browser"}, flow_alias="browser")
  1631. assert res == b"", res
  1632. assert len(admin.get_authentication_flows()) == (default_flows + 1)
  1633. # Test create
  1634. res = admin.create_authentication_flow(
  1635. payload={"alias": "test-create", "providerId": "basic-flow"}
  1636. )
  1637. assert res == b""
  1638. with pytest.raises(KeycloakPostError) as err:
  1639. admin.create_authentication_flow(payload={"alias": "test-create", "builtIn": False})
  1640. assert err.match('409: b\'{"errorMessage":"Flow test-create already exists"}\'')
  1641. assert admin.create_authentication_flow(
  1642. payload={"alias": "test-create"}, skip_exists=True
  1643. ) == {"msg": "Already exists"}
  1644. # Test flow executions
  1645. res = admin.get_authentication_flow_executions(flow_alias="browser")
  1646. assert len(res) == 8, res
  1647. with pytest.raises(KeycloakGetError) as err:
  1648. admin.get_authentication_flow_executions(flow_alias="bad")
  1649. assert err.match("404: b''")
  1650. exec_id = res[0]["id"]
  1651. res = admin.get_authentication_flow_execution(execution_id=exec_id)
  1652. assert set(res.keys()) == {
  1653. "alternative",
  1654. "authenticator",
  1655. "authenticatorFlow",
  1656. "conditional",
  1657. "disabled",
  1658. "enabled",
  1659. "id",
  1660. "parentFlow",
  1661. "priority",
  1662. "required",
  1663. "requirement",
  1664. }, res
  1665. with pytest.raises(KeycloakGetError) as err:
  1666. admin.get_authentication_flow_execution(execution_id="bad")
  1667. assert err.match('404: b\'{"error":"Illegal execution"}\'')
  1668. with pytest.raises(KeycloakPostError) as err:
  1669. admin.create_authentication_flow_execution(payload=dict(), flow_alias="browser")
  1670. assert err.match('400: b\'{"error":"It is illegal to add execution to a built in flow"}\'')
  1671. res = admin.create_authentication_flow_execution(
  1672. payload={"provider": "auth-cookie"}, flow_alias="test-create"
  1673. )
  1674. assert res == b""
  1675. assert len(admin.get_authentication_flow_executions(flow_alias="test-create")) == 1
  1676. with pytest.raises(KeycloakPutError) as err:
  1677. admin.update_authentication_flow_executions(
  1678. payload={"required": "yes"}, flow_alias="test-create"
  1679. )
  1680. assert err.match('400: b\'{"error":"Unrecognized field')
  1681. payload = admin.get_authentication_flow_executions(flow_alias="test-create")[0]
  1682. payload["displayName"] = "test"
  1683. res = admin.update_authentication_flow_executions(payload=payload, flow_alias="test-create")
  1684. assert res
  1685. exec_id = admin.get_authentication_flow_executions(flow_alias="test-create")[0]["id"]
  1686. res = admin.delete_authentication_flow_execution(execution_id=exec_id)
  1687. assert res == dict()
  1688. with pytest.raises(KeycloakDeleteError) as err:
  1689. admin.delete_authentication_flow_execution(execution_id=exec_id)
  1690. assert err.match('404: b\'{"error":"Illegal execution"}\'')
  1691. # Test subflows
  1692. res = admin.create_authentication_flow_subflow(
  1693. payload={
  1694. "alias": "test-subflow",
  1695. "provider": "basic-flow",
  1696. "type": "something",
  1697. "description": "something",
  1698. },
  1699. flow_alias="test-browser",
  1700. )
  1701. assert res == b""
  1702. with pytest.raises(KeycloakPostError) as err:
  1703. admin.create_authentication_flow_subflow(
  1704. payload={"alias": "test-subflow", "providerId": "basic-flow"},
  1705. flow_alias="test-browser",
  1706. )
  1707. assert err.match('409: b\'{"errorMessage":"New flow alias name already exists"}\'')
  1708. res = admin.create_authentication_flow_subflow(
  1709. payload={
  1710. "alias": "test-subflow",
  1711. "provider": "basic-flow",
  1712. "type": "something",
  1713. "description": "something",
  1714. },
  1715. flow_alias="test-create",
  1716. skip_exists=True,
  1717. )
  1718. assert res == {"msg": "Already exists"}
  1719. # Test delete auth flow
  1720. flow_id = [x for x in admin.get_authentication_flows() if x["alias"] == "test-browser"][0][
  1721. "id"
  1722. ]
  1723. res = admin.delete_authentication_flow(flow_id=flow_id)
  1724. assert res == dict()
  1725. with pytest.raises(KeycloakDeleteError) as err:
  1726. admin.delete_authentication_flow(flow_id=flow_id)
  1727. assert err.match('404: b\'{"error":"Could not find flow with id"}\'')
  1728. def test_authentication_configs(admin: KeycloakAdmin, realm: str):
  1729. """Test authentication configs.
  1730. :param admin: Keycloak Admin client
  1731. :type admin: KeycloakAdmin
  1732. :param realm: Keycloak realm
  1733. :type realm: str
  1734. """
  1735. admin.realm_name = realm
  1736. # Test list of auth providers
  1737. res = admin.get_authenticator_providers()
  1738. assert len(res) > 1
  1739. res = admin.get_authenticator_provider_config_description(provider_id="auth-cookie")
  1740. assert res == {
  1741. "helpText": "Validates the SSO cookie set by the auth server.",
  1742. "name": "Cookie",
  1743. "properties": [],
  1744. "providerId": "auth-cookie",
  1745. }
  1746. # Test authenticator config
  1747. # Currently unable to find a sustainable way to fetch the config id,
  1748. # therefore testing only failures
  1749. with pytest.raises(KeycloakGetError) as err:
  1750. admin.get_authenticator_config(config_id="bad")
  1751. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1752. with pytest.raises(KeycloakPutError) as err:
  1753. admin.update_authenticator_config(payload=dict(), config_id="bad")
  1754. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1755. with pytest.raises(KeycloakDeleteError) as err:
  1756. admin.delete_authenticator_config(config_id="bad")
  1757. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1758. def test_sync_users(admin: KeycloakAdmin, realm: str):
  1759. """Test sync users.
  1760. :param admin: Keycloak Admin client
  1761. :type admin: KeycloakAdmin
  1762. :param realm: Keycloak realm
  1763. :type realm: str
  1764. """
  1765. admin.realm_name = realm
  1766. # Only testing the error message
  1767. with pytest.raises(KeycloakPostError) as err:
  1768. admin.sync_users(storage_id="does-not-exist", action="triggerFullSync")
  1769. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1770. def test_client_scopes(admin: KeycloakAdmin, realm: str):
  1771. """Test client scopes.
  1772. :param admin: Keycloak Admin client
  1773. :type admin: KeycloakAdmin
  1774. :param realm: Keycloak realm
  1775. :type realm: str
  1776. """
  1777. admin.realm_name = realm
  1778. # Test get client scopes
  1779. res = admin.get_client_scopes()
  1780. scope_names = {x["name"] for x in res}
  1781. assert len(res) == 10
  1782. assert "email" in scope_names
  1783. assert "profile" in scope_names
  1784. assert "offline_access" in scope_names
  1785. with pytest.raises(KeycloakGetError) as err:
  1786. admin.get_client_scope(client_scope_id="does-not-exist")
  1787. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1788. scope = admin.get_client_scope(client_scope_id=res[0]["id"])
  1789. assert res[0] == scope
  1790. scope = admin.get_client_scope_by_name(client_scope_name=res[0]["name"])
  1791. assert res[0] == scope
  1792. # Test create client scope
  1793. res = admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=True)
  1794. assert res
  1795. res2 = admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=True)
  1796. assert res == res2
  1797. with pytest.raises(KeycloakPostError) as err:
  1798. admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=False)
  1799. assert err.match('409: b\'{"errorMessage":"Client Scope test-scope already exists"}\'')
  1800. # Test update client scope
  1801. with pytest.raises(KeycloakPutError) as err:
  1802. admin.update_client_scope(client_scope_id="does-not-exist", payload=dict())
  1803. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1804. res_update = admin.update_client_scope(
  1805. client_scope_id=res, payload={"name": "test-scope-update"}
  1806. )
  1807. assert res_update == dict()
  1808. admin.get_client_scope(client_scope_id=res)["name"] == "test-scope-update"
  1809. # Test get mappers
  1810. mappers = admin.get_mappers_from_client_scope(client_scope_id=res)
  1811. assert mappers == list()
  1812. # Test add mapper
  1813. with pytest.raises(KeycloakPostError) as err:
  1814. admin.add_mapper_to_client_scope(client_scope_id=res, payload=dict())
  1815. assert err.match('404: b\'{"error":"ProtocolMapper provider not found"}\'')
  1816. res_add = admin.add_mapper_to_client_scope(
  1817. client_scope_id=res,
  1818. payload={
  1819. "name": "test-mapper",
  1820. "protocol": "openid-connect",
  1821. "protocolMapper": "oidc-usermodel-attribute-mapper",
  1822. },
  1823. )
  1824. assert res_add == b""
  1825. assert len(admin.get_mappers_from_client_scope(client_scope_id=res)) == 1
  1826. # Test update mapper
  1827. test_mapper = admin.get_mappers_from_client_scope(client_scope_id=res)[0]
  1828. with pytest.raises(KeycloakPutError) as err:
  1829. admin.update_mapper_in_client_scope(
  1830. client_scope_id="does-not-exist", protocol_mapper_id=test_mapper["id"], payload=dict()
  1831. )
  1832. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1833. test_mapper["config"]["user.attribute"] = "test"
  1834. res_update = admin.update_mapper_in_client_scope(
  1835. client_scope_id=res, protocol_mapper_id=test_mapper["id"], payload=test_mapper
  1836. )
  1837. assert res_update == dict()
  1838. assert (
  1839. admin.get_mappers_from_client_scope(client_scope_id=res)[0]["config"]["user.attribute"]
  1840. == "test"
  1841. )
  1842. # Test delete mapper
  1843. res_del = admin.delete_mapper_from_client_scope(
  1844. client_scope_id=res, protocol_mapper_id=test_mapper["id"]
  1845. )
  1846. assert res_del == dict()
  1847. with pytest.raises(KeycloakDeleteError) as err:
  1848. admin.delete_mapper_from_client_scope(
  1849. client_scope_id=res, protocol_mapper_id=test_mapper["id"]
  1850. )
  1851. assert err.match('404: b\'{"error":"Model not found"}\'')
  1852. # Test default default scopes
  1853. res_defaults = admin.get_default_default_client_scopes()
  1854. assert len(res_defaults) == 6
  1855. with pytest.raises(KeycloakPutError) as err:
  1856. admin.add_default_default_client_scope(scope_id="does-not-exist")
  1857. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1858. res_add = admin.add_default_default_client_scope(scope_id=res)
  1859. assert res_add == dict()
  1860. assert len(admin.get_default_default_client_scopes()) == 7
  1861. with pytest.raises(KeycloakDeleteError) as err:
  1862. admin.delete_default_default_client_scope(scope_id="does-not-exist")
  1863. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1864. res_del = admin.delete_default_default_client_scope(scope_id=res)
  1865. assert res_del == dict()
  1866. assert len(admin.get_default_default_client_scopes()) == 6
  1867. # Test default optional scopes
  1868. res_defaults = admin.get_default_optional_client_scopes()
  1869. assert len(res_defaults) == 4
  1870. with pytest.raises(KeycloakPutError) as err:
  1871. admin.add_default_optional_client_scope(scope_id="does-not-exist")
  1872. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1873. res_add = admin.add_default_optional_client_scope(scope_id=res)
  1874. assert res_add == dict()
  1875. assert len(admin.get_default_optional_client_scopes()) == 5
  1876. with pytest.raises(KeycloakDeleteError) as err:
  1877. admin.delete_default_optional_client_scope(scope_id="does-not-exist")
  1878. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1879. res_del = admin.delete_default_optional_client_scope(scope_id=res)
  1880. assert res_del == dict()
  1881. assert len(admin.get_default_optional_client_scopes()) == 4
  1882. # Test client scope delete
  1883. res_del = admin.delete_client_scope(client_scope_id=res)
  1884. assert res_del == dict()
  1885. with pytest.raises(KeycloakDeleteError) as err:
  1886. admin.delete_client_scope(client_scope_id=res)
  1887. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1888. def test_components(admin: KeycloakAdmin, realm: str):
  1889. """Test components.
  1890. :param admin: Keycloak Admin client
  1891. :type admin: KeycloakAdmin
  1892. :param realm: Keycloak realm
  1893. :type realm: str
  1894. """
  1895. admin.realm_name = realm
  1896. # Test get components
  1897. res = admin.get_components()
  1898. assert len(res) == 12
  1899. with pytest.raises(KeycloakGetError) as err:
  1900. admin.get_component(component_id="does-not-exist")
  1901. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1902. res_get = admin.get_component(component_id=res[0]["id"])
  1903. assert res_get == res[0]
  1904. # Test create component
  1905. with pytest.raises(KeycloakPostError) as err:
  1906. admin.create_component(payload={"bad": "dict"})
  1907. assert err.match('400: b\'{"error":"Unrecognized field')
  1908. res = admin.create_component(
  1909. payload={
  1910. "name": "Test Component",
  1911. "providerId": "max-clients",
  1912. "providerType": "org.keycloak.services.clientregistration."
  1913. + "policy.ClientRegistrationPolicy",
  1914. "config": {"max-clients": ["1000"]},
  1915. }
  1916. )
  1917. assert res
  1918. assert admin.get_component(component_id=res)["name"] == "Test Component"
  1919. # Test update component
  1920. component = admin.get_component(component_id=res)
  1921. component["name"] = "Test Component Update"
  1922. with pytest.raises(KeycloakPutError) as err:
  1923. admin.update_component(component_id="does-not-exist", payload=dict())
  1924. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1925. res_upd = admin.update_component(component_id=res, payload=component)
  1926. assert res_upd == dict()
  1927. assert admin.get_component(component_id=res)["name"] == "Test Component Update"
  1928. # Test delete component
  1929. res_del = admin.delete_component(component_id=res)
  1930. assert res_del == dict()
  1931. with pytest.raises(KeycloakDeleteError) as err:
  1932. admin.delete_component(component_id=res)
  1933. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1934. def test_keys(admin: KeycloakAdmin, realm: str):
  1935. """Test keys.
  1936. :param admin: Keycloak Admin client
  1937. :type admin: KeycloakAdmin
  1938. :param realm: Keycloak realm
  1939. :type realm: str
  1940. """
  1941. admin.realm_name = realm
  1942. assert set(admin.get_keys()["active"].keys()) == {"AES", "HS256", "RS256", "RSA-OAEP"}
  1943. assert {k["algorithm"] for k in admin.get_keys()["keys"]} == {
  1944. "HS256",
  1945. "RSA-OAEP",
  1946. "AES",
  1947. "RS256",
  1948. }
  1949. def test_events(admin: KeycloakAdmin, realm: str):
  1950. """Test events.
  1951. :param admin: Keycloak Admin client
  1952. :type admin: KeycloakAdmin
  1953. :param realm: Keycloak realm
  1954. :type realm: str
  1955. """
  1956. admin.realm_name = realm
  1957. events = admin.get_events()
  1958. assert events == list()
  1959. with pytest.raises(KeycloakPutError) as err:
  1960. admin.set_events(payload={"bad": "conf"})
  1961. assert err.match('400: b\'{"error":"Unrecognized field')
  1962. res = admin.set_events(payload={"adminEventsDetailsEnabled": True, "adminEventsEnabled": True})
  1963. assert res == dict()
  1964. admin.create_client(payload={"name": "test", "clientId": "test"})
  1965. events = admin.get_events()
  1966. assert events == list()
  1967. @freezegun.freeze_time("2023-02-25 10:00:00")
  1968. def test_auto_refresh(admin_frozen: KeycloakAdmin, realm: str):
  1969. """Test auto refresh token.
  1970. :param admin_frozen: Keycloak Admin client with time frozen in place
  1971. :type admin_frozen: KeycloakAdmin
  1972. :param realm: Keycloak realm
  1973. :type realm: str
  1974. """
  1975. admin = admin_frozen
  1976. # Test get refresh
  1977. admin.connection.custom_headers = {
  1978. "Authorization": "Bearer bad",
  1979. "Content-Type": "application/json",
  1980. }
  1981. with pytest.raises(KeycloakAuthenticationError) as err:
  1982. admin.get_realm(realm_name=realm)
  1983. assert err.match('401: b\'{"error":"HTTP 401 Unauthorized"}\'')
  1984. # Freeze time to simulate the access token expiring
  1985. with freezegun.freeze_time("2023-02-25 10:05:00"):
  1986. assert admin.connection.expires_at < datetime_parser.parse("2023-02-25 10:05:00")
  1987. assert admin.get_realm(realm_name=realm)
  1988. assert admin.connection.expires_at > datetime_parser.parse("2023-02-25 10:05:00")
  1989. # Test bad refresh token, but first make sure access token has expired again
  1990. with freezegun.freeze_time("2023-02-25 10:10:00"):
  1991. admin.connection.custom_headers = {"Content-Type": "application/json"}
  1992. admin.connection.token["refresh_token"] = "bad"
  1993. with pytest.raises(KeycloakPostError) as err:
  1994. admin.get_realm(realm_name="test-refresh")
  1995. assert err.match(
  1996. '400: b\'{"error":"invalid_grant","error_description":"Invalid refresh token"}\''
  1997. )
  1998. admin.connection.get_token()
  1999. # Test post refresh
  2000. with freezegun.freeze_time("2023-02-25 10:15:00"):
  2001. assert admin.connection.expires_at < datetime_parser.parse("2023-02-25 10:15:00")
  2002. admin.connection.token = None
  2003. assert admin.create_realm(payload={"realm": "test-refresh"}) == b""
  2004. assert admin.connection.expires_at > datetime_parser.parse("2023-02-25 10:15:00")
  2005. # Test update refresh
  2006. with freezegun.freeze_time("2023-02-25 10:25:00"):
  2007. assert admin.connection.expires_at < datetime_parser.parse("2023-02-25 10:25:00")
  2008. admin.connection.token = None
  2009. assert (
  2010. admin.update_realm(realm_name="test-refresh", payload={"accountTheme": "test"})
  2011. == dict()
  2012. )
  2013. assert admin.connection.expires_at > datetime_parser.parse("2023-02-25 10:25:00")
  2014. # Test delete refresh
  2015. with freezegun.freeze_time("2023-02-25 10:35:00"):
  2016. assert admin.connection.expires_at < datetime_parser.parse("2023-02-25 10:35:00")
  2017. admin.connection.token = None
  2018. assert admin.delete_realm(realm_name="test-refresh") == dict()
  2019. assert admin.connection.expires_at > datetime_parser.parse("2023-02-25 10:35:00")
  2020. def test_get_required_actions(admin: KeycloakAdmin, realm: str):
  2021. """Test required actions.
  2022. :param admin: Keycloak Admin client
  2023. :type admin: KeycloakAdmin
  2024. :param realm: Keycloak realm
  2025. :type realm: str
  2026. """
  2027. admin.realm_name = realm
  2028. ractions = admin.get_required_actions()
  2029. assert isinstance(ractions, list)
  2030. for ra in ractions:
  2031. for key in [
  2032. "alias",
  2033. "name",
  2034. "providerId",
  2035. "enabled",
  2036. "defaultAction",
  2037. "priority",
  2038. "config",
  2039. ]:
  2040. assert key in ra
  2041. def test_get_required_action_by_alias(admin: KeycloakAdmin, realm: str):
  2042. """Test get required action by alias.
  2043. :param admin: Keycloak Admin client
  2044. :type admin: KeycloakAdmin
  2045. :param realm: Keycloak realm
  2046. :type realm: str
  2047. """
  2048. admin.realm_name = realm
  2049. ractions = admin.get_required_actions()
  2050. ra = admin.get_required_action_by_alias("UPDATE_PASSWORD")
  2051. assert ra in ractions
  2052. assert ra["alias"] == "UPDATE_PASSWORD"
  2053. assert admin.get_required_action_by_alias("does-not-exist") is None
  2054. def test_update_required_action(admin: KeycloakAdmin, realm: str):
  2055. """Test update required action.
  2056. :param admin: Keycloak Admin client
  2057. :type admin: KeycloakAdmin
  2058. :param realm: Keycloak realm
  2059. :type realm: str
  2060. """
  2061. admin.realm_name = realm
  2062. ra = admin.get_required_action_by_alias("UPDATE_PASSWORD")
  2063. old = copy.deepcopy(ra)
  2064. ra["enabled"] = False
  2065. admin.update_required_action("UPDATE_PASSWORD", ra)
  2066. newra = admin.get_required_action_by_alias("UPDATE_PASSWORD")
  2067. assert old != newra
  2068. assert newra["enabled"] is False
  2069. def test_get_composite_client_roles_of_group(
  2070. admin: KeycloakAdmin, realm: str, client: str, group: str, composite_client_role: str
  2071. ):
  2072. """Test get composite client roles of group.
  2073. :param admin: Keycloak Admin client
  2074. :type admin: KeycloakAdmin
  2075. :param realm: Keycloak realm
  2076. :type realm: str
  2077. :param client: Keycloak client
  2078. :type client: str
  2079. :param group: Keycloak group
  2080. :type group: str
  2081. :param composite_client_role: Composite client role
  2082. :type composite_client_role: str
  2083. """
  2084. admin.realm_name = realm
  2085. role = admin.get_client_role(client, composite_client_role)
  2086. admin.assign_group_client_roles(group_id=group, client_id=client, roles=[role])
  2087. result = admin.get_composite_client_roles_of_group(client, group)
  2088. assert role["id"] in [x["id"] for x in result]
  2089. def test_get_role_client_level_children(
  2090. admin: KeycloakAdmin, realm: str, client: str, composite_client_role: str, client_role: str
  2091. ):
  2092. """Test get children of composite client role.
  2093. :param admin: Keycloak Admin client
  2094. :type admin: KeycloakAdmin
  2095. :param realm: Keycloak realm
  2096. :type realm: str
  2097. :param client: Keycloak client
  2098. :type client: str
  2099. :param composite_client_role: Composite client role
  2100. :type composite_client_role: str
  2101. :param client_role: Client role
  2102. :type client_role: str
  2103. """
  2104. admin.realm_name = realm
  2105. child = admin.get_client_role(client, client_role)
  2106. parent = admin.get_client_role(client, composite_client_role)
  2107. res = admin.get_role_client_level_children(client, parent["id"])
  2108. assert child["id"] in [x["id"] for x in res]
  2109. def test_upload_certificate(admin: KeycloakAdmin, realm: str, client: str, selfsigned_cert: tuple):
  2110. """Test upload certificate.
  2111. :param admin: Keycloak Admin client
  2112. :type admin: KeycloakAdmin
  2113. :param realm: Keycloak realm
  2114. :type realm: str
  2115. :param client: Keycloak client
  2116. :type client: str
  2117. :param selfsigned_cert: Selfsigned certificates
  2118. :type selfsigned_cert: tuple
  2119. """
  2120. admin.realm_name = realm
  2121. cert, _ = selfsigned_cert
  2122. cert = cert.decode("utf-8").strip()
  2123. admin.upload_certificate(client, cert)
  2124. cl = admin.get_client(client)
  2125. assert cl["attributes"]["jwt.credential.certificate"] == "".join(cert.splitlines()[1:-1])
  2126. def test_get_bruteforce_status_for_user(
  2127. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str], realm: str
  2128. ):
  2129. """Test users.
  2130. :param admin: Keycloak Admin client
  2131. :type admin: KeycloakAdmin
  2132. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  2133. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2134. :param realm: Keycloak realm
  2135. :type realm: str
  2136. """
  2137. oid, username, password = oid_with_credentials
  2138. admin.realm_name = realm
  2139. # Turn on bruteforce protection
  2140. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": True})
  2141. res = admin.get_realm(realm_name=realm)
  2142. assert res["bruteForceProtected"] is True
  2143. # Test login user with wrong credentials
  2144. try:
  2145. oid.token(username=username, password="wrongpassword")
  2146. except KeycloakAuthenticationError:
  2147. pass
  2148. user_id = admin.get_user_id(username)
  2149. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2150. assert bruteforce_status["numFailures"] == 1
  2151. # Cleanup
  2152. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": False})
  2153. res = admin.get_realm(realm_name=realm)
  2154. assert res["bruteForceProtected"] is False
  2155. def test_clear_bruteforce_attempts_for_user(
  2156. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str], realm: str
  2157. ):
  2158. """Test users.
  2159. :param admin: Keycloak Admin client
  2160. :type admin: KeycloakAdmin
  2161. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  2162. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2163. :param realm: Keycloak realm
  2164. :type realm: str
  2165. """
  2166. oid, username, password = oid_with_credentials
  2167. admin.realm_name = realm
  2168. # Turn on bruteforce protection
  2169. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": True})
  2170. res = admin.get_realm(realm_name=realm)
  2171. assert res["bruteForceProtected"] is True
  2172. # Test login user with wrong credentials
  2173. try:
  2174. oid.token(username=username, password="wrongpassword")
  2175. except KeycloakAuthenticationError:
  2176. pass
  2177. user_id = admin.get_user_id(username)
  2178. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2179. assert bruteforce_status["numFailures"] == 1
  2180. res = admin.clear_bruteforce_attempts_for_user(user_id)
  2181. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2182. assert bruteforce_status["numFailures"] == 0
  2183. # Cleanup
  2184. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": False})
  2185. res = admin.get_realm(realm_name=realm)
  2186. assert res["bruteForceProtected"] is False
  2187. def test_clear_bruteforce_attempts_for_all_users(
  2188. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str], realm: str
  2189. ):
  2190. """Test users.
  2191. :param admin: Keycloak Admin client
  2192. :type admin: KeycloakAdmin
  2193. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  2194. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2195. :param realm: Keycloak realm
  2196. :type realm: str
  2197. """
  2198. oid, username, password = oid_with_credentials
  2199. admin.realm_name = realm
  2200. # Turn on bruteforce protection
  2201. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": True})
  2202. res = admin.get_realm(realm_name=realm)
  2203. assert res["bruteForceProtected"] is True
  2204. # Test login user with wrong credentials
  2205. try:
  2206. oid.token(username=username, password="wrongpassword")
  2207. except KeycloakAuthenticationError:
  2208. pass
  2209. user_id = admin.get_user_id(username)
  2210. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2211. assert bruteforce_status["numFailures"] == 1
  2212. res = admin.clear_all_bruteforce_attempts()
  2213. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2214. assert bruteforce_status["numFailures"] == 0
  2215. # Cleanup
  2216. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": False})
  2217. res = admin.get_realm(realm_name=realm)
  2218. assert res["bruteForceProtected"] is False
  2219. def test_default_realm_role_present(realm: str, admin: KeycloakAdmin) -> None:
  2220. """Test that the default realm role is present in a brand new realm.
  2221. :param realm: Realm name
  2222. :type realm: str
  2223. :param admin: Keycloak admin
  2224. :type admin: KeycloakAdmin
  2225. """
  2226. admin.realm_name = realm
  2227. assert f"default-roles-{realm}" in [x["name"] for x in admin.get_realm_roles()]
  2228. assert (
  2229. len([x["name"] for x in admin.get_realm_roles() if x["name"] == f"default-roles-{realm}"])
  2230. == 1
  2231. )
  2232. def test_get_default_realm_role_id(realm: str, admin: KeycloakAdmin) -> None:
  2233. """Test getter for the ID of the default realm role.
  2234. :param realm: Realm name
  2235. :type realm: str
  2236. :param admin: Keycloak admin
  2237. :type admin: KeycloakAdmin
  2238. """
  2239. admin.realm_name = realm
  2240. assert (
  2241. admin.get_default_realm_role_id()
  2242. == [x["id"] for x in admin.get_realm_roles() if x["name"] == f"default-roles-{realm}"][0]
  2243. )
  2244. def test_realm_default_roles(admin: KeycloakAdmin, realm: str) -> None:
  2245. """Test getting, adding and deleting default realm roles.
  2246. :param realm: Realm name
  2247. :type realm: str
  2248. :param admin: Keycloak admin
  2249. :type admin: KeycloakAdmin
  2250. """
  2251. admin.realm_name = realm
  2252. # Test listing all default realm roles
  2253. roles = admin.get_realm_default_roles()
  2254. assert len(roles) == 2
  2255. assert {x["name"] for x in roles} == {"offline_access", "uma_authorization"}
  2256. with pytest.raises(KeycloakGetError) as err:
  2257. admin.realm_name = "doesnotexist"
  2258. admin.get_realm_default_roles()
  2259. assert err.match('404: b\'{"error":"Realm not found."}\'')
  2260. admin.realm_name = realm
  2261. # Test removing a default realm role
  2262. res = admin.remove_realm_default_roles(payload=[roles[0]])
  2263. assert res == {}
  2264. assert roles[0] not in admin.get_realm_default_roles()
  2265. assert len(admin.get_realm_default_roles()) == 1
  2266. with pytest.raises(KeycloakDeleteError) as err:
  2267. admin.remove_realm_default_roles(payload=[{"id": "bad id"}])
  2268. assert err.match('404: b\'{"error":"Could not find composite role"}\'')
  2269. # Test adding a default realm role
  2270. res = admin.add_realm_default_roles(payload=[roles[0]])
  2271. assert res == {}
  2272. assert roles[0] in admin.get_realm_default_roles()
  2273. assert len(admin.get_realm_default_roles()) == 2
  2274. with pytest.raises(KeycloakPostError) as err:
  2275. admin.add_realm_default_roles(payload=[{"id": "bad id"}])
  2276. assert err.match('404: b\'{"error":"Could not find composite role"}\'')
  2277. def test_clear_keys_cache(realm: str, admin: KeycloakAdmin) -> None:
  2278. """Test clearing the keys cache.
  2279. :param realm: Realm name
  2280. :type realm: str
  2281. :param admin: Keycloak admin
  2282. :type admin: KeycloakAdmin
  2283. """
  2284. admin.realm_name = realm
  2285. res = admin.clear_keys_cache()
  2286. assert res == {}
  2287. def test_clear_realm_cache(realm: str, admin: KeycloakAdmin) -> None:
  2288. """Test clearing the realm cache.
  2289. :param realm: Realm name
  2290. :type realm: str
  2291. :param admin: Keycloak admin
  2292. :type admin: KeycloakAdmin
  2293. """
  2294. admin.realm_name = realm
  2295. res = admin.clear_realm_cache()
  2296. assert res == {}
  2297. def test_clear_user_cache(realm: str, admin: KeycloakAdmin) -> None:
  2298. """Test clearing the user cache.
  2299. :param realm: Realm name
  2300. :type realm: str
  2301. :param admin: Keycloak admin
  2302. :type admin: KeycloakAdmin
  2303. """
  2304. admin.realm_name = realm
  2305. res = admin.clear_user_cache()
  2306. assert res == {}
  2307. def test_initial_access_token(
  2308. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2309. ) -> None:
  2310. """Test initial access token and client creation.
  2311. :param admin: Keycloak admin
  2312. :type admin: KeycloakAdmin
  2313. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  2314. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2315. """
  2316. res = admin.create_initial_access_token(2, 3)
  2317. assert "token" in res
  2318. assert res["count"] == 2
  2319. assert res["expiration"] == 3
  2320. oid, username, password = oid_with_credentials
  2321. client = str(uuid.uuid4())
  2322. secret = str(uuid.uuid4())
  2323. res = oid.register_client(
  2324. token=res["token"],
  2325. payload={
  2326. "name": "DynamicRegisteredClient",
  2327. "clientId": client,
  2328. "enabled": True,
  2329. "publicClient": False,
  2330. "protocol": "openid-connect",
  2331. "secret": secret,
  2332. "clientAuthenticatorType": "client-secret",
  2333. },
  2334. )
  2335. assert res["clientId"] == client
  2336. new_secret = str(uuid.uuid4())
  2337. res = oid.update_client(res["registrationAccessToken"], client, payload={"secret": new_secret})
  2338. assert res["secret"] == new_secret