-
Notifications
You must be signed in to change notification settings - Fork 37.7k
/
ResourceHttpRequestHandlerTests.java
787 lines (654 loc) · 35.2 KB
/
ResourceHttpRequestHandlerTests.java
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
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.accept.ContentNegotiationManagerFactoryBean;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.testfixture.servlet.MockHttpServletRequest;
import org.springframework.web.testfixture.servlet.MockHttpServletResponse;
import org.springframework.web.testfixture.servlet.MockServletContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Unit tests for {@link ResourceHttpRequestHandler}.
*
* @author Keith Donald
* @author Jeremy Grelle
* @author Rossen Stoyanchev
* @author Brian Clozel
*/
@ExtendWith(GzipSupport.class)
public class ResourceHttpRequestHandlerTests {
private ResourceHttpRequestHandler handler;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@BeforeEach
public void setup() throws Exception {
List<Resource> paths = new ArrayList<>(2);
paths.add(new ClassPathResource("test/", getClass()));
paths.add(new ClassPathResource("testalternatepath/", getClass()));
paths.add(new ClassPathResource("META-INF/resources/webjars/"));
TestServletContext servletContext = new TestServletContext();
this.handler = new ResourceHttpRequestHandler();
this.handler.setLocations(paths);
this.handler.setCacheSeconds(3600);
this.handler.setServletContext(servletContext);
this.handler.afterPropertiesSet();
this.request = new MockHttpServletRequest(servletContext, "GET", "");
this.response = new MockHttpServletResponse();
}
@Test
public void getResource() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getContentType()).isEqualTo("text/css");
assertThat(this.response.getContentLength()).isEqualTo(17);
assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600");
assertThat(this.response.containsHeader("Last-Modified")).isTrue();
assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("test/foo.css") / 1000);
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }");
}
@Test
public void getResourceHttpHeader() throws Exception {
this.request.setMethod("HEAD");
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(200);
assertThat(this.response.getContentType()).isEqualTo("text/css");
assertThat(this.response.getContentLength()).isEqualTo(17);
assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600");
assertThat(this.response.containsHeader("Last-Modified")).isTrue();
assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("test/foo.css") / 1000);
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
}
@Test
public void getResourceHttpOptions() throws Exception {
this.request.setMethod("OPTIONS");
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(200);
assertThat(this.response.getHeader("Allow")).isEqualTo("GET,HEAD,OPTIONS");
}
@Test
public void getResourceNoCache() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
this.handler.setCacheSeconds(0);
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getHeader("Cache-Control")).isEqualTo("no-store");
assertThat(this.response.containsHeader("Last-Modified")).isTrue();
assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("test/foo.css") / 1000);
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
}
@Test
public void getVersionedResource() throws Exception {
VersionResourceResolver versionResolver = new VersionResourceResolver()
.addFixedVersionStrategy("versionString", "/**");
this.handler.setResourceResolvers(Arrays.asList(versionResolver, new PathResourceResolver()));
this.handler.afterPropertiesSet();
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "versionString/foo.css");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getHeader("ETag")).isEqualTo("W/\"versionString\"");
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
}
@Test
@SuppressWarnings("deprecation")
public void getResourceHttp10BehaviorCache() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
this.handler.setCacheSeconds(3600);
this.handler.setUseExpiresHeader(true);
this.handler.setUseCacheControlHeader(true);
this.handler.setAlwaysMustRevalidate(true);
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600, must-revalidate");
assertThat(this.response.getDateHeader("Expires") >= System.currentTimeMillis() - 1000 + (3600 * 1000)).isTrue();
assertThat(this.response.containsHeader("Last-Modified")).isTrue();
assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("test/foo.css") / 1000);
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
}
@Test
@SuppressWarnings("deprecation")
public void getResourceHttp10BehaviorNoCache() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
this.handler.setCacheSeconds(0);
this.handler.setUseExpiresHeader(true);
this.handler.setUseCacheControlNoStore(false);
this.handler.setUseCacheControlHeader(true);
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getHeader("Pragma")).isEqualTo("no-cache");
assertThat(this.response.getHeaderValues("Cache-Control")).hasSize(1);
assertThat(this.response.getHeader("Cache-Control")).isEqualTo("no-cache");
assertThat(this.response.getDateHeader("Expires") <= System.currentTimeMillis()).isTrue();
assertThat(this.response.containsHeader("Last-Modified")).isTrue();
assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("test/foo.css") / 1000);
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
}
@Test
public void getResourceWithHtmlMediaType() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.html");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getContentType()).isEqualTo("text/html");
assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600");
assertThat(this.response.containsHeader("Last-Modified")).isTrue();
assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("test/foo.html") / 1000);
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
}
@Test
public void getResourceFromAlternatePath() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "baz.css");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getContentType()).isEqualTo("text/css");
assertThat(this.response.getContentLength()).isEqualTo(17);
assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600");
assertThat(this.response.containsHeader("Last-Modified")).isTrue();
assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("testalternatepath/baz.css") / 1000);
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }");
}
@Test
public void getResourceFromSubDirectory() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "js/foo.js");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getContentType()).isEqualTo("text/javascript");
assertThat(this.response.getContentAsString()).isEqualTo("function foo() { console.log(\"hello world\"); }");
}
@Test
public void getResourceFromSubDirectoryOfAlternatePath() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "js/baz.js");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getContentType()).isEqualTo("text/javascript");
assertThat(this.response.getContentAsString()).isEqualTo("function foo() { console.log(\"hello world\"); }");
}
@Test // SPR-13658
@SuppressWarnings("deprecation")
public void getResourceWithRegisteredMediaType() throws Exception {
ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean();
factory.addMediaType("bar", new MediaType("foo", "bar"));
factory.afterPropertiesSet();
ContentNegotiationManager manager = factory.getObject();
List<Resource> paths = Collections.singletonList(new ClassPathResource("test/", getClass()));
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
handler.setServletContext(new MockServletContext());
handler.setLocations(paths);
handler.setContentNegotiationManager(manager);
handler.afterPropertiesSet();
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.bar");
handler.handleRequest(this.request, this.response);
assertThat(this.response.getContentType()).isEqualTo("foo/bar");
assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }");
}
@Test // SPR-14577
@SuppressWarnings("deprecation")
public void getMediaTypeWithFavorPathExtensionOff() throws Exception {
ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean();
factory.setFavorPathExtension(false);
factory.afterPropertiesSet();
ContentNegotiationManager manager = factory.getObject();
List<Resource> paths = Collections.singletonList(new ClassPathResource("test/", getClass()));
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
handler.setServletContext(new MockServletContext());
handler.setLocations(paths);
handler.setContentNegotiationManager(manager);
handler.afterPropertiesSet();
this.request.addHeader("Accept", "application/json,text/plain,*/*");
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.html");
handler.handleRequest(this.request, this.response);
assertThat(this.response.getContentType()).isEqualTo("text/html");
}
@Test // SPR-14368
public void getResourceWithMediaTypeResolvedThroughServletContext() throws Exception {
MockServletContext servletContext = new MockServletContext() {
@Override
public String getMimeType(String filePath) {
return "foo/bar";
}
};
List<Resource> paths = Collections.singletonList(new ClassPathResource("test/", getClass()));
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
handler.setServletContext(servletContext);
handler.setLocations(paths);
handler.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "");
request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
handler.handleRequest(request, this.response);
assertThat(this.response.getContentType()).isEqualTo("foo/bar");
assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }");
}
@Test // gh-27538
public void filterNonExistingLocations() throws Exception {
List<Resource> inputLocations = Arrays.asList(
new ClassPathResource("test/", getClass()),
new ClassPathResource("testalternatepath/", getClass()),
new ClassPathResource("nosuchpath/", getClass()));
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
handler.setServletContext(new MockServletContext());
handler.setLocations(inputLocations);
handler.afterPropertiesSet();
List<Resource> actual = handler.getLocations();
assertThat(actual).hasSize(2);
assertThat(actual.get(0).getURL().toString()).endsWith("test/");
assertThat(actual.get(1).getURL().toString()).endsWith("testalternatepath/");
}
@Test
public void testInvalidPath() throws Exception {
// Use mock ResourceResolver: i.e. we're only testing upfront validations...
Resource resource = mock(Resource.class);
given(resource.getFilename()).willThrow(new AssertionError("Resource should not be resolved"));
given(resource.getInputStream()).willThrow(new AssertionError("Resource should not be resolved"));
ResourceResolver resolver = mock(ResourceResolver.class);
given(resolver.resolveResource(any(), any(), any(), any())).willReturn(resource);
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
handler.setLocations(Collections.singletonList(new ClassPathResource("test/", getClass())));
handler.setResourceResolvers(Collections.singletonList(resolver));
handler.setServletContext(new TestServletContext());
handler.afterPropertiesSet();
testInvalidPath("../testsecret/secret.txt", handler);
testInvalidPath("test/../../testsecret/secret.txt", handler);
testInvalidPath(":/../../testsecret/secret.txt", handler);
Resource location = new UrlResource(getClass().getResource("./test/"));
this.handler.setLocations(Collections.singletonList(location));
Resource secretResource = new UrlResource(getClass().getResource("testsecret/secret.txt"));
String secretPath = secretResource.getURL().getPath();
testInvalidPath("file:" + secretPath, handler);
testInvalidPath("/file:" + secretPath, handler);
testInvalidPath("url:" + secretPath, handler);
testInvalidPath("/url:" + secretPath, handler);
testInvalidPath("/../.." + secretPath, handler);
testInvalidPath("/%2E%2E/testsecret/secret.txt", handler);
testInvalidPath("/%2E%2E/testsecret/secret.txt", handler);
testInvalidPath("%2F%2F%2E%2E%2F%2F%2E%2E" + secretPath, handler);
}
private void testInvalidPath(String requestPath, ResourceHttpRequestHandler handler) throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, requestPath);
this.response = new MockHttpServletResponse();
handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
}
@Test
public void resolvePathWithTraversal() throws Exception {
for (HttpMethod method : HttpMethod.values()) {
this.request = new MockHttpServletRequest("GET", "");
this.response = new MockHttpServletResponse();
testResolvePathWithTraversal(method);
}
}
private void testResolvePathWithTraversal(HttpMethod httpMethod) throws Exception {
this.request.setMethod(httpMethod.name());
Resource location = new ClassPathResource("test/", getClass());
this.handler.setLocations(Collections.singletonList(location));
testResolvePathWithTraversal(location, "../testsecret/secret.txt");
testResolvePathWithTraversal(location, "test/../../testsecret/secret.txt");
testResolvePathWithTraversal(location, ":/../../testsecret/secret.txt");
location = new UrlResource(getClass().getResource("./test/"));
this.handler.setLocations(Collections.singletonList(location));
Resource secretResource = new UrlResource(getClass().getResource("testsecret/secret.txt"));
String secretPath = secretResource.getURL().getPath();
testResolvePathWithTraversal(location, "file:" + secretPath);
testResolvePathWithTraversal(location, "/file:" + secretPath);
testResolvePathWithTraversal(location, "url:" + secretPath);
testResolvePathWithTraversal(location, "/url:" + secretPath);
testResolvePathWithTraversal(location, "/" + secretPath);
testResolvePathWithTraversal(location, "////../.." + secretPath);
testResolvePathWithTraversal(location, "/%2E%2E/testsecret/secret.txt");
testResolvePathWithTraversal(location, "%2F%2F%2E%2E%2F%2Ftestsecret/secret.txt");
testResolvePathWithTraversal(location, "/ " + secretPath);
}
private void testResolvePathWithTraversal(Resource location, String requestPath) throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, requestPath);
this.response = new MockHttpServletResponse();
this.handler.handleRequest(this.request, this.response);
if (!location.createRelative(requestPath).exists() && !requestPath.contains(":")) {
fail(requestPath + " doesn't actually exist as a relative path");
}
assertThat(this.response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
}
@Test
public void ignoreInvalidEscapeSequence() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/%foo%/bar.txt");
this.response = new MockHttpServletResponse();
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(404);
}
@Test
public void processPath() {
// Unchanged
assertThat(this.handler.processPath("/foo/bar")).isSameAs("/foo/bar");
assertThat(this.handler.processPath("foo/bar")).isSameAs("foo/bar");
// leading whitespace control characters (00-1F)
assertThat(this.handler.processPath(" /foo/bar")).isEqualTo("/foo/bar");
assertThat(this.handler.processPath((char) 1 + "/foo/bar")).isEqualTo("/foo/bar");
assertThat(this.handler.processPath((char) 31 + "/foo/bar")).isEqualTo("/foo/bar");
assertThat(this.handler.processPath(" foo/bar")).isEqualTo("foo/bar");
assertThat(this.handler.processPath((char) 31 + "foo/bar")).isEqualTo("foo/bar");
// leading control character 0x7F (DEL)
assertThat(this.handler.processPath((char) 127 + "/foo/bar")).isEqualTo("/foo/bar");
assertThat(this.handler.processPath((char) 127 + "/foo/bar")).isEqualTo("/foo/bar");
// leading control and '/' characters
assertThat(this.handler.processPath(" / foo/bar")).isEqualTo("/foo/bar");
assertThat(this.handler.processPath(" / / foo/bar")).isEqualTo("/foo/bar");
assertThat(this.handler.processPath(" // /// //// foo/bar")).isEqualTo("/foo/bar");
assertThat(this.handler.processPath((char) 1 + " / " + (char) 127 + " // foo/bar")).isEqualTo("/foo/bar");
// root or empty path
assertThat(this.handler.processPath(" ")).isEqualTo("");
assertThat(this.handler.processPath("/")).isEqualTo("/");
assertThat(this.handler.processPath("///")).isEqualTo("/");
assertThat(this.handler.processPath("/ / / ")).isEqualTo("/");
assertThat(this.handler.processPath("\\/ \\/ \\/ ")).isEqualTo("/");
// duplicate slash or backslash
assertThat(this.handler.processPath("//foo/ /bar//baz//")).isEqualTo("/foo/ /bar/baz/");
assertThat(this.handler.processPath("\\\\foo\\ \\bar\\\\baz\\\\")).isEqualTo("/foo/ /bar/baz/");
assertThat(this.handler.processPath("foo\\\\/\\////bar")).isEqualTo("foo/bar");
}
@Test
public void initAllowedLocations() {
PathResourceResolver resolver = (PathResourceResolver) this.handler.getResourceResolvers().get(0);
Resource[] locations = resolver.getAllowedLocations();
assertThat(locations.length).isEqualTo(3);
assertThat(((ClassPathResource) locations[0]).getPath()).isEqualTo("test/");
assertThat(((ClassPathResource) locations[1]).getPath()).isEqualTo("testalternatepath/");
assertThat(((ClassPathResource) locations[2]).getPath()).isEqualTo("META-INF/resources/webjars/");
}
@Test
public void initAllowedLocationsWithExplicitConfiguration() throws Exception {
ClassPathResource location1 = new ClassPathResource("test/", getClass());
ClassPathResource location2 = new ClassPathResource("testalternatepath/", getClass());
PathResourceResolver pathResolver = new PathResourceResolver();
pathResolver.setAllowedLocations(location1);
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
handler.setResourceResolvers(Collections.singletonList(pathResolver));
handler.setServletContext(new MockServletContext());
handler.setLocations(Arrays.asList(location1, location2));
handler.afterPropertiesSet();
Resource[] locations = pathResolver.getAllowedLocations();
assertThat(locations.length).isEqualTo(1);
assertThat(((ClassPathResource) locations[0]).getPath()).isEqualTo("test/");
}
@Test
public void notModified() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
this.request.addHeader("If-Modified-Since", resourceLastModified("test/foo.css"));
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_NOT_MODIFIED);
}
@Test
public void modified() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
this.request.addHeader("If-Modified-Since", resourceLastModified("test/foo.css") / 1000 * 1000 - 1);
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }");
}
@Test
public void directory() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "js/");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(404);
}
@Test
public void directoryInJarFile() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "underscorejs/");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(404);
}
@Test
public void missingResourcePath() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(404);
}
@Test
public void noPathWithinHandlerMappingAttribute() throws Exception {
assertThatIllegalStateException().isThrownBy(() ->
this.handler.handleRequest(this.request, this.response));
}
@Test
public void unsupportedHttpMethod() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
this.request.setMethod("POST");
assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class).isThrownBy(() ->
this.handler.handleRequest(this.request, this.response));
}
@Test
public void resourceNotFound() throws Exception {
for (HttpMethod method : HttpMethod.values()) {
this.request = new MockHttpServletRequest("GET", "");
this.response = new MockHttpServletResponse();
resourceNotFound(method);
}
}
private void resourceNotFound(HttpMethod httpMethod) throws Exception {
this.request.setMethod(httpMethod.name());
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "not-there.css");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
}
@Test
public void partialContentByteRange() throws Exception {
this.request.addHeader("Range", "bytes=0-1");
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(206);
assertThat(this.response.getContentType()).isEqualTo("text/plain");
assertThat(this.response.getContentLength()).isEqualTo(2);
assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 0-1/10");
assertThat(this.response.getContentAsString()).isEqualTo("So");
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
}
@Test
public void partialContentByteRangeNoEnd() throws Exception {
this.request.addHeader("Range", "bytes=9-");
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(206);
assertThat(this.response.getContentType()).isEqualTo("text/plain");
assertThat(this.response.getContentLength()).isEqualTo(1);
assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 9-9/10");
assertThat(this.response.getContentAsString()).isEqualTo(".");
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
}
@Test
public void partialContentByteRangeLargeEnd() throws Exception {
this.request.addHeader("Range", "bytes=9-10000");
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(206);
assertThat(this.response.getContentType()).isEqualTo("text/plain");
assertThat(this.response.getContentLength()).isEqualTo(1);
assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 9-9/10");
assertThat(this.response.getContentAsString()).isEqualTo(".");
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
}
@Test
public void partialContentSuffixRange() throws Exception {
this.request.addHeader("Range", "bytes=-1");
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(206);
assertThat(this.response.getContentType()).isEqualTo("text/plain");
assertThat(this.response.getContentLength()).isEqualTo(1);
assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 9-9/10");
assertThat(this.response.getContentAsString()).isEqualTo(".");
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
}
@Test
public void partialContentSuffixRangeLargeSuffix() throws Exception {
this.request.addHeader("Range", "bytes=-11");
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(206);
assertThat(this.response.getContentType()).isEqualTo("text/plain");
assertThat(this.response.getContentLength()).isEqualTo(10);
assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 0-9/10");
assertThat(this.response.getContentAsString()).isEqualTo("Some text.");
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
}
@Test
public void partialContentInvalidRangeHeader() throws Exception {
this.request.addHeader("Range", "bytes= foo bar");
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(416);
assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes */10");
assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
}
@Test
public void partialContentMultipleByteRanges() throws Exception {
this.request.addHeader("Range", "bytes=0-1, 4-5, 8-9");
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(206);
assertThat(this.response.getContentType().startsWith("multipart/byteranges; boundary=")).isTrue();
String boundary = "--" + this.response.getContentType().substring(31);
String content = this.response.getContentAsString();
String[] ranges = StringUtils.tokenizeToStringArray(content, "\r\n", false, true);
assertThat(ranges[0]).isEqualTo(boundary);
assertThat(ranges[1]).isEqualTo("Content-Type: text/plain");
assertThat(ranges[2]).isEqualTo("Content-Range: bytes 0-1/10");
assertThat(ranges[3]).isEqualTo("So");
assertThat(ranges[4]).isEqualTo(boundary);
assertThat(ranges[5]).isEqualTo("Content-Type: text/plain");
assertThat(ranges[6]).isEqualTo("Content-Range: bytes 4-5/10");
assertThat(ranges[7]).isEqualTo(" t");
assertThat(ranges[8]).isEqualTo(boundary);
assertThat(ranges[9]).isEqualTo("Content-Type: text/plain");
assertThat(ranges[10]).isEqualTo("Content-Range: bytes 8-9/10");
assertThat(ranges[11]).isEqualTo("t.");
}
@Test // gh-25976
public void partialContentByteRangeWithEncodedResource(GzipSupport.GzippedFiles gzippedFiles) throws Exception {
String path = "js/foo.js";
gzippedFiles.create(path);
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
handler.setResourceResolvers(Arrays.asList(new EncodedResourceResolver(), new PathResourceResolver()));
handler.setLocations(Collections.singletonList(new ClassPathResource("test/", getClass())));
handler.setServletContext(new MockServletContext());
handler.afterPropertiesSet();
this.request.addHeader("Accept-Encoding", "gzip");
this.request.addHeader("Range", "bytes=0-1");
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, path);
handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(206);
assertThat(this.response.getHeaderNames()).containsExactlyInAnyOrder(
"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges",
"Last-Modified", "Content-Encoding", "Vary");
assertThat(this.response.getContentType()).isEqualTo("text/javascript");
assertThat(this.response.getContentLength()).isEqualTo(2);
assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 0-1/66");
assertThat(this.response.getHeaderValues("Accept-Ranges")).containsExactly("bytes");
assertThat(this.response.getHeaderValues("Content-Encoding")).containsExactly("gzip");
assertThat(this.response.getHeaderValues("Vary")).containsExactly("Accept-Encoding");
}
@Test // gh-25976
public void partialContentWithHttpHead() throws Exception {
this.request.setMethod("HEAD");
this.request.addHeader("Range", "bytes=0-1");
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getStatus()).isEqualTo(206);
assertThat(this.response.getContentType()).isEqualTo("text/plain");
assertThat(this.response.getContentLength()).isEqualTo(2);
assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 0-1/10");
assertThat(this.response.getHeaderValues("Accept-Ranges")).containsExactly("bytes");
}
@Test // SPR-14005
public void doOverwriteExistingCacheControlHeaders() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
this.response.setHeader("Cache-Control", "no-store");
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600");
}
@Test
public void ignoreLastModified() throws Exception {
this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
this.handler.setUseLastModified(false);
this.handler.handleRequest(this.request, this.response);
assertThat(this.response.getContentType()).isEqualTo("text/css");
assertThat(this.response.getContentLength()).isEqualTo(17);
assertThat(this.response.containsHeader("Last-Modified")).isFalse();
assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }");
}
@Test
public void servletContextRootValidation() {
StaticWebApplicationContext context = new StaticWebApplicationContext() {
@Override
public Resource getResource(String location) {
return new FileSystemResource("/");
}
};
ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
handler.setLocationValues(Collections.singletonList("/"));
handler.setApplicationContext(context);
assertThatIllegalStateException().isThrownBy(handler::afterPropertiesSet)
.withMessage("The String-based location \"/\" should be relative to the web application root but " +
"resolved to a Resource of type: class org.springframework.core.io.FileSystemResource. " +
"If this is intentional, please pass it as a pre-configured Resource via setLocations.");
}
private long resourceLastModified(String resourceName) throws IOException {
return new ClassPathResource(resourceName, getClass()).getFile().lastModified();
}
private static class TestServletContext extends MockServletContext {
@Override
public String getMimeType(String filePath) {
if (filePath.endsWith(".css")) {
return "text/css";
}
else if (filePath.endsWith(".js")) {
return "text/javascript";
}
else {
return super.getMimeType(filePath);
}
}
}
}