File: sync_handler.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 (272 lines) | stat: -rw-r--r-- 9,878 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
// Copyright 2023 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/ui/webui/password_manager/sync_handler.h"

#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/sync/sync_service_factory.h"
#include "chrome/browser/sync/sync_ui_util.h"
#include "components/password_manager/core/browser/features/password_manager_features_util.h"
#include "components/sync/base/data_type.h"
#include "components/sync/service/sync_service.h"
#include "components/sync/service/sync_service_utils.h"
#include "components/sync/service/sync_user_settings.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/webui/web_ui_util.h"

#if BUILDFLAG(ENABLE_DICE_SUPPORT)
#include "chrome/browser/profiles/batch_upload/batch_upload_service.h"
#include "chrome/browser/profiles/batch_upload/batch_upload_service_factory.h"
#include "chrome/browser/ui/browser_finder.h"
#endif

namespace password_manager {

#if BUILDFLAG(ENABLE_DICE_SUPPORT)
namespace {

// Entry points to the Batch Upload dialog in the passwords settings section.
// It is a subset of the entry points in `BatchUploadService::EntryPoint`.
// WARNING: Keep synced with
// chrome/browser/resources/password_manager/sync_browser_proxy.ts.
enum class BatchUploadPasswordsEntryPoint {
  kPasswordManager = 0,
  kPromoCard = 1,

  kMaxValue = kPromoCard,
};

BatchUploadService::EntryPoint ToBatchUploadEntryPoint(
    BatchUploadPasswordsEntryPoint password_entry_point) {
  switch (password_entry_point) {
    case BatchUploadPasswordsEntryPoint::kPasswordManager:
      return BatchUploadService::EntryPoint::kPasswordManagerSettings;
    case BatchUploadPasswordsEntryPoint::kPromoCard:
      return BatchUploadService::EntryPoint::kPasswordPromoCard;
  }
}

}  // namespace
#endif

using password_manager::features_util::ShouldShowAccountStorageSettingToggle;

SyncHandler::SyncHandler(Profile* profile) : profile_(profile) {}

SyncHandler::~SyncHandler() = default;

void SyncHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback(
      "GetSyncTrustedVaultBannerState",
      base::BindRepeating(&SyncHandler::HandleGetTrustedVaultBannerState,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "GetAccountInfo", base::BindRepeating(&SyncHandler::HandleGetAccountInfo,
                                            base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "GetSyncInfo", base::BindRepeating(&SyncHandler::HandleGetSyncInfo,
                                         base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "GetLocalPasswordCount",
      base::BindRepeating(&SyncHandler::HandleGetLocalPasswordCount,
                          base::Unretained(this)));
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
  web_ui()->RegisterMessageCallback(
      "OpenBatchUpload",
      base::BindRepeating(&SyncHandler::HandleOpenBatchUploadDialog,
                          base::Unretained(this)));
#endif
}

void SyncHandler::OnJavascriptAllowed() {
  // This is intentionally not using GetSyncService(), to go around the
  // Profile::IsSyncAllowed() check.
  syncer::SyncService* sync_service =
      SyncServiceFactory::GetForProfile(profile_);
  if (sync_service) {
    sync_service_observation_.Observe(sync_service);
  }

  signin::IdentityManager* identity_manager(
      IdentityManagerFactory::GetInstance()->GetForProfile(profile_));
  if (identity_manager) {
    identity_manager_observation_.Observe(identity_manager);
  }
}

void SyncHandler::OnJavascriptDisallowed() {
  sync_service_observation_.Reset();
  identity_manager_observation_.Reset();
  weak_ptr_factory_.InvalidateWeakPtrs();
}

base::Value SyncHandler::GetTrustedVaultBannerState() const {
  syncer::SyncService* sync_service = GetSyncService();
  auto state = TrustedVaultBannerState::kNotShown;
  if (sync_service && sync_service->GetUserSettings()->GetPassphraseType() ==
                          syncer::PassphraseType::kTrustedVaultPassphrase) {
    state = TrustedVaultBannerState::kOptedIn;
  } else if (syncer::ShouldOfferTrustedVaultOptIn(sync_service)) {
    state = TrustedVaultBannerState::kOfferOptIn;
  }

  return base::Value(static_cast<int>(state));
}

void SyncHandler::HandleGetTrustedVaultBannerState(
    const base::Value::List& args) {
  AllowJavascript();
  CHECK_EQ(1U, args.size());
  const base::Value& callback_id = args[0];

  ResolveJavascriptCallback(callback_id, GetTrustedVaultBannerState());
}

base::Value::Dict SyncHandler::GetSyncInfo() const {
  base::Value::Dict dict;

  syncer::SyncService* sync_service = GetSyncService();
  // sync_service might be nullptr if SyncServiceFactory::IsSyncAllowed is
  // false.
  if (!sync_service) {
    return dict;
  }

  PrefService* pref_service = profile_->GetPrefs();
  syncer::UserSelectableTypeSet types =
      sync_service->GetUserSettings()->GetSelectedTypes();

  auto* identity_manager = IdentityManagerFactory::GetForProfile(profile_);
  dict.Set("isEligibleForAccountStorage",
           (!identity_manager->HasPrimaryAccount(signin::ConsentLevel::kSync) &&
            ShouldShowAccountStorageSettingToggle(pref_service, sync_service)));
  dict.Set("isSyncingPasswords",
           (sync_service->IsSyncFeatureEnabled() &&
            types.Has(syncer::UserSelectableType::kPasswords)));
  return dict;
}

void SyncHandler::HandleGetSyncInfo(const base::Value::List& args) {
  AllowJavascript();

  CHECK_EQ(1U, args.size());
  const base::Value& callback_id = args[0];

  ResolveJavascriptCallback(callback_id, GetSyncInfo());
}

base::Value::Dict SyncHandler::GetAccountInfo() const {
  signin::IdentityManager* identity_manager(
      IdentityManagerFactory::GetInstance()->GetForProfile(profile_));
  auto stored_account = identity_manager->FindExtendedAccountInfo(
      identity_manager->GetPrimaryAccountInfo(signin::ConsentLevel::kSignin));

  base::Value::Dict dict;
  dict.Set("email", stored_account.email);
  const auto& avatar_image = stored_account.account_image;
  if (!avatar_image.IsEmpty()) {
    dict.Set("avatarImage", webui::GetBitmapDataUrl(avatar_image.AsBitmap()));
  }
  return dict;
}

void SyncHandler::HandleGetAccountInfo(const base::Value::List& args) {
  AllowJavascript();
  CHECK_EQ(1U, args.size());
  const base::Value& callback_id = args[0];

  ResolveJavascriptCallback(callback_id, GetAccountInfo());
}

#if BUILDFLAG(ENABLE_DICE_SUPPORT)
void SyncHandler::HandleOpenBatchUploadDialog(const base::Value::List& args) {
  AllowJavascript();
  CHECK_EQ(1U, args.size());
  CHECK(args[0].is_int());
  int entry_point_int = args[0].GetInt();
  CHECK(entry_point_int >= 0 &&
        entry_point_int <=
            static_cast<int>(BatchUploadPasswordsEntryPoint::kMaxValue));

  BatchUploadService::EntryPoint entry_point = ToBatchUploadEntryPoint(
      static_cast<BatchUploadPasswordsEntryPoint>(entry_point_int));
  BatchUploadService* batch_upload =
      BatchUploadServiceFactory::GetForProfile(profile_);
  CHECK(batch_upload);
  batch_upload->OpenBatchUpload(chrome::FindBrowserWithProfile(profile_),
                                entry_point);
}
#endif

void SyncHandler::HandleGetLocalPasswordCount(const base::Value::List& args) {
  AllowJavascript();
  CHECK_EQ(1U, args.size());
  const base::Value& callback_id = args[0];

  syncer::SyncService* sync_service = GetSyncService();
  if (!sync_service) {
    ResolveJavascriptCallback(callback_id, base::Value(0));
    return;
  }

  sync_service->GetLocalDataDescriptions(
      {syncer::PASSWORDS},
      base::BindOnce(&SyncHandler::OnGetLocalDataDescriptionReceived,
                     weak_ptr_factory_.GetWeakPtr(), callback_id.Clone()));
}

void SyncHandler::OnStateChanged(syncer::SyncService* sync_service) {
  FireWebUIListener("trusted-vault-banner-state-changed",
                    GetTrustedVaultBannerState());
  FireWebUIListener("sync-info-changed", GetSyncInfo());

  // Only update when the `sync_service` is not configuring to avoid flickering
  // updates since the state can change between configuring and active multiple
  // times in a session.
  if (sync_service->GetTransportState() !=
      syncer::SyncService::TransportState::CONFIGURING) {
    sync_service->GetLocalDataDescriptions(
        {syncer::PASSWORDS},
        base::BindOnce(&SyncHandler::FireOnGetLocalDataDescriptionReceived,
                       weak_ptr_factory_.GetWeakPtr()));
  }
}

void SyncHandler::FireOnGetLocalDataDescriptionReceived(
    std::map<syncer::DataType, syncer::LocalDataDescription> data) {
  int local_password_count =
      data.contains(syncer::PASSWORDS)
          ? data[syncer::PASSWORDS].local_data_models.size()
          : 0;
  FireWebUIListener("sync-service-local-password-count",
                    base::Value(local_password_count));
}

void SyncHandler::OnGetLocalDataDescriptionReceived(
    base::Value callback_id,
    std::map<syncer::DataType, syncer::LocalDataDescription> data) {
  int local_password_count =
      data.contains(syncer::PASSWORDS)
          ? data[syncer::PASSWORDS].local_data_models.size()
          : 0;
  ResolveJavascriptCallback(callback_id, base::Value(local_password_count));
}

void SyncHandler::OnExtendedAccountInfoUpdated(const AccountInfo& info) {
  FireWebUIListener("stored-accounts-changed", GetAccountInfo());
}

void SyncHandler::OnExtendedAccountInfoRemoved(const AccountInfo& info) {
  FireWebUIListener("stored-accounts-changed", GetAccountInfo());
}

syncer::SyncService* SyncHandler::GetSyncService() const {
  return SyncServiceFactory::IsSyncAllowed(profile_)
             ? SyncServiceFactory::GetForProfile(profile_)
             : nullptr;
}

}  // namespace password_manager