File: affiliation_service_impl.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (333 lines) | stat: -rw-r--r-- 12,183 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
// Copyright 2020 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/affiliations/core/browser/affiliation_service_impl.h"

#include <algorithm>
#include <vector>

#include "base/containers/contains.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/functional/callback_forward.h"
#include "base/location.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/time/default_clock.h"
#include "base/time/default_tick_clock.h"
#include "components/affiliations/core/browser/affiliation_backend.h"
#include "components/affiliations/core/browser/affiliation_fetcher_interface.h"
#include "components/affiliations/core/browser/affiliation_utils.h"
#include "services/network/public/cpp/network_connection_tracker.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "url/gurl.h"

namespace affiliations {

namespace {

void LogFetchResult(GetChangePasswordUrlMetric result) {
  base::UmaHistogramEnumeration(kGetChangePasswordURLMetricName, result);
}

// Creates a look-up (Facet URI : change password URL) map for facets from
// requested |groupings|. If a facet does not have change password URL it gets
// paired with another facet's URL, which belongs to the same group. In case
// none of the group's facets have change password URLs then those facets are
// not inserted to the map.
std::map<FacetURI, AffiliationServiceImpl::ChangePasswordUrlMatch>
CreateFacetUriToChangePasswordUrlMap(
    const std::vector<GroupedFacets>& groupings) {
  std::map<FacetURI, AffiliationServiceImpl::ChangePasswordUrlMatch> uri_to_url;
  for (const auto& grouped_facets : groupings) {
    std::vector<FacetURI> uris_without_urls;
    GURL fallback_url;
    for (const auto& facet : grouped_facets.facets) {
      if (!facet.change_password_url.is_valid()) {
        uris_without_urls.push_back(facet.uri);
        continue;
      }
      uri_to_url[facet.uri] = AffiliationServiceImpl::ChangePasswordUrlMatch{
          .change_password_url = facet.change_password_url,
          .group_url_override = false};
      fallback_url = facet.change_password_url;
    }
    if (fallback_url.is_valid()) {
      for (const auto& uri : uris_without_urls) {
        uri_to_url[uri] = AffiliationServiceImpl::ChangePasswordUrlMatch{
            .change_password_url = fallback_url, .group_url_override = true};
      }
    }
  }
  return uri_to_url;
}

FacetURI ConvertGURLToFacet(const GURL& url) {
  if (url.SchemeIs(url::kAndroidScheme)) {
    return FacetURI::FromPotentiallyInvalidSpec(url.possibly_invalid_spec());
  } else {
    // Path should be stripped before converting into FacetURI.
    return FacetURI::FromPotentiallyInvalidSpec(url.GetWithEmptyPath().spec());
  }
}

// Returns FacetURI corresponding to the top level domain of the `facet`. Empty
// if `facet` is android app, eTLD+1 can't be extracted, or `facet` is already
// top level domain.
FacetURI GetFacetForTopLevelDomain(FacetURI facet) {
  if (!facet.IsValidWebFacetURI()) {
    return FacetURI();
  }

  std::string top_domain =
      GetExtendedTopLevelDomain(GURL(facet.canonical_spec()), {});
  if (top_domain.empty()) {
    return FacetURI();
  }

  FacetURI result =
      FacetURI::FromPotentiallyInvalidSpec("https://" + top_domain);

  if (!result.is_valid() || result == facet) {
    return FacetURI();
  }

  return result;
}

void LogChangePasswordURLTypeUsed(
    const AffiliationServiceImpl::ChangePasswordUrlMatch& match) {
  if (match.group_url_override) {
    LogFetchResult(GetChangePasswordUrlMetric::kGroupUrlOverrideUsed);
  } else if (match.main_domain_override) {
    LogFetchResult(GetChangePasswordUrlMetric::kMainDomainUsed);
  } else {
    LogFetchResult(GetChangePasswordUrlMetric::kUrlOverrideUsed);
  }
}

}  // namespace

const char kGetChangePasswordURLMetricName[] =
    "PasswordManager.AffiliationService.GetChangePasswordUsage";

struct AffiliationServiceImpl::FetchInfo {
  FetchInfo(FacetURI facet, base::OnceClosure result_callback)
      : requested_facet(std::move(facet)),
        top_level_domain(GetFacetForTopLevelDomain(requested_facet)),
        callback(std::move(result_callback)) {}

  FetchInfo(FetchInfo&& other) = default;

  FetchInfo& operator=(FetchInfo&& other) = default;

  ~FetchInfo() {
    // Check if the callback is still there. |FetchInfo| is moved into a
    // callback, so it can be gone by the time the destructor is called.
    if (callback) {
      // If a fetch is not possible, |AffiliationFetcherManager::Fetch| can
      // invoke its callback immediately. Posting a task here instead or
      // directly running it will prevent the caller of
      // |PrefetchChangePasswordURL| from unexpectedly receiving the result of
      // the callback during the execution of |PrefetchChangePasswordURL|.
      base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
          FROM_HERE, std::move(callback));
    }
  }

  ChangePasswordUrlMatch GetChangePasswordURL(
      const AffiliationFetcherInterface::ParsedFetchResponse& result) const {
    std::map<FacetURI, AffiliationServiceImpl::ChangePasswordUrlMatch>
        uri_to_url = CreateFacetUriToChangePasswordUrlMap(result.groupings);

    auto it = uri_to_url.find(requested_facet);
    if (it != uri_to_url.end()) {
      return it->second;
    }

    // Check if change password URL available for the main domain.
    it = uri_to_url.find(top_level_domain);
    if (it != uri_to_url.end()) {
      it->second.main_domain_override = true;
      return it->second;
    }

    return ChangePasswordUrlMatch();
  }

  std::vector<FacetURI> FacetsToRequest() const {
    if (top_level_domain.is_valid() && top_level_domain != requested_facet) {
      return {requested_facet, top_level_domain};
    }
    return {requested_facet};
  }

  FacetURI requested_facet;
  FacetURI top_level_domain;
  // Callback is passed in PrefetchChangePasswordURLs and is run to indicate the
  // prefetch has finished or got canceled.
  base::OnceClosure callback;
};

// TODO(crbug.com/40789139): Create the backend task runner in Init and stop
// passing it in the constructor.
AffiliationServiceImpl::AffiliationServiceImpl(
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    scoped_refptr<base::SequencedTaskRunner> backend_task_runner)
    : url_loader_factory_(std::move(url_loader_factory)),
      backend_task_runner_(std::move(backend_task_runner)) {}

AffiliationServiceImpl::~AffiliationServiceImpl() = default;

void AffiliationServiceImpl::Init(
    network::NetworkConnectionTracker* network_connection_tracker,
    const base::FilePath& db_path) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  fetcher_manager_ =
      std::make_unique<AffiliationFetcherManager>(url_loader_factory_);
  backend_ = std::make_unique<AffiliationBackend>(
      backend_task_runner_, base::DefaultClock::GetInstance(),
      base::DefaultTickClock::GetInstance());

  PostToBackend(&AffiliationBackend::Initialize, url_loader_factory_->Clone(),
                base::Unretained(network_connection_tracker), db_path);
}

void AffiliationServiceImpl::Shutdown() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (backend_) {
    backend_task_runner_->DeleteSoon(FROM_HERE, std::move(backend_));
  }
}

void AffiliationServiceImpl::PrefetchChangePasswordURL(
    const GURL& url,
    base::OnceClosure callback) {
  FacetURI facet_uri = ConvertGURLToFacet(url);
  if (!facet_uri.is_valid() ||
      base::Contains(change_password_urls_, facet_uri)) {
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, std::move(callback));
    return;
  }
  FetchInfo fetch_info(facet_uri, std::move(callback));
  auto facets_to_request = fetch_info.FacetsToRequest();
  fetcher_manager_->Fetch(
      facets_to_request, kChangePasswordUrlRequestInfo,
      base::BindOnce(&AffiliationServiceImpl::OnFetchFinished,
                     weak_ptr_factory_.GetWeakPtr(), std::move(fetch_info)));
}

GURL AffiliationServiceImpl::GetChangePasswordURL(const GURL& url) const {
  FacetURI uri = ConvertGURLToFacet(url);

  auto it = change_password_urls_.find(uri);
  if (it != change_password_urls_.end()) {
    LogChangePasswordURLTypeUsed(it->second);
    return it->second.change_password_url;
  }
  auto requested_facet_uris = fetcher_manager_->GetRequestedFacetURIs();
  if (base::Contains(requested_facet_uris, uri)) {
    LogFetchResult(GetChangePasswordUrlMetric::kNotFetchedYet);
  } else {
    LogFetchResult(GetChangePasswordUrlMetric::kNoUrlOverrideAvailable);
  }
  return GURL();
}

void AffiliationServiceImpl::OnFetchFinished(
    const FetchInfo& fetch_info,
    AffiliationFetcherInterface::FetchResult fetch_result) {
  // Handle the successful case only. On failure the fetch will be discarded
  // without retries.
  if (fetch_result.IsSuccessful()) {
    change_password_urls_[fetch_info.requested_facet] =
        fetch_info.GetChangePasswordURL(fetch_result.data.value());
  }
}

void AffiliationServiceImpl::GetAffiliationsAndBranding(
    const FacetURI& facet_uri,
    ResultCallback result_callback) {
  PostToBackend(&AffiliationBackend::GetAffiliationsAndBranding, facet_uri,
                std::move(result_callback),
                base::SequencedTaskRunner::GetCurrentDefault());
}

void AffiliationServiceImpl::Prefetch(const FacetURI& facet_uri,
                                      const base::Time& keep_fresh_until) {
  PostToBackend(&AffiliationBackend::Prefetch, facet_uri, keep_fresh_until);
}

void AffiliationServiceImpl::CancelPrefetch(
    const FacetURI& facet_uri,
    const base::Time& keep_fresh_until) {
  PostToBackend(&AffiliationBackend::CancelPrefetch, facet_uri,
                keep_fresh_until);
}

void AffiliationServiceImpl::KeepPrefetchForFacets(
    std::vector<FacetURI> facet_uris) {
  PostToBackend(&AffiliationBackend::KeepPrefetchForFacets,
                std::move(facet_uris));
}

void AffiliationServiceImpl::TrimUnusedCache(std::vector<FacetURI> facet_uris) {
  PostToBackend(&AffiliationBackend::TrimUnusedCache, std::move(facet_uris));
}

void AffiliationServiceImpl::GetGroupingInfo(std::vector<FacetURI> facet_uris,
                                             GroupsCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // If `backend` is destroyed there is nothing to do.
  if (!backend_) {
    return;
  }

  backend_task_runner_->PostTaskAndReplyWithResult(
      FROM_HERE,
      base::BindOnce(&AffiliationBackend::GetGroupingInfo,
                     base::Unretained(backend_.get()), std::move(facet_uris)),
      std::move(callback));
}

void AffiliationServiceImpl::GetPSLExtensions(
    base::OnceCallback<void(std::vector<std::string>)> callback) const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // If `backend` is destroyed there is nothing to do.
  if (!backend_) {
    return;
  }

  backend_task_runner_->PostTaskAndReplyWithResult(
      FROM_HERE,
      base::BindOnce(&AffiliationBackend::GetPSLExtensions,
                     base::Unretained(backend_.get())),
      std::move(callback));
}

void AffiliationServiceImpl::UpdateAffiliationsAndBranding(
    const std::vector<FacetURI>& facets,
    base::OnceClosure callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(backend_);
  auto callback_in_main_sequence =
      base::BindOnce(base::IgnoreResult(&base::TaskRunner::PostTask),
                     base::SequencedTaskRunner::GetCurrentDefault(), FROM_HERE,
                     std::move(callback));
  backend_task_runner_->PostTask(
      FROM_HERE,
      base::BindOnce(&AffiliationBackend::UpdateAffiliationsAndBranding,
                     base::Unretained(backend_.get()), facets,
                     std::move(callback_in_main_sequence)));
}

void AffiliationServiceImpl::RegisterSource(
    std::unique_ptr<AffiliationSource> source) {
  prefetcher_.RegisterSource(std::move(source));
}

}  // namespace affiliations