forked from jooby-project/jooby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCors.java
More file actions
390 lines (342 loc) · 9.8 KB
/
Cors.java
File metadata and controls
390 lines (342 loc) · 9.8 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
/**
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import com.typesafe.config.Config;
import javax.annotation.Nonnull;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static java.util.Objects.requireNonNull;
/**
* <h1>Cross-origin resource sharing</h1>
* <p>
* Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts,
* JavaScript, etc.) on a web page to be requested from another domain outside the domain from which
* the resource originated.
* </p>
*
* <p>
* This class represent the available options for configure CORS in Jooby.
* </p>
*
* <h2>usage</h2>
*
* <pre>
* {
* decorator(new CorsHandler());
* }
* </pre>
*
* <p>
* Previous example, adds a cors filter using the default cors options.
* </p>
*
* @author edgar
* @since 2.0.4
*/
public class Cors {
private static class Matcher<T> implements Predicate<T> {
private List<String> values;
private Predicate<T> predicate;
private boolean wild;
Matcher(final List<String> values, final Predicate<T> predicate) {
this.values = values;
this.predicate = predicate;
this.wild = values.contains("*");
}
@Override
public boolean test(final T value) {
return predicate.test(value);
}
@Override public String toString() {
return values.toString();
}
}
/** Default max-age in minutes. */
private static final int _30 = 30;
private Matcher<String> origin;
private boolean credentials;
private Matcher<String> methods;
private Matcher<List<String>> headers;
private Duration maxAge;
private List<String> exposedHeaders = Collections.emptyList();
/**
* Creates default {@link Cors}. Default options are:
*
* <pre>
* origin: "*"
* credentials: true
* allowedMethods: [GET, POST]
* allowedHeaders: [X-Requested-With, Content-Type, Accept, Origin]
* maxAge: 30m
* exposedHeaders: []
* </pre>
*/
public Cors() {
setOrigin("*");
setUseCredentials(true);
setMethods("GET", "POST");
setHeaders("X-Requested-With", "Content-Type", "Accept", "Origin");
setMaxAge(Duration.ofMinutes(_30));
}
/**
* If true, set the <code>Access-Control-Allow-Credentials</code> header.
*
* @return If the <code>Access-Control-Allow-Credentials</code> header must be set.
*/
public boolean getUseCredentials() {
return this.credentials;
}
/**
* If true, set the <code>Access-Control-Allow-Credentials</code> header.
*
* @param credentials Credentials.
* @return This cors.
*/
public Cors setUseCredentials(boolean credentials) {
this.credentials = credentials;
return this;
}
/**
* @return True if any origin is accepted.
*/
public boolean anyOrigin() {
return origin.wild;
}
/**
* An origin must be a "*" (any origin), a domain name (like, http://foo.com) and/or a regex
* (like, http://*.domain.com).
*
* @return List of valid origins: Default is: <code>*</code>
*/
public List<String> getOrigin() {
return origin.values;
}
/**
* Test if the given origin is allowed or not.
*
* @param origin The origin to test.
* @return True if the origin is allowed.
*/
public boolean allowOrigin(final String origin) {
return this.origin.test(origin);
}
/**
* Set the allowed origins. An origin must be a "*" (any origin), a domain name (like,
* http://foo.com) and/or a regex (like, http://*.domain.com).
*
* @param origin One ore more origin.
* @return This cors.
*/
public Cors setOrigin(final String... origin) {
return setOrigin(Arrays.asList(origin));
}
/**
* Set the allowed origins. An origin must be a "*" (any origin), a domain name (like,
* http://foo.com) and/or a regex (like, http://*.domain.com).
*
* @param origin One ore more origin.
* @return This cors.
*/
public Cors setOrigin(final List<String> origin) {
this.origin = firstMatch(requireNonNull(origin, "Origins are required."));
return this;
}
/**
* True if the method is allowed.
*
* @param method Method to test.
* @return True if the method is allowed.
*/
public boolean allowMethod(final String method) {
return this.methods.test(method);
}
/**
* @return List of allowed methods.
*/
public List<String> getMethods() {
return methods.values;
}
/**
* Set one or more allowed methods.
*
* @param methods One or more method.
* @return This cors.
*/
public Cors setMethods(final String... methods) {
return setMethods(Arrays.asList(methods));
}
/**
* Set one or more allowed methods.
*
* @param methods One or more method.
* @return This cors.
*/
public Cors setMethods(final List<String> methods) {
this.methods = firstMatch(methods);
return this;
}
/**
* @return True if any header is allowed: <code>*</code>.
*/
public boolean anyHeader() {
return headers.wild;
}
/**
* True if all the headers are allowed.
*
* @param headers Headers to test.
* @return True if all the headers are allowed.
*/
public boolean allowHeader(final String... headers) {
return allowHeaders(Arrays.asList(headers));
}
/**
* True if all the headers are allowed.
*
* @param headers Headers to test.
* @return True if all the headers are allowed.
*/
public boolean allowHeaders(final List<String> headers) {
return this.headers.test(headers);
}
/**
* @return List of allowed headers. Default are: <code>X-Requested-With</code>,
* <code>Content-Type</code>, <code>Accept</code> and <code>Origin</code>.
*/
public List<String> getHeaders() {
return headers.values;
}
/**
* Set one or more allowed headers. Possible values are a header name or <code>*</code> if any
* header is allowed.
*
* @param headers Headers to set.
* @return This cors.
*/
public Cors setHeaders(final String... headers) {
return setHeaders(Arrays.asList(headers));
}
/**
* Set one or more allowed headers. Possible values are a header name or <code>*</code> if any
* header is allowed.
*
* @param headers Headers to set.
* @return This cors.
*/
public Cors setHeaders(final List<String> headers) {
this.headers = allMatch(headers);
return this;
}
/**
* @return List of exposed headers.
*/
public List<String> getExposedHeaders() {
return exposedHeaders;
}
/**
* Set the list of exposed headers.
*
* @param exposedHeaders Headers to expose.
* @return This cors.
*/
public Cors setExposedHeaders(final String... exposedHeaders) {
return setExposedHeaders(Arrays.asList(exposedHeaders));
}
/**
* Set the list of exposed headers.
*
* @param exposedHeaders Headers to expose.
* @return This cors.
*/
public Cors setExposedHeaders(final List<String> exposedHeaders) {
this.exposedHeaders = requireNonNull(exposedHeaders, "Exposed headers are required.");
return this;
}
/**
* @return Preflight max age. How many seconds a client can cache a preflight request.
*/
public Duration getMaxAge() {
return maxAge;
}
/**
* Set the preflight max age header. That's how many seconds a client can cache a preflight
* request.
*
* @param preflightMaxAge Number of seconds or <code>-1</code> to turn this off.
* @return This cors.
*/
public Cors setMaxAge(final Duration preflightMaxAge) {
this.maxAge = preflightMaxAge;
return this;
}
/**
* Get cors options from application configuration file.
*
* <pre>{@code
* cors {
* origin: *
* methods: [GET, POST]
* headers: [Custom-Header]
* maxAge: 30m
* exposesHeaders: [Header]
* }
* }</pre>
*
* @param conf Configuration.
* @return Cors options.
*/
public static @Nonnull Cors from(@Nonnull Config conf) {
Config cors = conf.hasPath("cors") ? conf.getConfig("cors") : conf;
Cors options = new Cors();
if (cors.hasPath("origin")) {
options.setOrigin(list(cors.getAnyRef("origin")));
}
if (cors.hasPath("credentials")) {
options.setUseCredentials(cors.getBoolean("credentials"));
}
if (cors.hasPath("methods")) {
options.setMethods(list(cors.getAnyRef("methods")));
}
if (cors.hasPath("headers")) {
options.setHeaders(list(cors.getAnyRef("headers")));
}
if (cors.hasPath("maxAge")) {
options.setMaxAge(Duration.ofSeconds(cors.getDuration("maxAge", TimeUnit.SECONDS)));
}
if (cors.hasPath("exposedHeaders")) {
options.setExposedHeaders(list(cors.getAnyRef("exposedHeaders")));
}
return options;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static List<String> list(final Object value) {
return value instanceof List ? (List) value : Collections.singletonList(value.toString());
}
private static Matcher<List<String>> allMatch(final List<String> values) {
Predicate<String> predicate = firstMatch(values);
Predicate<List<String>> allmatch = it -> it.stream().allMatch(predicate);
return new Matcher<>(values, allmatch);
}
private static Matcher<String> firstMatch(final List<String> values) {
List<Pattern> patterns = values.stream()
.map(Cors::rewrite)
.collect(Collectors.toList());
Predicate<String> predicate = it -> patterns.stream()
.filter(pattern -> pattern.matcher(it).matches())
.findFirst()
.isPresent();
return new Matcher<>(values, predicate);
}
private static Pattern rewrite(final String origin) {
return Pattern.compile(origin.replace(".", "\\.").replace("*", ".*"), Pattern.CASE_INSENSITIVE);
}
}