Exemple #1
0
  private void describeLimitsForRequest(
      HttpServletRequest request, FilterDirector director, MediaType preferredMediaType) {
    if (preferredMediaType.getMimeType() == MimeType.UNKNOWN) {
      director.setFilterAction(FilterAction.RETURN);
      director.setResponseStatus(HttpStatusCode.NOT_ACCEPTABLE);
    } else {
      // If include absolute limits let request pass thru but prepare the combined
      // (absolute and active) limits when processing the response
      if (includeAbsoluteLimits) {
        director.setFilterAction(FilterAction.PROCESS_RESPONSE);
        director
            .requestHeaderManager()
            .putHeader(CommonHttpHeader.ACCEPT.toString(), MimeType.APPLICATION_XML.toString());
      } else {
        try {
          final MimeType mimeType =
              rateLimitingServiceHelper.queryActiveLimits(
                  request, preferredMediaType, director.getResponseOutputStream());

          director
              .responseHeaderManager()
              .putHeader(CommonHttpHeader.CONTENT_TYPE.toString(), mimeType.toString());
          director.setFilterAction(FilterAction.RETURN);
          director.setResponseStatus(HttpStatusCode.OK);
        } catch (Exception e) {
          consumeException(e, director);
        }
      }
    }
  }
  public VersionedOriginService getOriginServiceForRequest(
      HttpRequestInfo requestInfo, FilterDirector director) throws VersionedHostNotFoundException {
    // Check URI first to see if it matches configured host href
    VersionedOriginService targetOriginService = findOriginServiceByUri(requestInfo);

    // If version info not in URI look in accept header
    if (targetOriginService == null) {
      final MediaType range = requestInfo.getPreferedMediaRange();
      final VersionedMapType currentServiceVersion = getServiceVersionForMediaRange(range);

      if (currentServiceVersion != null) {
        final Destination destination =
            getHostForVersionMapping(currentServiceVersion.getServiceVersionMapping());
        director
            .requestHeaderManager()
            .putHeader(
                CommonHttpHeader.ACCEPT.toString(), currentServiceVersion.getMediaType().getBase());
        targetOriginService =
            new VersionedOriginService(
                currentServiceVersion.getServiceVersionMapping(), destination);
      }
    }

    return targetOriginService;
  }
    /** Test of handleRequest method, of class HeaderNormalizationHandler. */
    @Test
    public void shouldWhiteListRequestsMatchingUriAndMethod() {

      FilterDirector myDirector = new FilterDirectorImpl();
      when(request.getRequestURI()).thenReturn(requestUri1);
      when(request.getMethod()).thenReturn("GET");

      myDirector = handler.handleRequest(request, null);

      assertFalse(myDirector.requestHeaderManager().headersToRemove().isEmpty());
      assertFalse(myDirector.requestHeaderManager().headersToRemove().contains("X-Group-Header"));
      assertEquals(
          "Filter Director should be set to remove 2 headers",
          myDirector.requestHeaderManager().headersToRemove().size(),
          2);
    }
  @Override
  public FilterDirector handleRequest(
      HttpServletRequest httpRequest, ReadableHttpServletResponse httpResponse) {
    MutableHttpServletRequest request = MutableHttpServletRequest.wrap(httpRequest);
    MutableHttpServletResponse response =
        MutableHttpServletResponse.wrap(httpRequest, httpResponse);
    FilterDirector filterDirector = new FilterDirectorImpl();
    MediaType contentType = getContentType(request.getHeaderValue("content-type"));
    List<MediaType> acceptValues =
        getAcceptValues(request.getPreferredHeaders("Accept", DEFAULT_TYPE));
    List<XmlChainPool> pools =
        getHandlerChainPool(request.getMethod(), contentType, acceptValues, "", requestProcessors);

    if (pools.isEmpty()) {
      filterDirector.setFilterAction(FilterAction.PROCESS_RESPONSE);
      return filterDirector;
    }

    try {
      ServletInputStream in = request.getInputStream();
      TranslationResult result = null;
      for (XmlChainPool pool : pools) {
        final ByteBuffer internalBuffer = new CyclicByteBuffer(DEFAULT_BUFFER_SIZE, true);
        result =
            pool.executePool(
                new TranslationPreProcessor(in, contentType, true).getBodyStream(),
                new ByteBufferServletOutputStream(internalBuffer),
                getInputParameters(TranslationType.REQUEST, request, response, result));

        if (result.isSuccess()) {
          in = new ByteBufferInputStream(internalBuffer);
          request.setInputStream(in);
          result.applyResults(filterDirector);
          if (StringUtilities.isNotBlank(pool.getResultContentType())) {
            filterDirector
                .requestHeaderManager()
                .putHeader("content-type", pool.getResultContentType());
            contentType = getContentType(pool.getResultContentType());
          }
          filterDirector.setFilterAction(FilterAction.PROCESS_RESPONSE);
        } else {
          filterDirector.setResponseStatus(HttpStatusCode.BAD_REQUEST);
          filterDirector.setFilterAction(FilterAction.RETURN);
          break;
        }
      }
    } catch (IOException ex) {
      LOG.error("Error executing request transformer chain", ex);
      filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR);
      filterDirector.setFilterAction(FilterAction.RETURN);
    }

    return filterDirector;
  }
    /** Test of handleRequest method, of class HeaderNormalizationHandler. */
    @Test
    public void shouldWhiteListRequestsWithCatchAllUri() {

      FilterDirector myDirector = new FilterDirectorImpl();
      when(request.getRequestURI()).thenReturn(requestUri1);
      when(request.getMethod()).thenReturn("GET");

      myDirector = handler.handleRequest(request, null);

      assertFalse(
          "Filter Director should be set to remove headers",
          myDirector.requestHeaderManager().headersToRemove().isEmpty());
      assertTrue(
          "Filter Director should be set to remove the 'X-Auth-Token'",
          myDirector.requestHeaderManager().headersToRemove().contains("x-auth-token"));
      assertEquals(
          "Filter Director should be set to remove 4 headers",
          myDirector.requestHeaderManager().headersToRemove().size(),
          4);
    }
    @Test
    public void shouldNotWhiteListRequestNotMatchingUri() {

      FilterDirector myDirector = new FilterDirectorImpl();
      when(request.getRequestURI()).thenReturn(requestUri2);
      when(request.getMethod()).thenReturn("DELETE");

      myDirector = handler.handleRequest(request, null);

      assertTrue(myDirector.requestHeaderManager().headersToRemove().isEmpty());
    }
 @Test
 public void shouldNotCatchUserInQueryParam() {
   when(request.getRequestURI()).thenReturn("/v1.0/servers/service");
   when(request.getQueryString()).thenReturn("crowd=huge&username=usertest1");
   final FilterDirector requestDirector = handler.handleRequest(request, response);
   assertFalse(
       requestDirector
           .requestHeaderManager()
           .headersToAdd()
           .get("x-authorization")
           .toString()
           .equalsIgnoreCase("[Proxy usertest1]"));
 }
    @Test
    public void shouldNotHaveUserHeader() {
      when(request.getRequestURI()).thenReturn(URIFAIL);

      FilterDirector result = handler.handleRequest(request, response);

      Set<String> values =
          result
              .requestHeaderManager()
              .headersToAdd()
              .get(HeaderName.wrap(PowerApiHeader.USER.toString()));
      assertTrue(
          "Should not have " + PowerApiHeader.USER.toString() + " header set.",
          values == null || values.isEmpty());
    }
    @Test
    public void shouldSetTheUserHeaderToThe2ndRegexResult() {
      when(request.getRequestURI()).thenReturn(URI2);

      FilterDirector result = handler.handleRequest(request, response);

      Set<String> values =
          result
              .requestHeaderManager()
              .headersToAdd()
              .get(HeaderName.wrap(PowerApiHeader.USER.toString()));
      assertFalse(
          "Should have " + PowerApiHeader.USER.toString() + " header set.",
          values == null || values.isEmpty());

      String userName = values.iterator().next();

      assertEquals("Should find user name in header", USER2 + QUALITY_VALUE, userName);
    }
  @Override
  public FilterDirector handleResponse(
      HttpServletRequest httpRequest, ReadableHttpServletResponse httpResponse) {
    MutableHttpServletRequest request = MutableHttpServletRequest.wrap(httpRequest);
    MutableHttpServletResponse response =
        MutableHttpServletResponse.wrap(httpRequest, httpResponse);
    final FilterDirector filterDirector = new FilterDirectorImpl();
    filterDirector.setFilterAction(FilterAction.PASS);
    MediaType contentType = getContentType(response.getHeaderValue("Content-Type"));
    List<MediaType> acceptValues =
        getAcceptValues(request.getPreferredHeaders("Accept", DEFAULT_TYPE));
    List<XmlChainPool> pools =
        getHandlerChainPool(
            "",
            contentType,
            acceptValues,
            String.valueOf(response.getStatus()),
            responseProcessors);

    if (pools.isEmpty()) {
      filterDirector.setResponseStatusCode(response.getStatus());
      return filterDirector;
    }

    try {
      filterDirector.setResponseStatusCode(response.getStatus());
      if (response.hasBody()) {
        InputStream in = response.getBufferedOutputAsInputStream();

        TranslationResult result = null;
        for (XmlChainPool pool : pools) {
          if (in.available() > 0) {
            result =
                pool.executePool(
                    new TranslationPreProcessor(in, contentType, true).getBodyStream(),
                    filterDirector.getResponseOutputStream(),
                    getInputParameters(TranslationType.RESPONSE, request, response, result));

            if (result.isSuccess()) {
              result.applyResults(filterDirector);
              if (StringUtilities.isNotBlank(pool.getResultContentType())) {
                filterDirector
                    .requestHeaderManager()
                    .putHeader("content-type", pool.getResultContentType());
                contentType = getContentType(pool.getResultContentType());
              }
              in = new ByteArrayInputStream(filterDirector.getResponseMessageBodyBytes());
            } else {
              filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR);
              response.setContentLength(0);
              filterDirector.responseHeaderManager().removeHeader("Content-Length");
              break;
            }
          }
        }
      }
    } catch (IOException ex) {
      LOG.error("Error executing response transformer chain", ex);
      filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR);
      response.setContentLength(0);
    }

    return filterDirector;
  }