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.

1684 lines
63 KiB

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