sync_auth_manager.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef COMPONENTS_SYNC_DRIVER_SYNC_AUTH_MANAGER_H_
  5. #define COMPONENTS_SYNC_DRIVER_SYNC_AUTH_MANAGER_H_
  6. #include <memory>
  7. #include <string>
  8. #include "base/callback.h"
  9. #include "base/memory/raw_ptr.h"
  10. #include "base/memory/weak_ptr.h"
  11. #include "base/time/time.h"
  12. #include "base/timer/timer.h"
  13. #include "components/signin/public/identity_manager/account_info.h"
  14. #include "components/signin/public/identity_manager/identity_manager.h"
  15. #include "components/sync/driver/sync_auth_util.h"
  16. #include "components/sync/driver/sync_token_status.h"
  17. #include "components/sync/engine/connection_status.h"
  18. #include "google_apis/gaia/google_service_auth_error.h"
  19. #include "net/base/backoff_entry.h"
  20. namespace signin {
  21. class AccessTokenFetcher;
  22. struct AccessTokenInfo;
  23. } // namespace signin
  24. namespace syncer {
  25. struct SyncCredentials;
  26. // SyncAuthManager tracks the account to be used for Sync and its authentication
  27. // state. Note that this account may or may not be the primary account (as per
  28. // IdentityManager::GetPrimaryAccountInfo() etc).
  29. class SyncAuthManager : public signin::IdentityManager::Observer {
  30. public:
  31. // Called when the existence of an authenticated account changes. It's
  32. // guaranteed that this is only called for going from "no account" to "have
  33. // account" or vice versa, or if the existing account's |is_primary| bit
  34. // changed. I.e. SyncAuthManager will never directly switch from one account
  35. // to a different one. Call GetActiveAccountInfo to get the new state.
  36. using AccountStateChangedCallback = base::RepeatingClosure;
  37. // Called when the credential state changes, i.e. an access token was
  38. // added/changed/removed. Call GetCredentials to get the new state.
  39. using CredentialsChangedCallback = base::RepeatingClosure;
  40. // |identity_manager| may be null (this is the case if local Sync is enabled),
  41. // but if non-null, must outlive this object.
  42. SyncAuthManager(signin::IdentityManager* identity_manager,
  43. const AccountStateChangedCallback& account_state_changed,
  44. const CredentialsChangedCallback& credentials_changed);
  45. SyncAuthManager(const SyncAuthManager&) = delete;
  46. SyncAuthManager& operator=(const SyncAuthManager&) = delete;
  47. ~SyncAuthManager() override;
  48. // Tells the tracker to start listening for changes to the account/sign-in
  49. // status. This gets called during SyncService initialization, except in the
  50. // case of local Sync. Before this is called, GetActiveAccountInfo will always
  51. // return an empty AccountInfo. Note that this will *not* trigger any
  52. // callbacks, even if there is an active account afterwards.
  53. void RegisterForAuthNotifications();
  54. // Returns whether all relevant account information as returned by
  55. // GetActiveAccountInfo() has been fully loaded.
  56. bool IsActiveAccountInfoFullyLoaded() const;
  57. // Returns the account which should be used when communicating with the Sync
  58. // server. Note that this account may not be blessed for Sync-the-feature.
  59. SyncAccountInfo GetActiveAccountInfo() const;
  60. // Returns the last auth error that was encountered. The error could have come
  61. // from the Sync server or from the IdentityManager.
  62. GoogleServiceAuthError GetLastAuthError() const;
  63. // Returns the time at which the last auth error was set.
  64. base::Time GetLastAuthErrorTime() const;
  65. // Returns whether we are in the "Sync paused" state. That means there is a
  66. // primary account, but the user signed out in the content area, and so we
  67. // don't have credentials for it anymore.
  68. bool IsSyncPaused() const;
  69. // Returns the credentials to be passed to the SyncEngine.
  70. SyncCredentials GetCredentials() const;
  71. const std::string& access_token() const { return access_token_; }
  72. // Returns the state of the access token and token request, for display in
  73. // internals UI.
  74. SyncTokenStatus GetSyncTokenStatus() const;
  75. // Called by SyncServiceImpl when Sync starts up and will try talking to
  76. // the server soon. This initiates fetching an access token.
  77. void ConnectionOpened();
  78. // Called by SyncServiceImpl when the status of the connection to the Sync
  79. // server changed. Updates auth error state accordingly.
  80. void ConnectionStatusChanged(ConnectionStatus status);
  81. // Called by SyncServiceImpl when the connection to the Sync server is
  82. // closed (due to Sync being shut down). Clears all related state (such as
  83. // cached access token, error from the server, etc).
  84. void ConnectionClosed();
  85. // signin::IdentityManager::Observer implementation.
  86. void OnPrimaryAccountChanged(
  87. const signin::PrimaryAccountChangeEvent& event) override;
  88. void OnRefreshTokenUpdatedForAccount(
  89. const CoreAccountInfo& account_info) override;
  90. void OnRefreshTokenRemovedForAccount(
  91. const CoreAccountId& account_id) override;
  92. void OnRefreshTokensLoaded() override;
  93. // Test-only methods for inspecting/modifying internal state.
  94. bool IsRetryingAccessTokenFetchForTest() const;
  95. void ResetRequestAccessTokenBackoffForTest();
  96. private:
  97. SyncAccountInfo DetermineAccountToUse() const;
  98. // Updates |sync_account_| to the appropriate account (i.e.
  99. // DetermineAccountToUse) if necessary, and notifies observers of any changes
  100. // (sign-in/sign-out/"primary" bit change). Note that changing from one
  101. // account to another is exposed to observers as a sign-out + sign-in.
  102. // Returns whether the syncing account was updated.
  103. bool UpdateSyncAccountIfNecessary();
  104. // Invalidates any current access token, which means invalidating it with the
  105. // IdentityManager and also dropping our own cached copy. Meant to be called
  106. // when we know the current token is invalid (e.g. expired). Does not do
  107. // anything about any scheduled or ongoing request.
  108. void InvalidateAccessToken();
  109. // Clears any access token we have, and cancels any pending or scheduled
  110. // request for one.
  111. void ClearAccessTokenAndRequest();
  112. // Schedules a request for an access token according to the current
  113. // |request_access_token_backoff_|. Usually called after some transient error.
  114. void ScheduleAccessTokenRequest();
  115. // Immediately starts an access token request, unless one is already ongoing.
  116. // If another request is scheduled for later, it is canceled. Any access token
  117. // we currently have is invalidated.
  118. void RequestAccessToken();
  119. // Callback for |ongoing_access_token_fetch_|.
  120. void AccessTokenFetched(GoogleServiceAuthError error,
  121. signin::AccessTokenInfo access_token_info);
  122. void SetLastAuthError(const GoogleServiceAuthError& error);
  123. const raw_ptr<signin::IdentityManager> identity_manager_;
  124. const AccountStateChangedCallback account_state_changed_callback_;
  125. const CredentialsChangedCallback credentials_changed_callback_;
  126. bool registered_for_auth_notifications_ = false;
  127. // The account which we are using to sync. If this is non-empty, that does
  128. // *not* necessarily imply that Sync is actually running, e.g. because of
  129. // delayed startup.
  130. SyncAccountInfo sync_account_;
  131. // This is a cache of the last authentication response we received from
  132. // Chrome's identity/token management system.
  133. GoogleServiceAuthError last_auth_error_;
  134. base::Time last_auth_error_time_;
  135. // Whether Sync is currently connected to the server, i.e. ConnectionOpened()
  136. // has been called, but ConnectionClosed() hasn't. While this is false, we
  137. // don't try to get an access token. While it's true, we will *usually* have
  138. // either an access token or a pending/scheduled request for one, but this is
  139. // not guaranteed (e.g. in the case of a persistent auth error).
  140. bool connection_open_ = false;
  141. // The current access token. This is mutually exclusive with
  142. // |ongoing_access_token_fetch_| and |request_access_token_retry_timer_|:
  143. // We have at most one of a) an access token OR b) a pending request OR c) a
  144. // pending retry i.e. a scheduled request.
  145. std::string access_token_;
  146. // Pending request for an access token. Non-null iff there is a request
  147. // ongoing.
  148. std::unique_ptr<signin::AccessTokenFetcher> ongoing_access_token_fetch_;
  149. // If RequestAccessToken fails with transient error then retry requesting
  150. // access token with exponential backoff.
  151. base::OneShotTimer request_access_token_retry_timer_;
  152. net::BackoffEntry request_access_token_backoff_;
  153. // Info about the state of our access token, for display in the internals UI.
  154. // "Partial" because this instance is not fully populated - in particular,
  155. // |has_token| and |next_token_request_time| get computed on demand.
  156. SyncTokenStatus partial_token_status_;
  157. // Whether there was a retry done to fetch the access token when the request
  158. // was cancelled for the first time. This works around an issue that can only
  159. // happen once during browser startup, so it's sufficient to have a single
  160. // retry (i.e. not per request).
  161. bool access_token_retried_ = false;
  162. base::WeakPtrFactory<SyncAuthManager> weak_ptr_factory_{this};
  163. };
  164. } // namespace syncer
  165. #endif // COMPONENTS_SYNC_DRIVER_SYNC_AUTH_MANAGER_H_