Search in sources :

Example 41 with Header

use of com.predic8.membrane.core.http.Header in project service-proxy by membrane.

the class AMQuotaInterceptorTest method testAMQuota.

@Test
public void testAMQuota() throws IOException, InterruptedException {
    final Exchange exc = new Exchange(null);
    exc.setRequest(new Request.Builder().header("Test", "test").body("hello").build());
    exc.setResponse(new Response.ResponseBuilder().header("Test2", "test2").body("Hello back!").build());
    exc.setProperty(Exchange.API_KEY, "junit");
    exc.setRule(new ServiceProxy());
    exc.getRule().setName("junit API");
    ApiManagementConfiguration amc = new ApiManagementConfiguration(System.getProperty("user.dir"), "src\\test\\resources\\apimanagement\\api.yaml");
    long reqSize = exc.getRequest().getHeader().toString().getBytes().length + exc.getRequest().getHeader().getContentLength();
    long respSize = exc.getResponse().getHeader().toString().getBytes().length + exc.getResponse().getHeader().getContentLength();
    assertEquals(31 + 5, reqSize);
    assertEquals(34 + 11, respSize);
    final AMQuota amq = new AMQuota();
    amq.setAmc(amc);
    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 = amq.handleRequest(exc);
                    if (out == Outcome.CONTINUE) {
                        continues.incrementAndGet();
                    } else if (out == Outcome.RETURN) {
                        returns.incrementAndGet();
                    }
                    amq.handleResponse(exc);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        threads.add(t);
        // t.start();
        // doing sync because else we cant predictably count request/response pairs
        t.run();
    }
    for (Thread t : threads) {
        t.join();
    }
    // the limit is ( or should be ) 120B
    // 31+5 ( Req ) + 34+11 ( Resp ) = 81 for every completed exchange
    // the second request adds another 31+5 -> 81 + 36 = 117 < 120B -> after the second request it should block because the limit is 120b and the following response would bring it over the limit ( responses never block, only requests )
    assertEquals(2, continues.get());
    assertEquals(998, returns.get());
    Thread.sleep(2000);
    assertEquals(Outcome.CONTINUE, amq.handleRequest(exc));
}
Also used : ArrayList(java.util.ArrayList) AMQuota(com.predic8.membrane.core.interceptor.apimanagement.quota.AMQuota) IOException(java.io.IOException) Exchange(com.predic8.membrane.core.exchange.Exchange) ServiceProxy(com.predic8.membrane.core.rules.ServiceProxy) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Outcome(com.predic8.membrane.core.interceptor.Outcome) Test(org.junit.Test)

Example 42 with Header

use of com.predic8.membrane.core.http.Header in project service-proxy by membrane.

the class AMStatisticsCollectorTest method testThreadedStatisticCollection.

@Test
public void testThreadedStatisticCollection() throws InterruptedException {
    final AMStatisticsCollector amSc = new AMStatisticsCollector();
    amSc.setCollectTimeInSeconds(2);
    ArrayList<Thread> threads = new ArrayList<Thread>();
    for (int i = 0; i < 1000; i++) {
        final int j = i;
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Exchange exc = new Exchange(null);
                    exc.setRequest(new Request.Builder().header("Test", "Test").body("Hello").build());
                    exc.setResponse(new Response.ResponseBuilder().header("Test", "Test").body("Hello back").build());
                    exc.setProperty(Exchange.API_KEY, "junit-" + j);
                    exc.setRule(new ServiceProxy());
                    exc.getRule().setName("junit API");
                    for (int k = 0; k < 10; k++) {
                        amSc.addExchangeToQueue(exc);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        threads.add(t);
        t.start();
    }
    for (Thread t : threads) {
        t.join();
    }
    Thread.sleep(amSc.getCollectTimeInSeconds() * 1000 * 2);
    amSc.shutdown();
}
Also used : ArrayList(java.util.ArrayList) Request(com.predic8.membrane.core.http.Request) AMStatisticsCollector(com.predic8.membrane.core.interceptor.apimanagement.statistics.AMStatisticsCollector) Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) ServiceProxy(com.predic8.membrane.core.rules.ServiceProxy) Test(org.junit.Test)

Example 43 with Header

use of com.predic8.membrane.core.http.Header in project service-proxy by membrane.

the class HeaderFilterInterceptorTest method doit.

@Test
public void doit() throws Exception {
    Exchange exc = new Exchange(null);
    exc.setResponse(Response.ok().header("a", "b").header("c", "d").header("c", "d2").header("e", "f").build());
    HeaderFilterInterceptor fhi = new HeaderFilterInterceptor();
    fhi.setRules(Lists.newArrayList(new Rule[] { // implicitly set by Response.ok()
    new Rule("Server", Action.REMOVE), new Rule("a", Action.KEEP), new Rule("c.*", Action.REMOVE) }));
    fhi.handleResponse(exc);
    HeaderField[] h = exc.getResponse().getHeader().getAllHeaderFields();
    assertEquals(3, h.length);
    assertEquals("Content-Length", h[0].getHeaderName().toString());
    assertEquals("a", h[1].getHeaderName().toString());
    assertEquals("e", h[2].getHeaderName().toString());
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) HeaderField(com.predic8.membrane.core.http.HeaderField) Rule(com.predic8.membrane.core.interceptor.HeaderFilterInterceptor.Rule) Test(org.junit.Test)

Example 44 with Header

use of com.predic8.membrane.core.http.Header in project service-proxy by membrane.

the class OAuth2ResourceInterceptor method handleRequest.

public boolean handleRequest(Exchange exc, String state, String publicURL, Session session) throws Exception {
    String path = uriFactory.create(exc.getDestinations().get(0)).getPath();
    if (path == null)
        return false;
    if (path.endsWith("/oauth2callback")) {
        try {
            Map<String, String> params = URLParamUtil.getParams(uriFactory, exc);
            String state2 = params.get("state");
            if (state2 == null)
                throw new RuntimeException("No CSRF token.");
            Map<String, String> param = URLParamUtil.parseQueryString(state2);
            if (param == null || !param.containsKey("security_token"))
                throw new RuntimeException("No CSRF token.");
            boolean csrfMatch = false;
            for (String state3 : stateToOriginalUrl.keySet()) if (param.get("security_token").equals(state3))
                csrfMatch = true;
            if (!csrfMatch)
                throw new RuntimeException("CSRF token mismatch.");
            Request originalRequest = stateToOriginalUrl.get(param.get("security_token"));
            String url = originalRequest.getUri();
            if (url == null)
                url = "/";
            stateToOriginalUrl.remove(state2);
            if (log.isDebugEnabled())
                log.debug("CSRF token match.");
            String code = params.get("code");
            if (code == null)
                throw new RuntimeException("No code received.");
            Exchange e = new Request.Builder().post(auth.getTokenEndpoint()).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded").header(Header.ACCEPT, "application/json").header(Header.USER_AGENT, Constants.USERAGENT).body("code=" + code + "&client_id=" + auth.getClientId() + "&client_secret=" + auth.getClientSecret() + "&redirect_uri=" + publicURL + "oauth2callback" + "&grant_type=authorization_code").buildExchange();
            LogInterceptor logi = null;
            if (log.isDebugEnabled()) {
                logi = new LogInterceptor();
                logi.setHeaderOnly(false);
                logi.handleRequest(e);
            }
            Response response = auth.doRequest(e);
            if (response.getStatusCode() != 200) {
                response.getBody().read();
                throw new RuntimeException("Authentication server returned " + response.getStatusCode() + ".");
            }
            if (log.isDebugEnabled())
                logi.handleResponse(e);
            HashMap<String, String> json = Util.parseSimpleJSONResponse(response);
            if (!json.containsKey("access_token"))
                throw new RuntimeException("No access_token received.");
            // and also "scope": "", "token_type": "bearer"
            String token = (String) json.get("access_token");
            OAuth2AnswerParameters oauth2Answer = new OAuth2AnswerParameters();
            synchronized (session) {
                // saving for logout
                session.getUserAttributes().put("access_token", token);
            }
            oauth2Answer.setAccessToken(token);
            oauth2Answer.setTokenType(json.get("token_type"));
            oauth2Answer.setExpiration(json.get("expires_in"));
            oauth2Answer.setRefreshToken(json.get("refresh_token"));
            oauth2Answer.setReceivedAt(LocalDateTime.now());
            if (json.containsKey("id_token")) {
                if (idTokenIsValid(json.get("id_token")))
                    oauth2Answer.setIdToken(json.get("id_token"));
                else
                    oauth2Answer.setIdToken("INVALID");
            }
            validTokens.put(token, true);
            Exchange e2 = new Request.Builder().get(auth.getUserInfoEndpoint()).header("Authorization", json.get("token_type") + " " + token).header("User-Agent", Constants.USERAGENT).header(Header.ACCEPT, "application/json").buildExchange();
            if (log.isDebugEnabled()) {
                logi.setHeaderOnly(false);
                logi.handleRequest(e2);
            }
            Response response2 = auth.doRequest(e2);
            if (log.isDebugEnabled())
                logi.handleResponse(e2);
            if (response2.getStatusCode() != 200) {
                statistics.accessTokenInvalid();
                throw new RuntimeException("User data could not be retrieved.");
            }
            statistics.accessTokenValid();
            HashMap<String, String> json2 = Util.parseSimpleJSONResponse(response2);
            oauth2Answer.setUserinfo(json2);
            session.getUserAttributes().put(OAUTH2_ANSWER, oauth2Answer.serialize());
            processUserInfo(json2, session);
            exc.setRequest(originalRequest);
            return true;
        } catch (Exception e) {
            exc.setResponse(Response.badRequest().body(e.getMessage()).build());
            return true;
        }
    }
    return false;
}
Also used : CacheBuilder(com.google.common.cache.CacheBuilder) Request(com.predic8.membrane.core.http.Request) ParseException(com.floreysoft.jmte.message.ParseException) IOException(java.io.IOException) Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) LogInterceptor(com.predic8.membrane.core.interceptor.LogInterceptor)

Example 45 with Header

use of com.predic8.membrane.core.http.Header in project service-proxy by membrane.

the class OAuth2ResourceInterceptor method revalidateToken.

private HashMap<String, String> revalidateToken(OAuth2AnswerParameters params) throws Exception {
    Exchange e2 = new Request.Builder().get(auth.getUserInfoEndpoint()).header("Authorization", params.getTokenType() + " " + params.getAccessToken()).header("User-Agent", Constants.USERAGENT).header(Header.ACCEPT, "application/json").buildExchange();
    Response response2 = auth.doRequest(e2);
    if (response2.getStatusCode() != 200) {
        statistics.accessTokenInvalid();
        return null;
    } else {
        statistics.accessTokenValid();
        return Util.parseSimpleJSONResponse(response2);
    }
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) Request(com.predic8.membrane.core.http.Request)

Aggregations

Exchange (com.predic8.membrane.core.exchange.Exchange)26 Header (com.predic8.membrane.core.http.Header)16 Request (com.predic8.membrane.core.http.Request)13 IOException (java.io.IOException)13 Response (com.predic8.membrane.core.http.Response)12 CacheBuilder (com.google.common.cache.CacheBuilder)8 Test (org.junit.Test)8 AbstractExchange (com.predic8.membrane.core.exchange.AbstractExchange)7 HttpClient (com.predic8.membrane.core.transport.http.HttpClient)6 UnknownHostException (java.net.UnknownHostException)6 MCElement (com.predic8.membrane.annot.MCElement)5 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)4 AbstractExchangeSnapshot (com.predic8.membrane.core.exchange.snapshots.AbstractExchangeSnapshot)4 DynamicAbstractExchangeSnapshot (com.predic8.membrane.core.exchange.snapshots.DynamicAbstractExchangeSnapshot)4 HeaderField (com.predic8.membrane.core.http.HeaderField)4 JsonFactory (com.fasterxml.jackson.core.JsonFactory)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 DateTimeFormatter (org.joda.time.format.DateTimeFormatter)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Cache (com.google.common.cache.Cache)2