ffmpeg_common: s/PIX_FMT/AV_PIX_FMT/
[chromium-blink-merge.git] / sync / internal_api / sync_manager_impl_unittest.cc
blob34ba76f97a4e7b02fee77ed1af9c5886f6c81f68
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.
9 #include <cstddef>
10 #include <map>
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/run_loop.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/test/values_test_util.h"
24 #include "base/values.h"
25 #include "google_apis/gaia/gaia_constants.h"
26 #include "sync/engine/sync_scheduler.h"
27 #include "sync/internal_api/public/base/attachment_id_proto.h"
28 #include "sync/internal_api/public/base/cancelation_signal.h"
29 #include "sync/internal_api/public/base/model_type_test_util.h"
30 #include "sync/internal_api/public/change_record.h"
31 #include "sync/internal_api/public/engine/model_safe_worker.h"
32 #include "sync/internal_api/public/engine/polling_constants.h"
33 #include "sync/internal_api/public/events/protocol_event.h"
34 #include "sync/internal_api/public/http_post_provider_factory.h"
35 #include "sync/internal_api/public/http_post_provider_interface.h"
36 #include "sync/internal_api/public/read_node.h"
37 #include "sync/internal_api/public/read_transaction.h"
38 #include "sync/internal_api/public/test/test_entry_factory.h"
39 #include "sync/internal_api/public/test/test_internal_components_factory.h"
40 #include "sync/internal_api/public/test/test_user_share.h"
41 #include "sync/internal_api/public/write_node.h"
42 #include "sync/internal_api/public/write_transaction.h"
43 #include "sync/internal_api/sync_encryption_handler_impl.h"
44 #include "sync/internal_api/sync_manager_impl.h"
45 #include "sync/internal_api/syncapi_internal.h"
46 #include "sync/js/js_backend.h"
47 #include "sync/js/js_event_handler.h"
48 #include "sync/js/js_test_util.h"
49 #include "sync/protocol/bookmark_specifics.pb.h"
50 #include "sync/protocol/encryption.pb.h"
51 #include "sync/protocol/extension_specifics.pb.h"
52 #include "sync/protocol/password_specifics.pb.h"
53 #include "sync/protocol/preference_specifics.pb.h"
54 #include "sync/protocol/proto_value_conversions.h"
55 #include "sync/protocol/sync.pb.h"
56 #include "sync/sessions/sync_session.h"
57 #include "sync/syncable/directory.h"
58 #include "sync/syncable/entry.h"
59 #include "sync/syncable/mutable_entry.h"
60 #include "sync/syncable/nigori_util.h"
61 #include "sync/syncable/syncable_id.h"
62 #include "sync/syncable/syncable_read_transaction.h"
63 #include "sync/syncable/syncable_util.h"
64 #include "sync/syncable/syncable_write_transaction.h"
65 #include "sync/test/callback_counter.h"
66 #include "sync/test/engine/fake_model_worker.h"
67 #include "sync/test/engine/fake_sync_scheduler.h"
68 #include "sync/test/engine/test_id_factory.h"
69 #include "sync/test/fake_encryptor.h"
70 #include "sync/util/cryptographer.h"
71 #include "sync/util/extensions_activity.h"
72 #include "sync/util/mock_unrecoverable_error_handler.h"
73 #include "sync/util/time.h"
74 #include "testing/gmock/include/gmock/gmock.h"
75 #include "testing/gtest/include/gtest/gtest.h"
76 #include "url/gurl.h"
78 using base::ExpectDictStringValue;
79 using testing::_;
80 using testing::DoAll;
81 using testing::InSequence;
82 using testing::Return;
83 using testing::SaveArg;
84 using testing::StrictMock;
86 namespace syncer {
88 using sessions::SyncSessionSnapshot;
89 using syncable::GET_BY_HANDLE;
90 using syncable::IS_DEL;
91 using syncable::IS_UNSYNCED;
92 using syncable::NON_UNIQUE_NAME;
93 using syncable::SPECIFICS;
94 using syncable::kEncryptedString;
96 namespace {
98 // Makes a child node under the type root folder. Returns the id of the
99 // newly-created node.
100 int64 MakeNode(UserShare* share,
101 ModelType model_type,
102 const std::string& client_tag) {
103 WriteTransaction trans(FROM_HERE, share);
104 WriteNode node(&trans);
105 WriteNode::InitUniqueByCreationResult result =
106 node.InitUniqueByCreation(model_type, client_tag);
107 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
108 node.SetIsFolder(false);
109 return node.GetId();
112 // Makes a non-folder child of the root node. Returns the id of the
113 // newly-created node.
114 int64 MakeNodeWithRoot(UserShare* share,
115 ModelType model_type,
116 const std::string& client_tag) {
117 WriteTransaction trans(FROM_HERE, share);
118 ReadNode root_node(&trans);
119 root_node.InitByRootLookup();
120 WriteNode node(&trans);
121 WriteNode::InitUniqueByCreationResult result =
122 node.InitUniqueByCreation(model_type, root_node, client_tag);
123 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
124 node.SetIsFolder(false);
125 return node.GetId();
128 // Makes a folder child of a non-root node. Returns the id of the
129 // newly-created node.
130 int64 MakeFolderWithParent(UserShare* share,
131 ModelType model_type,
132 int64 parent_id,
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));
139 node.SetIsFolder(true);
140 return node.GetId();
143 int64 MakeBookmarkWithParent(UserShare* share,
144 int64 parent_id,
145 BaseNode* predecessor) {
146 WriteTransaction trans(FROM_HERE, share);
147 ReadNode parent_node(&trans);
148 EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
149 WriteNode node(&trans);
150 EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor));
151 return node.GetId();
154 // Creates the "synced" root node for a particular datatype. We use the syncable
155 // methods here so that the syncer treats these nodes as if they were already
156 // received from the server.
157 int64 MakeTypeRoot(UserShare* share, ModelType model_type) {
158 sync_pb::EntitySpecifics specifics;
159 AddDefaultFieldValue(model_type, &specifics);
160 syncable::WriteTransaction trans(
161 FROM_HERE, syncable::UNITTEST, share->directory.get());
162 // Attempt to lookup by nigori tag.
163 std::string type_tag = ModelTypeToRootTag(model_type);
164 syncable::Id node_id = syncable::Id::CreateFromServerId(type_tag);
165 syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
166 node_id);
167 EXPECT_TRUE(entry.good());
168 entry.PutBaseVersion(1);
169 entry.PutServerVersion(1);
170 entry.PutIsUnappliedUpdate(false);
171 entry.PutParentId(syncable::Id::GetRoot());
172 entry.PutServerParentId(syncable::Id::GetRoot());
173 entry.PutServerIsDir(true);
174 entry.PutIsDir(true);
175 entry.PutServerSpecifics(specifics);
176 entry.PutSpecifics(specifics);
177 entry.PutUniqueServerTag(type_tag);
178 entry.PutNonUniqueName(type_tag);
179 entry.PutIsDel(false);
180 return entry.GetMetahandle();
183 // Simulates creating a "synced" node as a child of the root datatype node.
184 int64 MakeServerNode(UserShare* share, ModelType model_type,
185 const std::string& client_tag,
186 const std::string& hashed_tag,
187 const sync_pb::EntitySpecifics& specifics) {
188 syncable::WriteTransaction trans(
189 FROM_HERE, syncable::UNITTEST, share->directory.get());
190 syncable::Entry root_entry(&trans, syncable::GET_TYPE_ROOT, model_type);
191 EXPECT_TRUE(root_entry.good());
192 syncable::Id root_id = root_entry.GetId();
193 syncable::Id node_id = syncable::Id::CreateFromServerId(client_tag);
194 syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
195 node_id);
196 EXPECT_TRUE(entry.good());
197 entry.PutBaseVersion(1);
198 entry.PutServerVersion(1);
199 entry.PutIsUnappliedUpdate(false);
200 entry.PutServerParentId(root_id);
201 entry.PutParentId(root_id);
202 entry.PutServerIsDir(false);
203 entry.PutIsDir(false);
204 entry.PutServerSpecifics(specifics);
205 entry.PutSpecifics(specifics);
206 entry.PutNonUniqueName(client_tag);
207 entry.PutUniqueClientTag(hashed_tag);
208 entry.PutIsDel(false);
209 return entry.GetMetahandle();
212 } // namespace
214 class SyncApiTest : public testing::Test {
215 public:
216 void SetUp() override { test_user_share_.SetUp(); }
218 void TearDown() override { test_user_share_.TearDown(); }
220 protected:
221 // Create an entry with the given |model_type|, |client_tag| and
222 // |attachment_metadata|.
223 void CreateEntryWithAttachmentMetadata(
224 const ModelType& model_type,
225 const std::string& client_tag,
226 const sync_pb::AttachmentMetadata& attachment_metadata);
228 // Attempts to load the entry specified by |model_type| and |client_tag| and
229 // returns the lookup result code.
230 BaseNode::InitByLookupResult LookupEntryByClientTag(
231 const ModelType& model_type,
232 const std::string& client_tag);
234 // Replace the entry specified by |model_type| and |client_tag| with a
235 // tombstone.
236 void ReplaceWithTombstone(const ModelType& model_type,
237 const std::string& client_tag);
239 // Save changes to the Directory, destroy it then reload it.
240 bool ReloadDir();
242 UserShare* user_share();
243 syncable::Directory* dir();
244 SyncEncryptionHandler* encryption_handler();
246 private:
247 base::MessageLoop message_loop_;
248 TestUserShare test_user_share_;
251 UserShare* SyncApiTest::user_share() {
252 return test_user_share_.user_share();
255 syncable::Directory* SyncApiTest::dir() {
256 return test_user_share_.user_share()->directory.get();
259 SyncEncryptionHandler* SyncApiTest::encryption_handler() {
260 return test_user_share_.encryption_handler();
263 bool SyncApiTest::ReloadDir() {
264 return test_user_share_.Reload();
267 void SyncApiTest::CreateEntryWithAttachmentMetadata(
268 const ModelType& model_type,
269 const std::string& client_tag,
270 const sync_pb::AttachmentMetadata& attachment_metadata) {
271 syncer::WriteTransaction trans(FROM_HERE, user_share());
272 syncer::ReadNode root_node(&trans);
273 root_node.InitByRootLookup();
274 syncer::WriteNode node(&trans);
275 ASSERT_EQ(node.InitUniqueByCreation(model_type, root_node, client_tag),
276 syncer::WriteNode::INIT_SUCCESS);
277 node.SetAttachmentMetadata(attachment_metadata);
280 BaseNode::InitByLookupResult SyncApiTest::LookupEntryByClientTag(
281 const ModelType& model_type,
282 const std::string& client_tag) {
283 syncer::ReadTransaction trans(FROM_HERE, user_share());
284 syncer::ReadNode node(&trans);
285 return node.InitByClientTagLookup(model_type, client_tag);
288 void SyncApiTest::ReplaceWithTombstone(const ModelType& model_type,
289 const std::string& client_tag) {
290 syncer::WriteTransaction trans(FROM_HERE, user_share());
291 syncer::WriteNode node(&trans);
292 ASSERT_EQ(node.InitByClientTagLookup(model_type, client_tag),
293 syncer::WriteNode::INIT_OK);
294 node.Tombstone();
297 TEST_F(SyncApiTest, SanityCheckTest) {
299 ReadTransaction trans(FROM_HERE, user_share());
300 EXPECT_TRUE(trans.GetWrappedTrans());
303 WriteTransaction trans(FROM_HERE, user_share());
304 EXPECT_TRUE(trans.GetWrappedTrans());
307 // No entries but root should exist
308 ReadTransaction trans(FROM_HERE, user_share());
309 ReadNode node(&trans);
310 // Metahandle 1 can be root, sanity check 2
311 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByIdLookup(2));
315 TEST_F(SyncApiTest, BasicTagWrite) {
317 ReadTransaction trans(FROM_HERE, user_share());
318 ReadNode root_node(&trans);
319 root_node.InitByRootLookup();
320 EXPECT_EQ(kInvalidId, root_node.GetFirstChildId());
323 ignore_result(MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag"));
326 ReadTransaction trans(FROM_HERE, user_share());
327 ReadNode node(&trans);
328 EXPECT_EQ(BaseNode::INIT_OK,
329 node.InitByClientTagLookup(BOOKMARKS, "testtag"));
330 EXPECT_NE(0, node.GetId());
332 ReadNode root_node(&trans);
333 root_node.InitByRootLookup();
334 EXPECT_EQ(node.GetId(), root_node.GetFirstChildId());
338 TEST_F(SyncApiTest, BasicTagWriteWithImplicitParent) {
339 int64 type_root = MakeTypeRoot(user_share(), PREFERENCES);
342 ReadTransaction trans(FROM_HERE, user_share());
343 ReadNode type_root_node(&trans);
344 EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root));
345 EXPECT_EQ(kInvalidId, type_root_node.GetFirstChildId());
348 ignore_result(MakeNode(user_share(), PREFERENCES, "testtag"));
351 ReadTransaction trans(FROM_HERE, user_share());
352 ReadNode node(&trans);
353 EXPECT_EQ(BaseNode::INIT_OK,
354 node.InitByClientTagLookup(PREFERENCES, "testtag"));
355 EXPECT_EQ(kInvalidId, node.GetParentId());
357 ReadNode type_root_node(&trans);
358 EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root));
359 EXPECT_EQ(node.GetId(), type_root_node.GetFirstChildId());
363 TEST_F(SyncApiTest, ModelTypesSiloed) {
365 WriteTransaction trans(FROM_HERE, user_share());
366 ReadNode root_node(&trans);
367 root_node.InitByRootLookup();
368 EXPECT_EQ(root_node.GetFirstChildId(), 0);
371 ignore_result(MakeNodeWithRoot(user_share(), BOOKMARKS, "collideme"));
372 ignore_result(MakeNodeWithRoot(user_share(), PREFERENCES, "collideme"));
373 ignore_result(MakeNodeWithRoot(user_share(), AUTOFILL, "collideme"));
376 ReadTransaction trans(FROM_HERE, user_share());
378 ReadNode bookmarknode(&trans);
379 EXPECT_EQ(BaseNode::INIT_OK,
380 bookmarknode.InitByClientTagLookup(BOOKMARKS,
381 "collideme"));
383 ReadNode prefnode(&trans);
384 EXPECT_EQ(BaseNode::INIT_OK,
385 prefnode.InitByClientTagLookup(PREFERENCES,
386 "collideme"));
388 ReadNode autofillnode(&trans);
389 EXPECT_EQ(BaseNode::INIT_OK,
390 autofillnode.InitByClientTagLookup(AUTOFILL,
391 "collideme"));
393 EXPECT_NE(bookmarknode.GetId(), prefnode.GetId());
394 EXPECT_NE(autofillnode.GetId(), prefnode.GetId());
395 EXPECT_NE(bookmarknode.GetId(), autofillnode.GetId());
399 TEST_F(SyncApiTest, ReadMissingTagsFails) {
401 ReadTransaction trans(FROM_HERE, user_share());
402 ReadNode node(&trans);
403 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
404 node.InitByClientTagLookup(BOOKMARKS,
405 "testtag"));
408 WriteTransaction trans(FROM_HERE, user_share());
409 WriteNode node(&trans);
410 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
411 node.InitByClientTagLookup(BOOKMARKS,
412 "testtag"));
416 // TODO(chron): Hook this all up to the server and write full integration tests
417 // for update->undelete behavior.
418 TEST_F(SyncApiTest, TestDeleteBehavior) {
419 int64 node_id;
420 int64 folder_id;
421 std::string test_title("test1");
424 WriteTransaction trans(FROM_HERE, user_share());
425 ReadNode root_node(&trans);
426 root_node.InitByRootLookup();
428 // we'll use this spare folder later
429 WriteNode folder_node(&trans);
430 EXPECT_TRUE(folder_node.InitBookmarkByCreation(root_node, NULL));
431 folder_id = folder_node.GetId();
433 WriteNode wnode(&trans);
434 WriteNode::InitUniqueByCreationResult result =
435 wnode.InitUniqueByCreation(BOOKMARKS, root_node, "testtag");
436 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
437 wnode.SetIsFolder(false);
438 wnode.SetTitle(test_title);
440 node_id = wnode.GetId();
443 // Ensure we can delete something with a tag.
445 WriteTransaction trans(FROM_HERE, user_share());
446 WriteNode wnode(&trans);
447 EXPECT_EQ(BaseNode::INIT_OK,
448 wnode.InitByClientTagLookup(BOOKMARKS,
449 "testtag"));
450 EXPECT_FALSE(wnode.GetIsFolder());
451 EXPECT_EQ(wnode.GetTitle(), test_title);
453 wnode.Tombstone();
456 // Lookup of a node which was deleted should return failure,
457 // but have found some data about the node.
459 ReadTransaction trans(FROM_HERE, user_share());
460 ReadNode node(&trans);
461 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL,
462 node.InitByClientTagLookup(BOOKMARKS,
463 "testtag"));
464 // Note that for proper function of this API this doesn't need to be
465 // filled, we're checking just to make sure the DB worked in this test.
466 EXPECT_EQ(node.GetTitle(), test_title);
470 WriteTransaction trans(FROM_HERE, user_share());
471 ReadNode folder_node(&trans);
472 EXPECT_EQ(BaseNode::INIT_OK, folder_node.InitByIdLookup(folder_id));
474 WriteNode wnode(&trans);
475 // This will undelete the tag.
476 WriteNode::InitUniqueByCreationResult result =
477 wnode.InitUniqueByCreation(BOOKMARKS, folder_node, "testtag");
478 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
479 EXPECT_EQ(wnode.GetIsFolder(), false);
480 EXPECT_EQ(wnode.GetParentId(), folder_node.GetId());
481 EXPECT_EQ(wnode.GetId(), node_id);
482 EXPECT_NE(wnode.GetTitle(), test_title); // Title should be cleared
483 wnode.SetTitle(test_title);
486 // Now look up should work.
488 ReadTransaction trans(FROM_HERE, user_share());
489 ReadNode node(&trans);
490 EXPECT_EQ(BaseNode::INIT_OK,
491 node.InitByClientTagLookup(BOOKMARKS,
492 "testtag"));
493 EXPECT_EQ(node.GetTitle(), test_title);
494 EXPECT_EQ(node.GetModelType(), BOOKMARKS);
498 TEST_F(SyncApiTest, WriteAndReadPassword) {
499 KeyParams params = {"localhost", "username", "passphrase"};
501 ReadTransaction trans(FROM_HERE, user_share());
502 trans.GetCryptographer()->AddKey(params);
505 WriteTransaction trans(FROM_HERE, user_share());
506 ReadNode root_node(&trans);
507 root_node.InitByRootLookup();
509 WriteNode password_node(&trans);
510 WriteNode::InitUniqueByCreationResult result =
511 password_node.InitUniqueByCreation(PASSWORDS,
512 root_node, "foo");
513 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
514 sync_pb::PasswordSpecificsData data;
515 data.set_password_value("secret");
516 password_node.SetPasswordSpecifics(data);
519 ReadTransaction trans(FROM_HERE, user_share());
521 ReadNode password_node(&trans);
522 EXPECT_EQ(BaseNode::INIT_OK,
523 password_node.InitByClientTagLookup(PASSWORDS, "foo"));
524 const sync_pb::PasswordSpecificsData& data =
525 password_node.GetPasswordSpecifics();
526 EXPECT_EQ("secret", data.password_value());
530 TEST_F(SyncApiTest, WriteEncryptedTitle) {
531 KeyParams params = {"localhost", "username", "passphrase"};
533 ReadTransaction trans(FROM_HERE, user_share());
534 trans.GetCryptographer()->AddKey(params);
536 encryption_handler()->EnableEncryptEverything();
537 int bookmark_id;
539 WriteTransaction trans(FROM_HERE, user_share());
540 ReadNode root_node(&trans);
541 root_node.InitByRootLookup();
543 WriteNode bookmark_node(&trans);
544 ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, NULL));
545 bookmark_id = bookmark_node.GetId();
546 bookmark_node.SetTitle("foo");
548 WriteNode pref_node(&trans);
549 WriteNode::InitUniqueByCreationResult result =
550 pref_node.InitUniqueByCreation(PREFERENCES, root_node, "bar");
551 ASSERT_EQ(WriteNode::INIT_SUCCESS, result);
552 pref_node.SetTitle("bar");
555 ReadTransaction trans(FROM_HERE, user_share());
557 ReadNode bookmark_node(&trans);
558 ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id));
559 EXPECT_EQ("foo", bookmark_node.GetTitle());
560 EXPECT_EQ(kEncryptedString,
561 bookmark_node.GetEntry()->GetNonUniqueName());
563 ReadNode pref_node(&trans);
564 ASSERT_EQ(BaseNode::INIT_OK,
565 pref_node.InitByClientTagLookup(PREFERENCES,
566 "bar"));
567 EXPECT_EQ(kEncryptedString, pref_node.GetTitle());
571 // Non-unique name should not be empty. For bookmarks non-unique name is copied
572 // from bookmark title. This test verifies that setting bookmark title to ""
573 // results in single space title and non-unique name in internal representation.
574 // GetTitle should still return empty string.
575 TEST_F(SyncApiTest, WriteEmptyBookmarkTitle) {
576 int bookmark_id;
578 WriteTransaction trans(FROM_HERE, user_share());
579 ReadNode root_node(&trans);
580 root_node.InitByRootLookup();
582 WriteNode bookmark_node(&trans);
583 ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, NULL));
584 bookmark_id = bookmark_node.GetId();
585 bookmark_node.SetTitle("");
588 ReadTransaction trans(FROM_HERE, user_share());
590 ReadNode bookmark_node(&trans);
591 ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id));
592 EXPECT_EQ("", bookmark_node.GetTitle());
593 EXPECT_EQ(" ", bookmark_node.GetEntry()->GetSpecifics().bookmark().title());
594 EXPECT_EQ(" ", bookmark_node.GetEntry()->GetNonUniqueName());
598 TEST_F(SyncApiTest, BaseNodeSetSpecifics) {
599 int64 child_id = MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag");
600 WriteTransaction trans(FROM_HERE, user_share());
601 WriteNode node(&trans);
602 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
604 sync_pb::EntitySpecifics entity_specifics;
605 entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
607 EXPECT_NE(entity_specifics.SerializeAsString(),
608 node.GetEntitySpecifics().SerializeAsString());
609 node.SetEntitySpecifics(entity_specifics);
610 EXPECT_EQ(entity_specifics.SerializeAsString(),
611 node.GetEntitySpecifics().SerializeAsString());
614 TEST_F(SyncApiTest, BaseNodeSetSpecificsPreservesUnknownFields) {
615 int64 child_id = MakeNodeWithRoot(user_share(), BOOKMARKS, "testtag");
616 WriteTransaction trans(FROM_HERE, user_share());
617 WriteNode node(&trans);
618 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
619 EXPECT_TRUE(node.GetEntitySpecifics().unknown_fields().empty());
621 sync_pb::EntitySpecifics entity_specifics;
622 entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
623 entity_specifics.mutable_unknown_fields()->AddFixed32(5, 100);
624 node.SetEntitySpecifics(entity_specifics);
625 EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
627 entity_specifics.mutable_unknown_fields()->Clear();
628 node.SetEntitySpecifics(entity_specifics);
629 EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
632 TEST_F(SyncApiTest, EmptyTags) {
633 WriteTransaction trans(FROM_HERE, user_share());
634 ReadNode root_node(&trans);
635 root_node.InitByRootLookup();
636 WriteNode node(&trans);
637 std::string empty_tag;
638 WriteNode::InitUniqueByCreationResult result =
639 node.InitUniqueByCreation(TYPED_URLS, root_node, empty_tag);
640 EXPECT_NE(WriteNode::INIT_SUCCESS, result);
641 EXPECT_EQ(BaseNode::INIT_FAILED_PRECONDITION,
642 node.InitByClientTagLookup(TYPED_URLS, empty_tag));
645 // Test counting nodes when the type's root node has no children.
646 TEST_F(SyncApiTest, GetTotalNodeCountEmpty) {
647 int64 type_root = MakeTypeRoot(user_share(), BOOKMARKS);
649 ReadTransaction trans(FROM_HERE, user_share());
650 ReadNode type_root_node(&trans);
651 EXPECT_EQ(BaseNode::INIT_OK,
652 type_root_node.InitByIdLookup(type_root));
653 EXPECT_EQ(1, type_root_node.GetTotalNodeCount());
657 // Test counting nodes when there is one child beneath the type's root.
658 TEST_F(SyncApiTest, GetTotalNodeCountOneChild) {
659 int64 type_root = MakeTypeRoot(user_share(), BOOKMARKS);
660 int64 parent = MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL);
662 ReadTransaction trans(FROM_HERE, user_share());
663 ReadNode type_root_node(&trans);
664 EXPECT_EQ(BaseNode::INIT_OK,
665 type_root_node.InitByIdLookup(type_root));
666 EXPECT_EQ(2, type_root_node.GetTotalNodeCount());
667 ReadNode parent_node(&trans);
668 EXPECT_EQ(BaseNode::INIT_OK,
669 parent_node.InitByIdLookup(parent));
670 EXPECT_EQ(1, parent_node.GetTotalNodeCount());
674 // Test counting nodes when there are multiple children beneath the type root,
675 // and one of those children has children of its own.
676 TEST_F(SyncApiTest, GetTotalNodeCountMultipleChildren) {
677 int64 type_root = MakeTypeRoot(user_share(), BOOKMARKS);
678 int64 parent = MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL);
679 ignore_result(MakeFolderWithParent(user_share(), BOOKMARKS, type_root, NULL));
680 int64 child1 = MakeFolderWithParent(user_share(), BOOKMARKS, parent, NULL);
681 ignore_result(MakeBookmarkWithParent(user_share(), parent, NULL));
682 ignore_result(MakeBookmarkWithParent(user_share(), child1, NULL));
685 ReadTransaction trans(FROM_HERE, user_share());
686 ReadNode type_root_node(&trans);
687 EXPECT_EQ(BaseNode::INIT_OK,
688 type_root_node.InitByIdLookup(type_root));
689 EXPECT_EQ(6, type_root_node.GetTotalNodeCount());
690 ReadNode node(&trans);
691 EXPECT_EQ(BaseNode::INIT_OK,
692 node.InitByIdLookup(parent));
693 EXPECT_EQ(4, node.GetTotalNodeCount());
697 // Verify that Directory keeps track of which attachments are referenced by
698 // which entries.
699 TEST_F(SyncApiTest, AttachmentLinking) {
700 // Add an entry with an attachment.
701 std::string tag1("some tag");
702 syncer::AttachmentId attachment_id(syncer::AttachmentId::Create(0, 0));
703 sync_pb::AttachmentMetadata attachment_metadata;
704 sync_pb::AttachmentMetadataRecord* record = attachment_metadata.add_record();
705 *record->mutable_id() = attachment_id.GetProto();
706 ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
707 CreateEntryWithAttachmentMetadata(PREFERENCES, tag1, attachment_metadata);
709 // See that the directory knows it's linked.
710 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
712 // Add a second entry referencing the same attachment.
713 std::string tag2("some other tag");
714 CreateEntryWithAttachmentMetadata(PREFERENCES, tag2, attachment_metadata);
716 // See that the directory knows it's still linked.
717 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
719 // Tombstone the first entry.
720 ReplaceWithTombstone(syncer::PREFERENCES, tag1);
722 // See that the attachment is still considered linked because the entry hasn't
723 // been purged from the Directory.
724 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
726 // Save changes and see that the entry is truly gone.
727 ASSERT_TRUE(dir()->SaveChanges());
728 ASSERT_EQ(LookupEntryByClientTag(PREFERENCES, tag1),
729 syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD);
731 // However, the attachment is still linked.
732 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
734 // Save, destroy, and recreate the directory. See that it's still linked.
735 ASSERT_TRUE(ReloadDir());
736 ASSERT_TRUE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
738 // Tombstone the second entry, save changes, see that it's truly gone.
739 ReplaceWithTombstone(syncer::PREFERENCES, tag2);
740 ASSERT_TRUE(dir()->SaveChanges());
741 ASSERT_EQ(LookupEntryByClientTag(PREFERENCES, tag2),
742 syncer::WriteNode::INIT_FAILED_ENTRY_NOT_GOOD);
744 // Finally, the attachment is no longer linked.
745 ASSERT_FALSE(dir()->IsAttachmentLinked(attachment_id.GetProto()));
748 namespace {
750 class TestHttpPostProviderInterface : public HttpPostProviderInterface {
751 public:
752 ~TestHttpPostProviderInterface() override {}
754 void SetExtraRequestHeaders(const char* headers) override {}
755 void SetURL(const char* url, int port) override {}
756 void SetPostPayload(const char* content_type,
757 int content_length,
758 const char* content) override {}
759 bool MakeSynchronousPost(int* error_code, int* response_code) override {
760 return false;
762 int GetResponseContentLength() const override { return 0; }
763 const char* GetResponseContent() const override { return ""; }
764 const std::string GetResponseHeaderValue(
765 const std::string& name) const override {
766 return std::string();
768 void Abort() override {}
771 class TestHttpPostProviderFactory : public HttpPostProviderFactory {
772 public:
773 ~TestHttpPostProviderFactory() override {}
774 void Init(const std::string& user_agent) override {}
775 HttpPostProviderInterface* Create() override {
776 return new TestHttpPostProviderInterface();
778 void Destroy(HttpPostProviderInterface* http) override {
779 delete static_cast<TestHttpPostProviderInterface*>(http);
783 class SyncManagerObserverMock : public SyncManager::Observer {
784 public:
785 MOCK_METHOD1(OnSyncCycleCompleted,
786 void(const SyncSessionSnapshot&)); // NOLINT
787 MOCK_METHOD4(OnInitializationComplete,
788 void(const WeakHandle<JsBackend>&,
789 const WeakHandle<DataTypeDebugInfoListener>&,
790 bool,
791 syncer::ModelTypeSet)); // NOLINT
792 MOCK_METHOD1(OnConnectionStatusChange, void(ConnectionStatus)); // NOLINT
793 MOCK_METHOD1(OnUpdatedToken, void(const std::string&)); // NOLINT
794 MOCK_METHOD1(OnActionableError, void(const SyncProtocolError&)); // NOLINT
795 MOCK_METHOD1(OnMigrationRequested, void(syncer::ModelTypeSet)); // NOLINT
796 MOCK_METHOD1(OnProtocolEvent, void(const ProtocolEvent&)); // NOLINT
799 class SyncEncryptionHandlerObserverMock
800 : public SyncEncryptionHandler::Observer {
801 public:
802 MOCK_METHOD2(OnPassphraseRequired,
803 void(PassphraseRequiredReason,
804 const sync_pb::EncryptedData&)); // NOLINT
805 MOCK_METHOD0(OnPassphraseAccepted, void()); // NOLINT
806 MOCK_METHOD2(OnBootstrapTokenUpdated,
807 void(const std::string&, BootstrapTokenType type)); // NOLINT
808 MOCK_METHOD2(OnEncryptedTypesChanged,
809 void(ModelTypeSet, bool)); // NOLINT
810 MOCK_METHOD0(OnEncryptionComplete, void()); // NOLINT
811 MOCK_METHOD1(OnCryptographerStateChanged, void(Cryptographer*)); // NOLINT
812 MOCK_METHOD2(OnPassphraseTypeChanged, void(PassphraseType,
813 base::Time)); // NOLINT
814 MOCK_METHOD1(OnLocalSetPassphraseEncryption,
815 void(const SyncEncryptionHandler::NigoriState&)); // NOLINT
818 } // namespace
820 class SyncManagerTest : public testing::Test,
821 public SyncManager::ChangeDelegate {
822 protected:
823 enum NigoriStatus {
824 DONT_WRITE_NIGORI,
825 WRITE_TO_NIGORI
828 enum EncryptionStatus {
829 UNINITIALIZED,
830 DEFAULT_ENCRYPTION,
831 FULL_ENCRYPTION
834 SyncManagerTest()
835 : sync_manager_("Test sync manager") {
836 switches_.encryption_method =
837 InternalComponentsFactory::ENCRYPTION_KEYSTORE;
840 virtual ~SyncManagerTest() {
843 // Test implementation.
844 void SetUp() {
845 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
847 extensions_activity_ = new ExtensionsActivity();
849 SyncCredentials credentials;
850 credentials.email = "foo@bar.com";
851 credentials.sync_token = "sometoken";
852 OAuth2TokenService::ScopeSet scope_set;
853 scope_set.insert(GaiaConstants::kChromeSyncOAuth2Scope);
854 credentials.scope_set = scope_set;
856 sync_manager_.AddObserver(&manager_observer_);
857 EXPECT_CALL(manager_observer_, OnInitializationComplete(_, _, _, _)).
858 WillOnce(DoAll(SaveArg<0>(&js_backend_),
859 SaveArg<2>(&initialization_succeeded_)));
861 EXPECT_FALSE(js_backend_.IsInitialized());
863 std::vector<scoped_refptr<ModelSafeWorker> > workers;
864 ModelSafeRoutingInfo routing_info;
865 GetModelSafeRoutingInfo(&routing_info);
867 // This works only because all routing info types are GROUP_PASSIVE.
868 // If we had types in other groups, we would need additional workers
869 // to support them.
870 scoped_refptr<ModelSafeWorker> worker = new FakeModelWorker(GROUP_PASSIVE);
871 workers.push_back(worker);
873 SyncManager::InitArgs args;
874 args.database_location = temp_dir_.path();
875 args.service_url = GURL("https://example.com/");
876 args.post_factory =
877 scoped_ptr<HttpPostProviderFactory>(new TestHttpPostProviderFactory());
878 args.workers = workers;
879 args.extensions_activity = extensions_activity_.get(),
880 args.change_delegate = this;
881 args.credentials = credentials;
882 args.invalidator_client_id = "fake_invalidator_client_id";
883 args.internal_components_factory.reset(GetFactory());
884 args.encryptor = &encryptor_;
885 args.unrecoverable_error_handler =
886 MakeWeakHandle(mock_unrecoverable_error_handler_.GetWeakPtr());
887 args.cancelation_signal = &cancelation_signal_;
888 sync_manager_.Init(&args);
890 sync_manager_.GetEncryptionHandler()->AddObserver(&encryption_observer_);
892 EXPECT_TRUE(js_backend_.IsInitialized());
893 EXPECT_EQ(InternalComponentsFactory::STORAGE_ON_DISK,
894 storage_used_);
896 if (initialization_succeeded_) {
897 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
898 i != routing_info.end(); ++i) {
899 type_roots_[i->first] =
900 MakeTypeRoot(sync_manager_.GetUserShare(), i->first);
904 PumpLoop();
907 void TearDown() {
908 sync_manager_.RemoveObserver(&manager_observer_);
909 sync_manager_.ShutdownOnSyncThread(STOP_SYNC);
910 PumpLoop();
913 void GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) {
914 (*out)[NIGORI] = GROUP_PASSIVE;
915 (*out)[DEVICE_INFO] = GROUP_PASSIVE;
916 (*out)[EXPERIMENTS] = GROUP_PASSIVE;
917 (*out)[BOOKMARKS] = GROUP_PASSIVE;
918 (*out)[THEMES] = GROUP_PASSIVE;
919 (*out)[SESSIONS] = GROUP_PASSIVE;
920 (*out)[PASSWORDS] = GROUP_PASSIVE;
921 (*out)[PREFERENCES] = GROUP_PASSIVE;
922 (*out)[PRIORITY_PREFERENCES] = GROUP_PASSIVE;
923 (*out)[ARTICLES] = GROUP_PASSIVE;
926 ModelTypeSet GetEnabledTypes() {
927 ModelSafeRoutingInfo routing_info;
928 GetModelSafeRoutingInfo(&routing_info);
929 return GetRoutingInfoTypes(routing_info);
932 void OnChangesApplied(
933 ModelType model_type,
934 int64 model_version,
935 const BaseTransaction* trans,
936 const ImmutableChangeRecordList& changes) override {}
938 void OnChangesComplete(ModelType model_type) override {}
940 // Helper methods.
941 bool SetUpEncryption(NigoriStatus nigori_status,
942 EncryptionStatus encryption_status) {
943 UserShare* share = sync_manager_.GetUserShare();
945 // We need to create the nigori node as if it were an applied server update.
946 int64 nigori_id = GetIdForDataType(NIGORI);
947 if (nigori_id == kInvalidId)
948 return false;
950 // Set the nigori cryptographer information.
951 if (encryption_status == FULL_ENCRYPTION)
952 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
954 WriteTransaction trans(FROM_HERE, share);
955 Cryptographer* cryptographer = trans.GetCryptographer();
956 if (!cryptographer)
957 return false;
958 if (encryption_status != UNINITIALIZED) {
959 KeyParams params = {"localhost", "dummy", "foobar"};
960 cryptographer->AddKey(params);
961 } else {
962 DCHECK_NE(nigori_status, WRITE_TO_NIGORI);
964 if (nigori_status == WRITE_TO_NIGORI) {
965 sync_pb::NigoriSpecifics nigori;
966 cryptographer->GetKeys(nigori.mutable_encryption_keybag());
967 share->directory->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes(
968 &nigori,
969 trans.GetWrappedTrans());
970 WriteNode node(&trans);
971 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(nigori_id));
972 node.SetNigoriSpecifics(nigori);
974 return cryptographer->is_ready();
977 int64 GetIdForDataType(ModelType type) {
978 if (type_roots_.count(type) == 0)
979 return 0;
980 return type_roots_[type];
983 void PumpLoop() {
984 base::RunLoop().RunUntilIdle();
987 void SetJsEventHandler(const WeakHandle<JsEventHandler>& event_handler) {
988 js_backend_.Call(FROM_HERE, &JsBackend::SetJsEventHandler,
989 event_handler);
990 PumpLoop();
993 // Looks up an entry by client tag and resets IS_UNSYNCED value to false.
994 // Returns true if entry was previously unsynced, false if IS_UNSYNCED was
995 // already false.
996 bool ResetUnsyncedEntry(ModelType type,
997 const std::string& client_tag) {
998 UserShare* share = sync_manager_.GetUserShare();
999 syncable::WriteTransaction trans(
1000 FROM_HERE, syncable::UNITTEST, share->directory.get());
1001 const std::string hash = syncable::GenerateSyncableHash(type, client_tag);
1002 syncable::MutableEntry entry(&trans, syncable::GET_BY_CLIENT_TAG,
1003 hash);
1004 EXPECT_TRUE(entry.good());
1005 if (!entry.GetIsUnsynced())
1006 return false;
1007 entry.PutIsUnsynced(false);
1008 return true;
1011 virtual InternalComponentsFactory* GetFactory() {
1012 return new TestInternalComponentsFactory(
1013 GetSwitches(), InternalComponentsFactory::STORAGE_IN_MEMORY,
1014 &storage_used_);
1017 // Returns true if we are currently encrypting all sync data. May
1018 // be called on any thread.
1019 bool EncryptEverythingEnabledForTest() {
1020 return sync_manager_.GetEncryptionHandler()->EncryptEverythingEnabled();
1023 // Gets the set of encrypted types from the cryptographer
1024 // Note: opens a transaction. May be called from any thread.
1025 ModelTypeSet GetEncryptedTypes() {
1026 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1027 return GetEncryptedTypesWithTrans(&trans);
1030 ModelTypeSet GetEncryptedTypesWithTrans(BaseTransaction* trans) {
1031 return trans->GetDirectory()->GetNigoriHandler()->
1032 GetEncryptedTypes(trans->GetWrappedTrans());
1035 void SimulateInvalidatorEnabledForTest(bool is_enabled) {
1036 DCHECK(sync_manager_.thread_checker_.CalledOnValidThread());
1037 sync_manager_.SetInvalidatorEnabled(is_enabled);
1040 void SetProgressMarkerForType(ModelType type, bool set) {
1041 if (set) {
1042 sync_pb::DataTypeProgressMarker marker;
1043 marker.set_token("token");
1044 marker.set_data_type_id(GetSpecificsFieldNumberFromModelType(type));
1045 sync_manager_.directory()->SetDownloadProgress(type, marker);
1046 } else {
1047 sync_pb::DataTypeProgressMarker marker;
1048 sync_manager_.directory()->SetDownloadProgress(type, marker);
1052 InternalComponentsFactory::Switches GetSwitches() const {
1053 return switches_;
1056 void ExpectPassphraseAcceptance() {
1057 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted());
1058 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1059 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1062 void SetImplicitPassphraseAndCheck(const std::string& passphrase) {
1063 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1064 passphrase,
1065 false);
1066 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1067 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1070 void SetCustomPassphraseAndCheck(const std::string& passphrase) {
1071 EXPECT_CALL(encryption_observer_,
1072 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1073 sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase(
1074 passphrase,
1075 true);
1076 EXPECT_EQ(CUSTOM_PASSPHRASE,
1077 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1080 bool HasUnrecoverableError() {
1081 return mock_unrecoverable_error_handler_.invocation_count() > 0;
1084 private:
1085 // Needed by |sync_manager_|.
1086 base::MessageLoop message_loop_;
1087 // Needed by |sync_manager_|.
1088 base::ScopedTempDir temp_dir_;
1089 // Sync Id's for the roots of the enabled datatypes.
1090 std::map<ModelType, int64> type_roots_;
1091 scoped_refptr<ExtensionsActivity> extensions_activity_;
1093 protected:
1094 FakeEncryptor encryptor_;
1095 SyncManagerImpl sync_manager_;
1096 CancelationSignal cancelation_signal_;
1097 WeakHandle<JsBackend> js_backend_;
1098 bool initialization_succeeded_;
1099 StrictMock<SyncManagerObserverMock> manager_observer_;
1100 StrictMock<SyncEncryptionHandlerObserverMock> encryption_observer_;
1101 InternalComponentsFactory::Switches switches_;
1102 InternalComponentsFactory::StorageOption storage_used_;
1103 MockUnrecoverableErrorHandler mock_unrecoverable_error_handler_;
1106 TEST_F(SyncManagerTest, GetAllNodesForTypeTest) {
1107 ModelSafeRoutingInfo routing_info;
1108 GetModelSafeRoutingInfo(&routing_info);
1109 sync_manager_.StartSyncingNormally(routing_info, base::Time());
1111 scoped_ptr<base::ListValue> node_list(
1112 sync_manager_.GetAllNodesForType(syncer::PREFERENCES));
1114 // Should have one node: the type root node.
1115 ASSERT_EQ(1U, node_list->GetSize());
1117 const base::DictionaryValue* first_result;
1118 ASSERT_TRUE(node_list->GetDictionary(0, &first_result));
1119 EXPECT_TRUE(first_result->HasKey("ID"));
1120 EXPECT_TRUE(first_result->HasKey("NON_UNIQUE_NAME"));
1123 TEST_F(SyncManagerTest, RefreshEncryptionReady) {
1124 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1125 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1126 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1127 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1129 sync_manager_.GetEncryptionHandler()->Init();
1130 PumpLoop();
1132 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1133 EXPECT_TRUE(encrypted_types.Has(PASSWORDS));
1134 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1137 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1138 ReadNode node(&trans);
1139 EXPECT_EQ(BaseNode::INIT_OK,
1140 node.InitByIdLookup(GetIdForDataType(NIGORI)));
1141 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1142 EXPECT_TRUE(nigori.has_encryption_keybag());
1143 Cryptographer* cryptographer = trans.GetCryptographer();
1144 EXPECT_TRUE(cryptographer->is_ready());
1145 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1149 // Attempt to refresh encryption when nigori not downloaded.
1150 TEST_F(SyncManagerTest, RefreshEncryptionNotReady) {
1151 // Don't set up encryption (no nigori node created).
1153 // Should fail. Triggers an OnPassphraseRequired because the cryptographer
1154 // is not ready.
1155 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _)).Times(1);
1156 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1157 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1158 sync_manager_.GetEncryptionHandler()->Init();
1159 PumpLoop();
1161 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1162 EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
1163 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1166 // Attempt to refresh encryption when nigori is empty.
1167 TEST_F(SyncManagerTest, RefreshEncryptionEmptyNigori) {
1168 EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI, DEFAULT_ENCRYPTION));
1169 EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(1);
1170 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1171 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1173 // Should write to nigori.
1174 sync_manager_.GetEncryptionHandler()->Init();
1175 PumpLoop();
1177 const ModelTypeSet encrypted_types = GetEncryptedTypes();
1178 EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded.
1179 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1182 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1183 ReadNode node(&trans);
1184 EXPECT_EQ(BaseNode::INIT_OK,
1185 node.InitByIdLookup(GetIdForDataType(NIGORI)));
1186 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1187 EXPECT_TRUE(nigori.has_encryption_keybag());
1188 Cryptographer* cryptographer = trans.GetCryptographer();
1189 EXPECT_TRUE(cryptographer->is_ready());
1190 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1194 TEST_F(SyncManagerTest, EncryptDataTypesWithNoData) {
1195 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1196 EXPECT_CALL(encryption_observer_,
1197 OnEncryptedTypesChanged(
1198 HasModelTypes(EncryptableUserTypes()), true));
1199 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1200 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1201 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1204 TEST_F(SyncManagerTest, EncryptDataTypesWithData) {
1205 size_t batch_size = 5;
1206 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1208 // Create some unencrypted unsynced data.
1209 int64 folder = MakeFolderWithParent(sync_manager_.GetUserShare(),
1210 BOOKMARKS,
1211 GetIdForDataType(BOOKMARKS),
1212 NULL);
1213 // First batch_size nodes are children of folder.
1214 size_t i;
1215 for (i = 0; i < batch_size; ++i) {
1216 MakeBookmarkWithParent(sync_manager_.GetUserShare(), folder, NULL);
1218 // Next batch_size nodes are a different type and on their own.
1219 for (; i < 2*batch_size; ++i) {
1220 MakeNodeWithRoot(sync_manager_.GetUserShare(), SESSIONS,
1221 base::StringPrintf("%" PRIuS "", i));
1223 // Last batch_size nodes are a third type that will not need encryption.
1224 for (; i < 3*batch_size; ++i) {
1225 MakeNodeWithRoot(sync_manager_.GetUserShare(), THEMES,
1226 base::StringPrintf("%" PRIuS "", i));
1230 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1231 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1232 SyncEncryptionHandler::SensitiveTypes()));
1233 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1234 trans.GetWrappedTrans(),
1235 BOOKMARKS,
1236 false /* not encrypted */));
1237 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1238 trans.GetWrappedTrans(),
1239 SESSIONS,
1240 false /* not encrypted */));
1241 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1242 trans.GetWrappedTrans(),
1243 THEMES,
1244 false /* not encrypted */));
1247 EXPECT_CALL(encryption_observer_,
1248 OnEncryptedTypesChanged(
1249 HasModelTypes(EncryptableUserTypes()), true));
1250 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1251 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1252 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1254 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1255 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1256 EncryptableUserTypes()));
1257 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1258 trans.GetWrappedTrans(),
1259 BOOKMARKS,
1260 true /* is encrypted */));
1261 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1262 trans.GetWrappedTrans(),
1263 SESSIONS,
1264 true /* is encrypted */));
1265 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1266 trans.GetWrappedTrans(),
1267 THEMES,
1268 true /* is encrypted */));
1271 // Trigger's a ReEncryptEverything with new passphrase.
1272 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1273 EXPECT_CALL(encryption_observer_,
1274 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1275 ExpectPassphraseAcceptance();
1276 SetCustomPassphraseAndCheck("new_passphrase");
1277 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1279 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1280 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1281 EncryptableUserTypes()));
1282 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1283 trans.GetWrappedTrans(),
1284 BOOKMARKS,
1285 true /* is encrypted */));
1286 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1287 trans.GetWrappedTrans(),
1288 SESSIONS,
1289 true /* is encrypted */));
1290 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1291 trans.GetWrappedTrans(),
1292 THEMES,
1293 true /* is encrypted */));
1295 // Calling EncryptDataTypes with an empty encrypted types should not trigger
1296 // a reencryption and should just notify immediately.
1297 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1298 EXPECT_CALL(encryption_observer_,
1299 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)).Times(0);
1300 EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()).Times(0);
1301 EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(0);
1302 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1305 // Test that when there are no pending keys and the cryptographer is not
1306 // initialized, we add a key based on the current GAIA password.
1307 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1308 TEST_F(SyncManagerTest, SetInitialGaiaPass) {
1309 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1310 EXPECT_CALL(encryption_observer_,
1311 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1312 ExpectPassphraseAcceptance();
1313 SetImplicitPassphraseAndCheck("new_passphrase");
1314 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1316 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1317 ReadNode node(&trans);
1318 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1319 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1320 Cryptographer* cryptographer = trans.GetCryptographer();
1321 EXPECT_TRUE(cryptographer->is_ready());
1322 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag()));
1326 // Test that when there are no pending keys and we have on the old GAIA
1327 // password, we update and re-encrypt everything with the new GAIA password.
1328 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1329 TEST_F(SyncManagerTest, UpdateGaiaPass) {
1330 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1331 Cryptographer verifier(&encryptor_);
1333 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1334 Cryptographer* cryptographer = trans.GetCryptographer();
1335 std::string bootstrap_token;
1336 cryptographer->GetBootstrapToken(&bootstrap_token);
1337 verifier.Bootstrap(bootstrap_token);
1339 EXPECT_CALL(encryption_observer_,
1340 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1341 ExpectPassphraseAcceptance();
1342 SetImplicitPassphraseAndCheck("new_passphrase");
1343 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1345 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1346 Cryptographer* cryptographer = trans.GetCryptographer();
1347 EXPECT_TRUE(cryptographer->is_ready());
1348 // Verify the default key has changed.
1349 sync_pb::EncryptedData encrypted;
1350 cryptographer->GetKeys(&encrypted);
1351 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1355 // Sets a new explicit passphrase. This should update the bootstrap token
1356 // and re-encrypt everything.
1357 // (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1358 TEST_F(SyncManagerTest, SetPassphraseWithPassword) {
1359 Cryptographer verifier(&encryptor_);
1360 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1362 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1363 // Store the default (soon to be old) key.
1364 Cryptographer* cryptographer = trans.GetCryptographer();
1365 std::string bootstrap_token;
1366 cryptographer->GetBootstrapToken(&bootstrap_token);
1367 verifier.Bootstrap(bootstrap_token);
1369 ReadNode root_node(&trans);
1370 root_node.InitByRootLookup();
1372 WriteNode password_node(&trans);
1373 WriteNode::InitUniqueByCreationResult result =
1374 password_node.InitUniqueByCreation(PASSWORDS,
1375 root_node, "foo");
1376 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
1377 sync_pb::PasswordSpecificsData data;
1378 data.set_password_value("secret");
1379 password_node.SetPasswordSpecifics(data);
1381 EXPECT_CALL(encryption_observer_,
1382 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1383 ExpectPassphraseAcceptance();
1384 SetCustomPassphraseAndCheck("new_passphrase");
1385 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1387 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1388 Cryptographer* cryptographer = trans.GetCryptographer();
1389 EXPECT_TRUE(cryptographer->is_ready());
1390 // Verify the default key has changed.
1391 sync_pb::EncryptedData encrypted;
1392 cryptographer->GetKeys(&encrypted);
1393 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1395 ReadNode password_node(&trans);
1396 EXPECT_EQ(BaseNode::INIT_OK,
1397 password_node.InitByClientTagLookup(PASSWORDS,
1398 "foo"));
1399 const sync_pb::PasswordSpecificsData& data =
1400 password_node.GetPasswordSpecifics();
1401 EXPECT_EQ("secret", data.password_value());
1405 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1406 // being encrypted with a new (unprovided) GAIA password, then supply the
1407 // password.
1408 // (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1409 TEST_F(SyncManagerTest, SupplyPendingGAIAPass) {
1410 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1411 Cryptographer other_cryptographer(&encryptor_);
1413 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1414 Cryptographer* cryptographer = trans.GetCryptographer();
1415 std::string bootstrap_token;
1416 cryptographer->GetBootstrapToken(&bootstrap_token);
1417 other_cryptographer.Bootstrap(bootstrap_token);
1419 // Now update the nigori to reflect the new keys, and update the
1420 // cryptographer to have pending keys.
1421 KeyParams params = {"localhost", "dummy", "passphrase2"};
1422 other_cryptographer.AddKey(params);
1423 WriteNode node(&trans);
1424 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1425 sync_pb::NigoriSpecifics nigori;
1426 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1427 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1428 EXPECT_TRUE(cryptographer->has_pending_keys());
1429 node.SetNigoriSpecifics(nigori);
1431 EXPECT_CALL(encryption_observer_,
1432 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1433 ExpectPassphraseAcceptance();
1434 sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("passphrase2");
1435 EXPECT_EQ(IMPLICIT_PASSPHRASE,
1436 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1437 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1439 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1440 Cryptographer* cryptographer = trans.GetCryptographer();
1441 EXPECT_TRUE(cryptographer->is_ready());
1442 // Verify we're encrypting with the new key.
1443 sync_pb::EncryptedData encrypted;
1444 cryptographer->GetKeys(&encrypted);
1445 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1449 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1450 // being encrypted with an old (unprovided) GAIA password. Attempt to supply
1451 // the current GAIA password and verify the bootstrap token is updated. Then
1452 // supply the old GAIA password, and verify we re-encrypt all data with the
1453 // new GAIA password.
1454 // (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1455 TEST_F(SyncManagerTest, SupplyPendingOldGAIAPass) {
1456 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1457 Cryptographer other_cryptographer(&encryptor_);
1459 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1460 Cryptographer* cryptographer = trans.GetCryptographer();
1461 std::string bootstrap_token;
1462 cryptographer->GetBootstrapToken(&bootstrap_token);
1463 other_cryptographer.Bootstrap(bootstrap_token);
1465 // Now update the nigori to reflect the new keys, and update the
1466 // cryptographer to have pending keys.
1467 KeyParams params = {"localhost", "dummy", "old_gaia"};
1468 other_cryptographer.AddKey(params);
1469 WriteNode node(&trans);
1470 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1471 sync_pb::NigoriSpecifics nigori;
1472 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1473 node.SetNigoriSpecifics(nigori);
1474 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1476 // other_cryptographer now contains all encryption keys, and is encrypting
1477 // with the newest gaia.
1478 KeyParams new_params = {"localhost", "dummy", "new_gaia"};
1479 other_cryptographer.AddKey(new_params);
1481 // The bootstrap token should have been updated. Save it to ensure it's based
1482 // on the new GAIA password.
1483 std::string bootstrap_token;
1484 EXPECT_CALL(encryption_observer_,
1485 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN))
1486 .WillOnce(SaveArg<0>(&bootstrap_token));
1487 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_,_));
1488 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1489 SetImplicitPassphraseAndCheck("new_gaia");
1490 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1491 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1493 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1494 Cryptographer* cryptographer = trans.GetCryptographer();
1495 EXPECT_TRUE(cryptographer->is_initialized());
1496 EXPECT_FALSE(cryptographer->is_ready());
1497 // Verify we're encrypting with the new key, even though we have pending
1498 // keys.
1499 sync_pb::EncryptedData encrypted;
1500 other_cryptographer.GetKeys(&encrypted);
1501 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1503 EXPECT_CALL(encryption_observer_,
1504 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1505 ExpectPassphraseAcceptance();
1506 SetImplicitPassphraseAndCheck("old_gaia");
1508 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1509 Cryptographer* cryptographer = trans.GetCryptographer();
1510 EXPECT_TRUE(cryptographer->is_ready());
1512 // Verify we're encrypting with the new key.
1513 sync_pb::EncryptedData encrypted;
1514 other_cryptographer.GetKeys(&encrypted);
1515 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1517 // Verify the saved bootstrap token is based on the new gaia password.
1518 Cryptographer temp_cryptographer(&encryptor_);
1519 temp_cryptographer.Bootstrap(bootstrap_token);
1520 EXPECT_TRUE(temp_cryptographer.CanDecrypt(encrypted));
1524 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1525 // being encrypted with an explicit (unprovided) passphrase, then supply the
1526 // passphrase.
1527 // (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1528 TEST_F(SyncManagerTest, SupplyPendingExplicitPass) {
1529 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1530 Cryptographer other_cryptographer(&encryptor_);
1532 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1533 Cryptographer* cryptographer = trans.GetCryptographer();
1534 std::string bootstrap_token;
1535 cryptographer->GetBootstrapToken(&bootstrap_token);
1536 other_cryptographer.Bootstrap(bootstrap_token);
1538 // Now update the nigori to reflect the new keys, and update the
1539 // cryptographer to have pending keys.
1540 KeyParams params = {"localhost", "dummy", "explicit"};
1541 other_cryptographer.AddKey(params);
1542 WriteNode node(&trans);
1543 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1544 sync_pb::NigoriSpecifics nigori;
1545 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1546 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1547 EXPECT_TRUE(cryptographer->has_pending_keys());
1548 nigori.set_keybag_is_frozen(true);
1549 node.SetNigoriSpecifics(nigori);
1551 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1552 EXPECT_CALL(encryption_observer_,
1553 OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _));
1554 EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _));
1555 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
1556 sync_manager_.GetEncryptionHandler()->Init();
1557 EXPECT_CALL(encryption_observer_,
1558 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1559 ExpectPassphraseAcceptance();
1560 sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("explicit");
1561 EXPECT_EQ(CUSTOM_PASSPHRASE,
1562 sync_manager_.GetEncryptionHandler()->GetPassphraseType());
1563 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1565 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1566 Cryptographer* cryptographer = trans.GetCryptographer();
1567 EXPECT_TRUE(cryptographer->is_ready());
1568 // Verify we're encrypting with the new key.
1569 sync_pb::EncryptedData encrypted;
1570 cryptographer->GetKeys(&encrypted);
1571 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1575 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1576 // being encrypted with a new (unprovided) GAIA password, then supply the
1577 // password as a user-provided password.
1578 // This is the android case 7/8.
1579 TEST_F(SyncManagerTest, SupplyPendingGAIAPassUserProvided) {
1580 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1581 Cryptographer other_cryptographer(&encryptor_);
1583 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1584 Cryptographer* cryptographer = trans.GetCryptographer();
1585 // Now update the nigori to reflect the new keys, and update the
1586 // cryptographer to have pending keys.
1587 KeyParams params = {"localhost", "dummy", "passphrase"};
1588 other_cryptographer.AddKey(params);
1589 WriteNode node(&trans);
1590 EXPECT_EQ(BaseNode::INIT_OK, node.InitTypeRoot(NIGORI));
1591 sync_pb::NigoriSpecifics nigori;
1592 other_cryptographer.GetKeys(nigori.mutable_encryption_keybag());
1593 node.SetNigoriSpecifics(nigori);
1594 cryptographer->SetPendingKeys(nigori.encryption_keybag());
1595 EXPECT_FALSE(cryptographer->is_ready());
1597 EXPECT_CALL(encryption_observer_,
1598 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1599 ExpectPassphraseAcceptance();
1600 SetImplicitPassphraseAndCheck("passphrase");
1601 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1603 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1604 Cryptographer* cryptographer = trans.GetCryptographer();
1605 EXPECT_TRUE(cryptographer->is_ready());
1609 TEST_F(SyncManagerTest, SetPassphraseWithEmptyPasswordNode) {
1610 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1611 int64 node_id = 0;
1612 std::string tag = "foo";
1614 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1615 ReadNode root_node(&trans);
1616 root_node.InitByRootLookup();
1618 WriteNode password_node(&trans);
1619 WriteNode::InitUniqueByCreationResult result =
1620 password_node.InitUniqueByCreation(PASSWORDS, root_node, tag);
1621 EXPECT_EQ(WriteNode::INIT_SUCCESS, result);
1622 node_id = password_node.GetId();
1624 EXPECT_CALL(encryption_observer_,
1625 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1626 ExpectPassphraseAcceptance();
1627 SetCustomPassphraseAndCheck("new_passphrase");
1628 EXPECT_FALSE(EncryptEverythingEnabledForTest());
1630 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1631 ReadNode password_node(&trans);
1632 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1633 password_node.InitByClientTagLookup(PASSWORDS,
1634 tag));
1637 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1638 ReadNode password_node(&trans);
1639 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1640 password_node.InitByIdLookup(node_id));
1644 // Friended by WriteNode, so can't be in an anonymouse namespace.
1645 TEST_F(SyncManagerTest, EncryptBookmarksWithLegacyData) {
1646 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1647 std::string title;
1648 SyncAPINameToServerName("Google", &title);
1649 std::string url = "http://www.google.com";
1650 std::string raw_title2 = ".."; // An invalid cosmo title.
1651 std::string title2;
1652 SyncAPINameToServerName(raw_title2, &title2);
1653 std::string url2 = "http://www.bla.com";
1655 // Create a bookmark using the legacy format.
1656 int64 node_id1 =
1657 MakeNodeWithRoot(sync_manager_.GetUserShare(), BOOKMARKS, "testtag");
1658 int64 node_id2 =
1659 MakeNodeWithRoot(sync_manager_.GetUserShare(), BOOKMARKS, "testtag2");
1661 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1662 WriteNode node(&trans);
1663 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1665 sync_pb::EntitySpecifics entity_specifics;
1666 entity_specifics.mutable_bookmark()->set_url(url);
1667 node.SetEntitySpecifics(entity_specifics);
1669 // Set the old style title.
1670 syncable::MutableEntry* node_entry = node.entry_;
1671 node_entry->PutNonUniqueName(title);
1673 WriteNode node2(&trans);
1674 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1676 sync_pb::EntitySpecifics entity_specifics2;
1677 entity_specifics2.mutable_bookmark()->set_url(url2);
1678 node2.SetEntitySpecifics(entity_specifics2);
1680 // Set the old style title.
1681 syncable::MutableEntry* node_entry2 = node2.entry_;
1682 node_entry2->PutNonUniqueName(title2);
1686 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1687 ReadNode node(&trans);
1688 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1689 EXPECT_EQ(BOOKMARKS, node.GetModelType());
1690 EXPECT_EQ(title, node.GetTitle());
1691 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1692 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1694 ReadNode node2(&trans);
1695 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1696 EXPECT_EQ(BOOKMARKS, node2.GetModelType());
1697 // We should de-canonicalize the title in GetTitle(), but the title in the
1698 // specifics should be stored in the server legal form.
1699 EXPECT_EQ(raw_title2, node2.GetTitle());
1700 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1701 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1705 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1706 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1707 trans.GetWrappedTrans(),
1708 BOOKMARKS,
1709 false /* not encrypted */));
1712 EXPECT_CALL(encryption_observer_,
1713 OnEncryptedTypesChanged(
1714 HasModelTypes(EncryptableUserTypes()), true));
1715 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1716 sync_manager_.GetEncryptionHandler()->EnableEncryptEverything();
1717 EXPECT_TRUE(EncryptEverythingEnabledForTest());
1720 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1721 EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals(
1722 EncryptableUserTypes()));
1723 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1724 trans.GetWrappedTrans(),
1725 BOOKMARKS,
1726 true /* is encrypted */));
1728 ReadNode node(&trans);
1729 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1730 EXPECT_EQ(BOOKMARKS, node.GetModelType());
1731 EXPECT_EQ(title, node.GetTitle());
1732 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1733 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1735 ReadNode node2(&trans);
1736 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1737 EXPECT_EQ(BOOKMARKS, node2.GetModelType());
1738 // We should de-canonicalize the title in GetTitle(), but the title in the
1739 // specifics should be stored in the server legal form.
1740 EXPECT_EQ(raw_title2, node2.GetTitle());
1741 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1742 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1746 // Create a bookmark and set the title/url, then verify the data was properly
1747 // set. This replicates the unique way bookmarks have of creating sync nodes.
1748 // See BookmarkChangeProcessor::PlaceSyncNode(..).
1749 TEST_F(SyncManagerTest, CreateLocalBookmark) {
1750 std::string title = "title";
1751 std::string url = "url";
1753 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1754 ReadNode bookmark_root(&trans);
1755 ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitTypeRoot(BOOKMARKS));
1756 WriteNode node(&trans);
1757 ASSERT_TRUE(node.InitBookmarkByCreation(bookmark_root, NULL));
1758 node.SetIsFolder(false);
1759 node.SetTitle(title);
1761 sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
1762 bookmark_specifics.set_url(url);
1763 node.SetBookmarkSpecifics(bookmark_specifics);
1766 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1767 ReadNode bookmark_root(&trans);
1768 ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitTypeRoot(BOOKMARKS));
1769 int64 child_id = bookmark_root.GetFirstChildId();
1771 ReadNode node(&trans);
1772 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
1773 EXPECT_FALSE(node.GetIsFolder());
1774 EXPECT_EQ(title, node.GetTitle());
1775 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1779 // Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary
1780 // changes.
1781 TEST_F(SyncManagerTest, UpdateEntryWithEncryption) {
1782 std::string client_tag = "title";
1783 sync_pb::EntitySpecifics entity_specifics;
1784 entity_specifics.mutable_bookmark()->set_url("url");
1785 entity_specifics.mutable_bookmark()->set_title("title");
1786 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
1787 syncable::GenerateSyncableHash(BOOKMARKS,
1788 client_tag),
1789 entity_specifics);
1790 // New node shouldn't start off unsynced.
1791 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1792 // Manually change to the same data. Should not set is_unsynced.
1794 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1795 WriteNode node(&trans);
1796 EXPECT_EQ(BaseNode::INIT_OK,
1797 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1798 node.SetEntitySpecifics(entity_specifics);
1800 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1802 // Encrypt the datatatype, should set is_unsynced.
1803 EXPECT_CALL(encryption_observer_,
1804 OnEncryptedTypesChanged(
1805 HasModelTypes(EncryptableUserTypes()), true));
1806 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1807 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
1809 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1810 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
1811 sync_manager_.GetEncryptionHandler()->Init();
1812 PumpLoop();
1814 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1815 ReadNode node(&trans);
1816 EXPECT_EQ(BaseNode::INIT_OK,
1817 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1818 const syncable::Entry* node_entry = node.GetEntry();
1819 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1820 EXPECT_TRUE(specifics.has_encrypted());
1821 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1822 Cryptographer* cryptographer = trans.GetCryptographer();
1823 EXPECT_TRUE(cryptographer->is_ready());
1824 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1825 specifics.encrypted()));
1827 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1829 // Set a new passphrase. Should set is_unsynced.
1830 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1831 EXPECT_CALL(encryption_observer_,
1832 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
1833 ExpectPassphraseAcceptance();
1834 SetCustomPassphraseAndCheck("new_passphrase");
1836 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1837 ReadNode node(&trans);
1838 EXPECT_EQ(BaseNode::INIT_OK,
1839 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1840 const syncable::Entry* node_entry = node.GetEntry();
1841 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1842 EXPECT_TRUE(specifics.has_encrypted());
1843 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1844 Cryptographer* cryptographer = trans.GetCryptographer();
1845 EXPECT_TRUE(cryptographer->is_ready());
1846 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1847 specifics.encrypted()));
1849 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1851 // Force a re-encrypt everything. Should not set is_unsynced.
1852 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
1853 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
1854 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
1855 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
1857 sync_manager_.GetEncryptionHandler()->Init();
1858 PumpLoop();
1861 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1862 ReadNode node(&trans);
1863 EXPECT_EQ(BaseNode::INIT_OK,
1864 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1865 const syncable::Entry* node_entry = node.GetEntry();
1866 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1867 EXPECT_TRUE(specifics.has_encrypted());
1868 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1869 Cryptographer* cryptographer = trans.GetCryptographer();
1870 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1871 specifics.encrypted()));
1873 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1875 // Manually change to the same data. Should not set is_unsynced.
1877 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1878 WriteNode node(&trans);
1879 EXPECT_EQ(BaseNode::INIT_OK,
1880 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1881 node.SetEntitySpecifics(entity_specifics);
1882 const syncable::Entry* node_entry = node.GetEntry();
1883 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1884 EXPECT_TRUE(specifics.has_encrypted());
1885 EXPECT_FALSE(node_entry->GetIsUnsynced());
1886 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1887 Cryptographer* cryptographer = trans.GetCryptographer();
1888 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1889 specifics.encrypted()));
1891 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
1893 // Manually change to different data. Should set is_unsynced.
1895 entity_specifics.mutable_bookmark()->set_url("url2");
1896 entity_specifics.mutable_bookmark()->set_title("title2");
1897 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1898 WriteNode node(&trans);
1899 EXPECT_EQ(BaseNode::INIT_OK,
1900 node.InitByClientTagLookup(BOOKMARKS, client_tag));
1901 node.SetEntitySpecifics(entity_specifics);
1902 const syncable::Entry* node_entry = node.GetEntry();
1903 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
1904 EXPECT_TRUE(specifics.has_encrypted());
1905 EXPECT_TRUE(node_entry->GetIsUnsynced());
1906 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
1907 Cryptographer* cryptographer = trans.GetCryptographer();
1908 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
1909 specifics.encrypted()));
1913 // Passwords have their own handling for encryption. Verify it does not result
1914 // in unnecessary writes via SetEntitySpecifics.
1915 TEST_F(SyncManagerTest, UpdatePasswordSetEntitySpecificsNoChange) {
1916 std::string client_tag = "title";
1917 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1918 sync_pb::EntitySpecifics entity_specifics;
1920 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1921 Cryptographer* cryptographer = trans.GetCryptographer();
1922 sync_pb::PasswordSpecificsData data;
1923 data.set_password_value("secret");
1924 cryptographer->Encrypt(
1925 data,
1926 entity_specifics.mutable_password()->
1927 mutable_encrypted());
1929 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
1930 syncable::GenerateSyncableHash(PASSWORDS,
1931 client_tag),
1932 entity_specifics);
1933 // New node shouldn't start off unsynced.
1934 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1936 // Manually change to the same data via SetEntitySpecifics. Should not set
1937 // is_unsynced.
1939 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1940 WriteNode node(&trans);
1941 EXPECT_EQ(BaseNode::INIT_OK,
1942 node.InitByClientTagLookup(PASSWORDS, client_tag));
1943 node.SetEntitySpecifics(entity_specifics);
1945 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1948 // Passwords have their own handling for encryption. Verify it does not result
1949 // in unnecessary writes via SetPasswordSpecifics.
1950 TEST_F(SyncManagerTest, UpdatePasswordSetPasswordSpecifics) {
1951 std::string client_tag = "title";
1952 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1953 sync_pb::EntitySpecifics entity_specifics;
1955 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1956 Cryptographer* cryptographer = trans.GetCryptographer();
1957 sync_pb::PasswordSpecificsData data;
1958 data.set_password_value("secret");
1959 cryptographer->Encrypt(
1960 data,
1961 entity_specifics.mutable_password()->
1962 mutable_encrypted());
1964 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
1965 syncable::GenerateSyncableHash(PASSWORDS,
1966 client_tag),
1967 entity_specifics);
1968 // New node shouldn't start off unsynced.
1969 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1971 // Manually change to the same data via SetPasswordSpecifics. Should not set
1972 // is_unsynced.
1974 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1975 WriteNode node(&trans);
1976 EXPECT_EQ(BaseNode::INIT_OK,
1977 node.InitByClientTagLookup(PASSWORDS, client_tag));
1978 node.SetPasswordSpecifics(node.GetPasswordSpecifics());
1980 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
1982 // Manually change to different data. Should set is_unsynced.
1984 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1985 WriteNode node(&trans);
1986 EXPECT_EQ(BaseNode::INIT_OK,
1987 node.InitByClientTagLookup(PASSWORDS, client_tag));
1988 Cryptographer* cryptographer = trans.GetCryptographer();
1989 sync_pb::PasswordSpecificsData data;
1990 data.set_password_value("secret2");
1991 cryptographer->Encrypt(
1992 data,
1993 entity_specifics.mutable_password()->mutable_encrypted());
1994 node.SetPasswordSpecifics(data);
1995 const syncable::Entry* node_entry = node.GetEntry();
1996 EXPECT_TRUE(node_entry->GetIsUnsynced());
2000 // Passwords have their own handling for encryption. Verify setting a new
2001 // passphrase updates the data.
2002 TEST_F(SyncManagerTest, UpdatePasswordNewPassphrase) {
2003 std::string client_tag = "title";
2004 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2005 sync_pb::EntitySpecifics entity_specifics;
2007 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2008 Cryptographer* cryptographer = trans.GetCryptographer();
2009 sync_pb::PasswordSpecificsData data;
2010 data.set_password_value("secret");
2011 cryptographer->Encrypt(
2012 data,
2013 entity_specifics.mutable_password()->mutable_encrypted());
2015 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
2016 syncable::GenerateSyncableHash(PASSWORDS,
2017 client_tag),
2018 entity_specifics);
2019 // New node shouldn't start off unsynced.
2020 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2022 // Set a new passphrase. Should set is_unsynced.
2023 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2024 EXPECT_CALL(encryption_observer_,
2025 OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN));
2026 ExpectPassphraseAcceptance();
2027 SetCustomPassphraseAndCheck("new_passphrase");
2028 EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2031 // Passwords have their own handling for encryption. Verify it does not result
2032 // in unnecessary writes via ReencryptEverything.
2033 TEST_F(SyncManagerTest, UpdatePasswordReencryptEverything) {
2034 std::string client_tag = "title";
2035 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2036 sync_pb::EntitySpecifics entity_specifics;
2038 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2039 Cryptographer* cryptographer = trans.GetCryptographer();
2040 sync_pb::PasswordSpecificsData data;
2041 data.set_password_value("secret");
2042 cryptographer->Encrypt(
2043 data,
2044 entity_specifics.mutable_password()->mutable_encrypted());
2046 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag,
2047 syncable::GenerateSyncableHash(PASSWORDS,
2048 client_tag),
2049 entity_specifics);
2050 // New node shouldn't start off unsynced.
2051 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2053 // Force a re-encrypt everything. Should not set is_unsynced.
2054 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2055 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2056 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2057 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
2058 sync_manager_.GetEncryptionHandler()->Init();
2059 PumpLoop();
2060 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag));
2063 // Test that attempting to start up with corrupted password data triggers
2064 // an unrecoverable error (rather than crashing).
2065 TEST_F(SyncManagerTest, ReencryptEverythingWithUnrecoverableErrorPasswords) {
2066 const char kClientTag[] = "client_tag";
2068 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2069 sync_pb::EntitySpecifics entity_specifics;
2071 // Create a synced bookmark with undecryptable data.
2072 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2074 Cryptographer other_cryptographer(&encryptor_);
2075 KeyParams fake_params = {"localhost", "dummy", "fake_key"};
2076 other_cryptographer.AddKey(fake_params);
2077 sync_pb::PasswordSpecificsData data;
2078 data.set_password_value("secret");
2079 other_cryptographer.Encrypt(
2080 data,
2081 entity_specifics.mutable_password()->mutable_encrypted());
2083 // Set up the real cryptographer with a different key.
2084 KeyParams real_params = {"localhost", "username", "real_key"};
2085 trans.GetCryptographer()->AddKey(real_params);
2087 MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, kClientTag,
2088 syncable::GenerateSyncableHash(PASSWORDS,
2089 kClientTag),
2090 entity_specifics);
2091 EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, kClientTag));
2093 // Force a re-encrypt everything. Should trigger an unrecoverable error due
2094 // to being unable to decrypt the data that was previously applied.
2095 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2096 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2097 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2098 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false));
2099 EXPECT_FALSE(HasUnrecoverableError());
2100 sync_manager_.GetEncryptionHandler()->Init();
2101 PumpLoop();
2102 EXPECT_TRUE(HasUnrecoverableError());
2105 // Test that attempting to start up with corrupted bookmark data triggers
2106 // an unrecoverable error (rather than crashing).
2107 TEST_F(SyncManagerTest, ReencryptEverythingWithUnrecoverableErrorBookmarks) {
2108 const char kClientTag[] = "client_tag";
2109 EXPECT_CALL(encryption_observer_,
2110 OnEncryptedTypesChanged(
2111 HasModelTypes(EncryptableUserTypes()), true));
2112 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2113 sync_pb::EntitySpecifics entity_specifics;
2115 // Create a synced bookmark with undecryptable data.
2116 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2118 Cryptographer other_cryptographer(&encryptor_);
2119 KeyParams fake_params = {"localhost", "dummy", "fake_key"};
2120 other_cryptographer.AddKey(fake_params);
2121 sync_pb::EntitySpecifics bm_specifics;
2122 bm_specifics.mutable_bookmark()->set_title("title");
2123 bm_specifics.mutable_bookmark()->set_url("url");
2124 sync_pb::EncryptedData encrypted;
2125 other_cryptographer.Encrypt(bm_specifics, &encrypted);
2126 entity_specifics.mutable_encrypted()->CopyFrom(encrypted);
2128 // Set up the real cryptographer with a different key.
2129 KeyParams real_params = {"localhost", "username", "real_key"};
2130 trans.GetCryptographer()->AddKey(real_params);
2132 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, kClientTag,
2133 syncable::GenerateSyncableHash(BOOKMARKS,
2134 kClientTag),
2135 entity_specifics);
2136 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, kClientTag));
2138 // Force a re-encrypt everything. Should trigger an unrecoverable error due
2139 // to being unable to decrypt the data that was previously applied.
2140 testing::Mock::VerifyAndClearExpectations(&encryption_observer_);
2141 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2142 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2143 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2144 EXPECT_FALSE(HasUnrecoverableError());
2145 sync_manager_.GetEncryptionHandler()->Init();
2146 PumpLoop();
2147 EXPECT_TRUE(HasUnrecoverableError());
2150 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks
2151 // when we write the same data, but does set it when we write new data.
2152 TEST_F(SyncManagerTest, SetBookmarkTitle) {
2153 std::string client_tag = "title";
2154 sync_pb::EntitySpecifics entity_specifics;
2155 entity_specifics.mutable_bookmark()->set_url("url");
2156 entity_specifics.mutable_bookmark()->set_title("title");
2157 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2158 syncable::GenerateSyncableHash(BOOKMARKS,
2159 client_tag),
2160 entity_specifics);
2161 // New node shouldn't start off unsynced.
2162 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2164 // Manually change to the same title. Should not set is_unsynced.
2166 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2167 WriteNode node(&trans);
2168 EXPECT_EQ(BaseNode::INIT_OK,
2169 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2170 node.SetTitle(client_tag);
2172 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2174 // Manually change to new title. Should set is_unsynced.
2176 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2177 WriteNode node(&trans);
2178 EXPECT_EQ(BaseNode::INIT_OK,
2179 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2180 node.SetTitle("title2");
2182 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2185 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2186 // bookmarks when we write the same data, but does set it when we write new
2187 // data.
2188 TEST_F(SyncManagerTest, SetBookmarkTitleWithEncryption) {
2189 std::string client_tag = "title";
2190 sync_pb::EntitySpecifics entity_specifics;
2191 entity_specifics.mutable_bookmark()->set_url("url");
2192 entity_specifics.mutable_bookmark()->set_title("title");
2193 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2194 syncable::GenerateSyncableHash(BOOKMARKS,
2195 client_tag),
2196 entity_specifics);
2197 // New node shouldn't start off unsynced.
2198 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2200 // Encrypt the datatatype, should set is_unsynced.
2201 EXPECT_CALL(encryption_observer_,
2202 OnEncryptedTypesChanged(
2203 HasModelTypes(EncryptableUserTypes()), true));
2204 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2205 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2206 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2207 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2208 sync_manager_.GetEncryptionHandler()->Init();
2209 PumpLoop();
2210 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2212 // Manually change to the same title. Should not set is_unsynced.
2213 // NON_UNIQUE_NAME should be kEncryptedString.
2215 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2216 WriteNode node(&trans);
2217 EXPECT_EQ(BaseNode::INIT_OK,
2218 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2219 node.SetTitle(client_tag);
2220 const syncable::Entry* node_entry = node.GetEntry();
2221 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2222 EXPECT_TRUE(specifics.has_encrypted());
2223 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2225 EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2227 // Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME
2228 // should still be kEncryptedString.
2230 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2231 WriteNode node(&trans);
2232 EXPECT_EQ(BaseNode::INIT_OK,
2233 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2234 node.SetTitle("title2");
2235 const syncable::Entry* node_entry = node.GetEntry();
2236 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2237 EXPECT_TRUE(specifics.has_encrypted());
2238 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2240 EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag));
2243 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks
2244 // when we write the same data, but does set it when we write new data.
2245 TEST_F(SyncManagerTest, SetNonBookmarkTitle) {
2246 std::string client_tag = "title";
2247 sync_pb::EntitySpecifics entity_specifics;
2248 entity_specifics.mutable_preference()->set_name("name");
2249 entity_specifics.mutable_preference()->set_value("value");
2250 MakeServerNode(sync_manager_.GetUserShare(),
2251 PREFERENCES,
2252 client_tag,
2253 syncable::GenerateSyncableHash(PREFERENCES,
2254 client_tag),
2255 entity_specifics);
2256 // New node shouldn't start off unsynced.
2257 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2259 // Manually change to the same title. Should not set is_unsynced.
2261 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2262 WriteNode node(&trans);
2263 EXPECT_EQ(BaseNode::INIT_OK,
2264 node.InitByClientTagLookup(PREFERENCES, client_tag));
2265 node.SetTitle(client_tag);
2267 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2269 // Manually change to new title. Should set is_unsynced.
2271 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2272 WriteNode node(&trans);
2273 EXPECT_EQ(BaseNode::INIT_OK,
2274 node.InitByClientTagLookup(PREFERENCES, client_tag));
2275 node.SetTitle("title2");
2277 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2280 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2281 // non-bookmarks when we write the same data or when we write new data
2282 // data (should remained kEncryptedString).
2283 TEST_F(SyncManagerTest, SetNonBookmarkTitleWithEncryption) {
2284 std::string client_tag = "title";
2285 sync_pb::EntitySpecifics entity_specifics;
2286 entity_specifics.mutable_preference()->set_name("name");
2287 entity_specifics.mutable_preference()->set_value("value");
2288 MakeServerNode(sync_manager_.GetUserShare(),
2289 PREFERENCES,
2290 client_tag,
2291 syncable::GenerateSyncableHash(PREFERENCES,
2292 client_tag),
2293 entity_specifics);
2294 // New node shouldn't start off unsynced.
2295 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2297 // Encrypt the datatatype, should set is_unsynced.
2298 EXPECT_CALL(encryption_observer_,
2299 OnEncryptedTypesChanged(
2300 HasModelTypes(EncryptableUserTypes()), true));
2301 EXPECT_CALL(encryption_observer_, OnEncryptionComplete());
2302 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2303 EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_));
2304 EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true));
2305 sync_manager_.GetEncryptionHandler()->Init();
2306 PumpLoop();
2307 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2309 // Manually change to the same title. Should not set is_unsynced.
2310 // NON_UNIQUE_NAME should be kEncryptedString.
2312 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2313 WriteNode node(&trans);
2314 EXPECT_EQ(BaseNode::INIT_OK,
2315 node.InitByClientTagLookup(PREFERENCES, client_tag));
2316 node.SetTitle(client_tag);
2317 const syncable::Entry* node_entry = node.GetEntry();
2318 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2319 EXPECT_TRUE(specifics.has_encrypted());
2320 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2322 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag));
2324 // Manually change to new title. Should not set is_unsynced because the
2325 // NON_UNIQUE_NAME should still be kEncryptedString.
2327 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2328 WriteNode node(&trans);
2329 EXPECT_EQ(BaseNode::INIT_OK,
2330 node.InitByClientTagLookup(PREFERENCES, client_tag));
2331 node.SetTitle("title2");
2332 const syncable::Entry* node_entry = node.GetEntry();
2333 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2334 EXPECT_TRUE(specifics.has_encrypted());
2335 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2336 EXPECT_FALSE(node_entry->GetIsUnsynced());
2340 // Ensure that titles are truncated to 255 bytes, and attempting to reset
2341 // them to their longer version does not set IS_UNSYNCED.
2342 TEST_F(SyncManagerTest, SetLongTitle) {
2343 const int kNumChars = 512;
2344 const std::string kClientTag = "tag";
2345 std::string title(kNumChars, '0');
2346 sync_pb::EntitySpecifics entity_specifics;
2347 entity_specifics.mutable_preference()->set_name("name");
2348 entity_specifics.mutable_preference()->set_value("value");
2349 MakeServerNode(sync_manager_.GetUserShare(),
2350 PREFERENCES,
2351 "short_title",
2352 syncable::GenerateSyncableHash(PREFERENCES,
2353 kClientTag),
2354 entity_specifics);
2355 // New node shouldn't start off unsynced.
2356 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2358 // Manually change to the long title. Should set is_unsynced.
2360 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2361 WriteNode node(&trans);
2362 EXPECT_EQ(BaseNode::INIT_OK,
2363 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2364 node.SetTitle(title);
2365 EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
2367 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2369 // Manually change to the same title. Should not set is_unsynced.
2371 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2372 WriteNode node(&trans);
2373 EXPECT_EQ(BaseNode::INIT_OK,
2374 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2375 node.SetTitle(title);
2376 EXPECT_EQ(node.GetTitle(), title.substr(0, 255));
2378 EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2380 // Manually change to new title. Should set is_unsynced.
2382 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2383 WriteNode node(&trans);
2384 EXPECT_EQ(BaseNode::INIT_OK,
2385 node.InitByClientTagLookup(PREFERENCES, kClientTag));
2386 node.SetTitle("title2");
2388 EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag));
2391 // Create an encrypted entry when the cryptographer doesn't think the type is
2392 // marked for encryption. Ensure reads/writes don't break and don't unencrypt
2393 // the data.
2394 TEST_F(SyncManagerTest, SetPreviouslyEncryptedSpecifics) {
2395 std::string client_tag = "tag";
2396 std::string url = "url";
2397 std::string url2 = "new_url";
2398 std::string title = "title";
2399 sync_pb::EntitySpecifics entity_specifics;
2400 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2402 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2403 Cryptographer* crypto = trans.GetCryptographer();
2404 sync_pb::EntitySpecifics bm_specifics;
2405 bm_specifics.mutable_bookmark()->set_title("title");
2406 bm_specifics.mutable_bookmark()->set_url("url");
2407 sync_pb::EncryptedData encrypted;
2408 crypto->Encrypt(bm_specifics, &encrypted);
2409 entity_specifics.mutable_encrypted()->CopyFrom(encrypted);
2410 AddDefaultFieldValue(BOOKMARKS, &entity_specifics);
2412 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2413 syncable::GenerateSyncableHash(BOOKMARKS,
2414 client_tag),
2415 entity_specifics);
2418 // Verify the data.
2419 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2420 ReadNode node(&trans);
2421 EXPECT_EQ(BaseNode::INIT_OK,
2422 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2423 EXPECT_EQ(title, node.GetTitle());
2424 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
2428 // Overwrite the url (which overwrites the specifics).
2429 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2430 WriteNode node(&trans);
2431 EXPECT_EQ(BaseNode::INIT_OK,
2432 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2434 sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics());
2435 bookmark_specifics.set_url(url2);
2436 node.SetBookmarkSpecifics(bookmark_specifics);
2440 // Verify it's still encrypted and it has the most recent url.
2441 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2442 ReadNode node(&trans);
2443 EXPECT_EQ(BaseNode::INIT_OK,
2444 node.InitByClientTagLookup(BOOKMARKS, client_tag));
2445 EXPECT_EQ(title, node.GetTitle());
2446 EXPECT_EQ(url2, node.GetBookmarkSpecifics().url());
2447 const syncable::Entry* node_entry = node.GetEntry();
2448 EXPECT_EQ(kEncryptedString, node_entry->GetNonUniqueName());
2449 const sync_pb::EntitySpecifics& specifics = node_entry->GetSpecifics();
2450 EXPECT_TRUE(specifics.has_encrypted());
2454 // Verify transaction version of a model type is incremented when node of
2455 // that type is updated.
2456 TEST_F(SyncManagerTest, IncrementTransactionVersion) {
2457 ModelSafeRoutingInfo routing_info;
2458 GetModelSafeRoutingInfo(&routing_info);
2461 ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
2462 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
2463 i != routing_info.end(); ++i) {
2464 // Transaction version is incremented when SyncManagerTest::SetUp()
2465 // creates a node of each type.
2466 EXPECT_EQ(1,
2467 sync_manager_.GetUserShare()->directory->
2468 GetTransactionVersion(i->first));
2472 // Create bookmark node to increment transaction version of bookmark model.
2473 std::string client_tag = "title";
2474 sync_pb::EntitySpecifics entity_specifics;
2475 entity_specifics.mutable_bookmark()->set_url("url");
2476 entity_specifics.mutable_bookmark()->set_title("title");
2477 MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag,
2478 syncable::GenerateSyncableHash(BOOKMARKS,
2479 client_tag),
2480 entity_specifics);
2483 ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare());
2484 for (ModelSafeRoutingInfo::iterator i = routing_info.begin();
2485 i != routing_info.end(); ++i) {
2486 EXPECT_EQ(i->first == BOOKMARKS ? 2 : 1,
2487 sync_manager_.GetUserShare()->directory->
2488 GetTransactionVersion(i->first));
2493 class MockSyncScheduler : public FakeSyncScheduler {
2494 public:
2495 MockSyncScheduler() : FakeSyncScheduler() {}
2496 virtual ~MockSyncScheduler() {}
2498 MOCK_METHOD2(Start, void(SyncScheduler::Mode, base::Time));
2499 MOCK_METHOD1(ScheduleConfiguration, void(const ConfigurationParams&));
2502 class ComponentsFactory : public TestInternalComponentsFactory {
2503 public:
2504 ComponentsFactory(const Switches& switches,
2505 SyncScheduler* scheduler_to_use,
2506 sessions::SyncSessionContext** session_context,
2507 InternalComponentsFactory::StorageOption* storage_used)
2508 : TestInternalComponentsFactory(
2509 switches, InternalComponentsFactory::STORAGE_IN_MEMORY, storage_used),
2510 scheduler_to_use_(scheduler_to_use),
2511 session_context_(session_context) {}
2512 ~ComponentsFactory() override {}
2514 scoped_ptr<SyncScheduler> BuildScheduler(
2515 const std::string& name,
2516 sessions::SyncSessionContext* context,
2517 CancelationSignal* stop_handle) override {
2518 *session_context_ = context;
2519 return scheduler_to_use_.Pass();
2522 private:
2523 scoped_ptr<SyncScheduler> scheduler_to_use_;
2524 sessions::SyncSessionContext** session_context_;
2527 class SyncManagerTestWithMockScheduler : public SyncManagerTest {
2528 public:
2529 SyncManagerTestWithMockScheduler() : scheduler_(NULL) {}
2530 InternalComponentsFactory* GetFactory() override {
2531 scheduler_ = new MockSyncScheduler();
2532 return new ComponentsFactory(GetSwitches(), scheduler_, &session_context_,
2533 &storage_used_);
2536 MockSyncScheduler* scheduler() { return scheduler_; }
2537 sessions::SyncSessionContext* session_context() {
2538 return session_context_;
2541 private:
2542 MockSyncScheduler* scheduler_;
2543 sessions::SyncSessionContext* session_context_;
2546 // Test that the configuration params are properly created and sent to
2547 // ScheduleConfigure. No callback should be invoked. Any disabled datatypes
2548 // should be purged.
2549 TEST_F(SyncManagerTestWithMockScheduler, BasicConfiguration) {
2550 ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
2551 ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
2552 ModelSafeRoutingInfo new_routing_info;
2553 GetModelSafeRoutingInfo(&new_routing_info);
2554 ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
2555 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2557 ConfigurationParams params;
2558 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE, _));
2559 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)).
2560 WillOnce(SaveArg<0>(&params));
2562 // Set data for all types.
2563 ModelTypeSet protocol_types = ProtocolTypes();
2564 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2565 iter.Inc()) {
2566 SetProgressMarkerForType(iter.Get(), true);
2569 CallbackCounter ready_task_counter, retry_task_counter;
2570 sync_manager_.ConfigureSyncer(
2571 reason,
2572 types_to_download,
2573 disabled_types,
2574 ModelTypeSet(),
2575 ModelTypeSet(),
2576 new_routing_info,
2577 base::Bind(&CallbackCounter::Callback,
2578 base::Unretained(&ready_task_counter)),
2579 base::Bind(&CallbackCounter::Callback,
2580 base::Unretained(&retry_task_counter)));
2581 EXPECT_EQ(0, ready_task_counter.times_called());
2582 EXPECT_EQ(0, retry_task_counter.times_called());
2583 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION,
2584 params.source);
2585 EXPECT_TRUE(types_to_download.Equals(params.types_to_download));
2586 EXPECT_EQ(new_routing_info, params.routing_info);
2588 // Verify all the disabled types were purged.
2589 EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().Equals(
2590 enabled_types));
2591 EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken(
2592 ModelTypeSet::All()).Equals(disabled_types));
2595 // Test that on a reconfiguration (configuration where the session context
2596 // already has routing info), only those recently disabled types are purged.
2597 TEST_F(SyncManagerTestWithMockScheduler, ReConfiguration) {
2598 ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION;
2599 ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES);
2600 ModelTypeSet disabled_types = ModelTypeSet(THEMES, SESSIONS);
2601 ModelSafeRoutingInfo old_routing_info;
2602 ModelSafeRoutingInfo new_routing_info;
2603 GetModelSafeRoutingInfo(&old_routing_info);
2604 new_routing_info = old_routing_info;
2605 new_routing_info.erase(THEMES);
2606 new_routing_info.erase(SESSIONS);
2607 ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info);
2609 ConfigurationParams params;
2610 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE, _));
2611 EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)).
2612 WillOnce(SaveArg<0>(&params));
2614 // Set data for all types except those recently disabled (so we can verify
2615 // only those recently disabled are purged) .
2616 ModelTypeSet protocol_types = ProtocolTypes();
2617 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2618 iter.Inc()) {
2619 if (!disabled_types.Has(iter.Get())) {
2620 SetProgressMarkerForType(iter.Get(), true);
2621 } else {
2622 SetProgressMarkerForType(iter.Get(), false);
2626 // Set the context to have the old routing info.
2627 session_context()->SetRoutingInfo(old_routing_info);
2629 CallbackCounter ready_task_counter, retry_task_counter;
2630 sync_manager_.ConfigureSyncer(
2631 reason,
2632 types_to_download,
2633 ModelTypeSet(),
2634 ModelTypeSet(),
2635 ModelTypeSet(),
2636 new_routing_info,
2637 base::Bind(&CallbackCounter::Callback,
2638 base::Unretained(&ready_task_counter)),
2639 base::Bind(&CallbackCounter::Callback,
2640 base::Unretained(&retry_task_counter)));
2641 EXPECT_EQ(0, ready_task_counter.times_called());
2642 EXPECT_EQ(0, retry_task_counter.times_called());
2643 EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION,
2644 params.source);
2645 EXPECT_TRUE(types_to_download.Equals(params.types_to_download));
2646 EXPECT_EQ(new_routing_info, params.routing_info);
2648 // Verify only the recently disabled types were purged.
2649 EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken(
2650 ProtocolTypes()).Equals(disabled_types));
2653 // Test that SyncManager::ClearServerData invokes the scheduler.
2654 TEST_F(SyncManagerTestWithMockScheduler, ClearServerData) {
2655 EXPECT_CALL(*scheduler(), Start(SyncScheduler::CLEAR_SERVER_DATA_MODE, _));
2656 CallbackCounter callback_counter;
2657 sync_manager_.ClearServerData(base::Bind(
2658 &CallbackCounter::Callback, base::Unretained(&callback_counter)));
2659 PumpLoop();
2660 EXPECT_EQ(1, callback_counter.times_called());
2663 // Test that PurgePartiallySyncedTypes purges only those types that have not
2664 // fully completed their initial download and apply.
2665 TEST_F(SyncManagerTest, PurgePartiallySyncedTypes) {
2666 ModelSafeRoutingInfo routing_info;
2667 GetModelSafeRoutingInfo(&routing_info);
2668 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2670 UserShare* share = sync_manager_.GetUserShare();
2672 // The test harness automatically initializes all types in the routing info.
2673 // Check that autofill is not among them.
2674 ASSERT_FALSE(enabled_types.Has(AUTOFILL));
2676 // Further ensure that the test harness did not create its root node.
2678 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2679 syncable::Entry autofill_root_node(&trans,
2680 syncable::GET_TYPE_ROOT,
2681 AUTOFILL);
2682 ASSERT_FALSE(autofill_root_node.good());
2685 // One more redundant check.
2686 ASSERT_FALSE(sync_manager_.InitialSyncEndedTypes().Has(AUTOFILL));
2688 // Give autofill a progress marker.
2689 sync_pb::DataTypeProgressMarker autofill_marker;
2690 autofill_marker.set_data_type_id(
2691 GetSpecificsFieldNumberFromModelType(AUTOFILL));
2692 autofill_marker.set_token("token");
2693 share->directory->SetDownloadProgress(AUTOFILL, autofill_marker);
2695 // Also add a pending autofill root node update from the server.
2696 TestEntryFactory factory_(share->directory.get());
2697 int autofill_meta = factory_.CreateUnappliedRootNode(AUTOFILL);
2699 // Preferences is an enabled type. Check that the harness initialized it.
2700 ASSERT_TRUE(enabled_types.Has(PREFERENCES));
2701 ASSERT_TRUE(sync_manager_.InitialSyncEndedTypes().Has(PREFERENCES));
2703 // Give preferencse a progress marker.
2704 sync_pb::DataTypeProgressMarker prefs_marker;
2705 prefs_marker.set_data_type_id(
2706 GetSpecificsFieldNumberFromModelType(PREFERENCES));
2707 prefs_marker.set_token("token");
2708 share->directory->SetDownloadProgress(PREFERENCES, prefs_marker);
2710 // Add a fully synced preferences node under the root.
2711 std::string pref_client_tag = "prefABC";
2712 std::string pref_hashed_tag = "hashXYZ";
2713 sync_pb::EntitySpecifics pref_specifics;
2714 AddDefaultFieldValue(PREFERENCES, &pref_specifics);
2715 int pref_meta = MakeServerNode(
2716 share, PREFERENCES, pref_client_tag, pref_hashed_tag, pref_specifics);
2718 // And now, the purge.
2719 EXPECT_TRUE(sync_manager_.PurgePartiallySyncedTypes());
2721 // Ensure that autofill lost its progress marker, but preferences did not.
2722 ModelTypeSet empty_tokens =
2723 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All());
2724 EXPECT_TRUE(empty_tokens.Has(AUTOFILL));
2725 EXPECT_FALSE(empty_tokens.Has(PREFERENCES));
2727 // Ensure that autofill lots its node, but preferences did not.
2729 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2730 syncable::Entry autofill_node(&trans, GET_BY_HANDLE, autofill_meta);
2731 syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref_meta);
2732 EXPECT_FALSE(autofill_node.good());
2733 EXPECT_TRUE(pref_node.good());
2737 // Test CleanupDisabledTypes properly purges all disabled types as specified
2738 // by the previous and current enabled params.
2739 TEST_F(SyncManagerTest, PurgeDisabledTypes) {
2740 ModelSafeRoutingInfo routing_info;
2741 GetModelSafeRoutingInfo(&routing_info);
2742 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2743 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2745 // The harness should have initialized the enabled_types for us.
2746 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2748 // Set progress markers for all types.
2749 ModelTypeSet protocol_types = ProtocolTypes();
2750 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2751 iter.Inc()) {
2752 SetProgressMarkerForType(iter.Get(), true);
2755 // Verify all the enabled types remain after cleanup, and all the disabled
2756 // types were purged.
2757 sync_manager_.PurgeDisabledTypes(disabled_types,
2758 ModelTypeSet(),
2759 ModelTypeSet());
2760 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2761 EXPECT_TRUE(disabled_types.Equals(
2762 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2764 // Disable some more types.
2765 disabled_types.Put(BOOKMARKS);
2766 disabled_types.Put(PREFERENCES);
2767 ModelTypeSet new_enabled_types =
2768 Difference(ModelTypeSet::All(), disabled_types);
2770 // Verify only the non-disabled types remain after cleanup.
2771 sync_manager_.PurgeDisabledTypes(disabled_types,
2772 ModelTypeSet(),
2773 ModelTypeSet());
2774 EXPECT_TRUE(new_enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2775 EXPECT_TRUE(disabled_types.Equals(
2776 sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All())));
2779 // Test PurgeDisabledTypes properly unapplies types by deleting their local data
2780 // and preserving their server data and progress marker.
2781 TEST_F(SyncManagerTest, PurgeUnappliedTypes) {
2782 ModelSafeRoutingInfo routing_info;
2783 GetModelSafeRoutingInfo(&routing_info);
2784 ModelTypeSet unapplied_types = ModelTypeSet(BOOKMARKS, PREFERENCES);
2785 ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info);
2786 ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types);
2788 // The harness should have initialized the enabled_types for us.
2789 EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes()));
2791 // Set progress markers for all types.
2792 ModelTypeSet protocol_types = ProtocolTypes();
2793 for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good();
2794 iter.Inc()) {
2795 SetProgressMarkerForType(iter.Get(), true);
2798 // Add the following kinds of items:
2799 // 1. Fully synced preference.
2800 // 2. Locally created preference, server unknown, unsynced
2801 // 3. Locally deleted preference, server known, unsynced
2802 // 4. Server deleted preference, locally known.
2803 // 5. Server created preference, locally unknown, unapplied.
2804 // 6. A fully synced bookmark (no unique_client_tag).
2805 UserShare* share = sync_manager_.GetUserShare();
2806 sync_pb::EntitySpecifics pref_specifics;
2807 AddDefaultFieldValue(PREFERENCES, &pref_specifics);
2808 sync_pb::EntitySpecifics bm_specifics;
2809 AddDefaultFieldValue(BOOKMARKS, &bm_specifics);
2810 int pref1_meta = MakeServerNode(
2811 share, PREFERENCES, "pref1", "hash1", pref_specifics);
2812 int64 pref2_meta = MakeNodeWithRoot(share, PREFERENCES, "pref2");
2813 int pref3_meta = MakeServerNode(
2814 share, PREFERENCES, "pref3", "hash3", pref_specifics);
2815 int pref4_meta = MakeServerNode(
2816 share, PREFERENCES, "pref4", "hash4", pref_specifics);
2817 int pref5_meta = MakeServerNode(
2818 share, PREFERENCES, "pref5", "hash5", pref_specifics);
2819 int bookmark_meta = MakeServerNode(
2820 share, BOOKMARKS, "bookmark", "", bm_specifics);
2823 syncable::WriteTransaction trans(FROM_HERE,
2824 syncable::SYNCER,
2825 share->directory.get());
2826 // Pref's 1 and 2 are already set up properly.
2827 // Locally delete pref 3.
2828 syncable::MutableEntry pref3(&trans, GET_BY_HANDLE, pref3_meta);
2829 pref3.PutIsDel(true);
2830 pref3.PutIsUnsynced(true);
2831 // Delete pref 4 at the server.
2832 syncable::MutableEntry pref4(&trans, GET_BY_HANDLE, pref4_meta);
2833 pref4.PutServerIsDel(true);
2834 pref4.PutIsUnappliedUpdate(true);
2835 pref4.PutServerVersion(2);
2836 // Pref 5 is an new unapplied update.
2837 syncable::MutableEntry pref5(&trans, GET_BY_HANDLE, pref5_meta);
2838 pref5.PutIsUnappliedUpdate(true);
2839 pref5.PutIsDel(true);
2840 pref5.PutBaseVersion(-1);
2841 // Bookmark is already set up properly
2844 // Take a snapshot to clear all the dirty bits.
2845 share->directory.get()->SaveChanges();
2847 // Now request a purge for the unapplied types.
2848 disabled_types.PutAll(unapplied_types);
2849 sync_manager_.PurgeDisabledTypes(disabled_types,
2850 ModelTypeSet(),
2851 unapplied_types);
2853 // Verify the unapplied types still have progress markers and initial sync
2854 // ended after cleanup.
2855 EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().HasAll(unapplied_types));
2856 EXPECT_TRUE(
2857 sync_manager_.GetTypesWithEmptyProgressMarkerToken(unapplied_types).
2858 Empty());
2860 // Ensure the items were unapplied as necessary.
2862 syncable::ReadTransaction trans(FROM_HERE, share->directory.get());
2863 syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref1_meta);
2864 ASSERT_TRUE(pref_node.good());
2865 EXPECT_TRUE(pref_node.GetKernelCopy().is_dirty());
2866 EXPECT_FALSE(pref_node.GetIsUnsynced());
2867 EXPECT_TRUE(pref_node.GetIsUnappliedUpdate());
2868 EXPECT_TRUE(pref_node.GetIsDel());
2869 EXPECT_GT(pref_node.GetServerVersion(), 0);
2870 EXPECT_EQ(pref_node.GetBaseVersion(), -1);
2872 // Pref 2 should just be locally deleted.
2873 syncable::Entry pref2_node(&trans, GET_BY_HANDLE, pref2_meta);
2874 ASSERT_TRUE(pref2_node.good());
2875 EXPECT_TRUE(pref2_node.GetKernelCopy().is_dirty());
2876 EXPECT_FALSE(pref2_node.GetIsUnsynced());
2877 EXPECT_TRUE(pref2_node.GetIsDel());
2878 EXPECT_FALSE(pref2_node.GetIsUnappliedUpdate());
2879 EXPECT_TRUE(pref2_node.GetIsDel());
2880 EXPECT_EQ(pref2_node.GetServerVersion(), 0);
2881 EXPECT_EQ(pref2_node.GetBaseVersion(), -1);
2883 syncable::Entry pref3_node(&trans, GET_BY_HANDLE, pref3_meta);
2884 ASSERT_TRUE(pref3_node.good());
2885 EXPECT_TRUE(pref3_node.GetKernelCopy().is_dirty());
2886 EXPECT_FALSE(pref3_node.GetIsUnsynced());
2887 EXPECT_TRUE(pref3_node.GetIsUnappliedUpdate());
2888 EXPECT_TRUE(pref3_node.GetIsDel());
2889 EXPECT_GT(pref3_node.GetServerVersion(), 0);
2890 EXPECT_EQ(pref3_node.GetBaseVersion(), -1);
2892 syncable::Entry pref4_node(&trans, GET_BY_HANDLE, pref4_meta);
2893 ASSERT_TRUE(pref4_node.good());
2894 EXPECT_TRUE(pref4_node.GetKernelCopy().is_dirty());
2895 EXPECT_FALSE(pref4_node.GetIsUnsynced());
2896 EXPECT_TRUE(pref4_node.GetIsUnappliedUpdate());
2897 EXPECT_TRUE(pref4_node.GetIsDel());
2898 EXPECT_GT(pref4_node.GetServerVersion(), 0);
2899 EXPECT_EQ(pref4_node.GetBaseVersion(), -1);
2901 // Pref 5 should remain untouched.
2902 syncable::Entry pref5_node(&trans, GET_BY_HANDLE, pref5_meta);
2903 ASSERT_TRUE(pref5_node.good());
2904 EXPECT_FALSE(pref5_node.GetKernelCopy().is_dirty());
2905 EXPECT_FALSE(pref5_node.GetIsUnsynced());
2906 EXPECT_TRUE(pref5_node.GetIsUnappliedUpdate());
2907 EXPECT_TRUE(pref5_node.GetIsDel());
2908 EXPECT_GT(pref5_node.GetServerVersion(), 0);
2909 EXPECT_EQ(pref5_node.GetBaseVersion(), -1);
2911 syncable::Entry bookmark_node(&trans, GET_BY_HANDLE, bookmark_meta);
2912 ASSERT_TRUE(bookmark_node.good());
2913 EXPECT_TRUE(bookmark_node.GetKernelCopy().is_dirty());
2914 EXPECT_FALSE(bookmark_node.GetIsUnsynced());
2915 EXPECT_TRUE(bookmark_node.GetIsUnappliedUpdate());
2916 EXPECT_TRUE(bookmark_node.GetIsDel());
2917 EXPECT_GT(bookmark_node.GetServerVersion(), 0);
2918 EXPECT_EQ(bookmark_node.GetBaseVersion(), -1);
2922 // A test harness to exercise the code that processes and passes changes from
2923 // the "SYNCER"-WriteTransaction destructor, through the SyncManager, to the
2924 // ChangeProcessor.
2925 class SyncManagerChangeProcessingTest : public SyncManagerTest {
2926 public:
2927 void OnChangesApplied(ModelType model_type,
2928 int64 model_version,
2929 const BaseTransaction* trans,
2930 const ImmutableChangeRecordList& changes) override {
2931 last_changes_ = changes;
2934 void OnChangesComplete(ModelType model_type) override {}
2936 const ImmutableChangeRecordList& GetRecentChangeList() {
2937 return last_changes_;
2940 UserShare* share() {
2941 return sync_manager_.GetUserShare();
2944 // Set some flags so our nodes reasonably approximate the real world scenario
2945 // and can get past CheckTreeInvariants.
2947 // It's never going to be truly accurate, since we're squashing update
2948 // receipt, processing and application into a single transaction.
2949 void SetNodeProperties(syncable::MutableEntry *entry) {
2950 entry->PutId(id_factory_.NewServerId());
2951 entry->PutBaseVersion(10);
2952 entry->PutServerVersion(10);
2955 // Looks for the given change in the list. Returns the index at which it was
2956 // found. Returns -1 on lookup failure.
2957 size_t FindChangeInList(int64 id, ChangeRecord::Action action) {
2958 SCOPED_TRACE(id);
2959 for (size_t i = 0; i < last_changes_.Get().size(); ++i) {
2960 if (last_changes_.Get()[i].id == id
2961 && last_changes_.Get()[i].action == action) {
2962 return i;
2965 ADD_FAILURE() << "Failed to find specified change";
2966 return static_cast<size_t>(-1);
2969 // Returns the current size of the change list.
2971 // Note that spurious changes do not necessarily indicate a problem.
2972 // Assertions on change list size can help detect problems, but it may be
2973 // necessary to reduce their strictness if the implementation changes.
2974 size_t GetChangeListSize() {
2975 return last_changes_.Get().size();
2978 void ClearChangeList() { last_changes_ = ImmutableChangeRecordList(); }
2980 protected:
2981 ImmutableChangeRecordList last_changes_;
2982 TestIdFactory id_factory_;
2985 // Test creation of a folder and a bookmark.
2986 TEST_F(SyncManagerChangeProcessingTest, AddBookmarks) {
2987 int64 type_root = GetIdForDataType(BOOKMARKS);
2988 int64 folder_id = kInvalidId;
2989 int64 child_id = kInvalidId;
2991 // Create a folder and a bookmark under it.
2993 syncable::WriteTransaction trans(
2994 FROM_HERE, syncable::SYNCER, share()->directory.get());
2995 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
2996 ASSERT_TRUE(root.good());
2998 syncable::MutableEntry folder(&trans, syncable::CREATE,
2999 BOOKMARKS, root.GetId(), "folder");
3000 ASSERT_TRUE(folder.good());
3001 SetNodeProperties(&folder);
3002 folder.PutIsDir(true);
3003 folder_id = folder.GetMetahandle();
3005 syncable::MutableEntry child(&trans, syncable::CREATE,
3006 BOOKMARKS, folder.GetId(), "child");
3007 ASSERT_TRUE(child.good());
3008 SetNodeProperties(&child);
3009 child_id = child.GetMetahandle();
3012 // The closing of the above scope will delete the transaction. Its processed
3013 // changes should be waiting for us in a member of the test harness.
3014 EXPECT_EQ(2UL, GetChangeListSize());
3016 // We don't need to check these return values here. The function will add a
3017 // non-fatal failure if these changes are not found.
3018 size_t folder_change_pos =
3019 FindChangeInList(folder_id, ChangeRecord::ACTION_ADD);
3020 size_t child_change_pos =
3021 FindChangeInList(child_id, ChangeRecord::ACTION_ADD);
3023 // Parents are delivered before children.
3024 EXPECT_LT(folder_change_pos, child_change_pos);
3027 // Test creation of a preferences (with implicit parent Id)
3028 TEST_F(SyncManagerChangeProcessingTest, AddPreferences) {
3029 int64 item1_id = kInvalidId;
3030 int64 item2_id = kInvalidId;
3032 // Create two preferences.
3034 syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER,
3035 share()->directory.get());
3037 syncable::MutableEntry item1(&trans, syncable::CREATE, PREFERENCES,
3038 "test_item_1");
3039 ASSERT_TRUE(item1.good());
3040 SetNodeProperties(&item1);
3041 item1_id = item1.GetMetahandle();
3043 // Need at least two items to ensure hitting all possible codepaths in
3044 // ChangeReorderBuffer::Traversal::ExpandToInclude.
3045 syncable::MutableEntry item2(&trans, syncable::CREATE, PREFERENCES,
3046 "test_item_2");
3047 ASSERT_TRUE(item2.good());
3048 SetNodeProperties(&item2);
3049 item2_id = item2.GetMetahandle();
3052 // The closing of the above scope will delete the transaction. Its processed
3053 // changes should be waiting for us in a member of the test harness.
3054 EXPECT_EQ(2UL, GetChangeListSize());
3056 FindChangeInList(item1_id, ChangeRecord::ACTION_ADD);
3057 FindChangeInList(item2_id, ChangeRecord::ACTION_ADD);
3060 // Test moving a bookmark into an empty folder.
3061 TEST_F(SyncManagerChangeProcessingTest, MoveBookmarkIntoEmptyFolder) {
3062 int64 type_root = GetIdForDataType(BOOKMARKS);
3063 int64 folder_b_id = kInvalidId;
3064 int64 child_id = kInvalidId;
3066 // Create two folders. Place a child under folder A.
3068 syncable::WriteTransaction trans(
3069 FROM_HERE, syncable::SYNCER, share()->directory.get());
3070 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3071 ASSERT_TRUE(root.good());
3073 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3074 BOOKMARKS, root.GetId(), "folderA");
3075 ASSERT_TRUE(folder_a.good());
3076 SetNodeProperties(&folder_a);
3077 folder_a.PutIsDir(true);
3079 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3080 BOOKMARKS, root.GetId(), "folderB");
3081 ASSERT_TRUE(folder_b.good());
3082 SetNodeProperties(&folder_b);
3083 folder_b.PutIsDir(true);
3084 folder_b_id = folder_b.GetMetahandle();
3086 syncable::MutableEntry child(&trans, syncable::CREATE,
3087 BOOKMARKS, folder_a.GetId(),
3088 "child");
3089 ASSERT_TRUE(child.good());
3090 SetNodeProperties(&child);
3091 child_id = child.GetMetahandle();
3094 // Close that transaction. The above was to setup the initial scenario. The
3095 // real test starts now.
3097 // Move the child from folder A to folder B.
3099 syncable::WriteTransaction trans(
3100 FROM_HERE, syncable::SYNCER, share()->directory.get());
3102 syncable::Entry folder_b(&trans, syncable::GET_BY_HANDLE, folder_b_id);
3103 syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
3105 child.PutParentId(folder_b.GetId());
3108 EXPECT_EQ(1UL, GetChangeListSize());
3110 // Verify that this was detected as a real change. An early version of the
3111 // UniquePosition code had a bug where moves from one folder to another were
3112 // ignored unless the moved node's UniquePosition value was also changed in
3113 // some way.
3114 FindChangeInList(child_id, ChangeRecord::ACTION_UPDATE);
3117 // Test moving a bookmark into a non-empty folder.
3118 TEST_F(SyncManagerChangeProcessingTest, MoveIntoPopulatedFolder) {
3119 int64 type_root = GetIdForDataType(BOOKMARKS);
3120 int64 child_a_id = kInvalidId;
3121 int64 child_b_id = kInvalidId;
3123 // Create two folders. Place one child each under folder A and folder B.
3125 syncable::WriteTransaction trans(
3126 FROM_HERE, syncable::SYNCER, share()->directory.get());
3127 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3128 ASSERT_TRUE(root.good());
3130 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3131 BOOKMARKS, root.GetId(), "folderA");
3132 ASSERT_TRUE(folder_a.good());
3133 SetNodeProperties(&folder_a);
3134 folder_a.PutIsDir(true);
3136 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3137 BOOKMARKS, root.GetId(), "folderB");
3138 ASSERT_TRUE(folder_b.good());
3139 SetNodeProperties(&folder_b);
3140 folder_b.PutIsDir(true);
3142 syncable::MutableEntry child_a(&trans, syncable::CREATE,
3143 BOOKMARKS, folder_a.GetId(),
3144 "childA");
3145 ASSERT_TRUE(child_a.good());
3146 SetNodeProperties(&child_a);
3147 child_a_id = child_a.GetMetahandle();
3149 syncable::MutableEntry child_b(&trans, syncable::CREATE,
3150 BOOKMARKS, folder_b.GetId(),
3151 "childB");
3152 SetNodeProperties(&child_b);
3153 child_b_id = child_b.GetMetahandle();
3156 // Close that transaction. The above was to setup the initial scenario. The
3157 // real test starts now.
3160 syncable::WriteTransaction trans(
3161 FROM_HERE, syncable::SYNCER, share()->directory.get());
3163 syncable::MutableEntry child_a(&trans, syncable::GET_BY_HANDLE, child_a_id);
3164 syncable::MutableEntry child_b(&trans, syncable::GET_BY_HANDLE, child_b_id);
3166 // Move child A from folder A to folder B and update its position.
3167 child_a.PutParentId(child_b.GetParentId());
3168 child_a.PutPredecessor(child_b.GetId());
3171 EXPECT_EQ(1UL, GetChangeListSize());
3173 // Verify that only child a is in the change list.
3174 // (This function will add a failure if the lookup fails.)
3175 FindChangeInList(child_a_id, ChangeRecord::ACTION_UPDATE);
3178 // Tests the ordering of deletion changes.
3179 TEST_F(SyncManagerChangeProcessingTest, DeletionsAndChanges) {
3180 int64 type_root = GetIdForDataType(BOOKMARKS);
3181 int64 folder_a_id = kInvalidId;
3182 int64 folder_b_id = kInvalidId;
3183 int64 child_id = kInvalidId;
3185 // Create two folders. Place a child under folder A.
3187 syncable::WriteTransaction trans(
3188 FROM_HERE, syncable::SYNCER, share()->directory.get());
3189 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3190 ASSERT_TRUE(root.good());
3192 syncable::MutableEntry folder_a(&trans, syncable::CREATE,
3193 BOOKMARKS, root.GetId(), "folderA");
3194 ASSERT_TRUE(folder_a.good());
3195 SetNodeProperties(&folder_a);
3196 folder_a.PutIsDir(true);
3197 folder_a_id = folder_a.GetMetahandle();
3199 syncable::MutableEntry folder_b(&trans, syncable::CREATE,
3200 BOOKMARKS, root.GetId(), "folderB");
3201 ASSERT_TRUE(folder_b.good());
3202 SetNodeProperties(&folder_b);
3203 folder_b.PutIsDir(true);
3204 folder_b_id = folder_b.GetMetahandle();
3206 syncable::MutableEntry child(&trans, syncable::CREATE,
3207 BOOKMARKS, folder_a.GetId(),
3208 "child");
3209 ASSERT_TRUE(child.good());
3210 SetNodeProperties(&child);
3211 child_id = child.GetMetahandle();
3214 // Close that transaction. The above was to setup the initial scenario. The
3215 // real test starts now.
3218 syncable::WriteTransaction trans(
3219 FROM_HERE, syncable::SYNCER, share()->directory.get());
3221 syncable::MutableEntry folder_a(
3222 &trans, syncable::GET_BY_HANDLE, folder_a_id);
3223 syncable::MutableEntry folder_b(
3224 &trans, syncable::GET_BY_HANDLE, folder_b_id);
3225 syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id);
3227 // Delete folder B and its child.
3228 child.PutIsDel(true);
3229 folder_b.PutIsDel(true);
3231 // Make an unrelated change to folder A.
3232 folder_a.PutNonUniqueName("NewNameA");
3235 EXPECT_EQ(3UL, GetChangeListSize());
3237 size_t folder_a_pos =
3238 FindChangeInList(folder_a_id, ChangeRecord::ACTION_UPDATE);
3239 size_t folder_b_pos =
3240 FindChangeInList(folder_b_id, ChangeRecord::ACTION_DELETE);
3241 size_t child_pos = FindChangeInList(child_id, ChangeRecord::ACTION_DELETE);
3243 // Deletes should appear before updates.
3244 EXPECT_LT(child_pos, folder_a_pos);
3245 EXPECT_LT(folder_b_pos, folder_a_pos);
3248 // See that attachment metadata changes are not filtered out by
3249 // SyncManagerImpl::VisiblePropertiesDiffer.
3250 TEST_F(SyncManagerChangeProcessingTest, AttachmentMetadataOnlyChanges) {
3251 // Create an article with no attachments. See that a change is generated.
3252 int64 article_id = kInvalidId;
3254 syncable::WriteTransaction trans(
3255 FROM_HERE, syncable::SYNCER, share()->directory.get());
3256 int64 type_root = GetIdForDataType(ARTICLES);
3257 syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root);
3258 ASSERT_TRUE(root.good());
3259 syncable::MutableEntry article(
3260 &trans, syncable::CREATE, ARTICLES, root.GetId(), "article");
3261 ASSERT_TRUE(article.good());
3262 SetNodeProperties(&article);
3263 article_id = article.GetMetahandle();
3265 ASSERT_EQ(1UL, GetChangeListSize());
3266 FindChangeInList(article_id, ChangeRecord::ACTION_ADD);
3267 ClearChangeList();
3269 // Modify the article by adding one attachment. Don't touch anything else.
3270 // See that a change is generated.
3272 syncable::WriteTransaction trans(
3273 FROM_HERE, syncable::SYNCER, share()->directory.get());
3274 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3275 sync_pb::AttachmentMetadata metadata;
3276 *metadata.add_record()->mutable_id() = CreateAttachmentIdProto(0, 0);
3277 article.PutAttachmentMetadata(metadata);
3279 ASSERT_EQ(1UL, GetChangeListSize());
3280 FindChangeInList(article_id, ChangeRecord::ACTION_UPDATE);
3281 ClearChangeList();
3283 // Modify the article by replacing its attachment with a different one. See
3284 // that a change is generated.
3286 syncable::WriteTransaction trans(
3287 FROM_HERE, syncable::SYNCER, share()->directory.get());
3288 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3289 sync_pb::AttachmentMetadata metadata = article.GetAttachmentMetadata();
3290 *metadata.add_record()->mutable_id() = CreateAttachmentIdProto(0, 0);
3291 article.PutAttachmentMetadata(metadata);
3293 ASSERT_EQ(1UL, GetChangeListSize());
3294 FindChangeInList(article_id, ChangeRecord::ACTION_UPDATE);
3295 ClearChangeList();
3297 // Modify the article by replacing its attachment metadata with the same
3298 // attachment metadata. No change should be generated.
3300 syncable::WriteTransaction trans(
3301 FROM_HERE, syncable::SYNCER, share()->directory.get());
3302 syncable::MutableEntry article(&trans, syncable::GET_BY_HANDLE, article_id);
3303 article.PutAttachmentMetadata(article.GetAttachmentMetadata());
3305 ASSERT_EQ(0UL, GetChangeListSize());
3308 // During initialization SyncManagerImpl loads sqlite database. If it fails to
3309 // do so it should fail initialization. This test verifies this behavior.
3310 // Test reuses SyncManagerImpl initialization from SyncManagerTest but overrides
3311 // InternalComponentsFactory to return DirectoryBackingStore that always fails
3312 // to load.
3313 class SyncManagerInitInvalidStorageTest : public SyncManagerTest {
3314 public:
3315 SyncManagerInitInvalidStorageTest() {
3318 InternalComponentsFactory* GetFactory() override {
3319 return new TestInternalComponentsFactory(
3320 GetSwitches(), InternalComponentsFactory::STORAGE_INVALID,
3321 &storage_used_);
3325 // SyncManagerInitInvalidStorageTest::GetFactory will return
3326 // DirectoryBackingStore that ensures that SyncManagerImpl::OpenDirectory fails.
3327 // SyncManagerImpl initialization is done in SyncManagerTest::SetUp. This test's
3328 // task is to ensure that SyncManagerImpl reported initialization failure in
3329 // OnInitializationComplete callback.
3330 TEST_F(SyncManagerInitInvalidStorageTest, FailToOpenDatabase) {
3331 EXPECT_FALSE(initialization_succeeded_);
3334 } // namespace syncer