Repository navigation
Expand file tree
/
Copy pathCors.java
More file actions
415 lines (363 loc) · 10.8 KB
/
Copy pathCors.java
File metadata and controls
415 lines (363 loc) · 10.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
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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.jooby.handlers;
import static java.util.Objects.requireNonNull;
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 javax.inject.Inject;
import javax.inject.Named;
import com.google.common.collect.ImmutableList;
import com.typesafe.config.Config;
/**
* <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>
* {
* use("*", new CorsHandler(new Cors()));
* }
* </pre>
*
* <p>
* Previous example, adds a cors filter using the default cors options.
* </p>
*
* @author edgar
* @since 0.8.0
*/
public class Cors {
private static class Matcher<T> implements Predicate<T> {
private List<String> values;
private Predicate<T> predicate;
private boolean wild;
public Matcher(final List<String> values, final Predicate<T> predicate) {
this.values = ImmutableList.copyOf(values);
this.predicate = predicate;
this.wild = values.contains("*");
}
@Override
public boolean test(final T value) {
return predicate.test(value);
}
}
private boolean enabled;
private Matcher<String> origin;
private boolean credentials;
private Matcher<String> requestMehods;
private Matcher<List<String>> requestHeaders;
private int maxAge;
private List<String> exposedHeaders;
/**
* Creates {@link Cors} options from {@link Config}:
*
* <pre>
* origin: "*"
* credentials: true
* allowedMethods: [GET, POST]
* allowedHeaders: [X-Requested-With, Content-Type, Accept, Origin]
* exposedHeaders: []
* </pre>
*
* @param config Config to use.
*/
@Inject
public Cors(@Named("cors") final Config config) {
requireNonNull(config, "Config is required.");
this.enabled = config.hasPath("enabled") ? config.getBoolean("enabled") : true;
withOrigin(list(config.getAnyRef("origin")));
this.credentials = config.getBoolean("credentials");
withMethods(list(config.getAnyRef("allowedMethods")));
withHeaders(list(config.getAnyRef("allowedHeaders")));
withMaxAge((int) config.getDuration("maxAge", TimeUnit.SECONDS));
withExposedHeaders(config.hasPath("exposedHeaders")
? list(config.getAnyRef("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]
* exposedHeaders: []
* </pre>
*/
public Cors() {
this.enabled = true;
withOrigin("*");
credentials = true;
withMethods("GET", "POST");
withHeaders("X-Requested-With", "Content-Type", "Accept", "Origin");
withMaxAge(1800);
withExposedHeaders();
}
/**
* Set {@link #credentials()} to false.
*
* @return This cors.
*/
public Cors withoutCreds() {
this.credentials = false;
return this;
}
/**
* @return True, if cors is enabled. Controlled by: <code>cors.enabled</code> property. Default
* is: <code>true</code>.
*/
public boolean enabled() {
return enabled;
}
/**
* Disabled cors (enabled = false).
*
* @return This cors.
*/
public Cors disabled() {
enabled = false;
return this;
}
/**
* If true, set the <code>Access-Control-Allow-Credentials</code> header. Controlled by:
* <code>cors.credentials</code> property. Default is: <code>true</code>
*
* @return If the <code>Access-Control-Allow-Credentials</code> header must be set.
*/
public boolean credentials() {
return this.credentials;
}
/**
* @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> origin() {
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 withOrigin(final String... origin) {
return withOrigin(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 withOrigin(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.requestMehods.test(method);
}
/**
* @return List of allowed methods.
*/
public List<String> allowedMethods() {
return requestMehods.values;
}
/**
* Set one or more allowed methods.
*
* @param methods One or more method.
* @return This cors.
*/
public Cors withMethods(final String... methods) {
return withMethods(Arrays.asList(methods));
}
/**
* Set one or more allowed methods.
*
* @param methods One or more method.
* @return This cors.
*/
public Cors withMethods(final List<String> methods) {
this.requestMehods = firstMatch(methods);
return this;
}
/**
* @return True if any header is allowed: <code>*</code>.
*/
public boolean anyHeader() {
return requestHeaders.wild;
}
/**
* @param header A header to test.
* @return True if a header is allowed.
*/
public boolean allowHeader(final String header) {
return allowHeaders(ImmutableList.of(header));
}
/**
* True if all the headers are allowed.
*
* @param headers Headers to test.
* @return True if all the headers are allowed.
*/
public boolean allowHeaders(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.requestHeaders.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> allowedHeaders() {
return requestHeaders.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 withHeaders(final String... headers) {
return withHeaders(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 withHeaders(final List<String> headers) {
this.requestHeaders = allMatch(headers);
return this;
}
/**
* @return List of exposed headers.
*/
public List<String> exposedHeaders() {
return exposedHeaders;
}
/**
* Set the list of exposed headers.
*
* @param exposedHeaders Headers to expose.
* @return This cors.
*/
public Cors withExposedHeaders(final String... exposedHeaders) {
return withExposedHeaders(Arrays.asList(exposedHeaders));
}
/**
* Set the list of exposed headers.
*
* @param exposedHeaders Headers to expose.
* @return This cors.
*/
public Cors withExposedHeaders(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 int maxAge() {
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 withMaxAge(final int preflightMaxAge) {
this.maxAge = preflightMaxAge;
return this;
}
@SuppressWarnings({"unchecked", "rawtypes" })
private List<String> list(final Object value) {
return value instanceof List ? (List) value : ImmutableList.of(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<List<String>>(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<String>(values, predicate);
}
private static Pattern rewrite(final String origin) {
return Pattern.compile(origin.replace(".", "\\.").replace("*", ".*"), Pattern.CASE_INSENSITIVE);
}
}