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.

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