-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathWKURLSchemeHandler-1.mm
More file actions
1733 lines (1474 loc) · 72.6 KB
/
Copy pathWKURLSchemeHandler-1.mm
File metadata and controls
1733 lines (1474 loc) · 72.6 KB
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 (C) 2017 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "config.h"
#import "DeprecatedGlobalValues.h"
#import "HTTPServer.h"
#import "PlatformUtilities.h"
#import "Test.h"
#import "TestNavigationDelegate.h"
#import "TestUIDelegate.h"
#import "TestURLSchemeHandler.h"
#import "TestWKWebView.h"
#import "WKWebViewConfigurationExtras.h"
#import <WebKit/WKErrorPrivate.h>
#import <WebKit/WKFrameInfoPrivate.h>
#import <WebKit/WKProcessPoolPrivate.h>
#import <WebKit/WKURLSchemeHandler.h>
#import <WebKit/WKURLSchemeTaskPrivate.h>
#import <WebKit/WKWebViewConfigurationPrivate.h>
#import <WebKit/WebKit.h>
#import <WebKit/_WKFrameHandle.h>
#import <WebKit/_WKFrameTreeNode.h>
#import <wtf/BlockPtr.h>
#import <wtf/HashMap.h>
#import <wtf/RetainPtr.h>
#import <wtf/RunLoop.h>
#import <wtf/Threading.h>
#import <wtf/Vector.h>
#import <wtf/WeakObjCPtr.h>
#import <wtf/text/StringConcatenateNumbers.h>
#import <wtf/text/StringHash.h>
#import <wtf/text/StringToIntegerConversion.h>
#import <wtf/text/WTFString.h>
@interface SchemeHandler : NSObject <WKURLSchemeHandler>
@property (readonly) NSMutableArray<NSURL *> *startedURLs;
@property (readonly) NSMutableArray<NSURL *> *stoppedURLs;
@property (assign) BOOL shouldFinish;
- (instancetype)initWithData:(NSData *)data mimeType:(NSString *)inMIMEType;
@end
@implementation SchemeHandler {
RetainPtr<NSData> resourceData;
RetainPtr<NSString> mimeType;
}
- (instancetype)initWithData:(NSData *)data mimeType:(NSString *)inMIMEType
{
self = [super init];
if (!self)
return nil;
resourceData = data;
mimeType = inMIMEType;
_startedURLs = [[NSMutableArray alloc] init];
_stoppedURLs = [[NSMutableArray alloc] init];
_shouldFinish = YES;
return self;
}
- (void)dealloc
{
[_startedURLs release];
[_stoppedURLs release];
[super dealloc];
}
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id <WKURLSchemeTask>)task
{
[_startedURLs addObject:task.request.URL];
// Always fail the image load.
if ([task.request.URL.absoluteString isEqualToString:@"testing:image"]) {
[task didFailWithError:[NSError errorWithDomain:@"TestWebKitAPI" code:1 userInfo:nil]];
done = true;
return;
}
RetainPtr<NSURLResponse> response = adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:mimeType.get() expectedContentLength:1 textEncodingName:nil]);
[task didReceiveResponse:response.get()];
[task didReceiveData:resourceData.get()];
if (_shouldFinish)
[task didFinish];
}
- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id <WKURLSchemeTask>)task
{
[_stoppedURLs addObject:task.request.URL];
done = true;
}
@end
@interface URLSchemeHandlerAsyncNavigationDelegate : NSObject <WKNavigationDelegate, WKUIDelegate>
@end
@implementation URLSchemeHandlerAsyncNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
int64_t deferredWaitTime = 100 * NSEC_PER_MSEC;
dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, deferredWaitTime);
dispatch_after(when, dispatch_get_main_queue(), ^{
decisionHandler(WKNavigationActionPolicyAllow);
});
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
int64_t deferredWaitTime = 100 * NSEC_PER_MSEC;
dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, deferredWaitTime);
dispatch_after(when, dispatch_get_main_queue(), ^{
decisionHandler(WKNavigationResponsePolicyAllow);
});
}
@end
static const char mainBytes[] =
"<html>" \
"<img src='testing:image'>" \
"</html>";
TEST(URLSchemeHandler, Basic)
{
done = false;
RetainPtr<WKWebViewConfiguration> configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
RetainPtr<SchemeHandler> handler = adoptNS([[SchemeHandler alloc] initWithData:[NSData dataWithBytesNoCopy:(void*)mainBytes length:sizeof(mainBytes) freeWhenDone:NO] mimeType:@"text/html"]);
[configuration setURLSchemeHandler:handler.get() forURLScheme:@"testing"];
RetainPtr<WKWebView> webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"testing:main"]];
[webView loadRequest:request];
TestWebKitAPI::Util::run(&done);
EXPECT_EQ([handler.get().startedURLs count], 2u);
EXPECT_TRUE([[handler.get().startedURLs objectAtIndex:0] isEqual:[NSURL URLWithString:@"testing:main"]]);
EXPECT_TRUE([[handler.get().startedURLs objectAtIndex:1] isEqual:[NSURL URLWithString:@"testing:image"]]);
EXPECT_EQ([handler.get().stoppedURLs count], 0u);
}
TEST(URLSchemeHandler, BasicWithAsyncPolicyDelegate)
{
done = false;
RetainPtr<WKWebViewConfiguration> configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
RetainPtr<SchemeHandler> handler = adoptNS([[SchemeHandler alloc] initWithData:[NSData dataWithBytesNoCopy:(void*)mainBytes length:sizeof(mainBytes) freeWhenDone:NO] mimeType:@"text/html"]);
[configuration setURLSchemeHandler:handler.get() forURLScheme:@"testing"];
RetainPtr<WKWebView> webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
auto delegate = adoptNS([[URLSchemeHandlerAsyncNavigationDelegate alloc] init]);
[webView setNavigationDelegate:delegate.get()];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"testing:main"]];
[webView loadRequest:request];
TestWebKitAPI::Util::run(&done);
EXPECT_EQ([handler.get().startedURLs count], 2u);
EXPECT_TRUE([[handler.get().startedURLs objectAtIndex:0] isEqual:[NSURL URLWithString:@"testing:main"]]);
EXPECT_TRUE([[handler.get().startedURLs objectAtIndex:1] isEqual:[NSURL URLWithString:@"testing:image"]]);
EXPECT_EQ([handler.get().stoppedURLs count], 0u);
}
TEST(URLSchemeHandler, NoMIMEType)
{
// Since there's no MIMEType, and no NavigationDelegate to tell WebKit to do the load anyways, WebKit will ignore (silently fail) the load.
// This test makes sure that is communicated back to the URLSchemeHandler.
done = false;
RetainPtr<WKWebViewConfiguration> configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
RetainPtr<SchemeHandler> handler = adoptNS([[SchemeHandler alloc] initWithData:[NSData dataWithBytesNoCopy:(void*)mainBytes length:sizeof(mainBytes) freeWhenDone:NO] mimeType:nil]);
handler.get().shouldFinish = NO;
[configuration setURLSchemeHandler:handler.get() forURLScheme:@"testing"];
RetainPtr<WKWebView> webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"testing:main"]];
[webView loadRequest:request];
TestWebKitAPI::Util::run(&done);
EXPECT_EQ([handler.get().startedURLs count], 1u);
EXPECT_TRUE([[handler.get().startedURLs objectAtIndex:0] isEqual:[NSURL URLWithString:@"testing:main"]]);
EXPECT_EQ([handler.get().stoppedURLs count], 1u);
EXPECT_TRUE([[handler.get().stoppedURLs objectAtIndex:0] isEqual:[NSURL URLWithString:@"testing:main"]]);
}
static NSString *handledSchemes[] = {
@"about",
@"applewebdata",
@"blob",
@"data",
@"file",
@"ftp",
@"http",
@"https",
@"javascript",
@"webkit-fake-url",
@"ws",
@"wss",
#if PLATFORM(MAC)
@"safari-extension",
#endif
#if ENABLE(CONTENT_FILTERING)
@"x-apple-content-filter",
#endif
#if USE(QUICK_LOOK)
@"x-apple-ql-id",
#endif
};
static NSString *notHandledSchemes[] = {
@"gopher",
@"my-custom-scheme",
};
TEST(URLSchemeHandler, BuiltinSchemes)
{
RetainPtr<WKWebViewConfiguration> configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
RetainPtr<SchemeHandler> handler = adoptNS([[SchemeHandler alloc] initWithData:nil mimeType:nil]);
for (NSString *scheme : handledSchemes) {
EXPECT_TRUE([WKWebView handlesURLScheme:scheme]);
bool exceptionRaised = false;
@try {
[configuration setURLSchemeHandler:handler.get() forURLScheme:scheme];
} @catch (NSException *exception) {
EXPECT_WK_STREQ(NSInvalidArgumentException, exception.name);
exceptionRaised = true;
}
EXPECT_TRUE(exceptionRaised);
}
for (NSString *scheme : notHandledSchemes) {
EXPECT_FALSE([WKWebView handlesURLScheme:scheme]);
bool exceptionRaised = false;
@try {
[configuration setURLSchemeHandler:handler.get() forURLScheme:scheme];
} @catch (NSException *exception) {
exceptionRaised = true;
}
EXPECT_FALSE(exceptionRaised);
}
}
static bool receivedRedirect;
static bool responsePolicyDecided;
@interface RedirectSchemeHandler : NSObject <WKURLSchemeHandler, WKNavigationDelegate, WKScriptMessageHandler>
@end
@implementation RedirectSchemeHandler { }
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id <WKURLSchemeTask>)task
{
ASSERT_STREQ(task.request.URL.absoluteString.UTF8String, "testing:///initial");
auto redirectResponse = adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:nil expectedContentLength:0 textEncodingName:nil]);
auto request = adoptNS([[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"testing:///redirected"]]);
[(id<WKURLSchemeTaskPrivate>)task _didPerformRedirection:redirectResponse.get() newRequest:request.get()];
ASSERT_FALSE(receivedRedirect);
ASSERT_STREQ(task.request.URL.absoluteString.UTF8String, "testing:///redirected");
NSString *html = @"<script>window.webkit.messageHandlers.testHandler.postMessage('Document URL: ' + document.URL);</script>";
auto finalResponse = adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:@"text/html" expectedContentLength:html.length textEncodingName:nil]);
[task didReceiveResponse:finalResponse.get()];
[task didReceiveData:[html dataUsingEncoding:NSUTF8StringEncoding]];
[task didFinish];
}
- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id <WKURLSchemeTask>)task
{
ASSERT_TRUE(false);
}
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
ASSERT_FALSE(receivedRedirect);
receivedRedirect = true;
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
ASSERT_TRUE(receivedRedirect);
ASSERT_STREQ(navigationResponse.response.URL.absoluteString.UTF8String, "testing:///redirected");
ASSERT_FALSE(responsePolicyDecided);
responsePolicyDecided = true;
decisionHandler(WKNavigationResponsePolicyAllow);
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
EXPECT_WK_STREQ(@"Document URL: testing:///redirected", [message body]);
done = true;
}
@end
TEST(URLSchemeHandler, Redirection)
{
auto configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
auto handler = adoptNS([[RedirectSchemeHandler alloc] init]);
[configuration setURLSchemeHandler:handler.get() forURLScheme:@"testing"];
[[configuration userContentController] addScriptMessageHandler:handler.get() name:@"testHandler"];
auto webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
[webView setNavigationDelegate:handler.get()];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"testing:///initial"]];
[webView loadRequest:request];
TestWebKitAPI::Util::run(&done);
EXPECT_TRUE(responsePolicyDecided);
EXPECT_STREQ(webView.get().URL.absoluteString.UTF8String, "testing:///redirected");
}
enum class Command {
Redirect,
APIRedirect,
Response,
Data,
Finish,
Error,
};
@interface TaskSchemeHandler : NSObject <WKURLSchemeHandler>
- (instancetype)initWithCommands:(Vector<Command>&&)commandVector expectedException:(bool)expected;
@end
@implementation TaskSchemeHandler {
Vector<Command> commands;
bool expectedException;
}
- (instancetype)initWithCommands:(Vector<Command>&&)commandVector expectedException:(bool)expected
{
self = [super init];
if (!self)
return nil;
self->commands = WTFMove(commandVector);
self->expectedException = expected;
return self;
}
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id <WKURLSchemeTask>)task
{
bool caughtException = false;
@try {
for (auto command : commands) {
switch (command) {
case Command::Redirect:
[(id<WKURLSchemeTaskPrivate>)task _didPerformRedirection:adoptNS([[NSURLResponse alloc] init]).get() newRequest:adoptNS([[NSURLRequest alloc] init]).get()];
break;
case Command::APIRedirect:
[(id<WKURLSchemeTaskPrivate>)task _willPerformRedirection:adoptNS([[NSURLResponse alloc] init]).get() newRequest:adoptNS([[NSURLRequest alloc] init]).get() completionHandler:^(NSURLRequest*) { }];
break;
case Command::Response:
[task didReceiveResponse:adoptNS([[NSURLResponse alloc] init]).get()];
break;
case Command::Data:
[task didReceiveData:adoptNS([[NSData alloc] init]).get()];
break;
case Command::Finish:
[task didFinish];
break;
case Command::Error:
[task didFailWithError:[NSError errorWithDomain:@"WebKit" code:1 userInfo:nil]];
break;
}
}
}
@catch(NSException *exception)
{
caughtException = true;
}
ASSERT_EQ(caughtException, expectedException);
done = true;
}
- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id <WKURLSchemeTask>)task
{
}
@end
enum class ShouldRaiseException : bool { No, Yes };
static void checkCallSequence(Vector<Command>&& commands, ShouldRaiseException shouldRaiseException)
{
done = false;
auto configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
auto handler = adoptNS([[TaskSchemeHandler alloc] initWithCommands:WTFMove(commands) expectedException:shouldRaiseException == ShouldRaiseException::Yes]);
[configuration setURLSchemeHandler:handler.get() forURLScheme:@"testing"];
auto webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"testing:///initial"]]];
TestWebKitAPI::Util::run(&done);
}
TEST(URLSchemeHandler, Exceptions)
{
checkCallSequence({Command::Response, Command::Data, Command::Finish}, ShouldRaiseException::No);
checkCallSequence({Command::Response, Command::Redirect}, ShouldRaiseException::Yes);
checkCallSequence({Command::Redirect, Command::Response}, ShouldRaiseException::No);
checkCallSequence({Command::Data, Command::Finish}, ShouldRaiseException::Yes);
checkCallSequence({Command::Error}, ShouldRaiseException::No);
checkCallSequence({Command::Error, Command::Error}, ShouldRaiseException::Yes);
checkCallSequence({Command::Error, Command::Data}, ShouldRaiseException::Yes);
checkCallSequence({Command::Response, Command::Finish, Command::Data}, ShouldRaiseException::Yes);
checkCallSequence({Command::Response, Command::Finish, Command::Redirect}, ShouldRaiseException::Yes);
checkCallSequence({Command::Response, Command::Finish, Command::Response}, ShouldRaiseException::Yes);
checkCallSequence({Command::Response, Command::Finish, Command::Finish}, ShouldRaiseException::Yes);
checkCallSequence({Command::Response, Command::Finish, Command::Error}, ShouldRaiseException::Yes);
checkCallSequence({Command::APIRedirect, Command::Redirect}, ShouldRaiseException::Yes);
checkCallSequence({Command::APIRedirect, Command::Response}, ShouldRaiseException::Yes);
checkCallSequence({Command::APIRedirect, Command::Data}, ShouldRaiseException::Yes);
checkCallSequence({Command::APIRedirect, Command::Finish}, ShouldRaiseException::Yes);
checkCallSequence({Command::APIRedirect, Command::Error}, ShouldRaiseException::No);
}
struct SchemeResourceInfo {
RetainPtr<NSString> mimeType;
const char* data;
bool shouldRespond;
};
static bool startedXHR;
static bool receivedStop;
@interface SyncScheme : NSObject <WKURLSchemeHandler> {
@public
HashMap<String, SchemeResourceInfo> resources;
}
@end
@implementation SyncScheme
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id <WKURLSchemeTask>)task
{
auto entry = resources.find([task.request.URL absoluteString]);
if (entry == resources.end()) {
NSLog(@"Did not find resource entry for URL %@", task.request.URL);
return;
}
if (entry->key == "syncxhr://host/test.dat"_s)
startedXHR = true;
if (!entry->value.shouldRespond)
return;
RetainPtr<NSURLResponse> response = adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:entry->value.mimeType.get() expectedContentLength:1 textEncodingName:nil]);
[task didReceiveResponse:response.get()];
[task didReceiveData:[NSData dataWithBytesNoCopy:(void*)entry->value.data length:strlen(entry->value.data) freeWhenDone:NO]];
[task didFinish];
if (entry->key == "syncxhr://host/test.dat"_s)
startedXHR = false;
}
- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id <WKURLSchemeTask>)task
{
EXPECT_TRUE([[task.request.URL absoluteString] isEqualToString:@"syncxhr://host/test.dat"]);
receivedStop = true;
}
@end
static bool receivedMessage;
@interface SyncMessageHandler : NSObject <WKScriptMessageHandler>
@end
@implementation SyncMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
if ([message body])
[receivedMessages addObject:[message body]];
else
[receivedMessages addObject:@""];
receivedMessage = true;
}
@end
static const char syncMainBytes[] = R"SYNCRESOURCE(
<script>
var req = new XMLHttpRequest();
req.open("GET", "test.dat", false);
try
{
req.send(null);
window.webkit.messageHandlers.sync.postMessage(req.responseText);
}
catch (e)
{
window.webkit.messageHandlers.sync.postMessage("Failed sync XHR load");
}
</script>
)SYNCRESOURCE";
static const char syncXHRBytes[] = "My XHR text!";
TEST(URLSchemeHandler, SyncXHR)
{
@autoreleasepool {
auto webViewConfiguration = adoptNS([[WKWebViewConfiguration alloc] init]);
auto handler = adoptNS([[SyncScheme alloc] init]);
[webViewConfiguration setURLSchemeHandler:handler.get() forURLScheme:@"syncxhr"];
handler.get()->resources.set("syncxhr://host/main.html"_s, SchemeResourceInfo { @"text/html", syncMainBytes, true });
handler.get()->resources.set("syncxhr://host/test.dat"_s, SchemeResourceInfo { @"text/plain", syncXHRBytes, true });
auto messageHandler = adoptNS([[SyncMessageHandler alloc] init]);
[[webViewConfiguration userContentController] addScriptMessageHandler:messageHandler.get() name:@"sync"];
auto webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:webViewConfiguration.get()]);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"syncxhr://host/main.html"]];
[webView loadRequest:request];
TestWebKitAPI::Util::run(&receivedMessage);
receivedMessage = false;
EXPECT_EQ((unsigned)receivedMessages.get().count, (unsigned)1);
EXPECT_TRUE([receivedMessages.get()[0] isEqualToString:@"My XHR text!"]);
// Now try again, but hang the WebProcess in the reply to the XHR by telling the scheme handler to never
// respond to it.
handler.get()->resources.find("syncxhr://host/test.dat"_s)->value.shouldRespond = false;
[webView loadRequest:request];
TestWebKitAPI::Util::run(&startedXHR);
receivedMessage = false;
[webView _close];
}
TestWebKitAPI::Util::run(&receivedStop);
}
@interface SyncErrorScheme : NSObject <WKURLSchemeHandler, WKUIDelegate>
@end
@implementation SyncErrorScheme
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id <WKURLSchemeTask>)task
{
if ([task.request.URL.absoluteString isEqualToString:@"syncerror:///main.html"]) {
static const char* bytes = "<script>var xhr=new XMLHttpRequest();xhr.open('GET','subresource',false);try{xhr.send(null);alert('no error')}catch(e){alert(e)}</script>";
[task didReceiveResponse:adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:@"text/html" expectedContentLength:strlen(bytes) textEncodingName:nil]).get()];
[task didReceiveData:[NSData dataWithBytes:bytes length:strlen(bytes)]];
[task didFinish];
} else {
EXPECT_STREQ(task.request.URL.absoluteString.UTF8String, "syncerror:///subresource");
[task didReceiveResponse:adoptNS([[NSURLResponse alloc] init]).get()];
[task didFailWithError:[NSError errorWithDomain:@"TestErrorDomain" code:123 userInfo:nil]];
}
}
- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id <WKURLSchemeTask>)task
{
}
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
EXPECT_STREQ(message.UTF8String, "NetworkError: A network error occurred.");
completionHandler();
done = true;
}
@end
TEST(URLSchemeHandler, SyncXHRError)
{
auto webViewConfiguration = adoptNS([[WKWebViewConfiguration alloc] init]);
auto handler = adoptNS([[SyncErrorScheme alloc] init]);
[webViewConfiguration setURLSchemeHandler:handler.get() forURLScheme:@"syncerror"];
auto webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:webViewConfiguration.get()]);
[webView setUIDelegate:handler.get()];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"syncerror:///main.html"]]];
TestWebKitAPI::Util::run(&done);
}
static constexpr auto xhrPostDocument = R"XHRPOSTRESOURCE(<html><head><script>
window.onload = function()
{
{
var xhr = new XMLHttpRequest();
xhr.open('POST', '/arraybuffer');
var chars = [];
var str = "Hi there";
for (var i = 0; i < str.length; ++i)
chars.push(str.charCodeAt(i));
xhr.send(new Uint8Array(chars));
}
{
var xhr = new XMLHttpRequest();
xhr.open('POST', '/string');
xhr.send('foo=bar');
}
{
var xhr = new XMLHttpRequest();
xhr.open('POST', '/string-upload');
var upload = xhr.upload;
xhr.send('foo=bar2');
}
{
var xhr = new XMLHttpRequest();
xhr.open('POST', '/document');
xhr.send(window.document);
}
{
var xhr = new XMLHttpRequest();
xhr.open('POST', '/formdata');
var formData = new FormData();
formData.append("foo", "baz");
xhr.send(formData);
}
{
// // FIXME: XHR posting of Blobs is currently unsupported
// // https://bugs.webkit.org/show_bug.cgi?id=197237
// var xhr = new XMLHttpRequest();
// xhr.open('POST', '/blob');
// var blob = new Blob(["Hello world!"], {type: "text/plain"});
// xhr.send(blob);
}
};
</script></head>
<body>
Hello world!
</body></html>)XHRPOSTRESOURCE"_s;
TEST(URLSchemeHandler, XHRPost)
{
auto handler = adoptNS([[TestURLSchemeHandler alloc] init]);
auto configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
[configuration setURLSchemeHandler:handler.get() forURLScheme:@"xhrpost"];
auto webView = adoptNS([[TestWKWebView alloc] initWithFrame:CGRectMake(0, 0, 800, 600) configuration:configuration.get()]);
static bool done;
static uint8_t seenTasks;
[handler setStartURLSchemeTaskHandler:^(WKWebView *, id<WKURLSchemeTask> task) {
if ([task.request.URL.absoluteString isEqualToString:@"xhrpost://example/string"]) {
static bool reached;
EXPECT_FALSE(reached);
reached = true;
EXPECT_EQ(task.request.HTTPBody.length, 7u);
EXPECT_STREQ(static_cast<const char*>(task.request.HTTPBody.bytes), "foo=bar");
} else if ([task.request.URL.absoluteString isEqualToString:@"xhrpost://example/string-upload"]) {
static bool reached;
EXPECT_FALSE(reached);
reached = true;
auto stream = task.request.HTTPBodyStream;
EXPECT_TRUE(!!stream);
[stream open];
EXPECT_TRUE(stream.hasBytesAvailable);
uint8_t buffer[9];
memset(buffer, 0, 9);
auto length = [stream read:buffer maxLength:9];
EXPECT_EQ(length, 8);
EXPECT_STREQ(reinterpret_cast<const char*>(buffer), "foo=bar2");
EXPECT_FALSE(stream.hasBytesAvailable);
[stream close];
} else if ([task.request.URL.absoluteString isEqualToString:@"xhrpost://example/arraybuffer"]) {
static bool reached;
EXPECT_FALSE(reached);
reached = true;
EXPECT_EQ(task.request.HTTPBody.length, 8u);
EXPECT_STREQ(static_cast<const char*>(task.request.HTTPBody.bytes), "Hi there");
} else if ([task.request.URL.absoluteString isEqualToString:@"xhrpost://example/document"]) {
static bool reached;
EXPECT_FALSE(reached);
reached = true;
EXPECT_EQ(task.request.HTTPBody.length, strlen(xhrPostDocument));
EXPECT_STREQ(static_cast<const char*>(task.request.HTTPBody.bytes), xhrPostDocument);
} else if ([task.request.URL.absoluteString isEqualToString:@"xhrpost://example/formdata"]) {
static bool reached;
EXPECT_FALSE(reached);
reached = true;
// The length of this is variable
auto *formDataString = [NSString stringWithUTF8String:static_cast<const char*>(task.request.HTTPBody.bytes)];
EXPECT_TRUE([formDataString containsString:@"Content-Disposition: form-data; name=\"foo\""]);
EXPECT_TRUE([formDataString containsString:@"baz"]);
EXPECT_TRUE([formDataString containsString:@"WebKitFormBoundary"]);
} else if ([task.request.URL.absoluteString isEqualToString:@"xhrpost://example/blob"]) {
static bool reached;
EXPECT_FALSE(reached);
reached = true;
// FIXME: XHR posting of Blobs is currently unsupported
// https://bugs.webkit.org/show_bug.cgi?id=197237
FAIL();
} else {
// We only expect one of the 5 URLs up above.
FAIL();
}
auto response = adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:@"text/html" expectedContentLength:0 textEncodingName:nil]);
[task didReceiveResponse:response.get()];
[task didFinish];
if (++seenTasks == 5)
done = true;
}];
[webView loadHTMLString:[NSString stringWithUTF8String:xhrPostDocument] baseURL:[NSURL URLWithString:@"xhrpost://example/xhrtest"]];
TestWebKitAPI::Util::run(&done);
}
TEST(URLSchemeHandler, Threads)
{
static bool done;
static NeverDestroyed<RetainPtr<id<WKURLSchemeTask>>> theTask;
static RefPtr<Thread> theThread;
@autoreleasepool {
auto handler = adoptNS([[TestURLSchemeHandler alloc] init]);
auto configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
[configuration setURLSchemeHandler:handler.get() forURLScheme:@"threads"];
auto webView = adoptNS([[TestWKWebView alloc] initWithFrame:CGRectMake(0, 0, 800, 600) configuration:configuration.get()]);
[handler setStartURLSchemeTaskHandler:^(WKWebView *, id<WKURLSchemeTask> task) {
theTask.get() = retainPtr(task);
theThread = Thread::create("A", [task] {
auto response = adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:@"text/html" expectedContentLength:0 textEncodingName:nil]);
[task didReceiveResponse:response.get()];
[task didFinish];
done = true;
});
}];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"threads://main.html"]]];
TestWebKitAPI::Util::run(&done);
handler = nil;
configuration = nil;
webView = nil;
theThread = nullptr;
}
Thread::create("B", [] {
theTask.get() = nil;
})->waitForCompletion();
}
TEST(URLSchemeHandler, CORS)
{
auto handler = adoptNS([[TestURLSchemeHandler alloc] init]);
auto configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
[configuration setURLSchemeHandler:handler.get() forURLScheme:@"cors"];
auto webView = adoptNS([[TestWKWebView alloc] initWithFrame:CGRectMake(0, 0, 800, 600) configuration:configuration.get()]);
__block bool done = false;
__block bool includeCORSHeaderFieldInResponse = false;
__block bool corssuccess = false;
__block bool corsfailure = false;
[handler setStartURLSchemeTaskHandler:^(WKWebView *, id<WKURLSchemeTask> task) {
if ([task.request.URL.path isEqualToString:@"/main.html"]) {
NSData *data = [@"<script>fetch('cors://host2/corsresource').then(function(){fetch('/corssuccess')}).catch(function(){fetch('/corsfailure')})</script>" dataUsingEncoding:NSUTF8StringEncoding];
[task didReceiveResponse:adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:@"text/html" expectedContentLength:data.length textEncodingName:nil]).get()];
[task didReceiveData:data];
[task didFinish];
} else if ([task.request.URL.path isEqualToString:@"/corsresource"]) {
if (includeCORSHeaderFieldInResponse) {
[task didReceiveResponse:adoptNS([[NSHTTPURLResponse alloc] initWithURL:task.request.URL statusCode:200 HTTPVersion:nil headerFields:@{
@"Access-Control-Allow-Origin": @"*",
@"Content-Length": @"2",
@"Content-Type":@"text/html"
}]).get()];
} else
[task didReceiveResponse:adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:@"text/html" expectedContentLength:0 textEncodingName:nil]).get()];
[task didReceiveData:[@"HI" dataUsingEncoding:NSUTF8StringEncoding]];
[task didFinish];
} else if ([task.request.URL.path isEqualToString:@"/corssuccess"]) {
corssuccess = true;
done = true;
} else if ([task.request.URL.path isEqualToString:@"/corsfailure"]) {
corsfailure = true;
done = true;
}
}];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"cors://host1/main.html"]]];
TestWebKitAPI::Util::run(&done);
EXPECT_TRUE(corsfailure);
EXPECT_FALSE(corssuccess);
corsfailure = false;
corssuccess = false;
done = false;
includeCORSHeaderFieldInResponse = true;
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"cors://host1/main.html"]]];
TestWebKitAPI::Util::run(&done);
EXPECT_TRUE(corssuccess);
EXPECT_FALSE(corsfailure);
}
TEST(URLSchemeHandler, DisableCORS)
{
TestWebKitAPI::HTTPServer server({
{ "/subresource"_s, { {{ "Content-Type"_s, "application/json"_s }, { "headerName"_s, "headerValue"_s }}, "{\"testKey\":\"testValue\"}"_s } }
});
bool corssuccess = false;
bool corsfailure = false;
bool done = false;
auto handler = adoptNS([[TestURLSchemeHandler alloc] init]);
auto configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
[configuration setURLSchemeHandler:handler.get() forURLScheme:@"cors"];
NSString *testJS = [NSString stringWithFormat:
@"fetch('http://127.0.0.1:%d/subresource').then(async (r) => {"
"if (r.headers.get('headerName') != 'headerValue')"
"return fetch('/corsfailure');"
"const object = await r.json();"
"if (object.testKey != 'testValue')"
"return fetch('/corsfailure');"
"fetch('/corssuccess');"
"}).catch(function(){fetch('/corsfailure')})"
, server.port()];
[handler setStartURLSchemeTaskHandler:[&](WKWebView *, id<WKURLSchemeTask> task) {
if ([task.request.URL.path isEqualToString:@"/main.html"]) {
NSData *data = [[NSString stringWithFormat:@"<script>%@</script>", testJS] dataUsingEncoding:NSUTF8StringEncoding];
[task didReceiveResponse:adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:@"text/html" expectedContentLength:data.length textEncodingName:nil]).get()];
[task didReceiveData:data];
[task didFinish];
} else if ([task.request.URL.path isEqualToString:@"/corssuccess"]) {
corssuccess = true;
done = true;
} else if ([task.request.URL.path isEqualToString:@"/corsfailure"]) {
corsfailure = true;
done = true;
} else
ASSERT_NOT_REACHED();
}];
{
auto webView = adoptNS([[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 800, 600) configuration:configuration.get()]);
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"cors://host1/main.html"]]];
TestWebKitAPI::Util::run(&done);
}
EXPECT_FALSE(corssuccess);
EXPECT_TRUE(corsfailure);
corssuccess = false;
corsfailure = false;
done = false;
configuration.get()._corsDisablingPatterns = @[@"*://*/*"];
auto webView = adoptNS([[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 800, 600) configuration:configuration.get()]);
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"cors://host1/main.html"]]];
TestWebKitAPI::Util::run(&done);
EXPECT_TRUE(corssuccess);
EXPECT_FALSE(corsfailure);
corssuccess = false;
corsfailure = false;
done = false;
}
TEST(URLSchemeHandler, DisableCORSCredentials)
{
TestWebKitAPI::HTTPServer server({
{ "/subresource"_s, { {{ "Access-Control-Allow-Origin"_s, "*"_s }}, "subresourcecontent"_s } }
});
bool corssuccess = false;
bool corsfailure = false;
bool done = false;
auto handler = adoptNS([[TestURLSchemeHandler alloc] init]);
auto configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
[configuration setURLSchemeHandler:handler.get() forURLScheme:@"cors"];
[handler setStartURLSchemeTaskHandler:[&](WKWebView *, id<WKURLSchemeTask> task) {
if ([task.request.URL.path isEqualToString:@"/main.html"]) {
NSData *data = [[NSString stringWithFormat:@"<script>fetch('http://127.0.0.1:%d/subresource', {credentials:'include'}).then(function(){fetch('/corssuccess')}).catch(function(){fetch('/corsfailure')})</script>", server.port()] dataUsingEncoding:NSUTF8StringEncoding];
[task didReceiveResponse:adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:@"text/html" expectedContentLength:data.length textEncodingName:nil]).get()];
[task didReceiveData:data];
[task didFinish];
} else if ([task.request.URL.path isEqualToString:@"/corssuccess"]) {
corssuccess = true;
done = true;
} else if ([task.request.URL.path isEqualToString:@"/corsfailure"]) {
corsfailure = true;
done = true;
} else
ASSERT_NOT_REACHED();
}];
{
auto webView = adoptNS([[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 800, 600) configuration:configuration.get()]);
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"cors://host1/main.html"]]];
TestWebKitAPI::Util::run(&done);
}
EXPECT_FALSE(corssuccess);
EXPECT_TRUE(corsfailure);
corssuccess = false;
corsfailure = false;
done = false;
configuration.get()._crossOriginAccessControlCheckEnabled = NO;
{
auto webView = adoptNS([[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 800, 600) configuration:configuration.get()]);
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"cors://host1/main.html"]]];
TestWebKitAPI::Util::run(&done);
}
EXPECT_TRUE(corssuccess);
EXPECT_FALSE(corsfailure);
}
TEST(URLSchemeHandler, DisableCORSScript)
{
TestWebKitAPI::HTTPServer server({
{ "/"_s, { "fetch('loadSuccess')"_s } }
});
bool loadSuccess = false;
bool loadFail = false;
bool done = false;
auto handler = adoptNS([TestURLSchemeHandler new]);
auto configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
[configuration setURLSchemeHandler:handler.get() forURLScheme:@"cors"];
[handler setStartURLSchemeTaskHandler:[&](WKWebView *, id<WKURLSchemeTask> task) {
if ([task.request.URL.path isEqualToString:@"/main.html"]) {
NSData *data = [[NSString stringWithFormat:@"<script type='text/javascript' crossorigin='anonymous' onerror='fetch(\"loadFail\")' src='http://127.0.0.1:%d/'></script>", server.port()] dataUsingEncoding:NSUTF8StringEncoding];
[task didReceiveResponse:adoptNS([[NSURLResponse alloc] initWithURL:task.request.URL MIMEType:@"text/html" expectedContentLength:data.length textEncodingName:nil]).get()];
[task didReceiveData:data];
[task didFinish];
} else if ([task.request.URL.path isEqualToString:@"/loadSuccess"]) {
loadSuccess = true;
done = true;
} else if ([task.request.URL.path isEqualToString:@"/loadFail"]) {
loadFail = true;
done = true;
} else
ASSERT_NOT_REACHED();
}];
{
auto webView = adoptNS([[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 800, 600) configuration:configuration.get()]);
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"cors://host1/main.html"]]];
TestWebKitAPI::Util::run(&done);
}
EXPECT_FALSE(loadSuccess);
EXPECT_TRUE(loadFail);
loadSuccess = false;