Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / components / autofill / content / renderer / password_generation_agent.cc
1 // Copyright 2013 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 #include "components/autofill/content/renderer/password_generation_agent.h"
6
7 #include "base/command_line.h"
8 #include "base/logging.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "components/autofill/content/common/autofill_messages.h"
11 #include "components/autofill/content/renderer/form_autofill_util.h"
12 #include "components/autofill/content/renderer/password_form_conversion_utils.h"
13 #include "components/autofill/core/common/autofill_switches.h"
14 #include "components/autofill/core/common/form_data.h"
15 #include "components/autofill/core/common/password_form.h"
16 #include "components/autofill/core/common/password_generation_util.h"
17 #include "content/public/renderer/render_view.h"
18 #include "google_apis/gaia/gaia_urls.h"
19 #include "third_party/WebKit/public/platform/WebCString.h"
20 #include "third_party/WebKit/public/platform/WebRect.h"
21 #include "third_party/WebKit/public/platform/WebVector.h"
22 #include "third_party/WebKit/public/web/WebDocument.h"
23 #include "third_party/WebKit/public/web/WebFormElement.h"
24 #include "third_party/WebKit/public/web/WebFrame.h"
25 #include "third_party/WebKit/public/web/WebInputElement.h"
26 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
27 #include "third_party/WebKit/public/web/WebView.h"
28 #include "ui/gfx/rect.h"
29
30 namespace autofill {
31
32 namespace {
33
34 // Returns true if we think that this form is for account creation. |passwords|
35 // is filled with the password field(s) in the form.
36 bool GetAccountCreationPasswordFields(
37     const blink::WebFormElement& form,
38     std::vector<blink::WebInputElement>* passwords) {
39   // Grab all of the passwords for the form.
40   blink::WebVector<blink::WebFormControlElement> control_elements;
41   form.getFormControlElements(control_elements);
42
43   size_t num_input_elements = 0;
44   for (size_t i = 0; i < control_elements.size(); i++) {
45     blink::WebInputElement* input_element =
46         toWebInputElement(&control_elements[i]);
47     // Only pay attention to visible password fields.
48     if (input_element &&
49         input_element->isTextField() &&
50         input_element->hasNonEmptyBoundingBox()) {
51       num_input_elements++;
52       if (input_element->isPasswordField())
53         passwords->push_back(*input_element);
54     }
55   }
56
57   // This may be too lenient, but we assume that any form with at least three
58   // input elements where at least one of them is a password is an account
59   // creation form.
60   if (!passwords->empty() && num_input_elements >= 3) {
61     // We trim |passwords| because occasionally there are forms where the
62     // security question answers are put in password fields and we don't want
63     // to fill those.
64     if (passwords->size() > 2)
65       passwords->resize(2);
66
67     return true;
68   }
69
70   return false;
71 }
72
73 bool ContainsURL(const std::vector<GURL>& urls, const GURL& url) {
74   return std::find(urls.begin(), urls.end(), url) != urls.end();
75 }
76
77 // Returns true if the |form1| is essentially equal to |form2|.
78 bool FormsAreEqual(const autofill::FormData& form1,
79                    const PasswordForm& form2) {
80   // TODO(zysxqn): use more signals than just origin to compare.
81   // Note that FormData strips the fragement from the url while PasswordForm
82   // strips both the fragement and the path, so we can't just compare these
83   // two directly.
84   return form1.origin.GetOrigin() == form2.origin.GetOrigin();
85 }
86
87 bool ContainsForm(const std::vector<autofill::FormData>& forms,
88                   const PasswordForm& form) {
89   for (std::vector<autofill::FormData>::const_iterator it =
90            forms.begin(); it != forms.end(); ++it) {
91     if (FormsAreEqual(*it, form))
92       return true;
93   }
94   return false;
95 }
96
97 }  // namespace
98
99 PasswordGenerationAgent::PasswordGenerationAgent(
100     content::RenderView* render_view)
101     : content::RenderViewObserver(render_view),
102       render_view_(render_view),
103       password_is_generated_(false),
104       password_edited_(false),
105       enabled_(password_generation::IsPasswordGenerationEnabled()) {
106   DVLOG(2) << "Password Generation is " << (enabled_ ? "Enabled" : "Disabled");
107 }
108 PasswordGenerationAgent::~PasswordGenerationAgent() {}
109
110 void PasswordGenerationAgent::DidFinishDocumentLoad(blink::WebFrame* frame) {
111   // In every navigation, the IPC message sent by the password autofill manager
112   // to query whether the current form is blacklisted or not happens when the
113   // document load finishes, so we need to clear previous states here before we
114   // hear back from the browser. We only clear this state on main frame load
115   // as we don't want subframe loads to clear state that we have received from
116   // the main frame. Note that we assume there is only one account creation
117   // form, but there could be multiple password forms in each frame.
118   if (!frame->parent()) {
119     not_blacklisted_password_form_origins_.clear();
120     generation_enabled_forms_.clear();
121     generation_element_.reset();
122     possible_account_creation_form_.reset(new PasswordForm());
123     password_elements_.clear();
124     password_is_generated_ = false;
125     if (password_edited_) {
126       password_generation::LogPasswordGenerationEvent(
127           password_generation::PASSWORD_EDITED);
128     }
129     password_edited_ = false;
130   }
131 }
132
133 void PasswordGenerationAgent::DidFinishLoad(blink::WebFrame* frame) {
134   if (!enabled_)
135     return;
136
137   // We don't want to generate passwords if the browser won't store or sync
138   // them.
139   if (!ShouldAnalyzeDocument(frame->document()))
140     return;
141
142   blink::WebVector<blink::WebFormElement> forms;
143   frame->document().forms(forms);
144   for (size_t i = 0; i < forms.size(); ++i) {
145     if (forms[i].isNull())
146       continue;
147
148     // If we can't get a valid PasswordForm, we skip this form because the
149     // the password won't get saved even if we generate it.
150     scoped_ptr<PasswordForm> password_form(
151         CreatePasswordForm(forms[i]));
152     if (!password_form.get()) {
153       DVLOG(2) << "Skipping form as it would not be saved";
154       continue;
155     }
156
157     // Do not generate password for GAIA since it is used to retrieve the
158     // generated paswords.
159     GURL realm(password_form->signon_realm);
160     if (realm == GaiaUrls::GetInstance()->gaia_login_form_realm())
161       continue;
162
163     std::vector<blink::WebInputElement> passwords;
164     if (GetAccountCreationPasswordFields(forms[i], &passwords)) {
165       DVLOG(2) << "Account creation form detected";
166       password_generation::LogPasswordGenerationEvent(
167           password_generation::SIGN_UP_DETECTED);
168       password_elements_ = passwords;
169       possible_account_creation_form_.swap(password_form);
170       DetermineGenerationElement();
171       // We assume that there is only one account creation field per URL.
172       return;
173     }
174   }
175   password_generation::LogPasswordGenerationEvent(
176       password_generation::NO_SIGN_UP_DETECTED);
177 }
178
179 bool PasswordGenerationAgent::ShouldAnalyzeDocument(
180     const blink::WebDocument& document) const {
181   // Make sure that this security origin is allowed to use password manager.
182   // Generating a password that can't be saved is a bad idea.
183   blink::WebSecurityOrigin origin = document.securityOrigin();
184   if (!origin.canAccessPasswordManager()) {
185     DVLOG(1) << "No PasswordManager access";
186     return false;
187   }
188
189   return true;
190 }
191
192 bool PasswordGenerationAgent::OnMessageReceived(const IPC::Message& message) {
193   bool handled = true;
194   IPC_BEGIN_MESSAGE_MAP(PasswordGenerationAgent, message)
195     IPC_MESSAGE_HANDLER(AutofillMsg_FormNotBlacklisted,
196                         OnFormNotBlacklisted)
197     IPC_MESSAGE_HANDLER(AutofillMsg_GeneratedPasswordAccepted,
198                         OnPasswordAccepted)
199     IPC_MESSAGE_HANDLER(AutofillMsg_AccountCreationFormsDetected,
200                         OnAccountCreationFormsDetected)
201     IPC_MESSAGE_UNHANDLED(handled = false)
202   IPC_END_MESSAGE_MAP()
203   return handled;
204 }
205
206 void PasswordGenerationAgent::OnFormNotBlacklisted(const PasswordForm& form) {
207   not_blacklisted_password_form_origins_.push_back(form.origin);
208   DetermineGenerationElement();
209 }
210
211 void PasswordGenerationAgent::OnPasswordAccepted(
212     const base::string16& password) {
213   password_is_generated_ = true;
214   password_generation::LogPasswordGenerationEvent(
215       password_generation::PASSWORD_ACCEPTED);
216   for (std::vector<blink::WebInputElement>::iterator it =
217            password_elements_.begin();
218        it != password_elements_.end(); ++it) {
219     it->setValue(password);
220     it->setAutofilled(true);
221     // Advance focus to the next input field. We assume password fields in
222     // an account creation form are always adjacent.
223     render_view_->GetWebView()->advanceFocus(false);
224   }
225 }
226
227 void PasswordGenerationAgent::OnAccountCreationFormsDetected(
228     const std::vector<autofill::FormData>& forms) {
229   generation_enabled_forms_.insert(
230       generation_enabled_forms_.end(), forms.begin(), forms.end());
231   DetermineGenerationElement();
232 }
233
234 void PasswordGenerationAgent::DetermineGenerationElement() {
235   // Make sure local heuristics have identified a possible account creation
236   // form.
237   if (!possible_account_creation_form_.get() || password_elements_.empty()) {
238     DVLOG(2) << "Local hueristics have not detected a possible account "
239              << "creation form";
240     return;
241   }
242
243   if (CommandLine::ForCurrentProcess()->HasSwitch(
244           switches::kLocalHeuristicsOnlyForPasswordGeneration)) {
245     DVLOG(2) << "Bypassing additional checks.";
246   } else if (not_blacklisted_password_form_origins_.empty() ||
247              !ContainsURL(not_blacklisted_password_form_origins_,
248                           possible_account_creation_form_->origin)) {
249     DVLOG(2) << "Have not received confirmation that password form isn't "
250              << "blacklisted";
251     return;
252   } else if (generation_enabled_forms_.empty() ||
253              !ContainsForm(generation_enabled_forms_,
254                            *possible_account_creation_form_)) {
255     // Note that this message will never be sent if this feature is disabled
256     // (e.g. Password saving is disabled).
257     DVLOG(2) << "Have not received confirmation from Autofill that form is "
258              << "used for account creation";
259     return;
260   }
261
262   DVLOG(2) << "Password generation eligible form found";
263   generation_element_ = password_elements_[0];
264   password_generation::LogPasswordGenerationEvent(
265       password_generation::GENERATION_AVAILABLE);
266 }
267
268 void PasswordGenerationAgent::FocusedNodeChanged(const blink::WebNode& node) {
269   if (!generation_element_.isNull())
270     generation_element_.setShouldRevealPassword(false);
271
272   if (node.isNull() || !node.isElementNode())
273     return;
274
275   const blink::WebElement web_element = node.toConst<blink::WebElement>();
276   if (!web_element.document().frame())
277     return;
278
279   const blink::WebInputElement* element = toWebInputElement(&web_element);
280   if (!element || *element != generation_element_)
281     return;
282
283   if (password_is_generated_) {
284     generation_element_.setShouldRevealPassword(true);
285     ShowEditingPopup();
286   }
287
288   // Only trigger if the password field is empty.
289   if (!element->isReadOnly() &&
290       element->isEnabled() &&
291       element->value().isEmpty()) {
292     ShowGenerationPopup();
293   }
294 }
295
296 bool PasswordGenerationAgent::TextDidChangeInTextField(
297     const blink::WebInputElement& element) {
298   if (element != generation_element_)
299     return false;
300
301   if (element.value().isEmpty()) {
302     if (password_is_generated_) {
303       // User generated a password and then deleted it.
304       password_generation::LogPasswordGenerationEvent(
305           password_generation::PASSWORD_DELETED);
306     }
307
308     // Do not treat the password as generated.
309     // TODO(gcasto): Set PasswordForm::type in the browser to TYPE_NORMAL.
310     password_is_generated_ = false;
311     generation_element_.setShouldRevealPassword(false);
312
313     // Offer generation again.
314     ShowGenerationPopup();
315   } else if (!password_is_generated_) {
316     // User has rejected the feature and has started typing a password.
317     HidePopup();
318   } else {
319     password_edited_ = true;
320     // Mirror edits to any confirmation password fields.
321     for (std::vector<blink::WebInputElement>::iterator it =
322              password_elements_.begin();
323          it != password_elements_.end(); ++it) {
324       it->setValue(element.value());
325     }
326   }
327
328   return true;
329 }
330
331 void PasswordGenerationAgent::ShowGenerationPopup() {
332   gfx::RectF bounding_box_scaled =
333       GetScaledBoundingBox(render_view_->GetWebView()->pageScaleFactor(),
334                            &generation_element_);
335
336   Send(new AutofillHostMsg_ShowPasswordGenerationPopup(
337       routing_id(),
338       bounding_box_scaled,
339       generation_element_.maxLength(),
340       *possible_account_creation_form_));
341
342   password_generation::LogPasswordGenerationEvent(
343       password_generation::GENERATION_POPUP_SHOWN);
344 }
345
346 void PasswordGenerationAgent::ShowEditingPopup() {
347   gfx::RectF bounding_box_scaled =
348       GetScaledBoundingBox(render_view_->GetWebView()->pageScaleFactor(),
349                            &generation_element_);
350
351   Send(new AutofillHostMsg_ShowPasswordEditingPopup(
352       routing_id(),
353       bounding_box_scaled,
354       *possible_account_creation_form_));
355
356   password_generation::LogPasswordGenerationEvent(
357       password_generation::EDITING_POPUP_SHOWN);
358 }
359
360 void PasswordGenerationAgent::HidePopup() {
361   Send(new AutofillHostMsg_HidePasswordGenerationPopup(routing_id()));
362 }
363
364 }  // namespace autofill