-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
print_browsertest.cc
4029 lines (3422 loc) · 156 KB
/
print_browsertest.cc
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <utility>
#include <vector>
#include "base/auto_reset.h"
#include "base/check_op.h"
#include "base/containers/contains.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/path_service.h"
#include "base/ranges/algorithm.h"
#include "base/run_loop.h"
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/printing/print_error_dialog.h"
#include "chrome/browser/printing/print_job.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/browser/printing/print_test_utils.h"
#include "chrome/browser/printing/print_view_manager.h"
#include "chrome/browser/printing/print_view_manager_common.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/printing/test_print_preview_observer.h"
#include "chrome/browser/printing/test_print_view_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/prefs/pref_service.h"
#include "components/printing/browser/print_composite_client.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/common/print.mojom-test-utils.h"
#include "components/printing/common/print.mojom.h"
#include "components/web_modal/web_contents_modal_dialog_manager.h"
#include "content/public/browser/browser_message_filter.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/back_forward_cache_util.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/fenced_frame_test_util.h"
#include "content/public/test/prerender_test_util.h"
#include "extensions/common/extension.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "printing/backend/test_print_backend.h"
#include "printing/buildflags/buildflags.h"
#include "printing/mojom/print.mojom.h"
#include "printing/page_setup.h"
#include "printing/print_settings.h"
#include "printing/printing_context.h"
#include "printing/printing_context_factory_for_test.h"
#include "printing/printing_features.h"
#include "printing/printing_utils.h"
#include "printing/test_printing_context.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/scheduler/web_scheduler_tracked_feature.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#if BUILDFLAG(ENABLE_OOP_PRINTING)
#include "chrome/browser/printing/print_backend_service_manager.h"
#include "chrome/browser/printing/print_backend_service_test_impl.h"
#include "chrome/browser/printing/print_job_worker_oop.h"
#include "chrome/browser/printing/printer_query_oop.h"
#include "chrome/services/printing/public/mojom/print_backend_service.mojom.h"
#endif
#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS)
#include "chrome/browser/enterprise/connectors/analysis/fake_content_analysis_delegate.h"
#include "chrome/browser/enterprise/connectors/common.h"
#include "chrome/browser/policy/dm_token_utils.h"
#include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_test_utils.h"
#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS)
namespace printing {
using testing::_;
using OnDidCreatePrintJobCallback =
base::RepeatingCallback<void(PrintJob* print_job)>;
#if BUILDFLAG(ENABLE_OOP_PRINTING)
using OnUseDefaultSettingsCallback = base::RepeatingClosure;
using OnGetSettingsWithUICallback = base::RepeatingClosure;
using ErrorCheckCallback =
base::RepeatingCallback<void(mojom::ResultCode result)>;
using OnDidUseDefaultSettingsCallback =
base::RepeatingCallback<void(mojom::ResultCode result)>;
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
using OnDidAskUserForSettingsCallback =
base::RepeatingCallback<void(mojom::ResultCode result)>;
#endif
using OnDidStartPrintingCallback =
base::RepeatingCallback<void(mojom::ResultCode result)>;
#if BUILDFLAG(IS_WIN)
using OnDidRenderPrintedPageCallback =
base::RepeatingCallback<void(uint32_t page_number,
mojom::ResultCode result)>;
#endif
using OnDidRenderPrintedDocumentCallback =
base::RepeatingCallback<void(mojom::ResultCode result)>;
using OnDidDocumentDoneCallback =
base::RepeatingCallback<void(mojom::ResultCode result)>;
using OnDidCancelCallback = base::RepeatingClosure;
using OnDidShowErrorDialog = base::RepeatingClosure;
#endif // BUILDFLAG(ENABLE_OOP_PRINTING)
namespace {
constexpr int kTestPrinterCapabilitiesMaxCopies = 99;
constexpr int kDefaultDocumentCookie = 1234;
#if !BUILDFLAG(IS_CHROMEOS)
constexpr gfx::Size kPhysicalSize = gfx::Size(612, 792);
constexpr gfx::Rect kPrintableArea = gfx::Rect(0, 0, 612, 792);
// The default margins are set to 1.0cm in //printing/print_settings.cc, which
// is about 28 printer units. The resulting content size is 556 x 736.
constexpr gfx::Size kExpectedContentSize = gfx::Size(556, 736);
#endif // !BUILDFLAG(IS_CHROMEOS)
const PrinterSemanticCapsAndDefaults::Paper kTestPaper{
/*display_name=*/"Letter", /*vendor_id=*/"45",
/*size_um=*/gfx::Size(215900, 279400),
/*printable_area_um=*/gfx::Rect(0, 0, 215900, 279400)};
#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS)
constexpr char kFakeDmToken[] = "fake-dm-token";
#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS)
std::unique_ptr<TestPrintingContext> MakeDefaultTestPrintingContext(
PrintingContext::Delegate* delegate,
bool skip_system_calls,
const std::string& printer_name) {
auto context =
std::make_unique<TestPrintingContext>(delegate, skip_system_calls);
context->SetDeviceSettings(printer_name,
MakeDefaultPrintSettings(printer_name));
return context;
}
class BrowserPrintingContextFactoryForTest
: public PrintingContextFactoryForTest {
public:
std::unique_ptr<PrintingContext> CreatePrintingContext(
PrintingContext::Delegate* delegate,
bool skip_system_calls) override {
auto context = MakeDefaultTestPrintingContext(delegate, skip_system_calls,
printer_name_);
if (cancels_in_new_document_) {
context->SetNewDocumentCancels();
}
if (failed_error_for_new_document_)
context->SetNewDocumentFails();
if (access_denied_errors_for_new_document_)
context->SetNewDocumentBlockedByPermissions();
#if BUILDFLAG(IS_WIN)
if (access_denied_errors_for_render_page_)
context->SetOnRenderPageBlockedByPermissions();
if (failed_error_for_render_page_number_) {
context->SetOnRenderPageFailsForPage(
failed_error_for_render_page_number_);
}
#endif
if (access_denied_errors_for_render_document_)
context->SetOnRenderDocumentBlockedByPermissions();
if (access_denied_errors_for_document_done_)
context->SetDocumentDoneBlockedByPermissions();
if (fail_on_use_default_settings_)
context->SetUseDefaultSettingsFails();
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
if (cancel_on_ask_user_for_settings_)
context->SetAskUserForSettingsCanceled();
#endif
context->SetUserSettings(*MakeUserModifiedPrintSettings(printer_name_));
context->SetOnNewDocumentCallback(base::BindRepeating(
&BrowserPrintingContextFactoryForTest::OnNewDocument,
base::Unretained(this)));
return std::move(context);
}
void SetPrinterNameForSubsequentContexts(const std::string& printer_name) {
printer_name_ = printer_name;
}
void SetCancelErrorOnNewDocument(bool cause_errors) {
cancels_in_new_document_ = cause_errors;
}
void SetFailedErrorOnNewDocument(bool cause_errors) {
failed_error_for_new_document_ = cause_errors;
}
void SetAccessDeniedErrorOnNewDocument(bool cause_errors) {
access_denied_errors_for_new_document_ = cause_errors;
}
#if BUILDFLAG(IS_WIN)
void SetAccessDeniedErrorOnRenderPage(bool cause_errors) {
access_denied_errors_for_render_page_ = cause_errors;
}
void SetFailedErrorForRenderPage(uint32_t page_number) {
failed_error_for_render_page_number_ = page_number;
}
#endif
void SetAccessDeniedErrorOnRenderDocument(bool cause_errors) {
access_denied_errors_for_render_document_ = cause_errors;
}
void SetAccessDeniedErrorOnDocumentDone(bool cause_errors) {
access_denied_errors_for_document_done_ = cause_errors;
}
void SetFailErrorOnUseDefaultSettings() {
fail_on_use_default_settings_ = true;
}
#if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG)
void SetCancelErrorOnAskUserForSettings() {
cancel_on_ask_user_for_settings_ = true;
}
#endif
void OnNewDocument(const PrintSettings& settings) {
++new_document_called_count_;
document_print_settings_ = settings;
}
int new_document_called_count() { return new_document_called_count_; }
const absl::optional<PrintSettings>& document_print_settings() const {
return document_print_settings_;
}
private:
std::string printer_name_;
bool cancels_in_new_document_ = false;
bool failed_error_for_new_document_ = false;
bool access_denied_errors_for_new_document_ = false;
#if BUILDFLAG(IS_WIN)
bool access_denied_errors_for_render_page_ = false;
uint32_t failed_error_for_render_page_number_ = 0;
#endif
bool access_denied_errors_for_render_document_ = false;
bool access_denied_errors_for_document_done_ = false;
bool fail_on_use_default_settings_ = false;
#if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG)
bool cancel_on_ask_user_for_settings_ = false;
#endif
int new_document_called_count_ = 0;
absl::optional<PrintSettings> document_print_settings_;
};
class TestPrintRenderFrame
: public mojom::PrintRenderFrameInterceptorForTesting {
public:
TestPrintRenderFrame(content::RenderFrameHost* frame_host,
content::WebContents* web_contents,
int document_cookie,
base::RepeatingClosure msg_callback)
: frame_host_(frame_host),
web_contents_(web_contents),
document_cookie_(document_cookie),
task_runner_(base::SequencedTaskRunner::GetCurrentDefault()),
msg_callback_(msg_callback) {}
~TestPrintRenderFrame() override = default;
void OnDidPrintFrameContent(int document_cookie,
mojom::DidPrintContentParamsPtr param,
PrintFrameContentCallback callback) const {
EXPECT_EQ(document_cookie, document_cookie_);
ASSERT_TRUE(param->metafile_data_region.IsValid());
EXPECT_GT(param->metafile_data_region.GetSize(), 0U);
std::move(callback).Run(document_cookie, std::move(param));
task_runner_->PostTask(FROM_HERE, msg_callback_);
}
void Bind(mojo::ScopedInterfaceEndpointHandle handle) {
receiver_.Bind(mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame>(
std::move(handle)));
}
static mojom::DidPrintContentParamsPtr GetDefaultDidPrintContentParams() {
auto printed_frame_params = mojom::DidPrintContentParams::New();
// Creates a small amount of region to avoid passing empty data to mojo.
constexpr size_t kSize = 10;
base::MappedReadOnlyRegion region_mapping =
base::ReadOnlySharedMemoryRegion::Create(kSize);
printed_frame_params->metafile_data_region =
std::move(region_mapping.region);
return printed_frame_params;
}
// mojom::PrintRenderFrameInterceptorForTesting
mojom::PrintRenderFrame* GetForwardingInterface() override {
NOTREACHED();
return nullptr;
}
void PrintFrameContent(mojom::PrintFrameContentParamsPtr params,
PrintFrameContentCallback callback) override {
// Sends the printed result back.
OnDidPrintFrameContent(params->document_cookie,
GetDefaultDidPrintContentParams(),
std::move(callback));
auto* client = PrintCompositeClient::FromWebContents(web_contents_);
if (!client)
return;
// Prints its children.
content::RenderFrameHost* child = ChildFrameAt(frame_host_.get(), 0);
for (size_t i = 1; child; i++) {
if (child->GetSiteInstance() != frame_host_->GetSiteInstance()) {
client->PrintCrossProcessSubframe(gfx::Rect(), params->document_cookie,
child);
}
child = ChildFrameAt(frame_host_.get(), i);
}
}
private:
raw_ptr<content::RenderFrameHost> frame_host_;
raw_ptr<content::WebContents> web_contents_;
const int document_cookie_;
scoped_refptr<base::SequencedTaskRunner> task_runner_;
base::RepeatingClosure msg_callback_;
mojo::AssociatedReceiver<mojom::PrintRenderFrame> receiver_{this};
};
class KillPrintRenderFrame
: public mojom::PrintRenderFrameInterceptorForTesting {
public:
explicit KillPrintRenderFrame(content::RenderProcessHost* rph) : rph_(rph) {}
~KillPrintRenderFrame() override = default;
void OverrideBinderForTesting(content::RenderFrameHost* render_frame_host) {
render_frame_host->GetRemoteAssociatedInterfaces()
->OverrideBinderForTesting(
mojom::PrintRenderFrame::Name_,
base::BindRepeating(&KillPrintRenderFrame::Bind,
base::Unretained(this)));
}
void KillRenderProcess(int document_cookie,
mojom::DidPrintContentParamsPtr param,
PrintFrameContentCallback callback) const {
std::move(callback).Run(document_cookie, std::move(param));
rph_->Shutdown(0);
}
void Bind(mojo::ScopedInterfaceEndpointHandle handle) {
receiver_.Bind(mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame>(
std::move(handle)));
}
// mojom::PrintRenderFrameInterceptorForTesting
mojom::PrintRenderFrame* GetForwardingInterface() override {
NOTREACHED();
return nullptr;
}
void PrintFrameContent(mojom::PrintFrameContentParamsPtr params,
PrintFrameContentCallback callback) override {
// Sends the printed result back.
const size_t kSize = 10;
mojom::DidPrintContentParamsPtr printed_frame_params =
mojom::DidPrintContentParams::New();
base::MappedReadOnlyRegion region_mapping =
base::ReadOnlySharedMemoryRegion::Create(kSize);
printed_frame_params->metafile_data_region =
std::move(region_mapping.region);
KillRenderProcess(params->document_cookie, std::move(printed_frame_params),
std::move(callback));
}
private:
const raw_ptr<content::RenderProcessHost> rph_;
mojo::AssociatedReceiver<mojom::PrintRenderFrame> receiver_{this};
};
class PrintPreviewDoneObserver
: public mojom::PrintRenderFrameInterceptorForTesting {
public:
PrintPreviewDoneObserver(content::RenderFrameHost* render_frame_host,
mojom::PrintRenderFrame* print_render_frame)
: render_frame_host_(render_frame_host),
print_render_frame_(print_render_frame) {
OverrideBinderForTesting();
}
~PrintPreviewDoneObserver() override {
render_frame_host_->GetRemoteAssociatedInterfaces()
->OverrideBinderForTesting(mojom::PrintRenderFrame::Name_,
base::NullCallback());
}
void WaitForPrintPreviewDialogClosed() { run_loop_.Run(); }
// mojom::PrintRenderFrameInterceptorForTesting:
mojom::PrintRenderFrame* GetForwardingInterface() override {
return print_render_frame_;
}
void OnPrintPreviewDialogClosed() override {
GetForwardingInterface()->OnPrintPreviewDialogClosed();
run_loop_.Quit();
}
private:
void OverrideBinderForTesting() {
// Safe to use base::Unretained() below because:
// 1) Normally, Bind() will unregister the override after it gets called.
// 2) If Bind() does not get called, the dtor will unregister the override.
render_frame_host_->GetRemoteAssociatedInterfaces()
->OverrideBinderForTesting(
mojom::PrintRenderFrame::Name_,
base::BindRepeating(&PrintPreviewDoneObserver::Bind,
base::Unretained(this)));
}
void Bind(mojo::ScopedInterfaceEndpointHandle handle) {
receiver_.Bind(mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame>(
std::move(handle)));
// After the initial binding, reset the binder override. Otherwise,
// PrintPreviewDoneObserver will also try to bind the remote passed by
// SetPrintPreviewUI(), which will fail since `receiver_` is already bound.
render_frame_host_->GetRemoteAssociatedInterfaces()
->OverrideBinderForTesting(mojom::PrintRenderFrame::Name_,
base::NullCallback());
}
raw_ptr<content::RenderFrameHost> const render_frame_host_;
raw_ptr<mojom::PrintRenderFrame> const print_render_frame_;
mojo::AssociatedReceiver<mojom::PrintRenderFrame> receiver_{this};
base::RunLoop run_loop_;
};
} // namespace
class TestPrintViewManagerForDLP : public TestPrintViewManager {
public:
// Used to simulate Data Leak Prevention polices and possible user actions.
enum class RestrictionLevel {
// No DLP restrictions set - printing is allowed.
kNotSet,
// The user is warned and selects "continue" - printing is allowed.
kWarnAllow,
// The user is warned and selects "cancel" - printing is not allowed.
kWarnCancel,
// Printing is blocked, no print preview is shown.
kBlock,
};
static TestPrintViewManagerForDLP* CreateForWebContents(
content::WebContents* web_contents,
RestrictionLevel restriction_level) {
auto manager = std::make_unique<TestPrintViewManagerForDLP>(
web_contents, restriction_level);
auto* manager_ptr = manager.get();
web_contents->SetUserData(PrintViewManager::UserDataKey(),
std::move(manager));
return manager_ptr;
}
// Used by the TestPrintViewManagerForDLP to check that the correct action is
// taken based on the restriction level.
enum class PrintAllowance {
// No checks done yet to determine whether printing is allowed or not.
kUnknown,
// There are no restrictions/user allowed printing.
kAllowed,
// There are BLOCK restrictions or user canceled the printing.
kDisallowed,
};
TestPrintViewManagerForDLP(content::WebContents* web_contents,
RestrictionLevel restriction_level)
: TestPrintViewManager(web_contents),
restriction_level_(restriction_level) {
PrintViewManager::SetReceiverImplForTesting(this);
}
TestPrintViewManagerForDLP(const TestPrintViewManagerForDLP&) = delete;
TestPrintViewManagerForDLP& operator=(const TestPrintViewManagerForDLP&) =
delete;
~TestPrintViewManagerForDLP() override {
PrintViewManager::SetReceiverImplForTesting(nullptr);
}
PrintAllowance GetPrintAllowance() const { return allowance_; }
private:
void RejectPrintPreviewRequestIfRestricted(
content::GlobalRenderFrameHostId rfh_id,
base::OnceCallback<void(bool)> callback) override {
switch (restriction_level_) {
case RestrictionLevel::kNotSet:
case RestrictionLevel::kWarnAllow:
std::move(callback).Run(true);
break;
case RestrictionLevel::kBlock:
case RestrictionLevel::kWarnCancel:
std::move(callback).Run(false);
break;
}
}
void PrintPreviewRejectedForTesting() override {
run_loop_->Quit();
allowance_ = PrintAllowance::kDisallowed;
}
void PrintPreviewAllowedForTesting() override {
run_loop_->Quit();
allowance_ = PrintAllowance::kAllowed;
}
RestrictionLevel restriction_level_ = RestrictionLevel::kNotSet;
PrintAllowance allowance_ = PrintAllowance::kUnknown;
};
#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS)
class TestPrintViewManagerForContentAnalysis : public TestPrintViewManager {
public:
class Observer : public PrintViewManagerBase::Observer {
public:
void OnPrintNow(const content::RenderFrameHost* rfh) override {
print_now_called_ = true;
}
void OnScriptedPrint() override { scripted_print_called_ = true; }
bool print_now_called() const { return print_now_called_; }
bool scripted_print_called() const { return scripted_print_called_; }
private:
bool print_now_called_ = false;
bool scripted_print_called_ = false;
};
static TestPrintViewManagerForContentAnalysis* CreateForWebContents(
content::WebContents* web_contents) {
auto manager =
std::make_unique<TestPrintViewManagerForContentAnalysis>(web_contents);
auto* manager_ptr = manager.get();
web_contents->SetUserData(PrintViewManager::UserDataKey(),
std::move(manager));
return manager_ptr;
}
explicit TestPrintViewManagerForContentAnalysis(
content::WebContents* web_contents)
: TestPrintViewManager(web_contents) {
AddObserver(observer_);
PrintViewManager::SetReceiverImplForTesting(this);
}
~TestPrintViewManagerForContentAnalysis() override {
PrintViewManager::SetReceiverImplForTesting(nullptr);
}
void WaitOnScanning() { scanning_run_loop_.Run(); }
void WaitOnPreview() { preview_run_loop_.Run(); }
bool print_now_called() const { return observer_.print_now_called(); }
bool scripted_print_called() const {
return observer_.scripted_print_called();
}
const absl::optional<bool>& preview_allowed() const {
return preview_allowed_;
}
#if BUILDFLAG(IS_CHROMEOS)
void set_allowed_by_dlp(bool allowed) { allowed_by_dlp_ = allowed; }
#endif // BUILDFLAG(IS_CHROMEOS)
protected:
void OnGotSnapshotCallback(
base::OnceCallback<void(bool should_proceed)> callback,
enterprise_connectors::ContentAnalysisDelegate::Data data,
content::GlobalRenderFrameHostId rfh_id,
mojom::DidPrintDocumentParamsPtr params) override {
ASSERT_TRUE(web_contents());
ASSERT_TRUE(params);
EXPECT_TRUE(params->content->metafile_data_region.IsValid());
EXPECT_EQ(data.url,
web_contents()->GetOutermostWebContents()->GetLastCommittedURL());
PrintViewManager::OnGotSnapshotCallback(
std::move(callback), std::move(data), rfh_id, std::move(params));
}
void OnCompositedForContentAnalysis(
base::OnceCallback<void(bool should_proceed)> callback,
enterprise_connectors::ContentAnalysisDelegate::Data data,
content::GlobalRenderFrameHostId rfh_id,
mojom::PrintCompositor::Status status,
base::ReadOnlySharedMemoryRegion page_region) override {
EXPECT_TRUE(content::RenderFrameHost::FromID(rfh_id));
EXPECT_EQ(status, mojom::PrintCompositor::Status::kSuccess);
// The settings passed to this function should match the content of the
// print Connector policy.
EXPECT_EQ(data.settings.tags.size(), 1u);
EXPECT_TRUE(base::Contains(data.settings.tags, "dlp"));
EXPECT_TRUE(data.settings.cloud_or_local_settings.is_cloud_analysis());
EXPECT_EQ(data.settings.cloud_or_local_settings.dm_token(), kFakeDmToken);
EXPECT_EQ(data.settings.block_until_verdict,
enterprise_connectors::BlockUntilVerdict::kBlock);
EXPECT_TRUE(data.settings.block_large_files);
EXPECT_EQ(data.url,
web_contents()->GetOutermostWebContents()->GetLastCommittedURL());
// The snapshot should be valid and populated.
EXPECT_TRUE(LooksLikePdf(page_region.Map().GetMemoryAsSpan<char>()));
PrintViewManager::OnCompositedForContentAnalysis(
base::BindOnce(
[](base::OnceCallback<void(bool should_proceed)> callback,
base::RunLoop* scanning_run_loop, bool allowed) {
std::move(callback).Run(allowed);
scanning_run_loop->Quit();
},
std::move(callback), &scanning_run_loop_),
std::move(data), rfh_id, status, std::move(page_region));
}
#if BUILDFLAG(IS_CHROMEOS)
void OnDlpPrintingRestrictionsChecked(
content::GlobalRenderFrameHostId rfh_id,
base::OnceCallback<void(bool should_proceed)> callback,
bool should_proceed) override {
PrintViewManager::OnDlpPrintingRestrictionsChecked(
rfh_id, std::move(callback), allowed_by_dlp_);
}
#endif // BUILDFLAG(IS_CHROMEOS)
void CompleteScriptedPrint(content::RenderFrameHost* rfh,
mojom::ScriptedPrintParamsPtr params,
ScriptedPrintCallback callback) override {
auto print_params = mojom::PrintPagesParams::New();
print_params->params = mojom::PrintParams::New();
std::move(callback).Run(std::move(print_params));
for (auto& observer : GetObservers())
observer.OnScriptedPrint();
}
private:
void PrintPreviewRejectedForTesting() override {
preview_allowed_ = false;
preview_run_loop_.Quit();
}
void PrintPreviewAllowedForTesting() override {
preview_allowed_ = true;
preview_run_loop_.Quit();
}
#if BUILDFLAG(IS_CHROMEOS)
bool allowed_by_dlp_ = true;
#endif // BUILDFLAG(IS_CHROMEOS)
// Indicates whether the preview was allowed after checking against content
// analysis and DLP (if on CrOS). This is unpopulated until then.
absl::optional<bool> preview_allowed_;
base::RunLoop preview_run_loop_;
base::RunLoop scanning_run_loop_;
Observer observer_;
};
#endif // BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS)
class PrintBrowserTest : public InProcessBrowserTest {
public:
struct PrintParams {
bool print_only_selection = false;
int pages_per_sheet = 1;
};
PrintBrowserTest() = default;
~PrintBrowserTest() override = default;
void SetUp() override {
test_print_backend_ = base::MakeRefCounted<TestPrintBackend>();
PrintBackend::SetPrintBackendForTesting(test_print_backend_.get());
PrintingContext::SetPrintingContextFactoryForTest(
&test_printing_context_factory_);
num_expected_messages_ = 1; // By default, only wait on one message.
num_received_messages_ = 0;
InProcessBrowserTest::SetUp();
}
void SetUpOnMainThread() override {
// Safe to use `base::Unretained(this)` since this testing class
// necessarily must outlive all interactions from the tests which will
// run through the printing stack using derivatives of
// `PrintViewManagerBase` and `PrintPreviewHandler`, which can trigger
// this callback.
SetShowPrintErrorDialogForTest(base::BindRepeating(
&PrintBrowserTest::ShowPrintErrorDialog, base::Unretained(this)));
host_resolver()->AddRule("*", "127.0.0.1");
content::SetupCrossSiteRedirector(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
}
void TearDownOnMainThread() override {
// Remove map of objects pointing to //content objects before they go away.
frame_content_.clear();
SetShowPrintErrorDialogForTest(base::NullCallback());
InProcessBrowserTest::TearDownOnMainThread();
}
void TearDown() override {
InProcessBrowserTest::TearDown();
PrintingContext::SetPrintingContextFactoryForTest(/*factory=*/nullptr);
PrintBackend::SetPrintBackendForTesting(/*print_backend=*/nullptr);
}
void AddPrinter(const std::string& printer_name) {
PrinterBasicInfo printer_info(
printer_name,
/*display_name=*/"test printer",
/*printer_description=*/"A printer for testing.",
/*printer_status=*/0,
/*is_default=*/true, kTestDummyPrintInfoOptions);
auto default_caps = std::make_unique<PrinterSemanticCapsAndDefaults>();
default_caps->copies_max = kTestPrinterCapabilitiesMaxCopies;
default_caps->dpis = kTestPrinterCapabilitiesDefaultDpis;
default_caps->default_dpi = kTestPrinterCapabilitiesDpi;
default_caps->papers.push_back(kTestPaper);
test_print_backend_->AddValidPrinter(
printer_name, std::move(default_caps),
std::make_unique<PrinterBasicInfo>(printer_info));
}
void SetPrinterNameForSubsequentContexts(const std::string& printer_name) {
test_printing_context_factory_.SetPrinterNameForSubsequentContexts(
printer_name);
}
void PrintAndWaitUntilPreviewIsReady() {
const PrintParams kParams;
PrintAndWaitUntilPreviewIsReady(kParams);
}
void PrintAndWaitUntilPreviewIsReady(const PrintParams& params) {
TestPrintPreviewObserver print_preview_observer(/*wait_for_loaded=*/false,
params.pages_per_sheet);
StartPrint(browser()->tab_strip_model()->GetActiveWebContents(),
/*print_renderer=*/mojo::NullAssociatedRemote(),
/*print_preview_disabled=*/false, params.print_only_selection);
print_preview_observer.WaitUntilPreviewIsReady();
set_rendered_page_count(print_preview_observer.rendered_page_count());
}
void PrintAndWaitUntilPreviewIsReadyAndLoaded() {
const PrintParams kParams;
PrintAndWaitUntilPreviewIsReadyAndLoaded(kParams);
}
void PrintAndWaitUntilPreviewIsReadyAndLoaded(const PrintParams& params) {
TestPrintPreviewObserver print_preview_observer(/*wait_for_loaded=*/true,
params.pages_per_sheet);
StartPrint(browser()->tab_strip_model()->GetActiveWebContents(),
/*print_renderer=*/mojo::NullAssociatedRemote(),
/*print_preview_disabled=*/false, params.print_only_selection);
print_preview_observer.WaitUntilPreviewIsReady();
set_rendered_page_count(print_preview_observer.rendered_page_count());
}
// The following are helper functions for having a wait loop in the test and
// exit when all expected messages are received.
void SetNumExpectedMessages(unsigned int num) {
num_expected_messages_ = num;
}
void WaitUntilCallbackReceived() {
base::RunLoop run_loop;
quit_callback_ = run_loop.QuitClosure();
run_loop.Run();
}
void CheckForQuit() {
if (++num_received_messages_ != num_expected_messages_)
return;
if (quit_callback_)
std::move(quit_callback_).Run();
}
void CreateTestPrintRenderFrame(content::RenderFrameHost* frame_host,
content::WebContents* web_contents) {
frame_content_.emplace(
frame_host, std::make_unique<TestPrintRenderFrame>(
frame_host, web_contents, kDefaultDocumentCookie,
base::BindRepeating(&PrintBrowserTest::CheckForQuit,
base::Unretained(this))));
OverrideBinderForTesting(frame_host);
}
static mojom::PrintFrameContentParamsPtr GetDefaultPrintFrameParams() {
return mojom::PrintFrameContentParams::New(gfx::Rect(800, 600),
kDefaultDocumentCookie);
}
const mojo::AssociatedRemote<mojom::PrintRenderFrame>& GetPrintRenderFrame(
content::RenderFrameHost* rfh) {
if (!remote_)
rfh->GetRemoteAssociatedInterfaces()->GetInterface(&remote_);
return remote_;
}
uint32_t rendered_page_count() const { return rendered_page_count_; }
uint32_t error_dialog_shown_count() const {
return error_dialog_shown_count_;
}
protected:
TestPrintBackend* test_print_backend() { return test_print_backend_.get(); }
BrowserPrintingContextFactoryForTest* test_printing_context_factory() {
return &test_printing_context_factory_;
}
void set_rendered_page_count(uint32_t page_count) {
rendered_page_count_ = page_count;
}
const absl::optional<PrintSettings>& document_print_settings() const {
return test_printing_context_factory_.document_print_settings();
}
private:
TestPrintRenderFrame* GetFrameContent(content::RenderFrameHost* host) const {
auto iter = frame_content_.find(host);
return iter != frame_content_.end() ? iter->second.get() : nullptr;
}
void OverrideBinderForTesting(content::RenderFrameHost* render_frame_host) {
render_frame_host->GetRemoteAssociatedInterfaces()
->OverrideBinderForTesting(
mojom::PrintRenderFrame::Name_,
base::BindRepeating(
&TestPrintRenderFrame::Bind,
base::Unretained(GetFrameContent(render_frame_host))));
}
void ShowPrintErrorDialog() {
++error_dialog_shown_count_;
CheckForQuit();
}
uint32_t error_dialog_shown_count_ = 0;
uint32_t rendered_page_count_ = 0;
unsigned int num_expected_messages_;
unsigned int num_received_messages_;
base::OnceClosure quit_callback_;
mojo::AssociatedRemote<mojom::PrintRenderFrame> remote_;
std::map<content::RenderFrameHost*, std::unique_ptr<TestPrintRenderFrame>>
frame_content_;
scoped_refptr<TestPrintBackend> test_print_backend_;
BrowserPrintingContextFactoryForTest test_printing_context_factory_;
};
class SitePerProcessPrintBrowserTest : public PrintBrowserTest {
public:
SitePerProcessPrintBrowserTest() = default;
~SitePerProcessPrintBrowserTest() override = default;
// content::BrowserTestBase
void SetUpCommandLine(base::CommandLine* command_line) override {
content::IsolateAllSitesForTesting(command_line);
}
};
class IsolateOriginsPrintBrowserTest : public PrintBrowserTest {
public:
static constexpr char kIsolatedSite[] = "b.com";
IsolateOriginsPrintBrowserTest() = default;
~IsolateOriginsPrintBrowserTest() override = default;
// content::BrowserTestBase
void SetUpCommandLine(base::CommandLine* command_line) override {
ASSERT_TRUE(embedded_test_server()->Start());
std::string origin_list =
embedded_test_server()->GetURL(kIsolatedSite, "/").spec();
command_line->AppendSwitchASCII(switches::kIsolateOrigins, origin_list);
}
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
}
};
class BackForwardCachePrintBrowserTest : public PrintBrowserTest {
public:
BackForwardCachePrintBrowserTest() = default;
BackForwardCachePrintBrowserTest(const BackForwardCachePrintBrowserTest&) =
delete;
BackForwardCachePrintBrowserTest& operator=(
const BackForwardCachePrintBrowserTest&) = delete;
~BackForwardCachePrintBrowserTest() override = default;
void SetUpCommandLine(base::CommandLine* command_line) override {
scoped_feature_list_.InitWithFeaturesAndParameters(
content::GetDefaultEnabledBackForwardCacheFeaturesForTesting(
/*ignore_outstanding_network_request=*/false),
content::GetDefaultDisabledBackForwardCacheFeaturesForTesting());
PrintBrowserTest::SetUpCommandLine(command_line);
}
content::WebContents* web_contents() const {
return browser()->tab_strip_model()->GetActiveWebContents();
}
content::RenderFrameHost* current_frame_host() {
return web_contents()->GetPrimaryMainFrame();
}
void ExpectBlocklistedFeature(
blink::scheduler::WebSchedulerTrackedFeature feature,
base::Location location) {
base::HistogramBase::Sample sample = base::HistogramBase::Sample(feature);
AddSampleToBuckets(&expected_blocklisted_features_, sample);
EXPECT_THAT(
histogram_tester_.GetAllSamples(
"BackForwardCache.HistoryNavigationOutcome."
"BlocklistedFeature"),
testing::UnorderedElementsAreArray(expected_blocklisted_features_))
<< location.ToString();
EXPECT_THAT(
histogram_tester_.GetAllSamples(
"BackForwardCache.AllSites.HistoryNavigationOutcome."
"BlocklistedFeature"),
testing::UnorderedElementsAreArray(expected_blocklisted_features_))
<< location.ToString();
}
private:
void AddSampleToBuckets(std::vector<base::Bucket>* buckets,
base::HistogramBase::Sample sample) {
auto it = base::ranges::find(*buckets, sample, &base::Bucket::min);
if (it == buckets->end()) {