File: floating_sso_sync_bridge_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (532 lines) | stat: -rw-r--r-- 22,777 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/floating_sso/floating_sso_sync_bridge.h"

#include <map>
#include <memory>
#include <optional>

#include "base/barrier_closure.h"
#include "base/test/protobuf_matchers.h"
#include "base/test/run_until.h"
#include "base/test/task_environment.h"
#include "base/test/test_future.h"
#include "base/time/time.h"
#include "chrome/browser/ash/floating_sso/cookie_sync_conversions.h"
#include "chrome/browser/ash/floating_sso/cookie_sync_test_util.h"
#include "components/sync/model/data_batch.h"
#include "components/sync/model/data_type_store.h"
#include "components/sync/model/model_error.h"
#include "components/sync/protocol/cookie_specifics.pb.h"
#include "components/sync/protocol/entity_data.h"
#include "components/sync/test/data_type_store_test_util.h"
#include "components/sync/test/mock_data_type_local_change_processor.h"
#include "net/cookies/canonical_cookie.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace ash::floating_sso {

namespace {

using testing::_;
using testing::SizeIs;

// Simple value for tests which only use keys, but not CookieSpecifics.
constexpr char kKeyForTests[] = "test_key_value";

// Key and name which are distinct from other predefined test keys and names.
constexpr char kNewUniqueKey[] =
    "https://toplevelsite.comtrueNewNamewww.example.com/baz219";
constexpr char kNewName[] = "NewName";

class MockBridgeObserver : public FloatingSsoSyncBridge::Observer {
 public:
  MOCK_METHOD(void,
              OnCookiesAddedOrUpdatedRemotely,
              (const std::vector<net::CanonicalCookie>&),
              (override));

  MOCK_METHOD(void,
              OnCookiesRemovedRemotely,
              (const std::vector<net::CanonicalCookie>&),
              (override));
};

void CommitToStoreAndWait(
    syncer::DataTypeStore* store,
    std::unique_ptr<syncer::DataTypeStore::WriteBatch> batch) {
  base::test::TestFuture<const std::optional<syncer::ModelError>&> future;

  store->CommitWriteBatch(std::move(batch), future.GetCallback());
  const std::optional<syncer::ModelError>& error = future.Get();
  EXPECT_FALSE(error.has_value()) << error->ToString();
}

}  // namespace

class FloatingSsoSyncBridgeTest : public testing::Test {
 public:
  void SetUp() override {
    // Create a sync bridge with an in-memory store for testing.
    store_ = syncer::DataTypeStoreTestUtil::CreateInMemoryStoreForTest();
    bridge_ = std::make_unique<FloatingSsoSyncBridge>(
        processor_.CreateForwardingProcessor(),
        syncer::DataTypeStoreTestUtil::FactoryForForwardingStore(store_.get()));

    // Add some initial data to the store, and cache it in `initial_specifics`
    // to later verify that it ended up being in the store.
    std::vector<sync_pb::CookieSpecifics> initial_specifics;
    base::Time creation_time = base::Time::Now();
    for (size_t i = 0; i < kNamesForTests.size(); ++i) {
      initial_specifics.push_back(
          CreatePredefinedCookieSpecificsForTest(i, creation_time));
      std::unique_ptr<net::CanonicalCookie> cookie =
          FromSyncProto(initial_specifics[i]);
      ASSERT_TRUE(cookie);
      bridge_->AddOrUpdateCookie(*cookie);
    }

    // Wait until the bridge finishes reading initial data from the store.
    ASSERT_TRUE(base::test::RunUntil([&bridge = bridge_]() {
      return bridge->IsInitialDataReadFinishedForTest();
    }));

    // Check that the store contains the data we've added there.
    const auto& entries = bridge().CookieSpecificsInStore();
    ASSERT_EQ(entries.size(), kNamesForTests.size());
    for (size_t i = 0; i < kNamesForTests.size(); ++i) {
      ASSERT_THAT(entries.at(kUniqueKeysForTests[i]),
                  base::test::EqualsProto(initial_specifics[i]));
    }
    bridge_->AddObserver(&mock_observer_);
  }

  FloatingSsoSyncBridge& bridge() { return *bridge_; }
  syncer::MockDataTypeLocalChangeProcessor& processor() { return processor_; }
  MockBridgeObserver& mock_observer() { return mock_observer_; }

 private:
  testing::NiceMock<syncer::MockDataTypeLocalChangeProcessor> processor_;
  base::test::SingleThreadTaskEnvironment task_environment_;
  std::unique_ptr<syncer::DataTypeStore> store_;
  std::unique_ptr<FloatingSsoSyncBridge> bridge_;
  testing::NiceMock<MockBridgeObserver> mock_observer_;
};

TEST_F(FloatingSsoSyncBridgeTest, GetStorageKey) {
  syncer::EntityData entity;
  entity.specifics.mutable_cookie()->set_unique_key(kKeyForTests);
  EXPECT_EQ(kKeyForTests, bridge().GetStorageKey(entity));
}

TEST_F(FloatingSsoSyncBridgeTest, GetClientTag) {
  syncer::EntityData entity;
  entity.specifics.mutable_cookie()->set_unique_key(kKeyForTests);
  EXPECT_EQ(kKeyForTests, bridge().GetClientTag(entity));
}

TEST_F(FloatingSsoSyncBridgeTest, GetDataForCommit) {
  std::unique_ptr<syncer::DataBatch> data_batch = bridge().GetDataForCommit(
      {kUniqueKeysForTests[1], kUniqueKeysForTests[3]});
  ASSERT_TRUE(data_batch);

  const auto& entries = bridge().CookieSpecificsInStore();
  for (size_t i : {1, 3}) {
    ASSERT_TRUE(data_batch->HasNext());
    syncer::KeyAndData key_and_data = data_batch->Next();
    EXPECT_EQ(kUniqueKeysForTests[i], key_and_data.first);
    EXPECT_EQ(kUniqueKeysForTests[i], key_and_data.second->name);
    EXPECT_THAT(key_and_data.second->specifics.cookie(),
                base::test::EqualsProto(entries.at(key_and_data.first)));
  }
  // Batch should have no other elements except for the two handled above.
  EXPECT_FALSE(data_batch->HasNext());
}

TEST_F(FloatingSsoSyncBridgeTest, GetDataForDebugging) {
  std::unique_ptr<syncer::DataBatch> data_batch =
      bridge().GetAllDataForDebugging();
  ASSERT_TRUE(data_batch);
  const auto& entries = bridge().CookieSpecificsInStore();
  size_t batch_size = 0;
  // Check that `data_batch` and `entries` contain the same data.
  while (data_batch->HasNext()) {
    batch_size += 1;
    const syncer::KeyAndData key_and_data = data_batch->Next();
    auto it = entries.find(key_and_data.first);
    ASSERT_NE(it, entries.end());
    EXPECT_EQ(key_and_data.second->name, it->first);
    EXPECT_THAT(key_and_data.second->specifics.cookie(),
                base::test::EqualsProto(it->second));
  }
  EXPECT_EQ(batch_size, entries.size());
}

// Verify that local data doesn't change after applying an incremental change
// with an empty change list.
TEST_F(FloatingSsoSyncBridgeTest, ApplyEmptyChange) {
  auto initial_entries_copy = bridge().CookieSpecificsInStore();
  EXPECT_CALL(mock_observer(), OnCookiesAddedOrUpdatedRemotely(_)).Times(0);
  EXPECT_CALL(mock_observer(), OnCookiesRemovedRemotely(_)).Times(0);
  bridge().ApplyIncrementalSyncChanges(bridge().CreateMetadataChangeList(),
                                       syncer::EntityChangeList());
  const auto& current_entries = bridge().CookieSpecificsInStore();
  EXPECT_EQ(initial_entries_copy.size(), current_entries.size());
  for (const auto& [key, specifics] : current_entries) {
    EXPECT_THAT(specifics,
                base::test::EqualsProto(initial_entries_copy.at(key)));
  }
}

TEST_F(FloatingSsoSyncBridgeTest, IncrementalDeleteAndAdd) {
  const auto& entries = bridge().CookieSpecificsInStore();
  size_t initial_size = entries.size();
  ASSERT_TRUE(entries.contains(kUniqueKeysForTests[0]));

  // Delete the first entity.
  syncer::EntityChangeList delete_first;
  delete_first.push_back(syncer::EntityChange::CreateDelete(
      kUniqueKeysForTests[0], syncer::EntityData()));
  EXPECT_CALL(mock_observer(), OnCookiesRemovedRemotely(SizeIs(1)));
  EXPECT_CALL(mock_observer(), OnCookiesAddedOrUpdatedRemotely(_)).Times(0);
  bridge().ApplyIncrementalSyncChanges(bridge().CreateMetadataChangeList(),
                                       std::move(delete_first));
  EXPECT_EQ(entries.size(), initial_size - 1);
  EXPECT_FALSE(entries.contains(kUniqueKeysForTests[0]));

  // Add the entity back.
  syncer::EntityChangeList add_first;
  const sync_pb::CookieSpecifics cookie_proto =
      CreatePredefinedCookieSpecificsForTest(
          0, /*creation_time=*/base::Time::Now());
  add_first.push_back(syncer::EntityChange::CreateAdd(
      kUniqueKeysForTests[0], CreateEntityDataForTest(cookie_proto)));
  EXPECT_CALL(mock_observer(), OnCookiesRemovedRemotely(_)).Times(0);
  EXPECT_CALL(mock_observer(), OnCookiesAddedOrUpdatedRemotely(SizeIs(1)));
  bridge().ApplyIncrementalSyncChanges(bridge().CreateMetadataChangeList(),
                                       std::move(add_first));
  EXPECT_EQ(entries.size(), initial_size);
  EXPECT_TRUE(entries.contains(kUniqueKeysForTests[0]));
  EXPECT_THAT(entries.at(kUniqueKeysForTests[0]),
              base::test::EqualsProto(cookie_proto));
}

TEST_F(FloatingSsoSyncBridgeTest, IncrementalUpdate) {
  auto initial_entries_copy = bridge().CookieSpecificsInStore();
  ASSERT_TRUE(initial_entries_copy.contains(kUniqueKeysForTests[0]));

  // Update the first entity.
  syncer::EntityChangeList update;
  sync_pb::CookieSpecifics updated_specifics =
      CreatePredefinedCookieSpecificsForTest(
          0, /*creation_time=*/base::Time::Now());
  updated_specifics.set_value("UpdatedValue");
  // Make sure that `updated_specifics` is not equal to the proto we had
  // initially.
  ASSERT_THAT(initial_entries_copy.at(kUniqueKeysForTests[0]),
              testing::Not(base::test::EqualsProto(updated_specifics)));
  update.push_back(syncer::EntityChange::CreateUpdate(
      kUniqueKeysForTests[0], CreateEntityDataForTest(updated_specifics)));

  EXPECT_CALL(mock_observer(), OnCookiesAddedOrUpdatedRemotely(SizeIs(1)));
  EXPECT_CALL(mock_observer(), OnCookiesRemovedRemotely(_)).Times(0);

  bridge().ApplyIncrementalSyncChanges(bridge().CreateMetadataChangeList(),
                                       std::move(update));

  // Check that the first entry got updated while others remained the same.
  const auto& current_entries = bridge().CookieSpecificsInStore();
  EXPECT_EQ(initial_entries_copy.size(), current_entries.size());
  for (const auto& [key, specifics] : current_entries) {
    EXPECT_THAT(specifics,
                base::test::EqualsProto(key == kUniqueKeysForTests[0]
                                            ? updated_specifics
                                            : initial_entries_copy.at(key)));
  }
}

TEST_F(FloatingSsoSyncBridgeTest, ServerAsksToDeleteNonPresentCookie) {
  auto initial_entries_copy = bridge().CookieSpecificsInStore();

  // Create a change asking to delete a cookie which is not present in the
  // store.
  syncer::EntityChangeList change_list;
  change_list.push_back(syncer::EntityChange::CreateDelete(
      "key not present in the store", syncer::EntityData()));
  // Expect that we are not passing a deletion to observers in case when
  // there is nothing to delete.
  EXPECT_CALL(mock_observer(), OnCookiesRemovedRemotely(_)).Times(0);
  EXPECT_CALL(mock_observer(), OnCookiesAddedOrUpdatedRemotely(_)).Times(0);
  bridge().ApplyIncrementalSyncChanges(bridge().CreateMetadataChangeList(),
                                       std::move(change_list));

  // Check that store hasn't changed.
  const auto& current_entries = bridge().CookieSpecificsInStore();
  EXPECT_EQ(current_entries.size(), initial_entries_copy.size());
  EXPECT_EQ(initial_entries_copy.size(), current_entries.size());
  for (const auto& [key, specifics] : current_entries) {
    EXPECT_THAT(specifics,
                base::test::EqualsProto(initial_entries_copy.at(key)));
  }
}

TEST_F(FloatingSsoSyncBridgeTest, MergeFullSyncData) {
  auto initial_entries_copy = bridge().CookieSpecificsInStore();

  // This test future is used to check that `MergeFullSyncData` triggers the
  // callback set via `SetOnMergeFullSyncDataCallback`.
  base::test::TestFuture<void> merge_full_sync_data_future;
  bridge().SetOnMergeFullSyncDataCallback(
      merge_full_sync_data_future.GetCallback());

  // This should make us prefer the local version of the cookie with the given
  // key during conflict resolution in
  // `FloatingSsoSyncBridge::MergeFullSyncData`;
  bridge().AddToLocallyPreferredCookies(kUniqueKeysForTests[1]);

  constexpr char kNewValue[] = "NewRemoteValue";
  syncer::EntityChangeList remote_entities;

  // Remote cookie which should update a corresponding locally stored cookie.
  sync_pb::CookieSpecifics updated_cookie =
      CreatePredefinedCookieSpecificsForTest(
          0, /*creation_time=*/base::Time::Now());
  ASSERT_NE(updated_cookie.value(), kNewValue);
  updated_cookie.set_value(kNewValue);
  remote_entities.push_back(syncer::EntityChange::CreateAdd(
      kUniqueKeysForTests[0], CreateEntityDataForTest(updated_cookie)));

  // Remote cookie which should not update a corresponding locally stored
  // cookie.
  sync_pb::CookieSpecifics rejected_remote_cookie_update =
      CreatePredefinedCookieSpecificsForTest(
          1, /*creation_time=*/base::Time::Now());
  ASSERT_NE(rejected_remote_cookie_update.value(), kNewValue);
  rejected_remote_cookie_update.set_value(kNewValue);
  remote_entities.push_back(syncer::EntityChange::CreateAdd(
      kUniqueKeysForTests[1],
      CreateEntityDataForTest(rejected_remote_cookie_update)));

  // Remote cookie which should be completely new for the client.
  sync_pb::CookieSpecifics new_remote_cookie = CreateCookieSpecificsForTest(
      kNewUniqueKey, kNewName, /*creation_time=*/base::Time::Now());
  // Make sure this key is not present locally.
  ASSERT_FALSE(initial_entries_copy.contains(new_remote_cookie.unique_key()));
  remote_entities.push_back(syncer::EntityChange::CreateAdd(
      new_remote_cookie.unique_key(),
      CreateEntityDataForTest(new_remote_cookie)));

  // Expect the following local cookies to be sent to Sync server.
  EXPECT_CALL(processor(), Put(kUniqueKeysForTests[1], _, _));
  EXPECT_CALL(processor(), Put(kUniqueKeysForTests[2], _, _));
  EXPECT_CALL(processor(), Put(kUniqueKeysForTests[3], _, _));

  EXPECT_CALL(mock_observer(), OnCookiesAddedOrUpdatedRemotely(SizeIs(2)));
  EXPECT_CALL(mock_observer(), OnCookiesRemovedRemotely(_)).Times(0);

  bridge().MergeFullSyncData(bridge().CreateMetadataChangeList(),
                             std::move(remote_entities));

  const auto& current_local_entries = bridge().CookieSpecificsInStore();
  // Expect one new entry and one updated entry, the rest should be the same as
  // before.
  EXPECT_EQ(current_local_entries.size(), initial_entries_copy.size() + 1);
  for (const auto& [key, specifics] : current_local_entries) {
    if (key == kNewUniqueKey) {
      EXPECT_THAT(specifics, base::test::EqualsProto(new_remote_cookie));
    } else if (key == kUniqueKeysForTests[0]) {
      EXPECT_THAT(specifics, base::test::EqualsProto(updated_cookie));
    } else {
      EXPECT_THAT(specifics,
                  base::test::EqualsProto(initial_entries_copy.at(key)));
    }
  }
  EXPECT_TRUE(merge_full_sync_data_future.Wait());
}

TEST_F(FloatingSsoSyncBridgeTest, MergeFullSyncDataCallbackSetLate) {
  syncer::EntityChangeList remote_entities;
  // Some cookie - this test doesn't care about specific cookie values.
  sync_pb::CookieSpecifics new_remote_cookie = CreateCookieSpecificsForTest(
      kNewUniqueKey, kNewName, /*creation_time=*/base::Time::Now());
  remote_entities.push_back(syncer::EntityChange::CreateAdd(
      new_remote_cookie.unique_key(),
      CreateEntityDataForTest(new_remote_cookie)));

  bridge().MergeFullSyncData(bridge().CreateMetadataChangeList(),
                             std::move(remote_entities));

  // Check that the callback set via `SetOnMergeFullSyncDataCallback` will be
  // called even when we set the callback after `MergeFullSyncData` was already
  // executed.
  base::test::TestFuture<void> merge_full_sync_data_future;
  bridge().SetOnMergeFullSyncDataCallback(
      merge_full_sync_data_future.GetCallback());
  EXPECT_TRUE(merge_full_sync_data_future.Wait());
}

TEST_F(FloatingSsoSyncBridgeTest, AddOrUpdateCookie) {
  auto initial_entries_copy = bridge().CookieSpecificsInStore();
  ASSERT_TRUE(initial_entries_copy.contains(kUniqueKeysForTests[0]));

  // Update the first entity.
  sync_pb::CookieSpecifics updated_specifics =
      CreatePredefinedCookieSpecificsForTest(
          0, /*creation_time=*/base::Time::Now());
  constexpr char kUpdatedValue[] = "UpdatedValue";
  updated_specifics.set_value(kUpdatedValue);

  // Check that the updated entry will be sent to the Sync server.
  EXPECT_CALL(processor(), Put(kUniqueKeysForTests[0], _, _));

  std::unique_ptr<net::CanonicalCookie> updated_cookie =
      FromSyncProto(updated_specifics);
  ASSERT_TRUE(updated_cookie);
  bridge().AddOrUpdateCookie(*updated_cookie);

  // Check that repeated attempt to add the same cookie will not result in a
  // change sent to the Sync server.
  EXPECT_CALL(processor(), Put(kUniqueKeysForTests[0], _, _)).Times(0);
  bridge().AddOrUpdateCookie(*updated_cookie);

  // Check that the first entry got updated while others remained the same.
  auto current_entries = bridge().CookieSpecificsInStore();
  EXPECT_EQ(initial_entries_copy.size(), current_entries.size());

  for (const auto& [key, specifics] : current_entries) {
    EXPECT_EQ(specifics.value(), key == kUniqueKeysForTests[0]
                                     ? kUpdatedValue
                                     : initial_entries_copy.at(key).value());
  }

  // Add new entry.
  sync_pb::CookieSpecifics new_specifics = CreateCookieSpecificsForTest(
      kNewUniqueKey, kNewName, /*creation_time=*/base::Time::Now());

  // Check that the new entry will be sent to the Sync server.
  EXPECT_CALL(processor(), Put(kNewUniqueKey, _, _));

  std::unique_ptr<net::CanonicalCookie> new_cookie =
      FromSyncProto(new_specifics);
  ASSERT_TRUE(new_cookie);
  bridge().AddOrUpdateCookie(*new_cookie);

  // Check that a new entry was added.
  current_entries = bridge().CookieSpecificsInStore();
  EXPECT_EQ(initial_entries_copy.size() + 1, current_entries.size());
  EXPECT_TRUE(current_entries.contains(kNewUniqueKey));

  // Check current entries.
  for (const auto& [key, specifics] : current_entries) {
    EXPECT_EQ(specifics.name(), key == kNewUniqueKey
                                    ? kNewName
                                    : initial_entries_copy.at(key).name());
  }
}

TEST_F(FloatingSsoSyncBridgeTest, DeleteCookie) {
  auto initial_entries_copy = bridge().CookieSpecificsInStore();
  ASSERT_TRUE(initial_entries_copy.contains(kUniqueKeysForTests[0]));

  // Check that the entry deletion will be sent to the Sync server.
  EXPECT_CALL(processor(), Delete(kUniqueKeysForTests[0], _, _));

  // Delete the first entity.
  std::unique_ptr<net::CanonicalCookie> first_cookie =
      FromSyncProto(initial_entries_copy[kUniqueKeysForTests[0]]);
  ASSERT_TRUE(first_cookie);
  bridge().DeleteCookie(*first_cookie);

  // Check that the first entry was deleted.
  const auto& current_entries = bridge().CookieSpecificsInStore();
  EXPECT_EQ(initial_entries_copy.size() - 1, current_entries.size());

  // Check that repeated attempt to delete the same cookie will not result in a
  // change sent to the Sync server.
  EXPECT_CALL(processor(), Delete(kUniqueKeysForTests[0], _, _)).Times(0);
  bridge().DeleteCookie(*first_cookie);

  // Check current entries.
  EXPECT_FALSE(current_entries.contains(kUniqueKeysForTests[0]));
  EXPECT_TRUE(current_entries.contains(kUniqueKeysForTests[1]));
  EXPECT_TRUE(current_entries.contains(kUniqueKeysForTests[2]));
  EXPECT_TRUE(current_entries.contains(kUniqueKeysForTests[3]));
}

TEST(FloatingSsoSyncBridgeInitialization, EventsWhileStoreIsLoading) {
  base::test::SingleThreadTaskEnvironment task_environment;
  testing::NiceMock<syncer::MockDataTypeLocalChangeProcessor> processor;
  auto store = syncer::DataTypeStoreTestUtil::CreateInMemoryStoreForTest();

  // Add a cookie to the store so that we can delete it later.
  std::unique_ptr<syncer::DataTypeStore::WriteBatch> batch =
      store->CreateWriteBatch();
  sync_pb::CookieSpecifics delete_specifics =
      CreatePredefinedCookieSpecificsForTest(
          0, /*creation_time=*/base::Time::Now());
  batch->WriteData(delete_specifics.unique_key(),
                   delete_specifics.SerializeAsString());
  CommitToStoreAndWait(store.get(), std::move(batch));

  base::test::TestFuture<syncer::DataType, syncer::DataTypeStore::InitCallback>
      store_future;

  // Create a bridge.
  auto bridge = std::make_unique<FloatingSsoSyncBridge>(
      processor.CreateForwardingProcessor(), store_future.GetCallback());

  // Delete already existing item from store.
  std::unique_ptr<net::CanonicalCookie> delete_cookie =
      FromSyncProto(delete_specifics);
  ASSERT_TRUE(delete_cookie);
  bridge->DeleteCookie(*delete_cookie);

  // Add a cookie before the store is initialized to test the queue.
  sync_pb::CookieSpecifics add_specifics =
      CreatePredefinedCookieSpecificsForTest(
          1, /*creation_time=*/base::Time::Now());
  // Used for waiting for the two store commits to be finalized.
  base::test::TestFuture<void> commit_future;
  bridge->SetOnStoreCommitCallbackForTest(base::BarrierClosure(
      /*num_callbacks=*/2, commit_future.GetRepeatingCallback()));
  std::unique_ptr<net::CanonicalCookie> add_cookie =
      FromSyncProto(add_specifics);
  ASSERT_TRUE(add_cookie);
  bridge->AddOrUpdateCookie(*add_cookie);

  // Add another cookie and remove it from the queue before the store
  // initializes.
  sync_pb::CookieSpecifics new_specifics = CreateCookieSpecificsForTest(
      kNewUniqueKey, kNewName, /*creation_time=*/base::Time::Now());
  std::unique_ptr<net::CanonicalCookie> new_cookie =
      FromSyncProto(new_specifics);
  ASSERT_TRUE(new_cookie);
  bridge->AddOrUpdateCookie(*new_cookie);
  bridge->DeleteCookie(*new_cookie);

  auto [type, callback] = store_future.Take();
  // Trigger OnStoreCreated().
  std::move(callback).Run(
      /*error=*/std::nullopt, std::move(store));

  // Wait until the bridge finishes reading initial data from the store.
  ASSERT_TRUE(base::test::RunUntil([&bridge_internal = bridge]() {
    return bridge_internal->IsInitialDataReadFinishedForTest();
  }));

  // Wait for commits.
  commit_future.Get();

  // Check that there is just kUniqueKeysForTests[0] in the store and the other
  // cookie was not added.
  const auto& current_entries = bridge->CookieSpecificsInStore();
  EXPECT_EQ(1u, current_entries.size());
  EXPECT_TRUE(current_entries.contains(kUniqueKeysForTests[1]));
  EXPECT_FALSE(current_entries.contains(kUniqueKeysForTests[0]));
  EXPECT_FALSE(current_entries.contains(kNewUniqueKey));
}

}  // namespace ash::floating_sso