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.

2745 lines
98 KiB

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