summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/loader/document_loader_test.cc
blob: c680b9071207e170648e8705fb3f3a137ede389b (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
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
// Copyright 2015 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 "third_party/blink/renderer/core/loader/document_loader.h"

#include <utility>

#include "base/auto_reset.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom-shared.h"
#include "third_party/blink/public/mojom/feature_policy/policy_disposition.mojom-blink.h"
#include "third_party/blink/public/mojom/frame/frame_owner_element_type.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_url_loader_client.h"
#include "third_party/blink/public/platform/web_url_loader_mock_factory.h"
#include "third_party/blink/renderer/core/frame/frame_test_helpers.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/testing/scoped_fake_plugin_registry.h"
#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
#include "third_party/blink/renderer/platform/loader/static_data_navigation_body_loader.h"
#include "third_party/blink/renderer/platform/testing/histogram_tester.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
#include "third_party/blink/renderer/platform/wtf/deque.h"

namespace blink {

class DocumentLoaderTest : public testing::Test {
 protected:
  void SetUp() override {
    web_view_helper_.Initialize();
    url_test_helpers::RegisterMockedURLLoad(
        url_test_helpers::ToKURL("https://example.com/foo.html"),
        test::CoreTestDataPath("foo.html"));
    url_test_helpers::RegisterMockedURLLoad(
        url_test_helpers::ToKURL("https://example.com:8000/foo.html"),
        test::CoreTestDataPath("foo.html"));
  }

  void TearDown() override {
    url_test_helpers::UnregisterAllURLsAndClearMemoryCache();
  }

  class ScopedLoaderDelegate {
   public:
    ScopedLoaderDelegate(WebURLLoaderTestDelegate* delegate) {
      url_test_helpers::SetLoaderDelegate(delegate);
    }
    ~ScopedLoaderDelegate() { url_test_helpers::SetLoaderDelegate(nullptr); }
  };

  WebLocalFrameImpl* MainFrame() { return web_view_helper_.LocalMainFrame(); }

  frame_test_helpers::WebViewHelper web_view_helper_;
};

TEST_F(DocumentLoaderTest, SingleChunk) {
  class TestDelegate : public WebURLLoaderTestDelegate {
   public:
    void DidReceiveData(WebURLLoaderClient* original_client,
                        const char* data,
                        int data_length) override {
      EXPECT_EQ(34, data_length) << "foo.html was not served in a single chunk";
      original_client->DidReceiveData(data, data_length);
    }
  } delegate;

  ScopedLoaderDelegate loader_delegate(&delegate);
  frame_test_helpers::LoadFrame(MainFrame(), "https://example.com/foo.html");

  // TODO(dcheng): How should the test verify that the original callback is
  // invoked? The test currently still passes even if the test delegate
  // forgets to invoke the callback.
}

// Test normal case of DocumentLoader::dataReceived(): data in multiple chunks,
// with no reentrancy.
TEST_F(DocumentLoaderTest, MultiChunkNoReentrancy) {
  class TestDelegate : public WebURLLoaderTestDelegate {
   public:
    void DidReceiveData(WebURLLoaderClient* original_client,
                        const char* data,
                        int data_length) override {
      EXPECT_EQ(34, data_length) << "foo.html was not served in a single chunk";
      // Chunk the reply into one byte chunks.
      for (int i = 0; i < data_length; ++i)
        original_client->DidReceiveData(&data[i], 1);
    }
  } delegate;

  ScopedLoaderDelegate loader_delegate(&delegate);
  frame_test_helpers::LoadFrame(MainFrame(), "https://example.com/foo.html");
}

// Finally, test reentrant callbacks to DocumentLoader::BodyDataReceived().
TEST_F(DocumentLoaderTest, MultiChunkWithReentrancy) {
  // This test delegate chunks the response stage into three distinct stages:
  // 1. The first BodyDataReceived() callback, which triggers frame detach
  //    due to committing a provisional load.
  // 2. The middle part of the response, which is dispatched to
  //    BodyDataReceived() reentrantly.
  // 3. The final chunk, which is dispatched normally at the top-level.
  class MainFrameClient : public WebURLLoaderTestDelegate,
                          public frame_test_helpers::TestWebFrameClient {
   public:
    // WebURLLoaderTestDelegate overrides:
    bool FillNavigationParamsResponse(WebNavigationParams* params) override {
      params->response = WebURLResponse(params->url);
      params->response.SetMimeType("application/x-webkit-test-webplugin");
      params->response.SetHttpStatusCode(200);

      String data("<html><body>foo</body></html>");
      for (wtf_size_t i = 0; i < data.length(); i++)
        data_.push_back(data[i]);

      auto body_loader = std::make_unique<StaticDataNavigationBodyLoader>();
      body_loader_ = body_loader.get();
      params->body_loader = std::move(body_loader);
      return true;
    }

    void Serve() {
      {
        // Serve the first byte to the real WebURLLoaderCLient, which
        // should trigger frameDetach() due to committing a provisional
        // load.
        base::AutoReset<bool> dispatching(&dispatching_did_receive_data_, true);
        DispatchOneByte();
      }

      // Serve the remaining bytes to complete the load.
      EXPECT_FALSE(data_.IsEmpty());
      while (!data_.IsEmpty())
        DispatchOneByte();

      body_loader_->Finish();
      body_loader_ = nullptr;
    }

    // WebLocalFrameClient overrides:
    void RunScriptsAtDocumentElementAvailable() override {
      if (dispatching_did_receive_data_) {
        // This should be called by the first BodyDataReceived() call, since
        // it should create a plugin document structure and trigger this.
        EXPECT_GT(data_.size(), 10u);
        // Dispatch BodyDataReceived() callbacks for part of the remaining
        // data, saving the rest to be dispatched at the top-level as
        // normal.
        while (data_.size() > 10)
          DispatchOneByte();
        served_reentrantly_ = true;
      }
      TestWebFrameClient::RunScriptsAtDocumentElementAvailable();
    }

    void DispatchOneByte() {
      char c = data_.TakeFirst();
      body_loader_->Write(&c, 1);
    }

    bool ServedReentrantly() const { return served_reentrantly_; }

   private:
    Deque<char> data_;
    bool dispatching_did_receive_data_ = false;
    bool served_reentrantly_ = false;
    StaticDataNavigationBodyLoader* body_loader_ = nullptr;
  };

  // We use a plugin document triggered by "application/x-webkit-test-webplugin"
  // mime type, because that gives us reliable way to get a WebLocalFrameClient
  // callback from inside BodyDataReceived() call.
  ScopedFakePluginRegistry fake_plugins;
  MainFrameClient main_frame_client;
  web_view_helper_.Initialize(&main_frame_client);
  web_view_helper_.GetWebView()->GetPage()->GetSettings().SetPluginsEnabled(
      true);

  {
    ScopedLoaderDelegate loader_delegate(&main_frame_client);
    frame_test_helpers::LoadFrameDontWait(
        MainFrame(), url_test_helpers::ToKURL("https://example.com/foo.html"));
    main_frame_client.Serve();
    frame_test_helpers::PumpPendingRequestsForFrameToLoad(MainFrame());
  }

  // Sanity check that we did actually test reeentrancy.
  EXPECT_TRUE(main_frame_client.ServedReentrantly());

  // MainFrameClient is stack-allocated, so manually Reset to avoid UAF.
  web_view_helper_.Reset();
}

TEST_F(DocumentLoaderTest, isCommittedButEmpty) {
  WebViewImpl* web_view_impl =
      web_view_helper_.InitializeAndLoad("about:blank");
  EXPECT_TRUE(To<LocalFrame>(web_view_impl->GetPage()->MainFrame())
                  ->Loader()
                  .GetDocumentLoader()
                  ->IsCommittedButEmpty());
}

class DocumentLoaderSimTest : public SimTest {};

TEST_F(DocumentLoaderSimTest, DocumentOpenUpdatesUrl) {
  SimRequest main_resource("https://example.com", "text/html");
  LoadURL("https://example.com");
  main_resource.Write("<iframe src='javascript:42;'></iframe>");

  auto* child_frame = To<WebLocalFrameImpl>(MainFrame().FirstChild());
  auto* child_document = child_frame->GetFrame()->GetDocument();
  EXPECT_TRUE(child_document->HasPendingJavaScriptUrlsForTest());

  main_resource.Write(
      "<script>"
      "window[0].document.open();"
      "window[0].document.write('hello');"
      "window[0].document.close();"
      "</script>");

  main_resource.Finish();

  // document.open() should have cancelled the pending JavaScript URLs.
  EXPECT_FALSE(child_document->HasPendingJavaScriptUrlsForTest());

  // Per https://whatwg.org/C/dynamic-markup-insertion.html#document-open-steps,
  // the URL associated with the Document should match the URL of the entry
  // Document.
  EXPECT_EQ(KURL("https://example.com"), child_document->Url());
  // Similarly, the URL of the DocumentLoader should also match.
  EXPECT_EQ(KURL("https://example.com"), child_document->Loader()->Url());
}

TEST_F(DocumentLoaderSimTest, FramePolicyIntegrityOnNavigationCommit) {
  SimRequest main_resource("https://example.com", "text/html");
  SimRequest iframe_resource("https://example.com/foo.html", "text/html");
  LoadURL("https://example.com");

  main_resource.Write(R"(
    <iframe id='frame1'></iframe>
    <script>
      const iframe = document.getElementById('frame1');
      iframe.src = 'https://example.com/foo.html'; // navigation triggered
      iframe.allow = "payment 'none'"; // should not take effect until the
                                       // next navigation on iframe
    </script>
  )");

  main_resource.Finish();
  iframe_resource.Finish();

  auto* child_frame = To<WebLocalFrameImpl>(MainFrame().FirstChild());
  auto* child_document = child_frame->GetFrame()->GetDocument();

  EXPECT_TRUE(child_document->IsFeatureEnabled(
      blink::mojom::blink::FeaturePolicyFeature::kPayment));
}
// When runtime feature DocumentPolicy is not enabled, specifying
// Document-Policy and Require-Document-Policy should have no effect, i.e.
// document load should not be blocked even if the required policy and incoming
// policy are incompatible and calling
// |Document::IsFeatureEnabled(DocumentPolicyFeature...)| should always return
// true.
TEST_F(DocumentLoaderSimTest, DocumentPolicyNoEffectWhenFlagNotSet) {
  blink::ScopedDocumentPolicyForTest sdp(false);
  SimRequest::Params params;
  params.response_http_headers = {
      {"Document-Policy", "unoptimized-lossless-images;bpp=1.1"}};

  SimRequest main_resource("https://example.com", "text/html");
  SimRequest iframe_resource("https://example.com/foo.html", "text/html",
                             params);

  LoadURL("https://example.com");
  main_resource.Complete(R"(
    <iframe
      src="https://example.com/foo.html"
      policy="unoptimized-lossless-images;bpp=1.0">
    </iframe>
  )");

  iframe_resource.Finish();
  auto* child_frame = To<WebLocalFrameImpl>(MainFrame().FirstChild());
  auto* child_document = child_frame->GetFrame()->GetDocument();
  auto& console_messages = static_cast<frame_test_helpers::TestWebFrameClient*>(
                               child_frame->Client())
                               ->ConsoleMessages();

  // Should not receive a console error message caused by document policy
  // violation blocking document load.
  EXPECT_TRUE(console_messages.IsEmpty());

  EXPECT_EQ(child_document->Url(), KURL("https://example.com/foo.html"));

  EXPECT_FALSE(child_document->IsUseCounted(
      mojom::WebFeature::kDocumentPolicyCausedPageUnload));

  // Unoptimized-lossless-images should still be allowed in main document.
  EXPECT_TRUE(GetDocument().IsFeatureEnabled(
      mojom::blink::DocumentPolicyFeature::kUnoptimizedLosslessImages,
      PolicyValue(2.0)));
  EXPECT_TRUE(GetDocument().IsFeatureEnabled(
      mojom::blink::DocumentPolicyFeature::kUnoptimizedLosslessImages,
      PolicyValue(1.0)));

  // Unoptimized-lossless-images should still be allowed in child document.
  EXPECT_TRUE(child_document->IsFeatureEnabled(
      mojom::blink::DocumentPolicyFeature::kUnoptimizedLosslessImages,
      PolicyValue(2.0)));
  EXPECT_TRUE(child_document->IsFeatureEnabled(
      mojom::blink::DocumentPolicyFeature::kUnoptimizedLosslessImages,
      PolicyValue(1.0)));
}

TEST_F(DocumentLoaderSimTest, ReportDocumentPolicyHeaderParsingError) {
  blink::ScopedDocumentPolicyForTest sdp(true);
  SimRequest::Params params;
  params.response_http_headers = {{"Document-Policy", "bad-feature-name"}};
  SimRequest main_resource("https://example.com", "text/html", params);
  LoadURL("https://example.com");
  main_resource.Finish();

  EXPECT_EQ(ConsoleMessages().size(), 1u);
  EXPECT_TRUE(
      ConsoleMessages().front().StartsWith("Document-Policy HTTP header:"));
}

TEST_F(DocumentLoaderSimTest, ReportRequireDocumentPolicyHeaderParsingError) {
  blink::ScopedDocumentPolicyForTest sdp(true);
  SimRequest::Params params;
  params.response_http_headers = {
      {"Require-Document-Policy", "bad-feature-name"}};
  SimRequest main_resource("https://example.com", "text/html", params);
  LoadURL("https://example.com");
  main_resource.Finish();

  EXPECT_EQ(ConsoleMessages().size(), 1u);
  EXPECT_TRUE(ConsoleMessages().front().StartsWith(
      "Require-Document-Policy HTTP header:"));
}

TEST_F(DocumentLoaderSimTest, ReportErrorWhenDocumentPolicyIncompatible) {
  blink::ScopedDocumentPolicyForTest sdp(true);
  SimRequest::Params params;
  params.response_http_headers = {
      {"Document-Policy", "unoptimized-lossless-images;bpp=1.1"}};

  SimRequest main_resource("https://example.com", "text/html");
  SimRequest iframe_resource("https://example.com/foo.html", "text/html",
                             params);

  LoadURL("https://example.com");
  main_resource.Complete(R"(
    <iframe
      src="https://example.com/foo.html"
      policy="unoptimized-lossless-images;bpp=1.0">
    </iframe>
  )");

  // When blocked by document policy, the document should be filled in with an
  // empty response, with Finish called on |navigation_body_loader| already.
  // If Finish was not called on the loader, because the document was not
  // blocked, this test will fail by crashing here.
  iframe_resource.Finish(true /* body_loader_finished */);

  auto* child_frame = To<WebLocalFrameImpl>(MainFrame().FirstChild());
  auto* child_document = child_frame->GetFrame()->GetDocument();

  // Should console log a error message.
  auto& console_messages = static_cast<frame_test_helpers::TestWebFrameClient*>(
                               child_frame->Client())
                               ->ConsoleMessages();

  ASSERT_EQ(console_messages.size(), 1u);
  EXPECT_TRUE(console_messages.front().Contains("document policy"));

  // Should replace the document's origin with an opaque origin.
  EXPECT_EQ(child_document->Url(), SecurityOrigin::UrlWithUniqueOpaqueOrigin());

  EXPECT_TRUE(child_document->IsUseCounted(
      mojom::WebFeature::kDocumentPolicyCausedPageUnload));
}

// HTTP header Require-Document-Policy should only take effect on subtree of
// current document, but not on current document.
TEST_F(DocumentLoaderSimTest,
       RequireDocumentPolicyHeaderShouldNotAffectCurrentDocument) {
  blink::ScopedDocumentPolicyForTest sdp(true);
  SimRequest::Params params;
  params.response_http_headers = {
      {"Require-Document-Policy", "unoptimized-lossless-images;bpp=1.0"},
      {"Document-Policy", "unoptimized-lossless-images;bpp=1.1"}};

  SimRequest main_resource("https://example.com", "text/html", params);
  LoadURL("https://example.com");
  // If document is blocked by document policy because of incompatible document
  // policy, this test will fail by crashing here.
  main_resource.Finish();
}

TEST_F(DocumentLoaderSimTest, DocumentPolicyHeaderHistogramTest) {
  blink::ScopedDocumentPolicyForTest sdp(true);
  HistogramTester histogram_tester;

  SimRequest::Params params;
  params.response_http_headers = {
      {"Document-Policy",
       "font-display-late-swap, unoptimized-lossless-images;bpp=1.1"}};

  SimRequest main_resource("https://example.com", "text/html", params);
  LoadURL("https://example.com");
  main_resource.Finish();

  histogram_tester.ExpectTotalCount("Blink.UseCounter.DocumentPolicy.Header",
                                    2);
  histogram_tester.ExpectBucketCount("Blink.UseCounter.DocumentPolicy.Header",
                                     1 /* kFontDisplay */, 1);
  histogram_tester.ExpectBucketCount("Blink.UseCounter.DocumentPolicy.Header",
                                     2 /* kUnoptimizedLosslessImages */, 1);
}

TEST_F(DocumentLoaderSimTest, DocumentPolicyPolicyAttributeHistogramTest) {
  blink::ScopedDocumentPolicyForTest sdp(true);
  HistogramTester histogram_tester;

  SimRequest main_resource("https://example.com", "text/html");
  LoadURL("https://example.com");

  // Same feature should only be reported once in a document despite its
  // occurrence.
  main_resource.Complete(R"(
    <iframe policy="font-display-late-swap"></iframe>
    <iframe policy="no-font-display-late-swap"></iframe>
    <iframe
      policy="font-display-late-swap, unoptimized-lossless-images;bpp=1.1">
    </iframe>
  )");

  histogram_tester.ExpectTotalCount(
      "Blink.UseCounter.DocumentPolicy.PolicyAttribute", 2);
  histogram_tester.ExpectBucketCount(
      "Blink.UseCounter.DocumentPolicy.PolicyAttribute", 1 /* kFontDisplay */,
      1);
  histogram_tester.ExpectBucketCount(
      "Blink.UseCounter.DocumentPolicy.PolicyAttribute",
      2 /* kUnoptimizedLosslessImages */, 1);
}

TEST_F(DocumentLoaderSimTest, DocumentPolicyEnforcedReportHistogramTest) {
  blink::ScopedDocumentPolicyForTest sdp(true);
  HistogramTester histogram_tester;

  SimRequest main_resource("https://example.com", "text/html");
  LoadURL("https://example.com");
  main_resource.Finish();

  Window().ReportDocumentPolicyViolation(
      mojom::blink::DocumentPolicyFeature::kFontDisplay,
      mojom::blink::PolicyDisposition::kEnforce);

  histogram_tester.ExpectTotalCount("Blink.UseCounter.DocumentPolicy.Enforced",
                                    1);
  histogram_tester.ExpectBucketCount("Blink.UseCounter.DocumentPolicy.Enforced",
                                     1 /* kFontDisplay */, 1);

  // Multiple reports should be recorded multiple times.
  Window().ReportDocumentPolicyViolation(
      mojom::blink::DocumentPolicyFeature::kFontDisplay,
      mojom::blink::PolicyDisposition::kEnforce);

  histogram_tester.ExpectTotalCount("Blink.UseCounter.DocumentPolicy.Enforced",
                                    2);
  histogram_tester.ExpectBucketCount("Blink.UseCounter.DocumentPolicy.Enforced",
                                     1 /* kFontDisplay */, 2);
}

TEST_F(DocumentLoaderSimTest, DocumentPolicyReportOnlyReportHistogramTest) {
  blink::ScopedDocumentPolicyForTest sdp(true);
  HistogramTester histogram_tester;

  SimRequest::Params params;
  params.response_http_headers = {
      {"Document-Policy-Report-Only", "font-display-late-swap"}};
  SimRequest main_resource("https://example.com", "text/html", params);

  LoadURL("https://example.com");
  main_resource.Finish();

  Window().ReportDocumentPolicyViolation(
      mojom::blink::DocumentPolicyFeature::kFontDisplay,
      mojom::blink::PolicyDisposition::kReport);

  histogram_tester.ExpectTotalCount(
      "Blink.UseCounter.DocumentPolicy.ReportOnly", 1);
  histogram_tester.ExpectBucketCount(
      "Blink.UseCounter.DocumentPolicy.ReportOnly", 1 /* kFontDisplay */, 1);

  // Multiple reports should be recorded multiple times.
  Window().ReportDocumentPolicyViolation(
      mojom::blink::DocumentPolicyFeature::kFontDisplay,
      mojom::blink::PolicyDisposition::kReport);

  histogram_tester.ExpectTotalCount(
      "Blink.UseCounter.DocumentPolicy.ReportOnly", 2);
  histogram_tester.ExpectBucketCount(
      "Blink.UseCounter.DocumentPolicy.ReportOnly", 1 /* kFontDisplay */, 2);
}

class DocumentPolicyHeaderUseCounterTest
    : public DocumentLoaderSimTest,
      public testing::WithParamInterface<std::tuple<bool, bool, bool>> {};

TEST_P(DocumentPolicyHeaderUseCounterTest, ShouldObserveUseCounterUpdate) {
  blink::ScopedDocumentPolicyForTest sdp(true);

  bool has_document_policy_header, has_report_only_header, has_require_header;
  std::tie(has_document_policy_header, has_report_only_header,
           has_require_header) = GetParam();

  SimRequest::Params params;
  if (has_document_policy_header) {
    params.response_http_headers.insert("Document-Policy",
                                        "unoptimized-lossless-images;bpp=1.0");
  }
  if (has_report_only_header) {
    params.response_http_headers.insert("Document-Policy-Report-Only",
                                        "unoptimized-lossless-images;bpp=1.0");
  }
  if (has_require_header) {
    params.response_http_headers.insert("Require-Document-Policy",
                                        "unoptimized-lossless-images;bpp=1.0");
  }
  SimRequest main_resource("https://example.com", "text/html", params);
  LoadURL("https://example.com");
  main_resource.Complete();

  EXPECT_EQ(
      GetDocument().IsUseCounted(mojom::WebFeature::kDocumentPolicyHeader),
      has_document_policy_header);
  EXPECT_EQ(GetDocument().IsUseCounted(
                mojom::WebFeature::kDocumentPolicyReportOnlyHeader),
            has_report_only_header);
  EXPECT_EQ(GetDocument().IsUseCounted(
                mojom::WebFeature::kRequireDocumentPolicyHeader),
            has_require_header);
}

INSTANTIATE_TEST_SUITE_P(DocumentPolicyHeaderValues,
                         DocumentPolicyHeaderUseCounterTest,
                         ::testing::Combine(::testing::Bool(),
                                            ::testing::Bool(),
                                            ::testing::Bool()));

TEST_F(DocumentLoaderSimTest,
       DocumentPolicyIframePolicyAttributeUseCounterTest) {
  blink::ScopedDocumentPolicyForTest sdp(true);
  SimRequest main_resource("https://example.com", "text/html");
  SimRequest::Params iframe_params;
  iframe_params.response_http_headers = {
      {"Document-Policy", "unoptimized-lossless-images;bpp=1.0"}};
  SimRequest iframe_resource("https://example.com/foo.html", "text/html",
                             iframe_params);
  LoadURL("https://example.com");
  main_resource.Complete(R"(
    <iframe
      src="https://example.com/foo.html"
      policy="unoptimized-lossless-images;bpp=1.0"
    ></iframe>
  )");
  iframe_resource.Finish();

  EXPECT_TRUE(GetDocument().IsUseCounted(
      mojom::WebFeature::kDocumentPolicyIframePolicyAttribute));
  EXPECT_FALSE(
      GetDocument().IsUseCounted(mojom::WebFeature::kRequiredDocumentPolicy));

  auto* child_frame = To<WebLocalFrameImpl>(MainFrame().FirstChild());
  auto* child_document = child_frame->GetFrame()->GetDocument();

  EXPECT_FALSE(child_document->IsUseCounted(
      mojom::WebFeature::kDocumentPolicyIframePolicyAttribute));
  EXPECT_TRUE(
      child_document->IsUseCounted(mojom::WebFeature::kRequiredDocumentPolicy));
}

TEST_F(DocumentLoaderSimTest, RequiredDocumentPolicyUseCounterTest) {
  blink::ScopedDocumentPolicyForTest sdp(true);

  SimRequest::Params main_frame_params;
  main_frame_params.response_http_headers = {
      {"Require-Document-Policy", "unoptimized-lossless-images;bpp=1.0"}};
  SimRequest main_resource("https://example.com", "text/html",
                           main_frame_params);

  SimRequest::Params iframe_params;
  iframe_params.response_http_headers = {
      {"Document-Policy", "unoptimized-lossless-images;bpp=1.0"}};
  SimRequest iframe_resource("https://example.com/foo.html", "text/html",
                             iframe_params);

  LoadURL("https://example.com");
  main_resource.Complete(R"(
    <iframe src="https://example.com/foo.html"></iframe>
  )");
  iframe_resource.Finish();

  EXPECT_FALSE(GetDocument().IsUseCounted(
      mojom::WebFeature::kDocumentPolicyIframePolicyAttribute));
  EXPECT_FALSE(
      GetDocument().IsUseCounted(mojom::WebFeature::kRequiredDocumentPolicy));

  auto* child_frame = To<WebLocalFrameImpl>(MainFrame().FirstChild());
  auto* child_document = child_frame->GetFrame()->GetDocument();

  EXPECT_FALSE(child_document->IsUseCounted(
      mojom::WebFeature::kDocumentPolicyIframePolicyAttribute));
  EXPECT_TRUE(
      child_document->IsUseCounted(mojom::WebFeature::kRequiredDocumentPolicy));
}

TEST_F(DocumentLoaderTest, CommitsDeferredOnSameOriginNavigation) {
  const KURL& requestor_url =
      KURL(NullURL(), "https://www.example.com/foo.html");
  WebViewImpl* web_view_impl =
      web_view_helper_.InitializeAndLoad("https://example.com/foo.html");

  const KURL& same_origin_url =
      KURL(NullURL(), "https://www.example.com/bar.html");
  std::unique_ptr<WebNavigationParams> params =
      WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(),
                                                same_origin_url);
  params->requestor_origin = WebSecurityOrigin::Create(WebURL(requestor_url));
  LocalFrame* local_frame =
      To<LocalFrame>(web_view_impl->GetPage()->MainFrame());
  local_frame->Loader().CommitNavigation(std::move(params), nullptr);

  EXPECT_TRUE(local_frame->GetDocument()->DeferredCompositorCommitIsAllowed());
}

TEST_F(DocumentLoaderTest, CommitsNotDeferredOnDifferentOriginNavigation) {
  const KURL& requestor_url =
      KURL(NullURL(), "https://www.example.com/foo.html");
  WebViewImpl* web_view_impl =
      web_view_helper_.InitializeAndLoad("https://example.com/foo.html");

  const KURL& other_origin_url =
      KURL(NullURL(), "https://www.another.com/bar.html");
  std::unique_ptr<WebNavigationParams> params =
      WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(),
                                                other_origin_url);
  params->requestor_origin = WebSecurityOrigin::Create(WebURL(requestor_url));
  LocalFrame* local_frame =
      To<LocalFrame>(web_view_impl->GetPage()->MainFrame());
  local_frame->Loader().CommitNavigation(std::move(params), nullptr);

  EXPECT_FALSE(local_frame->GetDocument()->DeferredCompositorCommitIsAllowed());
}

TEST_F(DocumentLoaderTest, CommitsNotDeferredOnDifferentPortNavigation) {
  const KURL& requestor_url =
      KURL(NullURL(), "https://www.example.com:8000/foo.html");
  WebViewImpl* web_view_impl =
      web_view_helper_.InitializeAndLoad("https://example.com:8000/foo.html");

  const KURL& different_port_url =
      KURL(NullURL(), "https://www.example.com:8080/bar.html");
  std::unique_ptr<WebNavigationParams> params =
      WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(),
                                                different_port_url);
  params->requestor_origin = WebSecurityOrigin::Create(WebURL(requestor_url));
  LocalFrame* local_frame =
      To<LocalFrame>(web_view_impl->GetPage()->MainFrame());
  local_frame->Loader().CommitNavigation(std::move(params), nullptr);

  EXPECT_FALSE(local_frame->GetDocument()->DeferredCompositorCommitIsAllowed());
}

TEST_F(DocumentLoaderTest, CommitsNotDeferredOnDataURLNavigation) {
  const KURL& requestor_url =
      KURL(NullURL(), "https://www.example.com/foo.html");
  WebViewImpl* web_view_impl =
      web_view_helper_.InitializeAndLoad("https://example.com/foo.html");

  const KURL& data_url = KURL(NullURL(), "data:,Hello%2C%20World!");
  std::unique_ptr<WebNavigationParams> params =
      WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(),
                                                data_url);
  params->requestor_origin = WebSecurityOrigin::Create(WebURL(requestor_url));
  LocalFrame* local_frame =
      To<LocalFrame>(web_view_impl->GetPage()->MainFrame());
  local_frame->Loader().CommitNavigation(std::move(params), nullptr);

  EXPECT_FALSE(local_frame->GetDocument()->DeferredCompositorCommitIsAllowed());
}

TEST_F(DocumentLoaderTest, SameOriginNavigation) {
  const KURL& requestor_url =
      KURL(NullURL(), "https://www.example.com/foo.html");
  WebViewImpl* web_view_impl =
      web_view_helper_.InitializeAndLoad("https://example.com/foo.html");

  const KURL& same_origin_url =
      KURL(NullURL(), "https://www.example.com/bar.html");
  std::unique_ptr<WebNavigationParams> params =
      WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(),
                                                same_origin_url);
  params->requestor_origin = WebSecurityOrigin::Create(WebURL(requestor_url));
  LocalFrame* local_frame =
      To<LocalFrame>(web_view_impl->GetPage()->MainFrame());
  local_frame->Loader().CommitNavigation(std::move(params), nullptr);

  EXPECT_TRUE(
      local_frame->Loader().GetDocumentLoader()->IsSameOriginNavigation());
}

TEST_F(DocumentLoaderTest, CrossOriginNavigation) {
  const KURL& requestor_url =
      KURL(NullURL(), "https://www.example.com/foo.html");
  WebViewImpl* web_view_impl =
      web_view_helper_.InitializeAndLoad("https://example.com/foo.html");

  const KURL& other_origin_url =
      KURL(NullURL(), "https://www.another.com/bar.html");
  std::unique_ptr<WebNavigationParams> params =
      WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(),
                                                other_origin_url);
  params->requestor_origin = WebSecurityOrigin::Create(WebURL(requestor_url));
  LocalFrame* local_frame =
      To<LocalFrame>(web_view_impl->GetPage()->MainFrame());
  local_frame->Loader().CommitNavigation(std::move(params), nullptr);

  EXPECT_FALSE(
      local_frame->Loader().GetDocumentLoader()->IsSameOriginNavigation());
}

}  // namespace blink