File: usb_chooser_context.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (681 lines) | stat: -rw-r--r-- 23,990 bytes parent folder | download | duplicates (6)
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
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/usb/usb_chooser_context.h"

#include <memory>
#include <string_view>
#include <utility>
#include <vector>

#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/observer_list.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/usb/web_usb_histograms.h"
#include "chrome/grit/generated_resources.h"
#include "components/content_settings/core/common/content_settings.h"
#include "content/public/browser/device_service.h"
#include "services/device/public/cpp/usb/usb_ids.h"
#include "services/device/public/mojom/usb_device.mojom.h"
#include "ui/base/l10n/l10n_util.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "chromeos/ash/components/settings/cros_settings.h"
#include "chromeos/ash/components/settings/cros_settings_names.h"
#endif

namespace {

constexpr char kDeviceNameKey[] = "name";
constexpr char kGuidKey[] = "ephemeral-guid";
constexpr char kProductIdKey[] = "product-id";
constexpr char kSerialNumberKey[] = "serial-number";
constexpr char kVendorIdKey[] = "vendor-id";
constexpr int kDeviceIdWildcard = -1;
constexpr int kUsbClassMassStorage = 0x08;

bool CanStorePersistentEntry(const device::mojom::UsbDeviceInfo& device_info) {
  return device_info.serial_number && !device_info.serial_number->empty();
}

std::pair<int, int> GetDeviceIds(const base::Value::Dict& object) {
  DCHECK(object.FindInt(kVendorIdKey));
  int vendor_id = *object.FindInt(kVendorIdKey);

  DCHECK(object.FindInt(kProductIdKey));
  int product_id = *object.FindInt(kProductIdKey);

  return std::make_pair(vendor_id, product_id);
}

std::u16string GetDeviceNameFromIds(int vendor_id, int product_id) {
#if !BUILDFLAG(IS_ANDROID)
  const char* product_name =
      device::UsbIds::GetProductName(vendor_id, product_id);
  if (product_name)
    return base::UTF8ToUTF16(product_name);

  const char* vendor_name = device::UsbIds::GetVendorName(vendor_id);
  if (vendor_name) {
    if (product_id == kDeviceIdWildcard) {
      return l10n_util::GetStringFUTF16(
          IDS_USB_POLICY_DEVICE_DESCRIPTION_FOR_VENDOR_NAME,
          base::UTF8ToUTF16(vendor_name));
    }

    return l10n_util::GetStringFUTF16(
        IDS_USB_POLICY_DEVICE_DESCRIPTION_FOR_PRODUCT_ID_AND_VENDOR_NAME,
        base::ASCIIToUTF16(base::StringPrintf("0x%04X", product_id)),
        base::UTF8ToUTF16(vendor_name));
  }
#endif  // !BUILDFLAG(IS_ANDROID)

  if (product_id == kDeviceIdWildcard) {
    if (vendor_id == kDeviceIdWildcard)
      return l10n_util::GetStringUTF16(
          IDS_USB_POLICY_DEVICE_DESCRIPTION_FOR_ANY_VENDOR);

    return l10n_util::GetStringFUTF16(
        IDS_USB_POLICY_DEVICE_DESCRIPTION_FOR_VENDOR_ID,
        base::ASCIIToUTF16(base::StringPrintf("0x%04X", vendor_id)));
  }

  return l10n_util::GetStringFUTF16(
      IDS_USB_POLICY_DEVICE_DESCRIPTION_FOR_PRODUCT_ID_AND_VENDOR_ID,
      base::ASCIIToUTF16(base::StringPrintf("0x%04X", product_id)),
      base::ASCIIToUTF16(base::StringPrintf("0x%04X", vendor_id)));
}

base::Value::Dict DeviceIdsToValue(int vendor_id, int product_id) {
  base::Value::Dict device_value;
  std::u16string device_name = GetDeviceNameFromIds(vendor_id, product_id);

  device_value.Set(kDeviceNameKey, device_name);
  device_value.Set(kVendorIdKey, vendor_id);
  device_value.Set(kProductIdKey, product_id);
  device_value.Set(kSerialNumberKey, std::string());

  return device_value;
}

#if BUILDFLAG(IS_CHROMEOS)
bool IsDetachable(int vid, int pid) {
  const base::Value::List* policy_list;
  if (ash::CrosSettings::Get()->GetList(ash::kUsbDetachableAllowlist,
                                        &policy_list)) {
    for (const auto& entry : *policy_list) {
      if (entry.GetDict().FindInt(ash::kUsbDetachableAllowlistKeyVid) == vid &&
          entry.GetDict().FindInt(ash::kUsbDetachableAllowlistKeyPid) == pid) {
        return true;
      }
    }
  }
  return false;
}
#endif  // BUILDFLAG(IS_CHROMEOS)

bool IsMassStorageInterface(const device::mojom::UsbInterfaceInfo& interface) {
  for (auto& alternate : interface.alternates) {
    if (alternate->class_code == kUsbClassMassStorage)
      return true;
  }
  return false;
}

bool ShouldExposeDevice(const device::mojom::UsbDeviceInfo& device_info) {
#if BUILDFLAG(IS_CHROMEOS)
  if (IsDetachable(device_info.vendor_id, device_info.product_id))
    return true;
#endif  // BUILDFLAG(IS_CHROMEOS)

  // blink::USBDevice::claimInterface() disallows claiming mass storage
  // interfaces, but explicitly prevent access in the browser process as
  // ChromeOS would allow these interfaces to be claimed.
  for (auto& configuration : device_info.configurations) {
    if (configuration->interfaces.size() == 0) {
        return true;
    }
    for (auto& interface : configuration->interfaces) {
      if (!IsMassStorageInterface(*interface))
        return true;
    }
  }
  return false;
}

}  // namespace

void UsbChooserContext::DeviceObserver::OnDeviceAdded(
    const device::mojom::UsbDeviceInfo& device_info) {}

void UsbChooserContext::DeviceObserver::OnDeviceRemoved(
    const device::mojom::UsbDeviceInfo& device_info) {}

void UsbChooserContext::DeviceObserver::OnDeviceManagerConnectionError() {}

UsbChooserContext::UsbChooserContext(Profile* profile)
    : ObjectPermissionContextBase(
          ContentSettingsType::USB_GUARD,
          ContentSettingsType::USB_CHOOSER_DATA,
          HostContentSettingsMapFactory::GetForProfile(profile)),
      is_incognito_(profile->IsOffTheRecord()) {
  usb_policy_allowed_devices_ =
      std::make_unique<UsbPolicyAllowedDevices>(profile->GetPrefs());
}

// static
base::Value::Dict UsbChooserContext::DeviceInfoToValue(
    const device::mojom::UsbDeviceInfo& device_info) {
  base::Value::Dict device_value;
  device_value.Set(kDeviceNameKey, device_info.product_name
                                       ? *device_info.product_name
                                       : std::u16string_view());
  device_value.Set(kVendorIdKey, device_info.vendor_id);
  device_value.Set(kProductIdKey, device_info.product_id);

  // CanStorePersistentEntry checks if |device_info.serial_number| is not empty.
  if (CanStorePersistentEntry(device_info)) {
    device_value.Set(kSerialNumberKey, *device_info.serial_number);
  } else {
    device_value.Set(kGuidKey, device_info.guid);
  }

  return device_value;
}

void UsbChooserContext::InitDeviceList(
    std::vector<device::mojom::UsbDeviceInfoPtr> devices) {
  for (auto& device_info : devices) {
    DCHECK(device_info);
    if (ShouldExposeDevice(*device_info)) {
      devices_.insert(
          std::make_pair(device_info->guid, std::move(device_info)));
    }
  }
  is_initialized_ = true;

  while (!pending_get_devices_requests_.empty()) {
    std::vector<device::mojom::UsbDeviceInfoPtr> device_list;
    for (const auto& entry : devices_) {
      device_list.push_back(entry.second->Clone());
    }
    std::move(pending_get_devices_requests_.front())
        .Run(std::move(device_list));
    pending_get_devices_requests_.pop();
  }
}

void UsbChooserContext::Shutdown() {
  FlushScheduledSaveSettingsCalls();
  permissions::ObjectPermissionContextBase::Shutdown();
}

void UsbChooserContext::EnsureConnectionWithDeviceManager() {
  if (device_manager_)
    return;

  // Receive mojo::Remote<UsbDeviceManager> from DeviceService.
  content::GetDeviceService().BindUsbDeviceManager(
      device_manager_.BindNewPipeAndPassReceiver());

  SetUpDeviceManagerConnection();
}

void UsbChooserContext::SetUpDeviceManagerConnection() {
  DCHECK(device_manager_);
  device_manager_.set_disconnect_handler(
      base::BindOnce(&UsbChooserContext::OnDeviceManagerConnectionError,
                     base::Unretained(this)));

  // Listen for added/removed device events.
  DCHECK(!client_receiver_.is_bound());
  device_manager_->EnumerateDevicesAndSetClient(
      client_receiver_.BindNewEndpointAndPassRemote(),
      base::BindOnce(&UsbChooserContext::InitDeviceList,
                     weak_factory_.GetWeakPtr()));
}

#if BUILDFLAG(IS_ANDROID)
void UsbChooserContext::OnDeviceInfoRefreshed(
    device::mojom::UsbDeviceManager::RefreshDeviceInfoCallback callback,
    device::mojom::UsbDeviceInfoPtr device_info) {
  if (!device_info) {
    std::move(callback).Run(nullptr);
    return;
  }

  auto it = devices_.find(device_info->guid);
  if (it == devices_.end()) {
    std::move(callback).Run(nullptr);
    return;
  }

  it->second = std::move(device_info);
  std::move(callback).Run(it->second->Clone());
}
#endif

UsbChooserContext::~UsbChooserContext() {
  OnDeviceManagerConnectionError();
  for (auto& observer : device_observer_list_) {
    observer.OnBrowserContextShutdown();
    DCHECK(!device_observer_list_.HasObserver(&observer));
  }
  DCHECK(permission_observer_list_.empty());
}

std::vector<std::unique_ptr<permissions::ObjectPermissionContextBase::Object>>
UsbChooserContext::GetGrantedObjects(const url::Origin& origin) {
  std::vector<std::unique_ptr<Object>> objects =
      ObjectPermissionContextBase::GetGrantedObjects(origin);

  if (CanRequestObjectPermission(origin)) {
    auto it = ephemeral_devices_.find(origin);
    if (it != ephemeral_devices_.end()) {
      for (const std::string& guid : it->second) {
        // |devices_| should be initialized when |ephemeral_devices_| is filled.
        // Because |ephemeral_devices_| is filled by GrantDevicePermission()
        // which is called in UsbChooserController::Select(), this method will
        // always be called after device initialization in UsbChooserController
        // which always returns after the device list initialization in this
        // class.
        DCHECK(base::Contains(devices_, guid));
        objects.push_back(std::make_unique<Object>(
            origin, DeviceInfoToValue(*devices_[guid]),
            content_settings::SettingSource::kUser, is_incognito_));
      }
    }
  }

  // Iterate through the user granted objects and create a mapping of device IDs
  // to device object if the object is also allowed by policy. Any objects that
  // have been granted by policy are removed from |objects| to avoid duplicate
  // permissions from being displayed.
  // TODO(crbug.com/40611788): This logic is very similar to the logic for
  // GetAllGrantedObjects(), so it could potentially be centralized.
  std::map<std::pair<int, int>, base::Value::Dict> device_ids_to_object_map;
  for (auto it = objects.begin(); it != objects.end();) {
    base::Value::Dict& object = (*it)->value;
    auto device_ids = GetDeviceIds(object);

    if (usb_policy_allowed_devices_->IsDeviceAllowed(origin, device_ids)) {
      device_ids_to_object_map[device_ids] = std::move(object);
      it = objects.erase(it);
    } else {
      ++it;
    }
  }

  for (const auto& allowed_devices_entry : usb_policy_allowed_devices_->map()) {
    // The map key is a tuple of (vendor_id, product_id).
    const int vendor_id = allowed_devices_entry.first.first;
    const int product_id = allowed_devices_entry.first.second;

    for (const auto& url : allowed_devices_entry.second) {
      // Skip entries that do not match the |origin|.
      if (url != origin)
        continue;

      // If there is an entry for the device in |device_ids_to_object_map|, use
      // that object to represent the device. Otherwise, attempt to figure out
      // the name of the device from the |vendor_id| and |product_id|.
      base::Value::Dict object;
      auto it =
          device_ids_to_object_map.find(std::make_pair(vendor_id, product_id));
      if (it != device_ids_to_object_map.end()) {
        object = std::move(it->second);
      } else {
        object = DeviceIdsToValue(vendor_id, product_id);
      }

      objects.push_back(std::make_unique<Object>(
          url, std::move(object), content_settings::SettingSource::kPolicy,
          is_incognito_));
    }
  }

  return objects;
}

std::vector<std::unique_ptr<permissions::ObjectPermissionContextBase::Object>>
UsbChooserContext::GetAllGrantedObjects() {
  std::vector<std::unique_ptr<Object>> objects =
      ObjectPermissionContextBase::GetAllGrantedObjects();

  for (const auto& map_entry : ephemeral_devices_) {
    const url::Origin& origin = map_entry.first;

    if (!CanRequestObjectPermission(origin))
      continue;

    for (const std::string& guid : map_entry.second) {
      DCHECK(base::Contains(devices_, guid));
      objects.push_back(std::make_unique<Object>(
          origin, DeviceInfoToValue(*devices_[guid]),
          content_settings::SettingSource::kUser, is_incognito_));
    }
  }

  // Iterate through the user granted objects to create a mapping of device IDs
  // to device object for the policy granted objects to use, and remove
  // objects that have already been granted permission by the policy.
  // TODO(crbug.com/40611788): This logic is very similar to the logic for
  // GetGrantedObjects(), so it could potentially be centralized.
  std::map<std::pair<int, int>, base::Value::Dict> device_ids_to_object_map;
  for (auto it = objects.begin(); it != objects.end();) {
    Object& object = **it;
    auto device_ids = GetDeviceIds(object.value);
    auto origin = url::Origin::Create(object.origin);

    if (usb_policy_allowed_devices_->IsDeviceAllowed(origin, device_ids)) {
      device_ids_to_object_map[device_ids] = std::move(object.value);
      it = objects.erase(it);
    } else {
      ++it;
    }
  }

  for (const auto& allowed_devices_entry : usb_policy_allowed_devices_->map()) {
    // The map key is a tuple of (vendor_id, product_id).
    const int vendor_id = allowed_devices_entry.first.first;
    const int product_id = allowed_devices_entry.first.second;

    for (const auto& url : allowed_devices_entry.second) {
      // If there is an entry for the device in |device_ids_to_object_map|, use
      // that object to represent the device. Otherwise, attempt to figure out
      // the name of the device from the |vendor_id| and |product_id|.
      base::Value::Dict object;
      auto it =
          device_ids_to_object_map.find(std::make_pair(vendor_id, product_id));
      if (it != device_ids_to_object_map.end()) {
        object = it->second.Clone();
      } else {
        object = DeviceIdsToValue(vendor_id, product_id);
      }

      objects.push_back(std::make_unique<Object>(
          url, std::move(object), content_settings::SettingSource::kPolicy,
          is_incognito_));
    }
  }

  return objects;
}

void UsbChooserContext::RevokeObjectPermission(
    const url::Origin& origin,
    const base::Value::Dict& object) {
  RevokeObjectPermissionInternal(origin, object, /*revoked_by_website=*/false);
}

void UsbChooserContext::RevokeDevicePermissionWebInitiated(
    const url::Origin& origin,
    const device::mojom::UsbDeviceInfo& device) {
  DCHECK(base::Contains(devices_, device.guid));
  RevokeObjectPermissionInternal(origin, DeviceInfoToValue(device),
                                 /*revoked_by_website=*/true);
}

void UsbChooserContext::RevokeObjectPermissionInternal(
    const url::Origin& origin,
    const base::Value::Dict& object,
    bool revoked_by_website = false) {
  const std::string* guid = object.FindString(kGuidKey);

  if (!guid) {
    ObjectPermissionContextBase::RevokeObjectPermission(origin, object);
    RecordWebUsbPermissionRevocation(revoked_by_website
                                         ? WEBUSB_PERMISSION_REVOKED_BY_WEBSITE
                                         : WEBUSB_PERMISSION_REVOKED_BY_USER);
    return;
  }

  auto it = ephemeral_devices_.find(origin);
  if (it != ephemeral_devices_.end()) {
    it->second.erase(*guid);
    if (it->second.empty())
      ephemeral_devices_.erase(it);
    NotifyPermissionRevoked(origin);
  }

  RecordWebUsbPermissionRevocation(
      revoked_by_website ? WEBUSB_PERMISSION_REVOKED_EPHEMERAL_BY_WEBSITE
                         : WEBUSB_PERMISSION_REVOKED_EPHEMERAL_BY_USER);
}

std::string UsbChooserContext::GetKeyForObject(
    const base::Value::Dict& object) {
  if (!IsValidObject(object))
    return std::string();
  return base::JoinString(
      {base::NumberToString(*(object.FindInt(kVendorIdKey))),
       base::NumberToString(*(object.FindInt(kProductIdKey))),
       *(object.FindString(kSerialNumberKey))},
      "|");
}

bool UsbChooserContext::IsValidObject(const base::Value::Dict& object) {
  return object.size() == 4 && object.FindString(kDeviceNameKey) &&
         object.FindInt(kVendorIdKey) && object.FindInt(kProductIdKey) &&
         (object.FindString(kSerialNumberKey) || object.FindString(kGuidKey));
}

std::u16string UsbChooserContext::GetObjectDisplayName(
    const base::Value::Dict& object) {
  const std::string* name = object.FindString(kDeviceNameKey);
  DCHECK(name);
  if (!name->empty())
    return base::UTF8ToUTF16(*name);

  std::optional<int> vendor_id = object.FindInt(kVendorIdKey);
  std::optional<int> product_id = object.FindInt(kProductIdKey);
  DCHECK(vendor_id && product_id);
  return GetDeviceNameFromIds(*vendor_id, *product_id);
}

void UsbChooserContext::GrantDevicePermission(
    const url::Origin& origin,
    const device::mojom::UsbDeviceInfo& device_info) {
  if (CanStorePersistentEntry(device_info)) {
    GrantObjectPermission(origin, DeviceInfoToValue(device_info));
  } else {
    ephemeral_devices_[origin].insert(device_info.guid);
    NotifyPermissionChanged();
  }
}

bool UsbChooserContext::HasDevicePermission(
    const url::Origin& origin,
    const device::mojom::UsbDeviceInfo& device_info) {

  if (usb_policy_allowed_devices_->IsDeviceAllowed(origin, device_info)) {
    return true;
  }

  if (!CanRequestObjectPermission(origin))
    return false;

  auto it = ephemeral_devices_.find(origin);
  if (it != ephemeral_devices_.end() &&
      base::Contains(it->second, device_info.guid)) {
    return true;
  }

  std::vector<std::unique_ptr<Object>> object_list = GetGrantedObjects(origin);
  for (const auto& object : object_list) {
    const base::Value::Dict& device = object->value;
    DCHECK(IsValidObject(device));

    const int vendor_id = *device.FindInt(kVendorIdKey);
    const int product_id = *device.FindInt(kProductIdKey);
    const std::string* serial_number = device.FindString(kSerialNumberKey);
    if (device_info.vendor_id == vendor_id &&
        device_info.product_id == product_id && serial_number &&
        device_info.serial_number == base::UTF8ToUTF16(*serial_number)) {
      return true;
    }
  }

  return false;
}

void UsbChooserContext::GetDevices(
    device::mojom::UsbDeviceManager::GetDevicesCallback callback) {
  if (!is_initialized_) {
    EnsureConnectionWithDeviceManager();
    pending_get_devices_requests_.push(std::move(callback));
    return;
  }

  std::vector<device::mojom::UsbDeviceInfoPtr> device_list;
  for (const auto& pair : devices_)
    device_list.push_back(pair.second->Clone());
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindOnce(std::move(callback), std::move(device_list)));
}

void UsbChooserContext::GetDevice(
    const std::string& guid,
    base::span<const uint8_t> blocked_interface_classes,
    mojo::PendingReceiver<device::mojom::UsbDevice> device_receiver,
    mojo::PendingRemote<device::mojom::UsbDeviceClient> device_client) {
  EnsureConnectionWithDeviceManager();
  device_manager_->GetDevice(
      guid,
      std::vector<uint8_t>(blocked_interface_classes.begin(),
                           blocked_interface_classes.end()),
      std::move(device_receiver), std::move(device_client));
}

const device::mojom::UsbDeviceInfo* UsbChooserContext::GetDeviceInfo(
    const std::string& guid) {
  DCHECK(is_initialized_);
  auto it = devices_.find(guid);
  return it == devices_.end() ? nullptr : it->second.get();
}

#if BUILDFLAG(IS_ANDROID)
void UsbChooserContext::RefreshDeviceInfo(
    const std::string& guid,
    device::mojom::UsbDeviceManager::RefreshDeviceInfoCallback callback) {
  EnsureConnectionWithDeviceManager();
  device_manager_->RefreshDeviceInfo(
      guid, base::BindOnce(&UsbChooserContext::OnDeviceInfoRefreshed,
                           weak_factory_.GetWeakPtr(), std::move(callback)));
}
#endif

void UsbChooserContext::AddObserver(DeviceObserver* observer) {
  EnsureConnectionWithDeviceManager();
  device_observer_list_.AddObserver(observer);
}

void UsbChooserContext::RemoveObserver(DeviceObserver* observer) {
  device_observer_list_.RemoveObserver(observer);
}

base::WeakPtr<UsbChooserContext> UsbChooserContext::AsWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

void UsbChooserContext::OnDeviceAdded(
    device::mojom::UsbDeviceInfoPtr device_info) {
  DCHECK(device_info);
  // Update the device list.
  DCHECK(!base::Contains(devices_, device_info->guid));
  if (!ShouldExposeDevice(*device_info))
    return;
  devices_.insert(std::make_pair(device_info->guid, device_info->Clone()));

  // Notify all observers.
  for (auto& observer : device_observer_list_)
    observer.OnDeviceAdded(*device_info);
}

void UsbChooserContext::OnDeviceRemoved(
    device::mojom::UsbDeviceInfoPtr device_info) {
  DCHECK(device_info);

  if (!ShouldExposeDevice(*device_info)) {
    DCHECK(!base::Contains(devices_, device_info->guid));
    return;
  }

  // Update the device list.
  DCHECK(base::Contains(devices_, device_info->guid));
  devices_.erase(device_info->guid);

  // Notify all device observers.
  for (auto& observer : device_observer_list_)
    observer.OnDeviceRemoved(*device_info);

  // If the device was persistent, return. Otherwise, notify all permission
  // observers that its permissions were revoked.
  if (device_info->serial_number &&
      !device_info->serial_number.value().empty()) {
    return;
  }

  std::vector<url::Origin> revoked_urls;
  for (auto& map_entry : ephemeral_devices_) {
    if (map_entry.second.erase(device_info->guid) > 0)
      revoked_urls.push_back(map_entry.first);
  }

  for (auto& observer : permission_observer_list_) {
    observer.OnObjectPermissionChanged(guard_content_settings_type_,
                                       data_content_settings_type_);
    for (auto& url : revoked_urls) {
      observer.OnPermissionRevoked(url);
    }
  }
}

void UsbChooserContext::OnDeviceManagerConnectionError() {
  device_manager_.reset();
  client_receiver_.reset();
  devices_.clear();
  is_initialized_ = false;

  // Store the revoked URLs to notify observers of the revoked permissions.
  std::vector<url::Origin> revoked_origins;
  for (auto& map_entry : ephemeral_devices_)
    revoked_origins.push_back(map_entry.first);
  ephemeral_devices_.clear();

  // Notify all device observers.
  for (auto& observer : device_observer_list_)
    observer.OnDeviceManagerConnectionError();

  // Notify all permission observers.
  for (auto& observer : permission_observer_list_) {
    observer.OnObjectPermissionChanged(guard_content_settings_type_,
                                       data_content_settings_type_);
    for (auto& origin : revoked_origins) {
      observer.OnPermissionRevoked(origin);
    }
  }
}

void UsbChooserContext::SetDeviceManagerForTesting(
    mojo::PendingRemote<device::mojom::UsbDeviceManager> fake_device_manager) {
  // `device_manager_` can be bound in some test scenarios, in that case, just
  // reset the connection.
  if (device_manager_) {
    device_manager_.reset();
    client_receiver_.reset();
  }
  DCHECK(fake_device_manager);
  device_manager_.Bind(std::move(fake_device_manager));
  SetUpDeviceManagerConnection();
}