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

Side by Side Diff: chrome/browser/sync/internal_api/syncapi_unittest.cc

Issue 10147003: [Sync] Move 'syncapi_core' and 'sync_unit_tests' targets to sync/ (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Fix Win update errors Created 8 years, 8 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 | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
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 <cstddef>
10 #include <map>
11
12 #include "base/basictypes.h"
13 #include "base/callback.h"
14 #include "base/compiler_specific.h"
15 #include "base/format_macros.h"
16 #include "base/location.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/message_loop.h"
19 #include "base/message_loop_proxy.h"
20 #include "base/scoped_temp_dir.h"
21 #include "base/string_number_conversions.h"
22 #include "base/stringprintf.h"
23 #include "base/test/values_test_util.h"
24 #include "base/utf_string_conversions.h"
25 #include "base/values.h"
26 #include "chrome/browser/sync/internal_api/change_record.h"
27 #include "chrome/browser/sync/internal_api/http_post_provider_factory.h"
28 #include "chrome/browser/sync/internal_api/http_post_provider_interface.h"
29 #include "chrome/browser/sync/internal_api/read_node.h"
30 #include "chrome/browser/sync/internal_api/read_transaction.h"
31 #include "chrome/browser/sync/internal_api/sync_manager.h"
32 #include "chrome/browser/sync/internal_api/syncapi_internal.h"
33 #include "chrome/browser/sync/internal_api/write_node.h"
34 #include "chrome/browser/sync/internal_api/write_transaction.h"
35 #include "chrome/browser/sync/test/engine/test_user_share.h"
36 #include "sync/engine/model_safe_worker.h"
37 #include "sync/engine/nigori_util.h"
38 #include "sync/engine/polling_constants.h"
39 #include "sync/js/js_arg_list.h"
40 #include "sync/js/js_backend.h"
41 #include "sync/js/js_event_handler.h"
42 #include "sync/js/js_reply_handler.h"
43 #include "sync/js/js_test_util.h"
44 #include "sync/notifier/sync_notifier.h"
45 #include "sync/notifier/sync_notifier_observer.h"
46 #include "sync/protocol/bookmark_specifics.pb.h"
47 #include "sync/protocol/encryption.pb.h"
48 #include "sync/protocol/extension_specifics.pb.h"
49 #include "sync/protocol/password_specifics.pb.h"
50 #include "sync/protocol/preference_specifics.pb.h"
51 #include "sync/protocol/proto_value_conversions.h"
52 #include "sync/protocol/sync.pb.h"
53 #include "sync/sessions/sync_session.h"
54 #include "sync/syncable/model_type_test_util.h"
55 #include "sync/syncable/syncable.h"
56 #include "sync/syncable/syncable_id.h"
57 #include "sync/test/fake_encryptor.h"
58 #include "sync/test/fake_extensions_activity_monitor.h"
59 #include "sync/util/cryptographer.h"
60 #include "sync/util/extensions_activity_monitor.h"
61 #include "sync/util/test_unrecoverable_error_handler.h"
62 #include "sync/util/time.h"
63 #include "testing/gmock/include/gmock/gmock.h"
64 #include "testing/gtest/include/gtest/gtest.h"
65
66 using base::ExpectDictStringValue;
67 using browser_sync::Cryptographer;
68 using browser_sync::FakeEncryptor;
69 using browser_sync::FakeExtensionsActivityMonitor;
70 using browser_sync::HasArgsAsList;
71 using browser_sync::HasDetailsAsDictionary;
72 using browser_sync::KeyParams;
73 using browser_sync::kNigoriTag;
74 using browser_sync::JsArgList;
75 using browser_sync::JsBackend;
76 using browser_sync::JsEventHandler;
77 using browser_sync::JsReplyHandler;
78 using browser_sync::MockJsEventHandler;
79 using browser_sync::MockJsReplyHandler;
80 using browser_sync::ModelSafeRoutingInfo;
81 using browser_sync::ModelSafeWorker;
82 using browser_sync::ModelSafeWorkerRegistrar;
83 using browser_sync::sessions::SyncSessionSnapshot;
84 using browser_sync::TestUnrecoverableErrorHandler;
85 using browser_sync::WeakHandle;
86 using syncable::IS_DEL;
87 using syncable::IS_UNSYNCED;
88 using syncable::kEncryptedString;
89 using syncable::ModelTypeSet;
90 using syncable::ModelType;
91 using syncable::NON_UNIQUE_NAME;
92 using syncable::SPECIFICS;
93 using testing::_;
94 using testing::AnyNumber;
95 using testing::AtLeast;
96 using testing::InSequence;
97 using testing::Invoke;
98 using testing::SaveArg;
99 using testing::StrictMock;
100
101 namespace sync_api {
102
103 namespace {
104
105 const char kTestChromeVersion[] = "test chrome version";
106
107 void DoNothing() {}
108
109 void ExpectInt64Value(int64 expected_value,
110 const DictionaryValue& value, const std::string& key) {
111 std::string int64_str;
112 EXPECT_TRUE(value.GetString(key, &int64_str));
113 int64 val = 0;
114 EXPECT_TRUE(base::StringToInt64(int64_str, &val));
115 EXPECT_EQ(expected_value, val);
116 }
117
118 void ExpectTimeValue(const base::Time& expected_value,
119 const DictionaryValue& value, const std::string& key) {
120 std::string time_str;
121 EXPECT_TRUE(value.GetString(key, &time_str));
122 EXPECT_EQ(browser_sync::GetTimeDebugString(expected_value), time_str);
123 }
124
125 // Makes a non-folder child of the root node. Returns the id of the
126 // newly-created node.
127 int64 MakeNode(UserShare* share,
128 ModelType model_type,
129 const std::string& client_tag) {
130 WriteTransaction trans(FROM_HERE, share);
131 ReadNode root_node(&trans);
132 root_node.InitByRootLookup();
133 WriteNode node(&trans);
134 EXPECT_TRUE(node.InitUniqueByCreation(model_type, root_node, client_tag));
135 node.SetIsFolder(false);
136 return node.GetId();
137 }
138
139 // Makes a non-folder child of a non-root node. Returns the id of the
140 // newly-created node.
141 int64 MakeNodeWithParent(UserShare* share,
142 ModelType model_type,
143 const std::string& client_tag,
144 int64 parent_id) {
145 WriteTransaction trans(FROM_HERE, share);
146 ReadNode parent_node(&trans);
147 EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
148 WriteNode node(&trans);
149 EXPECT_TRUE(node.InitUniqueByCreation(model_type, parent_node, client_tag));
150 node.SetIsFolder(false);
151 return node.GetId();
152 }
153
154 // Makes a folder child of a non-root node. Returns the id of the
155 // newly-created node.
156 int64 MakeFolderWithParent(UserShare* share,
157 ModelType model_type,
158 int64 parent_id,
159 BaseNode* predecessor) {
160 WriteTransaction trans(FROM_HERE, share);
161 ReadNode parent_node(&trans);
162 EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id));
163 WriteNode node(&trans);
164 EXPECT_TRUE(node.InitByCreation(model_type, parent_node, predecessor));
165 node.SetIsFolder(true);
166 return node.GetId();
167 }
168
169 // Creates the "synced" root node for a particular datatype. We use the syncable
170 // methods here so that the syncer treats these nodes as if they were already
171 // received from the server.
172 int64 MakeServerNodeForType(UserShare* share,
173 ModelType model_type) {
174 sync_pb::EntitySpecifics specifics;
175 syncable::AddDefaultFieldValue(model_type, &specifics);
176 syncable::WriteTransaction trans(
177 FROM_HERE, syncable::UNITTEST, share->directory.get());
178 // Attempt to lookup by nigori tag.
179 std::string type_tag = syncable::ModelTypeToRootTag(model_type);
180 syncable::Id node_id = syncable::Id::CreateFromServerId(type_tag);
181 syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
182 node_id);
183 EXPECT_TRUE(entry.good());
184 entry.Put(syncable::BASE_VERSION, 1);
185 entry.Put(syncable::SERVER_VERSION, 1);
186 entry.Put(syncable::IS_UNAPPLIED_UPDATE, false);
187 entry.Put(syncable::SERVER_PARENT_ID, syncable::GetNullId());
188 entry.Put(syncable::SERVER_IS_DIR, true);
189 entry.Put(syncable::IS_DIR, true);
190 entry.Put(syncable::SERVER_SPECIFICS, specifics);
191 entry.Put(syncable::UNIQUE_SERVER_TAG, type_tag);
192 entry.Put(syncable::NON_UNIQUE_NAME, type_tag);
193 entry.Put(syncable::IS_DEL, false);
194 entry.Put(syncable::SPECIFICS, specifics);
195 return entry.Get(syncable::META_HANDLE);
196 }
197
198 // Simulates creating a "synced" node as a child of the root datatype node.
199 int64 MakeServerNode(UserShare* share, ModelType model_type,
200 const std::string& client_tag,
201 const std::string& hashed_tag,
202 const sync_pb::EntitySpecifics& specifics) {
203 syncable::WriteTransaction trans(
204 FROM_HERE, syncable::UNITTEST, share->directory.get());
205 syncable::Entry root_entry(&trans, syncable::GET_BY_SERVER_TAG,
206 syncable::ModelTypeToRootTag(model_type));
207 EXPECT_TRUE(root_entry.good());
208 syncable::Id root_id = root_entry.Get(syncable::ID);
209 syncable::Id node_id = syncable::Id::CreateFromServerId(client_tag);
210 syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM,
211 node_id);
212 EXPECT_TRUE(entry.good());
213 entry.Put(syncable::BASE_VERSION, 1);
214 entry.Put(syncable::SERVER_VERSION, 1);
215 entry.Put(syncable::IS_UNAPPLIED_UPDATE, false);
216 entry.Put(syncable::SERVER_PARENT_ID, root_id);
217 entry.Put(syncable::PARENT_ID, root_id);
218 entry.Put(syncable::SERVER_IS_DIR, false);
219 entry.Put(syncable::IS_DIR, false);
220 entry.Put(syncable::SERVER_SPECIFICS, specifics);
221 entry.Put(syncable::NON_UNIQUE_NAME, client_tag);
222 entry.Put(syncable::UNIQUE_CLIENT_TAG, hashed_tag);
223 entry.Put(syncable::IS_DEL, false);
224 entry.Put(syncable::SPECIFICS, specifics);
225 return entry.Get(syncable::META_HANDLE);
226 }
227
228 } // namespace
229
230 class SyncApiTest : public testing::Test {
231 public:
232 virtual void SetUp() {
233 test_user_share_.SetUp();
234 }
235
236 virtual void TearDown() {
237 test_user_share_.TearDown();
238 }
239
240 protected:
241 MessageLoop message_loop_;
242 browser_sync::TestUserShare test_user_share_;
243 };
244
245 TEST_F(SyncApiTest, SanityCheckTest) {
246 {
247 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
248 EXPECT_TRUE(trans.GetWrappedTrans() != NULL);
249 }
250 {
251 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
252 EXPECT_TRUE(trans.GetWrappedTrans() != NULL);
253 }
254 {
255 // No entries but root should exist
256 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
257 ReadNode node(&trans);
258 // Metahandle 1 can be root, sanity check 2
259 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByIdLookup(2));
260 }
261 }
262
263 TEST_F(SyncApiTest, BasicTagWrite) {
264 {
265 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
266 ReadNode root_node(&trans);
267 root_node.InitByRootLookup();
268 EXPECT_EQ(root_node.GetFirstChildId(), 0);
269 }
270
271 ignore_result(MakeNode(test_user_share_.user_share(),
272 syncable::BOOKMARKS, "testtag"));
273
274 {
275 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
276 ReadNode node(&trans);
277 EXPECT_EQ(BaseNode::INIT_OK,
278 node.InitByClientTagLookup(syncable::BOOKMARKS, "testtag"));
279
280 ReadNode root_node(&trans);
281 root_node.InitByRootLookup();
282 EXPECT_NE(node.GetId(), 0);
283 EXPECT_EQ(node.GetId(), root_node.GetFirstChildId());
284 }
285 }
286
287 TEST_F(SyncApiTest, GenerateSyncableHash) {
288 EXPECT_EQ("OyaXV5mEzrPS4wbogmtKvRfekAI=",
289 BaseNode::GenerateSyncableHash(syncable::BOOKMARKS, "tag1"));
290 EXPECT_EQ("iNFQtRFQb+IZcn1kKUJEZDDkLs4=",
291 BaseNode::GenerateSyncableHash(syncable::PREFERENCES, "tag1"));
292 EXPECT_EQ("gO1cPZQXaM73sHOvSA+tKCKFs58=",
293 BaseNode::GenerateSyncableHash(syncable::AUTOFILL, "tag1"));
294
295 EXPECT_EQ("A0eYIHXM1/jVwKDDp12Up20IkKY=",
296 BaseNode::GenerateSyncableHash(syncable::BOOKMARKS, "tag2"));
297 EXPECT_EQ("XYxkF7bhS4eItStFgiOIAU23swI=",
298 BaseNode::GenerateSyncableHash(syncable::PREFERENCES, "tag2"));
299 EXPECT_EQ("GFiWzo5NGhjLlN+OyCfhy28DJTQ=",
300 BaseNode::GenerateSyncableHash(syncable::AUTOFILL, "tag2"));
301 }
302
303 TEST_F(SyncApiTest, ModelTypesSiloed) {
304 {
305 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
306 ReadNode root_node(&trans);
307 root_node.InitByRootLookup();
308 EXPECT_EQ(root_node.GetFirstChildId(), 0);
309 }
310
311 ignore_result(MakeNode(test_user_share_.user_share(),
312 syncable::BOOKMARKS, "collideme"));
313 ignore_result(MakeNode(test_user_share_.user_share(),
314 syncable::PREFERENCES, "collideme"));
315 ignore_result(MakeNode(test_user_share_.user_share(),
316 syncable::AUTOFILL, "collideme"));
317
318 {
319 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
320
321 ReadNode bookmarknode(&trans);
322 EXPECT_EQ(BaseNode::INIT_OK,
323 bookmarknode.InitByClientTagLookup(syncable::BOOKMARKS,
324 "collideme"));
325
326 ReadNode prefnode(&trans);
327 EXPECT_EQ(BaseNode::INIT_OK,
328 prefnode.InitByClientTagLookup(syncable::PREFERENCES,
329 "collideme"));
330
331 ReadNode autofillnode(&trans);
332 EXPECT_EQ(BaseNode::INIT_OK,
333 autofillnode.InitByClientTagLookup(syncable::AUTOFILL,
334 "collideme"));
335
336 EXPECT_NE(bookmarknode.GetId(), prefnode.GetId());
337 EXPECT_NE(autofillnode.GetId(), prefnode.GetId());
338 EXPECT_NE(bookmarknode.GetId(), autofillnode.GetId());
339 }
340 }
341
342 TEST_F(SyncApiTest, ReadMissingTagsFails) {
343 {
344 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
345 ReadNode node(&trans);
346 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
347 node.InitByClientTagLookup(syncable::BOOKMARKS,
348 "testtag"));
349 }
350 {
351 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
352 WriteNode node(&trans);
353 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD,
354 node.InitByClientTagLookup(syncable::BOOKMARKS,
355 "testtag"));
356 }
357 }
358
359 // TODO(chron): Hook this all up to the server and write full integration tests
360 // for update->undelete behavior.
361 TEST_F(SyncApiTest, TestDeleteBehavior) {
362 int64 node_id;
363 int64 folder_id;
364 std::string test_title("test1");
365
366 {
367 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
368 ReadNode root_node(&trans);
369 root_node.InitByRootLookup();
370
371 // we'll use this spare folder later
372 WriteNode folder_node(&trans);
373 EXPECT_TRUE(folder_node.InitByCreation(syncable::BOOKMARKS,
374 root_node, NULL));
375 folder_id = folder_node.GetId();
376
377 WriteNode wnode(&trans);
378 EXPECT_TRUE(wnode.InitUniqueByCreation(syncable::BOOKMARKS,
379 root_node, "testtag"));
380 wnode.SetIsFolder(false);
381 wnode.SetTitle(UTF8ToWide(test_title));
382
383 node_id = wnode.GetId();
384 }
385
386 // Ensure we can delete something with a tag.
387 {
388 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
389 WriteNode wnode(&trans);
390 EXPECT_EQ(BaseNode::INIT_OK,
391 wnode.InitByClientTagLookup(syncable::BOOKMARKS,
392 "testtag"));
393 EXPECT_FALSE(wnode.GetIsFolder());
394 EXPECT_EQ(wnode.GetTitle(), test_title);
395
396 wnode.Remove();
397 }
398
399 // Lookup of a node which was deleted should return failure,
400 // but have found some data about the node.
401 {
402 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
403 ReadNode node(&trans);
404 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL,
405 node.InitByClientTagLookup(syncable::BOOKMARKS,
406 "testtag"));
407 // Note that for proper function of this API this doesn't need to be
408 // filled, we're checking just to make sure the DB worked in this test.
409 EXPECT_EQ(node.GetTitle(), test_title);
410 }
411
412 {
413 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
414 ReadNode folder_node(&trans);
415 EXPECT_EQ(BaseNode::INIT_OK, folder_node.InitByIdLookup(folder_id));
416
417 WriteNode wnode(&trans);
418 // This will undelete the tag.
419 EXPECT_TRUE(wnode.InitUniqueByCreation(syncable::BOOKMARKS,
420 folder_node, "testtag"));
421 EXPECT_EQ(wnode.GetIsFolder(), false);
422 EXPECT_EQ(wnode.GetParentId(), folder_node.GetId());
423 EXPECT_EQ(wnode.GetId(), node_id);
424 EXPECT_NE(wnode.GetTitle(), test_title); // Title should be cleared
425 wnode.SetTitle(UTF8ToWide(test_title));
426 }
427
428 // Now look up should work.
429 {
430 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
431 ReadNode node(&trans);
432 EXPECT_EQ(BaseNode::INIT_OK,
433 node.InitByClientTagLookup(syncable::BOOKMARKS,
434 "testtag"));
435 EXPECT_EQ(node.GetTitle(), test_title);
436 EXPECT_EQ(node.GetModelType(), syncable::BOOKMARKS);
437 }
438 }
439
440 TEST_F(SyncApiTest, WriteAndReadPassword) {
441 KeyParams params = {"localhost", "username", "passphrase"};
442 {
443 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
444 trans.GetCryptographer()->AddKey(params);
445 }
446 {
447 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
448 ReadNode root_node(&trans);
449 root_node.InitByRootLookup();
450
451 WriteNode password_node(&trans);
452 EXPECT_TRUE(password_node.InitUniqueByCreation(syncable::PASSWORDS,
453 root_node, "foo"));
454 sync_pb::PasswordSpecificsData data;
455 data.set_password_value("secret");
456 password_node.SetPasswordSpecifics(data);
457 }
458 {
459 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
460 ReadNode root_node(&trans);
461 root_node.InitByRootLookup();
462
463 ReadNode password_node(&trans);
464 EXPECT_EQ(BaseNode::INIT_OK,
465 password_node.InitByClientTagLookup(syncable::PASSWORDS,
466 "foo"));
467 const sync_pb::PasswordSpecificsData& data =
468 password_node.GetPasswordSpecifics();
469 EXPECT_EQ("secret", data.password_value());
470 }
471 }
472
473 TEST_F(SyncApiTest, WriteEncryptedTitle) {
474 KeyParams params = {"localhost", "username", "passphrase"};
475 {
476 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
477 trans.GetCryptographer()->AddKey(params);
478 trans.GetCryptographer()->set_encrypt_everything();
479 }
480 {
481 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
482 ReadNode root_node(&trans);
483 root_node.InitByRootLookup();
484
485 WriteNode bookmark_node(&trans);
486 EXPECT_TRUE(bookmark_node.InitUniqueByCreation(syncable::BOOKMARKS,
487 root_node, "foo"));
488 bookmark_node.SetTitle(UTF8ToWide("foo"));
489
490 WriteNode pref_node(&trans);
491 EXPECT_TRUE(pref_node.InitUniqueByCreation(syncable::PREFERENCES,
492 root_node, "bar"));
493 pref_node.SetTitle(UTF8ToWide("bar"));
494 }
495 {
496 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
497 ReadNode root_node(&trans);
498 root_node.InitByRootLookup();
499
500 ReadNode bookmark_node(&trans);
501 EXPECT_EQ(BaseNode::INIT_OK,
502 bookmark_node.InitByClientTagLookup(syncable::BOOKMARKS,
503 "foo"));
504 EXPECT_EQ("foo", bookmark_node.GetTitle());
505 EXPECT_EQ(kEncryptedString,
506 bookmark_node.GetEntry()->Get(syncable::NON_UNIQUE_NAME));
507
508 ReadNode pref_node(&trans);
509 EXPECT_EQ(BaseNode::INIT_OK,
510 pref_node.InitByClientTagLookup(syncable::PREFERENCES,
511 "bar"));
512 EXPECT_EQ(kEncryptedString, pref_node.GetTitle());
513 }
514 }
515
516 TEST_F(SyncApiTest, BaseNodeSetSpecifics) {
517 int64 child_id = MakeNode(test_user_share_.user_share(),
518 syncable::BOOKMARKS, "testtag");
519 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
520 WriteNode node(&trans);
521 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
522
523 sync_pb::EntitySpecifics entity_specifics;
524 entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
525
526 EXPECT_NE(entity_specifics.SerializeAsString(),
527 node.GetEntitySpecifics().SerializeAsString());
528 node.SetEntitySpecifics(entity_specifics);
529 EXPECT_EQ(entity_specifics.SerializeAsString(),
530 node.GetEntitySpecifics().SerializeAsString());
531 }
532
533 TEST_F(SyncApiTest, BaseNodeSetSpecificsPreservesUnknownFields) {
534 int64 child_id = MakeNode(test_user_share_.user_share(),
535 syncable::BOOKMARKS, "testtag");
536 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
537 WriteNode node(&trans);
538 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
539 EXPECT_TRUE(node.GetEntitySpecifics().unknown_fields().empty());
540
541 sync_pb::EntitySpecifics entity_specifics;
542 entity_specifics.mutable_bookmark()->set_url("http://www.google.com");
543 entity_specifics.mutable_unknown_fields()->AddFixed32(5, 100);
544 node.SetEntitySpecifics(entity_specifics);
545 EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
546
547 entity_specifics.mutable_unknown_fields()->Clear();
548 node.SetEntitySpecifics(entity_specifics);
549 EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty());
550 }
551
552 namespace {
553
554 void CheckNodeValue(const BaseNode& node, const DictionaryValue& value,
555 bool is_detailed) {
556 ExpectInt64Value(node.GetId(), value, "id");
557 {
558 bool is_folder = false;
559 EXPECT_TRUE(value.GetBoolean("isFolder", &is_folder));
560 EXPECT_EQ(node.GetIsFolder(), is_folder);
561 }
562 ExpectDictStringValue(node.GetTitle(), value, "title");
563 {
564 ModelType expected_model_type = node.GetModelType();
565 std::string type_str;
566 EXPECT_TRUE(value.GetString("type", &type_str));
567 if (expected_model_type >= syncable::FIRST_REAL_MODEL_TYPE) {
568 ModelType model_type =
569 syncable::ModelTypeFromString(type_str);
570 EXPECT_EQ(expected_model_type, model_type);
571 } else if (expected_model_type == syncable::TOP_LEVEL_FOLDER) {
572 EXPECT_EQ("Top-level folder", type_str);
573 } else if (expected_model_type == syncable::UNSPECIFIED) {
574 EXPECT_EQ("Unspecified", type_str);
575 } else {
576 ADD_FAILURE();
577 }
578 }
579 if (is_detailed) {
580 ExpectInt64Value(node.GetParentId(), value, "parentId");
581 ExpectTimeValue(node.GetModificationTime(), value, "modificationTime");
582 ExpectInt64Value(node.GetExternalId(), value, "externalId");
583 ExpectInt64Value(node.GetPredecessorId(), value, "predecessorId");
584 ExpectInt64Value(node.GetSuccessorId(), value, "successorId");
585 ExpectInt64Value(node.GetFirstChildId(), value, "firstChildId");
586 {
587 scoped_ptr<DictionaryValue> expected_entry(node.GetEntry()->ToValue());
588 Value* entry = NULL;
589 EXPECT_TRUE(value.Get("entry", &entry));
590 EXPECT_TRUE(Value::Equals(entry, expected_entry.get()));
591 }
592 EXPECT_EQ(11u, value.size());
593 } else {
594 EXPECT_EQ(4u, value.size());
595 }
596 }
597
598 } // namespace
599
600 TEST_F(SyncApiTest, BaseNodeGetSummaryAsValue) {
601 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
602 ReadNode node(&trans);
603 node.InitByRootLookup();
604 scoped_ptr<DictionaryValue> details(node.GetSummaryAsValue());
605 if (details.get()) {
606 CheckNodeValue(node, *details, false);
607 } else {
608 ADD_FAILURE();
609 }
610 }
611
612 TEST_F(SyncApiTest, BaseNodeGetDetailsAsValue) {
613 ReadTransaction trans(FROM_HERE, test_user_share_.user_share());
614 ReadNode node(&trans);
615 node.InitByRootLookup();
616 scoped_ptr<DictionaryValue> details(node.GetDetailsAsValue());
617 if (details.get()) {
618 CheckNodeValue(node, *details, true);
619 } else {
620 ADD_FAILURE();
621 }
622 }
623
624 TEST_F(SyncApiTest, EmptyTags) {
625 WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
626 ReadNode root_node(&trans);
627 root_node.InitByRootLookup();
628 WriteNode node(&trans);
629 std::string empty_tag;
630 EXPECT_FALSE(node.InitUniqueByCreation(
631 syncable::TYPED_URLS, root_node, empty_tag));
632 EXPECT_EQ(BaseNode::INIT_FAILED_PRECONDITION,
633 node.InitByTagLookup(empty_tag));
634 }
635
636 namespace {
637
638 class TestHttpPostProviderInterface : public HttpPostProviderInterface {
639 public:
640 virtual ~TestHttpPostProviderInterface() {}
641
642 virtual void SetUserAgent(const char* user_agent) OVERRIDE {}
643 virtual void SetExtraRequestHeaders(const char* headers) OVERRIDE {}
644 virtual void SetURL(const char* url, int port) OVERRIDE {}
645 virtual void SetPostPayload(const char* content_type,
646 int content_length,
647 const char* content) OVERRIDE {}
648 virtual bool MakeSynchronousPost(int* error_code, int* response_code)
649 OVERRIDE {
650 return false;
651 }
652 virtual int GetResponseContentLength() const OVERRIDE {
653 return 0;
654 }
655 virtual const char* GetResponseContent() const OVERRIDE {
656 return "";
657 }
658 virtual const std::string GetResponseHeaderValue(
659 const std::string& name) const OVERRIDE {
660 return "";
661 }
662 virtual void Abort() OVERRIDE {}
663 };
664
665 class TestHttpPostProviderFactory : public HttpPostProviderFactory {
666 public:
667 virtual ~TestHttpPostProviderFactory() {}
668 virtual HttpPostProviderInterface* Create() OVERRIDE {
669 return new TestHttpPostProviderInterface();
670 }
671 virtual void Destroy(HttpPostProviderInterface* http) OVERRIDE {
672 delete http;
673 }
674 };
675
676 class SyncManagerObserverMock : public SyncManager::Observer {
677 public:
678 MOCK_METHOD1(OnSyncCycleCompleted,
679 void(const SyncSessionSnapshot*)); // NOLINT
680 MOCK_METHOD2(OnInitializationComplete,
681 void(const WeakHandle<JsBackend>&, bool)); // NOLINT
682 MOCK_METHOD1(OnConnectionStatusChange, void(ConnectionStatus)); // NOLINT
683 MOCK_METHOD2(OnPassphraseRequired,
684 void(sync_api::PassphraseRequiredReason,
685 const sync_pb::EncryptedData&)); // NOLINT
686 MOCK_METHOD0(OnPassphraseAccepted, void()); // NOLINT
687 MOCK_METHOD1(OnBootstrapTokenUpdated, void(const std::string&)); // NOLINT
688 MOCK_METHOD0(OnStopSyncingPermanently, void()); // NOLINT
689 MOCK_METHOD1(OnUpdatedToken, void(const std::string&)); // NOLINT
690 MOCK_METHOD0(OnClearServerDataFailed, void()); // NOLINT
691 MOCK_METHOD0(OnClearServerDataSucceeded, void()); // NOLINT
692 MOCK_METHOD2(OnEncryptedTypesChanged,
693 void(ModelTypeSet, bool)); // NOLINT
694 MOCK_METHOD0(OnEncryptionComplete, void()); // NOLINT
695 MOCK_METHOD1(OnActionableError,
696 void(const browser_sync::SyncProtocolError&)); // NOLINT
697 };
698
699 class SyncNotifierMock : public sync_notifier::SyncNotifier {
700 public:
701 MOCK_METHOD1(AddObserver, void(sync_notifier::SyncNotifierObserver*));
702 MOCK_METHOD1(RemoveObserver, void(sync_notifier::SyncNotifierObserver*));
703 MOCK_METHOD1(SetUniqueId, void(const std::string&));
704 MOCK_METHOD1(SetState, void(const std::string&));
705 MOCK_METHOD2(UpdateCredentials,
706 void(const std::string&, const std::string&));
707 MOCK_METHOD1(UpdateEnabledTypes,
708 void(syncable::ModelTypeSet));
709 MOCK_METHOD1(SendNotification, void(syncable::ModelTypeSet));
710 };
711
712 } // namespace
713
714 class SyncManagerTest : public testing::Test,
715 public ModelSafeWorkerRegistrar,
716 public SyncManager::ChangeDelegate {
717 protected:
718 enum NigoriStatus {
719 DONT_WRITE_NIGORI,
720 WRITE_TO_NIGORI
721 };
722
723 enum EncryptionStatus {
724 UNINITIALIZED,
725 DEFAULT_ENCRYPTION,
726 FULL_ENCRYPTION
727 };
728
729 SyncManagerTest()
730 : sync_notifier_mock_(NULL),
731 sync_manager_("Test sync manager"),
732 sync_notifier_observer_(NULL),
733 update_enabled_types_call_count_(0) {}
734
735 virtual ~SyncManagerTest() {
736 EXPECT_FALSE(sync_notifier_mock_);
737 }
738
739 // Test implementation.
740 void SetUp() {
741 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
742
743 SyncCredentials credentials;
744 credentials.email = "foo@bar.com";
745 credentials.sync_token = "sometoken";
746
747 sync_notifier_mock_ = new StrictMock<SyncNotifierMock>();
748 EXPECT_CALL(*sync_notifier_mock_, AddObserver(_)).
749 WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierAddObserver));
750 EXPECT_CALL(*sync_notifier_mock_, SetUniqueId(_));
751 EXPECT_CALL(*sync_notifier_mock_, SetState(""));
752 EXPECT_CALL(*sync_notifier_mock_,
753 UpdateCredentials(credentials.email, credentials.sync_token));
754 EXPECT_CALL(*sync_notifier_mock_, UpdateEnabledTypes(_)).
755 Times(AtLeast(1)).
756 WillRepeatedly(
757 Invoke(this, &SyncManagerTest::SyncNotifierUpdateEnabledTypes));
758 EXPECT_CALL(*sync_notifier_mock_, RemoveObserver(_)).
759 WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierRemoveObserver));
760
761 sync_manager_.AddObserver(&observer_);
762 EXPECT_CALL(observer_, OnInitializationComplete(_, _)).
763 WillOnce(SaveArg<0>(&js_backend_));
764
765 EXPECT_FALSE(sync_notifier_observer_);
766 EXPECT_FALSE(js_backend_.IsInitialized());
767
768 // Takes ownership of |sync_notifier_mock_|.
769 sync_manager_.Init(temp_dir_.path(),
770 WeakHandle<JsEventHandler>(),
771 "bogus", 0, false,
772 base::MessageLoopProxy::current(),
773 new TestHttpPostProviderFactory(), this,
774 &extensions_activity_monitor_, this, "bogus",
775 credentials,
776 false /* enable_sync_tabs_for_other_clients */,
777 sync_notifier_mock_, "",
778 sync_api::SyncManager::TEST_IN_MEMORY,
779 &encryptor_,
780 &handler_,
781 NULL);
782
783 EXPECT_TRUE(sync_notifier_observer_);
784 EXPECT_TRUE(js_backend_.IsInitialized());
785
786 EXPECT_EQ(1, update_enabled_types_call_count_);
787
788 ModelSafeRoutingInfo routes;
789 GetModelSafeRoutingInfo(&routes);
790 for (ModelSafeRoutingInfo::iterator i = routes.begin(); i != routes.end();
791 ++i) {
792 type_roots_[i->first] = MakeServerNodeForType(
793 sync_manager_.GetUserShare(), i->first);
794 }
795 PumpLoop();
796 }
797
798 void TearDown() {
799 sync_manager_.RemoveObserver(&observer_);
800 sync_manager_.ShutdownOnSyncThread();
801 sync_notifier_mock_ = NULL;
802 EXPECT_FALSE(sync_notifier_observer_);
803 PumpLoop();
804 }
805
806 // ModelSafeWorkerRegistrar implementation.
807 virtual void GetWorkers(std::vector<ModelSafeWorker*>* out) OVERRIDE {
808 NOTIMPLEMENTED();
809 out->clear();
810 }
811 virtual void GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) OVERRIDE {
812 (*out)[syncable::NIGORI] = browser_sync::GROUP_PASSIVE;
813 (*out)[syncable::BOOKMARKS] = browser_sync::GROUP_PASSIVE;
814 (*out)[syncable::THEMES] = browser_sync::GROUP_PASSIVE;
815 (*out)[syncable::SESSIONS] = browser_sync::GROUP_PASSIVE;
816 (*out)[syncable::PASSWORDS] = browser_sync::GROUP_PASSIVE;
817 (*out)[syncable::PREFERENCES] = browser_sync::GROUP_PASSIVE;
818 }
819
820 virtual void OnChangesApplied(
821 syncable::ModelType model_type,
822 const BaseTransaction* trans,
823 const ImmutableChangeRecordList& changes) OVERRIDE {}
824
825 virtual void OnChangesComplete(syncable::ModelType model_type) OVERRIDE {}
826
827 // Helper methods.
828 bool SetUpEncryption(NigoriStatus nigori_status,
829 EncryptionStatus encryption_status) {
830 UserShare* share = sync_manager_.GetUserShare();
831 share->directory->set_initial_sync_ended_for_type(syncable::NIGORI, true);
832
833 // We need to create the nigori node as if it were an applied server update.
834 int64 nigori_id = GetIdForDataType(syncable::NIGORI);
835 if (nigori_id == kInvalidId)
836 return false;
837
838 // Set the nigori cryptographer information.
839 WriteTransaction trans(FROM_HERE, share);
840 Cryptographer* cryptographer = trans.GetCryptographer();
841 if (!cryptographer)
842 return false;
843 if (encryption_status != UNINITIALIZED) {
844 KeyParams params = {"localhost", "dummy", "foobar"};
845 cryptographer->AddKey(params);
846 } else {
847 DCHECK_NE(nigori_status, WRITE_TO_NIGORI);
848 }
849 if (encryption_status == FULL_ENCRYPTION)
850 cryptographer->set_encrypt_everything();
851 if (nigori_status == WRITE_TO_NIGORI) {
852 sync_pb::NigoriSpecifics nigori;
853 cryptographer->GetKeys(nigori.mutable_encrypted());
854 cryptographer->UpdateNigoriFromEncryptedTypes(&nigori);
855 WriteNode node(&trans);
856 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(nigori_id));
857 node.SetNigoriSpecifics(nigori);
858 }
859 return cryptographer->is_ready();
860 }
861
862 int64 GetIdForDataType(ModelType type) {
863 if (type_roots_.count(type) == 0)
864 return 0;
865 return type_roots_[type];
866 }
867
868 void SyncNotifierAddObserver(
869 sync_notifier::SyncNotifierObserver* sync_notifier_observer) {
870 EXPECT_EQ(NULL, sync_notifier_observer_);
871 sync_notifier_observer_ = sync_notifier_observer;
872 }
873
874 void SyncNotifierRemoveObserver(
875 sync_notifier::SyncNotifierObserver* sync_notifier_observer) {
876 EXPECT_EQ(sync_notifier_observer_, sync_notifier_observer);
877 sync_notifier_observer_ = NULL;
878 }
879
880 void SyncNotifierUpdateEnabledTypes(syncable::ModelTypeSet types) {
881 ModelSafeRoutingInfo routes;
882 GetModelSafeRoutingInfo(&routes);
883 const syncable::ModelTypeSet expected_types =
884 GetRoutingInfoTypes(routes);
885 EXPECT_TRUE(types.Equals(expected_types));
886 ++update_enabled_types_call_count_;
887 }
888
889 void PumpLoop() {
890 message_loop_.RunAllPending();
891 }
892
893 void SendJsMessage(const std::string& name, const JsArgList& args,
894 const WeakHandle<JsReplyHandler>& reply_handler) {
895 js_backend_.Call(FROM_HERE, &JsBackend::ProcessJsMessage,
896 name, args, reply_handler);
897 PumpLoop();
898 }
899
900 void SetJsEventHandler(const WeakHandle<JsEventHandler>& event_handler) {
901 js_backend_.Call(FROM_HERE, &JsBackend::SetJsEventHandler,
902 event_handler);
903 PumpLoop();
904 }
905
906 // Looks up an entry by client tag and resets IS_UNSYNCED value to false.
907 // Returns true if entry was previously unsynced, false if IS_UNSYNCED was
908 // already false.
909 bool ResetUnsyncedEntry(syncable::ModelType type,
910 const std::string& client_tag) {
911 UserShare* share = sync_manager_.GetUserShare();
912 syncable::WriteTransaction trans(
913 FROM_HERE, syncable::UNITTEST, share->directory.get());
914 const std::string hash = BaseNode::GenerateSyncableHash(type, client_tag);
915 syncable::MutableEntry entry(&trans, syncable::GET_BY_CLIENT_TAG,
916 hash);
917 EXPECT_TRUE(entry.good());
918 if (!entry.Get(IS_UNSYNCED))
919 return false;
920 entry.Put(IS_UNSYNCED, false);
921 return true;
922 }
923
924 private:
925 // Needed by |sync_manager_|.
926 MessageLoop message_loop_;
927 // Needed by |sync_manager_|.
928 ScopedTempDir temp_dir_;
929 // Sync Id's for the roots of the enabled datatypes.
930 std::map<ModelType, int64> type_roots_;
931 FakeExtensionsActivityMonitor extensions_activity_monitor_;
932 StrictMock<SyncNotifierMock>* sync_notifier_mock_;
933
934 protected:
935 FakeEncryptor encryptor_;
936 TestUnrecoverableErrorHandler handler_;
937 SyncManager sync_manager_;
938 WeakHandle<JsBackend> js_backend_;
939 StrictMock<SyncManagerObserverMock> observer_;
940 sync_notifier::SyncNotifierObserver* sync_notifier_observer_;
941 int update_enabled_types_call_count_;
942 };
943
944 TEST_F(SyncManagerTest, UpdateEnabledTypes) {
945 EXPECT_EQ(1, update_enabled_types_call_count_);
946 // Triggers SyncNotifierUpdateEnabledTypes.
947 sync_manager_.UpdateEnabledTypes();
948 EXPECT_EQ(2, update_enabled_types_call_count_);
949 }
950
951 TEST_F(SyncManagerTest, DoNotSyncTabsInNigoriNode) {
952 const syncable::ModelTypeSet encrypted_types(syncable::TYPED_URLS);
953 sync_manager_.MaybeSetSyncTabsInNigoriNode(encrypted_types);
954
955 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
956 ReadNode node(&trans);
957 ASSERT_EQ(BaseNode::INIT_OK,
958 node.InitByIdLookup(GetIdForDataType(syncable::NIGORI)));
959 EXPECT_FALSE(node.GetNigoriSpecifics().sync_tabs());
960 }
961
962 TEST_F(SyncManagerTest, SyncTabsInNigoriNode) {
963 const syncable::ModelTypeSet encrypted_types(syncable::SESSIONS);
964 sync_manager_.MaybeSetSyncTabsInNigoriNode(encrypted_types);
965
966 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
967 ReadNode node(&trans);
968 ASSERT_EQ(BaseNode::INIT_OK,
969 node.InitByIdLookup(GetIdForDataType(syncable::NIGORI)));
970 EXPECT_TRUE(node.GetNigoriSpecifics().sync_tabs());
971 }
972
973 TEST_F(SyncManagerTest, ProcessJsMessage) {
974 const JsArgList kNoArgs;
975
976 StrictMock<MockJsReplyHandler> reply_handler;
977
978 ListValue false_args;
979 false_args.Append(Value::CreateBooleanValue(false));
980
981 EXPECT_CALL(reply_handler,
982 HandleJsReply("getNotificationState",
983 HasArgsAsList(false_args)));
984
985 // This message should be dropped.
986 SendJsMessage("unknownMessage", kNoArgs, reply_handler.AsWeakHandle());
987
988 SendJsMessage("getNotificationState", kNoArgs, reply_handler.AsWeakHandle());
989 }
990
991 TEST_F(SyncManagerTest, ProcessJsMessageGetRootNodeDetails) {
992 const JsArgList kNoArgs;
993
994 StrictMock<MockJsReplyHandler> reply_handler;
995
996 JsArgList return_args;
997
998 EXPECT_CALL(reply_handler,
999 HandleJsReply("getRootNodeDetails", _))
1000 .WillOnce(SaveArg<1>(&return_args));
1001
1002 SendJsMessage("getRootNodeDetails", kNoArgs, reply_handler.AsWeakHandle());
1003
1004 EXPECT_EQ(1u, return_args.Get().GetSize());
1005 DictionaryValue* node_info = NULL;
1006 EXPECT_TRUE(return_args.Get().GetDictionary(0, &node_info));
1007 if (node_info) {
1008 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1009 ReadNode node(&trans);
1010 node.InitByRootLookup();
1011 CheckNodeValue(node, *node_info, true);
1012 } else {
1013 ADD_FAILURE();
1014 }
1015 }
1016
1017 void CheckGetNodesByIdReturnArgs(const SyncManager& sync_manager,
1018 const JsArgList& return_args,
1019 int64 id,
1020 bool is_detailed) {
1021 EXPECT_EQ(1u, return_args.Get().GetSize());
1022 ListValue* nodes = NULL;
1023 ASSERT_TRUE(return_args.Get().GetList(0, &nodes));
1024 ASSERT_TRUE(nodes);
1025 EXPECT_EQ(1u, nodes->GetSize());
1026 DictionaryValue* node_info = NULL;
1027 EXPECT_TRUE(nodes->GetDictionary(0, &node_info));
1028 ASSERT_TRUE(node_info);
1029 ReadTransaction trans(FROM_HERE, sync_manager.GetUserShare());
1030 ReadNode node(&trans);
1031 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id));
1032 CheckNodeValue(node, *node_info, is_detailed);
1033 }
1034
1035 class SyncManagerGetNodesByIdTest : public SyncManagerTest {
1036 protected:
1037 virtual ~SyncManagerGetNodesByIdTest() {}
1038
1039 void RunGetNodesByIdTest(const char* message_name, bool is_detailed) {
1040 int64 root_id = kInvalidId;
1041 {
1042 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1043 ReadNode root_node(&trans);
1044 root_node.InitByRootLookup();
1045 root_id = root_node.GetId();
1046 }
1047
1048 int64 child_id =
1049 MakeNode(sync_manager_.GetUserShare(),
1050 syncable::BOOKMARKS, "testtag");
1051
1052 StrictMock<MockJsReplyHandler> reply_handler;
1053
1054 JsArgList return_args;
1055
1056 const int64 ids[] = { root_id, child_id };
1057
1058 EXPECT_CALL(reply_handler,
1059 HandleJsReply(message_name, _))
1060 .Times(arraysize(ids)).WillRepeatedly(SaveArg<1>(&return_args));
1061
1062 for (size_t i = 0; i < arraysize(ids); ++i) {
1063 ListValue args;
1064 ListValue* id_values = new ListValue();
1065 args.Append(id_values);
1066 id_values->Append(Value::CreateStringValue(base::Int64ToString(ids[i])));
1067 SendJsMessage(message_name,
1068 JsArgList(&args), reply_handler.AsWeakHandle());
1069
1070 CheckGetNodesByIdReturnArgs(sync_manager_, return_args,
1071 ids[i], is_detailed);
1072 }
1073 }
1074
1075 void RunGetNodesByIdFailureTest(const char* message_name) {
1076 StrictMock<MockJsReplyHandler> reply_handler;
1077
1078 ListValue empty_list_args;
1079 empty_list_args.Append(new ListValue());
1080
1081 EXPECT_CALL(reply_handler,
1082 HandleJsReply(message_name,
1083 HasArgsAsList(empty_list_args)))
1084 .Times(6);
1085
1086 {
1087 ListValue args;
1088 SendJsMessage(message_name,
1089 JsArgList(&args), reply_handler.AsWeakHandle());
1090 }
1091
1092 {
1093 ListValue args;
1094 args.Append(new ListValue());
1095 SendJsMessage(message_name,
1096 JsArgList(&args), reply_handler.AsWeakHandle());
1097 }
1098
1099 {
1100 ListValue args;
1101 ListValue* ids = new ListValue();
1102 args.Append(ids);
1103 ids->Append(Value::CreateStringValue(""));
1104 SendJsMessage(message_name,
1105 JsArgList(&args), reply_handler.AsWeakHandle());
1106 }
1107
1108 {
1109 ListValue args;
1110 ListValue* ids = new ListValue();
1111 args.Append(ids);
1112 ids->Append(Value::CreateStringValue("nonsense"));
1113 SendJsMessage(message_name,
1114 JsArgList(&args), reply_handler.AsWeakHandle());
1115 }
1116
1117 {
1118 ListValue args;
1119 ListValue* ids = new ListValue();
1120 args.Append(ids);
1121 ids->Append(Value::CreateStringValue("0"));
1122 SendJsMessage(message_name,
1123 JsArgList(&args), reply_handler.AsWeakHandle());
1124 }
1125
1126 {
1127 ListValue args;
1128 ListValue* ids = new ListValue();
1129 args.Append(ids);
1130 ids->Append(Value::CreateStringValue("9999"));
1131 SendJsMessage(message_name,
1132 JsArgList(&args), reply_handler.AsWeakHandle());
1133 }
1134 }
1135 };
1136
1137 TEST_F(SyncManagerGetNodesByIdTest, GetNodeSummariesById) {
1138 RunGetNodesByIdTest("getNodeSummariesById", false);
1139 }
1140
1141 TEST_F(SyncManagerGetNodesByIdTest, GetNodeDetailsById) {
1142 RunGetNodesByIdTest("getNodeDetailsById", true);
1143 }
1144
1145 TEST_F(SyncManagerGetNodesByIdTest, GetNodeSummariesByIdFailure) {
1146 RunGetNodesByIdFailureTest("getNodeSummariesById");
1147 }
1148
1149 TEST_F(SyncManagerGetNodesByIdTest, GetNodeDetailsByIdFailure) {
1150 RunGetNodesByIdFailureTest("getNodeDetailsById");
1151 }
1152
1153 TEST_F(SyncManagerTest, GetChildNodeIds) {
1154 StrictMock<MockJsReplyHandler> reply_handler;
1155
1156 JsArgList return_args;
1157
1158 EXPECT_CALL(reply_handler,
1159 HandleJsReply("getChildNodeIds", _))
1160 .Times(1).WillRepeatedly(SaveArg<1>(&return_args));
1161
1162 {
1163 ListValue args;
1164 args.Append(Value::CreateStringValue("1"));
1165 SendJsMessage("getChildNodeIds",
1166 JsArgList(&args), reply_handler.AsWeakHandle());
1167 }
1168
1169 EXPECT_EQ(1u, return_args.Get().GetSize());
1170 ListValue* nodes = NULL;
1171 ASSERT_TRUE(return_args.Get().GetList(0, &nodes));
1172 ASSERT_TRUE(nodes);
1173 EXPECT_EQ(6u, nodes->GetSize());
1174 }
1175
1176 TEST_F(SyncManagerTest, GetChildNodeIdsFailure) {
1177 StrictMock<MockJsReplyHandler> reply_handler;
1178
1179 ListValue empty_list_args;
1180 empty_list_args.Append(new ListValue());
1181
1182 EXPECT_CALL(reply_handler,
1183 HandleJsReply("getChildNodeIds",
1184 HasArgsAsList(empty_list_args)))
1185 .Times(5);
1186
1187 {
1188 ListValue args;
1189 SendJsMessage("getChildNodeIds",
1190 JsArgList(&args), reply_handler.AsWeakHandle());
1191 }
1192
1193 {
1194 ListValue args;
1195 args.Append(Value::CreateStringValue(""));
1196 SendJsMessage("getChildNodeIds",
1197 JsArgList(&args), reply_handler.AsWeakHandle());
1198 }
1199
1200 {
1201 ListValue args;
1202 args.Append(Value::CreateStringValue("nonsense"));
1203 SendJsMessage("getChildNodeIds",
1204 JsArgList(&args), reply_handler.AsWeakHandle());
1205 }
1206
1207 {
1208 ListValue args;
1209 args.Append(Value::CreateStringValue("0"));
1210 SendJsMessage("getChildNodeIds",
1211 JsArgList(&args), reply_handler.AsWeakHandle());
1212 }
1213
1214 {
1215 ListValue args;
1216 args.Append(Value::CreateStringValue("9999"));
1217 SendJsMessage("getChildNodeIds",
1218 JsArgList(&args), reply_handler.AsWeakHandle());
1219 }
1220 }
1221
1222 TEST_F(SyncManagerTest, GetAllNodesTest) {
1223 StrictMock<MockJsReplyHandler> reply_handler;
1224 JsArgList return_args;
1225
1226 EXPECT_CALL(reply_handler,
1227 HandleJsReply("getAllNodes", _))
1228 .Times(1).WillRepeatedly(SaveArg<1>(&return_args));
1229
1230 {
1231 ListValue args;
1232 SendJsMessage("getAllNodes",
1233 JsArgList(&args), reply_handler.AsWeakHandle());
1234 }
1235
1236 // There's not much value in verifying every attribute on every node here.
1237 // Most of the value of this test has already been achieved: we've verified we
1238 // can call the above function without crashing or leaking memory.
1239 //
1240 // Let's just check the list size and a few of its elements. Anything more
1241 // would make this test brittle without greatly increasing our chances of
1242 // catching real bugs.
1243
1244 ListValue* node_list;
1245 DictionaryValue* first_result;
1246
1247 // The resulting argument list should have one argument, a list of nodes.
1248 ASSERT_EQ(1U, return_args.Get().GetSize());
1249 ASSERT_TRUE(return_args.Get().GetList(0, &node_list));
1250
1251 // The database creation logic depends on the routing info.
1252 // Refer to setup methods for more information.
1253 ModelSafeRoutingInfo routes;
1254 GetModelSafeRoutingInfo(&routes);
1255 size_t directory_size = routes.size() + 1;
1256
1257 ASSERT_EQ(directory_size, node_list->GetSize());
1258 ASSERT_TRUE(node_list->GetDictionary(0, &first_result));
1259 EXPECT_TRUE(first_result->HasKey("ID"));
1260 EXPECT_TRUE(first_result->HasKey("NON_UNIQUE_NAME"));
1261 }
1262
1263 TEST_F(SyncManagerTest, OnNotificationStateChange) {
1264 InSequence dummy;
1265 StrictMock<MockJsEventHandler> event_handler;
1266
1267 DictionaryValue true_details;
1268 true_details.SetBoolean("enabled", true);
1269 DictionaryValue false_details;
1270 false_details.SetBoolean("enabled", false);
1271
1272 EXPECT_CALL(event_handler,
1273 HandleJsEvent("onNotificationStateChange",
1274 HasDetailsAsDictionary(true_details)));
1275 EXPECT_CALL(event_handler,
1276 HandleJsEvent("onNotificationStateChange",
1277 HasDetailsAsDictionary(false_details)));
1278
1279 sync_manager_.TriggerOnNotificationStateChangeForTest(true);
1280 sync_manager_.TriggerOnNotificationStateChangeForTest(false);
1281
1282 SetJsEventHandler(event_handler.AsWeakHandle());
1283 sync_manager_.TriggerOnNotificationStateChangeForTest(true);
1284 sync_manager_.TriggerOnNotificationStateChangeForTest(false);
1285 SetJsEventHandler(WeakHandle<JsEventHandler>());
1286
1287 sync_manager_.TriggerOnNotificationStateChangeForTest(true);
1288 sync_manager_.TriggerOnNotificationStateChangeForTest(false);
1289
1290 // Should trigger the replies.
1291 PumpLoop();
1292 }
1293
1294 TEST_F(SyncManagerTest, OnIncomingNotification) {
1295 StrictMock<MockJsEventHandler> event_handler;
1296
1297 const syncable::ModelTypeSet empty_model_types;
1298 const syncable::ModelTypeSet model_types(
1299 syncable::BOOKMARKS, syncable::THEMES);
1300
1301 // Build expected_args to have a single argument with the string
1302 // equivalents of model_types.
1303 DictionaryValue expected_details;
1304 {
1305 ListValue* model_type_list = new ListValue();
1306 expected_details.SetString("source", "REMOTE_NOTIFICATION");
1307 expected_details.Set("changedTypes", model_type_list);
1308 for (syncable::ModelTypeSet::Iterator it = model_types.First();
1309 it.Good(); it.Inc()) {
1310 model_type_list->Append(
1311 Value::CreateStringValue(
1312 syncable::ModelTypeToString(it.Get())));
1313 }
1314 }
1315
1316 EXPECT_CALL(event_handler,
1317 HandleJsEvent("onIncomingNotification",
1318 HasDetailsAsDictionary(expected_details)));
1319
1320 sync_manager_.TriggerOnIncomingNotificationForTest(empty_model_types);
1321 sync_manager_.TriggerOnIncomingNotificationForTest(model_types);
1322
1323 SetJsEventHandler(event_handler.AsWeakHandle());
1324 sync_manager_.TriggerOnIncomingNotificationForTest(model_types);
1325 SetJsEventHandler(WeakHandle<JsEventHandler>());
1326
1327 sync_manager_.TriggerOnIncomingNotificationForTest(empty_model_types);
1328 sync_manager_.TriggerOnIncomingNotificationForTest(model_types);
1329
1330 // Should trigger the replies.
1331 PumpLoop();
1332 }
1333
1334 TEST_F(SyncManagerTest, RefreshEncryptionReady) {
1335 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1336 EXPECT_CALL(observer_, OnEncryptionComplete());
1337
1338 sync_manager_.RefreshNigori(kTestChromeVersion, base::Bind(&DoNothing));
1339 PumpLoop();
1340
1341 const syncable::ModelTypeSet encrypted_types =
1342 sync_manager_.GetEncryptedDataTypesForTest();
1343 EXPECT_TRUE(encrypted_types.Has(syncable::PASSWORDS));
1344 EXPECT_FALSE(sync_manager_.EncryptEverythingEnabledForTest());
1345 {
1346 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1347 ReadNode node(&trans);
1348 EXPECT_EQ(BaseNode::INIT_OK,
1349 node.InitByIdLookup(GetIdForDataType(syncable::NIGORI)));
1350 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1351 EXPECT_TRUE(nigori.has_encrypted());
1352 Cryptographer* cryptographer = trans.GetCryptographer();
1353 EXPECT_TRUE(cryptographer->is_ready());
1354 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encrypted()));
1355 }
1356 }
1357
1358 // Attempt to refresh encryption when nigori not downloaded.
1359 TEST_F(SyncManagerTest, RefreshEncryptionNotReady) {
1360 // Don't set up encryption (no nigori node created).
1361
1362 // Should fail.
1363 sync_manager_.RefreshNigori(kTestChromeVersion, base::Bind(&DoNothing));
1364 PumpLoop();
1365
1366 const syncable::ModelTypeSet encrypted_types =
1367 sync_manager_.GetEncryptedDataTypesForTest();
1368 EXPECT_TRUE(encrypted_types.Has(syncable::PASSWORDS)); // Hardcoded.
1369 EXPECT_FALSE(sync_manager_.EncryptEverythingEnabledForTest());
1370 }
1371
1372 // Attempt to refresh encryption when nigori is empty.
1373 TEST_F(SyncManagerTest, RefreshEncryptionEmptyNigori) {
1374 EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI, DEFAULT_ENCRYPTION));
1375 EXPECT_CALL(observer_, OnEncryptionComplete());
1376
1377 // Should write to nigori.
1378 sync_manager_.RefreshNigori(kTestChromeVersion, base::Bind(&DoNothing));
1379 PumpLoop();
1380
1381 const syncable::ModelTypeSet encrypted_types =
1382 sync_manager_.GetEncryptedDataTypesForTest();
1383 EXPECT_TRUE(encrypted_types.Has(syncable::PASSWORDS)); // Hardcoded.
1384 EXPECT_FALSE(sync_manager_.EncryptEverythingEnabledForTest());
1385 {
1386 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1387 ReadNode node(&trans);
1388 EXPECT_EQ(BaseNode::INIT_OK,
1389 node.InitByIdLookup(GetIdForDataType(syncable::NIGORI)));
1390 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1391 EXPECT_TRUE(nigori.has_encrypted());
1392 Cryptographer* cryptographer = trans.GetCryptographer();
1393 EXPECT_TRUE(cryptographer->is_ready());
1394 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encrypted()));
1395 }
1396 }
1397
1398 TEST_F(SyncManagerTest, EncryptDataTypesWithNoData) {
1399 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1400 EXPECT_CALL(observer_,
1401 OnEncryptedTypesChanged(
1402 HasModelTypes(syncable::ModelTypeSet::All()), true));
1403 EXPECT_CALL(observer_, OnEncryptionComplete());
1404 sync_manager_.EnableEncryptEverything();
1405 EXPECT_TRUE(sync_manager_.EncryptEverythingEnabledForTest());
1406 }
1407
1408 TEST_F(SyncManagerTest, EncryptDataTypesWithData) {
1409 size_t batch_size = 5;
1410 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1411
1412 // Create some unencrypted unsynced data.
1413 int64 folder = MakeFolderWithParent(sync_manager_.GetUserShare(),
1414 syncable::BOOKMARKS,
1415 GetIdForDataType(syncable::BOOKMARKS),
1416 NULL);
1417 // First batch_size nodes are children of folder.
1418 size_t i;
1419 for (i = 0; i < batch_size; ++i) {
1420 MakeNodeWithParent(sync_manager_.GetUserShare(), syncable::BOOKMARKS,
1421 base::StringPrintf("%"PRIuS"", i), folder);
1422 }
1423 // Next batch_size nodes are a different type and on their own.
1424 for (; i < 2*batch_size; ++i) {
1425 MakeNodeWithParent(sync_manager_.GetUserShare(), syncable::SESSIONS,
1426 base::StringPrintf("%"PRIuS"", i),
1427 GetIdForDataType(syncable::SESSIONS));
1428 }
1429 // Last batch_size nodes are a third type that will not need encryption.
1430 for (; i < 3*batch_size; ++i) {
1431 MakeNodeWithParent(sync_manager_.GetUserShare(), syncable::THEMES,
1432 base::StringPrintf("%"PRIuS"", i),
1433 GetIdForDataType(syncable::THEMES));
1434 }
1435
1436 {
1437 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1438 EXPECT_TRUE(GetEncryptedTypes(&trans).Equals(
1439 Cryptographer::SensitiveTypes()));
1440 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1441 trans.GetWrappedTrans(),
1442 trans.GetCryptographer(),
1443 syncable::BOOKMARKS,
1444 false /* not encrypted */));
1445 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1446 trans.GetWrappedTrans(),
1447 trans.GetCryptographer(),
1448 syncable::SESSIONS,
1449 false /* not encrypted */));
1450 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1451 trans.GetWrappedTrans(),
1452 trans.GetCryptographer(),
1453 syncable::THEMES,
1454 false /* not encrypted */));
1455 }
1456
1457 EXPECT_CALL(observer_,
1458 OnEncryptedTypesChanged(
1459 HasModelTypes(syncable::ModelTypeSet::All()), true));
1460 EXPECT_CALL(observer_, OnEncryptionComplete());
1461 sync_manager_.EnableEncryptEverything();
1462 EXPECT_TRUE(sync_manager_.EncryptEverythingEnabledForTest());
1463 {
1464 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1465 EXPECT_TRUE(GetEncryptedTypes(&trans).Equals(
1466 syncable::ModelTypeSet::All()));
1467 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1468 trans.GetWrappedTrans(),
1469 trans.GetCryptographer(),
1470 syncable::BOOKMARKS,
1471 true /* is encrypted */));
1472 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1473 trans.GetWrappedTrans(),
1474 trans.GetCryptographer(),
1475 syncable::SESSIONS,
1476 true /* is encrypted */));
1477 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1478 trans.GetWrappedTrans(),
1479 trans.GetCryptographer(),
1480 syncable::THEMES,
1481 true /* is encrypted */));
1482 }
1483
1484 // Trigger's a ReEncryptEverything with new passphrase.
1485 testing::Mock::VerifyAndClearExpectations(&observer_);
1486 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_));
1487 EXPECT_CALL(observer_, OnPassphraseAccepted());
1488 EXPECT_CALL(observer_, OnEncryptionComplete());
1489 sync_manager_.SetEncryptionPassphrase("new_passphrase", true);
1490 EXPECT_TRUE(sync_manager_.EncryptEverythingEnabledForTest());
1491 {
1492 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1493 EXPECT_TRUE(GetEncryptedTypes(&trans).Equals(
1494 syncable::ModelTypeSet::All()));
1495 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1496 trans.GetWrappedTrans(),
1497 trans.GetCryptographer(),
1498 syncable::BOOKMARKS,
1499 true /* is encrypted */));
1500 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1501 trans.GetWrappedTrans(),
1502 trans.GetCryptographer(),
1503 syncable::SESSIONS,
1504 true /* is encrypted */));
1505 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1506 trans.GetWrappedTrans(),
1507 trans.GetCryptographer(),
1508 syncable::THEMES,
1509 true /* is encrypted */));
1510 }
1511 // Calling EncryptDataTypes with an empty encrypted types should not trigger
1512 // a reencryption and should just notify immediately.
1513 // TODO(zea): add logic to ensure nothing was written.
1514 testing::Mock::VerifyAndClearExpectations(&observer_);
1515 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_)).Times(0);
1516 EXPECT_CALL(observer_, OnPassphraseAccepted()).Times(0);
1517 EXPECT_CALL(observer_, OnEncryptionComplete());
1518 sync_manager_.EnableEncryptEverything();
1519 }
1520
1521 // Test that when there are no pending keys and the cryptographer is not
1522 // initialized, we add a key based on the current GAIA password.
1523 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1524 TEST_F(SyncManagerTest, SetInitialGaiaPass) {
1525 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1526 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_));
1527 EXPECT_CALL(observer_, OnPassphraseAccepted());
1528 EXPECT_CALL(observer_, OnEncryptionComplete());
1529 sync_manager_.SetEncryptionPassphrase("new_passphrase", false);
1530 EXPECT_FALSE(sync_manager_.EncryptEverythingEnabledForTest());
1531 {
1532 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1533 ReadNode node(&trans);
1534 EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag));
1535 sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics();
1536 Cryptographer* cryptographer = trans.GetCryptographer();
1537 EXPECT_TRUE(cryptographer->is_ready());
1538 EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encrypted()));
1539 }
1540 }
1541
1542 // Test that when there are no pending keys and we have on the old GAIA
1543 // password, we update and re-encrypt everything with the new GAIA password.
1544 // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1545 TEST_F(SyncManagerTest, UpdateGaiaPass) {
1546 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1547 Cryptographer verifier(&encryptor_);
1548 {
1549 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1550 Cryptographer* cryptographer = trans.GetCryptographer();
1551 std::string bootstrap_token;
1552 cryptographer->GetBootstrapToken(&bootstrap_token);
1553 verifier.Bootstrap(bootstrap_token);
1554 }
1555 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_));
1556 EXPECT_CALL(observer_, OnPassphraseAccepted());
1557 EXPECT_CALL(observer_, OnEncryptionComplete());
1558 sync_manager_.SetEncryptionPassphrase("new_passphrase", false);
1559 EXPECT_FALSE(sync_manager_.EncryptEverythingEnabledForTest());
1560 {
1561 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1562 Cryptographer* cryptographer = trans.GetCryptographer();
1563 EXPECT_TRUE(cryptographer->is_ready());
1564 // Verify the default key has changed.
1565 sync_pb::EncryptedData encrypted;
1566 cryptographer->GetKeys(&encrypted);
1567 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1568 }
1569 }
1570
1571 // Sets a new explicit passphrase. This should update the bootstrap token
1572 // and re-encrypt everything.
1573 // (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1574 TEST_F(SyncManagerTest, SetPassphraseWithPassword) {
1575 Cryptographer verifier(&encryptor_);
1576 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1577 {
1578 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1579 // Store the default (soon to be old) key.
1580 Cryptographer* cryptographer = trans.GetCryptographer();
1581 std::string bootstrap_token;
1582 cryptographer->GetBootstrapToken(&bootstrap_token);
1583 verifier.Bootstrap(bootstrap_token);
1584
1585 ReadNode root_node(&trans);
1586 root_node.InitByRootLookup();
1587
1588 WriteNode password_node(&trans);
1589 EXPECT_TRUE(password_node.InitUniqueByCreation(syncable::PASSWORDS,
1590 root_node, "foo"));
1591 sync_pb::PasswordSpecificsData data;
1592 data.set_password_value("secret");
1593 password_node.SetPasswordSpecifics(data);
1594 }
1595 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_));
1596 EXPECT_CALL(observer_, OnPassphraseAccepted());
1597 EXPECT_CALL(observer_, OnEncryptionComplete());
1598 sync_manager_.SetEncryptionPassphrase("new_passphrase", true);
1599 EXPECT_FALSE(sync_manager_.EncryptEverythingEnabledForTest());
1600 {
1601 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1602 Cryptographer* cryptographer = trans.GetCryptographer();
1603 EXPECT_TRUE(cryptographer->is_ready());
1604 // Verify the default key has changed.
1605 sync_pb::EncryptedData encrypted;
1606 cryptographer->GetKeys(&encrypted);
1607 EXPECT_FALSE(verifier.CanDecrypt(encrypted));
1608
1609 ReadNode password_node(&trans);
1610 EXPECT_EQ(BaseNode::INIT_OK,
1611 password_node.InitByClientTagLookup(syncable::PASSWORDS,
1612 "foo"));
1613 const sync_pb::PasswordSpecificsData& data =
1614 password_node.GetPasswordSpecifics();
1615 EXPECT_EQ("secret", data.password_value());
1616 }
1617 }
1618
1619 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1620 // being encrypted with a new (unprovided) GAIA password, then supply the
1621 // password.
1622 // (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1623 TEST_F(SyncManagerTest, SupplyPendingGAIAPass) {
1624 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1625 Cryptographer other_cryptographer(&encryptor_);
1626 {
1627 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1628 Cryptographer* cryptographer = trans.GetCryptographer();
1629 std::string bootstrap_token;
1630 cryptographer->GetBootstrapToken(&bootstrap_token);
1631 other_cryptographer.Bootstrap(bootstrap_token);
1632
1633 // Now update the nigori to reflect the new keys, and update the
1634 // cryptographer to have pending keys.
1635 KeyParams params = {"localhost", "dummy", "passphrase2"};
1636 other_cryptographer.AddKey(params);
1637 WriteNode node(&trans);
1638 EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag));
1639 sync_pb::NigoriSpecifics nigori;
1640 other_cryptographer.GetKeys(nigori.mutable_encrypted());
1641 cryptographer->Update(nigori);
1642 EXPECT_TRUE(cryptographer->has_pending_keys());
1643 node.SetNigoriSpecifics(nigori);
1644 }
1645 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_));
1646 EXPECT_CALL(observer_, OnPassphraseAccepted());
1647 EXPECT_CALL(observer_, OnEncryptionComplete());
1648 sync_manager_.SetDecryptionPassphrase("passphrase2");
1649 EXPECT_FALSE(sync_manager_.EncryptEverythingEnabledForTest());
1650 {
1651 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1652 Cryptographer* cryptographer = trans.GetCryptographer();
1653 EXPECT_TRUE(cryptographer->is_ready());
1654 // Verify we're encrypting with the new key.
1655 sync_pb::EncryptedData encrypted;
1656 cryptographer->GetKeys(&encrypted);
1657 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1658 }
1659 }
1660
1661 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1662 // being encrypted with an old (unprovided) GAIA password. Attempt to supply
1663 // the current GAIA password and verify the bootstrap token is updated. Then
1664 // supply the old GAIA password, and verify we re-encrypt all data with the
1665 // new GAIA password.
1666 // (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase)
1667 TEST_F(SyncManagerTest, SupplyPendingOldGAIAPass) {
1668 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1669 Cryptographer other_cryptographer(&encryptor_);
1670 {
1671 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1672 Cryptographer* cryptographer = trans.GetCryptographer();
1673 std::string bootstrap_token;
1674 cryptographer->GetBootstrapToken(&bootstrap_token);
1675 other_cryptographer.Bootstrap(bootstrap_token);
1676
1677 // Now update the nigori to reflect the new keys, and update the
1678 // cryptographer to have pending keys.
1679 KeyParams params = {"localhost", "dummy", "old_gaia"};
1680 other_cryptographer.AddKey(params);
1681 WriteNode node(&trans);
1682 EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag));
1683 sync_pb::NigoriSpecifics nigori;
1684 other_cryptographer.GetKeys(nigori.mutable_encrypted());
1685 node.SetNigoriSpecifics(nigori);
1686 cryptographer->Update(nigori);
1687
1688 // other_cryptographer now contains all encryption keys, and is encrypting
1689 // with the newest gaia.
1690 KeyParams new_params = {"localhost", "dummy", "new_gaia"};
1691 other_cryptographer.AddKey(new_params);
1692 }
1693 // The bootstrap token should have been updated. Save it to ensure it's based
1694 // on the new GAIA password.
1695 std::string bootstrap_token;
1696 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_))
1697 .WillOnce(SaveArg<0>(&bootstrap_token));
1698 EXPECT_CALL(observer_, OnPassphraseRequired(_,_));
1699 sync_manager_.SetEncryptionPassphrase("new_gaia", false);
1700 EXPECT_FALSE(sync_manager_.EncryptEverythingEnabledForTest());
1701 testing::Mock::VerifyAndClearExpectations(&observer_);
1702 {
1703 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1704 Cryptographer* cryptographer = trans.GetCryptographer();
1705 EXPECT_TRUE(cryptographer->is_initialized());
1706 EXPECT_FALSE(cryptographer->is_ready());
1707 // Verify we're encrypting with the new key, even though we have pending
1708 // keys.
1709 sync_pb::EncryptedData encrypted;
1710 other_cryptographer.GetKeys(&encrypted);
1711 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1712 }
1713 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_));
1714 EXPECT_CALL(observer_, OnPassphraseAccepted());
1715 EXPECT_CALL(observer_, OnEncryptionComplete());
1716 sync_manager_.SetEncryptionPassphrase("old_gaia", false);
1717 {
1718 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1719 Cryptographer* cryptographer = trans.GetCryptographer();
1720 EXPECT_TRUE(cryptographer->is_ready());
1721
1722 // Verify we're encrypting with the new key.
1723 sync_pb::EncryptedData encrypted;
1724 other_cryptographer.GetKeys(&encrypted);
1725 EXPECT_TRUE(cryptographer->CanDecrypt(encrypted));
1726
1727 // Verify the saved bootstrap token is based on the new gaia password.
1728 Cryptographer temp_cryptographer(&encryptor_);
1729 temp_cryptographer.Bootstrap(bootstrap_token);
1730 EXPECT_TRUE(temp_cryptographer.CanDecrypt(encrypted));
1731 }
1732 }
1733
1734 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1735 // being encrypted with an explicit (unprovided) passphrase, then supply the
1736 // passphrase.
1737 // (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase)
1738 TEST_F(SyncManagerTest, SupplyPendingExplicitPass) {
1739 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1740 Cryptographer other_cryptographer(&encryptor_);
1741 {
1742 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1743 Cryptographer* cryptographer = trans.GetCryptographer();
1744 std::string bootstrap_token;
1745 cryptographer->GetBootstrapToken(&bootstrap_token);
1746 other_cryptographer.Bootstrap(bootstrap_token);
1747
1748 // Now update the nigori to reflect the new keys, and update the
1749 // cryptographer to have pending keys.
1750 KeyParams params = {"localhost", "dummy", "explicit"};
1751 other_cryptographer.AddKey(params);
1752 WriteNode node(&trans);
1753 EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag));
1754 sync_pb::NigoriSpecifics nigori;
1755 other_cryptographer.GetKeys(nigori.mutable_encrypted());
1756 cryptographer->Update(nigori);
1757 EXPECT_TRUE(cryptographer->has_pending_keys());
1758 nigori.set_using_explicit_passphrase(true);
1759 node.SetNigoriSpecifics(nigori);
1760 }
1761 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_));
1762 EXPECT_CALL(observer_, OnPassphraseAccepted());
1763 EXPECT_CALL(observer_, OnEncryptionComplete());
1764 sync_manager_.SetDecryptionPassphrase("explicit");
1765 EXPECT_FALSE(sync_manager_.EncryptEverythingEnabledForTest());
1766 {
1767 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1768 Cryptographer* cryptographer = trans.GetCryptographer();
1769 EXPECT_TRUE(cryptographer->is_ready());
1770 // Verify we're encrypting with the new key.
1771 sync_pb::EncryptedData encrypted;
1772 cryptographer->GetKeys(&encrypted);
1773 EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted));
1774 }
1775 }
1776
1777 // Manually set the pending keys in the cryptographer/nigori to reflect the data
1778 // being encrypted with a new (unprovided) GAIA password, then supply the
1779 // password as a user-provided password.
1780 // This is the android case 7/8.
1781 TEST_F(SyncManagerTest, SupplyPendingGAIAPassUserProvided) {
1782 EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED));
1783 Cryptographer other_cryptographer(&encryptor_);
1784 {
1785 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1786 Cryptographer* cryptographer = trans.GetCryptographer();
1787 // Now update the nigori to reflect the new keys, and update the
1788 // cryptographer to have pending keys.
1789 KeyParams params = {"localhost", "dummy", "passphrase"};
1790 other_cryptographer.AddKey(params);
1791 WriteNode node(&trans);
1792 EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag));
1793 sync_pb::NigoriSpecifics nigori;
1794 other_cryptographer.GetKeys(nigori.mutable_encrypted());
1795 node.SetNigoriSpecifics(nigori);
1796 cryptographer->Update(nigori);
1797 EXPECT_FALSE(cryptographer->is_ready());
1798 }
1799 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_));
1800 EXPECT_CALL(observer_, OnPassphraseAccepted());
1801 EXPECT_CALL(observer_, OnEncryptionComplete());
1802 sync_manager_.SetEncryptionPassphrase("passphrase", false);
1803 EXPECT_FALSE(sync_manager_.EncryptEverythingEnabledForTest());
1804 {
1805 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1806 Cryptographer* cryptographer = trans.GetCryptographer();
1807 EXPECT_TRUE(cryptographer->is_ready());
1808 }
1809 }
1810
1811 TEST_F(SyncManagerTest, SetPassphraseWithEmptyPasswordNode) {
1812 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1813 int64 node_id = 0;
1814 std::string tag = "foo";
1815 {
1816 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1817 ReadNode root_node(&trans);
1818 root_node.InitByRootLookup();
1819
1820 WriteNode password_node(&trans);
1821 EXPECT_TRUE(password_node.InitUniqueByCreation(syncable::PASSWORDS,
1822 root_node, tag));
1823 node_id = password_node.GetId();
1824 }
1825 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_));
1826 EXPECT_CALL(observer_, OnPassphraseAccepted());
1827 EXPECT_CALL(observer_, OnEncryptionComplete());
1828 sync_manager_.SetEncryptionPassphrase("new_passphrase", true);
1829 EXPECT_FALSE(sync_manager_.EncryptEverythingEnabledForTest());
1830 {
1831 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1832 ReadNode password_node(&trans);
1833 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1834 password_node.InitByClientTagLookup(syncable::PASSWORDS,
1835 tag));
1836 }
1837 {
1838 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1839 ReadNode password_node(&trans);
1840 EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY,
1841 password_node.InitByIdLookup(node_id));
1842 }
1843 }
1844
1845 TEST_F(SyncManagerTest, NudgeDelayTest) {
1846 EXPECT_EQ(sync_manager_.GetNudgeDelayTimeDelta(syncable::BOOKMARKS),
1847 base::TimeDelta::FromMilliseconds(
1848 SyncManager::kDefaultNudgeDelayMilliseconds));
1849
1850 EXPECT_EQ(sync_manager_.GetNudgeDelayTimeDelta(syncable::AUTOFILL),
1851 base::TimeDelta::FromSeconds(
1852 browser_sync::kDefaultShortPollIntervalSeconds));
1853
1854 EXPECT_EQ(sync_manager_.GetNudgeDelayTimeDelta(syncable::PREFERENCES),
1855 base::TimeDelta::FromMilliseconds(
1856 SyncManager::kPreferencesNudgeDelayMilliseconds));
1857 }
1858
1859 // Friended by WriteNode, so can't be in an anonymouse namespace.
1860 TEST_F(SyncManagerTest, EncryptBookmarksWithLegacyData) {
1861 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
1862 std::string title;
1863 SyncAPINameToServerName("Google", &title);
1864 std::string url = "http://www.google.com";
1865 std::string raw_title2 = ".."; // An invalid cosmo title.
1866 std::string title2;
1867 SyncAPINameToServerName(raw_title2, &title2);
1868 std::string url2 = "http://www.bla.com";
1869
1870 // Create a bookmark using the legacy format.
1871 int64 node_id1 = MakeNode(sync_manager_.GetUserShare(),
1872 syncable::BOOKMARKS,
1873 "testtag");
1874 int64 node_id2 = MakeNode(sync_manager_.GetUserShare(),
1875 syncable::BOOKMARKS,
1876 "testtag2");
1877 {
1878 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1879 WriteNode node(&trans);
1880 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1881
1882 sync_pb::EntitySpecifics entity_specifics;
1883 entity_specifics.mutable_bookmark()->set_url(url);
1884 node.SetEntitySpecifics(entity_specifics);
1885
1886 // Set the old style title.
1887 syncable::MutableEntry* node_entry = node.entry_;
1888 node_entry->Put(syncable::NON_UNIQUE_NAME, title);
1889
1890 WriteNode node2(&trans);
1891 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1892
1893 sync_pb::EntitySpecifics entity_specifics2;
1894 entity_specifics2.mutable_bookmark()->set_url(url2);
1895 node2.SetEntitySpecifics(entity_specifics2);
1896
1897 // Set the old style title.
1898 syncable::MutableEntry* node_entry2 = node2.entry_;
1899 node_entry2->Put(syncable::NON_UNIQUE_NAME, title2);
1900 }
1901
1902 {
1903 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1904 ReadNode node(&trans);
1905 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1906 EXPECT_EQ(syncable::BOOKMARKS, node.GetModelType());
1907 EXPECT_EQ(title, node.GetTitle());
1908 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1909 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1910
1911 ReadNode node2(&trans);
1912 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1913 EXPECT_EQ(syncable::BOOKMARKS, node2.GetModelType());
1914 // We should de-canonicalize the title in GetTitle(), but the title in the
1915 // specifics should be stored in the server legal form.
1916 EXPECT_EQ(raw_title2, node2.GetTitle());
1917 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1918 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1919 }
1920
1921 {
1922 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1923 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1924 trans.GetWrappedTrans(),
1925 trans.GetCryptographer(),
1926 syncable::BOOKMARKS,
1927 false /* not encrypted */));
1928 }
1929
1930 EXPECT_CALL(observer_,
1931 OnEncryptedTypesChanged(
1932 HasModelTypes(syncable::ModelTypeSet::All()), true));
1933 EXPECT_CALL(observer_, OnEncryptionComplete());
1934 sync_manager_.EnableEncryptEverything();
1935 EXPECT_TRUE(sync_manager_.EncryptEverythingEnabledForTest());
1936
1937 {
1938 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1939 EXPECT_TRUE(GetEncryptedTypes(&trans).Equals(
1940 syncable::ModelTypeSet::All()));
1941 EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest(
1942 trans.GetWrappedTrans(),
1943 trans.GetCryptographer(),
1944 syncable::BOOKMARKS,
1945 true /* is encrypted */));
1946
1947 ReadNode node(&trans);
1948 EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1));
1949 EXPECT_EQ(syncable::BOOKMARKS, node.GetModelType());
1950 EXPECT_EQ(title, node.GetTitle());
1951 EXPECT_EQ(title, node.GetBookmarkSpecifics().title());
1952 EXPECT_EQ(url, node.GetBookmarkSpecifics().url());
1953
1954 ReadNode node2(&trans);
1955 EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2));
1956 EXPECT_EQ(syncable::BOOKMARKS, node2.GetModelType());
1957 // We should de-canonicalize the title in GetTitle(), but the title in the
1958 // specifics should be stored in the server legal form.
1959 EXPECT_EQ(raw_title2, node2.GetTitle());
1960 EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title());
1961 EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url());
1962 }
1963 }
1964
1965 // Create a bookmark and set the title/url, then verify the data was properly
1966 // set. This replicates the unique way bookmarks have of creating sync nodes.
1967 // See BookmarkChangeProcessor::PlaceSyncNode(..).
1968 TEST_F(SyncManagerTest, CreateLocalBookmark) {
1969 std::string title = "title";
1970 GURL url("url");
1971 {
1972 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1973 ReadNode root_node(&trans);
1974 root_node.InitByRootLookup();
1975 WriteNode node(&trans);
1976 ASSERT_TRUE(node.InitByCreation(syncable::BOOKMARKS, root_node, NULL));
1977 node.SetIsFolder(false);
1978 node.SetTitle(UTF8ToWide(title));
1979 node.SetURL(url);
1980 }
1981 {
1982 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
1983 ReadNode root_node(&trans);
1984 root_node.InitByRootLookup();
1985 int64 child_id = root_node.GetFirstChildId();
1986
1987 ReadNode node(&trans);
1988 ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id));
1989 EXPECT_FALSE(node.GetIsFolder());
1990 EXPECT_EQ(title, node.GetTitle());
1991 EXPECT_EQ(url, node.GetURL());
1992 }
1993 }
1994
1995 // Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary
1996 // changes.
1997 TEST_F(SyncManagerTest, UpdateEntryWithEncryption) {
1998 std::string client_tag = "title";
1999 sync_pb::EntitySpecifics entity_specifics;
2000 entity_specifics.mutable_bookmark()->set_url("url");
2001 entity_specifics.mutable_bookmark()->set_title("title");
2002 MakeServerNode(sync_manager_.GetUserShare(), syncable::BOOKMARKS, client_tag,
2003 BaseNode::GenerateSyncableHash(syncable::BOOKMARKS,
2004 client_tag),
2005 entity_specifics);
2006 // New node shouldn't start off unsynced.
2007 EXPECT_FALSE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2008 // Manually change to the same data. Should not set is_unsynced.
2009 {
2010 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2011 WriteNode node(&trans);
2012 EXPECT_EQ(BaseNode::INIT_OK,
2013 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2014 node.SetEntitySpecifics(entity_specifics);
2015 }
2016 EXPECT_FALSE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2017
2018 // Encrypt the datatatype, should set is_unsynced.
2019 EXPECT_CALL(observer_,
2020 OnEncryptedTypesChanged(
2021 HasModelTypes(syncable::ModelTypeSet::All()), true));
2022 EXPECT_CALL(observer_, OnEncryptionComplete());
2023 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2024
2025 sync_manager_.RefreshNigori(kTestChromeVersion, base::Bind(&DoNothing));
2026 PumpLoop();
2027 {
2028 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2029 ReadNode node(&trans);
2030 EXPECT_EQ(BaseNode::INIT_OK,
2031 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2032 const syncable::Entry* node_entry = node.GetEntry();
2033 const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS);
2034 EXPECT_TRUE(specifics.has_encrypted());
2035 EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME));
2036 Cryptographer* cryptographer = trans.GetCryptographer();
2037 EXPECT_TRUE(cryptographer->is_ready());
2038 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
2039 specifics.encrypted()));
2040 }
2041 EXPECT_TRUE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2042
2043 // Set a new passphrase. Should set is_unsynced.
2044 testing::Mock::VerifyAndClearExpectations(&observer_);
2045 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_));
2046 EXPECT_CALL(observer_, OnPassphraseAccepted());
2047 EXPECT_CALL(observer_, OnEncryptionComplete());
2048 sync_manager_.SetEncryptionPassphrase("new_passphrase", true);
2049 {
2050 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2051 ReadNode node(&trans);
2052 EXPECT_EQ(BaseNode::INIT_OK,
2053 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2054 const syncable::Entry* node_entry = node.GetEntry();
2055 const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS);
2056 EXPECT_TRUE(specifics.has_encrypted());
2057 EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME));
2058 Cryptographer* cryptographer = trans.GetCryptographer();
2059 EXPECT_TRUE(cryptographer->is_ready());
2060 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
2061 specifics.encrypted()));
2062 }
2063 EXPECT_TRUE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2064
2065 // Force a re-encrypt everything. Should not set is_unsynced.
2066 testing::Mock::VerifyAndClearExpectations(&observer_);
2067 EXPECT_CALL(observer_, OnEncryptionComplete());
2068
2069 sync_manager_.RefreshNigori(kTestChromeVersion, base::Bind(&DoNothing));
2070 PumpLoop();
2071
2072 {
2073 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2074 ReadNode node(&trans);
2075 EXPECT_EQ(BaseNode::INIT_OK,
2076 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2077 const syncable::Entry* node_entry = node.GetEntry();
2078 const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS);
2079 EXPECT_TRUE(specifics.has_encrypted());
2080 EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME));
2081 Cryptographer* cryptographer = trans.GetCryptographer();
2082 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
2083 specifics.encrypted()));
2084 }
2085 EXPECT_FALSE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2086
2087 // Manually change to the same data. Should not set is_unsynced.
2088 {
2089 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2090 WriteNode node(&trans);
2091 EXPECT_EQ(BaseNode::INIT_OK,
2092 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2093 node.SetEntitySpecifics(entity_specifics);
2094 const syncable::Entry* node_entry = node.GetEntry();
2095 const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS);
2096 EXPECT_TRUE(specifics.has_encrypted());
2097 EXPECT_FALSE(node_entry->Get(IS_UNSYNCED));
2098 EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME));
2099 Cryptographer* cryptographer = trans.GetCryptographer();
2100 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
2101 specifics.encrypted()));
2102 }
2103 EXPECT_FALSE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2104
2105 // Manually change to different data. Should set is_unsynced.
2106 {
2107 entity_specifics.mutable_bookmark()->set_url("url2");
2108 entity_specifics.mutable_bookmark()->set_title("title2");
2109 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2110 WriteNode node(&trans);
2111 EXPECT_EQ(BaseNode::INIT_OK,
2112 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2113 node.SetEntitySpecifics(entity_specifics);
2114 const syncable::Entry* node_entry = node.GetEntry();
2115 const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS);
2116 EXPECT_TRUE(specifics.has_encrypted());
2117 EXPECT_TRUE(node_entry->Get(IS_UNSYNCED));
2118 EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME));
2119 Cryptographer* cryptographer = trans.GetCryptographer();
2120 EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey(
2121 specifics.encrypted()));
2122 }
2123 }
2124
2125 // Passwords have their own handling for encryption. Verify it does not result
2126 // in unnecessary writes via SetEntitySpecifics.
2127 TEST_F(SyncManagerTest, UpdatePasswordSetEntitySpecificsNoChange) {
2128 std::string client_tag = "title";
2129 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2130 sync_pb::EntitySpecifics entity_specifics;
2131 {
2132 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2133 Cryptographer* cryptographer = trans.GetCryptographer();
2134 sync_pb::PasswordSpecificsData data;
2135 data.set_password_value("secret");
2136 cryptographer->Encrypt(
2137 data,
2138 entity_specifics.mutable_password()->
2139 mutable_encrypted());
2140 }
2141 MakeServerNode(sync_manager_.GetUserShare(), syncable::PASSWORDS, client_tag,
2142 BaseNode::GenerateSyncableHash(syncable::PASSWORDS,
2143 client_tag),
2144 entity_specifics);
2145 // New node shouldn't start off unsynced.
2146 EXPECT_FALSE(ResetUnsyncedEntry(syncable::PASSWORDS, client_tag));
2147
2148 // Manually change to the same data via SetEntitySpecifics. Should not set
2149 // is_unsynced.
2150 {
2151 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2152 WriteNode node(&trans);
2153 EXPECT_EQ(BaseNode::INIT_OK,
2154 node.InitByClientTagLookup(syncable::PASSWORDS, client_tag));
2155 node.SetEntitySpecifics(entity_specifics);
2156 }
2157 EXPECT_FALSE(ResetUnsyncedEntry(syncable::PASSWORDS, client_tag));
2158 }
2159
2160 // Passwords have their own handling for encryption. Verify it does not result
2161 // in unnecessary writes via SetPasswordSpecifics.
2162 TEST_F(SyncManagerTest, UpdatePasswordSetPasswordSpecifics) {
2163 std::string client_tag = "title";
2164 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2165 sync_pb::EntitySpecifics entity_specifics;
2166 {
2167 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2168 Cryptographer* cryptographer = trans.GetCryptographer();
2169 sync_pb::PasswordSpecificsData data;
2170 data.set_password_value("secret");
2171 cryptographer->Encrypt(
2172 data,
2173 entity_specifics.mutable_password()->
2174 mutable_encrypted());
2175 }
2176 MakeServerNode(sync_manager_.GetUserShare(), syncable::PASSWORDS, client_tag,
2177 BaseNode::GenerateSyncableHash(syncable::PASSWORDS,
2178 client_tag),
2179 entity_specifics);
2180 // New node shouldn't start off unsynced.
2181 EXPECT_FALSE(ResetUnsyncedEntry(syncable::PASSWORDS, client_tag));
2182
2183 // Manually change to the same data via SetPasswordSpecifics. Should not set
2184 // is_unsynced.
2185 {
2186 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2187 WriteNode node(&trans);
2188 EXPECT_EQ(BaseNode::INIT_OK,
2189 node.InitByClientTagLookup(syncable::PASSWORDS, client_tag));
2190 node.SetPasswordSpecifics(node.GetPasswordSpecifics());
2191 }
2192 EXPECT_FALSE(ResetUnsyncedEntry(syncable::PASSWORDS, client_tag));
2193
2194 // Manually change to different data. Should set is_unsynced.
2195 {
2196 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2197 WriteNode node(&trans);
2198 EXPECT_EQ(BaseNode::INIT_OK,
2199 node.InitByClientTagLookup(syncable::PASSWORDS, client_tag));
2200 Cryptographer* cryptographer = trans.GetCryptographer();
2201 sync_pb::PasswordSpecificsData data;
2202 data.set_password_value("secret2");
2203 cryptographer->Encrypt(
2204 data,
2205 entity_specifics.mutable_password()->mutable_encrypted());
2206 node.SetPasswordSpecifics(data);
2207 const syncable::Entry* node_entry = node.GetEntry();
2208 EXPECT_TRUE(node_entry->Get(IS_UNSYNCED));
2209 }
2210 }
2211
2212 // Passwords have their own handling for encryption. Verify setting a new
2213 // passphrase updates the data.
2214 TEST_F(SyncManagerTest, UpdatePasswordNewPassphrase) {
2215 std::string client_tag = "title";
2216 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2217 sync_pb::EntitySpecifics entity_specifics;
2218 {
2219 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2220 Cryptographer* cryptographer = trans.GetCryptographer();
2221 sync_pb::PasswordSpecificsData data;
2222 data.set_password_value("secret");
2223 cryptographer->Encrypt(
2224 data,
2225 entity_specifics.mutable_password()->mutable_encrypted());
2226 }
2227 MakeServerNode(sync_manager_.GetUserShare(), syncable::PASSWORDS, client_tag,
2228 BaseNode::GenerateSyncableHash(syncable::PASSWORDS,
2229 client_tag),
2230 entity_specifics);
2231 // New node shouldn't start off unsynced.
2232 EXPECT_FALSE(ResetUnsyncedEntry(syncable::PASSWORDS, client_tag));
2233
2234 // Set a new passphrase. Should set is_unsynced.
2235 testing::Mock::VerifyAndClearExpectations(&observer_);
2236 EXPECT_CALL(observer_, OnBootstrapTokenUpdated(_));
2237 EXPECT_CALL(observer_, OnPassphraseAccepted());
2238 EXPECT_CALL(observer_, OnEncryptionComplete());
2239 sync_manager_.SetEncryptionPassphrase("new_passphrase", true);
2240 EXPECT_TRUE(ResetUnsyncedEntry(syncable::PASSWORDS, client_tag));
2241 }
2242
2243 // Passwords have their own handling for encryption. Verify it does not result
2244 // in unnecessary writes via ReencryptEverything.
2245 TEST_F(SyncManagerTest, UpdatePasswordReencryptEverything) {
2246 std::string client_tag = "title";
2247 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2248 sync_pb::EntitySpecifics entity_specifics;
2249 {
2250 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2251 Cryptographer* cryptographer = trans.GetCryptographer();
2252 sync_pb::PasswordSpecificsData data;
2253 data.set_password_value("secret");
2254 cryptographer->Encrypt(
2255 data,
2256 entity_specifics.mutable_password()->mutable_encrypted());
2257 }
2258 MakeServerNode(sync_manager_.GetUserShare(), syncable::PASSWORDS, client_tag,
2259 BaseNode::GenerateSyncableHash(syncable::PASSWORDS,
2260 client_tag),
2261 entity_specifics);
2262 // New node shouldn't start off unsynced.
2263 EXPECT_FALSE(ResetUnsyncedEntry(syncable::PASSWORDS, client_tag));
2264
2265 // Force a re-encrypt everything. Should not set is_unsynced.
2266 testing::Mock::VerifyAndClearExpectations(&observer_);
2267 EXPECT_CALL(observer_, OnEncryptionComplete());
2268 sync_manager_.RefreshNigori(kTestChromeVersion, base::Bind(&DoNothing));
2269 PumpLoop();
2270 EXPECT_FALSE(ResetUnsyncedEntry(syncable::PASSWORDS, client_tag));
2271 }
2272
2273 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks
2274 // when we write the same data, but does set it when we write new data.
2275 TEST_F(SyncManagerTest, SetBookmarkTitle) {
2276 std::string client_tag = "title";
2277 sync_pb::EntitySpecifics entity_specifics;
2278 entity_specifics.mutable_bookmark()->set_url("url");
2279 entity_specifics.mutable_bookmark()->set_title("title");
2280 MakeServerNode(sync_manager_.GetUserShare(), syncable::BOOKMARKS, client_tag,
2281 BaseNode::GenerateSyncableHash(syncable::BOOKMARKS,
2282 client_tag),
2283 entity_specifics);
2284 // New node shouldn't start off unsynced.
2285 EXPECT_FALSE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2286
2287 // Manually change to the same title. Should not set is_unsynced.
2288 {
2289 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2290 WriteNode node(&trans);
2291 EXPECT_EQ(BaseNode::INIT_OK,
2292 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2293 node.SetTitle(UTF8ToWide(client_tag));
2294 }
2295 EXPECT_FALSE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2296
2297 // Manually change to new title. Should set is_unsynced.
2298 {
2299 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2300 WriteNode node(&trans);
2301 EXPECT_EQ(BaseNode::INIT_OK,
2302 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2303 node.SetTitle(UTF8ToWide("title2"));
2304 }
2305 EXPECT_TRUE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2306 }
2307
2308 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2309 // bookmarks when we write the same data, but does set it when we write new
2310 // data.
2311 TEST_F(SyncManagerTest, SetBookmarkTitleWithEncryption) {
2312 std::string client_tag = "title";
2313 sync_pb::EntitySpecifics entity_specifics;
2314 entity_specifics.mutable_bookmark()->set_url("url");
2315 entity_specifics.mutable_bookmark()->set_title("title");
2316 MakeServerNode(sync_manager_.GetUserShare(), syncable::BOOKMARKS, client_tag,
2317 BaseNode::GenerateSyncableHash(syncable::BOOKMARKS,
2318 client_tag),
2319 entity_specifics);
2320 // New node shouldn't start off unsynced.
2321 EXPECT_FALSE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2322
2323 // Encrypt the datatatype, should set is_unsynced.
2324 EXPECT_CALL(observer_,
2325 OnEncryptedTypesChanged(
2326 HasModelTypes(syncable::ModelTypeSet::All()), true));
2327 EXPECT_CALL(observer_, OnEncryptionComplete());
2328 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2329 sync_manager_.RefreshNigori(kTestChromeVersion, base::Bind(&DoNothing));
2330 PumpLoop();
2331 EXPECT_TRUE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2332
2333 // Manually change to the same title. Should not set is_unsynced.
2334 // NON_UNIQUE_NAME should be kEncryptedString.
2335 {
2336 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2337 WriteNode node(&trans);
2338 EXPECT_EQ(BaseNode::INIT_OK,
2339 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2340 node.SetTitle(UTF8ToWide(client_tag));
2341 const syncable::Entry* node_entry = node.GetEntry();
2342 const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS);
2343 EXPECT_TRUE(specifics.has_encrypted());
2344 EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME));
2345 }
2346 EXPECT_FALSE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2347
2348 // Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME
2349 // should still be kEncryptedString.
2350 {
2351 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2352 WriteNode node(&trans);
2353 EXPECT_EQ(BaseNode::INIT_OK,
2354 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2355 node.SetTitle(UTF8ToWide("title2"));
2356 const syncable::Entry* node_entry = node.GetEntry();
2357 const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS);
2358 EXPECT_TRUE(specifics.has_encrypted());
2359 EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME));
2360 }
2361 EXPECT_TRUE(ResetUnsyncedEntry(syncable::BOOKMARKS, client_tag));
2362 }
2363
2364 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks
2365 // when we write the same data, but does set it when we write new data.
2366 TEST_F(SyncManagerTest, SetNonBookmarkTitle) {
2367 std::string client_tag = "title";
2368 sync_pb::EntitySpecifics entity_specifics;
2369 entity_specifics.mutable_preference()->set_name("name");
2370 entity_specifics.mutable_preference()->set_value("value");
2371 MakeServerNode(sync_manager_.GetUserShare(),
2372 syncable::PREFERENCES,
2373 client_tag,
2374 BaseNode::GenerateSyncableHash(syncable::PREFERENCES,
2375 client_tag),
2376 entity_specifics);
2377 // New node shouldn't start off unsynced.
2378 EXPECT_FALSE(ResetUnsyncedEntry(syncable::PREFERENCES, client_tag));
2379
2380 // Manually change to the same title. Should not set is_unsynced.
2381 {
2382 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2383 WriteNode node(&trans);
2384 EXPECT_EQ(BaseNode::INIT_OK,
2385 node.InitByClientTagLookup(syncable::PREFERENCES, client_tag));
2386 node.SetTitle(UTF8ToWide(client_tag));
2387 }
2388 EXPECT_FALSE(ResetUnsyncedEntry(syncable::PREFERENCES, client_tag));
2389
2390 // Manually change to new title. Should set is_unsynced.
2391 {
2392 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2393 WriteNode node(&trans);
2394 EXPECT_EQ(BaseNode::INIT_OK,
2395 node.InitByClientTagLookup(syncable::PREFERENCES, client_tag));
2396 node.SetTitle(UTF8ToWide("title2"));
2397 }
2398 EXPECT_TRUE(ResetUnsyncedEntry(syncable::PREFERENCES, client_tag));
2399 }
2400
2401 // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted
2402 // non-bookmarks when we write the same data or when we write new data
2403 // data (should remained kEncryptedString).
2404 TEST_F(SyncManagerTest, SetNonBookmarkTitleWithEncryption) {
2405 std::string client_tag = "title";
2406 sync_pb::EntitySpecifics entity_specifics;
2407 entity_specifics.mutable_preference()->set_name("name");
2408 entity_specifics.mutable_preference()->set_value("value");
2409 MakeServerNode(sync_manager_.GetUserShare(),
2410 syncable::PREFERENCES,
2411 client_tag,
2412 BaseNode::GenerateSyncableHash(syncable::PREFERENCES,
2413 client_tag),
2414 entity_specifics);
2415 // New node shouldn't start off unsynced.
2416 EXPECT_FALSE(ResetUnsyncedEntry(syncable::PREFERENCES, client_tag));
2417
2418 // Encrypt the datatatype, should set is_unsynced.
2419 EXPECT_CALL(observer_,
2420 OnEncryptedTypesChanged(
2421 HasModelTypes(syncable::ModelTypeSet::All()), true));
2422 EXPECT_CALL(observer_, OnEncryptionComplete());
2423 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION));
2424 sync_manager_.RefreshNigori(kTestChromeVersion, base::Bind(&DoNothing));
2425 PumpLoop();
2426 EXPECT_TRUE(ResetUnsyncedEntry(syncable::PREFERENCES, client_tag));
2427
2428 // Manually change to the same title. Should not set is_unsynced.
2429 // NON_UNIQUE_NAME should be kEncryptedString.
2430 {
2431 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2432 WriteNode node(&trans);
2433 EXPECT_EQ(BaseNode::INIT_OK,
2434 node.InitByClientTagLookup(syncable::PREFERENCES, client_tag));
2435 node.SetTitle(UTF8ToWide(client_tag));
2436 const syncable::Entry* node_entry = node.GetEntry();
2437 const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS);
2438 EXPECT_TRUE(specifics.has_encrypted());
2439 EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME));
2440 }
2441 EXPECT_FALSE(ResetUnsyncedEntry(syncable::PREFERENCES, client_tag));
2442
2443 // Manually change to new title. Should not set is_unsynced because the
2444 // NON_UNIQUE_NAME should still be kEncryptedString.
2445 {
2446 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2447 WriteNode node(&trans);
2448 EXPECT_EQ(BaseNode::INIT_OK,
2449 node.InitByClientTagLookup(syncable::PREFERENCES, client_tag));
2450 node.SetTitle(UTF8ToWide("title2"));
2451 const syncable::Entry* node_entry = node.GetEntry();
2452 const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS);
2453 EXPECT_TRUE(specifics.has_encrypted());
2454 EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME));
2455 EXPECT_FALSE(node_entry->Get(IS_UNSYNCED));
2456 }
2457 }
2458
2459 // Create an encrypted entry when the cryptographer doesn't think the type is
2460 // marked for encryption. Ensure reads/writes don't break and don't unencrypt
2461 // the data.
2462 TEST_F(SyncManagerTest, SetPreviouslyEncryptedSpecifics) {
2463 std::string client_tag = "tag";
2464 std::string url = "url";
2465 std::string url2 = "new_url";
2466 std::string title = "title";
2467 sync_pb::EntitySpecifics entity_specifics;
2468 EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION));
2469 {
2470 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2471 browser_sync::Cryptographer* crypto = trans.GetCryptographer();
2472 sync_pb::EntitySpecifics bm_specifics;
2473 bm_specifics.mutable_bookmark()->set_title("title");
2474 bm_specifics.mutable_bookmark()->set_url("url");
2475 sync_pb::EncryptedData encrypted;
2476 crypto->Encrypt(bm_specifics, &encrypted);
2477 entity_specifics.mutable_encrypted()->CopyFrom(encrypted);
2478 syncable::AddDefaultFieldValue(syncable::BOOKMARKS, &entity_specifics);
2479 }
2480 MakeServerNode(sync_manager_.GetUserShare(), syncable::BOOKMARKS, client_tag,
2481 BaseNode::GenerateSyncableHash(syncable::BOOKMARKS,
2482 client_tag),
2483 entity_specifics);
2484
2485 {
2486 // Verify the data.
2487 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2488 ReadNode node(&trans);
2489 EXPECT_EQ(BaseNode::INIT_OK,
2490 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2491 EXPECT_EQ(title, node.GetTitle());
2492 EXPECT_EQ(GURL(url), node.GetURL());
2493 }
2494
2495 {
2496 // Overwrite the url (which overwrites the specifics).
2497 WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2498 WriteNode node(&trans);
2499 EXPECT_EQ(BaseNode::INIT_OK,
2500 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2501 node.SetURL(GURL(url2));
2502 }
2503
2504 {
2505 // Verify it's still encrypted and it has the most recent url.
2506 ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare());
2507 ReadNode node(&trans);
2508 EXPECT_EQ(BaseNode::INIT_OK,
2509 node.InitByClientTagLookup(syncable::BOOKMARKS, client_tag));
2510 EXPECT_EQ(title, node.GetTitle());
2511 EXPECT_EQ(GURL(url2), node.GetURL());
2512 const syncable::Entry* node_entry = node.GetEntry();
2513 EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME));
2514 const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS);
2515 EXPECT_TRUE(specifics.has_encrypted());
2516 }
2517 }
2518
2519 } // namespace browser_sync
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698