1 // Copyright 2012 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.
5 // Unit tests for the SyncApi. Note that a lot of the underlying
6 // functionality is provided by the Syncable layer, which has its own
7 // unit tests. We'll test SyncApi specific things in this harness.
12 #include "base/basictypes.h"
13 #include "base/callback.h"
14 #include "base/compiler_specific.h"
15 #include "base/files/scoped_temp_dir.h"
16 #include "base/format_macros.h"
17 #include "base/location.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/message_loop/message_loop.h"
20 #include "base/message_loop/message_loop_proxy.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/test/values_test_util.h"
25 #include "base/values.h"
26 #include "sync/engine/sync_scheduler.h"
27 #include "sync/internal_api/public/base/cancelation_signal.h"
28 #include "sync/internal_api/public/base/model_type_test_util.h"
29 #include "sync/internal_api/public/change_record.h"
30 #include "sync/internal_api/public/engine/model_safe_worker.h"
31 #include "sync/internal_api/public/engine/polling_constants.h"
32 #include "sync/internal_api/public/http_post_provider_factory.h"
33 #include "sync/internal_api/public/http_post_provider_interface.h"
34 #include "sync/internal_api/public/read_node.h"
35 #include "sync/internal_api/public/read_transaction.h"
36 #include "sync/internal_api/public/test/test_entry_factory.h"
37 #include "sync/internal_api/public/test/test_internal_components_factory.h"
38 #include "sync/internal_api/public/test/test_user_share.h"
39 #include "sync/internal_api/public/write_node.h"
40 #include "sync/internal_api/public/write_transaction.h"
41 #include "sync/internal_api/sync_encryption_handler_impl.h"
42 #include "sync/internal_api/sync_manager_impl.h"
43 #include "sync/internal_api/syncapi_internal.h"
44 #include "sync/js/js_arg_list.h"
45 #include "sync/js/js_backend.h"
46 #include "sync/js/js_event_handler.h"
47 #include "sync/js/js_reply_handler.h"
48 #include "sync/js/js_test_util.h"
49 #include "sync/notifier/fake_invalidation_handler.h"
50 #include "sync/notifier/invalidation_handler.h"
51 #include "sync/notifier/invalidator.h"
52 #include "sync/protocol/bookmark_specifics.pb.h"
53 #include "sync/protocol/encryption.pb.h"
54 #include "sync/protocol/extension_specifics.pb.h"
55 #include "sync/protocol/password_specifics.pb.h"
56 #include "sync/protocol/preference_specifics.pb.h"
57 #include "sync/protocol/proto_value_conversions.h"
58 #include "sync/protocol/sync.pb.h"
59 #include "sync/sessions/sync_session.h"
60 #include "sync/syncable/directory.h"
61 #include "sync/syncable/entry.h"
62 #include "sync/syncable/mutable_entry.h"
63 #include "sync/syncable/nigori_util.h"
64 #include "sync/syncable/syncable_id.h"
65 #include "sync/syncable/syncable_read_transaction.h"
66 #include "sync/syncable/syncable_util.h"
67 #include "sync/syncable/syncable_write_transaction.h"
68 #include "sync/test/callback_counter.h"
69 #include "sync/test/engine/fake_model_worker.h"
70 #include "sync/test/engine/fake_sync_scheduler.h"
71 #include "sync/test/engine/test_id_factory.h"
72 #include "sync/test/fake_encryptor.h"
73 #include "sync/util/cryptographer.h"
74 #include "sync/util/extensions_activity.h"
75 #include "sync/util/test_unrecoverable_error_handler.h"
76 #include "sync/util/time.h"
77 #include "testing/gmock/include/gmock/gmock.h"
78 #include "testing/gtest/include/gtest/gtest.h"
80 using base::ExpectDictStringValue;
83 using testing::InSequence;
84 using testing::Return;
85 using testing::SaveArg;
86 using testing::StrictMock;
90 using sessions::SyncSessionSnapshot;
91 using syncable::GET_BY_HANDLE;
92 using syncable::IS_DEL;
93 using syncable::IS_UNSYNCED;
94 using syncable::NON_UNIQUE_NAME;
95 using syncable::SPECIFICS;
96 using syncable::kEncryptedString;
100 // Makes a non-folder child of the root node. Returns the id of the
101 // newly-created node.
102 int64 MakeNode(UserShare* share,
103 ModelType model_type,
104 const std::string& client_tag) {
105 WriteTransaction trans(FROM_HERE, share);
106 ReadNode root_node(&trans);
107 root_node.InitByRootLookup();
108 WriteNode node(&trans);
109 WriteNode::InitUniqueByCreationResult result =
110 node.InitUniqueByCreation(model_type, root_node, client_tag);
111 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
112 node.SetIsFolder(false);
116 // Makes a folder child of a non-root node. Returns the id of the
117 // newly-created node.
118 int64 MakeFolderWithParent(UserShare* share,
119 ModelType model_type,
121 BaseNode* predecessor) {
122 WriteTransaction trans(FROM_HERE, share);
123 ReadNode parent_node(&trans);
124 EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
125 WriteNode node(&trans);
126 EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor));
127 node.SetIsFolder(true);
131 int64 MakeBookmarkWithParent(UserShare* share,
133 BaseNode* predecessor) {
134 WriteTransaction trans(FROM_HERE, share);
135 ReadNode parent_node(&trans);
136 EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
137 WriteNode node(&trans);
138 EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor));
142 // Creates the "synced" root node for a particular datatype. We use the syncable
143 // methods here so that the syncer treats these nodes as if they were already
144 // received from the server.
145 int64 MakeServerNodeForType(UserShare* share,
146 ModelType model_type) {
147 sync_pb::EntitySpecifics specifics;
148 AddDefaultFieldValue(model_type, &specifics);
149 syncable::WriteTransaction trans(
150 FROM_HERE, syncable::UNITTEST, share->directory.get());
151 // Attempt to lookup by nigori tag.
152 std::string type_tag = ModelTypeToRootTag(model_type);
153 syncable::Id node_id = syncable::Id::CreateFromServerId(type_tag);
154 syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
156 EXPECT_TRUE(entry.good());
157 entry.PutBaseVersion(1);
158 entry.PutServerVersion(1);
159 entry.PutIsUnappliedUpdate(false);
160 entry.PutServerParentId(syncable::GetNullId());
161 entry.PutServerIsDir(true);
162 entry.PutIsDir(true);
163 entry.PutServerSpecifics(specifics);
164 entry.PutUniqueServerTag(type_tag);
165 entry.PutNonUniqueName(type_tag);
166 entry.PutIsDel(false);
167 entry.PutSpecifics(specifics);
168 return entry.GetMetahandle();
171 // Simulates creating a "synced" node as a child of the root datatype node.
172 int64 MakeServerNode(UserShare* share, ModelType model_type,
173 const std::string& client_tag,
174 const std::string& hashed_tag,
175 const sync_pb::EntitySpecifics& specifics) {
176 syncable::WriteTransaction trans(
177 FROM_HERE, syncable::UNITTEST, share->directory.get());
178 syncable::Entry root_entry(&trans, syncable::GET_BY_SERVER_TAG,
179 ModelTypeToRootTag(model_type));
180 EXPECT_TRUE(root_entry.good());
181 syncable::Id root_id = root_entry.GetId();
182 syncable::Id node_id = syncable::Id::CreateFromServerId(client_tag);
183 syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
185 EXPECT_TRUE(entry.good());
186 entry.PutBaseVersion(1);
187 entry.PutServerVersion(1);
188 entry.PutIsUnappliedUpdate(false);
189 entry.PutServerParentId(root_id);
190 entry.PutParentId(root_id);
191 entry.PutServerIsDir(false);
192 entry.PutIsDir(false);
193 entry.PutServerSpecifics(specifics);
194 entry.PutNonUniqueName(client_tag);
195 entry.PutUniqueClientTag(hashed_tag);
196 entry.PutIsDel(false);
197 entry.PutSpecifics(specifics);
198 return entry.GetMetahandle();
203 class SyncApiTest : public testing::Test {
205 virtual void SetUp() {
206 test_user_share_.SetUp();
209 virtual void TearDown() {
210 test_user_share_.TearDown();
214 base::MessageLoop message_loop_;
215 TestUserShare test_user_share_;
218 TEST_F(SyncApiTest, SanityCheckTest) {
220 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
221 EXPECT_TRUE(trans.GetWrappedTrans());
224 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
225 EXPECT_TRUE(trans.GetWrappedTrans());
228 // No entries but root should exist
229 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
230 ReadNode node(&trans);
231 // Metahandle 1 can be root, sanity check 2
232 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByIdLookup(2));
236 TEST_F(SyncApiTest, BasicTagWrite) {
238 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
239 ReadNode root_node(&trans);
240 root_node.InitByRootLookup();
241 EXPECT_EQ(root_node.GetFirstChildId(), 0);
244 ignore_result(MakeNode(test_user_share_.user_share(),
245 BOOKMARKS, "testtag"));
248 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
249 ReadNode node(&trans);
250 EXPECT_EQ(BaseNode::INIT_OK,
251 node.InitByClientTagLookup(BOOKMARKS, "testtag"));
253 ReadNode root_node(&trans);
254 root_node.InitByRootLookup();
255 EXPECT_NE(node.GetId(), 0);
256 EXPECT_EQ(node.GetId(), root_node.GetFirstChildId());
260 TEST_F(SyncApiTest, ModelTypesSiloed) {
262 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
263 ReadNode root_node(&trans);
264 root_node.InitByRootLookup();
265 EXPECT_EQ(root_node.GetFirstChildId(), 0);
268 ignore_result(MakeNode(test_user_share_.user_share(),
269 BOOKMARKS, "collideme"));
270 ignore_result(MakeNode(test_user_share_.user_share(),
271 PREFERENCES, "collideme"));
272 ignore_result(MakeNode(test_user_share_.user_share(),
273 AUTOFILL, "collideme"));
276 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
278 ReadNode bookmarknode(&trans);
279 EXPECT_EQ(BaseNode::INIT_OK,
280 bookmarknode.InitByClientTagLookup(BOOKMARKS,
283 ReadNode prefnode(&trans);
284 EXPECT_EQ(BaseNode::INIT_OK,
285 prefnode.InitByClientTagLookup(PREFERENCES,
288 ReadNode autofillnode(&trans);
289 EXPECT_EQ(BaseNode::INIT_OK,
290 autofillnode.InitByClientTagLookup(AUTOFILL,
293 EXPECT_NE(bookmarknode.GetId(), prefnode.GetId());
294 EXPECT_NE(autofillnode.GetId(), prefnode.GetId());
295 EXPECT_NE(bookmarknode.GetId(), autofillnode.GetId());
299 TEST_F(SyncApiTest, ReadMissingTagsFails) {
301 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
302 ReadNode node(&trans);
303 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
304 node.InitByClientTagLookup(BOOKMARKS,
308 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
309 WriteNode node(&trans);
310 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
311 node.InitByClientTagLookup(BOOKMARKS,
316 // TODO(chron): Hook this all up to the server and write full integration tests
317 // for update->undelete behavior.
318 TEST_F(SyncApiTest, TestDeleteBehavior) {
321 std::string test_title("test1");
324 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
325 ReadNode root_node(&trans);
326 root_node.InitByRootLookup();
328 // we'll use this spare folder later
329 WriteNode folder_node(&trans);
330 EXPECT_TRUE(folder_node.InitBookmarkByCreation(root_node, NULL));
331 folder_id = folder_node.GetId();
333 WriteNode wnode(&trans);
334 WriteNode::InitUniqueByCreationResult result =
335 wnode.InitUniqueByCreation(BOOKMARKS, root_node, "testtag");
336 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
337 wnode.SetIsFolder(false);
338 wnode.SetTitle(base::UTF8ToWide(test_title));
340 node_id = wnode.GetId();
343 // Ensure we can delete something with a tag.
345 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
346 WriteNode wnode(&trans);
347 EXPECT_EQ(BaseNode::INIT_OK,
348 wnode.InitByClientTagLookup(BOOKMARKS,
350 EXPECT_FALSE(wnode.GetIsFolder());
351 EXPECT_EQ(wnode.GetTitle(), test_title);
356 // Lookup of a node which was deleted should return failure,
357 // but have found some data about the node.
359 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
360 ReadNode node(&trans);
361 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL,
362 node.InitByClientTagLookup(BOOKMARKS,
364 // Note that for proper function of this API this doesn't need to be
365 // filled, we're checking just to make sure the DB worked in this test.
366 EXPECT_EQ(node.GetTitle(), test_title);
370 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
371 ReadNode folder_node(&trans);
372 EXPECT_EQ(BaseNode::INIT_OK, folder_node.InitByIdLookup(folder_id));
374 WriteNode wnode(&trans);
375 // This will undelete the tag.
376 WriteNode::InitUniqueByCreationResult result =
377 wnode.InitUniqueByCreation(BOOKMARKS, folder_node, "testtag");
378 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
379 EXPECT_EQ(wnode.GetIsFolder(), false);
380 EXPECT_EQ(wnode.GetParentId(), folder_node.GetId());
381 EXPECT_EQ(wnode.GetId(), node_id);
382 EXPECT_NE(wnode.GetTitle(), test_title); // Title should be cleared
383 wnode.SetTitle(base::UTF8ToWide(test_title));
386 // Now look up should work.
388 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
389 ReadNode node(&trans);
390 EXPECT_EQ(BaseNode::INIT_OK,
391 node.InitByClientTagLookup(BOOKMARKS,
393 EXPECT_EQ(node.GetTitle(), test_title);
394 EXPECT_EQ(node.GetModelType(), BOOKMARKS);
398 TEST_F(SyncApiTest, WriteAndReadPassword) {
399 KeyParams params = {"localhost", "username", "passphrase"};
401 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
402 trans.GetCryptographer()->AddKey(params);
405 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
406 ReadNode root_node(&trans);
407 root_node.InitByRootLookup();
409 WriteNode password_node(&trans);
410 WriteNode::InitUniqueByCreationResult result =
411 password_node.InitUniqueByCreation(PASSWORDS,
413 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
414 sync_pb::PasswordSpecificsData data;
415 data.set_password_value("secret");
416 password_node.SetPasswordSpecifics(data);
419 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
420 ReadNode root_node(&trans);
421 root_node.InitByRootLookup();
423 ReadNode password_node(&trans);
424 EXPECT_EQ(BaseNode::INIT_OK,
425 password_node.InitByClientTagLookup(PASSWORDS, "foo"));
426 const sync_pb::PasswordSpecificsData& data =
427 password_node.GetPasswordSpecifics();
428 EXPECT_EQ("secret", data.password_value());
432 TEST_F(SyncApiTest, WriteEncryptedTitle) {
433 KeyParams params = {"localhost", "username", "passphrase"};
435 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
436 trans.GetCryptographer()->AddKey(params);
438 test_user_share_.encryption_handler()->EnableEncryptEverything();
441 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
442 ReadNode root_node(&trans);
443 root_node.InitByRootLookup();
445 WriteNode bookmark_node(&trans);
446 ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, NULL));
447 bookmark_id = bookmark_node.GetId();
448 bookmark_node.SetTitle(base::UTF8ToWide("foo"));
450 WriteNode pref_node(&trans);
451 WriteNode::InitUniqueByCreationResult result =
452 pref_node.InitUniqueByCreation(PREFERENCES, root_node, "bar");
453 ASSERT_EQ(WriteNode::INIT_SUCCESS, result);
454 pref_node.SetTitle(base::UTF8ToWide("bar"));
457 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
458 ReadNode root_node(&trans);
459 root_node.InitByRootLookup();
461 ReadNode bookmark_node(&trans);
462 ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id));
463 EXPECT_EQ("foo", bookmark_node.GetTitle());
464 EXPECT_EQ(kEncryptedString,
465 bookmark_node.GetEntry()->GetNonUniqueName());
467 ReadNode pref_node(&trans);
468 ASSERT_EQ(BaseNode::INIT_OK,
469 pref_node.InitByClientTagLookup(PREFERENCES,
471 EXPECT_EQ(kEncryptedString, pref_node.GetTitle());
475 TEST_F(SyncApiTest, BaseNodeSetSpecifics) {
476 int64 child_id = MakeNode(test_user_share_.user_share(),
477 BOOKMARKS, "testtag");
478 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
479 WriteNode node(&trans);
480 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
482 sync_pb::EntitySpecifics entity_specifics;
483 entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
485 EXPECT_NE(entity_specifics.SerializeAsString(),
486 node.GetEntitySpecifics().SerializeAsString());
487 node.SetEntitySpecifics(entity_specifics);
488 EXPECT_EQ(entity_specifics.SerializeAsString(),
489 node.GetEntitySpecifics().SerializeAsString());
492 TEST_F(SyncApiTest, BaseNodeSetSpecificsPreservesUnknownFields) {
493 int64 child_id = MakeNode(test_user_share_.user_share(),
494 BOOKMARKS, "testtag");
495 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
496 WriteNode node(&trans);
497 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
498 EXPECT_TRUE(node.GetEntitySpecifics().unknown_fields().empty());
500 sync_pb::EntitySpecifics entity_specifics;
501 entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
502 entity_specifics.mutable_unknown_fields()->AddFixed32(5, 100);
503 node.SetEntitySpecifics(entity_specifics);
504 EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
506 entity_specifics.mutable_unknown_fields()->Clear();
507 node.SetEntitySpecifics(entity_specifics);
508 EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
511 TEST_F(SyncApiTest, EmptyTags) {
512 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
513 ReadNode root_node(&trans);
514 root_node.InitByRootLookup();
515 WriteNode node(&trans);
516 std::string empty_tag;
517 WriteNode::InitUniqueByCreationResult result =
518 node.InitUniqueByCreation(TYPED_URLS, root_node, empty_tag);
519 EXPECT_NE(WriteNode::INIT_SUCCESS, result);
520 EXPECT_EQ(BaseNode::INIT_FAILED_PRECONDITION,
521 node.InitByTagLookup(empty_tag));
524 // Test counting nodes when the type's root node has no children.
525 TEST_F(SyncApiTest, GetTotalNodeCountEmpty) {
526 int64 type_root = MakeServerNodeForType(test_user_share_.user_share(),
529 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
530 ReadNode type_root_node(&trans);
531 EXPECT_EQ(BaseNode::INIT_OK,
532 type_root_node.InitByIdLookup(type_root));
533 EXPECT_EQ(1, type_root_node.GetTotalNodeCount());
537 // Test counting nodes when there is one child beneath the type's root.
538 TEST_F(SyncApiTest, GetTotalNodeCountOneChild) {
539 int64 type_root = MakeServerNodeForType(test_user_share_.user_share(),
541 int64 parent = MakeFolderWithParent(test_user_share_.user_share(),
546 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
547 ReadNode type_root_node(&trans);
548 EXPECT_EQ(BaseNode::INIT_OK,
549 type_root_node.InitByIdLookup(type_root));
550 EXPECT_EQ(2, type_root_node.GetTotalNodeCount());
551 ReadNode parent_node(&trans);
552 EXPECT_EQ(BaseNode::INIT_OK,
553 parent_node.InitByIdLookup(parent));
554 EXPECT_EQ(1, parent_node.GetTotalNodeCount());
558 // Test counting nodes when there are multiple children beneath the type root,
559 // and one of those children has children of its own.
560 TEST_F(SyncApiTest, GetTotalNodeCountMultipleChildren) {
561 int64 type_root = MakeServerNodeForType(test_user_share_.user_share(),
563 int64 parent = MakeFolderWithParent(test_user_share_.user_share(),
567 ignore_result(MakeFolderWithParent(test_user_share_.user_share(),
571 int64 child1 = MakeFolderWithParent(
572 test_user_share_.user_share(),
576 ignore_result(MakeBookmarkWithParent(
577 test_user_share_.user_share(),
580 ignore_result(MakeBookmarkWithParent(
581 test_user_share_.user_share(),
586 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
587 ReadNode type_root_node(&trans);
588 EXPECT_EQ(BaseNode::INIT_OK,
589 type_root_node.InitByIdLookup(type_root));
590 EXPECT_EQ(6, type_root_node.GetTotalNodeCount());
591 ReadNode node(&trans);
592 EXPECT_EQ(BaseNode::INIT_OK,
593 node.InitByIdLookup(parent));
594 EXPECT_EQ(4, node.GetTotalNodeCount());
600 class TestHttpPostProviderInterface : public HttpPostProviderInterface {
602 virtual ~TestHttpPostProviderInterface() {}
604 virtual void SetExtraRequestHeaders(const char* headers) OVERRIDE {}
605 virtual void SetURL(const char* url, int port) OVERRIDE {}
606 virtual void SetPostPayload(const char* content_type,
608 const char* content) OVERRIDE {}
609 virtual bool MakeSynchronousPost(int* error_code, int* response_code)
613 virtual int GetResponseContentLength() const OVERRIDE {
616 virtual const char* GetResponseContent() const OVERRIDE {
619 virtual const std::string GetResponseHeaderValue(
620 const std::string& name) const OVERRIDE {
621 return std::string();
623 virtual void Abort() OVERRIDE {}
626 class TestHttpPostProviderFactory : public HttpPostProviderFactory {
628 virtual ~TestHttpPostProviderFactory() {}
629 virtual void Init(const std::string& user_agent) OVERRIDE { }
630 virtual HttpPostProviderInterface* Create() OVERRIDE {
631 return new TestHttpPostProviderInterface();
633 virtual void Destroy(HttpPostProviderInterface* http) OVERRIDE {
634 delete static_cast<TestHttpPostProviderInterface*>(http);
638 class SyncManagerObserverMock : public SyncManager::Observer {
640 MOCK_METHOD1(OnSyncCycleCompleted,
641 void(const SyncSessionSnapshot&)); // NOLINT
642 MOCK_METHOD4(OnInitializationComplete,
643 void(const WeakHandle<JsBackend>&,
644 const WeakHandle<DataTypeDebugInfoListener>&,
646 syncer::ModelTypeSet)); // NOLINT
647 MOCK_METHOD1(OnConnectionStatusChange, void(ConnectionStatus)); // NOLINT
648 MOCK_METHOD1(OnUpdatedToken, void(const std::string&)); // NOLINT
649 MOCK_METHOD1(OnActionableError,
650 void(const SyncProtocolError&)); // NOLINT
651 MOCK_METHOD1(OnMigrationRequested,
652 void(syncer::ModelTypeSet)); // NOLINT
655 class SyncEncryptionHandlerObserverMock
656 : public SyncEncryptionHandler::Observer {
658 MOCK_METHOD2(OnPassphraseRequired,
659 void(PassphraseRequiredReason,
660 const sync_pb::EncryptedData&)); // NOLINT
661 MOCK_METHOD0(OnPassphraseAccepted, void()); // NOLINT
662 MOCK_METHOD2(OnBootstrapTokenUpdated,
663 void(const std::string&, BootstrapTokenType type)); // NOLINT
664 MOCK_METHOD2(OnEncryptedTypesChanged,
665 void(ModelTypeSet, bool)); // NOLINT
666 MOCK_METHOD0(OnEncryptionComplete, void()); // NOLINT
667 MOCK_METHOD1(OnCryptographerStateChanged, void(Cryptographer*)); // NOLINT
668 MOCK_METHOD2(OnPassphraseTypeChanged, void(PassphraseType,
669 base::Time)); // NOLINT
674 class SyncManagerTest : public testing::Test,
675 public SyncManager::ChangeDelegate {
682 enum EncryptionStatus {
689 : sync_manager_("Test sync manager") {
690 switches_.encryption_method =
691 InternalComponentsFactory::ENCRYPTION_KEYSTORE;
694 virtual ~SyncManagerTest() {
697 // Test implementation.
699 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
701 extensions_activity_ = new ExtensionsActivity();
703 SyncCredentials credentials;
704 credentials.email = "foo@bar.com";
705 credentials.sync_token = "sometoken";
707 sync_manager_.AddObserver(&manager_observer_);
708 EXPECT_CALL(manager_observer_, OnInitializationComplete(_, _, _, _)).
709 WillOnce(DoAll(SaveArg<0>(&js_backend_),
710 SaveArg<2>(&initialization_succeeded_)));
712 EXPECT_FALSE(js_backend_.IsInitialized());
714 std::vector<scoped_refptr<ModelSafeWorker> > workers;
715 ModelSafeRoutingInfo routing_info;
716 GetModelSafeRoutingInfo(&routing_info);
718 // This works only because all routing info types are GROUP_PASSIVE.
719 // If we had types in other groups, we would need additional workers
721 scoped_refptr<ModelSafeWorker> worker = new FakeModelWorker(GROUP_PASSIVE);
722 workers.push_back(worker);
724 // Takes ownership of |fake_invalidator_|.
727 WeakHandle<JsEventHandler>(),
731 scoped_ptr<HttpPostProviderFactory>(new TestHttpPostProviderFactory()),
733 extensions_activity_.get(),
736 "fake_invalidator_client_id",
738 std::string(), // bootstrap tokens
739 scoped_ptr<InternalComponentsFactory>(GetFactory()).get(),
741 scoped_ptr<UnrecoverableErrorHandler>(
742 new TestUnrecoverableErrorHandler).Pass(),
744 &cancelation_signal_);
746 sync_manager_.GetEncryptionHandler()->AddObserver(&encryption_observer_);
748 EXPECT_TRUE(js_backend_.IsInitialized());
750 if (initialization_succeeded_) {
751 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
752 i != routing_info.end(); ++i) {
753 type_roots_[i->first] = MakeServerNodeForType(
754 sync_manager_.GetUserShare(), i->first);
761 sync_manager_.RemoveObserver(&manager_observer_);
762 sync_manager_.ShutdownOnSyncThread();
766 void GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) {
767 (*out)[NIGORI] = GROUP_PASSIVE;
768 (*out)[DEVICE_INFO] = GROUP_PASSIVE;
769 (*out)[EXPERIMENTS] = GROUP_PASSIVE;
770 (*out)[BOOKMARKS] = GROUP_PASSIVE;
771 (*out)[THEMES] = GROUP_PASSIVE;
772 (*out)[SESSIONS] = GROUP_PASSIVE;
773 (*out)[PASSWORDS] = GROUP_PASSIVE;
774 (*out)[PREFERENCES] = GROUP_PASSIVE;
775 (*out)[PRIORITY_PREFERENCES] = GROUP_PASSIVE;
778 ModelTypeSet GetEnabledTypes() {
779 ModelSafeRoutingInfo routing_info;
780 GetModelSafeRoutingInfo(&routing_info);
781 return GetRoutingInfoTypes(routing_info);
784 virtual void OnChangesApplied(
785 ModelType model_type,
787 const BaseTransaction* trans,
788 const ImmutableChangeRecordList& changes) OVERRIDE {}
790 virtual void OnChangesComplete(ModelType model_type) OVERRIDE {}
793 bool SetUpEncryption(NigoriStatus nigori_status,
794 EncryptionStatus encryption_status) {
795 UserShare* share = sync_manager_.GetUserShare();
797 // We need to create the nigori node as if it were an applied server update.
798 int64 nigori_id = GetIdForDataType(NIGORI);
799 if (nigori_id == kInvalidId)
802 // Set the nigori cryptographer information.
803 if (encryption_status == FULL_ENCRYPTION)
804 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
806 WriteTransaction trans(FROM_HERE, share);
807 Cryptographer* cryptographer = trans.GetCryptographer();
810 if (encryption_status != UNINITIALIZED) {
811 KeyParams params = {"localhost", "dummy", "foobar"};
812 cryptographer->AddKey(params);
814 DCHECK_NE(nigori_status, WRITE_TO_NIGORI);
816 if (nigori_status == WRITE_TO_NIGORI) {
817 sync_pb::NigoriSpecifics nigori;
818 cryptographer->GetKeys(nigori.mutable_encryption_keybag());
819 share->directory->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes(
821 trans.GetWrappedTrans());
822 WriteNode node(&trans);
823 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(nigori_id));
824 node.SetNigoriSpecifics(nigori);
826 return cryptographer->is_ready();
829 int64 GetIdForDataType(ModelType type) {
830 if (type_roots_.count(type) == 0)
832 return type_roots_[type];
836 message_loop_.RunUntilIdle();
839 void SendJsMessage(const std::string& name, const JsArgList& args,
840 const WeakHandle<JsReplyHandler>& reply_handler) {
841 js_backend_.Call(FROM_HERE, &JsBackend::ProcessJsMessage,
842 name, args, reply_handler);
846 void SetJsEventHandler(const WeakHandle<JsEventHandler>& event_handler) {
847 js_backend_.Call(FROM_HERE, &JsBackend::SetJsEventHandler,
852 // Looks up an entry by client tag and resets IS_UNSYNCED value to false.
853 // Returns true if entry was previously unsynced, false if IS_UNSYNCED was
855 bool ResetUnsyncedEntry(ModelType type,
856 const std::string& client_tag) {
857 UserShare* share = sync_manager_.GetUserShare();
858 syncable::WriteTransaction trans(
859 FROM_HERE, syncable::UNITTEST, share->directory.get());
860 const std::string hash = syncable::GenerateSyncableHash(type, client_tag);
861 syncable::MutableEntry entry(&trans, syncable::GET_BY_CLIENT_TAG,
863 EXPECT_TRUE(entry.good());
864 if (!entry.GetIsUnsynced())
866 entry.PutIsUnsynced(false);
870 virtual InternalComponentsFactory* GetFactory() {
871 return new TestInternalComponentsFactory(GetSwitches(), STORAGE_IN_MEMORY);
874 // Returns true if we are currently encrypting all sync data. May
875 // be called on any thread.
876 bool EncryptEverythingEnabledForTest() {
877 return sync_manager_.GetEncryptionHandler()->EncryptEverythingEnabled();
880 // Gets the set of encrypted types from the cryptographer
881 // Note: opens a transaction. May be called from any thread.
882 ModelTypeSet GetEncryptedTypes() {
883 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
884 return GetEncryptedTypesWithTrans(&trans);
887 ModelTypeSet GetEncryptedTypesWithTrans(BaseTransaction* trans) {
888 return trans->GetDirectory()->GetNigoriHandler()->
889 GetEncryptedTypes(trans->GetWrappedTrans());
892 void SimulateInvalidatorStateChangeForTest(InvalidatorState state) {
893 DCHECK(sync_manager_.thread_checker_.CalledOnValidThread());
894 sync_manager_.OnInvalidatorStateChange(state);
897 void TriggerOnIncomingNotificationForTest(ModelTypeSet model_types) {
898 DCHECK(sync_manager_.thread_checker_.CalledOnValidThread());
899 ObjectIdSet id_set = ModelTypeSetToObjectIdSet(model_types);
900 ObjectIdInvalidationMap invalidation_map =
901 ObjectIdInvalidationMap::InvalidateAll(id_set);
902 sync_manager_.OnIncomingInvalidation(invalidation_map);
905 void SetProgressMarkerForType(ModelType type, bool set) {
907 sync_pb::DataTypeProgressMarker marker;
908 marker.set_token("token");
909 marker.set_data_type_id(GetSpecificsFieldNumberFromModelType(type));
910 sync_manager_.directory()->SetDownloadProgress(type, marker);
912 sync_pb::DataTypeProgressMarker marker;
913 sync_manager_.directory()->SetDownloadProgress(type, marker);
917 InternalComponentsFactory::Switches GetSwitches() const {
922 // Needed by |sync_manager_|.
923 base::MessageLoop message_loop_;
924 // Needed by |sync_manager_|.
925 base::ScopedTempDir temp_dir_;
926 // Sync Id's for the roots of the enabled datatypes.
927 std::map<ModelType, int64> type_roots_;
928 scoped_refptr<ExtensionsActivity> extensions_activity_;
931 FakeEncryptor encryptor_;
932 SyncManagerImpl sync_manager_;
933 CancelationSignal cancelation_signal_;
934 WeakHandle<JsBackend> js_backend_;
935 bool initialization_succeeded_;
936 StrictMock<SyncManagerObserverMock> manager_observer_;
937 StrictMock<SyncEncryptionHandlerObserverMock> encryption_observer_;
938 InternalComponentsFactory::Switches switches_;
941 TEST_F(SyncManagerTest, ProcessJsMessage) {
942 const JsArgList kNoArgs;
944 StrictMock<MockJsReplyHandler> reply_handler;
946 EXPECT_CALL(reply_handler,
947 HandleJsReply("getNotificationInfo", _));
949 // This message should be dropped.
950 SendJsMessage("unknownMessage", kNoArgs, reply_handler.AsWeakHandle());
952 SendJsMessage("getNotificationInfo", kNoArgs, reply_handler.AsWeakHandle());
955 TEST_F(SyncManagerTest, GetAllNodesTest) {
956 StrictMock<MockJsReplyHandler> reply_handler;
957 JsArgList return_args;
959 EXPECT_CALL(reply_handler,
960 HandleJsReply("getAllNodes", _))
961 .Times(1).WillRepeatedly(SaveArg<1>(&return_args));
964 base::ListValue args;
965 SendJsMessage("getAllNodes",
966 JsArgList(&args), reply_handler.AsWeakHandle());
969 // There's not much value in verifying every attribute on every node here.
970 // Most of the value of this test has already been achieved: we've verified we
971 // can call the above function without crashing or leaking memory.
973 // Let's just check the list size and a few of its elements. Anything more
974 // would make this test brittle without greatly increasing our chances of
975 // catching real bugs.
977 const base::ListValue* node_list;
978 const base::DictionaryValue* first_result;
980 // The resulting argument list should have one argument, a list of nodes.
981 ASSERT_EQ(1U, return_args.Get().GetSize());
982 ASSERT_TRUE(return_args.Get().GetList(0, &node_list));
984 // The database creation logic depends on the routing info.
985 // Refer to setup methods for more information.
986 ModelSafeRoutingInfo routes;
987 GetModelSafeRoutingInfo(&routes);
988 size_t directory_size = routes.size() + 1;
990 ASSERT_EQ(directory_size, node_list->GetSize());
991 ASSERT_TRUE(node_list->GetDictionary(0, &first_result));
992 EXPECT_TRUE(first_result->HasKey("ID"));
993 EXPECT_TRUE(first_result->HasKey("NON_UNIQUE_NAME"));
996 // Simulate various invalidator state changes. Those should propagate
998 TEST_F(SyncManagerTest, OnInvalidatorStateChangeJsEvents) {
999 StrictMock<MockJsEventHandler> event_handler;
1001 base::DictionaryValue enabled_details;
1002 enabled_details.SetString("state", "INVALIDATIONS_ENABLED");
1003 base::DictionaryValue credentials_rejected_details;
1004 credentials_rejected_details.SetString(
1005 "state", "INVALIDATION_CREDENTIALS_REJECTED");
1006 base::DictionaryValue transient_error_details;
1007 transient_error_details.SetString("state", "TRANSIENT_INVALIDATION_ERROR");
1008 base::DictionaryValue auth_error_details;
1009 auth_error_details.SetString("status", "CONNECTION_AUTH_ERROR");
1011 EXPECT_CALL(event_handler,
1012 HandleJsEvent("onNotificationStateChange",
1013 HasDetailsAsDictionary(enabled_details)));
1017 HandleJsEvent("onNotificationStateChange",
1018 HasDetailsAsDictionary(credentials_rejected_details)))
1021 EXPECT_CALL(event_handler,
1022 HandleJsEvent("onNotificationStateChange",
1023 HasDetailsAsDictionary(transient_error_details)));
1025 // Test needs to simulate INVALIDATION_CREDENTIALS_REJECTED with event handler
1026 // attached because this is the only time when CONNECTION_AUTH_ERROR
1027 // notification will be generated, therefore the only chance to verify that
1028 // "onConnectionStatusChange" event is delivered
1029 SetJsEventHandler(event_handler.AsWeakHandle());
1030 SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED);
1031 SetJsEventHandler(WeakHandle<JsEventHandler>());
1033 SimulateInvalidatorStateChangeForTest(INVALIDATIONS_ENABLED);
1034 SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED);
1035 SimulateInvalidatorStateChangeForTest(TRANSIENT_INVALIDATION_ERROR);
1037 SetJsEventHandler(event_handler.AsWeakHandle());
1038 SimulateInvalidatorStateChangeForTest(INVALIDATIONS_ENABLED);
1039 SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED);
1040 SimulateInvalidatorStateChangeForTest(TRANSIENT_INVALIDATION_ERROR);
1041 SetJsEventHandler(WeakHandle<JsEventHandler>());
1043 SimulateInvalidatorStateChangeForTest(INVALIDATIONS_ENABLED);
1044 SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED);
1045 SimulateInvalidatorStateChangeForTest(TRANSIENT_INVALIDATION_ERROR);
1047 // Should trigger the replies.
1051 TEST_F(SyncManagerTest, OnIncomingNotification) {
1052 StrictMock<MockJsEventHandler> event_handler;
1054 const ModelTypeSet empty_model_types;
1055 const ModelTypeSet model_types(
1058 // Build expected_args to have a single argument with the string
1059 // equivalents of model_types.
1060 base::DictionaryValue expected_details;
1062 base::ListValue* model_type_list = new base::ListValue();
1063 expected_details.SetString("source", "REMOTE_INVALIDATION");
1064 expected_details.Set("changedTypes", model_type_list);
1065 for (ModelTypeSet::Iterator it = model_types.First();
1066 it.Good(); it.Inc()) {
1067 model_type_list->Append(
1068 new base::StringValue(ModelTypeToString(it.Get())));
1072 EXPECT_CALL(event_handler,
1073 HandleJsEvent("onIncomingNotification",
1074 HasDetailsAsDictionary(expected_details)));
1076 TriggerOnIncomingNotificationForTest(empty_model_types);
1077 TriggerOnIncomingNotificationForTest(model_types);
1079 SetJsEventHandler(event_handler.AsWeakHandle());
1080 TriggerOnIncomingNotificationForTest(model_types);
1081 SetJsEventHandler(WeakHandle<JsEventHandler>());
1083 TriggerOnIncomingNotificationForTest(empty_model_types);
1084 TriggerOnIncomingNotificationForTest(model_types);
1086 // Should trigger the replies.
1090 TEST_F(SyncManagerTest, RefreshEncryptionReady) {
1091 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1092 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1093 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1094 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1096 sync_manager_.GetEncryptionHandler()->Init();
1099 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1100 EXPECT_TRUE(encrypted_types.Has(PASSWORDS));
1101 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1104 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1105 ReadNode node(&trans);
1106 EXPECT_EQ(BaseNode::INIT_OK,
1107 node.InitByIdLookup(GetIdForDataType(NIGORI)));
1108 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1109 EXPECT_TRUE(nigori.has_encryption_keybag());
1110 Cryptographer* cryptographer = trans.GetCryptographer();
1111 EXPECT_TRUE(cryptographer->is_ready());
1112 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1116 // Attempt to refresh encryption when nigori not downloaded.
1117 TEST_F(SyncManagerTest, RefreshEncryptionNotReady) {
1118 // Don't set up encryption (no nigori node created).
1120 // Should fail. Triggers an OnPassphraseRequired because the cryptographer
1122 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _)).Times(1);
1123 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1124 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1125 sync_manager_.GetEncryptionHandler()->Init();
1128 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1129 EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
1130 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1133 // Attempt to refresh encryption when nigori is empty.
1134 TEST_F(SyncManagerTest, RefreshEncryptionEmptyNigori) {
1135 EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI, DEFAULT_ENCRYPTION));
1136 EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(1);
1137 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1138 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1140 // Should write to nigori.
1141 sync_manager_.GetEncryptionHandler()->Init();
1144 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1145 EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
1146 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1149 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1150 ReadNode node(&trans);
1151 EXPECT_EQ(BaseNode::INIT_OK,
1152 node.InitByIdLookup(GetIdForDataType(NIGORI)));
1153 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1154 EXPECT_TRUE(nigori.has_encryption_keybag());
1155 Cryptographer* cryptographer = trans.GetCryptographer();
1156 EXPECT_TRUE(cryptographer->is_ready());
1157 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1161 TEST_F(SyncManagerTest, EncryptDataTypesWithNoData) {
1162 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1163 EXPECT_CALL(encryption_observer_,
1164 OnEncryptedTypesChanged(
1165 HasModelTypes(EncryptableUserTypes()), true));
1166 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1167 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1168 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1171 TEST_F(SyncManagerTest, EncryptDataTypesWithData) {
1172 size_t batch_size = 5;
1173 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1175 // Create some unencrypted unsynced data.
1176 int64 folder = MakeFolderWithParent(sync_manager_.GetUserShare(),
1178 GetIdForDataType(BOOKMARKS),
1180 // First batch_size nodes are children of folder.
1182 for (i = 0; i < batch_size; ++i) {
1183 MakeBookmarkWithParent(sync_manager_.GetUserShare(), folder, NULL);
1185 // Next batch_size nodes are a different type and on their own.
1186 for (; i < 2*batch_size; ++i) {
1187 MakeNode(sync_manager_.GetUserShare(), SESSIONS,
1188 base::StringPrintf("%" PRIuS "", i));
1190 // Last batch_size nodes are a third type that will not need encryption.
1191 for (; i < 3*batch_size; ++i) {
1192 MakeNode(sync_manager_.GetUserShare(), THEMES,
1193 base::StringPrintf("%" PRIuS "", i));
1197 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1198 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1199 SyncEncryptionHandler::SensitiveTypes()));
1200 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1201 trans.GetWrappedTrans(),
1203 false /* not encrypted */));
1204 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1205 trans.GetWrappedTrans(),
1207 false /* not encrypted */));
1208 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1209 trans.GetWrappedTrans(),
1211 false /* not encrypted */));
1214 EXPECT_CALL(encryption_observer_,
1215 OnEncryptedTypesChanged(
1216 HasModelTypes(EncryptableUserTypes()), true));
1217 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1218 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1219 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1221 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1222 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1223 EncryptableUserTypes()));
1224 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1225 trans.GetWrappedTrans(),
1227 true /* is encrypted */));
1228 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1229 trans.GetWrappedTrans(),
1231 true /* is encrypted */));
1232 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1233 trans.GetWrappedTrans(),
1235 true /* is encrypted */));
1238 // Trigger's a ReEncryptEverything with new passphrase.
1239 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1240 EXPECT_CALL(encryption_observer_,
1241 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1242 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1243 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1244 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1245 EXPECT_CALL(encryption_observer_,
1246 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1247 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1248 "new_passphrase", true);
1249 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1251 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1252 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1253 EncryptableUserTypes()));
1254 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1255 trans.GetWrappedTrans(),
1257 true /* is encrypted */));
1258 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1259 trans.GetWrappedTrans(),
1261 true /* is encrypted */));
1262 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1263 trans.GetWrappedTrans(),
1265 true /* is encrypted */));
1267 // Calling EncryptDataTypes with an empty encrypted types should not trigger
1268 // a reencryption and should just notify immediately.
1269 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1270 EXPECT_CALL(encryption_observer_,
1271 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)).Times(0);
1272 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()).Times(0);
1273 EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(0);
1274 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1277 // Test that when there are no pending keys and the cryptographer is not
1278 // initialized, we add a key based on the current GAIA password.
1279 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1280 TEST_F(SyncManagerTest, SetInitialGaiaPass) {
1281 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1282 EXPECT_CALL(encryption_observer_,
1283 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1284 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1285 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1286 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1287 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1290 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1291 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1292 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1294 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1295 ReadNode node(&trans);
1296 EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag));
1297 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1298 Cryptographer* cryptographer = trans.GetCryptographer();
1299 EXPECT_TRUE(cryptographer->is_ready());
1300 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1304 // Test that when there are no pending keys and we have on the old GAIA
1305 // password, we update and re-encrypt everything with the new GAIA password.
1306 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1307 TEST_F(SyncManagerTest, UpdateGaiaPass) {
1308 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1309 Cryptographer verifier(&encryptor_);
1311 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1312 Cryptographer* cryptographer = trans.GetCryptographer();
1313 std::string bootstrap_token;
1314 cryptographer->GetBootstrapToken(&bootstrap_token);
1315 verifier.Bootstrap(bootstrap_token);
1317 EXPECT_CALL(encryption_observer_,
1318 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1319 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1320 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1321 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1322 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1325 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1326 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1327 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1329 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1330 Cryptographer* cryptographer = trans.GetCryptographer();
1331 EXPECT_TRUE(cryptographer->is_ready());
1332 // Verify the default key has changed.
1333 sync_pb::EncryptedData encrypted;
1334 cryptographer->GetKeys(&encrypted);
1335 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1339 // Sets a new explicit passphrase. This should update the bootstrap token
1340 // and re-encrypt everything.
1341 // (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1342 TEST_F(SyncManagerTest, SetPassphraseWithPassword) {
1343 Cryptographer verifier(&encryptor_);
1344 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1346 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1347 // Store the default (soon to be old) key.
1348 Cryptographer* cryptographer = trans.GetCryptographer();
1349 std::string bootstrap_token;
1350 cryptographer->GetBootstrapToken(&bootstrap_token);
1351 verifier.Bootstrap(bootstrap_token);
1353 ReadNode root_node(&trans);
1354 root_node.InitByRootLookup();
1356 WriteNode password_node(&trans);
1357 WriteNode::InitUniqueByCreationResult result =
1358 password_node.InitUniqueByCreation(PASSWORDS,
1360 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
1361 sync_pb::PasswordSpecificsData data;
1362 data.set_password_value("secret");
1363 password_node.SetPasswordSpecifics(data);
1365 EXPECT_CALL(encryption_observer_,
1366 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1367 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1368 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1369 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1370 EXPECT_CALL(encryption_observer_,
1371 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1372 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1375 EXPECT_EQ(CUSTOM_PASSPHRASE,
1376 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1377 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1379 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1380 Cryptographer* cryptographer = trans.GetCryptographer();
1381 EXPECT_TRUE(cryptographer->is_ready());
1382 // Verify the default key has changed.
1383 sync_pb::EncryptedData encrypted;
1384 cryptographer->GetKeys(&encrypted);
1385 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1387 ReadNode password_node(&trans);
1388 EXPECT_EQ(BaseNode::INIT_OK,
1389 password_node.InitByClientTagLookup(PASSWORDS,
1391 const sync_pb::PasswordSpecificsData& data =
1392 password_node.GetPasswordSpecifics();
1393 EXPECT_EQ("secret", data.password_value());
1397 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1398 // being encrypted with a new (unprovided) GAIA password, then supply the
1400 // (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1401 TEST_F(SyncManagerTest, SupplyPendingGAIAPass) {
1402 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1403 Cryptographer other_cryptographer(&encryptor_);
1405 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1406 Cryptographer* cryptographer = trans.GetCryptographer();
1407 std::string bootstrap_token;
1408 cryptographer->GetBootstrapToken(&bootstrap_token);
1409 other_cryptographer.Bootstrap(bootstrap_token);
1411 // Now update the nigori to reflect the new keys, and update the
1412 // cryptographer to have pending keys.
1413 KeyParams params = {"localhost", "dummy", "passphrase2"};
1414 other_cryptographer.AddKey(params);
1415 WriteNode node(&trans);
1416 EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag));
1417 sync_pb::NigoriSpecifics nigori;
1418 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1419 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1420 EXPECT_TRUE(cryptographer->has_pending_keys());
1421 node.SetNigoriSpecifics(nigori);
1423 EXPECT_CALL(encryption_observer_,
1424 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1425 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1426 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1427 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1428 sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("passphrase2");
1429 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1430 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1431 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1433 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1434 Cryptographer* cryptographer = trans.GetCryptographer();
1435 EXPECT_TRUE(cryptographer->is_ready());
1436 // Verify we're encrypting with the new key.
1437 sync_pb::EncryptedData encrypted;
1438 cryptographer->GetKeys(&encrypted);
1439 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1443 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1444 // being encrypted with an old (unprovided) GAIA password. Attempt to supply
1445 // the current GAIA password and verify the bootstrap token is updated. Then
1446 // supply the old GAIA password, and verify we re-encrypt all data with the
1447 // new GAIA password.
1448 // (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1449 TEST_F(SyncManagerTest, SupplyPendingOldGAIAPass) {
1450 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1451 Cryptographer other_cryptographer(&encryptor_);
1453 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1454 Cryptographer* cryptographer = trans.GetCryptographer();
1455 std::string bootstrap_token;
1456 cryptographer->GetBootstrapToken(&bootstrap_token);
1457 other_cryptographer.Bootstrap(bootstrap_token);
1459 // Now update the nigori to reflect the new keys, and update the
1460 // cryptographer to have pending keys.
1461 KeyParams params = {"localhost", "dummy", "old_gaia"};
1462 other_cryptographer.AddKey(params);
1463 WriteNode node(&trans);
1464 EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag));
1465 sync_pb::NigoriSpecifics nigori;
1466 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1467 node.SetNigoriSpecifics(nigori);
1468 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1470 // other_cryptographer now contains all encryption keys, and is encrypting
1471 // with the newest gaia.
1472 KeyParams new_params = {"localhost", "dummy", "new_gaia"};
1473 other_cryptographer.AddKey(new_params);
1475 // The bootstrap token should have been updated. Save it to ensure it's based
1476 // on the new GAIA password.
1477 std::string bootstrap_token;
1478 EXPECT_CALL(encryption_observer_,
1479 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN))
1480 .WillOnce(SaveArg<0>(&bootstrap_token));
1481 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_,_));
1482 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1483 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1486 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1487 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1488 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1489 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1491 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1492 Cryptographer* cryptographer = trans.GetCryptographer();
1493 EXPECT_TRUE(cryptographer->is_initialized());
1494 EXPECT_FALSE(cryptographer->is_ready());
1495 // Verify we're encrypting with the new key, even though we have pending
1497 sync_pb::EncryptedData encrypted;
1498 other_cryptographer.GetKeys(&encrypted);
1499 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1501 EXPECT_CALL(encryption_observer_,
1502 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1503 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1504 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1505 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1506 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1509 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1510 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1512 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1513 Cryptographer* cryptographer = trans.GetCryptographer();
1514 EXPECT_TRUE(cryptographer->is_ready());
1516 // Verify we're encrypting with the new key.
1517 sync_pb::EncryptedData encrypted;
1518 other_cryptographer.GetKeys(&encrypted);
1519 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1521 // Verify the saved bootstrap token is based on the new gaia password.
1522 Cryptographer temp_cryptographer(&encryptor_);
1523 temp_cryptographer.Bootstrap(bootstrap_token);
1524 EXPECT_TRUE(temp_cryptographer.CanDecrypt(encrypted));
1528 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1529 // being encrypted with an explicit (unprovided) passphrase, then supply the
1531 // (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1532 TEST_F(SyncManagerTest, SupplyPendingExplicitPass) {
1533 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1534 Cryptographer other_cryptographer(&encryptor_);
1536 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1537 Cryptographer* cryptographer = trans.GetCryptographer();
1538 std::string bootstrap_token;
1539 cryptographer->GetBootstrapToken(&bootstrap_token);
1540 other_cryptographer.Bootstrap(bootstrap_token);
1542 // Now update the nigori to reflect the new keys, and update the
1543 // cryptographer to have pending keys.
1544 KeyParams params = {"localhost", "dummy", "explicit"};
1545 other_cryptographer.AddKey(params);
1546 WriteNode node(&trans);
1547 EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag));
1548 sync_pb::NigoriSpecifics nigori;
1549 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1550 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1551 EXPECT_TRUE(cryptographer->has_pending_keys());
1552 nigori.set_keybag_is_frozen(true);
1553 node.SetNigoriSpecifics(nigori);
1555 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1556 EXPECT_CALL(encryption_observer_,
1557 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1558 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _));
1559 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1560 sync_manager_.GetEncryptionHandler()->Init();
1561 EXPECT_CALL(encryption_observer_,
1562 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1563 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1564 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1565 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1566 sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("explicit");
1567 EXPECT_EQ(CUSTOM_PASSPHRASE,
1568 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1569 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1571 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1572 Cryptographer* cryptographer = trans.GetCryptographer();
1573 EXPECT_TRUE(cryptographer->is_ready());
1574 // Verify we're encrypting with the new key.
1575 sync_pb::EncryptedData encrypted;
1576 cryptographer->GetKeys(&encrypted);
1577 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1581 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1582 // being encrypted with a new (unprovided) GAIA password, then supply the
1583 // password as a user-provided password.
1584 // This is the android case 7/8.
1585 TEST_F(SyncManagerTest, SupplyPendingGAIAPassUserProvided) {
1586 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1587 Cryptographer other_cryptographer(&encryptor_);
1589 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1590 Cryptographer* cryptographer = trans.GetCryptographer();
1591 // Now update the nigori to reflect the new keys, and update the
1592 // cryptographer to have pending keys.
1593 KeyParams params = {"localhost", "dummy", "passphrase"};
1594 other_cryptographer.AddKey(params);
1595 WriteNode node(&trans);
1596 EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag));
1597 sync_pb::NigoriSpecifics nigori;
1598 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1599 node.SetNigoriSpecifics(nigori);
1600 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1601 EXPECT_FALSE(cryptographer->is_ready());
1603 EXPECT_CALL(encryption_observer_,
1604 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1605 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1606 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1607 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1608 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1611 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1612 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1613 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1615 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1616 Cryptographer* cryptographer = trans.GetCryptographer();
1617 EXPECT_TRUE(cryptographer->is_ready());
1621 TEST_F(SyncManagerTest, SetPassphraseWithEmptyPasswordNode) {
1622 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1624 std::string tag = "foo";
1626 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1627 ReadNode root_node(&trans);
1628 root_node.InitByRootLookup();
1630 WriteNode password_node(&trans);
1631 WriteNode::InitUniqueByCreationResult result =
1632 password_node.InitUniqueByCreation(PASSWORDS, root_node, tag);
1633 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
1634 node_id = password_node.GetId();
1636 EXPECT_CALL(encryption_observer_,
1637 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1638 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1639 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1640 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1641 EXPECT_CALL(encryption_observer_,
1642 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1643 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1646 EXPECT_EQ(CUSTOM_PASSPHRASE,
1647 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1648 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1650 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1651 ReadNode password_node(&trans);
1652 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1653 password_node.InitByClientTagLookup(PASSWORDS,
1657 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1658 ReadNode password_node(&trans);
1659 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1660 password_node.InitByIdLookup(node_id));
1664 TEST_F(SyncManagerTest, NudgeDelayTest) {
1665 EXPECT_EQ(sync_manager_.GetNudgeDelayTimeDelta(BOOKMARKS),
1666 base::TimeDelta::FromMilliseconds(
1667 SyncManagerImpl::GetDefaultNudgeDelay()));
1669 EXPECT_EQ(sync_manager_.GetNudgeDelayTimeDelta(AUTOFILL),
1670 base::TimeDelta::FromSeconds(
1671 kDefaultShortPollIntervalSeconds));
1673 EXPECT_EQ(sync_manager_.GetNudgeDelayTimeDelta(PREFERENCES),
1674 base::TimeDelta::FromMilliseconds(
1675 SyncManagerImpl::GetPreferencesNudgeDelay()));
1678 // Friended by WriteNode, so can't be in an anonymouse namespace.
1679 TEST_F(SyncManagerTest, EncryptBookmarksWithLegacyData) {
1680 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1682 SyncAPINameToServerName("Google", &title);
1683 std::string url = "http://www.google.com";
1684 std::string raw_title2 = ".."; // An invalid cosmo title.
1686 SyncAPINameToServerName(raw_title2, &title2);
1687 std::string url2 = "http://www.bla.com";
1689 // Create a bookmark using the legacy format.
1690 int64 node_id1 = MakeNode(sync_manager_.GetUserShare(),
1693 int64 node_id2 = MakeNode(sync_manager_.GetUserShare(),
1697 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1698 WriteNode node(&trans);
1699 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1701 sync_pb::EntitySpecifics entity_specifics;
1702 entity_specifics.mutable_bookmark()->set_url(url);
1703 node.SetEntitySpecifics(entity_specifics);
1705 // Set the old style title.
1706 syncable::MutableEntry* node_entry = node.entry_;
1707 node_entry->PutNonUniqueName(title);
1709 WriteNode node2(&trans);
1710 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1712 sync_pb::EntitySpecifics entity_specifics2;
1713 entity_specifics2.mutable_bookmark()->set_url(url2);
1714 node2.SetEntitySpecifics(entity_specifics2);
1716 // Set the old style title.
1717 syncable::MutableEntry* node_entry2 = node2.entry_;
1718 node_entry2->PutNonUniqueName(title2);
1722 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1723 ReadNode node(&trans);
1724 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1725 EXPECT_EQ(BOOKMARKS, node.GetModelType());
1726 EXPECT_EQ(title, node.GetTitle());
1727 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1728 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1730 ReadNode node2(&trans);
1731 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1732 EXPECT_EQ(BOOKMARKS, node2.GetModelType());
1733 // We should de-canonicalize the title in GetTitle(), but the title in the
1734 // specifics should be stored in the server legal form.
1735 EXPECT_EQ(raw_title2, node2.GetTitle());
1736 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1737 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1741 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1742 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1743 trans.GetWrappedTrans(),
1745 false /* not encrypted */));
1748 EXPECT_CALL(encryption_observer_,
1749 OnEncryptedTypesChanged(
1750 HasModelTypes(EncryptableUserTypes()), true));
1751 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1752 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1753 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1756 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1757 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1758 EncryptableUserTypes()));
1759 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1760 trans.GetWrappedTrans(),
1762 true /* is encrypted */));
1764 ReadNode node(&trans);
1765 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1766 EXPECT_EQ(BOOKMARKS, node.GetModelType());
1767 EXPECT_EQ(title, node.GetTitle());
1768 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1769 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1771 ReadNode node2(&trans);
1772 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1773 EXPECT_EQ(BOOKMARKS, node2.GetModelType());
1774 // We should de-canonicalize the title in GetTitle(), but the title in the
1775 // specifics should be stored in the server legal form.
1776 EXPECT_EQ(raw_title2, node2.GetTitle());
1777 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1778 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1782 // Create a bookmark and set the title/url, then verify the data was properly
1783 // set. This replicates the unique way bookmarks have of creating sync nodes.
1784 // See BookmarkChangeProcessor::PlaceSyncNode(..).
1785 TEST_F(SyncManagerTest, CreateLocalBookmark) {
1786 std::string title = "title";
1787 std::string url = "url";
1789 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1790 ReadNode bookmark_root(&trans);
1791 ASSERT_EQ(BaseNode::INIT_OK,
1792 bookmark_root.InitByTagLookup(ModelTypeToRootTag(BOOKMARKS)));
1793 WriteNode node(&trans);
1794 ASSERT_TRUE(node.InitBookmarkByCreation(bookmark_root, NULL));
1795 node.SetIsFolder(false);
1796 node.SetTitle(base::UTF8ToWide(title));
1798 sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
1799 bookmark_specifics.set_url(url);
1800 node.SetBookmarkSpecifics(bookmark_specifics);
1803 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1804 ReadNode bookmark_root(&trans);
1805 ASSERT_EQ(BaseNode::INIT_OK,
1806 bookmark_root.InitByTagLookup(ModelTypeToRootTag(BOOKMARKS)));
1807 int64 child_id = bookmark_root.GetFirstChildId();
1809 ReadNode node(&trans);
1810 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
1811 EXPECT_FALSE(node.GetIsFolder());
1812 EXPECT_EQ(title, node.GetTitle());
1813 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1817 // Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary
1819 TEST_F(SyncManagerTest, UpdateEntryWithEncryption) {
1820 std::string client_tag = "title";
1821 sync_pb::EntitySpecifics entity_specifics;
1822 entity_specifics.mutable_bookmark()->set_url("url");
1823 entity_specifics.mutable_bookmark()->set_title("title");
1824 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
1825 syncable::GenerateSyncableHash(BOOKMARKS,
1828 // New node shouldn't start off unsynced.
1829 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1830 // Manually change to the same data. Should not set is_unsynced.
1832 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1833 WriteNode node(&trans);
1834 EXPECT_EQ(BaseNode::INIT_OK,
1835 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1836 node.SetEntitySpecifics(entity_specifics);
1838 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1840 // Encrypt the datatatype, should set is_unsynced.
1841 EXPECT_CALL(encryption_observer_,
1842 OnEncryptedTypesChanged(
1843 HasModelTypes(EncryptableUserTypes()), true));
1844 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1845 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
1847 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1848 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
1849 sync_manager_.GetEncryptionHandler()->Init();
1852 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1853 ReadNode node(&trans);
1854 EXPECT_EQ(BaseNode::INIT_OK,
1855 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1856 const syncable::Entry* node_entry = node.GetEntry();
1857 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1858 EXPECT_TRUE(specifics.has_encrypted());
1859 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1860 Cryptographer* cryptographer = trans.GetCryptographer();
1861 EXPECT_TRUE(cryptographer->is_ready());
1862 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1863 specifics.encrypted()));
1865 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1867 // Set a new passphrase. Should set is_unsynced.
1868 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1869 EXPECT_CALL(encryption_observer_,
1870 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1871 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1872 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1873 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1874 EXPECT_CALL(encryption_observer_,
1875 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1876 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1880 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1881 ReadNode node(&trans);
1882 EXPECT_EQ(BaseNode::INIT_OK,
1883 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1884 const syncable::Entry* node_entry = node.GetEntry();
1885 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1886 EXPECT_TRUE(specifics.has_encrypted());
1887 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1888 Cryptographer* cryptographer = trans.GetCryptographer();
1889 EXPECT_TRUE(cryptographer->is_ready());
1890 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1891 specifics.encrypted()));
1893 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1895 // Force a re-encrypt everything. Should not set is_unsynced.
1896 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1897 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1898 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1899 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
1901 sync_manager_.GetEncryptionHandler()->Init();
1905 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1906 ReadNode node(&trans);
1907 EXPECT_EQ(BaseNode::INIT_OK,
1908 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1909 const syncable::Entry* node_entry = node.GetEntry();
1910 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1911 EXPECT_TRUE(specifics.has_encrypted());
1912 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1913 Cryptographer* cryptographer = trans.GetCryptographer();
1914 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1915 specifics.encrypted()));
1917 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1919 // Manually change to the same data. Should not set is_unsynced.
1921 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1922 WriteNode node(&trans);
1923 EXPECT_EQ(BaseNode::INIT_OK,
1924 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1925 node.SetEntitySpecifics(entity_specifics);
1926 const syncable::Entry* node_entry = node.GetEntry();
1927 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1928 EXPECT_TRUE(specifics.has_encrypted());
1929 EXPECT_FALSE(node_entry->GetIsUnsynced());
1930 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1931 Cryptographer* cryptographer = trans.GetCryptographer();
1932 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1933 specifics.encrypted()));
1935 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1937 // Manually change to different data. Should set is_unsynced.
1939 entity_specifics.mutable_bookmark()->set_url("url2");
1940 entity_specifics.mutable_bookmark()->set_title("title2");
1941 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1942 WriteNode node(&trans);
1943 EXPECT_EQ(BaseNode::INIT_OK,
1944 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1945 node.SetEntitySpecifics(entity_specifics);
1946 const syncable::Entry* node_entry = node.GetEntry();
1947 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1948 EXPECT_TRUE(specifics.has_encrypted());
1949 EXPECT_TRUE(node_entry->GetIsUnsynced());
1950 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1951 Cryptographer* cryptographer = trans.GetCryptographer();
1952 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1953 specifics.encrypted()));
1957 // Passwords have their own handling for encryption. Verify it does not result
1958 // in unnecessary writes via SetEntitySpecifics.
1959 TEST_F(SyncManagerTest, UpdatePasswordSetEntitySpecificsNoChange) {
1960 std::string client_tag = "title";
1961 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1962 sync_pb::EntitySpecifics entity_specifics;
1964 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1965 Cryptographer* cryptographer = trans.GetCryptographer();
1966 sync_pb::PasswordSpecificsData data;
1967 data.set_password_value("secret");
1968 cryptographer->Encrypt(
1970 entity_specifics.mutable_password()->
1971 mutable_encrypted());
1973 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
1974 syncable::GenerateSyncableHash(PASSWORDS,
1977 // New node shouldn't start off unsynced.
1978 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1980 // Manually change to the same data via SetEntitySpecifics. Should not set
1983 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1984 WriteNode node(&trans);
1985 EXPECT_EQ(BaseNode::INIT_OK,
1986 node.InitByClientTagLookup(PASSWORDS, client_tag));
1987 node.SetEntitySpecifics(entity_specifics);
1989 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1992 // Passwords have their own handling for encryption. Verify it does not result
1993 // in unnecessary writes via SetPasswordSpecifics.
1994 TEST_F(SyncManagerTest, UpdatePasswordSetPasswordSpecifics) {
1995 std::string client_tag = "title";
1996 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1997 sync_pb::EntitySpecifics entity_specifics;
1999 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2000 Cryptographer* cryptographer = trans.GetCryptographer();
2001 sync_pb::PasswordSpecificsData data;
2002 data.set_password_value("secret");
2003 cryptographer->Encrypt(
2005 entity_specifics.mutable_password()->
2006 mutable_encrypted());
2008 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
2009 syncable::GenerateSyncableHash(PASSWORDS,
2012 // New node shouldn't start off unsynced.
2013 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2015 // Manually change to the same data via SetPasswordSpecifics. Should not set
2018 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2019 WriteNode node(&trans);
2020 EXPECT_EQ(BaseNode::INIT_OK,
2021 node.InitByClientTagLookup(PASSWORDS, client_tag));
2022 node.SetPasswordSpecifics(node.GetPasswordSpecifics());
2024 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2026 // Manually change to different data. Should set is_unsynced.
2028 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2029 WriteNode node(&trans);
2030 EXPECT_EQ(BaseNode::INIT_OK,
2031 node.InitByClientTagLookup(PASSWORDS, client_tag));
2032 Cryptographer* cryptographer = trans.GetCryptographer();
2033 sync_pb::PasswordSpecificsData data;
2034 data.set_password_value("secret2");
2035 cryptographer->Encrypt(
2037 entity_specifics.mutable_password()->mutable_encrypted());
2038 node.SetPasswordSpecifics(data);
2039 const syncable::Entry* node_entry = node.GetEntry();
2040 EXPECT_TRUE(node_entry->GetIsUnsynced());
2044 // Passwords have their own handling for encryption. Verify setting a new
2045 // passphrase updates the data.
2046 TEST_F(SyncManagerTest, UpdatePasswordNewPassphrase) {
2047 std::string client_tag = "title";
2048 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2049 sync_pb::EntitySpecifics entity_specifics;
2051 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2052 Cryptographer* cryptographer = trans.GetCryptographer();
2053 sync_pb::PasswordSpecificsData data;
2054 data.set_password_value("secret");
2055 cryptographer->Encrypt(
2057 entity_specifics.mutable_password()->mutable_encrypted());
2059 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
2060 syncable::GenerateSyncableHash(PASSWORDS,
2063 // New node shouldn't start off unsynced.
2064 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2066 // Set a new passphrase. Should set is_unsynced.
2067 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2068 EXPECT_CALL(encryption_observer_,
2069 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
2070 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
2071 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2072 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2073 EXPECT_CALL(encryption_observer_,
2074 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
2075 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
2078 EXPECT_EQ(CUSTOM_PASSPHRASE,
2079 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
2080 EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2083 // Passwords have their own handling for encryption. Verify it does not result
2084 // in unnecessary writes via ReencryptEverything.
2085 TEST_F(SyncManagerTest, UpdatePasswordReencryptEverything) {
2086 std::string client_tag = "title";
2087 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2088 sync_pb::EntitySpecifics entity_specifics;
2090 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2091 Cryptographer* cryptographer = trans.GetCryptographer();
2092 sync_pb::PasswordSpecificsData data;
2093 data.set_password_value("secret");
2094 cryptographer->Encrypt(
2096 entity_specifics.mutable_password()->mutable_encrypted());
2098 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
2099 syncable::GenerateSyncableHash(PASSWORDS,
2102 // New node shouldn't start off unsynced.
2103 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2105 // Force a re-encrypt everything. Should not set is_unsynced.
2106 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2107 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2108 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2109 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
2110 sync_manager_.GetEncryptionHandler()->Init();
2112 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2115 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks
2116 // when we write the same data, but does set it when we write new data.
2117 TEST_F(SyncManagerTest, SetBookmarkTitle) {
2118 std::string client_tag = "title";
2119 sync_pb::EntitySpecifics entity_specifics;
2120 entity_specifics.mutable_bookmark()->set_url("url");
2121 entity_specifics.mutable_bookmark()->set_title("title");
2122 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2123 syncable::GenerateSyncableHash(BOOKMARKS,
2126 // New node shouldn't start off unsynced.
2127 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2129 // Manually change to the same title. Should not set is_unsynced.
2131 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2132 WriteNode node(&trans);
2133 EXPECT_EQ(BaseNode::INIT_OK,
2134 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2135 node.SetTitle(base::UTF8ToWide(client_tag));
2137 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2139 // Manually change to new title. Should set is_unsynced.
2141 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2142 WriteNode node(&trans);
2143 EXPECT_EQ(BaseNode::INIT_OK,
2144 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2145 node.SetTitle(base::UTF8ToWide("title2"));
2147 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2150 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2151 // bookmarks when we write the same data, but does set it when we write new
2153 TEST_F(SyncManagerTest, SetBookmarkTitleWithEncryption) {
2154 std::string client_tag = "title";
2155 sync_pb::EntitySpecifics entity_specifics;
2156 entity_specifics.mutable_bookmark()->set_url("url");
2157 entity_specifics.mutable_bookmark()->set_title("title");
2158 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2159 syncable::GenerateSyncableHash(BOOKMARKS,
2162 // New node shouldn't start off unsynced.
2163 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2165 // Encrypt the datatatype, should set is_unsynced.
2166 EXPECT_CALL(encryption_observer_,
2167 OnEncryptedTypesChanged(
2168 HasModelTypes(EncryptableUserTypes()), true));
2169 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2170 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2171 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2172 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2173 sync_manager_.GetEncryptionHandler()->Init();
2175 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2177 // Manually change to the same title. Should not set is_unsynced.
2178 // NON_UNIQUE_NAME should be kEncryptedString.
2180 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2181 WriteNode node(&trans);
2182 EXPECT_EQ(BaseNode::INIT_OK,
2183 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2184 node.SetTitle(base::UTF8ToWide(client_tag));
2185 const syncable::Entry* node_entry = node.GetEntry();
2186 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2187 EXPECT_TRUE(specifics.has_encrypted());
2188 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2190 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2192 // Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME
2193 // should still be kEncryptedString.
2195 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2196 WriteNode node(&trans);
2197 EXPECT_EQ(BaseNode::INIT_OK,
2198 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2199 node.SetTitle(base::UTF8ToWide("title2"));
2200 const syncable::Entry* node_entry = node.GetEntry();
2201 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2202 EXPECT_TRUE(specifics.has_encrypted());
2203 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2205 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2208 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks
2209 // when we write the same data, but does set it when we write new data.
2210 TEST_F(SyncManagerTest, SetNonBookmarkTitle) {
2211 std::string client_tag = "title";
2212 sync_pb::EntitySpecifics entity_specifics;
2213 entity_specifics.mutable_preference()->set_name("name");
2214 entity_specifics.mutable_preference()->set_value("value");
2215 MakeServerNode(sync_manager_.GetUserShare(),
2218 syncable::GenerateSyncableHash(PREFERENCES,
2221 // New node shouldn't start off unsynced.
2222 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2224 // Manually change to the same title. Should not set is_unsynced.
2226 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2227 WriteNode node(&trans);
2228 EXPECT_EQ(BaseNode::INIT_OK,
2229 node.InitByClientTagLookup(PREFERENCES, client_tag));
2230 node.SetTitle(base::UTF8ToWide(client_tag));
2232 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2234 // Manually change to new title. Should set is_unsynced.
2236 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2237 WriteNode node(&trans);
2238 EXPECT_EQ(BaseNode::INIT_OK,
2239 node.InitByClientTagLookup(PREFERENCES, client_tag));
2240 node.SetTitle(base::UTF8ToWide("title2"));
2242 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2245 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2246 // non-bookmarks when we write the same data or when we write new data
2247 // data (should remained kEncryptedString).
2248 TEST_F(SyncManagerTest, SetNonBookmarkTitleWithEncryption) {
2249 std::string client_tag = "title";
2250 sync_pb::EntitySpecifics entity_specifics;
2251 entity_specifics.mutable_preference()->set_name("name");
2252 entity_specifics.mutable_preference()->set_value("value");
2253 MakeServerNode(sync_manager_.GetUserShare(),
2256 syncable::GenerateSyncableHash(PREFERENCES,
2259 // New node shouldn't start off unsynced.
2260 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2262 // Encrypt the datatatype, should set is_unsynced.
2263 EXPECT_CALL(encryption_observer_,
2264 OnEncryptedTypesChanged(
2265 HasModelTypes(EncryptableUserTypes()), true));
2266 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2267 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2268 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2269 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2270 sync_manager_.GetEncryptionHandler()->Init();
2272 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2274 // Manually change to the same title. Should not set is_unsynced.
2275 // NON_UNIQUE_NAME should be kEncryptedString.
2277 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2278 WriteNode node(&trans);
2279 EXPECT_EQ(BaseNode::INIT_OK,
2280 node.InitByClientTagLookup(PREFERENCES, client_tag));
2281 node.SetTitle(base::UTF8ToWide(client_tag));
2282 const syncable::Entry* node_entry = node.GetEntry();
2283 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2284 EXPECT_TRUE(specifics.has_encrypted());
2285 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2287 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2289 // Manually change to new title. Should not set is_unsynced because the
2290 // NON_UNIQUE_NAME should still be kEncryptedString.
2292 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2293 WriteNode node(&trans);
2294 EXPECT_EQ(BaseNode::INIT_OK,
2295 node.InitByClientTagLookup(PREFERENCES, client_tag));
2296 node.SetTitle(base::UTF8ToWide("title2"));
2297 const syncable::Entry* node_entry = node.GetEntry();
2298 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2299 EXPECT_TRUE(specifics.has_encrypted());
2300 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2301 EXPECT_FALSE(node_entry->GetIsUnsynced());
2305 // Ensure that titles are truncated to 255 bytes, and attempting to reset
2306 // them to their longer version does not set IS_UNSYNCED.
2307 TEST_F(SyncManagerTest, SetLongTitle) {
2308 const int kNumChars = 512;
2309 const std::string kClientTag = "tag";
2310 std::string title(kNumChars, '0');
2311 sync_pb::EntitySpecifics entity_specifics;
2312 entity_specifics.mutable_preference()->set_name("name");
2313 entity_specifics.mutable_preference()->set_value("value");
2314 MakeServerNode(sync_manager_.GetUserShare(),
2317 syncable::GenerateSyncableHash(PREFERENCES,
2320 // New node shouldn't start off unsynced.
2321 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2323 // Manually change to the long title. Should set is_unsynced.
2325 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2326 WriteNode node(&trans);
2327 EXPECT_EQ(BaseNode::INIT_OK,
2328 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2329 node.SetTitle(base::UTF8ToWide(title));
2330 EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
2332 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2334 // Manually change to the same title. Should not set is_unsynced.
2336 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2337 WriteNode node(&trans);
2338 EXPECT_EQ(BaseNode::INIT_OK,
2339 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2340 node.SetTitle(base::UTF8ToWide(title));
2341 EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
2343 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2345 // Manually change to new title. Should set is_unsynced.
2347 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2348 WriteNode node(&trans);
2349 EXPECT_EQ(BaseNode::INIT_OK,
2350 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2351 node.SetTitle(base::UTF8ToWide("title2"));
2353 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2356 // Create an encrypted entry when the cryptographer doesn't think the type is
2357 // marked for encryption. Ensure reads/writes don't break and don't unencrypt
2359 TEST_F(SyncManagerTest, SetPreviouslyEncryptedSpecifics) {
2360 std::string client_tag = "tag";
2361 std::string url = "url";
2362 std::string url2 = "new_url";
2363 std::string title = "title";
2364 sync_pb::EntitySpecifics entity_specifics;
2365 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2367 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2368 Cryptographer* crypto = trans.GetCryptographer();
2369 sync_pb::EntitySpecifics bm_specifics;
2370 bm_specifics.mutable_bookmark()->set_title("title");
2371 bm_specifics.mutable_bookmark()->set_url("url");
2372 sync_pb::EncryptedData encrypted;
2373 crypto->Encrypt(bm_specifics, &encrypted);
2374 entity_specifics.mutable_encrypted()->CopyFrom(encrypted);
2375 AddDefaultFieldValue(BOOKMARKS, &entity_specifics);
2377 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2378 syncable::GenerateSyncableHash(BOOKMARKS,
2384 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2385 ReadNode node(&trans);
2386 EXPECT_EQ(BaseNode::INIT_OK,
2387 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2388 EXPECT_EQ(title, node.GetTitle());
2389 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
2393 // Overwrite the url (which overwrites the specifics).
2394 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2395 WriteNode node(&trans);
2396 EXPECT_EQ(BaseNode::INIT_OK,
2397 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2399 sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
2400 bookmark_specifics.set_url(url2);
2401 node.SetBookmarkSpecifics(bookmark_specifics);
2405 // Verify it's still encrypted and it has the most recent url.
2406 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2407 ReadNode node(&trans);
2408 EXPECT_EQ(BaseNode::INIT_OK,
2409 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2410 EXPECT_EQ(title, node.GetTitle());
2411 EXPECT_EQ(url2, node.GetBookmarkSpecifics().url());
2412 const syncable::Entry* node_entry = node.GetEntry();
2413 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2414 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2415 EXPECT_TRUE(specifics.has_encrypted());
2419 // Verify transaction version of a model type is incremented when node of
2420 // that type is updated.
2421 TEST_F(SyncManagerTest, IncrementTransactionVersion) {
2422 ModelSafeRoutingInfo routing_info;
2423 GetModelSafeRoutingInfo(&routing_info);
2426 ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
2427 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
2428 i != routing_info.end(); ++i) {
2429 // Transaction version is incremented when SyncManagerTest::SetUp()
2430 // creates a node of each type.
2432 sync_manager_.GetUserShare()->directory->
2433 GetTransactionVersion(i->first));
2437 // Create bookmark node to increment transaction version of bookmark model.
2438 std::string client_tag = "title";
2439 sync_pb::EntitySpecifics entity_specifics;
2440 entity_specifics.mutable_bookmark()->set_url("url");
2441 entity_specifics.mutable_bookmark()->set_title("title");
2442 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2443 syncable::GenerateSyncableHash(BOOKMARKS,
2448 ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
2449 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
2450 i != routing_info.end(); ++i) {
2451 EXPECT_EQ(i->first == BOOKMARKS ? 2 : 1,
2452 sync_manager_.GetUserShare()->directory->
2453 GetTransactionVersion(i->first));
2458 class MockSyncScheduler : public FakeSyncScheduler {
2460 MockSyncScheduler() : FakeSyncScheduler() {}
2461 virtual ~MockSyncScheduler() {}
2463 MOCK_METHOD1(Start, void(SyncScheduler::Mode));
2464 MOCK_METHOD1(ScheduleConfiguration, void(const ConfigurationParams&));
2467 class ComponentsFactory : public TestInternalComponentsFactory {
2469 ComponentsFactory(const Switches& switches,
2470 SyncScheduler* scheduler_to_use,
2471 sessions::SyncSessionContext** session_context)
2472 : TestInternalComponentsFactory(switches, syncer::STORAGE_IN_MEMORY),
2473 scheduler_to_use_(scheduler_to_use),
2474 session_context_(session_context) {}
2475 virtual ~ComponentsFactory() {}
2477 virtual scoped_ptr<SyncScheduler> BuildScheduler(
2478 const std::string& name,
2479 sessions::SyncSessionContext* context,
2480 CancelationSignal* stop_handle) OVERRIDE {
2481 *session_context_ = context;
2482 return scheduler_to_use_.Pass();
2486 scoped_ptr<SyncScheduler> scheduler_to_use_;
2487 sessions::SyncSessionContext** session_context_;
2490 class SyncManagerTestWithMockScheduler : public SyncManagerTest {
2492 SyncManagerTestWithMockScheduler() : scheduler_(NULL) {}
2493 virtual InternalComponentsFactory* GetFactory() OVERRIDE {
2494 scheduler_ = new MockSyncScheduler();
2495 return new ComponentsFactory(GetSwitches(), scheduler_, &session_context_);
2498 MockSyncScheduler* scheduler() { return scheduler_; }
2499 sessions::SyncSessionContext* session_context() {
2500 return session_context_;
2504 MockSyncScheduler* scheduler_;
2505 sessions::SyncSessionContext* session_context_;
2508 // Test that the configuration params are properly created and sent to
2509 // ScheduleConfigure. No callback should be invoked. Any disabled datatypes
2510 // should be purged.
2511 TEST_F(SyncManagerTestWithMockScheduler, BasicConfiguration) {
2512 ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
2513 ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
2514 ModelSafeRoutingInfo new_routing_info;
2515 GetModelSafeRoutingInfo(&new_routing_info);
2516 ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
2517 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2519 ConfigurationParams params;
2520 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE));
2521 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)).
2522 WillOnce(SaveArg<0>(¶ms));
2524 // Set data for all types.
2525 ModelTypeSet protocol_types = ProtocolTypes();
2526 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2528 SetProgressMarkerForType(iter.Get(), true);
2531 CallbackCounter ready_task_counter, retry_task_counter;
2532 sync_manager_.ConfigureSyncer(
2539 base::Bind(&CallbackCounter::Callback,
2540 base::Unretained(&ready_task_counter)),
2541 base::Bind(&CallbackCounter::Callback,
2542 base::Unretained(&retry_task_counter)));
2543 EXPECT_EQ(0, ready_task_counter.times_called());
2544 EXPECT_EQ(0, retry_task_counter.times_called());
2545 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION,
2547 EXPECT_TRUE(types_to_download.Equals(params.types_to_download));
2548 EXPECT_EQ(new_routing_info, params.routing_info);
2550 // Verify all the disabled types were purged.
2551 EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().Equals(
2553 EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken(
2554 ModelTypeSet::All()).Equals(disabled_types));
2557 // Test that on a reconfiguration (configuration where the session context
2558 // already has routing info), only those recently disabled types are purged.
2559 TEST_F(SyncManagerTestWithMockScheduler, ReConfiguration) {
2560 ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
2561 ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
2562 ModelTypeSet disabled_types = ModelTypeSet(THEMES, SESSIONS);
2563 ModelSafeRoutingInfo old_routing_info;
2564 ModelSafeRoutingInfo new_routing_info;
2565 GetModelSafeRoutingInfo(&old_routing_info);
2566 new_routing_info = old_routing_info;
2567 new_routing_info.erase(THEMES);
2568 new_routing_info.erase(SESSIONS);
2569 ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
2571 ConfigurationParams params;
2572 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE));
2573 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)).
2574 WillOnce(SaveArg<0>(¶ms));
2576 // Set data for all types except those recently disabled (so we can verify
2577 // only those recently disabled are purged) .
2578 ModelTypeSet protocol_types = ProtocolTypes();
2579 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2581 if (!disabled_types.Has(iter.Get())) {
2582 SetProgressMarkerForType(iter.Get(), true);
2584 SetProgressMarkerForType(iter.Get(), false);
2588 // Set the context to have the old routing info.
2589 session_context()->SetRoutingInfo(old_routing_info);
2591 CallbackCounter ready_task_counter, retry_task_counter;
2592 sync_manager_.ConfigureSyncer(
2599 base::Bind(&CallbackCounter::Callback,
2600 base::Unretained(&ready_task_counter)),
2601 base::Bind(&CallbackCounter::Callback,
2602 base::Unretained(&retry_task_counter)));
2603 EXPECT_EQ(0, ready_task_counter.times_called());
2604 EXPECT_EQ(0, retry_task_counter.times_called());
2605 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION,
2607 EXPECT_TRUE(types_to_download.Equals(params.types_to_download));
2608 EXPECT_EQ(new_routing_info, params.routing_info);
2610 // Verify only the recently disabled types were purged.
2611 EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken(
2612 ProtocolTypes()).Equals(disabled_types));
2615 // Test that PurgePartiallySyncedTypes purges only those types that have not
2616 // fully completed their initial download and apply.
2617 TEST_F(SyncManagerTest, PurgePartiallySyncedTypes) {
2618 ModelSafeRoutingInfo routing_info;
2619 GetModelSafeRoutingInfo(&routing_info);
2620 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2622 UserShare* share = sync_manager_.GetUserShare();
2624 // The test harness automatically initializes all types in the routing info.
2625 // Check that autofill is not among them.
2626 ASSERT_FALSE(enabled_types.Has(AUTOFILL));
2628 // Further ensure that the test harness did not create its root node.
2630 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2631 syncable::Entry autofill_root_node(&trans, syncable::GET_BY_SERVER_TAG,
2632 ModelTypeToRootTag(AUTOFILL));
2633 ASSERT_FALSE(autofill_root_node.good());
2636 // One more redundant check.
2637 ASSERT_FALSE(sync_manager_.InitialSyncEndedTypes().Has(AUTOFILL));
2639 // Give autofill a progress marker.
2640 sync_pb::DataTypeProgressMarker autofill_marker;
2641 autofill_marker.set_data_type_id(
2642 GetSpecificsFieldNumberFromModelType(AUTOFILL));
2643 autofill_marker.set_token("token");
2644 share->directory->SetDownloadProgress(AUTOFILL, autofill_marker);
2646 // Also add a pending autofill root node update from the server.
2647 TestEntryFactory factory_(share->directory.get());
2648 int autofill_meta = factory_.CreateUnappliedRootNode(AUTOFILL);
2650 // Preferences is an enabled type. Check that the harness initialized it.
2651 ASSERT_TRUE(enabled_types.Has(PREFERENCES));
2652 ASSERT_TRUE(sync_manager_.InitialSyncEndedTypes().Has(PREFERENCES));
2654 // Give preferencse a progress marker.
2655 sync_pb::DataTypeProgressMarker prefs_marker;
2656 prefs_marker.set_data_type_id(
2657 GetSpecificsFieldNumberFromModelType(PREFERENCES));
2658 prefs_marker.set_token("token");
2659 share->directory->SetDownloadProgress(PREFERENCES, prefs_marker);
2661 // Add a fully synced preferences node under the root.
2662 std::string pref_client_tag = "prefABC";
2663 std::string pref_hashed_tag = "hashXYZ";
2664 sync_pb::EntitySpecifics pref_specifics;
2665 AddDefaultFieldValue(PREFERENCES, &pref_specifics);
2666 int pref_meta = MakeServerNode(
2667 share, PREFERENCES, pref_client_tag, pref_hashed_tag, pref_specifics);
2669 // And now, the purge.
2670 EXPECT_TRUE(sync_manager_.PurgePartiallySyncedTypes());
2672 // Ensure that autofill lost its progress marker, but preferences did not.
2673 ModelTypeSet empty_tokens =
2674 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All());
2675 EXPECT_TRUE(empty_tokens.Has(AUTOFILL));
2676 EXPECT_FALSE(empty_tokens.Has(PREFERENCES));
2678 // Ensure that autofill lots its node, but preferences did not.
2680 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2681 syncable::Entry autofill_node(&trans, GET_BY_HANDLE, autofill_meta);
2682 syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref_meta);
2683 EXPECT_FALSE(autofill_node.good());
2684 EXPECT_TRUE(pref_node.good());
2688 // Test CleanupDisabledTypes properly purges all disabled types as specified
2689 // by the previous and current enabled params.
2690 TEST_F(SyncManagerTest, PurgeDisabledTypes) {
2691 ModelSafeRoutingInfo routing_info;
2692 GetModelSafeRoutingInfo(&routing_info);
2693 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2694 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2696 // The harness should have initialized the enabled_types for us.
2697 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2699 // Set progress markers for all types.
2700 ModelTypeSet protocol_types = ProtocolTypes();
2701 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2703 SetProgressMarkerForType(iter.Get(), true);
2706 // Verify all the enabled types remain after cleanup, and all the disabled
2707 // types were purged.
2708 sync_manager_.PurgeDisabledTypes(disabled_types,
2711 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2712 EXPECT_TRUE(disabled_types.Equals(
2713 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2715 // Disable some more types.
2716 disabled_types.Put(BOOKMARKS);
2717 disabled_types.Put(PREFERENCES);
2718 ModelTypeSet new_enabled_types =
2719 Difference(ModelTypeSet::All(), disabled_types);
2721 // Verify only the non-disabled types remain after cleanup.
2722 sync_manager_.PurgeDisabledTypes(disabled_types,
2725 EXPECT_TRUE(new_enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2726 EXPECT_TRUE(disabled_types.Equals(
2727 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2730 // Test PurgeDisabledTypes properly unapplies types by deleting their local data
2731 // and preserving their server data and progress marker.
2732 TEST_F(SyncManagerTest, PurgeUnappliedTypes) {
2733 ModelSafeRoutingInfo routing_info;
2734 GetModelSafeRoutingInfo(&routing_info);
2735 ModelTypeSet unapplied_types = ModelTypeSet(BOOKMARKS, PREFERENCES);
2736 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2737 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2739 // The harness should have initialized the enabled_types for us.
2740 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2742 // Set progress markers for all types.
2743 ModelTypeSet protocol_types = ProtocolTypes();
2744 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2746 SetProgressMarkerForType(iter.Get(), true);
2749 // Add the following kinds of items:
2750 // 1. Fully synced preference.
2751 // 2. Locally created preference, server unknown, unsynced
2752 // 3. Locally deleted preference, server known, unsynced
2753 // 4. Server deleted preference, locally known.
2754 // 5. Server created preference, locally unknown, unapplied.
2755 // 6. A fully synced bookmark (no unique_client_tag).
2756 UserShare* share = sync_manager_.GetUserShare();
2757 sync_pb::EntitySpecifics pref_specifics;
2758 AddDefaultFieldValue(PREFERENCES, &pref_specifics);
2759 sync_pb::EntitySpecifics bm_specifics;
2760 AddDefaultFieldValue(BOOKMARKS, &bm_specifics);
2761 int pref1_meta = MakeServerNode(
2762 share, PREFERENCES, "pref1", "hash1", pref_specifics);
2763 int64 pref2_meta = MakeNode(share, PREFERENCES, "pref2");
2764 int pref3_meta = MakeServerNode(
2765 share, PREFERENCES, "pref3", "hash3", pref_specifics);
2766 int pref4_meta = MakeServerNode(
2767 share, PREFERENCES, "pref4", "hash4", pref_specifics);
2768 int pref5_meta = MakeServerNode(
2769 share, PREFERENCES, "pref5", "hash5", pref_specifics);
2770 int bookmark_meta = MakeServerNode(
2771 share, BOOKMARKS, "bookmark", "", bm_specifics);
2774 syncable::WriteTransaction trans(FROM_HERE,
2776 share->directory.get());
2777 // Pref's 1 and 2 are already set up properly.
2778 // Locally delete pref 3.
2779 syncable::MutableEntry pref3(&trans, GET_BY_HANDLE, pref3_meta);
2780 pref3.PutIsDel(true);
2781 pref3.PutIsUnsynced(true);
2782 // Delete pref 4 at the server.
2783 syncable::MutableEntry pref4(&trans, GET_BY_HANDLE, pref4_meta);
2784 pref4.PutServerIsDel(true);
2785 pref4.PutIsUnappliedUpdate(true);
2786 pref4.PutServerVersion(2);
2787 // Pref 5 is an new unapplied update.
2788 syncable::MutableEntry pref5(&trans, GET_BY_HANDLE, pref5_meta);
2789 pref5.PutIsUnappliedUpdate(true);
2790 pref5.PutIsDel(true);
2791 pref5.PutBaseVersion(-1);
2792 // Bookmark is already set up properly
2795 // Take a snapshot to clear all the dirty bits.
2796 share->directory.get()->SaveChanges();
2798 // Now request a purge for the unapplied types.
2799 disabled_types.PutAll(unapplied_types);
2800 sync_manager_.PurgeDisabledTypes(disabled_types,
2804 // Verify the unapplied types still have progress markers and initial sync
2805 // ended after cleanup.
2806 EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().HasAll(unapplied_types));
2808 sync_manager_.GetTypesWithEmptyProgressMarkerToken(unapplied_types).
2811 // Ensure the items were unapplied as necessary.
2813 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2814 syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref1_meta);
2815 ASSERT_TRUE(pref_node.good());
2816 EXPECT_TRUE(pref_node.GetKernelCopy().is_dirty());
2817 EXPECT_FALSE(pref_node.GetIsUnsynced());
2818 EXPECT_TRUE(pref_node.GetIsUnappliedUpdate());
2819 EXPECT_TRUE(pref_node.GetIsDel());
2820 EXPECT_GT(pref_node.GetServerVersion(), 0);
2821 EXPECT_EQ(pref_node.GetBaseVersion(), -1);
2823 // Pref 2 should just be locally deleted.
2824 syncable::Entry pref2_node(&trans, GET_BY_HANDLE, pref2_meta);
2825 ASSERT_TRUE(pref2_node.good());
2826 EXPECT_TRUE(pref2_node.GetKernelCopy().is_dirty());
2827 EXPECT_FALSE(pref2_node.GetIsUnsynced());
2828 EXPECT_TRUE(pref2_node.GetIsDel());
2829 EXPECT_FALSE(pref2_node.GetIsUnappliedUpdate());
2830 EXPECT_TRUE(pref2_node.GetIsDel());
2831 EXPECT_EQ(pref2_node.GetServerVersion(), 0);
2832 EXPECT_EQ(pref2_node.GetBaseVersion(), -1);
2834 syncable::Entry pref3_node(&trans, GET_BY_HANDLE, pref3_meta);
2835 ASSERT_TRUE(pref3_node.good());
2836 EXPECT_TRUE(pref3_node.GetKernelCopy().is_dirty());
2837 EXPECT_FALSE(pref3_node.GetIsUnsynced());
2838 EXPECT_TRUE(pref3_node.GetIsUnappliedUpdate());
2839 EXPECT_TRUE(pref3_node.GetIsDel());
2840 EXPECT_GT(pref3_node.GetServerVersion(), 0);
2841 EXPECT_EQ(pref3_node.GetBaseVersion(), -1);
2843 syncable::Entry pref4_node(&trans, GET_BY_HANDLE, pref4_meta);
2844 ASSERT_TRUE(pref4_node.good());
2845 EXPECT_TRUE(pref4_node.GetKernelCopy().is_dirty());
2846 EXPECT_FALSE(pref4_node.GetIsUnsynced());
2847 EXPECT_TRUE(pref4_node.GetIsUnappliedUpdate());
2848 EXPECT_TRUE(pref4_node.GetIsDel());
2849 EXPECT_GT(pref4_node.GetServerVersion(), 0);
2850 EXPECT_EQ(pref4_node.GetBaseVersion(), -1);
2852 // Pref 5 should remain untouched.
2853 syncable::Entry pref5_node(&trans, GET_BY_HANDLE, pref5_meta);
2854 ASSERT_TRUE(pref5_node.good());
2855 EXPECT_FALSE(pref5_node.GetKernelCopy().is_dirty());
2856 EXPECT_FALSE(pref5_node.GetIsUnsynced());
2857 EXPECT_TRUE(pref5_node.GetIsUnappliedUpdate());
2858 EXPECT_TRUE(pref5_node.GetIsDel());
2859 EXPECT_GT(pref5_node.GetServerVersion(), 0);
2860 EXPECT_EQ(pref5_node.GetBaseVersion(), -1);
2862 syncable::Entry bookmark_node(&trans, GET_BY_HANDLE, bookmark_meta);
2863 ASSERT_TRUE(bookmark_node.good());
2864 EXPECT_TRUE(bookmark_node.GetKernelCopy().is_dirty());
2865 EXPECT_FALSE(bookmark_node.GetIsUnsynced());
2866 EXPECT_TRUE(bookmark_node.GetIsUnappliedUpdate());
2867 EXPECT_TRUE(bookmark_node.GetIsDel());
2868 EXPECT_GT(bookmark_node.GetServerVersion(), 0);
2869 EXPECT_EQ(bookmark_node.GetBaseVersion(), -1);
2873 // A test harness to exercise the code that processes and passes changes from
2874 // the "SYNCER"-WriteTransaction destructor, through the SyncManager, to the
2876 class SyncManagerChangeProcessingTest : public SyncManagerTest {
2878 virtual void OnChangesApplied(
2879 ModelType model_type,
2880 int64 model_version,
2881 const BaseTransaction* trans,
2882 const ImmutableChangeRecordList& changes) OVERRIDE {
2883 last_changes_ = changes;
2886 virtual void OnChangesComplete(ModelType model_type) OVERRIDE {}
2888 const ImmutableChangeRecordList& GetRecentChangeList() {
2889 return last_changes_;
2892 UserShare* share() {
2893 return sync_manager_.GetUserShare();
2896 // Set some flags so our nodes reasonably approximate the real world scenario
2897 // and can get past CheckTreeInvariants.
2899 // It's never going to be truly accurate, since we're squashing update
2900 // receipt, processing and application into a single transaction.
2901 void SetNodeProperties(syncable::MutableEntry *entry) {
2902 entry->PutId(id_factory_.NewServerId());
2903 entry->PutBaseVersion(10);
2904 entry->PutServerVersion(10);
2907 // Looks for the given change in the list. Returns the index at which it was
2908 // found. Returns -1 on lookup failure.
2909 size_t FindChangeInList(int64 id, ChangeRecord::Action action) {
2911 for (size_t i = 0; i < last_changes_.Get().size(); ++i) {
2912 if (last_changes_.Get()[i].id == id
2913 && last_changes_.Get()[i].action == action) {
2917 ADD_FAILURE() << "Failed to find specified change";
2921 // Returns the current size of the change list.
2923 // Note that spurious changes do not necessarily indicate a problem.
2924 // Assertions on change list size can help detect problems, but it may be
2925 // necessary to reduce their strictness if the implementation changes.
2926 size_t GetChangeListSize() {
2927 return last_changes_.Get().size();
2931 ImmutableChangeRecordList last_changes_;
2932 TestIdFactory id_factory_;
2935 // Test creation of a folder and a bookmark.
2936 TEST_F(SyncManagerChangeProcessingTest, AddBookmarks) {
2937 int64 type_root = GetIdForDataType(BOOKMARKS);
2938 int64 folder_id = kInvalidId;
2939 int64 child_id = kInvalidId;
2941 // Create a folder and a bookmark under it.
2943 syncable::WriteTransaction trans(
2944 FROM_HERE, syncable::SYNCER, share()->directory.get());
2945 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
2946 ASSERT_TRUE(root.good());
2948 syncable::MutableEntry folder(&trans, syncable::CREATE,
2949 BOOKMARKS, root.GetId(), "folder");
2950 ASSERT_TRUE(folder.good());
2951 SetNodeProperties(&folder);
2952 folder.PutIsDir(true);
2953 folder_id = folder.GetMetahandle();
2955 syncable::MutableEntry child(&trans, syncable::CREATE,
2956 BOOKMARKS, folder.GetId(), "child");
2957 ASSERT_TRUE(child.good());
2958 SetNodeProperties(&child);
2959 child_id = child.GetMetahandle();
2962 // The closing of the above scope will delete the transaction. Its processed
2963 // changes should be waiting for us in a member of the test harness.
2964 EXPECT_EQ(2UL, GetChangeListSize());
2966 // We don't need to check these return values here. The function will add a
2967 // non-fatal failure if these changes are not found.
2968 size_t folder_change_pos =
2969 FindChangeInList(folder_id, ChangeRecord::ACTION_ADD);
2970 size_t child_change_pos =
2971 FindChangeInList(child_id, ChangeRecord::ACTION_ADD);
2973 // Parents are delivered before children.
2974 EXPECT_LT(folder_change_pos, child_change_pos);
2977 // Test moving a bookmark into an empty folder.
2978 TEST_F(SyncManagerChangeProcessingTest, MoveBookmarkIntoEmptyFolder) {
2979 int64 type_root = GetIdForDataType(BOOKMARKS);
2980 int64 folder_b_id = kInvalidId;
2981 int64 child_id = kInvalidId;
2983 // Create two folders. Place a child under folder A.
2985 syncable::WriteTransaction trans(
2986 FROM_HERE, syncable::SYNCER, share()->directory.get());
2987 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
2988 ASSERT_TRUE(root.good());
2990 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
2991 BOOKMARKS, root.GetId(), "folderA");
2992 ASSERT_TRUE(folder_a.good());
2993 SetNodeProperties(&folder_a);
2994 folder_a.PutIsDir(true);
2996 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
2997 BOOKMARKS, root.GetId(), "folderB");
2998 ASSERT_TRUE(folder_b.good());
2999 SetNodeProperties(&folder_b);
3000 folder_b.PutIsDir(true);
3001 folder_b_id = folder_b.GetMetahandle();
3003 syncable::MutableEntry child(&trans, syncable::CREATE,
3004 BOOKMARKS, folder_a.GetId(),
3006 ASSERT_TRUE(child.good());
3007 SetNodeProperties(&child);
3008 child_id = child.GetMetahandle();
3011 // Close that transaction. The above was to setup the initial scenario. The
3012 // real test starts now.
3014 // Move the child from folder A to folder B.
3016 syncable::WriteTransaction trans(
3017 FROM_HERE, syncable::SYNCER, share()->directory.get());
3019 syncable::Entry folder_b(&trans, syncable::GET_BY_HANDLE, folder_b_id);
3020 syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
3022 child.PutParentId(folder_b.GetId());
3025 EXPECT_EQ(1UL, GetChangeListSize());
3027 // Verify that this was detected as a real change. An early version of the
3028 // UniquePosition code had a bug where moves from one folder to another were
3029 // ignored unless the moved node's UniquePosition value was also changed in
3031 FindChangeInList(child_id, ChangeRecord::ACTION_UPDATE);
3034 // Test moving a bookmark into a non-empty folder.
3035 TEST_F(SyncManagerChangeProcessingTest, MoveIntoPopulatedFolder) {
3036 int64 type_root = GetIdForDataType(BOOKMARKS);
3037 int64 child_a_id = kInvalidId;
3038 int64 child_b_id = kInvalidId;
3040 // Create two folders. Place one child each under folder A and folder B.
3042 syncable::WriteTransaction trans(
3043 FROM_HERE, syncable::SYNCER, share()->directory.get());
3044 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3045 ASSERT_TRUE(root.good());
3047 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3048 BOOKMARKS, root.GetId(), "folderA");
3049 ASSERT_TRUE(folder_a.good());
3050 SetNodeProperties(&folder_a);
3051 folder_a.PutIsDir(true);
3053 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3054 BOOKMARKS, root.GetId(), "folderB");
3055 ASSERT_TRUE(folder_b.good());
3056 SetNodeProperties(&folder_b);
3057 folder_b.PutIsDir(true);
3059 syncable::MutableEntry child_a(&trans, syncable::CREATE,
3060 BOOKMARKS, folder_a.GetId(),
3062 ASSERT_TRUE(child_a.good());
3063 SetNodeProperties(&child_a);
3064 child_a_id = child_a.GetMetahandle();
3066 syncable::MutableEntry child_b(&trans, syncable::CREATE,
3067 BOOKMARKS, folder_b.GetId(),
3069 SetNodeProperties(&child_b);
3070 child_b_id = child_b.GetMetahandle();
3074 // Close that transaction. The above was to setup the initial scenario. The
3075 // real test starts now.
3078 syncable::WriteTransaction trans(
3079 FROM_HERE, syncable::SYNCER, share()->directory.get());
3081 syncable::MutableEntry child_a(&trans, syncable::GET_BY_HANDLE, child_a_id);
3082 syncable::MutableEntry child_b(&trans, syncable::GET_BY_HANDLE, child_b_id);
3084 // Move child A from folder A to folder B and update its position.
3085 child_a.PutParentId(child_b.GetParentId());
3086 child_a.PutPredecessor(child_b.GetId());
3089 EXPECT_EQ(1UL, GetChangeListSize());
3091 // Verify that only child a is in the change list.
3092 // (This function will add a failure if the lookup fails.)
3093 FindChangeInList(child_a_id, ChangeRecord::ACTION_UPDATE);
3096 // Tests the ordering of deletion changes.
3097 TEST_F(SyncManagerChangeProcessingTest, DeletionsAndChanges) {
3098 int64 type_root = GetIdForDataType(BOOKMARKS);
3099 int64 folder_a_id = kInvalidId;
3100 int64 folder_b_id = kInvalidId;
3101 int64 child_id = kInvalidId;
3103 // Create two folders. Place a child under folder A.
3105 syncable::WriteTransaction trans(
3106 FROM_HERE, syncable::SYNCER, share()->directory.get());
3107 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3108 ASSERT_TRUE(root.good());
3110 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3111 BOOKMARKS, root.GetId(), "folderA");
3112 ASSERT_TRUE(folder_a.good());
3113 SetNodeProperties(&folder_a);
3114 folder_a.PutIsDir(true);
3115 folder_a_id = folder_a.GetMetahandle();
3117 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3118 BOOKMARKS, root.GetId(), "folderB");
3119 ASSERT_TRUE(folder_b.good());
3120 SetNodeProperties(&folder_b);
3121 folder_b.PutIsDir(true);
3122 folder_b_id = folder_b.GetMetahandle();
3124 syncable::MutableEntry child(&trans, syncable::CREATE,
3125 BOOKMARKS, folder_a.GetId(),
3127 ASSERT_TRUE(child.good());
3128 SetNodeProperties(&child);
3129 child_id = child.GetMetahandle();
3132 // Close that transaction. The above was to setup the initial scenario. The
3133 // real test starts now.
3136 syncable::WriteTransaction trans(
3137 FROM_HERE, syncable::SYNCER, share()->directory.get());
3139 syncable::MutableEntry folder_a(
3140 &trans, syncable::GET_BY_HANDLE, folder_a_id);
3141 syncable::MutableEntry folder_b(
3142 &trans, syncable::GET_BY_HANDLE, folder_b_id);
3143 syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
3145 // Delete folder B and its child.
3146 child.PutIsDel(true);
3147 folder_b.PutIsDel(true);
3149 // Make an unrelated change to folder A.
3150 folder_a.PutNonUniqueName("NewNameA");
3153 EXPECT_EQ(3UL, GetChangeListSize());
3155 size_t folder_a_pos =
3156 FindChangeInList(folder_a_id, ChangeRecord::ACTION_UPDATE);
3157 size_t folder_b_pos =
3158 FindChangeInList(folder_b_id, ChangeRecord::ACTION_DELETE);
3159 size_t child_pos = FindChangeInList(child_id, ChangeRecord::ACTION_DELETE);
3161 // Deletes should appear before updates.
3162 EXPECT_LT(child_pos, folder_a_pos);
3163 EXPECT_LT(folder_b_pos, folder_a_pos);
3166 // During initialization SyncManagerImpl loads sqlite database. If it fails to
3167 // do so it should fail initialization. This test verifies this behavior.
3168 // Test reuses SyncManagerImpl initialization from SyncManagerTest but overrides
3169 // InternalComponentsFactory to return DirectoryBackingStore that always fails
3171 class SyncManagerInitInvalidStorageTest : public SyncManagerTest {
3173 SyncManagerInitInvalidStorageTest() {
3176 virtual InternalComponentsFactory* GetFactory() OVERRIDE {
3177 return new TestInternalComponentsFactory(GetSwitches(), STORAGE_INVALID);
3181 // SyncManagerInitInvalidStorageTest::GetFactory will return
3182 // DirectoryBackingStore that ensures that SyncManagerImpl::OpenDirectory fails.
3183 // SyncManagerImpl initialization is done in SyncManagerTest::SetUp. This test's
3184 // task is to ensure that SyncManagerImpl reported initialization failure in
3185 // OnInitializationComplete callback.
3186 TEST_F(SyncManagerInitInvalidStorageTest, FailToOpenDatabase) {
3187 EXPECT_FALSE(initialization_succeeded_);