-
Notifications
You must be signed in to change notification settings - Fork 871
/
JwtFilter.java
261 lines (233 loc) · 9.84 KB
/
JwtFilter.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
/*
* Copyright 2021 Collate
* 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.openmetadata.service.security;
import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty;
import static org.openmetadata.service.security.jwt.JWTTokenGenerator.TOKEN_TYPE;
import com.auth0.jwk.Jwk;
import com.auth0.jwk.JwkProvider;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.node.TextNode;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import java.net.URL;
import java.security.interfaces.RSAPublicKey;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.openmetadata.schema.api.security.AuthenticationConfiguration;
import org.openmetadata.schema.api.security.AuthorizerConfiguration;
import org.openmetadata.schema.auth.LogoutRequest;
import org.openmetadata.schema.auth.ServiceTokenType;
import org.openmetadata.schema.services.connections.metadata.AuthProvider;
import org.openmetadata.service.security.auth.BotTokenCache;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
import org.openmetadata.service.security.auth.UserTokenCache;
import org.openmetadata.service.security.saml.JwtTokenCacheManager;
@Slf4j
@Provider
public class JwtFilter implements ContainerRequestFilter {
public static final String AUTHORIZATION_HEADER = "Authorization";
public static final String TOKEN_PREFIX = "Bearer";
public static final String BOT_CLAIM = "isBot";
private List<String> jwtPrincipalClaims;
private JwkProvider jwkProvider;
private String principalDomain;
private boolean enforcePrincipalDomain;
private AuthProvider providerType;
public static final List<String> EXCLUDED_ENDPOINTS =
List.of(
"v1/system/config/jwks",
"v1/system/config/authorizer",
"v1/system/config/customLogoConfiguration",
"v1/users/signup",
"v1/system/version",
"v1/users/registrationConfirmation",
"v1/users/resendRegistrationToken",
"v1/users/generatePasswordResetLink",
"v1/users/password/reset",
"v1/users/checkEmailInUse",
"v1/users/login",
"v1/users/refresh");
@SuppressWarnings("unused")
private JwtFilter() {}
@SneakyThrows
public JwtFilter(
AuthenticationConfiguration authenticationConfiguration, AuthorizerConfiguration authorizerConfiguration) {
this.providerType = authenticationConfiguration.getProvider();
this.jwtPrincipalClaims = authenticationConfiguration.getJwtPrincipalClaims();
ImmutableList.Builder<URL> publicKeyUrlsBuilder = ImmutableList.builder();
for (String publicKeyUrlStr : authenticationConfiguration.getPublicKeyUrls()) {
publicKeyUrlsBuilder.add(new URL(publicKeyUrlStr));
}
this.jwkProvider = new MultiUrlJwkProvider(publicKeyUrlsBuilder.build());
this.principalDomain = authorizerConfiguration.getPrincipalDomain();
this.enforcePrincipalDomain = authorizerConfiguration.getEnforcePrincipalDomain();
}
@VisibleForTesting
JwtFilter(
JwkProvider jwkProvider,
List<String> jwtPrincipalClaims,
String principalDomain,
boolean enforcePrincipalDomain) {
this.jwkProvider = jwkProvider;
this.jwtPrincipalClaims = jwtPrincipalClaims;
this.principalDomain = principalDomain;
this.enforcePrincipalDomain = enforcePrincipalDomain;
}
@SneakyThrows
@Override
public void filter(ContainerRequestContext requestContext) {
UriInfo uriInfo = requestContext.getUriInfo();
if (EXCLUDED_ENDPOINTS.stream().anyMatch(endpoint -> uriInfo.getPath().equalsIgnoreCase(endpoint))) {
return;
}
// Extract token from the header
MultivaluedMap<String, String> headers = requestContext.getHeaders();
String tokenFromHeader = extractToken(headers);
LOG.debug("Token from header:{}", tokenFromHeader);
// the case where OMD generated the Token for the Client
if (AuthProvider.BASIC.equals(providerType) || AuthProvider.SAML.equals(providerType)) {
validateTokenIsNotUsedAfterLogout(tokenFromHeader);
}
DecodedJWT jwt = validateAndReturnDecodedJwtToken(tokenFromHeader);
Map<String, Claim> claims = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
claims.putAll(jwt.getClaims());
String userName = validateAndReturnUsername(claims);
// validate bot token
if (claims.containsKey(BOT_CLAIM) && Boolean.TRUE.equals(claims.get(BOT_CLAIM).asBoolean())) {
validateBotToken(tokenFromHeader, userName);
}
// validate access token
if (claims.containsKey(TOKEN_TYPE)
&& ServiceTokenType.PERSONAL_ACCESS.equals(ServiceTokenType.fromValue(claims.get(TOKEN_TYPE).asString()))) {
validatePersonalAccessToken(tokenFromHeader, userName);
}
// Setting Security Context
CatalogPrincipal catalogPrincipal = new CatalogPrincipal(userName);
String scheme = requestContext.getUriInfo().getRequestUri().getScheme();
CatalogSecurityContext catalogSecurityContext =
new CatalogSecurityContext(catalogPrincipal, scheme, SecurityContext.DIGEST_AUTH);
LOG.debug("SecurityContext {}", catalogSecurityContext);
requestContext.setSecurityContext(catalogSecurityContext);
}
@SneakyThrows
public DecodedJWT validateAndReturnDecodedJwtToken(String token) {
// Decode JWT Token
DecodedJWT jwt;
try {
jwt = JWT.decode(token);
} catch (JWTDecodeException e) {
throw new AuthenticationException("Invalid token", e);
}
// Check if expired
// If expiresAt is set to null, treat it as never expiring token
if (jwt.getExpiresAt() != null
&& jwt.getExpiresAt().before(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime())) {
throw new AuthenticationException("Expired token!");
}
// Validate JWT with public key
Jwk jwk = jwkProvider.get(jwt.getKeyId());
Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);
try {
algorithm.verify(jwt);
} catch (RuntimeException runtimeException) {
throw new AuthenticationException("Invalid token", runtimeException);
}
return jwt;
}
@SneakyThrows
public String validateAndReturnUsername(Map<String, Claim> claims) {
// Get username from JWT token
String jwtClaim =
jwtPrincipalClaims.stream()
.filter(claims::containsKey)
.findFirst()
.map(claims::get)
.map(claim -> claim.as(TextNode.class).asText())
.orElseThrow(
() ->
new AuthenticationException(
"Invalid JWT token, none of the following claims are present " + jwtPrincipalClaims));
String userName;
String domain;
if (jwtClaim.contains("@")) {
userName = jwtClaim.split("@")[0];
domain = jwtClaim.split("@")[1];
} else {
userName = jwtClaim;
domain = StringUtils.EMPTY;
}
// validate principal domain
if (enforcePrincipalDomain && !domain.equals(principalDomain)) {
throw new AuthenticationException(
String.format("Not Authorized! Email does not match the principal domain %s", principalDomain));
}
return userName;
}
protected static String extractToken(MultivaluedMap<String, String> headers) {
LOG.debug("Request Headers:{}", headers);
String source = headers.getFirst(AUTHORIZATION_HEADER);
if (nullOrEmpty(source)) {
throw AuthenticationException.getTokenNotPresentException();
}
// Extract the bearer token
if (source.startsWith(TOKEN_PREFIX)) {
return source.substring(TOKEN_PREFIX.length() + 1);
}
throw AuthenticationException.getTokenNotPresentException();
}
public static String extractToken(String tokenFromHeader) {
LOG.debug("Request Token:{}", tokenFromHeader);
if (nullOrEmpty(tokenFromHeader)) {
throw AuthenticationException.getTokenNotPresentException();
}
// Extract the bearer token
if (tokenFromHeader.startsWith(TOKEN_PREFIX)) {
return tokenFromHeader.substring(TOKEN_PREFIX.length() + 1);
}
throw AuthenticationException.getTokenNotPresentException();
}
private void validateBotToken(String tokenFromHeader, String userName) {
if (tokenFromHeader.equals(BotTokenCache.getToken(userName))) {
return;
}
throw AuthenticationException.getInvalidTokenException();
}
private void validatePersonalAccessToken(String tokenFromHeader, String userName) {
if (UserTokenCache.getToken(userName).contains(tokenFromHeader)) {
return;
}
throw AuthenticationException.getInvalidTokenException();
}
private void validateTokenIsNotUsedAfterLogout(String authToken) {
LogoutRequest previouslyLoggedOutEvent = JwtTokenCacheManager.getInstance().getLogoutEventForToken(authToken);
if (previouslyLoggedOutEvent != null) {
throw new AuthenticationException("Expired token!");
}
}
}