From 4a0180d8e6a18952bce59c81c27e0453a4d57b9c Mon Sep 17 00:00:00 2001 From: Thibaud Av Date: Fri, 21 Jan 2022 14:15:30 +0100 Subject: [PATCH] style: setup & apply prettier --- .prettierrc | 2 + pom.xml | 17 ++ .../io/gravitee/policy/jwt/JWTPolicy.java | 152 ++++++------ .../configuration/JWTPolicyConfiguration.java | 6 +- .../AuthorizationSchemeException.java | 1 + .../policy/jwt/jwks/CachedJWKSource.java | 1 - .../policy/jwt/jwks/JWKSourceResolver.java | 2 - .../policy/jwt/jwks/URLJWKSourceResolver.java | 11 +- .../jwt/jwks/hmac/MACJWKSourceResolver.java | 1 - .../jwt/jwks/retriever/ResourceRetriever.java | 2 - .../retriever/VertxResourceRetriever.java | 38 +-- .../jwt/jwks/rsa/RSAJWKSourceResolver.java | 1 - .../policy/jwt/key/PublicKeyHelper.java | 9 +- .../jwt/processor/AbstractKeyProcessor.java | 26 +- .../jwt/processor/HMACKeyProcessor.java | 11 +- .../policy/jwt/processor/KeyProcessor.java | 2 - .../processor/NoAlgorithmRSAKeyProcessor.java | 22 +- .../policy/jwt/processor/RSAKeyProcessor.java | 18 +- .../resolver/GatewaySignatureKeyResolver.java | 5 +- .../policy/jwt/resolver/KeyResolver.java | 2 +- .../jwt/resolver/SignatureKeyResolver.java | 1 - .../TemplatableSignatureKeyResolver.java | 1 - .../policy/jwt/token/TokenExtractor.java | 11 +- .../policy/jwt/HMACJWTPolicyTest.java | 2 - .../io/gravitee/policy/jwt/JWTPolicyTest.java | 229 +++++++++--------- .../jwt/RSACertificateJWTPolicyTest.java | 6 +- .../policy/jwt/RSAKeyJWTPolicyTest.java | 7 +- .../policy/jwt/RSAPublicKeyJWTPolicyTest.java | 7 +- .../io/gravitee/policy/jwt/TestNimbus.java | 9 +- .../jwt/jwks/URLJWKSourceResolverTest.java | 13 +- .../policy/jwt/key/PublicKeyHelperTest.java | 19 +- .../policy/jwt/token/TokenExtractorTest.java | 16 +- 32 files changed, 329 insertions(+), 321 deletions(-) create mode 100644 .prettierrc diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000..aa85a8f4 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,2 @@ +printWidth: 140 +tabWidth: 4 diff --git a/pom.xml b/pom.xml index 3ef9a37c..f7207240 100644 --- a/pom.xml +++ b/pom.xml @@ -201,6 +201,23 @@ 8 + + com.hubspot.maven.plugins + prettier-maven-plugin + 0.17 + + 12.13.0 + 1.6.1 + + + + validate + + check + + + + diff --git a/src/main/java/io/gravitee/policy/jwt/JWTPolicy.java b/src/main/java/io/gravitee/policy/jwt/JWTPolicy.java index 52f97507..a71747ae 100644 --- a/src/main/java/io/gravitee/policy/jwt/JWTPolicy.java +++ b/src/main/java/io/gravitee/policy/jwt/JWTPolicy.java @@ -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; @@ -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 @@ -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); @@ -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; } @@ -217,14 +221,14 @@ private CompletableFuture 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"); @@ -252,9 +256,17 @@ private CompletableFuture 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); diff --git a/src/main/java/io/gravitee/policy/jwt/configuration/JWTPolicyConfiguration.java b/src/main/java/io/gravitee/policy/jwt/configuration/JWTPolicyConfiguration.java index 3c593200..97f5d808 100644 --- a/src/main/java/io/gravitee/policy/jwt/configuration/JWTPolicyConfiguration.java +++ b/src/main/java/io/gravitee/policy/jwt/configuration/JWTPolicyConfiguration.java @@ -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; @@ -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; } diff --git a/src/main/java/io/gravitee/policy/jwt/exceptions/AuthorizationSchemeException.java b/src/main/java/io/gravitee/policy/jwt/exceptions/AuthorizationSchemeException.java index b584d729..27252a3d 100644 --- a/src/main/java/io/gravitee/policy/jwt/exceptions/AuthorizationSchemeException.java +++ b/src/main/java/io/gravitee/policy/jwt/exceptions/AuthorizationSchemeException.java @@ -19,6 +19,7 @@ * @author Guillaume Gillon (guillaume.gillon at outlook.com) */ public class AuthorizationSchemeException extends Exception { + public AuthorizationSchemeException(String message) { super(message); } diff --git a/src/main/java/io/gravitee/policy/jwt/jwks/CachedJWKSource.java b/src/main/java/io/gravitee/policy/jwt/jwks/CachedJWKSource.java index 73b5210d..b8a81cdb 100644 --- a/src/main/java/io/gravitee/policy/jwt/jwks/CachedJWKSource.java +++ b/src/main/java/io/gravitee/policy/jwt/jwks/CachedJWKSource.java @@ -16,7 +16,6 @@ package io.gravitee.policy.jwt.jwks; import com.nimbusds.jose.jwk.source.JWKSource; - import java.time.LocalDateTime; /** diff --git a/src/main/java/io/gravitee/policy/jwt/jwks/JWKSourceResolver.java b/src/main/java/io/gravitee/policy/jwt/jwks/JWKSourceResolver.java index bac0f224..bfa98519 100644 --- a/src/main/java/io/gravitee/policy/jwt/jwks/JWKSourceResolver.java +++ b/src/main/java/io/gravitee/policy/jwt/jwks/JWKSourceResolver.java @@ -17,7 +17,6 @@ import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.SecurityContext; - import java.util.concurrent.CompletableFuture; /** @@ -25,6 +24,5 @@ * @author GraviteeSource Team */ public interface JWKSourceResolver { - CompletableFuture> resolve(); } diff --git a/src/main/java/io/gravitee/policy/jwt/jwks/URLJWKSourceResolver.java b/src/main/java/io/gravitee/policy/jwt/jwks/URLJWKSourceResolver.java index f1691add..45eb4cba 100644 --- a/src/main/java/io/gravitee/policy/jwt/jwks/URLJWKSourceResolver.java +++ b/src/main/java/io/gravitee/policy/jwt/jwks/URLJWKSourceResolver.java @@ -22,9 +22,6 @@ 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; @@ -32,6 +29,8 @@ 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) @@ -45,16 +44,16 @@ public class URLJWKSourceResolver implements JWKSourc private final URL jwksUrl; private final ResourceRetriever resourceRetriever; - final static ConcurrentHashMap cache = new ConcurrentHashMap<>(); + static final ConcurrentHashMap 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> resolve() { - CachedJWKSource cachedJWKSource = cache.get(jwksUrl.toString()); if (cachedJWKSource != null && !isCacheExpired(cachedJWKSource)) { return CompletableFuture.completedFuture(cachedJWKSource.getJwkSource()); diff --git a/src/main/java/io/gravitee/policy/jwt/jwks/hmac/MACJWKSourceResolver.java b/src/main/java/io/gravitee/policy/jwt/jwks/hmac/MACJWKSourceResolver.java index b94ac533..7879bfcd 100644 --- a/src/main/java/io/gravitee/policy/jwt/jwks/hmac/MACJWKSourceResolver.java +++ b/src/main/java/io/gravitee/policy/jwt/jwks/hmac/MACJWKSourceResolver.java @@ -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; /** diff --git a/src/main/java/io/gravitee/policy/jwt/jwks/retriever/ResourceRetriever.java b/src/main/java/io/gravitee/policy/jwt/jwks/retriever/ResourceRetriever.java index 231a7896..65325cc2 100644 --- a/src/main/java/io/gravitee/policy/jwt/jwks/retriever/ResourceRetriever.java +++ b/src/main/java/io/gravitee/policy/jwt/jwks/retriever/ResourceRetriever.java @@ -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 retrieve(URL url); } diff --git a/src/main/java/io/gravitee/policy/jwt/jwks/retriever/VertxResourceRetriever.java b/src/main/java/io/gravitee/policy/jwt/jwks/retriever/VertxResourceRetriever.java index 9327d2fd..9776d25c 100644 --- a/src/main/java/io/gravitee/policy/jwt/jwks/retriever/VertxResourceRetriever.java +++ b/src/main/java/io/gravitee/policy/jwt/jwks/retriever/VertxResourceRetriever.java @@ -24,13 +24,12 @@ import io.vertx.core.http.*; import io.vertx.core.net.ProxyOptions; import io.vertx.core.net.ProxyType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.env.Environment; - import java.net.URL; import java.util.Objects; import java.util.concurrent.CompletableFuture; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; /** * @author David BRASSELY (david.brassely at graviteesource.com) @@ -53,8 +52,7 @@ public VertxResourceRetriever(final Vertx vertx, Environment environment, boolea @Override public CompletableFuture retrieve(URL url) { - HttpClientOptions options = new HttpClientOptions() - .setConnectTimeout(2000); + HttpClientOptions options = new HttpClientOptions().setConnectTimeout(2000); if (useSystemProxy) { options.setProxyOptions(getSystemProxyOptions(url)); @@ -69,18 +67,20 @@ public CompletableFuture retrieve(URL url) { Promise promise = Promise.promise(); final RequestOptions requestOptions = new RequestOptions() - .setMethod(HttpMethod.GET) - .setAbsoluteURI(url.toString()) - .setTimeout(2000L); + .setMethod(HttpMethod.GET) + .setAbsoluteURI(url.toString()) + .setTimeout(2000L); final Future futureRequest = httpClient.request(requestOptions); futureRequest - .onFailure(throwable -> handleFailure(httpClient, promise, throwable)) - .onSuccess(httpRequest -> - httpRequest.send() - .onFailure(throwable -> handleFailure(httpClient, promise, throwable)) - .onSuccess(httpResponse -> handleSuccess(httpClient, promise, httpResponse))); + .onFailure(throwable -> handleFailure(httpClient, promise, throwable)) + .onSuccess(httpRequest -> + httpRequest + .send() + .onFailure(throwable -> handleFailure(httpClient, promise, throwable)) + .onSuccess(httpResponse -> handleSuccess(httpClient, promise, httpResponse)) + ); return promise.future().toCompletionStage().toCompletableFuture(); } @@ -88,8 +88,7 @@ public CompletableFuture retrieve(URL url) { private void handleSuccess(HttpClient httpClient, Promise promise, HttpClientResponse httpResponse) { if (httpResponse.statusCode() >= 200 && httpResponse.statusCode() <= 299) { httpResponse.bodyHandler(body -> { - promise.complete(new Resource(body.toString(), - httpResponse.getHeader(io.gravitee.common.http.HttpHeaders.CONTENT_TYPE))); + promise.complete(new Resource(body.toString(), httpResponse.getHeader(io.gravitee.common.http.HttpHeaders.CONTENT_TYPE))); httpClient.close(); }); } else { @@ -105,7 +104,6 @@ private void handleFailure(HttpClient httpClient, Promise promise, Thr } private ProxyOptions getSystemProxyOptions(URL url) { - StringBuilder errors = new StringBuilder(); ProxyOptions proxyOptions = new ProxyOptions(); @@ -134,7 +132,11 @@ private ProxyOptions getSystemProxyOptions(URL url) { if (errors.length() == 0) { return proxyOptions; } else { - LOGGER.warn("JWTPlugin requires a system proxy to be defined to retrieve resource [{}] but some configurations are missing or not well defined: {}", url.toString(), errors); + LOGGER.warn( + "JWTPlugin requires a system proxy to be defined to retrieve resource [{}] but some configurations are missing or not well defined: {}", + url.toString(), + errors + ); LOGGER.warn("Ignoring system proxy"); return null; } diff --git a/src/main/java/io/gravitee/policy/jwt/jwks/rsa/RSAJWKSourceResolver.java b/src/main/java/io/gravitee/policy/jwt/jwks/rsa/RSAJWKSourceResolver.java index 5bcf4cb1..aa2bdb71 100644 --- a/src/main/java/io/gravitee/policy/jwt/jwks/rsa/RSAJWKSourceResolver.java +++ b/src/main/java/io/gravitee/policy/jwt/jwks/rsa/RSAJWKSourceResolver.java @@ -25,7 +25,6 @@ import io.gravitee.policy.jwt.jwks.JWKSourceResolver; import io.gravitee.policy.jwt.key.PublicKeyHelper; import io.gravitee.policy.jwt.resolver.SignatureKeyResolver; - import java.security.interfaces.RSAPublicKey; import java.util.concurrent.CompletableFuture; diff --git a/src/main/java/io/gravitee/policy/jwt/key/PublicKeyHelper.java b/src/main/java/io/gravitee/policy/jwt/key/PublicKeyHelper.java index ecd2f3f6..1fbaaecb 100644 --- a/src/main/java/io/gravitee/policy/jwt/key/PublicKeyHelper.java +++ b/src/main/java/io/gravitee/policy/jwt/key/PublicKeyHelper.java @@ -36,7 +36,7 @@ public final class PublicKeyHelper { private static final Pattern SSH_PUB_KEY = Pattern.compile("(ssh-(rsa|dsa) )?([A-Za-z0-9/+]+=*) ?(.*)"); - private static final byte[] PREFIX = new byte[] {0,0,0,7, 's','s','h','-','r','s','a'}; + private static final byte[] PREFIX = new byte[] { 0, 0, 0, 7, 's', 's', 'h', '-', 'r', 's', 'a' }; private static final String SSH_RSA_ALG = "ssh-rsa"; @@ -81,8 +81,8 @@ private static RSAPublicKey parseSSHPublicKey(String encKey) { throw new IllegalArgumentException("SSH key prefix not found"); } - BigInteger e = new BigInteger(readBigInteger(in));//public exponent - BigInteger n = new BigInteger(readBigInteger(in));//modulus + BigInteger e = new BigInteger(readBigInteger(in)); //public exponent + BigInteger n = new BigInteger(readBigInteger(in)); //modulus return createPublicKey(n, e); } catch (IOException e) { @@ -93,8 +93,7 @@ private static RSAPublicKey parseSSHPublicKey(String encKey) { private static RSAPublicKey createPublicKey(BigInteger n, BigInteger e) { try { return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(n, e)); - } - catch (Exception ex) { + } catch (Exception ex) { throw new RuntimeException(ex); } } diff --git a/src/main/java/io/gravitee/policy/jwt/processor/AbstractKeyProcessor.java b/src/main/java/io/gravitee/policy/jwt/processor/AbstractKeyProcessor.java index 1967dc89..eea5cf85 100644 --- a/src/main/java/io/gravitee/policy/jwt/processor/AbstractKeyProcessor.java +++ b/src/main/java/io/gravitee/policy/jwt/processor/AbstractKeyProcessor.java @@ -25,7 +25,6 @@ import io.gravitee.policy.jwt.alg.Signature; import io.gravitee.policy.jwt.exceptions.InvalidTokenException; import io.gravitee.policy.jwt.jwks.JWKSourceResolver; - import java.util.concurrent.CompletableFuture; /** @@ -36,7 +35,7 @@ public abstract class AbstractKeyProcessor implements private JWKSourceResolver jwkSourceResolver; - private final static DefaultJWTClaimsVerifier claimsVerifier = new DefaultJWTClaimsVerifier<>(); + private static final DefaultJWTClaimsVerifier claimsVerifier = new DefaultJWTClaimsVerifier<>(); // To ensure compatibility with previous version of JWT policy. // TODO: should be configurable from policy configuration. @@ -47,19 +46,18 @@ public abstract class AbstractKeyProcessor implements @Override public CompletableFuture process(Signature signature, String token) { return jwkSourceResolver - .resolve() - .thenCompose(jwkSource -> { - ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor<>(); - jwtProcessor.setJWTClaimsSetVerifier(claimsVerifier); - jwtProcessor.setJWSKeySelector(jwsKeySelector(jwkSource, signature)); + .resolve() + .thenCompose(jwkSource -> { + ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor<>(); + jwtProcessor.setJWTClaimsSetVerifier(claimsVerifier); + jwtProcessor.setJWSKeySelector(jwsKeySelector(jwkSource, signature)); - try { - return CompletableFuture.completedFuture( - jwtProcessor.process(token, null)); - } catch (Exception ex) { - throw new InvalidTokenException(ex); - } - }); + try { + return CompletableFuture.completedFuture(jwtProcessor.process(token, null)); + } catch (Exception ex) { + throw new InvalidTokenException(ex); + } + }); } public void setJwkSourceResolver(JWKSourceResolver jwkSourceResolver) { diff --git a/src/main/java/io/gravitee/policy/jwt/processor/HMACKeyProcessor.java b/src/main/java/io/gravitee/policy/jwt/processor/HMACKeyProcessor.java index 544ee29b..01a0de4f 100644 --- a/src/main/java/io/gravitee/policy/jwt/processor/HMACKeyProcessor.java +++ b/src/main/java/io/gravitee/policy/jwt/processor/HMACKeyProcessor.java @@ -36,17 +36,16 @@ JWSKeySelector jwsKeySelector(JWKSource jwkSource, Signature signature) { return new JWSVerificationKeySelector(signature.getAlg(), jwkSource) { @Override protected JWKMatcher createJWKMatcher(final JWSHeader jwsHeader) { - - if (! getExpectedJWSAlgorithm().equals(jwsHeader.getAlgorithm())) { + if (!getExpectedJWSAlgorithm().equals(jwsHeader.getAlgorithm())) { // Unexpected JWS alg return null; } else if (JWSAlgorithm.Family.HMAC_SHA.contains(getExpectedJWSAlgorithm())) { // HMAC secret matcher return new JWKMatcher.Builder() - .keyType(KeyType.forAlgorithm(getExpectedJWSAlgorithm())) - .privateOnly(true) - .algorithms(getExpectedJWSAlgorithm(), null) - .build(); + .keyType(KeyType.forAlgorithm(getExpectedJWSAlgorithm())) + .privateOnly(true) + .algorithms(getExpectedJWSAlgorithm(), null) + .build(); } else { return null; // Unsupported algorithm } diff --git a/src/main/java/io/gravitee/policy/jwt/processor/KeyProcessor.java b/src/main/java/io/gravitee/policy/jwt/processor/KeyProcessor.java index 4435fa3f..a0508ba7 100644 --- a/src/main/java/io/gravitee/policy/jwt/processor/KeyProcessor.java +++ b/src/main/java/io/gravitee/policy/jwt/processor/KeyProcessor.java @@ -17,7 +17,6 @@ import com.nimbusds.jwt.JWTClaimsSet; import io.gravitee.policy.jwt.alg.Signature; - import java.util.concurrent.CompletableFuture; /** @@ -25,6 +24,5 @@ * @author GraviteeSource Team */ public interface KeyProcessor { - CompletableFuture process(Signature signature, String token); } diff --git a/src/main/java/io/gravitee/policy/jwt/processor/NoAlgorithmRSAKeyProcessor.java b/src/main/java/io/gravitee/policy/jwt/processor/NoAlgorithmRSAKeyProcessor.java index 8595a826..0e02c517 100644 --- a/src/main/java/io/gravitee/policy/jwt/processor/NoAlgorithmRSAKeyProcessor.java +++ b/src/main/java/io/gravitee/policy/jwt/processor/NoAlgorithmRSAKeyProcessor.java @@ -24,13 +24,12 @@ import com.nimbusds.jose.proc.JWSVerificationKeySelector; import com.nimbusds.jose.proc.SecurityContext; import io.gravitee.policy.jwt.alg.Signature; - -import javax.crypto.SecretKey; import java.security.Key; import java.security.PublicKey; import java.util.Collections; import java.util.LinkedList; import java.util.List; +import javax.crypto.SecretKey; /** * @author David BRASSELY (david.brassely at graviteesource.com) @@ -44,22 +43,23 @@ JWSKeySelector jwsKeySelector(JWKSource jwkSource, Signature signature) { return new JWSVerificationKeySelector(Signature.RSA_RS256.getAlg(), jwkSource) { @Override protected JWKMatcher createJWKMatcher(final JWSHeader jwsHeader) { - if (JWSAlgorithm.Family.RSA.contains(jwsHeader.getAlgorithm()) || JWSAlgorithm.Family.EC.contains(jwsHeader.getAlgorithm())) { + if ( + JWSAlgorithm.Family.RSA.contains(jwsHeader.getAlgorithm()) || JWSAlgorithm.Family.EC.contains(jwsHeader.getAlgorithm()) + ) { // RSA or EC key matcher return new JWKMatcher.Builder() - .keyType(KeyType.forAlgorithm(jwsHeader.getAlgorithm())) - .keyUses(KeyUse.SIGNATURE, null) - .algorithms(jwsHeader.getAlgorithm(), null) - .x509CertSHA256Thumbprint(jwsHeader.getX509CertSHA256Thumbprint()) - .build(); + .keyType(KeyType.forAlgorithm(jwsHeader.getAlgorithm())) + .keyUses(KeyUse.SIGNATURE, null) + .algorithms(jwsHeader.getAlgorithm(), null) + .x509CertSHA256Thumbprint(jwsHeader.getX509CertSHA256Thumbprint()) + .build(); } else { return null; // Unsupported algorithm } } @Override - public List selectJWSKeys(final JWSHeader jwsHeader, final C context) - throws KeySourceException { + public List selectJWSKeys(final JWSHeader jwsHeader, final C context) throws KeySourceException { JWKMatcher jwkMatcher = createJWKMatcher(jwsHeader); if (jwkMatcher == null) { return Collections.emptyList(); @@ -69,7 +69,7 @@ public List selectJWSKeys(final JWSHeader jwsHeader, final C context) List sanitizedKeyList = new LinkedList<>(); - for (Key key: KeyConverter.toJavaKeys(jwkMatches)) { + for (Key key : KeyConverter.toJavaKeys(jwkMatches)) { if (key instanceof PublicKey || key instanceof SecretKey) { sanitizedKeyList.add(key); } // skip asymmetric private keys diff --git a/src/main/java/io/gravitee/policy/jwt/processor/RSAKeyProcessor.java b/src/main/java/io/gravitee/policy/jwt/processor/RSAKeyProcessor.java index e1390f3e..5f2ad86b 100644 --- a/src/main/java/io/gravitee/policy/jwt/processor/RSAKeyProcessor.java +++ b/src/main/java/io/gravitee/policy/jwt/processor/RSAKeyProcessor.java @@ -37,18 +37,20 @@ JWSKeySelector jwsKeySelector(JWKSource jwkSource, Signature signature) { return new JWSVerificationKeySelector(signature.getAlg(), jwkSource) { @Override protected JWKMatcher createJWKMatcher(final JWSHeader jwsHeader) { - - if (! getExpectedJWSAlgorithm().equals(jwsHeader.getAlgorithm())) { + if (!getExpectedJWSAlgorithm().equals(jwsHeader.getAlgorithm())) { // Unexpected JWS alg return null; - } else if (JWSAlgorithm.Family.RSA.contains(getExpectedJWSAlgorithm()) || JWSAlgorithm.Family.EC.contains(getExpectedJWSAlgorithm())) { + } else if ( + JWSAlgorithm.Family.RSA.contains(getExpectedJWSAlgorithm()) || + JWSAlgorithm.Family.EC.contains(getExpectedJWSAlgorithm()) + ) { // RSA or EC key matcher return new JWKMatcher.Builder() - .keyType(KeyType.forAlgorithm(getExpectedJWSAlgorithm())) - .keyUses(KeyUse.SIGNATURE, null) - .algorithms(getExpectedJWSAlgorithm(), null) - .x509CertSHA256Thumbprint(jwsHeader.getX509CertSHA256Thumbprint()) - .build(); + .keyType(KeyType.forAlgorithm(getExpectedJWSAlgorithm())) + .keyUses(KeyUse.SIGNATURE, null) + .algorithms(getExpectedJWSAlgorithm(), null) + .x509CertSHA256Thumbprint(jwsHeader.getX509CertSHA256Thumbprint()) + .build(); } else { return null; // Unsupported algorithm } diff --git a/src/main/java/io/gravitee/policy/jwt/resolver/GatewaySignatureKeyResolver.java b/src/main/java/io/gravitee/policy/jwt/resolver/GatewaySignatureKeyResolver.java index c6a12075..db0ec0a2 100644 --- a/src/main/java/io/gravitee/policy/jwt/resolver/GatewaySignatureKeyResolver.java +++ b/src/main/java/io/gravitee/policy/jwt/resolver/GatewaySignatureKeyResolver.java @@ -18,12 +18,11 @@ import com.nimbusds.jose.JWSHeader; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTParser; +import java.text.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; -import java.text.ParseException; - /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team @@ -49,7 +48,7 @@ public String resolve() { final JWT jwt = JWTParser.parse(token); final String iss = jwt.getJWTClaimsSet().getIssuer(); - String keyId = ((JWSHeader)jwt.getHeader()).getKeyID(); + String keyId = ((JWSHeader) jwt.getHeader()).getKeyID(); if (keyId == null || keyId.isEmpty()) { keyId = DEFAULT_KID; diff --git a/src/main/java/io/gravitee/policy/jwt/resolver/KeyResolver.java b/src/main/java/io/gravitee/policy/jwt/resolver/KeyResolver.java index 92d6d031..e506e781 100644 --- a/src/main/java/io/gravitee/policy/jwt/resolver/KeyResolver.java +++ b/src/main/java/io/gravitee/policy/jwt/resolver/KeyResolver.java @@ -23,5 +23,5 @@ public enum KeyResolver { GIVEN_KEY, GATEWAY_KEYS, - JWKS_URL + JWKS_URL, } diff --git a/src/main/java/io/gravitee/policy/jwt/resolver/SignatureKeyResolver.java b/src/main/java/io/gravitee/policy/jwt/resolver/SignatureKeyResolver.java index 3e80de84..81cfc04c 100644 --- a/src/main/java/io/gravitee/policy/jwt/resolver/SignatureKeyResolver.java +++ b/src/main/java/io/gravitee/policy/jwt/resolver/SignatureKeyResolver.java @@ -20,6 +20,5 @@ * @author GraviteeSource Team */ public interface SignatureKeyResolver { - String resolve(); } diff --git a/src/main/java/io/gravitee/policy/jwt/resolver/TemplatableSignatureKeyResolver.java b/src/main/java/io/gravitee/policy/jwt/resolver/TemplatableSignatureKeyResolver.java index fd2538ec..7845f72e 100644 --- a/src/main/java/io/gravitee/policy/jwt/resolver/TemplatableSignatureKeyResolver.java +++ b/src/main/java/io/gravitee/policy/jwt/resolver/TemplatableSignatureKeyResolver.java @@ -15,7 +15,6 @@ */ package io.gravitee.policy.jwt.resolver; - import io.gravitee.el.TemplateEngine; /** diff --git a/src/main/java/io/gravitee/policy/jwt/token/TokenExtractor.java b/src/main/java/io/gravitee/policy/jwt/token/TokenExtractor.java index e429b862..2eee5ebc 100644 --- a/src/main/java/io/gravitee/policy/jwt/token/TokenExtractor.java +++ b/src/main/java/io/gravitee/policy/jwt/token/TokenExtractor.java @@ -18,10 +18,9 @@ import io.gravitee.gateway.api.Request; import io.gravitee.gateway.api.http.HttpHeaderNames; import io.gravitee.policy.jwt.exceptions.AuthorizationSchemeException; -import org.springframework.util.StringUtils; - import java.util.List; import java.util.Optional; +import org.springframework.util.StringUtils; /** * @author David BRASSELY (david.brassely at graviteesource.com) @@ -44,12 +43,12 @@ public static String extract(Request request) throws AuthorizationSchemeExceptio if (authorizationHeaders != null && !authorizationHeaders.isEmpty()) { Optional authorizationBearerHeader = authorizationHeaders - .stream() - .filter(h -> StringUtils.startsWithIgnoreCase(h, BEARER)) - .findFirst(); + .stream() + .filter(h -> StringUtils.startsWithIgnoreCase(h, BEARER)) + .findFirst(); if (authorizationBearerHeader.isPresent()) { String authToken = authorizationBearerHeader.get().substring(BEARER.length()).trim(); - if (! authToken.isEmpty()) { + if (!authToken.isEmpty()) { return authToken; } else { throw new AuthorizationSchemeException("Authorization scheme is not supported for JWT"); diff --git a/src/test/java/io/gravitee/policy/jwt/HMACJWTPolicyTest.java b/src/test/java/io/gravitee/policy/jwt/HMACJWTPolicyTest.java index f103ce8e..8e415b14 100644 --- a/src/test/java/io/gravitee/policy/jwt/HMACJWTPolicyTest.java +++ b/src/test/java/io/gravitee/policy/jwt/HMACJWTPolicyTest.java @@ -19,7 +19,6 @@ import com.nimbusds.jose.crypto.MACSigner; import com.nimbusds.jose.jwk.OctetSequenceKey; import io.gravitee.policy.jwt.alg.Signature; - import java.security.SecureRandom; /** @@ -49,7 +48,6 @@ protected JWSSigner getSigner() throws Exception { protected String getSignatureKey() throws Exception { return SECRET; } - /* @Test public void test_hmac256_with_given_key_and_valid_authorization_header() throws Exception { diff --git a/src/test/java/io/gravitee/policy/jwt/JWTPolicyTest.java b/src/test/java/io/gravitee/policy/jwt/JWTPolicyTest.java index ac4a2456..26b7013b 100644 --- a/src/test/java/io/gravitee/policy/jwt/JWTPolicyTest.java +++ b/src/test/java/io/gravitee/policy/jwt/JWTPolicyTest.java @@ -15,6 +15,9 @@ */ package io.gravitee.policy.jwt; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; + import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.JWSSigner; import com.nimbusds.jwt.JWTClaimsSet; @@ -33,20 +36,16 @@ import io.gravitee.policy.jwt.configuration.JWTPolicyConfiguration; import io.gravitee.policy.jwt.resolver.KeyResolver; import io.gravitee.reporter.api.http.Metrics; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.core.env.Environment; - import java.time.Instant; import java.util.Collections; import java.util.Date; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.core.env.Environment; /** * @author Alexandre FARIA (alexandre82.faria at gmail.com) @@ -60,19 +59,25 @@ public abstract class JWTPolicyTest { @Mock private ExecutionContext executionContext; + @Mock private Environment environment; + @Mock private Request request; + @Mock private Response response; + @Mock private PolicyChain policyChain; + @Mock private JWTPolicyConfiguration configuration; + @Mock TemplateEngine templateEngine; - + @Before public void init() { MockitoAnnotations.initMocks(this); @@ -86,9 +91,8 @@ public void test_with_gateway_keys_and_valid_authorization_header() throws Excep when(executionContext.getComponent(Environment.class)).thenReturn(environment); when(environment.getProperty("policy.jwt.issuer.gravitee.authorization.server.MAIN")).thenReturn(getSignatureKey()); - - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); @@ -104,8 +108,7 @@ public void test_with_gateway_keys_and_valid_lowercase_authorization_header() th when(executionContext.getComponent(Environment.class)).thenReturn(environment); when(environment.getProperty("policy.jwt.issuer.gravitee.authorization.server.MAIN")).thenReturn(getSignatureKey()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); @@ -124,15 +127,13 @@ public void test_get_client_with_client_id_claim() throws Exception { String jwt = sign(builder.build()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); executePolicy(configuration, request, response, executionContext, policyChain); - verify(executionContext, times(1)) - .setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id"); + verify(executionContext, times(1)).setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id"); verify(policyChain, times(1)).doNext(request, response); } @@ -147,17 +148,19 @@ public void test_unsigned_jwt() throws Exception { String jwt = sign(builder.build()); - jwt = jwt.substring(0, jwt.lastIndexOf('.')+1); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + jwt = jwt.substring(0, jwt.lastIndexOf('.') + 1); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); executePolicy(configuration, request, response, executionContext, policyChain); - verify(policyChain,times(1)).failWith(argThat( - result -> result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 - && JWTPolicy.JWT_INVALID_TOKEN_KEY.equals(result.key()))); + verify(policyChain, times(1)) + .failWith( + argThat(result -> + result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 && JWTPolicy.JWT_INVALID_TOKEN_KEY.equals(result.key()) + ) + ); verify(policyChain, never()).doNext(request, response); } @@ -172,15 +175,13 @@ public void test_get_client_with_aud_claim() throws Exception { String jwt = sign(builder.build()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); executePolicy(configuration, request, response, executionContext, policyChain); - verify(executionContext, times(1)) - .setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id-from-aud"); + verify(executionContext, times(1)).setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id-from-aud"); verify(policyChain, times(1)).doNext(request, response); } @@ -197,16 +198,14 @@ public void test_get_client_with_configuration() throws Exception { String jwt = sign(builder.build()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); when(configuration.getClientIdClaim()).thenReturn("configuration_client_id"); executePolicy(configuration, request, response, executionContext, policyChain); - verify(executionContext, times(1)) - .setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id-from-configuration"); + verify(executionContext, times(1)).setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id-from-configuration"); verify(policyChain, times(1)).doNext(request, response); } @@ -223,16 +222,14 @@ public void test_get_client_with_configuration_array() throws Exception { String jwt = sign(builder.build()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); when(configuration.getClientIdClaim()).thenReturn("configuration_client_id"); executePolicy(configuration, request, response, executionContext, policyChain); - verify(executionContext, times(1)) - .setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id-from-configuration"); + verify(executionContext, times(1)).setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id-from-configuration"); verify(policyChain, times(1)).doNext(request, response); } @@ -248,15 +245,13 @@ public void test_get_client_with_aud_array_claim() throws Exception { String jwt = sign(builder.build()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); executePolicy(configuration, request, response, executionContext, policyChain); - verify(executionContext, times(1)) - .setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id-from-aud"); + verify(executionContext, times(1)).setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id-from-aud"); verify(policyChain, times(1)).doNext(request, response); } @@ -272,15 +267,13 @@ public void test_get_client_with_azp_claim() throws Exception { String jwt = sign(builder.build()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); executePolicy(configuration, request, response, executionContext, policyChain); - verify(executionContext, times(1)) - .setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id-from-azp"); + verify(executionContext, times(1)).setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id-from-azp"); verify(policyChain, times(1)).doNext(request, response); } @@ -292,20 +285,18 @@ public void test_get_client_with_multiple_client_claims() throws Exception { JWTClaimsSet.Builder builder = getJsonWebTokenBuilder(7200); builder.claim(JWTPolicy.CONTEXT_ATTRIBUTE_CLIENT_ID, "my-client-id"); - builder.claim(JWTPolicy.CONTEXT_ATTRIBUTE_AUDIENCE, new String [] {"my-client-id-from-aud"}); + builder.claim(JWTPolicy.CONTEXT_ATTRIBUTE_AUDIENCE, new String[] { "my-client-id-from-aud" }); builder.claim(JWTPolicy.CONTEXT_ATTRIBUTE_AUTHORIZED_PARTY, "my-client-id-from-azp"); String jwt = sign(builder.build()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); executePolicy(configuration, request, response, executionContext, policyChain); - verify(executionContext, times(1)) - .setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id-from-azp"); + verify(executionContext, times(1)).setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, "my-client-id-from-azp"); verify(policyChain, times(1)).doNext(request, response); } @@ -319,15 +310,13 @@ public void test_get_client_without_client_claim() throws Exception { String jwt = sign(builder.build()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); executePolicy(configuration, request, response, executionContext, policyChain); - verify(executionContext, times(1)) - .setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, null); + verify(executionContext, times(1)).setAttribute(JWTPolicy.CONTEXT_ATTRIBUTE_OAUTH_CLIENT_ID, null); verify(policyChain, times(1)).doNext(request, response); } @@ -339,8 +328,7 @@ public void test_with_given_key_and_valid_authorization_header() throws Exceptio when(executionContext.getComponent(Environment.class)).thenReturn(environment); when(environment.getProperty("policy.jwt.issuer.gravitee.authorization.server.MAIN")).thenReturn(getSignatureKey()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GIVEN_KEY); when(configuration.getResolverParameter()).thenReturn(getSignatureKey()); @@ -351,17 +339,16 @@ public void test_with_given_key_and_valid_authorization_header() throws Exceptio verify(policyChain, times(1)).doNext(request, response); } - + @Test public void test_with_given_key_using_EL_and_valid_authorization_header() throws Exception { String jwt = getJsonWebToken(7200); final String property = "prop['key']"; - + when(executionContext.getComponent(Environment.class)).thenReturn(environment); when(environment.getProperty("policy.jwt.issuer.gravitee.authorization.server.MAIN")).thenReturn(getSignatureKey()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GIVEN_KEY); when(configuration.getResolverParameter()).thenReturn(property); @@ -372,7 +359,7 @@ public void test_with_given_key_using_EL_and_valid_authorization_header() throws verify(policyChain, times(1)).doNext(request, response); } - + @Test public void test_with_given_key_but_not_provided() throws Exception { String jwt = getJsonWebToken(7200); @@ -380,28 +367,30 @@ public void test_with_given_key_but_not_provided() throws Exception { when(executionContext.getComponent(Environment.class)).thenReturn(environment); when(environment.getProperty("policy.jwt.issuer.gravitee.authorization.server.MAIN")).thenReturn(getSignatureKey()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GIVEN_KEY); when(configuration.getResolverParameter()).thenReturn(null); executePolicy(configuration, request, response, executionContext, policyChain); - verify(policyChain, times(1)).failWith(argThat( - result -> result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 - && JWTPolicy.JWT_MISSING_TOKEN_KEY.equals(result.key()))); + verify(policyChain, times(1)) + .failWith( + argThat(result -> + result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 && JWTPolicy.JWT_MISSING_TOKEN_KEY.equals(result.key()) + ) + ); verify(policyChain, never()).doNext(request, response); } - + @Test public void test_with_gateway_keys_and_valid_access_token() throws Exception { String jwt = getJsonWebToken(7200); when(executionContext.getComponent(Environment.class)).thenReturn(environment); when(environment.getProperty("policy.jwt.issuer.gravitee.authorization.server.MAIN")).thenReturn(getSignatureKey()); - - MultiValueMap parameters = new LinkedMultiValueMap<>(1); + + MultiValueMap parameters = new LinkedMultiValueMap<>(1); parameters.put("access_token", Collections.singletonList(jwt)); when(request.headers()).thenReturn(HttpHeaders.create()); @@ -413,7 +402,7 @@ public void test_with_gateway_keys_and_valid_access_token() throws Exception { verify(request, times(2)).parameters(); verify(policyChain, times(1)).doNext(request, response); } - + @Test public void test_with_gateway_keys_and_expired_header_token() throws Exception { String jwt = getJsonWebToken(0); @@ -421,36 +410,40 @@ public void test_with_gateway_keys_and_expired_header_token() throws Exception { when(executionContext.getComponent(Environment.class)).thenReturn(environment); when(environment.getProperty("policy.jwt.issuer.gravitee.authorization.server.MAIN")).thenReturn(getSignatureKey()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); executePolicy(configuration, request, response, executionContext, policyChain); - - verify(policyChain, times(1)).failWith(argThat( - result -> result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 - && JWTPolicy.JWT_INVALID_TOKEN_KEY.equals(result.key()))); + + verify(policyChain, times(1)) + .failWith( + argThat(result -> + result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 && JWTPolicy.JWT_INVALID_TOKEN_KEY.equals(result.key()) + ) + ); verify(policyChain, never()).doNext(request, response); } @Test public void test_with_gateway_keys_and_unknown_issuer() throws Exception { - String jwt = getJsonWebToken(7200,"unknown"); + String jwt = getJsonWebToken(7200, "unknown"); when(executionContext.getComponent(Environment.class)).thenReturn(environment); when(environment.getProperty("policy.jwt.issuer.gravitee.authorization.server.MAIN")).thenReturn(getSignatureKey()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); executePolicy(configuration, request, response, executionContext, policyChain); - verify(policyChain, times(1)).failWith(argThat( - result -> result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 - && JWTPolicy.JWT_MISSING_TOKEN_KEY.equals(result.key()))); + verify(policyChain, times(1)) + .failWith( + argThat(result -> + result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 && JWTPolicy.JWT_MISSING_TOKEN_KEY.equals(result.key()) + ) + ); verify(policyChain, never()).doNext(request, response); } @@ -458,30 +451,34 @@ public void test_with_gateway_keys_and_unknown_issuer() throws Exception { public void test_not_authentification_scheme() throws Exception { String jwt = getJsonWebToken(7200); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", jwt); when(request.headers()).thenReturn(headers); executePolicy(configuration, request, response, executionContext, policyChain); - verify(policyChain,times(1)).failWith(argThat( - result -> result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 - && JWTPolicy.JWT_MISSING_TOKEN_KEY.equals(result.key()))); + verify(policyChain, times(1)) + .failWith( + argThat(result -> + result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 && JWTPolicy.JWT_MISSING_TOKEN_KEY.equals(result.key()) + ) + ); } @Test public void test_not_authentification_scheme_supported() throws Exception { String jwt = getJsonWebToken(7200); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Basic " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Basic " + jwt); when(request.headers()).thenReturn(headers); executePolicy(configuration, request, response, executionContext, policyChain); - verify(policyChain,times(1)).failWith(argThat( - result -> result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 - && JWTPolicy.JWT_MISSING_TOKEN_KEY.equals(result.key()))); + verify(policyChain, times(1)) + .failWith( + argThat(result -> + result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 && JWTPolicy.JWT_MISSING_TOKEN_KEY.equals(result.key()) + ) + ); } @Test @@ -495,17 +492,19 @@ public void test_with_processing_error() throws Exception { String jwt = sign(builder.build()); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.GATEWAY_KEYS); when(configuration.getUserClaim()).thenReturn("aud"); executePolicy(configuration, request, response, executionContext, policyChain); - verify(policyChain, times(1)).failWith(argThat( - result -> result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 - && JWTPolicy.JWT_INVALID_TOKEN_KEY.equals(result.key()))); + verify(policyChain, times(1)) + .failWith( + argThat(result -> + result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 && JWTPolicy.JWT_INVALID_TOKEN_KEY.equals(result.key()) + ) + ); verify(policyChain, never()).doNext(request, response); } @@ -516,8 +515,7 @@ public void test_with_jwks_url() throws Exception { when(executionContext.getTemplateEngine()).thenReturn(templateEngine); - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Bearer " + jwt); when(request.headers()).thenReturn(headers); when(configuration.getPublicKeyResolver()).thenReturn(KeyResolver.JWKS_URL); when(configuration.getResolverParameter()).thenReturn(jwksUrl); @@ -527,14 +525,22 @@ public void test_with_jwks_url() throws Exception { // Here we expect that JWKSet resource has not been retrieved and so we finally get a 401. // Note: VertxResourceRetriever is hard to mock and throws an NPE (that's why we get a 401). - verify(policyChain, times(1)).failWith(argThat( - result -> result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 - && JWTPolicy.JWT_MISSING_TOKEN_KEY.equals(result.key()))); + verify(policyChain, times(1)) + .failWith( + argThat(result -> + result.statusCode() == HttpStatusCode.UNAUTHORIZED_401 && JWTPolicy.JWT_MISSING_TOKEN_KEY.equals(result.key()) + ) + ); verify(policyChain, never()).doNext(request, response); } - private void executePolicy(JWTPolicyConfiguration configuration, Request request, Response response, - ExecutionContext executionContext, PolicyChain policyChain) throws InterruptedException { + private void executePolicy( + JWTPolicyConfiguration configuration, + Request request, + Response response, + ExecutionContext executionContext, + PolicyChain policyChain + ) throws InterruptedException { final CountDownLatch lock = new CountDownLatch(1); new JWTPolicy(configuration).onRequest(request, response, executionContext, policyChain); @@ -568,9 +574,9 @@ private String getJsonWebToken(long secondsToAdd, String iss) throws Exception { private JWTClaimsSet.Builder getJsonWebTokenBuilder(long secondsToAdd, String iss) throws Exception { // Prepare JWT with claims set return new JWTClaimsSet.Builder() - .subject("alexluso") - .issuer(iss != null ? iss : ISS) - .expirationTime(Date.from(Instant.now().plusSeconds(secondsToAdd))); + .subject("alexluso") + .issuer(iss != null ? iss : ISS) + .expirationTime(Date.from(Instant.now().plusSeconds(secondsToAdd))); } private String sign(JWTClaimsSet claimsSet) throws Exception { @@ -581,10 +587,9 @@ private String sign(JWTClaimsSet claimsSet, String kid) throws Exception { JWSSigner signer = getSigner(); SignedJWT signedJWT = new SignedJWT( - new JWSHeader.Builder(getSignature().getAlg()) - .keyID(kid != null ? kid : KID) - .build(), - claimsSet); + new JWSHeader.Builder(getSignature().getAlg()).keyID(kid != null ? kid : KID).build(), + claimsSet + ); signedJWT.sign(signer); @@ -592,6 +597,8 @@ private String sign(JWTClaimsSet claimsSet, String kid) throws Exception { } abstract Signature getSignature(); + abstract JWSSigner getSigner() throws Exception; + abstract String getSignatureKey() throws Exception; } diff --git a/src/test/java/io/gravitee/policy/jwt/RSACertificateJWTPolicyTest.java b/src/test/java/io/gravitee/policy/jwt/RSACertificateJWTPolicyTest.java index f741a6df..716a88e1 100644 --- a/src/test/java/io/gravitee/policy/jwt/RSACertificateJWTPolicyTest.java +++ b/src/test/java/io/gravitee/policy/jwt/RSACertificateJWTPolicyTest.java @@ -21,7 +21,6 @@ import com.nimbusds.jose.jwk.RSAKey; import io.gravitee.policy.jwt.alg.Signature; import io.gravitee.policy.jwt.key.PublicKeyHelper; - import java.io.*; import java.security.KeyFactory; import java.security.PrivateKey; @@ -39,10 +38,7 @@ protected Signature getSignature() { } protected JWSSigner getSigner() throws Exception { - RSAKey rsaKey = new RSAKey - .Builder(PublicKeyHelper.parsePublicKey(getPublicKey())) - .privateKey(getPrivateKey()) - .build(); + RSAKey rsaKey = new RSAKey.Builder(PublicKeyHelper.parsePublicKey(getPublicKey())).privateKey(getPrivateKey()).build(); return new RSASSASigner(rsaKey); } diff --git a/src/test/java/io/gravitee/policy/jwt/RSAKeyJWTPolicyTest.java b/src/test/java/io/gravitee/policy/jwt/RSAKeyJWTPolicyTest.java index 163d0b3a..3dcf21e3 100644 --- a/src/test/java/io/gravitee/policy/jwt/RSAKeyJWTPolicyTest.java +++ b/src/test/java/io/gravitee/policy/jwt/RSAKeyJWTPolicyTest.java @@ -20,7 +20,6 @@ import com.nimbusds.jose.jwk.RSAKey; import io.gravitee.policy.jwt.alg.Signature; import io.gravitee.policy.jwt.key.PublicKeyHelper; - import java.io.*; import java.security.KeyFactory; import java.security.PrivateKey; @@ -38,10 +37,7 @@ protected Signature getSignature() { } protected JWSSigner getSigner() throws Exception { - RSAKey rsaKey = new RSAKey - .Builder(PublicKeyHelper.parsePublicKey(getPublicKey())) - .privateKey(getPrivateKey()) - .build(); + RSAKey rsaKey = new RSAKey.Builder(PublicKeyHelper.parsePublicKey(getPublicKey())).privateKey(getPrivateKey()).build(); return new RSASSASigner(rsaKey); } @@ -50,7 +46,6 @@ protected String getSignatureKey() throws IOException { return getPublicKey(); } - /** * Return string value of public key matching format ssh-(rsa|dsa) ([A-Za-z0-9/+]+=*) (.*) * @return String diff --git a/src/test/java/io/gravitee/policy/jwt/RSAPublicKeyJWTPolicyTest.java b/src/test/java/io/gravitee/policy/jwt/RSAPublicKeyJWTPolicyTest.java index e82dcdb9..a8426f9a 100644 --- a/src/test/java/io/gravitee/policy/jwt/RSAPublicKeyJWTPolicyTest.java +++ b/src/test/java/io/gravitee/policy/jwt/RSAPublicKeyJWTPolicyTest.java @@ -20,7 +20,6 @@ import com.nimbusds.jose.jwk.RSAKey; import io.gravitee.policy.jwt.alg.Signature; import io.gravitee.policy.jwt.key.PublicKeyHelper; - import java.io.*; import java.security.KeyFactory; import java.security.PrivateKey; @@ -38,10 +37,7 @@ protected Signature getSignature() { } protected JWSSigner getSigner() throws Exception { - RSAKey rsaKey = new RSAKey - .Builder(PublicKeyHelper.parsePublicKey(getRsaKey())) - .privateKey(getPrivateKey()) - .build(); + RSAKey rsaKey = new RSAKey.Builder(PublicKeyHelper.parsePublicKey(getRsaKey())).privateKey(getPrivateKey()).build(); return new RSASSASigner(rsaKey); } @@ -50,7 +46,6 @@ protected String getSignatureKey() throws IOException { return getPublicKey(); } - /** * Return string value of public key matching format ssh-(rsa|dsa) ([A-Za-z0-9/+]+=*) (.*) * @return String diff --git a/src/test/java/io/gravitee/policy/jwt/TestNimbus.java b/src/test/java/io/gravitee/policy/jwt/TestNimbus.java index da87bdb9..40bfd864 100644 --- a/src/test/java/io/gravitee/policy/jwt/TestNimbus.java +++ b/src/test/java/io/gravitee/policy/jwt/TestNimbus.java @@ -19,7 +19,6 @@ import com.nimbusds.jose.jwk.KeyUse; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.jwk.gen.RSAKeyGenerator; - import java.util.Base64; import java.util.UUID; @@ -27,9 +26,9 @@ public class TestNimbus { public static void main(String[] args) throws JOSEException { RSAKey jwk = new RSAKeyGenerator(2048) - .keyUse(KeyUse.ENCRYPTION) // indicate the intended use of the key - .keyID(UUID.randomUUID().toString()) // give the key a unique ID - .generate(); + .keyUse(KeyUse.ENCRYPTION) // indicate the intended use of the key + .keyID(UUID.randomUUID().toString()) // give the key a unique ID + .generate(); RSAKey recipientPublicJWK = jwk.toPublicJWK(); @@ -37,8 +36,6 @@ public static void main(String[] args) throws JOSEException { String publicKeyStr = encoder.encodeToString(recipientPublicJWK.toPublicKey().getEncoded()); //String privateKeyStr = encoder.encodeToString(recipientPublicJWK.toPrivateKey().getEncoded()); - - System.out.println(publicKeyStr); //System.out.println(privateKeyStr); } diff --git a/src/test/java/io/gravitee/policy/jwt/jwks/URLJWKSourceResolverTest.java b/src/test/java/io/gravitee/policy/jwt/jwks/URLJWKSourceResolverTest.java index 82d750d4..4bf356d4 100644 --- a/src/test/java/io/gravitee/policy/jwt/jwks/URLJWKSourceResolverTest.java +++ b/src/test/java/io/gravitee/policy/jwt/jwks/URLJWKSourceResolverTest.java @@ -15,23 +15,22 @@ */ package io.gravitee.policy.jwt.jwks; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.util.Resource; import io.gravitee.el.TemplateEngine; import io.gravitee.policy.jwt.jwks.retriever.ResourceRetriever; +import java.net.MalformedURLException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import java.net.MalformedURLException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - /** * @author GraviteeSource Team */ diff --git a/src/test/java/io/gravitee/policy/jwt/key/PublicKeyHelperTest.java b/src/test/java/io/gravitee/policy/jwt/key/PublicKeyHelperTest.java index 7fb6b5b0..3c31bfcf 100644 --- a/src/test/java/io/gravitee/policy/jwt/key/PublicKeyHelperTest.java +++ b/src/test/java/io/gravitee/policy/jwt/key/PublicKeyHelperTest.java @@ -15,11 +15,10 @@ */ package io.gravitee.policy.jwt.key; +import java.security.interfaces.RSAPublicKey; import org.junit.Assert; import org.junit.Test; -import java.security.interfaces.RSAPublicKey; - /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team @@ -28,28 +27,36 @@ public class PublicKeyHelperTest { @Test public void shouldGetPublicKey_completeSshRsa() { - RSAPublicKey publicKey = PublicKeyHelper.parsePublicKey("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCDUffTA84NNSLgfk2rc3xjWdBqTQBzgHLVSpyG+E4X4t6tgZlSbeh8P3fSeIaNWfclvPubU8Xu93s0iM8cjpC2UhN8f76pf+8rPYOsfSExvsO/8FifowZJOHoLhBhmShncgDfTFdCrk0GLdExp/hKEN0oIMVEFzkLPwoS4Dg9RYITQ1/dUb93n1Llb8Kr//dFD0HsBn+ZNOZL1xH9RtglF1zn//ApE40YqjhnamIDCIYuEtdVubg3I+Eb0xZayrbmfjNbt6lUdtpHxhB2N0pcASbcDA+tGo88wX68AxZzJbZQrh9zPHfH3NlM0sU16yX+1X5zrKWQFvKbE0VQZ2Yy1 brasseld@gmail.com"); + RSAPublicKey publicKey = PublicKeyHelper.parsePublicKey( + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCDUffTA84NNSLgfk2rc3xjWdBqTQBzgHLVSpyG+E4X4t6tgZlSbeh8P3fSeIaNWfclvPubU8Xu93s0iM8cjpC2UhN8f76pf+8rPYOsfSExvsO/8FifowZJOHoLhBhmShncgDfTFdCrk0GLdExp/hKEN0oIMVEFzkLPwoS4Dg9RYITQ1/dUb93n1Llb8Kr//dFD0HsBn+ZNOZL1xH9RtglF1zn//ApE40YqjhnamIDCIYuEtdVubg3I+Eb0xZayrbmfjNbt6lUdtpHxhB2N0pcASbcDA+tGo88wX68AxZzJbZQrh9zPHfH3NlM0sU16yX+1X5zrKWQFvKbE0VQZ2Yy1 brasseld@gmail.com" + ); Assert.assertNotNull(publicKey); } @Test public void shouldGetPublicKey2_noAlg() { - RSAPublicKey publicKey = PublicKeyHelper.parsePublicKey("AAAAB3NzaC1yc2EAAAADAQABAAABAQCDUffTA84NNSLgfk2rc3xjWdBqTQBzgHLVSpyG+E4X4t6tgZlSbeh8P3fSeIaNWfclvPubU8Xu93s0iM8cjpC2UhN8f76pf+8rPYOsfSExvsO/8FifowZJOHoLhBhmShncgDfTFdCrk0GLdExp/hKEN0oIMVEFzkLPwoS4Dg9RYITQ1/dUb93n1Llb8Kr//dFD0HsBn+ZNOZL1xH9RtglF1zn//ApE40YqjhnamIDCIYuEtdVubg3I+Eb0xZayrbmfjNbt6lUdtpHxhB2N0pcASbcDA+tGo88wX68AxZzJbZQrh9zPHfH3NlM0sU16yX+1X5zrKWQFvKbE0VQZ2Yy1 brasseld@gmail.com"); + RSAPublicKey publicKey = PublicKeyHelper.parsePublicKey( + "AAAAB3NzaC1yc2EAAAADAQABAAABAQCDUffTA84NNSLgfk2rc3xjWdBqTQBzgHLVSpyG+E4X4t6tgZlSbeh8P3fSeIaNWfclvPubU8Xu93s0iM8cjpC2UhN8f76pf+8rPYOsfSExvsO/8FifowZJOHoLhBhmShncgDfTFdCrk0GLdExp/hKEN0oIMVEFzkLPwoS4Dg9RYITQ1/dUb93n1Llb8Kr//dFD0HsBn+ZNOZL1xH9RtglF1zn//ApE40YqjhnamIDCIYuEtdVubg3I+Eb0xZayrbmfjNbt6lUdtpHxhB2N0pcASbcDA+tGo88wX68AxZzJbZQrh9zPHfH3NlM0sU16yX+1X5zrKWQFvKbE0VQZ2Yy1 brasseld@gmail.com" + ); Assert.assertNotNull(publicKey); } @Test public void shouldGetPublicKey2_noAlgAndMail() { - RSAPublicKey publicKey = PublicKeyHelper.parsePublicKey("AAAAB3NzaC1yc2EAAAADAQABAAABAQCDUffTA84NNSLgfk2rc3xjWdBqTQBzgHLVSpyG+E4X4t6tgZlSbeh8P3fSeIaNWfclvPubU8Xu93s0iM8cjpC2UhN8f76pf+8rPYOsfSExvsO/8FifowZJOHoLhBhmShncgDfTFdCrk0GLdExp/hKEN0oIMVEFzkLPwoS4Dg9RYITQ1/dUb93n1Llb8Kr//dFD0HsBn+ZNOZL1xH9RtglF1zn//ApE40YqjhnamIDCIYuEtdVubg3I+Eb0xZayrbmfjNbt6lUdtpHxhB2N0pcASbcDA+tGo88wX68AxZzJbZQrh9zPHfH3NlM0sU16yX+1X5zrKWQFvKbE0VQZ2Yy1"); + RSAPublicKey publicKey = PublicKeyHelper.parsePublicKey( + "AAAAB3NzaC1yc2EAAAADAQABAAABAQCDUffTA84NNSLgfk2rc3xjWdBqTQBzgHLVSpyG+E4X4t6tgZlSbeh8P3fSeIaNWfclvPubU8Xu93s0iM8cjpC2UhN8f76pf+8rPYOsfSExvsO/8FifowZJOHoLhBhmShncgDfTFdCrk0GLdExp/hKEN0oIMVEFzkLPwoS4Dg9RYITQ1/dUb93n1Llb8Kr//dFD0HsBn+ZNOZL1xH9RtglF1zn//ApE40YqjhnamIDCIYuEtdVubg3I+Eb0xZayrbmfjNbt6lUdtpHxhB2N0pcASbcDA+tGo88wX68AxZzJbZQrh9zPHfH3NlM0sU16yX+1X5zrKWQFvKbE0VQZ2Yy1" + ); Assert.assertNotNull(publicKey); } @Test public void shouldGetPublicKey_completeSshRsa_RS384() { - RSAPublicKey publicKey = PublicKeyHelper.parsePublicKey("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCBKYIaYRQU5eHRNqi09OP/dxY/uqS3+RYUBDMBaQeaCydgxciGWg0ijY+FlkjaIj/dlC4QfNxsglOgZtlZ2oFiQ5sDri0kGcczRbgDkTpg0q9+2W0huFxccCM0YOGuKBN8VZCIQhnRvC4gPHwzOdgNNCJqJc0qbuwN9WEkBt5O5aqLbVS395r9qbHFg76K3TVbPUXLtYr6Cmig9iTePEBiXyS4ZV0JjqvDryNP/nCeWf9oz091Eto3UKPZ4K6h1fsi7F9OdP867/2I+F3y/Gxdwk4GHkpq/mVzzVM3x//xTPYfgTZtDf8triNS3gBn0JbEIk8sSMh5MVA1nnAoEsxQM6WWlYJbLbWT5Q1N5nQKShTTnAamTuUg2o4MPJoozVW7GDYHWLL6zkbwGzjXULeZQVQi0VH7ZXdXjk4FC6DxmrIRE9gZhkFC7YpMk/fUmB7aLsXGkpLxjM/2DEq02ypAFfPcQwR3Oi0S+TKb9DqwjX/sb06C4n7pIaZzxMJn4xc= brasseld@gmail.com"); + RSAPublicKey publicKey = PublicKeyHelper.parsePublicKey( + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCBKYIaYRQU5eHRNqi09OP/dxY/uqS3+RYUBDMBaQeaCydgxciGWg0ijY+FlkjaIj/dlC4QfNxsglOgZtlZ2oFiQ5sDri0kGcczRbgDkTpg0q9+2W0huFxccCM0YOGuKBN8VZCIQhnRvC4gPHwzOdgNNCJqJc0qbuwN9WEkBt5O5aqLbVS395r9qbHFg76K3TVbPUXLtYr6Cmig9iTePEBiXyS4ZV0JjqvDryNP/nCeWf9oz091Eto3UKPZ4K6h1fsi7F9OdP867/2I+F3y/Gxdwk4GHkpq/mVzzVM3x//xTPYfgTZtDf8triNS3gBn0JbEIk8sSMh5MVA1nnAoEsxQM6WWlYJbLbWT5Q1N5nQKShTTnAamTuUg2o4MPJoozVW7GDYHWLL6zkbwGzjXULeZQVQi0VH7ZXdXjk4FC6DxmrIRE9gZhkFC7YpMk/fUmB7aLsXGkpLxjM/2DEq02ypAFfPcQwR3Oi0S+TKb9DqwjX/sb06C4n7pIaZzxMJn4xc= brasseld@gmail.com" + ); Assert.assertNotNull(publicKey); } diff --git a/src/test/java/io/gravitee/policy/jwt/token/TokenExtractorTest.java b/src/test/java/io/gravitee/policy/jwt/token/TokenExtractorTest.java index 59e30ff1..5a355cb2 100644 --- a/src/test/java/io/gravitee/policy/jwt/token/TokenExtractorTest.java +++ b/src/test/java/io/gravitee/policy/jwt/token/TokenExtractorTest.java @@ -15,6 +15,8 @@ */ package io.gravitee.policy.jwt.token; +import static org.mockito.Mockito.when; + import io.gravitee.common.util.LinkedMultiValueMap; import io.gravitee.gateway.api.Request; import io.gravitee.gateway.api.http.HttpHeaders; @@ -25,8 +27,6 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import static org.mockito.Mockito.when; - /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team @@ -55,8 +55,7 @@ public void shouldNotExtract_noAuthorizationHeader() throws AuthorizationSchemeE public void shouldNotExtract_unknownAuthorizationHeader() throws AuthorizationSchemeException { String jwt = "dummy-token"; - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "Basic " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "Basic " + jwt); when(request.headers()).thenReturn(headers); String token = TokenExtractor.extract(request); @@ -68,8 +67,7 @@ public void shouldNotExtract_unknownAuthorizationHeader() throws AuthorizationSc public void shouldNotExtract_bearerAuthorizationHeader_noValue() throws AuthorizationSchemeException { String jwt = "dummy-token"; - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", TokenExtractor.BEARER); + HttpHeaders headers = HttpHeaders.create().set("Authorization", TokenExtractor.BEARER); when(request.headers()).thenReturn(headers); String token = TokenExtractor.extract(request); @@ -81,8 +79,7 @@ public void shouldNotExtract_bearerAuthorizationHeader_noValue() throws Authoriz public void shouldExtract_fromHeader() throws AuthorizationSchemeException { String jwt = "dummy-token"; - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", TokenExtractor.BEARER + ' ' + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", TokenExtractor.BEARER + ' ' + jwt); when(request.headers()).thenReturn(headers); String token = TokenExtractor.extract(request); @@ -95,8 +92,7 @@ public void shouldExtract_fromHeader() throws AuthorizationSchemeException { public void shouldExtract_fromInsensitiveHeader() throws AuthorizationSchemeException { String jwt = "dummy-token"; - HttpHeaders headers = HttpHeaders.create() - .set("Authorization", "bearer " + jwt); + HttpHeaders headers = HttpHeaders.create().set("Authorization", "bearer " + jwt); when(request.headers()).thenReturn(headers); String token = TokenExtractor.extract(request);