File: autofill_driver_router.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 (673 lines) | stat: -rw-r--r-- 27,768 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
// Copyright 2021 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/autofill/core/browser/foundations/autofill_driver_router.h"

#include <algorithm>
#include <functional>

#include "base/check_deref.h"
#include "base/containers/contains.h"
#include "base/containers/to_vector.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/time/time.h"
#include "base/types/optional_ref.h"
#include "base/types/zip.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/autofill/core/common/mojom/autofill_types.mojom-shared.h"
#include "components/autofill/core/common/password_form_fill_data.h"
#include "components/autofill/core/common/signatures.h"
#include "components/autofill/core/common/unique_ids.h"

namespace autofill {

namespace {

// Calls |fun| for all drivers in |form_forest|.
void ForEachFrame(internal::FormForest& form_forest,
                  base::FunctionRef<void(AutofillDriver&)> fun) {
  for (const std::unique_ptr<internal::FormForest::FrameData>& some_frame :
       form_forest.frame_datas()) {
    if (some_frame->driver) {
      std::invoke(fun, *some_frame->driver);
    }
  }
}

}  // namespace

AutofillDriverRouter::AutofillDriverRouter() = default;
AutofillDriverRouter::~AutofillDriverRouter() {
  base::UmaHistogramCounts1000("Autofill.NumberOfFramesPerFormForest",
                               max_frame_datas_);
}

AutofillDriver* AutofillDriverRouter::DriverOfFrame(LocalFrameToken frame) {
  const auto& frames = form_forest_.frame_datas();
  max_frame_datas_ = std::max(max_frame_datas_, frames.size());
  auto it = frames.find(frame);
  return it != frames.end() ? static_cast<AutofillDriver*>((*it)->driver.get())
                            : nullptr;
}

void AutofillDriverRouter::UnregisterDriver(AutofillDriver& driver,
                                            bool driver_is_dying) {
  // TODO: crbug.com/365097975 - Remove the crash keys.
  bool found_token = false;
  bool found_token_has_driver = false;
  bool found_token_has_right_driver = false;
  bool found_driver = false;
  bool found_driver_right_token = false;
  bool found_driver_deleted = false;
  if (auto it = form_forest_.frame_datas().find(driver.GetFrameToken());
      it != form_forest_.frame_datas().end()) {
    found_token = true;
    found_token_has_driver = (*it)->driver != nullptr;
    found_token_has_right_driver = (*it)->driver == &driver;
  }
  SCOPED_CRASH_KEY_NUMBER("Autofill", "num_frame_datas_before",
                          form_forest_.frame_datas().size());
  for (const std::unique_ptr<internal::FormForest::FrameData>& frame :
       form_forest_.frame_datas()) {
    if (frame->driver == &driver) {
      found_driver = true;
      found_driver_right_token = frame->frame_token == driver.GetFrameToken();
      form_forest_.EraseFormsOfFrame(frame->frame_token,
                                     /*keep_frame=*/!driver_is_dying);
      found_driver_deleted =
          !form_forest_.frame_datas().contains(driver.GetFrameToken());
      break;
    }
  }
  SCOPED_CRASH_KEY_NUMBER("Autofill", "num_frame_datas_after",
                          form_forest_.frame_datas().size());
  SCOPED_CRASH_KEY_BOOL("Autofill", "found_token", found_token);
  SCOPED_CRASH_KEY_BOOL("Autofill", "found_token_has_driver",
                        found_token_has_driver);
  SCOPED_CRASH_KEY_BOOL("Autofill", "found_token_has_right_driver",
                        found_token_has_right_driver);
  SCOPED_CRASH_KEY_BOOL("Autofill", "found_driver", found_driver);
  SCOPED_CRASH_KEY_BOOL("Autofill", "found_driver_right_token",
                        found_driver_right_token);
  SCOPED_CRASH_KEY_BOOL("Autofill", "found_driver_deleted",
                        found_driver_deleted);
  if (driver_is_dying) {
    if (found_token_has_driver) {
      CHECK(found_driver);
      CHECK(found_driver_deleted);
    } else {
      CHECK(!found_driver);
    }
  }
}

// Routing of events called by the renderer:

// Calls TriggerFormExtraction() on all AutofillDrivers in |form_forest_| as
// well as their ancestor AutofillDrivers.
//
// An ancestor might not be contained in the form tree known to FormForest: if
// the ancestor contained only invisible iframe(s) and no interesting fields, it
// would not be sent to the browser. In the meantime, these frames may have
// become visible. Therefore, we also call TriggerFormExtraction() in all
// ancestors.
//
// The typical use case is that some frame triggers form extractions on its own
// initiative and triggers an event. Then AutofillDriverRouter's event handler
// tells the other frames to form extraction, too, using
// TriggerFormExtractionExcept(source).
void AutofillDriverRouter::TriggerFormExtractionExcept(
    AutofillDriver& exception) {
#if BUILDFLAG(IS_IOS)
  if (!base::FeatureList::IsEnabled(
          autofill::features::kAutofillAcrossIframesIosTriggerFormExtraction)) {
    return;
  }
#endif
  // TODO(crbug.com/384874225): Cleanup that instrumentation once the feature is
  // launched on iOS.
  SCOPED_UMA_HISTOGRAM_TIMER_MICROS(
      "Autofill.DriverRouter.TriggerFormExtractionExcept.Duration");
  size_t frame_count = form_forest_.frame_datas().size();
  base::UmaHistogramCounts10000(
      "Autofill.DriverRouter.TriggerFormExtractionExcept.FrameCount",
      frame_count);
  SCOPED_CRASH_KEY_NUMBER("Autofill", "num_frame_extract_total", frame_count);
  base::flat_set<AutofillDriver*> already_triggered;
  ForEachFrame(form_forest_, [&](AutofillDriver& driver_ref) {
    AutofillDriver* driver = &driver_ref;
    do {
      SCOPED_CRASH_KEY_NUMBER("Autofill", "num_frame_extract_so_far",
                              already_triggered.size());
      if (driver == &exception) {
        continue;
      }
      if (!driver->IsActive()) {
        // The `form_forest_` may contain inactive frames because it retains
        // BFcached frames.
        continue;
      }
      if (!already_triggered.insert(driver).second) {
        // An earlier invocation of this lambda has executed the rest of this
        // loop's body for `driver` and hence also for all its ancestors.
        break;
      }
      driver->TriggerFormExtractionInDriverFrame(/*pass_key=*/{});
    } while ((driver = driver->GetParent()) != nullptr);
  });
}

void AutofillDriverRouter::FormsSeen(
    RoutedCallback<const std::vector<FormData>&,
                   const std::vector<FormGlobalId>&> callback,
    AutofillDriver& source,
    std::vector<FormData> renderer_forms,
    const std::vector<FormGlobalId>& removed_forms) {
  base::flat_set<FormGlobalId> forms_with_removed_fields =
      form_forest_.EraseForms(removed_forms);

  std::vector<FormGlobalId> renderer_form_ids =
      base::ToVector(renderer_forms, &FormData::global_id);

  for (FormData& form : renderer_forms) {
    form_forest_.UpdateTreeOfRendererForm(std::move(form), source);
  }

  // Collects the browser forms of the |renderer_forms_ids|. If all forms in
  // |renderer_forms_ids| are root forms, each of them has a different browser
  // form. Otherwise, all forms in |renderer_forms_ids| are non-root forms in
  // the same tree, and |browser_forms| will contain the flattened root of this
  // tree.
  std::vector<FormData> browser_forms;
  browser_forms.reserve(renderer_form_ids.size());
  for (FormGlobalId renderer_form_id : renderer_form_ids) {
    const FormData& browser_form =
        form_forest_.GetBrowserForm(renderer_form_id);
    if (!base::Contains(browser_forms, browser_form.global_id(),
                        &FormData::global_id)) {
      browser_forms.push_back(browser_form);
    }
  }
  DCHECK(browser_forms.size() == renderer_form_ids.size() ||
         browser_forms.size() == 1);

  for (const FormGlobalId form_id : forms_with_removed_fields) {
    const FormData& browser_form = form_forest_.GetBrowserForm(form_id);
    if (!base::Contains(browser_forms, browser_form.global_id(),
                        &FormData::global_id)) {
      browser_forms.push_back(browser_form);
    }
  }

  // Send the browser forms to the individual frames.
  if (!browser_forms.empty()) {
    LocalFrameToken frame = browser_forms.front().host_frame();
    DCHECK(std::ranges::all_of(browser_forms, [frame](const FormData& f) {
      return f.host_frame() == frame;
    }));
    AutofillDriver* target = DriverOfFrame(frame);
    callback(CHECK_DEREF(target), browser_forms, removed_forms);
  } else if (!removed_forms.empty()) {
    callback(source, {}, removed_forms);
  }
}

void AutofillDriverRouter::FormSubmitted(
    RoutedCallback<const FormData&, mojom::SubmissionSource> callback,
    AutofillDriver& source,
    FormData form,
    mojom::SubmissionSource submission_source) {
  FormGlobalId form_id = form.global_id();
  form_forest_.UpdateTreeOfRendererForm(std::move(form), source);

  const FormData& browser_form = form_forest_.GetBrowserForm(form_id);
  auto* target = DriverOfFrame(browser_form.host_frame());
  callback(CHECK_DEREF(target), browser_form, submission_source);
}

void AutofillDriverRouter::CaretMovedInFormField(
    RoutedCallback<const FormData&, const FieldGlobalId&, const gfx::Rect&>
        callback,
    AutofillDriver& source,
    FormData form,
    const FieldGlobalId& field_id,
    const gfx::Rect& caret_bounds) {
  FormGlobalId form_id = form.global_id();
  form_forest_.UpdateTreeOfRendererForm(std::move(form), source);

  const FormData& browser_form = form_forest_.GetBrowserForm(form_id);
  if (!base::Contains(browser_form.fields(), field_id,
                      &FormFieldData::global_id)) {
    // To avoid very large flattened forms, UpdateTreeOfRendererForm() may have
    // cut the tree into two and, as a result, may have lost some fields. We
    // drop such events.
    // See `kMaxVisits` in FormForest::UpdateTreeOfRendererForm() for details.
    return;
  }
  auto* target = DriverOfFrame(browser_form.host_frame());
  callback(CHECK_DEREF(target), browser_form, field_id, caret_bounds);
}

void AutofillDriverRouter::TextFieldValueChanged(
    RoutedCallback<const FormData&, const FieldGlobalId&, base::TimeTicks>
        callback,
    AutofillDriver& source,
    FormData form,
    const FieldGlobalId& field_id,
    base::TimeTicks timestamp) {
  FormGlobalId form_id = form.global_id();
  form_forest_.UpdateTreeOfRendererForm(std::move(form), source);

  TriggerFormExtractionExcept(source);

  const FormData& browser_form = form_forest_.GetBrowserForm(form_id);
  if (!base::Contains(browser_form.fields(), field_id,
                      &FormFieldData::global_id)) {
    // To avoid very large flattened forms, UpdateTreeOfRendererForm() may have
    // cut the tree into two and, as a result, may have lost some fields. We
    // drop such events.
    // See `kMaxVisits` in FormForest::UpdateTreeOfRendererForm() for details.
    return;
  }
  auto* target = DriverOfFrame(browser_form.host_frame());
  callback(CHECK_DEREF(target), browser_form, field_id, timestamp);
}

void AutofillDriverRouter::TextFieldDidScroll(
    RoutedCallback<const FormData&, const FieldGlobalId&> callback,
    AutofillDriver& source,
    FormData form,
    const FieldGlobalId& field_id) {
  FormGlobalId form_id = form.global_id();
  form_forest_.UpdateTreeOfRendererForm(std::move(form), source);

  TriggerFormExtractionExcept(source);

  const FormData& browser_form = form_forest_.GetBrowserForm(form_id);
  if (!base::Contains(browser_form.fields(), field_id,
                      &FormFieldData::global_id)) {
    // To avoid very large flattened forms, UpdateTreeOfRendererForm() may have
    // cut the tree into two and, as a result, may have lost some fields. We
    // drop such events.
    // See `kMaxVisits` in FormForest::UpdateTreeOfRendererForm() for details.
    return;
  }
  auto* target = DriverOfFrame(browser_form.host_frame());
  callback(CHECK_DEREF(target), browser_form, field_id);
}

void AutofillDriverRouter::SelectControlSelectionChanged(
    RoutedCallback<const FormData&, const FieldGlobalId&> callback,
    AutofillDriver& source,
    FormData form,
    const FieldGlobalId& field_id) {
  FormGlobalId form_id = form.global_id();
  form_forest_.UpdateTreeOfRendererForm(std::move(form), source);

  TriggerFormExtractionExcept(source);

  const FormData& browser_form = form_forest_.GetBrowserForm(form_id);
  if (!base::Contains(browser_form.fields(), field_id,
                      &FormFieldData::global_id)) {
    // To avoid very large flattened forms, UpdateTreeOfRendererForm() may have
    // cut the tree into two and, as a result, may have lost some fields. We
    // drop such events.
    // See `kMaxVisits` in FormForest::UpdateTreeOfRendererForm() for details.
    return;
  }
  auto* target = DriverOfFrame(browser_form.host_frame());
  callback(CHECK_DEREF(target), browser_form, field_id);
}

void AutofillDriverRouter::AskForValuesToFill(
    RoutedCallback<const FormData&,
                   const FieldGlobalId&,
                   const gfx::Rect&,
                   AutofillSuggestionTriggerSource,
                   base::optional_ref<const PasswordSuggestionRequest>>
        callback,
    AutofillDriver& source,
    FormData form,
    const FieldGlobalId& field_id,
    const gfx::Rect& caret_bounds,
    AutofillSuggestionTriggerSource trigger_source,
    base::optional_ref<const PasswordSuggestionRequest> password_request) {
  FormGlobalId form_id = form.global_id();
  form_forest_.UpdateTreeOfRendererForm(std::move(form), source);

  TriggerFormExtractionExcept(source);

  const FormData& browser_form = form_forest_.GetBrowserForm(form_id);
  if (!base::Contains(browser_form.fields(), field_id,
                      &FormFieldData::global_id)) {
    // To avoid very large flattened forms, UpdateTreeOfRendererForm() may have
    // cut the tree into two and, as a result, may have lost some fields. We
    // drop such events.
    // See `kMaxVisits` in FormForest::UpdateTreeOfRendererForm() for details.
    return;
  }
  auto* target = DriverOfFrame(browser_form.host_frame());
  callback(CHECK_DEREF(target), browser_form, field_id, caret_bounds,
           trigger_source, password_request);
}

void AutofillDriverRouter::HidePopup(RoutedCallback<> callback,
                                     AutofillDriver& source) {
  // We don't know which AutofillManager is currently displaying the popup.
  // Since the the general approach of popup hiding in Autofill seems to be
  // "better safe than sorry", broadcasting this event is fine.
  // TODO(crbug.com/40284890): This event should go away when the popup-hiding
  // mechanism has been cleaned up.
  ForEachFrame(form_forest_, callback);
}

void AutofillDriverRouter::FocusOnNonFormField(RoutedCallback<> callback,
                                               AutofillDriver& source) {
  // Suppresses FocusOnNonFormField() if the focus has already moved to a
  // different frame.
  if (focused_frame_ != source.GetFrameToken()) {
    return;
  }

  // Prevents FocusOnFormField() from calling FocusOnNonFormField().
  focus_no_longer_on_form_has_fired_ = true;

  TriggerFormExtractionExcept(source);

  // The last-focused form is not known at this time. Even if
  // FocusOnNonFormField() had a FormGlobalId parameter, we couldn't call
  // `form_forest_.GetBrowserForm()` because this is admissible only after a
  // `form_forest_.UpdateTreeOfRendererForm()` for the same form.
  //
  // Therefore, we simply broadcast the event.
  ForEachFrame(form_forest_, callback);
}

void AutofillDriverRouter::FocusOnFormField(
    RoutedCallback<const FormData&, const FieldGlobalId&> callback,
    AutofillDriver& source,
    FormData form,
    const FieldGlobalId& field_id,
    RoutedCallback<> focus_no_longer_on_form) {
  FormGlobalId form_id = form.global_id();
  form_forest_.UpdateTreeOfRendererForm(std::move(form), source);

  // Calls FocusOnNonFormField() if the focus has already moved from a
  // different frame and FocusOnNonFormField() hasn't been called yet.
  if (focused_frame_ != source.GetFrameToken() &&
      !focus_no_longer_on_form_has_fired_) {
    ForEachFrame(form_forest_, focus_no_longer_on_form);
  }

  // Suppresses late FocusOnNonFormField().
  focused_frame_ = source.GetFrameToken();
  focus_no_longer_on_form_has_fired_ = false;

  TriggerFormExtractionExcept(source);

  const FormData& browser_form = form_forest_.GetBrowserForm(form_id);
  if (!base::Contains(browser_form.fields(), field_id,
                      &FormFieldData::global_id)) {
    // To avoid very large flattened forms, UpdateTreeOfRendererForm() may have
    // cut the tree into two and, as a result, may have lost some fields. We
    // drop such events.
    // See `kMaxVisits` in FormForest::UpdateTreeOfRendererForm() for details.
    return;
  }
  auto* target = DriverOfFrame(browser_form.host_frame());
  callback(CHECK_DEREF(target), browser_form, field_id);
}

void AutofillDriverRouter::DidFillAutofillFormData(
    RoutedCallback<const FormData&, base::TimeTicks> callback,
    AutofillDriver& source,
    FormData form,
    base::TimeTicks timestamp) {
  FormGlobalId form_id = form.global_id();
  form_forest_.UpdateTreeOfRendererForm(std::move(form), source);

  const FormData& browser_form = form_forest_.GetBrowserForm(form_id);
  auto* target = DriverOfFrame(browser_form.host_frame());
  callback(CHECK_DEREF(target), browser_form, timestamp);
}

void AutofillDriverRouter::DidEndTextFieldEditing(RoutedCallback<> callback,
                                                  AutofillDriver& source) {
  TriggerFormExtractionExcept(source);

  // The last-focused form is not known at this time. Even if
  // DidEndTextFieldEditing() had a FormGlobalId parameter, we couldn't call
  // `form_forest_.GetBrowserForm()` because this is admissible only after a
  // `form_forest_.UpdateTreeOfRendererForm()` for the same form.
  //
  // Therefore, we simply broadcast the event.
  ForEachFrame(form_forest_, callback);
}

void AutofillDriverRouter::SelectFieldOptionsDidChange(
    RoutedCallback<const FormData&> callback,
    AutofillDriver& source,
    FormData form) {
  FormGlobalId form_id = form.global_id();
  form_forest_.UpdateTreeOfRendererForm(std::move(form), source);

  TriggerFormExtractionExcept(source);

  const FormData& browser_form = form_forest_.GetBrowserForm(form_id);
  auto* target = DriverOfFrame(browser_form.host_frame());
  callback(CHECK_DEREF(target), browser_form);
}

void AutofillDriverRouter::JavaScriptChangedAutofilledValue(
    RoutedCallback<const FormData&, const FieldGlobalId&, const std::u16string&>
        callback,
    AutofillDriver& source,
    FormData form,
    const FieldGlobalId& field_id,
    const std::u16string& old_value) {
  FormGlobalId form_id = form.global_id();
  form_forest_.UpdateTreeOfRendererForm(std::move(form), source);

  TriggerFormExtractionExcept(source);

  const FormData& browser_form = form_forest_.GetBrowserForm(form_id);
  if (!base::Contains(browser_form.fields(), field_id,
                      &FormFieldData::global_id)) {
    // To avoid very large flattened forms, UpdateTreeOfRendererForm() may have
    // cut the tree into two and, as a result, may have lost some fields. We
    // drop such events.
    // See `kMaxVisits` in FormForest::UpdateTreeOfRendererForm() for details.
    return;
  }
  auto* target = DriverOfFrame(browser_form.host_frame());
  callback(CHECK_DEREF(target), browser_form, field_id, old_value);
}

// Routing of events triggered by the browser.
//
// Below, `DriverOfFrame() == nullptr` does not necessarily indicate a bug and
// is therefore not NOTREACHED().
// The reason is that browser forms may be outdated and hence refer to frames
// that do not exist anymore.

base::flat_set<FieldGlobalId> AutofillDriverRouter::ApplyFormAction(
    RoutedCallback<mojom::FormActionType,
                   mojom::ActionPersistence,
                   const std::vector<FormFieldData::FillData>&> callback,
    mojom::FormActionType action_type,
    mojom::ActionPersistence action_persistence,
    base::span<const FormFieldData> data,
    const url::Origin& main_origin,
    const url::Origin& triggered_origin,
    const base::flat_map<FieldGlobalId, FieldType>& field_type_map) {
  // Since Undo only affects fields that were already filled, and only sets
  // values to fields to something that already existed in it prior to the
  // filling, it is okay to bypass the filling security checks and hence passing
  // `TrustAllOrigins()`.
  internal::FormForest::RendererForms renderer_forms =
      form_forest_.GetRendererFormsOfBrowserFields(
          data, action_type == mojom::FormActionType::kUndo
                    ? internal::FormForest::SecurityOptions::TrustAllOrigins()
                    : internal::FormForest::SecurityOptions(
                          &main_origin, &triggered_origin, &field_type_map));
  // Collect the fields per frame and emit a single fill operation per frame,
  // even if multiple renderer forms belong to the same iframe due to
  // flattening.
  base::flat_map<AutofillDriver*, std::vector<FormFieldData::FillData>>
      fields_of_driver;
  for (FormData& renderer_form : renderer_forms.renderer_forms) {
    if (auto* target = DriverOfFrame(renderer_form.host_frame())) {
      for (const FormFieldData& field : renderer_form.fields()) {
        // Skip unsafe fields so that they do not get filled in the renderer.
        if (renderer_forms.safe_fields.contains(field.global_id())) {
          fields_of_driver[target].emplace_back(field);
        }
      }
    }
  }
  for (const auto& [target, fields] : fields_of_driver) {
    CHECK(!fields.empty());
    callback(CHECK_DEREF(target), action_type, action_persistence, fields);
  }
  return renderer_forms.safe_fields;
}

void AutofillDriverRouter::ApplyFieldAction(
    RoutedCallback<mojom::FieldActionType,
                   mojom::ActionPersistence,
                   FieldRendererId,
                   const std::u16string&> callback,
    mojom::FieldActionType action_type,
    mojom::ActionPersistence action_persistence,
    const FieldGlobalId& field_id,
    const std::u16string& value) {
  if (auto* target = DriverOfFrame(field_id.frame_token)) {
    callback(*target, action_type, action_persistence, field_id.renderer_id,
             value);
  }
}

void AutofillDriverRouter::ExtractForm(
    RoutedCallback<FormRendererId, RendererFormHandler> callback,
    FormGlobalId form_id,
    BrowserFormHandler browser_form_handler) {
  if (auto* target = DriverOfFrame(form_id.frame_token)) {
    // `renderer_form_handler` converts a received renderer `form` into a
    // browser form and passes that to `browser_form_handler`.
    // Binding `*this` and `*target` is safe because
    // - `*this` outlives `*target`, and
    // - `*target` outlives all pending callbacks of `*target`'s AutofillAgent.
    auto renderer_form_handler = base::BindOnce(
        [](raw_ref<AutofillDriverRouter> self,
           raw_ref<AutofillDriver> response_source,
           BrowserFormHandler browser_form_handler,
           const std::optional<FormData>& form) {
          if (!form) {
            std::move(browser_form_handler).Run(nullptr, std::nullopt);
            return;
          }
          self->form_forest_.UpdateTreeOfRendererForm(*form, *response_source);
          const FormData& browser_form =
              self->form_forest_.GetBrowserForm(form->global_id());
          auto* response_target =
              self->DriverOfFrame(browser_form.host_frame());
          std::move(browser_form_handler).Run(response_target, browser_form);
        },
        raw_ref(*this), raw_ref(*target), std::move(browser_form_handler));
    callback(*target, form_id.renderer_id, std::move(renderer_form_handler));
  } else {
    std::move(browser_form_handler).Run(nullptr, std::nullopt);
  }
}

void AutofillDriverRouter::SendTypePredictionsToRenderer(
    RoutedCallback<const std::vector<FormDataPredictions>&> callback,
    const FormDataPredictions& browser_fdp) {
  // Splits the FrameDataPredictions according to the FormData's renderer forms,
  // and groups these FormDataPredictions by the renderer form's frame. We uso
  // "fdp" as abbreviation of FormDataPredictions.
  std::map<LocalFrameToken, std::vector<FormDataPredictions>> renderer_fdps;

  // Builds an index of the field predictions by the field's global ID.
  std::map<FieldGlobalId, FormFieldDataPredictions> field_predictions;
  DCHECK_EQ(browser_fdp.data.fields().size(), browser_fdp.fields.size());
  for (auto [field, field_prediction] :
       base::zip(browser_fdp.data.fields(), browser_fdp.fields)) {
    field_predictions.emplace(field.global_id(), field_prediction);
  }

  // Builds the FormDataPredictions of each renderer form and groups them by
  // the renderer form's frame in |renderer_fdps|.
  internal::FormForest::RendererForms renderer_forms =
      form_forest_.GetRendererFormsOfBrowserFields(
          browser_fdp.data.fields(), {&browser_fdp.data.main_frame_origin(),
                                      &browser_fdp.data.main_frame_origin(),
                                      /*field_type_map=*/nullptr});
  for (FormData& renderer_form : renderer_forms.renderer_forms) {
    LocalFrameToken frame = renderer_form.host_frame();
    FormDataPredictions renderer_fdp;
    renderer_fdp.data = std::move(renderer_form);
    renderer_fdp.signature = browser_fdp.signature;
    renderer_fdp.alternative_signature = browser_fdp.alternative_signature;
    for (const FormFieldData& field : renderer_fdp.data.fields()) {
      renderer_fdp.fields.push_back(
          std::move(field_predictions[field.global_id()]));
    }
    renderer_fdps[frame].push_back(std::move(renderer_fdp));
  }

  // Sends the predictions of the renderer forms to the individual frames.
  for (const auto& p : renderer_fdps) {
    LocalFrameToken frame = p.first;
    const std::vector<FormDataPredictions>& renderer_fdp = p.second;
    if (auto* target = DriverOfFrame(frame)) {
      callback(*target, renderer_fdp);
    }
  }
}

void AutofillDriverRouter::RendererShouldAcceptDataListSuggestion(
    RoutedCallback<FieldRendererId, const std::u16string&> callback,
    const FieldGlobalId& field_id,
    const std::u16string& value) {
  if (auto* target = DriverOfFrame(field_id.frame_token)) {
    callback(*target, field_id.renderer_id, value);
  }
}

void AutofillDriverRouter::RendererShouldClearPreviewedForm(
    RoutedCallback<> callback) {
  ForEachFrame(form_forest_, callback);
}

void AutofillDriverRouter::RendererShouldTriggerSuggestions(
    RoutedCallback<FieldRendererId, AutofillSuggestionTriggerSource> callback,
    const FieldGlobalId& field_id,
    AutofillSuggestionTriggerSource trigger_source) {
  if (AutofillDriver* target = DriverOfFrame(field_id.frame_token)) {
    callback(*target, field_id.renderer_id, trigger_source);
  }
}

void AutofillDriverRouter::RendererShouldSetSuggestionAvailability(
    RoutedCallback<FieldRendererId, mojom::AutofillSuggestionAvailability>
        callback,
    const FieldGlobalId& field_id,
    mojom::AutofillSuggestionAvailability suggestion_availability) {
  if (auto* target = DriverOfFrame(field_id.frame_token)) {
    callback(*target, field_id.renderer_id, suggestion_availability);
  }
}

std::vector<FormData> AutofillDriverRouter::GetRendererForms(
    const FormData& browser_form) const {
  return form_forest_
      .GetRendererFormsOfBrowserFields(
          browser_form.fields(),
          internal::FormForest::SecurityOptions::TrustAllOrigins())
      .renderer_forms;
}

}  // namespace autofill