summaryrefslogtreecommitdiffstats
path: root/tests/auto/core/origins/tst_origins.cpp
blob: 1d716c418f82dc1f8e5429e7a1e6f654a4920555 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include <util.h>
#include "httpserver.h"

#include <QtCore/qfile.h>
#include <QtTest/QtTest>
#include <QtWebEngineCore/qwebengineurlrequestinterceptor.h>
#include <QtWebEngineCore/qwebengineurlrequestjob.h>
#include <QtWebEngineCore/qwebengineurlscheme.h>
#include <QtWebEngineCore/qwebengineurlschemehandler.h>
#include <QtWebEngineCore/qwebenginesettings.h>
#include <QtWebEngineCore/qwebengineprofile.h>
#include <QtWebEngineCore/qwebenginepage.h>

#if defined(WEBSOCKETS)
#include <QtWebSockets/qwebsocket.h>
#include <QtWebSockets/qwebsocketserver.h>
#include <QtWebChannel/qwebchannel.h>
#endif
#include <qaction.h>

#define QSL QStringLiteral
#define QBAL QByteArrayLiteral

Q_LOGGING_CATEGORY(lc, "qt.webengine.tests")

void registerSchemes()
{
    {
        QWebEngineUrlScheme scheme(QBAL("PathSyntax"));
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("PathSyntax-Secure"));
        scheme.setFlags(QWebEngineUrlScheme::SecureScheme);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("PathSyntax-Secure-ServiceWorkersAllowed"));
        scheme.setFlags(QWebEngineUrlScheme::SecureScheme | QWebEngineUrlScheme::ServiceWorkersAllowed);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("PathSyntax-Local"));
        scheme.setFlags(QWebEngineUrlScheme::LocalScheme);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("PathSyntax-LocalAccessAllowed"));
        scheme.setFlags(QWebEngineUrlScheme::LocalAccessAllowed);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("PathSyntax-NoAccessAllowed"));
        scheme.setFlags(QWebEngineUrlScheme::NoAccessAllowed);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("PathSyntax-ServiceWorkersAllowed"));
        scheme.setFlags(QWebEngineUrlScheme::ServiceWorkersAllowed);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("PathSyntax-ViewSourceAllowed"));
        scheme.setFlags(QWebEngineUrlScheme::ViewSourceAllowed);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("HostSyntax"));
        scheme.setSyntax(QWebEngineUrlScheme::Syntax::Host);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("HostSyntax-ContentSecurityPolicyIgnored"));
        scheme.setSyntax(QWebEngineUrlScheme::Syntax::Host);
        scheme.setFlags(QWebEngineUrlScheme::ContentSecurityPolicyIgnored);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("HostAndPortSyntax"));
        scheme.setSyntax(QWebEngineUrlScheme::Syntax::HostAndPort);
        scheme.setDefaultPort(42);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("HostPortAndUserInformationSyntax"));
        scheme.setSyntax(QWebEngineUrlScheme::Syntax::HostPortAndUserInformation);
        scheme.setDefaultPort(42);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("redirect"));
        scheme.setFlags(QWebEngineUrlScheme::CorsEnabled);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("redirect-secure"));
        scheme.setFlags(QWebEngineUrlScheme::SecureScheme);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("redirect-local"));
        scheme.setFlags(QWebEngineUrlScheme::LocalScheme | QWebEngineUrlScheme::LocalAccessAllowed);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

    {
        QWebEngineUrlScheme scheme(QBAL("cors"));
        scheme.setFlags(QWebEngineUrlScheme::CorsEnabled);
        QWebEngineUrlScheme::registerScheme(scheme);
    }
    {
        QWebEngineUrlScheme scheme(QBAL("secure-cors"));
        scheme.setFlags(QWebEngineUrlScheme::SecureScheme | QWebEngineUrlScheme::CorsEnabled);
        QWebEngineUrlScheme::registerScheme(scheme);
    }
    {
        QWebEngineUrlScheme scheme(QBAL("localaccess"));
        scheme.setFlags(QWebEngineUrlScheme::LocalAccessAllowed);
        QWebEngineUrlScheme::registerScheme(scheme);
    }
    {
        QWebEngineUrlScheme scheme(QBAL("local"));
        scheme.setFlags(QWebEngineUrlScheme::LocalScheme);
        QWebEngineUrlScheme::registerScheme(scheme);
    }
    {
        QWebEngineUrlScheme scheme(QBAL("local-localaccess"));
        scheme.setFlags(QWebEngineUrlScheme::LocalScheme | QWebEngineUrlScheme::LocalAccessAllowed);
        QWebEngineUrlScheme::registerScheme(scheme);
    }
    {
        QWebEngineUrlScheme scheme(QBAL("local-cors"));
        scheme.setFlags(QWebEngineUrlScheme::LocalScheme | QWebEngineUrlScheme::CorsEnabled);
        QWebEngineUrlScheme::registerScheme(scheme);
    }

}
Q_CONSTRUCTOR_FUNCTION(registerSchemes)

class TstUrlSchemeHandler final : public QWebEngineUrlSchemeHandler {
    Q_OBJECT

public:
    TstUrlSchemeHandler(QWebEngineProfile *profile)
    {
        profile->installUrlSchemeHandler(QBAL("tst"), this);

        profile->installUrlSchemeHandler(QBAL("PathSyntax"), this);
        profile->installUrlSchemeHandler(QBAL("PathSyntax-Secure"), this);
        profile->installUrlSchemeHandler(QBAL("PathSyntax-Secure-ServiceWorkersAllowed"), this);
        profile->installUrlSchemeHandler(QBAL("PathSyntax-Local"), this);
        profile->installUrlSchemeHandler(QBAL("PathSyntax-LocalAccessAllowed"), this);
        profile->installUrlSchemeHandler(QBAL("PathSyntax-NoAccessAllowed"), this);
        profile->installUrlSchemeHandler(QBAL("PathSyntax-ServiceWorkersAllowed"), this);
        profile->installUrlSchemeHandler(QBAL("PathSyntax-ViewSourceAllowed"), this);
        profile->installUrlSchemeHandler(QBAL("HostSyntax"), this);
        profile->installUrlSchemeHandler(QBAL("HostSyntax-ContentSecurityPolicyIgnored"), this);
        profile->installUrlSchemeHandler(QBAL("HostAndPortSyntax"), this);
        profile->installUrlSchemeHandler(QBAL("HostPortAndUserInformationSyntax"), this);
        profile->installUrlSchemeHandler(QBAL("redirect"), this);
        profile->installUrlSchemeHandler(QBAL("redirect-secure"), this);
        profile->installUrlSchemeHandler(QBAL("redirect-local"), this);
        profile->installUrlSchemeHandler(QBAL("cors"), this);
        profile->installUrlSchemeHandler(QBAL("secure-cors"), this);
        profile->installUrlSchemeHandler(QBAL("localaccess"), this);
        profile->installUrlSchemeHandler(QBAL("local"), this);
        profile->installUrlSchemeHandler(QBAL("local-localaccess"), this);
        profile->installUrlSchemeHandler(QBAL("local-cors"), this);
    }

    QList<QUrl> &requests() { return m_requests; }

private:
    void requestStarted(QWebEngineUrlRequestJob *job) override
    {
        QUrl url = job->requestUrl();
        m_requests << url;

        if (url.scheme().startsWith("redirect")) {
            QString path = url.path();
            int idx = path.indexOf(QChar('/'));
            if (idx > 0) {
                url.setScheme(path.first(idx));
                url.setPath(path.mid(idx, -1));
                job->redirect(url);
                return;
            }
        }

        QString pathPrefix = QDir(QT_TESTCASE_SOURCEDIR).canonicalPath();
        if (url.path().startsWith("/qtwebchannel/"))
            pathPrefix = QSL(":");
        QString pathSuffix = url.path();
        auto file = std::make_unique<QFile>(pathPrefix + pathSuffix, job);
        if (!file->open(QIODevice::ReadOnly)) {
            qWarning() << "Failed to read data for:" << url << file->errorString();
            job->fail(QWebEngineUrlRequestJob::RequestFailed);
            return;
        }
        QByteArray mimeType = QBAL("text/html");
        if (pathSuffix.endsWith(QSL(".js")))
            mimeType = QBAL("application/javascript");
        else if (pathSuffix.endsWith(QSL(".css")))
            mimeType = QBAL("text/css");
        job->reply(mimeType, file.release());
    }

    QList<QUrl> m_requests;
};

class TestRequestInterceptor : public QWebEngineUrlRequestInterceptor
{
public:
    TestRequestInterceptor() = default;
    void interceptRequest(QWebEngineUrlRequestInfo &info) override
    {
        qCDebug(lc) << this << "Type:" << info.resourceType() << info.requestMethod() << "Navigation:" << info.navigationType()
                    << info.requestUrl() << "Initiator:" << info.initiator();

        QUrl url = info.requestUrl();
        requests << url;
        if (url.scheme().startsWith("redirect")) {
            QString path = url.path();
            int idx = path.indexOf(QChar('/'));
            if (idx > 0) {
                url.setScheme(path.first(idx));
                url.setPath(path.mid(idx, -1));
                info.redirect(url);
            }
        }
    }
    QList<QUrl> requests;
};

class TestPage : public QWebEnginePage
{
public:
    TestPage(QWebEngineProfile *profile) : QWebEnginePage(profile, nullptr)
    {
    }
    void javaScriptConsoleMessage(JavaScriptConsoleMessageLevel,
                                  const QString &message, int,
                                  const QString &) override
    {
        messages << message;
        qCDebug(lc) << message;
    }

    bool logContainsDoneMarker() const { return messages.contains("TEST:done"); }

    QString findResultInLog() const
    {
        // make sure we do not have some extra logs from blink
        for (auto message : messages) {
            QStringList s = message.split(':');
            if (s.size() > 1 && s[0] == "TEST")
                return s[1];
        }
        return QString();
    }

    void clearLog() { messages.clear(); }

private:
    QStringList messages;
};

class tst_Origins final : public QObject {
    Q_OBJECT

private Q_SLOTS:
    void initTestCase();
    void cleanupTestCase();
    void init();
    void cleanup();

    void jsUrlCanon();
    void jsUrlRelative();
    void jsUrlOrigin();
    void subdirWithAccess();
    void subdirWithoutAccess();
    void fileAccessRemoteUrl_data();
    void fileAccessRemoteUrl();
    void mixedSchemes_data();
    void mixedSchemes();
    void mixedSchemesWithCsp();
    void mixedXHR_data();
    void mixedXHR();
    void mixedContent_data();
    void mixedContent();
    void localMediaBlock_data();
    void localMediaBlock();
#if defined(WEBSOCKETS)
    void webSocket();
#endif
    void dedicatedWorker();
    void sharedWorker();
    void serviceWorker();
    void viewSource();
    void createObjectURL();
    void redirectScheme();
    void redirectSchemeLocal();
    void redirectSchemeSecure();
    void redirectInterceptor();
    void redirectInterceptorLocal();
    void redirectInterceptorSecure();
    void redirectInterceptorFile();
    void redirectInterceptorHttp();

private:
    bool verifyLoad(const QUrl &url)
    {
        QSignalSpy spy(m_page, &QWebEnginePage::loadFinished);
        m_page->load(url);
        [&spy]() { QTRY_VERIFY_WITH_TIMEOUT(!spy.isEmpty(), 90000); }();
        return !spy.isEmpty() && spy.front().value(0).toBool();
    }

    QVariant eval(const QString &code)
    {
        return evaluateJavaScriptSync(m_page, code);
    }

    QWebEngineProfile m_profile;
    TestPage *m_page = nullptr;
    TstUrlSchemeHandler *m_handler = nullptr;
};

void tst_Origins::initTestCase()
{
    QTest::ignoreMessage(
            QtWarningMsg,
            QRegularExpression("Please register the custom scheme 'tst'.*"));

    m_handler = new TstUrlSchemeHandler(&m_profile);
}

void tst_Origins::cleanupTestCase()
{
    QVERIFY(!m_page);
    delete m_handler;
}

void tst_Origins::init()
{
    m_page = new TestPage(&m_profile);
}

void tst_Origins::cleanup()
{
    delete m_page;
    m_page = nullptr;
    m_handler->requests().clear();
}

// Test URL parsing and canonicalization in Blink. The implementation of this
// part is mostly shared between Blink and Chromium proper.
void tst_Origins::jsUrlCanon()
{
    QVERIFY(verifyLoad(QSL("about:blank")));

    // Standard schemes are biased towards the authority part.
    QCOMPARE(eval(QSL("new URL(\"http:foo/bar\").href")),    QVariant(QSL("http://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"http:/foo/bar\").href")),   QVariant(QSL("http://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"http://foo/bar\").href")),  QVariant(QSL("http://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"http:///foo/bar\").href")), QVariant(QSL("http://foo/bar")));

    // The file scheme is however a (particularly) special case.
#ifdef Q_OS_WIN
    QCOMPARE(eval(QSL("new URL(\"file:foo/bar\").href")),    QVariant(QSL("file://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"file:/foo/bar\").href")),   QVariant(QSL("file://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"file://foo/bar\").href")),  QVariant(QSL("file://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"file:///foo/bar\").href")), QVariant(QSL("file:///foo/bar")));
#else
    QCOMPARE(eval(QSL("new URL(\"file:foo/bar\").href")),    QVariant(QSL("file:///foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"file:/foo/bar\").href")),   QVariant(QSL("file:///foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"file://foo/bar\").href")),  QVariant(QSL("file://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"file:///foo/bar\").href")), QVariant(QSL("file:///foo/bar")));
#endif

    // The qrc scheme is a PathSyntax scheme, having only a path and nothing else.
    QCOMPARE(eval(QSL("new URL(\"qrc:foo/bar\").href")),    QVariant(QSL("qrc:foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"qrc:/foo/bar\").href")),   QVariant(QSL("qrc:/foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"qrc://foo/bar\").href")),  QVariant(QSL("qrc://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"qrc:///foo/bar\").href")), QVariant(QSL("qrc:///foo/bar")));

    // Same for unregistered schemes.
    QCOMPARE(eval(QSL("new URL(\"tst:foo/bar\").href")),    QVariant(QSL("tst:foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"tst:/foo/bar\").href")),   QVariant(QSL("tst:/foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"tst://foo/bar\").href")),  QVariant(QSL("tst://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"tst:///foo/bar\").href")), QVariant(QSL("tst:///foo/bar")));

    // A HostSyntax scheme is like http without the port & user information.
    QCOMPARE(eval(QSL("new URL(\"HostSyntax:foo/bar\").href")),     QVariant(QSL("hostsyntax://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"HostSyntax:foo:42/bar\").href")),  QVariant(QSL("hostsyntax://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"HostSyntax:a:b@foo/bar\").href")), QVariant(QSL("hostsyntax://foo/bar")));

    // A HostAndPortSyntax scheme is like http without the user information.
    QCOMPARE(eval(QSL("new URL(\"HostAndPortSyntax:foo/bar\").href")),
             QVariant(QSL("hostandportsyntax://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"HostAndPortSyntax:foo:41/bar\").href")),
             QVariant(QSL("hostandportsyntax://foo:41/bar")));
    QCOMPARE(eval(QSL("new URL(\"HostAndPortSyntax:foo:42/bar\").href")),
             QVariant(QSL("hostandportsyntax://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"HostAndPortSyntax:a:b@foo/bar\").href")),
             QVariant(QSL("hostandportsyntax://foo/bar")));

    // A HostPortAndUserInformationSyntax scheme is exactly like http.
    QCOMPARE(eval(QSL("new URL(\"HostPortAndUserInformationSyntax:foo/bar\").href")),
             QVariant(QSL("hostportanduserinformationsyntax://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"HostPortAndUserInformationSyntax:foo:41/bar\").href")),
             QVariant(QSL("hostportanduserinformationsyntax://foo:41/bar")));
    QCOMPARE(eval(QSL("new URL(\"HostPortAndUserInformationSyntax:foo:42/bar\").href")),
             QVariant(QSL("hostportanduserinformationsyntax://foo/bar")));
    QCOMPARE(eval(QSL("new URL(\"HostPortAndUserInformationSyntax:a:b@foo/bar\").href")),
             QVariant(QSL("hostportanduserinformationsyntax://a:b@foo/bar")));
}

// Test relative URL resolution.
void tst_Origins::jsUrlRelative()
{
    QVERIFY(verifyLoad(QSL("about:blank")));

    // Schemes with hosts, like http, work as expected.
    QCOMPARE(eval(QSL("new URL('bar', 'http://foo').href")), QVariant(QSL("http://foo/bar")));
    QCOMPARE(eval(QSL("new URL('baz', 'http://foo/bar').href")), QVariant(QSL("http://foo/baz")));
    QCOMPARE(eval(QSL("new URL('baz', 'http://foo/bar/').href")), QVariant(QSL("http://foo/bar/baz")));
    QCOMPARE(eval(QSL("new URL('/baz', 'http://foo/bar/').href")), QVariant(QSL("http://foo/baz")));
    QCOMPARE(eval(QSL("new URL('./baz', 'http://foo/bar/').href")), QVariant(QSL("http://foo/bar/baz")));
    QCOMPARE(eval(QSL("new URL('../baz', 'http://foo/bar/').href")), QVariant(QSL("http://foo/baz")));
    QCOMPARE(eval(QSL("new URL('../../baz', 'http://foo/bar/').href")), QVariant(QSL("http://foo/baz")));
    QCOMPARE(eval(QSL("new URL('//baz', 'http://foo/bar/').href")), QVariant(QSL("http://baz/")));

    // In the case of schemes without hosts, relative URLs only work if the URL
    // starts with a single slash -- and canonicalization does not guarantee
    // this. The following cases all fail with TypeErrors.
    QCOMPARE(eval(QSL("new URL('bar', 'tst:foo').href")), QVariant());
    QCOMPARE(eval(QSL("new URL('baz', 'tst:foo/bar').href")), QVariant());
    QCOMPARE(eval(QSL("new URL('bar', 'tst://foo').href")), QVariant());
    QCOMPARE(eval(QSL("new URL('bar', 'tst:///foo').href")), QVariant());

    // However, registered custom schemes have been patched to allow relative
    // URLs even without an initial slash.
    QCOMPARE(eval(QSL("new URL('bar', 'qrc:foo').href")), QVariant(QSL("qrc:bar")));
    QCOMPARE(eval(QSL("new URL('baz', 'qrc:foo/bar').href")), QVariant(QSL("qrc:foo/baz")));
    QCOMPARE(eval(QSL("new URL('bar', 'qrc://foo').href")), QVariant(QSL("qrc://bar")));
    QCOMPARE(eval(QSL("new URL('bar', 'qrc:///foo').href")), QVariant(QSL("qrc:///bar")));

    // With a slash it works the same as http except 'foo' is part of the path and not the host.
    QCOMPARE(eval(QSL("new URL('bar', 'qrc:/foo').href")), QVariant(QSL("qrc:/bar")));
    QCOMPARE(eval(QSL("new URL('bar', 'qrc:/foo/').href")), QVariant(QSL("qrc:/foo/bar")));
    QCOMPARE(eval(QSL("new URL('baz', 'qrc:/foo/bar').href")), QVariant(QSL("qrc:/foo/baz")));
    QCOMPARE(eval(QSL("new URL('baz', 'qrc:/foo/bar/').href")), QVariant(QSL("qrc:/foo/bar/baz")));
    QCOMPARE(eval(QSL("new URL('/baz', 'qrc:/foo/bar/').href")), QVariant(QSL("qrc:/baz")));
    QCOMPARE(eval(QSL("new URL('./baz', 'qrc:/foo/bar/').href")), QVariant(QSL("qrc:/foo/bar/baz")));
    QCOMPARE(eval(QSL("new URL('../baz', 'qrc:/foo/bar/').href")), QVariant(QSL("qrc:/foo/baz")));
    QCOMPARE(eval(QSL("new URL('../../baz', 'qrc:/foo/bar/').href")), QVariant(QSL("qrc:/baz")));
    QCOMPARE(eval(QSL("new URL('../../../baz', 'qrc:/foo/bar/').href")), QVariant(QSL("qrc:/baz")));

    // If the relative URL begins with >= 2 slashes, then the scheme is treated
    // not as a Syntax::Path scheme but as a Syntax::HostPortAndUserInformation
    // scheme.
    QCOMPARE(eval(QSL("new URL('//baz', 'qrc:/foo/bar/').href")), QVariant(QSL("qrc://baz/")));
    QCOMPARE(eval(QSL("new URL('///baz', 'qrc:/foo/bar/').href")), QVariant(QSL("qrc://baz/")));
}

// Test origin serialization in Blink, implemented by blink::KURL and
// blink::SecurityOrigin as opposed to GURL and url::Origin.
void tst_Origins::jsUrlOrigin()
{
    QVERIFY(verifyLoad(QSL("about:blank")));

    // For network protocols the origin string must include the domain and port.
    QCOMPARE(eval(QSL("new URL(\"http://foo.com/page.html\").origin")), QVariant(QSL("http://foo.com")));
    QCOMPARE(eval(QSL("new URL(\"https://foo.com/page.html\").origin")), QVariant(QSL("https://foo.com")));

    // Even though file URL can also have domains, these are not included in the
    // origin string by Chromium. The standard does not specify a value here,
    // but suggests 'null' (https://url.spec.whatwg.org/#origin).
    QCOMPARE(eval(QSL("new URL(\"file:/etc/passwd\").origin")), QVariant(QSL("file://")));
    QCOMPARE(eval(QSL("new URL(\"file://foo.com/etc/passwd\").origin")), QVariant(QSL("file://")));

    // Unregistered schemes behave like file.
    QCOMPARE(eval(QSL("new URL(\"tst:/banana\").origin")), QVariant(QSL("tst://")));
    QCOMPARE(eval(QSL("new URL(\"tst://foo.com/banana\").origin")), QVariant(QSL("tst://")));

    // The non-PathSyntax schemes should have hosts and potentially ports.
    QCOMPARE(eval(QSL("new URL(\"HostSyntax:foo:41/bar\").origin")),
             QVariant(QSL("hostsyntax://foo")));
    QCOMPARE(eval(QSL("new URL(\"HostAndPortSyntax:foo:41/bar\").origin")),
             QVariant(QSL("hostandportsyntax://foo:41")));
    QCOMPARE(eval(QSL("new URL(\"HostAndPortSyntax:foo:42/bar\").origin")),
             QVariant(QSL("hostandportsyntax://foo")));
    QCOMPARE(eval(QSL("new URL(\"HostPortAndUserInformationSyntax:foo:41/bar\").origin")),
             QVariant(QSL("hostportanduserinformationsyntax://foo:41")));
    QCOMPARE(eval(QSL("new URL(\"HostPortAndUserInformationSyntax:foo:42/bar\").origin")),
             QVariant(QSL("hostportanduserinformationsyntax://foo")));

    // A PathSyntax scheme should have a 'universal' origin.
    QCOMPARE(eval(QSL("new URL(\"PathSyntax:foo\").origin")), QVariant(QSL("pathsyntax:")));
    QCOMPARE(eval(QSL("new URL(\"qrc:/crysis.css\").origin")), QVariant(QSL("qrc:")));
    QCOMPARE(eval(QSL("new URL(\"qrc://foo.com/crysis.css\").origin")), QVariant(QSL("qrc:")));

    // The NoAccessAllowed flag forces opaque origins.
    QCOMPARE(eval(QSL("new URL(\"PathSyntax-NoAccessAllowed:foo\").origin")),
             QVariant(QSL("null")));
}

class ScopedAttribute {
public:
    ScopedAttribute(QWebEngineSettings *settings, QWebEngineSettings::WebAttribute attribute, bool newValue)
        : m_settings(settings)
        , m_attribute(attribute)
        , m_oldValue(m_settings->testAttribute(m_attribute))
    {
        m_settings->setAttribute(m_attribute, newValue);
    }
    ~ScopedAttribute()
    {
        m_settings->setAttribute(m_attribute, m_oldValue);
    }
private:
    QWebEngineSettings *m_settings;
    QWebEngineSettings::WebAttribute m_attribute;
    bool m_oldValue;
};

// Test same-origin policy of file, qrc and custom schemes.
//
// Note the test case involves the main page trying to load an iframe from a
// file that resides in a parent directory. This is just a small detail to
// demonstrate the difference with Firefox where such access is not allowed.
void tst_Origins::subdirWithAccess()
{
    ScopedAttribute sa(m_page->settings(), QWebEngineSettings::LocalContentCanAccessFileUrls, true);

    QVERIFY(verifyLoad("file:" + QDir(QT_TESTCASE_SOURCEDIR).canonicalPath()
                       + "/resources/subdir/index.html"));
    QCOMPARE(eval(QSL("msg[0]")), QVariant(QSL("hello")));
    QCOMPARE(eval(QSL("msg[1]")), QVariant(QSL("world")));

    QVERIFY(verifyLoad(QSL("qrc:/resources/subdir/index.html")));
    QCOMPARE(eval(QSL("msg[0]")), QVariant(QSL("hello")));
    QCOMPARE(eval(QSL("msg[1]")), QVariant(QSL("world")));

    QVERIFY(verifyLoad(QSL("tst:/resources/subdir/index.html")));
    QCOMPARE(eval(QSL("msg[0]")), QVariant(QSL("hello")));
    QCOMPARE(eval(QSL("msg[1]")), QVariant(QSL("world")));
}

// In this variation the LocalContentCanAccessFileUrls attribute is disabled. As
// a result all file URLs will be considered to have unique/opaque origins, that
// is, they are not the 'same origin as' any other origin.
//
// Note that this applies only to file URLs and not qrc or custom schemes.
//
// See also (in Blink):
//   - the allow_file_access_from_file_urls option and
//   - the blink::SecurityOrigin::BlockLocalAccessFromLocalOrigin() method.
void tst_Origins::subdirWithoutAccess()
{
    ScopedAttribute sa(m_page->settings(), QWebEngineSettings::LocalContentCanAccessFileUrls, false);

    QVERIFY(verifyLoad("file:" + QDir(QT_TESTCASE_SOURCEDIR).canonicalPath()
                       + "/resources/subdir/index.html"));
    QCOMPARE(eval(QSL("msg[0]")), QVariant());
    QCOMPARE(eval(QSL("msg[1]")), QVariant());

    QVERIFY(verifyLoad(QSL("qrc:/resources/subdir/index.html")));
    QCOMPARE(eval(QSL("msg[0]")), QVariant(QSL("hello")));
    QCOMPARE(eval(QSL("msg[1]")), QVariant(QSL("world")));

    QVERIFY(verifyLoad(QSL("tst:/resources/subdir/index.html")));
    QCOMPARE(eval(QSL("msg[0]")), QVariant(QSL("hello")));
    QCOMPARE(eval(QSL("msg[1]")), QVariant(QSL("world")));
}

void tst_Origins::fileAccessRemoteUrl_data()
{
    QTest::addColumn<bool>("EnableAccess");
    QTest::addRow("enabled") << true;
    QTest::addRow("disabled") << false;
}

void tst_Origins::fileAccessRemoteUrl()
{
    QFETCH(bool, EnableAccess);

    HttpServer server;
    server.setResourceDirs({ QDir(QT_TESTCASE_SOURCEDIR).canonicalPath() + "/resources" });
    QVERIFY(server.start());

    ScopedAttribute sa1(m_page->settings(), QWebEngineSettings::LocalContentCanAccessRemoteUrls, EnableAccess);
    ScopedAttribute sa2(m_page->settings(), QWebEngineSettings::ErrorPageEnabled, false);

    QVERIFY(verifyLoad("file:" + QDir(QT_TESTCASE_SOURCEDIR).canonicalPath()
                       + "/resources/mixedXHR.html"));

    eval("sendXHR('" + server.url("/mixedXHR.txt").toString() + "')");
    QTRY_COMPARE(eval("result"), (EnableAccess ? QString("ok") : QString("error")));
}

// Load the main page over one scheme with an iframe over another scheme.
//
// For file and qrc schemes, the iframe should load but it should not be
// possible for scripts in different frames to interact.
//
// Additionally for unregistered custom schemes and custom schemes without
// LocalAccessAllowed it should not be possible to load an iframe over the
// file: scheme.
void tst_Origins::mixedSchemes_data()
{
    QTest::addColumn<QString>("schemeFrom");
    QTest::addColumn<QVariantMap>("testPairs");

    QVariant SLF = QVariant(QSL("canLoadAndAccess")), OK = QVariant(QSL("canLoadButNotAccess")),
             ERR = QVariant(QSL("cannotLoad"));
    std::vector<std::pair<const char *, std::vector<std::pair<const char *, QVariant>>>> data = {
        { "file",
          {
                  { "file", SLF },
                  { "qrc", OK },
                  { "tst", ERR },
          } },
        { "qrc",
          {
                  { "file", ERR },
                  { "qrc", SLF },
                  { "tst", OK },
          } },
        { "tst",
          {
                  { "file", ERR },
                  { "qrc", OK },
                  { "tst", SLF },
          } },
        { "PathSyntax",
          {
                  { "PathSyntax", SLF },
                  { "PathSyntax-Local", ERR },
                  { "PathSyntax-LocalAccessAllowed", OK },
                  { "PathSyntax-NoAccessAllowed", OK },
          } },
        { "PathSyntax-LocalAccessAllowed",
          {
                  { "PathSyntax", OK },
                  { "PathSyntax-Local", OK },
                  { "PathSyntax-LocalAccessAllowed", SLF },
                  { "PathSyntax-NoAccessAllowed", OK },
          } },
        { "PathSyntax-NoAccessAllowed",
          {
                  { "PathSyntax", OK },
                  { "PathSyntax-Local", ERR },
                  { "PathSyntax-LocalAccessAllowed", OK },
                  { "PathSyntax-NoAccessAllowed", OK },
          } },
        { "HostSyntax://a",
          {
                  { "HostSyntax://a", SLF },
                  { "HostSyntax://b", OK },
          } },
        { "local-localaccess",
          {
                  { "local-cors", OK },
                  { "local-localaccess", SLF },
                  { "local", OK },
          } },
        { "local-cors",
          {
                  { "local", OK },
                  { "local-cors", SLF },
          } },
    };

    for (auto &&d : data) {
        auto schemeFrom = d.first;
        QVariantMap testPairs;
        for (auto &&destSchemes : d.second) {
            auto &&destScheme = destSchemes.first;
            testPairs[destScheme] = destSchemes.second;
        }
        QTest::addRow("%s", schemeFrom) << schemeFrom << testPairs;
    }
}

static QStringList protocolAndHost(const QString scheme)
{
    static QString srcDir(QDir(QT_TESTCASE_SOURCEDIR).canonicalPath());
    QStringList result;
    if (scheme == QSL("file")) {
        return QStringList{ scheme, srcDir };
    }
    if (scheme.contains(QSL("HostSyntax:"))) {
        const QStringList &res = scheme.split(':');
        Q_ASSERT(res.size() == 2);
        return res;
    }
    return QStringList{ scheme, "" };
}

void tst_Origins::mixedSchemes()
{
    QFETCH(QString, schemeFrom);
    QFETCH(QVariantMap, testPairs);

    ScopedAttribute sa(m_page->settings(), QWebEngineSettings::ErrorPageEnabled, false);
    QString srcDir(QDir(QT_TESTCASE_SOURCEDIR).canonicalPath());
    QString host;
    auto pah = protocolAndHost(schemeFrom);
    auto loadUrl = QString("%1:%2/resources/mixedSchemes.html").arg(pah[0]).arg(pah[1]);
    QVERIFY(verifyLoad(loadUrl));

    QStringList schemesTo, expected, results;
    for (auto it = testPairs.begin(), end = testPairs.end(); it != end; ++it) {

        auto schemeTo = it.key();
        auto pah = protocolAndHost(schemeTo);
        auto expectedResult = it.value().toString();
        auto frameUrl = QString("%1:%2/resources/mixedSchemes_frame.html").arg(pah[0]).arg(pah[1]);
        auto imgUrl = QString("%1:%2/resources/red.png").arg(pah[0]).arg(pah[1]);

        eval(QString("setIFrameUrl('%1','%2')").arg(frameUrl).arg(imgUrl));

        // wait for token in the log
        QTRY_VERIFY(m_page->logContainsDoneMarker());
        const QString result = m_page->findResultInLog();
        m_page->clearLog();
        schemesTo.append(schemeTo.rightJustified(20));
        results.append(result.rightJustified(20));
        expected.append(expectedResult.rightJustified(20));
    }

    QVERIFY2(results == expected,
             qPrintable(QString("\nFrom '%1' to:\n\tScheme: %2\n\tActual: %3\n\tExpect: %4")
                                .arg(schemeFrom)
                                .arg(schemesTo.join(' '))
                                .arg(results.join(' '))
                                .arg(expected.join(' '))));
}

// Like mixedSchemes but adds a Content-Security-Policy: frame-src 'none' header.
void tst_Origins::mixedSchemesWithCsp()
{
    QVERIFY(verifyLoad(QSL("HostSyntax://a/resources/mixedSchemesWithCsp.html")));
    eval(QSL("setIFrameUrl('HostSyntax://a/resources/mixedSchemes_frame.html')"));
    QTRY_COMPARE(eval(QSL("result")), QVariant(QSL("canLoadButNotAccess")));
    eval(QSL("setIFrameUrl('HostSyntax://b/resources/mixedSchemes_frame.html')"));
    QTRY_COMPARE(eval(QSL("result")), QVariant(QSL("canLoadButNotAccess")));

    QVERIFY(verifyLoad(QSL("HostSyntax-ContentSecurityPolicyIgnored://a/resources/mixedSchemesWithCsp.html")));
    eval(QSL("setIFrameUrl('HostSyntax-ContentSecurityPolicyIgnored://a/resources/mixedSchemes_frame.html')"));
    QTRY_COMPARE(eval(QSL("result")), QVariant(QSL("canLoadAndAccess")));
    eval(QSL("setIFrameUrl('HostSyntax-ContentSecurityPolicyIgnored://b/resources/mixedSchemes_frame.html')"));
    QTRY_COMPARE(eval(QSL("result")), QVariant(QSL("canLoadButNotAccess")));
}

// Load the main page over one scheme, then make an XMLHttpRequest to a
// different scheme.
//
// Cross-origin XMLHttpRequests can only be made to CORS-enabled schemes. These
// include the builtin schemes http, https, data, and chrome, as well as custom
// schemes with the CorsEnabled flag.
void tst_Origins::mixedXHR_data()
{
    QTest::addColumn<QString>("schemeFrom");
    QTest::addColumn<bool>("canAccessFileUrls");
    QTest::addColumn<bool>("canAccessRemoteUrl");
    QTest::addColumn<QVariantMap>("testPairs");

    bool defaultFileAccess = QWebEnginePage().settings()->testAttribute(QWebEngineSettings::LocalContentCanAccessFileUrls);
    bool defaultRemoteAccess = QWebEnginePage().settings()->testAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls);
    Q_ASSERT(defaultFileAccess);
    Q_ASSERT(!defaultRemoteAccess);
    std::vector<std::pair<bool, bool>> settingCombinations = {
        { defaultFileAccess, defaultRemoteAccess },  // tag: *schemeFrom*_local_noremote
        { defaultFileAccess, !defaultRemoteAccess }, // tag: *schemeFrom*_local_remote
        { !defaultFileAccess, defaultRemoteAccess }, // tag: *schemeFrom*_nolocal_noremote
        { !defaultFileAccess, !defaultRemoteAccess } // tag: *schemeFrom*_nolocal_remote
    };

    QVariant OK = QString("ok"), ERR = QString("error");
    std::vector<
        std::pair<const char *, std::vector<
            std::pair<const char *, std::vector<QVariant>>>>> data = {
        { "file", {
            { "file",               {  OK,  OK, ERR, ERR } },
            { "qrc",                { ERR, ERR, ERR, ERR } },
            { "tst",                { ERR, ERR, ERR, ERR } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               { ERR,  OK, ERR,  OK } },
            { "local-localaccess",  {  OK,  OK, ERR, ERR } },
            { "local-cors",         {  OK,  OK, ERR, ERR } }, } },

        { "qrc",  {
            { "file",               { ERR, ERR, ERR, ERR } },
            { "qrc",                {  OK,  OK,  OK,  OK } },
            { "tst",                { ERR, ERR, ERR, ERR } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               {  OK,  OK,  OK,  OK } },
            { "local-localaccess",  { ERR, ERR, ERR, ERR } },
            { "local-cors",         { ERR, ERR, ERR, ERR } }, } },

        { "tst",  {
            { "file",               { ERR, ERR, ERR, ERR } },
            { "qrc",                { ERR, ERR, ERR, ERR } },
            { "tst",                {  OK,  OK,  OK,  OK } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               {  OK,  OK,  OK,  OK } },
            { "local-localaccess",  { ERR, ERR, ERR, ERR } },
            { "local-cors",         { ERR, ERR, ERR, ERR } }, } },

        { "cors", {                 // -local +cors -local-access
            { "file",               { ERR, ERR, ERR, ERR } },
            { "qrc",                { ERR, ERR, ERR, ERR } },
            { "tst",                { ERR, ERR, ERR, ERR } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               {  OK,  OK,  OK,  OK } },
            { "local-localaccess",  { ERR, ERR, ERR, ERR } },
            { "local-cors",         { ERR, ERR, ERR, ERR } }, } },

        { "local", {                // +local -cors -local-access
            { "file",               {  OK,  OK, ERR, ERR } },
            { "qrc",                { ERR, ERR, ERR, ERR } },
            { "tst",                { ERR, ERR, ERR, ERR } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               { ERR,  OK, ERR,  OK } },
            { "local-localaccess",  {  OK,  OK, ERR, ERR } },
            { "local-cors",         {  OK,  OK, ERR, ERR } }, } },

        { "local-cors", {           // +local +cors -local-access
            { "file",               {  OK,  OK, ERR, ERR } },
            { "qrc",                { ERR, ERR, ERR, ERR } },
            { "tst",                { ERR, ERR, ERR, ERR } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               { ERR,  OK, ERR,  OK } },
            { "local-localaccess",  {  OK,  OK, ERR, ERR } },
            { "local-cors",         {  OK,  OK, ERR, ERR } }, } },

        { "local-localaccess", {    // +local -cors +local-access
            { "file",               {  OK,  OK,  OK,  OK } },
            { "qrc",                { ERR, ERR, ERR, ERR } },
            { "tst",                { ERR, ERR, ERR, ERR } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               { ERR,  OK, ERR,  OK } },
            { "local-localaccess",  {  OK,  OK,  OK,  OK } },
            { "local-cors",         {  OK,  OK,  OK,  OK } }, } },

        { "localaccess", {          // -local -cors +local-access
            { "file",               {  OK,  OK,  OK,  OK } },
            { "qrc",                { ERR, ERR, ERR, ERR } },
            { "tst",                { ERR, ERR, ERR, ERR } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               {  OK,  OK,  OK,  OK } },
            { "local-localaccess",  {  OK,  OK,  OK,  OK } },
            { "local-cors",         {  OK,  OK,  OK,  OK } }, } },
    };

    for (auto &&d : data) {
        auto schemeFrom = d.first;

        for (int i = 0; i < 4; ++i) {
            const auto &it = settingCombinations[i];
            bool canAccessFileUrls = it.first, canAccessRemoteUrl = it.second;

            QVariantMap testPairs;
            for (auto &&destSchemes : d.second) {
                auto &&destScheme = destSchemes.first;
                auto &&expectedResults = destSchemes.second;
                testPairs[destScheme] = expectedResults[i];
            }

            QTest::addRow("%s_%s_%s", schemeFrom, (canAccessFileUrls ? "local" : "nolocal"), (canAccessRemoteUrl ? "remote" : "noremote"))
                << schemeFrom << canAccessFileUrls << canAccessRemoteUrl << testPairs;
        }
    }
}

void tst_Origins::mixedXHR()
{
    QFETCH(QString, schemeFrom);
    QFETCH(bool, canAccessFileUrls);
    QFETCH(bool, canAccessRemoteUrl);
    QFETCH(QVariantMap, testPairs);

    QString srcDir(QDir(QT_TESTCASE_SOURCEDIR).canonicalPath());
    auto loadUrl = QString("%1:%2/resources/mixedXHR.html").arg(schemeFrom).arg(schemeFrom == "file" ? srcDir : "");
    auto sendXHR = [&] (const QString &scheme) {
        if (scheme == "data")
            return QString("sendXHR('data:,ok')");
        return QString("sendXHR('%1:%2/resources/mixedXHR.txt')").arg(scheme).arg(scheme == "file" ? srcDir : "");
    };

    QCOMPARE(testPairs.size(), 7);
    ScopedAttribute sa0(m_page->settings(), QWebEngineSettings::LocalContentCanAccessFileUrls, canAccessFileUrls);
    ScopedAttribute sa1(m_page->settings(), QWebEngineSettings::LocalContentCanAccessRemoteUrls, canAccessRemoteUrl);
    QVERIFY(verifyLoad(loadUrl));

    QStringList schemesTo, expected, results;
    for (auto it = testPairs.begin(), end = testPairs.end(); it != end; ++it) {
        auto schemeTo = it.key();
        auto expectedResult = it.value().toString();
        auto command = sendXHR(schemeTo);

        eval(command);

        QTRY_COMPARE(eval(QSL("result !== undefined")), QVariant(true));
        auto result = eval(QSL("result")).toString();

        schemesTo.append(schemeTo.rightJustified(10));
        results.append(result.rightJustified(10));
        expected.append(expectedResult.rightJustified(10));
    }
    QVERIFY2(results == expected,
        qPrintable(QString("From '%1' to:\n\tScheme: %2\n\tActual: %3\n\tExpect: %4")
            .arg(schemeFrom).arg(schemesTo.join(' ')).arg(results.join(' ')).arg(expected.join(' '))));
}

// Load the main page over one scheme, then load an iframe over a different scheme. This load is not considered CORS.
void tst_Origins::mixedContent_data()
{
    QTest::addColumn<QString>("schemeFrom");
    QTest::addColumn<bool>("canAccessFileUrls");
    QTest::addColumn<bool>("canAccessRemoteUrl");
    QTest::addColumn<QVariantMap>("testPairs");

    bool defaultFileAccess = true;
    bool defaultRemoteAccess = false;
    std::vector<std::pair<bool, bool>> settingCombinations = {
        { defaultFileAccess, defaultRemoteAccess },  // tag: *schemeFrom*_local_noremote
        { defaultFileAccess, !defaultRemoteAccess }, // tag: *schemeFrom*_local_remote
        { !defaultFileAccess, defaultRemoteAccess }, // tag: *schemeFrom*_nolocal_noremote
        { !defaultFileAccess, !defaultRemoteAccess } // tag: *schemeFrom*_nolocal_remote
    };

    QVariant SLF = QVariant(QSL("canLoadAndAccess")), OK = QVariant(QSL("canLoadButNotAccess")), ERR = QVariant(QSL("cannotLoad"));
    std::vector<
        std::pair<const char *, std::vector<
            std::pair<const char *, std::vector<QVariant>>>>> data = {
        { "file", {
            { "file",               { SLF, SLF, ERR, ERR } },
            { "qrc",                {  OK,  OK,  OK,  OK } },
            { "tst",                { ERR,  OK, ERR,  OK } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               { ERR,  OK, ERR,  OK } },
            { "local-localaccess",  {  OK,  OK, ERR, ERR } },
            { "local-cors",         {  OK,  OK, ERR, ERR } },
        } },

        { "qrc",  {
            { "file",               { ERR, ERR, ERR, ERR } },
            { "qrc",                { SLF, SLF, SLF, SLF } },
            { "tst",                {  OK,  OK,  OK,  OK } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               {  OK,  OK,  OK,  OK } },
            { "local-localaccess",  { ERR, ERR, ERR, ERR } },
            { "local-cors",         { ERR, ERR, ERR, ERR } }, } },

        { "tst",  {
            { "file",               { ERR, ERR, ERR, ERR } },
            { "qrc",                {  OK,  OK,  OK,  OK } },
            { "tst",                { SLF, SLF, SLF, SLF } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               {  OK,  OK,  OK,  OK } },
            { "local-localaccess",  { ERR, ERR, ERR, ERR } },
            { "local-cors",         { ERR, ERR, ERR, ERR } }, } },

        { "cors", {                 // -local +cors -local-access
            { "file",               { ERR, ERR, ERR, ERR } },
            { "qrc",                {  OK,  OK,  OK,  OK } },
            { "tst",                {  OK,  OK,  OK,  OK } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               { SLF, SLF, SLF, SLF } },
            { "local-localaccess",  { ERR, ERR, ERR, ERR } },
            { "local-cors",         { ERR, ERR, ERR, ERR } }, } },

        { "local", {                // +local -cors -local-access
            { "file",               {  OK,  OK, ERR, ERR } },
            { "qrc",                {  OK,  OK,  OK,  OK } },
            { "tst",                { ERR,  OK, ERR,  OK } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               { ERR,  OK, ERR,  OK } },
            { "local-localaccess",  {  OK,  OK, ERR, ERR } },
            { "local-cors",         {  OK,  OK, ERR, ERR } },
        } },

        { "local-cors", {           // +local +cors -local-access
            { "file",               {  OK,  OK, ERR, ERR } },
            { "qrc",                {  OK,  OK,  OK,  OK } },
            { "tst",                { ERR,  OK, ERR,  OK } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               { ERR,  OK, ERR,  OK } },
            { "local-localaccess",  {  OK,  OK, ERR, ERR } },
            { "local-cors",         { SLF, SLF, ERR, ERR } },
        } },

        { "local-localaccess", {    // +local -cors + OK-access
            { "file",               {  OK,  OK,  OK,  OK } },
            { "qrc",                {  OK,  OK,  OK,  OK } },
            { "tst",                { ERR,  OK, ERR,  OK } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               { ERR,  OK, ERR,  OK } },
            { "local-localaccess",  { SLF, SLF,  OK,  OK } }, // ### should probably be: SLF, SLF, SLF, SLF
            { "local-cors",         {  OK,  OK,  OK,  OK } },
        } },

        { "localaccess", {          // -local -cors +local-access
            { "file",               {  OK,  OK,  OK,  OK } },
            { "qrc",                {  OK,  OK,  OK,  OK } },
            { "tst",                {  OK,  OK,  OK,  OK } },
            { "data",               {  OK,  OK,  OK,  OK } },
            { "cors",               {  OK,  OK,  OK,  OK } },
            { "local-localaccess",  {  OK,  OK,  OK,  OK } },
            { "local-cors",         {  OK,  OK,  OK,  OK } }, } },
    };

    for (auto &&d : data) {
        auto schemeFrom = d.first;

        for (int i = 0; i < 4; ++i) {
            const auto &it = settingCombinations[i];
            bool canAccessFileUrls = it.first, canAccessRemoteUrl = it.second;

            QVariantMap testPairs;
            for (auto &&destSchemes : d.second) {
                auto &&destScheme = destSchemes.first;
                auto &&expectedResults = destSchemes.second;
                testPairs[destScheme] = expectedResults[i];
            }

            QTest::addRow("%s_%s_%s", schemeFrom, (canAccessFileUrls ? "local" : "nolocal"), (canAccessRemoteUrl ? "remote" : "noremote"))
                << schemeFrom << canAccessFileUrls << canAccessRemoteUrl << testPairs;
        }
    }
}

void tst_Origins::mixedContent()
{
    QFETCH(QString, schemeFrom);
    QFETCH(bool, canAccessFileUrls);
    QFETCH(bool, canAccessRemoteUrl);
    QFETCH(QVariantMap, testPairs);

    QString srcDir(QDir(QT_TESTCASE_SOURCEDIR).canonicalPath());
    auto loadUrl = QString("%1:%2/resources/mixedSchemes.html").arg(schemeFrom).arg(schemeFrom == "file" ? srcDir : "");

    QCOMPARE(testPairs.size(), 7);
    ScopedAttribute sa2(m_page->settings(), QWebEngineSettings::ErrorPageEnabled, false);
    ScopedAttribute sa0(m_page->settings(), QWebEngineSettings::LocalContentCanAccessFileUrls, canAccessFileUrls);
    ScopedAttribute sa1(m_page->settings(), QWebEngineSettings::LocalContentCanAccessRemoteUrls, canAccessRemoteUrl);
    QVERIFY(verifyLoad(loadUrl));

    auto setIFrameUrl = [&] (const QString &scheme) {
        if (scheme == "data")
            return QString("setIFrameUrl('data:,<script>var canary = true; parent.canary = "
                           "true</script>','data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA"
                           "AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/"
                           "w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==')");
        auto frameUrl = QString("%1:%2/resources/mixedSchemes_frame.html").arg(scheme).arg(scheme == "file" ? srcDir : "");
        auto imgUrl =
                QString("%1:%2/resources/red.png").arg(scheme).arg(scheme == "file" ? srcDir : "");
        return QString("setIFrameUrl('%1','%2')").arg(frameUrl).arg(imgUrl);
    };

    m_page->clearLog();
    QStringList schemesTo, expected, results;
    for (auto it = testPairs.begin(), end = testPairs.end(); it != end; ++it) {

        auto schemeTo = it.key();
        auto expectedResult = it.value().toString();

        eval(setIFrameUrl(schemeTo));

        // wait for token in the log
        QTRY_VERIFY(m_page->logContainsDoneMarker());
        const QString result = m_page->findResultInLog();
        m_page->clearLog();
        schemesTo.append(schemeTo.rightJustified(20));
        results.append(result.rightJustified(20));
        expected.append(expectedResult.rightJustified(20));
    }
    QVERIFY2(results == expected,
        qPrintable(QString("\nFrom '%1' to:\n\tScheme: %2\n\tActual: %3\n\tExpect: %4")
            .arg(schemeFrom).arg(schemesTo.join(' ')).arg(results.join(' ')).arg(expected.join(' '))));
}

#if defined(WEBSOCKETS)
class EchoServer : public QObject {
    Q_OBJECT
    Q_PROPERTY(QUrl url READ url NOTIFY urlChanged)
public:
    EchoServer() : webSocketServer(QSL("EchoServer"), QWebSocketServer::NonSecureMode)
    {
        connect(&webSocketServer, &QWebSocketServer::newConnection, this, &EchoServer::onNewConnection);
    }

    bool listen()
    {
        if (webSocketServer.listen(QHostAddress::Any)) {
            Q_EMIT urlChanged();
            return true;
        }
        return false;
    }

    QUrl url() const
    {
        return webSocketServer.serverUrl();
    }

Q_SIGNALS:
    void urlChanged();

private:
    void onNewConnection()
    {
        QWebSocket *socket = webSocketServer.nextPendingConnection();
        connect(socket, &QWebSocket::textMessageReceived, this, &EchoServer::onTextMessageReceived);
        connect(socket, &QWebSocket::disconnected, socket, &QObject::deleteLater);
    }

    void onTextMessageReceived(const QString &message)
    {
        QWebSocket *socket = qobject_cast<QWebSocket *>(sender());
        socket->sendTextMessage(message);
    }

    QWebSocketServer webSocketServer;
};

// Try opening a WebSocket from pages loaded over various URL schemes.
void tst_Origins::webSocket()
{
    EchoServer echoServer;
    QWebChannel channel;
    channel.registerObject(QSL("echoServer"), &echoServer);
    m_page->setWebChannel(&channel);
    QVERIFY(echoServer.listen());

    QVERIFY(verifyLoad("file:" + QDir(QT_TESTCASE_SOURCEDIR).canonicalPath()
                       + "/resources/websocket.html"));
    QTRY_COMPARE(eval(QSL("result")), QVariant(QSL("ok")));

    QVERIFY(verifyLoad(QSL("qrc:/resources/websocket.html")));
    QTRY_COMPARE(eval(QSL("result")), QVariant(QSL("ok")));

    // Unregistered schemes can also open WebSockets (since Chromium 71)
    QVERIFY(verifyLoad(QSL("tst:/resources/websocket2.html")));
    QTRY_COMPARE(eval(QSL("result")), QVariant(QSL("ok")));

    // Even an insecure registered scheme can open WebSockets.
    QVERIFY(verifyLoad(QSL("PathSyntax:/resources/websocket2.html")));
    QTRY_COMPARE(eval(QSL("result")), QVariant(QSL("ok")));
}
#endif
// Create a (Dedicated)Worker. Since dedicated workers can only be accessed from
// one page, there is not much need for security restrictions.
void tst_Origins::dedicatedWorker()
{
    QVERIFY(verifyLoad("file:" + QDir(QT_TESTCASE_SOURCEDIR).canonicalPath()
                       + "/resources/dedicatedWorker.html"));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QCOMPARE(eval(QSL("result")), QVariant(42));

    QVERIFY(verifyLoad(QSL("qrc:/resources/dedicatedWorker.html")));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QCOMPARE(eval(QSL("result")), QVariant(42));

    // Unregistered schemes can also create Workers (since Chromium 71)
    QVERIFY(verifyLoad(QSL("tst:/resources/dedicatedWorker.html")));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QCOMPARE(eval(QSL("result")), QVariant(42));

    // Even an insecure registered scheme can create Workers.
    QVERIFY(verifyLoad(QSL("PathSyntax:/resources/dedicatedWorker.html")));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QCOMPARE(eval(QSL("result")), QVariant(42));

    // But not if the NoAccessAllowed flag is set.
    QVERIFY(verifyLoad(QSL("PathSyntax-NoAccessAllowed:/resources/dedicatedWorker.html")));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QVERIFY(eval(QSL("error")).toString()
            .contains(QSL("cannot be accessed from origin 'null'")));
}

// Create a SharedWorker. Shared workers can be accessed from multiple pages,
// and therefore the same-origin policy applies.
void tst_Origins::sharedWorker()
{
    {
        ScopedAttribute sa(m_page->settings(), QWebEngineSettings::LocalContentCanAccessFileUrls, false);
        QVERIFY(verifyLoad("file:" + QDir(QT_TESTCASE_SOURCEDIR).canonicalPath()
                           + "/resources/sharedWorker.html"));
        QTRY_VERIFY_WITH_TIMEOUT(eval(QSL("done")).toBool(), 10000);
        QVERIFY(eval(QSL("error")).toString()
                .contains(QSL("cannot be accessed from origin 'null'")));
    }

    {
        ScopedAttribute sa(m_page->settings(), QWebEngineSettings::LocalContentCanAccessFileUrls, true);
        QVERIFY(verifyLoad("file:" + QDir(QT_TESTCASE_SOURCEDIR).canonicalPath()
                           + "/resources/sharedWorker.html"));
        QTRY_VERIFY_WITH_TIMEOUT(eval(QSL("done")).toBool(), 10000);
        QCOMPARE(eval(QSL("result")), QVariant(42));
    }

    QVERIFY(verifyLoad(QSL("qrc:/resources/sharedWorker.html")));
    QTRY_VERIFY_WITH_TIMEOUT(eval(QSL("done")).toBool(), 10000);
    QCOMPARE(eval(QSL("result")), QVariant(42));

    // Unregistered schemes should not create SharedWorkers.

    QVERIFY(verifyLoad(QSL("PathSyntax:/resources/sharedWorker.html")));
    QTRY_VERIFY_WITH_TIMEOUT(eval(QSL("done")).toBool(), 10000);
    QCOMPARE(eval(QSL("result")), QVariant(42));

    QVERIFY(verifyLoad(QSL("PathSyntax-NoAccessAllowed:/resources/sharedWorker.html")));
    QTRY_VERIFY_WITH_TIMEOUT(eval(QSL("done")).toBool(), 10000);
    QVERIFY(eval(QSL("error")).toString()
            .contains(QSL("denied to origin 'null'")));
}

// Service workers have to be explicitly enabled for a scheme.
void tst_Origins::serviceWorker()
{
    QVERIFY(verifyLoad("file:" + QDir(QT_TESTCASE_SOURCEDIR).canonicalPath()
                       + "/resources/serviceWorker.html"));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QVERIFY(eval(QSL("error")).toString()
            .contains(QSL("The URL protocol of the current origin ('file://') is not supported.")));

    QVERIFY(verifyLoad(QSL("qrc:/resources/serviceWorker.html")));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QVERIFY(eval(QSL("error")).toString()
            .contains(QSL("The URL protocol of the current origin ('qrc:') is not supported.")));

    QVERIFY(verifyLoad(QSL("tst:/resources/serviceWorker.html")));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QVERIFY(eval(QSL("error")).toString()
             .contains(QSL("Cannot read properties of undefined")));

    QVERIFY(verifyLoad(QSL("PathSyntax:/resources/serviceWorker.html")));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QVERIFY(eval(QSL("error")).toString()
            .contains(QSL("Cannot read properties of undefined")));

    QVERIFY(verifyLoad(QSL("PathSyntax-Secure:/resources/serviceWorker.html")));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QVERIFY(eval(QSL("error")).toString()
            .contains(QSL("The URL protocol of the current origin ('pathsyntax-secure:') is not supported.")));

    QVERIFY(verifyLoad(QSL("PathSyntax-ServiceWorkersAllowed:/resources/serviceWorker.html")));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QVERIFY(eval(QSL("error")).toString()
            .contains(QSL("Cannot read properties of undefined")));

    QVERIFY(verifyLoad(QSL("PathSyntax-Secure-ServiceWorkersAllowed:/resources/serviceWorker.html")));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QCOMPARE(eval(QSL("error")), QVariant());

    QVERIFY(verifyLoad(QSL("PathSyntax-NoAccessAllowed:/resources/serviceWorker.html")));
    QTRY_VERIFY(eval(QSL("done")).toBool());
    QVERIFY(eval(QSL("error")).toString()
            .contains(QSL("Cannot read properties of undefined")));
}

// Support for view-source must be enabled explicitly.
void tst_Origins::viewSource()
{
    QVERIFY(verifyLoad("view-source:file:" + QDir(QT_TESTCASE_SOURCEDIR).canonicalPath()
                       + "/resources/viewSource.html"));
#ifdef Q_OS_WIN
    QCOMPARE(m_page->requestedUrl().toString(),
             "file:///" + QDir(QT_TESTCASE_SOURCEDIR).canonicalPath()
                     + "/resources/viewSource.html");
#else
    QCOMPARE(m_page->requestedUrl().toString(),
             "file://" + QDir(QT_TESTCASE_SOURCEDIR).canonicalPath()
                     + "/resources/viewSource.html");
#endif

    QVERIFY(verifyLoad(QSL("view-source:qrc:/resources/viewSource.html")));
    QCOMPARE(m_page->requestedUrl().toString(), QSL("qrc:/resources/viewSource.html"));

    QVERIFY(verifyLoad(QSL("view-source:tst:/resources/viewSource.html")));
    QCOMPARE(m_page->requestedUrl().toString(), QSL("about:blank"));

    QVERIFY(verifyLoad(QSL("view-source:PathSyntax:/resources/viewSource.html")));
    QCOMPARE(m_page->requestedUrl().toString(), QSL("about:blank"));

    QVERIFY(verifyLoad(QSL("view-source:PathSyntax-ViewSourceAllowed:/resources/viewSource.html")));
    QCOMPARE(m_page->requestedUrl().toString(), QSL("pathsyntax-viewsourceallowed:/resources/viewSource.html"));
}

void tst_Origins::createObjectURL()
{
    // Legal for registered custom schemes.
    QVERIFY(verifyLoad(QSL("qrc:/resources/createObjectURL.html")));
    QVERIFY(eval(QSL("result")).toString().startsWith(QSL("blob:qrc:")));

    // Also legal for unregistered schemes (since Chromium 71)
    QVERIFY(verifyLoad(QSL("tst:/resources/createObjectURL.html")));
    QVERIFY(eval(QSL("result")).toString().startsWith(QSL("blob:tst:")));
}

void tst_Origins::redirectScheme()
{
    QVERIFY(verifyLoad(QSL("redirect:cors/resources/redirect.html")));
    eval("addStylesheetLink('redirect:cors/resources/redirect.css')");
    QTRY_COMPARE(m_handler->requests().size(), 4);
    QCOMPARE(m_handler->requests()[0], QUrl(QStringLiteral("redirect:cors/resources/redirect.html")));
    QCOMPARE(m_handler->requests()[1], QUrl(QStringLiteral("cors:/resources/redirect.html")));
    QCOMPARE(m_handler->requests()[2], QUrl(QStringLiteral("redirect:cors/resources/redirect.css")));
    QCOMPARE(m_handler->requests()[3], QUrl(QStringLiteral("cors:/resources/redirect.css")));

    QVERIFY(!verifyLoad(QSL("redirect:file/resources/redirect.html")));
    QVERIFY(!verifyLoad(QSL("redirect:local/resources/redirect.html")));
    QVERIFY(!verifyLoad(QSL("redirect:local-cors/resources/redirect.html")));
}

void tst_Origins::redirectSchemeLocal()
{
    QVERIFY(verifyLoad(QSL("redirect-local:local/resources/redirect.html")));
    eval("addStylesheetLink('redirect-local:local/resources/redirect.css')");
    QTRY_COMPARE(m_handler->requests().size(), 4);
    QCOMPARE(m_handler->requests()[0], QUrl(QStringLiteral("redirect-local:local/resources/redirect.html")));
    QCOMPARE(m_handler->requests()[1], QUrl(QStringLiteral("local:/resources/redirect.html")));
    QCOMPARE(m_handler->requests()[2], QUrl(QStringLiteral("redirect-local:local/resources/redirect.css")));
    QCOMPARE(m_handler->requests()[3], QUrl(QStringLiteral("local:/resources/redirect.css")));
}

void tst_Origins::redirectSchemeSecure()
{
    QVERIFY(verifyLoad(QSL("redirect-secure:secure-cors/resources/redirect.html")));
    eval("addStylesheetLink('redirect-secure:secure-cors/resources/redirect.css')");
    QTRY_COMPARE(m_handler->requests().size(), 4);
    QCOMPARE(m_handler->requests()[0], QUrl(QStringLiteral("redirect-secure:secure-cors/resources/redirect.html")));
    QCOMPARE(m_handler->requests()[1], QUrl(QStringLiteral("secure-cors:/resources/redirect.html")));
    QCOMPARE(m_handler->requests()[2], QUrl(QStringLiteral("redirect-secure:secure-cors/resources/redirect.css")));
    QCOMPARE(m_handler->requests()[3], QUrl(QStringLiteral("secure-cors:/resources/redirect.css")));
}

void tst_Origins::redirectInterceptor()
{
    TestRequestInterceptor interceptor;
    m_profile.setUrlRequestInterceptor(&interceptor);

    QVERIFY(verifyLoad(QSL("redirect:cors/resources/redirect.html")));
    eval("addStylesheetLink('redirect:cors/resources/redirect.css')");

    QTRY_COMPARE(interceptor.requests.size(), 4);
    QTRY_COMPARE(m_handler->requests().size(), 2);
    QCOMPARE(m_handler->requests()[0], QUrl(QStringLiteral("cors:/resources/redirect.html")));
    QCOMPARE(m_handler->requests()[1], QUrl(QStringLiteral("cors:/resources/redirect.css")));

    QCOMPARE(interceptor.requests[0], QUrl(QStringLiteral("redirect:cors/resources/redirect.html")));
    QCOMPARE(interceptor.requests[1], QUrl(QStringLiteral("cors:/resources/redirect.html")));
    QCOMPARE(interceptor.requests[2], QUrl(QStringLiteral("redirect:cors/resources/redirect.css")));
    QCOMPARE(interceptor.requests[3], QUrl(QStringLiteral("cors:/resources/redirect.css")));

    QVERIFY(!verifyLoad(QSL("redirect:file/resources/redirect.html")));
    QVERIFY(!verifyLoad(QSL("redirect:local/resources/redirect.html")));
    QVERIFY(!verifyLoad(QSL("redirect:local-cors/resources/redirect.html")));
}

void tst_Origins::redirectInterceptorLocal()
{
    TestRequestInterceptor interceptor;
    m_profile.setUrlRequestInterceptor(&interceptor);

    QVERIFY(verifyLoad(QSL("redirect-local:local/resources/redirect.html")));
    eval("addStylesheetLink('redirect-local:local/resources/redirect.css')");

    QTRY_COMPARE(interceptor.requests.size(), 4);
    QTRY_COMPARE(m_handler->requests().size(), 2);
    QCOMPARE(m_handler->requests()[0], QUrl(QStringLiteral("local:/resources/redirect.html")));
    QCOMPARE(m_handler->requests()[1], QUrl(QStringLiteral("local:/resources/redirect.css")));

    QCOMPARE(interceptor.requests[0], QUrl(QStringLiteral("redirect-local:local/resources/redirect.html")));
    QCOMPARE(interceptor.requests[1], QUrl(QStringLiteral("local:/resources/redirect.html")));
    QCOMPARE(interceptor.requests[2], QUrl(QStringLiteral("redirect-local:local/resources/redirect.css")));
    QCOMPARE(interceptor.requests[3], QUrl(QStringLiteral("local:/resources/redirect.css")));
}

void tst_Origins::redirectInterceptorSecure()
{
    TestRequestInterceptor interceptor;
    m_profile.setUrlRequestInterceptor(&interceptor);

    QVERIFY(verifyLoad(QSL("redirect-secure:secure-cors/resources/redirect.html")));
    eval("addStylesheetLink('redirect-secure:secure-cors/resources/redirect.css')");

    QTRY_COMPARE(interceptor.requests.size(), 4);
    QTRY_COMPARE(m_handler->requests().size(), 2);
    QCOMPARE(m_handler->requests()[0], QUrl(QStringLiteral("secure-cors:/resources/redirect.html")));
    QCOMPARE(m_handler->requests()[1], QUrl(QStringLiteral("secure-cors:/resources/redirect.css")));

    QCOMPARE(interceptor.requests[0], QUrl(QStringLiteral("redirect-secure:secure-cors/resources/redirect.html")));
    QCOMPARE(interceptor.requests[1], QUrl(QStringLiteral("secure-cors:/resources/redirect.html")));
    QCOMPARE(interceptor.requests[2], QUrl(QStringLiteral("redirect-secure:secure-cors/resources/redirect.css")));
    QCOMPARE(interceptor.requests[3], QUrl(QStringLiteral("secure-cors:/resources/redirect.css")));
}

class TestRedirectInterceptor : public QWebEngineUrlRequestInterceptor
{
public:
    TestRedirectInterceptor() = default;
    void interceptRequest(QWebEngineUrlRequestInfo &info) override
    {
        qCDebug(lc) << this << "Type:" << info.resourceType() << info.requestMethod() << "Navigation:" << info.navigationType()
                    << info.requestUrl() << "Initiator:" << info.initiator();

        QUrl url = info.requestUrl();
        requests << url;
        if (url.path().startsWith("/redirect")) {
            QString path = url.path();
            int idx = path.indexOf(QChar('/'), 10);
            if (idx > 0) {
                url.setScheme(path.mid(10, idx - 10));
                url.setPath(path.mid(idx, -1));
                url.setHost({});
                info.redirect(url);
            }
        }
    }
    QList<QUrl> requests;
};

void tst_Origins::redirectInterceptorFile()
{
    TestRedirectInterceptor interceptor;
    m_profile.setUrlRequestInterceptor(&interceptor);

    QVERIFY(verifyLoad(QSL("file:///redirect/local-cors/resources/redirect.html")));
    eval("addStylesheetLink('file:///redirect/local-cors/resources/redirect.css')");

    QTRY_COMPARE(interceptor.requests.size(), 4);
    QTRY_COMPARE(m_handler->requests().size(), 2);
    QCOMPARE(m_handler->requests()[0], QUrl(QStringLiteral("local-cors:/resources/redirect.html")));
    QCOMPARE(m_handler->requests()[1], QUrl(QStringLiteral("local-cors:/resources/redirect.css")));

    QCOMPARE(interceptor.requests[0], QUrl(QStringLiteral("file:///redirect/local-cors/resources/redirect.html")));
    QCOMPARE(interceptor.requests[1], QUrl(QStringLiteral("local-cors:/resources/redirect.html")));
    QCOMPARE(interceptor.requests[2], QUrl(QStringLiteral("file:///redirect/local-cors/resources/redirect.css")));
    QCOMPARE(interceptor.requests[3], QUrl(QStringLiteral("local-cors:/resources/redirect.css")));
}

void tst_Origins::redirectInterceptorHttp()
{
    TestRedirectInterceptor interceptor;
    m_profile.setUrlRequestInterceptor(&interceptor);

    QVERIFY(verifyLoad(QSL("http://hallo/redirect/cors/resources/redirect.html")));
    eval("addStylesheetLink('http://hallo/redirect/cors/resources/redirect.css')");

    QTRY_COMPARE(interceptor.requests.size(), 4);
    QTRY_COMPARE(m_handler->requests().size(), 2);
    QCOMPARE(m_handler->requests()[0], QUrl(QStringLiteral("cors:/resources/redirect.html")));
    QCOMPARE(m_handler->requests()[1], QUrl(QStringLiteral("cors:/resources/redirect.css")));

    QCOMPARE(interceptor.requests[0], QUrl(QStringLiteral("http://hallo/redirect/cors/resources/redirect.html")));
    QCOMPARE(interceptor.requests[1], QUrl(QStringLiteral("cors:/resources/redirect.html")));
    QCOMPARE(interceptor.requests[2], QUrl(QStringLiteral("http://hallo/redirect/cors/resources/redirect.css")));
    QCOMPARE(interceptor.requests[3], QUrl(QStringLiteral("cors:/resources/redirect.css")));
}

void tst_Origins::localMediaBlock_data()
{
    QTest::addColumn<bool>("enableAccess");
    QTest::addRow("enabled") << true;
    QTest::addRow("disabled") << false;
}

void tst_Origins::localMediaBlock()
{
    QFETCH(bool, enableAccess);

    std::atomic<bool> accessed = false;
    HttpServer server;
    server.setResourceDirs({ QDir(QT_TESTCASE_SOURCEDIR).canonicalPath() + "/resources" });
    connect(&server, &HttpServer::newRequest, [&](HttpReqRep *) { accessed.store(true); });
    QVERIFY(server.start());

    ScopedAttribute sa1(m_page->settings(), QWebEngineSettings::LocalContentCanAccessRemoteUrls, enableAccess);

    QVERIFY(verifyLoad("file:" + QDir(QT_TESTCASE_SOURCEDIR).canonicalPath()
                       + "/resources/media.html"));
    eval("addAudio('" + server.url("/mixedXHR.txt").toString() + "')");

    // Give it a chance to avoid a false positive on the default value of accessed.
    if (!enableAccess)
        QTest::qSleep(500);
    QTRY_COMPARE(accessed.load(), enableAccess);

}

QTEST_MAIN(tst_Origins)
#include "tst_origins.moc"