summaryrefslogtreecommitdiff
path: root/chromium/content/browser/worker_host/dedicated_worker_host.cc
blob: 546c134b1d9a8069c5310ccd7fce17df36346312 (plain)
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
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>
#include <string>
#include <utility>

#include "content/browser/worker_host/dedicated_worker_host.h"

#include "base/bind.h"
#include "content/browser/appcache/appcache_navigation_handle.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/frame_host/frame_tree.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/interface_provider_filtering.h"
#include "content/browser/service_worker/service_worker_navigation_handle.h"
#include "content/browser/service_worker/service_worker_object_host.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/websockets/websocket_connector_impl.h"
#include "content/browser/webtransport/quic_transport_connector_impl.h"
#include "content/browser/worker_host/worker_script_fetch_initiator.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/common/content_client.h"
#include "content/public/common/network_service_util.h"
#include "mojo/public/cpp/bindings/pending_associated_remote.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "net/base/network_isolation_key.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/mojom/loader/fetch_client_settings_object.mojom.h"
#include "third_party/blink/public/mojom/usb/web_usb_service.mojom.h"
#include "url/origin.h"

namespace content {

DedicatedWorkerHost::DedicatedWorkerHost(
    int worker_process_id,
    int ancestor_render_frame_id,
    int creator_render_frame_id,
    const url::Origin& origin,
    mojo::PendingReceiver<blink::mojom::DedicatedWorkerHost> host)
    : worker_process_id_(worker_process_id),
      ancestor_render_frame_id_(ancestor_render_frame_id),
      creator_render_frame_id_(creator_render_frame_id),
      origin_(origin),
      host_receiver_(this, std::move(host)) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
}

DedicatedWorkerHost::~DedicatedWorkerHost() = default;

void DedicatedWorkerHost::BindBrowserInterfaceBrokerReceiver(
    mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker> receiver) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(receiver.is_valid());
  broker_receiver_.Bind(std::move(receiver));
  broker_receiver_.set_disconnect_handler(base::BindOnce(
      &DedicatedWorkerHost::OnMojoDisconnect, base::Unretained(this)));
}

void DedicatedWorkerHost::OnMojoDisconnect() {
  delete this;
}

void DedicatedWorkerHost::LifecycleStateChanged(
    blink::mojom::FrameLifecycleState state) {
  switch (state) {
    case blink::mojom::FrameLifecycleState::kFrozen:
    case blink::mojom::FrameLifecycleState::kFrozenAutoResumeMedia:
      is_frozen_ = true;
      break;
    case blink::mojom::FrameLifecycleState::kRunning:
      is_frozen_ = false;
      break;
    case blink::mojom::FrameLifecycleState::kPaused:
      // This shouldn't be reached, the render process does not send this
      // state.
      NOTREACHED();
      break;
  }
}

void DedicatedWorkerHost::StartScriptLoad(
    const GURL& script_url,
    const url::Origin& request_initiator_origin,
    network::mojom::CredentialsMode credentials_mode,
    blink::mojom::FetchClientSettingsObjectPtr
        outside_fetch_client_settings_object,
    mojo::PendingRemote<blink::mojom::BlobURLToken> blob_url_token,
    mojo::Remote<blink::mojom::DedicatedWorkerHostFactoryClient> client) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(base::FeatureList::IsEnabled(blink::features::kPlzDedicatedWorker));

  DCHECK(!client_);
  DCHECK(client);
  client_ = std::move(client);

  // Get a storage partition.
  auto* worker_process_host = RenderProcessHost::FromID(worker_process_id_);
  if (!worker_process_host) {
    client_->OnScriptLoadStartFailed();
    return;
  }
  auto* storage_partition_impl = static_cast<StoragePartitionImpl*>(
      worker_process_host->GetStoragePartition());

  // Get nearest ancestor render frame host in order to determine the
  // top-frame origin to use for the network isolation key.
  RenderFrameHostImpl* nearest_ancestor_render_frame_host =
      GetAncestorRenderFrameHost();
  if (!nearest_ancestor_render_frame_host) {
    client_->OnScriptLoadStartFailed();
    return;
  }

  network_isolation_key_ =
      nearest_ancestor_render_frame_host->GetNetworkIsolationKey();

  // Get a storage domain.
  SiteInstance* site_instance =
      nearest_ancestor_render_frame_host->GetSiteInstance();
  if (!site_instance) {
    client_->OnScriptLoadStartFailed();
    return;
  }
  std::string storage_domain;
  std::string partition_name;
  bool in_memory;
  GetContentClient()->browser()->GetStoragePartitionConfigForSite(
      storage_partition_impl->browser_context(), site_instance->GetSiteURL(),
      /*can_be_default=*/true, &storage_domain, &partition_name, &in_memory);

  scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory;
  if (script_url.SchemeIsBlob()) {
    if (!blob_url_token) {
      mojo::ReportBadMessage("DWH_NO_BLOB_URL_TOKEN");
      return;
    }
    blob_url_loader_factory =
        ChromeBlobStorageContext::URLLoaderFactoryForToken(
            storage_partition_impl->browser_context(),
            std::move(blob_url_token));
  } else if (blob_url_token) {
    mojo::ReportBadMessage("DWH_NOT_BLOB_URL");
    return;
  }

  // If this is a nested worker, there is no creator frame.
  RenderFrameHostImpl* creator_render_frame_host = nullptr;
  if (creator_render_frame_id_ != MSG_ROUTING_NONE) {
    // Use |worker_process_id_| as the creator render frame's process ID as the
    // frame surely lives in the same process for dedicated workers.
    creator_render_frame_host = RenderFrameHostImpl::FromID(
        worker_process_id_, creator_render_frame_id_);
    if (!creator_render_frame_host) {
      client_->OnScriptLoadStartFailed();
      return;
    }
  }

  // A dedicated worker depends on its nearest ancestor's appcache host.
  AppCacheHost* appcache_host = nullptr;
  const AppCacheNavigationHandle* appcache_handle =
      nearest_ancestor_render_frame_host->GetAppCacheNavigationHandle();
  if (appcache_handle) {
    appcache_host = storage_partition_impl->GetAppCacheService()->GetHost(
        appcache_handle->appcache_host_id());
  }

  // Set if the subresource loader factories support file URLs so that we can
  // recreate the factories after Network Service crashes.
  // TODO(nhiroki): Currently this flag is calculated based on the request
  // initiator origin to keep consistency with WorkerScriptFetchInitiator, but
  // probably this should be calculated based on the worker origin as the
  // factories be used for subresource loading on the worker.
  file_url_support_ = request_initiator_origin.scheme() == url::kFileScheme;

  service_worker_handle_ = std::make_unique<ServiceWorkerNavigationHandle>(
      storage_partition_impl->GetServiceWorkerContext());

  WorkerScriptFetchInitiator::Start(
      worker_process_id_, script_url, creator_render_frame_host,
      request_initiator_origin, network_isolation_key_, credentials_mode,
      std::move(outside_fetch_client_settings_object), ResourceType::kWorker,
      storage_partition_impl->GetServiceWorkerContext(),
      service_worker_handle_.get(),
      appcache_host ? appcache_host->GetWeakPtr() : nullptr,
      std::move(blob_url_loader_factory), nullptr, storage_partition_impl,
      storage_domain,
      base::BindOnce(&DedicatedWorkerHost::DidStartScriptLoad,
                     weak_factory_.GetWeakPtr()));
}

void DedicatedWorkerHost::DidStartScriptLoad(
    std::unique_ptr<blink::PendingURLLoaderFactoryBundle>
        subresource_loader_factories,
    blink::mojom::WorkerMainScriptLoadParamsPtr main_script_load_params,
    blink::mojom::ControllerServiceWorkerInfoPtr controller,
    base::WeakPtr<ServiceWorkerObjectHost>
        controller_service_worker_object_host,
    bool success) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(base::FeatureList::IsEnabled(blink::features::kPlzDedicatedWorker));

  if (!success) {
    client_->OnScriptLoadStartFailed();
    return;
  }

  // TODO(https://crbug.com/986188): Check if the main script's final response
  // URL is commitable.

  auto* worker_process_host = RenderProcessHost::FromID(worker_process_id_);
  if (!worker_process_host) {
    client_->OnScriptLoadStartFailed();
    return;
  }

  // TODO(cammie): Change this approach when we support shared workers
  // creating dedicated workers, as there might be no ancestor frame.
  RenderFrameHostImpl* ancestor_render_frame_host =
      GetAncestorRenderFrameHost();
  if (!ancestor_render_frame_host) {
    client_->OnScriptLoadStartFailed();
    return;
  }

  // Start observing Network Service crash when it's running out-of-process.
  if (IsOutOfProcessNetworkService()) {
    ObserveNetworkServiceCrash(static_cast<StoragePartitionImpl*>(
        worker_process_host->GetStoragePartition()));
  }

  // Set up the default network loader factory.
  bool bypass_redirect_checks = false;
  subresource_loader_factories->pending_default_factory() =
      CreateNetworkFactoryForSubresources(worker_process_host,
                                          ancestor_render_frame_host,
                                          &bypass_redirect_checks);
  subresource_loader_factories->set_bypass_redirect_checks(
      bypass_redirect_checks);

  // Prepare the controller service worker info to pass to the renderer.
  // |object_info| can be nullptr when the service worker context or the
  // service worker version is gone during dedicated worker startup.
  mojo::PendingAssociatedRemote<blink::mojom::ServiceWorkerObject>
      service_worker_remote_object;
  blink::mojom::ServiceWorkerState service_worker_state;
  if (controller && controller->object_info) {
    controller->object_info->receiver =
        service_worker_remote_object.InitWithNewEndpointAndPassReceiver();
    service_worker_state = controller->object_info->state;
  }

  client_->OnScriptLoadStarted(
      service_worker_handle_->TakeProviderInfo(),
      std::move(main_script_load_params),
      std::move(subresource_loader_factories),
      subresource_loader_updater_.BindNewPipeAndPassReceiver(),
      std::move(controller));

  // |service_worker_remote_object| is an associated remote, so calls can't be
  // made on it until its receiver is sent. Now that the receiver was sent, it
  // can be used, so add it to ServiceWorkerObjectHost.
  if (service_worker_remote_object) {
    RunOrPostTaskOnThread(
        FROM_HERE, ServiceWorkerContext::GetCoreThreadId(),
        base::BindOnce(
            &ServiceWorkerObjectHost::AddRemoteObjectPtrAndUpdateState,
            controller_service_worker_object_host,
            std::move(service_worker_remote_object), service_worker_state));
  }
}

mojo::PendingRemote<network::mojom::URLLoaderFactory>
DedicatedWorkerHost::CreateNetworkFactoryForSubresources(
    RenderProcessHost* worker_process_host,
    RenderFrameHostImpl* ancestor_render_frame_host,
    bool* bypass_redirect_checks) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(worker_process_host);
  DCHECK(ancestor_render_frame_host);
  DCHECK(bypass_redirect_checks);

  auto* storage_partition_impl = static_cast<StoragePartitionImpl*>(
      worker_process_host->GetStoragePartition());

  mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_default_factory;
  mojo::PendingReceiver<network::mojom::URLLoaderFactory>
      default_factory_receiver =
          pending_default_factory.InitWithNewPipeAndPassReceiver();

  mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>
      default_header_client;
  network::mojom::URLLoaderFactoryOverridePtr factory_override;
  GetContentClient()->browser()->WillCreateURLLoaderFactory(
      storage_partition_impl->browser_context(),
      /*frame=*/nullptr, worker_process_id_,
      ContentBrowserClient::URLLoaderFactoryType::kWorkerSubResource, origin_,
      /*navigation_id=*/base::nullopt, &default_factory_receiver,
      &default_header_client, bypass_redirect_checks, &factory_override);

  // TODO(nhiroki): Call devtools_instrumentation::WillCreateURLLoaderFactory()
  // here.

  worker_process_host->CreateURLLoaderFactory(
      origin_, origin_,
      ancestor_render_frame_host->cross_origin_embedder_policy(),
      /*preferences=*/nullptr, network_isolation_key_,
      std::move(default_header_client),
      ancestor_render_frame_host->GetTopFrameToken(),
      std::move(default_factory_receiver), std::move(factory_override));

  return pending_default_factory;
}

void DedicatedWorkerHost::CreateWebUsbService(
    mojo::PendingReceiver<blink::mojom::WebUsbService> receiver) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  RenderFrameHostImpl* ancestor_render_frame_host =
      GetAncestorRenderFrameHost();
  // The ancestor frame may have already been closed. In that case, the worker
  // will soon be terminated too, so abort the connection.
  if (!ancestor_render_frame_host)
    return;

  ancestor_render_frame_host->CreateWebUsbService(std::move(receiver));
}

void DedicatedWorkerHost::CreateWebSocketConnector(
    mojo::PendingReceiver<blink::mojom::WebSocketConnector> receiver) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  RenderFrameHostImpl* ancestor_render_frame_host =
      GetAncestorRenderFrameHost();
  if (!ancestor_render_frame_host) {
    // The ancestor frame may have already been closed. In that case, the worker
    // will soon be terminated too, so abort the connection.
    receiver.ResetWithReason(network::mojom::WebSocket::kInsufficientResources,
                             "The parent frame has already been gone.");
    return;
  }
  mojo::MakeSelfOwnedReceiver(std::make_unique<WebSocketConnectorImpl>(
                                  worker_process_id_, ancestor_render_frame_id_,
                                  origin_, network_isolation_key_),
                              std::move(receiver));
}

void DedicatedWorkerHost::CreateQuicTransportConnector(
    mojo::PendingReceiver<blink::mojom::QuicTransportConnector> receiver) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  RenderFrameHostImpl* ancestor_render_frame_host =
      GetAncestorRenderFrameHost();
  if (!ancestor_render_frame_host) {
    // The ancestor frame may have already been closed. In that case, the worker
    // will soon be terminated too, so abort the connection.
    return;
  }
  mojo::MakeSelfOwnedReceiver(
      std::make_unique<QuicTransportConnectorImpl>(worker_process_id_, origin_,
                                                   network_isolation_key_),
      std::move(receiver));
}

void DedicatedWorkerHost::CreateNestedDedicatedWorker(
    mojo::PendingReceiver<blink::mojom::DedicatedWorkerHostFactory> receiver) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  CreateDedicatedWorkerHostFactory(worker_process_id_,
                                   ancestor_render_frame_id_,
                                   /*creator_render_frame_id=*/MSG_ROUTING_NONE,
                                   origin_, std::move(receiver));
}

void DedicatedWorkerHost::CreateIdleManager(
    mojo::PendingReceiver<blink::mojom::IdleManager> receiver) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  RenderFrameHostImpl* ancestor_render_frame_host =
      GetAncestorRenderFrameHost();
  if (!ancestor_render_frame_host) {
    // The ancestor frame may have already been closed. In that case, the worker
    // will soon be terminated too, so abort the connection.
    return;
  }
  if (!ancestor_render_frame_host->IsFeatureEnabled(
          blink::mojom::FeaturePolicyFeature::kIdleDetection)) {
    mojo::ReportBadMessage("Feature policy blocks access to IdleDetection.");
    return;
  }
  static_cast<StoragePartitionImpl*>(
      ancestor_render_frame_host->GetProcess()->GetStoragePartition())
      ->GetIdleManager()
      ->CreateService(std::move(receiver));
}

void DedicatedWorkerHost::BindSmsReceiverReceiver(
    mojo::PendingReceiver<blink::mojom::SmsReceiver> receiver) {
  RenderFrameHostImpl* ancestor_render_frame_host =
      GetAncestorRenderFrameHost();
  if (!ancestor_render_frame_host) {
    // The ancestor frame may have already been closed. In that case, the worker
    // will soon be terminated too, so abort the connection.
    return;
  }

  ancestor_render_frame_host->BindSmsReceiverReceiver(std::move(receiver));
}

#if !defined(OS_ANDROID)
void DedicatedWorkerHost::BindSerialService(
    mojo::PendingReceiver<blink::mojom::SerialService> receiver) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  RenderFrameHostImpl* ancestor_render_frame_host =
      GetAncestorRenderFrameHost();
  if (!ancestor_render_frame_host) {
    // The ancestor frame may have already been closed. In that case, the worker
    // will soon be terminated too, so abort the connection.
    return;
  }

  ancestor_render_frame_host->BindSerialService(std::move(receiver));
}
#endif

void DedicatedWorkerHost::ObserveNetworkServiceCrash(
    StoragePartitionImpl* storage_partition_impl) {
  auto params = network::mojom::URLLoaderFactoryParams::New();
  params->process_id = worker_process_id_;
  network_service_connection_error_handler_holder_.reset();
  storage_partition_impl->GetNetworkContext()->CreateURLLoaderFactory(
      network_service_connection_error_handler_holder_
          .BindNewPipeAndPassReceiver(),
      std::move(params));
  network_service_connection_error_handler_holder_.set_disconnect_handler(
      base::BindOnce(&DedicatedWorkerHost::UpdateSubresourceLoaderFactories,
                     weak_factory_.GetWeakPtr()));
}

void DedicatedWorkerHost::UpdateSubresourceLoaderFactories() {
  DCHECK(IsOutOfProcessNetworkService());
  DCHECK(subresource_loader_updater_.is_bound());
  DCHECK(network_service_connection_error_handler_holder_);
  DCHECK(!network_service_connection_error_handler_holder_.is_connected());

  // Get a storage partition.
  auto* worker_process_host = RenderProcessHost::FromID(worker_process_id_);
  if (!worker_process_host)
    return;
  auto* storage_partition_impl = static_cast<StoragePartitionImpl*>(
      worker_process_host->GetStoragePartition());

  // Get a storage domain.
  if (!GetAncestorRenderFrameHost() ||
      !GetAncestorRenderFrameHost()->GetSiteInstance())
    return;
  std::string storage_domain;
  std::string partition_name;
  bool in_memory;
  GetContentClient()->browser()->GetStoragePartitionConfigForSite(
      storage_partition_impl->browser_context(),
      GetAncestorRenderFrameHost()->GetSiteInstance()->GetSiteURL(),
      /*can_be_default=*/true, &storage_domain, &partition_name, &in_memory);

  // Start observing Network Service crash again.
  ObserveNetworkServiceCrash(storage_partition_impl);

  // Recreate the default URLLoaderFactory. This doesn't support
  // AppCache-specific factory.
  std::unique_ptr<blink::PendingURLLoaderFactoryBundle>
      subresource_loader_factories =
          WorkerScriptFetchInitiator::CreateFactoryBundle(
              WorkerScriptFetchInitiator::LoaderType::kSubResource,
              worker_process_id_, storage_partition_impl, storage_domain,
              file_url_support_, /*filesystem_url_support=*/true);

  bool bypass_redirect_checks = false;
  subresource_loader_factories->pending_default_factory() =
      CreateNetworkFactoryForSubresources(worker_process_host,
                                          GetAncestorRenderFrameHost(),
                                          &bypass_redirect_checks);
  subresource_loader_factories->set_bypass_redirect_checks(
      bypass_redirect_checks);

  subresource_loader_updater_->UpdateSubresourceLoaderFactories(
      std::move(subresource_loader_factories));
}

// May return a nullptr.
RenderFrameHostImpl* DedicatedWorkerHost::GetAncestorRenderFrameHost() {
  // Use |worker_process_id_| as the ancestor render frame's process ID as the
  // frame surely lives in the same process for dedicated workers.
  const int ancestor_render_frame_process_id = worker_process_id_;
  return RenderFrameHostImpl::FromID(ancestor_render_frame_process_id,
                                     ancestor_render_frame_id_);
}

namespace {
// A factory for creating DedicatedWorkerHosts. Its lifetime is managed by the
// renderer over mojo via SelfOwnedReceiver. It lives on the UI thread.
class DedicatedWorkerHostFactoryImpl final
    : public blink::mojom::DedicatedWorkerHostFactory {
 public:
  DedicatedWorkerHostFactoryImpl(int creator_process_id,
                                 int ancestor_render_frame_id,
                                 int creator_render_frame_id,
                                 const url::Origin& parent_context_origin)
      : creator_process_id_(creator_process_id),
        ancestor_render_frame_id_(ancestor_render_frame_id),
        creator_render_frame_id_(creator_render_frame_id),
        parent_context_origin_(parent_context_origin) {
    DCHECK_CURRENTLY_ON(BrowserThread::UI);
  }

  // blink::mojom::DedicatedWorkerHostFactory:
  void CreateWorkerHost(
      const url::Origin& origin,
      mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker>
          broker_receiver,
      mojo::PendingReceiver<blink::mojom::DedicatedWorkerHost> host_receiver)
      override {
    DCHECK_CURRENTLY_ON(BrowserThread::UI);
    if (base::FeatureList::IsEnabled(blink::features::kPlzDedicatedWorker)) {
      mojo::ReportBadMessage("DWH_INVALID_WORKER_CREATION");
      return;
    }

    // TODO(crbug.com/729021): Once |parent_context_origin_| no longer races
    // with the request for |DedicatedWorkerHostFactory|, enforce that
    // the worker's origin either matches the origin of the creating context
    // (Document or DedicatedWorkerGlobalScope), or is unique.
    // Deletes itself on Mojo disconnection.
    auto* host = new DedicatedWorkerHost(
        creator_process_id_, ancestor_render_frame_id_,
        creator_render_frame_id_, origin, std::move(host_receiver));
    host->BindBrowserInterfaceBrokerReceiver(std::move(broker_receiver));
  }

  // PlzDedicatedWorker:
  void CreateWorkerHostAndStartScriptLoad(
      const GURL& script_url,
      const url::Origin& request_initiator_origin,
      network::mojom::CredentialsMode credentials_mode,
      blink::mojom::FetchClientSettingsObjectPtr
          outside_fetch_client_settings_object,
      mojo::PendingRemote<blink::mojom::BlobURLToken> blob_url_token,
      mojo::PendingRemote<blink::mojom::DedicatedWorkerHostFactoryClient>
          client,
      mojo::PendingReceiver<blink::mojom::DedicatedWorkerHost> host_receiver)
      override {
    DCHECK_CURRENTLY_ON(BrowserThread::UI);
    if (!base::FeatureList::IsEnabled(blink::features::kPlzDedicatedWorker)) {
      mojo::ReportBadMessage("DWH_BROWSER_SCRIPT_FETCH_DISABLED");
      return;
    }

    // Create a worker host that will start a new dedicated worker in the
    // renderer process whose ID is |creator_process_id_|.
    //
    // TODO(crbug.com/729021): Once |parent_context_origin_| no longer races
    // with the request for |DedicatedWorkerHostFactory|, enforce that
    // the worker's origin either matches the origin of the creating context
    // (Document or DedicatedWorkerGlobalScope), or is unique.
    // Deletes itself on Mojo disconnection.
    auto* host = new DedicatedWorkerHost(
        creator_process_id_, ancestor_render_frame_id_,
        creator_render_frame_id_, request_initiator_origin,
        std::move(host_receiver));
    mojo::PendingRemote<blink::mojom::BrowserInterfaceBroker> broker;
    host->BindBrowserInterfaceBrokerReceiver(
        broker.InitWithNewPipeAndPassReceiver());
    mojo::Remote<blink::mojom::DedicatedWorkerHostFactoryClient> remote_client(
        std::move(client));
    remote_client->OnWorkerHostCreated(std::move(broker));
    host->StartScriptLoad(script_url, request_initiator_origin,
                          credentials_mode,
                          std::move(outside_fetch_client_settings_object),
                          std::move(blob_url_token), std::move(remote_client));
  }

 private:
  // See comments on the corresponding members of DedicatedWorkerHost.
  const int creator_process_id_;
  const int ancestor_render_frame_id_;
  const int creator_render_frame_id_;

  const url::Origin parent_context_origin_;

  DISALLOW_COPY_AND_ASSIGN(DedicatedWorkerHostFactoryImpl);
};

}  // namespace

void CreateDedicatedWorkerHostFactory(
    int creator_process_id,
    int ancestor_render_frame_id,
    int creator_render_frame_id,
    const url::Origin& origin,
    mojo::PendingReceiver<blink::mojom::DedicatedWorkerHostFactory> receiver) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  mojo::MakeSelfOwnedReceiver(std::make_unique<DedicatedWorkerHostFactoryImpl>(
                                  creator_process_id, ancestor_render_frame_id,
                                  creator_render_frame_id, origin),
                              std::move(receiver));
}

}  // namespace content