@Override
 public FilterDirector handleRequest(
     HttpServletRequest request, ReadableHttpServletResponse response) {
   FilterDirector filterDirector = new FilterDirectorImpl();
   filterDirector.setFilterAction(FilterAction.PROCESS_RESPONSE);
   return filterDirector;
 }
  @Override
  public FilterDirector handleResponse(
      HttpServletRequest request, ReadableHttpServletResponse response) {
    FilterDirector myDirector = new FilterDirectorImpl();

    /// The WWW Authenticate header can be used to communicate to the client
    // (since we are a proxy) how to correctly authenticate itself
    final String wwwAuthenticateHeader =
        response.getHeader(CommonHttpHeader.WWW_AUTHENTICATE.toString());

    switch (HttpStatusCode.fromInt(response.getStatus())) {
        // NOTE: We should only mutate the WWW-Authenticate header on a
        // 401 (unauthorized) or 403 (forbidden) response from the origin service
      case UNAUTHORIZED:
      case FORBIDDEN:
        myDirector = updateHttpResponse(myDirector, wwwAuthenticateHeader);
        break;
      case NOT_IMPLEMENTED:
        if ((!StringUtilities.isBlank(wwwAuthenticateHeader)
            && wwwAuthenticateHeader.contains("Delegated"))) {
          myDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR);
          LOG.error(
              "Repose authentication component is configured as delegetable but origin service does not support delegated mode.");
        } else {
          myDirector.setResponseStatus(HttpStatusCode.NOT_IMPLEMENTED);
        }
        break;
    }

    return myDirector;
  }
 @Test
 public void shouldProcessUriNotOnWhiteListAsNonAuthedRequest() {
   when(request.getRequestURI()).thenReturn("?param=/v1.0/application.wadl");
   final FilterDirector requestDirector = handler.handleRequest(request, response);
   assertEquals(
       "Auth component must process requests with uri not on white list when in delegated mode",
       FilterAction.PROCESS_RESPONSE,
       requestDirector.getFilterAction());
 }
 @Test
 public void shouldReturnForUriNotOnWhiteList() {
   when(request.getRequestURI()).thenReturn("?param=/v1.0/application.wadl");
   final FilterDirector requestDirector = handler.handleRequest(request, response);
   assertEquals(
       "Auth component must return requests with uri not on white list",
       FilterAction.RETURN,
       requestDirector.getFilterAction());
 }
  @Test
  public void handleRequest_nullChain() throws Exception {
    compressionHandler.setFilterChain(null);

    FilterDirector director = compressionHandler.handleRequest(request, response);

    assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.intValue(), director.getResponseStatusCode());
    assertThat(director.getFilterAction(), equalTo(FilterAction.RETURN));
  }
    @Test
    public void shouldRejectInvalidCredentials() {
      final FilterDirector director = handler.handleRequest(request, response);

      assertEquals(
          "Auth component must reject invalid requests",
          FilterAction.RETURN,
          director.getFilterAction());
    }
 @Test
 public void shouldRejectInvalidCredentials() {
   when(request.getRequestURI()).thenReturn("/start/12345/a/resource");
   final FilterDirector requestDirector = handler.handleRequest(request, response);
   assertEquals(
       "Auth component must reject requests with invalid credentials",
       FilterAction.RETURN,
       requestDirector.getFilterAction());
 }
 @Test
 public void shouldPassUriOnWhiteList() {
   when(request.getRequestURI()).thenReturn("/v1.0/application.wadl");
   final FilterDirector requestDirector = handler.handleRequest(request, response);
   assertEquals(
       "Auth component must pass requests with uri on white list",
       FilterAction.PASS,
       requestDirector.getFilterAction());
 }
 @Test
 public void shouldPassNullOrBlankCredentials() {
   when(request.getRequestURI()).thenReturn("/start/");
   when(request.getHeader(anyString())).thenReturn("");
   final FilterDirector requestDirector = handler.handleRequest(request, response);
   assertEquals(
       "Auth component must pass requests with invalid credentials",
       FilterAction.PROCESS_RESPONSE,
       requestDirector.getFilterAction());
 }
  public void onCacheDelete(HttpServletRequest request, final FilterDirector director)
      throws DatastoreOperationException, MalformedCacheRequestException {
    final CacheRequest cacheDelete = CacheRequest.marshallCacheRequest(request);
    hashRingDatastore.remove(
        cacheDelete.getCacheKey(),
        encodingProvider.decode(cacheDelete.getCacheKey()),
        cacheDelete.getRequestedRemoteBehavior());

    director.setResponseStatus(HttpStatusCode.ACCEPTED);
    director.setFilterAction(FilterAction.RETURN);
  }
    @Test
    public void shouldCheckCacheForGroup() throws IOException {
      final AuthToken user = new OpenStackToken(authResponse);
      when(authService.validateToken(anyString(), anyString())).thenReturn(user);

      final FilterDirector director = handlerWithCache.handleRequest(request, response);

      verify(store, times(1)).get(eq(AUTH_GROUP_CACHE_PREFIX + "." + user.getTokenId()));
      assertEquals(
          "Auth component must pass valid requests", FilterAction.PASS, director.getFilterAction());
    }
  @Test
  public void handleRequest_validRequest() throws Exception {
    compressionHandler.setFilterChain(filterChain);
    doNothing().when(compressingFilter, "doFilter", request, response, filterChain);
    when(response.getStatus()).thenReturn(200);

    FilterDirector director = compressionHandler.handleRequest(request, response);

    assertEquals(HttpStatusCode.OK.intValue(), director.getResponseStatusCode());
    assertThat(director.getFilterAction(), equalTo(FilterAction.RETURN));
  }
    @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 shouldReturn501OnAuthFailureWithNoWwwAuthenticateHeaderSet() {
      when(response.getStatus()).thenReturn(401);

      final FilterDirector responseDirector = handler.handleResponse(request, response);

      assertEquals(
          "Auth component must identify proxy auth failures",
          HttpStatusCode.INTERNAL_SERVER_ERROR,
          responseDirector.getResponseStatus());
    }
    @Test
    public void shouldPassValidCredentials() {
      final AuthToken token =
          generateCachableTokenInfo("role1,role2", "tokentokentoken", "username", "12345");
      when(authService.validateToken(anyString(), anyString())).thenReturn(token);

      final FilterDirector director = handler.handleRequest(request, response);

      assertEquals(
          "Auth component must pass valid requests", FilterAction.PASS, director.getFilterAction());
    }
    @Test
    public void shouldNotModifyResponseOnResponseStatusCodeNotEqualTo401or403() {
      when(request.getRequestURI()).thenReturn("/start/12345/a/resource");
      when(response.getStatus()).thenReturn(200);

      final FilterDirector responseDirector = handler.handleResponse(request, response);

      assertEquals(
          "Auth component must pass valid, delegated responses",
          FilterAction.NOT_SET,
          responseDirector.getFilterAction());
    }
  @Test
  public void handleRequest_handleGZIPError() throws Exception {
    compressionHandler.setFilterChain(filterChain);
    doThrow(new ZipException("Not in GZIP format"))
        .when(compressingFilter)
        .doFilter(any(ServletRequest.class), any(ServletResponse.class), any(FilterChain.class));

    FilterDirector director = compressionHandler.handleRequest(request, response);

    assertEquals(HttpStatusCode.BAD_REQUEST.intValue(), director.getResponseStatusCode());
    assertThat(director.getFilterAction(), equalTo(FilterAction.RETURN));
  }
    @Test
    public void shouldCheckCacheForCredentials() throws IOException {
      final AuthToken user = new OpenStackToken(authResponse);
      byte[] userInfoBytes = ObjectSerializer.instance().writeObject(user);
      when(authService.validateToken(anyString(), anyString())).thenReturn(user);

      final FilterDirector director = handlerWithCache.handleRequest(request, response);

      verify(store).get(eq(AUTH_TOKEN_CACHE_PREFIX + "." + user.getTokenId()));
      assertEquals(
          "Auth component must pass valid requests", FilterAction.PASS, director.getFilterAction());
    }
  @Test
  public void handleRequest_handleGenericIOError() throws Exception {
    compressionHandler.setFilterChain(filterChain);
    doThrow(new IOException())
        .when(compressingFilter)
        .doFilter(any(ServletRequest.class), any(ServletResponse.class), any(FilterChain.class));

    FilterDirector director = compressionHandler.handleRequest(request, response);

    assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.intValue(), director.getResponseStatusCode());
    assertThat(director.getFilterAction(), equalTo(FilterAction.RETURN));
  }
    @Test
    public void shouldNotUseCachedGroupInfoForExpired() throws InterruptedException {
      final AuthToken user = new OpenStackToken(authResponse);
      when(authService.validateToken(anyString(), anyString())).thenReturn(user);

      final FilterDirector director = handlerWithCache.handleRequest(request, response);

      verify(store, times(1)).get(eq(AUTH_TOKEN_CACHE_PREFIX + "." + user.getTokenId()));
      // Service should be called since token has expired
      verify(authService, times(0)).getGroups(anyString());
      assertEquals(
          "Auth component must pass valid requests", FilterAction.PASS, director.getFilterAction());
    }
    @Test
    public void shouldReturn501OnAuth501FailureWithDelegatedWwwAuthenticateHeaderNotSet() {
      when(response.getHeader(CommonHttpHeader.WWW_AUTHENTICATE.toString()))
          .thenReturn("Not-Delegate");
      when(response.getStatus()).thenReturn(501);

      final FilterDirector responseDirector = handler.handleResponse(request, response);

      assertEquals(
          "Auth component must identify proxy auth failures",
          HttpStatusCode.NOT_IMPLEMENTED,
          responseDirector.getResponseStatus());
    }
  @Override
  public FilterDirector handleResponse(
      HttpServletRequest request, ReadableHttpServletResponse response) {
    FilterDirector filterDirector = new FilterDirectorImpl();
    filterDirector.setResponseStatusCode(response.getStatus());
    filterDirector.setFilterAction(FilterAction.PASS);

    for (HttpLoggerWrapper loggerWrapper : loggers) {
      loggerWrapper.handle(request, response);
    }

    return filterDirector;
  }
 @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]"));
 }
Beispiel #24
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 void onCachePut(HttpServletRequest request, final FilterDirector director)
      throws MalformedCacheRequestException, DatastoreOperationException {
    final CacheRequest cachePut = CacheRequest.marshallCachePutRequest(request);
    hashRingDatastore.put(
        cachePut.getCacheKey(),
        encodingProvider.decode(cachePut.getCacheKey()),
        cachePut.getPayload(),
        cachePut.getTtlInSeconds(),
        TimeUnit.SECONDS,
        cachePut.getRequestedRemoteBehavior());

    director.setResponseStatus(HttpStatusCode.ACCEPTED);
    director.setFilterAction(FilterAction.RETURN);
  }
    @Test
    public void shouldUseCachedUserInfo() {
      final AuthToken user = new OpenStackToken(authResponse);
      when(authService.validateToken(anyString(), anyString())).thenReturn(user);

      when(store.get(eq(AUTH_TOKEN_CACHE_PREFIX + "." + user.getTokenId()))).thenReturn(user);

      final FilterDirector director = handlerWithCache.handleRequest(request, response);

      // Service should not be called if we found the token in the cache
      verify(authService, times(0)).validateToken(anyString(), anyString());
      assertEquals(
          "Auth component must pass valid requests", FilterAction.PASS, director.getFilterAction());
    }
    @Test
    public void shouldNotUseCachedUserInfoForBadTokenId() {
      authResponse.getToken().setId("differentId");
      final AuthToken user = new OpenStackToken(authResponse);
      when(authService.validateToken(anyString(), anyString())).thenReturn(user);

      when(store.get(eq(AUTH_TOKEN_CACHE_PREFIX + ".104772"))).thenReturn(user);

      final FilterDirector director = handlerWithCache.handleRequest(request, response);

      verify(authService, times(1)).validateToken(anyString(), anyString());
      assertEquals(
          "Auth component must pass valid requests", FilterAction.PASS, director.getFilterAction());
    }
    @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 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);
    }
  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;
  }