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.

2679 lines
95 KiB

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