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.

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