File: content_password_manager_driver.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (704 lines) | stat: -rw-r--r-- 27,220 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/password_manager/content/browser/content_password_manager_driver.h"

#include <utility>

#include "base/metrics/histogram_macros.h"
#include "components/autofill/content/browser/content_autofill_client.h"
#include "components/autofill/content/browser/content_autofill_driver.h"
#include "components/autofill/core/browser/logging/log_manager.h"
#include "components/autofill/core/browser/logging/log_router.h"
#include "components/autofill/core/common/aliases.h"
#include "components/autofill/core/common/form_data.h"
#include "components/autofill/core/common/unique_ids.h"
#include "components/password_manager/content/browser/bad_message.h"
#include "components/password_manager/content/browser/content_password_manager_driver_factory.h"
#include "components/password_manager/content/browser/form_meta_data.h"
#include "components/password_manager/core/browser/browser_save_password_progress_logger.h"
#include "components/password_manager/core/browser/password_manager.h"
#include "components/password_manager/core/browser/password_manager_client.h"
#include "components/password_manager/core/browser/password_manager_metrics_recorder.h"
#include "components/password_manager/core/browser/password_suggestion_generator.h"
#include "components/password_manager/core/common/password_manager_features.h"
#include "components/safe_browsing/buildflags.h"
#include "content/public/browser/back_forward_cache.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_constants.h"
#include "mojo/public/cpp/bindings/message.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"

using autofill::mojom::FocusedFieldType;

namespace password_manager {

namespace {

gfx::RectF TransformToRootCoordinates(
    content::RenderFrameHost* render_frame_host,
    const gfx::RectF& bounds_in_frame_coordinates) {
  content::RenderWidgetHostView* rwhv = render_frame_host->GetView();
  if (!rwhv)
    return bounds_in_frame_coordinates;
  return gfx::RectF(rwhv->TransformPointToRootCoordSpaceF(
                        bounds_in_frame_coordinates.origin()),
                    bounds_in_frame_coordinates.size());
}

void LogSiteIsolationMetricsForSubmittedForm(
    content::RenderFrameHost* render_frame_host) {
  UMA_HISTOGRAM_BOOLEAN(
      "SiteIsolation.IsPasswordFormSubmittedInDedicatedProcess",
      render_frame_host->GetSiteInstance()->RequiresDedicatedProcess());
}

bool HasValidURL(content::RenderFrameHost* render_frame_host) {
  GURL url = GetURLFromRenderFrameHost(render_frame_host);

  // URL might be invalid when GetLastCommittedOrigin is opaque.
  if (!url.is_valid())
    return false;

  return password_manager::bad_message::CheckForIllegalURL(
      render_frame_host, url,
      password_manager::BadMessageReason::CPMD_BAD_ORIGIN_FORM_SUBMITTED);
}

bool IsRenderFrameHostSupported(content::RenderFrameHost* rfh) {
  // Explanation of current PasswordManagerDriver limitations:
  // * Currently, PasswordManagerDriver binding has RenderFrameHost lifetime,
  //   not document lifetime. This can lead to premature binding in rare race
  //   conditions (see https://crbug.com/329989911).
  // * Due to this, we can't reliably determine if the document will be
  //   credentialless at this stage. Returning 'false' speculatively would be
  //   destructive.
  // * Workaround: Temporarily return 'true'; the function will be re-evaluated
  //   on commit via `DidNavigate`.
  //
  // TODO(https://crbug.com/40615943): After RenderDocument is enabled, consider
  // simplifying by binding PasswordManagerDriver via `PopulateFrameBinders`
  // instead of `RegisterAssociatedInterfaceBindersForRenderFrameHost`.
  if (rfh->GetLifecycleState() ==
      content::RenderFrameHost::LifecycleState::kPendingCommit) {
    return true;
  }

  if (rfh->GetLifecycleState() ==
      content::RenderFrameHost::LifecycleState::kPrerendering) {
    return false;
  }

  // [spec] https://wicg.github.io/anonymous-iframe/#spec-autofill
  // > Browsers that implement autofill or password manager functionalities
  //   should make them unavailable in credentialless iframes.
  if (rfh->IsCredentialless()) {
    return false;
  }

  return true;
}

}  // namespace

ContentPasswordManagerDriver::ContentPasswordManagerDriver(
    content::RenderFrameHost* render_frame_host,
    PasswordManagerClient* client)
    : render_frame_host_(render_frame_host),
      client_(client),
      password_generation_helper_(client, this),
      password_autofill_manager_(
          this,
          autofill::ContentAutofillClient::FromWebContents(
              content::WebContents::FromRenderFrameHost(render_frame_host)),
          client) {
  static unsigned next_free_id = 0;
  id_ = next_free_id++;

  render_frame_host_->GetRemoteAssociatedInterfaces()->GetInterface(
      &password_autofill_agent_);

  // For some frames `this` may be instantiated before log manager creation, so
  // here we can not send logging state to renderer process for them. For such
  // cases, after the log manager got ready later,
  // ContentPasswordManagerDriverFactory::RequestSendLoggingAvailability() will
  // call ContentPasswordManagerDriver::SendLoggingAvailability() on `this` to
  // do it actually.
  if (autofill::LogManager* log_manager = client_->GetCurrentLogManager()) {
    // RenderFrameHost might be a speculative one: it hasn't committed its
    // document. We don't know if its is safe to use the whole
    // PasswordAutofillAgent interface. For this reason, we use directly
    // `password_autofill_agent_`, as opposed to `GetPasswordAutofillAgent()`.
    // We know the `SetLoggingState()` is safe to be called no matter the state
    // of the RenderFrameHost.
    password_autofill_agent_->SetLoggingState(log_manager->IsLoggingActive());
  }
}

ContentPasswordManagerDriver::~ContentPasswordManagerDriver() = default;

// static
ContentPasswordManagerDriver*
ContentPasswordManagerDriver::GetForRenderFrameHost(
    content::RenderFrameHost* render_frame_host) {
  ContentPasswordManagerDriverFactory* factory =
      ContentPasswordManagerDriverFactory::FromWebContents(
          content::WebContents::FromRenderFrameHost(render_frame_host));
  return factory ? factory->GetDriverForFrame(
                       render_frame_host,
                       base::PassKey<ContentPasswordManagerDriver>())
                 : nullptr;
}

void ContentPasswordManagerDriver::BindPendingReceiver(
    mojo::PendingAssociatedReceiver<autofill::mojom::PasswordManagerDriver>
        pending_receiver) {
  if (IsRenderFrameHostSupported(render_frame_host_)) {
    password_manager_receiver_.Bind(std::move(pending_receiver));
  }
}

void ContentPasswordManagerDriver::DidNavigate() {
  if (!IsRenderFrameHostSupported(render_frame_host_)) {
    password_manager_receiver_.reset();
  }
}

int ContentPasswordManagerDriver::GetId() const {
  return id_;
}

int ContentPasswordManagerDriver::GetFrameId() const {
  // Use the associated FrameTreeNode ID as the Frame ID.
  return render_frame_host_->GetFrameTreeNodeId().value();
}

void ContentPasswordManagerDriver::PropagateFillDataOnParsingCompletion(
    const autofill::PasswordFormFillData& form_data) {
  password_autofill_manager_.OnAddPasswordFillData(form_data);
  if (const auto& agent = GetPasswordAutofillAgent()) {
    agent->ApplyFillDataOnParsingCompletion(
        autofill::MaybeClearPasswordValues(form_data));
  }
}

void ContentPasswordManagerDriver::InformNoSavedCredentials(
    bool should_show_popup_without_passwords) {
  if (const auto& agent = GetPasswordAutofillAgent()) {
    agent->InformNoSavedCredentials(should_show_popup_without_passwords);
  }
}

void ContentPasswordManagerDriver::FormEligibleForGenerationFound(
    const autofill::PasswordFormGenerationData& form) {
  if (GetPasswordGenerationHelper()->IsGenerationEnabled(
          /*log_debug_data=*/true)) {
    GetPasswordGenerationAgent()->FoundFormEligibleForGeneration(form);
  }
}

void ContentPasswordManagerDriver::GeneratedPasswordAccepted(
    const std::u16string& password) {
  // Same check as in PasswordGenerationAgent::GeneratedPasswordAccepted. The
  // generated password can't be too short.
  CHECK_LE(4u, password.size());
  GetPasswordGenerationAgent()->GeneratedPasswordAccepted(password);
}

void ContentPasswordManagerDriver::GeneratedPasswordAccepted(
    const autofill::FormData& raw_form,
    autofill::FieldRendererId generation_element_id,
    const std::u16string& password) {
  // In case we can't obtain a valid URL or a frame isn't allowed to perform an
  // operation with generated URL, don't forward anything to password manager.
  // TODO(crbug.com/40191770): Test that PasswordManager doesn't receive url
  // and full_url from renderer.
  if (!HasValidURL(render_frame_host_))
    return;

  GetPasswordManager()->OnGeneratedPasswordAccepted(
      this, GetFormWithFrameAndFormMetaData(render_frame_host_, raw_form),
      generation_element_id, password);
}

void ContentPasswordManagerDriver::GeneratedPasswordRejected() {
  GetPasswordGenerationAgent()->GeneratedPasswordRejected();
}

void ContentPasswordManagerDriver::FocusNextFieldAfterPasswords() {
  GetPasswordGenerationAgent()->FocusNextFieldAfterPasswords();
}

void ContentPasswordManagerDriver::FillField(
    const std::u16string& value,
    autofill::AutofillSuggestionTriggerSource suggestion_source) {
  if (const auto& agent = GetPasswordAutofillAgent()) {
    LogFilledFieldType();
    agent->FillField(last_triggering_field_id_, value, suggestion_source);
  }
}

void ContentPasswordManagerDriver::FillChangePasswordForm(
    autofill::FieldRendererId password_element_id,
    autofill::FieldRendererId new_password_element_id,
    autofill::FieldRendererId confirm_password_element_id,
    const std::u16string& old_password,
    const std::u16string& new_password,
    base::OnceCallback<void(const std::optional<autofill::FormData>&)>
        form_data_callback) {
  if (const auto& agent = GetPasswordAutofillAgent()) {
    LogFilledFieldType();
    agent->FillChangePasswordForm(
        password_element_id, new_password_element_id,
        confirm_password_element_id, old_password, new_password,
        base::BindOnce(
            &ContentPasswordManagerDriver::OnChangePasswordFormFilled,
            weak_factory_.GetWeakPtr(), std::move(form_data_callback)));
  }
}

void ContentPasswordManagerDriver::SubmitFormWithEnter(
    autofill::FieldRendererId field,
    base::OnceCallback<void(bool)> success_callback) {
  if (const auto& agent = GetPasswordAutofillAgent()) {
    agent->SubmitFormWithEnter(field, std::move(success_callback));
  }
}

void ContentPasswordManagerDriver::FillSuggestion(
    const std::u16string& username,
    const std::u16string& password,
    base::OnceCallback<void(bool)> success_callback) {
  LogFilledFieldType();
  GetPasswordAutofillAgent()->FillPasswordSuggestion(
      username, password, std::move(success_callback));
}

void ContentPasswordManagerDriver::FillSuggestionById(
    autofill::FieldRendererId username_element_id,
    autofill::FieldRendererId password_element_id,
    const std::u16string& username,
    const std::u16string& password,
    autofill::AutofillSuggestionTriggerSource suggestion_source) {
  LogFilledFieldType();
  GetPasswordAutofillAgent()->FillPasswordSuggestionById(
      username_element_id, password_element_id, username, password,
      suggestion_source);
}

void ContentPasswordManagerDriver::FillIntoFocusedField(
    bool is_password,
    const std::u16string& credential) {
  if (const auto& agent = GetPasswordAutofillAgent()) {
    LogFilledFieldType();
    agent->FillIntoFocusedField(is_password, credential);
  }
}

#if BUILDFLAG(IS_ANDROID)
void ContentPasswordManagerDriver::TriggerFormSubmission() {
  GetPasswordAutofillAgent()->TriggerFormSubmission();
}
#endif

void ContentPasswordManagerDriver::PreviewField(
    autofill::FieldRendererId field_id,
    const std::u16string& value) {
  if (const auto& agent = GetPasswordAutofillAgent()) {
    agent->PreviewField(field_id, value);
  }
}

void ContentPasswordManagerDriver::PreviewSuggestion(
    const std::u16string& username,
    const std::u16string& password) {
  GetAutofillAgent()->PreviewPasswordSuggestion(username, password);
}

void ContentPasswordManagerDriver::PreviewSuggestionById(
    autofill::FieldRendererId username_element_id,
    autofill::FieldRendererId password_element_id,
    const std::u16string& username,
    const std::u16string& password) {
  GetPasswordAutofillAgent()->PreviewPasswordSuggestionById(
      username_element_id, password_element_id, username, password);
}

void ContentPasswordManagerDriver::PreviewGenerationSuggestion(
    const std::u16string& password) {
  GetAutofillAgent()->PreviewPasswordGenerationSuggestion(password);
}

void ContentPasswordManagerDriver::ClearPreviewedForm() {
  GetAutofillAgent()->ClearPreviewedForm();
}

void ContentPasswordManagerDriver::SetSuggestionAvailability(
    autofill::FieldRendererId element_id,
    autofill::mojom::AutofillSuggestionAvailability suggestion_availability) {
  GetAutofillAgent()->SetSuggestionAvailability(element_id,
                                                suggestion_availability);
}

PasswordGenerationFrameHelper*
ContentPasswordManagerDriver::GetPasswordGenerationHelper() {
  return &password_generation_helper_;
}

PasswordManagerInterface* ContentPasswordManagerDriver::GetPasswordManager() {
  return client_->GetPasswordManager();
}

PasswordAutofillManager*
ContentPasswordManagerDriver::GetPasswordAutofillManager() {
  return &password_autofill_manager_;
}

void ContentPasswordManagerDriver::SendLoggingAvailability() {
  if (const auto& agent = GetPasswordAutofillAgent()) {
    autofill::LogManager* log_manager = client_->GetCurrentLogManager();
    agent->SetLoggingState(log_manager && log_manager->IsLoggingActive());
  }
}

bool ContentPasswordManagerDriver::IsInPrimaryMainFrame() const {
  return render_frame_host_->IsInPrimaryMainFrame();
}

bool ContentPasswordManagerDriver::CanShowAutofillUi() const {
  // Don't show AutofillUi for inactive RenderFrameHost.
  return render_frame_host_->IsActive();
}

const GURL& ContentPasswordManagerDriver::GetLastCommittedURL() const {
  return render_frame_host_->GetLastCommittedURL();
}

void ContentPasswordManagerDriver::AnnotateFieldsWithParsingResult(
    const autofill::ParsingResult& parsing_result) {
  if (const auto& agent = GetPasswordAutofillAgent()) {
    agent->AnnotateFieldsWithParsingResult(parsing_result);
  }
}

base::WeakPtr<password_manager::PasswordManagerDriver>
ContentPasswordManagerDriver::AsWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

void ContentPasswordManagerDriver::GeneratePassword(
    autofill::mojom::PasswordGenerationAgent::TriggeredGeneratePasswordCallback
        callback) {
  GetPasswordGenerationAgent()->TriggeredGeneratePassword(std::move(callback));
}

bool ContentPasswordManagerDriver::IsPasswordFieldForPasswordManager(
    autofill::FieldRendererId field_renderer_id,
    std::optional<blink::mojom::FormControlType> form_control_type) {
  if (form_control_type == blink::mojom::FormControlType::kInputPassword) {
    return true;
  }
  password_manager::PasswordGenerationFrameHelper*
      password_generation_frame_helper = GetPasswordGenerationHelper();
  if (!password_generation_frame_helper) {
    return false;
  }
  return password_generation_frame_helper->IsManualGenerationEnabledField(
      field_renderer_id);
}

void ContentPasswordManagerDriver::PasswordFormsParsed(
    const std::vector<autofill::FormData>& raw_forms) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_))
    return;

  // In case we can't obtain a valid URL or a frame isn't allowed to perform an
  // operation with generated URL, don't forward anything to password manager.
  if (!HasValidURL(render_frame_host_))
    return;

  autofill::LogManager* log_manager = client_->GetCurrentLogManager();
  std::unique_ptr<BrowserSavePasswordProgressLogger> logger;
  if (log_manager && log_manager->IsLoggingActive()) {
    logger = std::make_unique<BrowserSavePasswordProgressLogger>(log_manager);
  }
  std::vector<autofill::FormData> forms = raw_forms;
  for (auto& form : forms) {
    SetFrameAndFormMetaData(render_frame_host_, form);
    if (logger) {
      logger->LogFormData(
          BrowserSavePasswordProgressLogger::STRING_FORM_IS_PASSWORD, form);
    }
  }

  GetPasswordManager()->OnPasswordFormsParsed(this, forms);
}

void ContentPasswordManagerDriver::PasswordFormsRendered(
    const std::vector<autofill::FormData>& raw_forms) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_))
    return;

  // In case we can't obtain a valid URL or a frame isn't allowed to perform an
  // operation with generated URL, don't forward anything to password manager.
  if (!HasValidURL(render_frame_host_))
    return;

  std::vector<autofill::FormData> forms = raw_forms;
  for (auto& form : forms)
    SetFrameAndFormMetaData(render_frame_host_, form);

  GetPasswordManager()->OnPasswordFormsRendered(this, forms);
}

void ContentPasswordManagerDriver::PasswordFormSubmitted(
    const autofill::FormData& raw_form) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_))
    return;

  // In case we can't obtain a valid URL or a frame isn't allowed to perform an
  // operation with generated URL, don't forward anything to password manager.
  if (!HasValidURL(render_frame_host_))
    return;

  GetPasswordManager()->OnPasswordFormSubmitted(
      this, GetFormWithFrameAndFormMetaData(render_frame_host_, raw_form));

  LogSiteIsolationMetricsForSubmittedForm(render_frame_host_);
}

void ContentPasswordManagerDriver::InformAboutUserInput(
    const autofill::FormData& raw_form) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_))
    return;

  // In case we can't obtain a valid URL or a frame isn't allowed to perform an
  // operation with generated URL, don't forward anything to password manager.
  // TODO(crbug.com/40191770): Test that PasswordManager doesn't receive url
  // and full_url from renderer.
  if (!HasValidURL(render_frame_host_))
    return;

  autofill::FormData form_data =
      GetFormWithFrameAndFormMetaData(render_frame_host_, raw_form);
  GetPasswordManager()->OnInformAboutUserInput(this, form_data);

  if (FormHasNonEmptyPasswordField(form_data) &&
      client_->IsIsolationForPasswordSitesEnabled()) {
    // This function signals that a password field has been filled (whether by
    // the user, JS, autofill, or some other means) or a password form has been
    // submitted. Use this as a heuristic to start site-isolating the form's
    // site. This is intended to be used primarily when full site isolation is
    // not used, such as on Android.
    content::SiteInstance::StartIsolatingSite(
        render_frame_host_->GetSiteInstance()->GetBrowserContext(),
        form_data.url(),
        content::ChildProcessSecurityPolicy::IsolatedOriginSource::
            USER_TRIGGERED);
  }
}

void ContentPasswordManagerDriver::DynamicFormSubmission(
    autofill::mojom::SubmissionIndicatorEvent submission_indication_event) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_))
    return;
  GetPasswordManager()->OnDynamicFormSubmission(this,
                                                submission_indication_event);
  LogSiteIsolationMetricsForSubmittedForm(render_frame_host_);
}

void ContentPasswordManagerDriver::PasswordFormCleared(
    const autofill::FormData& raw_form) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_))
    return;

  // In case we can't obtain a valid URL or a frame isn't allowed to perform an
  // operation with generated URL, don't forward anything to password manager.
  if (!HasValidURL(render_frame_host_))
    return;

  GetPasswordManager()->OnPasswordFormCleared(
      this, GetFormWithFrameAndFormMetaData(render_frame_host_, raw_form));
}

void ContentPasswordManagerDriver::RecordSavePasswordProgress(
    const std::string& log) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_))
    return;
  // Skip messages from chrome:// URLs as they are just noise for
  // chrome://password-manager-internals based debugging.
  if (GetLastCommittedURL().SchemeIs(content::kChromeUIScheme))
    return;
  LOG_AF(client_->GetCurrentLogManager())
      << autofill::Tag{"div"}
      << autofill::Attrib{"class", "preserve-white-space"} << log
      << autofill::CTag{"div"};
}

void ContentPasswordManagerDriver::UserModifiedPasswordField() {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_))
    return;
  if (client_->GetMetricsRecorder())
    client_->GetMetricsRecorder()->RecordUserModifiedPasswordField();
  // A user has modified an input field, it wouldn't be a submission "after
  // Touch To Fill".
  client_->ResetSubmissionTrackingAfterTouchToFill();
}

void ContentPasswordManagerDriver::UserModifiedNonPasswordField(
    autofill::FieldRendererId renderer_id,
    const std::u16string& value,
    bool autocomplete_attribute_has_username,
    bool is_likely_otp) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_))
    return;
  GetPasswordManager()->OnUserModifiedNonPasswordField(
      this, renderer_id, value, autocomplete_attribute_has_username,
      is_likely_otp);
  // A user has modified an input field, it wouldn't be a submission "after
  // Touch To Fill".
  client_->ResetSubmissionTrackingAfterTouchToFill();
}

void ContentPasswordManagerDriver::ShowPasswordSuggestions(
    const autofill::PasswordSuggestionRequest& request) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_))
    return;

  if ((request.username_field_index > request.form_data.fields().size()) ||
      (request.password_field_index > request.form_data.fields().size())) {
    mojo::ReportBadMessage(
        "username_field_index or password_field_index cannot be greater than "
        "form.fields.size()!");
  }

  last_triggering_field_id_ = request.field.element_id;

#if !BUILDFLAG(IS_ANDROID)
  ShowPasswordSuggestionsForField(request.field);
#else
  client_->ShowKeyboardReplacingSurface(this, request);
#endif  // !BUILDFLAG(IS_ANDROID)
}

void ContentPasswordManagerDriver::ShowPasswordSuggestionsForField(
    const autofill::TriggeringField& triggering_field) {
  GetPasswordAutofillManager()->OnShowPasswordSuggestions(
      triggering_field.element_id, triggering_field.trigger_source,
      triggering_field.text_direction, triggering_field.typed_username,
      ShowWebAuthnCredentials(triggering_field.show_webauthn_credentials),
      ShowIdentityCredentials(triggering_field.show_identity_credentials),
      TransformToRootCoordinates(render_frame_host_, triggering_field.bounds));
}

void ContentPasswordManagerDriver::CheckSafeBrowsingReputation(
    const GURL& form_action,
    const GURL& frame_url) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_))
    return;
#if defined(ON_FOCUS_PING_ENABLED) && BUILDFLAG(SAFE_BROWSING_AVAILABLE)
  client_->CheckSafeBrowsingReputation(form_action, frame_url);
#endif
}

void ContentPasswordManagerDriver::FocusedInputChanged(
    autofill::FieldRendererId focused_field_id,
    FocusedFieldType focused_field_type) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_)) {
    return;
  }
  GetPasswordAutofillManager()->FocusedInputChanged();
  client_->FocusedInputChanged(this, focused_field_id, focused_field_type);
}

void ContentPasswordManagerDriver::LogFirstFillingResult(
    autofill::FormRendererId form_renderer_id,
    int32_t result) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_))
    return;
  GetPasswordManager()->LogFirstFillingResult(this, form_renderer_id, result);
}

void ContentPasswordManagerDriver::LogFilledFieldType() {
  bool field_classified_as_target_filling_password =
      GetPasswordManager()->GetPasswordFormCache()->GetPasswordForm(
          this, last_triggering_field_id_);
  base::UmaHistogramBoolean("Autofill.FilledFieldType.Password",
                            field_classified_as_target_filling_password);
}

const mojo::AssociatedRemote<autofill::mojom::AutofillAgent>&
ContentPasswordManagerDriver::GetAutofillAgent() {
  autofill::ContentAutofillDriver* autofill_driver =
      autofill::ContentAutofillDriver::GetForRenderFrameHost(
          render_frame_host_);
  DCHECK(autofill_driver);
  return autofill_driver->GetAutofillAgent();
}

const mojo::AssociatedRemote<autofill::mojom::PasswordAutofillAgent>&
ContentPasswordManagerDriver::GetPasswordAutofillAgent() {
  // Autofill is not expected to interact with a RenderFrameHost that hasn't yet
  // committed its document.
  CHECK_NE(render_frame_host_->GetLifecycleState(),
           content::RenderFrameHost::LifecycleState::kPendingCommit);

  return IsRenderFrameHostSupported(render_frame_host_)
             ? password_autofill_agent_
             : password_autofill_agent_unbound_;
}

const mojo::AssociatedRemote<autofill::mojom::PasswordGenerationAgent>&
ContentPasswordManagerDriver::GetPasswordGenerationAgent() {
  DCHECK(!password_gen_agent_ ||
         (content::RenderFrameHost::LifecycleState::kPrerendering !=
          render_frame_host_->GetLifecycleState()));
  if (!password_gen_agent_) {
    render_frame_host_->GetRemoteAssociatedInterfaces()->GetInterface(
        &password_gen_agent_);
  }

  return password_gen_agent_;
}

void ContentPasswordManagerDriver::OnChangePasswordFormFilled(
    base::OnceCallback<void(const std::optional<autofill::FormData>&)>
        form_data_callback,
    const std::optional<autofill::FormData>& raw_form) {
  if (!password_manager::bad_message::CheckFrameNotPrerendering(
          render_frame_host_)) {
    return;
  }

  // In case we can't obtain a valid URL or a frame isn't allowed to perform an
  // operation with generated URL, don't forward anything to password manager.
  if (!HasValidURL(render_frame_host_)) {
    return;
  }
  std::move(form_data_callback)
      .Run(raw_form ? GetFormWithFrameAndFormMetaData(render_frame_host_,
                                                      raw_form.value())
                    : raw_form);
}

}  // namespace password_manager