Search in sources :

Example 51 with Status

use of com.networknt.status.Status in project light-rest-4j by networknt.

the class ValidatorHandlerTest method testInvalidRequstPath.

@Test
public void testInvalidRequstPath() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/api").setMethod(Methods.GET);
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(404, statusCode);
    if (statusCode == 404) {
        Status status = Config.getInstance().getMapper().readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10007", status.getCode());
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) Status(com.networknt.status.Status) ClientConnection(io.undertow.client.ClientConnection) AtomicReference(java.util.concurrent.atomic.AtomicReference) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) IOException(java.io.IOException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Example 52 with Status

use of com.networknt.status.Status in project light-rest-4j by networknt.

the class SwaggerHandlerTest method testWrongMethod.

@Test
public void testWrongMethod() throws Exception {
    // this path is not in petstore swagger specification. get error
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet").setMethod(Methods.GET);
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(405, statusCode);
    if (statusCode == 405) {
        Status status = Config.getInstance().getMapper().readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10008", status.getCode());
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) Status(com.networknt.status.Status) ClientConnection(io.undertow.client.ClientConnection) AtomicReference(java.util.concurrent.atomic.AtomicReference) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Example 53 with Status

use of com.networknt.status.Status in project light-rest-4j by networknt.

the class JwtVerifyHandler method handleRequest.

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    HeaderMap headerMap = exchange.getRequestHeaders();
    String authorization = headerMap.getFirst(Headers.AUTHORIZATION);
    String jwt = JwtHelper.getJwtFromAuthorization(authorization);
    if (jwt != null) {
        try {
            JwtClaims claims = JwtHelper.verifyJwt(jwt);
            Map<String, Object> auditInfo = exchange.getAttachment(AuditHandler.AUDIT_INFO);
            // endpoint and swaggerOperation available. This handler will enrich the auditInfo.
            if (auditInfo == null) {
                auditInfo = new HashMap<>();
                exchange.putAttachment(AuditHandler.AUDIT_INFO, auditInfo);
            }
            auditInfo.put(Constants.CLIENT_ID_STRING, claims.getStringClaimValue(Constants.CLIENT_ID_STRING));
            auditInfo.put(Constants.USER_ID_STRING, claims.getStringClaimValue(Constants.USER_ID_STRING));
            auditInfo.put(Constants.SUBJECT_CLAIMS, claims);
            if (config != null && (Boolean) config.get(ENABLE_VERIFY_SCOPE) && SwaggerHelper.swagger != null) {
                Operation operation = null;
                SwaggerOperation swaggerOperation = (SwaggerOperation) auditInfo.get(Constants.SWAGGER_OPERATION_STRING);
                if (swaggerOperation == null) {
                    final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
                    final Optional<NormalisedPath> maybeApiPath = SwaggerHelper.findMatchingApiPath(requestPath);
                    if (!maybeApiPath.isPresent()) {
                        Status status = new Status(STATUS_INVALID_REQUEST_PATH);
                        exchange.setStatusCode(status.getStatusCode());
                        logger.error("Error in JwtVerifyHandler: " + status.toString());
                        exchange.getResponseSender().send(status.toString());
                        return;
                    }
                    final NormalisedPath swaggerPathString = maybeApiPath.get();
                    final Path swaggerPath = SwaggerHelper.swagger.getPath(swaggerPathString.original());
                    final HttpMethod httpMethod = HttpMethod.valueOf(exchange.getRequestMethod().toString());
                    operation = swaggerPath.getOperationMap().get(httpMethod);
                    if (operation == null) {
                        Status status = new Status(STATUS_METHOD_NOT_ALLOWED);
                        exchange.setStatusCode(status.getStatusCode());
                        logger.error("Error in JwtVerifyHandler: " + status.toString());
                        exchange.getResponseSender().send(status.toString());
                        return;
                    }
                    swaggerOperation = new SwaggerOperation(swaggerPathString, swaggerPath, httpMethod, operation);
                    auditInfo.put(Constants.SWAGGER_OPERATION_STRING, swaggerOperation);
                    auditInfo.put(Constants.ENDPOINT_STRING, swaggerPathString.normalised() + "@" + httpMethod);
                } else {
                    operation = swaggerOperation.getOperation();
                }
                // is there a scope token
                String scopeHeader = headerMap.getFirst(Constants.SCOPE_TOKEN);
                String scopeJwt = JwtHelper.getJwtFromAuthorization(scopeHeader);
                List<String> secondaryScopes = null;
                if (scopeJwt != null) {
                    try {
                        JwtClaims scopeClaims = JwtHelper.verifyJwt(scopeJwt);
                        secondaryScopes = scopeClaims.getStringListClaimValue("scope");
                        auditInfo.put(Constants.SCOPE_CLIENT_ID_STRING, scopeClaims.getStringClaimValue(Constants.CLIENT_ID_STRING));
                        auditInfo.put(Constants.ACCESS_CLAIMS, scopeClaims);
                    } catch (InvalidJwtException | MalformedClaimException e) {
                        logger.error("InvalidJwtException", e);
                        Status status = new Status(STATUS_INVALID_SCOPE_TOKEN);
                        exchange.setStatusCode(status.getStatusCode());
                        logger.error("Error in JwtVerifyHandler: " + status.toString());
                        exchange.getResponseSender().send(status.toString());
                        return;
                    } catch (ExpiredTokenException e) {
                        Status status = new Status(STATUS_SCOPE_TOKEN_EXPIRED);
                        exchange.setStatusCode(status.getStatusCode());
                        logger.error("Error in JwtVerifyHandler: " + status.toString());
                        exchange.getResponseSender().send(status.toString());
                        return;
                    }
                }
                // get scope defined in swagger spec for this endpoint.
                List<String> specScopes = null;
                List<Map<String, List<String>>> security = operation.getSecurity();
                if (security != null) {
                    for (Map<String, List<String>> requirement : security) {
                        specScopes = requirement.get(SwaggerHelper.oauth2Name);
                        if (specScopes != null)
                            break;
                    }
                }
                // validate scope
                if (scopeHeader != null) {
                    if (secondaryScopes == null || !matchedScopes(secondaryScopes, specScopes)) {
                        Status status = new Status(STATUS_SCOPE_TOKEN_SCOPE_MISMATCH, secondaryScopes, specScopes);
                        exchange.setStatusCode(status.getStatusCode());
                        logger.error("Error in JwtVerifyHandler: " + status.toString());
                        exchange.getResponseSender().send(status.toString());
                        return;
                    }
                } else {
                    // no scope token, verify scope from auth token.
                    List<String> primaryScopes;
                    try {
                        primaryScopes = claims.getStringListClaimValue("scope");
                    } catch (MalformedClaimException e) {
                        logger.error("MalformedClaimException", e);
                        Status status = new Status(STATUS_INVALID_AUTH_TOKEN);
                        exchange.setStatusCode(status.getStatusCode());
                        logger.error("Error in JwtVerifyHandler: " + status.toString());
                        exchange.getResponseSender().send(status.toString());
                        return;
                    }
                    if (!matchedScopes(primaryScopes, specScopes)) {
                        Status status = new Status(STATUS_AUTH_TOKEN_SCOPE_MISMATCH, primaryScopes, specScopes);
                        exchange.setStatusCode(status.getStatusCode());
                        logger.error("Error in JwtVerifyHandler: " + status.toString());
                        exchange.getResponseSender().send(status.toString());
                        return;
                    }
                }
            }
            next.handleRequest(exchange);
        } catch (InvalidJwtException e) {
            // only log it and unauthorized is returned.
            logger.error("Exception: ", e);
            Status status = new Status(STATUS_INVALID_AUTH_TOKEN);
            exchange.setStatusCode(status.getStatusCode());
            logger.error("Error in JwtVerifyHandler: " + status.toString());
            exchange.getResponseSender().send(status.toString());
        } catch (ExpiredTokenException e) {
            Status status = new Status(STATUS_AUTH_TOKEN_EXPIRED);
            exchange.setStatusCode(status.getStatusCode());
            logger.error("Error in JwtVerifyHandler: " + status.toString());
            exchange.getResponseSender().send(status.toString());
        }
    } else {
        Status status = new Status(STATUS_MISSING_AUTH_TOKEN);
        exchange.setStatusCode(status.getStatusCode());
        logger.error("Error in JwtVerifyHandler: " + status.toString());
        exchange.getResponseSender().send(status.toString());
    }
}
Also used : Status(com.networknt.status.Status) InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) ExpiredTokenException(com.networknt.exception.ExpiredTokenException) JwtClaims(org.jose4j.jwt.JwtClaims) HttpString(io.undertow.util.HttpString) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) HeaderMap(io.undertow.util.HeaderMap) List(java.util.List) HashMap(java.util.HashMap) HeaderMap(io.undertow.util.HeaderMap) Map(java.util.Map)

Example 54 with Status

use of com.networknt.status.Status in project light-rest-4j by networknt.

the class JwtVerifyHandlerTest method testUnmatchedScopeInIdToken.

@Test
public void testUnmatchedScopeInIdToken() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet/111").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.AUTHORIZATION, "Bearer eyJraWQiOiIxMDAiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTgwNTEzNjU1MSwianRpIjoiTVJiZHdlQ295eG13a2ZUM3lVWGloQSIsImlhdCI6MTQ4OTc3NjU1MSwibmJmIjoxNDg5Nzc2NDMxLCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6ImVyaWMiLCJ1c2VyX3R5cGUiOiJFTVBMT1lFRSIsImNsaWVudF9pZCI6ImY3ZDQyMzQ4LWM2NDctNGVmYi1hNTJkLTRjNTc4NzQyMWU3MiIsInNjb3BlIjpbIkFUTVAxMDAwLnciLCJBVE1QMTAwMC5yIl19.VOEggO6UIMHNJLrxShGivCh7sGyHiz7h9FqDjlKwywGP9xKbVTTODy2-FitUaS1Y2vjiHlJ0TNyxmj1SO11YwYnJlW1zn-6vfKWKI70DyvRwsvSX_8Z2fj0jPUiBqezwKRtLCHSsmiEpMrW6YQHYw0qzZ9kkMhiH2uFpZNCekOQWL1piRn1xVQkUmeFiTDvJQESHadFzw-9x0klO7-SxgKeHHDroxnpbLv2j795oMTB1gM_wJP6HO_M-gK6N1Uh6zssfnbyFReRNWkhZFOp3Y8DvwpfKhqXIVGUc_5WsO9M-y66icClVNl5zwLSmjsrNtqZkmeBCwQ6skBnRLfMocQ");
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(403, statusCode);
    if (statusCode == 403) {
        Status status = Config.getInstance().getMapper().readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10005", status.getCode());
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) Status(com.networknt.status.Status) ClientConnection(io.undertow.client.ClientConnection) AtomicReference(java.util.concurrent.atomic.AtomicReference) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Example 55 with Status

use of com.networknt.status.Status in project light-rest-4j by networknt.

the class ValidatorHandlerTest method testInvalidPost.

@Test
public void testInvalidPost() throws Exception {
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    try {
        String post = "{\"name\":\"Pinky\", \"photoUrl\": \"http://www.photo.com/1.jpg\"}";
        connection.getIoThread().execute(new Runnable() {

            @Override
            public void run() {
                final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/post");
                request.getRequestHeaders().put(Headers.HOST, "localhost");
                request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
                request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
                connection.sendRequest(request, client.createClientCallback(reference, latch, post));
            }
        });
        latch.await(10, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(404, statusCode);
    if (statusCode == 404) {
        Status status = Config.getInstance().getMapper().readValue(body, Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10007", status.getCode());
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) Status(com.networknt.status.Status) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpString(io.undertow.util.HttpString) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) IOException(java.io.IOException) ClientConnection(io.undertow.client.ClientConnection) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Aggregations

Status (com.networknt.status.Status)71 Test (org.junit.Test)45 Http2Client (com.networknt.client.Http2Client)19 ClientException (com.networknt.exception.ClientException)19 URI (java.net.URI)19 CountDownLatch (java.util.concurrent.CountDownLatch)19 AtomicReference (java.util.concurrent.atomic.AtomicReference)19 ClientConnection (io.undertow.client.ClientConnection)17 ClientRequest (io.undertow.client.ClientRequest)17 ClientResponse (io.undertow.client.ClientResponse)17 IOException (java.io.IOException)12 FrameworkException (com.networknt.exception.FrameworkException)9 HttpString (io.undertow.util.HttpString)7 IntegerProperty (io.swagger.models.properties.IntegerProperty)4 BigDecimal (java.math.BigDecimal)4 HashMap (java.util.HashMap)4 JsonParseException (com.fasterxml.jackson.core.JsonParseException)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 JsonSchema (com.networknt.schema.JsonSchema)3 ValidationMessage (com.networknt.schema.ValidationMessage)3