summaryrefslogtreecommitdiffstats
path: root/chromium/components/commerce/core/account_checker.cc
blob: 161b5f706aea8ce96ef8dc6e5aa156111ed2a720 (plain)
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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/commerce/core/account_checker.h"
#include "base/feature_list.h"
#include "base/json/json_writer.h"
#include "base/json/values_util.h"
#include "base/values.h"
#include "components/commerce/core/commerce_feature_list.h"
#include "components/commerce/core/pref_names.h"
#include "components/endpoint_fetcher/endpoint_fetcher.h"
#include "components/prefs/pref_change_registrar.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/unified_consent/url_keyed_data_collection_consent_helper.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/data_decoder/public/cpp/data_decoder.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"

namespace {

const char kOAuthScope[] = "https://www.googleapis.com/auth/chromememex";
const char kOAuthName[] = "chromememex_svc";
const char kGetHttpMethod[] = "GET";
const char kPostHttpMethod[] = "POST";
const char kContentType[] = "application/json; charset=UTF-8";
const char kEmptyPostData[] = "";
const int64_t kTimeoutMs = 10000;

const char kNotificationsPrefUrl[] =
    "https://memex-pa.googleapis.com/v1/notifications/preferences";
const char kPriceTrackEmailPref[] = "price_track_email";
const char kPreferencesKey[] = "preferences";

}  // namespace

namespace commerce {

AccountChecker::AccountChecker(
    PrefService* pref_service,
    signin::IdentityManager* identity_manager,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
    : pref_service_(pref_service),
      identity_manager_(identity_manager),
      url_loader_factory_(url_loader_factory),
      weak_ptr_factory_(this) {
  if (identity_manager) {
    FetchWaaStatus();
    scoped_identity_manager_observation_.Observe(identity_manager);
  }
  // TODO(crbug.com/1366165): Avoid pushing the fetched pref value to the server
  // again.
  if (pref_service) {
    pref_change_registrar_ = std::make_unique<PrefChangeRegistrar>();
    pref_change_registrar_->Init(pref_service);
    pref_change_registrar_->Add(
        kPriceEmailNotificationsEnabled,
        base::BindRepeating(&AccountChecker::SendPriceEmailPref,
                            weak_ptr_factory_.GetWeakPtr()));
  }
}

AccountChecker::~AccountChecker() = default;

bool AccountChecker::IsSignedIn() {
  return identity_manager_ &&
         identity_manager_->HasPrimaryAccount(signin::ConsentLevel::kSync);
}

bool AccountChecker::IsAnonymizedUrlDataCollectionEnabled() {
  return pref_service_ &&
         unified_consent::UrlKeyedDataCollectionConsentHelper::
             NewAnonymizedDataCollectionConsentHelper(pref_service_)
                 ->IsEnabled();
}

bool AccountChecker::IsWebAndAppActivityEnabled() {
  return pref_service_ &&
         pref_service_->GetBoolean(kWebAndAppActivityEnabledForShopping);
}

void AccountChecker::OnPrimaryAccountChanged(
    const signin::PrimaryAccountChangeEvent& event_details) {
  FetchWaaStatus();
}

void AccountChecker::FetchWaaStatus() {
  // For now we need to update users' consent status on web and app activity
  // only when ShoppingList feature is enabled.
  if (!base::FeatureList::IsEnabled(kShoppingList) || !IsSignedIn())
    return;
  // TODO(crbug.com/1311754): These parameters (url, oauth_scope, etc.) are
  // copied from web_history_service.cc directly, it works now but we should
  // figure out a better way to keep these parameters in sync.
  const char waa_oauth_name[] = "web_history";
  const char waa_query_url[] =
      "https://history.google.com/history/api/lookup?client=web_app";
  const char waa_oauth_scope[] = "https://www.googleapis.com/auth/chromesync";
  const char waa_content_type[] = "application/json; charset=UTF-8";
  const char waa_get_method[] = "GET";
  const int64_t waa_timeout_ms = 30000;
  const char waa_post_data[] = "";
  net::NetworkTrafficAnnotationTag traffic_annotation =
      net::DefineNetworkTrafficAnnotation("chrome_commerce_waa_fetcher",
                                          R"(
        semantics {
          sender: "Chrome Shopping"
          description:
            "Check whether Web & App Activity is paused in My Google Activity."
            "If it is paused, some Chrome Shopping features such as Price "
            "Tracking Notifications become disabled."
          trigger:
            "On account checker initialization or every time after the user "
            "changes their primary account."
          data:
            "The request includes an OAuth2 token authenticating the user. The "
            "response includes a boolean indicating whether the feature is "
            "enabled."
          destination: GOOGLE_OWNED_SERVICE
        }
        policy {
          cookies_allowed: NO
          setting:
            "This fetch is only enabled for signed-in users. There's no "
            "direct Chromium's setting to disable this, but users can manage "
            "their preferences by visiting myactivity.google.com."
          chrome_policy {
            BrowserSignin {
              policy_options {mode: MANDATORY}
              BrowserSignin: 0
            }
          }
        })");
  auto endpoint_fetcher = std::make_unique<EndpointFetcher>(
      url_loader_factory_, waa_oauth_name, GURL(waa_query_url), waa_get_method,
      waa_content_type, std::vector<std::string>{waa_oauth_scope},
      waa_timeout_ms, waa_post_data, traffic_annotation, identity_manager_);
  endpoint_fetcher.get()->Fetch(base::BindOnce(
      &AccountChecker::HandleFetchWaaResponse, weak_ptr_factory_.GetWeakPtr(),
      pref_service_, std::move(endpoint_fetcher)));
}

void AccountChecker::HandleFetchWaaResponse(
    PrefService* pref_service,
    std::unique_ptr<EndpointFetcher> endpoint_fetcher,
    std::unique_ptr<EndpointResponse> responses) {
  data_decoder::DataDecoder::ParseJsonIsolated(
      responses->response,
      base::BindOnce(
          [](PrefService* pref_service,
             data_decoder::DataDecoder::ValueOrError result) {
            if (pref_service && result.has_value() && result->is_dict()) {
              const char waa_response_key[] = "history_recording_enabled";
              if (auto waa_enabled = result->FindBoolKey(waa_response_key)) {
                pref_service->SetBoolean(kWebAndAppActivityEnabledForShopping,
                                         *waa_enabled);
              }
            }
          },
          pref_service));
}

void AccountChecker::FetchPriceEmailPref() {
  if (!base::FeatureList::IsEnabled(kShoppingList) || !IsSignedIn())
    return;

  is_waiting_for_pref_fetch_completion_ = true;
  net::NetworkTrafficAnnotationTag traffic_annotation =
      net::DefineNetworkTrafficAnnotation(
          "chrome_commerce_price_email_pref_fetcher",
          R"(
        semantics {
          sender: "Chrome Shopping"
          description:
            "Check whether the user paused receiving price drop emails."
            "If it is paused, we need to update the preference value to "
            "correctly reflect the user's choice in Chrome settings."
          trigger:
            "Every time when the user opens the Chrome settings."
          data:
            "The request includes an OAuth2 token authenticating the user. The "
            "response includes a map of commerce notification preference key "
            "strings to current user opt-in status."
          destination: GOOGLE_OWNED_SERVICE
        }
        policy {
          cookies_allowed: NO
          setting:
            "This fetch is only enabled for users with Sync turned on. "
            "There's no direct Chromium's setting to disable this, but users "
            "can manage their preferences in Chrome settings."
          chrome_policy {
            SyncDisabled {
              policy_options {mode: MANDATORY}
              SyncDisabled: true
            }
          }
        })");
  auto endpoint_fetcher = std::make_unique<EndpointFetcher>(
      url_loader_factory_, kOAuthName, GURL(kNotificationsPrefUrl),
      kGetHttpMethod, kContentType, std::vector<std::string>{kOAuthScope},
      kTimeoutMs, kEmptyPostData, traffic_annotation, identity_manager_);
  endpoint_fetcher.get()->Fetch(base::BindOnce(
      &AccountChecker::HandleFetchPriceEmailPrefResponse,
      weak_ptr_factory_.GetWeakPtr(), std::move(endpoint_fetcher)));
}

void AccountChecker::HandleFetchPriceEmailPrefResponse(
    std::unique_ptr<EndpointFetcher> endpoint_fetcher,
    std::unique_ptr<EndpointResponse> responses) {
  data_decoder::DataDecoder::ParseJsonIsolated(
      responses->response,
      base::BindOnce(&AccountChecker::OnFetchPriceEmailPrefJsonParsed,
                     weak_ptr_factory_.GetWeakPtr()));
}

void AccountChecker::OnFetchPriceEmailPrefJsonParsed(
    data_decoder::DataDecoder::ValueOrError result) {
  // Only update the pref if we're still waiting for the pref fetch completion.
  // If users update the pref faster than we hear back from the server fetch,
  // the fetched result should be discarded.
  if (pref_service_ && is_waiting_for_pref_fetch_completion_ &&
      result.has_value() && result->is_dict()) {
    if (auto* preferences_map = result->FindKey(kPreferencesKey)) {
      if (absl::optional<bool> price_email_pref =
              preferences_map->FindBoolKey(kPriceTrackEmailPref)) {
        // Only set the pref value when necessary since it could affect
        // PrefService::Preference::IsDefaultValue().
        if (pref_service_->GetBoolean(kPriceEmailNotificationsEnabled) !=
            *price_email_pref) {
          pref_service_->SetBoolean(kPriceEmailNotificationsEnabled,
                                    *price_email_pref);
        }
      }
    }
  }
  is_waiting_for_pref_fetch_completion_ = false;
}

void AccountChecker::SendPriceEmailPref() {
  if (!base::FeatureList::IsEnabled(kShoppingList) || !IsSignedIn() ||
      !pref_service_)
    return;

  // If users update the pref faster than we hear back from the server fetch,
  // the fetched result should be discarded.
  is_waiting_for_pref_fetch_completion_ = false;
  base::Value preferences_map(base::Value::Type::DICTIONARY);
  preferences_map.SetBoolKey(
      kPriceTrackEmailPref,
      pref_service_->GetBoolean(kPriceEmailNotificationsEnabled));
  base::Value post_json(base::Value::Type::DICTIONARY);
  post_json.SetKey(kPreferencesKey, std::move(preferences_map));
  std::string post_data;
  base::JSONWriter::Write(post_json, &post_data);

  net::NetworkTrafficAnnotationTag traffic_annotation =
      net::DefineNetworkTrafficAnnotation(
          "chrome_commerce_price_email_pref_sender",
          R"(
        semantics {
          sender: "Chrome Shopping"
          description:
            "Send the user's choice on whether to receive price drop emails."
          trigger:
            "Every time when the user changes their preference in the Chrome "
            "settings."
          data:
            "The map of commerce notification preference key strings to the "
            "new opt-in status. The request also includes an OAuth2 token "
            "authenticating the user."
          destination: GOOGLE_OWNED_SERVICE
        }
        policy {
          cookies_allowed: NO
          setting:
            "This request is only enabled for users with Sync turned on. "
            "There's no direct Chromium's setting to disable this, but users "
            "can manage their preferences in Chrome settings."
          chrome_policy {
            SyncDisabled {
              policy_options {mode: MANDATORY}
              SyncDisabled: true
            }
          }
        })");
  auto endpoint_fetcher = std::make_unique<EndpointFetcher>(
      url_loader_factory_, kOAuthName, GURL(kNotificationsPrefUrl),
      kPostHttpMethod, kContentType, std::vector<std::string>{kOAuthScope},
      kTimeoutMs, post_data, traffic_annotation, identity_manager_);
  endpoint_fetcher.get()->Fetch(base::BindOnce(
      &AccountChecker::HandleSendPriceEmailPrefResponse,
      weak_ptr_factory_.GetWeakPtr(), std::move(endpoint_fetcher)));
}

void AccountChecker::HandleSendPriceEmailPrefResponse(
    std::unique_ptr<EndpointFetcher> endpoint_fetcher,
    std::unique_ptr<EndpointResponse> responses) {
  data_decoder::DataDecoder::ParseJsonIsolated(
      responses->response,
      base::BindOnce(&AccountChecker::OnSendPriceEmailPrefJsonParsed,
                     weak_ptr_factory_.GetWeakPtr()));
}

void AccountChecker::OnSendPriceEmailPrefJsonParsed(
    data_decoder::DataDecoder::ValueOrError result) {
  if (pref_service_ && result.has_value() && result->is_dict()) {
    if (auto* preferences_map = result->FindKey(kPreferencesKey)) {
      if (auto price_email_pref =
              preferences_map->FindBoolKey(kPriceTrackEmailPref)) {
        if (pref_service_->GetBoolean(kPriceEmailNotificationsEnabled) !=
            *price_email_pref) {
          VLOG(1) << "Fail to update the price email pref";
        }
      }
    }
  }
}

}  // namespace commerce