forked from wildfly-security/elytron-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ElytronHttpExchange.java
608 lines (518 loc) · 20.7 KB
/
ElytronHttpExchange.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
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 org.wildfly.elytron.web.undertow.server;
import static org.wildfly.common.Assert.checkNotNullParam;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.http.HttpAuthenticationException;
import org.wildfly.security.http.HttpExchangeSpi;
import org.wildfly.security.http.HttpScope;
import org.wildfly.security.http.HttpScopeNotification;
import org.wildfly.security.http.HttpServerCookie;
import org.wildfly.security.http.Scope;
import org.xnio.SslClientAuthMode;
import io.undertow.security.api.SecurityContext;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.RenegotiationRequiredException;
import io.undertow.server.SSLSessionInfo;
import io.undertow.server.handlers.Cookie;
import io.undertow.server.handlers.CookieImpl;
import io.undertow.server.handlers.form.FormData;
import io.undertow.server.handlers.form.FormData.FormValue;
import io.undertow.server.handlers.form.FormDataParser;
import io.undertow.server.handlers.form.FormParserFactory;
import io.undertow.server.session.Session;
import io.undertow.server.session.SessionConfig;
import io.undertow.server.session.SessionManager;
import io.undertow.util.AbstractAttachable;
import io.undertow.util.AttachmentKey;
import io.undertow.util.Headers;
import io.undertow.util.HttpString;
/**
* Implementation of {@link HttpExchangeSpi} to wrap access to the Undertow specific {@link HttpServerExchange}.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
public class ElytronHttpExchange implements HttpExchangeSpi {
private static final AttachmentKey<HttpScope> HTTP_SCOPE_ATTACHMENT_KEY = AttachmentKey.create(HttpScope.class);
private static final FormParserFactory FORM_PARSER_FACTORY = FormParserFactory.builder().build();
private final HttpServerExchange httpServerExchange;
private final Map<Scope, Function<HttpServerExchange, HttpScope>> scopeResolvers;
private final ScopeSessionListener scopeSessionListener;
protected Map<String, List<String>> requestParameters;
protected ElytronHttpExchange(final HttpServerExchange httpServerExchange,
final Map<Scope, Function<HttpServerExchange, HttpScope>> scopeResolvers,
final ScopeSessionListener scopeSessionListener) {
this.httpServerExchange = checkNotNullParam("httpServerExchange", httpServerExchange);
this.scopeResolvers = scopeResolvers;
this.scopeSessionListener = scopeSessionListener;
}
protected ElytronHttpExchange(final HttpServerExchange httpServerExchange) {
this(httpServerExchange, Collections.emptyMap(), null);
}
/**
* @see org.wildfly.security.http.HttpExchangeSpi#getRequestHeaderValues(java.lang.String)
*/
@Override
public List<String> getRequestHeaderValues(String headerName) {
return httpServerExchange.getRequestHeaders().get(headerName);
}
/**
* @see org.wildfly.security.http.HttpExchangeSpi#addResponseHeader(java.lang.String, java.lang.String)
*/
@Override
public void addResponseHeader(String headerName, String headerValue) {
HttpString headerString = Headers.fromCache(headerName);
httpServerExchange.getResponseHeaders().add(headerString != null ? headerString : new HttpString(headerName),
headerValue);
}
/**
* @see org.wildfly.security.http.HttpExchangeSpi#getSSLSession()
*/
@Override
public SSLSession getSSLSession() {
SSLSessionInfo sessionInfo = httpServerExchange.getConnection().getSslSessionInfo();
if (sessionInfo != null) {
return sessionInfo.getSSLSession();
}
return null;
}
@Override
public Certificate[] getPeerCertificates(boolean renegotiate) {
SSLSessionInfo info = httpServerExchange.getConnection().getSslSessionInfo();
if(info == null) {
return null;
}
try {
Certificate[] peerCertificates = info.getPeerCertificates();
if (peerCertificates != null || renegotiate==false) return peerCertificates;
} catch (SSLPeerUnverifiedException |RenegotiationRequiredException e) {}
try {
info.renegotiate(httpServerExchange, SslClientAuthMode.REQUESTED);
return httpServerExchange.getConnection().getSslSessionInfo().getPeerCertificates();
} catch (IOException | RenegotiationRequiredException e) {}
return null;
}
/**
* @see org.wildfly.security.http.HttpExchangeSpi#authenticationComplete(SecurityIdentity, String)
*/
@Override
public void authenticationComplete(SecurityIdentity securityIdentity, String mechanismName) {
SecurityContext securityContext = httpServerExchange.getSecurityContext();
if (securityContext != null) {
securityContext.authenticationComplete(new ElytronAccount(securityIdentity), mechanismName, false);
}
}
/**
* @see org.wildfly.security.http.HttpExchangeSpi#authenticationFailed(String, String)
*/
@Override
public void authenticationFailed(String message, String mechanismName) {
SecurityContext securityContext = httpServerExchange.getSecurityContext();
if (securityContext != null) {
securityContext.authenticationFailed(message, mechanismName);
}
}
@Override
public void badRequest(HttpAuthenticationException error, String mechanismName) {
}
@Override
public String getRequestMethod() {
return httpServerExchange.getRequestMethod().toString();
}
@Override
public URI getRequestURI() {
final String scheme;
final String host;
final int port;
final String path;
final String query = httpServerExchange.getQueryString();
try {
if (httpServerExchange.isHostIncludedInRequestURI()) {
URI tempUri = new URI(httpServerExchange.getRequestURI());
scheme = tempUri.getScheme();
host = tempUri.getHost();
port = tempUri.getPort();
path = tempUri.getPath();
} else {
scheme = httpServerExchange.getRequestScheme();
host = httpServerExchange.getHostName();
port = httpServerExchange.getHostPort();
path = httpServerExchange.getRequestURI();
}
StringBuilder uriBuilder = new StringBuilder();
if (scheme != null) {
uriBuilder.append(scheme);
uriBuilder.append(':');
}
if (host != null) {
uriBuilder.append("//");
boolean needBrackets = ((host.indexOf(':') >= 0)
&& ! host.startsWith("[")
&& ! host.endsWith("]"));
if (needBrackets) {
uriBuilder.append('[');
}
uriBuilder.append(host);
if (needBrackets) {
uriBuilder.append(']');
}
}
if (! (("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443))) {
uriBuilder.append(':');
uriBuilder.append(port);
}
if (path != null) {
uriBuilder.append(path);
}
if (query != null && ! query.isEmpty()) {
uriBuilder.append("?");
uriBuilder.append(query);
}
return new URI(uriBuilder.toString());
} catch (URISyntaxException e) {
return null;
}
}
@Override
public String getRequestPath() {
return httpServerExchange.getRelativePath();
}
@Override
public Map<String, List<String>> getRequestParameters() {
if (requestParameters == null) {
synchronized(this) {
if (requestParameters == null) {
HashMap<String, List<String>> parameters = new HashMap<>();
Map<String, Deque<String>> queryParameters = httpServerExchange.getQueryParameters();
FormDataParser parser = FORM_PARSER_FACTORY.createParser(httpServerExchange);
if (parser != null) {
try {
FormData data = parser.parseBlocking();
for (Map.Entry<String, Deque<String>> queryParametersEntry : queryParameters.entrySet()) {
List<String> values = new ArrayList<>(queryParametersEntry.getValue());
if (data.contains(queryParametersEntry.getKey())) {
Deque<FormValue> formValues = data.get(queryParametersEntry.getKey());
formValues.stream().filter((FormValue fv) -> fv.isFile() == false)
.forEach((FormValue fv) -> values.add(fv.getValue()));
}
parameters.put(queryParametersEntry.getKey(), Collections.unmodifiableList(values));
}
StreamSupport
.stream(data.spliterator(), false)
.filter((String s) -> parameters.containsKey(s) == false)
.forEach(
(String s) -> parameters.put(s,
Collections.unmodifiableList(data.get(s).stream()
.filter((FormValue v) -> v.isFile() == false)
.map((FormValue fv) -> fv.getValue()).collect(Collectors.toList()))));
} catch (IOException e) {}
} else {
queryParameters.forEach((name, values) -> parameters.put(name, Collections.unmodifiableList(new ArrayList<String>(values))));
}
requestParameters = Collections.unmodifiableMap(parameters);
}
}
}
return requestParameters;
}
@Override
public List<HttpServerCookie> getCookies() {
Map<String, Cookie> cookies = httpServerExchange.getRequestCookies();
return cookies.values().stream().map((Function<Cookie, HttpServerCookie>) cookie -> new HttpServerCookie() {
@Override
public String getName() {
return cookie.getName();
}
@Override
public String getValue() {
return cookie.getValue();
}
@Override
public String getDomain() {
return cookie.getDomain();
}
@Override
public int getMaxAge() {
return cookie.getMaxAge();
}
@Override
public String getPath() {
return cookie.getPath();
}
@Override
public boolean isSecure() {
return cookie.isSecure();
}
@Override
public int getVersion() {
return cookie.getVersion();
}
@Override
public boolean isHttpOnly() {
return cookie.isHttpOnly();
}
}).collect(Collectors.toList());
}
@Override
public InputStream getRequestInputStream() {
return httpServerExchange.getInputStream();
}
@Override
public InetSocketAddress getSourceAddress() {
return httpServerExchange.getSourceAddress();
}
@Override
public void setResponseCookie(HttpServerCookie cookie) {
CookieImpl actualCookie = new CookieImpl(cookie.getName(), cookie.getValue());
actualCookie.setDomain(cookie.getDomain());
actualCookie.setMaxAge(cookie.getMaxAge());
actualCookie.setHttpOnly(cookie.isHttpOnly());
actualCookie.setSecure(cookie.isSecure());
actualCookie.setPath(cookie.getPath());
httpServerExchange.setResponseCookie(actualCookie);
}
@Override
public OutputStream getResponseOutputStream() {
return httpServerExchange.getOutputStream();
}
@Override
public HttpScope getScope(Scope scope) {
if (scopeResolvers.containsKey(scope)) {
return scopeResolvers.get(scope).apply(httpServerExchange);
}
switch (scope) {
case APPLICATION: {
SessionManager sessionManager = getSessionManager();
if (sessionManager == null) return null;
return new HttpScope() {
@Override
public String getID() {
// TODO Find a better mechanism for obtaining a unique deployment ID
return sessionManager.getDeploymentName();
}
};
}
case CONNECTION:
return getScope(httpServerExchange.getConnection());
case EXCHANGE:
return getScope(httpServerExchange);
case GLOBAL:
return null;
case SESSION:
return toScope(null);
case SSL_SESSION:
return getScope(getSSLSession());
}
return null;
}
@Override
public Collection<String> getScopeIds(Scope scope) {
if (scope == Scope.SESSION) {
SessionManager sessionManager = getSessionManager();
return sessionManager.getAllSessions();
}
return null;
}
@Override
public HttpScope getScope(Scope scope, String id) {
if (scope == Scope.SESSION) {
return toScope(id);
}
return null;
}
@Override
public void setStatusCode(int statusCode) {
if (httpServerExchange.isResponseStarted() == false) {
httpServerExchange.setStatusCode(statusCode);
}
}
@Override
public String getRemoteUser() {
return httpServerExchange.getAttachment(HttpServerExchange.REMOTE_USER);
}
/**
* Sub-types may override this method to define how {@link SessionManager} is obtained.
*
* @return the {@link SessionManager}
*/
protected SessionManager getSessionManager() {
return httpServerExchange.getAttachment(SessionManager.ATTACHMENT_KEY);
}
/**
* Sub-types may override this method to define how {@link SessionConfig} is obtained.
*
* @return the {@link SessionConfig}
*/
protected SessionConfig getSessionConfig() {
return httpServerExchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
}
private HttpScope toScope(String id) {
SessionManager sessionManager = getSessionManager();
SessionConfig sessionConfig = getSessionConfig();
if (sessionManager == null || sessionConfig == null) {
return null;
}
return new HttpScope() {
private Session session = id == null ? sessionManager.getSession(httpServerExchange, sessionConfig) : sessionManager.getSession(id);
@Override
public String getID() {
if (exists()) {
return session.getId();
}
return null;
}
@Override
public boolean exists() {
return session != null;
}
@Override
public boolean create() {
if (exists()) {
return false;
}
session = sessionManager.createSession(httpServerExchange, sessionConfig);
return session != null;
}
@Override
public boolean supportsAttachments() {
return exists();
}
@Override
public void setAttachment(String key, Object value) {
if (supportsAttachments()) {
session.setAttribute(key, value);
}
}
@Override
public Object getAttachment(String key) {
if (supportsAttachments()) {
return session.getAttribute(key);
}
return null;
}
@Override
public boolean supportsInvalidation() {
return exists();
}
@Override
public boolean invalidate() {
if (supportsInvalidation()) {
session.invalidate(httpServerExchange);
return true;
}
return false;
}
@Override
public boolean supportsNotifications() {
return exists() && scopeSessionListener != null;
}
@Override
public void registerForNotification(Consumer<HttpScopeNotification> notificationConsumer) {
if (supportsNotifications()) {
scopeSessionListener.registerListener(session.getId(), notificationConsumer);
}
}
};
}
private HttpScope getScope(AbstractAttachable attachable) {
HttpScope httpScope = attachable.getAttachment(HTTP_SCOPE_ATTACHMENT_KEY);
if (httpScope == null) {
synchronized (attachable) {
httpScope = attachable.getAttachment(HTTP_SCOPE_ATTACHMENT_KEY);
if (httpScope == null) {
final Map<String, Object> storageMap = new HashMap<>();
httpScope = new HttpScope() {
@Override
public boolean exists() {
return true;
}
@Override
public boolean create() {
return false;
}
@Override
public boolean supportsAttachments() {
return true;
}
@Override
public void setAttachment(String key, Object value) {
if (value != null) {
storageMap.put(key, value);
} else {
storageMap.remove(key);
}
}
@Override
public Object getAttachment(String key) {
return storageMap.get(key);
}
};
attachable.putAttachment(HTTP_SCOPE_ATTACHMENT_KEY, httpScope);
}
}
}
return httpScope;
}
private HttpScope getScope(final SSLSession sslSession) {
if (sslSession == null) {
return null;
}
return new HttpScope() {
@Override
public boolean exists() {
return true;
}
@Override
public boolean create() {
return false;
}
@Override
public boolean supportsAttachments() {
return true;
}
@Override
public void setAttachment(String key, Object value) {
sslSession.putValue(key, value);
}
@Override
public Object getAttachment(String key) {
return sslSession.getValue(key);
}
};
}
}