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 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/autofill/content/renderer/password_autofill_agent.h"
#include <stddef.h>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/i18n/case_conversion.h"
#include "base/memory/linked_ptr.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "components/autofill/content/renderer/form_autofill_util.h"
#include "components/autofill/content/renderer/password_form_conversion_utils.h"
#include "components/autofill/content/renderer/renderer_save_password_progress_logger.h"
#include "components/autofill/core/common/autofill_constants.h"
#include "components/autofill/core/common/autofill_util.h"
#include "components/autofill/core/common/form_field_data.h"
#include "components/autofill/core/common/password_form_fill_data.h"
#include "components/security_state/core/security_state.h"
#include "content/public/common/origin_util.h"
#include "content/public/renderer/document_state.h"
#include "content/public/renderer/navigation_state.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "services/service_manager/public/cpp/interface_registry.h"
#include "third_party/WebKit/public/platform/WebInputEvent.h"
#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
#include "third_party/WebKit/public/platform/WebVector.h"
#include "third_party/WebKit/public/web/WebAutofillClient.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebElement.h"
#include "third_party/WebKit/public/web/WebFormElement.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebNode.h"
#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "ui/base/page_transition_types.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "url/gurl.h"
namespace autofill {
namespace {
// The size above which we stop triggering autocomplete.
static const size_t kMaximumTextSizeForAutocomplete = 1000;
const char kDummyUsernameField[] = "anonymous_username";
const char kDummyPasswordField[] = "anonymous_password";
// Maps element names to the actual elements to simplify form filling.
typedef std::map<base::string16, blink::WebInputElement> FormInputElementMap;
// Use the shorter name when referencing SavePasswordProgressLogger::StringID
// values to spare line breaks. The code provides enough context for that
// already.
typedef SavePasswordProgressLogger Logger;
typedef std::vector<FormInputElementMap> FormElementsList;
bool FillDataContainsFillableUsername(const PasswordFormFillData& fill_data) {
return !fill_data.username_field.name.empty() &&
(!fill_data.additional_logins.empty() ||
!fill_data.username_field.value.empty());
}
// Returns true if password form has username and password fields with either
// same or no name and id attributes supplied.
bool DoesFormContainAmbiguousOrEmptyNames(
const PasswordFormFillData& fill_data) {
return (fill_data.username_field.name == fill_data.password_field.name) ||
(fill_data.password_field.name ==
base::ASCIIToUTF16(kDummyPasswordField) &&
(!FillDataContainsFillableUsername(fill_data) ||
fill_data.username_field.name ==
base::ASCIIToUTF16(kDummyUsernameField)));
}
bool IsPasswordField(const FormFieldData& field) {
return (field.form_control_type == "password");
}
// Returns true if any password field within |control_elements| is supplied with
// either |autocomplete='current-password'| or |autocomplete='new-password'|
// attribute.
bool HasPasswordWithAutocompleteAttribute(
const std::vector<blink::WebFormControlElement>& control_elements) {
for (const blink::WebFormControlElement& control_element : control_elements) {
if (!control_element.hasHTMLTagName("input"))
continue;
const blink::WebInputElement input_element =
control_element.toConst<blink::WebInputElement>();
if (input_element.isPasswordField() &&
(HasAutocompleteAttributeValue(input_element, "current-password") ||
HasAutocompleteAttributeValue(input_element, "new-password")))
return true;
}
return false;
}
// Returns the |field|'s autofillable name. If |ambiguous_or_empty_names| is set
// to true returns a dummy name instead.
base::string16 FieldName(const FormFieldData& field,
bool ambiguous_or_empty_names) {
return ambiguous_or_empty_names
? IsPasswordField(field) ? base::ASCIIToUTF16(kDummyPasswordField)
: base::ASCIIToUTF16(kDummyUsernameField)
: field.name;
}
bool IsUnownedPasswordFormVisible(blink::WebFrame* frame,
const GURL& action,
const GURL& origin,
const FormData& form_data,
const FormsPredictionsMap& form_predictions) {
std::unique_ptr<PasswordForm> unowned_password_form(
CreatePasswordFormFromUnownedInputElements(*frame, nullptr,
&form_predictions));
if (!unowned_password_form)
return false;
std::vector<blink::WebFormControlElement> control_elements =
form_util::GetUnownedAutofillableFormFieldElements(
frame->document().all(), nullptr);
if (!form_util::IsSomeControlElementVisible(control_elements))
return false;
#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
const bool action_is_empty = action == origin;
bool forms_are_same =
action_is_empty ? form_data.SameFormAs(unowned_password_form->form_data)
: action == unowned_password_form->action;
return forms_are_same;
#else // OS_MACOSX or OS_ANDROID
return action == unowned_password_form->action;
#endif
}
// Utility function to find the unique entry of |control_elements| for the
// specified input |field|. On successful find, adds it to |result| and returns
// |true|. Otherwise clears the references from each |HTMLInputElement| from
// |result| and returns |false|.
bool FindFormInputElement(
const std::vector<blink::WebFormControlElement>& control_elements,
const FormFieldData& field,
bool ambiguous_or_empty_names,
FormInputElementMap* result) {
// Match the first input element, if any.
bool found_input = false;
bool is_password_field = IsPasswordField(field);
bool does_password_field_has_ambigous_or_empty_name =
ambiguous_or_empty_names && is_password_field;
bool ambiguous_and_multiple_password_fields_with_autocomplete =
does_password_field_has_ambigous_or_empty_name &&
HasPasswordWithAutocompleteAttribute(control_elements);
base::string16 field_name = FieldName(field, ambiguous_or_empty_names);
for (const blink::WebFormControlElement& control_element : control_elements) {
if (!ambiguous_or_empty_names &&
control_element.nameForAutofill() != field_name) {
continue;
}
if (!control_element.hasHTMLTagName("input"))
continue;
// Only fill saved passwords into password fields and usernames into text
// fields.
const blink::WebInputElement input_element =
control_element.toConst<blink::WebInputElement>();
if (!input_element.isTextField() ||
input_element.isPasswordField() != is_password_field)
continue;
// For change password form with ambiguous or empty names keep only the
// first password field having |autocomplete='current-password'| attribute
// set. Also make sure we avoid keeping password fields having
// |autocomplete='new-password'| attribute set.
if (ambiguous_and_multiple_password_fields_with_autocomplete &&
!HasAutocompleteAttributeValue(input_element, "current-password")) {
continue;
}
// Check for a non-unique match.
if (found_input) {
// For change password form keep only the first password field entry.
if (does_password_field_has_ambigous_or_empty_name) {
if (!form_util::IsWebNodeVisible((*result)[field_name])) {
// If a previously chosen field was invisible then take the current
// one.
(*result)[field_name] = input_element;
}
continue;
}
found_input = false;
break;
}
(*result)[field_name] = input_element;
found_input = true;
}
// A required element was not found. This is not the right form.
// Make sure no input elements from a partially matched form in this
// iteration remain in the result set.
// Note: clear will remove a reference from each InputElement.
if (!found_input) {
result->clear();
return false;
}
return true;
}
// Helper to search through |control_elements| for the specified input elements
// in |data|, and add results to |result|.
bool FindFormInputElements(
const std::vector<blink::WebFormControlElement>& control_elements,
const PasswordFormFillData& data,
bool ambiguous_or_empty_names,
FormInputElementMap* result) {
return FindFormInputElement(control_elements, data.password_field,
ambiguous_or_empty_names, result) &&
(!FillDataContainsFillableUsername(data) ||
FindFormInputElement(control_elements, data.username_field,
ambiguous_or_empty_names, result));
}
// Helper to locate form elements identified by |data|.
void FindFormElements(content::RenderFrame* render_frame,
const PasswordFormFillData& data,
bool ambiguous_or_empty_names,
FormElementsList* results) {
DCHECK(results);
blink::WebDocument doc = render_frame->GetWebFrame()->document();
if (data.origin != form_util::GetCanonicalOriginForDocument(doc))
return;
blink::WebVector<blink::WebFormElement> forms;
doc.forms(forms);
for (size_t i = 0; i < forms.size(); ++i) {
blink::WebFormElement fe = forms[i];
// Action URL must match.
if (data.action != form_util::GetCanonicalActionForForm(fe))
continue;
std::vector<blink::WebFormControlElement> control_elements =
form_util::ExtractAutofillableElementsInForm(fe);
FormInputElementMap cur_map;
if (FindFormInputElements(control_elements, data, ambiguous_or_empty_names,
&cur_map))
results->push_back(cur_map);
}
// If the element to be filled are not in a <form> element, the "action" and
// origin should be the same.
if (data.action != data.origin)
return;
std::vector<blink::WebFormControlElement> control_elements =
form_util::GetUnownedAutofillableFormFieldElements(doc.all(), nullptr);
FormInputElementMap unowned_elements_map;
if (FindFormInputElements(control_elements, data, ambiguous_or_empty_names,
&unowned_elements_map))
results->push_back(unowned_elements_map);
}
bool IsElementEditable(const blink::WebInputElement& element) {
return element.isEnabled() && !element.isReadOnly();
}
bool DoUsernamesMatch(const base::string16& username1,
const base::string16& username2,
bool exact_match) {
if (exact_match)
return username1 == username2;
return FieldIsSuggestionSubstringStartingOnTokenBoundary(username1, username2,
true);
}
// Returns |true| if the given element is editable. Otherwise, returns |false|.
bool IsElementAutocompletable(const blink::WebInputElement& element) {
return IsElementEditable(element);
}
// Return true if either password_value or new_password_value is not empty and
// not default.
bool FormContainsNonDefaultPasswordValue(const PasswordForm& password_form) {
return (!password_form.password_value.empty() &&
!password_form.password_value_is_default) ||
(!password_form.new_password_value.empty() &&
!password_form.new_password_value_is_default);
}
// Log a message including the name, method and action of |form|.
void LogHTMLForm(SavePasswordProgressLogger* logger,
SavePasswordProgressLogger::StringID message_id,
const blink::WebFormElement& form) {
logger->LogHTMLForm(message_id,
form.name().utf8(),
GURL(form.action().utf8()));
}
// Returns true if there are any suggestions to be derived from |fill_data|.
// Unless |show_all| is true, only considers suggestions with usernames having
// |current_username| as a prefix.
bool CanShowSuggestion(const PasswordFormFillData& fill_data,
const base::string16& current_username,
bool show_all) {
base::string16 current_username_lower = base::i18n::ToLower(current_username);
for (const auto& usernames : fill_data.other_possible_usernames) {
for (size_t i = 0; i < usernames.second.size(); ++i) {
if (show_all ||
base::StartsWith(
base::i18n::ToLower(base::string16(usernames.second[i])),
current_username_lower, base::CompareCase::SENSITIVE)) {
return true;
}
}
}
if (show_all ||
base::StartsWith(base::i18n::ToLower(fill_data.username_field.value),
current_username_lower, base::CompareCase::SENSITIVE)) {
return true;
}
for (const auto& login : fill_data.additional_logins) {
if (show_all ||
base::StartsWith(base::i18n::ToLower(login.first),
current_username_lower,
base::CompareCase::SENSITIVE)) {
return true;
}
}
return false;
}
// Updates the value (i.e. the pair of elements's value |value| and field
// properties |added_flags|) associated with the key |element| in
// |field_value_and_properties_map|.
// Flags in |added_flags| are added with bitwise OR operation.
// If |value| is null, the value is neither updated nor added.
void UpdateFieldValueAndPropertiesMaskMap(
const blink::WebFormControlElement& element,
const base::string16* value,
FieldPropertiesMask added_flags,
FieldValueAndPropertiesMaskMap* field_value_and_properties_map) {
FieldValueAndPropertiesMaskMap::iterator it =
field_value_and_properties_map->find(element);
if (it != field_value_and_properties_map->end()) {
if (value)
it->second.first.reset(new base::string16(*value));
it->second.second |= added_flags;
} else {
(*field_value_and_properties_map)[element] = std::make_pair(
value ? base::MakeUnique<base::string16>(*value) : nullptr,
added_flags);
}
}
// This function attempts to fill |username_element| and |password_element|
// with values from |fill_data|. The |password_element| will only have the
// suggestedValue set, and will be registered for copying that to the real
// value through |registration_callback|. If a match is found, return true and
// |field_value_and_properties_map| will be modified with the autofilled
// credentials and |FieldPropertiesFlags::AUTOFILLED| flag.
bool FillUserNameAndPassword(
blink::WebInputElement* username_element,
blink::WebInputElement* password_element,
const PasswordFormFillData& fill_data,
bool exact_username_match,
bool set_selection,
FieldValueAndPropertiesMaskMap* field_value_and_properties_map,
base::Callback<void(blink::WebInputElement*)> registration_callback,
RendererSavePasswordProgressLogger* logger) {
if (logger)
logger->LogMessage(Logger::STRING_FILL_USERNAME_AND_PASSWORD_METHOD);
// Don't fill username if password can't be set.
if (!IsElementAutocompletable(*password_element))
return false;
base::string16 current_username;
if (!username_element->isNull()) {
current_username = username_element->value();
}
// username and password will contain the match found if any.
base::string16 username;
base::string16 password;
// Look for any suitable matches to current field text.
if (DoUsernamesMatch(fill_data.username_field.value, current_username,
exact_username_match)) {
username = fill_data.username_field.value;
password = fill_data.password_field.value;
if (logger)
logger->LogMessage(Logger::STRING_USERNAMES_MATCH);
} else {
// Scan additional logins for a match.
for (const auto& it : fill_data.additional_logins) {
if (DoUsernamesMatch(it.first, current_username, exact_username_match)) {
username = it.first;
password = it.second.password;
break;
}
}
if (logger) {
logger->LogBoolean(Logger::STRING_MATCH_IN_ADDITIONAL,
!(username.empty() && password.empty()));
}
// Check possible usernames.
if (username.empty() && password.empty()) {
for (const auto& it : fill_data.other_possible_usernames) {
for (size_t i = 0; i < it.second.size(); ++i) {
if (DoUsernamesMatch(
it.second[i], current_username, exact_username_match)) {
username = it.second[i];
password = it.first.password;
break;
}
}
if (!username.empty() && !password.empty())
break;
}
}
}
if (password.empty())
return false;
// TODO(tkent): Check maxlength and pattern for both username and password
// fields.
// Input matches the username, fill in required values.
if (!username_element->isNull() &&
IsElementAutocompletable(*username_element)) {
// TODO(crbug.com/507714): Why not setSuggestedValue?
username_element->setValue(username, true);
UpdateFieldValueAndPropertiesMaskMap(*username_element, &username,
FieldPropertiesFlags::AUTOFILLED,
field_value_and_properties_map);
username_element->setAutofilled(true);
if (logger)
logger->LogElementName(Logger::STRING_USERNAME_FILLED, *username_element);
if (set_selection) {
form_util::PreviewSuggestion(username, current_username,
username_element);
}
} else if (current_username != username) {
// If the username can't be filled and it doesn't match a saved password
// as is, don't autofill a password.
return false;
}
// Wait to fill in the password until a user gesture occurs. This is to make
// sure that we do not fill in the DOM with a password until we believe the
// user is intentionally interacting with the page.
password_element->setSuggestedValue(password);
UpdateFieldValueAndPropertiesMaskMap(*password_element, &password,
FieldPropertiesFlags::AUTOFILLED,
field_value_and_properties_map);
registration_callback.Run(password_element);
password_element->setAutofilled(true);
if (logger)
logger->LogElementName(Logger::STRING_PASSWORD_FILLED, *password_element);
return true;
}
// Attempts to fill |username_element| and |password_element| with the
// |fill_data|. Will use the data corresponding to the preferred username,
// unless the |username_element| already has a value set. In that case,
// attempts to fill the password matching the already filled username, if
// such a password exists. The |password_element| will have the
// |suggestedValue| set, and |suggestedValue| will be registered for copying to
// the real value through |registration_callback|. Returns true if the password
// is filled.
bool FillFormOnPasswordReceived(
const PasswordFormFillData& fill_data,
blink::WebInputElement username_element,
blink::WebInputElement password_element,
FieldValueAndPropertiesMaskMap* field_value_and_properties_map,
base::Callback<void(blink::WebInputElement*)> registration_callback,
RendererSavePasswordProgressLogger* logger) {
// Do not fill if the password field is in a chain of iframes not having
// identical origin.
blink::WebFrame* cur_frame = password_element.document().frame();
blink::WebString bottom_frame_origin =
cur_frame->getSecurityOrigin().toString();
DCHECK(cur_frame);
while (cur_frame->parent()) {
cur_frame = cur_frame->parent();
if (!bottom_frame_origin.equals(cur_frame->getSecurityOrigin().toString()))
return false;
}
// If we can't modify the password, don't try to set the username
if (!IsElementAutocompletable(password_element))
return false;
bool form_contains_fillable_username_field =
FillDataContainsFillableUsername(fill_data);
bool ambiguous_or_empty_names =
DoesFormContainAmbiguousOrEmptyNames(fill_data);
base::string16 username_field_name;
if (form_contains_fillable_username_field)
username_field_name =
FieldName(fill_data.username_field, ambiguous_or_empty_names);
// If the form contains an autocompletable username field, try to set the
// username to the preferred name, but only if:
// (a) The fill-on-account-select flag is not set, and
// (b) The username element isn't prefilled
//
// If (a) is false, then just mark the username element as autofilled if the
// user is not in the "no highlighting" group and return so the fill step is
// skipped.
//
// If there is no autocompletable username field, and (a) is false, then the
// username element cannot be autofilled, but the user should still be able to
// select to fill the password element, so the password element must be marked
// as autofilled and the fill step should also be skipped if the user is not
// in the "no highlighting" group.
//
// In all other cases, do nothing.
bool form_has_fillable_username = !username_field_name.empty() &&
IsElementAutocompletable(username_element);
if (form_has_fillable_username && username_element.value().isEmpty()) {
// TODO(tkent): Check maxlength and pattern.
username_element.setValue(fill_data.username_field.value, true);
}
// Fill if we have an exact match for the username. Note that this sets
// username to autofilled.
return FillUserNameAndPassword(
&username_element, &password_element, fill_data,
true /* exact_username_match */, false /* set_selection */,
field_value_and_properties_map, registration_callback, logger);
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// PasswordAutofillAgent, public:
PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame)
: content::RenderFrameObserver(render_frame),
logging_state_active_(false),
was_username_autofilled_(false),
was_password_autofilled_(false),
binding_(this) {
// PasswordAutofillAgent is guaranteed to outlive |render_frame|.
render_frame->GetInterfaceRegistry()->AddInterface(
base::Bind(&PasswordAutofillAgent::BindRequest, base::Unretained(this)));
}
PasswordAutofillAgent::~PasswordAutofillAgent() {
}
void PasswordAutofillAgent::BindRequest(
mojom::PasswordAutofillAgentRequest request) {
binding_.Bind(std::move(request));
}
void PasswordAutofillAgent::SetAutofillAgent(AutofillAgent* autofill_agent) {
autofill_agent_ = autofill_agent;
}
PasswordAutofillAgent::PasswordValueGatekeeper::PasswordValueGatekeeper()
: was_user_gesture_seen_(false) {
}
PasswordAutofillAgent::PasswordValueGatekeeper::~PasswordValueGatekeeper() {
}
void PasswordAutofillAgent::PasswordValueGatekeeper::RegisterElement(
blink::WebInputElement* element) {
if (was_user_gesture_seen_)
ShowValue(element);
else
elements_.push_back(*element);
}
void PasswordAutofillAgent::PasswordValueGatekeeper::OnUserGesture() {
was_user_gesture_seen_ = true;
for (blink::WebInputElement& element : elements_)
ShowValue(&element);
elements_.clear();
}
void PasswordAutofillAgent::PasswordValueGatekeeper::Reset() {
was_user_gesture_seen_ = false;
elements_.clear();
}
void PasswordAutofillAgent::PasswordValueGatekeeper::ShowValue(
blink::WebInputElement* element) {
if (!element->isNull() && !element->suggestedValue().isEmpty())
element->setValue(element->suggestedValue(), true);
}
bool PasswordAutofillAgent::TextDidChangeInTextField(
const blink::WebInputElement& element) {
// TODO(vabr): Get a mutable argument instead. http://crbug.com/397083
blink::WebInputElement mutable_element = element; // We need a non-const.
mutable_element.setAutofilled(false);
WebInputToPasswordInfoMap::iterator iter =
web_input_to_password_info_.find(element);
if (iter != web_input_to_password_info_.end()) {
iter->second.password_was_edited_last = false;
}
// Show the popup with the list of available usernames.
return ShowSuggestions(element, false, false);
}
void PasswordAutofillAgent::UpdateStateForTextChange(
const blink::WebInputElement& element) {
// TODO(vabr): Get a mutable argument instead. http://crbug.com/397083
blink::WebInputElement mutable_element = element; // We need a non-const.
if (element.isTextField()) {
const base::string16 element_value = element.value();
UpdateFieldValueAndPropertiesMaskMap(element, &element_value,
FieldPropertiesFlags::USER_TYPED,
&field_value_and_properties_map_);
}
blink::WebFrame* const element_frame = element.document().frame();
// The element's frame might have been detached in the meantime (see
// http://crbug.com/585363, comments 5 and 6), in which case frame() will
// return null. This was hardly caused by form submission (unless the user
// is supernaturally quick), so it is OK to drop the ball here.
if (!element_frame)
return;
DCHECK_EQ(element_frame, render_frame()->GetWebFrame());
// Some login forms have event handlers that put a hash of the password into
// a hidden field and then clear the password (http://crbug.com/28910,
// http://crbug.com/391693). This method gets called before any of those
// handlers run, so save away a copy of the password in case it gets lost.
// To honor the user having explicitly cleared the password, even an empty
// password will be saved here.
std::unique_ptr<PasswordForm> password_form;
if (element.form().isNull()) {
password_form = CreatePasswordFormFromUnownedInputElements(
*element_frame, &field_value_and_properties_map_, &form_predictions_);
} else {
password_form = CreatePasswordFormFromWebForm(
element.form(), &field_value_and_properties_map_, &form_predictions_);
}
ProvisionallySavePassword(std::move(password_form), RESTRICTION_NONE);
if (element.isPasswordField()) {
PasswordToLoginMap::iterator iter = password_to_username_.find(element);
if (iter != password_to_username_.end()) {
web_input_to_password_info_[iter->second].password_was_edited_last = true;
// Note that the suggested value of |mutable_element| was reset when its
// value changed.
mutable_element.setAutofilled(false);
}
}
}
bool PasswordAutofillAgent::FillSuggestion(
const blink::WebFormControlElement& control_element,
const base::string16& username,
const base::string16& password) {
// The element in context of the suggestion popup.
const blink::WebInputElement* element = toWebInputElement(&control_element);
if (!element)
return false;
blink::WebInputElement username_element;
blink::WebInputElement password_element;
PasswordInfo* password_info;
if (!FindPasswordInfoForElement(*element, &username_element,
&password_element, &password_info) ||
!IsElementAutocompletable(password_element)) {
return false;
}
password_info->password_was_edited_last = false;
if (element->isPasswordField()) {
password_info->password_field_suggestion_was_accepted = true;
password_info->password_field = password_element;
} else if (!username_element.isNull() &&
IsElementAutocompletable(username_element)) {
username_element.setValue(blink::WebString(username), true);
username_element.setAutofilled(true);
UpdateFieldValueAndPropertiesMaskMap(username_element, &username,
FieldPropertiesFlags::AUTOFILLED,
&field_value_and_properties_map_);
}
password_element.setValue(blink::WebString(password), true);
password_element.setAutofilled(true);
UpdateFieldValueAndPropertiesMaskMap(password_element, &password,
FieldPropertiesFlags::AUTOFILLED,
&field_value_and_properties_map_);
blink::WebInputElement mutable_filled_element = *element;
mutable_filled_element.setSelectionRange(element->value().length(),
element->value().length());
return true;
}
bool PasswordAutofillAgent::PreviewSuggestion(
const blink::WebFormControlElement& control_element,
const blink::WebString& username,
const blink::WebString& password) {
// The element in context of the suggestion popup.
const blink::WebInputElement* element = toWebInputElement(&control_element);
if (!element)
return false;
blink::WebInputElement username_element;
blink::WebInputElement password_element;
PasswordInfo* password_info;
if (!FindPasswordInfoForElement(*element, &username_element,
&password_element, &password_info) ||
!IsElementAutocompletable(password_element)) {
return false;
}
if (!element->isPasswordField() && !username_element.isNull() &&
IsElementAutocompletable(username_element)) {
if (username_query_prefix_.empty())
username_query_prefix_ = username_element.value();
was_username_autofilled_ = username_element.isAutofilled();
username_element.setSuggestedValue(username);
username_element.setAutofilled(true);
form_util::PreviewSuggestion(username_element.suggestedValue(),
username_query_prefix_, &username_element);
}
was_password_autofilled_ = password_element.isAutofilled();
password_element.setSuggestedValue(password);
password_element.setAutofilled(true);
return true;
}
bool PasswordAutofillAgent::DidClearAutofillSelection(
const blink::WebFormControlElement& control_element) {
const blink::WebInputElement* element = toWebInputElement(&control_element);
if (!element)
return false;
blink::WebInputElement username_element;
blink::WebInputElement password_element;
PasswordInfo* password_info;
if (!FindPasswordInfoForElement(*element, &username_element,
&password_element, &password_info))
return false;
ClearPreview(&username_element, &password_element);
return true;
}
bool PasswordAutofillAgent::FindPasswordInfoForElement(
const blink::WebInputElement& element,
blink::WebInputElement* username_element,
blink::WebInputElement* password_element,
PasswordInfo** password_info) {
DCHECK(username_element && password_element && password_info);
username_element->reset();
password_element->reset();
if (!element.isPasswordField()) {
*username_element = element;
} else {
WebInputToPasswordInfoMap::iterator iter =
web_input_to_password_info_.find(element);
if (iter != web_input_to_password_info_.end()) {
// It's a password field without corresponding username field.
*password_element = element;
*password_info = &iter->second;
return true;
}
PasswordToLoginMap::const_iterator password_iter =
password_to_username_.find(element);
if (password_iter == password_to_username_.end()) {
if (web_input_to_password_info_.empty())
return false;
*password_element = element;
// Now all PasswordInfo items refer to the same set of credentials for
// fill, so it is ok to take any of them.
*password_info = &web_input_to_password_info_.begin()->second;
return true;
}
*username_element = password_iter->second;
*password_element = element;
}
WebInputToPasswordInfoMap::iterator iter =
web_input_to_password_info_.find(*username_element);
if (iter == web_input_to_password_info_.end())
return false;
*password_info = &iter->second;
if (password_element->isNull())
*password_element = (*password_info)->password_field;
return true;
}
bool PasswordAutofillAgent::ShowSuggestions(
const blink::WebInputElement& element,
bool show_all,
bool generation_popup_showing) {
blink::WebInputElement username_element;
blink::WebInputElement password_element;
PasswordInfo* password_info;
if (!FindPasswordInfoForElement(element, &username_element, &password_element,
&password_info)) {
// If we don't have a password stored, but the form is non-secure, warn
// the user about the non-secure form.
if ((element.isPasswordField() ||
HasAutocompleteAttributeValue(element, "username")) &&
security_state::IsHttpWarningInFormEnabled() &&
!content::IsOriginSecure(
url::Origin(
render_frame()->GetWebFrame()->top()->getSecurityOrigin())
.GetURL())) {
autofill_agent_->ShowNotSecureWarning(element);
return true;
}
return false;
}
// If autocomplete='off' is set on the form elements, no suggestion dialog
// should be shown. However, return |true| to indicate that this is a known
// password form and that the request to show suggestions has been handled (as
// a no-op).
if (!element.isTextField() || !IsElementAutocompletable(element) ||
!IsElementAutocompletable(password_element))
return true;
if (element.nameForAutofill().isEmpty() &&
!DoesFormContainAmbiguousOrEmptyNames(password_info->fill_data)) {
return false; // If the field has no name, then we won't have values.
}
// Don't attempt to autofill with values that are too large.
if (element.value().length() > kMaximumTextSizeForAutocomplete)
return false;
// If the element is a password field, do not to show a popup if the user has
// already accepted a password suggestion on another password field.
if (element.isPasswordField() &&
(password_info->password_field_suggestion_was_accepted &&
element != password_info->password_field))
return true;
UMA_HISTOGRAM_BOOLEAN(
"PasswordManager.AutocompletePopupSuppressedByGeneration",
generation_popup_showing);
if (generation_popup_showing)
return false;
// Chrome should never show more than one account for a password element since
// this implies that the username element cannot be modified. Thus even if
// |show_all| is true, check if the element in question is a password element
// for the call to ShowSuggestionPopup.
return ShowSuggestionPopup(*password_info, element,
show_all && !element.isPasswordField(),
element.isPasswordField());
}
void PasswordAutofillAgent::ShowNotSecureWarning(
const blink::WebInputElement& element) {
FormData form;
FormFieldData field;
form_util::FindFormAndFieldForFormControlElement(element, &form, &field);
GetPasswordManagerDriver()->ShowNotSecureWarning(
field.text_direction,
render_frame()->GetRenderView()->ElementBoundsInWindow(element));
}
bool PasswordAutofillAgent::OriginCanAccessPasswordManager(
const blink::WebSecurityOrigin& origin) {
return origin.canAccessPasswordManager();
}
void PasswordAutofillAgent::OnDynamicFormsSeen() {
SendPasswordForms(false /* only_visible */);
}
void PasswordAutofillAgent::AJAXSucceeded() {
OnSamePageNavigationCompleted();
}
void PasswordAutofillAgent::OnSamePageNavigationCompleted() {
if (!ProvisionallySavedPasswordIsValid())
return;
// Prompt to save only if the form is now gone, either invisible or
// removed from the DOM.
blink::WebFrame* frame = render_frame()->GetWebFrame();
if (form_util::IsFormVisible(frame, provisionally_saved_form_->action,
provisionally_saved_form_->origin,
provisionally_saved_form_->form_data) ||
IsUnownedPasswordFormVisible(frame, provisionally_saved_form_->action,
provisionally_saved_form_->origin,
provisionally_saved_form_->form_data,
form_predictions_)) {
return;
}
GetPasswordManagerDriver()->InPageNavigation(*provisionally_saved_form_);
provisionally_saved_form_.reset();
}
void PasswordAutofillAgent::FirstUserGestureObserved() {
gatekeeper_.OnUserGesture();
}
void PasswordAutofillAgent::SendPasswordForms(bool only_visible) {
std::unique_ptr<RendererSavePasswordProgressLogger> logger;
if (logging_state_active_) {
logger.reset(new RendererSavePasswordProgressLogger(
GetPasswordManagerDriver().get()));
logger->LogMessage(Logger::STRING_SEND_PASSWORD_FORMS_METHOD);
logger->LogBoolean(Logger::STRING_ONLY_VISIBLE, only_visible);
}
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
// Make sure that this security origin is allowed to use password manager.
blink::WebSecurityOrigin origin = frame->document().getSecurityOrigin();
if (logger) {
logger->LogURL(Logger::STRING_SECURITY_ORIGIN,
GURL(origin.toString().utf8()));
}
if (!OriginCanAccessPasswordManager(origin)) {
if (logger) {
logger->LogMessage(Logger::STRING_SECURITY_ORIGIN_FAILURE);
}
return;
}
// Checks whether the webpage is a redirect page or an empty page.
if (form_util::IsWebpageEmpty(frame)) {
if (logger) {
logger->LogMessage(Logger::STRING_WEBPAGE_EMPTY);
}
return;
}
blink::WebVector<blink::WebFormElement> forms;
frame->document().forms(forms);
if (logger)
logger->LogNumber(Logger::STRING_NUMBER_OF_ALL_FORMS, forms.size());
std::vector<PasswordForm> password_forms;
for (const blink::WebFormElement& form : forms) {
if (only_visible) {
bool is_form_visible = form_util::AreFormContentsVisible(form);
if (logger) {
LogHTMLForm(logger.get(), Logger::STRING_FORM_FOUND_ON_PAGE, form);
logger->LogBoolean(Logger::STRING_FORM_IS_VISIBLE, is_form_visible);
}
// If requested, ignore non-rendered forms, e.g., those styled with
// display:none.
if (!is_form_visible)
continue;
}
std::unique_ptr<PasswordForm> password_form(
CreatePasswordFormFromWebForm(form, nullptr, &form_predictions_));
if (password_form) {
if (logger) {
logger->LogPasswordForm(Logger::STRING_FORM_IS_PASSWORD,
*password_form);
}
password_forms.push_back(*password_form);
}
}
// See if there are any unattached input elements that could be used for
// password submission.
bool add_unowned_inputs = true;
if (only_visible) {
std::vector<blink::WebFormControlElement> control_elements =
form_util::GetUnownedAutofillableFormFieldElements(
frame->document().all(), nullptr);
add_unowned_inputs =
form_util::IsSomeControlElementVisible(control_elements);
if (logger) {
logger->LogBoolean(Logger::STRING_UNOWNED_INPUTS_VISIBLE,
add_unowned_inputs);
}
}
if (add_unowned_inputs) {
std::unique_ptr<PasswordForm> password_form(
CreatePasswordFormFromUnownedInputElements(*frame, nullptr,
&form_predictions_));
if (password_form) {
if (logger) {
logger->LogPasswordForm(Logger::STRING_FORM_IS_PASSWORD,
*password_form);
}
password_forms.push_back(*password_form);
}
}
if (password_forms.empty() && !only_visible) {
// We need to send the PasswordFormsRendered message regardless of whether
// there are any forms visible, as this is also the code path that triggers
// showing the infobar.
return;
}
if (only_visible) {
blink::WebFrame* main_frame = render_frame()->GetWebFrame()->top();
bool did_stop_loading = !main_frame || !main_frame->isLoading();
GetPasswordManagerDriver()->PasswordFormsRendered(password_forms,
did_stop_loading);
} else {
GetPasswordManagerDriver()->PasswordFormsParsed(password_forms);
}
}
void PasswordAutofillAgent::DidFinishDocumentLoad() {
// The |frame| contents have been parsed, but not yet rendered. Let the
// PasswordManager know that forms are loaded, even though we can't yet tell
// whether they're visible.
form_util::ScopedLayoutPreventer layout_preventer;
SendPasswordForms(false);
}
void PasswordAutofillAgent::DidFinishLoad() {
// The |frame| contents have been rendered. Let the PasswordManager know
// which of the loaded frames are actually visible to the user. This also
// triggers the "Save password?" infobar if the user just submitted a password
// form.
SendPasswordForms(true);
}
void PasswordAutofillAgent::WillCommitProvisionalLoad() {
FrameClosing();
}
void PasswordAutofillAgent::DidCommitProvisionalLoad(
bool is_new_navigation, bool is_same_page_navigation) {
if (is_same_page_navigation) {
OnSamePageNavigationCompleted();
}
}
void PasswordAutofillAgent::FrameDetached() {
// If a sub frame has been destroyed while the user was entering information
// into a password form, try to save the data. See https://crbug.com/450806
// for examples of sites that perform login using this technique.
if (render_frame()->GetWebFrame()->parent() &&
ProvisionallySavedPasswordIsValid()) {
GetPasswordManagerDriver()->InPageNavigation(*provisionally_saved_form_);
}
FrameClosing();
}
void PasswordAutofillAgent::WillSendSubmitEvent(
const blink::WebFormElement& form) {
// Forms submitted via XHR are not seen by WillSubmitForm if the default
// onsubmit handler is overridden. Such submission first gets detected in
// DidStartProvisionalLoad, which no longer knows about the particular form,
// and uses the candidate stored in |provisionally_saved_form_|.
//
// User-typed password will get stored to |provisionally_saved_form_| in
// TextDidChangeInTextField. Autofilled or JavaScript-copied passwords need to
// be saved here.
//
// Only non-empty passwords are saved here. Empty passwords were likely
// cleared by some scripts (http://crbug.com/28910, http://crbug.com/391693).
// Had the user cleared the password, |provisionally_saved_form_| would
// already have been updated in TextDidChangeInTextField.
std::unique_ptr<PasswordForm> password_form = CreatePasswordFormFromWebForm(
form, &field_value_and_properties_map_, &form_predictions_);
ProvisionallySavePassword(std::move(password_form),
RESTRICTION_NON_EMPTY_PASSWORD);
}
void PasswordAutofillAgent::WillSubmitForm(const blink::WebFormElement& form) {
std::unique_ptr<RendererSavePasswordProgressLogger> logger;
if (logging_state_active_) {
logger.reset(new RendererSavePasswordProgressLogger(
GetPasswordManagerDriver().get()));
logger->LogMessage(Logger::STRING_WILL_SUBMIT_FORM_METHOD);
LogHTMLForm(logger.get(), Logger::STRING_HTML_FORM_FOR_SUBMIT, form);
}
std::unique_ptr<PasswordForm> submitted_form = CreatePasswordFormFromWebForm(
form, &field_value_and_properties_map_, &form_predictions_);
// If there is a provisionally saved password, copy over the previous
// password value so we get the user's typed password, not the value that
// may have been transformed for submit.
// TODO(gcasto): Do we need to have this action equality check? Is it trying
// to prevent accidentally copying over passwords from a different form?
if (submitted_form) {
if (logger) {
logger->LogPasswordForm(Logger::STRING_CREATED_PASSWORD_FORM,
*submitted_form);
}
if (provisionally_saved_form_ &&
submitted_form->action == provisionally_saved_form_->action) {
if (logger)
logger->LogMessage(Logger::STRING_SUBMITTED_PASSWORD_REPLACED);
submitted_form->password_value =
provisionally_saved_form_->password_value;
submitted_form->new_password_value =
provisionally_saved_form_->new_password_value;
submitted_form->username_value =
provisionally_saved_form_->username_value;
}
// Some observers depend on sending this information now instead of when
// the frame starts loading. If there are redirects that cause a new
// RenderView to be instantiated (such as redirects to the WebStore)
// we will never get to finish the load.
GetPasswordManagerDriver()->PasswordFormSubmitted(*submitted_form);
provisionally_saved_form_.reset();
} else if (logger) {
logger->LogMessage(Logger::STRING_FORM_IS_NOT_PASSWORD);
}
}
void PasswordAutofillAgent::OnDestruct() {
binding_.Close();
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
}
void PasswordAutofillAgent::DidStartProvisionalLoad() {
std::unique_ptr<RendererSavePasswordProgressLogger> logger;
if (logging_state_active_) {
logger.reset(new RendererSavePasswordProgressLogger(
GetPasswordManagerDriver().get()));
logger->LogMessage(Logger::STRING_DID_START_PROVISIONAL_LOAD_METHOD);
}
const blink::WebLocalFrame* navigated_frame = render_frame()->GetWebFrame();
if (navigated_frame->parent()) {
if (logger)
logger->LogMessage(Logger::STRING_FRAME_NOT_MAIN_FRAME);
return;
}
// Bug fix for crbug.com/368690. isProcessingUserGesture() is false when
// the user is performing actions outside the page (e.g. typed url,
// history navigation). We don't want to trigger saving in these cases.
content::DocumentState* document_state =
content::DocumentState::FromDataSource(
navigated_frame->provisionalDataSource());
content::NavigationState* navigation_state =
document_state->navigation_state();
ui::PageTransition type = navigation_state->GetTransitionType();
if (ui::PageTransitionIsWebTriggerable(type) &&
ui::PageTransitionIsNewNavigation(type) &&
!blink::WebUserGestureIndicator::isProcessingUserGesture()) {
// If onsubmit has been called, try and save that form.
if (provisionally_saved_form_) {
if (logger) {
logger->LogPasswordForm(
Logger::STRING_PROVISIONALLY_SAVED_FORM_FOR_FRAME,
*provisionally_saved_form_);
}
GetPasswordManagerDriver()->PasswordFormSubmitted(
*provisionally_saved_form_);
provisionally_saved_form_.reset();
} else {
std::vector<std::unique_ptr<PasswordForm>> possible_submitted_forms;
// Loop through the forms on the page looking for one that has been
// filled out. If one exists, try and save the credentials.
blink::WebVector<blink::WebFormElement> forms;
render_frame()->GetWebFrame()->document().forms(forms);
bool password_forms_found = false;
for (size_t i = 0; i < forms.size(); ++i) {
blink::WebFormElement form_element = forms[i];
if (logger) {
LogHTMLForm(logger.get(), Logger::STRING_FORM_FOUND_ON_PAGE,
form_element);
}
possible_submitted_forms.push_back(CreatePasswordFormFromWebForm(
form_element, &field_value_and_properties_map_,
&form_predictions_));
}
possible_submitted_forms.push_back(
CreatePasswordFormFromUnownedInputElements(
*render_frame()->GetWebFrame(), &field_value_and_properties_map_,
&form_predictions_));
for (const auto& password_form : possible_submitted_forms) {
if (password_form && !password_form->username_value.empty() &&
FormContainsNonDefaultPasswordValue(*password_form)) {
password_forms_found = true;
if (logger) {
logger->LogPasswordForm(Logger::STRING_PASSWORD_FORM_FOUND_ON_PAGE,
*password_form);
}
GetPasswordManagerDriver()->PasswordFormSubmitted(*password_form);
break;
}
}
if (!password_forms_found && logger)
logger->LogMessage(Logger::STRING_PASSWORD_FORM_NOT_FOUND_ON_PAGE);
}
}
// This is a new navigation, so require a new user gesture before filling in
// passwords.
gatekeeper_.Reset();
}
// mojom::PasswordAutofillAgent:
void PasswordAutofillAgent::FillPasswordForm(
int key,
const PasswordFormFillData& form_data) {
std::vector<blink::WebInputElement> elements;
std::unique_ptr<RendererSavePasswordProgressLogger> logger;
if (logging_state_active_) {
logger.reset(new RendererSavePasswordProgressLogger(
GetPasswordManagerDriver().get()));
logger->LogMessage(Logger::STRING_ON_FILL_PASSWORD_FORM_METHOD);
}
GetFillableElementFromFormData(key, form_data, logger.get(), &elements);
// If wait_for_username is true, we don't want to initially fill the form
// until the user types in a valid username.
if (form_data.wait_for_username)
return;
for (auto element : elements) {
blink::WebInputElement username_element =
!element.isPasswordField() ? element : password_to_username_[element];
blink::WebInputElement password_element =
element.isPasswordField()
? element
: web_input_to_password_info_[element].password_field;
FillFormOnPasswordReceived(
form_data, username_element, password_element,
&field_value_and_properties_map_,
base::Bind(&PasswordValueGatekeeper::RegisterElement,
base::Unretained(&gatekeeper_)),
logger.get());
}
}
void PasswordAutofillAgent::GetFillableElementFromFormData(
int key,
const PasswordFormFillData& form_data,
RendererSavePasswordProgressLogger* logger,
std::vector<blink::WebInputElement>* elements) {
DCHECK(elements);
bool ambiguous_or_empty_names =
DoesFormContainAmbiguousOrEmptyNames(form_data);
FormElementsList forms;
FindFormElements(render_frame(), form_data, ambiguous_or_empty_names, &forms);
if (logger) {
logger->LogBoolean(Logger::STRING_AMBIGUOUS_OR_EMPTY_NAMES,
ambiguous_or_empty_names);
logger->LogNumber(Logger::STRING_NUMBER_OF_POTENTIAL_FORMS_TO_FILL,
forms.size());
logger->LogBoolean(Logger::STRING_FORM_DATA_WAIT,
form_data.wait_for_username);
}
for (const auto& form : forms) {
base::string16 username_field_name;
base::string16 password_field_name =
FieldName(form_data.password_field, ambiguous_or_empty_names);
bool form_contains_fillable_username_field =
FillDataContainsFillableUsername(form_data);
if (form_contains_fillable_username_field) {
username_field_name =
FieldName(form_data.username_field, ambiguous_or_empty_names);
}
if (logger) {
logger->LogBoolean(Logger::STRING_CONTAINS_FILLABLE_USERNAME_FIELD,
form_contains_fillable_username_field);
logger->LogBoolean(Logger::STRING_USERNAME_FIELD_NAME_EMPTY,
username_field_name.empty());
logger->LogBoolean(Logger::STRING_PASSWORD_FIELD_NAME_EMPTY,
password_field_name.empty());
}
// Attach autocomplete listener to enable selecting alternate logins.
blink::WebInputElement username_element;
blink::WebInputElement password_element;
// Check whether the password form has a username input field.
if (!username_field_name.empty()) {
const auto it = form.find(username_field_name);
DCHECK(it != form.end());
username_element = it->second;
}
// No password field, bail out.
if (password_field_name.empty())
break;
// Get pointer to password element. (We currently only support single
// password forms).
{
const auto it = form.find(password_field_name);
DCHECK(it != form.end());
password_element = it->second;
}
blink::WebInputElement main_element =
username_element.isNull() ? password_element : username_element;
// We might have already filled this form if there are two <form> elements
// with identical markup.
if (web_input_to_password_info_.find(main_element) !=
web_input_to_password_info_.end())
continue;
PasswordInfo password_info;
password_info.fill_data = form_data;
password_info.key = key;
password_info.password_field = password_element;
web_input_to_password_info_[main_element] = password_info;
if (!main_element.isPasswordField())
password_to_username_[password_element] = username_element;
if (elements)
elements->push_back(main_element);
}
}
void PasswordAutofillAgent::FocusedNodeHasChanged(const blink::WebNode& node) {
if (node.isNull() || !node.isElementNode())
return;
const blink::WebElement web_element = node.toConst<blink::WebElement>();
if (!web_element.isFormControlElement())
return;
const blink::WebFormControlElement control_element =
web_element.toConst<blink::WebFormControlElement>();
UpdateFieldValueAndPropertiesMaskMap(control_element, nullptr,
FieldPropertiesFlags::HAD_FOCUS,
&field_value_and_properties_map_);
}
// mojom::PasswordAutofillAgent:
void PasswordAutofillAgent::SetLoggingState(bool active) {
logging_state_active_ = active;
}
void PasswordAutofillAgent::AutofillUsernameAndPasswordDataReceived(
const FormsPredictionsMap& predictions) {
form_predictions_.insert(predictions.begin(), predictions.end());
}
void PasswordAutofillAgent::FindFocusedPasswordForm(
const FindFocusedPasswordFormCallback& callback) {
std::unique_ptr<PasswordForm> password_form;
blink::WebElement element =
render_frame()->GetWebFrame()->document().focusedElement();
if (!element.isNull() && element.hasHTMLTagName("input")) {
blink::WebInputElement input = element.to<blink::WebInputElement>();
if (input.isPasswordField() && !input.form().isNull()) {
if (!input.form().isNull()) {
password_form = CreatePasswordFormFromWebForm(
input.form(), &field_value_and_properties_map_, &form_predictions_);
} else {
password_form = CreatePasswordFormFromUnownedInputElements(
*render_frame()->GetWebFrame(), &field_value_and_properties_map_,
&form_predictions_);
// Only try to use this form if |input| is one of the password elements
// for |password_form|.
if (password_form->password_element != input.nameForAutofill() &&
password_form->new_password_element != input.nameForAutofill())
password_form.reset();
}
}
}
if (!password_form)
password_form.reset(new PasswordForm());
callback.Run(*password_form);
}
////////////////////////////////////////////////////////////////////////////////
// PasswordAutofillAgent, private:
bool PasswordAutofillAgent::ShowSuggestionPopup(
const PasswordInfo& password_info,
const blink::WebInputElement& user_input,
bool show_all,
bool show_on_password_field) {
DCHECK(!user_input.isNull());
blink::WebFrame* frame = user_input.document().frame();
if (!frame)
return false;
blink::WebView* webview = frame->view();
if (!webview)
return false;
if (user_input.isPasswordField() && !user_input.isAutofilled() &&
!user_input.value().isEmpty()) {
GetAutofillDriver()->HidePopup();
return false;
}
FormData form;
FormFieldData field;
form_util::FindFormAndFieldForFormControlElement(user_input, &form, &field);
int options = 0;
if (show_all)
options |= SHOW_ALL;
if (show_on_password_field)
options |= IS_PASSWORD_FIELD;
base::string16 username_string(
user_input.isPasswordField()
? base::string16()
: static_cast<base::string16>(user_input.value()));
GetPasswordManagerDriver()->ShowPasswordSuggestions(
password_info.key, field.text_direction, username_string, options,
render_frame()->GetRenderView()->ElementBoundsInWindow(user_input));
username_query_prefix_ = username_string;
return CanShowSuggestion(password_info.fill_data, username_string, show_all);
}
void PasswordAutofillAgent::FrameClosing() {
for (auto const& iter : web_input_to_password_info_) {
password_to_username_.erase(iter.second.password_field);
}
web_input_to_password_info_.clear();
provisionally_saved_form_.reset();
field_value_and_properties_map_.clear();
}
void PasswordAutofillAgent::ClearPreview(
blink::WebInputElement* username,
blink::WebInputElement* password) {
if (!username->isNull() && !username->suggestedValue().isEmpty()) {
username->setSuggestedValue(blink::WebString());
username->setAutofilled(was_username_autofilled_);
username->setSelectionRange(username_query_prefix_.length(),
username->value().length());
}
if (!password->suggestedValue().isEmpty()) {
password->setSuggestedValue(blink::WebString());
password->setAutofilled(was_password_autofilled_);
}
}
void PasswordAutofillAgent::ProvisionallySavePassword(
std::unique_ptr<PasswordForm> password_form,
ProvisionallySaveRestriction restriction) {
if (!password_form || (restriction == RESTRICTION_NON_EMPTY_PASSWORD &&
password_form->password_value.empty() &&
password_form->new_password_value.empty())) {
return;
}
provisionally_saved_form_ = std::move(password_form);
}
bool PasswordAutofillAgent::ProvisionallySavedPasswordIsValid() {
return provisionally_saved_form_ &&
!provisionally_saved_form_->username_value.empty() &&
!(provisionally_saved_form_->password_value.empty() &&
provisionally_saved_form_->new_password_value.empty());
}
const mojom::AutofillDriverPtr& PasswordAutofillAgent::GetAutofillDriver() {
DCHECK(autofill_agent_);
return autofill_agent_->GetAutofillDriver();
}
const mojom::PasswordManagerDriverPtr&
PasswordAutofillAgent::GetPasswordManagerDriver() {
if (!password_manager_driver_) {
render_frame()->GetRemoteInterfaces()->GetInterface(
mojo::MakeRequest(&password_manager_driver_));
}
return password_manager_driver_;
}
} // namespace autofill
|