1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/password_manager/chrome_password_manager_client.h"
7 #include "base/bind_helpers.h"
8 #include "base/command_line.h"
9 #include "base/memory/singleton.h"
10 #include "base/metrics/histogram.h"
11 #include "base/prefs/pref_service.h"
12 #include "base/strings/string16.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "chrome/browser/browsing_data/browsing_data_helper.h"
15 #include "chrome/browser/password_manager/password_store_factory.h"
16 #include "chrome/browser/password_manager/save_password_infobar_delegate.h"
17 #include "chrome/browser/password_manager/sync_metrics.h"
18 #include "chrome/browser/profiles/profile.h"
19 #include "chrome/browser/sync/profile_sync_service.h"
20 #include "chrome/browser/sync/profile_sync_service_factory.h"
21 #include "chrome/browser/ui/autofill/password_generation_popup_controller_impl.h"
22 #include "chrome/browser/ui/passwords/manage_passwords_ui_controller.h"
23 #include "chrome/common/channel_info.h"
24 #include "chrome/common/chrome_switches.h"
25 #include "chrome/common/url_constants.h"
26 #include "components/autofill/content/browser/content_autofill_driver.h"
27 #include "components/autofill/content/browser/content_autofill_driver_factory.h"
28 #include "components/autofill/content/common/autofill_messages.h"
29 #include "components/autofill/core/browser/password_generator.h"
30 #include "components/autofill/core/common/password_form.h"
31 #include "components/password_manager/content/browser/content_password_manager_driver.h"
32 #include "components/password_manager/content/browser/password_manager_internals_service_factory.h"
33 #include "components/password_manager/content/common/credential_manager_messages.h"
34 #include "components/password_manager/core/browser/browser_save_password_progress_logger.h"
35 #include "components/password_manager/core/browser/log_receiver.h"
36 #include "components/password_manager/core/browser/password_form_manager.h"
37 #include "components/password_manager/core/browser/password_manager_internals_service.h"
38 #include "components/password_manager/core/browser/password_manager_metrics_util.h"
39 #include "components/password_manager/core/browser/password_manager_util.h"
40 #include "components/password_manager/core/common/credential_manager_types.h"
41 #include "components/password_manager/core/common/password_manager_pref_names.h"
42 #include "components/password_manager/core/common/password_manager_switches.h"
43 #include "components/version_info/version_info.h"
44 #include "content/public/browser/navigation_entry.h"
45 #include "content/public/browser/render_view_host.h"
46 #include "content/public/browser/web_contents.h"
47 #include "google_apis/gaia/gaia_urls.h"
48 #include "net/base/url_util.h"
49 #include "third_party/re2/re2/re2.h"
51 #if defined(OS_ANDROID)
52 #include "chrome/browser/password_manager/generated_password_saved_infobar_delegate_android.h"
55 using password_manager::ContentPasswordManagerDriverFactory
;
56 using password_manager::PasswordManagerInternalsService
;
57 using password_manager::PasswordManagerInternalsServiceFactory
;
59 // Shorten the name to spare line breaks. The code provides enough context
61 typedef autofill::SavePasswordProgressLogger Logger
;
63 DEFINE_WEB_CONTENTS_USER_DATA_KEY(ChromePasswordManagerClient
);
66 // This routine is called when PasswordManagerClient is constructed.
67 // Currently we report metrics only once at startup. We require
68 // that this is only ever called from a single thread in order to
69 // avoid needing to lock (a static boolean flag is then sufficient to
70 // guarantee running only once).
71 void ReportMetrics(bool password_manager_enabled
,
72 password_manager::PasswordManagerClient
* client
) {
73 static base::PlatformThreadId initial_thread_id
=
74 base::PlatformThread::CurrentId();
75 DCHECK_EQ(base::PlatformThread::CurrentId(), initial_thread_id
);
77 static bool ran_once
= false;
82 password_manager::PasswordStore
* store
= client
->GetPasswordStore();
83 // May be null in tests.
85 store
->ReportMetrics(client
->GetSyncUsername(),
86 client
->GetPasswordSyncState() ==
87 password_manager::SYNCING_WITH_CUSTOM_PASSPHRASE
);
89 UMA_HISTOGRAM_BOOLEAN("PasswordManager.Enabled", password_manager_enabled
);
95 void ChromePasswordManagerClient::CreateForWebContentsWithAutofillClient(
96 content::WebContents
* contents
,
97 autofill::AutofillClient
* autofill_client
) {
98 if (FromWebContents(contents
))
101 contents
->SetUserData(
103 new ChromePasswordManagerClient(contents
, autofill_client
));
106 ChromePasswordManagerClient::ChromePasswordManagerClient(
107 content::WebContents
* web_contents
,
108 autofill::AutofillClient
* autofill_client
)
109 : content::WebContentsObserver(web_contents
),
110 profile_(Profile::FromBrowserContext(web_contents
->GetBrowserContext())),
111 password_manager_(this),
112 driver_factory_(nullptr),
113 credential_manager_dispatcher_(web_contents
, this),
115 can_use_log_router_(false),
116 autofill_sync_state_(ALLOW_SYNC_CREDENTIALS
),
117 sync_credential_was_filtered_(false) {
118 ContentPasswordManagerDriverFactory::CreateForWebContents(web_contents
, this,
121 ContentPasswordManagerDriverFactory::FromWebContents(web_contents
);
123 PasswordManagerInternalsService
* service
=
124 PasswordManagerInternalsServiceFactory::GetForBrowserContext(profile_
);
126 can_use_log_router_
= service
->RegisterClient(this);
127 SetUpAutofillSyncState();
128 saving_passwords_enabled_
.Init(
129 password_manager::prefs::kPasswordManagerSavingEnabled
, GetPrefs());
130 ReportMetrics(*saving_passwords_enabled_
, this);
133 ChromePasswordManagerClient::~ChromePasswordManagerClient() {
134 PasswordManagerInternalsService
* service
=
135 PasswordManagerInternalsServiceFactory::GetForBrowserContext(profile_
);
137 service
->UnregisterClient(this);
140 bool ChromePasswordManagerClient::IsAutomaticPasswordSavingEnabled() const {
141 return base::CommandLine::ForCurrentProcess()->HasSwitch(
142 password_manager::switches::kEnableAutomaticPasswordSaving
) &&
143 chrome::GetChannel() == version_info::Channel::UNKNOWN
;
146 bool ChromePasswordManagerClient::IsPasswordManagementEnabledForCurrentPage()
148 DCHECK(web_contents());
149 content::NavigationEntry
* entry
=
150 web_contents()->GetController().GetLastCommittedEntry();
151 bool is_enabled
= false;
153 // TODO(gcasto): Determine if fix for crbug.com/388246 is relevant here.
155 } else if (IsURLPasswordWebsiteReauth(entry
->GetURL())) {
156 // Disable the password manager for online password management.
158 } else if (EnabledForSyncSignin()) {
161 // Do not fill nor save password when a user is signing in for sync. This
162 // is because users need to remember their password if they are syncing as
163 // this is effectively their master password.
164 is_enabled
= entry
->GetURL().host() != chrome::kChromeUIChromeSigninHost
;
166 if (IsLoggingActive()) {
167 password_manager::BrowserSavePasswordProgressLogger
logger(this);
169 Logger::STRING_PASSWORD_MANAGEMENT_ENABLED_FOR_CURRENT_PAGE
,
175 bool ChromePasswordManagerClient::IsSavingEnabledForCurrentPage() const {
176 return *saving_passwords_enabled_
&& !IsOffTheRecord() &&
177 !DidLastPageLoadEncounterSSLErrors() &&
178 IsPasswordManagementEnabledForCurrentPage();
181 bool ChromePasswordManagerClient::ShouldFilterAutofillResult(
182 const autofill::PasswordForm
& form
) {
183 if (!IsSyncAccountCredential(base::UTF16ToUTF8(form
.username_value
),
187 if (autofill_sync_state_
== DISALLOW_SYNC_CREDENTIALS
) {
188 sync_credential_was_filtered_
= true;
192 if (autofill_sync_state_
== DISALLOW_SYNC_CREDENTIALS_FOR_REAUTH
&&
193 LastLoadWasTransactionalReauthPage()) {
194 sync_credential_was_filtered_
= true;
201 std::string
ChromePasswordManagerClient::GetSyncUsername() const {
202 return password_manager_sync_metrics::GetSyncUsername(profile_
);
205 bool ChromePasswordManagerClient::IsSyncAccountCredential(
206 const std::string
& username
,
207 const std::string
& realm
) const {
208 return password_manager_sync_metrics::IsSyncAccountCredential(
209 profile_
, username
, realm
);
212 void ChromePasswordManagerClient::AutofillResultsComputed() {
213 UMA_HISTOGRAM_BOOLEAN("PasswordManager.SyncCredentialFiltered",
214 sync_credential_was_filtered_
);
215 sync_credential_was_filtered_
= false;
218 bool ChromePasswordManagerClient::PromptUserToSaveOrUpdatePassword(
219 scoped_ptr
<password_manager::PasswordFormManager
> form_to_save
,
220 password_manager::CredentialSourceType type
,
221 bool update_password
) {
222 // Save password infobar and the password bubble prompts in case of
223 // "webby" URLs and do not prompt in case of "non-webby" URLS (e.g. file://).
224 if (!BrowsingDataHelper::IsWebScheme(
225 web_contents()->GetLastCommittedURL().scheme())) {
229 if (IsTheHotNewBubbleUIEnabled()) {
230 ManagePasswordsUIController
* manage_passwords_ui_controller
=
231 ManagePasswordsUIController::FromWebContents(web_contents());
232 if (update_password
&& IsUpdatePasswordUIEnabled()) {
233 manage_passwords_ui_controller
->OnUpdatePasswordSubmitted(
234 form_to_save
.Pass());
236 manage_passwords_ui_controller
->OnPasswordSubmitted(form_to_save
.Pass());
239 std::string
uma_histogram_suffix(
240 password_manager::metrics_util::GroupIdToString(
241 password_manager::metrics_util::MonitoredDomainGroupId(
242 form_to_save
->realm(), GetPrefs())));
243 SavePasswordInfoBarDelegate::Create(
244 web_contents(), form_to_save
.Pass(), uma_histogram_suffix
, type
);
249 bool ChromePasswordManagerClient::PromptUserToChooseCredentials(
250 ScopedVector
<autofill::PasswordForm
> local_forms
,
251 ScopedVector
<autofill::PasswordForm
> federated_forms
,
253 base::Callback
<void(const password_manager::CredentialInfo
&)> callback
) {
254 return ManagePasswordsUIController::FromWebContents(web_contents())->
255 OnChooseCredentials(local_forms
.Pass(), federated_forms
.Pass(), origin
,
259 void ChromePasswordManagerClient::ForceSavePassword() {
260 password_manager::ContentPasswordManagerDriver
* driver
=
261 driver_factory_
->GetDriverForFrame(web_contents()->GetFocusedFrame());
262 driver
->ForceSavePassword();
265 void ChromePasswordManagerClient::NotifyUserAutoSignin(
266 ScopedVector
<autofill::PasswordForm
> local_forms
) {
267 DCHECK(!local_forms
.empty());
268 ManagePasswordsUIController::FromWebContents(web_contents())->
269 OnAutoSignin(local_forms
.Pass());
272 void ChromePasswordManagerClient::AutomaticPasswordSave(
273 scoped_ptr
<password_manager::PasswordFormManager
> saved_form
) {
274 #if defined(OS_ANDROID)
275 GeneratedPasswordSavedInfoBarDelegateAndroid::Create(web_contents());
277 if (IsTheHotNewBubbleUIEnabled()) {
278 ManagePasswordsUIController
* manage_passwords_ui_controller
=
279 ManagePasswordsUIController::FromWebContents(web_contents());
280 manage_passwords_ui_controller
->OnAutomaticPasswordSave(
286 void ChromePasswordManagerClient::PasswordWasAutofilled(
287 const autofill::PasswordFormMap
& best_matches
) const {
288 ManagePasswordsUIController
* manage_passwords_ui_controller
=
289 ManagePasswordsUIController::FromWebContents(web_contents());
290 if (manage_passwords_ui_controller
&& IsTheHotNewBubbleUIEnabled())
291 manage_passwords_ui_controller
->OnPasswordAutofilled(best_matches
);
294 void ChromePasswordManagerClient::PasswordAutofillWasBlocked(
295 const autofill::PasswordFormMap
& best_matches
) const {
296 ManagePasswordsUIController
* controller
=
297 ManagePasswordsUIController::FromWebContents(web_contents());
298 if (controller
&& IsTheHotNewBubbleUIEnabled())
299 controller
->OnBlacklistBlockedAutofill(best_matches
);
302 void ChromePasswordManagerClient::HidePasswordGenerationPopup() {
303 if (popup_controller_
)
304 popup_controller_
->HideAndDestroy();
307 PrefService
* ChromePasswordManagerClient::GetPrefs() {
308 return profile_
->GetPrefs();
311 password_manager::PasswordStore
*
312 ChromePasswordManagerClient::GetPasswordStore() const {
313 // Always use EXPLICIT_ACCESS as the password manager checks IsOffTheRecord
314 // itself when it shouldn't access the PasswordStore.
315 // TODO(gcasto): Is is safe to change this to
316 // ServiceAccessType::IMPLICIT_ACCESS?
317 return PasswordStoreFactory::GetForProfile(
318 profile_
, ServiceAccessType::EXPLICIT_ACCESS
).get();
321 password_manager::PasswordSyncState
322 ChromePasswordManagerClient::GetPasswordSyncState() const {
323 const ProfileSyncService
* sync_service
=
324 ProfileSyncServiceFactory::GetForProfile(profile_
);
325 return password_manager_util::GetPasswordSyncState(sync_service
);
328 void ChromePasswordManagerClient::OnLogRouterAvailabilityChanged(
329 bool router_can_be_used
) {
330 if (can_use_log_router_
== router_can_be_used
)
332 can_use_log_router_
= router_can_be_used
;
334 NotifyRendererOfLoggingAvailability();
337 void ChromePasswordManagerClient::LogSavePasswordProgress(
338 const std::string
& text
) const {
339 if (!IsLoggingActive())
341 PasswordManagerInternalsService
* service
=
342 PasswordManagerInternalsServiceFactory::GetForBrowserContext(profile_
);
344 service
->ProcessLog(text
);
347 bool ChromePasswordManagerClient::IsLoggingActive() const {
348 // WebUI tabs do not need to log password saving progress. In particular, the
349 // internals page itself should not send any logs.
350 return can_use_log_router_
&& !web_contents()->GetWebUI();
353 bool ChromePasswordManagerClient::WasLastNavigationHTTPError() const {
354 DCHECK(web_contents());
356 scoped_ptr
<password_manager::BrowserSavePasswordProgressLogger
> logger
;
357 if (IsLoggingActive()) {
358 logger
.reset(new password_manager::BrowserSavePasswordProgressLogger(this));
360 Logger::STRING_WAS_LAST_NAVIGATION_HTTP_ERROR_METHOD
);
363 content::NavigationEntry
* entry
=
364 web_contents()->GetController().GetVisibleEntry();
367 int http_status_code
= entry
->GetHttpStatusCode();
370 logger
->LogNumber(Logger::STRING_HTTP_STATUS_CODE
, http_status_code
);
372 if (http_status_code
>= 400 && http_status_code
< 600)
377 bool ChromePasswordManagerClient::DidLastPageLoadEncounterSSLErrors() const {
378 content::NavigationEntry
* entry
=
379 web_contents()->GetController().GetLastCommittedEntry();
380 bool ssl_errors
= true;
384 ssl_errors
= net::IsCertStatusError(entry
->GetSSL().cert_status
);
386 if (IsLoggingActive()) {
387 password_manager::BrowserSavePasswordProgressLogger
logger(this);
388 logger
.LogBoolean(Logger::STRING_SSL_ERRORS_PRESENT
, ssl_errors
);
393 bool ChromePasswordManagerClient::IsOffTheRecord() const {
394 return web_contents()->GetBrowserContext()->IsOffTheRecord();
397 password_manager::PasswordManager
*
398 ChromePasswordManagerClient::GetPasswordManager() {
399 return &password_manager_
;
402 autofill::AutofillManager
*
403 ChromePasswordManagerClient::GetAutofillManagerForMainFrame() {
404 autofill::ContentAutofillDriverFactory
* factory
=
405 autofill::ContentAutofillDriverFactory::FromWebContents(web_contents());
407 ? factory
->DriverForFrame(web_contents()->GetMainFrame())
412 void ChromePasswordManagerClient::SetTestObserver(
413 autofill::PasswordGenerationPopupObserver
* observer
) {
414 observer_
= observer
;
417 bool ChromePasswordManagerClient::OnMessageReceived(
418 const IPC::Message
& message
,
419 content::RenderFrameHost
* render_frame_host
) {
421 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(ChromePasswordManagerClient
, message
,
423 // Autofill messages:
424 IPC_MESSAGE_HANDLER(AutofillHostMsg_ShowPasswordGenerationPopup
,
425 ShowPasswordGenerationPopup
)
426 IPC_MESSAGE_HANDLER(AutofillHostMsg_ShowPasswordEditingPopup
,
427 ShowPasswordEditingPopup
)
428 IPC_END_MESSAGE_MAP()
430 IPC_BEGIN_MESSAGE_MAP(ChromePasswordManagerClient
, message
)
431 IPC_MESSAGE_HANDLER(AutofillHostMsg_HidePasswordGenerationPopup
,
432 HidePasswordGenerationPopup
)
433 IPC_MESSAGE_HANDLER(AutofillHostMsg_PasswordAutofillAgentConstructed
,
434 NotifyRendererOfLoggingAvailability
)
436 IPC_MESSAGE_UNHANDLED(handled
= false)
437 IPC_END_MESSAGE_MAP()
442 gfx::RectF
ChromePasswordManagerClient::GetBoundsInScreenSpace(
443 const gfx::RectF
& bounds
) {
444 gfx::Rect client_area
= web_contents()->GetContainerBounds();
445 return bounds
+ client_area
.OffsetFromOrigin();
448 void ChromePasswordManagerClient::ShowPasswordGenerationPopup(
449 content::RenderFrameHost
* render_frame_host
,
450 const gfx::RectF
& bounds
,
452 const autofill::PasswordForm
& form
) {
453 // TODO(gcasto): Validate data in PasswordForm.
455 gfx::RectF element_bounds_in_screen_space
= GetBoundsInScreenSpace(bounds
);
458 autofill::PasswordGenerationPopupControllerImpl::GetOrCreate(
459 popup_controller_
, element_bounds_in_screen_space
, form
, max_length
,
461 driver_factory_
->GetDriverForFrame(render_frame_host
), observer_
,
462 web_contents(), web_contents()->GetNativeView());
463 popup_controller_
->Show(true /* display_password */);
466 void ChromePasswordManagerClient::ShowPasswordEditingPopup(
467 content::RenderFrameHost
* render_frame_host
,
468 const gfx::RectF
& bounds
,
469 const autofill::PasswordForm
& form
) {
470 gfx::RectF element_bounds_in_screen_space
= GetBoundsInScreenSpace(bounds
);
472 autofill::PasswordGenerationPopupControllerImpl::GetOrCreate(
473 popup_controller_
, element_bounds_in_screen_space
, form
,
474 0, // Unspecified max length.
476 driver_factory_
->GetDriverForFrame(render_frame_host
), observer_
,
477 web_contents(), web_contents()->GetNativeView());
478 popup_controller_
->Show(false /* display_password */);
481 void ChromePasswordManagerClient::NotifyRendererOfLoggingAvailability() {
485 web_contents()->GetRenderViewHost()->Send(new AutofillMsg_SetLoggingState(
486 web_contents()->GetRenderViewHost()->GetRoutingID(),
487 can_use_log_router_
));
490 bool ChromePasswordManagerClient::LastLoadWasTransactionalReauthPage() const {
491 DCHECK(web_contents());
492 content::NavigationEntry
* entry
=
493 web_contents()->GetController().GetLastCommittedEntry();
497 if (entry
->GetURL().GetOrigin() !=
498 GaiaUrls::GetInstance()->gaia_url().GetOrigin())
501 // "rart" is the transactional reauth paramter.
502 std::string ignored_value
;
503 return net::GetValueForKeyInQuery(entry
->GetURL(),
508 bool ChromePasswordManagerClient::IsURLPasswordWebsiteReauth(
509 const GURL
& url
) const {
510 if (url
.GetOrigin() != GaiaUrls::GetInstance()->gaia_url().GetOrigin())
513 // "rart" param signals this page is for transactional reauth.
514 std::string param_value
;
515 if (!net::GetValueForKeyInQuery(url
, "rart", ¶m_value
))
518 // Check the "continue" param to see if this reauth page is for the passwords
521 if (!net::GetValueForKeyInQuery(url
, "continue", ¶m_value
))
524 // All password sites, including test sites, have autofilling disabled.
525 CR_DEFINE_STATIC_LOCAL(RE2
, account_dashboard_pattern
,
526 ("passwords(-([a-z-]+\\.corp))?\\.google\\.com"));
528 return RE2::FullMatch(GURL(param_value
).host(), account_dashboard_pattern
);
531 bool ChromePasswordManagerClient::IsTheHotNewBubbleUIEnabled() {
532 #if !defined(USE_AURA) && !defined(OS_MACOSX)
535 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
536 if (command_line
->HasSwitch(switches::kDisableSavePasswordBubble
))
539 if (command_line
->HasSwitch(switches::kEnableSavePasswordBubble
))
542 std::string group_name
=
543 base::FieldTrialList::FindFullName("PasswordManagerUI");
545 // The bubble should be the default case that runs on the bots.
546 return group_name
!= "Infobar";
549 bool ChromePasswordManagerClient::IsUpdatePasswordUIEnabled() const {
550 if (!ChromePasswordManagerClient::IsTheHotNewBubbleUIEnabled()) {
551 // Currently Password update UI is implemented only for Bubble UI.
554 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
555 return command_line
->HasSwitch(
556 password_manager::switches::kEnablePasswordChangeSupport
);
559 bool ChromePasswordManagerClient::EnabledForSyncSignin() {
560 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
561 if (command_line
->HasSwitch(
562 password_manager::switches::kDisableManagerForSyncSignin
))
565 if (command_line
->HasSwitch(
566 password_manager::switches::kEnableManagerForSyncSignin
))
569 // Default is enabled.
570 std::string group_name
=
571 base::FieldTrialList::FindFullName("PasswordManagerStateForSyncSignin");
572 return group_name
!= "Disabled";
575 void ChromePasswordManagerClient::SetUpAutofillSyncState() {
576 std::string group_name
=
577 base::FieldTrialList::FindFullName("AutofillSyncCredential");
579 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
580 if (command_line
->HasSwitch(
581 password_manager::switches::kAllowAutofillSyncCredential
)) {
582 autofill_sync_state_
= ALLOW_SYNC_CREDENTIALS
;
585 if (command_line
->HasSwitch(
586 password_manager::switches::
587 kDisallowAutofillSyncCredentialForReauth
)) {
588 autofill_sync_state_
= DISALLOW_SYNC_CREDENTIALS_FOR_REAUTH
;
591 if (command_line
->HasSwitch(
592 password_manager::switches::kDisallowAutofillSyncCredential
)) {
593 autofill_sync_state_
= DISALLOW_SYNC_CREDENTIALS
;
597 if (group_name
== "DisallowSyncCredentialsForReauth") {
598 autofill_sync_state_
= DISALLOW_SYNC_CREDENTIALS_FOR_REAUTH
;
599 } else if (group_name
== "DisallowSyncCredentials") {
600 autofill_sync_state_
= DISALLOW_SYNC_CREDENTIALS
;
603 autofill_sync_state_
= ALLOW_SYNC_CREDENTIALS
;
607 const GURL
& ChromePasswordManagerClient::GetMainFrameURL() const {
608 return web_contents()->GetVisibleURL();