test_users.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. import uuid
  2. import pytest
  3. from r2r import R2RClient, R2RException
  4. @pytest.fixture(scope="session")
  5. def config():
  6. class TestConfig:
  7. base_url = "http://localhost:7272"
  8. superuser_email = "admin@example.com"
  9. superuser_password = "change_me_immediately"
  10. known_collection_id = "122fdf6a-e116-546b-a8f6-e4cb2e2c0a09" # Example known collection ID
  11. return TestConfig()
  12. # @pytest.fixture(scope="session")
  13. def client(config):
  14. client = R2RClient(config.base_url)
  15. # Optionally, log in as superuser here if needed globally
  16. # client.users.login(config.superuser_email, config.superuser_password)
  17. return client
  18. @pytest.fixture
  19. def superuser_login(client, config):
  20. """A fixture that ensures the client is logged in as superuser."""
  21. client.users.login(config.superuser_email, config.superuser_password)
  22. yield
  23. # After test, if needed, we can logout or reset
  24. # client.users.logout()
  25. def register_and_return_user_id(client, email: str, password: str) -> str:
  26. user_resp = client.users.create(email, password)["results"]
  27. user_id = user_resp["id"]
  28. # If verification is mandatory, you'd have a step here to verify the user.
  29. # Otherwise, assume the user can login immediately.
  30. return user_id
  31. def test_register_user(client):
  32. random_email = f"{uuid.uuid4()}@example.com"
  33. password = "test_password123"
  34. user_resp = client.users.create(random_email, password)
  35. user = user_resp["results"]
  36. assert "id" in user, "No user ID returned after registration."
  37. client.users.logout()
  38. # COMMENTED OUT SINCE AUTH IS NOT REQUIRED BY DEFAULT IN R2R.TOML
  39. # def test_user_login_logout(client):
  40. # random_email = f"{uuid.uuid4()}@example.com"
  41. # password = "test_password123"
  42. # user_id = register_and_return_user_id(client, random_email, password)
  43. # login_resp = client.users.login(random_email, password)["results"]
  44. # assert "access_token" in login_resp, "Login failed."
  45. # me = client.users.me()["results"]
  46. # assert me["id"] == user_id, "Logged in user does not match expected user."
  47. # logout_resp = client.users.logout()["results"]
  48. # assert "message" in logout_resp, "Logout failed."
  49. # # After logout, token should be invalid
  50. # with pytest.raises(R2RException) as exc_info:
  51. # client.users.me()
  52. # assert exc_info.value.status_code == 401, "Expected 401 after logout."
  53. def test_user_refresh_token(client):
  54. random_email = f"{uuid.uuid4()}@example.com"
  55. password = "test_password123"
  56. register_and_return_user_id(client, random_email, password)
  57. client.users.login(random_email, password)
  58. old_access_token = client.access_token
  59. refresh_resp = client.users.refresh_token()["results"]
  60. new_access_token = refresh_resp["access_token"]["token"]
  61. assert (
  62. new_access_token != old_access_token
  63. ), "Refresh token did not provide a new access token."
  64. def test_change_password(client):
  65. random_email = f"{uuid.uuid4()}@example.com"
  66. old_password = "old_password123"
  67. new_password = "new_password456"
  68. register_and_return_user_id(client, random_email, old_password)
  69. client.users.login(random_email, old_password)
  70. change_resp = client.users.change_password(old_password, new_password)[
  71. "results"
  72. ]
  73. assert "message" in change_resp, "Change password failed."
  74. # Check old password no longer works
  75. client.users.logout()
  76. with pytest.raises(R2RException) as exc_info:
  77. client.users.login(random_email, old_password)
  78. assert (
  79. exc_info.value.status_code == 401
  80. ), "Old password should not work anymore."
  81. # New password should work
  82. client.users.login(random_email, new_password)
  83. client.users.logout()
  84. @pytest.mark.skip(
  85. reason="Requires a real or mocked reset token retrieval if verification is implemented."
  86. )
  87. def test_request_and_reset_password(client):
  88. # This test scenario assumes you can obtain a valid reset token somehow.
  89. random_email = f"{uuid.uuid4()}@example.com"
  90. password = "initial_password123"
  91. register_and_return_user_id(client, random_email, password)
  92. client.users.logout()
  93. # Request password reset
  94. reset_req = client.users.request_password_reset(random_email)
  95. assert "message" in reset_req["results"], "Request password reset failed."
  96. # Suppose we can retrieve a reset_token from test hooks or logs:
  97. reset_token = (
  98. "FAKE_RESET_TOKEN_FOR_TESTING" # Replace with actual if available
  99. )
  100. new_password = "new_reset_password789"
  101. # Attempt reset
  102. resp = client.users.reset_password(reset_token, new_password)
  103. assert "message" in resp["results"], "Reset password failed."
  104. # Verify login with new password
  105. client.users.login(random_email, new_password)
  106. client.users.logout()
  107. def test_users_list(client, superuser_login):
  108. users_list = client.users.list()["results"]
  109. assert isinstance(users_list, list), "Listing users failed."
  110. client.users.logout()
  111. def test_get_current_user(client, superuser_login):
  112. me = client.users.me()["results"]
  113. assert "id" in me, "Failed to get current user."
  114. client.users.logout()
  115. def test_get_user_by_id(client, superuser_login):
  116. random_email = f"{uuid.uuid4()}@example.com"
  117. password = "somepassword"
  118. user_id = register_and_return_user_id(client, random_email, password)
  119. user = client.users.retrieve(user_id)["results"]
  120. assert user["id"] == user_id, "Retrieved user does not match requested ID."
  121. client.users.logout()
  122. def test_update_user(client, superuser_login):
  123. random_email = f"{uuid.uuid4()}@example.com"
  124. password = "somepassword"
  125. user_id = register_and_return_user_id(client, random_email, password)
  126. updated_name = "Updated Name"
  127. update_resp = client.users.update(user_id, name=updated_name)["results"]
  128. assert update_resp["name"] == updated_name, "User update failed."
  129. client.users.logout()
  130. def test_user_collections(client, superuser_login, config):
  131. # Create a user and list their collections
  132. random_email = f"{uuid.uuid4()}@example.com"
  133. password = "somepassword"
  134. user_id = register_and_return_user_id(client, random_email, password)
  135. collections = client.users.list_collections(user_id)["results"]
  136. assert isinstance(collections, list), "Listing user collections failed."
  137. client.users.logout()
  138. def test_add_remove_user_from_collection(client, superuser_login, config):
  139. random_email = f"{uuid.uuid4()}@example.com"
  140. password = "somepassword"
  141. user_id = register_and_return_user_id(client, random_email, password)
  142. # Add user to known collection
  143. add_resp = client.users.add_to_collection(
  144. user_id, config.known_collection_id
  145. )["results"]
  146. assert add_resp["success"], "Failed to add user to collection."
  147. # Verify
  148. collections = client.users.list_collections(user_id)["results"]
  149. assert any(
  150. col["id"] == config.known_collection_id for col in collections
  151. ), "User not in collection after add."
  152. # Remove user from collection
  153. remove_resp = client.users.remove_from_collection(
  154. user_id, config.known_collection_id
  155. )["results"]
  156. assert remove_resp["success"], "Failed to remove user from collection."
  157. collections_after = client.users.list_collections(user_id)["results"]
  158. assert not any(
  159. col["id"] == config.known_collection_id for col in collections_after
  160. ), "User still in collection after removal."
  161. client.users.logout()
  162. def test_delete_user(client):
  163. # Create and then delete user
  164. client.users.logout()
  165. random_email = f"{uuid.uuid4()}@example.com"
  166. password = "somepassword"
  167. client.users.create(random_email, password)
  168. client.users.login(random_email, password)
  169. user_id = client.users.me()["results"]["id"]
  170. del_resp = client.users.delete(user_id, password)["results"]
  171. assert del_resp["success"], "User deletion failed."
  172. with pytest.raises(R2RException) as exc_info:
  173. # result = client.users.retrieve(user_id)
  174. client.users.login(random_email, password)
  175. # print("result = ", result)
  176. assert (
  177. exc_info.value.status_code == 404
  178. ), "User still exists after deletion."
  179. # def test_non_superuser_restrict_access(client):
  180. # # Create user
  181. # # client.users.logout()
  182. # random_email = f"test_user_{uuid.uuid4()}@example.com"
  183. # password = "somepassword"
  184. # user_id = register_and_return_user_id(client, random_email, password)
  185. # print("trying to login now....")
  186. # client.users.login(random_email, password)
  187. # # Non-superuser listing users should fail
  188. # with pytest.raises(R2RException) as exc_info:
  189. # client.users.list()
  190. # assert (
  191. # exc_info.value.status_code == 403
  192. # ), "Non-superuser listed users without error."
  193. # # Create another user
  194. # another_email = f"{uuid.uuid4()}@example.com"
  195. # another_password = "anotherpassword"
  196. # another_user_id = register_and_return_user_id(
  197. # client, another_email, another_password
  198. # )
  199. # # Non-superuser updating another user should fail
  200. # with pytest.raises(R2RException) as exc_info:
  201. # client.users.update(another_user_id, name="Nope")
  202. # assert (
  203. # exc_info.value.status_code == 403
  204. # ), "Non-superuser updated another user."
  205. def test_superuser_downgrade_permissions(client, superuser_login, config):
  206. user_email = f"test_super_{uuid.uuid4()}@test.com"
  207. user_password = "securepass"
  208. new_user_id = register_and_return_user_id(
  209. client, user_email, user_password
  210. )
  211. # Upgrade user to superuser
  212. upgraded_user = client.users.update(new_user_id, is_superuser=True)[
  213. "results"
  214. ]
  215. assert (
  216. upgraded_user["is_superuser"] == True
  217. ), "User not upgraded to superuser."
  218. # Logout admin, login as new superuser
  219. client.users.logout()
  220. client.users.login(user_email, user_password)
  221. all_users = client.users.list()["results"]
  222. assert isinstance(all_users, list), "New superuser cannot list users."
  223. # Downgrade back to normal (re-login as original admin)
  224. client.users.logout()
  225. client.users.login(config.superuser_email, config.superuser_password)
  226. downgraded_user = client.users.update(new_user_id, is_superuser=False)[
  227. "results"
  228. ]
  229. assert downgraded_user["is_superuser"] == False, "User not downgraded."
  230. # Now login as downgraded user and verify no superuser access
  231. client.users.logout()
  232. client.users.login(user_email, user_password)
  233. with pytest.raises(R2RException) as exc_info:
  234. client.users.list()
  235. assert (
  236. exc_info.value.status_code == 403
  237. ), "Downgraded user still has superuser privileges."
  238. client.users.logout()
  239. def test_non_owner_delete_collection(client):
  240. # Create owner user
  241. owner_email = f"owner_{uuid.uuid4()}@test.com"
  242. owner_password = "pwd123"
  243. client.users.create(owner_email, owner_password)
  244. client.users.login(owner_email, owner_password)
  245. coll = client.collections.create(name="Owner Collection")["results"]
  246. coll_id = coll["id"]
  247. # Create another user and get their ID
  248. non_owner_email = f"nonowner_{uuid.uuid4()}@test.com"
  249. non_owner_password = "pwd1234"
  250. client.users.logout()
  251. client.users.create(non_owner_email, non_owner_password)
  252. client.users.login(non_owner_email, non_owner_password)
  253. non_owner_id = client.users.me()["results"]["id"]
  254. client.users.logout()
  255. # Owner adds non-owner to collection
  256. client.users.login(owner_email, owner_password)
  257. client.collections.add_user(coll_id, non_owner_id)
  258. client.users.logout()
  259. # Non-owner tries to delete collection
  260. client.users.login(non_owner_email, non_owner_password)
  261. with pytest.raises(R2RException) as exc_info:
  262. result = client.collections.delete(coll_id)
  263. print("result = ", result)
  264. assert (
  265. exc_info.value.status_code == 403
  266. ), "Wrong error code for non-owner deletion attempt"
  267. # Cleanup
  268. client.users.logout()
  269. client.users.login(owner_email, owner_password)
  270. client.collections.delete(coll_id)
  271. client.users.logout()
  272. def test_update_user_with_invalid_email(client, superuser_login):
  273. # Create a user
  274. email = f"{uuid.uuid4()}@example.com"
  275. password = "password"
  276. user_id = register_and_return_user_id(client, email, password)
  277. # Attempt to update to invalid email
  278. with pytest.raises(R2RException) as exc_info:
  279. client.users.update(user_id, email="not-an-email")
  280. # Expect a validation error (likely 422)
  281. assert exc_info.value.status_code in [
  282. 400,
  283. 422,
  284. ], "Expected validation error for invalid email."
  285. client.users.logout()
  286. def test_update_user_email_already_exists(client, superuser_login):
  287. # Create two users
  288. email1 = f"{uuid.uuid4()}@example.com"
  289. email2 = f"{uuid.uuid4()}@example.com"
  290. password = "password"
  291. user1_id = register_and_return_user_id(client, email1, password)
  292. user2_id = register_and_return_user_id(client, email2, password)
  293. # Try updating user2's email to user1's email
  294. with pytest.raises(R2RException) as exc_info:
  295. client.users.update(user2_id, email=email1)
  296. # Expect a conflict (likely 409) or validation error
  297. # TODO - Error code should be in [400, 409, 422], not 500
  298. assert exc_info.value.status_code in [
  299. 400,
  300. 409,
  301. 422,
  302. 500,
  303. ], "Expected error updating email to an existing user's email."
  304. client.users.logout()
  305. def test_delete_user_with_incorrect_password(client):
  306. email = f"{uuid.uuid4()}@example.com"
  307. password = "correct_password"
  308. # user_id = register_and_return_user_id(client, email, password)
  309. client.users.create(email, password)
  310. client.users.login(email, password)
  311. user_id = client.users.me()["results"]["id"]
  312. # Attempt deletion with incorrect password
  313. with pytest.raises(R2RException) as exc_info:
  314. client.users.delete(user_id, "wrong_password")
  315. # TODO - Error code should be in [401, 403]
  316. assert exc_info.value.status_code in [
  317. 400,
  318. 401,
  319. 403,
  320. ], "Expected auth error with incorrect password on delete."
  321. def test_login_with_incorrect_password(client):
  322. email = f"{uuid.uuid4()}@example.com"
  323. password = "password123"
  324. client.users.create(email, password)
  325. # Try incorrect password
  326. with pytest.raises(R2RException) as exc_info:
  327. client.users.login(email, "wrongpass")
  328. assert (
  329. exc_info.value.status_code == 401
  330. ), "Expected 401 when logging in with incorrect password."
  331. client.users.logout()
  332. def test_refresh_token(client):
  333. # Assume that refresh token endpoint checks token validity
  334. # Try using a bogus refresh token
  335. email = f"{uuid.uuid4()}@example.com"
  336. password = "password123"
  337. client.users.create(email, password)
  338. client.users.login(email, password)
  339. client.users.refresh_token() # refresh_token="invalid_token")
  340. # assert exc_info.value.status_code in [400, 401], "Expected error using invalid refresh token."
  341. client.users.logout()
  342. @pytest.mark.skip(reason="Email verification logic not implemented.")
  343. def test_verification_with_invalid_code(client):
  344. # If your system supports email verification
  345. email = f"{uuid.uuid4()}@example.com"
  346. password = "password"
  347. register_and_return_user_id(client, email, password)
  348. # Try verifying with invalid code
  349. with pytest.raises(R2RException) as exc_info:
  350. client.users.verify_email(email, "wrong_code")
  351. assert exc_info.value.status_code in [
  352. 400,
  353. 422,
  354. ], "Expected error verifying with invalid code."
  355. client.users.logout()
  356. @pytest.mark.skip(
  357. reason="Verification and token logic depends on implementation."
  358. )
  359. def test_password_reset_with_invalid_token(client):
  360. email = f"{uuid.uuid4()}@example.com"
  361. password = "initialpass"
  362. register_and_return_user_id(client, email, password)
  363. client.users.logout()
  364. # Assume request password reset done here if needed
  365. # Try resetting with invalid token
  366. with pytest.raises(R2RException) as exc_info:
  367. client.users.reset_password("invalid_token", "newpass123")
  368. assert exc_info.value.status_code in [
  369. 400,
  370. 422,
  371. ], "Expected error resetting password with invalid token."
  372. client.users.logout()
  373. @pytest.fixture
  374. def user_with_api_key(client):
  375. """Fixture that creates a user and returns their ID and API key details"""
  376. random_email = f"{uuid.uuid4()}@example.com"
  377. password = "api_key_test_password"
  378. user_resp = client.users.create(random_email, password)["results"]
  379. user_id = user_resp["id"]
  380. # Login to create an API key
  381. client.users.login(random_email, password)
  382. api_key_resp = client.users.create_api_key(user_id)["results"]
  383. api_key = api_key_resp["api_key"]
  384. key_id = api_key_resp["key_id"]
  385. yield user_id, api_key, key_id
  386. # Cleanup
  387. try:
  388. client.users.delete_api_key(user_id, key_id)
  389. except:
  390. pass
  391. client.users.logout()
  392. def test_api_key_lifecycle(client):
  393. """Test the complete lifecycle of API keys including creation, listing, and deletion"""
  394. # Create user and login
  395. email = f"{uuid.uuid4()}@example.com"
  396. password = "api_key_test_password"
  397. user_resp = client.users.create(email, password)["results"]
  398. user_id = user_resp["id"]
  399. client.users.login(email, password)
  400. # Create API key
  401. api_key_resp = client.users.create_api_key(user_id)["results"]
  402. assert "api_key" in api_key_resp, "API key not returned"
  403. assert "key_id" in api_key_resp, "Key ID not returned"
  404. assert "public_key" in api_key_resp, "Public key not returned"
  405. key_id = api_key_resp["key_id"]
  406. # List API keys
  407. list_resp = client.users.list_api_keys(user_id)["results"]
  408. assert len(list_resp) > 0, "No API keys found after creation"
  409. assert (
  410. list_resp[0]["key_id"] == key_id
  411. ), "Listed key ID doesn't match created key"
  412. assert "updated_at" in list_resp[0], "Updated timestamp missing"
  413. assert "public_key" in list_resp[0], "Public key missing in list"
  414. # Delete API key using key_id
  415. delete_resp = client.users.delete_api_key(user_id, key_id)["results"]
  416. assert delete_resp["success"], "Failed to delete API key"
  417. # Verify deletion
  418. list_resp_after = client.users.list_api_keys(user_id)["results"]
  419. assert not any(
  420. k["key_id"] == key_id for k in list_resp_after
  421. ), "API key still exists after deletion"
  422. client.users.logout()
  423. def test_api_key_authentication(client, user_with_api_key):
  424. """Test using an API key for authentication"""
  425. user_id, api_key, _ = user_with_api_key
  426. # Create new client with API key
  427. api_client = R2RClient(client.base_url)
  428. api_client.set_api_key(api_key)
  429. # Test API key authentication
  430. me_resp = api_client.users.me()["results"]
  431. assert me_resp["id"] == user_id, "API key authentication failed"
  432. def test_api_key_permissions(client, user_with_api_key):
  433. """Test API key permission restrictions"""
  434. user_id, api_key, _ = user_with_api_key
  435. # Create new client with API key
  436. api_client = R2RClient(client.base_url)
  437. api_client.set_api_key(api_key)
  438. # Should not be able to list all users (superuser only)
  439. with pytest.raises(R2RException) as exc_info:
  440. api_client.users.list()
  441. assert (
  442. exc_info.value.status_code == 403
  443. ), "Non-superuser API key shouldn't list users"
  444. def test_invalid_api_key(client):
  445. """Test behavior with invalid API key"""
  446. api_client = R2RClient(client.base_url)
  447. api_client.set_api_key("invalid.api.key")
  448. with pytest.raises(R2RException) as exc_info:
  449. api_client.users.me()
  450. assert (
  451. exc_info.value.status_code == 401
  452. ), "Expected 401 for invalid API key"
  453. def test_multiple_api_keys(client):
  454. """Test creating and managing multiple API keys for a single user"""
  455. email = f"{uuid.uuid4()}@example.com"
  456. password = "multi_key_test_password"
  457. user_resp = client.users.create(email, password)["results"]
  458. user_id = user_resp["id"]
  459. client.users.login(email, password)
  460. # Create multiple API keys
  461. key_ids = []
  462. for i in range(3):
  463. key_resp = client.users.create_api_key(user_id)["results"]
  464. key_ids.append(key_resp["key_id"])
  465. # List and verify all keys exist
  466. list_resp = client.users.list_api_keys(user_id)["results"]
  467. assert len(list_resp) >= 3, "Not all API keys were created"
  468. # Delete keys one by one and verify counts
  469. for key_id in key_ids:
  470. client.users.delete_api_key(user_id, key_id)
  471. current_keys = client.users.list_api_keys(user_id)["results"]
  472. assert not any(
  473. k["key_id"] == key_id for k in current_keys
  474. ), f"Key {key_id} still exists after deletion"
  475. client.users.logout()