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.

2405 lines
85 KiB

  1. """Test the keycloak admin object."""
  2. import copy
  3. from typing import Tuple
  4. import pytest
  5. import keycloak
  6. from keycloak import KeycloakAdmin, KeycloakOpenID
  7. from keycloak.connection import ConnectionManager
  8. from keycloak.exceptions import (
  9. KeycloakAuthenticationError,
  10. KeycloakDeleteError,
  11. KeycloakGetError,
  12. KeycloakPostError,
  13. KeycloakPutError,
  14. )
  15. def test_keycloak_version():
  16. """Test version."""
  17. assert keycloak.__version__, keycloak.__version__
  18. def test_keycloak_admin_bad_init(env):
  19. """Test keycloak admin bad init.
  20. :param env: Environment fixture
  21. :type env: KeycloakTestEnv
  22. """
  23. with pytest.raises(TypeError) as err:
  24. KeycloakAdmin(
  25. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  26. username=env.KEYCLOAK_ADMIN,
  27. password=env.KEYCLOAK_ADMIN_PASSWORD,
  28. auto_refresh_token=1,
  29. )
  30. assert err.match("Expected a list of strings")
  31. with pytest.raises(TypeError) as err:
  32. KeycloakAdmin(
  33. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  34. username=env.KEYCLOAK_ADMIN,
  35. password=env.KEYCLOAK_ADMIN_PASSWORD,
  36. auto_refresh_token=["patch"],
  37. )
  38. assert err.match("Unexpected method in auto_refresh_token")
  39. def test_keycloak_admin_init(env):
  40. """Test keycloak admin init.
  41. :param env: Environment fixture
  42. :type env: KeycloakTestEnv
  43. """
  44. admin = KeycloakAdmin(
  45. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  46. username=env.KEYCLOAK_ADMIN,
  47. password=env.KEYCLOAK_ADMIN_PASSWORD,
  48. )
  49. assert admin.server_url == f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}", admin.server_url
  50. assert admin.realm_name == "master", admin.realm_name
  51. assert isinstance(admin.connection, ConnectionManager), type(admin.connection)
  52. assert admin.client_id == "admin-cli", admin.client_id
  53. assert admin.client_secret_key is None, admin.client_secret_key
  54. assert admin.verify, admin.verify
  55. assert admin.username == env.KEYCLOAK_ADMIN, admin.username
  56. assert admin.password == env.KEYCLOAK_ADMIN_PASSWORD, admin.password
  57. assert admin.totp is None, admin.totp
  58. assert admin.token is not None, admin.token
  59. assert admin.auto_refresh_token == list(), admin.auto_refresh_token
  60. assert admin.user_realm_name is None, admin.user_realm_name
  61. assert admin.custom_headers is None, admin.custom_headers
  62. assert admin.token
  63. admin = KeycloakAdmin(
  64. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  65. username=env.KEYCLOAK_ADMIN,
  66. password=env.KEYCLOAK_ADMIN_PASSWORD,
  67. realm_name=None,
  68. user_realm_name="master",
  69. )
  70. assert admin.token
  71. admin = KeycloakAdmin(
  72. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  73. username=env.KEYCLOAK_ADMIN,
  74. password=env.KEYCLOAK_ADMIN_PASSWORD,
  75. realm_name=None,
  76. user_realm_name=None,
  77. )
  78. assert admin.token
  79. admin.create_realm(payload={"realm": "authz", "enabled": True})
  80. admin.realm_name = "authz"
  81. admin.create_client(
  82. payload={
  83. "name": "authz-client",
  84. "clientId": "authz-client",
  85. "authorizationServicesEnabled": True,
  86. "serviceAccountsEnabled": True,
  87. "clientAuthenticatorType": "client-secret",
  88. "directAccessGrantsEnabled": False,
  89. "enabled": True,
  90. "implicitFlowEnabled": False,
  91. "publicClient": False,
  92. }
  93. )
  94. secret = admin.generate_client_secrets(client_id=admin.get_client_id("authz-client"))
  95. assert KeycloakAdmin(
  96. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  97. user_realm_name="authz",
  98. client_id="authz-client",
  99. client_secret_key=secret["value"],
  100. ).token
  101. admin.delete_realm(realm_name="authz")
  102. assert (
  103. KeycloakAdmin(
  104. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  105. username=None,
  106. password=None,
  107. client_secret_key=None,
  108. custom_headers={"custom": "header"},
  109. ).token
  110. is None
  111. )
  112. def test_realms(admin: KeycloakAdmin):
  113. """Test realms.
  114. :param admin: Keycloak Admin client
  115. :type admin: KeycloakAdmin
  116. """
  117. # Get realms
  118. realms = admin.get_realms()
  119. assert len(realms) == 1, realms
  120. assert "master" == realms[0]["realm"]
  121. # Create a test realm
  122. res = admin.create_realm(payload={"realm": "test"})
  123. assert res == b"", res
  124. # Create the same realm, should fail
  125. with pytest.raises(KeycloakPostError) as err:
  126. res = admin.create_realm(payload={"realm": "test"})
  127. assert err.match('409: b\'{"errorMessage":"Conflict detected. See logs for details"}\'')
  128. # Create the same realm, skip_exists true
  129. res = admin.create_realm(payload={"realm": "test"}, skip_exists=True)
  130. assert res == {"msg": "Already exists"}, res
  131. # Get a single realm
  132. res = admin.get_realm(realm_name="test")
  133. assert res["realm"] == "test"
  134. # Get non-existing realm
  135. with pytest.raises(KeycloakGetError) as err:
  136. admin.get_realm(realm_name="non-existent")
  137. assert err.match('404: b\'{"error":"Realm not found."}\'')
  138. # Update realm
  139. res = admin.update_realm(realm_name="test", payload={"accountTheme": "test"})
  140. assert res == dict(), res
  141. # Check that the update worked
  142. res = admin.get_realm(realm_name="test")
  143. assert res["realm"] == "test"
  144. assert res["accountTheme"] == "test"
  145. # Update wrong payload
  146. with pytest.raises(KeycloakPutError) as err:
  147. admin.update_realm(realm_name="test", payload={"wrong": "payload"})
  148. assert err.match('400: b\'{"error":"Unrecognized field')
  149. # Check that get realms returns both realms
  150. realms = admin.get_realms()
  151. realm_names = [x["realm"] for x in realms]
  152. assert len(realms) == 2, realms
  153. assert "master" in realm_names, realm_names
  154. assert "test" in realm_names, realm_names
  155. # Delete the realm
  156. res = admin.delete_realm(realm_name="test")
  157. assert res == dict(), res
  158. # Check that the realm does not exist anymore
  159. with pytest.raises(KeycloakGetError) as err:
  160. admin.get_realm(realm_name="test")
  161. assert err.match('404: b\'{"error":"Realm not found."}\'')
  162. # Delete non-existing realm
  163. with pytest.raises(KeycloakDeleteError) as err:
  164. admin.delete_realm(realm_name="non-existent")
  165. assert err.match('404: b\'{"error":"Realm not found."}\'')
  166. def test_import_export_realms(admin: KeycloakAdmin, realm: str):
  167. """Test import and export of realms.
  168. :param admin: Keycloak Admin client
  169. :type admin: KeycloakAdmin
  170. :param realm: Keycloak realm
  171. :type realm: str
  172. """
  173. admin.realm_name = realm
  174. realm_export = admin.export_realm(export_clients=True, export_groups_and_role=True)
  175. assert realm_export != dict(), realm_export
  176. admin.delete_realm(realm_name=realm)
  177. admin.realm_name = "master"
  178. res = admin.import_realm(payload=realm_export)
  179. assert res == b"", res
  180. # Test bad import
  181. with pytest.raises(KeycloakPostError) as err:
  182. admin.import_realm(payload=dict())
  183. assert err.match('500: b\'{"error":"unknown_error"}\'')
  184. def test_users(admin: KeycloakAdmin, realm: str):
  185. """Test users.
  186. :param admin: Keycloak Admin client
  187. :type admin: KeycloakAdmin
  188. :param realm: Keycloak realm
  189. :type realm: str
  190. """
  191. admin.realm_name = realm
  192. # Check no users present
  193. users = admin.get_users()
  194. assert users == list(), users
  195. # Test create user
  196. user_id = admin.create_user(payload={"username": "test", "email": "test@test.test"})
  197. assert user_id is not None, user_id
  198. # Test create the same user
  199. with pytest.raises(KeycloakPostError) as err:
  200. admin.create_user(payload={"username": "test", "email": "test@test.test"})
  201. assert err.match('409: b\'{"errorMessage":"User exists with same username"}\'')
  202. # Test create the same user, exists_ok true
  203. user_id_2 = admin.create_user(
  204. payload={"username": "test", "email": "test@test.test"}, exist_ok=True
  205. )
  206. assert user_id == user_id_2
  207. # Test get user
  208. user = admin.get_user(user_id=user_id)
  209. assert user["username"] == "test", user["username"]
  210. assert user["email"] == "test@test.test", user["email"]
  211. # Test update user
  212. res = admin.update_user(user_id=user_id, payload={"firstName": "Test"})
  213. assert res == dict(), res
  214. user = admin.get_user(user_id=user_id)
  215. assert user["firstName"] == "Test"
  216. # Test update user fail
  217. with pytest.raises(KeycloakPutError) as err:
  218. admin.update_user(user_id=user_id, payload={"wrong": "payload"})
  219. assert err.match('400: b\'{"error":"Unrecognized field')
  220. # Test get users again
  221. users = admin.get_users()
  222. usernames = [x["username"] for x in users]
  223. assert "test" in usernames
  224. # Test users counts
  225. count = admin.users_count()
  226. assert count == 1, count
  227. # Test users count with query
  228. count = admin.users_count(query={"username": "notpresent"})
  229. assert count == 0
  230. # Test user groups
  231. groups = admin.get_user_groups(user_id=user["id"])
  232. assert len(groups) == 0
  233. # Test user groups bad id
  234. with pytest.raises(KeycloakGetError) as err:
  235. admin.get_user_groups(user_id="does-not-exist")
  236. assert err.match('404: b\'{"error":"User not found"}\'')
  237. # Test logout
  238. res = admin.user_logout(user_id=user["id"])
  239. assert res == dict(), res
  240. # Test logout fail
  241. with pytest.raises(KeycloakPostError) as err:
  242. admin.user_logout(user_id="non-existent-id")
  243. assert err.match('404: b\'{"error":"User not found"}\'')
  244. # Test consents
  245. res = admin.user_consents(user_id=user["id"])
  246. assert len(res) == 0, res
  247. # Test consents fail
  248. with pytest.raises(KeycloakGetError) as err:
  249. admin.user_consents(user_id="non-existent-id")
  250. assert err.match('404: b\'{"error":"User not found"}\'')
  251. # Test delete user
  252. res = admin.delete_user(user_id=user_id)
  253. assert res == dict(), res
  254. with pytest.raises(KeycloakGetError) as err:
  255. admin.get_user(user_id=user_id)
  256. err.match('404: b\'{"error":"User not found"}\'')
  257. # Test delete fail
  258. with pytest.raises(KeycloakDeleteError) as err:
  259. admin.delete_user(user_id="non-existent-id")
  260. assert err.match('404: b\'{"error":"User not found"}\'')
  261. def test_users_pagination(admin: KeycloakAdmin, realm: str):
  262. """Test user pagination.
  263. :param admin: Keycloak Admin client
  264. :type admin: KeycloakAdmin
  265. :param realm: Keycloak realm
  266. :type realm: str
  267. """
  268. admin.realm_name = realm
  269. for ind in range(admin.PAGE_SIZE + 50):
  270. username = f"user_{ind}"
  271. admin.create_user(payload={"username": username, "email": f"{username}@test.test"})
  272. users = admin.get_users()
  273. assert len(users) == admin.PAGE_SIZE + 50, len(users)
  274. users = admin.get_users(query={"first": 100})
  275. assert len(users) == 50, len(users)
  276. users = admin.get_users(query={"max": 20})
  277. assert len(users) == 20, len(users)
  278. def test_idps(admin: KeycloakAdmin, realm: str):
  279. """Test IDPs.
  280. :param admin: Keycloak Admin client
  281. :type admin: KeycloakAdmin
  282. :param realm: Keycloak realm
  283. :type realm: str
  284. """
  285. admin.realm_name = realm
  286. # Create IDP
  287. res = admin.create_idp(
  288. payload=dict(
  289. providerId="github", alias="github", config=dict(clientId="test", clientSecret="test")
  290. )
  291. )
  292. assert res == b"", res
  293. # Test create idp fail
  294. with pytest.raises(KeycloakPostError) as err:
  295. admin.create_idp(payload={"providerId": "does-not-exist", "alias": "something"})
  296. assert err.match("Invalid identity provider id"), err
  297. # Test listing
  298. idps = admin.get_idps()
  299. assert len(idps) == 1
  300. assert "github" == idps[0]["alias"]
  301. # Test IdP update
  302. res = admin.update_idp(idp_alias="github", payload=idps[0])
  303. assert res == {}, res
  304. # Test adding a mapper
  305. res = admin.add_mapper_to_idp(
  306. idp_alias="github",
  307. payload={
  308. "identityProviderAlias": "github",
  309. "identityProviderMapper": "github-user-attribute-mapper",
  310. "name": "test",
  311. },
  312. )
  313. assert res == b"", res
  314. # Test mapper fail
  315. with pytest.raises(KeycloakPostError) as err:
  316. admin.add_mapper_to_idp(idp_alias="does-no-texist", payload=dict())
  317. assert err.match('404: b\'{"error":"HTTP 404 Not Found"}\'')
  318. # Test IdP mappers listing
  319. idp_mappers = admin.get_idp_mappers(idp_alias="github")
  320. assert len(idp_mappers) == 1
  321. # Test IdP mapper update
  322. res = admin.update_mapper_in_idp(
  323. idp_alias="github",
  324. mapper_id=idp_mappers[0]["id"],
  325. # For an obscure reason, keycloak expect all fields
  326. payload={
  327. "id": idp_mappers[0]["id"],
  328. "identityProviderAlias": "github-alias",
  329. "identityProviderMapper": "github-user-attribute-mapper",
  330. "name": "test",
  331. "config": idp_mappers[0]["config"],
  332. },
  333. )
  334. assert res == dict(), res
  335. # Test delete
  336. res = admin.delete_idp(idp_alias="github")
  337. assert res == dict(), res
  338. # Test delete fail
  339. with pytest.raises(KeycloakDeleteError) as err:
  340. admin.delete_idp(idp_alias="does-not-exist")
  341. assert err.match('404: b\'{"error":"HTTP 404 Not Found"}\'')
  342. def test_user_credentials(admin: KeycloakAdmin, user: str):
  343. """Test user credentials.
  344. :param admin: Keycloak Admin client
  345. :type admin: KeycloakAdmin
  346. :param user: Keycloak user
  347. :type user: str
  348. """
  349. res = admin.set_user_password(user_id=user, password="booya", temporary=True)
  350. assert res == dict(), res
  351. # Test user password set fail
  352. with pytest.raises(KeycloakPutError) as err:
  353. admin.set_user_password(user_id="does-not-exist", password="")
  354. assert err.match('404: b\'{"error":"User not found"}\'')
  355. credentials = admin.get_credentials(user_id=user)
  356. assert len(credentials) == 1
  357. assert credentials[0]["type"] == "password", credentials
  358. # Test get credentials fail
  359. with pytest.raises(KeycloakGetError) as err:
  360. admin.get_credentials(user_id="does-not-exist")
  361. assert err.match('404: b\'{"error":"User not found"}\'')
  362. res = admin.delete_credential(user_id=user, credential_id=credentials[0]["id"])
  363. assert res == dict(), res
  364. # Test delete fail
  365. with pytest.raises(KeycloakDeleteError) as err:
  366. admin.delete_credential(user_id=user, credential_id="does-not-exist")
  367. assert err.match('404: b\'{"error":"Credential not found"}\'')
  368. def test_social_logins(admin: KeycloakAdmin, user: str):
  369. """Test social logins.
  370. :param admin: Keycloak Admin client
  371. :type admin: KeycloakAdmin
  372. :param user: Keycloak user
  373. :type user: str
  374. """
  375. res = admin.add_user_social_login(
  376. user_id=user, provider_id="gitlab", provider_userid="test", provider_username="test"
  377. )
  378. assert res == dict(), res
  379. admin.add_user_social_login(
  380. user_id=user, provider_id="github", provider_userid="test", provider_username="test"
  381. )
  382. assert res == dict(), res
  383. # Test add social login fail
  384. with pytest.raises(KeycloakPostError) as err:
  385. admin.add_user_social_login(
  386. user_id="does-not-exist",
  387. provider_id="does-not-exist",
  388. provider_userid="test",
  389. provider_username="test",
  390. )
  391. assert err.match('404: b\'{"error":"User not found"}\'')
  392. res = admin.get_user_social_logins(user_id=user)
  393. assert res == list(), res
  394. # Test get social logins fail
  395. with pytest.raises(KeycloakGetError) as err:
  396. admin.get_user_social_logins(user_id="does-not-exist")
  397. assert err.match('404: b\'{"error":"User not found"}\'')
  398. res = admin.delete_user_social_login(user_id=user, provider_id="gitlab")
  399. assert res == {}, res
  400. res = admin.delete_user_social_login(user_id=user, provider_id="github")
  401. assert res == {}, res
  402. with pytest.raises(KeycloakDeleteError) as err:
  403. admin.delete_user_social_login(user_id=user, provider_id="instagram")
  404. assert err.match('404: b\'{"error":"Link not found"}\''), err
  405. def test_server_info(admin: KeycloakAdmin):
  406. """Test server info.
  407. :param admin: Keycloak Admin client
  408. :type admin: KeycloakAdmin
  409. """
  410. info = admin.get_server_info()
  411. assert set(info.keys()).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. def test_email(admin: KeycloakAdmin, user: str):
  1319. """Test email.
  1320. :param admin: Keycloak Admin client
  1321. :type admin: KeycloakAdmin
  1322. :param user: Keycloak user
  1323. :type user: str
  1324. """
  1325. # Emails will fail as we don't have SMTP test setup
  1326. with pytest.raises(KeycloakPutError) as err:
  1327. admin.send_update_account(user_id=user, payload=dict())
  1328. assert err.match('500: b\'{"error":"unknown_error"}\'')
  1329. admin.update_user(user_id=user, payload={"enabled": True})
  1330. with pytest.raises(KeycloakPutError) as err:
  1331. admin.send_verify_email(user_id=user)
  1332. assert err.match('500: b\'{"errorMessage":"Failed to send execute actions email"}\'')
  1333. def test_get_sessions(admin: KeycloakAdmin):
  1334. """Test get sessions.
  1335. :param admin: Keycloak Admin client
  1336. :type admin: KeycloakAdmin
  1337. """
  1338. sessions = admin.get_sessions(user_id=admin.get_user_id(username=admin.username))
  1339. assert len(sessions) >= 1
  1340. with pytest.raises(KeycloakGetError) as err:
  1341. admin.get_sessions(user_id="bad")
  1342. assert err.match('404: b\'{"error":"User not found"}\'')
  1343. def test_get_client_installation_provider(admin: KeycloakAdmin, client: str):
  1344. """Test get client installation provider.
  1345. :param admin: Keycloak Admin client
  1346. :type admin: KeycloakAdmin
  1347. :param client: Keycloak client
  1348. :type client: str
  1349. """
  1350. with pytest.raises(KeycloakGetError) as err:
  1351. admin.get_client_installation_provider(client_id=client, provider_id="bad")
  1352. assert err.match('404: b\'{"error":"Unknown Provider"}\'')
  1353. installation = admin.get_client_installation_provider(
  1354. client_id=client, provider_id="keycloak-oidc-keycloak-json"
  1355. )
  1356. assert set(installation.keys()) == {
  1357. "auth-server-url",
  1358. "confidential-port",
  1359. "credentials",
  1360. "realm",
  1361. "resource",
  1362. "ssl-required",
  1363. }
  1364. def test_auth_flows(admin: KeycloakAdmin, realm: str):
  1365. """Test auth flows.
  1366. :param admin: Keycloak Admin client
  1367. :type admin: KeycloakAdmin
  1368. :param realm: Keycloak realm
  1369. :type realm: str
  1370. """
  1371. admin.realm_name = realm
  1372. res = admin.get_authentication_flows()
  1373. assert len(res) == 8, res
  1374. assert set(res[0].keys()) == {
  1375. "alias",
  1376. "authenticationExecutions",
  1377. "builtIn",
  1378. "description",
  1379. "id",
  1380. "providerId",
  1381. "topLevel",
  1382. }
  1383. assert {x["alias"] for x in res} == {
  1384. "reset credentials",
  1385. "browser",
  1386. "http challenge",
  1387. "registration",
  1388. "docker auth",
  1389. "direct grant",
  1390. "first broker login",
  1391. "clients",
  1392. }
  1393. with pytest.raises(KeycloakGetError) as err:
  1394. admin.get_authentication_flow_for_id(flow_id="bad")
  1395. assert err.match('404: b\'{"error":"Could not find flow with id"}\'')
  1396. browser_flow_id = [x for x in res if x["alias"] == "browser"][0]["id"]
  1397. res = admin.get_authentication_flow_for_id(flow_id=browser_flow_id)
  1398. assert res["alias"] == "browser"
  1399. # Test copying
  1400. with pytest.raises(KeycloakPostError) as err:
  1401. admin.copy_authentication_flow(payload=dict(), flow_alias="bad")
  1402. assert err.match("404: b''")
  1403. res = admin.copy_authentication_flow(payload={"newName": "test-browser"}, flow_alias="browser")
  1404. assert res == b"", res
  1405. assert len(admin.get_authentication_flows()) == 9
  1406. # Test create
  1407. res = admin.create_authentication_flow(
  1408. payload={"alias": "test-create", "providerId": "basic-flow"}
  1409. )
  1410. assert res == b""
  1411. with pytest.raises(KeycloakPostError) as err:
  1412. admin.create_authentication_flow(payload={"alias": "test-create", "builtIn": False})
  1413. assert err.match('409: b\'{"errorMessage":"Flow test-create already exists"}\'')
  1414. assert admin.create_authentication_flow(
  1415. payload={"alias": "test-create"}, skip_exists=True
  1416. ) == {"msg": "Already exists"}
  1417. # Test flow executions
  1418. res = admin.get_authentication_flow_executions(flow_alias="browser")
  1419. assert len(res) == 8, res
  1420. with pytest.raises(KeycloakGetError) as err:
  1421. admin.get_authentication_flow_executions(flow_alias="bad")
  1422. assert err.match("404: b''")
  1423. exec_id = res[0]["id"]
  1424. res = admin.get_authentication_flow_execution(execution_id=exec_id)
  1425. assert set(res.keys()) == {
  1426. "alternative",
  1427. "authenticator",
  1428. "authenticatorFlow",
  1429. "conditional",
  1430. "disabled",
  1431. "enabled",
  1432. "id",
  1433. "parentFlow",
  1434. "priority",
  1435. "required",
  1436. "requirement",
  1437. }, res
  1438. with pytest.raises(KeycloakGetError) as err:
  1439. admin.get_authentication_flow_execution(execution_id="bad")
  1440. assert err.match('404: b\'{"error":"Illegal execution"}\'')
  1441. with pytest.raises(KeycloakPostError) as err:
  1442. admin.create_authentication_flow_execution(payload=dict(), flow_alias="browser")
  1443. assert err.match('400: b\'{"error":"It is illegal to add execution to a built in flow"}\'')
  1444. res = admin.create_authentication_flow_execution(
  1445. payload={"provider": "auth-cookie"}, flow_alias="test-create"
  1446. )
  1447. assert res == b""
  1448. assert len(admin.get_authentication_flow_executions(flow_alias="test-create")) == 1
  1449. with pytest.raises(KeycloakPutError) as err:
  1450. admin.update_authentication_flow_executions(
  1451. payload={"required": "yes"}, flow_alias="test-create"
  1452. )
  1453. assert err.match('400: b\'{"error":"Unrecognized field')
  1454. payload = admin.get_authentication_flow_executions(flow_alias="test-create")[0]
  1455. payload["displayName"] = "test"
  1456. res = admin.update_authentication_flow_executions(payload=payload, flow_alias="test-create")
  1457. assert res
  1458. exec_id = admin.get_authentication_flow_executions(flow_alias="test-create")[0]["id"]
  1459. res = admin.delete_authentication_flow_execution(execution_id=exec_id)
  1460. assert res == dict()
  1461. with pytest.raises(KeycloakDeleteError) as err:
  1462. admin.delete_authentication_flow_execution(execution_id=exec_id)
  1463. assert err.match('404: b\'{"error":"Illegal execution"}\'')
  1464. # Test subflows
  1465. res = admin.create_authentication_flow_subflow(
  1466. payload={
  1467. "alias": "test-subflow",
  1468. "provider": "basic-flow",
  1469. "type": "something",
  1470. "description": "something",
  1471. },
  1472. flow_alias="test-browser",
  1473. )
  1474. assert res == b""
  1475. with pytest.raises(KeycloakPostError) as err:
  1476. admin.create_authentication_flow_subflow(
  1477. payload={"alias": "test-subflow", "providerId": "basic-flow"},
  1478. flow_alias="test-browser",
  1479. )
  1480. assert err.match('409: b\'{"errorMessage":"New flow alias name already exists"}\'')
  1481. res = admin.create_authentication_flow_subflow(
  1482. payload={
  1483. "alias": "test-subflow",
  1484. "provider": "basic-flow",
  1485. "type": "something",
  1486. "description": "something",
  1487. },
  1488. flow_alias="test-create",
  1489. skip_exists=True,
  1490. )
  1491. assert res == {"msg": "Already exists"}
  1492. # Test delete auth flow
  1493. flow_id = [x for x in admin.get_authentication_flows() if x["alias"] == "test-browser"][0][
  1494. "id"
  1495. ]
  1496. res = admin.delete_authentication_flow(flow_id=flow_id)
  1497. assert res == dict()
  1498. with pytest.raises(KeycloakDeleteError) as err:
  1499. admin.delete_authentication_flow(flow_id=flow_id)
  1500. assert err.match('404: b\'{"error":"Could not find flow with id"}\'')
  1501. def test_authentication_configs(admin: KeycloakAdmin, realm: str):
  1502. """Test authentication configs.
  1503. :param admin: Keycloak Admin client
  1504. :type admin: KeycloakAdmin
  1505. :param realm: Keycloak realm
  1506. :type realm: str
  1507. """
  1508. admin.realm_name = realm
  1509. # Test list of auth providers
  1510. res = admin.get_authenticator_providers()
  1511. assert len(res) == 38
  1512. res = admin.get_authenticator_provider_config_description(provider_id="auth-cookie")
  1513. assert res == {
  1514. "helpText": "Validates the SSO cookie set by the auth server.",
  1515. "name": "Cookie",
  1516. "properties": [],
  1517. "providerId": "auth-cookie",
  1518. }
  1519. # Test authenticator config
  1520. # Currently unable to find a sustainable way to fetch the config id,
  1521. # therefore testing only failures
  1522. with pytest.raises(KeycloakGetError) as err:
  1523. admin.get_authenticator_config(config_id="bad")
  1524. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1525. with pytest.raises(KeycloakPutError) as err:
  1526. admin.update_authenticator_config(payload=dict(), config_id="bad")
  1527. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1528. with pytest.raises(KeycloakDeleteError) as err:
  1529. admin.delete_authenticator_config(config_id="bad")
  1530. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1531. def test_sync_users(admin: KeycloakAdmin, realm: str):
  1532. """Test sync users.
  1533. :param admin: Keycloak Admin client
  1534. :type admin: KeycloakAdmin
  1535. :param realm: Keycloak realm
  1536. :type realm: str
  1537. """
  1538. admin.realm_name = realm
  1539. # Only testing the error message
  1540. with pytest.raises(KeycloakPostError) as err:
  1541. admin.sync_users(storage_id="does-not-exist", action="triggerFullSync")
  1542. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1543. def test_client_scopes(admin: KeycloakAdmin, realm: str):
  1544. """Test client scopes.
  1545. :param admin: Keycloak Admin client
  1546. :type admin: KeycloakAdmin
  1547. :param realm: Keycloak realm
  1548. :type realm: str
  1549. """
  1550. admin.realm_name = realm
  1551. # Test get client scopes
  1552. res = admin.get_client_scopes()
  1553. scope_names = {x["name"] for x in res}
  1554. assert len(res) == 10
  1555. assert "email" in scope_names
  1556. assert "profile" in scope_names
  1557. assert "offline_access" in scope_names
  1558. with pytest.raises(KeycloakGetError) as err:
  1559. admin.get_client_scope(client_scope_id="does-not-exist")
  1560. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1561. scope = admin.get_client_scope(client_scope_id=res[0]["id"])
  1562. assert res[0] == scope
  1563. scope = admin.get_client_scope_by_name(client_scope_name=res[0]["name"])
  1564. assert res[0] == scope
  1565. # Test create client scope
  1566. res = admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=True)
  1567. assert res
  1568. res2 = admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=True)
  1569. assert res == res2
  1570. with pytest.raises(KeycloakPostError) as err:
  1571. admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=False)
  1572. assert err.match('409: b\'{"errorMessage":"Client Scope test-scope already exists"}\'')
  1573. # Test update client scope
  1574. with pytest.raises(KeycloakPutError) as err:
  1575. admin.update_client_scope(client_scope_id="does-not-exist", payload=dict())
  1576. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1577. res_update = admin.update_client_scope(
  1578. client_scope_id=res, payload={"name": "test-scope-update"}
  1579. )
  1580. assert res_update == dict()
  1581. admin.get_client_scope(client_scope_id=res)["name"] == "test-scope-update"
  1582. # Test get mappers
  1583. mappers = admin.get_mappers_from_client_scope(client_scope_id=res)
  1584. assert mappers == list()
  1585. # Test add mapper
  1586. with pytest.raises(KeycloakPostError) as err:
  1587. admin.add_mapper_to_client_scope(client_scope_id=res, payload=dict())
  1588. assert err.match('404: b\'{"error":"ProtocolMapper provider not found"}\'')
  1589. res_add = admin.add_mapper_to_client_scope(
  1590. client_scope_id=res,
  1591. payload={
  1592. "name": "test-mapper",
  1593. "protocol": "openid-connect",
  1594. "protocolMapper": "oidc-usermodel-attribute-mapper",
  1595. },
  1596. )
  1597. assert res_add == b""
  1598. assert len(admin.get_mappers_from_client_scope(client_scope_id=res)) == 1
  1599. # Test update mapper
  1600. test_mapper = admin.get_mappers_from_client_scope(client_scope_id=res)[0]
  1601. with pytest.raises(KeycloakPutError) as err:
  1602. admin.update_mapper_in_client_scope(
  1603. client_scope_id="does-not-exist", protocol_mapper_id=test_mapper["id"], payload=dict()
  1604. )
  1605. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1606. test_mapper["config"]["user.attribute"] = "test"
  1607. res_update = admin.update_mapper_in_client_scope(
  1608. client_scope_id=res, protocol_mapper_id=test_mapper["id"], payload=test_mapper
  1609. )
  1610. assert res_update == dict()
  1611. assert (
  1612. admin.get_mappers_from_client_scope(client_scope_id=res)[0]["config"]["user.attribute"]
  1613. == "test"
  1614. )
  1615. # Test delete mapper
  1616. res_del = admin.delete_mapper_from_client_scope(
  1617. client_scope_id=res, protocol_mapper_id=test_mapper["id"]
  1618. )
  1619. assert res_del == dict()
  1620. with pytest.raises(KeycloakDeleteError) as err:
  1621. admin.delete_mapper_from_client_scope(
  1622. client_scope_id=res, protocol_mapper_id=test_mapper["id"]
  1623. )
  1624. assert err.match('404: b\'{"error":"Model not found"}\'')
  1625. # Test default default scopes
  1626. res_defaults = admin.get_default_default_client_scopes()
  1627. assert len(res_defaults) == 6
  1628. with pytest.raises(KeycloakPutError) as err:
  1629. admin.add_default_default_client_scope(scope_id="does-not-exist")
  1630. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1631. res_add = admin.add_default_default_client_scope(scope_id=res)
  1632. assert res_add == dict()
  1633. assert len(admin.get_default_default_client_scopes()) == 7
  1634. with pytest.raises(KeycloakDeleteError) as err:
  1635. admin.delete_default_default_client_scope(scope_id="does-not-exist")
  1636. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1637. res_del = admin.delete_default_default_client_scope(scope_id=res)
  1638. assert res_del == dict()
  1639. assert len(admin.get_default_default_client_scopes()) == 6
  1640. # Test default optional scopes
  1641. res_defaults = admin.get_default_optional_client_scopes()
  1642. assert len(res_defaults) == 4
  1643. with pytest.raises(KeycloakPutError) as err:
  1644. admin.add_default_optional_client_scope(scope_id="does-not-exist")
  1645. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1646. res_add = admin.add_default_optional_client_scope(scope_id=res)
  1647. assert res_add == dict()
  1648. assert len(admin.get_default_optional_client_scopes()) == 5
  1649. with pytest.raises(KeycloakDeleteError) as err:
  1650. admin.delete_default_optional_client_scope(scope_id="does-not-exist")
  1651. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1652. res_del = admin.delete_default_optional_client_scope(scope_id=res)
  1653. assert res_del == dict()
  1654. assert len(admin.get_default_optional_client_scopes()) == 4
  1655. # Test client scope delete
  1656. res_del = admin.delete_client_scope(client_scope_id=res)
  1657. assert res_del == dict()
  1658. with pytest.raises(KeycloakDeleteError) as err:
  1659. admin.delete_client_scope(client_scope_id=res)
  1660. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1661. def test_components(admin: KeycloakAdmin, realm: str):
  1662. """Test components.
  1663. :param admin: Keycloak Admin client
  1664. :type admin: KeycloakAdmin
  1665. :param realm: Keycloak realm
  1666. :type realm: str
  1667. """
  1668. admin.realm_name = realm
  1669. # Test get components
  1670. res = admin.get_components()
  1671. assert len(res) == 12
  1672. with pytest.raises(KeycloakGetError) as err:
  1673. admin.get_component(component_id="does-not-exist")
  1674. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1675. res_get = admin.get_component(component_id=res[0]["id"])
  1676. assert res_get == res[0]
  1677. # Test create component
  1678. with pytest.raises(KeycloakPostError) as err:
  1679. admin.create_component(payload={"bad": "dict"})
  1680. assert err.match('400: b\'{"error":"Unrecognized field')
  1681. res = admin.create_component(
  1682. payload={
  1683. "name": "Test Component",
  1684. "providerId": "max-clients",
  1685. "providerType": "org.keycloak.services.clientregistration."
  1686. + "policy.ClientRegistrationPolicy",
  1687. "config": {"max-clients": ["1000"]},
  1688. }
  1689. )
  1690. assert res
  1691. assert admin.get_component(component_id=res)["name"] == "Test Component"
  1692. # Test update component
  1693. component = admin.get_component(component_id=res)
  1694. component["name"] = "Test Component Update"
  1695. with pytest.raises(KeycloakPutError) as err:
  1696. admin.update_component(component_id="does-not-exist", payload=dict())
  1697. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1698. res_upd = admin.update_component(component_id=res, payload=component)
  1699. assert res_upd == dict()
  1700. assert admin.get_component(component_id=res)["name"] == "Test Component Update"
  1701. # Test delete component
  1702. res_del = admin.delete_component(component_id=res)
  1703. assert res_del == dict()
  1704. with pytest.raises(KeycloakDeleteError) as err:
  1705. admin.delete_component(component_id=res)
  1706. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1707. def test_keys(admin: KeycloakAdmin, realm: str):
  1708. """Test keys.
  1709. :param admin: Keycloak Admin client
  1710. :type admin: KeycloakAdmin
  1711. :param realm: Keycloak realm
  1712. :type realm: str
  1713. """
  1714. admin.realm_name = realm
  1715. assert set(admin.get_keys()["active"].keys()) == {"AES", "HS256", "RS256", "RSA-OAEP"}
  1716. assert {k["algorithm"] for k in admin.get_keys()["keys"]} == {
  1717. "HS256",
  1718. "RSA-OAEP",
  1719. "AES",
  1720. "RS256",
  1721. }
  1722. def test_events(admin: KeycloakAdmin, realm: str):
  1723. """Test events.
  1724. :param admin: Keycloak Admin client
  1725. :type admin: KeycloakAdmin
  1726. :param realm: Keycloak realm
  1727. :type realm: str
  1728. """
  1729. admin.realm_name = realm
  1730. events = admin.get_events()
  1731. assert events == list()
  1732. with pytest.raises(KeycloakPutError) as err:
  1733. admin.set_events(payload={"bad": "conf"})
  1734. assert err.match('400: b\'{"error":"Unrecognized field')
  1735. res = admin.set_events(payload={"adminEventsDetailsEnabled": True, "adminEventsEnabled": True})
  1736. assert res == dict()
  1737. admin.create_client(payload={"name": "test", "clientId": "test"})
  1738. events = admin.get_events()
  1739. assert events == list()
  1740. def test_auto_refresh(admin: KeycloakAdmin, realm: str):
  1741. """Test auto refresh token.
  1742. :param admin: Keycloak Admin client
  1743. :type admin: KeycloakAdmin
  1744. :param realm: Keycloak realm
  1745. :type realm: str
  1746. """
  1747. # Test get refresh
  1748. admin.auto_refresh_token = list()
  1749. admin.connection = ConnectionManager(
  1750. base_url=admin.server_url,
  1751. headers={"Authorization": "Bearer bad", "Content-Type": "application/json"},
  1752. timeout=60,
  1753. verify=admin.verify,
  1754. )
  1755. with pytest.raises(KeycloakAuthenticationError) as err:
  1756. admin.get_realm(realm_name=realm)
  1757. assert err.match('401: b\'{"error":"HTTP 401 Unauthorized"}\'')
  1758. admin.auto_refresh_token = ["get"]
  1759. del admin.token["refresh_token"]
  1760. assert admin.get_realm(realm_name=realm)
  1761. # Test bad refresh token
  1762. admin.connection = ConnectionManager(
  1763. base_url=admin.server_url,
  1764. headers={"Authorization": "Bearer bad", "Content-Type": "application/json"},
  1765. timeout=60,
  1766. verify=admin.verify,
  1767. )
  1768. admin.token["refresh_token"] = "bad"
  1769. with pytest.raises(KeycloakPostError) as err:
  1770. admin.get_realm(realm_name="test-refresh")
  1771. assert err.match(
  1772. '400: b\'{"error":"invalid_grant","error_description":"Invalid refresh token"}\''
  1773. )
  1774. admin.realm_name = "master"
  1775. admin.get_token()
  1776. admin.realm_name = realm
  1777. # Test post refresh
  1778. admin.connection = ConnectionManager(
  1779. base_url=admin.server_url,
  1780. headers={"Authorization": "Bearer bad", "Content-Type": "application/json"},
  1781. timeout=60,
  1782. verify=admin.verify,
  1783. )
  1784. with pytest.raises(KeycloakAuthenticationError) as err:
  1785. admin.create_realm(payload={"realm": "test-refresh"})
  1786. assert err.match('401: b\'{"error":"HTTP 401 Unauthorized"}\'')
  1787. admin.auto_refresh_token = ["get", "post"]
  1788. admin.realm_name = "master"
  1789. admin.user_logout(user_id=admin.get_user_id(username=admin.username))
  1790. assert admin.create_realm(payload={"realm": "test-refresh"}) == b""
  1791. admin.realm_name = realm
  1792. # Test update refresh
  1793. admin.connection = ConnectionManager(
  1794. base_url=admin.server_url,
  1795. headers={"Authorization": "Bearer bad", "Content-Type": "application/json"},
  1796. timeout=60,
  1797. verify=admin.verify,
  1798. )
  1799. with pytest.raises(KeycloakAuthenticationError) as err:
  1800. admin.update_realm(realm_name="test-refresh", payload={"accountTheme": "test"})
  1801. assert err.match('401: b\'{"error":"HTTP 401 Unauthorized"}\'')
  1802. admin.auto_refresh_token = ["get", "post", "put"]
  1803. assert (
  1804. admin.update_realm(realm_name="test-refresh", payload={"accountTheme": "test"}) == dict()
  1805. )
  1806. # Test delete refresh
  1807. admin.connection = ConnectionManager(
  1808. base_url=admin.server_url,
  1809. headers={"Authorization": "Bearer bad", "Content-Type": "application/json"},
  1810. timeout=60,
  1811. verify=admin.verify,
  1812. )
  1813. with pytest.raises(KeycloakAuthenticationError) as err:
  1814. admin.delete_realm(realm_name="test-refresh")
  1815. assert err.match('401: b\'{"error":"HTTP 401 Unauthorized"}\'')
  1816. admin.auto_refresh_token = ["get", "post", "put", "delete"]
  1817. assert admin.delete_realm(realm_name="test-refresh") == dict()
  1818. def test_get_required_actions(admin: KeycloakAdmin, realm: str):
  1819. """Test required actions.
  1820. :param admin: Keycloak Admin client
  1821. :type admin: KeycloakAdmin
  1822. :param realm: Keycloak realm
  1823. :type realm: str
  1824. """
  1825. admin.realm_name = realm
  1826. ractions = admin.get_required_actions()
  1827. assert isinstance(ractions, list)
  1828. for ra in ractions:
  1829. for key in [
  1830. "alias",
  1831. "name",
  1832. "providerId",
  1833. "enabled",
  1834. "defaultAction",
  1835. "priority",
  1836. "config",
  1837. ]:
  1838. assert key in ra
  1839. def test_get_required_action_by_alias(admin: KeycloakAdmin, realm: str):
  1840. """Test get required action by alias.
  1841. :param admin: Keycloak Admin client
  1842. :type admin: KeycloakAdmin
  1843. :param realm: Keycloak realm
  1844. :type realm: str
  1845. """
  1846. admin.realm_name = realm
  1847. ractions = admin.get_required_actions()
  1848. ra = admin.get_required_action_by_alias("UPDATE_PASSWORD")
  1849. assert ra in ractions
  1850. assert ra["alias"] == "UPDATE_PASSWORD"
  1851. assert admin.get_required_action_by_alias("does-not-exist") is None
  1852. def test_update_required_action(admin: KeycloakAdmin, realm: str):
  1853. """Test update required action.
  1854. :param admin: Keycloak Admin client
  1855. :type admin: KeycloakAdmin
  1856. :param realm: Keycloak realm
  1857. :type realm: str
  1858. """
  1859. admin.realm_name = realm
  1860. ra = admin.get_required_action_by_alias("UPDATE_PASSWORD")
  1861. old = copy.deepcopy(ra)
  1862. ra["enabled"] = False
  1863. admin.update_required_action("UPDATE_PASSWORD", ra)
  1864. newra = admin.get_required_action_by_alias("UPDATE_PASSWORD")
  1865. assert old != newra
  1866. assert newra["enabled"] is False
  1867. def test_get_composite_client_roles_of_group(
  1868. admin: KeycloakAdmin, realm: str, client: str, group: str, composite_client_role: str
  1869. ):
  1870. """Test get composite client roles of group.
  1871. :param admin: Keycloak Admin client
  1872. :type admin: KeycloakAdmin
  1873. :param realm: Keycloak realm
  1874. :type realm: str
  1875. :param client: Keycloak client
  1876. :type client: str
  1877. :param group: Keycloak group
  1878. :type group: str
  1879. :param composite_client_role: Composite client role
  1880. :type composite_client_role: str
  1881. """
  1882. admin.realm_name = realm
  1883. role = admin.get_client_role(client, composite_client_role)
  1884. admin.assign_group_client_roles(group_id=group, client_id=client, roles=[role])
  1885. result = admin.get_composite_client_roles_of_group(client, group)
  1886. assert role["id"] in [x["id"] for x in result]
  1887. def test_get_role_client_level_children(
  1888. admin: KeycloakAdmin, realm: str, client: str, composite_client_role: str, client_role: str
  1889. ):
  1890. """Test get children of composite client role.
  1891. :param admin: Keycloak Admin client
  1892. :type admin: KeycloakAdmin
  1893. :param realm: Keycloak realm
  1894. :type realm: str
  1895. :param client: Keycloak client
  1896. :type client: str
  1897. :param composite_client_role: Composite client role
  1898. :type composite_client_role: str
  1899. :param client_role: Client role
  1900. :type client_role: str
  1901. """
  1902. admin.realm_name = realm
  1903. child = admin.get_client_role(client, client_role)
  1904. parent = admin.get_client_role(client, composite_client_role)
  1905. res = admin.get_role_client_level_children(client, parent["id"])
  1906. assert child["id"] in [x["id"] for x in res]
  1907. def test_upload_certificate(admin: KeycloakAdmin, realm: str, client: str, selfsigned_cert: tuple):
  1908. """Test upload certificate.
  1909. :param admin: Keycloak Admin client
  1910. :type admin: KeycloakAdmin
  1911. :param realm: Keycloak realm
  1912. :type realm: str
  1913. :param client: Keycloak client
  1914. :type client: str
  1915. :param selfsigned_cert: Selfsigned certificates
  1916. :type selfsigned_cert: tuple
  1917. """
  1918. admin.realm_name = realm
  1919. cert, _ = selfsigned_cert
  1920. cert = cert.decode("utf-8").strip()
  1921. admin.upload_certificate(client, cert)
  1922. cl = admin.get_client(client)
  1923. assert cl["attributes"]["jwt.credential.certificate"] == "".join(cert.splitlines()[1:-1])
  1924. def test_get_bruteforce_status_for_user(
  1925. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str], realm: str
  1926. ):
  1927. """Test users.
  1928. :param admin: Keycloak Admin client
  1929. :type admin: KeycloakAdmin
  1930. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  1931. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  1932. :param realm: Keycloak realm
  1933. :type realm: str
  1934. """
  1935. oid, username, password = oid_with_credentials
  1936. admin.realm_name = realm
  1937. # Turn on bruteforce protection
  1938. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": True})
  1939. res = admin.get_realm(realm_name=realm)
  1940. assert res["bruteForceProtected"] is True
  1941. # Test login user with wrong credentials
  1942. try:
  1943. oid.token(username=username, password="wrongpassword")
  1944. except KeycloakAuthenticationError:
  1945. pass
  1946. user_id = admin.get_user_id(username)
  1947. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  1948. assert bruteforce_status["numFailures"] == 1
  1949. # Cleanup
  1950. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": False})
  1951. res = admin.get_realm(realm_name=realm)
  1952. assert res["bruteForceProtected"] is False
  1953. def test_clear_bruteforce_attempts_for_user(
  1954. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str], realm: str
  1955. ):
  1956. """Test users.
  1957. :param admin: Keycloak Admin client
  1958. :type admin: KeycloakAdmin
  1959. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  1960. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  1961. :param realm: Keycloak realm
  1962. :type realm: str
  1963. """
  1964. oid, username, password = oid_with_credentials
  1965. admin.realm_name = realm
  1966. # Turn on bruteforce protection
  1967. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": True})
  1968. res = admin.get_realm(realm_name=realm)
  1969. assert res["bruteForceProtected"] is True
  1970. # Test login user with wrong credentials
  1971. try:
  1972. oid.token(username=username, password="wrongpassword")
  1973. except KeycloakAuthenticationError:
  1974. pass
  1975. user_id = admin.get_user_id(username)
  1976. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  1977. assert bruteforce_status["numFailures"] == 1
  1978. res = admin.clear_bruteforce_attempts_for_user(user_id)
  1979. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  1980. assert bruteforce_status["numFailures"] == 0
  1981. # Cleanup
  1982. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": False})
  1983. res = admin.get_realm(realm_name=realm)
  1984. assert res["bruteForceProtected"] is False
  1985. def test_clear_bruteforce_attempts_for_all_users(
  1986. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str], realm: str
  1987. ):
  1988. """Test users.
  1989. :param admin: Keycloak Admin client
  1990. :type admin: KeycloakAdmin
  1991. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  1992. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  1993. :param realm: Keycloak realm
  1994. :type realm: str
  1995. """
  1996. oid, username, password = oid_with_credentials
  1997. admin.realm_name = realm
  1998. # Turn on bruteforce protection
  1999. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": True})
  2000. res = admin.get_realm(realm_name=realm)
  2001. assert res["bruteForceProtected"] is True
  2002. # Test login user with wrong credentials
  2003. try:
  2004. oid.token(username=username, password="wrongpassword")
  2005. except KeycloakAuthenticationError:
  2006. pass
  2007. user_id = admin.get_user_id(username)
  2008. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2009. assert bruteforce_status["numFailures"] == 1
  2010. res = admin.clear_all_bruteforce_attempts()
  2011. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2012. assert bruteforce_status["numFailures"] == 0
  2013. # Cleanup
  2014. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": False})
  2015. res = admin.get_realm(realm_name=realm)
  2016. assert res["bruteForceProtected"] is False