diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2018-05-03 13:42:47 +0200 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2018-05-15 10:27:51 +0000 |
commit | 8c5c43c7b138c9b4b0bf56d946e61d3bbc111bec (patch) | |
tree | d29d987c4d7b173cf853279b79a51598f104b403 /chromium/components/autofill/core/browser | |
parent | 830c9e163d31a9180fadca926b3e1d7dfffb5021 (diff) | |
download | qtwebengine-chromium-8c5c43c7b138c9b4b0bf56d946e61d3bbc111bec.tar.gz |
BASELINE: Update Chromium to 66.0.3359.156
Change-Id: I0c9831ad39911a086b6377b16f995ad75a51e441
Reviewed-by: Michal Klocek <michal.klocek@qt.io>
Diffstat (limited to 'chromium/components/autofill/core/browser')
55 files changed, 876 insertions, 887 deletions
diff --git a/chromium/components/autofill/core/browser/BUILD.gn b/chromium/components/autofill/core/browser/BUILD.gn index 490257aef3f..cfdd2950579 100644 --- a/chromium/components/autofill/core/browser/BUILD.gn +++ b/chromium/components/autofill/core/browser/BUILD.gn @@ -236,7 +236,6 @@ static_library("browser") { "//components/pref_registry", "//components/prefs", "//components/security_state/core", - "//components/signin/core/browser", "//components/strings", "//components/sync", "//components/variations/net", @@ -244,6 +243,7 @@ static_library("browser") { "//components/webdata/common", "//google_apis", "//net", + "//services/identity/public/cpp", "//services/metrics/public/cpp:metrics_cpp", "//services/metrics/public/cpp:ukm_builders", "//sql", @@ -326,10 +326,10 @@ static_library("test_support") { "//components/os_crypt:test_support", "//components/pref_registry", "//components/prefs:test_support", - "//components/signin/core/browser", "//components/ukm", "//components/ukm:test_support", "//google_apis:test_support", + "//services/identity/public/cpp:test_support", "//skia", "//testing/gtest", "//third_party/libaddressinput:util", @@ -447,8 +447,6 @@ source_set("unit_tests") { "//components/prefs:test_support", "//components/resources", "//components/security_state/core", - "//components/signin/core/browser", - "//components/signin/core/browser:test_support", "//components/strings", "//components/sync", "//components/sync:test_support_driver", @@ -462,6 +460,7 @@ source_set("unit_tests") { "//google_apis", "//google_apis:test_support", "//net:test_support", + "//services/identity/public/cpp:test_support", "//services/metrics/public/cpp:ukm_builders", "//sql", "//testing/gmock", diff --git a/chromium/components/autofill/core/browser/DEPS b/chromium/components/autofill/core/browser/DEPS index ebd3a7e60b6..e50f9ccc9b5 100644 --- a/chromium/components/autofill/core/browser/DEPS +++ b/chromium/components/autofill/core/browser/DEPS @@ -6,7 +6,6 @@ include_rules = [ "+components/metrics", "+components/policy", "+components/security_state", - "+components/signin/core/browser", "+components/sync", "+components/variations", "+components/version_info", @@ -16,12 +15,12 @@ include_rules = [ "+google_apis/gaia", "+google_apis/google_api_keys.h", "+net", + "+services/identity/public", "+services/metrics/public", "+sql", "+third_party/fips181", "+third_party/libaddressinput", # For address i18n. "+third_party/libphonenumber", # For phone number i18n. - "+third_party/libxml", "+third_party/re2", "+ui/base", "+ui/gfx", diff --git a/chromium/components/autofill/core/browser/autocomplete_history_manager.cc b/chromium/components/autofill/core/browser/autocomplete_history_manager.cc index 8fbe4e467ec..1a4f54a622e 100644 --- a/chromium/components/autofill/core/browser/autocomplete_history_manager.cc +++ b/chromium/components/autofill/core/browser/autocomplete_history_manager.cc @@ -61,6 +61,7 @@ void AutocompleteHistoryManager::OnGetAutocompleteSuggestions( query_id_ = query_id; if (!autofill_client_->IsAutocompleteEnabled() || + !autofill_client_->IsAutofillSupported() || form_control_type == "textarea" || IsInAutofillSuggestionsDisabledExperiment()) { SendSuggestions(nullptr); diff --git a/chromium/components/autofill/core/browser/autofill_client.h b/chromium/components/autofill/core/browser/autofill_client.h index c44c5ec4fde..5dc4056f6fd 100644 --- a/chromium/components/autofill/core/browser/autofill_client.h +++ b/chromium/components/autofill/core/browser/autofill_client.h @@ -18,7 +18,6 @@ #include "ui/base/window_open_disposition.h" #include "url/gurl.h" -class IdentityProvider; class PrefService; namespace content { @@ -29,6 +28,10 @@ namespace gfx { class RectF; } +namespace identity { +class IdentityManager; +} + namespace syncer { class SyncService; } @@ -102,8 +105,8 @@ class AutofillClient : public RiskDataLoader { // Gets the sync service associated with the client. virtual syncer::SyncService* GetSyncService() = 0; - // Gets the IdentityProvider associated with the client (for OAuth2). - virtual IdentityProvider* GetIdentityProvider() = 0; + // Gets the IdentityManager associated with the client. + virtual identity::IdentityManager* GetIdentityManager() = 0; // Gets the UKM service associated with this client (for metrics). virtual ukm::UkmRecorder* GetUkmRecorder() = 0; diff --git a/chromium/components/autofill/core/browser/autofill_credit_card_filling_infobar_delegate_mobile.cc b/chromium/components/autofill/core/browser/autofill_credit_card_filling_infobar_delegate_mobile.cc index 2de1eae75f4..d302321d73b 100644 --- a/chromium/components/autofill/core/browser/autofill_credit_card_filling_infobar_delegate_mobile.cc +++ b/chromium/components/autofill/core/browser/autofill_credit_card_filling_infobar_delegate_mobile.cc @@ -72,11 +72,6 @@ bool AutofillCreditCardFillingInfoBarDelegateMobile::Cancel() { return true; } -infobars::InfoBarDelegate::Type -AutofillCreditCardFillingInfoBarDelegateMobile::GetInfoBarType() const { - return PAGE_ACTION_TYPE; -} - infobars::InfoBarDelegate::InfoBarIdentifier AutofillCreditCardFillingInfoBarDelegateMobile::GetIdentifier() const { return AUTOFILL_CREDIT_CARD_FILLING_INFOBAR_DELEGATE_ANDROID; diff --git a/chromium/components/autofill/core/browser/autofill_credit_card_filling_infobar_delegate_mobile.h b/chromium/components/autofill/core/browser/autofill_credit_card_filling_infobar_delegate_mobile.h index 04e030694d5..e73333928d5 100644 --- a/chromium/components/autofill/core/browser/autofill_credit_card_filling_infobar_delegate_mobile.h +++ b/chromium/components/autofill/core/browser/autofill_credit_card_filling_infobar_delegate_mobile.h @@ -41,7 +41,6 @@ class AutofillCreditCardFillingInfoBarDelegateMobile private: // ConfirmInfoBarDelegate (continued): - Type GetInfoBarType() const override; infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; base::string16 GetButtonLabel(InfoBarButton button) const override; diff --git a/chromium/components/autofill/core/browser/autofill_experiments.cc b/chromium/components/autofill/core/browser/autofill_experiments.cc index 07f9ab25513..15ceb84c27c 100644 --- a/chromium/components/autofill/core/browser/autofill_experiments.cc +++ b/chromium/components/autofill/core/browser/autofill_experiments.cc @@ -26,6 +26,8 @@ namespace autofill { const base::Feature kAutofillAlwaysFillAddresses{ "AlwaysFillAddresses", base::FEATURE_ENABLED_BY_DEFAULT}; +const base::Feature kAutofillAutoDismissableUpstreamBubble{ + "AutofillAutoDismissableUpstreamBubble", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kAutofillCreateDataForTest{ "AutofillCreateDataForTest", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kAutofillCreditCardAssist{ @@ -46,9 +48,8 @@ const base::Feature kAutofillDeleteDisusedCreditCards{ "AutofillDeleteDisusedCreditCards", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kAutofillExpandedPopupViews{ "AutofillExpandedPopupViews", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kAutofillOfferLocalSaveIfServerCardManuallyEntered{ - "AutofillOfferLocalSaveIfServerCardManuallyEntered", - base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kAutofillPreferServerNamePredictions{ + "AutofillPreferServerNamePredictions", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kAutofillRationalizeFieldTypePredictions{ "AutofillRationalizeFieldTypePredictions", base::FEATURE_ENABLED_BY_DEFAULT}; @@ -58,9 +59,6 @@ const base::Feature kAutofillSuppressDisusedAddresses{ "AutofillSuppressDisusedAddresses", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kAutofillSuppressDisusedCreditCards{ "AutofillSuppressDisusedCreditCards", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kAutofillToolkitViewsCreditCardDialogsMac{ - "AutofillToolkitViewsCreditCardDialogsMac", - base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kAutofillUpstreamAllowAllEmailDomains{ "AutofillUpstreamAllowAllEmailDomains", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kAutofillUpstreamRequestCvcIfMissing{ @@ -84,7 +82,7 @@ const char kAutofillCreditCardLastUsedDateShowExpirationDateKey[] = #if defined(OS_MACOSX) const base::Feature kCreditCardAutofillTouchBar{ - "CreditCardAutofillTouchBar", base::FEATURE_DISABLED_BY_DEFAULT}; + "CreditCardAutofillTouchBar", base::FEATURE_ENABLED_BY_DEFAULT}; #endif // defined(OS_MACOSX) namespace { @@ -125,6 +123,10 @@ bool IsAutofillCreditCardPopupLayoutExperimentEnabled() { return base::FeatureList::IsEnabled(kAutofillCreditCardPopupLayout); } +bool IsAutofillAutoDismissableUpstreamBubbleExperimentEnabled() { + return base::FeatureList::IsEnabled(kAutofillAutoDismissableUpstreamBubble); +} + bool IsAutofillCreditCardLastUsedDateDisplayExperimentEnabled() { return base::FeatureList::IsEnabled(kAutofillCreditCardLastUsedDateDisplay); } @@ -273,11 +275,6 @@ bool IsCreditCardUploadEnabled(const PrefService* pref_service, return !group_name.empty() && group_name != "Disabled"; } -bool IsAutofillOfferLocalSaveIfServerCardManuallyEnteredExperimentEnabled() { - return base::FeatureList::IsEnabled( - kAutofillOfferLocalSaveIfServerCardManuallyEntered); -} - bool IsAutofillSendBillingCustomerNumberExperimentEnabled() { return base::FeatureList::IsEnabled(kAutofillSendBillingCustomerNumber); } diff --git a/chromium/components/autofill/core/browser/autofill_experiments.h b/chromium/components/autofill/core/browser/autofill_experiments.h index 4589881391d..b0f8c9892cf 100644 --- a/chromium/components/autofill/core/browser/autofill_experiments.h +++ b/chromium/components/autofill/core/browser/autofill_experiments.h @@ -26,6 +26,7 @@ namespace autofill { struct Suggestion; extern const base::Feature kAutofillAlwaysFillAddresses; +extern const base::Feature kAutofillAutoDismissableUpstreamBubble; extern const base::Feature kAutofillCreateDataForTest; extern const base::Feature kAutofillCreditCardAssist; extern const base::Feature kAutofillScanCardholderName; @@ -36,12 +37,11 @@ extern const base::Feature kAutofillCreditCardLastUsedDateDisplay; extern const base::Feature kAutofillDeleteDisusedAddresses; extern const base::Feature kAutofillDeleteDisusedCreditCards; extern const base::Feature kAutofillExpandedPopupViews; -extern const base::Feature kAutofillOfferLocalSaveIfServerCardManuallyEntered; +extern const base::Feature kAutofillPreferServerNamePredictions; extern const base::Feature kAutofillRationalizeFieldTypePredictions; extern const base::Feature kAutofillSendBillingCustomerNumber; extern const base::Feature kAutofillSuppressDisusedAddresses; extern const base::Feature kAutofillSuppressDisusedCreditCards; -extern const base::Feature kAutofillToolkitViewsCreditCardDialogsMac; extern const base::Feature kAutofillUpstreamAllowAllEmailDomains; extern const base::Feature kAutofillUpstreamRequestCvcIfMissing; extern const base::Feature kAutofillUpstreamSendDetectedValues; @@ -83,6 +83,10 @@ bool IsCreditCardUploadEnabled(const PrefService* pref_service, // enabled. bool IsAutofillCreditCardPopupLayoutExperimentEnabled(); +// Returns whether the experiment to make the credit card Upstream bubble non +// sticky is enabled. +bool IsAutofillAutoDismissableUpstreamBubbleExperimentEnabled(); + // Returns whether Autofill credit card last used date display experiment is // enabled. bool IsAutofillCreditCardLastUsedDateDisplayExperimentEnabled(); @@ -125,12 +129,6 @@ void ModifyAutofillCreditCardSuggestion(struct Suggestion* suggestion); // layout. unsigned int GetPopupMargin(); -// Returns whether the experiment is enabled where if Chrome Autofill has a -// server card synced down from Payments but the user manually enters its card -// number into a checkout form anyway, the option to locally save the card is -// offered. -bool IsAutofillOfferLocalSaveIfServerCardManuallyEnteredExperimentEnabled(); - // Returns whether the experiment is enabled where Chrome reads billing customer // number from priority preference and sends it along with UploadCardRequest and // FullCardRequest. diff --git a/chromium/components/autofill/core/browser/autofill_field.cc b/chromium/components/autofill/core/browser/autofill_field.cc index 0e86da83827..40b92446559 100644 --- a/chromium/components/autofill/core/browser/autofill_field.cc +++ b/chromium/components/autofill/core/browser/autofill_field.cc @@ -6,7 +6,9 @@ #include <stdint.h> +#include "base/feature_list.h" #include "base/strings/string_number_conversions.h" +#include "components/autofill/core/browser/autofill_experiments.h" #include "components/autofill/core/browser/autofill_type.h" #include "components/autofill/core/browser/field_types.h" #include "components/autofill/core/browser/proto/server.pb.h" @@ -108,21 +110,29 @@ AutofillType AutofillField::Type() const { } if (overall_server_type_ != NO_SERVER_DATA) { - // See http://crbug.com/429236 for background on why we might not always - // believe the server. - // TODO(http://crbug.com/589129) investigate how well the server is doing in - // regard to credit card predictions. - bool believe_server = - !(overall_server_type_ == NAME_FULL && - heuristic_type_ == CREDIT_CARD_NAME_FULL) && - !(overall_server_type_ == CREDIT_CARD_NAME_FULL && - heuristic_type_ == NAME_FULL) && - !(overall_server_type_ == NAME_FIRST && - heuristic_type_ == CREDIT_CARD_NAME_FIRST) && - !(overall_server_type_ == NAME_LAST && - heuristic_type_ == CREDIT_CARD_NAME_LAST) && - // CVC is sometimes type="password", which tricks the server. - // See http://crbug.com/469007 + // Sometimes the server and heuristics disagree on whether a name field + // should be associated with an address or a credit card. There was a + // decision to prefer the heuristics in these cases, but it looks like + // it might be better to fix this server-side. + // See http://crbug.com/429236 for background. + bool believe_server; + if (base::FeatureList::IsEnabled(kAutofillPreferServerNamePredictions)) { + believe_server = true; + } else { + believe_server = !(overall_server_type_ == NAME_FULL && + heuristic_type_ == CREDIT_CARD_NAME_FULL) && + !(overall_server_type_ == CREDIT_CARD_NAME_FULL && + heuristic_type_ == NAME_FULL) && + !(overall_server_type_ == NAME_FIRST && + heuristic_type_ == CREDIT_CARD_NAME_FIRST) && + !(overall_server_type_ == NAME_LAST && + heuristic_type_ == CREDIT_CARD_NAME_LAST); + } + + // Either way, retain a preference for the the CVC heuristic over the + // server's password predictions (http://crbug.com/469007) + believe_server = + believe_server && !(AutofillType(overall_server_type_).group() == PASSWORD_FIELD && heuristic_type_ == CREDIT_CARD_VERIFICATION_CODE); if (believe_server) diff --git a/chromium/components/autofill/core/browser/autofill_manager.cc b/chromium/components/autofill/core/browser/autofill_manager.cc index 50180a1c2c9..1b129ef4724 100644 --- a/chromium/components/autofill/core/browser/autofill_manager.cc +++ b/chromium/components/autofill/core/browser/autofill_manager.cc @@ -69,7 +69,6 @@ #include "components/prefs/pref_service.h" #include "components/security_state/core/security_state.h" #include "components/strings/grit/components_strings.h" -#include "google_apis/gaia/identity_provider.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/geometry/rect.h" #include "url/gurl.h" @@ -96,9 +95,9 @@ const size_t kMaxFormCacheSize = 100; // Precondition: |form_structure| and |form| should correspond to the same // logical form. Returns true if any field in the given |section| within |form| // is auto-filled. -bool SectionIsAutofilled(const FormStructure& form_structure, - const FormData& form, - const std::string& section) { +bool SectionHasAutofilledField(const FormStructure& form_structure, + const FormData& form, + const std::string& section) { DCHECK_EQ(form_structure.field_count(), form.fields.size()); for (size_t i = 0; i < form_structure.field_count(); ++i) { if (form_structure.field(i)->section() == section && @@ -606,14 +605,14 @@ void AutofillManager::OnQueryFormFieldAutofillImpl( POPUP_ITEM_ID_INSECURE_CONTEXT_PAYMENT_DISABLED_MESSAGE; suggestions.assign(1, warning_suggestion); } else { - bool section_is_autofilled = SectionIsAutofilled( + bool section_has_autofilled_field = SectionHasAutofilledField( *form_structure, form, autofill_field->section()); - if (section_is_autofilled) { - // If the relevant section is auto-filled and the renderer is querying - // for suggestions, then the user is editing the value of a field. - // In this case, mimic autocomplete: don't display labels or icons, - // as that information is redundant. Moreover, filter out duplicate - // suggestions. + if (section_has_autofilled_field) { + // If the relevant section has auto-filled fields and the renderer is + // querying for suggestions, then for some fields, the user is editing + // the value of a field. In this case, mimic autocomplete: don't + // display labels or icons, as that information is redundant. + // Moreover, filter out duplicate suggestions. std::set<base::string16> seen_values; for (auto iter = suggestions.begin(); iter != suggestions.end();) { if (!seen_values.insert(iter->value).second) { @@ -631,7 +630,8 @@ void AutofillManager::OnQueryFormFieldAutofillImpl( // suggestions available. // TODO(mathp): Differentiate between number of suggestions available // (current metric) and number shown to the user. - if (!has_logged_address_suggestions_count_ && !section_is_autofilled) { + if (!has_logged_address_suggestions_count_ && + !section_has_autofilled_field) { AutofillMetrics::LogAddressSuggestionsCount(suggestions.size()); has_logged_address_suggestions_count_ = true; } @@ -690,17 +690,12 @@ bool AutofillManager::WillFillCreditCardNumber(const FormData& form, if (autofill_field->Type().GetStorableType() == CREDIT_CARD_NUMBER) return true; - // If the relevant section is already autofilled, the new fill operation will - // only fill |autofill_field|. - if (SectionIsAutofilled(*form_structure, form, autofill_field->section())) - return false; - DCHECK_EQ(form_structure->field_count(), form.fields.size()); for (size_t i = 0; i < form_structure->field_count(); ++i) { if (form_structure->field(i)->section() == autofill_field->section() && form_structure->field(i)->Type().GetStorableType() == CREDIT_CARD_NUMBER && - form.fields[i].value.empty()) { + form.fields[i].value.empty() && !form.fields[i].is_autofilled) { return true; } } @@ -1178,7 +1173,7 @@ AutofillManager::AutofillManager( payments_client_(std::make_unique<payments::PaymentsClient>( driver->GetURLRequestContext(), client->GetPrefs(), - client->GetIdentityProvider(), + client->GetIdentityManager(), /*unmask_delegate=*/this, // save_delegate starts out as nullptr and is set up by the // CreditCardSaveManager owned by form_data_importer_. @@ -1325,25 +1320,6 @@ void AutofillManager::FillOrPreviewDataModelForm( form_structure->RationalizePhoneNumbersInSection(autofill_field->section()); } - // If the relevant section is auto-filled, we should fill |field| but not the - // rest of the form. - if (SectionIsAutofilled(*form_structure, form, autofill_field->section())) { - for (FormFieldData& iter : result.fields) { - if (iter.SameFieldAs(field)) { - FillFieldWithValue(autofill_field, data_model, &iter, - /*should_notify=*/!is_credit_card, cvc); - break; - } - } - - // Note that this may invalidate |data_model|. - if (action == AutofillDriver::FORM_DATA_ACTION_FILL) - personal_data_->RecordUseOf(data_model); - - driver()->SendFormDataToRenderer(query_id, action, result); - return; - } - DCHECK_EQ(form_structure->field_count(), form.fields.size()); for (size_t i = 0; i < form_structure->field_count(); ++i) { @@ -1360,6 +1336,17 @@ void AutofillManager::FillOrPreviewDataModelForm( AutofillField* cached_field = form_structure->field(i); FieldTypeGroup field_group_type = cached_field->Type().group(); + // Don't fill hidden fields. + if (!cached_field->is_focusable || + cached_field->role == FormFieldData::ROLE_ATTRIBUTE_PRESENTATION) { + continue; + } + + // Don't fill previously autofilled fields. + if (result.fields[i].is_autofilled && !cached_field->SameFieldAs(field)) { + continue; + } + if (field_group_type == NO_GROUP) continue; @@ -1411,7 +1398,9 @@ std::unique_ptr<FormStructure> AutofillManager::ValidateSubmittedForm( if (!FindCachedForm(form, &cached_submitted_form)) return std::unique_ptr<FormStructure>(); - submitted_form->UpdateFromCache(*cached_submitted_form, false); + submitted_form->RetrieveFromCache(*cached_submitted_form, + /* apply_is_autofilled */ false, + /* only_server_and_autofill_state */ false); return submitted_form; } @@ -1513,9 +1502,11 @@ bool AutofillManager::UpdateCachedForm(const FormData& live_form, if (!ParseForm(live_form, updated_form)) return false; + // We need to keep the server data. if (cached_form) - (*updated_form)->UpdateFromCache(*cached_form, true); - + (*updated_form) + ->RetrieveFromCache(*cached_form, /* apply_is_autofilled */ true, + /* only_server_and_autofill_state */ true); // Annotate the updated form with its predicted types. driver()->SendAutofillTypePredictionsToRenderer({*updated_form}); diff --git a/chromium/components/autofill/core/browser/autofill_manager_unittest.cc b/chromium/components/autofill/core/browser/autofill_manager_unittest.cc index c59970f7156..ccfdc65244e 100644 --- a/chromium/components/autofill/core/browser/autofill_manager_unittest.cc +++ b/chromium/components/autofill/core/browser/autofill_manager_unittest.cc @@ -1852,10 +1852,16 @@ TEST_F(AutofillManagerTest, WillFillCreditCardNumber) { number_field->value.clear(); EXPECT_TRUE(WillFillCreditCardNumber(form, *name_field)); - // When part of the section is Autofilled, only fill the initiating field. - month_field->is_autofilled = true; + // When the number is already autofilled, we won't fill it. + number_field->is_autofilled = true; EXPECT_FALSE(WillFillCreditCardNumber(form, *name_field)); EXPECT_TRUE(WillFillCreditCardNumber(form, *number_field)); + + // If another field is filled, we would still fill other non-filled fields in + // the section. + number_field->is_autofilled = false; + name_field->is_autofilled = true; + EXPECT_TRUE(WillFillCreditCardNumber(form, *name_field)); } // Test that we correctly log FIELD_WAS_AUTOFILLED event in UserHappiness. @@ -2448,7 +2454,7 @@ TEST_F(AutofillManagerTest, FillCreditCardForm_ExpiredCard) { } // Test that non-focusable field is ignored while inferring boundaries between -// sections: http://crbug.com/231160 +// sections, but not filled. TEST_F(AutofillManagerTest, FillFormWithNonFocusableFields) { // Create a form with both focusable and non-focusable fields. FormData form; @@ -2488,8 +2494,8 @@ TEST_F(AutofillManagerTest, FillFormWithNonFocusableFields) { MakeFrontendID(std::string(), guid), &response_page_id, &response_data); - // The whole form should be filled as all the fields belong to the same - // logical section. + // All the visible fields should be filled as all the fields belong to the + // same logical section. ASSERT_EQ(6U, response_data.fields.size()); ExpectFilledField("First Name", "firstname", "Elvis", "text", response_data.fields[0]); @@ -2498,8 +2504,7 @@ TEST_F(AutofillManagerTest, FillFormWithNonFocusableFields) { response_data.fields[2]); ExpectFilledField("Phone Number", "phonenumber", "12345678901", "tel", response_data.fields[3]); - ExpectFilledField("", "email_", "theking@gmail.com", "text", - response_data.fields[4]); + ExpectFilledField("", "email_", "", "text", response_data.fields[4]); ExpectFilledField("Country", "country", "United States", "text", response_data.fields[5]); } @@ -2761,8 +2766,12 @@ TEST_F(AutofillManagerTest, FillAutofilledForm) { // Set up our form data. FormData form; test::CreateTestAddressFormData(&form); - // Mark one of the address fields as autofilled. - form.fields[4].is_autofilled = true; + // Mark the address fields as autofilled. + for (std::vector<FormFieldData>::iterator iter = form.fields.begin(); + iter != form.fields.end(); ++iter) { + iter->is_autofilled = true; + } + CreateTestCreditCardFormData(&form, true, false); std::vector<FormData> forms(1, form); FormsSeen(forms); @@ -2814,10 +2823,55 @@ TEST_F(AutofillManagerTest, FillAutofilledForm) { } } +// Test that we correctly fill a previously partly auto-filled form. +TEST_F(AutofillManagerTest, FillPartlyAutofilledForm) { + // Set up our form data. + FormData form; + test::CreateTestAddressFormData(&form); + // Mark couple of the address fields as autofilled. + form.fields[3].is_autofilled = true; + form.fields[4].is_autofilled = true; + form.fields[5].is_autofilled = true; + form.fields[6].is_autofilled = true; + form.fields[10].is_autofilled = true; + + CreateTestCreditCardFormData(&form, true, false); + std::vector<FormData> forms(1, form); + FormsSeen(forms); + + // First fill the address data. + const char guid[] = "00000000-0000-0000-0000-000000000001"; + int response_page_id = 0; + FormData response_data; + FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(), + MakeFrontendID(std::string(), guid), + &response_page_id, &response_data); + { + SCOPED_TRACE("Address"); + ExpectFilledForm(response_page_id, response_data, kDefaultPageID, "Elvis", + "Aaron", "Presley", "", "", "", "", "38116", + "United States", "12345678901", "", "", "", "", "", true, + true, false); + } + + // Now fill the credit card data. + const int kPageID2 = 2; + const char guid2[] = "00000000-0000-0000-0000-000000000004"; + response_page_id = 0; + FillAutofillFormDataAndSaveResults(kPageID2, form, form.fields.back(), + MakeFrontendID(guid2, std::string()), + &response_page_id, &response_data); + { + SCOPED_TRACE("Credit card 1"); + ExpectFilledCreditCardFormElvis(response_page_id, response_data, kPageID2, + true); + } +} + // Test that we correctly fill a phone number split across multiple fields. TEST_F(AutofillManagerTest, FillPhoneNumber) { - // In one form, rely on the maxlength attribute to imply US phone number - // parts. In the other form, rely on the autocompletetype attribute. + // In one form, rely on the max length attribute to imply US phone number + // parts. In the other form, rely on the autocomplete type attribute. FormData form_with_us_number_max_length; form_with_us_number_max_length.name = ASCIIToUTF16("MyMaxlengthPhoneForm"); form_with_us_number_max_length.origin = @@ -3555,7 +3609,7 @@ TEST_F(AutofillManagerTest, FillFirstPhoneNumber_HiddenFieldShouldNotCount) { ASSERT_EQ(4U, response_data.fields.size()); EXPECT_EQ(ASCIIToUTF16("Charles Hardin Holley"), response_data.fields[0].value); - EXPECT_EQ(ASCIIToUTF16("6505554567"), response_data.fields[1].value); + EXPECT_EQ(ASCIIToUTF16(""), response_data.fields[1].value); EXPECT_EQ(base::string16(), response_data.fields[2].value); EXPECT_EQ(ASCIIToUTF16("6505554567"), response_data.fields[3].value); } @@ -3767,6 +3821,79 @@ TEST_F(AutofillManagerTest, FormChangesAddField) { false); } +// Test that we can still fill a form when the visibility of some fields +// changes. +TEST_F(AutofillManagerTest, FormChangesVisibilityOfFields) { + // Set up our form data. + FormData form; + FormFieldData field; + + // Default is zero, have to set to a number autofill can process. + field.max_length = 10; + form.name = ASCIIToUTF16("multiple_groups_fields"); + test::CreateTestFormField("First Name", "first_name", "", "text", &field); + form.fields.push_back(field); + test::CreateTestFormField("Last Name", "last_name", "", "text", &field); + form.fields.push_back(field); + test::CreateTestFormField("Address", "address", "", "text", &field); + form.fields.push_back(field); + + test::CreateTestFormField("Postal Code", "postal_code", "", "text", &field); + field.is_focusable = false; + form.fields.push_back(field); + + test::CreateTestFormField("Country", "country", "", "text", &field); + field.is_focusable = false; + form.fields.push_back(field); + + std::vector<FormData> forms(1, form); + FormsSeen(forms); + + // Fill the form with the first profile. The hidden fields will not get + // filled. + const char guid[] = "00000000-0000-0000-0000-000000000001"; + int response_page_id = 0; + FormData response_data; + FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0], + MakeFrontendID(std::string(), guid), + &response_page_id, &response_data); + + ASSERT_EQ(5U, response_data.fields.size()); + ExpectFilledField("First Name", "first_name", "Elvis", "text", + response_data.fields[0]); + ExpectFilledField("Last Name", "last_name", "Presley", "text", + response_data.fields[1]); + ExpectFilledField("Address", "address", "3734 Elvis Presley Blvd.", "text", + response_data.fields[2]); + ExpectFilledField("Postal Code", "postal_code", "", "text", + response_data.fields[3]); + ExpectFilledField("Country", "country", "", "text", response_data.fields[4]); + + // Two other fields will show up. Select the second profile. The fields that + // were already filled, would be left unchanged, and the rest would be filled + // with the second profile. (Two different profiles are selected, to make sure + // the right fields are getting filled.) + response_data.fields[3].is_focusable = true; + response_data.fields[4].is_focusable = true; + FormData later_response_data; + const char guid2[] = "00000000-0000-0000-0000-000000000002"; + FillAutofillFormDataAndSaveResults(kDefaultPageID, response_data, + response_data.fields[4], + MakeFrontendID(std::string(), guid2), + &response_page_id, &later_response_data); + ASSERT_EQ(5U, later_response_data.fields.size()); + ExpectFilledField("First Name", "first_name", "Elvis", "text", + later_response_data.fields[0]); + ExpectFilledField("Last Name", "last_name", "Presley", "text", + later_response_data.fields[1]); + ExpectFilledField("Address", "address", "3734 Elvis Presley Blvd.", "text", + later_response_data.fields[2]); + ExpectFilledField("Postal Code", "postal_code", "79401", "text", + later_response_data.fields[3]); + ExpectFilledField("Country", "country", "United States", "text", + later_response_data.fields[4]); +} + // Test that we are able to save form data when forms are submitted. TEST_F(AutofillManagerTest, FormSubmitted) { // Set up our form data. diff --git a/chromium/components/autofill/core/browser/autofill_merge_unittest.cc b/chromium/components/autofill/core/browser/autofill_merge_unittest.cc index ce993ac659c..87dc8149da5 100644 --- a/chromium/components/autofill/core/browser/autofill_merge_unittest.cc +++ b/chromium/components/autofill/core/browser/autofill_merge_unittest.cc @@ -275,13 +275,10 @@ void AutofillMergeTest::MergeProfiles(const std::string& profiles, // Import the profile. std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - form_data_importer_->ImportFormData( - form_structure, - true, // credit card autofill enabled - false, // should return local card - &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card); + form_data_importer_->ImportFormData(form_structure, + true, // credit card autofill enabled + false, // should return local card + &imported_credit_card); EXPECT_FALSE(imported_credit_card); // Clear the |form| to start a new profile. diff --git a/chromium/components/autofill/core/browser/autofill_metrics.cc b/chromium/components/autofill/core/browser/autofill_metrics.cc index 3bf9b0264e8..4f9a0dbb69b 100644 --- a/chromium/components/autofill/core/browser/autofill_metrics.cc +++ b/chromium/components/autofill/core/browser/autofill_metrics.cc @@ -143,6 +143,7 @@ int GetFieldTypeGroupMetric(ServerFieldType field_type, break; case ADDRESS_HOME_STREET_ADDRESS: group = GROUP_STREET_ADDRESS; + break; case ADDRESS_HOME_CITY: group = GROUP_ADDRESS_CITY; break; @@ -271,8 +272,7 @@ const char* GetQualityMetricTypeSuffix( switch (metric_type) { default: NOTREACHED(); - // Fall through... - + FALLTHROUGH; case AutofillMetrics::TYPE_SUBMISSION: return ""; case AutofillMetrics::TYPE_NO_SUBMISSION: @@ -633,6 +633,14 @@ void AutofillMetrics::LogSubmittedServerCardExpirationStatusMetric( } // static +void AutofillMetrics::LogSubmittedCardStateMetric( + SubmittedCardStateMetric metric) { + DCHECK_LT(metric, NUM_SUBMITTED_CARD_STATE_METRICS); + UMA_HISTOGRAM_ENUMERATION("Autofill.SubmittedCardState", metric, + NUM_SUBMITTED_CARD_STATE_METRICS); +} + +// static void AutofillMetrics::LogCardUploadDecisionMetrics( int upload_decision_metrics) { DCHECK(upload_decision_metrics); @@ -1526,8 +1534,6 @@ void AutofillMetrics::FormEventLogger::Log(FormEvent event) const { } // Logging again in a different histogram for segmentation purposes. - // TODO(waltercacau): Re-evaluate if we still need such fine grained - // segmentation. http://crbug.com/454018 if (server_record_type_count_ == 0 && local_record_type_count_ == 0) name += ".WithNoData"; else if (server_record_type_count_ > 0 && local_record_type_count_ == 0) diff --git a/chromium/components/autofill/core/browser/autofill_metrics.h b/chromium/components/autofill/core/browser/autofill_metrics.h index 09e1d064b2b..be86575c086 100644 --- a/chromium/components/autofill/core/browser/autofill_metrics.h +++ b/chromium/components/autofill/core/browser/autofill_metrics.h @@ -118,6 +118,19 @@ class AutofillMetrics { NUM_INFO_BAR_METRICS, }; + // Represents card submitted state. + enum SubmittedCardStateMetric { + // Submitted card has valid card number and expiration date. + HAS_CARD_NUMBER_AND_EXPIRATION_DATE, + // Submitted card has a valid card number but an invalid or missing + // expiration date. + HAS_CARD_NUMBER_ONLY, + // Submitted card has a valid expiration date but an invalid or missing card + // number. + HAS_EXPIRATION_DATE_ONLY, + NUM_SUBMITTED_CARD_STATE_METRICS, + }; + // Metric to measure if a submitted card's expiration date matches the same // server card's expiration date (unmasked or not). Cards are considered to // be the same if they have the same card number (if unmasked) or if they have @@ -694,6 +707,8 @@ class AutofillMetrics { static void LogSubmittedServerCardExpirationStatusMetric( SubmittedServerCardExpirationStatusMetric metric); + static void LogSubmittedCardStateMetric(SubmittedCardStateMetric metric); + // |upload_decision_metrics| is a bitmask of |CardUploadDecisionMetric|. static void LogCardUploadDecisionMetrics(int upload_decision_metrics); static void LogCreditCardInfoBarMetric( diff --git a/chromium/components/autofill/core/browser/autofill_metrics_unittest.cc b/chromium/components/autofill/core/browser/autofill_metrics_unittest.cc index 87676d05c18..2db7c2a517b 100644 --- a/chromium/components/autofill/core/browser/autofill_metrics_unittest.cc +++ b/chromium/components/autofill/core/browser/autofill_metrics_unittest.cc @@ -14,6 +14,7 @@ #include "base/macros.h" #include "base/metrics/metrics_hashes.h" #include "base/strings/string16.h" +#include "base/strings/utf_string_conversions.h" #include "base/test/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/test/scoped_task_environment.h" @@ -35,10 +36,6 @@ #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/form_field_data.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/fake_signin_manager.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/test_signin_client.h" #include "components/ukm/test_ukm_recorder.h" #include "components/ukm/ukm_source.h" #include "components/webdata/common/web_data_results.h" @@ -207,7 +204,6 @@ class AutofillMetricsTest : public testing::Test { void TearDown() override; protected: - void EnableWalletSync(); void CreateAmbiguousProfiles(); // Removes all existing profiles and creates one profile. @@ -226,9 +222,6 @@ class AutofillMetricsTest : public testing::Test { base::test::ScopedTaskEnvironment scoped_task_environment_; ukm::TestAutoSetUkmRecorder test_ukm_recorder_; MockAutofillClient autofill_client_; - std::unique_ptr<AccountTrackerService> account_tracker_; - std::unique_ptr<FakeSigninManagerBase> signin_manager_; - std::unique_ptr<TestSigninClient> signin_client_; std::unique_ptr<TestAutofillDriver> autofill_driver_; std::unique_ptr<TestAutofillManager> autofill_manager_; std::unique_ptr<TestPersonalDataManager> personal_data_; @@ -248,21 +241,9 @@ AutofillMetricsTest::~AutofillMetricsTest() { void AutofillMetricsTest::SetUp() { autofill_client_.SetPrefs(test::PrefServiceForTesting()); - // Set up identity services. - signin_client_ = - std::make_unique<TestSigninClient>(autofill_client_.GetPrefs()); - account_tracker_ = std::make_unique<AccountTrackerService>(); - account_tracker_->Initialize(signin_client_.get()); - - signin_manager_ = std::make_unique<FakeSigninManagerBase>( - signin_client_.get(), account_tracker_.get()); - signin_manager_->Initialize(autofill_client_.GetPrefs()); - personal_data_ = std::make_unique<TestPersonalDataManager>(); personal_data_->set_database(autofill_client_.GetDatabase()); personal_data_->SetPrefService(autofill_client_.GetPrefs()); - personal_data_->set_account_tracker(account_tracker_.get()); - personal_data_->set_signin_manager(signin_manager_.get()); autofill_driver_ = std::make_unique<TestAutofillDriver>(); autofill_manager_ = std::make_unique<TestAutofillManager>( autofill_driver_.get(), &autofill_client_, personal_data_.get()); @@ -281,19 +262,10 @@ void AutofillMetricsTest::TearDown() { autofill_manager_.reset(); autofill_driver_.reset(); personal_data_.reset(); - signin_manager_->Shutdown(); - signin_manager_.reset(); - account_tracker_->Shutdown(); - account_tracker_.reset(); - signin_client_.reset(); test::ReenableSystemServices(); test_ukm_recorder_.Purge(); } -void AutofillMetricsTest::EnableWalletSync() { - signin_manager_->SetAuthenticatedAccountInfo("12345", "syncuser@example.com"); -} - void AutofillMetricsTest::CreateAmbiguousProfiles() { personal_data_->ClearProfiles(); CreateTestAutofillProfiles(); @@ -2462,8 +2434,7 @@ TEST_F(AutofillMetricsTest, AutofillIsEnabledAtStartup) { base::HistogramTester histogram_tester; personal_data_->SetAutofillEnabled(true); personal_data_->Init(autofill_client_.GetDatabase(), - autofill_client_.GetPrefs(), account_tracker_.get(), - signin_manager_.get(), false); + autofill_client_.GetPrefs(), nullptr, false); histogram_tester.ExpectUniqueSample("Autofill.IsEnabled.Startup", true, 1); } @@ -2472,8 +2443,7 @@ TEST_F(AutofillMetricsTest, AutofillIsDisabledAtStartup) { base::HistogramTester histogram_tester; personal_data_->SetAutofillEnabled(false); personal_data_->Init(autofill_client_.GetDatabase(), - autofill_client_.GetPrefs(), account_tracker_.get(), - signin_manager_.get(), false); + autofill_client_.GetPrefs(), nullptr, false); histogram_tester.ExpectUniqueSample("Autofill.IsEnabled.Startup", false, 1); } @@ -3139,7 +3109,6 @@ TEST_F(AutofillMetricsTest, CreditCardShownFormEvents) { // Test that we log selected form event for credit cards. TEST_F(AutofillMetricsTest, CreditCardSelectedFormEvents) { - EnableWalletSync(); // Creating all kinds of cards. RecreateCreditCards(true /* include_local_credit_card */, true /* include_masked_server_credit_card */, @@ -3381,7 +3350,6 @@ TEST_F(AutofillMetricsTest, CreditCardFilledFormEvents) { // Test that we log submitted form events for credit cards. TEST_F(AutofillMetricsTest, CreditCardGetRealPanDuration) { - EnableWalletSync(); // Creating masked card RecreateCreditCards(false /* include_local_credit_card */, true /* include_masked_server_credit_card */, @@ -3453,7 +3421,6 @@ TEST_F(AutofillMetricsTest, CreditCardGetRealPanDuration) { TEST_F(AutofillMetricsTest, CreditCardSubmittedWithoutSelectingSuggestionsNoCard) { - EnableWalletSync(); // Create a local card for testing, card number is 4111111111111111. RecreateCreditCards(true /* include_local_credit_card */, false /* include_masked_server_credit_card */, @@ -3496,7 +3463,6 @@ TEST_F(AutofillMetricsTest, TEST_F(AutofillMetricsTest, CreditCardSubmittedWithoutSelectingSuggestionsWrongSizeCard) { - EnableWalletSync(); // Create a local card for testing, card number is 4111111111111111. RecreateCreditCards(true /* include_local_credit_card */, false /* include_masked_server_credit_card */, @@ -3538,7 +3504,6 @@ TEST_F(AutofillMetricsTest, TEST_F(AutofillMetricsTest, CreditCardSubmittedWithoutSelectingSuggestionsFailLuhnCheckCard) { - EnableWalletSync(); // Create a local card for testing, card number is 4111111111111111. RecreateCreditCards(true /* include_local_credit_card */, false /* include_masked_server_credit_card */, @@ -3581,7 +3546,6 @@ TEST_F(AutofillMetricsTest, TEST_F(AutofillMetricsTest, CreditCardSubmittedWithoutSelectingSuggestionsUnknownCard) { - EnableWalletSync(); // Create a local card for testing, card number is 4111111111111111. RecreateCreditCards(true /* include_local_credit_card */, false /* include_masked_server_credit_card */, @@ -3626,7 +3590,6 @@ TEST_F(AutofillMetricsTest, TEST_F(AutofillMetricsTest, CreditCardSubmittedWithoutSelectingSuggestionsKnownCard) { - EnableWalletSync(); // Create a local card for testing, card number is 4111111111111111. RecreateCreditCards(true /* include_local_credit_card */, false /* include_masked_server_credit_card */, @@ -3671,7 +3634,6 @@ TEST_F(AutofillMetricsTest, TEST_F(AutofillMetricsTest, ShouldNotLogSubmitWithoutSelectingSuggestionsIfSuggestionFilled) { - EnableWalletSync(); // Create a local card for testing, card number is 4111111111111111. RecreateCreditCards(true /* include_local_credit_card */, false /* include_masked_server_credit_card */, @@ -3729,7 +3691,6 @@ TEST_F(AutofillMetricsTest, } TEST_F(AutofillMetricsTest, ShouldNotLogFormEventNoCardForAddressForm) { - EnableWalletSync(); // Create a profile. RecreateProfile(); // Set up our form data. @@ -3769,7 +3730,6 @@ TEST_F(AutofillMetricsTest, ShouldNotLogFormEventNoCardForAddressForm) { // Test that we log submitted form events for credit cards. TEST_F(AutofillMetricsTest, CreditCardSubmittedFormEvents) { - EnableWalletSync(); // Creating all kinds of cards. RecreateCreditCards(true /* include_local_credit_card */, true /* include_masked_server_credit_card */, @@ -4115,7 +4075,6 @@ TEST_F(AutofillMetricsTest, CreditCardSubmittedFormEvents) { // Test that we log "will submit" and "submitted" form events for credit // cards. TEST_F(AutofillMetricsTest, CreditCardWillSubmitFormEvents) { - EnableWalletSync(); // Creating all kinds of cards. RecreateCreditCards(true /* include_local_credit_card */, true /* include_masked_server_credit_card */, @@ -4392,7 +4351,6 @@ TEST_F(AutofillMetricsTest, AddressInteractedFormEvents) { // Test that we log suggestion shown form events for address. TEST_F(AutofillMetricsTest, AddressShownFormEvents) { - EnableWalletSync(); // Create a profile. RecreateProfile(); // Set up our form data. @@ -4483,7 +4441,6 @@ TEST_F(AutofillMetricsTest, AddressShownFormEvents) { // Test that we log filled form events for address. TEST_F(AutofillMetricsTest, AddressFilledFormEvents) { - EnableWalletSync(); // Create a profile. RecreateProfile(); // Set up our form data. @@ -4550,7 +4507,6 @@ TEST_F(AutofillMetricsTest, AddressFilledFormEvents) { // Test that we log submitted form events for address. TEST_F(AutofillMetricsTest, AddressSubmittedFormEvents) { - EnableWalletSync(); // Create a profile. RecreateProfile(); // Set up our form data. @@ -4750,7 +4706,6 @@ TEST_F(AutofillMetricsTest, AddressSubmittedFormEvents) { // Test that we log "will submit" and "submitted" form events for address. TEST_F(AutofillMetricsTest, AddressWillSubmitFormEvents) { - EnableWalletSync(); // Create a profile. RecreateProfile(); // Set up our form data. @@ -4924,8 +4879,6 @@ TEST_F(AutofillMetricsTest, AddressWillSubmitFormEvents) { // Test that we log interacted form event for credit cards only once. TEST_F(AutofillMetricsTest, CreditCardFormEventsAreSegmented) { - EnableWalletSync(); - // Set up our form data. FormData form; form.name = ASCIIToUTF16("TestForm"); @@ -5029,8 +4982,6 @@ TEST_F(AutofillMetricsTest, CreditCardFormEventsAreSegmented) { // Test that we log interacted form event for address only once. TEST_F(AutofillMetricsTest, AddressFormEventsAreSegmented) { - EnableWalletSync(); - // Set up our form data. FormData form; form.name = ASCIIToUTF16("TestForm"); diff --git a/chromium/components/autofill/core/browser/autofill_save_card_infobar_delegate_mobile.cc b/chromium/components/autofill/core/browser/autofill_save_card_infobar_delegate_mobile.cc index bc4d854bcdb..becc1289c2b 100644 --- a/chromium/components/autofill/core/browser/autofill_save_card_infobar_delegate_mobile.cc +++ b/chromium/components/autofill/core/browser/autofill_save_card_infobar_delegate_mobile.cc @@ -11,6 +11,7 @@ #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/legal_message_line.h" #include "components/autofill/core/common/autofill_constants.h" +#include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/autofill_pref_names.h" #include "components/grit/components_scaled_resources.h" #include "components/infobars/core/infobar.h" @@ -53,6 +54,10 @@ AutofillSaveCardInfoBarDelegateMobile::AutofillSaveCardInfoBarDelegateMobile( return; } } + if (IsGooglePayBrandingEnabled()) { + card_label_ = card.NetworkForDisplay() + base::string16(kMidlineEllipsis) + + card.LastFourDigits(); + } AutofillMetrics::LogCreditCardInfoBarMetric( AutofillMetrics::INFOBAR_SHOWN, upload_, @@ -77,23 +82,40 @@ bool AutofillSaveCardInfoBarDelegateMobile::LegalMessagesParsedSuccessfully() { return !upload_ || !legal_messages_.empty(); } +bool AutofillSaveCardInfoBarDelegateMobile::IsGooglePayBrandingEnabled() const { + return upload_ && + base::FeatureList::IsEnabled( + features::kAutofillUpstreamUseGooglePayOnAndroidBranding); +} + +base::string16 AutofillSaveCardInfoBarDelegateMobile::GetTitleText() const { + return l10n_util::GetStringUTF16( + IDS_AUTOFILL_SAVE_CARD_PROMPT_TITLE_TO_CLOUD_V3); +} + +base::string16 AutofillSaveCardInfoBarDelegateMobile::GetDescriptionText() + const { + return l10n_util::GetStringUTF16( + IDS_AUTOFILL_SAVE_CARD_PROMPT_UPLOAD_EXPLANATION_V2); +} + int AutofillSaveCardInfoBarDelegateMobile::GetIconId() const { - return IDR_INFOBAR_AUTOFILL_CC; + return IsGooglePayBrandingEnabled() ? 0 : IDR_INFOBAR_AUTOFILL_CC; } base::string16 AutofillSaveCardInfoBarDelegateMobile::GetMessageText() const { + if (IsGooglePayBrandingEnabled()) { + return base::string16(); + } return l10n_util::GetStringUTF16( upload_ ? IDS_AUTOFILL_SAVE_CARD_PROMPT_TITLE_TO_CLOUD : IDS_AUTOFILL_SAVE_CARD_PROMPT_TITLE_LOCAL); } base::string16 AutofillSaveCardInfoBarDelegateMobile::GetLinkText() const { - return l10n_util::GetStringUTF16(IDS_LEARN_MORE); -} - -infobars::InfoBarDelegate::Type -AutofillSaveCardInfoBarDelegateMobile::GetInfoBarType() const { - return PAGE_ACTION_TYPE; + return IsGooglePayBrandingEnabled() + ? base::string16() + : l10n_util::GetStringUTF16(IDS_LEARN_MORE); } infobars::InfoBarDelegate::InfoBarIdentifier @@ -133,7 +155,7 @@ bool AutofillSaveCardInfoBarDelegateMobile::Cancel() { } GURL AutofillSaveCardInfoBarDelegateMobile::GetLinkURL() const { - return GURL(kHelpURL); + return IsGooglePayBrandingEnabled() ? GURL() : GURL(kHelpURL); } void AutofillSaveCardInfoBarDelegateMobile::LogUserAction( diff --git a/chromium/components/autofill/core/browser/autofill_save_card_infobar_delegate_mobile.h b/chromium/components/autofill/core/browser/autofill_save_card_infobar_delegate_mobile.h index 8b933018107..0d4d63c0039 100644 --- a/chromium/components/autofill/core/browser/autofill_save_card_infobar_delegate_mobile.h +++ b/chromium/components/autofill/core/browser/autofill_save_card_infobar_delegate_mobile.h @@ -49,11 +49,18 @@ class AutofillSaveCardInfoBarDelegateMobile : public ConfirmInfoBarDelegate { // Legal messages are only specified for the upload case, not for local save. bool LegalMessagesParsedSuccessfully(); + // Google Pay branding is enabled with a flag and only for cards upstreamed + // to Google. + bool IsGooglePayBrandingEnabled() const; + + // All following changes are with respect to Google Pay branding. + base::string16 GetTitleText() const; + base::string16 GetDescriptionText() const; + // ConfirmInfoBarDelegate: int GetIconId() const override; base::string16 GetMessageText() const override; base::string16 GetLinkText() const override; - Type GetInfoBarType() const override; infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; bool ShouldExpire(const NavigationDetails& details) const override; void InfoBarDismissed() override; diff --git a/chromium/components/autofill/core/browser/autofill_scanner.h b/chromium/components/autofill/core/browser/autofill_scanner.h index 88b84e6fd94..0babe38a2fd 100644 --- a/chromium/components/autofill/core/browser/autofill_scanner.h +++ b/chromium/components/autofill/core/browser/autofill_scanner.h @@ -45,6 +45,9 @@ class AutofillScanner { // |RewindTo()|. size_t SaveCursor(); + // This is only for logging purposes. + size_t CursorIndex() { return static_cast<size_t>(cursor_ - begin_); }; + private: void Init(const std::vector<AutofillField*>& fields); diff --git a/chromium/components/autofill/core/browser/autofill_test_utils.cc b/chromium/components/autofill/core/browser/autofill_test_utils.cc index 091a4fcfdf3..6ed36affa53 100644 --- a/chromium/components/autofill/core/browser/autofill_test_utils.cc +++ b/chromium/components/autofill/core/browser/autofill_test_utils.cc @@ -26,9 +26,6 @@ #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/prefs/testing_pref_store.h" -#include "components/signin/core/browser/account_fetcher_service.h" -#include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/signin_pref_names.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/rect.h" @@ -60,26 +57,6 @@ std::unique_ptr<PrefService> PrefServiceForTesting( user_prefs::PrefRegistrySyncable* registry) { AutofillManager::RegisterProfilePrefs(registry); - // PDM depends on these prefs, which are normally registered in - // SigninManagerFactory. - registry->RegisterStringPref(::prefs::kGoogleServicesAccountId, - std::string()); - registry->RegisterStringPref(::prefs::kGoogleServicesLastAccountId, - std::string()); - registry->RegisterStringPref(::prefs::kGoogleServicesLastUsername, - std::string()); - registry->RegisterStringPref(::prefs::kGoogleServicesUserAccountId, - std::string()); - registry->RegisterStringPref(::prefs::kGoogleServicesUsername, - std::string()); - - // PDM depends on these prefs, which are normally registered in - // AccountTrackerServiceFactory. - registry->RegisterListPref(AccountTrackerService::kAccountInfoPref); - registry->RegisterIntegerPref(::prefs::kAccountIdMigrationState, - AccountTrackerService::MIGRATION_NOT_STARTED); - registry->RegisterInt64Pref(AccountFetcherService::kLastUpdatePref, 0); - PrefServiceFactory factory; factory.set_user_prefs(base::MakeRefCounted<TestingPrefStore>()); return factory.Create(registry); diff --git a/chromium/components/autofill/core/browser/autofill_wallet_data_type_controller_unittest.cc b/chromium/components/autofill/core/browser/autofill_wallet_data_type_controller_unittest.cc index 9610d5dd02b..49eddabe2f2 100644 --- a/chromium/components/autofill/core/browser/autofill_wallet_data_type_controller_unittest.cc +++ b/chromium/components/autofill/core/browser/autofill_wallet_data_type_controller_unittest.cc @@ -94,7 +94,7 @@ class AutofillWalletDataTypeControllerTest : public testing::Test, base::ThreadTaskRunnerHandle::Get()); autofill_wallet_dtc_ = std::make_unique<AutofillWalletDataTypeController>( syncer::AUTOFILL_WALLET_DATA, base::ThreadTaskRunnerHandle::Get(), - base::Bind(&base::DoNothing), this, web_data_service_); + base::DoNothing(), this, web_data_service_); last_type_ = syncer::UNSPECIFIED; last_error_ = syncer::SyncError(); diff --git a/chromium/components/autofill/core/browser/credit_card.cc b/chromium/components/autofill/core/browser/credit_card.cc index 87d845e341f..4788afc8cfc 100644 --- a/chromium/components/autofill/core/browser/credit_card.cc +++ b/chromium/components/autofill/core/browser/credit_card.cc @@ -624,8 +624,15 @@ bool CreditCard::IsEmpty(const std::string& app_locale) const { } bool CreditCard::IsValid() const { - return IsValidCreditCardNumber(number_) && - IsValidCreditCardExpirationDate(expiration_year_, expiration_month_, + return HasValidCardNumber() && HasValidExpirationDate(); +} + +bool CreditCard::HasValidCardNumber() const { + return IsValidCreditCardNumber(number_); +} + +bool CreditCard::HasValidExpirationDate() const { + return IsValidCreditCardExpirationDate(expiration_year_, expiration_month_, AutofillClock::Now()); } diff --git a/chromium/components/autofill/core/browser/credit_card.h b/chromium/components/autofill/core/browser/credit_card.h index 40ce0b39a3e..1894581ebd2 100644 --- a/chromium/components/autofill/core/browser/credit_card.h +++ b/chromium/components/autofill/core/browser/credit_card.h @@ -164,9 +164,15 @@ class CreditCard : public AutofillDataModel { // Returns true if there are no values (field types) set. bool IsEmpty(const std::string& app_locale) const; - // Returns true if all field types have valid values set and the card is not - // expired. MASKED_SERVER_CARDs will never be valid because the number is + // Returns true if credit card number is valid. + // MASKED_SERVER_CARDs will never be valid because the number is // not complete. + bool HasValidCardNumber() const; + + // Returns true if credit card has valid expiration date. + bool HasValidExpirationDate() const; + + // Returns true if IsValidCardNumber && IsValidExpirationDate. bool IsValid() const; // Returns the card number. diff --git a/chromium/components/autofill/core/browser/credit_card_field.cc b/chromium/components/autofill/core/browser/credit_card_field.cc index 3343e584b9b..a0c484b8dd9 100644 --- a/chromium/components/autofill/core/browser/credit_card_field.cc +++ b/chromium/components/autofill/core/browser/credit_card_field.cc @@ -88,6 +88,7 @@ std::unique_ptr<FormField> CreditCardField::Parse(AutofillScanner* scanner) { // Using 'new' to access private constructor. auto credit_card_field = base::WrapUnique(new CreditCardField()); size_t saved_cursor = scanner->SaveCursor(); + int nb_unknown_fields = 0; // Credit card fields can appear in many different orders. // We loop until no more credit card related fields are found, see |break| at @@ -134,6 +135,7 @@ std::unique_ptr<FormField> CreditCardField::Parse(AutofillScanner* scanner) { if (!credit_card_field->type_ && LikelyCardTypeSelectField(scanner)) { credit_card_field->type_ = scanner->Cursor(); scanner->Advance(); + nb_unknown_fields = 0; continue; } @@ -176,6 +178,7 @@ std::unique_ptr<FormField> CreditCardField::Parse(AutofillScanner* scanner) { credit_card_field->verification_ = nullptr; } } else { + nb_unknown_fields = 0; continue; } } @@ -204,11 +207,14 @@ std::unique_ptr<FormField> CreditCardField::Parse(AutofillScanner* scanner) { current_number_field->set_credit_card_number_offset(start_index); credit_card_field->numbers_.push_back(current_number_field); + nb_unknown_fields = 0; continue; } - if (credit_card_field->ParseExpirationDate(scanner)) + if (credit_card_field->ParseExpirationDate(scanner)) { + nb_unknown_fields = 0; continue; + } if (credit_card_field->expiration_month_ && !credit_card_field->expiration_year_ && @@ -218,6 +224,24 @@ std::unique_ptr<FormField> CreditCardField::Parse(AutofillScanner* scanner) { return nullptr; } + nb_unknown_fields++; + + // Since cc#/verification and expiration are inter-dependent for the final + // detection decision, we allow for 4 UNKONWN fields in between. + // We can't allow for a lot of unknown fields, because the name on address + // sections may sometimes be mistakenly detected as cardholder name. + if ((credit_card_field->verification_ || + !credit_card_field->numbers_.empty() || + credit_card_field->HasExpiration()) && + (!credit_card_field->verification_ || + credit_card_field->numbers_.empty() || + !credit_card_field->HasExpiration()) && + nb_unknown_fields < 4) { + scanner->Advance(); + fields--; // We continue searching in the same credit card section, but + // no more field is identified. + continue; + } break; } diff --git a/chromium/components/autofill/core/browser/credit_card_save_manager.cc b/chromium/components/autofill/core/browser/credit_card_save_manager.cc index 0ddd6ce1106..e3935b3c4be 100644 --- a/chromium/components/autofill/core/browser/credit_card_save_manager.cc +++ b/chromium/components/autofill/core/browser/credit_card_save_manager.cc @@ -37,7 +37,7 @@ #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_util.h" #include "components/prefs/pref_service.h" -#include "google_apis/gaia/identity_provider.h" +#include "services/identity/public/cpp/identity_manager.h" #include "url/gurl.h" namespace autofill { @@ -209,7 +209,7 @@ bool CreditCardSaveManager::IsCreditCardUploadEnabled() { return observer_for_testing_ || ::autofill::IsCreditCardUploadEnabled( client_->GetPrefs(), client_->GetSyncService(), - client_->GetIdentityProvider()->GetActiveUsername()); + client_->GetIdentityManager()->GetPrimaryAccountInfo().email); } void CreditCardSaveManager::OnDidUploadCard( diff --git a/chromium/components/autofill/core/browser/credit_card_save_manager_unittest.cc b/chromium/components/autofill/core/browser/credit_card_save_manager_unittest.cc index dfa40607188..ac381155f07 100644 --- a/chromium/components/autofill/core/browser/credit_card_save_manager_unittest.cc +++ b/chromium/components/autofill/core/browser/credit_card_save_manager_unittest.cc @@ -99,7 +99,7 @@ class CreditCardSaveManagerTest : public testing::Test { autofill_driver_->SetURLRequestContext(request_context_.get()); payments_client_ = new payments::TestPaymentsClient( autofill_driver_->GetURLRequestContext(), autofill_client_.GetPrefs(), - autofill_client_.GetIdentityProvider(), + autofill_client_.GetIdentityManager(), /*unmask_delegate=*/nullptr, // Will be set by CreditCardSaveManager's ctor /*save_delegate=*/nullptr); @@ -128,11 +128,6 @@ class CreditCardSaveManagerTest : public testing::Test { request_context_ = nullptr; } - void EnableAutofillOfferLocalSaveIfServerCardManuallyEnteredExperiment() { - scoped_feature_list_.InitAndEnableFeature( - kAutofillOfferLocalSaveIfServerCardManuallyEntered); - } - void EnableAutofillUpstreamRequestCvcIfMissingExperiment() { scoped_feature_list_.InitAndEnableFeature( kAutofillUpstreamRequestCvcIfMissing); @@ -1848,48 +1843,7 @@ TEST_F(CreditCardSaveManagerTest, UploadCreditCard_UploadDetailsFails) { AutofillMetrics::UPLOAD_NOT_OFFERED_GET_UPLOAD_DETAILS_FAILED); } -TEST_F(CreditCardSaveManagerTest, DuplicateMaskedCreditCard) { - EnableAutofillOfferLocalSaveIfServerCardManuallyEnteredExperiment(); - - personal_data_.ClearProfiles(); - credit_card_save_manager_->SetCreditCardUploadEnabled(true); - credit_card_save_manager_->SetAppLocale("en-US"); - - // Create, fill and submit an address form in order to establish a recent - // profile which can be selected for the upload request. - FormData address_form; - test::CreateTestAddressFormData(&address_form); - FormsSeen(std::vector<FormData>(1, address_form)); - ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form); - FormSubmitted(address_form); - - // Add a masked credit card whose |TypeAndLastFourDigits| matches what we will - // enter below. - CreditCard credit_card(CreditCard::MASKED_SERVER_CARD, "a123"); - test::SetCreditCardInfo(&credit_card, "Flo Master", "1111", "11", - NextYear().c_str(), "1"); - credit_card.SetNetworkForMaskedCard(kVisaCard); - personal_data_.AddServerCreditCard(credit_card); - - // Set up our credit card form data. - FormData credit_card_form; - CreateTestCreditCardFormData(&credit_card_form, true, false); - FormsSeen(std::vector<FormData>(1, credit_card_form)); - - // Edit the data, and submit. - credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master"); - credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111"); - credit_card_form.fields[2].value = ASCIIToUTF16("11"); - credit_card_form.fields[3].value = ASCIIToUTF16(NextYear()); - credit_card_form.fields[4].value = ASCIIToUTF16("123"); - - // The local save prompt should be shown. - EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)); - FormSubmitted(credit_card_form); - EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded()); -} - -TEST_F(CreditCardSaveManagerTest, DuplicateMaskedCreditCard_ExperimentOff) { +TEST_F(CreditCardSaveManagerTest, DuplicateMaskedCreditCard_NoUpload) { personal_data_.ClearProfiles(); credit_card_save_manager_->SetCreditCardUploadEnabled(true); credit_card_save_manager_->SetAppLocale("en-US"); @@ -1922,7 +1876,8 @@ TEST_F(CreditCardSaveManagerTest, DuplicateMaskedCreditCard_ExperimentOff) { credit_card_form.fields[3].value = ASCIIToUTF16(NextYear()); credit_card_form.fields[4].value = ASCIIToUTF16("123"); - // The local save prompt should not be shown because the experiment is off. + // Local save prompt should not be shown as there is alredy masked + // card with same |TypeAndLastFourDigits|. EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0); FormSubmitted(credit_card_form); EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded()); diff --git a/chromium/components/autofill/core/browser/credit_card_unittest.cc b/chromium/components/autofill/core/browser/credit_card_unittest.cc index b110302b1aa..99b28bf0e34 100644 --- a/chromium/components/autofill/core/browser/credit_card_unittest.cc +++ b/chromium/components/autofill/core/browser/credit_card_unittest.cc @@ -631,7 +631,7 @@ TEST(CreditCardTest, UpdateFromImportedCard) { EXPECT_EQ(original_card, a); } -TEST(CreditCardTest, IsValid) { +TEST(CreditCardTest, IsValidCardNumberAndExpiryDate) { CreditCard card; // Invalid because expired const base::Time now(base::Time::Now()); @@ -643,6 +643,8 @@ TEST(CreditCardTest, IsValid) { base::IntToString16(now_exploded.year - 1)); card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("4111111111111111")); EXPECT_FALSE(card.IsValid()); + EXPECT_FALSE(card.HasValidExpirationDate()); + EXPECT_TRUE(card.HasValidCardNumber()); // Invalid because card number is not complete card.SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("12")); @@ -654,11 +656,15 @@ TEST(CreditCardTest, IsValid) { SCOPED_TRACE(valid_number); card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16(valid_number)); EXPECT_TRUE(card.IsValid()); + EXPECT_TRUE(card.HasValidCardNumber()); + EXPECT_TRUE(card.HasValidExpirationDate()); } for (const char* invalid_number : kInvalidNumbers) { SCOPED_TRACE(invalid_number); card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16(invalid_number)); EXPECT_FALSE(card.IsValid()); + EXPECT_TRUE(card.HasValidExpirationDate()); + EXPECT_FALSE(card.HasValidCardNumber()); } } diff --git a/chromium/components/autofill/core/browser/form_data_importer.cc b/chromium/components/autofill/core/browser/form_data_importer.cc index 4a3f19fe7dc..5195eb23352 100644 --- a/chromium/components/autofill/core/browser/form_data_importer.cc +++ b/chromium/components/autofill/core/browser/form_data_importer.cc @@ -109,23 +109,17 @@ FormDataImporter::~FormDataImporter() {} void FormDataImporter::ImportFormData(const FormStructure& submitted_form, bool credit_card_autofill_enabled) { std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; if (!ImportFormData(submitted_form, credit_card_autofill_enabled, credit_card_save_manager_->IsCreditCardUploadEnabled(), - &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)) + &imported_credit_card)) return; // No card available to offer save or upload. if (!imported_credit_card) return; - if (!credit_card_save_manager_->IsCreditCardUploadEnabled() || - imported_credit_card_matches_masked_server_credit_card) { - // Offer local save. This block will only be reached if we have observed a - // new card or a card whose |TypeAndLastFourDigits| matches a masked server - // card. |ImportFormData| will return false if the card matches a full card - // that we have already stored. + if (!credit_card_save_manager_->IsCreditCardUploadEnabled()) { + // Offer local save. credit_card_save_manager_->OfferCardLocalSave(*imported_credit_card); } else { // Attempt to offer upload save. Because we pass IsCreditCardUploadEnabled() @@ -170,18 +164,15 @@ bool FormDataImporter::ImportFormData( const FormStructure& submitted_form, bool credit_card_autofill_enabled, bool should_return_local_card, - std::unique_ptr<CreditCard>* imported_credit_card, - bool* imported_credit_card_matches_masked_server_credit_card) { + std::unique_ptr<CreditCard>* imported_credit_card) { // We try the same |form| for both credit card and address import/update. // - ImportCreditCard may update an existing card, or fill // |imported_credit_card| with an extracted card. See .h for details of - // |should_return_local_card| and - // |imported_credit_card_matches_masked_server_credit_card|. + // |should_return_local_card|. bool cc_import = false; if (credit_card_autofill_enabled) { - cc_import = ImportCreditCard( - submitted_form, should_return_local_card, imported_credit_card, - imported_credit_card_matches_masked_server_credit_card); + cc_import = ImportCreditCard(submitted_form, should_return_local_card, + imported_credit_card); } // - ImportAddressProfiles may eventually save or update one or more address // profiles. @@ -307,10 +298,8 @@ bool FormDataImporter::ImportAddressProfileForSection( bool FormDataImporter::ImportCreditCard( const FormStructure& form, bool should_return_local_card, - std::unique_ptr<CreditCard>* imported_credit_card, - bool* imported_credit_card_matches_masked_server_credit_card) { + std::unique_ptr<CreditCard>* imported_credit_card) { DCHECK(!imported_credit_card->get()); - *imported_credit_card_matches_masked_server_credit_card = false; // The candidate for credit card import. There are many ways for the candidate // to be rejected (see everywhere this function returns false, below). @@ -323,10 +312,20 @@ bool FormDataImporter::ImportCreditCard( if (has_duplicate_field_type) return false; - // Reject the credit card if we did not detect enough filled credit card - // fields (such as valid number, month, year). - if (!candidate_credit_card.IsValid()) + if (!candidate_credit_card.IsValid()) { + if (candidate_credit_card.HasValidCardNumber()) { + AutofillMetrics::LogSubmittedCardStateMetric( + AutofillMetrics::HAS_CARD_NUMBER_ONLY); + } + if (candidate_credit_card.HasValidExpirationDate()) { + AutofillMetrics::LogSubmittedCardStateMetric( + AutofillMetrics::HAS_EXPIRATION_DATE_ONLY); + } + return false; + } + AutofillMetrics::LogSubmittedCardStateMetric( + AutofillMetrics::HAS_CARD_NUMBER_AND_EXPIRATION_DATE); // Attempt to merge with an existing credit card. Don't present a prompt if we // have already saved this card number, unless |should_return_local_card| is @@ -349,7 +348,7 @@ bool FormDataImporter::ImportCreditCard( } } - // Also don't offer to save if we already have this stored as a full server + // Also don't offer to save if we already have this stored as a server // card. We only check the number because if the new card has the same number // as the server card, upload is guaranteed to fail. There's no mechanism for // entries with the same number but different names or expiration dates as @@ -373,19 +372,7 @@ bool FormDataImporter::ImportCreditCard( : AutofillMetrics:: MASKED_SERVER_CARD_EXPIRATION_DATE_DID_NOT_MATCH); } - - // We can offer to save locally even if we already have this stored as - // another masked server card with the same |TypeAndLastFourDigits| as - // long as the AutofillOfferLocalSaveIfServerCardManuallyEntered flag is - // enabled. This will allow the user to fill the full card number in the - // future without having to unmask the card. - if (card->record_type() == CreditCard::FULL_SERVER_CARD || - !IsAutofillOfferLocalSaveIfServerCardManuallyEnteredExperimentEnabled()) { - return false; - } - DCHECK_EQ(card->record_type(), CreditCard::MASKED_SERVER_CARD); - *imported_credit_card_matches_masked_server_credit_card = true; - break; + return false; } } diff --git a/chromium/components/autofill/core/browser/form_data_importer.h b/chromium/components/autofill/core/browser/form_data_importer.h index d3c07d5c817..861b2fb5d43 100644 --- a/chromium/components/autofill/core/browser/form_data_importer.h +++ b/chromium/components/autofill/core/browser/form_data_importer.h @@ -63,17 +63,12 @@ class FormDataImporter { // data. If the form contains credit card data already present in a local // credit card entry *and* |should_return_local_card| is true, the data is // stored into |imported_credit_card| so that we can prompt the user whether - // to upload it. |imported_credit_card_matches_masked_server_credit_card| is - // set to |true| if the |TypeAndLastFourDigits| in |imported_credit_card| - // matches the |TypeAndLastFourDigits| in a saved masked server card. Returns - // |true| if sufficient address or credit card data was found. - // Exposed for testing. - bool ImportFormData( - const FormStructure& form, - bool credit_card_autofill_enabled, - bool should_return_local_card, - std::unique_ptr<CreditCard>* imported_credit_card, - bool* imported_credit_card_matches_masked_server_credit_card); + // to upload it. Returns |true| if sufficient address or credit card data + // was found. Exposed for testing. + bool ImportFormData(const FormStructure& form, + bool credit_card_autofill_enabled, + bool should_return_local_card, + std::unique_ptr<CreditCard>* imported_credit_card); // Go through the |form| fields and attempt to extract and import valid // address profiles. Returns true on extraction success of at least one @@ -89,16 +84,11 @@ class FormDataImporter { // Go through the |form| fields and attempt to extract a new credit card in // |imported_credit_card|, or update an existing card. // |should_return_local_card| will indicate whether |imported_credit_card| is - // filled even if an existing card was updated. - // |imported_credit_card_matches_masked_server_credit_card| will indicate - // whether |imported_credit_card| is filled even if an existing masked server - // card as the same |TypeAndLastFourDigits|. Success is defined as having a - // new card to import, or having merged with an existing card. - bool ImportCreditCard( - const FormStructure& form, - bool should_return_local_card, - std::unique_ptr<CreditCard>* imported_credit_card, - bool* imported_credit_card_matches_masked_server_credit_card); + // filled even if an existing card was updated. Success is defined as having + // a new card to import, or having merged with an existing card. + bool ImportCreditCard(const FormStructure& form, + bool should_return_local_card, + std::unique_ptr<CreditCard>* imported_credit_card); // Extracts credit card from the form structure. |hasDuplicateFieldType| will // be set as true if there are duplicated field types in the form. diff --git a/chromium/components/autofill/core/browser/form_data_importer_unittest.cc b/chromium/components/autofill/core/browser/form_data_importer_unittest.cc index 209c12f4ad9..f648321448f 100644 --- a/chromium/components/autofill/core/browser/form_data_importer_unittest.cc +++ b/chromium/components/autofill/core/browser/form_data_importer_unittest.cc @@ -43,9 +43,6 @@ #include "components/autofill/core/common/form_field_data.h" #include "components/os_crypt/os_crypt_mocker.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/fake_signin_manager.h" -#include "components/signin/core/browser/test_signin_client.h" #include "components/webdata/common/web_data_service_base.h" #include "components/webdata/common/web_database_service.h" #include "testing/gmock/include/gmock/gmock.h" @@ -120,8 +117,7 @@ class FormDataImporterTestBase { personal_data_manager_.reset(new PersonalDataManager("en")); personal_data_manager_->Init( scoped_refptr<AutofillWebDataService>(autofill_database_service_), - prefs_.get(), account_tracker_.get(), signin_manager_.get(), - is_incognito); + prefs_.get(), nullptr, is_incognito); personal_data_manager_->AddObserver(&personal_data_observer_); personal_data_manager_->OnSyncServiceInitialized(nullptr); @@ -132,8 +128,6 @@ class FormDataImporterTestBase { } void EnableWalletCardImport() { - signin_manager_->SetAuthenticatedAccountInfo("12345", - "syncuser@example.com"); base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableOfferStoreUnmaskedWalletCards); } @@ -175,14 +169,11 @@ class FormDataImporterTestBase { return form_data_importer_->ImportAddressProfiles(form); } - bool ImportCreditCard( - const FormStructure& form, - bool should_return_local_card, - std::unique_ptr<CreditCard>* imported_credit_card, - bool* imported_credit_card_matches_masked_server_credit_card) { - return form_data_importer_->ImportCreditCard( - form, should_return_local_card, imported_credit_card, - imported_credit_card_matches_masked_server_credit_card); + bool ImportCreditCard(const FormStructure& form, + bool should_return_local_card, + std::unique_ptr<CreditCard>* imported_credit_card) { + return form_data_importer_->ImportCreditCard(form, should_return_local_card, + imported_credit_card); } void SubmitFormAndExpectImportedCardWithData(const FormData& form, @@ -193,12 +184,8 @@ class FormDataImporterTestBase { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(ImportCreditCard( - form_structure, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure, false, &imported_credit_card)); ASSERT_TRUE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_manager_->SaveImportedCreditCard(*imported_credit_card); base::RunLoop run_loop; @@ -227,9 +214,6 @@ class FormDataImporterTestBase { base::ScopedTempDir temp_dir_; base::MessageLoopForUI message_loop_; std::unique_ptr<PrefService> prefs_; - std::unique_ptr<AccountTrackerService> account_tracker_; - std::unique_ptr<FakeSigninManagerBase> signin_manager_; - std::unique_ptr<TestSigninClient> signin_client_; scoped_refptr<AutofillWebDataService> autofill_database_service_; scoped_refptr<WebDatabaseService> web_database_; AutofillTable* autofill_table_; // weak ref @@ -249,14 +233,6 @@ class FormDataImporterTest : public FormDataImporterTestBase, new WebDatabaseService(path, base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get()); - // Set up account tracker. - signin_client_.reset(new TestSigninClient(prefs_.get())); - account_tracker_.reset(new AccountTrackerService()); - account_tracker_->Initialize(signin_client_.get()); - signin_manager_.reset(new FakeSigninManagerBase(signin_client_.get(), - account_tracker_.get())); - signin_manager_->Initialize(prefs_.get()); - // Hacky: hold onto a pointer but pass ownership. autofill_table_ = new AutofillTable; web_database_->AddTable(std::unique_ptr<WebDatabaseTable>(autofill_table_)); @@ -285,13 +261,6 @@ class FormDataImporterTest : public FormDataImporterTestBase, void TearDown() override { // Order of destruction is important as AutofillManager relies on // PersonalDataManager to be around when it gets destroyed. - signin_manager_->Shutdown(); - signin_manager_.reset(); - - account_tracker_->Shutdown(); - account_tracker_.reset(); - signin_client_.reset(); - test::ReenableSystemServices(); OSCryptMocker::TearDown(); } @@ -1393,12 +1362,12 @@ TEST_F(FormDataImporterTest, ImportCreditCard_Valid) { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(ImportCreditCard( - form_structure, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + base::HistogramTester histogram_tester; + EXPECT_TRUE(ImportCreditCard(form_structure, false, &imported_credit_card)); ASSERT_TRUE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); + histogram_tester.ExpectUniqueSample( + "Autofill.SubmittedCardState", + AutofillMetrics::HAS_CARD_NUMBER_AND_EXPIRATION_DATE, 1); personal_data_manager_->SaveImportedCreditCard(*imported_credit_card); WaitForOnPersonalDataChanged(); @@ -1412,8 +1381,8 @@ TEST_F(FormDataImporterTest, ImportCreditCard_Valid) { EXPECT_EQ(0, expected.Compare(*results[0])); } -// Tests that an invalid credit card is not extracted. -TEST_F(FormDataImporterTest, ImportCreditCard_Invalid) { +// Tests that an invalid credit card number is not extracted. +TEST_F(FormDataImporterTest, ImportCreditCard_InvalidCardNumber) { FormData form; AddFullCreditCardForm(&form, "Jim Johansen", "1000000000000000", "02", "2999"); @@ -1421,11 +1390,34 @@ TEST_F(FormDataImporterTest, ImportCreditCard_Invalid) { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_FALSE(ImportCreditCard( - form_structure, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + base::HistogramTester histogram_tester; + EXPECT_FALSE(ImportCreditCard(form_structure, false, &imported_credit_card)); + ASSERT_FALSE(imported_credit_card); + histogram_tester.ExpectUniqueSample("Autofill.SubmittedCardState", + AutofillMetrics::HAS_EXPIRATION_DATE_ONLY, + 1); + + // Since no refresh is expected, reload the data from the database to make + // sure no changes were written out. + ResetPersonalDataManager(USER_MODE_NORMAL); + + ASSERT_EQ(0U, personal_data_manager_->GetCreditCards().size()); +} + +// Tests that an invalid credit card expiration is not extracted. +TEST_F(FormDataImporterTest, ImportCreditCard_InvalidExpiryDate) { + FormData form; + AddFullCreditCardForm(&form, "Smalls Biggie", "4111-1111-1111-1111", "0", + "2999"); + + FormStructure form_structure(form); + form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); + std::unique_ptr<CreditCard> imported_credit_card; + base::HistogramTester histogram_tester; + EXPECT_FALSE(ImportCreditCard(form_structure, false, &imported_credit_card)); ASSERT_FALSE(imported_credit_card); + histogram_tester.ExpectUniqueSample("Autofill.SubmittedCardState", + AutofillMetrics::HAS_CARD_NUMBER_ONLY, 1); // Since no refresh is expected, reload the data from the database to make // sure no changes were written out. @@ -1457,12 +1449,12 @@ TEST_F(FormDataImporterTest, ImportCreditCard_MonthSelectInvalidText) { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(ImportCreditCard( - form_structure, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + base::HistogramTester histogram_tester; + EXPECT_TRUE(ImportCreditCard(form_structure, false, &imported_credit_card)); ASSERT_TRUE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); + histogram_tester.ExpectUniqueSample( + "Autofill.SubmittedCardState", + AutofillMetrics::HAS_CARD_NUMBER_AND_EXPIRATION_DATE, 1); personal_data_manager_->SaveImportedCreditCard(*imported_credit_card); WaitForOnPersonalDataChanged(); @@ -1486,12 +1478,8 @@ TEST_F(FormDataImporterTest, ImportCreditCard_TwoValidCards) { FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(ImportCreditCard( - form_structure1, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure1, false, &imported_credit_card)); ASSERT_TRUE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_manager_->SaveImportedCreditCard(*imported_credit_card); WaitForOnPersonalDataChanged(); @@ -1511,11 +1499,8 @@ TEST_F(FormDataImporterTest, ImportCreditCard_TwoValidCards) { FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card2; - EXPECT_TRUE(ImportCreditCard( - form_structure2, false, &imported_credit_card2, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure2, false, &imported_credit_card2)); ASSERT_TRUE(imported_credit_card2); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_manager_->SaveImportedCreditCard(*imported_credit_card2); WaitForOnPersonalDataChanged(); @@ -1606,15 +1591,9 @@ TEST_F(FormDataImporterTest, ImportCreditCard_2DigitYear) { } // Tests that a credit card is not extracted because the -// kAutofillOfferLocalSaveIfServerCardManuallyEntered feature flag is off even -// though the card matches a masked server card. +// card matches a masked server card. TEST_F(FormDataImporterTest, - ImportCreditCard_DuplicateServerCards_MaskedCard_ExperimentOff) { - // Ensure feature flag is off. - base::test::ScopedFeatureList scoped_feature_list_; - scoped_feature_list_.InitAndDisableFeature( - kAutofillOfferLocalSaveIfServerCardManuallyEntered); - + ImportCreditCard_DuplicateServerCards_MaskedCard_DontExtract) { // Add a masked server card. std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); @@ -1638,57 +1617,10 @@ TEST_F(FormDataImporterTest, FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_FALSE(ImportCreditCard( - form_structure, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_FALSE(ImportCreditCard(form_structure, false, &imported_credit_card)); ASSERT_FALSE(imported_credit_card); } -// Tests that a credit card is extracted because it matches a masked server card -// and the kAutofillOfferLocalSaveIfServerCardManuallyEntered feature flag is -// enabled. -TEST_F(FormDataImporterTest, - ImportCreditCard_DuplicateServerCards_MaskedCard_ExperimentOn) { - // Enable feature flag. - base::test::ScopedFeatureList scoped_feature_list_; - scoped_feature_list_.InitAndEnableFeature( - kAutofillOfferLocalSaveIfServerCardManuallyEntered); - - // Add a masked server card. - std::vector<CreditCard> server_cards; - server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); - test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", - "1111" /* Visa */, "01", "2999", ""); - server_cards.back().SetNetworkForMaskedCard(kVisaCard); - test::SetServerCreditCards(autofill_table_, server_cards); - - // Make sure everything is set up correctly. - personal_data_manager_->Refresh(); - WaitForOnPersonalDataChanged(); - EXPECT_EQ(1U, personal_data_manager_->GetCreditCards().size()); - - // Type the same data as the masked card into a form. - FormData form; - AddFullCreditCardForm(&form, "John Dillinger", "4111111111111111", "01", - "2999"); - - // The card should be offered to be saved locally because it matches the - // masked server card. - FormStructure form_structure(form); - form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); - std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(ImportCreditCard( - form_structure, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); - ASSERT_TRUE(imported_credit_card); - EXPECT_TRUE(imported_credit_card_matches_masked_server_credit_card); - personal_data_manager_->SaveImportedCreditCard(*imported_credit_card); - - WaitForOnPersonalDataChanged(); -} - // Tests that a credit card is not extracted because it matches a full server // card. TEST_F(FormDataImporterTest, ImportCreditCard_DuplicateServerCards_FullCard) { @@ -1714,10 +1646,7 @@ TEST_F(FormDataImporterTest, ImportCreditCard_DuplicateServerCards_FullCard) { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_FALSE(ImportCreditCard( - form_structure, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_FALSE(ImportCreditCard(form_structure, false, &imported_credit_card)); ASSERT_FALSE(imported_credit_card); } @@ -1730,12 +1659,8 @@ TEST_F(FormDataImporterTest, ImportCreditCard_SameCreditCardWithConflict) { FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(ImportCreditCard( - form_structure1, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure1, false, &imported_credit_card)); ASSERT_TRUE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_manager_->SaveImportedCreditCard(*imported_credit_card); WaitForOnPersonalDataChanged(); @@ -1757,9 +1682,7 @@ TEST_F(FormDataImporterTest, ImportCreditCard_SameCreditCardWithConflict) { FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card2; - EXPECT_TRUE(ImportCreditCard( - form_structure2, false, &imported_credit_card2, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure2, false, &imported_credit_card2)); EXPECT_FALSE(imported_credit_card2); WaitForOnPersonalDataChanged(); @@ -1784,12 +1707,8 @@ TEST_F(FormDataImporterTest, ImportCreditCard_ShouldReturnLocalCard) { FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(ImportCreditCard( - form_structure1, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure1, false, &imported_credit_card)); ASSERT_TRUE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_manager_->SaveImportedCreditCard(*imported_credit_card); WaitForOnPersonalDataChanged(); @@ -1811,13 +1730,11 @@ TEST_F(FormDataImporterTest, ImportCreditCard_ShouldReturnLocalCard) { FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card2; - EXPECT_TRUE(ImportCreditCard( - form_structure2, - /* should_return_local_card= */ true, &imported_credit_card2, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure2, + /* should_return_local_card= */ true, + &imported_credit_card2)); // The local card is returned after an update. EXPECT_TRUE(imported_credit_card2); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); WaitForOnPersonalDataChanged(); @@ -1841,12 +1758,8 @@ TEST_F(FormDataImporterTest, ImportCreditCard_EmptyCardWithConflict) { FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(ImportCreditCard( - form_structure1, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure1, false, &imported_credit_card)); ASSERT_TRUE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_manager_->SaveImportedCreditCard(*imported_credit_card); WaitForOnPersonalDataChanged(); @@ -1867,9 +1780,8 @@ TEST_F(FormDataImporterTest, ImportCreditCard_EmptyCardWithConflict) { FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card2; - EXPECT_FALSE(ImportCreditCard( - form_structure2, false, &imported_credit_card2, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_FALSE( + ImportCreditCard(form_structure2, false, &imported_credit_card2)); EXPECT_FALSE(imported_credit_card2); // Since no refresh is expected, reload the data from the database to make @@ -1895,12 +1807,8 @@ TEST_F(FormDataImporterTest, ImportCreditCard_MissingInfoInNew) { FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(ImportCreditCard( - form_structure1, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure1, false, &imported_credit_card)); ASSERT_TRUE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_manager_->SaveImportedCreditCard(*imported_credit_card); WaitForOnPersonalDataChanged(); @@ -1922,9 +1830,7 @@ TEST_F(FormDataImporterTest, ImportCreditCard_MissingInfoInNew) { FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card2; - EXPECT_TRUE(ImportCreditCard( - form_structure2, false, &imported_credit_card2, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure2, false, &imported_credit_card2)); EXPECT_FALSE(imported_credit_card2); // Since no refresh is expected, reload the data from the database to make @@ -1949,9 +1855,8 @@ TEST_F(FormDataImporterTest, ImportCreditCard_MissingInfoInNew) { FormStructure form_structure3(form3); form_structure3.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card3; - EXPECT_FALSE(ImportCreditCard( - form_structure3, false, &imported_credit_card3, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_FALSE( + ImportCreditCard(form_structure3, false, &imported_credit_card3)); ASSERT_FALSE(imported_credit_card3); // Since no refresh is expected, reload the data from the database to make @@ -1992,10 +1897,7 @@ TEST_F(FormDataImporterTest, ImportCreditCard_MissingInfoInOld) { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(ImportCreditCard( - form_structure, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure, false, &imported_credit_card)); EXPECT_FALSE(imported_credit_card); WaitForOnPersonalDataChanged(); @@ -2036,10 +1938,7 @@ TEST_F(FormDataImporterTest, ImportCreditCard_SameCardWithSeparators) { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(ImportCreditCard( - form_structure, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure, false, &imported_credit_card)); EXPECT_FALSE(imported_credit_card); // Since no refresh is expected, reload the data from the database to make @@ -2079,10 +1978,7 @@ TEST_F(FormDataImporterTest, FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(ImportCreditCard( - form_structure, false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + EXPECT_TRUE(ImportCreditCard(form_structure, false, &imported_credit_card)); ASSERT_FALSE(imported_credit_card); // Since no refresh is expected, reload the data from the database to make @@ -2130,14 +2026,11 @@ TEST_F(FormDataImporterTest, ImportFormData_OneAddressOneCreditCard) { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(form_data_importer_->ImportFormData( form_structure, /*credit_card_autofill_enabled=*/true, - /*should_return_local_card=*/false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + /*should_return_local_card=*/false, &imported_credit_card)); ASSERT_TRUE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_manager_->SaveImportedCreditCard(*imported_credit_card); WaitForOnPersonalDataChanged(); @@ -2211,14 +2104,11 @@ TEST_F(FormDataImporterTest, ImportFormData_TwoAddressesOneCreditCard) { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; // Still returns true because the credit card import was successful. EXPECT_TRUE(form_data_importer_->ImportFormData( form_structure, /*credit_card_autofill_enabled=*/true, - /*should_return_local_card=*/false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + /*should_return_local_card=*/false, &imported_credit_card)); ASSERT_TRUE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_manager_->SaveImportedCreditCard(*imported_credit_card); WaitForOnPersonalDataChanged(); @@ -2266,11 +2156,9 @@ TEST_F(FormDataImporterTest, ImportFormData_OneAddressCreditCardDisabled) { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(form_data_importer_->ImportFormData( form_structure, /*credit_card_autofill_enabled=*/false, - /*should_return_local_card=*/false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + /*should_return_local_card=*/false, &imported_credit_card)); ASSERT_FALSE(imported_credit_card); WaitForOnPersonalDataChanged(); @@ -2293,71 +2181,6 @@ TEST_F(FormDataImporterTest, ImportFormData_OneAddressCreditCardDisabled) { ASSERT_EQ(0U, results_cards.size()); } -TEST_F(FormDataImporterTest, AllowDuplicateMaskedServerCardIfFlagEnabled) { - EnableWalletCardImport(); - // Turn on feature flag. - base::test::ScopedFeatureList scoped_feature_list_; - scoped_feature_list_.InitAndEnableFeature( - kAutofillOfferLocalSaveIfServerCardManuallyEntered); - - std::vector<CreditCard> server_cards; - server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); - test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", - "1881" /* Visa */, "01", "2999", ""); - server_cards.back().SetNetworkForMaskedCard(kVisaCard); - - server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "c789")); - test::SetCreditCardInfo(&server_cards.back(), "Clyde Barrow", - "378282246310005" /* American Express */, "04", - "2999", ""); - - test::SetServerCreditCards(autofill_table_, server_cards); - - // Make sure everything is set up correctly. - personal_data_manager_->Refresh(); - WaitForOnPersonalDataChanged(); - EXPECT_EQ(2U, personal_data_manager_->GetCreditCards().size()); - - // A valid credit card form. A user re-enters one of their masked cards. - // We should offer to save locally so that user can fill future credit card - // forms without unmasking. - FormData form; - FormFieldData field; - test::CreateTestFormField("Name on card:", "name_on_card", "John Dillinger", - "text", &field); - form.fields.push_back(field); - test::CreateTestFormField("Card Number:", "card_number", "4012888888881881", - "text", &field); - form.fields.push_back(field); - test::CreateTestFormField("Exp Month:", "exp_month", "01", "text", &field); - form.fields.push_back(field); - test::CreateTestFormField("Exp Year:", "exp_year", "2999", "text", &field); - form.fields.push_back(field); - - FormStructure form_structure(form); - form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); - std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; - EXPECT_TRUE(form_data_importer_->ImportFormData( - form_structure, /*credit_card_autofill_enabled=*/true, - /*should_return_local_card=*/false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); - ASSERT_TRUE(imported_credit_card); - EXPECT_TRUE(imported_credit_card_matches_masked_server_credit_card); - personal_data_manager_->SaveImportedCreditCard(*imported_credit_card); - - WaitForOnPersonalDataChanged(); - - CreditCard local_card(base::GenerateGUID(), "https://www.example.com"); - test::SetCreditCardInfo(&local_card, "John Dillinger", "4012888888881881", - "01", "2999", ""); - const std::vector<CreditCard*>& results = - personal_data_manager_->GetLocalCreditCards(); - ASSERT_EQ(1U, results.size()); - EXPECT_EQ(0, local_card.Compare(*results[0])); - EXPECT_EQ(3U, personal_data_manager_->GetCreditCards().size()); -} - TEST_F(FormDataImporterTest, DontDuplicateMaskedServerCard) { EnableWalletCardImport(); @@ -2380,8 +2203,7 @@ TEST_F(FormDataImporterTest, DontDuplicateMaskedServerCard) { EXPECT_EQ(2U, personal_data_manager_->GetCreditCards().size()); // A valid credit card form. A user re-enters one of their masked cards. - // We should not offer to save locally because the - // AutofillOfferLocalSaveIfServerCardManuallyEntered flag is not enabled. + // We should not offer to save locally. FormData form; FormFieldData field; test::CreateTestFormField("Name on card:", "name_on_card", "John Dillinger", @@ -2398,13 +2220,10 @@ TEST_F(FormDataImporterTest, DontDuplicateMaskedServerCard) { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(form_data_importer_->ImportFormData( form_structure, /*credit_card_autofill_enabled=*/true, - /*should_return_local_card=*/false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + /*should_return_local_card=*/false, &imported_credit_card)); ASSERT_FALSE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); } TEST_F(FormDataImporterTest, DontDuplicateFullServerCard) { @@ -2447,13 +2266,10 @@ TEST_F(FormDataImporterTest, DontDuplicateFullServerCard) { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(form_data_importer_->ImportFormData( form_structure, /*credit_card_autofill_enabled=*/true, - /*should_return_local_card=*/false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + /*should_return_local_card=*/false, &imported_credit_card)); EXPECT_FALSE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); } TEST_F(FormDataImporterTest, @@ -2491,13 +2307,10 @@ TEST_F(FormDataImporterTest, FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(form_data_importer_->ImportFormData( form_structure, /*credit_card_autofill_enabled=*/true, - /*should_return_local_card=*/false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + /*should_return_local_card=*/false, &imported_credit_card)); EXPECT_FALSE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); histogram_tester.ExpectUniqueSample( "Autofill.SubmittedServerCardExpirationStatus", AutofillMetrics::FULL_SERVER_CARD_EXPIRATION_DATE_MATCHED, 1); @@ -2539,13 +2352,10 @@ TEST_F(FormDataImporterTest, FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(form_data_importer_->ImportFormData( form_structure, /*credit_card_autofill_enabled=*/true, - /*should_return_local_card=*/false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + /*should_return_local_card=*/false, &imported_credit_card)); EXPECT_FALSE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); histogram_tester.ExpectUniqueSample( "Autofill.SubmittedServerCardExpirationStatus", AutofillMetrics::FULL_SERVER_CARD_EXPIRATION_DATE_DID_NOT_MATCH, 1); @@ -2587,13 +2397,10 @@ TEST_F(FormDataImporterTest, FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(form_data_importer_->ImportFormData( form_structure, /*credit_card_autofill_enabled=*/true, - /*should_return_local_card=*/false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + /*should_return_local_card=*/false, &imported_credit_card)); EXPECT_FALSE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); histogram_tester.ExpectUniqueSample( "Autofill.SubmittedServerCardExpirationStatus", AutofillMetrics::MASKED_SERVER_CARD_EXPIRATION_DATE_MATCHED, 1); @@ -2636,13 +2443,10 @@ TEST_F(FormDataImporterTest, FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; - bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(form_data_importer_->ImportFormData( form_structure, /*credit_card_autofill_enabled=*/true, - /*should_return_local_card=*/false, &imported_credit_card, - &imported_credit_card_matches_masked_server_credit_card)); + /*should_return_local_card=*/false, &imported_credit_card)); EXPECT_FALSE(imported_credit_card); - EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); histogram_tester.ExpectUniqueSample( "Autofill.SubmittedServerCardExpirationStatus", AutofillMetrics::MASKED_SERVER_CARD_EXPIRATION_DATE_DID_NOT_MATCH, 1); diff --git a/chromium/components/autofill/core/browser/form_field.h b/chromium/components/autofill/core/browser/form_field.h index 3ec73b4cf3a..c721f4bed83 100644 --- a/chromium/components/autofill/core/browser/form_field.h +++ b/chromium/components/autofill/core/browser/form_field.h @@ -74,9 +74,9 @@ class FormField { // Parses the stream of fields in |scanner| with regular expression |pattern| // as specified in the |match_type| bit field (see |MatchType|). If |match| - // is non-NULL and the pattern matches, the matched field is returned. - // A |true| result is returned in the case of a successful match, false - // otherwise. + // is non-NULL and the pattern matches, |match| will be set to the matched + // field, and the scanner would advance by one step. A |true| result is + // returned in the case of a successful match, false otherwise. static bool ParseFieldSpecifics(AutofillScanner* scanner, const base::string16& pattern, int match_type, diff --git a/chromium/components/autofill/core/browser/form_structure.cc b/chromium/components/autofill/core/browser/form_structure.cc index ab0c22def95..3ac2d1a45a7 100644 --- a/chromium/components/autofill/core/browser/form_structure.cc +++ b/chromium/components/autofill/core/browser/form_structure.cc @@ -680,8 +680,10 @@ bool FormStructure::ShouldBeUploaded() const { ShouldBeParsed(); } -void FormStructure::UpdateFromCache(const FormStructure& cached_form, - const bool apply_is_autofilled) { +void FormStructure::RetrieveFromCache( + const FormStructure& cached_form, + const bool apply_is_autofilled, + const bool only_server_and_autofill_state) { // Map from field signatures to cached fields. std::map<base::string16, const AutofillField*> cached_fields; for (size_t i = 0; i < cached_form.field_count(); ++i) { @@ -691,28 +693,29 @@ void FormStructure::UpdateFromCache(const FormStructure& cached_form, for (auto& field : *this) { const auto& cached_field = cached_fields.find(field->unique_name()); if (cached_field != cached_fields.end()) { + if (!only_server_and_autofill_state) { + // Transfer attributes of the cached AutofillField to the newly created + // AutofillField. + field->set_heuristic_type(cached_field->second->heuristic_type()); + field->SetHtmlType(cached_field->second->html_type(), + cached_field->second->html_mode()); + field->set_section(cached_field->second->section()); + field->set_only_fill_when_focused( + cached_field->second->only_fill_when_focused()); + } + if (apply_is_autofilled) { + field->is_autofilled = cached_field->second->is_autofilled; + } if (field->form_control_type != "select-one" && field->value == cached_field->second->value) { // From the perspective of learning user data, text fields containing // default values are equivalent to empty fields. field->value = base::string16(); } - - // Transfer attributes of the cached AutofillField to the newly created - // AutofillField. - field->set_heuristic_type(cached_field->second->heuristic_type()); field->set_overall_server_type( cached_field->second->overall_server_type()); - field->SetHtmlType(cached_field->second->html_type(), - cached_field->second->html_mode()); - if (apply_is_autofilled) { - field->is_autofilled = cached_field->second->is_autofilled; - } field->set_previously_autofilled( cached_field->second->previously_autofilled()); - field->set_section(cached_field->second->section()); - field->set_only_fill_when_focused( - cached_field->second->only_fill_when_focused()); } } @@ -1330,6 +1333,8 @@ void FormStructure::IdentifySections(bool has_author_specified_sections) { std::set<ServerFieldType> seen_types; ServerFieldType previous_type = UNKNOWN_TYPE; + bool is_hidden_section = false; + base::string16 last_visible_section; for (const auto& field : fields_) { const ServerFieldType current_type = field->Type().GetStorableType(); // All credit card fields belong to the same section that's different @@ -1347,13 +1352,26 @@ void FormStructure::IdentifySections(bool has_author_specified_sections) { if (AutofillType(current_type).group() == PHONE_HOME) already_saw_current_type = false; - // Ignore non-focusable field and presentation role fields while inferring - // boundaries between sections. bool ignored_field = !field->is_focusable || field->role == FormFieldData::ROLE_ATTRIBUTE_PRESENTATION; - if (ignored_field) + + // This is the first visible field after a hidden section. Consider it as + // the continuation of the last visible section. + if (!ignored_field && is_hidden_section) { + current_section = last_visible_section; + } + + // Start a new section by an ignored field, only if the next field is also + // already seen. + size_t field_index = &field - &fields_[0]; + if (ignored_field && + (is_hidden_section || + !((field_index + 1) < fields_.size() && + seen_types.count( + fields_[field_index + 1]->Type().GetStorableType()) > 0))) { already_saw_current_type = false; + } // Some forms have adjacent fields of the same type. Two common examples: // * Forms with two email fields, where the second is meant to "confirm" @@ -1368,8 +1386,17 @@ void FormStructure::IdentifySections(bool has_author_specified_sections) { already_saw_current_type = false; if (current_type != UNKNOWN_TYPE && already_saw_current_type) { - // We reached the end of a section, so start a new section. - seen_types.clear(); + // Keep track of seen_types if the new section is hidden. The next + // visible section might be the continuation of the previous visible + // section. + if (ignored_field) { + is_hidden_section = true; + last_visible_section = current_section; + } + if (!is_hidden_section) + seen_types.clear(); + + // The end of a section, so start a new section. current_section = field->unique_name(); } @@ -1383,6 +1410,7 @@ void FormStructure::IdentifySections(bool has_author_specified_sections) { if (!ignored_field) { seen_types.insert(current_type); previous_type = current_type; + is_hidden_section = false; } field->set_section(base::UTF16ToUTF8(current_section)); diff --git a/chromium/components/autofill/core/browser/form_structure.h b/chromium/components/autofill/core/browser/form_structure.h index eb576f3b55c..b8783c4dcce 100644 --- a/chromium/components/autofill/core/browser/form_structure.h +++ b/chromium/components/autofill/core/browser/form_structure.h @@ -121,8 +121,9 @@ class FormStructure { bool ShouldBeUploaded() const; // Sets the field types to be those set for |cached_form|. - void UpdateFromCache(const FormStructure& cached_form, - const bool apply_is_autofilled); + void RetrieveFromCache(const FormStructure& cached_form, + const bool apply_is_autofilled, + const bool only_server_and_autofill_state); // Logs quality metrics for |this|, which should be a user-submitted form. // This method should only be called after the possible field types have been diff --git a/chromium/components/autofill/core/browser/form_structure_unittest.cc b/chromium/components/autofill/core/browser/form_structure_unittest.cc index 24217d68a35..07f8b818f5f 100644 --- a/chromium/components/autofill/core/browser/form_structure_unittest.cc +++ b/chromium/components/autofill/core/browser/form_structure_unittest.cc @@ -129,7 +129,7 @@ class FormStructureTest : public testing::Test { void EnableAutofillMetadataFieldTrial() { field_trial_list_.reset(); field_trial_list_.reset(new base::FieldTrialList( - std::make_unique<metrics::SHA1EntropyProvider>("foo"))); + std::make_unique<variations::SHA1EntropyProvider>("foo"))); field_trial_ = base::FieldTrialList::CreateFieldTrial( "AutofillFieldMetadata", "Enabled"); field_trial_->group(); diff --git a/chromium/components/autofill/core/browser/payments/full_card_request_unittest.cc b/chromium/components/autofill/core/browser/payments/full_card_request_unittest.cc index 6b2269fb013..3f95ca3a104 100644 --- a/chromium/components/autofill/core/browser/payments/full_card_request_unittest.cc +++ b/chromium/components/autofill/core/browser/payments/full_card_request_unittest.cc @@ -76,7 +76,7 @@ class FullCardRequestTest : public testing::Test, autofill_client_.SetPrefs(std::move(pref_service)); payments_client_ = std::make_unique<PaymentsClient>( request_context_.get(), autofill_client_.GetPrefs(), - autofill_client_.GetIdentityProvider(), this, nullptr); + autofill_client_.GetIdentityManager(), this, nullptr); request_ = std::make_unique<FullCardRequest>( &autofill_client_, payments_client_.get(), &personal_data_); // Silence the warning from PaymentsClient about matching sync and Payments diff --git a/chromium/components/autofill/core/browser/payments/payments_client.cc b/chromium/components/autofill/core/browser/payments/payments_client.cc index 719ad557bbd..f65c8214c22 100644 --- a/chromium/components/autofill/core/browser/payments/payments_client.cc +++ b/chromium/components/autofill/core/browser/payments/payments_client.cc @@ -24,13 +24,13 @@ #include "components/autofill/core/browser/payments/payments_request.h" #include "components/autofill/core/browser/payments/payments_service_url.h" #include "components/data_use_measurement/core/data_use_user_data.h" -#include "google_apis/gaia/identity_provider.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/http/http_status_code.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_request_context_getter.h" +#include "services/identity/public/cpp/identity_manager.h" namespace autofill { namespace payments { @@ -56,7 +56,7 @@ const char kUploadCardRequestFormatWithoutCvc[] = "requestContentType=application/json; charset=utf-8&request=%s" "&s7e_1_pan=%s"; -const char kTokenServiceConsumerId[] = "wallet_client"; +const char kTokenFetchId[] = "wallet_client"; const char kPaymentsOAuth2Scope[] = "https://www.googleapis.com/auth/wallet.chrome"; @@ -456,13 +456,12 @@ PaymentsClient::UploadRequestDetails::~UploadRequestDetails() {} PaymentsClient::PaymentsClient(net::URLRequestContextGetter* context_getter, PrefService* pref_service, - IdentityProvider* identity_provider, + identity::IdentityManager* identity_manager, PaymentsClientUnmaskDelegate* unmask_delegate, PaymentsClientSaveDelegate* save_delegate) - : OAuth2TokenService::Consumer(kTokenServiceConsumerId), - context_getter_(context_getter), + : context_getter_(context_getter), pref_service_(pref_service), - identity_provider_(identity_provider), + identity_manager_(identity_manager), unmask_delegate_(unmask_delegate), save_delegate_(save_delegate), has_retried_authorization_(false), @@ -581,7 +580,7 @@ void PaymentsClient::InitializeUrlFetcher() { void PaymentsClient::CancelRequest() { request_.reset(); url_fetcher_.reset(); - access_token_request_.reset(); + token_fetcher_.reset(); access_token_.clear(); has_retried_authorization_ = false; } @@ -654,46 +653,52 @@ void PaymentsClient::OnURLFetchComplete(const net::URLFetcher* source) { request_->RespondToDelegate(result); } -void PaymentsClient::OnGetTokenSuccess( - const OAuth2TokenService::Request* request, - const std::string& access_token, - const base::Time& expiration_time) { - DCHECK_EQ(request, access_token_request_.get()); +void PaymentsClient::AccessTokenFetchFinished( + const GoogleServiceAuthError& error, + const std::string& access_token) { + // Delete the fetcher only after we leave this method (which is called from + // the fetcher itself). + DCHECK(token_fetcher_); + std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> + token_fetcher_deleter(std::move(token_fetcher_)); + + if (error.state() != GoogleServiceAuthError::NONE) { + AccessTokenError(error); + return; + } + access_token_ = access_token; if (url_fetcher_) SetOAuth2TokenAndStartRequest(); - - access_token_request_.reset(); } -void PaymentsClient::OnGetTokenFailure( - const OAuth2TokenService::Request* request, - const GoogleServiceAuthError& error) { - DCHECK_EQ(request, access_token_request_.get()); +void PaymentsClient::AccessTokenError(const GoogleServiceAuthError& error) { VLOG(1) << "Unhandled OAuth2 error: " << error.ToString(); if (url_fetcher_) { url_fetcher_.reset(); request_->RespondToDelegate(AutofillClient::PERMANENT_FAILURE); } - access_token_request_.reset(); } void PaymentsClient::StartTokenFetch(bool invalidate_old) { // We're still waiting for the last request to come back. - if (!invalidate_old && access_token_request_) + if (!invalidate_old && token_fetcher_) return; OAuth2TokenService::ScopeSet payments_scopes; payments_scopes.insert(kPaymentsOAuth2Scope); if (invalidate_old) { DCHECK(!access_token_.empty()); - identity_provider_->GetTokenService()->InvalidateAccessToken( - identity_provider_->GetActiveAccountId(), payments_scopes, + identity_manager_->RemoveAccessTokenFromCache( + identity_manager_->GetPrimaryAccountInfo(), payments_scopes, access_token_); } access_token_.clear(); - access_token_request_ = identity_provider_->GetTokenService()->StartRequest( - identity_provider_->GetActiveAccountId(), payments_scopes, this); + token_fetcher_ = identity_manager_->CreateAccessTokenFetcherForPrimaryAccount( + kTokenFetchId, payments_scopes, + base::BindOnce(&PaymentsClient::AccessTokenFetchFinished, + base::Unretained(this)), + identity::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); } void PaymentsClient::SetOAuth2TokenAndStartRequest() { diff --git a/chromium/components/autofill/core/browser/payments/payments_client.h b/chromium/components/autofill/core/browser/payments/payments_client.h index 5b10f216341..f097be903ab 100644 --- a/chromium/components/autofill/core/browser/payments/payments_client.h +++ b/chromium/components/autofill/core/browser/payments/payments_client.h @@ -13,10 +13,13 @@ #include "components/autofill/core/browser/card_unmask_delegate.h" #include "components/autofill/core/browser/credit_card.h" #include "components/prefs/pref_service.h" -#include "google_apis/gaia/oauth2_token_service.h" +#include "google_apis/gaia/google_service_auth_error.h" #include "net/url_request/url_fetcher_delegate.h" -class IdentityProvider; +namespace identity { +class IdentityManager; +class PrimaryAccountAccessTokenFetcher; +} // namespace identity namespace net { class URLFetcher; @@ -59,8 +62,7 @@ class PaymentsClientSaveDelegate { // request will cancel a pending request. // Tests are located in // src/components/autofill/content/browser/payments/payments_client_unittest.cc. -class PaymentsClient : public net::URLFetcherDelegate, - public OAuth2TokenService::Consumer { +class PaymentsClient : public net::URLFetcherDelegate { public: // The names of the fields used to send non-location elements as part of an // address. Used in the implementation and in tests which verify that these @@ -100,11 +102,11 @@ class PaymentsClient : public net::URLFetcherDelegate, // |context_getter| is reference counted so it has no lifetime or ownership // requirements. |pref_service| is used to get the registered preference - // value, |identity_provider|, |unmask_delegate| and |save_delegate| must all + // value, |identity_manager|, |unmask_delegate| and |save_delegate| must all // outlive |this|. Either delegate might be nullptr. PaymentsClient(net::URLRequestContextGetter* context_getter, PrefService* pref_service, - IdentityProvider* identity_provider, + identity::IdentityManager* identity_manager, PaymentsClientUnmaskDelegate* unmask_delegate, PaymentsClientSaveDelegate* save_delegate); @@ -162,12 +164,12 @@ class PaymentsClient : public net::URLFetcherDelegate, // net::URLFetcherDelegate: void OnURLFetchComplete(const net::URLFetcher* source) override; - // OAuth2TokenService::Consumer implementation. - void OnGetTokenSuccess(const OAuth2TokenService::Request* request, - const std::string& access_token, - const base::Time& expiration_time) override; - void OnGetTokenFailure(const OAuth2TokenService::Request* request, - const GoogleServiceAuthError& error) override; + // Callback that handles a completed access token request. + void AccessTokenFetchFinished(const GoogleServiceAuthError& error, + const std::string& access_token); + + // Handles a completed access token request in the case of failure. + void AccessTokenError(const GoogleServiceAuthError& error); // Creates |url_fetcher_| based on the current state of |request_|. void InitializeUrlFetcher(); @@ -184,7 +186,7 @@ class PaymentsClient : public net::URLFetcherDelegate, // The pref service for this client. PrefService* const pref_service_; - IdentityProvider* const identity_provider_; + identity::IdentityManager* const identity_manager_; // Delegates for the results of the various requests to Payments. Both must // outlive |this|. @@ -197,8 +199,8 @@ class PaymentsClient : public net::URLFetcherDelegate, // The fetcher being used to issue the current request. std::unique_ptr<net::URLFetcher> url_fetcher_; - // The current OAuth2 token request object. - std::unique_ptr<OAuth2TokenService::Request> access_token_request_; + // The current OAuth2 token fetcher. + std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_; // The OAuth2 token, or empty if not fetched. std::string access_token_; diff --git a/chromium/components/autofill/core/browser/payments/payments_client_unittest.cc b/chromium/components/autofill/core/browser/payments/payments_client_unittest.cc index dcb3d01cf5e..50ef8b744b2 100644 --- a/chromium/components/autofill/core/browser/payments/payments_client_unittest.cc +++ b/chromium/components/autofill/core/browser/payments/payments_client_unittest.cc @@ -20,10 +20,9 @@ #include "components/autofill/core/common/autofill_switches.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h" -#include "google_apis/gaia/fake_identity_provider.h" -#include "google_apis/gaia/fake_oauth2_token_service.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_request_test_util.h" +#include "services/identity/public/cpp/identity_test_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace autofill { @@ -62,11 +61,10 @@ class PaymentsClientTest : public testing::Test, request_context_ = new net::TestURLRequestContextGetter( base::ThreadTaskRunnerHandle::Get()); - token_service_.reset(new FakeOAuth2TokenService()); - identity_provider_.reset(new FakeIdentityProvider(token_service_.get())); TestingPrefServiceSimple pref_service_; client_.reset(new PaymentsClient(request_context_.get(), &pref_service_, - identity_provider_.get(), this, this)); + identity_test_env_.identity_manager(), + this, this)); } void TearDown() override { client_.reset(); } @@ -110,8 +108,9 @@ class PaymentsClientTest : public testing::Test, base::test::ScopedFeatureList scoped_feature_list_; void StartUnmasking() { - token_service_->AddAccount("example@gmail.com"); - identity_provider_->LogIn("example@gmail.com"); + if (!identity_test_env_.identity_manager()->HasPrimaryAccount()) + identity_test_env_.MakePrimaryAccountAvailable("example@gmail.com"); + PaymentsClient::UnmaskRequestDetails request_details; request_details.billing_customer_number = 111222333444; request_details.card = test::GetMaskedServerCard(); @@ -121,16 +120,18 @@ class PaymentsClientTest : public testing::Test, } void StartGettingUploadDetails() { - token_service_->AddAccount("example@gmail.com"); - identity_provider_->LogIn("example@gmail.com"); + if (!identity_test_env_.identity_manager()->HasPrimaryAccount()) + identity_test_env_.MakePrimaryAccountAvailable("example@gmail.com"); + client_->GetUploadDetails(BuildTestProfiles(), kAllDetectableValues, /*pan_first_six=*/"411111", std::vector<const char*>(), "language-LOCALE"); } void StartUploading(bool include_cvc) { - token_service_->AddAccount("example@gmail.com"); - identity_provider_->LogIn("example@gmail.com"); + if (!identity_test_env_.identity_manager()->HasPrimaryAccount()) + identity_test_env_.MakePrimaryAccountAvailable("example@gmail.com"); + PaymentsClient::UploadRequestDetails request_details; request_details.billing_customer_number = 111222333444; request_details.card = test::GetCreditCard(); @@ -148,8 +149,8 @@ class PaymentsClientTest : public testing::Test, } void IssueOAuthToken() { - token_service_->IssueAllTokensForAccount( - "example@gmail.com", "totally_real_token", + identity_test_env_.WaitForAccessTokenRequestAndRespondWithToken( + "totally_real_token", base::Time::Now() + base::TimeDelta::FromDays(10)); // Verify the auth header. @@ -180,9 +181,8 @@ class PaymentsClientTest : public testing::Test, base::test::ScopedTaskEnvironment scoped_task_environment_; net::TestURLFetcherFactory factory_; scoped_refptr<net::TestURLRequestContextGetter> request_context_; - std::unique_ptr<FakeOAuth2TokenService> token_service_; - std::unique_ptr<FakeIdentityProvider> identity_provider_; std::unique_ptr<PaymentsClient> client_; + identity::IdentityTestEnvironment identity_test_env_; private: DISALLOW_COPY_AND_ASSIGN(PaymentsClientTest); @@ -220,8 +220,7 @@ class PaymentsClientTest : public testing::Test, TEST_F(PaymentsClientTest, OAuthError) { StartUnmasking(); - token_service_->IssueErrorForAllPendingRequestsForAccount( - "example@gmail.com", + identity_test_env_.WaitForAccessTokenRequestAndRespondWithError( GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE)); EXPECT_EQ(AutofillClient::PERMANENT_FAILURE, result_); EXPECT_TRUE(real_pan_.empty()); @@ -494,7 +493,10 @@ TEST_F(PaymentsClientTest, ReauthNeeded) { { StartUnmasking(); - IssueOAuthToken(); + // NOTE: Don't issue an access token here: the issuing of an access token + // first waits for the access token request to be received, but here there + // should be no access token request because PaymentsClient should reuse the + // access token from the previous request. ReturnResponse(net::HTTP_UNAUTHORIZED, ""); // No response yet. EXPECT_EQ(AutofillClient::NONE, result_); diff --git a/chromium/components/autofill/core/browser/payments/test_payments_client.cc b/chromium/components/autofill/core/browser/payments/test_payments_client.cc index c8d5be1ded6..845b84d895d 100644 --- a/chromium/components/autofill/core/browser/payments/test_payments_client.cc +++ b/chromium/components/autofill/core/browser/payments/test_payments_client.cc @@ -12,12 +12,12 @@ namespace payments { TestPaymentsClient::TestPaymentsClient( net::URLRequestContextGetter* context_getter, PrefService* pref_service, - IdentityProvider* identity_provider, + identity::IdentityManager* identity_manager, payments::PaymentsClientUnmaskDelegate* unmask_delegate, payments::PaymentsClientSaveDelegate* save_delegate) : PaymentsClient(context_getter, pref_service, - identity_provider, + identity_manager, unmask_delegate, save_delegate), save_delegate_(save_delegate) {} diff --git a/chromium/components/autofill/core/browser/payments/test_payments_client.h b/chromium/components/autofill/core/browser/payments/test_payments_client.h index 49b5ddfcf03..f8b0f4a8392 100644 --- a/chromium/components/autofill/core/browser/payments/test_payments_client.h +++ b/chromium/components/autofill/core/browser/payments/test_payments_client.h @@ -17,7 +17,7 @@ class TestPaymentsClient : public payments::PaymentsClient { public: TestPaymentsClient(net::URLRequestContextGetter* context_getter, PrefService* pref_service, - IdentityProvider* identity_provider, + identity::IdentityManager* identity_manager, payments::PaymentsClientUnmaskDelegate* unmask_delegate, payments::PaymentsClientSaveDelegate* save_delegate); diff --git a/chromium/components/autofill/core/browser/personal_data_manager.cc b/chromium/components/autofill/core/browser/personal_data_manager.cc index 327f2cbb0c0..a3a62f5e049 100644 --- a/chromium/components/autofill/core/browser/personal_data_manager.cc +++ b/chromium/components/autofill/core/browser/personal_data_manager.cc @@ -41,12 +41,10 @@ #include "components/autofill/core/common/autofill_switches.h" #include "components/autofill/core/common/autofill_util.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/signin_manager.h" -#include "components/signin/core/browser/signin_pref_names.h" #include "components/sync/driver/sync_service.h" #include "components/variations/variations_associated_data.h" #include "components/version_info/version_info.h" +#include "services/identity/public/cpp/identity_manager.h" #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h" #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_formatter.h" @@ -358,22 +356,20 @@ PersonalDataManager::PersonalDataManager(const std::string& app_locale) pending_server_creditcards_query_(0), app_locale_(app_locale), pref_service_(nullptr), - account_tracker_(nullptr), + identity_manager_(nullptr), is_off_the_record_(false), has_logged_stored_profile_metrics_(false), has_logged_stored_credit_card_metrics_(false) {} void PersonalDataManager::Init(scoped_refptr<AutofillWebDataService> database, PrefService* pref_service, - AccountTrackerService* account_tracker, - SigninManagerBase* signin_manager, + identity::IdentityManager* identity_manager, bool is_off_the_record) { CountryNames::SetLocaleString(app_locale_); database_ = database; SetPrefService(pref_service); - account_tracker_ = account_tracker; - signin_manager_ = signin_manager; + identity_manager_ = identity_manager; is_off_the_record_ = is_off_the_record; if (!is_off_the_record_) @@ -1992,9 +1988,8 @@ std::string PersonalDataManager::MergeServerAddressesIntoProfiles( // Wallet addresses don't have an email address, use the one from the // currently signed-in account. - std::string account_id = signin_manager_->GetAuthenticatedAccountId(); base::string16 email = - base::UTF8ToUTF16(account_tracker_->GetAccountInfo(account_id).email); + base::UTF8ToUTF16(identity_manager_->GetPrimaryAccountInfo().email); if (!email.empty()) existing_profiles->back().SetRawInfo(EMAIL_ADDRESS, email); diff --git a/chromium/components/autofill/core/browser/personal_data_manager.h b/chromium/components/autofill/core/browser/personal_data_manager.h index ce8f498aa67..178de2fb16b 100644 --- a/chromium/components/autofill/core/browser/personal_data_manager.h +++ b/chromium/components/autofill/core/browser/personal_data_manager.h @@ -29,11 +29,9 @@ #include "components/prefs/pref_member.h" #include "components/webdata/common/web_data_service_consumer.h" -class AccountTrackerService; class Browser; class PrefService; class RemoveAutofillTester; -class SigninManagerBase; namespace autofill { class AutofillInteractiveTest; @@ -46,6 +44,10 @@ void SetProfiles(int, std::vector<autofill::AutofillProfile>*); void SetCreditCards(int, std::vector<autofill::CreditCard>*); } // namespace autofill_helper +namespace identity { +class IdentityManager; +} + namespace syncer { class SyncService; } // namespace syncer @@ -72,8 +74,7 @@ class PersonalDataManager : public KeyedService, // context. void Init(scoped_refptr<AutofillWebDataService> database, PrefService* pref_service, - AccountTrackerService* account_tracker, - SigninManagerBase* signin_manager, + identity::IdentityManager* identity_manager, bool is_off_the_record); // Called once the sync service is known to be instantiated. Note that it may @@ -149,7 +150,7 @@ class PersonalDataManager : public KeyedService, // Updates the use stats and billing address id for the server |credit_card|. // Looks up the card by server_id. - void UpdateServerCardMetadata(const CreditCard& credit_card); + virtual void UpdateServerCardMetadata(const CreditCard& credit_card); // Resets the card for |guid| to the masked state. void ResetFullServerCard(const std::string& guid); @@ -424,14 +425,6 @@ class PersonalDataManager : public KeyedService, database_ = database; } - void set_account_tracker(AccountTrackerService* account_tracker) { - account_tracker_ = account_tracker; - } - - void set_signin_manager(SigninManagerBase* signin_manager) { - signin_manager_ = signin_manager; - } - // The backing database that this PersonalDataManager uses. scoped_refptr<AutofillWebDataService> database_; @@ -581,12 +574,8 @@ class PersonalDataManager : public KeyedService, // The PrefService that this instance uses. Must outlive this instance. PrefService* pref_service_; - // The AccountTrackerService that this instance uses. Must outlive this - // instance. - AccountTrackerService* account_tracker_; - - // The signin manager that this instance uses. Must outlive this instance. - SigninManagerBase* signin_manager_; + // The identity manager that this instance uses. Must outlive this instance. + identity::IdentityManager* identity_manager_; // Whether the user is currently operating in an off-the-record context. // Default value is false. diff --git a/chromium/components/autofill/core/browser/personal_data_manager_unittest.cc b/chromium/components/autofill/core/browser/personal_data_manager_unittest.cc index c8601ef1a79..36ec3b39174 100644 --- a/chromium/components/autofill/core/browser/personal_data_manager_unittest.cc +++ b/chromium/components/autofill/core/browser/personal_data_manager_unittest.cc @@ -45,13 +45,10 @@ #include "components/autofill/core/common/form_data.h" #include "components/os_crypt/os_crypt_mocker.h" #include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/fake_signin_manager.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "components/signin/core/browser/test_signin_client.h" #include "components/variations/variations_params_manager.h" #include "components/webdata/common/web_data_service_base.h" #include "components/webdata/common/web_database_service.h" +#include "services/identity/public/cpp/identity_test_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -125,8 +122,7 @@ class PersonalDataManagerTestBase { personal_data_.reset(new PersonalDataManager("en")); personal_data_->Init( scoped_refptr<AutofillWebDataService>(autofill_database_service_), - prefs_.get(), account_tracker_.get(), signin_manager_.get(), - is_incognito); + prefs_.get(), identity_test_env_.identity_manager(), is_incognito); personal_data_->AddObserver(&personal_data_observer_); personal_data_->OnSyncServiceInitialized(nullptr); @@ -142,8 +138,7 @@ class PersonalDataManagerTestBase { } void EnableWalletCardImport() { - signin_manager_->SetAuthenticatedAccountInfo("12345", - "syncuser@example.com"); + identity_test_env_.MakePrimaryAccountAvailable("syncuser@example.com"); base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableOfferStoreUnmaskedWalletCards); } @@ -252,9 +247,7 @@ class PersonalDataManagerTestBase { base::ScopedTempDir temp_dir_; base::MessageLoopForUI message_loop_; std::unique_ptr<PrefService> prefs_; - std::unique_ptr<AccountTrackerService> account_tracker_; - std::unique_ptr<FakeSigninManagerBase> signin_manager_; - std::unique_ptr<TestSigninClient> signin_client_; + identity::IdentityTestEnvironment identity_test_env_; scoped_refptr<AutofillWebDataService> autofill_database_service_; scoped_refptr<WebDatabaseService> web_database_; AutofillTable* autofill_table_; // weak ref @@ -275,14 +268,6 @@ class PersonalDataManagerTest : public PersonalDataManagerTestBase, new WebDatabaseService(path, base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get()); - // Set up account tracker. - signin_client_.reset(new TestSigninClient(prefs_.get())); - account_tracker_.reset(new AccountTrackerService()); - account_tracker_->Initialize(signin_client_.get()); - signin_manager_.reset(new FakeSigninManagerBase(signin_client_.get(), - account_tracker_.get())); - signin_manager_->Initialize(prefs_.get()); - // Hacky: hold onto a pointer but pass ownership. autofill_table_ = new AutofillTable; web_database_->AddTable(std::unique_ptr<WebDatabaseTable>(autofill_table_)); @@ -306,13 +291,6 @@ class PersonalDataManagerTest : public PersonalDataManagerTestBase, void TearDown() override { // Order of destruction is important as AutofillManager relies on // PersonalDataManager to be around when it gets destroyed. - signin_manager_->Shutdown(); - signin_manager_.reset(); - - account_tracker_->Shutdown(); - account_tracker_.reset(); - signin_client_.reset(); - test::ReenableSystemServices(); OSCryptMocker::TearDown(); } @@ -2965,14 +2943,6 @@ class SaveImportedProfileTest new WebDatabaseService(path, base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get()); - // Set up account tracker. - signin_client_.reset(new TestSigninClient(prefs_.get())); - account_tracker_.reset(new AccountTrackerService()); - account_tracker_->Initialize(signin_client_.get()); - signin_manager_.reset(new FakeSigninManagerBase(signin_client_.get(), - account_tracker_.get())); - signin_manager_->Initialize(prefs_.get()); - // Hacky: hold onto a pointer but pass ownership. autofill_table_ = new AutofillTable; web_database_->AddTable(std::unique_ptr<WebDatabaseTable>(autofill_table_)); @@ -2994,15 +2964,6 @@ class SaveImportedProfileTest } void TearDown() override { - // Order of destruction is important as AutofillManager relies on - // PersonalDataManager to be around when it gets destroyed. - signin_manager_->Shutdown(); - signin_manager_.reset(); - - account_tracker_->Shutdown(); - account_tracker_.reset(); - signin_client_.reset(); - test::DisableSystemServices(prefs_.get()); OSCryptMocker::TearDown(); } diff --git a/chromium/components/autofill/core/browser/state_names.h b/chromium/components/autofill/core/browser/state_names.h index cd71539de6a..ebeab8e1fe5 100644 --- a/chromium/components/autofill/core/browser/state_names.h +++ b/chromium/components/autofill/core/browser/state_names.h @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/strings/string16.h" - #ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_STATE_NAMES_H_ #define COMPONENTS_AUTOFILL_CORE_BROWSER_STATE_NAMES_H_ +#include "base/strings/string16.h" + namespace autofill { namespace state_names { diff --git a/chromium/components/autofill/core/browser/test_autofill_client.cc b/chromium/components/autofill/core/browser/test_autofill_client.cc index b72be19d713..62a36f7331b 100644 --- a/chromium/components/autofill/core/browser/test_autofill_client.cc +++ b/chromium/components/autofill/core/browser/test_autofill_client.cc @@ -12,8 +12,7 @@ namespace autofill { TestAutofillClient::TestAutofillClient() - : token_service_(new FakeOAuth2TokenService()), - identity_provider_(new FakeIdentityProvider(token_service_.get())), + : #if !defined(OS_ANDROID) save_card_bubble_controller_(new MockSaveCardBubbleController()), #endif @@ -38,8 +37,8 @@ syncer::SyncService* TestAutofillClient::GetSyncService() { return nullptr; } -IdentityProvider* TestAutofillClient::GetIdentityProvider() { - return identity_provider_.get(); +identity::IdentityManager* TestAutofillClient::GetIdentityManager() { + return identity_test_env_.identity_manager(); } ukm::UkmRecorder* TestAutofillClient::GetUkmRecorder() { diff --git a/chromium/components/autofill/core/browser/test_autofill_client.h b/chromium/components/autofill/core/browser/test_autofill_client.h index 4974ed68c69..e4ae77dcc86 100644 --- a/chromium/components/autofill/core/browser/test_autofill_client.h +++ b/chromium/components/autofill/core/browser/test_autofill_client.h @@ -16,8 +16,7 @@ #include "components/autofill/core/browser/autofill_client.h" #include "components/prefs/pref_service.h" #include "components/ukm/test_ukm_recorder.h" -#include "google_apis/gaia/fake_identity_provider.h" -#include "google_apis/gaia/fake_oauth2_token_service.h" +#include "services/identity/public/cpp/identity_test_environment.h" namespace autofill { @@ -32,7 +31,7 @@ class TestAutofillClient : public AutofillClient { scoped_refptr<AutofillWebDataService> GetDatabase() override; PrefService* GetPrefs() override; syncer::SyncService* GetSyncService() override; - IdentityProvider* GetIdentityProvider() override; + identity::IdentityManager* GetIdentityManager() override; ukm::UkmRecorder* GetUkmRecorder() override; AddressNormalizer* GetAddressNormalizer() override; SaveCardBubbleController* GetSaveCardBubbleController() override; @@ -85,10 +84,10 @@ class TestAutofillClient : public AutofillClient { void set_form_origin(const GURL& url) { form_origin_ = url; } private: + identity::IdentityTestEnvironment identity_test_env_; + // NULL by default. std::unique_ptr<PrefService> prefs_; - std::unique_ptr<FakeOAuth2TokenService> token_service_; - std::unique_ptr<FakeIdentityProvider> identity_provider_; #if !defined(OS_ANDROID) std::unique_ptr<SaveCardBubbleController> save_card_bubble_controller_; #endif diff --git a/chromium/components/autofill/core/browser/test_autofill_clock.cc b/chromium/components/autofill/core/browser/test_autofill_clock.cc index 4d5829b8a26..a43489ebced 100644 --- a/chromium/components/autofill/core/browser/test_autofill_clock.cc +++ b/chromium/components/autofill/core/browser/test_autofill_clock.cc @@ -12,13 +12,7 @@ namespace autofill { TestAutofillClock::TestAutofillClock() { - // Create a new test clock and set it as the AutofillClock clock and keep a - // pointer to manipulate the time it returns. - std::unique_ptr<base::SimpleTestClock> unique_test_clock( - new base::SimpleTestClock()); - // Keep a pointer to the clock to be able to use its SetNow() function. - test_clock_ = unique_test_clock.get(); - AutofillClock::SetTestClock(std::move(unique_test_clock)); + AutofillClock::SetTestClock(&test_clock_); } TestAutofillClock::~TestAutofillClock() { @@ -27,7 +21,7 @@ TestAutofillClock::~TestAutofillClock() { } void TestAutofillClock::SetNow(base::Time now) { - test_clock_->SetNow(now); + test_clock_.SetNow(now); } } // namespace autofill diff --git a/chromium/components/autofill/core/browser/test_autofill_clock.h b/chromium/components/autofill/core/browser/test_autofill_clock.h index a40f54fbd2f..71bc8825475 100644 --- a/chromium/components/autofill/core/browser/test_autofill_clock.h +++ b/chromium/components/autofill/core/browser/test_autofill_clock.h @@ -8,9 +8,9 @@ #include <memory> #include "base/macros.h" +#include "base/test/simple_test_clock.h" namespace base { -class SimpleTestClock; class Time; } // namespace base @@ -29,7 +29,7 @@ class TestAutofillClock { void SetNow(base::Time now); private: - base::SimpleTestClock* test_clock_; + base::SimpleTestClock test_clock_; DISALLOW_COPY_AND_ASSIGN(TestAutofillClock); }; diff --git a/chromium/components/autofill/core/browser/test_autofill_manager.cc b/chromium/components/autofill/core/browser/test_autofill_manager.cc index 2fab42d9855..1ef5b047513 100644 --- a/chromium/components/autofill/core/browser/test_autofill_manager.cc +++ b/chromium/components/autofill/core/browser/test_autofill_manager.cc @@ -23,7 +23,7 @@ TestAutofillManager::TestAutofillManager(AutofillDriver* driver, personal_data_(personal_data), context_getter_(driver->GetURLRequestContext()) { set_payments_client(new payments::PaymentsClient( - context_getter_, client->GetPrefs(), client->GetIdentityProvider(), + context_getter_, client->GetPrefs(), client->GetIdentityManager(), /*unmask_delegate=*/this, /*save_delegate=*/nullptr)); } diff --git a/chromium/components/autofill/core/browser/webdata/autocomplete_sync_bridge.cc b/chromium/components/autofill/core/browser/webdata/autocomplete_sync_bridge.cc index 31947b87d1b..44d20684d65 100644 --- a/chromium/components/autofill/core/browser/webdata/autocomplete_sync_bridge.cc +++ b/chromium/components/autofill/core/browser/webdata/autocomplete_sync_bridge.cc @@ -368,8 +368,8 @@ void AutocompleteSyncBridge::AutocompleteSyncBridge::GetData( DCHECK(thread_checker_.CalledOnValidThread()); std::vector<AutofillEntry> entries; if (!GetAutofillTable()->GetAllAutofillEntries(&entries)) { - change_processor()->ReportError(FROM_HERE, - "Failed to load entries from table."); + change_processor()->ReportError( + {FROM_HERE, "Failed to load entries from table."}); return; } @@ -390,8 +390,8 @@ void AutocompleteSyncBridge::GetAllData(DataCallback callback) { std::vector<AutofillEntry> entries; if (!GetAutofillTable()->GetAllAutofillEntries(&entries)) { - change_processor()->ReportError(FROM_HERE, - "Failed to load entries from table."); + change_processor()->ReportError( + {FROM_HERE, "Failed to load entries from table."}); return; } @@ -422,7 +422,7 @@ void AutocompleteSyncBridge::ActOnLocalChanges( &date_last_used); if (!success) { change_processor()->ReportError( - FROM_HERE, "Failed reading autofill entry from WebDatabase."); + {FROM_HERE, "Failed reading autofill entry from WebDatabase."}); return; } @@ -439,21 +439,21 @@ void AutocompleteSyncBridge::ActOnLocalChanges( } if (Optional<ModelError> error = metadata_change_list->TakeError()) - change_processor()->ReportError(error.value()); + change_processor()->ReportError(*error); } void AutocompleteSyncBridge::LoadMetadata() { if (!web_data_backend_ || !web_data_backend_->GetDatabase() || !GetAutofillTable()) { - change_processor()->ReportError(FROM_HERE, - "Failed to load AutofillWebDatabase."); + change_processor()->ReportError( + {FROM_HERE, "Failed to load AutofillWebDatabase."}); return; } auto batch = std::make_unique<syncer::MetadataBatch>(); if (!GetAutofillTable()->GetAllSyncMetadata(syncer::AUTOFILL, batch.get())) { change_processor()->ReportError( - FROM_HERE, "Failed reading autofill metadata from WebDatabase."); + {FROM_HERE, "Failed reading autofill metadata from WebDatabase."}); return; } change_processor()->ModelReadyToSync(std::move(batch)); diff --git a/chromium/components/autofill/core/browser/webdata/autofill_data_type_controller_unittest.cc b/chromium/components/autofill/core/browser/webdata/autofill_data_type_controller_unittest.cc index 78b169253e5..5424b1a2f47 100644 --- a/chromium/components/autofill/core/browser/webdata/autofill_data_type_controller_unittest.cc +++ b/chromium/components/autofill/core/browser/webdata/autofill_data_type_controller_unittest.cc @@ -92,7 +92,7 @@ class AutofillDataTypeControllerTest : public testing::Test, new FakeWebDataService(base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get()); autofill_dtc_ = std::make_unique<AutofillDataTypeController>( - base::ThreadTaskRunnerHandle::Get(), base::Bind(&base::DoNothing), this, + base::ThreadTaskRunnerHandle::Get(), base::DoNothing(), this, web_data_service_); last_type_ = syncer::UNSPECIFIED; diff --git a/chromium/components/autofill/core/browser/webdata/autofill_wallet_syncable_service.cc b/chromium/components/autofill/core/browser/webdata/autofill_wallet_syncable_service.cc index 90d6408695e..3ff3a516adb 100644 --- a/chromium/components/autofill/core/browser/webdata/autofill_wallet_syncable_service.cc +++ b/chromium/components/autofill/core/browser/webdata/autofill_wallet_syncable_service.cc @@ -11,6 +11,7 @@ #include "base/logging.h" #include "base/memory/ptr_util.h" +#include "base/metrics/histogram_macros.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -139,69 +140,58 @@ AutofillProfile ProfileFromSpecifics( return profile; } -// This function handles conditionally updating the AutofillTable with either -// a set of CreditCards or AutocompleteProfiles only when the existing data -// doesn't match. -// -// It's passed the getter and setter function on the AutofillTable for the -// corresponding data type, and expects the types to implement a Compare -// function. Note that the guid can't be used here as a key since these are -// generated locally and will be different each time, and the server ID can't -// be used because it's empty for addresses (though it could be used for credit -// cards if we wanted separate implementations). -// -// Returns true if anything changed. The previous number of items in the table -// (for sync tracking) will be placed into *prev_item_count. -template <class Data> -bool SetDataIfChanged( - AutofillTable* table, - const std::vector<Data>& data, - bool (AutofillTable::*getter)(std::vector<std::unique_ptr<Data>>*) const, - void (AutofillTable::*setter)(const std::vector<Data>&), - size_t* prev_item_count) { - std::vector<std::unique_ptr<Data>> existing_data; - (table->*getter)(&existing_data); - *prev_item_count = existing_data.size(); - - // If the user has a large number of addresses, don't bother verifying - // anything changed and just rewrite the data. - const size_t kTooBigToCheckThreshold = 8; - - bool difference_found; - if (existing_data.size() != data.size() || - data.size() > kTooBigToCheckThreshold) { - difference_found = true; - } else { - difference_found = false; - - // Implement brute-force searching. Address and card counts are typically - // small, and comparing them is relatively expensive (many string - // compares). A std::set only uses operator< requiring multiple calls to - // check equality, giving 8 compares for 2 elements and 16 for 3. For these - // set sizes, brute force O(n^2) is faster. - for (const auto& cur_existing : existing_data) { - bool found_match_for_cur_existing = false; - for (const Data& cur_new : data) { - if (cur_existing->Compare(cur_new) == 0) { - found_match_for_cur_existing = true; - break; - } - } - if (!found_match_for_cur_existing) { - difference_found = true; - break; - } +} // namespace + +// static +template <class Item> +AutofillWalletSyncableService::Diff AutofillWalletSyncableService::ComputeDiff( + const std::vector<std::unique_ptr<Item>>& old_data, + const std::vector<Item>& new_data) { + // Build vectors of pointers, so that we can mutate (sort) them. + std::vector<const Item*> old_ptrs; + old_ptrs.reserve(old_data.size()); + for (const std::unique_ptr<Item>& old_item : old_data) + old_ptrs.push_back(old_item.get()); + std::vector<const Item*> new_ptrs; + new_ptrs.reserve(new_data.size()); + for (const Item& new_item : new_data) + new_ptrs.push_back(&new_item); + + // Sort our vectors. + auto compare = [](const Item* lhs, const Item* rhs) { + return lhs->Compare(*rhs) < 0; + }; + std::sort(old_ptrs.begin(), old_ptrs.end(), compare); + std::sort(new_ptrs.begin(), new_ptrs.end(), compare); + + // Walk over both of them and count added/removed elements. + Diff result; + auto old_it = old_ptrs.begin(); + auto new_it = new_ptrs.begin(); + while (old_it != old_ptrs.end()) { + if (new_it == new_ptrs.end()) { + result.items_removed += std::distance(old_it, old_ptrs.end()); + break; + } + int cmp = (*old_it)->Compare(**new_it); + if (cmp < 0) { + ++result.items_removed; + ++old_it; + } else if (cmp == 0) { + ++old_it; + ++new_it; + } else { + ++result.items_added; + ++new_it; } } + result.items_added += std::distance(new_it, new_ptrs.end()); - if (difference_found) { - (table->*setter)(data); - return true; - } - return false; -} + DCHECK_EQ(old_data.size() + result.items_added - result.items_removed, + new_data.size()); -} // namespace + return result; +} AutofillWalletSyncableService::AutofillWalletSyncableService( AutofillWebDataBackend* webdata_backend, @@ -217,7 +207,8 @@ syncer::SyncMergeResult AutofillWalletSyncableService::MergeDataAndStartSyncing( std::unique_ptr<syncer::SyncErrorFactory> sync_error_factory) { DCHECK(thread_checker_.CalledOnValidThread()); sync_processor_ = std::move(sync_processor); - syncer::SyncMergeResult result = SetSyncData(initial_sync_data); + syncer::SyncMergeResult result = + SetSyncData(initial_sync_data, /*is_initial_data=*/true); if (webdata_backend_) webdata_backend_->NotifyThatSyncHasStarted(type); return result; @@ -243,7 +234,8 @@ syncer::SyncError AutofillWalletSyncableService::ProcessSyncChanges( DCHECK(thread_checker_.CalledOnValidThread()); // Don't bother handling incremental updates. Wallet data changes very rarely // and has few items. Instead, just get all the current data and save it. - SetSyncData(sync_processor_->GetAllSyncData(syncer::AUTOFILL_WALLET_DATA)); + SetSyncData(sync_processor_->GetAllSyncData(syncer::AUTOFILL_WALLET_DATA), + /*is_initial_data=*/false); return syncer::SyncError(); } @@ -334,7 +326,8 @@ void AutofillWalletSyncableService::CopyRelevantMetadataFromDisk( } syncer::SyncMergeResult AutofillWalletSyncableService::SetSyncData( - const syncer::SyncDataList& data_list) { + const syncer::SyncDataList& data_list, + bool is_initial_data) { std::vector<CreditCard> wallet_cards; std::vector<AutofillProfile> wallet_addresses; PopulateWalletCardsAndAddresses(data_list, &wallet_cards, &wallet_addresses); @@ -351,22 +344,42 @@ syncer::SyncMergeResult AutofillWalletSyncableService::SetSyncData( // to the database will require at least one DB page write and will schedule // a fsync. To avoid this I/O, it should be more efficient to do a read and // only do the writes if something changed. - size_t prev_card_count = 0; - size_t prev_address_count = 0; - bool changed_cards = SetDataIfChanged( - table, wallet_cards, &AutofillTable::GetServerCreditCards, - &AutofillTable::SetServerCreditCards, &prev_card_count); - bool changed_addresses = SetDataIfChanged( - table, wallet_addresses, &AutofillTable::GetServerProfiles, - &AutofillTable::SetServerProfiles, &prev_address_count); + std::vector<std::unique_ptr<CreditCard>> existing_cards; + table->GetServerCreditCards(&existing_cards); + Diff cards_diff = ComputeDiff(existing_cards, wallet_cards); + if (!cards_diff.IsEmpty()) + table->SetServerCreditCards(wallet_cards); + + std::vector<std::unique_ptr<AutofillProfile>> existing_addresses; + table->GetServerProfiles(&existing_addresses); + Diff addresses_diff = ComputeDiff(existing_addresses, wallet_addresses); + if (!addresses_diff.IsEmpty()) + table->SetServerProfiles(wallet_addresses); syncer::SyncMergeResult merge_result(syncer::AUTOFILL_WALLET_DATA); merge_result.set_num_items_before_association( - static_cast<int>(prev_card_count + prev_address_count)); + static_cast<int>(existing_cards.size() + existing_addresses.size())); merge_result.set_num_items_after_association( static_cast<int>(wallet_cards.size() + wallet_addresses.size())); - if (webdata_backend_ && (changed_cards || changed_addresses)) + if (!is_initial_data) { + UMA_HISTOGRAM_COUNTS_100("Autofill.WalletCardsAdded", + cards_diff.items_added); + UMA_HISTOGRAM_COUNTS_100("Autofill.WalletCardsRemoved", + cards_diff.items_removed); + UMA_HISTOGRAM_COUNTS_100("Autofill.WalletCardsAddedOrRemoved", + cards_diff.items_added + cards_diff.items_removed); + + UMA_HISTOGRAM_COUNTS_100("Autofill.WalletAddressesAdded", + addresses_diff.items_added); + UMA_HISTOGRAM_COUNTS_100("Autofill.WalletAddressesRemoved", + addresses_diff.items_removed); + UMA_HISTOGRAM_COUNTS_100( + "Autofill.WalletAddressesAddedOrRemoved", + addresses_diff.items_added + addresses_diff.items_removed); + } + + if (webdata_backend_ && (!cards_diff.IsEmpty() || !addresses_diff.IsEmpty())) webdata_backend_->NotifyOfMultipleAutofillChanges(); return merge_result; diff --git a/chromium/components/autofill/core/browser/webdata/autofill_wallet_syncable_service.h b/chromium/components/autofill/core/browser/webdata/autofill_wallet_syncable_service.h index 9b4e92a229c..c27626c36fd 100644 --- a/chromium/components/autofill/core/browser/webdata/autofill_wallet_syncable_service.h +++ b/chromium/components/autofill/core/browser/webdata/autofill_wallet_syncable_service.h @@ -77,8 +77,30 @@ class AutofillWalletSyncableService CopyRelevantMetadataFromDisk_KeepUseStats); FRIEND_TEST_ALL_PREFIXES(AutofillWalletSyncableServiceTest, NewWalletCard); FRIEND_TEST_ALL_PREFIXES(AutofillWalletSyncableServiceTest, EmptyNameOnCard); - - syncer::SyncMergeResult SetSyncData(const syncer::SyncDataList& data_list); + FRIEND_TEST_ALL_PREFIXES(AutofillWalletSyncableServiceTest, ComputeCardsDiff); + FRIEND_TEST_ALL_PREFIXES(AutofillWalletSyncableServiceTest, + ComputeAddressesDiff); + + struct Diff { + int items_added = 0; + int items_removed = 0; + + bool IsEmpty() const { return items_added == 0 && items_removed == 0; } + }; + + // Computes a "diff" (items added, items removed) of two vectors of items, + // which should be either CreditCard or AutofillProfile. This is used for two + // purposes: + // 1) Detecting if anything has changed, so that we don't write to disk in the + // common case where nothing has changed. + // 2) Recording metrics on the number of added/removed items. + // This is exposed as a static method so that it can be tested. + template <class Item> + static Diff ComputeDiff(const std::vector<std::unique_ptr<Item>>& old_data, + const std::vector<Item>& new_data); + + syncer::SyncMergeResult SetSyncData(const syncer::SyncDataList& data_list, + bool is_initial_data); // Populates the wallet cards and addresses from the sync data and uses the // sync data to link the card to its billing address. diff --git a/chromium/components/autofill/core/browser/webdata/autofill_wallet_syncable_service_unittest.cc b/chromium/components/autofill/core/browser/webdata/autofill_wallet_syncable_service_unittest.cc index f407085d98f..c31ea73a9d5 100644 --- a/chromium/components/autofill/core/browser/webdata/autofill_wallet_syncable_service_unittest.cc +++ b/chromium/components/autofill/core/browser/webdata/autofill_wallet_syncable_service_unittest.cc @@ -7,6 +7,7 @@ #include <memory> #include <vector> +#include "base/strings/utf_string_conversions.h" #include "components/autofill/core/browser/autofill_profile.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/test_autofill_clock.h" @@ -246,4 +247,110 @@ TEST(AutofillWalletSyncableServiceTest, EmptyNameOnCard) { wallet_cards.back().GetRawInfo(autofill::CREDIT_CARD_NAME_LAST).empty()); } +TEST(AutofillWalletSyncableServiceTest, ComputeCardsDiff) { + // Some arbitrary cards for testing. + CreditCard card0(CreditCard::MASKED_SERVER_CARD, "a"); + CreditCard card1(CreditCard::MASKED_SERVER_CARD, "b"); + CreditCard card2(CreditCard::MASKED_SERVER_CARD, "c"); + CreditCard card3(CreditCard::MASKED_SERVER_CARD, "d"); + // Make sure that card0 < card1 < card2 < card3. + ASSERT_LT(card0.Compare(card1), 0); + ASSERT_LT(card1.Compare(card2), 0); + ASSERT_LT(card2.Compare(card3), 0); + + struct TestCase { + const char* name; + const std::vector<CreditCard> old_cards; + const std::vector<CreditCard> new_cards; + int expected_added; + int expected_removed; + } test_cases[] = { + {"Both empty", {}, {}, 0, 0}, + {"Old empty", {}, {card0}, 1, 0}, + {"New empty", {card0}, {}, 0, 1}, + {"Identical", {card0, card1}, {card0, card1}, 0, 0}, + {"Identical unsorted", {card0, card1}, {card1, card0}, 0, 0}, + {"Added one", {card0}, {card0, card1}, 1, 0}, + {"Added two", {card1}, {card0, card1, card2}, 2, 0}, + {"Removed one", {card0, card1}, {card1}, 0, 1}, + {"Removed two", {card0, card1, card2}, {card1}, 0, 2}, + {"Replaced one", {card0}, {card1}, 1, 1}, + {"Replaced two", {card0, card1}, {card2, card3}, 2, 2}, + {"Added and removed one", {card0, card1}, {card1, card2}, 1, 1}, + }; + + for (const TestCase& test_case : test_cases) { + SCOPED_TRACE(test_case.name); + + // ComputeDiff expects a vector of unique_ptrs for the old data. + std::vector<std::unique_ptr<CreditCard>> old_cards_ptrs; + for (const CreditCard& card : test_case.old_cards) + old_cards_ptrs.push_back(std::make_unique<CreditCard>(card)); + + AutofillWalletSyncableService::Diff diff = + AutofillWalletSyncableService::ComputeDiff(old_cards_ptrs, + test_case.new_cards); + + EXPECT_EQ(test_case.expected_added, diff.items_added); + EXPECT_EQ(test_case.expected_removed, diff.items_removed); + } +} + +TEST(AutofillWalletSyncableServiceTest, ComputeAddressesDiff) { + // Some arbitrary addresses for testing. + AutofillProfile address0(AutofillProfile::SERVER_PROFILE, "a"); + AutofillProfile address1(AutofillProfile::SERVER_PROFILE, "b"); + AutofillProfile address2(AutofillProfile::SERVER_PROFILE, "c"); + AutofillProfile address3(AutofillProfile::SERVER_PROFILE, "d"); + address0.SetRawInfo(NAME_FULL, base::ASCIIToUTF16("a")); + address1.SetRawInfo(NAME_FULL, base::ASCIIToUTF16("b")); + address2.SetRawInfo(NAME_FULL, base::ASCIIToUTF16("c")); + address3.SetRawInfo(NAME_FULL, base::ASCIIToUTF16("d")); + // Make sure that address0 < address1 < address2 < address3. + ASSERT_LT(address0.Compare(address1), 0); + ASSERT_LT(address1.Compare(address2), 0); + ASSERT_LT(address2.Compare(address3), 0); + + struct TestCase { + const char* name; + const std::vector<AutofillProfile> old_addresses; + const std::vector<AutofillProfile> new_addresses; + int expected_added; + int expected_removed; + } test_cases[] = { + {"Both empty", {}, {}, 0, 0}, + {"Old empty", {}, {address0}, 1, 0}, + {"New empty", {address0}, {}, 0, 1}, + {"Identical", {address0, address1}, {address0, address1}, 0, 0}, + {"Identical unsorted", {address0, address1}, {address1, address0}, 0, 0}, + {"Added one", {address0}, {address0, address1}, 1, 0}, + {"Added two", {address1}, {address0, address1, address2}, 2, 0}, + {"Removed one", {address0, address1}, {address1}, 0, 1}, + {"Removed two", {address0, address1, address2}, {address1}, 0, 2}, + {"Replaced one", {address0}, {address1}, 1, 1}, + {"Replaced two", {address0, address1}, {address2, address3}, 2, 2}, + {"Added and removed one", + {address0, address1}, + {address1, address2}, + 1, + 1}, + }; + + for (const TestCase& test_case : test_cases) { + SCOPED_TRACE(test_case.name); + + // ComputeDiff expects a vector of unique_ptrs for the old data. + std::vector<std::unique_ptr<AutofillProfile>> old_addresses_ptrs; + for (const AutofillProfile& address : test_case.old_addresses) + old_addresses_ptrs.push_back(std::make_unique<AutofillProfile>(address)); + + AutofillWalletSyncableService::Diff diff = + AutofillWalletSyncableService::ComputeDiff(old_addresses_ptrs, + test_case.new_addresses); + + EXPECT_EQ(test_case.expected_added, diff.items_added); + EXPECT_EQ(test_case.expected_removed, diff.items_removed); + } +} + } // namespace autofill diff --git a/chromium/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.cc b/chromium/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.cc index 7a6f5536f43..67de7896c07 100644 --- a/chromium/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.cc +++ b/chromium/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.cc @@ -30,22 +30,21 @@ AutofillWebDataBackendImpl::AutofillWebDataBackendImpl( const base::Closure& on_changed_callback, const base::Callback<void(syncer::ModelType)>& on_sync_started_callback) : base::RefCountedDeleteOnSequence<AutofillWebDataBackendImpl>( - db_task_runner), + std::move(db_task_runner)), ui_task_runner_(ui_task_runner), - db_task_runner_(db_task_runner), web_database_backend_(web_database_backend), on_changed_callback_(on_changed_callback), on_sync_started_callback_(on_sync_started_callback) {} void AutofillWebDataBackendImpl::AddObserver( AutofillWebDataServiceObserverOnDBSequence* observer) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); db_observer_list_.AddObserver(observer); } void AutofillWebDataBackendImpl::RemoveObserver( AutofillWebDataServiceObserverOnDBSequence* observer) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); db_observer_list_.RemoveObserver(observer); } @@ -54,7 +53,7 @@ AutofillWebDataBackendImpl::~AutofillWebDataBackendImpl() { } WebDatabase* AutofillWebDataBackendImpl::GetDatabase() { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); return web_database_backend_->database(); } @@ -65,7 +64,7 @@ void AutofillWebDataBackendImpl::RemoveExpiredFormElements() { } void AutofillWebDataBackendImpl::NotifyOfMultipleAutofillChanges() { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); // DB sequence notification. for (auto& db_observer : db_observer_list_) @@ -77,7 +76,7 @@ void AutofillWebDataBackendImpl::NotifyOfMultipleAutofillChanges() { void AutofillWebDataBackendImpl::NotifyThatSyncHasStarted( syncer::ModelType model_type) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (on_sync_started_callback_.is_null()) return; @@ -88,7 +87,7 @@ void AutofillWebDataBackendImpl::NotifyThatSyncHasStarted( } base::SupportsUserData* AutofillWebDataBackendImpl::GetDBUserData() { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (!user_data_) user_data_.reset(new SupportsUserDataAggregatable()); return user_data_.get(); @@ -100,7 +99,7 @@ void AutofillWebDataBackendImpl::ResetUserData() { WebDatabase::State AutofillWebDataBackendImpl::AddFormElements( const std::vector<FormFieldData>& fields, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); AutofillChangeList changes; if (!AutofillTable::FromWebDatabase(db)->AddFormFieldValues( fields, &changes)) { @@ -123,7 +122,7 @@ AutofillWebDataBackendImpl::GetFormValuesForElementName( const base::string16& prefix, int limit, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); std::vector<base::string16> values; AutofillTable::FromWebDatabase(db)->GetFormValuesForElementName( name, prefix, &values, limit); @@ -135,7 +134,7 @@ WebDatabase::State AutofillWebDataBackendImpl::RemoveFormElementsAddedBetween( const base::Time& delete_begin, const base::Time& delete_end, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); AutofillChangeList changes; if (AutofillTable::FromWebDatabase(db)->RemoveFormElementsAddedBetween( @@ -154,7 +153,7 @@ WebDatabase::State AutofillWebDataBackendImpl::RemoveFormElementsAddedBetween( WebDatabase::State AutofillWebDataBackendImpl::RemoveFormValueForElementName( const base::string16& name, const base::string16& value, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (AutofillTable::FromWebDatabase(db)->RemoveFormElement(name, value)) { AutofillChangeList changes; @@ -172,7 +171,7 @@ WebDatabase::State AutofillWebDataBackendImpl::RemoveFormValueForElementName( WebDatabase::State AutofillWebDataBackendImpl::AddAutofillProfile( const AutofillProfile& profile, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (!AutofillTable::FromWebDatabase(db)->AddAutofillProfile(profile)) { NOTREACHED(); return WebDatabase::COMMIT_NOT_NEEDED; @@ -189,7 +188,7 @@ WebDatabase::State AutofillWebDataBackendImpl::AddAutofillProfile( WebDatabase::State AutofillWebDataBackendImpl::UpdateAutofillProfile( const AutofillProfile& profile, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); // Only perform the update if the profile exists. It is currently // valid to try to update a missing profile. We simply drop the write and // the caller will detect this on the next refresh. @@ -214,7 +213,7 @@ WebDatabase::State AutofillWebDataBackendImpl::UpdateAutofillProfile( WebDatabase::State AutofillWebDataBackendImpl::RemoveAutofillProfile( const std::string& guid, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); std::unique_ptr<AutofillProfile> profile = AutofillTable::FromWebDatabase(db)->GetAutofillProfile(guid); if (!profile) { @@ -237,7 +236,7 @@ WebDatabase::State AutofillWebDataBackendImpl::RemoveAutofillProfile( std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetAutofillProfiles( WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); std::vector<std::unique_ptr<AutofillProfile>> profiles; AutofillTable::FromWebDatabase(db)->GetAutofillProfiles(&profiles); return std::unique_ptr<WDTypedResult>( @@ -247,7 +246,7 @@ std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetAutofillProfiles( std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetServerProfiles( WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); std::vector<std::unique_ptr<AutofillProfile>> profiles; AutofillTable::FromWebDatabase(db)->GetServerProfiles(&profiles); return std::unique_ptr<WDTypedResult>( @@ -260,7 +259,7 @@ AutofillWebDataBackendImpl::GetCountOfValuesContainedBetween( const base::Time& begin, const base::Time& end, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); int value = AutofillTable::FromWebDatabase(db) ->GetCountOfValuesContainedBetween(begin, end); return std::unique_ptr<WDTypedResult>( @@ -270,7 +269,7 @@ AutofillWebDataBackendImpl::GetCountOfValuesContainedBetween( WebDatabase::State AutofillWebDataBackendImpl::UpdateAutofillEntries( const std::vector<AutofillEntry>& autofill_entries, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (!AutofillTable::FromWebDatabase(db) ->UpdateAutofillEntries(autofill_entries)) return WebDatabase::COMMIT_NOT_NEEDED; @@ -280,7 +279,7 @@ WebDatabase::State AutofillWebDataBackendImpl::UpdateAutofillEntries( WebDatabase::State AutofillWebDataBackendImpl::AddCreditCard( const CreditCard& credit_card, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (!AutofillTable::FromWebDatabase(db)->AddCreditCard(credit_card)) { NOTREACHED(); return WebDatabase::COMMIT_NOT_NEEDED; @@ -295,7 +294,7 @@ WebDatabase::State AutofillWebDataBackendImpl::AddCreditCard( WebDatabase::State AutofillWebDataBackendImpl::UpdateCreditCard( const CreditCard& credit_card, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); // It is currently valid to try to update a missing profile. We simply drop // the write and the caller will detect this on the next refresh. std::unique_ptr<CreditCard> original_credit_card = @@ -317,7 +316,7 @@ WebDatabase::State AutofillWebDataBackendImpl::UpdateCreditCard( WebDatabase::State AutofillWebDataBackendImpl::RemoveCreditCard( const std::string& guid, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (!AutofillTable::FromWebDatabase(db)->RemoveCreditCard(guid)) { NOTREACHED(); return WebDatabase::COMMIT_NOT_NEEDED; @@ -333,7 +332,7 @@ WebDatabase::State AutofillWebDataBackendImpl::RemoveCreditCard( WebDatabase::State AutofillWebDataBackendImpl::AddFullServerCreditCard( const CreditCard& credit_card, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (!AutofillTable::FromWebDatabase(db)->AddFullServerCreditCard( credit_card)) { NOTREACHED(); @@ -349,7 +348,7 @@ WebDatabase::State AutofillWebDataBackendImpl::AddFullServerCreditCard( std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetCreditCards( WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); std::vector<std::unique_ptr<CreditCard>> credit_cards; AutofillTable::FromWebDatabase(db)->GetCreditCards(&credit_cards); return std::unique_ptr<WDTypedResult>( @@ -359,7 +358,7 @@ std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetCreditCards( std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetServerCreditCards( WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); std::vector<std::unique_ptr<CreditCard>> credit_cards; AutofillTable::FromWebDatabase(db)->GetServerCreditCards(&credit_cards); return std::unique_ptr<WDTypedResult>( @@ -371,7 +370,7 @@ WebDatabase::State AutofillWebDataBackendImpl::UnmaskServerCreditCard( const CreditCard& card, const base::string16& full_number, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (AutofillTable::FromWebDatabase(db)->UnmaskServerCreditCard( card, full_number)) return WebDatabase::COMMIT_NEEDED; @@ -382,7 +381,7 @@ WebDatabase::State AutofillWebDataBackendImpl::MaskServerCreditCard( const std::string& id, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (AutofillTable::FromWebDatabase(db)->MaskServerCreditCard(id)) return WebDatabase::COMMIT_NEEDED; return WebDatabase::COMMIT_NOT_NEEDED; @@ -391,7 +390,7 @@ WebDatabase::State WebDatabase::State AutofillWebDataBackendImpl::UpdateServerCardMetadata( const CreditCard& card, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (!AutofillTable::FromWebDatabase(db)->UpdateServerCardMetadata(card)) return WebDatabase::COMMIT_NOT_NEEDED; @@ -406,7 +405,7 @@ WebDatabase::State AutofillWebDataBackendImpl::UpdateServerCardMetadata( WebDatabase::State AutofillWebDataBackendImpl::UpdateServerAddressMetadata( const AutofillProfile& profile, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (!AutofillTable::FromWebDatabase(db)->UpdateServerAddressMetadata( profile)) { return WebDatabase::COMMIT_NOT_NEEDED; @@ -422,7 +421,7 @@ WebDatabase::State AutofillWebDataBackendImpl::UpdateServerAddressMetadata( WebDatabase::State AutofillWebDataBackendImpl::ClearAllServerData( WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); if (AutofillTable::FromWebDatabase(db)->ClearAllServerData()) { NotifyOfMultipleAutofillChanges(); return WebDatabase::COMMIT_NEEDED; @@ -435,7 +434,7 @@ WebDatabase::State const base::Time& delete_begin, const base::Time& delete_end, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); std::vector<std::string> profile_guids; std::vector<std::string> credit_card_guids; if (AutofillTable::FromWebDatabase(db)->RemoveAutofillDataModifiedBetween( @@ -466,7 +465,7 @@ WebDatabase::State AutofillWebDataBackendImpl::RemoveOriginURLsModifiedBetween( const base::Time& delete_begin, const base::Time& delete_end, WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); std::vector<std::unique_ptr<AutofillProfile>> profiles; if (!AutofillTable::FromWebDatabase(db)->RemoveOriginURLsModifiedBetween( delete_begin, delete_end, &profiles)) { @@ -486,7 +485,7 @@ WebDatabase::State AutofillWebDataBackendImpl::RemoveOriginURLsModifiedBetween( WebDatabase::State AutofillWebDataBackendImpl::RemoveExpiredFormElementsImpl( WebDatabase* db) { - DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); + DCHECK(owning_task_runner()->RunsTasksInCurrentSequence()); AutofillChangeList changes; if (AutofillTable::FromWebDatabase(db)->RemoveExpiredFormElements(&changes)) { diff --git a/chromium/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.h b/chromium/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.h index 3720bd72214..9fcbc877a4b 100644 --- a/chromium/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.h +++ b/chromium/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.h @@ -202,9 +202,6 @@ class AutofillWebDataBackendImpl // The task runner that this class uses for its UI tasks. scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_; - // The task runner that this class uses for its DB tasks. - scoped_refptr<base::SingleThreadTaskRunner> db_task_runner_; - // Storage for user data to be accessed only on the DB sequence. May // be used e.g. for SyncableService subclasses that need to be owned // by this object. Is created on first call to |GetDBUserData()|. |