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.

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