Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(521)

Side by Side Diff: components/browser_sync/profile_sync_service.cc

Issue 2663783002: [Sync] Split encryption state and logic out of PSS and SBHI. (Closed)
Patch Set: Tweak comment. Created 3 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "components/browser_sync/profile_sync_service.h" 5 #include "components/browser_sync/profile_sync_service.h"
6 6
7 #include <stddef.h> 7 #include <stddef.h>
8 8
9 #include <cstddef> 9 #include <cstddef>
10 #include <map> 10 #include <map>
(...skipping 100 matching lines...) Expand 10 before | Expand all | Expand 10 after
111 using syncer::SyncCredentials; 111 using syncer::SyncCredentials;
112 using syncer::SyncProtocolError; 112 using syncer::SyncProtocolError;
113 using syncer::WeakHandle; 113 using syncer::WeakHandle;
114 114
115 namespace browser_sync { 115 namespace browser_sync {
116 116
117 namespace { 117 namespace {
118 118
119 typedef GoogleServiceAuthError AuthError; 119 typedef GoogleServiceAuthError AuthError;
120 120
121 // Events in ClearServerData flow to be recorded in histogram. Existing
122 // constants should not be deleted or reordered. New ones shold be added at the
123 // end, before CLEAR_SERVER_DATA_MAX.
124 enum ClearServerDataEvents {
125 // ClearServerData started after user switched to custom passphrase.
126 CLEAR_SERVER_DATA_STARTED,
127 // DataTypeManager reported that catchup configuration failed.
128 CLEAR_SERVER_DATA_CATCHUP_FAILED,
129 // ClearServerData flow restarted after browser restart.
130 CLEAR_SERVER_DATA_RETRIED,
131 // Success.
132 CLEAR_SERVER_DATA_SUCCEEDED,
133 // Client received RECET_LOCAL_SYNC_DATA after custom passphrase was enabled
134 // on different client.
135 CLEAR_SERVER_DATA_RESET_LOCAL_DATA_RECEIVED,
136 CLEAR_SERVER_DATA_MAX
137 };
138
139 const char kClearServerDataEventsHistogramName[] = "Sync.ClearServerDataEvents";
140
141 const char kSyncUnrecoverableErrorHistogram[] = "Sync.UnrecoverableErrors"; 121 const char kSyncUnrecoverableErrorHistogram[] = "Sync.UnrecoverableErrors";
142 122
143 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy = { 123 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy = {
144 // Number of initial errors (in sequence) to ignore before applying 124 // Number of initial errors (in sequence) to ignore before applying
145 // exponential back-off rules. 125 // exponential back-off rules.
146 0, 126 0,
147 127
148 // Initial delay for exponential back-off in ms. 128 // Initial delay for exponential back-off in ms.
149 2000, 129 2000,
150 130
(...skipping 27 matching lines...) Expand all
178 ProfileSyncService::InitParams::~InitParams() = default; 158 ProfileSyncService::InitParams::~InitParams() = default;
179 159
180 ProfileSyncService::ProfileSyncService(InitParams init_params) 160 ProfileSyncService::ProfileSyncService(InitParams init_params)
181 : SyncServiceBase(std::move(init_params.sync_client), 161 : SyncServiceBase(std::move(init_params.sync_client),
182 std::move(init_params.signin_wrapper), 162 std::move(init_params.signin_wrapper),
183 init_params.channel, 163 init_params.channel,
184 init_params.base_directory, 164 init_params.base_directory,
185 init_params.debug_identifier), 165 init_params.debug_identifier),
186 OAuth2TokenService::Consumer("sync"), 166 OAuth2TokenService::Consumer("sync"),
187 last_auth_error_(AuthError::AuthErrorNone()), 167 last_auth_error_(AuthError::AuthErrorNone()),
188 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED),
189 sync_service_url_( 168 sync_service_url_(
190 syncer::GetSyncServiceURL(*base::CommandLine::ForCurrentProcess(), 169 syncer::GetSyncServiceURL(*base::CommandLine::ForCurrentProcess(),
191 init_params.channel)), 170 init_params.channel)),
192 network_time_update_callback_( 171 network_time_update_callback_(
193 std::move(init_params.network_time_update_callback)), 172 std::move(init_params.network_time_update_callback)),
194 url_request_context_(init_params.url_request_context), 173 url_request_context_(init_params.url_request_context),
195 blocking_task_runner_(std::move(init_params.blocking_task_runner)), 174 blocking_task_runner_(std::move(init_params.blocking_task_runner)),
196 is_first_time_sync_configure_(false), 175 is_first_time_sync_configure_(false),
197 engine_initialized_(false), 176 engine_initialized_(false),
198 sync_disabled_by_admin_(false), 177 sync_disabled_by_admin_(false),
199 is_auth_in_progress_(false), 178 is_auth_in_progress_(false),
200 local_sync_backend_folder_(init_params.local_sync_backend_folder), 179 local_sync_backend_folder_(init_params.local_sync_backend_folder),
201 unrecoverable_error_reason_(ERROR_REASON_UNSET), 180 unrecoverable_error_reason_(ERROR_REASON_UNSET),
202 expect_sync_configuration_aborted_(false), 181 expect_sync_configuration_aborted_(false),
203 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
204 encrypt_everything_allowed_(true),
205 encrypt_everything_(false),
206 encryption_pending_(false),
207 configure_status_(DataTypeManager::UNKNOWN), 182 configure_status_(DataTypeManager::UNKNOWN),
208 oauth2_token_service_(init_params.oauth2_token_service), 183 oauth2_token_service_(init_params.oauth2_token_service),
209 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy), 184 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy),
210 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED), 185 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED),
211 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()), 186 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
212 gaia_cookie_manager_service_(init_params.gaia_cookie_manager_service), 187 gaia_cookie_manager_service_(init_params.gaia_cookie_manager_service),
213 network_resources_(new syncer::HttpBridgeNetworkResources), 188 network_resources_(new syncer::HttpBridgeNetworkResources),
214 start_behavior_(init_params.start_behavior), 189 start_behavior_(init_params.start_behavior),
215 passphrase_prompt_triggered_by_version_(false), 190 passphrase_prompt_triggered_by_version_(false),
216 sync_enabled_weak_factory_(this), 191 sync_enabled_weak_factory_(this),
(...skipping 149 matching lines...) Expand 10 before | Expand all | Expand 10 after
366 } else { 341 } else {
367 startup_controller_->TryStart(); 342 startup_controller_->TryStart();
368 } 343 }
369 } 344 }
370 345
371 void ProfileSyncService::StartSyncingWithServer() { 346 void ProfileSyncService::StartSyncingWithServer() {
372 if (base::FeatureList::IsEnabled( 347 if (base::FeatureList::IsEnabled(
373 switches::kSyncClearDataOnPassphraseEncryption) && 348 switches::kSyncClearDataOnPassphraseEncryption) &&
374 sync_prefs_.GetPassphraseEncryptionTransitionInProgress()) { 349 sync_prefs_.GetPassphraseEncryptionTransitionInProgress()) {
375 // We are restarting catchup configuration after browser restart. 350 // We are restarting catchup configuration after browser restart.
376 UMA_HISTOGRAM_ENUMERATION(kClearServerDataEventsHistogramName, 351 UMA_HISTOGRAM_ENUMERATION("Sync.ClearServerDataEvents",
377 CLEAR_SERVER_DATA_RETRIED, CLEAR_SERVER_DATA_MAX); 352 syncer::CLEAR_SERVER_DATA_RETRIED,
353 syncer::CLEAR_SERVER_DATA_MAX);
378 354
379 BeginConfigureCatchUpBeforeClear(); 355 crypto_->BeginConfigureCatchUpBeforeClear();
380 return; 356 return;
381 } 357 }
382 358
383 if (engine_) 359 if (engine_)
384 engine_->StartSyncingWithServer(); 360 engine_->StartSyncingWithServer();
385 } 361 }
386 362
387 void ProfileSyncService::RegisterAuthNotifications() { 363 void ProfileSyncService::RegisterAuthNotifications() {
388 DCHECK(thread_checker_.CalledOnValidThread()); 364 DCHECK(thread_checker_.CalledOnValidThread());
389 oauth2_token_service_->AddObserver(this); 365 oauth2_token_service_->AddObserver(this);
(...skipping 105 matching lines...) Expand 10 before | Expand all | Expand 10 after
495 return syncer::MakeWeakHandle(sync_js_controller_.AsWeakPtr()); 471 return syncer::MakeWeakHandle(sync_js_controller_.AsWeakPtr());
496 } 472 }
497 473
498 syncer::SyncEngine::HttpPostProviderFactoryGetter 474 syncer::SyncEngine::HttpPostProviderFactoryGetter
499 ProfileSyncService::MakeHttpPostProviderFactoryGetter() { 475 ProfileSyncService::MakeHttpPostProviderFactoryGetter() {
500 return base::Bind(&syncer::NetworkResources::GetHttpPostProviderFactory, 476 return base::Bind(&syncer::NetworkResources::GetHttpPostProviderFactory,
501 base::Unretained(network_resources_.get()), 477 base::Unretained(network_resources_.get()),
502 url_request_context_, network_time_update_callback_); 478 url_request_context_, network_time_update_callback_);
503 } 479 }
504 480
505 std::unique_ptr<syncer::SyncEncryptionHandler::NigoriState>
506 ProfileSyncService::MoveSavedNigoriState() {
507 return std::move(saved_nigori_state_);
508 }
509
510 syncer::WeakHandle<syncer::UnrecoverableErrorHandler> 481 syncer::WeakHandle<syncer::UnrecoverableErrorHandler>
511 ProfileSyncService::GetUnrecoverableErrorHandler() { 482 ProfileSyncService::GetUnrecoverableErrorHandler() {
512 return syncer::MakeWeakHandle(sync_enabled_weak_factory_.GetWeakPtr()); 483 return syncer::MakeWeakHandle(sync_enabled_weak_factory_.GetWeakPtr());
513 } 484 }
514 485
515 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const { 486 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
516 if (encryption_pending()) 487 if (encryption_pending())
517 return true; 488 return true;
518 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes(); 489 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
519 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes(); 490 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes();
(...skipping 248 matching lines...) Expand 10 before | Expand all | Expand 10 after
768 739
769 startup_controller_->Reset(GetRegisteredDataTypes()); 740 startup_controller_->Reset(GetRegisteredDataTypes());
770 741
771 // If the sync DB is getting destroyed, the local DeviceInfo is no longer 742 // If the sync DB is getting destroyed, the local DeviceInfo is no longer
772 // valid and should be cleared from the cache. 743 // valid and should be cleared from the cache.
773 if (reason == syncer::ShutdownReason::DISABLE_SYNC) { 744 if (reason == syncer::ShutdownReason::DISABLE_SYNC) {
774 local_device_->Clear(); 745 local_device_->Clear();
775 } 746 }
776 747
777 // Clear various state. 748 // Clear various state.
749 ResetCryptoState();
778 expect_sync_configuration_aborted_ = false; 750 expect_sync_configuration_aborted_ = false;
779 is_auth_in_progress_ = false; 751 is_auth_in_progress_ = false;
780 engine_initialized_ = false; 752 engine_initialized_ = false;
781 cached_passphrase_.clear();
782 encryption_pending_ = false;
783 encrypt_everything_ = false;
784 encrypted_types_ = syncer::SyncEncryptionHandler::SensitiveTypes();
785 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
786 access_token_.clear(); 753 access_token_.clear();
787 request_access_token_retry_timer_.Stop(); 754 request_access_token_retry_timer_.Stop();
788 last_snapshot_ = syncer::SyncCycleSnapshot(); 755 last_snapshot_ = syncer::SyncCycleSnapshot();
789 // Revert to "no auth error". 756 // Revert to "no auth error".
790 if (last_auth_error_.state() != GoogleServiceAuthError::NONE) 757 if (last_auth_error_.state() != GoogleServiceAuthError::NONE)
791 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone()); 758 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
792 759
793 NotifyObservers(); 760 NotifyObservers();
794 761
795 // Mark this as a clean shutdown(without crash). 762 // Mark this as a clean shutdown(without crash).
(...skipping 25 matching lines...) Expand all
821 sync_prefs_.SetFirstSetupComplete(); 788 sync_prefs_.SetFirstSetupComplete();
822 if (IsEngineInitialized()) { 789 if (IsEngineInitialized()) {
823 ReconfigureDatatypeManager(); 790 ReconfigureDatatypeManager();
824 } 791 }
825 } 792 }
826 793
827 void ProfileSyncService::UpdateLastSyncedTime() { 794 void ProfileSyncService::UpdateLastSyncedTime() {
828 sync_prefs_.SetLastSyncedTime(base::Time::Now()); 795 sync_prefs_.SetLastSyncedTime(base::Time::Now());
829 } 796 }
830 797
831 void ProfileSyncService::NotifyObservers() {
832 for (auto& observer : observers_)
833 observer.OnStateChanged();
834 }
835
836 void ProfileSyncService::NotifySyncCycleCompleted() { 798 void ProfileSyncService::NotifySyncCycleCompleted() {
837 for (auto& observer : observers_) 799 for (auto& observer : observers_)
838 observer.OnSyncCycleCompleted(); 800 observer.OnSyncCycleCompleted();
839 } 801 }
840 802
841 void ProfileSyncService::NotifyForeignSessionUpdated() { 803 void ProfileSyncService::NotifyForeignSessionUpdated() {
842 for (auto& observer : observers_) 804 for (auto& observer : observers_)
843 observer.OnForeignSessionUpdated(); 805 observer.OnForeignSessionUpdated();
844 } 806 }
845 807
(...skipping 123 matching lines...) Expand 10 before | Expand all | Expand 10 after
969 engine_->RequestBufferedProtocolEventsAndEnableForwarding(); 931 engine_->RequestBufferedProtocolEventsAndEnableForwarding();
970 } 932 }
971 933
972 if (type_debug_info_observers_.might_have_observers()) { 934 if (type_debug_info_observers_.might_have_observers()) {
973 engine_->EnableDirectoryTypeDebugInfoForwarding(); 935 engine_->EnableDirectoryTypeDebugInfoForwarding();
974 } 936 }
975 937
976 // If we have a cached passphrase use it to decrypt/encrypt data now that the 938 // If we have a cached passphrase use it to decrypt/encrypt data now that the
977 // backend is initialized. We want to call this before notifying observers in 939 // backend is initialized. We want to call this before notifying observers in
978 // case this operation affects the "passphrase required" status. 940 // case this operation affects the "passphrase required" status.
979 ConsumeCachedPassphraseIfPossible(); 941 crypto_->ConsumeCachedPassphraseIfPossible();
980 942
981 // The very first time the backend initializes is effectively the first time 943 // The very first time the backend initializes is effectively the first time
982 // we can say we successfully "synced". LastSyncedTime will only be null in 944 // we can say we successfully "synced". LastSyncedTime will only be null in
983 // this case, because the pref wasn't restored on StartUp. 945 // this case, because the pref wasn't restored on StartUp.
984 if (sync_prefs_.GetLastSyncedTime().is_null()) { 946 if (sync_prefs_.GetLastSyncedTime().is_null()) {
985 UpdateLastSyncedTime(); 947 UpdateLastSyncedTime();
986 } 948 }
987 949
988 data_type_manager_.reset( 950 data_type_manager_.reset(
989 sync_client_->GetSyncApiComponentFactory()->CreateDataTypeManager( 951 sync_client_->GetSyncApiComponentFactory()->CreateDataTypeManager(
990 initial_types, debug_info_listener_, &data_type_controllers_, this, 952 initial_types, debug_info_listener_, &data_type_controllers_, this,
991 engine_.get(), this)); 953 engine_.get(), this));
992 954
955 crypto_->SetSyncEngine(engine_.get());
956 crypto_->SetDataTypeManager(data_type_manager_.get());
957
993 // Auto-start means IsFirstSetupComplete gets set automatically. 958 // Auto-start means IsFirstSetupComplete gets set automatically.
994 if (start_behavior_ == AUTO_START && !IsFirstSetupComplete()) { 959 if (start_behavior_ == AUTO_START && !IsFirstSetupComplete()) {
995 // This will trigger a configure if it completes setup. 960 // This will trigger a configure if it completes setup.
996 SetFirstSetupComplete(); 961 SetFirstSetupComplete();
997 } else if (CanConfigureDataTypes()) { 962 } else if (CanConfigureDataTypes()) {
998 ConfigureDataTypeManager(); 963 ConfigureDataTypeManager();
999 } 964 }
1000 965
1001 // Check for a cookie jar mismatch. 966 // Check for a cookie jar mismatch.
1002 std::vector<gaia::ListedAccount> accounts; 967 std::vector<gaia::ListedAccount> accounts;
(...skipping 129 matching lines...) Expand 10 before | Expand all | Expand 10 after
1132 } 1097 }
1133 } 1098 }
1134 1099
1135 const GoogleServiceAuthError auth_error = 1100 const GoogleServiceAuthError auth_error =
1136 ConnectionStatusToAuthError(status); 1101 ConnectionStatusToAuthError(status);
1137 DVLOG(1) << "Connection status change: " << auth_error.ToString(); 1102 DVLOG(1) << "Connection status change: " << auth_error.ToString();
1138 UpdateAuthErrorState(auth_error); 1103 UpdateAuthErrorState(auth_error);
1139 } 1104 }
1140 } 1105 }
1141 1106
1142 void ProfileSyncService::OnPassphraseRequired(
1143 syncer::PassphraseRequiredReason reason,
1144 const sync_pb::EncryptedData& pending_keys) {
1145 DCHECK(thread_checker_.CalledOnValidThread());
1146 DCHECK(engine_);
1147 DCHECK(engine_->IsNigoriEnabled());
1148
1149 // TODO(lipalani) : add this check to other locations as well.
1150 if (HasUnrecoverableError()) {
1151 // When unrecoverable error is detected we post a task to shutdown the
1152 // engine. The task might not have executed yet.
1153 return;
1154 }
1155
1156 DVLOG(1) << "Passphrase required with reason: "
1157 << syncer::PassphraseRequiredReasonToString(reason);
1158 passphrase_required_reason_ = reason;
1159
1160 const syncer::ModelTypeSet types = GetPreferredDataTypes();
1161 if (data_type_manager_) {
1162 // Reconfigure without the encrypted types (excluded implicitly via the
1163 // failed datatypes handler).
1164 data_type_manager_->Configure(types, syncer::CONFIGURE_REASON_CRYPTO);
1165 }
1166
1167 // Notify observers that the passphrase status may have changed.
1168 NotifyObservers();
1169 }
1170
1171 void ProfileSyncService::OnPassphraseAccepted() {
1172 DCHECK(thread_checker_.CalledOnValidThread());
1173 DVLOG(1) << "Received OnPassphraseAccepted.";
1174
1175 // If the pending keys were resolved via keystore, it's possible we never
1176 // consumed our cached passphrase. Clear it now.
1177 if (!cached_passphrase_.empty())
1178 cached_passphrase_.clear();
1179
1180 // Reset passphrase_required_reason_ since we know we no longer require the
1181 // passphrase.
1182 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1183
1184 // Make sure the data types that depend on the passphrase are started at
1185 // this time.
1186 const syncer::ModelTypeSet types = GetPreferredDataTypes();
1187 if (data_type_manager_) {
1188 // Re-enable any encrypted types if necessary.
1189 data_type_manager_->Configure(types, syncer::CONFIGURE_REASON_CRYPTO);
1190 }
1191
1192 NotifyObservers();
1193 }
1194
1195 void ProfileSyncService::OnEncryptedTypesChanged(
1196 syncer::ModelTypeSet encrypted_types,
1197 bool encrypt_everything) {
1198 DCHECK(thread_checker_.CalledOnValidThread());
1199 encrypted_types_ = encrypted_types;
1200 encrypt_everything_ = encrypt_everything;
1201 DCHECK(encrypt_everything_allowed_ || !encrypt_everything_);
1202 DVLOG(1) << "Encrypted types changed to "
1203 << syncer::ModelTypeSetToString(encrypted_types_)
1204 << " (encrypt everything is set to "
1205 << (encrypt_everything_ ? "true" : "false") << ")";
1206 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
1207
1208 NotifyObservers();
1209 }
1210
1211 void ProfileSyncService::OnEncryptionComplete() {
1212 DCHECK(thread_checker_.CalledOnValidThread());
1213 DVLOG(1) << "Encryption complete";
1214 if (encryption_pending_ && encrypt_everything_) {
1215 encryption_pending_ = false;
1216 // This is to nudge the integration tests when encryption is
1217 // finished.
1218 NotifyObservers();
1219 }
1220 }
1221
1222 void ProfileSyncService::OnMigrationNeededForTypes(syncer::ModelTypeSet types) { 1107 void ProfileSyncService::OnMigrationNeededForTypes(syncer::ModelTypeSet types) {
1223 DCHECK(thread_checker_.CalledOnValidThread()); 1108 DCHECK(thread_checker_.CalledOnValidThread());
1224 DCHECK(engine_initialized_); 1109 DCHECK(engine_initialized_);
1225 DCHECK(data_type_manager_); 1110 DCHECK(data_type_manager_);
1226 1111
1227 // Migrator must be valid, because we don't sync until it is created and this 1112 // Migrator must be valid, because we don't sync until it is created and this
1228 // callback originates from a sync cycle. 1113 // callback originates from a sync cycle.
1229 migrator_->MigrateTypes(types); 1114 migrator_->MigrateTypes(types);
1230 } 1115 }
1231 1116
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
1266 break; 1151 break;
1267 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT: 1152 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT:
1268 // Sync disabled by domain admin. we should stop syncing until next 1153 // Sync disabled by domain admin. we should stop syncing until next
1269 // restart. 1154 // restart.
1270 sync_disabled_by_admin_ = true; 1155 sync_disabled_by_admin_ = true;
1271 ShutdownImpl(syncer::DISABLE_SYNC); 1156 ShutdownImpl(syncer::DISABLE_SYNC);
1272 break; 1157 break;
1273 case syncer::RESET_LOCAL_SYNC_DATA: 1158 case syncer::RESET_LOCAL_SYNC_DATA:
1274 ShutdownImpl(syncer::DISABLE_SYNC); 1159 ShutdownImpl(syncer::DISABLE_SYNC);
1275 startup_controller_->TryStart(); 1160 startup_controller_->TryStart();
1276 UMA_HISTOGRAM_ENUMERATION(kClearServerDataEventsHistogramName, 1161 UMA_HISTOGRAM_ENUMERATION(
1277 CLEAR_SERVER_DATA_RESET_LOCAL_DATA_RECEIVED, 1162 "Sync.ClearServerDataEvents",
1278 CLEAR_SERVER_DATA_MAX); 1163 syncer::CLEAR_SERVER_DATA_RESET_LOCAL_DATA_RECEIVED,
1164 syncer::CLEAR_SERVER_DATA_MAX);
1279 break; 1165 break;
1280 default: 1166 default:
1281 NOTREACHED(); 1167 NOTREACHED();
1282 } 1168 }
1283 NotifyObservers(); 1169 NotifyObservers();
1284 } 1170 }
1285 1171
1286 void ProfileSyncService::OnLocalSetPassphraseEncryption(
1287 const syncer::SyncEncryptionHandler::NigoriState& nigori_state) {
1288 DCHECK(thread_checker_.CalledOnValidThread());
1289 if (!base::FeatureList::IsEnabled(
1290 switches::kSyncClearDataOnPassphraseEncryption))
1291 return;
1292
1293 // At this point the user has set a custom passphrase and we have received the
1294 // updated nigori state. Time to cache the nigori state, and catch up the
1295 // active data types.
1296 UMA_HISTOGRAM_ENUMERATION(kClearServerDataEventsHistogramName,
1297 CLEAR_SERVER_DATA_STARTED, CLEAR_SERVER_DATA_MAX);
1298 sync_prefs_.SetNigoriSpecificsForPassphraseTransition(
1299 nigori_state.nigori_specifics);
1300 sync_prefs_.SetPassphraseEncryptionTransitionInProgress(true);
1301 BeginConfigureCatchUpBeforeClear();
1302 }
1303
1304 void ProfileSyncService::BeginConfigureCatchUpBeforeClear() {
1305 DCHECK(data_type_manager_);
1306 DCHECK(!saved_nigori_state_);
1307 saved_nigori_state_ =
1308 base::MakeUnique<syncer::SyncEncryptionHandler::NigoriState>();
1309 sync_prefs_.GetNigoriSpecificsForPassphraseTransition(
1310 &saved_nigori_state_->nigori_specifics);
1311 const syncer::ModelTypeSet types = GetActiveDataTypes();
1312 data_type_manager_->Configure(types, syncer::CONFIGURE_REASON_CATCH_UP);
1313 }
1314
1315 void ProfileSyncService::ClearAndRestartSyncForPassphraseEncryption() { 1172 void ProfileSyncService::ClearAndRestartSyncForPassphraseEncryption() {
1316 DCHECK(thread_checker_.CalledOnValidThread()); 1173 DCHECK(thread_checker_.CalledOnValidThread());
1317 engine_->ClearServerData( 1174 engine_->ClearServerData(
1318 base::Bind(&ProfileSyncService::OnClearServerDataDone, 1175 base::Bind(&ProfileSyncService::OnClearServerDataDone,
1319 sync_enabled_weak_factory_.GetWeakPtr())); 1176 sync_enabled_weak_factory_.GetWeakPtr()));
1320 } 1177 }
1321 1178
1322 void ProfileSyncService::OnClearServerDataDone() { 1179 void ProfileSyncService::OnClearServerDataDone() {
1323 DCHECK(sync_prefs_.GetPassphraseEncryptionTransitionInProgress()); 1180 DCHECK(sync_prefs_.GetPassphraseEncryptionTransitionInProgress());
1324 sync_prefs_.SetPassphraseEncryptionTransitionInProgress(false); 1181 sync_prefs_.SetPassphraseEncryptionTransitionInProgress(false);
1325 1182
1326 // Call to ClearServerData generates new keystore key on the server. This 1183 // Call to ClearServerData generates new keystore key on the server. This
1327 // makes keystore bootstrap token invalid. Let's clear it from preferences. 1184 // makes keystore bootstrap token invalid. Let's clear it from preferences.
1328 sync_prefs_.SetKeystoreEncryptionBootstrapToken(std::string()); 1185 sync_prefs_.SetKeystoreEncryptionBootstrapToken(std::string());
1329 1186
1330 // Shutdown sync, delete the Directory, then restart, restoring the cached 1187 // Shutdown sync, delete the Directory, then restart, restoring the cached
1331 // nigori state. 1188 // nigori state.
1332 ShutdownImpl(syncer::DISABLE_SYNC); 1189 ShutdownImpl(syncer::DISABLE_SYNC);
1333 startup_controller_->TryStart(); 1190 startup_controller_->TryStart();
1334 UMA_HISTOGRAM_ENUMERATION(kClearServerDataEventsHistogramName, 1191 UMA_HISTOGRAM_ENUMERATION("Sync.ClearServerDataEvents",
1335 CLEAR_SERVER_DATA_SUCCEEDED, CLEAR_SERVER_DATA_MAX); 1192 syncer::CLEAR_SERVER_DATA_SUCCEEDED,
1193 syncer::CLEAR_SERVER_DATA_MAX);
1336 } 1194 }
1337 1195
1338 void ProfileSyncService::OnConfigureDone( 1196 void ProfileSyncService::OnConfigureDone(
1339 const DataTypeManager::ConfigureResult& result) { 1197 const DataTypeManager::ConfigureResult& result) {
1340 DCHECK(thread_checker_.CalledOnValidThread()); 1198 DCHECK(thread_checker_.CalledOnValidThread());
1341 configure_status_ = result.status; 1199 configure_status_ = result.status;
1342 data_type_status_table_ = result.data_type_status_table; 1200 data_type_status_table_ = result.data_type_status_table;
1343 1201
1344 // We should have cleared our cached passphrase before we get here (in 1202 // We should have cleared our cached passphrase before we get here (in
1345 // OnEngineInitialized()). 1203 // OnEngineInitialized()).
1346 DCHECK(cached_passphrase_.empty()); 1204 DCHECK(crypto_->cached_passphrase().empty());
1347 1205
1348 if (!sync_configure_start_time_.is_null()) { 1206 if (!sync_configure_start_time_.is_null()) {
1349 if (configure_status_ == DataTypeManager::OK) { 1207 if (configure_status_ == DataTypeManager::OK) {
1350 base::Time sync_configure_stop_time = base::Time::Now(); 1208 base::Time sync_configure_stop_time = base::Time::Now();
1351 base::TimeDelta delta = 1209 base::TimeDelta delta =
1352 sync_configure_stop_time - sync_configure_start_time_; 1210 sync_configure_stop_time - sync_configure_start_time_;
1353 if (is_first_time_sync_configure_) { 1211 if (is_first_time_sync_configure_) {
1354 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta); 1212 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta);
1355 } else { 1213 } else {
1356 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime", delta); 1214 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime", delta);
(...skipping 18 matching lines...) Expand all
1375 expect_sync_configuration_aborted_) { 1233 expect_sync_configuration_aborted_) {
1376 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted"; 1234 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1377 expect_sync_configuration_aborted_ = false; 1235 expect_sync_configuration_aborted_ = false;
1378 return; 1236 return;
1379 } 1237 }
1380 1238
1381 // Handle unrecoverable error. 1239 // Handle unrecoverable error.
1382 if (configure_status_ != DataTypeManager::OK) { 1240 if (configure_status_ != DataTypeManager::OK) {
1383 if (result.was_catch_up_configure) { 1241 if (result.was_catch_up_configure) {
1384 // Record catchup configuration failure. 1242 // Record catchup configuration failure.
1385 UMA_HISTOGRAM_ENUMERATION(kClearServerDataEventsHistogramName, 1243 UMA_HISTOGRAM_ENUMERATION("Sync.ClearServerDataEvents",
1386 CLEAR_SERVER_DATA_CATCHUP_FAILED, 1244 syncer::CLEAR_SERVER_DATA_CATCHUP_FAILED,
1387 CLEAR_SERVER_DATA_MAX); 1245 syncer::CLEAR_SERVER_DATA_MAX);
1388 } 1246 }
1389 // Something catastrophic had happened. We should only have one 1247 // Something catastrophic had happened. We should only have one
1390 // error representing it. 1248 // error representing it.
1391 syncer::SyncError error = data_type_status_table_.GetUnrecoverableError(); 1249 syncer::SyncError error = data_type_status_table_.GetUnrecoverableError();
1392 DCHECK(error.IsSet()); 1250 DCHECK(error.IsSet());
1393 std::string message = 1251 std::string message =
1394 "Sync configuration failed with status " + 1252 "Sync configuration failed with status " +
1395 DataTypeManager::ConfigureStatusToString(configure_status_) + 1253 DataTypeManager::ConfigureStatusToString(configure_status_) +
1396 " caused by " + 1254 " caused by " +
1397 syncer::ModelTypeSetToString( 1255 syncer::ModelTypeSetToString(
1398 data_type_status_table_.GetUnrecoverableErrorTypes()) + 1256 data_type_status_table_.GetUnrecoverableErrorTypes()) +
1399 ": " + error.message(); 1257 ": " + error.message();
1400 LOG(ERROR) << "ProfileSyncService error: " << message; 1258 LOG(ERROR) << "ProfileSyncService error: " << message;
1401 OnInternalUnrecoverableError(error.location(), message, true, 1259 OnInternalUnrecoverableError(error.location(), message, true,
1402 ERROR_REASON_CONFIGURATION_FAILURE); 1260 ERROR_REASON_CONFIGURATION_FAILURE);
1403 return; 1261 return;
1404 } 1262 }
1405 1263
1406 DCHECK_EQ(DataTypeManager::OK, configure_status_); 1264 DCHECK_EQ(DataTypeManager::OK, configure_status_);
1407 1265
1408 // We should never get in a state where we have no encrypted datatypes 1266 // We should never get in a state where we have no encrypted datatypes
1409 // enabled, and yet we still think we require a passphrase for decryption. 1267 // enabled, and yet we still think we require a passphrase for decryption.
1410 DCHECK( 1268 DCHECK(
1411 !(IsPassphraseRequiredForDecryption() && !IsEncryptedDatatypeEnabled())); 1269 !(IsPassphraseRequiredForDecryption() && !IsEncryptedDatatypeEnabled()));
1412 1270
1413 // This must be done before we start syncing with the server to avoid 1271 // This must be done before we start syncing with the server to avoid
1414 // sending unencrypted data up on a first time sync. 1272 // sending unencrypted data up on a first time sync.
1415 if (encryption_pending_) 1273 if (crypto_->encryption_pending())
1416 engine_->EnableEncryptEverything(); 1274 engine_->EnableEncryptEverything();
1417 NotifyObservers(); 1275 NotifyObservers();
1418 1276
1419 if (migrator_.get() && migrator_->state() != BackendMigrator::IDLE) { 1277 if (migrator_.get() && migrator_->state() != BackendMigrator::IDLE) {
1420 // Migration in progress. Let the migrator know we just finished 1278 // Migration in progress. Let the migrator know we just finished
1421 // configuring something. It will be up to the migrator to call 1279 // configuring something. It will be up to the migrator to call
1422 // StartSyncingWithServer() if migration is now finished. 1280 // StartSyncingWithServer() if migration is now finished.
1423 migrator_->OnConfigureDone(result); 1281 migrator_->OnConfigureDone(result);
1424 return; 1282 return;
1425 } 1283 }
(...skipping 165 matching lines...) Expand 10 before | Expand all | Expand 10 after
1591 return current_experiments_; 1449 return current_experiments_;
1592 } 1450 }
1593 1451
1594 bool ProfileSyncService::HasUnrecoverableError() const { 1452 bool ProfileSyncService::HasUnrecoverableError() const {
1595 DCHECK(thread_checker_.CalledOnValidThread()); 1453 DCHECK(thread_checker_.CalledOnValidThread());
1596 return unrecoverable_error_reason_ != ERROR_REASON_UNSET; 1454 return unrecoverable_error_reason_ != ERROR_REASON_UNSET;
1597 } 1455 }
1598 1456
1599 bool ProfileSyncService::IsPassphraseRequired() const { 1457 bool ProfileSyncService::IsPassphraseRequired() const {
1600 DCHECK(thread_checker_.CalledOnValidThread()); 1458 DCHECK(thread_checker_.CalledOnValidThread());
1601 return passphrase_required_reason_ != syncer::REASON_PASSPHRASE_NOT_REQUIRED; 1459 return crypto_->passphrase_required_reason() !=
1460 syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1602 } 1461 }
1603 1462
1604 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const { 1463 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1605 DCHECK(thread_checker_.CalledOnValidThread()); 1464 DCHECK(thread_checker_.CalledOnValidThread());
1606 // If there is an encrypted datatype enabled and we don't have the proper 1465 // If there is an encrypted datatype enabled and we don't have the proper
1607 // passphrase, we must prompt the user for a passphrase. The only way for the 1466 // passphrase, we must prompt the user for a passphrase. The only way for the
1608 // user to avoid entering their passphrase is to disable the encrypted types. 1467 // user to avoid entering their passphrase is to disable the encrypted types.
1609 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired(); 1468 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1610 } 1469 }
1611 1470
(...skipping 152 matching lines...) Expand 10 before | Expand all | Expand 10 after
1764 for (DataTypeController::TypeMap::const_iterator it = 1623 for (DataTypeController::TypeMap::const_iterator it =
1765 data_type_controllers_.begin(); 1624 data_type_controllers_.begin();
1766 it != data_type_controllers_.end(); ++it) { 1625 it != data_type_controllers_.end(); ++it) {
1767 registered_types.Put(it->first); 1626 registered_types.Put(it->first);
1768 } 1627 }
1769 return registered_types; 1628 return registered_types;
1770 } 1629 }
1771 1630
1772 bool ProfileSyncService::IsUsingSecondaryPassphrase() const { 1631 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1773 DCHECK(thread_checker_.CalledOnValidThread()); 1632 DCHECK(thread_checker_.CalledOnValidThread());
1774 syncer::PassphraseType passphrase_type = GetPassphraseType(); 1633 return crypto_->IsUsingSecondaryPassphrase();
1775 return passphrase_type ==
1776 syncer::PassphraseType::FROZEN_IMPLICIT_PASSPHRASE ||
1777 passphrase_type == syncer::PassphraseType::CUSTOM_PASSPHRASE;
1778 } 1634 }
1779 1635
1780 std::string ProfileSyncService::GetCustomPassphraseKey() const { 1636 std::string ProfileSyncService::GetCustomPassphraseKey() const {
1781 DCHECK(thread_checker_.CalledOnValidThread()); 1637 DCHECK(thread_checker_.CalledOnValidThread());
1782 syncer::SystemEncryptor encryptor; 1638 syncer::SystemEncryptor encryptor;
1783 syncer::Cryptographer cryptographer(&encryptor); 1639 syncer::Cryptographer cryptographer(&encryptor);
1784 cryptographer.Bootstrap(sync_prefs_.GetEncryptionBootstrapToken()); 1640 cryptographer.Bootstrap(sync_prefs_.GetEncryptionBootstrapToken());
1785 return cryptographer.GetDefaultNigoriKeyData(); 1641 return cryptographer.GetDefaultNigoriKeyData();
1786 } 1642 }
1787 1643
1788 syncer::PassphraseType ProfileSyncService::GetPassphraseType() const { 1644 syncer::PassphraseType ProfileSyncService::GetPassphraseType() const {
1789 DCHECK(thread_checker_.CalledOnValidThread()); 1645 DCHECK(thread_checker_.CalledOnValidThread());
1790 return engine_->GetPassphraseType(); 1646 return crypto_->GetPassphraseType();
1791 } 1647 }
1792 1648
1793 base::Time ProfileSyncService::GetExplicitPassphraseTime() const { 1649 base::Time ProfileSyncService::GetExplicitPassphraseTime() const {
1794 DCHECK(thread_checker_.CalledOnValidThread()); 1650 DCHECK(thread_checker_.CalledOnValidThread());
1795 return engine_->GetExplicitPassphraseTime(); 1651 return crypto_->GetExplicitPassphraseTime();
1796 } 1652 }
1797 1653
1798 bool ProfileSyncService::IsCryptographerReady( 1654 bool ProfileSyncService::IsCryptographerReady(
1799 const syncer::BaseTransaction* trans) const { 1655 const syncer::BaseTransaction* trans) const {
1800 DCHECK(thread_checker_.CalledOnValidThread()); 1656 DCHECK(thread_checker_.CalledOnValidThread());
1801 return engine_ && engine_->IsCryptographerReady(trans); 1657 return engine_ && engine_->IsCryptographerReady(trans);
1802 } 1658 }
1803 1659
1804 void ProfileSyncService::SetPlatformSyncAllowedProvider( 1660 void ProfileSyncService::SetPlatformSyncAllowedProvider(
1805 const PlatformSyncAllowedProvider& platform_sync_allowed_provider) { 1661 const PlatformSyncAllowedProvider& platform_sync_allowed_provider) {
(...skipping 188 matching lines...) Expand 10 before | Expand all | Expand 10 after
1994 dtc_iter->second->GetStatusCounters(BindToCurrentThread( 1850 dtc_iter->second->GetStatusCounters(BindToCurrentThread(
1995 base::Bind(&ProfileSyncService::OnDatatypeStatusCounterUpdated, 1851 base::Bind(&ProfileSyncService::OnDatatypeStatusCounterUpdated,
1996 base::Unretained(this)))); 1852 base::Unretained(this))));
1997 } 1853 }
1998 1854
1999 result->Append(std::move(type_status)); 1855 result->Append(std::move(type_status));
2000 } 1856 }
2001 return std::move(result); 1857 return std::move(result);
2002 } 1858 }
2003 1859
2004 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2005 // If no cached passphrase, or sync engine hasn't started up yet, just exit.
2006 // If the engine isn't running yet, OnEngineInitialized() will call this
2007 // method again after the engine starts up.
2008 if (cached_passphrase_.empty() || !IsEngineInitialized())
2009 return;
2010
2011 // Engine is up and running, so we can consume the cached passphrase.
2012 std::string passphrase = cached_passphrase_;
2013 cached_passphrase_.clear();
2014
2015 // If we need a passphrase to decrypt data, try the cached passphrase.
2016 if (passphrase_required_reason() == syncer::REASON_DECRYPTION) {
2017 if (SetDecryptionPassphrase(passphrase)) {
2018 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2019 return;
2020 }
2021 }
2022
2023 // If we get here, we don't have pending keys (or at least, the passphrase
2024 // doesn't decrypt them) - just try to re-encrypt using the encryption
2025 // passphrase.
2026 if (!IsUsingSecondaryPassphrase())
2027 SetEncryptionPassphrase(passphrase, IMPLICIT);
2028 }
2029
2030 void ProfileSyncService::RequestAccessToken() { 1860 void ProfileSyncService::RequestAccessToken() {
2031 // Only one active request at a time. 1861 // Only one active request at a time.
2032 if (access_token_request_ != nullptr) 1862 if (access_token_request_ != nullptr)
2033 return; 1863 return;
2034 request_access_token_retry_timer_.Stop(); 1864 request_access_token_retry_timer_.Stop();
2035 OAuth2TokenService::ScopeSet oauth2_scopes; 1865 OAuth2TokenService::ScopeSet oauth2_scopes;
2036 oauth2_scopes.insert(signin_->GetSyncScopeToUse()); 1866 oauth2_scopes.insert(signin_->GetSyncScopeToUse());
2037 1867
2038 // Invalidate previous token, otherwise token service will return the same 1868 // Invalidate previous token, otherwise token service will return the same
2039 // token again. 1869 // token again.
2040 const std::string& account_id = signin_->GetAccountIdToUse(); 1870 const std::string& account_id = signin_->GetAccountIdToUse();
2041 if (!access_token_.empty()) { 1871 if (!access_token_.empty()) {
2042 oauth2_token_service_->InvalidateAccessToken(account_id, oauth2_scopes, 1872 oauth2_token_service_->InvalidateAccessToken(account_id, oauth2_scopes,
2043 access_token_); 1873 access_token_);
2044 } 1874 }
2045 1875
2046 access_token_.clear(); 1876 access_token_.clear();
2047 1877
2048 token_request_time_ = base::Time::Now(); 1878 token_request_time_ = base::Time::Now();
2049 token_receive_time_ = base::Time(); 1879 token_receive_time_ = base::Time();
2050 next_token_request_time_ = base::Time(); 1880 next_token_request_time_ = base::Time();
2051 access_token_request_ = 1881 access_token_request_ =
2052 oauth2_token_service_->StartRequest(account_id, oauth2_scopes, this); 1882 oauth2_token_service_->StartRequest(account_id, oauth2_scopes, this);
2053 } 1883 }
2054 1884
2055 void ProfileSyncService::SetEncryptionPassphrase(const std::string& passphrase, 1885 void ProfileSyncService::SetEncryptionPassphrase(const std::string& passphrase,
2056 PassphraseType type) { 1886 PassphraseType type) {
2057 DCHECK(thread_checker_.CalledOnValidThread()); 1887 DCHECK(thread_checker_.CalledOnValidThread());
2058 // This should only be called when the engine has been initialized. 1888 crypto_->SetEncryptionPassphrase(passphrase, type == EXPLICIT);
2059 DCHECK(IsEngineInitialized());
2060 DCHECK(!(type == IMPLICIT && IsUsingSecondaryPassphrase()))
2061 << "Data is already encrypted using an explicit passphrase";
2062 DCHECK(!(type == EXPLICIT &&
2063 passphrase_required_reason_ == syncer::REASON_DECRYPTION))
2064 << "Can not set explicit passphrase when decryption is needed.";
2065
2066 DVLOG(1) << "Setting " << (type == EXPLICIT ? "explicit" : "implicit")
2067 << " passphrase for encryption.";
2068 if (passphrase_required_reason_ == syncer::REASON_ENCRYPTION) {
2069 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2070 // keys. Hence, as long as we're not trying to do an invalid passphrase
2071 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2072 // will succeed. If for some reason a new encryption key arrives via
2073 // sync later, the SBH will trigger another OnPassphraseRequired().
2074 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
2075 NotifyObservers();
2076 }
2077 engine_->SetEncryptionPassphrase(passphrase, type == EXPLICIT);
2078 } 1889 }
2079 1890
2080 bool ProfileSyncService::SetDecryptionPassphrase( 1891 bool ProfileSyncService::SetDecryptionPassphrase(
2081 const std::string& passphrase) { 1892 const std::string& passphrase) {
2082 DCHECK(thread_checker_.CalledOnValidThread()); 1893 DCHECK(thread_checker_.CalledOnValidThread());
2083 if (IsPassphraseRequired()) { 1894 if (IsPassphraseRequired()) {
2084 DVLOG(1) << "Setting passphrase for decryption."; 1895 DVLOG(1) << "Setting passphrase for decryption.";
2085 bool result = engine_->SetDecryptionPassphrase(passphrase); 1896 bool result = crypto_->SetDecryptionPassphrase(passphrase);
2086 UMA_HISTOGRAM_BOOLEAN("Sync.PassphraseDecryptionSucceeded", result); 1897 UMA_HISTOGRAM_BOOLEAN("Sync.PassphraseDecryptionSucceeded", result);
2087 return result; 1898 return result;
2088 } else { 1899 } else {
2089 NOTREACHED() << "SetDecryptionPassphrase must not be called when " 1900 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2090 "IsPassphraseRequired() is false."; 1901 "IsPassphraseRequired() is false.";
2091 return false; 1902 return false;
2092 } 1903 }
2093 } 1904 }
2094 1905
2095 bool ProfileSyncService::IsEncryptEverythingAllowed() const { 1906 bool ProfileSyncService::IsEncryptEverythingAllowed() const {
2096 DCHECK(thread_checker_.CalledOnValidThread()); 1907 DCHECK(thread_checker_.CalledOnValidThread());
2097 return encrypt_everything_allowed_; 1908 return crypto_->IsEncryptEverythingAllowed();
2098 } 1909 }
2099 1910
2100 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed) { 1911 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed) {
2101 DCHECK(thread_checker_.CalledOnValidThread()); 1912 DCHECK(thread_checker_.CalledOnValidThread());
2102 DCHECK(allowed || !IsEngineInitialized() || !IsEncryptEverythingEnabled()); 1913 crypto_->SetEncryptEverythingAllowed(allowed);
2103 encrypt_everything_allowed_ = allowed;
2104 } 1914 }
2105 1915
2106 void ProfileSyncService::EnableEncryptEverything() { 1916 void ProfileSyncService::EnableEncryptEverything() {
2107 DCHECK(thread_checker_.CalledOnValidThread()); 1917 DCHECK(thread_checker_.CalledOnValidThread());
2108 DCHECK(IsEncryptEverythingAllowed()); 1918 crypto_->EnableEncryptEverything();
2109
2110 // Tests override IsEngineInitialized() to always return true, so we
2111 // must check that instead of |engine_initialized_|.
2112 // TODO(akalin): Fix the above. :/
2113 DCHECK(IsEngineInitialized());
2114 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2115 // problems around cancelling encryption in the background (crbug.com/119649).
2116 if (!encrypt_everything_)
2117 encryption_pending_ = true;
2118 } 1919 }
2119 1920
2120 bool ProfileSyncService::encryption_pending() const { 1921 bool ProfileSyncService::encryption_pending() const {
2121 DCHECK(thread_checker_.CalledOnValidThread()); 1922 DCHECK(thread_checker_.CalledOnValidThread());
2122 // We may be called during the setup process before we're 1923 // We may be called during the setup process before we're
2123 // initialized (via IsEncryptedDatatypeEnabled and 1924 // initialized (via IsEncryptedDatatypeEnabled and
2124 // IsPassphraseRequiredForDecryption). 1925 // IsPassphraseRequiredForDecryption).
2125 return encryption_pending_; 1926 return crypto_->encryption_pending();
2126 } 1927 }
2127 1928
2128 bool ProfileSyncService::IsEncryptEverythingEnabled() const { 1929 bool ProfileSyncService::IsEncryptEverythingEnabled() const {
2129 DCHECK(thread_checker_.CalledOnValidThread()); 1930 DCHECK(thread_checker_.CalledOnValidThread());
2130 DCHECK(engine_initialized_); 1931 return crypto_->IsEncryptEverythingEnabled();
2131 return encrypt_everything_ || encryption_pending_;
2132 } 1932 }
2133 1933
2134 syncer::ModelTypeSet ProfileSyncService::GetEncryptedDataTypes() const { 1934 syncer::ModelTypeSet ProfileSyncService::GetEncryptedDataTypes() const {
2135 DCHECK(thread_checker_.CalledOnValidThread()); 1935 DCHECK(thread_checker_.CalledOnValidThread());
2136 DCHECK(encrypted_types_.Has(syncer::PASSWORDS)); 1936 return crypto_->GetEncryptedDataTypes();
2137 // We may be called during the setup process before we're
2138 // initialized. In this case, we default to the sensitive types.
2139 return encrypted_types_;
2140 } 1937 }
2141 1938
2142 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) { 1939 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) {
2143 DCHECK(thread_checker_.CalledOnValidThread()); 1940 DCHECK(thread_checker_.CalledOnValidThread());
2144 if (is_sync_managed) { 1941 if (is_sync_managed) {
2145 StopImpl(CLEAR_DATA); 1942 StopImpl(CLEAR_DATA);
2146 } else { 1943 } else {
2147 // Sync is no longer disabled by policy. Try starting it up if appropriate. 1944 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2148 startup_controller_->TryStart(); 1945 startup_controller_->TryStart();
2149 } 1946 }
2150 } 1947 }
2151 1948
2152 void ProfileSyncService::GoogleSigninSucceeded(const std::string& account_id, 1949 void ProfileSyncService::GoogleSigninSucceeded(const std::string& account_id,
2153 const std::string& username, 1950 const std::string& username,
2154 const std::string& password) { 1951 const std::string& password) {
2155 DCHECK(thread_checker_.CalledOnValidThread()); 1952 DCHECK(thread_checker_.CalledOnValidThread());
2156 if (IsSyncRequested() && !password.empty()) { 1953 if (IsSyncRequested() && !password.empty()) {
2157 cached_passphrase_ = password; 1954 crypto_->CachePassphrase(password);
2158 // Try to consume the passphrase we just cached. If the sync engine 1955 // Try to consume the passphrase we just cached. If the sync engine
2159 // is not running yet, the passphrase will remain cached until the 1956 // is not running yet, the passphrase will remain cached until the
2160 // engine starts up. 1957 // engine starts up.
2161 ConsumeCachedPassphraseIfPossible(); 1958 crypto_->ConsumeCachedPassphraseIfPossible();
2162 } 1959 }
2163 #if defined(OS_CHROMEOS) 1960 #if defined(OS_CHROMEOS)
2164 RefreshSpareBootstrapToken(password); 1961 RefreshSpareBootstrapToken(password);
2165 #endif 1962 #endif
2166 if (!IsEngineInitialized() || GetAuthError().state() != AuthError::NONE) { 1963 if (!IsEngineInitialized() || GetAuthError().state() != AuthError::NONE) {
2167 // Track the fact that we're still waiting for auth to complete. 1964 // Track the fact that we're still waiting for auth to complete.
2168 is_auth_in_progress_ = true; 1965 is_auth_in_progress_ = true;
2169 } 1966 }
2170 } 1967 }
2171 1968
(...skipping 24 matching lines...) Expand all
2196 cookie_jar_mismatch = false; 1993 cookie_jar_mismatch = false;
2197 break; 1994 break;
2198 } 1995 }
2199 } 1996 }
2200 1997
2201 DVLOG(1) << "Cookie jar mismatch: " << cookie_jar_mismatch; 1998 DVLOG(1) << "Cookie jar mismatch: " << cookie_jar_mismatch;
2202 DVLOG(1) << "Cookie jar empty: " << cookie_jar_empty; 1999 DVLOG(1) << "Cookie jar empty: " << cookie_jar_empty;
2203 engine_->OnCookieJarChanged(cookie_jar_mismatch, cookie_jar_empty); 2000 engine_->OnCookieJarChanged(cookie_jar_mismatch, cookie_jar_empty);
2204 } 2001 }
2205 2002
2206 void ProfileSyncService::AddObserver(syncer::SyncServiceObserver* observer) {
2207 DCHECK(thread_checker_.CalledOnValidThread());
2208 observers_.AddObserver(observer);
2209 }
2210
2211 void ProfileSyncService::RemoveObserver(syncer::SyncServiceObserver* observer) {
2212 DCHECK(thread_checker_.CalledOnValidThread());
2213 observers_.RemoveObserver(observer);
2214 }
2215
2216 void ProfileSyncService::AddProtocolEventObserver( 2003 void ProfileSyncService::AddProtocolEventObserver(
2217 ProtocolEventObserver* observer) { 2004 ProtocolEventObserver* observer) {
2218 DCHECK(thread_checker_.CalledOnValidThread()); 2005 DCHECK(thread_checker_.CalledOnValidThread());
2219 protocol_event_observers_.AddObserver(observer); 2006 protocol_event_observers_.AddObserver(observer);
2220 if (HasSyncingEngine()) { 2007 if (HasSyncingEngine()) {
2221 engine_->RequestBufferedProtocolEventsAndEnableForwarding(); 2008 engine_->RequestBufferedProtocolEventsAndEnableForwarding();
2222 } 2009 }
2223 } 2010 }
2224 2011
2225 void ProfileSyncService::RemoveProtocolEventObserver( 2012 void ProfileSyncService::RemoveProtocolEventObserver(
(...skipping 131 matching lines...) Expand 10 before | Expand all | Expand 10 after
2357 } else { 2144 } else {
2358 // Control Types 2145 // Control Types
2359 helper->OnReceivedNodesForType( 2146 helper->OnReceivedNodesForType(
2360 it.Get(), 2147 it.Get(),
2361 syncer::DirectoryDataTypeController::GetAllNodesForTypeFromDirectory( 2148 syncer::DirectoryDataTypeController::GetAllNodesForTypeFromDirectory(
2362 it.Get(), GetUserShare()->directory.get())); 2149 it.Get(), GetUserShare()->directory.get()));
2363 } 2150 }
2364 } 2151 }
2365 } 2152 }
2366 2153
2367 bool ProfileSyncService::HasObserver(
2368 const syncer::SyncServiceObserver* observer) const {
2369 DCHECK(thread_checker_.CalledOnValidThread());
2370 return observers_.HasObserver(observer);
2371 }
2372
2373 base::WeakPtr<syncer::JsController> ProfileSyncService::GetJsController() { 2154 base::WeakPtr<syncer::JsController> ProfileSyncService::GetJsController() {
2374 DCHECK(thread_checker_.CalledOnValidThread()); 2155 DCHECK(thread_checker_.CalledOnValidThread());
2375 return sync_js_controller_.AsWeakPtr(); 2156 return sync_js_controller_.AsWeakPtr();
2376 } 2157 }
2377 2158
2378 // static 2159 // static
2379 void ProfileSyncService::SyncEvent(SyncEventCodes code) { 2160 void ProfileSyncService::SyncEvent(SyncEventCodes code) {
2380 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code, MAX_SYNC_EVENT_CODE); 2161 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code, MAX_SYNC_EVENT_CODE);
2381 } 2162 }
2382 2163
(...skipping 164 matching lines...) Expand 10 before | Expand all | Expand 10 after
2547 2328
2548 base::MessageLoop* ProfileSyncService::GetSyncLoopForTest() const { 2329 base::MessageLoop* ProfileSyncService::GetSyncLoopForTest() const {
2549 DCHECK(thread_checker_.CalledOnValidThread()); 2330 DCHECK(thread_checker_.CalledOnValidThread());
2550 if (sync_thread_) { 2331 if (sync_thread_) {
2551 return sync_thread_->message_loop(); 2332 return sync_thread_->message_loop();
2552 } else { 2333 } else {
2553 return nullptr; 2334 return nullptr;
2554 } 2335 }
2555 } 2336 }
2556 2337
2338 syncer::SyncEncryptionHandler::Observer*
2339 ProfileSyncService::GetEncryptionObserverForTest() const {
2340 return crypto_.get();
2341 }
2342
2557 void ProfileSyncService::RefreshTypesForTest(syncer::ModelTypeSet types) { 2343 void ProfileSyncService::RefreshTypesForTest(syncer::ModelTypeSet types) {
2558 DCHECK(thread_checker_.CalledOnValidThread()); 2344 DCHECK(thread_checker_.CalledOnValidThread());
2559 if (engine_initialized_) 2345 if (engine_initialized_)
2560 engine_->RefreshTypesForTest(types); 2346 engine_->RefreshTypesForTest(types);
2561 } 2347 }
2562 2348
2563 void ProfileSyncService::RemoveClientFromServer() const { 2349 void ProfileSyncService::RemoveClientFromServer() const {
2564 if (!engine_initialized_) 2350 if (!engine_initialized_)
2565 return; 2351 return;
2566 const std::string cache_guid = local_device_->GetLocalSyncCacheGUID(); 2352 const std::string cache_guid = local_device_->GetLocalSyncCacheGUID();
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
2628 2414
2629 DCHECK(startup_controller_->IsSetupInProgress()); 2415 DCHECK(startup_controller_->IsSetupInProgress());
2630 startup_controller_->SetSetupInProgress(false); 2416 startup_controller_->SetSetupInProgress(false);
2631 2417
2632 if (IsEngineInitialized()) 2418 if (IsEngineInitialized())
2633 ReconfigureDatatypeManager(); 2419 ReconfigureDatatypeManager();
2634 NotifyObservers(); 2420 NotifyObservers();
2635 } 2421 }
2636 2422
2637 } // namespace browser_sync 2423 } // namespace browser_sync
OLDNEW
« no previous file with comments | « components/browser_sync/profile_sync_service.h ('k') | components/browser_sync/profile_sync_service_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698