File: password_manager_android_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 (270 lines) | stat: -rw-r--r-- 12,008 bytes parent folder | download | duplicates (3)
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
// 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 "base/android/build_info.h"
#include "base/functional/callback_helpers.h"
#include "base/metrics/statistics_recorder.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/current_thread.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/test_future.h"
#include "chrome/browser/keyboard_accessory/android/password_accessory_controller.h"
#include "chrome/browser/password_manager/account_password_store_factory.h"
#include "chrome/browser/password_manager/android/password_generation_controller.h"
#include "chrome/browser/password_manager/android/password_manager_test_utils_bridge.h"
#include "chrome/browser/password_manager/chrome_password_manager_client.h"
#include "chrome/browser/password_manager/passwords_navigation_observer.h"
#include "chrome/browser/password_manager/profile_password_store_factory.h"
#include "chrome/browser/touch_to_fill/password_manager/password_generation/android/touch_to_fill_password_generation_controller.h"
#include "chrome/test/base/android/android_browser_test.h"
#include "chrome/test/base/chrome_test_utils.h"
#include "components/autofill/core/common/autofill_test_utils.h"
#include "components/autofill/core/common/mojom/autofill_types.mojom-shared.h"
#include "components/autofill/core/common/unique_ids.h"
#include "components/keyed_service/core/service_access_type.h"
#include "components/password_manager/content/browser/content_password_manager_driver.h"
#include "components/password_manager/core/browser/password_form.h"
#include "components/password_manager/core/browser/password_store/password_store_results_observer.h"
#include "components/password_manager/core/browser/split_stores_and_local_upm.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gtest/include/gtest/gtest-param-test.h"
#include "testing/gtest/include/gtest/gtest.h"

class PasswordManagerAndroidBrowserTest
    : public AndroidBrowserTest,
      public testing::WithParamInterface<bool> {
 public:
  PasswordManagerAndroidBrowserTest()
      : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
    // Set a GMS Core version that is guaranteed to provide full UPM support.
    // This ensures that calls to the password store are derministically
    // routed to the android backend.
    base::android::BuildInfo::GetInstance()->set_gms_version_code_for_test(
        base::NumberToString(password_manager::GetLocalUpmMinGmsVersion()));
    // See crbug.com/331746629. The login database on Android will be
    // deprecated soon. So create a fake backend on GMS Core for password
    // storing.
    SetUpGmsCoreFakeBackends();
  }
  ~PasswordManagerAndroidBrowserTest() override = default;

  content::WebContents* GetActiveWebContents() {
    return chrome_test_utils::GetActiveWebContents(this);
  }

  void SetUpOnMainThread() override {
    // Map all out-going DNS lookups to the local server. This must be used in
    // conjunction with switches::kIgnoreCertificateErrors to work.
    host_resolver()->AddRule("*", "127.0.0.1");

    // Setup HTTPS server serving files from standard test directory.
    static constexpr base::FilePath::CharType kDocRoot[] =
        FILE_PATH_LITERAL("chrome/test/data");
    https_server_.ServeFilesFromSourceDirectory(base::FilePath(kDocRoot));
    ASSERT_TRUE(https_server_.Start());
  }

  void NavigateToFile(const std::string& file_path) {
    PasswordsNavigationObserver observer(GetActiveWebContents());
    EXPECT_TRUE(content::NavigateToURL(GetActiveWebContents(),
                                       https_server_.GetURL(file_path)));
    ASSERT_TRUE(observer.Wait());
  }

  const GURL& base_url() const { return https_server_.base_url(); }

  void WaitForHistogram(const std::string& histogram_name,
                        const base::HistogramTester& histogram_tester) {
    // Continue if histogram was already recorded.
    if (base::StatisticsRecorder::FindHistogram(histogram_name)) {
      return;
    }

    // Else, wait until the histogram is recorded.
    base::RunLoop run_loop;
    auto histogram_observer = std::make_unique<
        base::StatisticsRecorder::ScopedHistogramSampleObserver>(
        histogram_name,
        base::BindLambdaForTesting(
            [&](std::string_view histogram_name, uint64_t name_hash,
                base::HistogramBase::Sample32 sample) { run_loop.Quit(); }));
    run_loop.Run();
  }

  Profile* GetProfile() { return chrome_test_utils::GetProfile(this); }

  void WaitForPasswordStores() {
    scoped_refptr<password_manager::PasswordStoreInterface>
        profile_password_store = ProfilePasswordStoreFactory::GetForProfile(
            GetProfile(), ServiceAccessType::IMPLICIT_ACCESS);
    password_manager::PasswordStoreResultsObserver profile_syncer;
    profile_password_store->GetAllLoginsWithAffiliationAndBrandingInformation(
        profile_syncer.GetWeakPtr());
    profile_syncer.WaitForResults();

    scoped_refptr<password_manager::PasswordStoreInterface>
        account_password_store = AccountPasswordStoreFactory::GetForProfile(
            GetProfile(), ServiceAccessType::IMPLICIT_ACCESS);
    if (account_password_store) {
      password_manager::PasswordStoreResultsObserver account_syncer;
      account_password_store->GetAllLoginsWithAffiliationAndBrandingInformation(
          account_syncer.GetWeakPtr());
      account_syncer.WaitForResults();
    }
  }

 private:
  autofill::test::AutofillBrowserTestEnvironment environment_;
  net::EmbeddedTestServer https_server_;
};

IN_PROC_BROWSER_TEST_P(PasswordManagerAndroidBrowserTest,
                       TriggerFormSubmission) {
  base::HistogramTester uma_recorder;

  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          GetProfile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();

  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = base_url().spec();
  signin_form.url = base_url();
  signin_form.action = base_url();
  signin_form.username_value = u"username";
  signin_form.password_value = u"password";
  password_store->AddLogin(signin_form);
  WaitForPasswordStores();

  bool has_form_tag = GetParam();
  NavigateToFile(has_form_tag ? "/password/simple_password.html"
                              : "/password/no_form_element.html");

  password_manager::ContentPasswordManagerDriver* driver =
      password_manager::ContentPasswordManagerDriver::GetForRenderFrameHost(
          GetActiveWebContents()->GetPrimaryMainFrame());

  // There should be only one form with two fields in the test html.
  ASSERT_EQ(static_cast<const password_manager::PasswordManager*>(
                driver->GetPasswordManager())
                ->form_managers()
                .size(),
            1u);

  PasswordsNavigationObserver observer(GetActiveWebContents());
  observer.SetPathToWaitFor("/password/done.html");

  // A user taps the username field.
  ASSERT_TRUE(
      content::ExecJs(GetActiveWebContents(),
                      "document.getElementById('username_field').focus();"));

  // Because on some simulator bots, renderer may take longer time to finish
  // the "focus()" call.
  content::MainThreadFrameObserver frame_observer(
      GetActiveWebContents()->GetRenderWidgetHostView()->GetRenderWidgetHost());
  frame_observer.Wait();

  // A user accepts a credential in TouchToFill. That fills in the credential
  // and submits it.
  base::test::TestFuture<bool> completion_future;
  driver->FillSuggestion(u"username", u"password",
                         completion_future.GetCallback());
  ASSERT_TRUE(completion_future.Wait());

  // TouchToFill tracking starts after filling the form.
  ChromePasswordManagerClient::FromWebContents(GetActiveWebContents())
      ->StartSubmissionTrackingAfterTouchToFill(u"username");

  driver->TriggerFormSubmission();

  ASSERT_TRUE(observer.Wait());

  // Wait for the histogram to be ready to reduce flakiness.
  WaitForHistogram("PasswordManager.TouchToFill.TimeToSuccessfulLogin",
                   uma_recorder);
  uma_recorder.ExpectTotalCount(
      "PasswordManager.TouchToFill.TimeToSuccessfulLogin", 1);
}

// Tests that manual password generation can be triggered on the text field if
// field's name contains "password".
IN_PROC_BROWSER_TEST_P(PasswordManagerAndroidBrowserTest,
                       TriggerPasswordGenerationOnTextField) {
  password_manager::PasswordFormManager::
      set_wait_for_server_predictions_for_filling(false);

  NavigateToFile("/password/sign_in_with_password_type_text.html");

  password_manager::ContentPasswordManagerDriver* driver =
      password_manager::ContentPasswordManagerDriver::GetForRenderFrameHost(
          GetActiveWebContents()->GetPrimaryMainFrame());

  // After parsing, text field is considered as manual generation eligible
  // field.
  EXPECT_TRUE(base::test::RunUntil([driver]() {
    return driver->GetPasswordGenerationHelper()
               ->GenerationEnabledFieldsForTests()
               .size() == 1;
  }));
  const base::flat_set<autofill::FieldRendererId>& generation_enabled_fields =
      driver->GetPasswordGenerationHelper()->GenerationEnabledFieldsForTests();
  autofill::FieldRendererId password_field_renderer_id =
      *generation_enabled_fields.begin();

  // A user taps on the password field. JS call updates the last focused field
  // for `PasswordAutofillAgent`. `PasswordGenerationAgent` uses the last
  // focused field info to fill the manually generated password.
  // TODO: crbug.com/372635030 - Replace JS script and get rid of with
  // `ChromePasswordManagerClient::FocusedInputChanged` once
  // `SimulateMouseClickOrTapElementWithId` call starts creation of keyboard
  // accessory.
  ASSERT_TRUE(
      content::ExecJs(GetActiveWebContents(),
                      "document.getElementById('password_field').focus();"));
  // Wait because on some emulator bots the renderer may take longer time to
  // finish the "focus()" call.
  content::MainThreadFrameObserver frame_observer(
      GetActiveWebContents()->GetRenderWidgetHostView()->GetRenderWidgetHost());
  frame_observer.Wait();
  ChromePasswordManagerClient::FromWebContents(GetActiveWebContents())
      ->FocusedInputChanged(
          driver, password_field_renderer_id,
          autofill::mojom::FocusedFieldType::kFillableNonSearchField);
  // User generates the password manually.
  PasswordAccessoryController* password_accessory =
      PasswordAccessoryController::GetIfExisting(GetActiveWebContents());
  ASSERT_TRUE(password_accessory);
  password_accessory->OnOptionSelected(
      autofill::AccessoryAction::GENERATE_PASSWORD_MANUAL);

  PasswordGenerationController* password_generation_controller =
      PasswordGenerationController::GetIfExisting(GetActiveWebContents());

  // Wait till password generation bottomsheet is shown to the user.
  EXPECT_TRUE(base::test::RunUntil([&]() {
    return password_generation_controller
        ->GetTouchToFillGenerationControllerForTesting();
  }));
  TouchToFillPasswordGenerationController* touch_to_fill_generation_controller =
      password_generation_controller
          ->GetTouchToFillGenerationControllerForTesting();

  touch_to_fill_generation_controller->OnGeneratedPasswordAccepted(u"Password");

  EXPECT_TRUE(
      content::EvalJs(
          GetActiveWebContents(),
          "document.getElementById('password_field').value === \"Password\"")
          .ExtractBool());
}

INSTANTIATE_TEST_SUITE_P(VariateFormElementPresence,
                         PasswordManagerAndroidBrowserTest,
                         testing::Bool());