use of com.networknt.status.Status in project light-4j by networknt.
the class ServerInfoDisabledTest method testServerInfo.
@Test
public void testServerInfo() 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("/v1/server/info").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();
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("ERR10013", status.getCode());
}
}
use of com.networknt.status.Status in project light-4j by networknt.
the class ExceptionHandlerTest method testRuntimeException.
@Test
public void testRuntimeException() 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("/runtime").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();
String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
Assert.assertEquals(500, statusCode);
if (statusCode == 500) {
Status status = Config.getInstance().getMapper().readValue(body, Status.class);
Assert.assertNotNull(status);
Assert.assertEquals("ERR10010", status.getCode());
}
}
use of com.networknt.status.Status in project light-4j by networknt.
the class ServerInfoGetHandler method handleRequest.
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
ServerInfoConfig config = (ServerInfoConfig) Config.getInstance().getJsonObjectConfig(CONFIG_NAME, ServerInfoConfig.class);
if (config.isEnableServerInfo()) {
Map<String, Object> infoMap = new LinkedHashMap<>();
infoMap.put("deployment", getDeployment());
infoMap.put("environment", getEnvironment(exchange));
infoMap.put("security", getSecurity());
infoMap.put("specification", Config.getInstance().getJsonMapConfigNoCache("swagger"));
infoMap.put("component", ModuleRegistry.getRegistry());
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(infoMap));
} else {
Status status = new Status(STATUS_SERVER_INFO_DISABLED);
exchange.setStatusCode(status.getStatusCode());
exchange.getResponseSender().send(status.toString());
}
}
use of com.networknt.status.Status in project light-rest-4j by networknt.
the class OpenApiHandlerTest 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("/v1/pets").setMethod(Methods.DELETE);
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());
}
}
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));
if (config != null && (Boolean) config.get(ENABLE_VERIFY_SCOPE) && OpenApiHelper.openApi3 != null) {
Operation operation = null;
OpenApiOperation openApiOperation = (OpenApiOperation) auditInfo.get(Constants.OPENAPI_OPERATION_STRING);
if (openApiOperation == null) {
final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
final Optional<NormalisedPath> maybeApiPath = OpenApiHelper.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 = OpenApiHelper.openApi3.getPath(swaggerPathString.original());
final String httpMethod = exchange.getRequestMethod().toString().toLowerCase();
operation = swaggerPath.getOperation(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;
}
openApiOperation = new OpenApiOperation(swaggerPathString, swaggerPath, httpMethod, operation);
auditInfo.put(Constants.OPENAPI_OPERATION_STRING, openApiOperation);
auditInfo.put(Constants.ENDPOINT_STRING, swaggerPathString.normalised() + "@" + httpMethod);
} else {
operation = openApiOperation.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));
} 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.
Collection<String> specScopes = null;
Collection<SecurityRequirement> securityRequirements = operation.getSecurityRequirements();
if (securityRequirements != null) {
for (SecurityRequirement requirement : securityRequirements) {
SecurityParameter securityParameter = requirement.getRequirement(OpenApiHelper.oauth2Name);
specScopes = securityParameter.getParameters();
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());
}
}
Aggregations