TestOAuth2.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from datetime import datetime
  4. from unittest.mock import MagicMock, Mock, patch
  5. from PyQt5.QtGui import QDesktopServices
  6. from PyQt5.QtNetwork import QNetworkReply
  7. from UM.Preferences import Preferences
  8. from cura.OAuth2.AuthorizationHelpers import AuthorizationHelpers, TOKEN_TIMESTAMP_FORMAT
  9. from cura.OAuth2.AuthorizationService import AuthorizationService, MYCLOUD_LOGOFF_URL
  10. from cura.OAuth2.LocalAuthorizationServer import LocalAuthorizationServer
  11. from cura.OAuth2.Models import OAuth2Settings, AuthenticationResponse, UserProfile
  12. CALLBACK_PORT = 32118
  13. OAUTH_ROOT = "https://account.ultimaker.com"
  14. CLOUD_API_ROOT = "https://api.ultimaker.com"
  15. OAUTH_SETTINGS = OAuth2Settings(
  16. OAUTH_SERVER_URL= OAUTH_ROOT,
  17. CALLBACK_PORT=CALLBACK_PORT,
  18. CALLBACK_URL="http://localhost:{}/callback".format(CALLBACK_PORT),
  19. CLIENT_ID="",
  20. CLIENT_SCOPES="",
  21. AUTH_DATA_PREFERENCE_KEY="test/auth_data",
  22. AUTH_SUCCESS_REDIRECT="{}/app/auth-success".format(OAUTH_ROOT),
  23. AUTH_FAILED_REDIRECT="{}/app/auth-error".format(OAUTH_ROOT)
  24. )
  25. FAILED_AUTH_RESPONSE = AuthenticationResponse(
  26. success = False,
  27. err_message = "FAILURE!"
  28. )
  29. SUCCESSFUL_AUTH_RESPONSE = AuthenticationResponse(
  30. access_token = "beep",
  31. refresh_token = "beep?",
  32. received_at = datetime.now().strftime(TOKEN_TIMESTAMP_FORMAT),
  33. expires_in = 300, # 5 minutes should be more than enough for testing
  34. success = True
  35. )
  36. EXPIRED_AUTH_RESPONSE = AuthenticationResponse(
  37. access_token = "expired",
  38. refresh_token = "beep?",
  39. received_at = datetime.now().strftime(TOKEN_TIMESTAMP_FORMAT),
  40. expires_in = 300, # 5 minutes should be more than enough for testing
  41. success = True
  42. )
  43. NO_REFRESH_AUTH_RESPONSE = AuthenticationResponse(
  44. access_token = "beep",
  45. received_at = datetime.now().strftime(TOKEN_TIMESTAMP_FORMAT),
  46. expires_in = 300, # 5 minutes should be more than enough for testing
  47. success = True
  48. )
  49. MALFORMED_AUTH_RESPONSE = AuthenticationResponse(success=False)
  50. def test_cleanAuthService() -> None:
  51. """
  52. Ensure that when setting up an AuthorizationService, no data is set.
  53. """
  54. authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
  55. authorization_service.initialize()
  56. mock_callback = Mock()
  57. authorization_service.getUserProfile(mock_callback)
  58. mock_callback.assert_called_once_with(None)
  59. assert authorization_service.getAccessToken() is None
  60. def test_refreshAccessTokenSuccess():
  61. authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
  62. authorization_service.initialize()
  63. with patch.object(AuthorizationService, "getUserProfile", return_value=UserProfile()):
  64. authorization_service._storeAuthData(SUCCESSFUL_AUTH_RESPONSE)
  65. authorization_service.onAuthStateChanged.emit = MagicMock()
  66. with patch.object(AuthorizationHelpers, "getAccessTokenUsingRefreshToken", return_value=SUCCESSFUL_AUTH_RESPONSE):
  67. authorization_service.refreshAccessToken()
  68. assert authorization_service.onAuthStateChanged.emit.called_with(True)
  69. def test__parseJWTNoRefreshToken():
  70. """
  71. Tests parsing the user profile if there is no refresh token stored, but there is a normal authentication token.
  72. The request for the user profile using the authentication token should still work normally.
  73. """
  74. authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
  75. with patch.object(AuthorizationService, "getUserProfile", return_value = UserProfile()):
  76. authorization_service._storeAuthData(NO_REFRESH_AUTH_RESPONSE)
  77. mock_callback = Mock() # To log the final profile response.
  78. mock_reply = Mock() # The user profile that the service should respond with.
  79. mock_reply.error = Mock(return_value = QNetworkReply.NetworkError.NoError)
  80. http_mock = Mock()
  81. http_mock.get = lambda url, headers_dict, callback, error_callback: callback(mock_reply)
  82. http_mock.readJSON = Mock(return_value = {"data": {"user_id": "id_ego_or_superego", "username": "Ghostkeeper"}})
  83. with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value = http_mock)):
  84. authorization_service._parseJWT(mock_callback)
  85. mock_callback.assert_called_once()
  86. profile_reply = mock_callback.call_args_list[0][0][0]
  87. assert profile_reply.user_id == "id_ego_or_superego"
  88. assert profile_reply.username == "Ghostkeeper"
  89. def test__parseJWTFailOnRefresh():
  90. """
  91. Tries to refresh the authentication token using an invalid refresh token. The request should fail.
  92. """
  93. authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
  94. with patch.object(AuthorizationService, "getUserProfile", return_value = UserProfile()):
  95. authorization_service._storeAuthData(SUCCESSFUL_AUTH_RESPONSE)
  96. mock_callback = Mock() # To log the final profile response.
  97. mock_reply = Mock() # The response that the request should give, containing an error about it failing to authenticate.
  98. mock_reply.error = Mock(return_value = QNetworkReply.NetworkError.AuthenticationRequiredError) # The reply is 403: Authentication required, meaning the server responded with a "Can't do that, Dave".
  99. http_mock = Mock()
  100. http_mock.get = lambda url, headers_dict, callback, error_callback: callback(mock_reply)
  101. http_mock.post = lambda url, data, headers_dict, callback, error_callback: callback(mock_reply)
  102. with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.readJSON", Mock(return_value = {"error_description": "Mock a failed request!"})):
  103. with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value = http_mock)):
  104. authorization_service._parseJWT(mock_callback)
  105. mock_callback.assert_called_once_with(None)
  106. def test__parseJWTSucceedOnRefresh():
  107. """
  108. Tries to refresh the authentication token using a valid refresh token. The request should succeed.
  109. """
  110. authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
  111. authorization_service.initialize()
  112. with patch.object(AuthorizationService, "getUserProfile", return_value = UserProfile()):
  113. authorization_service._storeAuthData(EXPIRED_AUTH_RESPONSE)
  114. mock_callback = Mock() # To log the final profile response.
  115. mock_reply_success = Mock() # The reply should be a failure when using the expired access token, but succeed when using the refresh token.
  116. mock_reply_success.error = Mock(return_value = QNetworkReply.NetworkError.NoError)
  117. mock_reply_failure = Mock()
  118. mock_reply_failure.error = Mock(return_value = QNetworkReply.NetworkError.AuthenticationRequiredError)
  119. http_mock = Mock()
  120. def mock_get(url, headers_dict, callback, error_callback):
  121. if(headers_dict == {"Authorization": "Bearer beep"}):
  122. callback(mock_reply_success)
  123. else:
  124. callback(mock_reply_failure)
  125. http_mock.get = mock_get
  126. http_mock.readJSON = Mock(return_value = {"data": {"user_id": "user_idea", "username": "Ghostkeeper"}})
  127. def mock_refresh(self, refresh_token, callback): # Refreshing gives a valid token.
  128. callback(SUCCESSFUL_AUTH_RESPONSE)
  129. with patch("cura.OAuth2.AuthorizationHelpers.AuthorizationHelpers.getAccessTokenUsingRefreshToken", mock_refresh):
  130. with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value = http_mock)):
  131. authorization_service._parseJWT(mock_callback)
  132. mock_callback.assert_called_once()
  133. profile_reply = mock_callback.call_args_list[0][0][0]
  134. assert profile_reply.user_id == "user_idea"
  135. assert profile_reply.username == "Ghostkeeper"
  136. def test_initialize():
  137. original_preference = MagicMock()
  138. initialize_preferences = MagicMock()
  139. authorization_service = AuthorizationService(OAUTH_SETTINGS, original_preference)
  140. authorization_service.initialize(initialize_preferences)
  141. initialize_preferences.addPreference.assert_called_once_with("test/auth_data", "{}")
  142. original_preference.addPreference.assert_not_called()
  143. def test_refreshAccessTokenFailed():
  144. """
  145. Test if the authentication is reset once the refresh token fails to refresh access.
  146. """
  147. authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
  148. authorization_service.initialize()
  149. def mock_refresh(self, refresh_token, callback): # Refreshing gives a valid token.
  150. callback(FAILED_AUTH_RESPONSE)
  151. mock_reply = Mock() # The response that the request should give, containing an error about it failing to authenticate.
  152. mock_reply.error = Mock(return_value = QNetworkReply.NetworkError.AuthenticationRequiredError) # The reply is 403: Authentication required, meaning the server responded with a "Can't do that, Dave".
  153. http_mock = Mock()
  154. http_mock.get = lambda url, headers_dict, callback, error_callback: callback(mock_reply)
  155. http_mock.post = lambda url, data, headers_dict, callback, error_callback: callback(mock_reply)
  156. with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.readJSON", Mock(return_value = {"error_description": "Mock a failed request!"})):
  157. with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value = http_mock)):
  158. authorization_service._storeAuthData(SUCCESSFUL_AUTH_RESPONSE)
  159. authorization_service.onAuthStateChanged.emit = MagicMock()
  160. with patch("cura.OAuth2.AuthorizationHelpers.AuthorizationHelpers.getAccessTokenUsingRefreshToken", mock_refresh):
  161. authorization_service.refreshAccessToken()
  162. assert authorization_service.onAuthStateChanged.emit.called_with(False)
  163. def test_refreshAccesTokenWithoutData():
  164. authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
  165. authorization_service.initialize()
  166. authorization_service.onAuthStateChanged.emit = MagicMock()
  167. authorization_service.refreshAccessToken()
  168. authorization_service.onAuthStateChanged.emit.assert_not_called()
  169. def test_failedLogin() -> None:
  170. authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
  171. authorization_service.onAuthenticationError.emit = MagicMock()
  172. authorization_service.onAuthStateChanged.emit = MagicMock()
  173. authorization_service.initialize()
  174. # Let the service think there was a failed response
  175. authorization_service._onAuthStateChanged(FAILED_AUTH_RESPONSE)
  176. # Check that the error signal was triggered
  177. assert authorization_service.onAuthenticationError.emit.call_count == 1
  178. # Since nothing changed, this should still be 0.
  179. assert authorization_service.onAuthStateChanged.emit.call_count == 0
  180. # Validate that there is no user profile or token
  181. assert authorization_service.getUserProfile() is None
  182. assert authorization_service.getAccessToken() is None
  183. @patch.object(AuthorizationService, "getUserProfile")
  184. def test_storeAuthData(get_user_profile) -> None:
  185. preferences = Preferences()
  186. authorization_service = AuthorizationService(OAUTH_SETTINGS, preferences)
  187. authorization_service.initialize()
  188. # Write stuff to the preferences.
  189. authorization_service._storeAuthData(SUCCESSFUL_AUTH_RESPONSE)
  190. preference_value = preferences.getValue(OAUTH_SETTINGS.AUTH_DATA_PREFERENCE_KEY)
  191. # Check that something was actually put in the preferences
  192. assert preference_value is not None and preference_value != {}
  193. # Create a second auth service, so we can load the data.
  194. second_auth_service = AuthorizationService(OAUTH_SETTINGS, preferences)
  195. second_auth_service.initialize()
  196. second_auth_service.loadAuthDataFromPreferences()
  197. assert second_auth_service.getAccessToken() == SUCCESSFUL_AUTH_RESPONSE.access_token
  198. @patch.object(LocalAuthorizationServer, "stop")
  199. @patch.object(LocalAuthorizationServer, "start")
  200. @patch.object(QDesktopServices, "openUrl")
  201. def test_localAuthServer(QDesktopServices_openUrl, start_auth_server, stop_auth_server) -> None:
  202. preferences = Preferences()
  203. authorization_service = AuthorizationService(OAUTH_SETTINGS, preferences)
  204. authorization_service.startAuthorizationFlow()
  205. assert QDesktopServices_openUrl.call_count == 1
  206. # Ensure that the Authorization service tried to start the server.
  207. assert start_auth_server.call_count == 1
  208. assert stop_auth_server.call_count == 0
  209. authorization_service._onAuthStateChanged(FAILED_AUTH_RESPONSE)
  210. # Ensure that it stopped the server.
  211. assert stop_auth_server.call_count == 1
  212. def test_loginAndLogout() -> None:
  213. preferences = Preferences()
  214. authorization_service = AuthorizationService(OAUTH_SETTINGS, preferences)
  215. authorization_service.onAuthenticationError.emit = MagicMock()
  216. authorization_service.onAuthStateChanged.emit = MagicMock()
  217. authorization_service.initialize()
  218. mock_reply = Mock() # The user profile that the service should respond with.
  219. mock_reply.error = Mock(return_value = QNetworkReply.NetworkError.NoError)
  220. http_mock = Mock()
  221. http_mock.get = lambda url, headers_dict, callback, error_callback: callback(mock_reply)
  222. http_mock.readJSON = Mock(return_value = {"data": {"user_id": "di_resu", "username": "Emanresu"}})
  223. # Let the service think there was a successful response
  224. with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value = http_mock)):
  225. authorization_service._onAuthStateChanged(SUCCESSFUL_AUTH_RESPONSE)
  226. # Ensure that the error signal was not triggered
  227. assert authorization_service.onAuthenticationError.emit.call_count == 0
  228. # Since we said that it went right this time, validate that we got a signal.
  229. assert authorization_service.onAuthStateChanged.emit.call_count == 1
  230. with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value = http_mock)):
  231. def callback(profile):
  232. assert profile is not None
  233. authorization_service.getUserProfile(callback)
  234. assert authorization_service.getAccessToken() == "beep"
  235. # Check that we stored the authentication data, so next time the user won't have to log in again.
  236. assert preferences.getValue("test/auth_data") is not None
  237. # We're logged in now, also check if logging out works
  238. authorization_service.deleteAuthData()
  239. assert authorization_service.onAuthStateChanged.emit.call_count == 2
  240. with patch("UM.TaskManagement.HttpRequestManager.HttpRequestManager.getInstance", MagicMock(return_value = http_mock)):
  241. def callback(profile):
  242. assert profile is None
  243. authorization_service.getUserProfile(callback)
  244. # Ensure the data is gone after we logged out.
  245. assert preferences.getValue("test/auth_data") == "{}"
  246. def test_wrongServerResponses() -> None:
  247. authorization_service = AuthorizationService(OAUTH_SETTINGS, Preferences())
  248. authorization_service.initialize()
  249. authorization_service._onAuthStateChanged(MALFORMED_AUTH_RESPONSE)
  250. def callback(profile):
  251. assert profile is None
  252. authorization_service.getUserProfile(callback)
  253. def test__generate_auth_url() -> None:
  254. preferences = Preferences()
  255. authorization_service = AuthorizationService(OAUTH_SETTINGS, preferences)
  256. query_parameters_dict = {
  257. "client_id": "",
  258. "redirect_uri": OAUTH_SETTINGS.CALLBACK_URL,
  259. "scope": OAUTH_SETTINGS.CLIENT_SCOPES,
  260. "response_type": "code"
  261. }
  262. auth_url = authorization_service._generate_auth_url(query_parameters_dict, force_browser_logout = False)
  263. assert MYCLOUD_LOGOFF_URL + "&next=" not in auth_url
  264. auth_url = authorization_service._generate_auth_url(query_parameters_dict, force_browser_logout = True)
  265. assert MYCLOUD_LOGOFF_URL + "&next=" in auth_url