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.

2810 lines
100 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. # Create permissions on the target client to reference this policy
  1544. admin.create_client_authz_scope_permission(
  1545. payload={
  1546. "id": token_exchange_permission_id,
  1547. "name": "test-permission",
  1548. "type": "scope",
  1549. "logic": "POSITIVE",
  1550. "decisionStrategy": "UNANIMOUS",
  1551. "resources": [token_exchange_resource_id],
  1552. "scopes": [token_exchange_scope_id],
  1553. "policies": [client_policy_id],
  1554. },
  1555. client_id=realm_management_id,
  1556. )
  1557. permission_name = admin.get_client_authz_scope_permission(
  1558. client_id=realm_management_id, scope_id=token_exchange_permission_id
  1559. )["name"]
  1560. assert permission_name == "test-permission"
  1561. with pytest.raises(KeycloakPostError) as err:
  1562. admin.create_client_authz_scope_permission(
  1563. payload={"name": "test-permission", "scopes": [token_exchange_scope_id]},
  1564. client_id="realm_management_id",
  1565. )
  1566. assert err.match('404: b\'{"errorMessage":"Could not find client"}\'')
  1567. def test_email(admin: KeycloakAdmin, user: str):
  1568. """Test email.
  1569. :param admin: Keycloak Admin client
  1570. :type admin: KeycloakAdmin
  1571. :param user: Keycloak user
  1572. :type user: str
  1573. """
  1574. # Emails will fail as we don't have SMTP test setup
  1575. with pytest.raises(KeycloakPutError) as err:
  1576. admin.send_update_account(user_id=user, payload=dict())
  1577. assert err.match('b\'{"error":"unknown_error"}\''), err
  1578. admin.update_user(user_id=user, payload={"enabled": True})
  1579. with pytest.raises(KeycloakPutError) as err:
  1580. admin.send_verify_email(user_id=user)
  1581. assert err.match('500: b\'{"errorMessage":"Failed to send execute actions email"}\'')
  1582. def test_get_sessions(admin: KeycloakAdmin):
  1583. """Test get sessions.
  1584. :param admin: Keycloak Admin client
  1585. :type admin: KeycloakAdmin
  1586. """
  1587. sessions = admin.get_sessions(user_id=admin.get_user_id(username=admin.username))
  1588. assert len(sessions) >= 1
  1589. with pytest.raises(KeycloakGetError) as err:
  1590. admin.get_sessions(user_id="bad")
  1591. assert err.match('404: b\'{"error":"User not found"}\'')
  1592. def test_get_client_installation_provider(admin: KeycloakAdmin, client: str):
  1593. """Test get client installation provider.
  1594. :param admin: Keycloak Admin client
  1595. :type admin: KeycloakAdmin
  1596. :param client: Keycloak client
  1597. :type client: str
  1598. """
  1599. with pytest.raises(KeycloakGetError) as err:
  1600. admin.get_client_installation_provider(client_id=client, provider_id="bad")
  1601. assert err.match('404: b\'{"error":"Unknown Provider"}\'')
  1602. installation = admin.get_client_installation_provider(
  1603. client_id=client, provider_id="keycloak-oidc-keycloak-json"
  1604. )
  1605. assert set(installation.keys()) == {
  1606. "auth-server-url",
  1607. "confidential-port",
  1608. "credentials",
  1609. "realm",
  1610. "resource",
  1611. "ssl-required",
  1612. }
  1613. def test_auth_flows(admin: KeycloakAdmin, realm: str):
  1614. """Test auth flows.
  1615. :param admin: Keycloak Admin client
  1616. :type admin: KeycloakAdmin
  1617. :param realm: Keycloak realm
  1618. :type realm: str
  1619. """
  1620. admin.realm_name = realm
  1621. res = admin.get_authentication_flows()
  1622. default_flows = len(res)
  1623. assert {x["alias"] for x in res}.issubset(
  1624. {
  1625. "reset credentials",
  1626. "browser",
  1627. "registration",
  1628. "http challenge",
  1629. "docker auth",
  1630. "direct grant",
  1631. "first broker login",
  1632. "clients",
  1633. }
  1634. )
  1635. assert set(res[0].keys()) == {
  1636. "alias",
  1637. "authenticationExecutions",
  1638. "builtIn",
  1639. "description",
  1640. "id",
  1641. "providerId",
  1642. "topLevel",
  1643. }
  1644. with pytest.raises(KeycloakGetError) as err:
  1645. admin.get_authentication_flow_for_id(flow_id="bad")
  1646. assert err.match('404: b\'{"error":"Could not find flow with id"}\'')
  1647. browser_flow_id = [x for x in res if x["alias"] == "browser"][0]["id"]
  1648. res = admin.get_authentication_flow_for_id(flow_id=browser_flow_id)
  1649. assert res["alias"] == "browser"
  1650. # Test copying
  1651. with pytest.raises(KeycloakPostError) as err:
  1652. admin.copy_authentication_flow(payload=dict(), flow_alias="bad")
  1653. assert err.match("404: b''")
  1654. res = admin.copy_authentication_flow(payload={"newName": "test-browser"}, flow_alias="browser")
  1655. assert res == b"", res
  1656. assert len(admin.get_authentication_flows()) == (default_flows + 1)
  1657. # Test create
  1658. res = admin.create_authentication_flow(
  1659. payload={"alias": "test-create", "providerId": "basic-flow"}
  1660. )
  1661. assert res == b""
  1662. with pytest.raises(KeycloakPostError) as err:
  1663. admin.create_authentication_flow(payload={"alias": "test-create", "builtIn": False})
  1664. assert err.match('409: b\'{"errorMessage":"Flow test-create already exists"}\'')
  1665. assert admin.create_authentication_flow(
  1666. payload={"alias": "test-create"}, skip_exists=True
  1667. ) == {"msg": "Already exists"}
  1668. # Test flow executions
  1669. res = admin.get_authentication_flow_executions(flow_alias="browser")
  1670. assert len(res) == 8, res
  1671. with pytest.raises(KeycloakGetError) as err:
  1672. admin.get_authentication_flow_executions(flow_alias="bad")
  1673. assert err.match("404: b''")
  1674. exec_id = res[0]["id"]
  1675. res = admin.get_authentication_flow_execution(execution_id=exec_id)
  1676. assert set(res.keys()) == {
  1677. "alternative",
  1678. "authenticator",
  1679. "authenticatorFlow",
  1680. "conditional",
  1681. "disabled",
  1682. "enabled",
  1683. "id",
  1684. "parentFlow",
  1685. "priority",
  1686. "required",
  1687. "requirement",
  1688. }, res
  1689. with pytest.raises(KeycloakGetError) as err:
  1690. admin.get_authentication_flow_execution(execution_id="bad")
  1691. assert err.match('404: b\'{"error":"Illegal execution"}\'')
  1692. with pytest.raises(KeycloakPostError) as err:
  1693. admin.create_authentication_flow_execution(payload=dict(), flow_alias="browser")
  1694. assert err.match('400: b\'{"error":"It is illegal to add execution to a built in flow"}\'')
  1695. res = admin.create_authentication_flow_execution(
  1696. payload={"provider": "auth-cookie"}, flow_alias="test-create"
  1697. )
  1698. assert res == b""
  1699. assert len(admin.get_authentication_flow_executions(flow_alias="test-create")) == 1
  1700. with pytest.raises(KeycloakPutError) as err:
  1701. admin.update_authentication_flow_executions(
  1702. payload={"required": "yes"}, flow_alias="test-create"
  1703. )
  1704. assert err.match('400: b\'{"error":"Unrecognized field')
  1705. payload = admin.get_authentication_flow_executions(flow_alias="test-create")[0]
  1706. payload["displayName"] = "test"
  1707. res = admin.update_authentication_flow_executions(payload=payload, flow_alias="test-create")
  1708. assert res
  1709. exec_id = admin.get_authentication_flow_executions(flow_alias="test-create")[0]["id"]
  1710. res = admin.delete_authentication_flow_execution(execution_id=exec_id)
  1711. assert res == dict()
  1712. with pytest.raises(KeycloakDeleteError) as err:
  1713. admin.delete_authentication_flow_execution(execution_id=exec_id)
  1714. assert err.match('404: b\'{"error":"Illegal execution"}\'')
  1715. # Test subflows
  1716. res = admin.create_authentication_flow_subflow(
  1717. payload={
  1718. "alias": "test-subflow",
  1719. "provider": "basic-flow",
  1720. "type": "something",
  1721. "description": "something",
  1722. },
  1723. flow_alias="test-browser",
  1724. )
  1725. assert res == b""
  1726. with pytest.raises(KeycloakPostError) as err:
  1727. admin.create_authentication_flow_subflow(
  1728. payload={"alias": "test-subflow", "providerId": "basic-flow"},
  1729. flow_alias="test-browser",
  1730. )
  1731. assert err.match('409: b\'{"errorMessage":"New flow alias name already exists"}\'')
  1732. res = admin.create_authentication_flow_subflow(
  1733. payload={
  1734. "alias": "test-subflow",
  1735. "provider": "basic-flow",
  1736. "type": "something",
  1737. "description": "something",
  1738. },
  1739. flow_alias="test-create",
  1740. skip_exists=True,
  1741. )
  1742. assert res == {"msg": "Already exists"}
  1743. # Test delete auth flow
  1744. flow_id = [x for x in admin.get_authentication_flows() if x["alias"] == "test-browser"][0][
  1745. "id"
  1746. ]
  1747. res = admin.delete_authentication_flow(flow_id=flow_id)
  1748. assert res == dict()
  1749. with pytest.raises(KeycloakDeleteError) as err:
  1750. admin.delete_authentication_flow(flow_id=flow_id)
  1751. assert err.match('404: b\'{"error":"Could not find flow with id"}\'')
  1752. def test_authentication_configs(admin: KeycloakAdmin, realm: str):
  1753. """Test authentication configs.
  1754. :param admin: Keycloak Admin client
  1755. :type admin: KeycloakAdmin
  1756. :param realm: Keycloak realm
  1757. :type realm: str
  1758. """
  1759. admin.realm_name = realm
  1760. # Test list of auth providers
  1761. res = admin.get_authenticator_providers()
  1762. assert len(res) > 1
  1763. res = admin.get_authenticator_provider_config_description(provider_id="auth-cookie")
  1764. assert res == {
  1765. "helpText": "Validates the SSO cookie set by the auth server.",
  1766. "name": "Cookie",
  1767. "properties": [],
  1768. "providerId": "auth-cookie",
  1769. }
  1770. # Test authenticator config
  1771. # Currently unable to find a sustainable way to fetch the config id,
  1772. # therefore testing only failures
  1773. with pytest.raises(KeycloakGetError) as err:
  1774. admin.get_authenticator_config(config_id="bad")
  1775. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1776. with pytest.raises(KeycloakPutError) as err:
  1777. admin.update_authenticator_config(payload=dict(), config_id="bad")
  1778. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1779. with pytest.raises(KeycloakDeleteError) as err:
  1780. admin.delete_authenticator_config(config_id="bad")
  1781. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1782. def test_sync_users(admin: KeycloakAdmin, realm: str):
  1783. """Test sync users.
  1784. :param admin: Keycloak Admin client
  1785. :type admin: KeycloakAdmin
  1786. :param realm: Keycloak realm
  1787. :type realm: str
  1788. """
  1789. admin.realm_name = realm
  1790. # Only testing the error message
  1791. with pytest.raises(KeycloakPostError) as err:
  1792. admin.sync_users(storage_id="does-not-exist", action="triggerFullSync")
  1793. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1794. def test_client_scopes(admin: KeycloakAdmin, realm: str):
  1795. """Test client scopes.
  1796. :param admin: Keycloak Admin client
  1797. :type admin: KeycloakAdmin
  1798. :param realm: Keycloak realm
  1799. :type realm: str
  1800. """
  1801. admin.realm_name = realm
  1802. # Test get client scopes
  1803. res = admin.get_client_scopes()
  1804. scope_names = {x["name"] for x in res}
  1805. assert len(res) == 10
  1806. assert "email" in scope_names
  1807. assert "profile" in scope_names
  1808. assert "offline_access" in scope_names
  1809. with pytest.raises(KeycloakGetError) as err:
  1810. admin.get_client_scope(client_scope_id="does-not-exist")
  1811. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1812. scope = admin.get_client_scope(client_scope_id=res[0]["id"])
  1813. assert res[0] == scope
  1814. scope = admin.get_client_scope_by_name(client_scope_name=res[0]["name"])
  1815. assert res[0] == scope
  1816. # Test create client scope
  1817. res = admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=True)
  1818. assert res
  1819. res2 = admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=True)
  1820. assert res == res2
  1821. with pytest.raises(KeycloakPostError) as err:
  1822. admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=False)
  1823. assert err.match('409: b\'{"errorMessage":"Client Scope test-scope already exists"}\'')
  1824. # Test update client scope
  1825. with pytest.raises(KeycloakPutError) as err:
  1826. admin.update_client_scope(client_scope_id="does-not-exist", payload=dict())
  1827. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1828. res_update = admin.update_client_scope(
  1829. client_scope_id=res, payload={"name": "test-scope-update"}
  1830. )
  1831. assert res_update == dict()
  1832. admin.get_client_scope(client_scope_id=res)["name"] == "test-scope-update"
  1833. # Test get mappers
  1834. mappers = admin.get_mappers_from_client_scope(client_scope_id=res)
  1835. assert mappers == list()
  1836. # Test add mapper
  1837. with pytest.raises(KeycloakPostError) as err:
  1838. admin.add_mapper_to_client_scope(client_scope_id=res, payload=dict())
  1839. assert err.match('404: b\'{"error":"ProtocolMapper provider not found"}\'')
  1840. res_add = admin.add_mapper_to_client_scope(
  1841. client_scope_id=res,
  1842. payload={
  1843. "name": "test-mapper",
  1844. "protocol": "openid-connect",
  1845. "protocolMapper": "oidc-usermodel-attribute-mapper",
  1846. },
  1847. )
  1848. assert res_add == b""
  1849. assert len(admin.get_mappers_from_client_scope(client_scope_id=res)) == 1
  1850. # Test update mapper
  1851. test_mapper = admin.get_mappers_from_client_scope(client_scope_id=res)[0]
  1852. with pytest.raises(KeycloakPutError) as err:
  1853. admin.update_mapper_in_client_scope(
  1854. client_scope_id="does-not-exist", protocol_mapper_id=test_mapper["id"], payload=dict()
  1855. )
  1856. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1857. test_mapper["config"]["user.attribute"] = "test"
  1858. res_update = admin.update_mapper_in_client_scope(
  1859. client_scope_id=res, protocol_mapper_id=test_mapper["id"], payload=test_mapper
  1860. )
  1861. assert res_update == dict()
  1862. assert (
  1863. admin.get_mappers_from_client_scope(client_scope_id=res)[0]["config"]["user.attribute"]
  1864. == "test"
  1865. )
  1866. # Test delete mapper
  1867. res_del = admin.delete_mapper_from_client_scope(
  1868. client_scope_id=res, protocol_mapper_id=test_mapper["id"]
  1869. )
  1870. assert res_del == dict()
  1871. with pytest.raises(KeycloakDeleteError) as err:
  1872. admin.delete_mapper_from_client_scope(
  1873. client_scope_id=res, protocol_mapper_id=test_mapper["id"]
  1874. )
  1875. assert err.match('404: b\'{"error":"Model not found"}\'')
  1876. # Test default default scopes
  1877. res_defaults = admin.get_default_default_client_scopes()
  1878. assert len(res_defaults) == 6
  1879. with pytest.raises(KeycloakPutError) as err:
  1880. admin.add_default_default_client_scope(scope_id="does-not-exist")
  1881. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1882. res_add = admin.add_default_default_client_scope(scope_id=res)
  1883. assert res_add == dict()
  1884. assert len(admin.get_default_default_client_scopes()) == 7
  1885. with pytest.raises(KeycloakDeleteError) as err:
  1886. admin.delete_default_default_client_scope(scope_id="does-not-exist")
  1887. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1888. res_del = admin.delete_default_default_client_scope(scope_id=res)
  1889. assert res_del == dict()
  1890. assert len(admin.get_default_default_client_scopes()) == 6
  1891. # Test default optional scopes
  1892. res_defaults = admin.get_default_optional_client_scopes()
  1893. assert len(res_defaults) == 4
  1894. with pytest.raises(KeycloakPutError) as err:
  1895. admin.add_default_optional_client_scope(scope_id="does-not-exist")
  1896. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1897. res_add = admin.add_default_optional_client_scope(scope_id=res)
  1898. assert res_add == dict()
  1899. assert len(admin.get_default_optional_client_scopes()) == 5
  1900. with pytest.raises(KeycloakDeleteError) as err:
  1901. admin.delete_default_optional_client_scope(scope_id="does-not-exist")
  1902. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1903. res_del = admin.delete_default_optional_client_scope(scope_id=res)
  1904. assert res_del == dict()
  1905. assert len(admin.get_default_optional_client_scopes()) == 4
  1906. # Test client scope delete
  1907. res_del = admin.delete_client_scope(client_scope_id=res)
  1908. assert res_del == dict()
  1909. with pytest.raises(KeycloakDeleteError) as err:
  1910. admin.delete_client_scope(client_scope_id=res)
  1911. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1912. def test_components(admin: KeycloakAdmin, realm: str):
  1913. """Test components.
  1914. :param admin: Keycloak Admin client
  1915. :type admin: KeycloakAdmin
  1916. :param realm: Keycloak realm
  1917. :type realm: str
  1918. """
  1919. admin.realm_name = realm
  1920. # Test get components
  1921. res = admin.get_components()
  1922. assert len(res) == 12
  1923. with pytest.raises(KeycloakGetError) as err:
  1924. admin.get_component(component_id="does-not-exist")
  1925. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1926. res_get = admin.get_component(component_id=res[0]["id"])
  1927. assert res_get == res[0]
  1928. # Test create component
  1929. with pytest.raises(KeycloakPostError) as err:
  1930. admin.create_component(payload={"bad": "dict"})
  1931. assert err.match('400: b\'{"error":"Unrecognized field')
  1932. res = admin.create_component(
  1933. payload={
  1934. "name": "Test Component",
  1935. "providerId": "max-clients",
  1936. "providerType": "org.keycloak.services.clientregistration."
  1937. + "policy.ClientRegistrationPolicy",
  1938. "config": {"max-clients": ["1000"]},
  1939. }
  1940. )
  1941. assert res
  1942. assert admin.get_component(component_id=res)["name"] == "Test Component"
  1943. # Test update component
  1944. component = admin.get_component(component_id=res)
  1945. component["name"] = "Test Component Update"
  1946. with pytest.raises(KeycloakPutError) as err:
  1947. admin.update_component(component_id="does-not-exist", payload=dict())
  1948. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1949. res_upd = admin.update_component(component_id=res, payload=component)
  1950. assert res_upd == dict()
  1951. assert admin.get_component(component_id=res)["name"] == "Test Component Update"
  1952. # Test delete component
  1953. res_del = admin.delete_component(component_id=res)
  1954. assert res_del == dict()
  1955. with pytest.raises(KeycloakDeleteError) as err:
  1956. admin.delete_component(component_id=res)
  1957. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1958. def test_keys(admin: KeycloakAdmin, realm: str):
  1959. """Test keys.
  1960. :param admin: Keycloak Admin client
  1961. :type admin: KeycloakAdmin
  1962. :param realm: Keycloak realm
  1963. :type realm: str
  1964. """
  1965. admin.realm_name = realm
  1966. assert set(admin.get_keys()["active"].keys()) == {"AES", "HS256", "RS256", "RSA-OAEP"}
  1967. assert {k["algorithm"] for k in admin.get_keys()["keys"]} == {
  1968. "HS256",
  1969. "RSA-OAEP",
  1970. "AES",
  1971. "RS256",
  1972. }
  1973. def test_events(admin: KeycloakAdmin, realm: str):
  1974. """Test events.
  1975. :param admin: Keycloak Admin client
  1976. :type admin: KeycloakAdmin
  1977. :param realm: Keycloak realm
  1978. :type realm: str
  1979. """
  1980. admin.realm_name = realm
  1981. events = admin.get_events()
  1982. assert events == list()
  1983. with pytest.raises(KeycloakPutError) as err:
  1984. admin.set_events(payload={"bad": "conf"})
  1985. assert err.match('400: b\'{"error":"Unrecognized field')
  1986. res = admin.set_events(payload={"adminEventsDetailsEnabled": True, "adminEventsEnabled": True})
  1987. assert res == dict()
  1988. admin.create_client(payload={"name": "test", "clientId": "test"})
  1989. events = admin.get_events()
  1990. assert events == list()
  1991. @freezegun.freeze_time("2023-02-25 10:00:00")
  1992. def test_auto_refresh(admin_frozen: KeycloakAdmin, realm: str):
  1993. """Test auto refresh token.
  1994. :param admin_frozen: Keycloak Admin client with time frozen in place
  1995. :type admin_frozen: KeycloakAdmin
  1996. :param realm: Keycloak realm
  1997. :type realm: str
  1998. """
  1999. admin = admin_frozen
  2000. # Test get refresh
  2001. admin.connection.custom_headers = {
  2002. "Authorization": "Bearer bad",
  2003. "Content-Type": "application/json",
  2004. }
  2005. with pytest.raises(KeycloakAuthenticationError) as err:
  2006. admin.get_realm(realm_name=realm)
  2007. assert err.match('401: b\'{"error":"HTTP 401 Unauthorized"}\'')
  2008. # Freeze time to simulate the access token expiring
  2009. with freezegun.freeze_time("2023-02-25 10:05:00"):
  2010. assert admin.connection.expires_at < datetime_parser.parse("2023-02-25 10:05:00")
  2011. assert admin.get_realm(realm_name=realm)
  2012. assert admin.connection.expires_at > datetime_parser.parse("2023-02-25 10:05:00")
  2013. # Test bad refresh token, but first make sure access token has expired again
  2014. with freezegun.freeze_time("2023-02-25 10:10:00"):
  2015. admin.connection.custom_headers = {"Content-Type": "application/json"}
  2016. admin.connection.token["refresh_token"] = "bad"
  2017. with pytest.raises(KeycloakPostError) as err:
  2018. admin.get_realm(realm_name="test-refresh")
  2019. assert err.match(
  2020. '400: b\'{"error":"invalid_grant","error_description":"Invalid refresh token"}\''
  2021. )
  2022. admin.connection.get_token()
  2023. # Test post refresh
  2024. with freezegun.freeze_time("2023-02-25 10:15:00"):
  2025. assert admin.connection.expires_at < datetime_parser.parse("2023-02-25 10:15:00")
  2026. admin.connection.token = None
  2027. assert admin.create_realm(payload={"realm": "test-refresh"}) == b""
  2028. assert admin.connection.expires_at > datetime_parser.parse("2023-02-25 10:15:00")
  2029. # Test update refresh
  2030. with freezegun.freeze_time("2023-02-25 10:25:00"):
  2031. assert admin.connection.expires_at < datetime_parser.parse("2023-02-25 10:25:00")
  2032. admin.connection.token = None
  2033. assert (
  2034. admin.update_realm(realm_name="test-refresh", payload={"accountTheme": "test"})
  2035. == dict()
  2036. )
  2037. assert admin.connection.expires_at > datetime_parser.parse("2023-02-25 10:25:00")
  2038. # Test delete refresh
  2039. with freezegun.freeze_time("2023-02-25 10:35:00"):
  2040. assert admin.connection.expires_at < datetime_parser.parse("2023-02-25 10:35:00")
  2041. admin.connection.token = None
  2042. assert admin.delete_realm(realm_name="test-refresh") == dict()
  2043. assert admin.connection.expires_at > datetime_parser.parse("2023-02-25 10:35:00")
  2044. def test_get_required_actions(admin: KeycloakAdmin, realm: str):
  2045. """Test required actions.
  2046. :param admin: Keycloak Admin client
  2047. :type admin: KeycloakAdmin
  2048. :param realm: Keycloak realm
  2049. :type realm: str
  2050. """
  2051. admin.realm_name = realm
  2052. ractions = admin.get_required_actions()
  2053. assert isinstance(ractions, list)
  2054. for ra in ractions:
  2055. for key in [
  2056. "alias",
  2057. "name",
  2058. "providerId",
  2059. "enabled",
  2060. "defaultAction",
  2061. "priority",
  2062. "config",
  2063. ]:
  2064. assert key in ra
  2065. def test_get_required_action_by_alias(admin: KeycloakAdmin, realm: str):
  2066. """Test get required action by alias.
  2067. :param admin: Keycloak Admin client
  2068. :type admin: KeycloakAdmin
  2069. :param realm: Keycloak realm
  2070. :type realm: str
  2071. """
  2072. admin.realm_name = realm
  2073. ractions = admin.get_required_actions()
  2074. ra = admin.get_required_action_by_alias("UPDATE_PASSWORD")
  2075. assert ra in ractions
  2076. assert ra["alias"] == "UPDATE_PASSWORD"
  2077. assert admin.get_required_action_by_alias("does-not-exist") is None
  2078. def test_update_required_action(admin: KeycloakAdmin, realm: str):
  2079. """Test update required action.
  2080. :param admin: Keycloak Admin client
  2081. :type admin: KeycloakAdmin
  2082. :param realm: Keycloak realm
  2083. :type realm: str
  2084. """
  2085. admin.realm_name = realm
  2086. ra = admin.get_required_action_by_alias("UPDATE_PASSWORD")
  2087. old = copy.deepcopy(ra)
  2088. ra["enabled"] = False
  2089. admin.update_required_action("UPDATE_PASSWORD", ra)
  2090. newra = admin.get_required_action_by_alias("UPDATE_PASSWORD")
  2091. assert old != newra
  2092. assert newra["enabled"] is False
  2093. def test_get_composite_client_roles_of_group(
  2094. admin: KeycloakAdmin, realm: str, client: str, group: str, composite_client_role: str
  2095. ):
  2096. """Test get composite client roles of group.
  2097. :param admin: Keycloak Admin client
  2098. :type admin: KeycloakAdmin
  2099. :param realm: Keycloak realm
  2100. :type realm: str
  2101. :param client: Keycloak client
  2102. :type client: str
  2103. :param group: Keycloak group
  2104. :type group: str
  2105. :param composite_client_role: Composite client role
  2106. :type composite_client_role: str
  2107. """
  2108. admin.realm_name = realm
  2109. role = admin.get_client_role(client, composite_client_role)
  2110. admin.assign_group_client_roles(group_id=group, client_id=client, roles=[role])
  2111. result = admin.get_composite_client_roles_of_group(client, group)
  2112. assert role["id"] in [x["id"] for x in result]
  2113. def test_get_role_client_level_children(
  2114. admin: KeycloakAdmin, realm: str, client: str, composite_client_role: str, client_role: str
  2115. ):
  2116. """Test get children of composite client role.
  2117. :param admin: Keycloak Admin client
  2118. :type admin: KeycloakAdmin
  2119. :param realm: Keycloak realm
  2120. :type realm: str
  2121. :param client: Keycloak client
  2122. :type client: str
  2123. :param composite_client_role: Composite client role
  2124. :type composite_client_role: str
  2125. :param client_role: Client role
  2126. :type client_role: str
  2127. """
  2128. admin.realm_name = realm
  2129. child = admin.get_client_role(client, client_role)
  2130. parent = admin.get_client_role(client, composite_client_role)
  2131. res = admin.get_role_client_level_children(client, parent["id"])
  2132. assert child["id"] in [x["id"] for x in res]
  2133. def test_upload_certificate(admin: KeycloakAdmin, realm: str, client: str, selfsigned_cert: tuple):
  2134. """Test upload certificate.
  2135. :param admin: Keycloak Admin client
  2136. :type admin: KeycloakAdmin
  2137. :param realm: Keycloak realm
  2138. :type realm: str
  2139. :param client: Keycloak client
  2140. :type client: str
  2141. :param selfsigned_cert: Selfsigned certificates
  2142. :type selfsigned_cert: tuple
  2143. """
  2144. admin.realm_name = realm
  2145. cert, _ = selfsigned_cert
  2146. cert = cert.decode("utf-8").strip()
  2147. admin.upload_certificate(client, cert)
  2148. cl = admin.get_client(client)
  2149. assert cl["attributes"]["jwt.credential.certificate"] == "".join(cert.splitlines()[1:-1])
  2150. def test_get_bruteforce_status_for_user(
  2151. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str], realm: str
  2152. ):
  2153. """Test users.
  2154. :param admin: Keycloak Admin client
  2155. :type admin: KeycloakAdmin
  2156. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  2157. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2158. :param realm: Keycloak realm
  2159. :type realm: str
  2160. """
  2161. oid, username, password = oid_with_credentials
  2162. admin.realm_name = realm
  2163. # Turn on bruteforce protection
  2164. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": True})
  2165. res = admin.get_realm(realm_name=realm)
  2166. assert res["bruteForceProtected"] is True
  2167. # Test login user with wrong credentials
  2168. try:
  2169. oid.token(username=username, password="wrongpassword")
  2170. except KeycloakAuthenticationError:
  2171. pass
  2172. user_id = admin.get_user_id(username)
  2173. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2174. assert bruteforce_status["numFailures"] == 1
  2175. # Cleanup
  2176. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": False})
  2177. res = admin.get_realm(realm_name=realm)
  2178. assert res["bruteForceProtected"] is False
  2179. def test_clear_bruteforce_attempts_for_user(
  2180. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str], realm: str
  2181. ):
  2182. """Test users.
  2183. :param admin: Keycloak Admin client
  2184. :type admin: KeycloakAdmin
  2185. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  2186. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2187. :param realm: Keycloak realm
  2188. :type realm: str
  2189. """
  2190. oid, username, password = oid_with_credentials
  2191. admin.realm_name = realm
  2192. # Turn on bruteforce protection
  2193. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": True})
  2194. res = admin.get_realm(realm_name=realm)
  2195. assert res["bruteForceProtected"] is True
  2196. # Test login user with wrong credentials
  2197. try:
  2198. oid.token(username=username, password="wrongpassword")
  2199. except KeycloakAuthenticationError:
  2200. pass
  2201. user_id = admin.get_user_id(username)
  2202. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2203. assert bruteforce_status["numFailures"] == 1
  2204. res = admin.clear_bruteforce_attempts_for_user(user_id)
  2205. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2206. assert bruteforce_status["numFailures"] == 0
  2207. # Cleanup
  2208. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": False})
  2209. res = admin.get_realm(realm_name=realm)
  2210. assert res["bruteForceProtected"] is False
  2211. def test_clear_bruteforce_attempts_for_all_users(
  2212. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str], realm: str
  2213. ):
  2214. """Test users.
  2215. :param admin: Keycloak Admin client
  2216. :type admin: KeycloakAdmin
  2217. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  2218. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2219. :param realm: Keycloak realm
  2220. :type realm: str
  2221. """
  2222. oid, username, password = oid_with_credentials
  2223. admin.realm_name = realm
  2224. # Turn on bruteforce protection
  2225. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": True})
  2226. res = admin.get_realm(realm_name=realm)
  2227. assert res["bruteForceProtected"] is True
  2228. # Test login user with wrong credentials
  2229. try:
  2230. oid.token(username=username, password="wrongpassword")
  2231. except KeycloakAuthenticationError:
  2232. pass
  2233. user_id = admin.get_user_id(username)
  2234. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2235. assert bruteforce_status["numFailures"] == 1
  2236. res = admin.clear_all_bruteforce_attempts()
  2237. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2238. assert bruteforce_status["numFailures"] == 0
  2239. # Cleanup
  2240. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": False})
  2241. res = admin.get_realm(realm_name=realm)
  2242. assert res["bruteForceProtected"] is False
  2243. def test_default_realm_role_present(realm: str, admin: KeycloakAdmin) -> None:
  2244. """Test that the default realm role is present in a brand new realm.
  2245. :param realm: Realm name
  2246. :type realm: str
  2247. :param admin: Keycloak admin
  2248. :type admin: KeycloakAdmin
  2249. """
  2250. admin.realm_name = realm
  2251. assert f"default-roles-{realm}" in [x["name"] for x in admin.get_realm_roles()]
  2252. assert (
  2253. len([x["name"] for x in admin.get_realm_roles() if x["name"] == f"default-roles-{realm}"])
  2254. == 1
  2255. )
  2256. def test_get_default_realm_role_id(realm: str, admin: KeycloakAdmin) -> None:
  2257. """Test getter for the ID of the default realm role.
  2258. :param realm: Realm name
  2259. :type realm: str
  2260. :param admin: Keycloak admin
  2261. :type admin: KeycloakAdmin
  2262. """
  2263. admin.realm_name = realm
  2264. assert (
  2265. admin.get_default_realm_role_id()
  2266. == [x["id"] for x in admin.get_realm_roles() if x["name"] == f"default-roles-{realm}"][0]
  2267. )
  2268. def test_realm_default_roles(admin: KeycloakAdmin, realm: str) -> None:
  2269. """Test getting, adding and deleting default realm roles.
  2270. :param realm: Realm name
  2271. :type realm: str
  2272. :param admin: Keycloak admin
  2273. :type admin: KeycloakAdmin
  2274. """
  2275. admin.realm_name = realm
  2276. # Test listing all default realm roles
  2277. roles = admin.get_realm_default_roles()
  2278. assert len(roles) == 2
  2279. assert {x["name"] for x in roles} == {"offline_access", "uma_authorization"}
  2280. with pytest.raises(KeycloakGetError) as err:
  2281. admin.realm_name = "doesnotexist"
  2282. admin.get_realm_default_roles()
  2283. assert err.match('404: b\'{"error":"Realm not found."}\'')
  2284. admin.realm_name = realm
  2285. # Test removing a default realm role
  2286. res = admin.remove_realm_default_roles(payload=[roles[0]])
  2287. assert res == {}
  2288. assert roles[0] not in admin.get_realm_default_roles()
  2289. assert len(admin.get_realm_default_roles()) == 1
  2290. with pytest.raises(KeycloakDeleteError) as err:
  2291. admin.remove_realm_default_roles(payload=[{"id": "bad id"}])
  2292. assert err.match('404: b\'{"error":"Could not find composite role"}\'')
  2293. # Test adding a default realm role
  2294. res = admin.add_realm_default_roles(payload=[roles[0]])
  2295. assert res == {}
  2296. assert roles[0] in admin.get_realm_default_roles()
  2297. assert len(admin.get_realm_default_roles()) == 2
  2298. with pytest.raises(KeycloakPostError) as err:
  2299. admin.add_realm_default_roles(payload=[{"id": "bad id"}])
  2300. assert err.match('404: b\'{"error":"Could not find composite role"}\'')
  2301. def test_clear_keys_cache(realm: str, admin: KeycloakAdmin) -> None:
  2302. """Test clearing the keys cache.
  2303. :param realm: Realm name
  2304. :type realm: str
  2305. :param admin: Keycloak admin
  2306. :type admin: KeycloakAdmin
  2307. """
  2308. admin.realm_name = realm
  2309. res = admin.clear_keys_cache()
  2310. assert res == {}
  2311. def test_clear_realm_cache(realm: str, admin: KeycloakAdmin) -> None:
  2312. """Test clearing the realm cache.
  2313. :param realm: Realm name
  2314. :type realm: str
  2315. :param admin: Keycloak admin
  2316. :type admin: KeycloakAdmin
  2317. """
  2318. admin.realm_name = realm
  2319. res = admin.clear_realm_cache()
  2320. assert res == {}
  2321. def test_clear_user_cache(realm: str, admin: KeycloakAdmin) -> None:
  2322. """Test clearing the user cache.
  2323. :param realm: Realm name
  2324. :type realm: str
  2325. :param admin: Keycloak admin
  2326. :type admin: KeycloakAdmin
  2327. """
  2328. admin.realm_name = realm
  2329. res = admin.clear_user_cache()
  2330. assert res == {}
  2331. def test_initial_access_token(
  2332. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2333. ) -> None:
  2334. """Test initial access token and client creation.
  2335. :param admin: Keycloak admin
  2336. :type admin: KeycloakAdmin
  2337. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  2338. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2339. """
  2340. res = admin.create_initial_access_token(2, 3)
  2341. assert "token" in res
  2342. assert res["count"] == 2
  2343. assert res["expiration"] == 3
  2344. oid, username, password = oid_with_credentials
  2345. client = str(uuid.uuid4())
  2346. secret = str(uuid.uuid4())
  2347. res = oid.register_client(
  2348. token=res["token"],
  2349. payload={
  2350. "name": "DynamicRegisteredClient",
  2351. "clientId": client,
  2352. "enabled": True,
  2353. "publicClient": False,
  2354. "protocol": "openid-connect",
  2355. "secret": secret,
  2356. "clientAuthenticatorType": "client-secret",
  2357. },
  2358. )
  2359. assert res["clientId"] == client
  2360. new_secret = str(uuid.uuid4())
  2361. res = oid.update_client(res["registrationAccessToken"], client, payload={"secret": new_secret})
  2362. assert res["secret"] == new_secret