/
HandlerHelper.java
515 lines (462 loc) · 18.1 KB
/
HandlerHelper.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
/*
* Copyright 2000-2024 Vaadin Ltd.
*
* 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
*
* http://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 com.vaadin.flow.server;
import jakarta.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.server.communication.PwaHandler;
import com.vaadin.flow.server.communication.StreamRequestHandler;
import com.vaadin.flow.server.frontend.FrontendUtils;
import com.vaadin.flow.shared.ApplicationConstants;
/**
* Contains helper methods for {@link VaadinServlet} and generally for handling
* {@link VaadinRequest VaadinRequests}.
*
* @since 1.0
*/
public class HandlerHelper implements Serializable {
/**
* The default SystemMessages (read-only).
*/
static final SystemMessages DEFAULT_SYSTEM_MESSAGES = new SystemMessages();
/**
* The pattern of error message shown when the URL path contains unsafe
* double encoding.
*/
static final String UNSAFE_PATH_ERROR_MESSAGE_PATTERN = "Blocked attempt to access file: {}";
private static final Pattern PARENT_DIRECTORY_REGEX = Pattern
.compile("(/|\\\\)\\.\\.(/|\\\\)?", Pattern.CASE_INSENSITIVE);
/**
* Framework internal enum for tracking the type of a request.
*/
public enum RequestType {
/**
* INIT requests.
*/
INIT(ApplicationConstants.REQUEST_TYPE_INIT),
/**
* UIDL requests.
*/
UIDL(ApplicationConstants.REQUEST_TYPE_UIDL),
/**
* WebComponent resynchronization requests.
*/
WEBCOMPONENT_RESYNC(
ApplicationConstants.REQUEST_TYPE_WEBCOMPONENT_RESYNC),
/**
* Heartbeat requests.
*/
HEARTBEAT(ApplicationConstants.REQUEST_TYPE_HEARTBEAT),
/**
* Push requests (any transport).
*/
PUSH(ApplicationConstants.REQUEST_TYPE_PUSH),
/**
* Page showing that the browser is unsupported.
*/
BROWSER_TOO_OLD("oldbrowser"),
/**
* Translation properties file requests.
*/
TRANSLATION_FILE(ApplicationConstants.REQUEST_TYPE_TRANSLATION_FILE);
private final String identifier;
private RequestType(String identifier) {
this.identifier = identifier;
}
/**
* Returns the identifier for the request type.
*
* @return the identifier
*/
public String getIdentifier() {
return identifier;
}
}
private static final String[] publicResourcesRoot;
private static final String[] publicResources;
static {
List<String> resources = new ArrayList<>();
resources.add("/" + PwaConfiguration.DEFAULT_PATH);
resources.add("/" + FrontendUtils.SERVICE_WORKER_SRC_JS);
resources.add(PwaHandler.SW_RUNTIME_PRECACHE_PATH);
resources.add("/" + PwaConfiguration.DEFAULT_OFFLINE_PATH);
resources.add("/" + PwaHandler.DEFAULT_OFFLINE_STUB_PATH);
resources.add("/" + PwaConfiguration.DEFAULT_ICON);
resources.add("/themes/**");
resources.addAll(getIconVariants(PwaConfiguration.DEFAULT_ICON));
publicResources = resources.toArray(new String[resources.size()]);
// These are always in the root of the app, not inside any url mapping
List<String> rootResources = new ArrayList<>();
rootResources.add("/favicon.ico");
publicResourcesRoot = rootResources
.toArray(new String[rootResources.size()]);
}
private HandlerHelper() {
// Only utility methods
}
/**
* Returns whether the given request is of the given type.
*
* @param request
* the request to check
* @param requestType
* the type to check for
* @return <code>true</code> if the request is of the given type,
* <code>false</code> otherwise
*/
public static boolean isRequestType(VaadinRequest request,
RequestType requestType) {
return requestType.getIdentifier().equals(request
.getParameter(ApplicationConstants.REQUEST_TYPE_PARAMETER));
}
/**
* Checks whether the request is an internal request.
*
* The requests listed in {@link RequestType} are considered internal as
* they are needed for applications to work.
* <p>
* Requests for routes, static resources requests and similar are not
* considered internal requests.
*
* @param servletMappingPath
* the path the Vaadin servlet is mapped to, with or without and
* ending "/*"
* @param request
* the servlet request
* @return {@code true} if the request is Vaadin internal, {@code false}
* otherwise
*/
public static boolean isFrameworkInternalRequest(String servletMappingPath,
HttpServletRequest request) {
return isFrameworkInternalRequest(servletMappingPath,
getRequestPathInsideContext(request), request.getParameter(
ApplicationConstants.REQUEST_TYPE_PARAMETER));
}
private static boolean isFrameworkInternalRequest(String servletMappingPath,
String requestedPath, String requestTypeParameter) {
/*
* According to the spec, pathInfo should be null but not all servers
* implement it like that...
*
* Additionally the spring servlet is mapped as /vaadinServlet right now
* it seems but requests are sent to /vaadinServlet/, causing a "/" path
* info
*/
// This is only an internal request if it is for the Vaadin servlet
Optional<String> requestedPathWithoutServletMapping = getPathIfInsideServlet(
servletMappingPath, requestedPath);
if (!requestedPathWithoutServletMapping.isPresent()) {
return false;
} else if (isInternalRequestInsideServlet(
requestedPathWithoutServletMapping.get(),
requestTypeParameter)) {
return true;
} else if (RequestType.PUSH.getIdentifier().equals(requestTypeParameter)
&& "VAADIN/push"
.equals(requestedPathWithoutServletMapping.get())) {
return true;
} else if (isUploadRequest(requestedPathWithoutServletMapping.get())) {
return true;
} else if (isHillaPush(requestedPathWithoutServletMapping.get())) {
return true;
}
return false;
}
private static boolean isUploadRequest(
String requestedPathWithoutServletMapping) {
// First key is uiId
// Second key is security key
return requestedPathWithoutServletMapping
.matches(StreamRequestHandler.DYN_RES_PREFIX
+ "(\\d+)/([0-9a-z-]*)/upload");
}
private static boolean isHillaPush(
String requestedPathWithoutServletMapping) {
return "HILLA/push".equals(requestedPathWithoutServletMapping);
}
static boolean isInternalRequestInsideServlet(
String requestedPathWithoutServletMapping,
String requestTypeParameter) {
if (requestedPathWithoutServletMapping == null
|| requestedPathWithoutServletMapping.isEmpty()
|| "/".equals(requestedPathWithoutServletMapping)) {
return requestTypeParameter != null;
}
return false;
}
/**
* Returns the rest of the path after the servlet mapping part, if the
* requested path targets a path inside the servlet.
*
* @param servletMappingPath
* the servlet mapping from the servlet configuration
* @param requestedPath
* the request path relative to the context root
* @return an optional containing the path relative to the servlet if the
* request is inside the servlet mapping, an empty optional
* otherwise
*/
public static Optional<String> getPathIfInsideServlet(
String servletMappingPath, String requestedPath) {
Objects.requireNonNull(servletMappingPath,
"servletMappingPath cannot be null");
Objects.requireNonNull(requestedPath, "requestedPath cannot be null");
/*
* The Servlet 4 spec says
*
* A string beginning with a ‘/’ character and ending with a ‘/*’ suffix
* is used for path mapping.
*
* A string beginning with a ‘*.’ prefix is used as an extension
* mapping.
*
* The empty string ("") is a special URL pattern that exactly maps to
* the application's context root, i.e., requests of the form
* http://host:port/<contextroot>/. In this case the path info is ’/’
* and the servlet path and context path is empty string (““).
*
* A string containing only the ’/’ character indicates the "default"
* servlet of the application. In this case the servlet path is the
* request URI minus the context path and the path info is null.
*
* All other strings are used for exact matches only
*/
if ("/*".equals(servletMappingPath) || "/".equals(servletMappingPath)) {
/*
* A string containing only the ’/’ character indicates the
* "default" servlet
*
* A /* mapping covers everything
*/
return Optional.of(requestedPath);
}
if (servletMappingPath.startsWith("/")
&& servletMappingPath.endsWith("/*")) {
/*
* A string beginning with a ‘/’ character and ending with a ‘/*’
* suffix is used for path mapping.
*/
String directory = servletMappingPath.substring(1,
servletMappingPath.length() - 2);
String directoryWithSlash = directory + "/";
// Requested path should not contain the initial slash,
// but if it does, we remove it to be consistent with directory
String relativeRequestedPath = requestedPath.replaceFirst("^/", "");
// /foo/* matches /foo
if (relativeRequestedPath.equals(directory)) {
return Optional.of("");
}
if (relativeRequestedPath.startsWith(directoryWithSlash)) {
return Optional.of(relativeRequestedPath
.substring(directoryWithSlash.length()));
}
return Optional.empty();
}
// Servlet is mapped only to a static path such as "" or /foo/bar
String servletMappingWithoutSlash;
if (servletMappingPath.startsWith("/")) {
// Requested path should not contain the initial slash
servletMappingWithoutSlash = servletMappingPath.substring(1);
} else {
servletMappingWithoutSlash = servletMappingPath;
}
if (requestedPath.equals(servletMappingWithoutSlash)) {
return Optional.of(requestedPath
.substring(servletMappingWithoutSlash.length()));
}
return Optional.empty();
}
/**
* Returns the requested path inside the context root.
*
* @param request
* the servlet request
* @return the path inside the context root, not including the slash after
* the context root path
*/
public static String getRequestPathInsideContext(
HttpServletRequest request) {
String servletPath = request.getServletPath();
String pathInfo = request.getPathInfo();
String url = "";
if (servletPath != null) {
if (servletPath.startsWith("/")) {
// This SHOULD always be true...
url += servletPath.substring(1);
} else {
url += servletPath;
}
}
if (pathInfo != null) {
url += pathInfo;
}
return url;
}
/**
* Helper to find the most most suitable Locale. These potential sources are
* checked in order until a Locale is found:
* <ol>
* <li>The passed component (or UI) if not null</li>
* <li>{@link UI#getCurrent()} if defined</li>
* <li>The passed session if not null</li>
* <li>{@link VaadinSession#getCurrent()} if defined</li>
* <li>The passed request if not null</li>
* <li>{@link VaadinService#getCurrentRequest()} if defined</li>
* <li>{@link Locale#getDefault()}</li>
* </ol>
*
* @param session
* the session that is searched for locale or <code>null</code>
* if not available
* @param request
* the request that is searched for locale or <code>null</code>
* if not available
* @return the found locale
*/
public static Locale findLocale(VaadinSession session,
VaadinRequest request) {
if (session == null) {
session = VaadinSession.getCurrent();
}
if (session != null) {
Locale locale = session.getLocale();
if (locale != null) {
return locale;
}
}
if (request == null) {
request = VaadinService.getCurrentRequest();
}
if (request != null) {
Locale locale = request.getLocale();
if (locale != null) {
return locale;
}
}
return Locale.getDefault();
}
/**
* Sets no cache headers to the specified response.
*
* @param headerSetter
* setter for string value headers
* @param longHeaderSetter
* setter for long value headers
*/
public static void setResponseNoCacheHeaders(
BiConsumer<String, String> headerSetter,
BiConsumer<String, Long> longHeaderSetter) {
headerSetter.accept("Cache-Control", "no-cache, no-store");
headerSetter.accept("Pragma", "no-cache");
longHeaderSetter.accept("Expires", 0L);
}
/**
* Gets a relative path that cancels the provided path. This essentially
* adds one .. for each part of the path to cancel.
*
* @param pathToCancel
* the path that should be canceled
* @return a relative path that cancels out the provided path segment
*/
public static String getCancelingRelativePath(String pathToCancel) {
StringBuilder sb = new StringBuilder(".");
// Start from i = 1 to ignore first slash
for (int i = 1; i < pathToCancel.length(); i++) {
if (pathToCancel.charAt(i) == '/') {
sb.append("/..");
}
}
return sb.toString();
}
/**
* Checks if the given URL path contains the directory change instruction
* (dot-dot), taking into account possible double encoding in hexadecimal
* format, which can be injected maliciously.
*
* @param path
* the URL path to be verified.
* @return {@code true}, if the given path has a directory change
* instruction, {@code false} otherwise.
*/
public static boolean isPathUnsafe(String path) {
// Check that the path does not have '/../', '\..\', %5C..%5C,
// %2F..%2F, nor '/..', '\..', %5C.., %2F..
try {
path = URLDecoder.decode(path, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("An error occurred during decoding URL.",
e);
} catch (IllegalArgumentException ex) {
// Ignore: the path is not URLEncoded, check it as is
}
return PARENT_DIRECTORY_REGEX.matcher(path).find();
}
/**
* URLs matching these patterns should be publicly available for
* applications to work. Can be used for defining a bypass for rules in e.g.
* Spring Security.
* <p>
* These paths are relative to a potential Vaadin mapping
*/
public static String[] getPublicResources() {
return publicResources;
}
/**
* URLs matching these patterns should be publicly available for
* applications to work. Can be used for defining a bypass for rules in e.g.
* Spring Security.
* <p>
* These URLs are always relative to the root path and independent of any
* Vaadin mapping
*/
public static String[] getPublicResourcesRoot() {
return publicResourcesRoot;
}
/**
* Gets the paths of the PWA icon variants for the given base icon.
*
* @param iconPath
* path of the base icon.
* @return list of paths of icon variants.
*/
public static List<String> getIconVariants(String iconPath) {
return PwaRegistry.getIconTemplates(iconPath).stream()
.map(PwaIcon::getRelHref).collect(Collectors.toList());
}
/**
* URLs matching these patterns should be publicly available for
* applications to work but might require a security context, i.e.
* authentication information.
*/
public static String[] getPublicResourcesRequiringSecurityContext() {
return new String[] { //
"/VAADIN/**", // This contains static bundle files which
// typically do not need a security
// context but also uploads go here
};
}
}