forked from quarkusio/quarkus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpSecurityRecorder.java
325 lines (290 loc) · 15.9 KB
/
HttpSecurityRecorder.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
package io.quarkus.vertx.http.runtime.security;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.CompletionException;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.enterprise.inject.spi.CDI;
import org.jboss.logging.Logger;
import io.quarkus.arc.runtime.BeanContainer;
import io.quarkus.arc.runtime.BeanContainerListener;
import io.quarkus.runtime.RuntimeValue;
import io.quarkus.runtime.annotations.Recorder;
import io.quarkus.security.AuthenticationCompletionException;
import io.quarkus.security.AuthenticationFailedException;
import io.quarkus.security.AuthenticationRedirectException;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.request.AnonymousAuthenticationRequest;
import io.quarkus.vertx.http.runtime.FormAuthConfig;
import io.quarkus.vertx.http.runtime.HttpBuildTimeConfig;
import io.quarkus.vertx.http.runtime.HttpConfiguration;
import io.smallrye.mutiny.CompositeException;
import io.smallrye.mutiny.Uni;
import io.smallrye.mutiny.subscription.UniSubscriber;
import io.smallrye.mutiny.subscription.UniSubscription;
import io.smallrye.mutiny.tuples.Functions;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpHeaders;
import io.vertx.ext.web.RoutingContext;
@Recorder
public class HttpSecurityRecorder {
private static final Logger log = Logger.getLogger(HttpSecurityRecorder.class);
protected static final Consumer<Throwable> NOOP_CALLBACK = new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
}
};
final RuntimeValue<HttpConfiguration> httpConfiguration;
final HttpBuildTimeConfig buildTimeConfig;
//the temp encryption key, persistent across dev mode restarts
static volatile String encryptionKey;
public HttpSecurityRecorder(RuntimeValue<HttpConfiguration> httpConfiguration, HttpBuildTimeConfig buildTimeConfig) {
this.httpConfiguration = httpConfiguration;
this.buildTimeConfig = buildTimeConfig;
}
public Handler<RoutingContext> authenticationMechanismHandler(boolean proactiveAuthentication) {
return new Handler<RoutingContext>() {
volatile HttpAuthenticator authenticator;
@Override
public void handle(RoutingContext event) {
if (authenticator == null) {
authenticator = CDI.current().select(HttpAuthenticator.class).get();
}
//we put the authenticator into the routing context so it can be used by other systems
event.put(HttpAuthenticator.class.getName(), authenticator);
//register the default auth failure handler
//if proactive auth is used this is the only one
//if using lazy auth this can be modified downstream, to control authentication behaviour
event.put(QuarkusHttpUser.AUTH_FAILURE_HANDLER, new BiConsumer<RoutingContext, Throwable>() {
@Override
public void accept(RoutingContext routingContext, Throwable throwable) {
throwable = extractRootCause(throwable);
//auth failed
if (throwable instanceof AuthenticationFailedException) {
authenticator.sendChallenge(event).subscribe().with(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) {
if (!event.response().ended()) {
event.response().end();
}
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
event.fail(throwable);
}
});
} else if (throwable instanceof AuthenticationCompletionException) {
event.response().setStatusCode(401);
event.response().end();
} else if (throwable instanceof AuthenticationRedirectException) {
AuthenticationRedirectException redirectEx = (AuthenticationRedirectException) throwable;
event.response().setStatusCode(redirectEx.getCode());
event.response().headers().set(HttpHeaders.LOCATION, redirectEx.getRedirectUri());
event.response().headers().set(HttpHeaders.CACHE_CONTROL, "no-store");
event.response().headers().set("Pragma", "no-cache");
event.response().end();
} else {
event.fail(throwable);
}
}
});
Uni<SecurityIdentity> potentialUser = authenticator.attemptAuthentication(event).memoize().indefinitely();
if (proactiveAuthentication) {
potentialUser
.subscribe().withSubscriber(new UniSubscriber<SecurityIdentity>() {
@Override
public void onSubscribe(UniSubscription subscription) {
}
@Override
public void onItem(SecurityIdentity identity) {
if (event.response().ended()) {
return;
}
if (identity == null) {
Uni<SecurityIdentity> anon = authenticator.getIdentityProviderManager()
.authenticate(AnonymousAuthenticationRequest.INSTANCE);
anon.subscribe().withSubscriber(new UniSubscriber<SecurityIdentity>() {
@Override
public void onSubscribe(UniSubscription subscription) {
}
@Override
public void onItem(SecurityIdentity item) {
event.put(QuarkusHttpUser.DEFERRED_IDENTITY_KEY, anon);
event.setUser(new QuarkusHttpUser(item));
event.next();
}
@Override
public void onFailure(Throwable failure) {
BiConsumer<RoutingContext, Throwable> handler = event
.get(QuarkusHttpUser.AUTH_FAILURE_HANDLER);
if (handler != null) {
handler.accept(event, failure);
}
}
});
} else {//when the result is evaluated we set the user, even if it is evaluated lazily
event.setUser(new QuarkusHttpUser(identity));
event.put(QuarkusHttpUser.DEFERRED_IDENTITY_KEY, potentialUser);
event.next();
}
}
@Override
public void onFailure(Throwable failure) {
//this can be customised
BiConsumer<RoutingContext, Throwable> handler = event
.get(QuarkusHttpUser.AUTH_FAILURE_HANDLER);
if (handler != null) {
handler.accept(event, failure);
}
}
});
} else {
Uni<SecurityIdentity> lazyUser = potentialUser
.flatMap(new Function<SecurityIdentity, Uni<? extends SecurityIdentity>>() {
@Override
public Uni<? extends SecurityIdentity> apply(SecurityIdentity securityIdentity) {
//if it is null we use the anonymous identity
if (securityIdentity == null) {
return authenticator.getIdentityProviderManager()
.authenticate(AnonymousAuthenticationRequest.INSTANCE);
}
return Uni.createFrom().item(securityIdentity);
}
}).onTermination().invoke(new Functions.TriConsumer<SecurityIdentity, Throwable, Boolean>() {
@Override
public void accept(SecurityIdentity identity, Throwable throwable, Boolean aBoolean) {
if (identity != null) {
//when the result is evaluated we set the user, even if it is evaluated lazily
if (identity != null) {
event.setUser(new QuarkusHttpUser(identity));
}
} else if (throwable != null) {
//handle the auth failure
//this can be customised
BiConsumer<RoutingContext, Throwable> handler = event
.get(QuarkusHttpUser.AUTH_FAILURE_HANDLER);
if (handler != null) {
handler.accept(event, throwable);
}
}
}
}).memoize().indefinitely();
event.put(QuarkusHttpUser.DEFERRED_IDENTITY_KEY, lazyUser);
event.next();
}
}
};
}
private Throwable extractRootCause(Throwable throwable) {
while ((throwable instanceof CompletionException && throwable.getCause() != null) ||
(throwable instanceof CompositeException)) {
if (throwable instanceof CompositeException) {
throwable = ((CompositeException) throwable).getCauses().get(0);
} else {
throwable = throwable.getCause();
}
}
return throwable;
}
public Handler<RoutingContext> permissionCheckHandler() {
return new Handler<RoutingContext>() {
volatile HttpAuthorizer authorizer;
@Override
public void handle(RoutingContext event) {
if (authorizer == null) {
authorizer = CDI.current().select(HttpAuthorizer.class).get();
}
authorizer.checkPermission(event);
}
};
}
public BeanContainerListener initPermissions(HttpBuildTimeConfig permissions,
Map<String, Supplier<HttpSecurityPolicy>> policies) {
return new BeanContainerListener() {
@Override
public void created(BeanContainer container) {
container.instance(PathMatchingHttpSecurityPolicy.class).init(permissions, policies);
}
};
}
public Supplier<FormAuthenticationMechanism> setupFormAuth() {
return new Supplier<FormAuthenticationMechanism>() {
@Override
public FormAuthenticationMechanism get() {
String key;
if (!httpConfiguration.getValue().encryptionKey.isPresent()) {
if (encryptionKey != null) {
//persist across dev mode restarts
key = encryptionKey;
} else {
byte[] data = new byte[32];
new SecureRandom().nextBytes(data);
key = encryptionKey = Base64.getEncoder().encodeToString(data);
log.warn("Encryption key was not specified for persistent FORM auth, using temporary key " + key);
}
} else {
key = httpConfiguration.getValue().encryptionKey.get();
}
FormAuthConfig form = buildTimeConfig.auth.form;
PersistentLoginManager loginManager = new PersistentLoginManager(key, form.cookieName, form.timeout.toMillis(),
form.newCookieInterval.toMillis());
String loginPage = form.loginPage.startsWith("/") ? form.loginPage : "/" + form.loginPage;
String errorPage = form.errorPage.startsWith("/") ? form.errorPage : "/" + form.errorPage;
String landingPage = form.landingPage.startsWith("/") ? form.landingPage : "/" + form.landingPage;
String postLocation = form.postLocation.startsWith("/") ? form.postLocation : "/" + form.postLocation;
String usernameParameter = form.usernameParameter;
String passwordParameter = form.passwordParameter;
String locationCookie = form.locationCookie;
boolean redirectAfterLogin = form.redirectAfterLogin;
return new FormAuthenticationMechanism(loginPage, postLocation, usernameParameter, passwordParameter,
errorPage, landingPage, redirectAfterLogin, locationCookie, loginManager);
}
};
}
public Supplier<?> setupBasicAuth(HttpBuildTimeConfig buildTimeConfig) {
return new Supplier<BasicAuthenticationMechanism>() {
@Override
public BasicAuthenticationMechanism get() {
return new BasicAuthenticationMechanism(buildTimeConfig.auth.realm.orElse(null),
buildTimeConfig.auth.form.enabled);
}
};
}
public Supplier<?> setupMtlsClientAuth() {
return new Supplier<MtlsAuthenticationMechanism>() {
@Override
public MtlsAuthenticationMechanism get() {
return new MtlsAuthenticationMechanism();
}
};
}
/**
* This handler resolves the identity, and will be mapped to the post location. Otherwise,
* for lazy auth the post will not be evaluated if there is no security rule for the post location.
*/
public Handler<RoutingContext> formAuthPostHandler() {
return new Handler<RoutingContext>() {
@Override
public void handle(RoutingContext event) {
Uni<SecurityIdentity> user = event.get(QuarkusHttpUser.DEFERRED_IDENTITY_KEY);
user.subscribe().withSubscriber(new UniSubscriber<SecurityIdentity>() {
@Override
public void onSubscribe(UniSubscription uniSubscription) {
}
@Override
public void onItem(SecurityIdentity securityIdentity) {
event.next();
}
@Override
public void onFailure(Throwable throwable) {
event.fail(throwable);
}
});
}
};
}
}