Skip to content

Commit

Permalink
style: setup & apply prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
ThibaudAV authored and phiz71 committed Jan 21, 2022
1 parent c4057d5 commit 4a0180d
Show file tree
Hide file tree
Showing 32 changed files with 329 additions and 321 deletions.
2 changes: 2 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
printWidth: 140
tabWidth: 4
17 changes: 17 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,23 @@
<source>8</source>
</configuration>
</plugin>
<plugin>
<groupId>com.hubspot.maven.plugins</groupId>
<artifactId>prettier-maven-plugin</artifactId>
<version>0.17</version>
<configuration>
<nodeVersion>12.13.0</nodeVersion>
<prettierJavaVersion>1.6.1</prettierJavaVersion>
</configuration>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
152 changes: 82 additions & 70 deletions src/main/java/io/gravitee/policy/jwt/JWTPolicy.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
*/
package io.gravitee.policy.jwt;

import static io.gravitee.gateway.api.ExecutionContext.ATTR_API;
import static io.gravitee.gateway.api.ExecutionContext.ATTR_USER;

import com.nimbusds.jwt.JWTClaimsSet;
import io.gravitee.common.http.HttpHeaders;
import io.gravitee.common.http.HttpStatusCode;
Expand All @@ -35,18 +38,14 @@
import io.gravitee.policy.jwt.resolver.*;
import io.gravitee.policy.jwt.token.TokenExtractor;
import io.vertx.core.Vertx;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;

import static io.gravitee.gateway.api.ExecutionContext.ATTR_API;
import static io.gravitee.gateway.api.ExecutionContext.ATTR_USER;

/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author GraviteeSource Team
Expand Down Expand Up @@ -100,74 +99,79 @@ public void onRequest(Request request, Response response, ExecutionContext execu

// 2_ Validate the token algorithm + signature
validate(executionContext, jwt)
.whenComplete((claims, throwable) -> {
final String api = String.valueOf(executionContext.getAttribute(ATTR_API));
MDC.put("api", api);
if (throwable != null) {
if (throwable.getCause() instanceof InvalidTokenException) {
LOGGER.debug(String.format(errorMessageFormat, api, request.id(), request.path(), throwable.getMessage()), throwable.getCause());
request.metrics().setMessage(throwable.getCause().getCause().getMessage());
.whenComplete((claims, throwable) -> {
final String api = String.valueOf(executionContext.getAttribute(ATTR_API));
MDC.put("api", api);
if (throwable != null) {
if (throwable.getCause() instanceof InvalidTokenException) {
LOGGER.debug(
String.format(errorMessageFormat, api, request.id(), request.path(), throwable.getMessage()),
throwable.getCause()
);
request.metrics().setMessage(throwable.getCause().getCause().getMessage());
} else {
LOGGER.error(
String.format(errorMessageFormat, api, request.id(), request.path(), throwable.getMessage()),
throwable.getCause()
);
request.metrics().setMessage(throwable.getCause().getMessage());
}
MDC.remove("api");
policyChain.failWith(
PolicyResult.failure(JWT_INVALID_TOKEN_KEY, HttpStatusCode.UNAUTHORIZED_401, UNAUTHORIZED_MESSAGE)
);
} else {
try {
// 3_ Set access_token in context
executionContext.setAttribute(CONTEXT_ATTRIBUTE_JWT_TOKEN, jwt);

String clientId = getClientId(claims);
executionContext.setAttribute(CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, clientId);

final String user;
if (configuration.getUserClaim() != null && !configuration.getUserClaim().isEmpty()) {
user = (String) claims.getClaim(configuration.getUserClaim());
} else {
LOGGER.error(String.format(errorMessageFormat, api, request.id(), request.path(), throwable.getMessage()), throwable.getCause());
request.metrics().setMessage(throwable.getCause().getMessage());
user = claims.getSubject();
}
MDC.remove("api");
policyChain.failWith(PolicyResult.failure(
JWT_INVALID_TOKEN_KEY,
HttpStatusCode.UNAUTHORIZED_401,
UNAUTHORIZED_MESSAGE));
}
else {
try {
// 3_ Set access_token in context
executionContext.setAttribute(CONTEXT_ATTRIBUTE_JWT_TOKEN, jwt);

String clientId = getClientId(claims);
executionContext.setAttribute(CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, clientId);

final String user;
if (configuration.getUserClaim() != null && !configuration.getUserClaim().isEmpty()) {
user = (String) claims.getClaim(configuration.getUserClaim());
} else {
user = claims.getSubject();
}
executionContext.setAttribute(ATTR_USER, user);
request.metrics().setUser(user);
executionContext.setAttribute(ATTR_USER, user);
request.metrics().setUser(user);

if (configuration.isExtractClaims()) {
executionContext.setAttribute(CONTEXT_ATTRIBUTE_JWT_CLAIMS, claims.getClaims());
}

if (!configuration.isPropagateAuthHeader()) {
request.headers().remove(HttpHeaders.AUTHORIZATION);
}
if (configuration.isExtractClaims()) {
executionContext.setAttribute(CONTEXT_ATTRIBUTE_JWT_CLAIMS, claims.getClaims());
}

// Finally continue the process...
policyChain.doNext(request, response);
} catch (Exception e) {
LOGGER.error(String.format(errorMessageFormat, api, request.id(), request.path(), e.getMessage()), e.getCause());
policyChain.failWith(PolicyResult.failure(
JWT_INVALID_TOKEN_KEY,
HttpStatusCode.UNAUTHORIZED_401,
UNAUTHORIZED_MESSAGE));
} finally {
MDC.remove("api");
if (!configuration.isPropagateAuthHeader()) {
request.headers().remove(HttpHeaders.AUTHORIZATION);
}

// Finally continue the process...
policyChain.doNext(request, response);
} catch (Exception e) {
LOGGER.error(
String.format(errorMessageFormat, api, request.id(), request.path(), e.getMessage()),
e.getCause()
);
policyChain.failWith(
PolicyResult.failure(JWT_INVALID_TOKEN_KEY, HttpStatusCode.UNAUTHORIZED_401, UNAUTHORIZED_MESSAGE)
);
} finally {
MDC.remove("api");
}
});
}
});
} catch (Exception e) {
MDC.put("api", String.valueOf(executionContext.getAttribute(ATTR_API)));
LOGGER.error(String.format(errorMessageFormat, executionContext.getAttribute(ATTR_API), request.id(), request.path(), e.getMessage()), e.getCause());
LOGGER.error(
String.format(errorMessageFormat, executionContext.getAttribute(ATTR_API), request.id(), request.path(), e.getMessage()),
e.getCause()
);
MDC.remove("api");
policyChain.failWith(PolicyResult.failure(
JWT_MISSING_TOKEN_KEY,
HttpStatusCode.UNAUTHORIZED_401,
UNAUTHORIZED_MESSAGE));
policyChain.failWith(PolicyResult.failure(JWT_MISSING_TOKEN_KEY, HttpStatusCode.UNAUTHORIZED_401, UNAUTHORIZED_MESSAGE));
}
}

private String getClientId(JWTClaimsSet claims) {

if (!StringUtils.isEmpty(configuration.getClientIdClaim())) {
Object clientIdClaim = claims.getClaim(configuration.getClientIdClaim());
return extractClientId(clientIdClaim);
Expand All @@ -177,7 +181,7 @@ private String getClientId(JWTClaimsSet claims) {

// Look for the OAuth2 client_id of the Relying Party from the Authorized party claim
String authorizedParty = (String) claims.getClaim(CONTEXT_ATTRIBUTE_AUTHORIZED_PARTY);
if (authorizedParty != null && ! authorizedParty.isEmpty()) {
if (authorizedParty != null && !authorizedParty.isEmpty()) {
clientId = authorizedParty;
}

Expand Down Expand Up @@ -217,14 +221,14 @@ private CompletableFuture<JWTClaimsSet> validate(ExecutionContext executionConte
SignatureKeyResolver signatureKeyResolver;
switch (configuration.getPublicKeyResolver()) {
case GIVEN_KEY:
signatureKeyResolver = new TemplatableSignatureKeyResolver(
signatureKeyResolver =
new TemplatableSignatureKeyResolver(
executionContext.getTemplateEngine(),
new UserDefinedSignatureKeyResolver(configuration.getResolverParameter()));
new UserDefinedSignatureKeyResolver(configuration.getResolverParameter())
);
break;
case GATEWAY_KEYS:
signatureKeyResolver = new GatewaySignatureKeyResolver(
executionContext.getComponent(Environment.class),
token);
signatureKeyResolver = new GatewaySignatureKeyResolver(executionContext.getComponent(Environment.class), token);
break;
default:
throw new IllegalArgumentException("Unexpected signature key resolver");
Expand Down Expand Up @@ -252,9 +256,17 @@ private CompletableFuture<JWTClaimsSet> validate(ExecutionContext executionConte
}
} else {
keyProcessor = new JWKSKeyProcessor();
keyProcessor.setJwkSourceResolver(new URLJWKSourceResolver(
executionContext.getTemplateEngine(), configuration.getResolverParameter(),
new VertxResourceRetriever(executionContext.getComponent(Vertx.class), executionContext.getComponent(Environment.class), configuration.isUseSystemProxy())));
keyProcessor.setJwkSourceResolver(
new URLJWKSourceResolver(
executionContext.getTemplateEngine(),
configuration.getResolverParameter(),
new VertxResourceRetriever(
executionContext.getComponent(Vertx.class),
executionContext.getComponent(Environment.class),
configuration.isUseSystemProxy()
)
)
);
}

return keyProcessor.process(signature, token);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class JWTPolicyConfiguration implements PolicyConfiguration {
private String userClaim;
private String clientIdClaim;
private boolean useSystemProxy;

//getter and setters
public KeyResolver getPublicKeyResolver() {
return publicKeyResolver;
Expand All @@ -44,11 +44,11 @@ public KeyResolver getPublicKeyResolver() {
public void setPublicKeyResolver(KeyResolver publicKeyResolver) {
this.publicKeyResolver = publicKeyResolver;
}

public String getResolverParameter() {
return resolverParameter;
}

public void setResolverParameter(String givenKey) {
this.resolverParameter = givenKey;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
* @author Guillaume Gillon (guillaume.gillon at outlook.com)
*/
public class AuthorizationSchemeException extends Exception {

public AuthorizationSchemeException(String message) {
super(message);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
package io.gravitee.policy.jwt.jwks;

import com.nimbusds.jose.jwk.source.JWKSource;

import java.time.LocalDateTime;

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,12 @@

import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;

import java.util.concurrent.CompletableFuture;

/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author GraviteeSource Team
*/
public interface JWKSourceResolver<C extends SecurityContext> {

CompletableFuture<JWKSource<C>> resolve();
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,15 @@
import com.nimbusds.jose.util.Resource;
import io.gravitee.el.TemplateEngine;
import io.gravitee.policy.jwt.jwks.retriever.ResourceRetriever;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* @author David BRASSELY (david.brassely at graviteesource.com)
Expand All @@ -45,16 +44,16 @@ public class URLJWKSourceResolver<C extends SecurityContext> implements JWKSourc
private final URL jwksUrl;
private final ResourceRetriever resourceRetriever;

final static ConcurrentHashMap<String, CachedJWKSource> cache = new ConcurrentHashMap<>();
static final ConcurrentHashMap<String, CachedJWKSource> cache = new ConcurrentHashMap<>();

public URLJWKSourceResolver(TemplateEngine templateEngine, String url, ResourceRetriever resourceRetriever) throws MalformedURLException {
public URLJWKSourceResolver(TemplateEngine templateEngine, String url, ResourceRetriever resourceRetriever)
throws MalformedURLException {
this.jwksUrl = new URL(templateEngine.getValue(url, String.class));
this.resourceRetriever = resourceRetriever;
}

@Override
public CompletableFuture<JWKSource<C>> resolve() {

CachedJWKSource cachedJWKSource = cache.get(jwksUrl.toString());
if (cachedJWKSource != null && !isCacheExpired(cachedJWKSource)) {
return CompletableFuture.completedFuture(cachedJWKSource.getJwkSource());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import com.nimbusds.jose.proc.SecurityContext;
import io.gravitee.policy.jwt.jwks.JWKSourceResolver;
import io.gravitee.policy.jwt.resolver.SignatureKeyResolver;

import java.util.concurrent.CompletableFuture;

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@
package io.gravitee.policy.jwt.jwks.retriever;

import com.nimbusds.jose.util.Resource;

import java.net.URL;
import java.util.concurrent.CompletableFuture;

public interface ResourceRetriever {

CompletableFuture<Resource> retrieve(URL url);
}
Loading

0 comments on commit 4a0180d

Please sign in to comment.