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.

1817 lines
68 KiB

  1. """Test the keycloak admin object."""
  2. import pytest
  3. import keycloak
  4. from keycloak import KeycloakAdmin
  5. from keycloak.connection import ConnectionManager
  6. from keycloak.exceptions import (
  7. KeycloakAuthenticationError,
  8. KeycloakDeleteError,
  9. KeycloakGetError,
  10. KeycloakPostError,
  11. KeycloakPutError,
  12. )
  13. def test_keycloak_version():
  14. """Test version."""
  15. assert keycloak.__version__, keycloak.__version__
  16. def test_keycloak_admin_bad_init(env):
  17. """Test keycloak admin bad init."""
  18. with pytest.raises(TypeError) as err:
  19. KeycloakAdmin(
  20. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  21. username=env.KEYCLOAK_ADMIN,
  22. password=env.KEYCLOAK_ADMIN_PASSWORD,
  23. auto_refresh_token=1,
  24. )
  25. assert err.match("Expected a list of strings")
  26. with pytest.raises(TypeError) as err:
  27. KeycloakAdmin(
  28. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  29. username=env.KEYCLOAK_ADMIN,
  30. password=env.KEYCLOAK_ADMIN_PASSWORD,
  31. auto_refresh_token=["patch"],
  32. )
  33. assert err.match("Unexpected method in auto_refresh_token")
  34. def test_keycloak_admin_init(env):
  35. """Test keycloak admin init."""
  36. admin = KeycloakAdmin(
  37. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  38. username=env.KEYCLOAK_ADMIN,
  39. password=env.KEYCLOAK_ADMIN_PASSWORD,
  40. )
  41. assert admin.server_url == f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}", admin.server_url
  42. assert admin.realm_name == "master", admin.realm_name
  43. assert isinstance(admin.connection, ConnectionManager), type(admin.connection)
  44. assert admin.client_id == "admin-cli", admin.client_id
  45. assert admin.client_secret_key is None, admin.client_secret_key
  46. assert admin.verify, admin.verify
  47. assert admin.username == env.KEYCLOAK_ADMIN, admin.username
  48. assert admin.password == env.KEYCLOAK_ADMIN_PASSWORD, admin.password
  49. assert admin.totp is None, admin.totp
  50. assert admin.token is not None, admin.token
  51. assert admin.auto_refresh_token == list(), admin.auto_refresh_token
  52. assert admin.user_realm_name is None, admin.user_realm_name
  53. assert admin.custom_headers is None, admin.custom_headers
  54. assert admin.token
  55. admin = KeycloakAdmin(
  56. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  57. username=env.KEYCLOAK_ADMIN,
  58. password=env.KEYCLOAK_ADMIN_PASSWORD,
  59. realm_name=None,
  60. user_realm_name="master",
  61. )
  62. assert admin.token
  63. admin = KeycloakAdmin(
  64. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  65. username=env.KEYCLOAK_ADMIN,
  66. password=env.KEYCLOAK_ADMIN_PASSWORD,
  67. realm_name=None,
  68. user_realm_name=None,
  69. )
  70. assert admin.token
  71. admin.create_realm(payload={"realm": "authz", "enabled": True})
  72. admin.realm_name = "authz"
  73. admin.create_client(
  74. payload={
  75. "name": "authz-client",
  76. "clientId": "authz-client",
  77. "authorizationServicesEnabled": True,
  78. "serviceAccountsEnabled": True,
  79. "clientAuthenticatorType": "client-secret",
  80. "directAccessGrantsEnabled": False,
  81. "enabled": True,
  82. "implicitFlowEnabled": False,
  83. "publicClient": False,
  84. }
  85. )
  86. secret = admin.generate_client_secrets(client_id=admin.get_client_id("authz-client"))
  87. assert KeycloakAdmin(
  88. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  89. user_realm_name="authz",
  90. client_id="authz-client",
  91. client_secret_key=secret["value"],
  92. ).token
  93. admin.delete_realm(realm_name="authz")
  94. assert (
  95. KeycloakAdmin(
  96. server_url=f"http://{env.KEYCLOAK_HOST}:{env.KEYCLOAK_PORT}",
  97. username=None,
  98. password=None,
  99. client_secret_key=None,
  100. custom_headers={"custom": "header"},
  101. ).token
  102. is None
  103. )
  104. def test_realms(admin: KeycloakAdmin):
  105. """Test realms."""
  106. # Get realms
  107. realms = admin.get_realms()
  108. assert len(realms) == 1, realms
  109. assert "master" == realms[0]["realm"]
  110. # Create a test realm
  111. res = admin.create_realm(payload={"realm": "test"})
  112. assert res == b"", res
  113. # Create the same realm, should fail
  114. with pytest.raises(KeycloakPostError) as err:
  115. res = admin.create_realm(payload={"realm": "test"})
  116. assert err.match('409: b\'{"errorMessage":"Conflict detected. See logs for details"}\'')
  117. # Create the same realm, skip_exists true
  118. res = admin.create_realm(payload={"realm": "test"}, skip_exists=True)
  119. assert res == {"msg": "Already exists"}, res
  120. # Get a single realm
  121. res = admin.get_realm(realm_name="test")
  122. assert res["realm"] == "test"
  123. # Get non-existing realm
  124. with pytest.raises(KeycloakGetError) as err:
  125. admin.get_realm(realm_name="non-existent")
  126. assert err.match('404: b\'{"error":"Realm not found."}\'')
  127. # Update realm
  128. res = admin.update_realm(realm_name="test", payload={"accountTheme": "test"})
  129. assert res == dict(), res
  130. # Check that the update worked
  131. res = admin.get_realm(realm_name="test")
  132. assert res["realm"] == "test"
  133. assert res["accountTheme"] == "test"
  134. # Update wrong payload
  135. with pytest.raises(KeycloakPutError) as err:
  136. admin.update_realm(realm_name="test", payload={"wrong": "payload"})
  137. assert err.match('400: b\'{"error":"Unrecognized field')
  138. # Check that get realms returns both realms
  139. realms = admin.get_realms()
  140. realm_names = [x["realm"] for x in realms]
  141. assert len(realms) == 2, realms
  142. assert "master" in realm_names, realm_names
  143. assert "test" in realm_names, realm_names
  144. # Delete the realm
  145. res = admin.delete_realm(realm_name="test")
  146. assert res == dict(), res
  147. # Check that the realm does not exist anymore
  148. with pytest.raises(KeycloakGetError) as err:
  149. admin.get_realm(realm_name="test")
  150. assert err.match('404: b\'{"error":"Realm not found."}\'')
  151. # Delete non-existing realm
  152. with pytest.raises(KeycloakDeleteError) as err:
  153. admin.delete_realm(realm_name="non-existent")
  154. assert err.match('404: b\'{"error":"Realm not found."}\'')
  155. def test_import_export_realms(admin: KeycloakAdmin, realm: str):
  156. """Test import and export of realms."""
  157. admin.realm_name = realm
  158. realm_export = admin.export_realm(export_clients=True, export_groups_and_role=True)
  159. assert realm_export != dict(), realm_export
  160. admin.delete_realm(realm_name=realm)
  161. admin.realm_name = "master"
  162. res = admin.import_realm(payload=realm_export)
  163. assert res == b"", res
  164. # Test bad import
  165. with pytest.raises(KeycloakPostError) as err:
  166. admin.import_realm(payload=dict())
  167. assert err.match('500: b\'{"error":"unknown_error"}\'')
  168. def test_users(admin: KeycloakAdmin, realm: str):
  169. """Test users."""
  170. admin.realm_name = realm
  171. # Check no users present
  172. users = admin.get_users()
  173. assert users == list(), users
  174. # Test create user
  175. user_id = admin.create_user(payload={"username": "test", "email": "test@test.test"})
  176. assert user_id is not None, user_id
  177. # Test create the same user
  178. with pytest.raises(KeycloakPostError) as err:
  179. admin.create_user(payload={"username": "test", "email": "test@test.test"})
  180. assert err.match('409: b\'{"errorMessage":"User exists with same username"}\'')
  181. # Test create the same user, exists_ok true
  182. user_id_2 = admin.create_user(
  183. payload={"username": "test", "email": "test@test.test"}, exist_ok=True
  184. )
  185. assert user_id == user_id_2
  186. # Test get user
  187. user = admin.get_user(user_id=user_id)
  188. assert user["username"] == "test", user["username"]
  189. assert user["email"] == "test@test.test", user["email"]
  190. # Test update user
  191. res = admin.update_user(user_id=user_id, payload={"firstName": "Test"})
  192. assert res == dict(), res
  193. user = admin.get_user(user_id=user_id)
  194. assert user["firstName"] == "Test"
  195. # Test update user fail
  196. with pytest.raises(KeycloakPutError) as err:
  197. admin.update_user(user_id=user_id, payload={"wrong": "payload"})
  198. assert err.match('400: b\'{"error":"Unrecognized field')
  199. # Test get users again
  200. users = admin.get_users()
  201. usernames = [x["username"] for x in users]
  202. assert "test" in usernames
  203. # Test users counts
  204. count = admin.users_count()
  205. assert count == 1, count
  206. # Test users count with query
  207. count = admin.users_count(query={"username": "notpresent"})
  208. assert count == 0
  209. # Test user groups
  210. groups = admin.get_user_groups(user_id=user["id"])
  211. assert len(groups) == 0
  212. # Test user groups bad id
  213. with pytest.raises(KeycloakGetError) as err:
  214. admin.get_user_groups(user_id="does-not-exist")
  215. assert err.match('404: b\'{"error":"User not found"}\'')
  216. # Test logout
  217. res = admin.user_logout(user_id=user["id"])
  218. assert res == dict(), res
  219. # Test logout fail
  220. with pytest.raises(KeycloakPostError) as err:
  221. admin.user_logout(user_id="non-existent-id")
  222. assert err.match('404: b\'{"error":"User not found"}\'')
  223. # Test consents
  224. res = admin.user_consents(user_id=user["id"])
  225. assert len(res) == 0, res
  226. # Test consents fail
  227. with pytest.raises(KeycloakGetError) as err:
  228. admin.user_consents(user_id="non-existent-id")
  229. assert err.match('404: b\'{"error":"User not found"}\'')
  230. # Test delete user
  231. res = admin.delete_user(user_id=user_id)
  232. assert res == dict(), res
  233. with pytest.raises(KeycloakGetError) as err:
  234. admin.get_user(user_id=user_id)
  235. err.match('404: b\'{"error":"User not found"}\'')
  236. # Test delete fail
  237. with pytest.raises(KeycloakDeleteError) as err:
  238. admin.delete_user(user_id="non-existent-id")
  239. assert err.match('404: b\'{"error":"User not found"}\'')
  240. def test_users_pagination(admin: KeycloakAdmin, realm: str):
  241. """Test user pagination."""
  242. admin.realm_name = realm
  243. for ind in range(admin.PAGE_SIZE + 50):
  244. username = f"user_{ind}"
  245. admin.create_user(payload={"username": username, "email": f"{username}@test.test"})
  246. users = admin.get_users()
  247. assert len(users) == admin.PAGE_SIZE + 50, len(users)
  248. users = admin.get_users(query={"first": 100})
  249. assert len(users) == 50, len(users)
  250. users = admin.get_users(query={"max": 20})
  251. assert len(users) == 20, len(users)
  252. def test_idps(admin: KeycloakAdmin, realm: str):
  253. """Test IDPs."""
  254. admin.realm_name = realm
  255. # Create IDP
  256. res = admin.create_idp(
  257. payload=dict(
  258. providerId="github", alias="github", config=dict(clientId="test", clientSecret="test")
  259. )
  260. )
  261. assert res == b"", res
  262. # Test create idp fail
  263. with pytest.raises(KeycloakPostError) as err:
  264. admin.create_idp(payload={"providerId": "does-not-exist", "alias": "something"})
  265. assert err.match("Invalid identity provider id"), err
  266. # Test listing
  267. idps = admin.get_idps()
  268. assert len(idps) == 1
  269. assert "github" == idps[0]["alias"]
  270. # Test IdP update
  271. res = admin.update_idp(idp_alias="github", payload=idps[0])
  272. assert res == {}, res
  273. # Test adding a mapper
  274. res = admin.add_mapper_to_idp(
  275. idp_alias="github",
  276. payload={
  277. "identityProviderAlias": "github",
  278. "identityProviderMapper": "github-user-attribute-mapper",
  279. "name": "test",
  280. },
  281. )
  282. assert res == b"", res
  283. # Test mapper fail
  284. with pytest.raises(KeycloakPostError) as err:
  285. admin.add_mapper_to_idp(idp_alias="does-no-texist", payload=dict())
  286. assert err.match('404: b\'{"error":"HTTP 404 Not Found"}\'')
  287. # Test IdP mappers listing
  288. idp_mappers = admin.get_idp_mappers(idp_alias="github")
  289. assert len(idp_mappers) == 1
  290. # Test IdP mapper update
  291. res = admin.update_mapper_in_idp(
  292. idp_alias="github",
  293. mapper_id=idp_mappers[0]["id"],
  294. # For an obscure reason, keycloak expect all fields
  295. payload={
  296. "id": idp_mappers[0]["id"],
  297. "identityProviderAlias": "github-alias",
  298. "identityProviderMapper": "github-user-attribute-mapper",
  299. "name": "test",
  300. "config": idp_mappers[0]["config"],
  301. },
  302. )
  303. assert res == dict(), res
  304. # Test delete
  305. res = admin.delete_idp(idp_alias="github")
  306. assert res == dict(), res
  307. # Test delete fail
  308. with pytest.raises(KeycloakDeleteError) as err:
  309. admin.delete_idp(idp_alias="does-not-exist")
  310. assert err.match('404: b\'{"error":"HTTP 404 Not Found"}\'')
  311. def test_user_credentials(admin: KeycloakAdmin, user: str):
  312. """Test user credentials."""
  313. res = admin.set_user_password(user_id=user, password="booya", temporary=True)
  314. assert res == dict(), res
  315. # Test user password set fail
  316. with pytest.raises(KeycloakPutError) as err:
  317. admin.set_user_password(user_id="does-not-exist", password="")
  318. assert err.match('404: b\'{"error":"User not found"}\'')
  319. credentials = admin.get_credentials(user_id=user)
  320. assert len(credentials) == 1
  321. assert credentials[0]["type"] == "password", credentials
  322. # Test get credentials fail
  323. with pytest.raises(KeycloakGetError) as err:
  324. admin.get_credentials(user_id="does-not-exist")
  325. assert err.match('404: b\'{"error":"User not found"}\'')
  326. res = admin.delete_credential(user_id=user, credential_id=credentials[0]["id"])
  327. assert res == dict(), res
  328. # Test delete fail
  329. with pytest.raises(KeycloakDeleteError) as err:
  330. admin.delete_credential(user_id=user, credential_id="does-not-exist")
  331. assert err.match('404: b\'{"error":"Credential not found"}\'')
  332. def test_social_logins(admin: KeycloakAdmin, user: str):
  333. """Test social logins."""
  334. res = admin.add_user_social_login(
  335. user_id=user, provider_id="gitlab", provider_userid="test", provider_username="test"
  336. )
  337. assert res == dict(), res
  338. admin.add_user_social_login(
  339. user_id=user, provider_id="github", provider_userid="test", provider_username="test"
  340. )
  341. assert res == dict(), res
  342. # Test add social login fail
  343. with pytest.raises(KeycloakPostError) as err:
  344. admin.add_user_social_login(
  345. user_id="does-not-exist",
  346. provider_id="does-not-exist",
  347. provider_userid="test",
  348. provider_username="test",
  349. )
  350. assert err.match('404: b\'{"error":"User not found"}\'')
  351. res = admin.get_user_social_logins(user_id=user)
  352. assert res == list(), res
  353. # Test get social logins fail
  354. with pytest.raises(KeycloakGetError) as err:
  355. admin.get_user_social_logins(user_id="does-not-exist")
  356. assert err.match('404: b\'{"error":"User not found"}\'')
  357. res = admin.delete_user_social_login(user_id=user, provider_id="gitlab")
  358. assert res == {}, res
  359. res = admin.delete_user_social_login(user_id=user, provider_id="github")
  360. assert res == {}, res
  361. with pytest.raises(KeycloakDeleteError) as err:
  362. admin.delete_user_social_login(user_id=user, provider_id="instagram")
  363. assert err.match('404: b\'{"error":"Link not found"}\''), err
  364. def test_server_info(admin: KeycloakAdmin):
  365. """Test server info."""
  366. info = admin.get_server_info()
  367. assert set(info.keys()) == {
  368. "systemInfo",
  369. "memoryInfo",
  370. "profileInfo",
  371. "themes",
  372. "socialProviders",
  373. "identityProviders",
  374. "providers",
  375. "protocolMapperTypes",
  376. "builtinProtocolMappers",
  377. "clientInstallations",
  378. "componentTypes",
  379. "passwordPolicies",
  380. "enums",
  381. }, info.keys()
  382. def test_groups(admin: KeycloakAdmin, user: str):
  383. """Test groups."""
  384. # Test get groups
  385. groups = admin.get_groups()
  386. assert len(groups) == 0
  387. # Test create group
  388. group_id = admin.create_group(payload={"name": "main-group"})
  389. assert group_id is not None, group_id
  390. # Test create subgroups
  391. subgroup_id_1 = admin.create_group(payload={"name": "subgroup-1"}, parent=group_id)
  392. subgroup_id_2 = admin.create_group(payload={"name": "subgroup-2"}, parent=group_id)
  393. # Test create group fail
  394. with pytest.raises(KeycloakPostError) as err:
  395. admin.create_group(payload={"name": "subgroup-1"}, parent=group_id)
  396. assert err.match('409: b\'{"error":"unknown_error"}\''), err
  397. # Test skip exists OK
  398. subgroup_id_1_eq = admin.create_group(
  399. payload={"name": "subgroup-1"}, parent=group_id, skip_exists=True
  400. )
  401. assert subgroup_id_1_eq is None
  402. # Test get groups again
  403. groups = admin.get_groups()
  404. assert len(groups) == 1, groups
  405. assert len(groups[0]["subGroups"]) == 2, groups["subGroups"]
  406. assert groups[0]["id"] == group_id
  407. assert {x["id"] for x in groups[0]["subGroups"]} == {subgroup_id_1, subgroup_id_2}
  408. # Test get groups query
  409. groups = admin.get_groups(query={"max": 10})
  410. assert len(groups) == 1, groups
  411. assert len(groups[0]["subGroups"]) == 2, groups["subGroups"]
  412. assert groups[0]["id"] == group_id
  413. assert {x["id"] for x in groups[0]["subGroups"]} == {subgroup_id_1, subgroup_id_2}
  414. # Test get group
  415. res = admin.get_group(group_id=subgroup_id_1)
  416. assert res["id"] == subgroup_id_1, res
  417. assert res["name"] == "subgroup-1"
  418. assert res["path"] == "/main-group/subgroup-1"
  419. # Test get group fail
  420. with pytest.raises(KeycloakGetError) as err:
  421. admin.get_group(group_id="does-not-exist")
  422. assert err.match('404: b\'{"error":"Could not find group by id"}\''), err
  423. # Create 1 more subgroup
  424. subsubgroup_id_1 = admin.create_group(payload={"name": "subsubgroup-1"}, parent=subgroup_id_2)
  425. main_group = admin.get_group(group_id=group_id)
  426. # Test nested searches
  427. res = admin.get_subgroups(group=main_group, path="/main-group/subgroup-2/subsubgroup-1")
  428. assert res is not None, res
  429. assert res["id"] == subsubgroup_id_1
  430. # Test empty search
  431. res = admin.get_subgroups(group=main_group, path="/none")
  432. assert res is None, res
  433. # Test get group by path
  434. res = admin.get_group_by_path(path="/main-group/subgroup-1")
  435. assert res is None, res
  436. res = admin.get_group_by_path(path="/main-group/subgroup-1", search_in_subgroups=True)
  437. assert res is not None, res
  438. assert res["id"] == subgroup_id_1, res
  439. res = admin.get_group_by_path(
  440. path="/main-group/subgroup-2/subsubgroup-1/test", search_in_subgroups=True
  441. )
  442. assert res is None, res
  443. res = admin.get_group_by_path(
  444. path="/main-group/subgroup-2/subsubgroup-1", search_in_subgroups=True
  445. )
  446. assert res is not None, res
  447. assert res["id"] == subsubgroup_id_1
  448. res = admin.get_group_by_path(path="/main-group")
  449. assert res is not None, res
  450. assert res["id"] == group_id, res
  451. # Test group members
  452. res = admin.get_group_members(group_id=subgroup_id_2)
  453. assert len(res) == 0, res
  454. # Test fail group members
  455. with pytest.raises(KeycloakGetError) as err:
  456. admin.get_group_members(group_id="does-not-exist")
  457. assert err.match('404: b\'{"error":"Could not find group by id"}\'')
  458. res = admin.group_user_add(user_id=user, group_id=subgroup_id_2)
  459. assert res == dict(), res
  460. res = admin.get_group_members(group_id=subgroup_id_2)
  461. assert len(res) == 1, res
  462. assert res[0]["id"] == user
  463. # Test get group members query
  464. res = admin.get_group_members(group_id=subgroup_id_2, query={"max": 10})
  465. assert len(res) == 1, res
  466. assert res[0]["id"] == user
  467. with pytest.raises(KeycloakDeleteError) as err:
  468. admin.group_user_remove(user_id="does-not-exist", group_id=subgroup_id_2)
  469. assert err.match('404: b\'{"error":"User not found"}\''), err
  470. res = admin.group_user_remove(user_id=user, group_id=subgroup_id_2)
  471. assert res == dict(), res
  472. # Test set permissions
  473. res = admin.group_set_permissions(group_id=subgroup_id_2, enabled=True)
  474. assert res["enabled"], res
  475. res = admin.group_set_permissions(group_id=subgroup_id_2, enabled=False)
  476. assert not res["enabled"], res
  477. with pytest.raises(KeycloakPutError) as err:
  478. admin.group_set_permissions(group_id=subgroup_id_2, enabled="blah")
  479. assert err.match('500: b\'{"error":"unknown_error"}\''), err
  480. # Test update group
  481. res = admin.update_group(group_id=subgroup_id_2, payload={"name": "new-subgroup-2"})
  482. assert res == dict(), res
  483. assert admin.get_group(group_id=subgroup_id_2)["name"] == "new-subgroup-2"
  484. # test update fail
  485. with pytest.raises(KeycloakPutError) as err:
  486. admin.update_group(group_id="does-not-exist", payload=dict())
  487. assert err.match('404: b\'{"error":"Could not find group by id"}\''), err
  488. # Test delete
  489. res = admin.delete_group(group_id=group_id)
  490. assert res == dict(), res
  491. assert len(admin.get_groups()) == 0
  492. # Test delete fail
  493. with pytest.raises(KeycloakDeleteError) as err:
  494. admin.delete_group(group_id="does-not-exist")
  495. assert err.match('404: b\'{"error":"Could not find group by id"}\''), err
  496. def test_clients(admin: KeycloakAdmin, realm: str):
  497. """Test clients."""
  498. admin.realm_name = realm
  499. # Test get clients
  500. clients = admin.get_clients()
  501. assert len(clients) == 6, clients
  502. assert {x["name"] for x in clients} == set(
  503. [
  504. "${client_admin-cli}",
  505. "${client_security-admin-console}",
  506. "${client_account-console}",
  507. "${client_broker}",
  508. "${client_account}",
  509. "${client_realm-management}",
  510. ]
  511. ), clients
  512. # Test create client
  513. client_id = admin.create_client(payload={"name": "test-client", "clientId": "test-client"})
  514. assert client_id, client_id
  515. with pytest.raises(KeycloakPostError) as err:
  516. admin.create_client(payload={"name": "test-client", "clientId": "test-client"})
  517. assert err.match('409: b\'{"errorMessage":"Client test-client already exists"}\''), err
  518. client_id_2 = admin.create_client(
  519. payload={"name": "test-client", "clientId": "test-client"}, skip_exists=True
  520. )
  521. assert client_id == client_id_2, client_id_2
  522. # Test get client
  523. res = admin.get_client(client_id=client_id)
  524. assert res["clientId"] == "test-client", res
  525. assert res["name"] == "test-client", res
  526. assert res["id"] == client_id, res
  527. with pytest.raises(KeycloakGetError) as err:
  528. admin.get_client(client_id="does-not-exist")
  529. assert err.match('404: b\'{"error":"Could not find client"}\'')
  530. assert len(admin.get_clients()) == 7
  531. # Test get client id
  532. assert admin.get_client_id(client_name="test-client") == client_id
  533. assert admin.get_client_id(client_name="does-not-exist") is None
  534. # Test update client
  535. res = admin.update_client(client_id=client_id, payload={"name": "test-client-change"})
  536. assert res == dict(), res
  537. with pytest.raises(KeycloakPutError) as err:
  538. admin.update_client(client_id="does-not-exist", payload={"name": "test-client-change"})
  539. assert err.match('404: b\'{"error":"Could not find client"}\'')
  540. # Test client mappers
  541. res = admin.get_mappers_from_client(client_id=client_id)
  542. assert len(res) == 0
  543. with pytest.raises(KeycloakPostError) as err:
  544. admin.add_mapper_to_client(client_id="does-not-exist", payload=dict())
  545. assert err.match('404: b\'{"error":"Could not find client"}\'')
  546. res = admin.add_mapper_to_client(
  547. client_id=client_id,
  548. payload={
  549. "name": "test-mapper",
  550. "protocol": "openid-connect",
  551. "protocolMapper": "oidc-usermodel-attribute-mapper",
  552. },
  553. )
  554. assert res == b""
  555. assert len(admin.get_mappers_from_client(client_id=client_id)) == 1
  556. mapper = admin.get_mappers_from_client(client_id=client_id)[0]
  557. with pytest.raises(KeycloakPutError) as err:
  558. admin.update_client_mapper(client_id=client_id, mapper_id="does-not-exist", payload=dict())
  559. assert err.match('404: b\'{"error":"Model not found"}\'')
  560. mapper["config"]["user.attribute"] = "test"
  561. res = admin.update_client_mapper(client_id=client_id, mapper_id=mapper["id"], payload=mapper)
  562. assert res == dict()
  563. res = admin.remove_client_mapper(client_id=client_id, client_mapper_id=mapper["id"])
  564. assert res == dict()
  565. with pytest.raises(KeycloakDeleteError) as err:
  566. admin.remove_client_mapper(client_id=client_id, client_mapper_id=mapper["id"])
  567. assert err.match('404: b\'{"error":"Model not found"}\'')
  568. # Test client sessions
  569. with pytest.raises(KeycloakGetError) as err:
  570. admin.get_client_all_sessions(client_id="does-not-exist")
  571. assert err.match('404: b\'{"error":"Could not find client"}\'')
  572. assert admin.get_client_all_sessions(client_id=client_id) == list()
  573. assert admin.get_client_sessions_stats() == list()
  574. # Test authz
  575. auth_client_id = admin.create_client(
  576. payload={
  577. "name": "authz-client",
  578. "clientId": "authz-client",
  579. "authorizationServicesEnabled": True,
  580. "serviceAccountsEnabled": True,
  581. }
  582. )
  583. res = admin.get_client_authz_settings(client_id=auth_client_id)
  584. assert res["allowRemoteResourceManagement"]
  585. assert res["decisionStrategy"] == "UNANIMOUS"
  586. assert len(res["policies"]) >= 0
  587. with pytest.raises(KeycloakGetError) as err:
  588. admin.get_client_authz_settings(client_id=client_id)
  589. assert err.match('500: b\'{"error":"HTTP 500 Internal Server Error"}\'')
  590. # Authz resources
  591. res = admin.get_client_authz_resources(client_id=auth_client_id)
  592. assert len(res) == 1
  593. assert res[0]["name"] == "Default Resource"
  594. with pytest.raises(KeycloakGetError) as err:
  595. admin.get_client_authz_resources(client_id=client_id)
  596. assert err.match('500: b\'{"error":"unknown_error"}\'')
  597. res = admin.create_client_authz_resource(
  598. client_id=auth_client_id, payload={"name": "test-resource"}
  599. )
  600. assert res["name"] == "test-resource", res
  601. test_resource_id = res["_id"]
  602. with pytest.raises(KeycloakPostError) as err:
  603. admin.create_client_authz_resource(
  604. client_id=auth_client_id, payload={"name": "test-resource"}
  605. )
  606. assert err.match('409: b\'{"error":"invalid_request"')
  607. assert admin.create_client_authz_resource(
  608. client_id=auth_client_id, payload={"name": "test-resource"}, skip_exists=True
  609. ) == {"msg": "Already exists"}
  610. res = admin.get_client_authz_resources(client_id=auth_client_id)
  611. assert len(res) == 2
  612. assert {x["name"] for x in res} == {"Default Resource", "test-resource"}
  613. # Authz policies
  614. res = admin.get_client_authz_policies(client_id=auth_client_id)
  615. assert len(res) == 1, res
  616. assert res[0]["name"] == "Default Policy"
  617. assert len(admin.get_client_authz_policies(client_id=client_id)) == 1
  618. with pytest.raises(KeycloakGetError) as err:
  619. admin.get_client_authz_policies(client_id="does-not-exist")
  620. assert err.match('404: b\'{"error":"Could not find client"}\'')
  621. role_id = admin.get_realm_role(role_name="offline_access")["id"]
  622. res = admin.create_client_authz_role_based_policy(
  623. client_id=auth_client_id,
  624. payload={"name": "test-authz-rb-policy", "roles": [{"id": role_id}]},
  625. )
  626. assert res["name"] == "test-authz-rb-policy", res
  627. with pytest.raises(KeycloakPostError) as err:
  628. admin.create_client_authz_role_based_policy(
  629. client_id=auth_client_id,
  630. payload={"name": "test-authz-rb-policy", "roles": [{"id": role_id}]},
  631. )
  632. assert err.match('409: b\'{"error":"Policy with name')
  633. assert admin.create_client_authz_role_based_policy(
  634. client_id=auth_client_id,
  635. payload={"name": "test-authz-rb-policy", "roles": [{"id": role_id}]},
  636. skip_exists=True,
  637. ) == {"msg": "Already exists"}
  638. assert len(admin.get_client_authz_policies(client_id=auth_client_id)) == 2
  639. # Test authz permissions
  640. res = admin.get_client_authz_permissions(client_id=auth_client_id)
  641. assert len(res) == 1, res
  642. assert res[0]["name"] == "Default Permission"
  643. assert len(admin.get_client_authz_permissions(client_id=client_id)) == 1
  644. with pytest.raises(KeycloakGetError) as err:
  645. admin.get_client_authz_permissions(client_id="does-not-exist")
  646. assert err.match('404: b\'{"error":"Could not find client"}\'')
  647. res = admin.create_client_authz_resource_based_permission(
  648. client_id=auth_client_id,
  649. payload={"name": "test-permission-rb", "resources": [test_resource_id]},
  650. )
  651. assert res, res
  652. assert res["name"] == "test-permission-rb"
  653. assert res["resources"] == [test_resource_id]
  654. with pytest.raises(KeycloakPostError) as err:
  655. admin.create_client_authz_resource_based_permission(
  656. client_id=auth_client_id,
  657. payload={"name": "test-permission-rb", "resources": [test_resource_id]},
  658. )
  659. assert err.match('409: b\'{"error":"Policy with name')
  660. assert admin.create_client_authz_resource_based_permission(
  661. client_id=auth_client_id,
  662. payload={"name": "test-permission-rb", "resources": [test_resource_id]},
  663. skip_exists=True,
  664. ) == {"msg": "Already exists"}
  665. assert len(admin.get_client_authz_permissions(client_id=auth_client_id)) == 2
  666. # Test authz scopes
  667. res = admin.get_client_authz_scopes(client_id=auth_client_id)
  668. assert len(res) == 0, res
  669. with pytest.raises(KeycloakGetError) as err:
  670. admin.get_client_authz_scopes(client_id=client_id)
  671. assert err.match('500: b\'{"error":"unknown_error"}\'')
  672. # Test service account user
  673. res = admin.get_client_service_account_user(client_id=auth_client_id)
  674. assert res["username"] == "service-account-authz-client", res
  675. with pytest.raises(KeycloakGetError) as err:
  676. admin.get_client_service_account_user(client_id=client_id)
  677. assert err.match('400: b\'{"error":"unknown_error"}\'')
  678. # Test delete client
  679. res = admin.delete_client(client_id=auth_client_id)
  680. assert res == dict(), res
  681. with pytest.raises(KeycloakDeleteError) as err:
  682. admin.delete_client(client_id=auth_client_id)
  683. assert err.match('404: b\'{"error":"Could not find client"}\'')
  684. # Test client credentials
  685. admin.create_client(
  686. payload={
  687. "name": "test-confidential",
  688. "enabled": True,
  689. "protocol": "openid-connect",
  690. "publicClient": False,
  691. "redirectUris": ["http://localhost/*"],
  692. "webOrigins": ["+"],
  693. "clientId": "test-confidential",
  694. "secret": "test-secret",
  695. "clientAuthenticatorType": "client-secret",
  696. }
  697. )
  698. with pytest.raises(KeycloakGetError) as err:
  699. admin.get_client_secrets(client_id="does-not-exist")
  700. assert err.match('404: b\'{"error":"Could not find client"}\'')
  701. secrets = admin.get_client_secrets(
  702. client_id=admin.get_client_id(client_name="test-confidential")
  703. )
  704. assert secrets == {"type": "secret", "value": "test-secret"}
  705. with pytest.raises(KeycloakPostError) as err:
  706. admin.generate_client_secrets(client_id="does-not-exist")
  707. assert err.match('404: b\'{"error":"Could not find client"}\'')
  708. res = admin.generate_client_secrets(
  709. client_id=admin.get_client_id(client_name="test-confidential")
  710. )
  711. assert res
  712. assert (
  713. admin.get_client_secrets(client_id=admin.get_client_id(client_name="test-confidential"))
  714. == res
  715. )
  716. def test_realm_roles(admin: KeycloakAdmin, realm: str):
  717. """Test realm roles."""
  718. admin.realm_name = realm
  719. # Test get realm roles
  720. roles = admin.get_realm_roles()
  721. assert len(roles) == 3, roles
  722. role_names = [x["name"] for x in roles]
  723. assert "uma_authorization" in role_names, role_names
  724. assert "offline_access" in role_names, role_names
  725. # Test empty members
  726. with pytest.raises(KeycloakGetError) as err:
  727. admin.get_realm_role_members(role_name="does-not-exist")
  728. assert err.match('404: b\'{"error":"Could not find role"}\'')
  729. members = admin.get_realm_role_members(role_name="offline_access")
  730. assert members == list(), members
  731. # Test create realm role
  732. role_id = admin.create_realm_role(payload={"name": "test-realm-role"}, skip_exists=True)
  733. assert role_id, role_id
  734. with pytest.raises(KeycloakPostError) as err:
  735. admin.create_realm_role(payload={"name": "test-realm-role"})
  736. assert err.match('409: b\'{"errorMessage":"Role with name test-realm-role already exists"}\'')
  737. role_id_2 = admin.create_realm_role(payload={"name": "test-realm-role"}, skip_exists=True)
  738. assert role_id == role_id_2
  739. # Test update realm role
  740. res = admin.update_realm_role(
  741. role_name="test-realm-role", payload={"name": "test-realm-role-update"}
  742. )
  743. assert res == dict(), res
  744. with pytest.raises(KeycloakPutError) as err:
  745. admin.update_realm_role(
  746. role_name="test-realm-role", payload={"name": "test-realm-role-update"}
  747. )
  748. assert err.match('404: b\'{"error":"Could not find role"}\''), err
  749. # Test realm role user assignment
  750. user_id = admin.create_user(payload={"username": "role-testing", "email": "test@test.test"})
  751. with pytest.raises(KeycloakPostError) as err:
  752. admin.assign_realm_roles(user_id=user_id, roles=["bad"])
  753. assert err.match('500: b\'{"error":"unknown_error"}\'')
  754. res = admin.assign_realm_roles(
  755. user_id=user_id,
  756. roles=[
  757. admin.get_realm_role(role_name="offline_access"),
  758. admin.get_realm_role(role_name="test-realm-role-update"),
  759. ],
  760. )
  761. assert res == dict(), res
  762. assert admin.get_user(user_id=user_id)["username"] in [
  763. x["username"] for x in admin.get_realm_role_members(role_name="offline_access")
  764. ]
  765. assert admin.get_user(user_id=user_id)["username"] in [
  766. x["username"] for x in admin.get_realm_role_members(role_name="test-realm-role-update")
  767. ]
  768. roles = admin.get_realm_roles_of_user(user_id=user_id)
  769. assert len(roles) == 3
  770. assert "offline_access" in [x["name"] for x in roles]
  771. assert "test-realm-role-update" in [x["name"] for x in roles]
  772. with pytest.raises(KeycloakDeleteError) as err:
  773. admin.delete_realm_roles_of_user(user_id=user_id, roles=["bad"])
  774. assert err.match('500: b\'{"error":"unknown_error"}\'')
  775. res = admin.delete_realm_roles_of_user(
  776. user_id=user_id, roles=[admin.get_realm_role(role_name="offline_access")]
  777. )
  778. assert res == dict(), res
  779. assert admin.get_realm_role_members(role_name="offline_access") == list()
  780. roles = admin.get_realm_roles_of_user(user_id=user_id)
  781. assert len(roles) == 2
  782. assert "offline_access" not in [x["name"] for x in roles]
  783. assert "test-realm-role-update" in [x["name"] for x in roles]
  784. roles = admin.get_available_realm_roles_of_user(user_id=user_id)
  785. assert len(roles) == 2
  786. assert "offline_access" in [x["name"] for x in roles]
  787. assert "uma_authorization" in [x["name"] for x in roles]
  788. # Test realm role group assignment
  789. group_id = admin.create_group(payload={"name": "test-group"})
  790. with pytest.raises(KeycloakPostError) as err:
  791. admin.assign_group_realm_roles(group_id=group_id, roles=["bad"])
  792. assert err.match('500: b\'{"error":"unknown_error"}\'')
  793. res = admin.assign_group_realm_roles(
  794. group_id=group_id,
  795. roles=[
  796. admin.get_realm_role(role_name="offline_access"),
  797. admin.get_realm_role(role_name="test-realm-role-update"),
  798. ],
  799. )
  800. assert res == dict(), res
  801. roles = admin.get_group_realm_roles(group_id=group_id)
  802. assert len(roles) == 2
  803. assert "offline_access" in [x["name"] for x in roles]
  804. assert "test-realm-role-update" in [x["name"] for x in roles]
  805. with pytest.raises(KeycloakDeleteError) as err:
  806. admin.delete_group_realm_roles(group_id=group_id, roles=["bad"])
  807. assert err.match('500: b\'{"error":"unknown_error"}\'')
  808. res = admin.delete_group_realm_roles(
  809. group_id=group_id, roles=[admin.get_realm_role(role_name="offline_access")]
  810. )
  811. assert res == dict(), res
  812. roles = admin.get_group_realm_roles(group_id=group_id)
  813. assert len(roles) == 1
  814. assert "test-realm-role-update" in [x["name"] for x in roles]
  815. # Test composite realm roles
  816. composite_role = admin.create_realm_role(payload={"name": "test-composite-role"})
  817. with pytest.raises(KeycloakPostError) as err:
  818. admin.add_composite_realm_roles_to_role(role_name=composite_role, roles=["bad"])
  819. assert err.match('500: b\'{"error":"unknown_error"}\'')
  820. res = admin.add_composite_realm_roles_to_role(
  821. role_name=composite_role, roles=[admin.get_realm_role(role_name="test-realm-role-update")]
  822. )
  823. assert res == dict(), res
  824. res = admin.get_composite_realm_roles_of_role(role_name=composite_role)
  825. assert len(res) == 1
  826. assert "test-realm-role-update" in res[0]["name"]
  827. with pytest.raises(KeycloakGetError) as err:
  828. admin.get_composite_realm_roles_of_role(role_name="bad")
  829. assert err.match('404: b\'{"error":"Could not find role"}\'')
  830. res = admin.get_composite_realm_roles_of_user(user_id=user_id)
  831. assert len(res) == 4
  832. assert "offline_access" in {x["name"] for x in res}
  833. assert "test-realm-role-update" in {x["name"] for x in res}
  834. assert "uma_authorization" in {x["name"] for x in res}
  835. with pytest.raises(KeycloakGetError) as err:
  836. admin.get_composite_realm_roles_of_user(user_id="bad")
  837. assert err.match('404: b\'{"error":"User not found"}\'')
  838. with pytest.raises(KeycloakDeleteError) as err:
  839. admin.remove_composite_realm_roles_to_role(role_name=composite_role, roles=["bad"])
  840. assert err.match('500: b\'{"error":"unknown_error"}\'')
  841. res = admin.remove_composite_realm_roles_to_role(
  842. role_name=composite_role, roles=[admin.get_realm_role(role_name="test-realm-role-update")]
  843. )
  844. assert res == dict(), res
  845. res = admin.get_composite_realm_roles_of_role(role_name=composite_role)
  846. assert len(res) == 0
  847. # Test delete realm role
  848. res = admin.delete_realm_role(role_name=composite_role)
  849. assert res == dict(), res
  850. with pytest.raises(KeycloakDeleteError) as err:
  851. admin.delete_realm_role(role_name=composite_role)
  852. assert err.match('404: b\'{"error":"Could not find role"}\'')
  853. def test_client_roles(admin: KeycloakAdmin, client: str):
  854. """Test client roles."""
  855. # Test get client roles
  856. res = admin.get_client_roles(client_id=client)
  857. assert len(res) == 0
  858. with pytest.raises(KeycloakGetError) as err:
  859. admin.get_client_roles(client_id="bad")
  860. assert err.match('404: b\'{"error":"Could not find client"}\'')
  861. # Test create client role
  862. client_role_id = admin.create_client_role(
  863. client_role_id=client, payload={"name": "client-role-test"}, skip_exists=True
  864. )
  865. with pytest.raises(KeycloakPostError) as err:
  866. admin.create_client_role(client_role_id=client, payload={"name": "client-role-test"})
  867. assert err.match('409: b\'{"errorMessage":"Role with name client-role-test already exists"}\'')
  868. client_role_id_2 = admin.create_client_role(
  869. client_role_id=client, payload={"name": "client-role-test"}, skip_exists=True
  870. )
  871. assert client_role_id == client_role_id_2
  872. # Test get client role
  873. res = admin.get_client_role(client_id=client, role_name="client-role-test")
  874. assert res["name"] == client_role_id
  875. with pytest.raises(KeycloakGetError) as err:
  876. admin.get_client_role(client_id=client, role_name="bad")
  877. assert err.match('404: b\'{"error":"Could not find role"}\'')
  878. res_ = admin.get_client_role_id(client_id=client, role_name="client-role-test")
  879. assert res_ == res["id"]
  880. with pytest.raises(KeycloakGetError) as err:
  881. admin.get_client_role_id(client_id=client, role_name="bad")
  882. assert err.match('404: b\'{"error":"Could not find role"}\'')
  883. assert len(admin.get_client_roles(client_id=client)) == 1
  884. # Test update client role
  885. res = admin.update_client_role(
  886. client_role_id=client,
  887. role_name="client-role-test",
  888. payload={"name": "client-role-test-update"},
  889. )
  890. assert res == dict()
  891. with pytest.raises(KeycloakPutError) as err:
  892. res = admin.update_client_role(
  893. client_role_id=client,
  894. role_name="client-role-test",
  895. payload={"name": "client-role-test-update"},
  896. )
  897. assert err.match('404: b\'{"error":"Could not find role"}\'')
  898. # Test user with client role
  899. res = admin.get_client_role_members(client_id=client, role_name="client-role-test-update")
  900. assert len(res) == 0
  901. with pytest.raises(KeycloakGetError) as err:
  902. admin.get_client_role_members(client_id=client, role_name="bad")
  903. assert err.match('404: b\'{"error":"Could not find role"}\'')
  904. user_id = admin.create_user(payload={"username": "test", "email": "test@test.test"})
  905. with pytest.raises(KeycloakPostError) as err:
  906. admin.assign_client_role(user_id=user_id, client_id=client, roles=["bad"])
  907. assert err.match('500: b\'{"error":"unknown_error"}\'')
  908. res = admin.assign_client_role(
  909. user_id=user_id,
  910. client_id=client,
  911. roles=[admin.get_client_role(client_id=client, role_name="client-role-test-update")],
  912. )
  913. assert res == dict()
  914. assert (
  915. len(admin.get_client_role_members(client_id=client, role_name="client-role-test-update"))
  916. == 1
  917. )
  918. roles = admin.get_client_roles_of_user(user_id=user_id, client_id=client)
  919. assert len(roles) == 1, roles
  920. with pytest.raises(KeycloakGetError) as err:
  921. admin.get_client_roles_of_user(user_id=user_id, client_id="bad")
  922. assert err.match('404: b\'{"error":"Client not found"}\'')
  923. roles = admin.get_composite_client_roles_of_user(user_id=user_id, client_id=client)
  924. assert len(roles) == 1, roles
  925. with pytest.raises(KeycloakGetError) as err:
  926. admin.get_composite_client_roles_of_user(user_id=user_id, client_id="bad")
  927. assert err.match('404: b\'{"error":"Client not found"}\'')
  928. roles = admin.get_available_client_roles_of_user(user_id=user_id, client_id=client)
  929. assert len(roles) == 0, roles
  930. with pytest.raises(KeycloakGetError) as err:
  931. admin.get_composite_client_roles_of_user(user_id=user_id, client_id="bad")
  932. assert err.match('404: b\'{"error":"Client not found"}\'')
  933. with pytest.raises(KeycloakDeleteError) as err:
  934. admin.delete_client_roles_of_user(user_id=user_id, client_id=client, roles=["bad"])
  935. assert err.match('500: b\'{"error":"unknown_error"}\'')
  936. admin.delete_client_roles_of_user(
  937. user_id=user_id,
  938. client_id=client,
  939. roles=[admin.get_client_role(client_id=client, role_name="client-role-test-update")],
  940. )
  941. assert len(admin.get_client_roles_of_user(user_id=user_id, client_id=client)) == 0
  942. # Test groups and client roles
  943. res = admin.get_client_role_groups(client_id=client, role_name="client-role-test-update")
  944. assert len(res) == 0
  945. with pytest.raises(KeycloakGetError) as err:
  946. admin.get_client_role_groups(client_id=client, role_name="bad")
  947. assert err.match('404: b\'{"error":"Could not find role"}\'')
  948. group_id = admin.create_group(payload={"name": "test-group"})
  949. res = admin.get_group_client_roles(group_id=group_id, client_id=client)
  950. assert len(res) == 0
  951. with pytest.raises(KeycloakGetError) as err:
  952. admin.get_group_client_roles(group_id=group_id, client_id="bad")
  953. assert err.match('404: b\'{"error":"Client not found"}\'')
  954. with pytest.raises(KeycloakPostError) as err:
  955. admin.assign_group_client_roles(group_id=group_id, client_id=client, roles=["bad"])
  956. assert err.match('500: b\'{"error":"unknown_error"}\'')
  957. res = admin.assign_group_client_roles(
  958. group_id=group_id,
  959. client_id=client,
  960. roles=[admin.get_client_role(client_id=client, role_name="client-role-test-update")],
  961. )
  962. assert res == dict()
  963. assert (
  964. len(admin.get_client_role_groups(client_id=client, role_name="client-role-test-update"))
  965. == 1
  966. )
  967. assert len(admin.get_group_client_roles(group_id=group_id, client_id=client)) == 1
  968. with pytest.raises(KeycloakDeleteError) as err:
  969. admin.delete_group_client_roles(group_id=group_id, client_id=client, roles=["bad"])
  970. assert err.match('500: b\'{"error":"unknown_error"}\'')
  971. res = admin.delete_group_client_roles(
  972. group_id=group_id,
  973. client_id=client,
  974. roles=[admin.get_client_role(client_id=client, role_name="client-role-test-update")],
  975. )
  976. assert res == dict()
  977. # Test composite client roles
  978. with pytest.raises(KeycloakPostError) as err:
  979. admin.add_composite_client_roles_to_role(
  980. client_role_id=client, role_name="client-role-test-update", roles=["bad"]
  981. )
  982. assert err.match('500: b\'{"error":"unknown_error"}\'')
  983. res = admin.add_composite_client_roles_to_role(
  984. client_role_id=client,
  985. role_name="client-role-test-update",
  986. roles=[admin.get_realm_role(role_name="offline_access")],
  987. )
  988. assert res == dict()
  989. assert admin.get_client_role(client_id=client, role_name="client-role-test-update")[
  990. "composite"
  991. ]
  992. # Test delete of client role
  993. res = admin.delete_client_role(client_role_id=client, role_name="client-role-test-update")
  994. assert res == dict()
  995. with pytest.raises(KeycloakDeleteError) as err:
  996. admin.delete_client_role(client_role_id=client, role_name="client-role-test-update")
  997. assert err.match('404: b\'{"error":"Could not find role"}\'')
  998. def test_enable_token_exchange(admin: KeycloakAdmin, realm: str):
  999. """Test enable token exchange."""
  1000. # Test enabling token exchange between two confidential clients
  1001. admin.realm_name = realm
  1002. # Create test clients
  1003. source_client_id = admin.create_client(
  1004. payload={"name": "Source Client", "clientId": "source-client"}
  1005. )
  1006. target_client_id = admin.create_client(
  1007. payload={"name": "Target Client", "clientId": "target-client"}
  1008. )
  1009. for c in admin.get_clients():
  1010. if c["clientId"] == "realm-management":
  1011. realm_management_id = c["id"]
  1012. break
  1013. else:
  1014. raise AssertionError("Missing realm management client")
  1015. # Enable permissions on the Superset client
  1016. admin.update_client_management_permissions(
  1017. payload={"enabled": True}, client_id=target_client_id
  1018. )
  1019. # Fetch various IDs and strings needed when creating the permission
  1020. token_exchange_permission_id = admin.get_client_management_permissions(
  1021. client_id=target_client_id
  1022. )["scopePermissions"]["token-exchange"]
  1023. scopes = admin.get_client_authz_policy_scopes(
  1024. client_id=realm_management_id, policy_id=token_exchange_permission_id
  1025. )
  1026. for s in scopes:
  1027. if s["name"] == "token-exchange":
  1028. token_exchange_scope_id = s["id"]
  1029. break
  1030. else:
  1031. raise AssertionError("Missing token-exchange scope")
  1032. resources = admin.get_client_authz_policy_resources(
  1033. client_id=realm_management_id, policy_id=token_exchange_permission_id
  1034. )
  1035. for r in resources:
  1036. if r["name"] == f"client.resource.{target_client_id}":
  1037. token_exchange_resource_id = r["_id"]
  1038. break
  1039. else:
  1040. raise AssertionError("Missing client resource")
  1041. # Create a client policy for source client
  1042. policy_name = "Exchange source client token with target client token"
  1043. client_policy_id = admin.create_client_authz_client_policy(
  1044. payload={
  1045. "type": "client",
  1046. "logic": "POSITIVE",
  1047. "decisionStrategy": "UNANIMOUS",
  1048. "name": policy_name,
  1049. "clients": [source_client_id],
  1050. },
  1051. client_id=realm_management_id,
  1052. )["id"]
  1053. policies = admin.get_client_authz_client_policies(client_id=realm_management_id)
  1054. for policy in policies:
  1055. if policy["name"] == policy_name:
  1056. assert policy["clients"] == [source_client_id]
  1057. break
  1058. else:
  1059. raise AssertionError("Missing client policy")
  1060. # Update permissions on the target client to reference this policy
  1061. permission_name = admin.get_client_authz_scope_permission(
  1062. client_id=realm_management_id, scope_id=token_exchange_permission_id
  1063. )["name"]
  1064. admin.update_client_authz_scope_permission(
  1065. payload={
  1066. "id": token_exchange_permission_id,
  1067. "name": permission_name,
  1068. "type": "scope",
  1069. "logic": "POSITIVE",
  1070. "decisionStrategy": "UNANIMOUS",
  1071. "resources": [token_exchange_resource_id],
  1072. "scopes": [token_exchange_scope_id],
  1073. "policies": [client_policy_id],
  1074. },
  1075. client_id=realm_management_id,
  1076. scope_id=token_exchange_permission_id,
  1077. )
  1078. def test_email(admin: KeycloakAdmin, user: str):
  1079. """Test email."""
  1080. # Emails will fail as we don't have SMTP test setup
  1081. with pytest.raises(KeycloakPutError) as err:
  1082. admin.send_update_account(user_id=user, payload=dict())
  1083. assert err.match('500: b\'{"error":"unknown_error"}\'')
  1084. admin.update_user(user_id=user, payload={"enabled": True})
  1085. with pytest.raises(KeycloakPutError) as err:
  1086. admin.send_verify_email(user_id=user)
  1087. assert err.match('500: b\'{"errorMessage":"Failed to send execute actions email"}\'')
  1088. def test_get_sessions(admin: KeycloakAdmin):
  1089. """Test get sessions."""
  1090. sessions = admin.get_sessions(user_id=admin.get_user_id(username=admin.username))
  1091. assert len(sessions) >= 1
  1092. with pytest.raises(KeycloakGetError) as err:
  1093. admin.get_sessions(user_id="bad")
  1094. assert err.match('404: b\'{"error":"User not found"}\'')
  1095. def test_get_client_installation_provider(admin: KeycloakAdmin, client: str):
  1096. """Test get client installation provider."""
  1097. with pytest.raises(KeycloakGetError) as err:
  1098. admin.get_client_installation_provider(client_id=client, provider_id="bad")
  1099. assert err.match('404: b\'{"error":"Unknown Provider"}\'')
  1100. installation = admin.get_client_installation_provider(
  1101. client_id=client, provider_id="keycloak-oidc-keycloak-json"
  1102. )
  1103. assert set(installation.keys()) == {
  1104. "auth-server-url",
  1105. "confidential-port",
  1106. "credentials",
  1107. "realm",
  1108. "resource",
  1109. "ssl-required",
  1110. }
  1111. def test_auth_flows(admin: KeycloakAdmin, realm: str):
  1112. """Test auth flows."""
  1113. admin.realm_name = realm
  1114. res = admin.get_authentication_flows()
  1115. assert len(res) == 8, res
  1116. assert set(res[0].keys()) == {
  1117. "alias",
  1118. "authenticationExecutions",
  1119. "builtIn",
  1120. "description",
  1121. "id",
  1122. "providerId",
  1123. "topLevel",
  1124. }
  1125. assert {x["alias"] for x in res} == {
  1126. "reset credentials",
  1127. "browser",
  1128. "http challenge",
  1129. "registration",
  1130. "docker auth",
  1131. "direct grant",
  1132. "first broker login",
  1133. "clients",
  1134. }
  1135. with pytest.raises(KeycloakGetError) as err:
  1136. admin.get_authentication_flow_for_id(flow_id="bad")
  1137. assert err.match('404: b\'{"error":"Could not find flow with id"}\'')
  1138. browser_flow_id = [x for x in res if x["alias"] == "browser"][0]["id"]
  1139. res = admin.get_authentication_flow_for_id(flow_id=browser_flow_id)
  1140. assert res["alias"] == "browser"
  1141. # Test copying
  1142. with pytest.raises(KeycloakPostError) as err:
  1143. admin.copy_authentication_flow(payload=dict(), flow_alias="bad")
  1144. assert err.match("404: b''")
  1145. res = admin.copy_authentication_flow(payload={"newName": "test-browser"}, flow_alias="browser")
  1146. assert res == b"", res
  1147. assert len(admin.get_authentication_flows()) == 9
  1148. # Test create
  1149. res = admin.create_authentication_flow(
  1150. payload={"alias": "test-create", "providerId": "basic-flow"}
  1151. )
  1152. assert res == b""
  1153. with pytest.raises(KeycloakPostError) as err:
  1154. admin.create_authentication_flow(payload={"alias": "test-create", "builtIn": False})
  1155. assert err.match('409: b\'{"errorMessage":"Flow test-create already exists"}\'')
  1156. assert admin.create_authentication_flow(
  1157. payload={"alias": "test-create"}, skip_exists=True
  1158. ) == {"msg": "Already exists"}
  1159. # Test flow executions
  1160. res = admin.get_authentication_flow_executions(flow_alias="browser")
  1161. assert len(res) == 8, res
  1162. with pytest.raises(KeycloakGetError) as err:
  1163. admin.get_authentication_flow_executions(flow_alias="bad")
  1164. assert err.match("404: b''")
  1165. exec_id = res[0]["id"]
  1166. res = admin.get_authentication_flow_execution(execution_id=exec_id)
  1167. assert set(res.keys()) == {
  1168. "alternative",
  1169. "authenticator",
  1170. "authenticatorFlow",
  1171. "conditional",
  1172. "disabled",
  1173. "enabled",
  1174. "id",
  1175. "parentFlow",
  1176. "priority",
  1177. "required",
  1178. "requirement",
  1179. }, res
  1180. with pytest.raises(KeycloakGetError) as err:
  1181. admin.get_authentication_flow_execution(execution_id="bad")
  1182. assert err.match('404: b\'{"error":"Illegal execution"}\'')
  1183. with pytest.raises(KeycloakPostError) as err:
  1184. admin.create_authentication_flow_execution(payload=dict(), flow_alias="browser")
  1185. assert err.match('400: b\'{"error":"It is illegal to add execution to a built in flow"}\'')
  1186. res = admin.create_authentication_flow_execution(
  1187. payload={"provider": "auth-cookie"}, flow_alias="test-create"
  1188. )
  1189. assert res == b""
  1190. assert len(admin.get_authentication_flow_executions(flow_alias="test-create")) == 1
  1191. with pytest.raises(KeycloakPutError) as err:
  1192. admin.update_authentication_flow_executions(
  1193. payload={"required": "yes"}, flow_alias="test-create"
  1194. )
  1195. assert err.match('400: b\'{"error":"Unrecognized field')
  1196. payload = admin.get_authentication_flow_executions(flow_alias="test-create")[0]
  1197. payload["displayName"] = "test"
  1198. res = admin.update_authentication_flow_executions(payload=payload, flow_alias="test-create")
  1199. assert res
  1200. exec_id = admin.get_authentication_flow_executions(flow_alias="test-create")[0]["id"]
  1201. res = admin.delete_authentication_flow_execution(execution_id=exec_id)
  1202. assert res == dict()
  1203. with pytest.raises(KeycloakDeleteError) as err:
  1204. admin.delete_authentication_flow_execution(execution_id=exec_id)
  1205. assert err.match('404: b\'{"error":"Illegal execution"}\'')
  1206. # Test subflows
  1207. res = admin.create_authentication_flow_subflow(
  1208. payload={
  1209. "alias": "test-subflow",
  1210. "provider": "basic-flow",
  1211. "type": "something",
  1212. "description": "something",
  1213. },
  1214. flow_alias="test-browser",
  1215. )
  1216. assert res == b""
  1217. with pytest.raises(KeycloakPostError) as err:
  1218. admin.create_authentication_flow_subflow(
  1219. payload={"alias": "test-subflow", "providerId": "basic-flow"},
  1220. flow_alias="test-browser",
  1221. )
  1222. assert err.match('409: b\'{"errorMessage":"New flow alias name already exists"}\'')
  1223. res = admin.create_authentication_flow_subflow(
  1224. payload={
  1225. "alias": "test-subflow",
  1226. "provider": "basic-flow",
  1227. "type": "something",
  1228. "description": "something",
  1229. },
  1230. flow_alias="test-create",
  1231. skip_exists=True,
  1232. )
  1233. assert res == {"msg": "Already exists"}
  1234. # Test delete auth flow
  1235. flow_id = [x for x in admin.get_authentication_flows() if x["alias"] == "test-browser"][0][
  1236. "id"
  1237. ]
  1238. res = admin.delete_authentication_flow(flow_id=flow_id)
  1239. assert res == dict()
  1240. with pytest.raises(KeycloakDeleteError) as err:
  1241. admin.delete_authentication_flow(flow_id=flow_id)
  1242. assert err.match('404: b\'{"error":"Could not find flow with id"}\'')
  1243. def test_authentication_configs(admin: KeycloakAdmin, realm: str):
  1244. """Test authentication configs."""
  1245. admin.realm_name = realm
  1246. # Test list of auth providers
  1247. res = admin.get_authenticator_providers()
  1248. assert len(res) == 39
  1249. res = admin.get_authenticator_provider_config_description(provider_id="auth-cookie")
  1250. assert res == {
  1251. "helpText": "Validates the SSO cookie set by the auth server.",
  1252. "name": "Cookie",
  1253. "properties": [],
  1254. "providerId": "auth-cookie",
  1255. }
  1256. # Test authenticator config
  1257. # Currently unable to find a sustainable way to fetch the config id,
  1258. # therefore testing only failures
  1259. with pytest.raises(KeycloakGetError) as err:
  1260. admin.get_authenticator_config(config_id="bad")
  1261. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1262. with pytest.raises(KeycloakPutError) as err:
  1263. admin.update_authenticator_config(payload=dict(), config_id="bad")
  1264. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1265. with pytest.raises(KeycloakDeleteError) as err:
  1266. admin.delete_authenticator_config(config_id="bad")
  1267. assert err.match('404: b\'{"error":"Could not find authenticator config"}\'')
  1268. def test_sync_users(admin: KeycloakAdmin, realm: str):
  1269. """Test sync users."""
  1270. admin.realm_name = realm
  1271. # Only testing the error message
  1272. with pytest.raises(KeycloakPostError) as err:
  1273. admin.sync_users(storage_id="does-not-exist", action="triggerFullSync")
  1274. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1275. def test_client_scopes(admin: KeycloakAdmin, realm: str):
  1276. """Test client scopes."""
  1277. admin.realm_name = realm
  1278. # Test get client scopes
  1279. res = admin.get_client_scopes()
  1280. scope_names = {x["name"] for x in res}
  1281. assert len(res) == 10
  1282. assert "email" in scope_names
  1283. assert "profile" in scope_names
  1284. assert "offline_access" in scope_names
  1285. with pytest.raises(KeycloakGetError) as err:
  1286. admin.get_client_scope(client_scope_id="does-not-exist")
  1287. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1288. scope = admin.get_client_scope(client_scope_id=res[0]["id"])
  1289. assert res[0] == scope
  1290. scope = admin.get_client_scope_by_name(client_scope_name=res[0]["name"])
  1291. assert res[0] == scope
  1292. # Test create client scope
  1293. res = admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=True)
  1294. assert res
  1295. res2 = admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=True)
  1296. assert res == res2
  1297. with pytest.raises(KeycloakPostError) as err:
  1298. admin.create_client_scope(payload={"name": "test-scope"}, skip_exists=False)
  1299. assert err.match('409: b\'{"errorMessage":"Client Scope test-scope already exists"}\'')
  1300. # Test update client scope
  1301. with pytest.raises(KeycloakPutError) as err:
  1302. admin.update_client_scope(client_scope_id="does-not-exist", payload=dict())
  1303. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1304. res_update = admin.update_client_scope(
  1305. client_scope_id=res, payload={"name": "test-scope-update"}
  1306. )
  1307. assert res_update == dict()
  1308. admin.get_client_scope(client_scope_id=res)["name"] == "test-scope-update"
  1309. # Test get mappers
  1310. mappers = admin.get_mappers_from_client_scope(client_scope_id=res)
  1311. assert mappers == list()
  1312. # Test add mapper
  1313. with pytest.raises(KeycloakPostError) as err:
  1314. admin.add_mapper_to_client_scope(client_scope_id=res, payload=dict())
  1315. assert err.match('404: b\'{"error":"ProtocolMapper provider not found"}\'')
  1316. res_add = admin.add_mapper_to_client_scope(
  1317. client_scope_id=res,
  1318. payload={
  1319. "name": "test-mapper",
  1320. "protocol": "openid-connect",
  1321. "protocolMapper": "oidc-usermodel-attribute-mapper",
  1322. },
  1323. )
  1324. assert res_add == b""
  1325. assert len(admin.get_mappers_from_client_scope(client_scope_id=res)) == 1
  1326. # Test update mapper
  1327. test_mapper = admin.get_mappers_from_client_scope(client_scope_id=res)[0]
  1328. with pytest.raises(KeycloakPutError) as err:
  1329. admin.update_mapper_in_client_scope(
  1330. client_scope_id="does-not-exist", protocol_mapper_id=test_mapper["id"], payload=dict()
  1331. )
  1332. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1333. test_mapper["config"]["user.attribute"] = "test"
  1334. res_update = admin.update_mapper_in_client_scope(
  1335. client_scope_id=res, protocol_mapper_id=test_mapper["id"], payload=test_mapper
  1336. )
  1337. assert res_update == dict()
  1338. assert (
  1339. admin.get_mappers_from_client_scope(client_scope_id=res)[0]["config"]["user.attribute"]
  1340. == "test"
  1341. )
  1342. # Test delete mapper
  1343. res_del = admin.delete_mapper_from_client_scope(
  1344. client_scope_id=res, protocol_mapper_id=test_mapper["id"]
  1345. )
  1346. assert res_del == dict()
  1347. with pytest.raises(KeycloakDeleteError) as err:
  1348. admin.delete_mapper_from_client_scope(
  1349. client_scope_id=res, protocol_mapper_id=test_mapper["id"]
  1350. )
  1351. assert err.match('404: b\'{"error":"Model not found"}\'')
  1352. # Test default default scopes
  1353. res_defaults = admin.get_default_default_client_scopes()
  1354. assert len(res_defaults) == 6
  1355. with pytest.raises(KeycloakPutError) as err:
  1356. admin.add_default_default_client_scope(scope_id="does-not-exist")
  1357. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1358. res_add = admin.add_default_default_client_scope(scope_id=res)
  1359. assert res_add == dict()
  1360. assert len(admin.get_default_default_client_scopes()) == 7
  1361. with pytest.raises(KeycloakDeleteError) as err:
  1362. admin.delete_default_default_client_scope(scope_id="does-not-exist")
  1363. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1364. res_del = admin.delete_default_default_client_scope(scope_id=res)
  1365. assert res_del == dict()
  1366. assert len(admin.get_default_default_client_scopes()) == 6
  1367. # Test default optional scopes
  1368. res_defaults = admin.get_default_optional_client_scopes()
  1369. assert len(res_defaults) == 4
  1370. with pytest.raises(KeycloakPutError) as err:
  1371. admin.add_default_optional_client_scope(scope_id="does-not-exist")
  1372. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1373. res_add = admin.add_default_optional_client_scope(scope_id=res)
  1374. assert res_add == dict()
  1375. assert len(admin.get_default_optional_client_scopes()) == 5
  1376. with pytest.raises(KeycloakDeleteError) as err:
  1377. admin.delete_default_optional_client_scope(scope_id="does-not-exist")
  1378. assert err.match('404: b\'{"error":"Client scope not found"}\'')
  1379. res_del = admin.delete_default_optional_client_scope(scope_id=res)
  1380. assert res_del == dict()
  1381. assert len(admin.get_default_optional_client_scopes()) == 4
  1382. # Test client scope delete
  1383. res_del = admin.delete_client_scope(client_scope_id=res)
  1384. assert res_del == dict()
  1385. with pytest.raises(KeycloakDeleteError) as err:
  1386. admin.delete_client_scope(client_scope_id=res)
  1387. assert err.match('404: b\'{"error":"Could not find client scope"}\'')
  1388. def test_components(admin: KeycloakAdmin, realm: str):
  1389. """Test components."""
  1390. admin.realm_name = realm
  1391. # Test get components
  1392. res = admin.get_components()
  1393. assert len(res) == 12
  1394. with pytest.raises(KeycloakGetError) as err:
  1395. admin.get_component(component_id="does-not-exist")
  1396. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1397. res_get = admin.get_component(component_id=res[0]["id"])
  1398. assert res_get == res[0]
  1399. # Test create component
  1400. with pytest.raises(KeycloakPostError) as err:
  1401. admin.create_component(payload={"bad": "dict"})
  1402. assert err.match('400: b\'{"error":"Unrecognized field')
  1403. res = admin.create_component(
  1404. payload={
  1405. "name": "Test Component",
  1406. "providerId": "max-clients",
  1407. "providerType": "org.keycloak.services.clientregistration."
  1408. + "policy.ClientRegistrationPolicy",
  1409. "config": {"max-clients": ["1000"]},
  1410. }
  1411. )
  1412. assert res
  1413. assert admin.get_component(component_id=res)["name"] == "Test Component"
  1414. # Test update component
  1415. component = admin.get_component(component_id=res)
  1416. component["name"] = "Test Component Update"
  1417. with pytest.raises(KeycloakPutError) as err:
  1418. admin.update_component(component_id="does-not-exist", payload=dict())
  1419. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1420. res_upd = admin.update_component(component_id=res, payload=component)
  1421. assert res_upd == dict()
  1422. assert admin.get_component(component_id=res)["name"] == "Test Component Update"
  1423. # Test delete component
  1424. res_del = admin.delete_component(component_id=res)
  1425. assert res_del == dict()
  1426. with pytest.raises(KeycloakDeleteError) as err:
  1427. admin.delete_component(component_id=res)
  1428. assert err.match('404: b\'{"error":"Could not find component"}\'')
  1429. def test_keys(admin: KeycloakAdmin, realm: str):
  1430. """Test keys."""
  1431. admin.realm_name = realm
  1432. assert set(admin.get_keys()["active"].keys()) == {"AES", "HS256", "RS256", "RSA-OAEP"}
  1433. assert {k["algorithm"] for k in admin.get_keys()["keys"]} == {
  1434. "HS256",
  1435. "RSA-OAEP",
  1436. "AES",
  1437. "RS256",
  1438. }
  1439. def test_events(admin: KeycloakAdmin, realm: str):
  1440. """Test events."""
  1441. admin.realm_name = realm
  1442. events = admin.get_events()
  1443. assert events == list()
  1444. with pytest.raises(KeycloakPutError) as err:
  1445. admin.set_events(payload={"bad": "conf"})
  1446. assert err.match('400: b\'{"error":"Unrecognized field')
  1447. res = admin.set_events(payload={"adminEventsDetailsEnabled": True, "adminEventsEnabled": True})
  1448. assert res == dict()
  1449. admin.create_client(payload={"name": "test", "clientId": "test"})
  1450. events = admin.get_events()
  1451. assert events == list()
  1452. def test_auto_refresh(admin: KeycloakAdmin, realm: str):
  1453. """Test auto refresh token."""
  1454. # Test get refresh
  1455. admin.auto_refresh_token = list()
  1456. admin.connection = ConnectionManager(
  1457. base_url=admin.server_url,
  1458. headers={"Authorization": "Bearer bad", "Content-Type": "application/json"},
  1459. timeout=60,
  1460. verify=admin.verify,
  1461. )
  1462. with pytest.raises(KeycloakAuthenticationError) as err:
  1463. admin.get_realm(realm_name=realm)
  1464. assert err.match('401: b\'{"error":"HTTP 401 Unauthorized"}\'')
  1465. admin.auto_refresh_token = ["get"]
  1466. del admin.token["refresh_token"]
  1467. assert admin.get_realm(realm_name=realm)
  1468. # Test bad refresh token
  1469. admin.connection = ConnectionManager(
  1470. base_url=admin.server_url,
  1471. headers={"Authorization": "Bearer bad", "Content-Type": "application/json"},
  1472. timeout=60,
  1473. verify=admin.verify,
  1474. )
  1475. admin.token["refresh_token"] = "bad"
  1476. with pytest.raises(KeycloakPostError) as err:
  1477. admin.get_realm(realm_name="test-refresh")
  1478. assert err.match(
  1479. '400: b\'{"error":"invalid_grant","error_description":"Invalid refresh token"}\''
  1480. )
  1481. admin.realm_name = "master"
  1482. admin.get_token()
  1483. admin.realm_name = realm
  1484. # Test post refresh
  1485. admin.connection = ConnectionManager(
  1486. base_url=admin.server_url,
  1487. headers={"Authorization": "Bearer bad", "Content-Type": "application/json"},
  1488. timeout=60,
  1489. verify=admin.verify,
  1490. )
  1491. with pytest.raises(KeycloakAuthenticationError) as err:
  1492. admin.create_realm(payload={"realm": "test-refresh"})
  1493. assert err.match('401: b\'{"error":"HTTP 401 Unauthorized"}\'')
  1494. admin.auto_refresh_token = ["get", "post"]
  1495. admin.realm_name = "master"
  1496. admin.user_logout(user_id=admin.get_user_id(username=admin.username))
  1497. assert admin.create_realm(payload={"realm": "test-refresh"}) == b""
  1498. admin.realm_name = realm
  1499. # Test update refresh
  1500. admin.connection = ConnectionManager(
  1501. base_url=admin.server_url,
  1502. headers={"Authorization": "Bearer bad", "Content-Type": "application/json"},
  1503. timeout=60,
  1504. verify=admin.verify,
  1505. )
  1506. with pytest.raises(KeycloakAuthenticationError) as err:
  1507. admin.update_realm(realm_name="test-refresh", payload={"accountTheme": "test"})
  1508. assert err.match('401: b\'{"error":"HTTP 401 Unauthorized"}\'')
  1509. admin.auto_refresh_token = ["get", "post", "put"]
  1510. assert (
  1511. admin.update_realm(realm_name="test-refresh", payload={"accountTheme": "test"}) == dict()
  1512. )
  1513. # Test delete refresh
  1514. admin.connection = ConnectionManager(
  1515. base_url=admin.server_url,
  1516. headers={"Authorization": "Bearer bad", "Content-Type": "application/json"},
  1517. timeout=60,
  1518. verify=admin.verify,
  1519. )
  1520. with pytest.raises(KeycloakAuthenticationError) as err:
  1521. admin.delete_realm(realm_name="test-refresh")
  1522. assert err.match('401: b\'{"error":"HTTP 401 Unauthorized"}\'')
  1523. admin.auto_refresh_token = ["get", "post", "put", "delete"]
  1524. assert admin.delete_realm(realm_name="test-refresh") == dict()