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.

2766 lines
99 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: str = res["_id"]
  693. # Test update authz resources
  694. admin.update_client_authz_resource(
  695. client_id=auth_client_id,
  696. resource_id=temp_resource_id,
  697. payload={"name": "temp-updated-resource"},
  698. )
  699. res = admin.get_client_authz_resource(client_id=auth_client_id, resource_id=temp_resource_id)
  700. assert res["name"] == "temp-updated-resource", res
  701. with pytest.raises(KeycloakPutError) as err:
  702. admin.update_client_authz_resource(
  703. client_id=auth_client_id,
  704. resource_id="invalid_resource_id",
  705. payload={"name": "temp-updated-resource"},
  706. )
  707. assert err.match("404: b''"), err
  708. admin.delete_client_authz_resource(client_id=auth_client_id, resource_id=temp_resource_id)
  709. with pytest.raises(KeycloakGetError) as err:
  710. admin.get_client_authz_resource(client_id=auth_client_id, resource_id=temp_resource_id)
  711. assert err.match("404: b''")
  712. # Authz policies
  713. res = admin.get_client_authz_policies(client_id=auth_client_id)
  714. assert len(res) == 1, res
  715. assert res[0]["name"] == "Default Policy"
  716. with pytest.raises(KeycloakGetError) as err:
  717. admin.get_client_authz_policies(client_id="does-not-exist")
  718. assert err.match('404: b\'{"error":"Could not find client"}\'')
  719. role_id = admin.get_realm_role(role_name="offline_access")["id"]
  720. res = admin.create_client_authz_role_based_policy(
  721. client_id=auth_client_id,
  722. payload={"name": "test-authz-rb-policy", "roles": [{"id": role_id}]},
  723. )
  724. assert res["name"] == "test-authz-rb-policy", res
  725. with pytest.raises(KeycloakPostError) as err:
  726. admin.create_client_authz_role_based_policy(
  727. client_id=auth_client_id,
  728. payload={"name": "test-authz-rb-policy", "roles": [{"id": role_id}]},
  729. )
  730. assert err.match('409: b\'{"error":"Policy with name')
  731. assert admin.create_client_authz_role_based_policy(
  732. client_id=auth_client_id,
  733. payload={"name": "test-authz-rb-policy", "roles": [{"id": role_id}]},
  734. skip_exists=True,
  735. ) == {"msg": "Already exists"}
  736. assert len(admin.get_client_authz_policies(client_id=auth_client_id)) == 2
  737. res = admin.create_client_authz_role_based_policy(
  738. client_id=auth_client_id,
  739. payload={"name": "test-authz-rb-policy-delete", "roles": [{"id": role_id}]},
  740. )
  741. res2 = admin.get_client_authz_policy(client_id=auth_client_id, policy_id=res["id"])
  742. assert res["id"] == res2["id"]
  743. admin.delete_client_authz_policy(client_id=auth_client_id, policy_id=res["id"])
  744. with pytest.raises(KeycloakGetError) as err:
  745. admin.get_client_authz_policy(client_id=auth_client_id, policy_id=res["id"])
  746. assert err.match("404: b''")
  747. res = admin.create_client_authz_policy(
  748. client_id=auth_client_id,
  749. payload={
  750. "name": "test-authz-policy",
  751. "type": "time",
  752. "config": {"hourEnd": "18", "hour": "9"},
  753. },
  754. )
  755. assert res["name"] == "test-authz-policy", res
  756. with pytest.raises(KeycloakPostError) as err:
  757. admin.create_client_authz_policy(
  758. client_id=auth_client_id,
  759. payload={
  760. "name": "test-authz-policy",
  761. "type": "time",
  762. "config": {"hourEnd": "18", "hour": "9"},
  763. },
  764. )
  765. assert err.match('409: b\'{"error":"Policy with name')
  766. assert admin.create_client_authz_policy(
  767. client_id=auth_client_id,
  768. payload={
  769. "name": "test-authz-policy",
  770. "type": "time",
  771. "config": {"hourEnd": "18", "hour": "9"},
  772. },
  773. skip_exists=True,
  774. ) == {"msg": "Already exists"}
  775. assert len(admin.get_client_authz_policies(client_id=auth_client_id)) == 3
  776. # Test authz permissions
  777. res = admin.get_client_authz_permissions(client_id=auth_client_id)
  778. assert len(res) == 1, res
  779. assert res[0]["name"] == "Default Permission"
  780. with pytest.raises(KeycloakGetError) as err:
  781. admin.get_client_authz_permissions(client_id="does-not-exist")
  782. assert err.match('404: b\'{"error":"Could not find client"}\'')
  783. res = admin.create_client_authz_resource_based_permission(
  784. client_id=auth_client_id,
  785. payload={"name": "test-permission-rb", "resources": [test_resource_id]},
  786. )
  787. assert res, res
  788. assert res["name"] == "test-permission-rb"
  789. assert res["resources"] == [test_resource_id]
  790. with pytest.raises(KeycloakPostError) as err:
  791. admin.create_client_authz_resource_based_permission(
  792. client_id=auth_client_id,
  793. payload={"name": "test-permission-rb", "resources": [test_resource_id]},
  794. )
  795. assert err.match('409: b\'{"error":"Policy with name')
  796. assert admin.create_client_authz_resource_based_permission(
  797. client_id=auth_client_id,
  798. payload={"name": "test-permission-rb", "resources": [test_resource_id]},
  799. skip_exists=True,
  800. ) == {"msg": "Already exists"}
  801. assert len(admin.get_client_authz_permissions(client_id=auth_client_id)) == 2
  802. # Test authz scopes
  803. res = admin.get_client_authz_scopes(client_id=auth_client_id)
  804. assert len(res) == 0, res
  805. with pytest.raises(KeycloakGetError) as err:
  806. admin.get_client_authz_scopes(client_id=client_id)
  807. assert err.match('404: b\'{"error":"HTTP 404 Not Found"}\'')
  808. res = admin.create_client_authz_scopes(
  809. client_id=auth_client_id, payload={"name": "test-authz-scope"}
  810. )
  811. assert res["name"] == "test-authz-scope", res
  812. test_scope_id = res["id"]
  813. with pytest.raises(KeycloakPostError) as err:
  814. admin.create_client_authz_scopes(
  815. client_id="invalid_client_id", payload={"name": "test-authz-scope"}
  816. )
  817. assert err.match('404: b\'{"error":"Could not find client"')
  818. assert admin.create_client_authz_scopes(
  819. client_id=auth_client_id, payload={"name": "test-authz-scope"}
  820. )
  821. res = admin.get_client_authz_scopes(client_id=auth_client_id)
  822. assert len(res) == 1
  823. assert {x["name"] for x in res} == {"test-authz-scope"}
  824. res = admin.create_client_authz_scope_based_permission(
  825. client_id=auth_client_id,
  826. payload={
  827. "name": "test-permission-sb",
  828. "resources": [test_resource_id],
  829. "scopes": [test_scope_id],
  830. },
  831. )
  832. assert res, res
  833. assert res["name"] == "test-permission-sb"
  834. assert res["resources"] == [test_resource_id]
  835. assert res["scopes"] == [test_scope_id]
  836. with pytest.raises(KeycloakPostError) as err:
  837. admin.create_client_authz_scope_based_permission(
  838. client_id=auth_client_id,
  839. payload={
  840. "name": "test-permission-sb",
  841. "resources": [test_resource_id],
  842. "scopes": [test_scope_id],
  843. },
  844. )
  845. assert err.match('409: b\'{"error":"Policy with name')
  846. assert admin.create_client_authz_scope_based_permission(
  847. client_id=auth_client_id,
  848. payload={
  849. "name": "test-permission-sb",
  850. "resources": [test_resource_id],
  851. "scopes": [test_scope_id],
  852. },
  853. skip_exists=True,
  854. ) == {"msg": "Already exists"}
  855. assert len(admin.get_client_authz_permissions(client_id=auth_client_id)) == 3
  856. # Test service account user
  857. res = admin.get_client_service_account_user(client_id=auth_client_id)
  858. assert res["username"] == "service-account-authz-client", res
  859. with pytest.raises(KeycloakGetError) as err:
  860. admin.get_client_service_account_user(client_id=client_id)
  861. assert err.match('400: b\'{"error":"unknown_error"}\'')
  862. # Test delete client
  863. res = admin.delete_client(client_id=auth_client_id)
  864. assert res == dict(), res
  865. with pytest.raises(KeycloakDeleteError) as err:
  866. admin.delete_client(client_id=auth_client_id)
  867. assert err.match('404: b\'{"error":"Could not find client"}\'')
  868. # Test client credentials
  869. admin.create_client(
  870. payload={
  871. "name": "test-confidential",
  872. "enabled": True,
  873. "protocol": "openid-connect",
  874. "publicClient": False,
  875. "redirectUris": ["http://localhost/*"],
  876. "webOrigins": ["+"],
  877. "clientId": "test-confidential",
  878. "secret": "test-secret",
  879. "clientAuthenticatorType": "client-secret",
  880. }
  881. )
  882. with pytest.raises(KeycloakGetError) as err:
  883. admin.get_client_secrets(client_id="does-not-exist")
  884. assert err.match('404: b\'{"error":"Could not find client"}\'')
  885. secrets = admin.get_client_secrets(
  886. client_id=admin.get_client_id(client_id="test-confidential")
  887. )
  888. assert secrets == {"type": "secret", "value": "test-secret"}
  889. with pytest.raises(KeycloakPostError) as err:
  890. admin.generate_client_secrets(client_id="does-not-exist")
  891. assert err.match('404: b\'{"error":"Could not find client"}\'')
  892. res = admin.generate_client_secrets(
  893. client_id=admin.get_client_id(client_id="test-confidential")
  894. )
  895. assert res
  896. assert (
  897. admin.get_client_secrets(client_id=admin.get_client_id(client_id="test-confidential"))
  898. == res
  899. )
  900. def test_realm_roles(admin: KeycloakAdmin, realm: str):
  901. """Test realm roles.
  902. :param admin: Keycloak Admin client
  903. :type admin: KeycloakAdmin
  904. :param realm: Keycloak realm
  905. :type realm: str
  906. """
  907. admin.realm_name = realm
  908. # Test get realm roles
  909. roles = admin.get_realm_roles()
  910. assert len(roles) == 3, roles
  911. role_names = [x["name"] for x in roles]
  912. assert "uma_authorization" in role_names, role_names
  913. assert "offline_access" in role_names, role_names
  914. # Test get realm roles with search text
  915. searched_roles = admin.get_realm_roles(search_text="uma_a")
  916. searched_role_names = [x["name"] for x in searched_roles]
  917. assert "uma_authorization" in searched_role_names, searched_role_names
  918. assert "offline_access" not in searched_role_names, searched_role_names
  919. # Test empty members
  920. with pytest.raises(KeycloakGetError) as err:
  921. admin.get_realm_role_members(role_name="does-not-exist")
  922. assert err.match('404: b\'{"error":"Could not find role"}\'')
  923. members = admin.get_realm_role_members(role_name="offline_access")
  924. assert members == list(), members
  925. # Test create realm role
  926. role_id = admin.create_realm_role(payload={"name": "test-realm-role"}, skip_exists=True)
  927. assert role_id, role_id
  928. with pytest.raises(KeycloakPostError) as err:
  929. admin.create_realm_role(payload={"name": "test-realm-role"})
  930. assert err.match('409: b\'{"errorMessage":"Role with name test-realm-role already exists"}\'')
  931. role_id_2 = admin.create_realm_role(payload={"name": "test-realm-role"}, skip_exists=True)
  932. assert role_id == role_id_2
  933. # Test update realm role
  934. res = admin.update_realm_role(
  935. role_name="test-realm-role", payload={"name": "test-realm-role-update"}
  936. )
  937. assert res == dict(), res
  938. with pytest.raises(KeycloakPutError) as err:
  939. admin.update_realm_role(
  940. role_name="test-realm-role", payload={"name": "test-realm-role-update"}
  941. )
  942. assert err.match('404: b\'{"error":"Could not find role"}\''), err
  943. # Test realm role user assignment
  944. user_id = admin.create_user(payload={"username": "role-testing", "email": "test@test.test"})
  945. with pytest.raises(KeycloakPostError) as err:
  946. admin.assign_realm_roles(user_id=user_id, roles=["bad"])
  947. assert err.match('b\'{"error":"unknown_error"}\''), err
  948. res = admin.assign_realm_roles(
  949. user_id=user_id,
  950. roles=[
  951. admin.get_realm_role(role_name="offline_access"),
  952. admin.get_realm_role(role_name="test-realm-role-update"),
  953. ],
  954. )
  955. assert res == dict(), res
  956. assert admin.get_user(user_id=user_id)["username"] in [
  957. x["username"] for x in admin.get_realm_role_members(role_name="offline_access")
  958. ]
  959. assert admin.get_user(user_id=user_id)["username"] in [
  960. x["username"] for x in admin.get_realm_role_members(role_name="test-realm-role-update")
  961. ]
  962. roles = admin.get_realm_roles_of_user(user_id=user_id)
  963. assert len(roles) == 3
  964. assert "offline_access" in [x["name"] for x in roles]
  965. assert "test-realm-role-update" in [x["name"] for x in roles]
  966. with pytest.raises(KeycloakDeleteError) as err:
  967. admin.delete_realm_roles_of_user(user_id=user_id, roles=["bad"])
  968. assert err.match('b\'{"error":"unknown_error"}\''), err
  969. res = admin.delete_realm_roles_of_user(
  970. user_id=user_id, roles=[admin.get_realm_role(role_name="offline_access")]
  971. )
  972. assert res == dict(), res
  973. assert admin.get_realm_role_members(role_name="offline_access") == list()
  974. roles = admin.get_realm_roles_of_user(user_id=user_id)
  975. assert len(roles) == 2
  976. assert "offline_access" not in [x["name"] for x in roles]
  977. assert "test-realm-role-update" in [x["name"] for x in roles]
  978. roles = admin.get_available_realm_roles_of_user(user_id=user_id)
  979. assert len(roles) == 2
  980. assert "offline_access" in [x["name"] for x in roles]
  981. assert "uma_authorization" in [x["name"] for x in roles]
  982. # Test realm role group assignment
  983. group_id = admin.create_group(payload={"name": "test-group"})
  984. with pytest.raises(KeycloakPostError) as err:
  985. admin.assign_group_realm_roles(group_id=group_id, roles=["bad"])
  986. assert err.match('b\'{"error":"unknown_error"}\''), err
  987. res = admin.assign_group_realm_roles(
  988. group_id=group_id,
  989. roles=[
  990. admin.get_realm_role(role_name="offline_access"),
  991. admin.get_realm_role(role_name="test-realm-role-update"),
  992. ],
  993. )
  994. assert res == dict(), res
  995. roles = admin.get_group_realm_roles(group_id=group_id)
  996. assert len(roles) == 2
  997. assert "offline_access" in [x["name"] for x in roles]
  998. assert "test-realm-role-update" in [x["name"] for x in roles]
  999. with pytest.raises(KeycloakDeleteError) as err:
  1000. admin.delete_group_realm_roles(group_id=group_id, roles=["bad"])
  1001. assert err.match('b\'{"error":"unknown_error"}\''), err
  1002. res = admin.delete_group_realm_roles(
  1003. group_id=group_id, roles=[admin.get_realm_role(role_name="offline_access")]
  1004. )
  1005. assert res == dict(), res
  1006. roles = admin.get_group_realm_roles(group_id=group_id)
  1007. assert len(roles) == 1
  1008. assert "test-realm-role-update" in [x["name"] for x in roles]
  1009. # Test composite realm roles
  1010. composite_role = admin.create_realm_role(payload={"name": "test-composite-role"})
  1011. with pytest.raises(KeycloakPostError) as err:
  1012. admin.add_composite_realm_roles_to_role(role_name=composite_role, roles=["bad"])
  1013. assert err.match('b\'{"error":"unknown_error"}\''), err
  1014. res = admin.add_composite_realm_roles_to_role(
  1015. role_name=composite_role, roles=[admin.get_realm_role(role_name="test-realm-role-update")]
  1016. )
  1017. assert res == dict(), res
  1018. res = admin.get_composite_realm_roles_of_role(role_name=composite_role)
  1019. assert len(res) == 1
  1020. assert "test-realm-role-update" in res[0]["name"]
  1021. with pytest.raises(KeycloakGetError) as err:
  1022. admin.get_composite_realm_roles_of_role(role_name="bad")
  1023. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1024. res = admin.get_composite_realm_roles_of_user(user_id=user_id)
  1025. assert len(res) == 4
  1026. assert "offline_access" in {x["name"] for x in res}
  1027. assert "test-realm-role-update" in {x["name"] for x in res}
  1028. assert "uma_authorization" in {x["name"] for x in res}
  1029. with pytest.raises(KeycloakGetError) as err:
  1030. admin.get_composite_realm_roles_of_user(user_id="bad")
  1031. assert err.match('b\'{"error":"User not found"}\''), err
  1032. with pytest.raises(KeycloakDeleteError) as err:
  1033. admin.remove_composite_realm_roles_to_role(role_name=composite_role, roles=["bad"])
  1034. assert err.match('b\'{"error":"unknown_error"}\''), err
  1035. res = admin.remove_composite_realm_roles_to_role(
  1036. role_name=composite_role, roles=[admin.get_realm_role(role_name="test-realm-role-update")]
  1037. )
  1038. assert res == dict(), res
  1039. res = admin.get_composite_realm_roles_of_role(role_name=composite_role)
  1040. assert len(res) == 0
  1041. # Test delete realm role
  1042. res = admin.delete_realm_role(role_name=composite_role)
  1043. assert res == dict(), res
  1044. with pytest.raises(KeycloakDeleteError) as err:
  1045. admin.delete_realm_role(role_name=composite_role)
  1046. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1047. @pytest.mark.parametrize(
  1048. "testcase, arg_brief_repr, includes_attributes",
  1049. [
  1050. ("brief True", {"brief_representation": True}, False),
  1051. ("brief False", {"brief_representation": False}, True),
  1052. ("default", {}, False),
  1053. ],
  1054. )
  1055. def test_role_attributes(
  1056. admin: KeycloakAdmin,
  1057. realm: str,
  1058. client: str,
  1059. arg_brief_repr: dict,
  1060. includes_attributes: bool,
  1061. testcase: str,
  1062. ):
  1063. """Test getting role attributes for bulk calls.
  1064. :param admin: Keycloak admin
  1065. :type admin: KeycloakAdmin
  1066. :param realm: Keycloak realm
  1067. :type realm: str
  1068. :param client: Keycloak client
  1069. :type client: str
  1070. :param arg_brief_repr: Brief representation
  1071. :type arg_brief_repr: dict
  1072. :param includes_attributes: Indicator whether to include attributes
  1073. :type includes_attributes: bool
  1074. :param testcase: Test case
  1075. :type testcase: str
  1076. """
  1077. # setup
  1078. attribute_role = "test-realm-role-w-attr"
  1079. test_attrs = {"attr1": ["val1"], "attr2": ["val2-1", "val2-2"]}
  1080. role_id = admin.create_realm_role(
  1081. payload={"name": attribute_role, "attributes": test_attrs}, skip_exists=True
  1082. )
  1083. assert role_id, role_id
  1084. cli_role_id = admin.create_client_role(
  1085. client, payload={"name": attribute_role, "attributes": test_attrs}, skip_exists=True
  1086. )
  1087. assert cli_role_id, cli_role_id
  1088. if not includes_attributes:
  1089. test_attrs = None
  1090. # tests
  1091. roles = admin.get_realm_roles(**arg_brief_repr)
  1092. roles_filtered = [role for role in roles if role["name"] == role_id]
  1093. assert roles_filtered, roles_filtered
  1094. role = roles_filtered[0]
  1095. assert role.get("attributes") == test_attrs, testcase
  1096. roles = admin.get_client_roles(client, **arg_brief_repr)
  1097. roles_filtered = [role for role in roles if role["name"] == cli_role_id]
  1098. assert roles_filtered, roles_filtered
  1099. role = roles_filtered[0]
  1100. assert role.get("attributes") == test_attrs, testcase
  1101. # cleanup
  1102. res = admin.delete_realm_role(role_name=attribute_role)
  1103. assert res == dict(), res
  1104. res = admin.delete_client_role(client, role_name=attribute_role)
  1105. assert res == dict(), res
  1106. def test_client_scope_realm_roles(admin: KeycloakAdmin, realm: str):
  1107. """Test client realm roles.
  1108. :param admin: Keycloak admin
  1109. :type admin: KeycloakAdmin
  1110. :param realm: Keycloak realm
  1111. :type realm: str
  1112. """
  1113. admin.realm_name = realm
  1114. # Test get realm roles
  1115. roles = admin.get_realm_roles()
  1116. assert len(roles) == 3, roles
  1117. role_names = [x["name"] for x in roles]
  1118. assert "uma_authorization" in role_names, role_names
  1119. assert "offline_access" in role_names, role_names
  1120. # create realm role for test
  1121. role_id = admin.create_realm_role(payload={"name": "test-realm-role"}, skip_exists=True)
  1122. assert role_id, role_id
  1123. # Test realm role client assignment
  1124. client_id = admin.create_client(
  1125. payload={"name": "role-testing-client", "clientId": "role-testing-client"}
  1126. )
  1127. with pytest.raises(KeycloakPostError) as err:
  1128. admin.assign_realm_roles_to_client_scope(client_id=client_id, roles=["bad"])
  1129. assert err.match('b\'{"error":"unknown_error"}\''), err
  1130. res = admin.assign_realm_roles_to_client_scope(
  1131. client_id=client_id,
  1132. roles=[
  1133. admin.get_realm_role(role_name="offline_access"),
  1134. admin.get_realm_role(role_name="test-realm-role"),
  1135. ],
  1136. )
  1137. assert res == dict(), res
  1138. roles = admin.get_realm_roles_of_client_scope(client_id=client_id)
  1139. assert len(roles) == 2
  1140. client_role_names = [x["name"] for x in roles]
  1141. assert "offline_access" in client_role_names, client_role_names
  1142. assert "test-realm-role" in client_role_names, client_role_names
  1143. assert "uma_authorization" not in client_role_names, client_role_names
  1144. # Test remove realm role of client
  1145. with pytest.raises(KeycloakDeleteError) as err:
  1146. admin.delete_realm_roles_of_client_scope(client_id=client_id, roles=["bad"])
  1147. assert err.match('b\'{"error":"unknown_error"}\''), err
  1148. res = admin.delete_realm_roles_of_client_scope(
  1149. client_id=client_id, roles=[admin.get_realm_role(role_name="offline_access")]
  1150. )
  1151. assert res == dict(), res
  1152. roles = admin.get_realm_roles_of_client_scope(client_id=client_id)
  1153. assert len(roles) == 1
  1154. assert "test-realm-role" in [x["name"] for x in roles]
  1155. res = admin.delete_realm_roles_of_client_scope(
  1156. client_id=client_id, roles=[admin.get_realm_role(role_name="test-realm-role")]
  1157. )
  1158. assert res == dict(), res
  1159. roles = admin.get_realm_roles_of_client_scope(client_id=client_id)
  1160. assert len(roles) == 0
  1161. def test_client_scope_client_roles(admin: KeycloakAdmin, realm: str, client: str):
  1162. """Test client assignment of other client roles.
  1163. :param admin: Keycloak admin
  1164. :type admin: KeycloakAdmin
  1165. :param realm: Keycloak realm
  1166. :type realm: str
  1167. :param client: Keycloak client
  1168. :type client: str
  1169. """
  1170. admin.realm_name = realm
  1171. client_id = admin.create_client(
  1172. payload={"name": "role-testing-client", "clientId": "role-testing-client"}
  1173. )
  1174. # Test get client roles
  1175. roles = admin.get_client_roles_of_client_scope(client_id, client)
  1176. assert len(roles) == 0, roles
  1177. # create client role for test
  1178. client_role_id = admin.create_client_role(
  1179. client_role_id=client, payload={"name": "client-role-test"}, skip_exists=True
  1180. )
  1181. assert client_role_id, client_role_id
  1182. # Test client role assignment to other client
  1183. with pytest.raises(KeycloakPostError) as err:
  1184. admin.assign_client_roles_to_client_scope(
  1185. client_id=client_id, client_roles_owner_id=client, roles=["bad"]
  1186. )
  1187. assert err.match('b\'{"error":"unknown_error"}\''), err
  1188. res = admin.assign_client_roles_to_client_scope(
  1189. client_id=client_id,
  1190. client_roles_owner_id=client,
  1191. roles=[admin.get_client_role(client_id=client, role_name="client-role-test")],
  1192. )
  1193. assert res == dict(), res
  1194. roles = admin.get_client_roles_of_client_scope(
  1195. client_id=client_id, client_roles_owner_id=client
  1196. )
  1197. assert len(roles) == 1
  1198. client_role_names = [x["name"] for x in roles]
  1199. assert "client-role-test" in client_role_names, client_role_names
  1200. # Test remove realm role of client
  1201. with pytest.raises(KeycloakDeleteError) as err:
  1202. admin.delete_client_roles_of_client_scope(
  1203. client_id=client_id, client_roles_owner_id=client, roles=["bad"]
  1204. )
  1205. assert err.match('b\'{"error":"unknown_error"}\''), err
  1206. res = admin.delete_client_roles_of_client_scope(
  1207. client_id=client_id,
  1208. client_roles_owner_id=client,
  1209. roles=[admin.get_client_role(client_id=client, role_name="client-role-test")],
  1210. )
  1211. assert res == dict(), res
  1212. roles = admin.get_client_roles_of_client_scope(
  1213. client_id=client_id, client_roles_owner_id=client
  1214. )
  1215. assert len(roles) == 0
  1216. def test_client_default_client_scopes(admin: KeycloakAdmin, realm: str, client: str):
  1217. """Test client assignment of default client scopes.
  1218. :param admin: Keycloak admin
  1219. :type admin: KeycloakAdmin
  1220. :param realm: Keycloak realm
  1221. :type realm: str
  1222. :param client: Keycloak client
  1223. :type client: str
  1224. """
  1225. admin.realm_name = realm
  1226. client_id = admin.create_client(
  1227. payload={"name": "role-testing-client", "clientId": "role-testing-client"}
  1228. )
  1229. # Test get client default scopes
  1230. # keycloak default roles: web-origins, acr, profile, roles, email
  1231. default_client_scopes = admin.get_client_default_client_scopes(client_id)
  1232. assert len(default_client_scopes) == 5, default_client_scopes
  1233. # Test add a client scope to client default scopes
  1234. default_client_scope = "test-client-default-scope"
  1235. new_client_scope = {
  1236. "name": default_client_scope,
  1237. "description": f"Test Client Scope: {default_client_scope}",
  1238. "protocol": "openid-connect",
  1239. "attributes": {},
  1240. }
  1241. new_client_scope_id = admin.create_client_scope(new_client_scope, skip_exists=False)
  1242. new_default_client_scope_data = {
  1243. "realm": realm,
  1244. "client": client_id,
  1245. "clientScopeId": new_client_scope_id,
  1246. }
  1247. admin.add_client_default_client_scope(
  1248. client_id, new_client_scope_id, new_default_client_scope_data
  1249. )
  1250. default_client_scopes = admin.get_client_default_client_scopes(client_id)
  1251. assert len(default_client_scopes) == 6, default_client_scopes
  1252. # Test remove a client default scope
  1253. admin.delete_client_default_client_scope(client_id, new_client_scope_id)
  1254. default_client_scopes = admin.get_client_default_client_scopes(client_id)
  1255. assert len(default_client_scopes) == 5, default_client_scopes
  1256. def test_client_optional_client_scopes(admin: KeycloakAdmin, realm: str, client: str):
  1257. """Test client assignment of optional client scopes.
  1258. :param admin: Keycloak admin
  1259. :type admin: KeycloakAdmin
  1260. :param realm: Keycloak realm
  1261. :type realm: str
  1262. :param client: Keycloak client
  1263. :type client: str
  1264. """
  1265. admin.realm_name = realm
  1266. client_id = admin.create_client(
  1267. payload={"name": "role-testing-client", "clientId": "role-testing-client"}
  1268. )
  1269. # Test get client optional scopes
  1270. # keycloak optional roles: microprofile-jwt, offline_access, address, phone
  1271. optional_client_scopes = admin.get_client_optional_client_scopes(client_id)
  1272. assert len(optional_client_scopes) == 4, optional_client_scopes
  1273. # Test add a client scope to client optional scopes
  1274. optional_client_scope = "test-client-optional-scope"
  1275. new_client_scope = {
  1276. "name": optional_client_scope,
  1277. "description": f"Test Client Scope: {optional_client_scope}",
  1278. "protocol": "openid-connect",
  1279. "attributes": {},
  1280. }
  1281. new_client_scope_id = admin.create_client_scope(new_client_scope, skip_exists=False)
  1282. new_optional_client_scope_data = {
  1283. "realm": realm,
  1284. "client": client_id,
  1285. "clientScopeId": new_client_scope_id,
  1286. }
  1287. admin.add_client_optional_client_scope(
  1288. client_id, new_client_scope_id, new_optional_client_scope_data
  1289. )
  1290. optional_client_scopes = admin.get_client_optional_client_scopes(client_id)
  1291. assert len(optional_client_scopes) == 5, optional_client_scopes
  1292. # Test remove a client optional scope
  1293. admin.delete_client_optional_client_scope(client_id, new_client_scope_id)
  1294. optional_client_scopes = admin.get_client_optional_client_scopes(client_id)
  1295. assert len(optional_client_scopes) == 4, optional_client_scopes
  1296. def test_client_roles(admin: KeycloakAdmin, client: str):
  1297. """Test client roles.
  1298. :param admin: Keycloak Admin client
  1299. :type admin: KeycloakAdmin
  1300. :param client: Keycloak client
  1301. :type client: str
  1302. """
  1303. # Test get client roles
  1304. res = admin.get_client_roles(client_id=client)
  1305. assert len(res) == 0
  1306. with pytest.raises(KeycloakGetError) as err:
  1307. admin.get_client_roles(client_id="bad")
  1308. assert err.match('404: b\'{"error":"Could not find client"}\'')
  1309. # Test create client role
  1310. client_role_id = admin.create_client_role(
  1311. client_role_id=client, payload={"name": "client-role-test"}, skip_exists=True
  1312. )
  1313. with pytest.raises(KeycloakPostError) as err:
  1314. admin.create_client_role(client_role_id=client, payload={"name": "client-role-test"})
  1315. assert err.match('409: b\'{"errorMessage":"Role with name client-role-test already exists"}\'')
  1316. client_role_id_2 = admin.create_client_role(
  1317. client_role_id=client, payload={"name": "client-role-test"}, skip_exists=True
  1318. )
  1319. assert client_role_id == client_role_id_2
  1320. # Test get client role
  1321. res = admin.get_client_role(client_id=client, role_name="client-role-test")
  1322. assert res["name"] == client_role_id
  1323. with pytest.raises(KeycloakGetError) as err:
  1324. admin.get_client_role(client_id=client, role_name="bad")
  1325. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1326. res_ = admin.get_client_role_id(client_id=client, role_name="client-role-test")
  1327. assert res_ == res["id"]
  1328. with pytest.raises(KeycloakGetError) as err:
  1329. admin.get_client_role_id(client_id=client, role_name="bad")
  1330. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1331. assert len(admin.get_client_roles(client_id=client)) == 1
  1332. # Test update client role
  1333. res = admin.update_client_role(
  1334. client_role_id=client,
  1335. role_name="client-role-test",
  1336. payload={"name": "client-role-test-update"},
  1337. )
  1338. assert res == dict()
  1339. with pytest.raises(KeycloakPutError) as err:
  1340. res = admin.update_client_role(
  1341. client_role_id=client,
  1342. role_name="client-role-test",
  1343. payload={"name": "client-role-test-update"},
  1344. )
  1345. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1346. # Test user with client role
  1347. res = admin.get_client_role_members(client_id=client, role_name="client-role-test-update")
  1348. assert len(res) == 0
  1349. with pytest.raises(KeycloakGetError) as err:
  1350. admin.get_client_role_members(client_id=client, role_name="bad")
  1351. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1352. user_id = admin.create_user(payload={"username": "test", "email": "test@test.test"})
  1353. with pytest.raises(KeycloakPostError) as err:
  1354. admin.assign_client_role(user_id=user_id, client_id=client, roles=["bad"])
  1355. assert err.match('b\'{"error":"unknown_error"}\''), err
  1356. res = admin.assign_client_role(
  1357. user_id=user_id,
  1358. client_id=client,
  1359. roles=[admin.get_client_role(client_id=client, role_name="client-role-test-update")],
  1360. )
  1361. assert res == dict()
  1362. assert (
  1363. len(admin.get_client_role_members(client_id=client, role_name="client-role-test-update"))
  1364. == 1
  1365. )
  1366. roles = admin.get_client_roles_of_user(user_id=user_id, client_id=client)
  1367. assert len(roles) == 1, roles
  1368. with pytest.raises(KeycloakGetError) as err:
  1369. admin.get_client_roles_of_user(user_id=user_id, client_id="bad")
  1370. assert err.match('404: b\'{"error":"Client not found"}\'')
  1371. roles = admin.get_composite_client_roles_of_user(user_id=user_id, client_id=client)
  1372. assert len(roles) == 1, roles
  1373. with pytest.raises(KeycloakGetError) as err:
  1374. admin.get_composite_client_roles_of_user(user_id=user_id, client_id="bad")
  1375. assert err.match('404: b\'{"error":"Client not found"}\'')
  1376. roles = admin.get_available_client_roles_of_user(user_id=user_id, client_id=client)
  1377. assert len(roles) == 0, roles
  1378. with pytest.raises(KeycloakGetError) as err:
  1379. admin.get_composite_client_roles_of_user(user_id=user_id, client_id="bad")
  1380. assert err.match('404: b\'{"error":"Client not found"}\'')
  1381. with pytest.raises(KeycloakDeleteError) as err:
  1382. admin.delete_client_roles_of_user(user_id=user_id, client_id=client, roles=["bad"])
  1383. assert err.match('b\'{"error":"unknown_error"}\''), err
  1384. admin.delete_client_roles_of_user(
  1385. user_id=user_id,
  1386. client_id=client,
  1387. roles=[admin.get_client_role(client_id=client, role_name="client-role-test-update")],
  1388. )
  1389. assert len(admin.get_client_roles_of_user(user_id=user_id, client_id=client)) == 0
  1390. # Test groups and client roles
  1391. res = admin.get_client_role_groups(client_id=client, role_name="client-role-test-update")
  1392. assert len(res) == 0
  1393. with pytest.raises(KeycloakGetError) as err:
  1394. admin.get_client_role_groups(client_id=client, role_name="bad")
  1395. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1396. group_id = admin.create_group(payload={"name": "test-group"})
  1397. res = admin.get_group_client_roles(group_id=group_id, client_id=client)
  1398. assert len(res) == 0
  1399. with pytest.raises(KeycloakGetError) as err:
  1400. admin.get_group_client_roles(group_id=group_id, client_id="bad")
  1401. assert err.match('404: b\'{"error":"Client not found"}\'')
  1402. with pytest.raises(KeycloakPostError) as err:
  1403. admin.assign_group_client_roles(group_id=group_id, client_id=client, roles=["bad"])
  1404. assert err.match('b\'{"error":"unknown_error"}\''), err
  1405. res = admin.assign_group_client_roles(
  1406. group_id=group_id,
  1407. client_id=client,
  1408. roles=[admin.get_client_role(client_id=client, role_name="client-role-test-update")],
  1409. )
  1410. assert res == dict()
  1411. assert (
  1412. len(admin.get_client_role_groups(client_id=client, role_name="client-role-test-update"))
  1413. == 1
  1414. )
  1415. assert len(admin.get_group_client_roles(group_id=group_id, client_id=client)) == 1
  1416. with pytest.raises(KeycloakDeleteError) as err:
  1417. admin.delete_group_client_roles(group_id=group_id, client_id=client, roles=["bad"])
  1418. assert err.match('b\'{"error":"unknown_error"}\''), err
  1419. res = admin.delete_group_client_roles(
  1420. group_id=group_id,
  1421. client_id=client,
  1422. roles=[admin.get_client_role(client_id=client, role_name="client-role-test-update")],
  1423. )
  1424. assert res == dict()
  1425. # Test composite client roles
  1426. with pytest.raises(KeycloakPostError) as err:
  1427. admin.add_composite_client_roles_to_role(
  1428. client_role_id=client, role_name="client-role-test-update", roles=["bad"]
  1429. )
  1430. assert err.match('b\'{"error":"unknown_error"}\''), err
  1431. res = admin.add_composite_client_roles_to_role(
  1432. client_role_id=client,
  1433. role_name="client-role-test-update",
  1434. roles=[admin.get_realm_role(role_name="offline_access")],
  1435. )
  1436. assert res == dict()
  1437. assert admin.get_client_role(client_id=client, role_name="client-role-test-update")[
  1438. "composite"
  1439. ]
  1440. # Test delete of client role
  1441. res = admin.delete_client_role(client_role_id=client, role_name="client-role-test-update")
  1442. assert res == dict()
  1443. with pytest.raises(KeycloakDeleteError) as err:
  1444. admin.delete_client_role(client_role_id=client, role_name="client-role-test-update")
  1445. assert err.match('404: b\'{"error":"Could not find role"}\'')
  1446. def test_enable_token_exchange(admin: KeycloakAdmin, realm: str):
  1447. """Test enable token exchange.
  1448. :param admin: Keycloak Admin client
  1449. :type admin: KeycloakAdmin
  1450. :param realm: Keycloak realm
  1451. :type realm: str
  1452. :raises AssertionError: In case of bad configuration
  1453. """
  1454. # Test enabling token exchange between two confidential clients
  1455. admin.realm_name = realm
  1456. # Create test clients
  1457. source_client_id = admin.create_client(
  1458. payload={"name": "Source Client", "clientId": "source-client"}
  1459. )
  1460. target_client_id = admin.create_client(
  1461. payload={"name": "Target Client", "clientId": "target-client"}
  1462. )
  1463. for c in admin.get_clients():
  1464. if c["clientId"] == "realm-management":
  1465. realm_management_id = c["id"]
  1466. break
  1467. else:
  1468. raise AssertionError("Missing realm management client")
  1469. # Enable permissions on the Superset client
  1470. admin.update_client_management_permissions(
  1471. payload={"enabled": True}, client_id=target_client_id
  1472. )
  1473. # Fetch various IDs and strings needed when creating the permission
  1474. token_exchange_permission_id = admin.get_client_management_permissions(
  1475. client_id=target_client_id
  1476. )["scopePermissions"]["token-exchange"]
  1477. scopes = admin.get_client_authz_policy_scopes(
  1478. client_id=realm_management_id, policy_id=token_exchange_permission_id
  1479. )
  1480. for s in scopes:
  1481. if s["name"] == "token-exchange":
  1482. token_exchange_scope_id = s["id"]
  1483. break
  1484. else:
  1485. raise AssertionError("Missing token-exchange scope")
  1486. resources = admin.get_client_authz_policy_resources(
  1487. client_id=realm_management_id, policy_id=token_exchange_permission_id
  1488. )
  1489. for r in resources:
  1490. if r["name"] == f"client.resource.{target_client_id}":
  1491. token_exchange_resource_id = r["_id"]
  1492. break
  1493. else:
  1494. raise AssertionError("Missing client resource")
  1495. # Create a client policy for source client
  1496. policy_name = "Exchange source client token with target client token"
  1497. client_policy_id = admin.create_client_authz_client_policy(
  1498. payload={
  1499. "type": "client",
  1500. "logic": "POSITIVE",
  1501. "decisionStrategy": "UNANIMOUS",
  1502. "name": policy_name,
  1503. "clients": [source_client_id],
  1504. },
  1505. client_id=realm_management_id,
  1506. )["id"]
  1507. policies = admin.get_client_authz_client_policies(client_id=realm_management_id)
  1508. for policy in policies:
  1509. if policy["name"] == policy_name:
  1510. assert policy["clients"] == [source_client_id]
  1511. break
  1512. else:
  1513. raise AssertionError("Missing client policy")
  1514. # Update permissions on the target client to reference this policy
  1515. permission_name = admin.get_client_authz_scope_permission(
  1516. client_id=realm_management_id, scope_id=token_exchange_permission_id
  1517. )["name"]
  1518. admin.update_client_authz_scope_permission(
  1519. payload={
  1520. "id": token_exchange_permission_id,
  1521. "name": permission_name,
  1522. "type": "scope",
  1523. "logic": "POSITIVE",
  1524. "decisionStrategy": "UNANIMOUS",
  1525. "resources": [token_exchange_resource_id],
  1526. "scopes": [token_exchange_scope_id],
  1527. "policies": [client_policy_id],
  1528. },
  1529. client_id=realm_management_id,
  1530. scope_id=token_exchange_permission_id,
  1531. )
  1532. def test_email(admin: KeycloakAdmin, user: str):
  1533. """Test email.
  1534. :param admin: Keycloak Admin client
  1535. :type admin: KeycloakAdmin
  1536. :param user: Keycloak user
  1537. :type user: str
  1538. """
  1539. # Emails will fail as we don't have SMTP test setup
  1540. with pytest.raises(KeycloakPutError) as err:
  1541. admin.send_update_account(user_id=user, payload=dict())
  1542. assert err.match('b\'{"error":"unknown_error"}\''), err
  1543. admin.update_user(user_id=user, payload={"enabled": True})
  1544. with pytest.raises(KeycloakPutError) as err:
  1545. admin.send_verify_email(user_id=user)
  1546. assert err.match('500: b\'{"errorMessage":"Failed to send execute actions email"}\'')
  1547. def test_get_sessions(admin: KeycloakAdmin):
  1548. """Test get sessions.
  1549. :param admin: Keycloak Admin client
  1550. :type admin: KeycloakAdmin
  1551. """
  1552. sessions = admin.get_sessions(user_id=admin.get_user_id(username=admin.username))
  1553. assert len(sessions) >= 1
  1554. with pytest.raises(KeycloakGetError) as err:
  1555. admin.get_sessions(user_id="bad")
  1556. assert err.match('404: b\'{"error":"User not found"}\'')
  1557. def test_get_client_installation_provider(admin: KeycloakAdmin, client: str):
  1558. """Test get client installation provider.
  1559. :param admin: Keycloak Admin client
  1560. :type admin: KeycloakAdmin
  1561. :param client: Keycloak client
  1562. :type client: str
  1563. """
  1564. with pytest.raises(KeycloakGetError) as err:
  1565. admin.get_client_installation_provider(client_id=client, provider_id="bad")
  1566. assert err.match('404: b\'{"error":"Unknown Provider"}\'')
  1567. installation = admin.get_client_installation_provider(
  1568. client_id=client, provider_id="keycloak-oidc-keycloak-json"
  1569. )
  1570. assert set(installation.keys()) == {
  1571. "auth-server-url",
  1572. "confidential-port",
  1573. "credentials",
  1574. "realm",
  1575. "resource",
  1576. "ssl-required",
  1577. }
  1578. def test_auth_flows(admin: KeycloakAdmin, realm: str):
  1579. """Test auth flows.
  1580. :param admin: Keycloak Admin client
  1581. :type admin: KeycloakAdmin
  1582. :param realm: Keycloak realm
  1583. :type realm: str
  1584. """
  1585. admin.realm_name = realm
  1586. res = admin.get_authentication_flows()
  1587. assert len(res) == 8, res
  1588. assert set(res[0].keys()) == {
  1589. "alias",
  1590. "authenticationExecutions",
  1591. "builtIn",
  1592. "description",
  1593. "id",
  1594. "providerId",
  1595. "topLevel",
  1596. }
  1597. assert {x["alias"] for x in res} == {
  1598. "reset credentials",
  1599. "browser",
  1600. "http challenge",
  1601. "registration",
  1602. "docker auth",
  1603. "direct grant",
  1604. "first broker login",
  1605. "clients",
  1606. }
  1607. with pytest.raises(KeycloakGetError) as err:
  1608. admin.get_authentication_flow_for_id(flow_id="bad")
  1609. assert err.match('404: b\'{"error":"Could not find flow with id"}\'')
  1610. browser_flow_id = [x for x in res if x["alias"] == "browser"][0]["id"]
  1611. res = admin.get_authentication_flow_for_id(flow_id=browser_flow_id)
  1612. assert res["alias"] == "browser"
  1613. # Test copying
  1614. with pytest.raises(KeycloakPostError) as err:
  1615. admin.copy_authentication_flow(payload=dict(), flow_alias="bad")
  1616. assert err.match("404: b''")
  1617. res = admin.copy_authentication_flow(payload={"newName": "test-browser"}, flow_alias="browser")
  1618. assert res == b"", res
  1619. assert len(admin.get_authentication_flows()) == 9
  1620. # Test create
  1621. res = admin.create_authentication_flow(
  1622. payload={"alias": "test-create", "providerId": "basic-flow"}
  1623. )
  1624. assert res == b""
  1625. with pytest.raises(KeycloakPostError) as err:
  1626. admin.create_authentication_flow(payload={"alias": "test-create", "builtIn": False})
  1627. assert err.match('409: b\'{"errorMessage":"Flow test-create already exists"}\'')
  1628. assert admin.create_authentication_flow(
  1629. payload={"alias": "test-create"}, skip_exists=True
  1630. ) == {"msg": "Already exists"}
  1631. # Test flow executions
  1632. res = admin.get_authentication_flow_executions(flow_alias="browser")
  1633. assert len(res) == 8, res
  1634. with pytest.raises(KeycloakGetError) as err:
  1635. admin.get_authentication_flow_executions(flow_alias="bad")
  1636. assert err.match("404: b''")
  1637. exec_id = res[0]["id"]
  1638. res = admin.get_authentication_flow_execution(execution_id=exec_id)
  1639. assert set(res.keys()) == {
  1640. "alternative",
  1641. "authenticator",
  1642. "authenticatorFlow",
  1643. "conditional",
  1644. "disabled",
  1645. "enabled",
  1646. "id",
  1647. "parentFlow",
  1648. "priority",
  1649. "required",
  1650. "requirement",
  1651. }, res
  1652. with pytest.raises(KeycloakGetError) as err:
  1653. admin.get_authentication_flow_execution(execution_id="bad")
  1654. assert err.match('404: b\'{"error":"Illegal execution"}\'')
  1655. with pytest.raises(KeycloakPostError) as err:
  1656. admin.create_authentication_flow_execution(payload=dict(), flow_alias="browser")
  1657. assert err.match('400: b\'{"error":"It is illegal to add execution to a built in flow"}\'')
  1658. res = admin.create_authentication_flow_execution(
  1659. payload={"provider": "auth-cookie"}, flow_alias="test-create"
  1660. )
  1661. assert res == b""
  1662. assert len(admin.get_authentication_flow_executions(flow_alias="test-create")) == 1
  1663. with pytest.raises(KeycloakPutError) as err:
  1664. admin.update_authentication_flow_executions(
  1665. payload={"required": "yes"}, flow_alias="test-create"
  1666. )
  1667. assert err.match('400: b\'{"error":"Unrecognized field')
  1668. payload = admin.get_authentication_flow_executions(flow_alias="test-create")[0]
  1669. payload["displayName"] = "test"
  1670. res = admin.update_authentication_flow_executions(payload=payload, flow_alias="test-create")
  1671. assert res
  1672. exec_id = admin.get_authentication_flow_executions(flow_alias="test-create")[0]["id"]
  1673. res = admin.delete_authentication_flow_execution(execution_id=exec_id)
  1674. assert res == dict()
  1675. with pytest.raises(KeycloakDeleteError) as err:
  1676. admin.delete_authentication_flow_execution(execution_id=exec_id)
  1677. assert err.match('404: b\'{"error":"Illegal execution"}\'')
  1678. # Test subflows
  1679. res = admin.create_authentication_flow_subflow(
  1680. payload={
  1681. "alias": "test-subflow",
  1682. "provider": "basic-flow",
  1683. "type": "something",
  1684. "description": "something",
  1685. },
  1686. flow_alias="test-browser",
  1687. )
  1688. assert res == b""
  1689. with pytest.raises(KeycloakPostError) as err:
  1690. admin.create_authentication_flow_subflow(
  1691. payload={"alias": "test-subflow", "providerId": "basic-flow"},
  1692. flow_alias="test-browser",
  1693. )
  1694. assert err.match('409: b\'{"errorMessage":"New flow alias name already exists"}\'')
  1695. res = admin.create_authentication_flow_subflow(
  1696. payload={
  1697. "alias": "test-subflow",
  1698. "provider": "basic-flow",
  1699. "type": "something",
  1700. "description": "something",
  1701. },
  1702. flow_alias="test-create",
  1703. skip_exists=True,
  1704. )
  1705. assert res == {"msg": "Already exists"}
  1706. # Test delete auth flow
  1707. flow_id = [x for x in admin.get_authentication_flows() if x["alias"] == "test-browser"][0][
  1708. "id"
  1709. ]
  1710. res = admin.delete_authentication_flow(flow_id=flow_id)
  1711. assert res == dict()
  1712. with pytest.raises(KeycloakDeleteError) as err:
  1713. admin.delete_authentication_flow(flow_id=flow_id)
  1714. assert err.match('404: b\'{"error":"Could not find flow with id"}\'')
  1715. def test_authentication_configs(admin: KeycloakAdmin, realm: str):
  1716. """Test authentication configs.
  1717. :param admin: Keycloak Admin client
  1718. :type admin: KeycloakAdmin
  1719. :param realm: Keycloak realm
  1720. :type realm: str
  1721. """
  1722. admin.realm_name = realm
  1723. # Test list of auth providers
  1724. res = admin.get_authenticator_providers()
  1725. assert len(res) == 38
  1726. res = admin.get_authenticator_provider_config_description(provider_id="auth-cookie")
  1727. assert res == {
  1728. "helpText": "Validates the SSO cookie set by the auth server.",
  1729. "name": "Cookie",
  1730. "properties": [],
  1731. "providerId": "auth-cookie",
  1732. }
  1733. # Test authenticator config
  1734. # Currently unable to find a sustainable way to fetch the config id,
  1735. # therefore testing only failures
  1736. with pytest.raises(KeycloakGetError) as err:
  1737. admin.get_authenticator_config(config_id="bad")
  1738. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1739. with pytest.raises(KeycloakPutError) as err:
  1740. admin.update_authenticator_config(payload=dict(), config_id="bad")
  1741. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1742. with pytest.raises(KeycloakDeleteError) as err:
  1743. admin.delete_authenticator_config(config_id="bad")
  1744. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1745. def test_sync_users(admin: KeycloakAdmin, realm: str):
  1746. """Test sync users.
  1747. :param admin: Keycloak Admin client
  1748. :type admin: KeycloakAdmin
  1749. :param realm: Keycloak realm
  1750. :type realm: str
  1751. """
  1752. admin.realm_name = realm
  1753. # Only testing the error message
  1754. with pytest.raises(KeycloakPostError) as err:
  1755. admin.sync_users(storage_id="does-not-exist", action="triggerFullSync")
  1756. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1757. def test_client_scopes(admin: KeycloakAdmin, realm: str):
  1758. """Test client scopes.
  1759. :param admin: Keycloak Admin client
  1760. :type admin: KeycloakAdmin
  1761. :param realm: Keycloak realm
  1762. :type realm: str
  1763. """
  1764. admin.realm_name = realm
  1765. # Test get client scopes
  1766. res = admin.get_client_scopes()
  1767. scope_names = {x["name"] for x in res}
  1768. assert len(res) == 10
  1769. assert "email" in scope_names
  1770. assert "profile" in scope_names
  1771. assert "offline_access" in scope_names
  1772. with pytest.raises(KeycloakGetError) as err:
  1773. admin.get_client_scope(client_scope_id="does-not-exist")
  1774. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1775. scope = admin.get_client_scope(client_scope_id=res[0]["id"])
  1776. assert res[0] == scope
  1777. scope = admin.get_client_scope_by_name(client_scope_name=res[0]["name"])
  1778. assert res[0] == scope
  1779. # Test create client scope
  1780. res = admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=True)
  1781. assert res
  1782. res2 = admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=True)
  1783. assert res == res2
  1784. with pytest.raises(KeycloakPostError) as err:
  1785. admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=False)
  1786. assert err.match('409: b\'{"errorMessage":"Client Scope test-scope already exists"}\'')
  1787. # Test update client scope
  1788. with pytest.raises(KeycloakPutError) as err:
  1789. admin.update_client_scope(client_scope_id="does-not-exist", payload=dict())
  1790. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1791. res_update = admin.update_client_scope(
  1792. client_scope_id=res, payload={"name": "test-scope-update"}
  1793. )
  1794. assert res_update == dict()
  1795. admin.get_client_scope(client_scope_id=res)["name"] == "test-scope-update"
  1796. # Test get mappers
  1797. mappers = admin.get_mappers_from_client_scope(client_scope_id=res)
  1798. assert mappers == list()
  1799. # Test add mapper
  1800. with pytest.raises(KeycloakPostError) as err:
  1801. admin.add_mapper_to_client_scope(client_scope_id=res, payload=dict())
  1802. assert err.match('404: b\'{"error":"ProtocolMapper provider not found"}\'')
  1803. res_add = admin.add_mapper_to_client_scope(
  1804. client_scope_id=res,
  1805. payload={
  1806. "name": "test-mapper",
  1807. "protocol": "openid-connect",
  1808. "protocolMapper": "oidc-usermodel-attribute-mapper",
  1809. },
  1810. )
  1811. assert res_add == b""
  1812. assert len(admin.get_mappers_from_client_scope(client_scope_id=res)) == 1
  1813. # Test update mapper
  1814. test_mapper = admin.get_mappers_from_client_scope(client_scope_id=res)[0]
  1815. with pytest.raises(KeycloakPutError) as err:
  1816. admin.update_mapper_in_client_scope(
  1817. client_scope_id="does-not-exist", protocol_mapper_id=test_mapper["id"], payload=dict()
  1818. )
  1819. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1820. test_mapper["config"]["user.attribute"] = "test"
  1821. res_update = admin.update_mapper_in_client_scope(
  1822. client_scope_id=res, protocol_mapper_id=test_mapper["id"], payload=test_mapper
  1823. )
  1824. assert res_update == dict()
  1825. assert (
  1826. admin.get_mappers_from_client_scope(client_scope_id=res)[0]["config"]["user.attribute"]
  1827. == "test"
  1828. )
  1829. # Test delete mapper
  1830. res_del = admin.delete_mapper_from_client_scope(
  1831. client_scope_id=res, protocol_mapper_id=test_mapper["id"]
  1832. )
  1833. assert res_del == dict()
  1834. with pytest.raises(KeycloakDeleteError) as err:
  1835. admin.delete_mapper_from_client_scope(
  1836. client_scope_id=res, protocol_mapper_id=test_mapper["id"]
  1837. )
  1838. assert err.match('404: b\'{"error":"Model not found"}\'')
  1839. # Test default default scopes
  1840. res_defaults = admin.get_default_default_client_scopes()
  1841. assert len(res_defaults) == 6
  1842. with pytest.raises(KeycloakPutError) as err:
  1843. admin.add_default_default_client_scope(scope_id="does-not-exist")
  1844. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1845. res_add = admin.add_default_default_client_scope(scope_id=res)
  1846. assert res_add == dict()
  1847. assert len(admin.get_default_default_client_scopes()) == 7
  1848. with pytest.raises(KeycloakDeleteError) as err:
  1849. admin.delete_default_default_client_scope(scope_id="does-not-exist")
  1850. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1851. res_del = admin.delete_default_default_client_scope(scope_id=res)
  1852. assert res_del == dict()
  1853. assert len(admin.get_default_default_client_scopes()) == 6
  1854. # Test default optional scopes
  1855. res_defaults = admin.get_default_optional_client_scopes()
  1856. assert len(res_defaults) == 4
  1857. with pytest.raises(KeycloakPutError) as err:
  1858. admin.add_default_optional_client_scope(scope_id="does-not-exist")
  1859. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1860. res_add = admin.add_default_optional_client_scope(scope_id=res)
  1861. assert res_add == dict()
  1862. assert len(admin.get_default_optional_client_scopes()) == 5
  1863. with pytest.raises(KeycloakDeleteError) as err:
  1864. admin.delete_default_optional_client_scope(scope_id="does-not-exist")
  1865. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1866. res_del = admin.delete_default_optional_client_scope(scope_id=res)
  1867. assert res_del == dict()
  1868. assert len(admin.get_default_optional_client_scopes()) == 4
  1869. # Test client scope delete
  1870. res_del = admin.delete_client_scope(client_scope_id=res)
  1871. assert res_del == dict()
  1872. with pytest.raises(KeycloakDeleteError) as err:
  1873. admin.delete_client_scope(client_scope_id=res)
  1874. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1875. def test_components(admin: KeycloakAdmin, realm: str):
  1876. """Test components.
  1877. :param admin: Keycloak Admin client
  1878. :type admin: KeycloakAdmin
  1879. :param realm: Keycloak realm
  1880. :type realm: str
  1881. """
  1882. admin.realm_name = realm
  1883. # Test get components
  1884. res = admin.get_components()
  1885. assert len(res) == 12
  1886. with pytest.raises(KeycloakGetError) as err:
  1887. admin.get_component(component_id="does-not-exist")
  1888. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1889. res_get = admin.get_component(component_id=res[0]["id"])
  1890. assert res_get == res[0]
  1891. # Test create component
  1892. with pytest.raises(KeycloakPostError) as err:
  1893. admin.create_component(payload={"bad": "dict"})
  1894. assert err.match('400: b\'{"error":"Unrecognized field')
  1895. res = admin.create_component(
  1896. payload={
  1897. "name": "Test Component",
  1898. "providerId": "max-clients",
  1899. "providerType": "org.keycloak.services.clientregistration."
  1900. + "policy.ClientRegistrationPolicy",
  1901. "config": {"max-clients": ["1000"]},
  1902. }
  1903. )
  1904. assert res
  1905. assert admin.get_component(component_id=res)["name"] == "Test Component"
  1906. # Test update component
  1907. component = admin.get_component(component_id=res)
  1908. component["name"] = "Test Component Update"
  1909. with pytest.raises(KeycloakPutError) as err:
  1910. admin.update_component(component_id="does-not-exist", payload=dict())
  1911. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1912. res_upd = admin.update_component(component_id=res, payload=component)
  1913. assert res_upd == dict()
  1914. assert admin.get_component(component_id=res)["name"] == "Test Component Update"
  1915. # Test delete component
  1916. res_del = admin.delete_component(component_id=res)
  1917. assert res_del == dict()
  1918. with pytest.raises(KeycloakDeleteError) as err:
  1919. admin.delete_component(component_id=res)
  1920. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1921. def test_keys(admin: KeycloakAdmin, realm: str):
  1922. """Test keys.
  1923. :param admin: Keycloak Admin client
  1924. :type admin: KeycloakAdmin
  1925. :param realm: Keycloak realm
  1926. :type realm: str
  1927. """
  1928. admin.realm_name = realm
  1929. assert set(admin.get_keys()["active"].keys()) == {"AES", "HS256", "RS256", "RSA-OAEP"}
  1930. assert {k["algorithm"] for k in admin.get_keys()["keys"]} == {
  1931. "HS256",
  1932. "RSA-OAEP",
  1933. "AES",
  1934. "RS256",
  1935. }
  1936. def test_events(admin: KeycloakAdmin, realm: str):
  1937. """Test events.
  1938. :param admin: Keycloak Admin client
  1939. :type admin: KeycloakAdmin
  1940. :param realm: Keycloak realm
  1941. :type realm: str
  1942. """
  1943. admin.realm_name = realm
  1944. events = admin.get_events()
  1945. assert events == list()
  1946. with pytest.raises(KeycloakPutError) as err:
  1947. admin.set_events(payload={"bad": "conf"})
  1948. assert err.match('400: b\'{"error":"Unrecognized field')
  1949. res = admin.set_events(payload={"adminEventsDetailsEnabled": True, "adminEventsEnabled": True})
  1950. assert res == dict()
  1951. admin.create_client(payload={"name": "test", "clientId": "test"})
  1952. events = admin.get_events()
  1953. assert events == list()
  1954. @freezegun.freeze_time("2023-02-25 10:00:00")
  1955. def test_auto_refresh(admin_frozen: KeycloakAdmin, realm: str):
  1956. """Test auto refresh token.
  1957. :param admin_frozen: Keycloak Admin client with time frozen in place
  1958. :type admin_frozen: KeycloakAdmin
  1959. :param realm: Keycloak realm
  1960. :type realm: str
  1961. """
  1962. admin = admin_frozen
  1963. # Test get refresh
  1964. admin.connection.custom_headers = {
  1965. "Authorization": "Bearer bad",
  1966. "Content-Type": "application/json",
  1967. }
  1968. with pytest.raises(KeycloakAuthenticationError) as err:
  1969. admin.get_realm(realm_name=realm)
  1970. assert err.match('401: b\'{"error":"HTTP 401 Unauthorized"}\'')
  1971. # Freeze time to simulate the access token expiring
  1972. with freezegun.freeze_time("2023-02-25 10:05:00"):
  1973. assert admin.connection.expires_at < datetime_parser.parse("2023-02-25 10:05:00")
  1974. assert admin.get_realm(realm_name=realm)
  1975. assert admin.connection.expires_at > datetime_parser.parse("2023-02-25 10:05:00")
  1976. # Test bad refresh token, but first make sure access token has expired again
  1977. with freezegun.freeze_time("2023-02-25 10:10:00"):
  1978. admin.connection.custom_headers = {"Content-Type": "application/json"}
  1979. admin.connection.token["refresh_token"] = "bad"
  1980. with pytest.raises(KeycloakPostError) as err:
  1981. admin.get_realm(realm_name="test-refresh")
  1982. assert err.match(
  1983. '400: b\'{"error":"invalid_grant","error_description":"Invalid refresh token"}\''
  1984. )
  1985. admin.connection.get_token()
  1986. # Test post refresh
  1987. with freezegun.freeze_time("2023-02-25 10:15:00"):
  1988. assert admin.connection.expires_at < datetime_parser.parse("2023-02-25 10:15:00")
  1989. admin.connection.token = None
  1990. assert admin.create_realm(payload={"realm": "test-refresh"}) == b""
  1991. assert admin.connection.expires_at > datetime_parser.parse("2023-02-25 10:15:00")
  1992. # Test update refresh
  1993. with freezegun.freeze_time("2023-02-25 10:25:00"):
  1994. assert admin.connection.expires_at < datetime_parser.parse("2023-02-25 10:25:00")
  1995. admin.connection.token = None
  1996. assert (
  1997. admin.update_realm(realm_name="test-refresh", payload={"accountTheme": "test"})
  1998. == dict()
  1999. )
  2000. assert admin.connection.expires_at > datetime_parser.parse("2023-02-25 10:25:00")
  2001. # Test delete refresh
  2002. with freezegun.freeze_time("2023-02-25 10:35:00"):
  2003. assert admin.connection.expires_at < datetime_parser.parse("2023-02-25 10:35:00")
  2004. admin.connection.token = None
  2005. assert admin.delete_realm(realm_name="test-refresh") == dict()
  2006. assert admin.connection.expires_at > datetime_parser.parse("2023-02-25 10:35:00")
  2007. def test_get_required_actions(admin: KeycloakAdmin, realm: str):
  2008. """Test required actions.
  2009. :param admin: Keycloak Admin client
  2010. :type admin: KeycloakAdmin
  2011. :param realm: Keycloak realm
  2012. :type realm: str
  2013. """
  2014. admin.realm_name = realm
  2015. ractions = admin.get_required_actions()
  2016. assert isinstance(ractions, list)
  2017. for ra in ractions:
  2018. for key in [
  2019. "alias",
  2020. "name",
  2021. "providerId",
  2022. "enabled",
  2023. "defaultAction",
  2024. "priority",
  2025. "config",
  2026. ]:
  2027. assert key in ra
  2028. def test_get_required_action_by_alias(admin: KeycloakAdmin, realm: str):
  2029. """Test get required action by alias.
  2030. :param admin: Keycloak Admin client
  2031. :type admin: KeycloakAdmin
  2032. :param realm: Keycloak realm
  2033. :type realm: str
  2034. """
  2035. admin.realm_name = realm
  2036. ractions = admin.get_required_actions()
  2037. ra = admin.get_required_action_by_alias("UPDATE_PASSWORD")
  2038. assert ra in ractions
  2039. assert ra["alias"] == "UPDATE_PASSWORD"
  2040. assert admin.get_required_action_by_alias("does-not-exist") is None
  2041. def test_update_required_action(admin: KeycloakAdmin, realm: str):
  2042. """Test update required action.
  2043. :param admin: Keycloak Admin client
  2044. :type admin: KeycloakAdmin
  2045. :param realm: Keycloak realm
  2046. :type realm: str
  2047. """
  2048. admin.realm_name = realm
  2049. ra = admin.get_required_action_by_alias("UPDATE_PASSWORD")
  2050. old = copy.deepcopy(ra)
  2051. ra["enabled"] = False
  2052. admin.update_required_action("UPDATE_PASSWORD", ra)
  2053. newra = admin.get_required_action_by_alias("UPDATE_PASSWORD")
  2054. assert old != newra
  2055. assert newra["enabled"] is False
  2056. def test_get_composite_client_roles_of_group(
  2057. admin: KeycloakAdmin, realm: str, client: str, group: str, composite_client_role: str
  2058. ):
  2059. """Test get composite client roles of group.
  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 group: Keycloak group
  2067. :type group: str
  2068. :param composite_client_role: Composite client role
  2069. :type composite_client_role: str
  2070. """
  2071. admin.realm_name = realm
  2072. role = admin.get_client_role(client, composite_client_role)
  2073. admin.assign_group_client_roles(group_id=group, client_id=client, roles=[role])
  2074. result = admin.get_composite_client_roles_of_group(client, group)
  2075. assert role["id"] in [x["id"] for x in result]
  2076. def test_get_role_client_level_children(
  2077. admin: KeycloakAdmin, realm: str, client: str, composite_client_role: str, client_role: str
  2078. ):
  2079. """Test get children of composite client role.
  2080. :param admin: Keycloak Admin client
  2081. :type admin: KeycloakAdmin
  2082. :param realm: Keycloak realm
  2083. :type realm: str
  2084. :param client: Keycloak client
  2085. :type client: str
  2086. :param composite_client_role: Composite client role
  2087. :type composite_client_role: str
  2088. :param client_role: Client role
  2089. :type client_role: str
  2090. """
  2091. admin.realm_name = realm
  2092. child = admin.get_client_role(client, client_role)
  2093. parent = admin.get_client_role(client, composite_client_role)
  2094. res = admin.get_role_client_level_children(client, parent["id"])
  2095. assert child["id"] in [x["id"] for x in res]
  2096. def test_upload_certificate(admin: KeycloakAdmin, realm: str, client: str, selfsigned_cert: tuple):
  2097. """Test upload certificate.
  2098. :param admin: Keycloak Admin client
  2099. :type admin: KeycloakAdmin
  2100. :param realm: Keycloak realm
  2101. :type realm: str
  2102. :param client: Keycloak client
  2103. :type client: str
  2104. :param selfsigned_cert: Selfsigned certificates
  2105. :type selfsigned_cert: tuple
  2106. """
  2107. admin.realm_name = realm
  2108. cert, _ = selfsigned_cert
  2109. cert = cert.decode("utf-8").strip()
  2110. admin.upload_certificate(client, cert)
  2111. cl = admin.get_client(client)
  2112. assert cl["attributes"]["jwt.credential.certificate"] == "".join(cert.splitlines()[1:-1])
  2113. def test_get_bruteforce_status_for_user(
  2114. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str], realm: str
  2115. ):
  2116. """Test users.
  2117. :param admin: Keycloak Admin client
  2118. :type admin: KeycloakAdmin
  2119. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  2120. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2121. :param realm: Keycloak realm
  2122. :type realm: str
  2123. """
  2124. oid, username, password = oid_with_credentials
  2125. admin.realm_name = realm
  2126. # Turn on bruteforce protection
  2127. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": True})
  2128. res = admin.get_realm(realm_name=realm)
  2129. assert res["bruteForceProtected"] is True
  2130. # Test login user with wrong credentials
  2131. try:
  2132. oid.token(username=username, password="wrongpassword")
  2133. except KeycloakAuthenticationError:
  2134. pass
  2135. user_id = admin.get_user_id(username)
  2136. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2137. assert bruteforce_status["numFailures"] == 1
  2138. # Cleanup
  2139. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": False})
  2140. res = admin.get_realm(realm_name=realm)
  2141. assert res["bruteForceProtected"] is False
  2142. def test_clear_bruteforce_attempts_for_user(
  2143. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str], realm: str
  2144. ):
  2145. """Test users.
  2146. :param admin: Keycloak Admin client
  2147. :type admin: KeycloakAdmin
  2148. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  2149. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2150. :param realm: Keycloak realm
  2151. :type realm: str
  2152. """
  2153. oid, username, password = oid_with_credentials
  2154. admin.realm_name = realm
  2155. # Turn on bruteforce protection
  2156. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": True})
  2157. res = admin.get_realm(realm_name=realm)
  2158. assert res["bruteForceProtected"] is True
  2159. # Test login user with wrong credentials
  2160. try:
  2161. oid.token(username=username, password="wrongpassword")
  2162. except KeycloakAuthenticationError:
  2163. pass
  2164. user_id = admin.get_user_id(username)
  2165. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2166. assert bruteforce_status["numFailures"] == 1
  2167. res = admin.clear_bruteforce_attempts_for_user(user_id)
  2168. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2169. assert bruteforce_status["numFailures"] == 0
  2170. # Cleanup
  2171. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": False})
  2172. res = admin.get_realm(realm_name=realm)
  2173. assert res["bruteForceProtected"] is False
  2174. def test_clear_bruteforce_attempts_for_all_users(
  2175. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str], realm: str
  2176. ):
  2177. """Test users.
  2178. :param admin: Keycloak Admin client
  2179. :type admin: KeycloakAdmin
  2180. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  2181. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2182. :param realm: Keycloak realm
  2183. :type realm: str
  2184. """
  2185. oid, username, password = oid_with_credentials
  2186. admin.realm_name = realm
  2187. # Turn on bruteforce protection
  2188. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": True})
  2189. res = admin.get_realm(realm_name=realm)
  2190. assert res["bruteForceProtected"] is True
  2191. # Test login user with wrong credentials
  2192. try:
  2193. oid.token(username=username, password="wrongpassword")
  2194. except KeycloakAuthenticationError:
  2195. pass
  2196. user_id = admin.get_user_id(username)
  2197. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2198. assert bruteforce_status["numFailures"] == 1
  2199. res = admin.clear_all_bruteforce_attempts()
  2200. bruteforce_status = admin.get_bruteforce_detection_status(user_id)
  2201. assert bruteforce_status["numFailures"] == 0
  2202. # Cleanup
  2203. res = admin.update_realm(realm_name=realm, payload={"bruteForceProtected": False})
  2204. res = admin.get_realm(realm_name=realm)
  2205. assert res["bruteForceProtected"] is False
  2206. def test_default_realm_role_present(realm: str, admin: KeycloakAdmin) -> None:
  2207. """Test that the default realm role is present in a brand new realm.
  2208. :param realm: Realm name
  2209. :type realm: str
  2210. :param admin: Keycloak admin
  2211. :type admin: KeycloakAdmin
  2212. """
  2213. admin.realm_name = realm
  2214. assert f"default-roles-{realm}" in [x["name"] for x in admin.get_realm_roles()]
  2215. assert (
  2216. len([x["name"] for x in admin.get_realm_roles() if x["name"] == f"default-roles-{realm}"])
  2217. == 1
  2218. )
  2219. def test_get_default_realm_role_id(realm: str, admin: KeycloakAdmin) -> None:
  2220. """Test getter for the ID of the default realm role.
  2221. :param realm: Realm name
  2222. :type realm: str
  2223. :param admin: Keycloak admin
  2224. :type admin: KeycloakAdmin
  2225. """
  2226. admin.realm_name = realm
  2227. assert (
  2228. admin.get_default_realm_role_id()
  2229. == [x["id"] for x in admin.get_realm_roles() if x["name"] == f"default-roles-{realm}"][0]
  2230. )
  2231. def test_realm_default_roles(admin: KeycloakAdmin, realm: str) -> None:
  2232. """Test getting, adding and deleting default realm roles.
  2233. :param realm: Realm name
  2234. :type realm: str
  2235. :param admin: Keycloak admin
  2236. :type admin: KeycloakAdmin
  2237. """
  2238. admin.realm_name = realm
  2239. # Test listing all default realm roles
  2240. roles = admin.get_realm_default_roles()
  2241. assert len(roles) == 2
  2242. assert {x["name"] for x in roles} == {"offline_access", "uma_authorization"}
  2243. with pytest.raises(KeycloakGetError) as err:
  2244. admin.realm_name = "doesnotexist"
  2245. admin.get_realm_default_roles()
  2246. assert err.match('404: b\'{"error":"Realm not found."}\'')
  2247. admin.realm_name = realm
  2248. # Test removing a default realm role
  2249. res = admin.remove_realm_default_roles(payload=[roles[0]])
  2250. assert res == {}
  2251. assert roles[0] not in admin.get_realm_default_roles()
  2252. assert len(admin.get_realm_default_roles()) == 1
  2253. with pytest.raises(KeycloakDeleteError) as err:
  2254. admin.remove_realm_default_roles(payload=[{"id": "bad id"}])
  2255. assert err.match('404: b\'{"error":"Could not find composite role"}\'')
  2256. # Test adding a default realm role
  2257. res = admin.add_realm_default_roles(payload=[roles[0]])
  2258. assert res == {}
  2259. assert roles[0] in admin.get_realm_default_roles()
  2260. assert len(admin.get_realm_default_roles()) == 2
  2261. with pytest.raises(KeycloakPostError) as err:
  2262. admin.add_realm_default_roles(payload=[{"id": "bad id"}])
  2263. assert err.match('404: b\'{"error":"Could not find composite role"}\'')
  2264. def test_clear_keys_cache(realm: str, admin: KeycloakAdmin) -> None:
  2265. """Test clearing the keys 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_keys_cache()
  2273. assert res == {}
  2274. def test_clear_realm_cache(realm: str, admin: KeycloakAdmin) -> None:
  2275. """Test clearing the realm cache.
  2276. :param realm: Realm name
  2277. :type realm: str
  2278. :param admin: Keycloak admin
  2279. :type admin: KeycloakAdmin
  2280. """
  2281. admin.realm_name = realm
  2282. res = admin.clear_realm_cache()
  2283. assert res == {}
  2284. def test_clear_user_cache(realm: str, admin: KeycloakAdmin) -> None:
  2285. """Test clearing the user cache.
  2286. :param realm: Realm name
  2287. :type realm: str
  2288. :param admin: Keycloak admin
  2289. :type admin: KeycloakAdmin
  2290. """
  2291. admin.realm_name = realm
  2292. res = admin.clear_user_cache()
  2293. assert res == {}
  2294. def test_initial_access_token(
  2295. admin: KeycloakAdmin, oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2296. ) -> None:
  2297. """Test initial access token and client creation.
  2298. :param admin: Keycloak admin
  2299. :type admin: KeycloakAdmin
  2300. :param oid_with_credentials: Keycloak OpenID client with pre-configured user credentials
  2301. :type oid_with_credentials: Tuple[KeycloakOpenID, str, str]
  2302. """
  2303. res = admin.create_initial_access_token(2, 3)
  2304. assert "token" in res
  2305. assert res["count"] == 2
  2306. assert res["expiration"] == 3
  2307. oid, username, password = oid_with_credentials
  2308. client = str(uuid.uuid4())
  2309. secret = str(uuid.uuid4())
  2310. res = oid.register_client(
  2311. token=res["token"],
  2312. payload={
  2313. "name": client,
  2314. "clientId": client,
  2315. "enabled": True,
  2316. "publicClient": False,
  2317. "protocol": "openid-connect",
  2318. "secret": secret,
  2319. "clientAuthenticatorType": "client-secret",
  2320. },
  2321. )
  2322. assert res["clientId"] == client