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.

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