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

Side by Side Diff: sync/internal_api/sync_manager_impl_unittest.cc

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

Powered by Google App Engine
This is Rietveld 408576698