File: web_app_profile_deletion_browsertest.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 (411 lines) | stat: -rw-r--r-- 16,840 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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// 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 "base/containers/flat_set.h"
#include "base/functional/callback_helpers.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/test_future.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/delete_profile_helper.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profile_metrics.h"
#include "chrome/browser/profiles/profile_test_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/web_applications/web_app_browsertest_base.h"
#include "chrome/browser/web_applications/app_service/web_app_publisher_helper.h"
#include "chrome/browser/web_applications/locks/noop_lock.h"
#include "chrome/browser/web_applications/preinstalled_web_app_manager.h"
#include "chrome/browser/web_applications/test/web_app_install_test_utils.h"
#include "chrome/browser/web_applications/test/web_app_test_observers.h"
#include "chrome/browser/web_applications/web_app_command_scheduler.h"
#include "chrome/browser/web_applications/web_app_install_utils.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/browser/web_applications/web_contents/web_app_data_retriever.h"
#include "chrome/browser/web_applications/web_contents/web_app_icon_downloader.h"
#include "chrome/test/base/profile_destruction_waiter.h"
#include "components/user_manager/user_manager.h"
#include "components/webapps/browser/installable/installable_logging.h"
#include "components/webapps/browser/web_contents/web_app_url_loader.h"
#include "components/webapps/common/web_app_id.h"
#include "content/public/test/browser_test.h"
#include "google_apis/gaia/gaia_id.h"
#include "third_party/blink/public/mojom/manifest/manifest.mojom.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "chromeos/ash/components/browser_context_helper/browser_context_helper.h"
#include "components/account_id/account_id.h"
#include "components/session_manager/core/session_manager.h"
#include "components/user_manager/test_helper.h"
#endif

namespace web_app {

class ProfileMarkedForDeletionObserver : public ProfileManagerObserver {
 public:
  explicit ProfileMarkedForDeletionObserver(Profile* profile)
      : profile_(profile) {
    if (ProfileManager* profile_manager =
            g_browser_process->profile_manager()) {
      profile_manager_observation_.Observe(profile_manager);
    }
  }

  void Wait() { run_loop_.Run(); }

  void OnProfileMarkedForPermanentDeletion(
      Profile* profile_to_be_deleted) override {
    if (profile_to_be_deleted != profile_) {
      return;
    }

    run_loop_.Quit();
  }

  void OnProfileManagerDestroying() override {
    profile_manager_observation_.Reset();
  }

 private:
  raw_ptr<Profile> profile_ = nullptr;
  base::RunLoop run_loop_;
  base::ScopedObservation<ProfileManager, ProfileManagerObserver>
      profile_manager_observation_{this};
};

class WebAppProfileDeletionBrowserTest : public WebAppBrowserTestBase {
 public:
  WebAppProfileDeletionBrowserTest()
      : skip_preinstalled_(PreinstalledWebAppManager::SkipStartupForTesting()) {
  }
  WebAppRegistrar& registrar() {
    auto* provider = WebAppProvider::GetForTest(profile());
    CHECK(provider);
    return provider->registrar_unsafe();
  }

  void ScheduleCurrentProfileForDeletion() {
    g_browser_process->profile_manager()
        ->GetDeleteProfileHelper()
        .MaybeScheduleProfileForDeletion(
            profile()->GetPath(), base::DoNothing(),
            ProfileMetrics::DELETE_PROFILE_USER_MANAGER);
  }

  webapps::AppId InstallAppToProfile(Profile* profile, const GURL& start_url) {
    auto web_app_info =
        WebAppInstallInfo::CreateWithStartUrlForTesting(start_url);
    web_app_info->scope = start_url.GetWithoutFilename();
    web_app_info->user_display_mode =
        web_app::mojom::UserDisplayMode::kStandalone;
    web_app_info->title = u"A Web App";
    return web_app::test::InstallWebApp(profile, std::move(web_app_info));
  }

  std::unique_ptr<content::WebContents>
  CreateWebContentsScheduledForDeletion() {
    ProfileManager* profile_manager = g_browser_process->profile_manager();
    base::FilePath profile_path_to_delete =
        profile_manager->GenerateNextProfileDirectoryPath();
    Profile& profile_to_delete = profiles::testing::CreateProfileSync(
        profile_manager, profile_path_to_delete);

    std::unique_ptr<content::WebContents> deleting_web_contents =
        content::WebContents::Create(
            content::WebContents::CreateParams(&profile_to_delete));
    EXPECT_NE(deleting_web_contents, nullptr);

    ProfileDestructionWaiter destruction_waiter(&profile_to_delete);
    profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion(
        profile_to_delete.GetPath(), base::DoNothing(),
        ProfileMetrics::DELETE_PROFILE_SETTINGS);
    destruction_waiter.Wait();

    return deleting_web_contents;
  }

#if BUILDFLAG(IS_CHROMEOS)
  void SetUpLocalStatePrefService(PrefService* local_state) override {
    WebAppBrowserTestBase::SetUpLocalStatePrefService(local_state);

    // Register a persisted user.
    user_manager::TestHelper::RegisterPersistedUser(*local_state,
                                                    test_account_id_);
  }

  Profile& StartUserSession(const AccountId& account_id) {
    auto* session_manager = session_manager::SessionManager::Get();
    session_manager->CreateSession(account_id, account_id.GetUserEmail(),
                                   /*new_user=*/false,
                                   /*has_active_session=*/false);

    ProfileManager* profile_manager = g_browser_process->profile_manager();
    Profile& profile = profiles::testing::CreateProfileSync(
        profile_manager,
        ash::BrowserContextHelper::Get()->GetBrowserContextPathByUserIdHash(
            user_manager::UserManager::Get()
                ->FindUser(account_id)
                ->username_hash()));

    session_manager->NotifyUserProfileLoaded(account_id);
    session_manager->SessionStarted();
    return profile;
  }

 protected:
  // Use a real domain to avoid policy loading problems.
  const std::string kTestUserName = "test@gmail.com";
  const GaiaId kTestUserGaiaId = GaiaId("9876543210");
  const AccountId test_account_id_ =
      AccountId::FromUserEmailGaiaId(kTestUserName, kTestUserGaiaId);
#endif  // BUILDFLAG(IS_CHROMEOS)
 private:
  base::AutoReset<bool> skip_preinstalled_;
};

class NoOpWebAppPublisherDelegate : public WebAppPublisherHelper::Delegate {
  // WebAppPublisherHelper::Delegate:
  void PublishWebApps(std::vector<apps::AppPtr> apps) override {}
  void PublishWebApp(apps::AppPtr app) override {}
  void ModifyWebAppCapabilityAccess(
      const std::string& app_id,
      std::optional<bool> accessing_camera,
      std::optional<bool> accessing_microphone) override {}
};

IN_PROC_BROWSER_TEST_F(WebAppProfileDeletionBrowserTest, OsIntegrationRemoved) {
  const GURL app_url = GetInstallableAppURL();

  /// Create a new profile and install a web app.
  ProfileManager* profile_manager = g_browser_process->profile_manager();
#if BUILDFLAG(IS_CHROMEOS)
  Profile& profile_to_delete = StartUserSession(test_account_id_);
#else
  base::FilePath profile_path_to_delete =
      profile_manager->GenerateNextProfileDirectoryPath();
  Profile& profile_to_delete = profiles::testing::CreateProfileSync(
      profile_manager, profile_path_to_delete);
#endif
  Browser::Create(Browser::CreateParams(&profile_to_delete, true));
  const webapps::AppId app_id =
      InstallAppToProfile(&profile_to_delete, app_url);
  auto* provider = WebAppProvider::GetForTest(&profile_to_delete);
  auto* web_app = provider->registrar_unsafe().GetAppById(app_id);
  ASSERT_TRUE(web_app);

  base::test::TestFuture<const webapps::AppId&> app_id_future;
  provider->os_integration_manager().SetForceUnregisterCalledForTesting(
      app_id_future.GetRepeatingCallback());

  // Trigger profile deletion while uninstalling the app to simulate profile
  // pointer being invalidated.
  profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion(
      profile_to_delete.GetPath(), base::DoNothing(),
      ProfileMetrics::DELETE_PROFILE_USER_MANAGER);

  ASSERT_TRUE(app_id_future.Wait());
  EXPECT_EQ(app_id_future.Get(), app_id);
}

IN_PROC_BROWSER_TEST_F(WebAppProfileDeletionBrowserTest,
                       CommandsNotScheduledAfterProfileMarkedForDeletion) {
  // Create a new profile.
  ProfileManager* profile_manager = g_browser_process->profile_manager();
#if BUILDFLAG(IS_CHROMEOS)
  Profile& profile_to_delete = StartUserSession(test_account_id_);
#else
  base::FilePath profile_path_to_delete =
      profile_manager->GenerateNextProfileDirectoryPath();
  Profile& profile_to_delete = profiles::testing::CreateProfileSync(
      profile_manager, profile_path_to_delete);
#endif

  WebAppCommandScheduler& command_scheduler =
      WebAppProvider::GetForTest(&profile_to_delete)->scheduler();
  ProfileMarkedForDeletionObserver deletion_observer(&profile_to_delete);

  profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion(
      profile_to_delete.GetPath(), base::DoNothing(),
      ProfileMetrics::DELETE_PROFILE_USER_MANAGER);
  deletion_observer.Wait();

  // Scheduling a test command post profile deletion should automatically be
  // stopped and the callback run.
  base::test::TestFuture<bool> commands_not_scheduled_future;
  command_scheduler.ScheduleCallbackWithResult(
      "TestCommandPostProfileDeletion", web_app::NoopLockDescription(),
      base::BindOnce(
          [](web_app::NoopLock&, base::Value::Dict&) { return true; }),
      commands_not_scheduled_future.GetCallback(), /*arg_for_shutdown=*/false);

  ASSERT_TRUE(commands_not_scheduled_future.Wait());
  ASSERT_FALSE(commands_not_scheduled_future.Get());
}

using WebAppProfileDeletionBrowserTest_WebAppPublisher =
    WebAppProfileDeletionBrowserTest;
IN_PROC_BROWSER_TEST_F(WebAppProfileDeletionBrowserTest_WebAppPublisher,
                       UninstallWhileProfileIsBeingDeleted) {
  const GURL app_url = GetInstallableAppURL();

  /// Create a new profile and install a web app.
  ProfileManager* profile_manager = g_browser_process->profile_manager();
#if BUILDFLAG(IS_CHROMEOS)
  Profile& profile_to_delete = StartUserSession(test_account_id_);
#else
  base::FilePath profile_path_to_delete =
      profile_manager->GenerateNextProfileDirectoryPath();
  Profile& profile_to_delete = profiles::testing::CreateProfileSync(
      profile_manager, profile_path_to_delete);
#endif
  Browser::Create(Browser::CreateParams(&profile_to_delete, true));
  const webapps::AppId app_id =
      InstallAppToProfile(&profile_to_delete, app_url);
  auto* provider = WebAppProvider::GetForTest(&profile_to_delete);
  auto* web_app = provider->registrar_unsafe().GetAppById(app_id);
  ASSERT_TRUE(web_app);

  base::test::TestFuture<const webapps::AppId&> app_id_future;
  provider->os_integration_manager().SetForceUnregisterCalledForTesting(
      app_id_future.GetRepeatingCallback());

  // Uninstall the web app.
  NoOpWebAppPublisherDelegate no_op_delegate;
  auto web_app_publisher_helper = std::make_unique<WebAppPublisherHelper>(
      &profile_to_delete, provider, &no_op_delegate);
  web_app_publisher_helper->UninstallWebApp(
      web_app, apps::UninstallSource::kAppList, /*clear_site_data*/ true,
      /*report_abuse*/ false);

  // Trigger profile deletion while uninstalling the app to simulate profile
  // pointer being invalidated.
  profile_manager->GetDeleteProfileHelper().MaybeScheduleProfileForDeletion(
      profile_to_delete.GetPath(), base::DoNothing(),
      ProfileMetrics::DELETE_PROFILE_USER_MANAGER);

  ASSERT_TRUE(app_id_future.Wait());
  EXPECT_EQ(app_id_future.Get(), app_id);
}

#if !BUILDFLAG(IS_CHROMEOS)
// TODO(crbug.com/40283231): Figure out a way having this test be run on
// ChromeOS Ash, i.e. properly trigger a browser context shutdown.

using WebAppProfileDeletionTest_WebContentsGracefulShutdown =
    WebAppProfileDeletionBrowserTest;

IN_PROC_BROWSER_TEST_F(WebAppProfileDeletionTest_WebContentsGracefulShutdown,
                       UrlLoading) {
  ASSERT_TRUE(embedded_test_server()->Start());
  webapps::WebAppUrlLoader loader;

  std::unique_ptr<content::WebContents> deleting_web_contents =
      CreateWebContentsScheduledForDeletion();

  base::test::TestFuture<webapps::WebAppUrlLoaderResult> loader_result;
  loader.LoadUrl(embedded_test_server()->GetURL("/title1.html"),
                 deleting_web_contents.get(),
                 webapps::WebAppUrlLoader::UrlComparison::kExact,
                 loader_result.GetCallback());
  EXPECT_TRUE(loader_result.Wait());

  EXPECT_EQ(loader_result.Get<webapps::WebAppUrlLoaderResult>(),
            webapps::WebAppUrlLoaderResult::kFailedWebContentsDestroyed);
}

IN_PROC_BROWSER_TEST_F(WebAppProfileDeletionTest_WebContentsGracefulShutdown,
                       IconDownloading) {
  WebAppIconDownloader icon_downloader;

  std::unique_ptr<content::WebContents> deleting_web_contents =
      CreateWebContentsScheduledForDeletion();

  base::test::TestFuture<IconsDownloadedResult, IconsMap,
                         DownloadedIconsHttpResults>
      icon_download_future;
  IconUrlSizeSet icon_urls;
  icon_urls.insert(IconUrlWithSize::CreateForUnspecifiedSize(
      GURL("https://www.example.com/favicon.ico")));
  icon_downloader.Start(deleting_web_contents.get(), icon_urls,
                        icon_download_future.GetCallback(),
                        IconDownloaderOptions());
  EXPECT_TRUE(icon_download_future.Wait());

  EXPECT_EQ(icon_download_future.Get<IconsDownloadedResult>(),
            IconsDownloadedResult::kPrimaryPageChanged);
}

IN_PROC_BROWSER_TEST_F(WebAppProfileDeletionTest_WebContentsGracefulShutdown,
                       DataRetrieverWebAppInfoFetching) {
  WebAppDataRetriever data_retriever;

  std::unique_ptr<content::WebContents> deleting_web_contents =
      CreateWebContentsScheduledForDeletion();

  base::test::TestFuture<std::unique_ptr<WebAppInstallInfo>>
      install_info_fetcher;
  data_retriever.GetWebAppInstallInfo(deleting_web_contents.get(),
                                      install_info_fetcher.GetCallback());
  EXPECT_TRUE(install_info_fetcher.Wait());

  EXPECT_EQ(install_info_fetcher.Get<std::unique_ptr<WebAppInstallInfo>>(),
            nullptr);
}

IN_PROC_BROWSER_TEST_F(WebAppProfileDeletionTest_WebContentsGracefulShutdown,
                       DataRetrieverInstallabilityFetch) {
  ASSERT_TRUE(embedded_test_server()->Start());
  WebAppDataRetriever data_retriever;

  std::unique_ptr<content::WebContents> deleting_web_contents =
      CreateWebContentsScheduledForDeletion();

  base::test::TestFuture<blink::mojom::ManifestPtr, bool,
                         webapps::InstallableStatusCode>
      installability_future;
  data_retriever.CheckInstallabilityAndRetrieveManifest(
      deleting_web_contents.get(), installability_future.GetCallback());
  EXPECT_TRUE(installability_future.Wait());

  EXPECT_EQ(installability_future.Get<webapps::InstallableStatusCode>(),
            webapps::InstallableStatusCode::RENDERER_CANCELLED);
}

IN_PROC_BROWSER_TEST_F(WebAppProfileDeletionTest_WebContentsGracefulShutdown,
                       DataRetrieverIconFetch) {
  ASSERT_TRUE(embedded_test_server()->Start());
  WebAppDataRetriever data_retriever;

  std::unique_ptr<content::WebContents> deleting_web_contents =
      CreateWebContentsScheduledForDeletion();

  base::test::TestFuture<blink::mojom::ManifestPtr, bool,
                         webapps::InstallableStatusCode>
      installability_future;
  data_retriever.CheckInstallabilityAndRetrieveManifest(
      deleting_web_contents.get(), installability_future.GetCallback());
  EXPECT_TRUE(installability_future.Wait());

  base::test::TestFuture<IconsDownloadedResult, IconsMap,
                         DownloadedIconsHttpResults>
      icon_download_future;
  IconUrlSizeSet icon_urls;
  icon_urls.insert(IconUrlWithSize::CreateForUnspecifiedSize(
      GURL("https://www.example.com/favicon.ico")));
  data_retriever.GetIcons(deleting_web_contents.get(), icon_urls,
                          /*skip_page_favicons=*/false,
                          /*fail_all_if_any_fail=*/false,
                          icon_download_future.GetCallback());
  EXPECT_TRUE(icon_download_future.Wait());

  EXPECT_EQ(icon_download_future.Get<IconsDownloadedResult>(),
            IconsDownloadedResult::kPrimaryPageChanged);
}

#endif  // !BUILDFLAG(IS_CHROMEOS)

}  // namespace web_app