Search in sources :

Example 1 with ExecutionContext

use of io.gravitee.gateway.api.ExecutionContext in project gravitee-gateway by gravitee-io.

the class ApiReactorHandler method doHandle.

@Override
protected void doHandle(Request serverRequest, Response serverResponse, Handler<Response> handler) {
    // Prepare request execution context
    ExecutionContext executionContext = executionContextFactory.create(serverRequest);
    executionContext.setAttribute(ExecutionContext.ATTR_CONTEXT_PATH, serverRequest.contextPath());
    try {
        // Set execution context attributes and metrics specific to this handler
        serverRequest.metrics().setApi(api.getId());
        executionContext.setAttribute(ExecutionContext.ATTR_API, api.getId());
        executionContext.setAttribute(ExecutionContext.ATTR_INVOKER, invoker);
        // Enable logging at client level
        if (api.getProxy().getLoggingMode().isClientMode()) {
            serverRequest = new LoggableClientRequest(serverRequest);
            serverResponse = new LoggableClientResponse(serverRequest, serverResponse);
        }
        Cors cors = api.getProxy().getCors();
        if (cors != null && cors.isEnabled()) {
            Request finalServerRequest = serverRequest;
            Response finalServerResponse = serverResponse;
            new CorsHandler(cors).responseHandler(new Handler<Response>() {

                @Override
                public void handle(Response response) {
                    handleClientRequest(finalServerRequest, finalServerResponse, executionContext, new CorsResponseHandler(handler));
                }
            }).handle(serverRequest, serverResponse, handler);
        } else {
            handleClientRequest(serverRequest, serverResponse, executionContext, handler);
        }
    } catch (Exception ex) {
        logger.error("An unexpected error occurs while processing request", ex);
        serverRequest.metrics().setMessage(Throwables.getStackTraceAsString(ex));
        // Send an INTERNAL_SERVER_ERROR (500)
        serverResponse.status(HttpStatusCode.INTERNAL_SERVER_ERROR_500);
        serverResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE);
        serverResponse.end();
        handler.handle(serverResponse);
    }
}
Also used : LoggableClientResponse(io.gravitee.gateway.handlers.api.logging.LoggableClientResponse) Response(io.gravitee.gateway.api.Response) ProxyResponse(io.gravitee.gateway.api.proxy.ProxyResponse) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) LoggableClientRequest(io.gravitee.gateway.handlers.api.logging.LoggableClientRequest) LoggableClientRequest(io.gravitee.gateway.handlers.api.logging.LoggableClientRequest) Request(io.gravitee.gateway.api.Request) CorsHandler(io.gravitee.gateway.handlers.api.cors.CorsHandler) Handler(io.gravitee.gateway.api.handler.Handler) CorsResponseHandler(io.gravitee.gateway.handlers.api.cors.CorsResponseHandler) AbstractReactorHandler(io.gravitee.gateway.reactor.handler.AbstractReactorHandler) CorsHandler(io.gravitee.gateway.handlers.api.cors.CorsHandler) LoggableClientResponse(io.gravitee.gateway.handlers.api.logging.LoggableClientResponse) Cors(io.gravitee.definition.model.Cors) CorsResponseHandler(io.gravitee.gateway.handlers.api.cors.CorsResponseHandler) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 2 with ExecutionContext

use of io.gravitee.gateway.api.ExecutionContext in project gravitee-gateway by gravitee-io.

the class AbstractPolicy method onResponse.

public void onResponse(Object... args) throws PolicyException {
    ExecutionContext executionContext = getParameterAssignableTo(ExecutionContext.class, args);
    PolicyChain policyChain = getParameterAssignableTo(PolicyChain.class, args);
    Request request = getParameterAssignableTo(Request.class, args);
    Response response = getParameterAssignableTo(Response.class, args);
    this.onResponse(request, response, policyChain, executionContext);
}
Also used : Response(io.gravitee.gateway.api.Response) PolicyChain(io.gravitee.policy.api.PolicyChain) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) Request(io.gravitee.gateway.api.Request)

Example 3 with ExecutionContext

use of io.gravitee.gateway.api.ExecutionContext in project gravitee-gateway by gravitee-io.

the class ApiPolicyChainResolver method calculate.

@Override
protected List<Policy> calculate(StreamType streamType, Request request, Response response, ExecutionContext executionContext) {
    // Resolve the "configured" path according to the inbound request
    Path path = pathResolver.resolve(request.path());
    executionContext.setAttribute(ExecutionContext.ATTR_RESOLVED_PATH, path.getResolvedPath());
    return path.getRules().stream().filter(rule -> rule.isEnabled() && rule.getMethods().contains(request.method())).map(rule -> create(streamType, rule.getPolicy().getName(), rule.getPolicy().getConfiguration())).filter(Objects::nonNull).collect(Collectors.toList());
}
Also used : Path(io.gravitee.gateway.handlers.api.path.Path) Objects(java.util.Objects) Policy(io.gravitee.gateway.policy.Policy) List(java.util.List) Response(io.gravitee.gateway.api.Response) Path(io.gravitee.gateway.handlers.api.path.Path) StreamType(io.gravitee.gateway.policy.StreamType) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) Request(io.gravitee.gateway.api.Request) AbstractPolicyChainResolver(io.gravitee.gateway.policy.AbstractPolicyChainResolver) PathResolver(io.gravitee.gateway.handlers.api.path.PathResolver) Autowired(org.springframework.beans.factory.annotation.Autowired) Collectors(java.util.stream.Collectors)

Example 4 with ExecutionContext

use of io.gravitee.gateway.api.ExecutionContext in project gravitee-gateway by gravitee-io.

the class PlanPolicyChainResolver method calculate.

@Override
protected List<Policy> calculate(StreamType streamType, Request request, Response response, ExecutionContext executionContext) {
    if (streamType == StreamType.ON_REQUEST) {
        String plan = (String) executionContext.getAttribute(ExecutionContext.ATTR_PLAN);
        String application = (String) executionContext.getAttribute(ExecutionContext.ATTR_APPLICATION);
        // String user = (String) executionContext.getAttribute(ExecutionContext.ATTR_USER_ID);
        // request.metrics().setUserId(user);
        request.metrics().setPlan(plan);
        request.metrics().setApplication(application);
        Plan apiPlan = api.getPlan(plan);
        // The call is probably not relative to the same API.
        if (plan != null && apiPlan != null) {
            Map<String, Path> paths = api.getPlan(plan).getPaths();
            if (paths != null && !paths.isEmpty()) {
                // For 1.0.0, there is only a single root path defined
                // Must be reconsidered when user will be able to manage policies at the plan level by himself
                Path rootPath = paths.values().iterator().next();
                return rootPath.getRules().stream().filter(rule -> rule.isEnabled() && rule.getMethods().contains(request.method())).map(rule -> create(streamType, rule.getPolicy().getName(), rule.getPolicy().getConfiguration())).filter(Objects::nonNull).collect(Collectors.toList());
            }
        } else {
            logger.warn("No plan has been selected to process request {}. Returning an unauthorized HTTP status (401)", request.id());
            return null;
        }
    }
    return Collections.emptyList();
}
Also used : Path(io.gravitee.definition.model.Path) PolicyChain(io.gravitee.gateway.policy.impl.PolicyChain) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) RequestPolicyChain(io.gravitee.gateway.policy.impl.RequestPolicyChain) Autowired(org.springframework.beans.factory.annotation.Autowired) Plan(io.gravitee.gateway.handlers.api.definition.Plan) ResponsePolicyChain(io.gravitee.gateway.policy.impl.ResponsePolicyChain) Collectors(java.util.stream.Collectors) HttpStatusCode(io.gravitee.common.http.HttpStatusCode) Objects(java.util.Objects) List(java.util.List) Response(io.gravitee.gateway.api.Response) Request(io.gravitee.gateway.api.Request) Map(java.util.Map) Api(io.gravitee.gateway.handlers.api.definition.Api) Path(io.gravitee.definition.model.Path) io.gravitee.gateway.policy(io.gravitee.gateway.policy) PolicyResult(io.gravitee.policy.api.PolicyResult) Collections(java.util.Collections) Plan(io.gravitee.gateway.handlers.api.definition.Plan)

Example 5 with ExecutionContext

use of io.gravitee.gateway.api.ExecutionContext in project gravitee-gateway by gravitee-io.

the class CheckSubscriptionPolicyTest method shouldReturnUnauthorized_noClient.

@Test
public void shouldReturnUnauthorized_noClient() throws PolicyException, TechnicalException {
    CheckSubscriptionPolicy policy = new CheckSubscriptionPolicy();
    Request request = mock(Request.class);
    Response response = mock(Response.class);
    when(response.headers()).thenReturn(mock(HttpHeaders.class));
    PolicyChain policyChain = mock(PolicyChain.class);
    ExecutionContext executionContext = mock(ExecutionContext.class);
    SubscriptionRepository subscriptionRepository = mock(SubscriptionRepository.class);
    when(executionContext.getComponent(SubscriptionRepository.class)).thenReturn(subscriptionRepository);
    Subscription subscription = mock(Subscription.class);
    when(subscription.getClientId()).thenReturn("my-bad-client-id");
    when(subscriptionRepository.search(any(SubscriptionCriteria.class))).thenReturn(Collections.singletonList(subscription));
    policy.onRequest(request, response, policyChain, executionContext);
    verify(policyChain, times(1)).failWith(argThat(statusCode(HttpStatusCode.UNAUTHORIZED_401)));
}
Also used : Response(io.gravitee.gateway.api.Response) HttpHeaders(io.gravitee.common.http.HttpHeaders) PolicyChain(io.gravitee.policy.api.PolicyChain) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) SubscriptionRepository(io.gravitee.repository.management.api.SubscriptionRepository) Request(io.gravitee.gateway.api.Request) SubscriptionCriteria(io.gravitee.repository.management.api.search.SubscriptionCriteria) Subscription(io.gravitee.repository.management.model.Subscription) Test(org.junit.Test)

Aggregations

ExecutionContext (io.gravitee.gateway.api.ExecutionContext)28 Request (io.gravitee.gateway.api.Request)22 Test (org.junit.Test)21 Response (io.gravitee.gateway.api.Response)19 PolicyChain (io.gravitee.gateway.policy.impl.PolicyChain)12 Handler (io.gravitee.gateway.api.handler.Handler)9 PolicyChain (io.gravitee.policy.api.PolicyChain)9 SubscriptionRepository (io.gravitee.repository.management.api.SubscriptionRepository)7 SubscriptionCriteria (io.gravitee.repository.management.api.search.SubscriptionCriteria)7 BufferedReadWriteStream (io.gravitee.gateway.api.stream.BufferedReadWriteStream)6 ReadWriteStream (io.gravitee.gateway.api.stream.ReadWriteStream)6 ResponsePolicyChain (io.gravitee.gateway.policy.impl.ResponsePolicyChain)6 RequestPolicyChain (io.gravitee.gateway.policy.impl.RequestPolicyChain)5 Subscription (io.gravitee.repository.management.model.Subscription)5 AuthenticationPolicy (io.gravitee.gateway.security.core.AuthenticationPolicy)4 PluginAuthenticationPolicy (io.gravitee.gateway.security.core.PluginAuthenticationPolicy)4 InOrder (org.mockito.InOrder)4 Autowired (org.springframework.beans.factory.annotation.Autowired)4 HttpHeaders (io.gravitee.common.http.HttpHeaders)3 HttpStatusCode (io.gravitee.common.http.HttpStatusCode)3