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.
4 
5 #ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_MANAGER_CLIENT_H_
6 #define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_MANAGER_CLIENT_H_
7 
8 #include <memory>
9 #include <string>
10 #include <vector>
11 
12 #include "base/callback.h"
13 #include "base/macros.h"
14 #include "base/memory/scoped_refptr.h"
15 #include "base/util/type_safety/strong_alias.h"
16 #include "build/build_config.h"
17 #include "components/autofill/core/common/mojom/autofill_types.mojom.h"
18 #include "components/autofill/core/common/password_form.h"
19 #include "components/password_manager/core/browser/credentials_filter.h"
20 #include "components/password_manager/core/browser/hsts_query.h"
21 #include "components/password_manager/core/browser/http_auth_manager.h"
22 #include "components/password_manager/core/browser/leak_detection_dialog_utils.h"
23 #include "components/password_manager/core/browser/manage_passwords_referrer.h"
24 #include "components/password_manager/core/browser/password_manager_metrics_util.h"
25 #include "components/password_manager/core/browser/password_reuse_detector.h"
26 #include "components/password_manager/core/browser/password_store.h"
27 #include "components/safe_browsing/buildflags.h"
28 #include "net/cert/cert_status_flags.h"
29 #include "services/metrics/public/cpp/ukm_recorder.h"
30 
31 class PrefService;
32 
33 namespace autofill {
34 class AutofillDownloadManager;
35 class LogManager;
36 }  // namespace autofill
37 
38 namespace favicon {
39 class FaviconService;
40 }
41 
42 namespace network {
43 class SharedURLLoaderFactory;
44 }  // namespace network
45 
46 namespace signin {
47 class IdentityManager;
48 }  // namespace signin
49 
50 struct CoreAccountId;
51 class GURL;
52 
53 #if defined(ON_FOCUS_PING_ENABLED)
54 namespace safe_browsing {
55 class PasswordProtectionService;
56 }
57 #endif
58 
59 namespace password_manager {
60 
61 class FieldInfoManager;
62 class PasswordFeatureManager;
63 class BiometricAuthenticator;
64 class PasswordFormManagerForUI;
65 class PasswordManager;
66 class PasswordManagerDriver;
67 class PasswordManagerMetricsRecorder;
68 class HttpAuthManager;
69 class PasswordRequirementsService;
70 class PasswordStore;
71 
72 enum SyncState {
73   NOT_SYNCING,
74   SYNCING_NORMAL_ENCRYPTION,
75   SYNCING_WITH_CUSTOM_PASSPHRASE,
76   ACCOUNT_PASSWORDS_ACTIVE_NORMAL_ENCRYPTION
77 };
78 
79 // An abstraction of operations that depend on the embedders (e.g. Chrome)
80 // environment.
81 class PasswordManagerClient {
82  public:
83   using CredentialsCallback =
84       base::Callback<void(const autofill::PasswordForm*)>;
85   using ReauthSucceeded = util::StrongAlias<class ReauthSucceededTag, bool>;
86 
PasswordManagerClient()87   PasswordManagerClient() {}
~PasswordManagerClient()88   virtual ~PasswordManagerClient() {}
89 
90   // Is saving new data for password autofill and filling of saved data enabled
91   // for the current profile and page? For example, saving is disabled in
92   // Incognito mode. |url| describes the URL to save the password for. It is not
93   // necessary the URL of the current page but can be a URL of a proxy or the
94   // page that hosted the form.
95   virtual bool IsSavingAndFillingEnabled(const GURL& url) const;
96 
97   // Checks if filling is enabled on the current page. Filling is disabled in
98   // the presence of SSL errors on a page. |url| describes the URL to fill the
99   // password for. It is not necessary the URL of the current page but can be a
100   // URL of a proxy or subframe.
101   virtual bool IsFillingEnabled(const GURL& url) const;
102 
103   // Checks if manual filling fallback is enabled for the page that has |url|
104   // address.
105   virtual bool IsFillingFallbackEnabled(const GURL& url) const;
106 
107   // Checks asynchronously whether HTTP Strict Transport Security (HSTS) is
108   // active for the host of the given origin. Notifies |callback| with the
109   // result on the calling thread.
110   virtual void PostHSTSQueryForHost(const GURL& origin,
111                                     HSTSCallback callback) const;
112 
113   // Checks if the Credential Manager API is allowed to run on the page. It's
114   // not allowed while prerendering and the pre-rendered WebContents will be
115   // destroyed in this case.
116   // Even if the method returns true the API may still be disabled or limited
117   // depending on the method called because IsFillingEnabled() and
118   // IsSavingAndFillingEnabled are respected.
119   virtual bool OnCredentialManagerUsed();
120 
121   // Informs the embedder of a password form that can be saved or updated in
122   // password store if the user allows it. The embedder is not required to
123   // prompt the user if it decides that this form doesn't need to be saved or
124   // updated. Returns true if the prompt was indeed displayed.
125   // There are 3 different cases when |update_password| == true:
126   // 1.A change password form was submitted and the user has only one stored
127   // credential. Then form_to_save.GetPendingCredentials() should correspond to
128   // the unique element from |form_to_save.best_matches_|.
129   // 2.A change password form was submitted and the user has more than one
130   // stored credential. Then we shouldn't expect anything from
131   // form_to_save.GetPendingCredentials() except correct origin, since we don't
132   // know which credentials should be updated.
133   // 3.A sign-in password form was submitted with a password different from
134   // the stored one. In this case form_to_save.IsPasswordOverridden() == true
135   // and form_to_save.GetPendingCredentials() should correspond to the
136   // credential that was overidden.
137   virtual bool PromptUserToSaveOrUpdatePassword(
138       std::unique_ptr<PasswordFormManagerForUI> form_to_save,
139       bool is_update) = 0;
140 
141   // Informs the embedder that the onboarding experience should be shown.
142   // This will also offer the ability to actually save the password.
143   // Returns true if both the onboarding and the saving prompt were displayed.
144   virtual bool ShowOnboarding(
145       std::unique_ptr<PasswordFormManagerForUI> form_to_save) = 0;
146 
147   // Informs the embedder that the user started typing a password and a password
148   // prompt should be available on click on the omnibox icon.
149   virtual void ShowManualFallbackForSaving(
150       std::unique_ptr<PasswordFormManagerForUI> form_to_save,
151       bool has_generated_password,
152       bool is_update) = 0;
153 
154   // Informs the embedder that the user cleared the password field and the
155   // fallback for password saving should be not available.
156   virtual void HideManualFallbackForSaving() = 0;
157 
158   // Informs the embedder that the focus changed to a different input in the
159   // same frame (e.g. tabbed from email to password field).
160   virtual void FocusedInputChanged(
161       PasswordManagerDriver* driver,
162       autofill::mojom::FocusedFieldType focused_field_type) = 0;
163 
164   // Informs the embedder of a password forms that the user should choose from.
165   // Returns true if the prompt is indeed displayed. If the prompt is not
166   // displayed, returns false and does not call |callback|.
167   // |callback| should be invoked with the chosen form.
168   virtual bool PromptUserToChooseCredentials(
169       std::vector<std::unique_ptr<autofill::PasswordForm>> local_forms,
170       const GURL& origin,
171       const CredentialsCallback& callback) = 0;
172 
173   // Instructs the client to show the Touch To Fill UI.
174   virtual void ShowTouchToFill(PasswordManagerDriver* driver);
175 
176   // Returns a pointer to a BiometricAuthenticator. Might be null if
177   // BiometricAuthentication is not available for a given platform.
178   virtual BiometricAuthenticator* GetBiometricAuthenticator();
179 
180   // Informs the embedder that the user has manually requested to generate a
181   // password in the focused password field.
182   virtual void GeneratePassword();
183 
184   // Informs the embedder that automatic signing in just happened. The form
185   // returned to the site is |local_forms[0]|. |local_forms| contains all the
186   // local credentials for the site. |origin| is a URL of the site the user was
187   // auto signed in to.
188   virtual void NotifyUserAutoSignin(
189       std::vector<std::unique_ptr<autofill::PasswordForm>> local_forms,
190       const GURL& origin) = 0;
191 
192   // Inform the embedder that automatic signin would have happened if the user
193   // had been through the first-run experience to ensure their opt-in. |form|
194   // contains the PasswordForm that would have been delivered.
195   virtual void NotifyUserCouldBeAutoSignedIn(
196       std::unique_ptr<autofill::PasswordForm> form) = 0;
197 
198   // Inform the embedder that the user signed in with a saved credential.
199   // |form| contains the form used.
200   virtual void NotifySuccessfulLoginWithExistingPassword(
201       const autofill::PasswordForm& form) = 0;
202 
203   // Inform the embedder that the site called 'store()'.
204   virtual void NotifyStorePasswordCalled() = 0;
205 
206   // Update the CredentialCache used to display fetched credentials in the UI.
207   // Currently only implemented on Android.
208   virtual void UpdateCredentialCache(
209       const GURL& origin,
210       const std::vector<const autofill::PasswordForm*>& best_matches,
211       bool is_blacklisted);
212 
213   // Called when a password is saved in an automated fashion. Embedder may
214   // inform the user that this save has occurred.
215   virtual void AutomaticPasswordSave(
216       std::unique_ptr<PasswordFormManagerForUI> saved_form_manager) = 0;
217 
218   // Called when a password is autofilled. |best_matches| contains the
219   // PasswordForm into which a password was filled: the client may choose to
220   // save this to the PasswordStore, for example. |origin| is the origin of the
221   // form into which a password was filled. |federated_matches| are the stored
222   // federated matches relevant to the filled form, this argument may be null.
223   // They are never filled, but might be needed in the UI, for example. Default
224   // implementation is a noop.
225   virtual void PasswordWasAutofilled(
226       const std::vector<const autofill::PasswordForm*>& best_matches,
227       const GURL& origin,
228       const std::vector<const autofill::PasswordForm*>* federated_matches);
229 
230   // Sends username/password from |preferred_match| for filling in the http auth
231   // prompt.
232   virtual void AutofillHttpAuth(const autofill::PasswordForm& preferred_match,
233                                 const PasswordFormManagerForUI* form_manager);
234 
235   // Informs the embedder that user credentials were leaked.
236   virtual void NotifyUserCredentialsWereLeaked(CredentialLeakType leak_type,
237                                                const GURL& origin,
238                                                const base::string16& username);
239 
240   // Requests a reauth for the given |account_id| and triggers the
241   // |reauth_callback| with ReauthSucceeded(true) if reauthentication succeeded.
242   virtual void TriggerReauthForAccount(
243       const CoreAccountId& account_id,
244       base::OnceCallback<void(ReauthSucceeded)> reauth_callback);
245 
246   // Gets prefs associated with this embedder.
247   virtual PrefService* GetPrefs() const = 0;
248 
249   // Returns the profile PasswordStore associated with this instance.
250   virtual PasswordStore* GetProfilePasswordStore() const = 0;
251 
252   // Returns the account PasswordStore associated with this instance.
253   virtual PasswordStore* GetAccountPasswordStore() const = 0;
254 
255   // Reports whether and how passwords are synced in the embedder. The default
256   // implementation always returns NOT_SYNCING.
257   virtual SyncState GetPasswordSyncState() const;
258 
259   // Returns true if last navigation page had HTTP error i.e 5XX or 4XX
260   virtual bool WasLastNavigationHTTPError() const;
261 
262   // Returns true if a credential leak dialog was shown. Used by Autofill
263   // Assistance to verify a password change intent. TODO(b/151391231): Remove
264   // when proper intent signing is implemented.
265   virtual bool WasCredentialLeakDialogShown() const;
266 
267   // Obtains the cert status for the main frame.
268   virtual net::CertStatus GetMainFrameCertStatus() const;
269 
270   // Shows the dialog where the user can accept or decline the global autosignin
271   // setting as a first run experience.
272   virtual void PromptUserToEnableAutosignin();
273 
274   // If this browsing session should not be persisted.
275   virtual bool IsIncognito() const;
276 
277   // Returns the PasswordManager associated with this client. The non-const
278   // version calls the const one.
279   PasswordManager* GetPasswordManager();
280   virtual const PasswordManager* GetPasswordManager() const;
281 
282   // Returns the PasswordFeatureManager associated with this client. The
283   // non-const version calls the const one.
284   PasswordFeatureManager* GetPasswordFeatureManager();
285   virtual const PasswordFeatureManager* GetPasswordFeatureManager() const;
286 
287   // Returns the HttpAuthManager associated with this client.
288   virtual HttpAuthManager* GetHttpAuthManager();
289 
290   // Returns the AutofillDownloadManager for votes uploading.
291   virtual autofill::AutofillDownloadManager* GetAutofillDownloadManager();
292 
293   // Returns the main frame URL.
294   virtual const GURL& GetMainFrameURL() const;
295 
296   // Returns true if the main frame URL has a secure origin.
297   virtual bool IsMainFrameSecure() const;
298 
299   virtual const GURL& GetLastCommittedEntryURL() const = 0;
300 
301   // Use this to filter credentials before handling them in password manager.
302   virtual const CredentialsFilter* GetStoreResultFilter() const = 0;
303 
304   // Returns a LogManager instance.
305   virtual const autofill::LogManager* GetLogManager() const;
306 
307   // Record that we saw a password field on this page.
308   virtual void AnnotateNavigationEntry(bool has_password_field);
309 
310   // Returns the current best guess as to the page's display language.
311   virtual std::string GetPageLanguage() const;
312 
313 #if defined(ON_FOCUS_PING_ENABLED)
314   // Return the PasswordProtectionService associated with this instance.
315   virtual safe_browsing::PasswordProtectionService*
316   GetPasswordProtectionService() const = 0;
317 
318   // Checks the safe browsing reputation of the webpage when the
319   // user focuses on a username/password field. This is used for reporting
320   // only, and won't trigger a warning.
321   virtual void CheckSafeBrowsingReputation(const GURL& form_action,
322                                            const GURL& frame_url) = 0;
323 #endif
324 
325 #if defined(SYNC_PASSWORD_REUSE_DETECTION_ENABLED)
326   // Checks the safe browsing reputation of the webpage where password reuse
327   // happens. This is called by the PasswordReuseDetectionManager when a
328   // protected password is typed on the wrong domain. This may trigger a
329   // warning dialog if it looks like the page is phishy.
330   // The |username| is the user name of the reused password. The user name
331   // can be an email or a username for a non-GAIA or saved-password reuse. No
332   // validation has been done on it.
333   virtual void CheckProtectedPasswordEntry(
334       metrics_util::PasswordType reused_password_type,
335       const std::string& username,
336       const std::vector<MatchingReusedCredential>& matching_reused_credentials,
337       bool password_field_exists) = 0;
338 #endif
339 
340 #if defined(SYNC_PASSWORD_REUSE_WARNING_ENABLED)
341   // Records a Chrome Sync event that GAIA password reuse was detected.
342   virtual void LogPasswordReuseDetectedEvent() = 0;
343 #endif
344 
345   // Gets a ukm::SourceId that is associated with the WebContents object
346   // and its last committed main frame navigation.
347   virtual ukm::SourceId GetUkmSourceId() = 0;
348 
349   // Gets a metrics recorder for the currently committed navigation.
350   // As PasswordManagerMetricsRecorder submits metrics on destruction, a new
351   // instance will be returned for each committed navigation. A caller must not
352   // hold on to the pointer. This method returns a nullptr if the client
353   // does not support metrics recording.
354   virtual PasswordManagerMetricsRecorder* GetMetricsRecorder() = 0;
355 
356   // Gets the PasswordRequirementsService associated with the client. It is
357   // valid that this method returns a nullptr if the PasswordRequirementsService
358   // has not been implemented for a specific platform or the context is an
359   // incognito context. Callers should guard against this.
360   virtual PasswordRequirementsService* GetPasswordRequirementsService();
361 
362   // Returns the favicon service used to retrieve icons for an origin.
363   virtual favicon::FaviconService* GetFaviconService();
364 
365   // Returns the identity manager for profile.
366   virtual signin::IdentityManager* GetIdentityManager() = 0;
367 
368   // Returns a pointer to the URLLoaderFactory owned by the storage partition of
369   // the current profile.
370   virtual scoped_refptr<network::SharedURLLoaderFactory>
371   GetURLLoaderFactory() = 0;
372 
373   // Whether the primary account of the current profile is under Advanced
374   // Protection - a type of Google Account that helps protect our most at-risk
375   // users.
376   virtual bool IsUnderAdvancedProtection() const;
377 
378   // Causes all live PasswordFormManager objects to query the password store
379   // again. Results in updating the fill information on the page.
UpdateFormManagers()380   virtual void UpdateFormManagers() {}
381 
382   // Causes a navigation to the manage passwords page.
NavigateToManagePasswordsPage(ManagePasswordsReferrer referrer)383   virtual void NavigateToManagePasswordsPage(ManagePasswordsReferrer referrer) {
384   }
385 
386   virtual bool IsIsolationForPasswordSitesEnabled() const = 0;
387 
388   // Returns true if the current page is to the new tab page.
389   virtual bool IsNewTabPage() const = 0;
390 
391   // Returns a FieldInfoManager associated with the current profile.
392   virtual FieldInfoManager* GetFieldInfoManager() const = 0;
393 
394  private:
395   DISALLOW_COPY_AND_ASSIGN(PasswordManagerClient);
396 };
397 
398 }  // namespace password_manager
399 
400 #endif  // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_MANAGER_CLIENT_H_
401