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.

2505 lines
89 KiB

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