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.

2088 lines
74 KiB

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