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.

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