Search in sources :

Example 36 with Outcome

use of com.predic8.membrane.core.interceptor.Outcome in project service-proxy by membrane.

the class XMLProtectionInterceptorTest method runOn.

private void runOn(String resource, boolean expectSuccess) throws Exception {
    exc.getRequest().getHeader().setContentType("application/xml");
    exc.getRequest().setBodyContent(ByteUtil.getByteArrayData(this.getClass().getResourceAsStream(resource)));
    Outcome outcome = interceptor.handleRequest(exc);
    assertEquals(expectSuccess ? Outcome.CONTINUE : Outcome.ABORT, outcome);
}
Also used : Outcome(com.predic8.membrane.core.interceptor.Outcome)

Example 37 with Outcome

use of com.predic8.membrane.core.interceptor.Outcome in project service-proxy by membrane.

the class RateLimitInterceptorTest method testHandleRequestRateLimit1SecondConcurrency.

@Test
public void testHandleRequestRateLimit1SecondConcurrency() throws Exception {
    final Exchange exc = new Exchange(null);
    exc.setResponse(ResponseBuilder.newInstance().build());
    exc.setRemoteAddrIp("192.168.1.100");
    int tryLimit = 16;
    int rateLimitSeconds = 1;
    final RateLimitInterceptor rli = new RateLimitInterceptor(Duration.standardSeconds(rateLimitSeconds), tryLimit);
    ArrayList<Thread> threads = new ArrayList<Thread>();
    final AtomicInteger continues = new AtomicInteger();
    final AtomicInteger returns = new AtomicInteger();
    for (int i = 0; i < 1000; i++) {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Outcome out = rli.handleRequest(exc);
                    if (out == Outcome.CONTINUE) {
                        continues.incrementAndGet();
                    } else if (out == Outcome.RETURN) {
                        returns.incrementAndGet();
                    }
                } catch (Exception e) {
                }
            }
        });
        threads.add(t);
        t.start();
    }
    for (Thread t : threads) {
        t.join();
    }
    assertEquals(16, continues.get());
    assertEquals(984, returns.get());
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Outcome(com.predic8.membrane.core.interceptor.Outcome) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 38 with Outcome

use of com.predic8.membrane.core.interceptor.Outcome in project service-proxy by membrane.

the class OAuth2ResourceTest method getMockAuthServiceProxy.

private ServiceProxy getMockAuthServiceProxy() throws IOException {
    ServiceProxy sp = new ServiceProxy(new ServiceProxyKey(serverPort), null, 99999);
    WellknownFile wkf = new WellknownFile();
    wkf.setIssuer(getServerAddress());
    wkf.setAuthorizationEndpoint(getServerAddress() + "/auth");
    wkf.setTokenEndpoint(getServerAddress() + "/token");
    wkf.setUserinfoEndpoint(getServerAddress() + "/userinfo");
    wkf.setRevocationEndpoint(getServerAddress() + "/revoke");
    wkf.setJwksUri(getServerAddress() + "/certs");
    wkf.setSupportedResponseTypes("code token");
    wkf.setSupportedSubjectType("public");
    wkf.setSupportedIdTokenSigningAlgValues("RS256");
    wkf.setSupportedScopes("openid email profile");
    wkf.setSupportedTokenEndpointAuthMethods("client_secret_post");
    wkf.setSupportedClaims("sub email username");
    wkf.init(new HttpRouter());
    sp.getInterceptors().add(new AbstractInterceptor() {

        SecureRandom rand = new SecureRandom();

        @Override
        public synchronized Outcome handleRequest(Exchange exc) throws Exception {
            if (exc.getRequestURI().endsWith("/.well-known/openid-configuration")) {
                exc.setResponse(Response.ok(wkf.getWellknown()).build());
            } else if (exc.getRequestURI().startsWith("/auth?")) {
                Map<String, String> params = URLParamUtil.getParams(new URIFactory(), exc);
                exc.setResponse(Response.redirect(getClientAddress() + "/oauth2callback?code=1234&state=" + params.get("state"), false).build());
            } else if (exc.getRequestURI().startsWith("/token")) {
                ObjectMapper om = new ObjectMapper();
                Map<String, String> res = new HashMap<>();
                res.put("access_token", new BigInteger(130, rand).toString(32));
                res.put("token_type", "bearer");
                res.put("expires_in", "1");
                res.put("refresh_token", new BigInteger(130, rand).toString(32));
                exc.setResponse(Response.ok(om.writeValueAsString(res)).contentType("application/json").build());
            } else if (exc.getRequestURI().startsWith("/userinfo")) {
                ObjectMapper om = new ObjectMapper();
                Map<String, String> res = new HashMap<>();
                res.put("username", "dummy");
                exc.setResponse(Response.ok(om.writeValueAsString(res)).contentType("application/json").build());
            }
            if (exc.getResponse() == null)
                exc.setResponse(Response.notFound().build());
            return Outcome.RETURN;
        }
    });
    return sp;
}
Also used : AbstractInterceptor(com.predic8.membrane.core.interceptor.AbstractInterceptor) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) Exchange(com.predic8.membrane.core.exchange.Exchange) ServiceProxyKey(com.predic8.membrane.core.rules.ServiceProxyKey) ServiceProxy(com.predic8.membrane.core.rules.ServiceProxy) Outcome(com.predic8.membrane.core.interceptor.Outcome) URIFactory(com.predic8.membrane.core.util.URIFactory) BigInteger(java.math.BigInteger) HttpRouter(com.predic8.membrane.core.HttpRouter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 39 with Outcome

use of com.predic8.membrane.core.interceptor.Outcome in project service-proxy by membrane.

the class SwaggerRewriterInterceptor method handleResponse.

@Override
public Outcome handleResponse(Exchange exc) throws Exception {
    // replacement in swagger.json
    if (exc.getRequest().getUri().endsWith(swaggerJson) && exc.getResponseContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
        Swagger swagBody = new SwaggerParser().parse(exc.getResponse().getBodyAsStringDecoded());
        swagBody.setHost(exc2originalHostPort(exc));
        exc.getResponse().setBodyContent(Json.pretty(swagBody).getBytes(exc.getResponse().getCharset()));
    }
    // replacement in json and javascript (specifically UI)
    if (rewriteUI && (exc.getRequest().getUri().matches("/.*.js(on)?") || exc.getResponse().getHeader().getContentType() != null && exc.getResponse().getHeader().getContentType().equals(MediaType.TEXT_HTML_VALUE))) {
        String from = "(http(s)?://)" + Pattern.quote(((ServiceProxy) exc.getRule()).getTarget().getHost()) + "(/.*\\.js(on)?)";
        String to = "$1" + exc2originalHostPort(exc) + "$3";
        byte[] body = exc.getResponse().getBodyAsStringDecoded().replaceAll(from, to).getBytes(exc.getResponse().getCharset());
        exc.getResponse().setBodyContent(body);
    }
    return super.handleResponse(exc);
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) ServiceProxy(com.predic8.membrane.core.rules.ServiceProxy) Swagger(io.swagger.models.Swagger)

Example 40 with Outcome

use of com.predic8.membrane.core.interceptor.Outcome in project service-proxy by membrane.

the class SOAP2RESTInterceptor method handleRequest.

@Override
public Outcome handleRequest(Exchange exc) throws Exception {
    // save SOAP operationName and namespace in exchange properties to generically construct response name
    soe.handleRequest(exc);
    // apply request XSLT
    transformAndReplaceBody(exc.getRequest(), requestXSLT, new StreamSource(exc.getRequest().getBodyAsStreamDecoded()), exc.getStringProperties());
    // fill Request object from HTTP-XML
    Header header = exc.getRequest().getHeader();
    header.removeFields(Header.CONTENT_TYPE);
    header.setContentType(MimeType.TEXT_XML_UTF8);
    XML2HTTP.unwrapMessageIfNecessary(exc.getRequest());
    // reset exchange destination to new request URI
    exc.getDestinations().clear();
    di.handleRequest(exc);
    return Outcome.CONTINUE;
}
Also used : Header(com.predic8.membrane.core.http.Header) StreamSource(javax.xml.transform.stream.StreamSource)

Aggregations

Outcome (com.predic8.membrane.core.interceptor.Outcome)25 Exchange (com.predic8.membrane.core.exchange.Exchange)19 AbstractInterceptor (com.predic8.membrane.core.interceptor.AbstractInterceptor)16 ServiceProxy (com.predic8.membrane.core.rules.ServiceProxy)14 IOException (java.io.IOException)14 ServiceProxyKey (com.predic8.membrane.core.rules.ServiceProxyKey)10 Test (org.junit.Test)9 HttpRouter (com.predic8.membrane.core.HttpRouter)8 URISyntaxException (java.net.URISyntaxException)7 Before (org.junit.Before)6 ArrayList (java.util.ArrayList)4 Header (com.predic8.membrane.core.http.Header)3 Session (com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)3 Rule (com.predic8.membrane.core.rules.Rule)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Body (com.predic8.membrane.core.http.Body)2 HttpClientConfiguration (com.predic8.membrane.core.transport.http.client.HttpClientConfiguration)2 MalformedURLException (java.net.MalformedURLException)2 InvalidParameterException (java.security.InvalidParameterException)2