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.

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