File: browsing_data_remover_browsertest_base.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 (391 lines) | stat: -rw-r--r-- 14,150 bytes parent folder | download | duplicates (6)
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
// 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 "chrome/browser/browsing_data/browsing_data_remover_browsertest_base.h"

#include <algorithm>
#include <memory>
#include <utility>
#include <vector>

#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/path_service.h"
#include "base/test/bind.h"
#include "base/test/test_future.h"
#include "build/build_config.h"
#include "build/buildflag.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browsing_data/browsing_data_file_system_util.h"
#include "chrome/browser/browsing_data/chrome_browsing_data_model_delegate.h"
#include "chrome/browser/browsing_data/counters/site_data_counting_helper.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_paths.h"
#include "components/browsing_data/content/browsing_data_model.h"
#include "components/browsing_data/content/browsing_data_test_util.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/content_paths.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/download_test_observer.h"
#include "google_apis/gaia/gaia_urls.h"
#include "net/base/filename_util.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "third_party/leveldatabase/env_chromium.h"
#include "third_party/re2/src/re2/re2.h"
#include "ui/base/models/tree_model.h"

#if !BUILDFLAG(IS_ANDROID)
#include "chrome/browser/download/download_browsertest_utils.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/ui_test_utils.h"
#endif

namespace {

#if BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/40169678): Move these functions to
// /chrome/test/base/test_utils.{h|cc}.
base::FilePath GetTestFilePath(const char* dir, const char* file) {
  base::FilePath path;
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::PathService::Get(chrome::DIR_TEST_DATA, &path);
  if (dir)
    path = path.AppendASCII(dir);
  return path.AppendASCII(file);
}

GURL GetTestUrl(const char* dir, const char* file) {
  return net::FilePathToFileURL(GetTestFilePath(dir, file));
}
#endif

// Class for waiting for download manager to be initiailized.
class DownloadManagerWaiter : public content::DownloadManager::Observer {
 public:
  explicit DownloadManagerWaiter(content::DownloadManager* download_manager)
      : initialized_(false), download_manager_(download_manager) {
    download_manager_->AddObserver(this);
  }

  ~DownloadManagerWaiter() override { download_manager_->RemoveObserver(this); }

  void WaitForInitialized() {
    initialized_ = download_manager_->IsManagerInitialized();
    if (initialized_)
      return;
    base::RunLoop run_loop;
    quit_closure_ = run_loop.QuitClosure();
    run_loop.Run();
  }

  void OnManagerInitialized() override {
    initialized_ = true;
    if (quit_closure_)
      std::move(quit_closure_).Run();
  }

 private:
  base::OnceClosure quit_closure_;
  bool initialized_;
  raw_ptr<content::DownloadManager> download_manager_;
};

// Check if |file| matches any regex in |ignore_file_patterns|.
bool ShouldIgnoreFile(const std::string& file,
                      const std::vector<std::string>& ignore_file_patterns) {
  for (const std::string& pattern : ignore_file_patterns) {
    if (RE2::PartialMatch(file, pattern))
      return true;
  }
  return false;
}

}  // namespace

BrowsingDataRemoverBrowserTestBase::BrowsingDataRemoverBrowserTestBase() =
    default;

BrowsingDataRemoverBrowserTestBase::~BrowsingDataRemoverBrowserTestBase() =
    default;

void BrowsingDataRemoverBrowserTestBase::InitFeatureLists(
    std::vector<base::test::FeatureRef> enabled_features,
    std::vector<base::test::FeatureRef> disabled_features) {
  feature_list_.InitWithFeatures(enabled_features, disabled_features);
}

#if !BUILDFLAG(IS_ANDROID)
Browser* BrowsingDataRemoverBrowserTestBase::GetBrowser() const {
  return incognito_browser_ ? incognito_browser_.get() : browser();
}

// Call to use an Incognito browser rather than the default.
void BrowsingDataRemoverBrowserTestBase::UseIncognitoBrowser() {
  ASSERT_EQ(nullptr, incognito_browser_.get());
  incognito_browser_ = CreateIncognitoBrowser();
}

void BrowsingDataRemoverBrowserTestBase::RestartIncognitoBrowser() {
  ASSERT_NE(nullptr, incognito_browser_);
  CloseBrowserSynchronously(incognito_browser_);
  incognito_browser_ = nullptr;
  UseIncognitoBrowser();
}

#endif

void BrowsingDataRemoverBrowserTestBase::SetUpOnMainThread() {
  base::FilePath path;
  base::PathService::Get(content::DIR_TEST_DATA, &path);
  embedded_test_server()->ServeFilesFromDirectory(path);
  ASSERT_TRUE(embedded_test_server()->Start());
}

void BrowsingDataRemoverBrowserTestBase::RunScriptAndCheckResult(
    const std::string& script,
    const std::string& result,
    content::WebContents* web_contents) {
  if (!web_contents)
    web_contents = GetActiveWebContents();
  ASSERT_EQ(result, content::EvalJs(web_contents, script));
}

bool BrowsingDataRemoverBrowserTestBase::RunScriptAndGetBool(
    const std::string& script,
    content::WebContents* web_contents) {
  EXPECT_TRUE(web_contents);
  return content::EvalJs(web_contents, script).ExtractBool();
}

void BrowsingDataRemoverBrowserTestBase::VerifyDownloadCount(size_t expected,
                                                             Profile* profile) {
  if (!profile)
    profile = GetProfile();
  content::DownloadManager* download_manager = profile->GetDownloadManager();
  DownloadManagerWaiter download_manager_waiter(download_manager);
  download_manager_waiter.WaitForInitialized();
  std::vector<raw_ptr<download::DownloadItem, VectorExperimental>> downloads;
  download_manager->GetAllDownloads(&downloads);
  EXPECT_EQ(expected, downloads.size());
}

void BrowsingDataRemoverBrowserTestBase::DownloadAnItem() {
  // Start a download.
  content::DownloadManager* download_manager =
      GetProfile()->GetDownloadManager();
  auto observer = std::make_unique<content::DownloadTestObserverTerminal>(
      download_manager, 1,
      content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT);

#if BUILDFLAG(IS_ANDROID)
  GURL download_url = GetTestUrl("downloads", "a_zip_file.zip");
  ASSERT_TRUE(content::NavigateToURL(GetActiveWebContents(), download_url,
                                     GURL("about:blank")));
#else
  GURL download_url =
      ui_test_utils::GetTestUrl(base::FilePath().AppendASCII("downloads"),
                                base::FilePath().AppendASCII("a_zip_file.zip"));
  SetPromptForDownload(GetBrowser(), false);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(GetBrowser(), download_url));
#endif
  observer->WaitForFinished();

  VerifyDownloadCount(1u);
}

bool BrowsingDataRemoverBrowserTestBase::HasDataForType(
    const std::string& type,
    content::WebContents* web_contents) {
  if (!web_contents)
    web_contents = GetActiveWebContents();
  return browsing_data_test_util::HasDataForType(type, web_contents);
}

void BrowsingDataRemoverBrowserTestBase::SetDataForType(
    const std::string& type,
    content::WebContents* web_contents) {
  if (!web_contents)
    web_contents = GetActiveWebContents();
  browsing_data_test_util::SetDataForType(type, web_contents);
}

int BrowsingDataRemoverBrowserTestBase::GetSiteDataCount(
    content::WebContents* web_contents) {
  if (!web_contents)
    web_contents = GetActiveWebContents();
  Profile* profile =
      Profile::FromBrowserContext(web_contents->GetBrowserContext());
  base::RunLoop run_loop;
  int count = -1;

  (new SiteDataCountingHelper(profile, base::Time(), base::Time::Max(),
                              base::BindLambdaForTesting([&](int c) {
                                count = c;
                                run_loop.Quit();
                              })))
      ->CountAndDestroySelfWhenFinished();
  run_loop.Run();
  return count;
}

network::mojom::NetworkContext*
BrowsingDataRemoverBrowserTestBase::network_context() {
  return GetProfile()->GetDefaultStoragePartition()->GetNetworkContext();
}

// Returns the active WebContents. On desktop this is in the first browser
// window created by tests, more specific behaviour requires other means.
content::WebContents*
BrowsingDataRemoverBrowserTestBase::GetActiveWebContents() {
#if BUILDFLAG(IS_ANDROID)
  return chrome_test_utils::GetActiveWebContents(this);
#else
  return GetBrowser()->tab_strip_model()->GetActiveWebContents();
#endif
}

#if !BUILDFLAG(IS_ANDROID)
content::WebContents* BrowsingDataRemoverBrowserTestBase::GetActiveWebContents(
    Browser* browser) {
  return browser->tab_strip_model()->GetActiveWebContents();
}
#endif  // !BUILDFLAG(IS_ANDROID)

Profile* BrowsingDataRemoverBrowserTestBase::GetProfile() {
#if BUILDFLAG(IS_ANDROID)
  return chrome_test_utils::GetProfile(this);
#else
  return GetBrowser()->profile();
#endif
}

bool BrowsingDataRemoverBrowserTestBase::CheckUserDirectoryForString(
    const std::string& hostname,
    const std::vector<std::string>& ignore_file_patterns,
    bool check_leveldb_content) {
  base::FilePath user_data_dir =
      g_browser_process->profile_manager()->user_data_dir();
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::FileEnumerator enumerator(
      user_data_dir, true /* recursive */,
      base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES);
  int found = 0;
  for (base::FilePath path = enumerator.Next(); !path.empty();
       path = enumerator.Next()) {
    // Remove |user_data_dir| part from path.
    std::string file =
        path.NormalizePathSeparatorsTo('/').AsUTF8Unsafe().substr(
            user_data_dir.AsUTF8Unsafe().length());

    // Check file name.
    if (file.find(hostname) != std::string::npos) {
      if (ShouldIgnoreFile(file, ignore_file_patterns)) {
        LOG(INFO) << "Ignored: " << file;
      } else {
        found++;
        LOG(WARNING) << "Found file name: " << file;
      }
    }

    // Check leveldb content.
    if (check_leveldb_content && path.BaseName().AsUTF8Unsafe() == "CURRENT") {
      // LevelDB instances consist of a folder where most files have variable
      // names that contain a revision number.
      // All leveldb folders have a "CURRENT" file that points to the current
      // manifest. We consider all folders with a CURRENT file to be leveldb
      // instances and try to open them.
      std::unique_ptr<leveldb::DB> db;
      std::string db_file = path.DirName().AsUTF8Unsafe();
      auto status = leveldb_env::OpenDB(leveldb_env::Options(), db_file, &db);
      if (status.ok()) {
        std::unique_ptr<leveldb::Iterator> it(
            db->NewIterator(leveldb::ReadOptions()));
        for (it->SeekToFirst(); it->Valid(); it->Next()) {
          std::string entry =
              it->key().ToString() + ":" + it->value().ToString();
          if (entry.find(hostname) != std::string::npos) {
            LOG(WARNING) << "Found leveldb entry: " << file << " " << entry;
            found++;
          }
        }
      } else {
        // TODO(crbug.com/40784064): Most databases are already open and
        // the LOCK prevents us from accessing them.
        LOG(INFO) << "Could not open: " << file << " " << status.ToString();
      }
    }

    // TODO(crbug.com/40577815): Add support for sqlite and other formats that
    // possibly contain non-plaintext data.

    // Check file content.
    if (enumerator.GetInfo().IsDirectory())
      continue;
    std::string content;
    if (!base::ReadFileToString(path, &content)) {
      LOG(INFO) << "Could not read: " << file;
      continue;
    }
    size_t pos = content.find(hostname);
    if (pos != std::string::npos) {
      if (ShouldIgnoreFile(file, ignore_file_patterns)) {
        LOG(INFO) << "Ignored: " << file;
        continue;
      }
      found++;
      // Print surrounding text of the match.
      std::string partial_content = content.substr(
          pos < 30 ? 0 : pos - 30,
          std::min(content.size() - 1, pos + hostname.size() + 30));
      LOG(WARNING) << "Found file content: " << file << "\n"
                   << partial_content << "\n" << found;
    }
  }
  return found;
}

std::unique_ptr<BrowsingDataModel>
BrowsingDataRemoverBrowserTestBase::GetBrowsingDataModel(Profile* profile) {
  base::test::TestFuture<std::unique_ptr<BrowsingDataModel>>
      browsing_data_model;
  BrowsingDataModel::BuildFromDisk(
      profile, ChromeBrowsingDataModelDelegate::CreateForProfile(profile),
      browsing_data_model.GetCallback());
  return browsing_data_model.Take();
}

#if BUILDFLAG(ENABLE_DICE_SUPPORT)
bool BrowsingDataRemoverBrowserTestBase::SetGaiaCookieForProfile(
    Profile* profile) {
  GURL google_url = GaiaUrls::GetInstance()->secure_google_url();
  auto cookie = net::CanonicalCookie::CreateUnsafeCookieForTesting(
      "SAPISID", std::string(), "." + google_url.host(), "/", base::Time(),
      base::Time(), base::Time(), base::Time(), /*secure=*/true,
      /*httponly=*/false, net::CookieSameSite::NO_RESTRICTION,
      net::COOKIE_PRIORITY_DEFAULT);
  bool success = false;
  base::RunLoop loop;
  base::OnceCallback<void(net::CookieAccessResult)> callback =
      base::BindLambdaForTesting([&success, &loop](net::CookieAccessResult r) {
        success = r.status.IsInclude();
        loop.Quit();
      });
  network::mojom::CookieManager* cookie_manager =
      profile->GetDefaultStoragePartition()
          ->GetCookieManagerForBrowserProcess();
  cookie_manager->SetCanonicalCookie(*cookie, google_url,
                                     net::CookieOptions::MakeAllInclusive(),
                                     std::move(callback));
  loop.Run();
  return success;
}
#endif