public boolean checkCorsPreflight(Request request, Response response) {
   log.finer("checkCorsPreflight " + request.getRequestURI());
   if (!request.getMethod().equalsIgnoreCase("OPTIONS")) {
     log.finer("checkCorsPreflight: not options ");
     return false;
   }
   if (request.getHeader("Origin") == null) {
     log.finer("checkCorsPreflight: no origin header");
     return false;
   }
   log.finer("Preflight request returning");
   response.setStatus(HttpServletResponse.SC_OK);
   String origin = request.getHeader("Origin");
   response.setHeader("Access-Control-Allow-Origin", origin);
   response.setHeader("Access-Control-Allow-Credentials", "true");
   String requestMethods = request.getHeader("Access-Control-Request-Method");
   if (requestMethods != null) {
     if (deployment.getCorsAllowedMethods() != null) {
       requestMethods = deployment.getCorsAllowedMethods();
     }
     response.setHeader("Access-Control-Allow-Methods", requestMethods);
   }
   String allowHeaders = request.getHeader("Access-Control-Request-Headers");
   if (allowHeaders != null) {
     if (deployment.getCorsAllowedHeaders() != null) {
       allowHeaders = deployment.getCorsAllowedHeaders();
     }
     response.setHeader("Access-Control-Allow-Headers", allowHeaders);
   }
   if (deployment.getCorsMaxAge() > -1) {
     response.setHeader("Access-Control-Max-Age", Integer.toString(deployment.getCorsMaxAge()));
   }
   return true;
 }
    public boolean parse(Request request, String authorization) {
      // Validate the authorization credentials format
      if (authorization == null) {
        return false;
      }

      Map<String, String> directives;
      try {
        directives = Authorization.parseAuthorizationDigest(new StringReader(authorization));
      } catch (IOException e) {
        return false;
      }

      if (directives == null) {
        return false;
      }

      method = request.getMethod();
      userName = directives.get("username");
      realmName = directives.get("realm");
      nonce = directives.get("nonce");
      nc = directives.get("nc");
      cnonce = directives.get("cnonce");
      qop = directives.get("qop");
      uri = directives.get("uri");
      response = directives.get("response");
      opaqueReceived = directives.get("opaque");

      return true;
    }
 /**
  * /** When we do GET call for WSDL/WADL, we do not want to authenticate/throttle the request.
  *
  * <p>TODO check logic
  *
  * @param request
  * @param response
  * @param compositeValve
  * @param context
  */
 private void handleWSDLGetRequest(
     Request request, Response response, CompositeValve compositeValve, String context) {
   if (request.getMethod().equals(Constants.Configuration.HTTP_METHOD_GET)) {
     // TODO:Need to get these paths from a config file.
     if (request.getRequestURI().matches(context + "/[^/]*/services")) {
       getNext().invoke(request, response, compositeValve);
       return;
     }
     Enumeration<String> params = request.getParameterNames();
     String paramName = null;
     while (params.hasMoreElements()) {
       paramName = params.nextElement();
       if (paramName.endsWith("wsdl") || paramName.endsWith("wadl")) {
         getNext().invoke(request, response, compositeValve);
         return;
       }
     }
   }
 }
  @BeforeMethod
  public void setUp() throws Exception {
    _service = mock(MemcachedSessionService.class);
    _request = mock(Request.class);
    _response = mock(Response.class);

    final Context _contextContainer = mock(Context.class);
    final Host _hostContainer = mock(Host.class);
    final SessionManager _manager = mock(SessionManager.class);

    when(_service.getManager()).thenReturn(_manager);
    when(_manager.getContainer()).thenReturn(_contextContainer);
    when(_contextContainer.getParent()).thenReturn(_hostContainer);
    when(_contextContainer.getPath()).thenReturn("/");

    _sessionTrackerValve = createSessionTrackerValve();
    _nextValve = mock(Valve.class);
    _sessionTrackerValve.setNext(_nextValve);
    _sessionTrackerValve.setContainer(_hostContainer);
    _memcachedNodesManager = mock(MemcachedNodesManager.class);
    _sessionIdFormat = mock(SessionIdFormat.class);

    when(_request.getRequestURI()).thenReturn("/someRequest");
    when(_request.getMethod()).thenReturn("GET");
    when(_request.getQueryString()).thenReturn(null);
    when(_request.getContext()).thenReturn(_contextContainer);

    when(_request.getNote(eq(RequestTrackingHostValve.REQUEST_PROCESSED))).thenReturn(Boolean.TRUE);
    when(_request.getNote(eq(RequestTrackingHostValve.SESSION_ID_CHANGED)))
        .thenReturn(Boolean.FALSE);

    when(_sessionIdFormat.extractMemcachedId(anyString())).thenReturn(PRIMARY_NODE_IDENTIFIER);
    when(_service.getMemcachedNodesManager()).thenReturn(_memcachedNodesManager);
    when(_memcachedNodesManager.isNodeAvailable(PRIMARY_NODE_IDENTIFIER))
        .thenReturn(IS_PRIMARY_MEMCACHED_NODE_OPERATIONAL);
    when(_memcachedNodesManager.getSessionIdFormat()).thenReturn(_sessionIdFormat);
  }
Example #5
0
  /**
   * Log the interesting request parameters, invoke the next Valve in the sequence, and log the
   * interesting response parameters.
   *
   * @param request The servlet request to be processed
   * @param response The servlet response to be created
   * @exception IOException if an input/output error occurs
   * @exception ServletException if a servlet error occurs
   */
  public void invoke(Request request, Response response) throws IOException, ServletException {

    Log log = container.getLogger();

    // Log pre-service information
    log.info("REQUEST URI       =" + request.getRequestURI());
    log.info("          authType=" + request.getAuthType());
    log.info(" characterEncoding=" + request.getCharacterEncoding());
    log.info("     contentLength=" + request.getContentLength());
    log.info("       contentType=" + request.getContentType());
    log.info("       contextPath=" + request.getContextPath());
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++)
        log.info("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
    }
    Enumeration hnames = request.getHeaderNames();
    while (hnames.hasMoreElements()) {
      String hname = (String) hnames.nextElement();
      Enumeration hvalues = request.getHeaders(hname);
      while (hvalues.hasMoreElements()) {
        String hvalue = (String) hvalues.nextElement();
        log.info("            header=" + hname + "=" + hvalue);
      }
    }
    log.info("            locale=" + request.getLocale());
    log.info("            method=" + request.getMethod());
    Enumeration pnames = request.getParameterNames();
    while (pnames.hasMoreElements()) {
      String pname = (String) pnames.nextElement();
      String pvalues[] = request.getParameterValues(pname);
      StringBuffer result = new StringBuffer(pname);
      result.append('=');
      for (int i = 0; i < pvalues.length; i++) {
        if (i > 0) result.append(", ");
        result.append(pvalues[i]);
      }
      log.info("         parameter=" + result.toString());
    }
    log.info("          pathInfo=" + request.getPathInfo());
    log.info("          protocol=" + request.getProtocol());
    log.info("       queryString=" + request.getQueryString());
    log.info("        remoteAddr=" + request.getRemoteAddr());
    log.info("        remoteHost=" + request.getRemoteHost());
    log.info("        remoteUser="******"requestedSessionId=" + request.getRequestedSessionId());
    log.info("            scheme=" + request.getScheme());
    log.info("        serverName=" + request.getServerName());
    log.info("        serverPort=" + request.getServerPort());
    log.info("       servletPath=" + request.getServletPath());
    log.info("          isSecure=" + request.isSecure());
    log.info("---------------------------------------------------------------");

    // Perform the request
    getNext().invoke(request, response);

    // Log post-service information
    log.info("---------------------------------------------------------------");
    log.info("          authType=" + request.getAuthType());
    log.info("     contentLength=" + response.getContentLength());
    log.info("       contentType=" + response.getContentType());
    Cookie rcookies[] = response.getCookies();
    for (int i = 0; i < rcookies.length; i++) {
      log.info(
          "            cookie="
              + rcookies[i].getName()
              + "="
              + rcookies[i].getValue()
              + "; domain="
              + rcookies[i].getDomain()
              + "; path="
              + rcookies[i].getPath());
    }
    String rhnames[] = response.getHeaderNames();
    for (int i = 0; i < rhnames.length; i++) {
      String rhvalues[] = response.getHeaderValues(rhnames[i]);
      for (int j = 0; j < rhvalues.length; j++)
        log.info("            header=" + rhnames[i] + "=" + rhvalues[j]);
    }
    log.info("           message=" + response.getMessage());
    log.info("        remoteUser="******"            status=" + response.getStatus());
    log.info("===============================================================");
  }
  public void invoke(Request request, Response response, CompositeValve compositeValve) {

    if (authenticator == null) {
      authenticator = new APITokenAuthenticator();
    }

    String context = request.getContextPath();
    if (context == null || context.equals("")) {
      // Invoke next valve in pipe.
      getNext().invoke(request, response, compositeValve);
      return;
    }

    // todo remove version from context - special case for apps
    //        context = stripVersionfromContext(context);

    boolean contextExist;
    Boolean contextValueInCache = null;
    if (APIUtil.getAPIContextCache().get(context) != null) {
      contextValueInCache =
          Boolean.parseBoolean(APIUtil.getAPIContextCache().get(context).toString());
    }

    if (contextValueInCache != null) {
      contextExist = contextValueInCache;
    } else {
      contextExist = ApiMgtDAO.isContextExist(context);
      APIUtil.getAPIContextCache().put(context, contextExist);
    }

    if (!contextExist) {
      getNext().invoke(request, response, compositeValve);
      return;
    }

    handleWSDLGetRequest(request, response, compositeValve, context);

    String dispatcherPath = null;
    boolean forwardingRequired = false;

    long requestTime = System.currentTimeMillis();
    APIManagerInterceptorOps interceptorOps = new APIManagerInterceptorOps();
    UsageStatConfiguration statConfiguration = new UsageStatConfiguration();
    if (contextExist) {
      // Use embedded API Management
      if (log.isDebugEnabled()) {
        log.debug("API Manager Interceptor Valve Got invoked!!");
      }

      String bearerToken = request.getHeader(APIConstants.OperationParameter.AUTH_PARAM_NAME);
      String accessToken = null;

      /* Authenticate*/
      try {
        if (bearerToken != null) {
          accessToken = APIManagetInterceptorUtils.getBearerToken(bearerToken);
        } else {
          // There can be some API published with None Auth Type
          /*
           * throw new
           * APIFaultException(APIConstants.KeyValidationStatus
           * .API_AUTH_INVALID_CREDENTIALS,
           * "Invalid format for Authorization header. Expected 'Bearer <token>'"
           * );
           */
        }

        String apiVersion = APIManagetInterceptorUtils.getAPIVersion(request);
        dispatcherPath = apiVersion;
        // todo get proper version
        // handling version for web-application API mgmt

        if (!APIManagerInterceptorConstant.DEFAULT_API_VERSION.equals(apiVersion)
            || "".equals(apiVersion)) {
          apiVersion = APIManagerInterceptorConstant.DEFAULT_API_VERSION;
        } else {
          forwardingRequired = true;
        }

        String domain = request.getHeader(APITokenValidator.getAPIManagerClientDomainHeader());
        String authLevel =
            authenticator.getResourceAuthenticationScheme(
                context, apiVersion, request.getRequestURI(), request.getMethod());
        if (authLevel.equals(APIConstants.NO_MATCHING_AUTH_SCHEME)) {
          APIManagetInterceptorUtils.handleNoMatchAuthSchemeCallForRestService(
              response, request.getMethod(), request.getRequestURI(), apiVersion, context);
          return;
        } else {
          interceptorOps.doAuthenticate(
              context,
              APIConstants.DEFAULT_VERSION_PREFIX + apiVersion,
              accessToken,
              authLevel,
              domain);
        }
      } catch (APIManagementException e) {
        // ignore
      } catch (APIFaultException e) {
          /* If !isAuthorized APIFaultException is thrown*/
        APIManagetInterceptorUtils.handleAPIFaultForRestService(
            e,
            APIManagerErrorConstants.API_SECURITY_NS,
            APIManagerErrorConstants.API_SECURITY_NS_PREFIX,
            response);
        return;
      }
      /* Throttle*/
      try {
        interceptorOps.doThrottle(request, accessToken);
      } catch (APIFaultException e) {
        APIManagetInterceptorUtils.handleAPIFaultForRestService(
            e,
            APIManagerErrorConstants.API_THROTTLE_NS,
            APIManagerErrorConstants.API_THROTTLE_NS_PREFIX,
            response);
        return;
      }
      /* Publish Statistic if enabled*/
      if (statConfiguration.isStatsPublishingEnabled()) {
        try {
          interceptorOps.publishStatistics(request, requestTime, false);
        } catch (APIManagementException e) {
          log.error("Error occurred when publishing stats", e);
        }
      }
    }

    if (forwardingRequired) {
      try {
        request
            .getRequestDispatcher(
                request.getContextPath() + "/services/customers/customerservice/customers/123")
            .forward(request, response);
        //                response.sendRedirect(request.getContextPath() +
        // "/services/customers/customerservice/customers/123");
        //                return;
      } catch (ServletException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    // Invoke next valve in pipe.
    getNext().invoke(request, response, compositeValve);

    // Handle Responses
    if (contextExist && statConfiguration.isStatsPublishingEnabled()) {
      try {
        interceptorOps.publishStatistics(request, requestTime, true);
      } catch (APIManagementException e) {
        log.error("Error occurred when publishing stats", e);
      }
    }
  }
  public void invoke(Request request, Response response, CompositeValve compositeValve) {

    String context = request.getContextPath();
    if (context == null || context.equals("")) {
      // Invoke next valve in pipe.
      getNext().invoke(request, response, compositeValve);
      return;
    }

    boolean contextExist;
    Boolean contextValueInCache = null;
    if (APIUtil.getAPIContextCache().get(context) != null) {
      contextValueInCache =
          Boolean.parseBoolean(APIUtil.getAPIContextCache().get(context).toString());
    }

    if (contextValueInCache != null) {
      contextExist = contextValueInCache;
    } else {
      contextExist = ApiMgtDAO.isContextExist(context);
      APIUtil.getAPIContextCache().put(context, contextExist);
    }

    if (!contextExist) {
      getNext().invoke(request, response, compositeValve);
      return;
    }

    handleWSDLGetRequest(request, response, compositeValve, context);

    long requestTime = System.currentTimeMillis();
    APIManagerInterceptorOps interceptorOps = new APIManagerInterceptorOps();
    UsageStatConfiguration statConfiguration = new UsageStatConfiguration();
    if (contextExist) {
      // Use embedded WebApp Management
      if (log.isDebugEnabled()) {
        log.debug("WebApp Manager Interceptor Valve Got invoked!!");
      }

      String bearerToken = request.getHeader(APIConstants.OperationParameter.AUTH_PARAM_NAME);
      String accessToken = null;

      /* Authenticate*/
      try {
        if (bearerToken != null) {
          accessToken = APIManagetInterceptorUtils.getBearerToken(bearerToken);
        } else {
          // There can be some WebApp published with None Auth Type
          /*
           * throw new
           * APIFaultException(APIConstants.KeyValidationStatus
           * .API_AUTH_INVALID_CREDENTIALS,
           * "Invalid format for Authorization header. Expected 'Bearer <token>'"
           * );
           */
        }

        String apiVersion = APIManagetInterceptorUtils.getAPIVersion(request);
        String domain = request.getHeader(APITokenValidator.getAPIManagerClientDomainHeader());
        String authLevel =
            authenticator.getResourceAuthenticationScheme(
                context, apiVersion, request.getRequestURI(), request.getMethod());
        if (authLevel == APIConstants.NO_MATCHING_AUTH_SCHEME) {
          APIManagetInterceptorUtils.handleNoMatchAuthSchemeCallForRestService(
              response, request.getMethod(), request.getRequestURI(), apiVersion, context);
          return;
        } else {
          interceptorOps.doAuthenticate(context, apiVersion, accessToken, authLevel, domain);
        }
      } catch (APIManagementException e) {
        // ignore
      } catch (APIFaultException e) {
          /* If !isAuthorized APIFaultException is thrown*/
        APIManagetInterceptorUtils.handleAPIFaultForRestService(
            e,
            APIManagerErrorConstants.API_SECURITY_NS,
            APIManagerErrorConstants.API_SECURITY_NS_PREFIX,
            response);
        return;
      }
      /* Throttle*/
      try {
        interceptorOps.doThrottle(request, accessToken);
      } catch (APIFaultException e) {
        APIManagetInterceptorUtils.handleAPIFaultForRestService(
            e,
            APIManagerErrorConstants.API_THROTTLE_NS,
            APIManagerErrorConstants.API_THROTTLE_NS_PREFIX,
            response);
        return;
      }
      /* Publish Statistic if enabled*/
      if (statConfiguration.isStatsPublishingEnabled()) {
        try {
          interceptorOps.publishStatistics(request, requestTime, false);
        } catch (APIManagementException e) {
          log.error("Error occured when publishing stats", e);
        }
      }
    }

    // Invoke next valve in pipe.
    getNext().invoke(request, response, compositeValve);

    // Handle Responses
    if (contextExist && statConfiguration.isStatsPublishingEnabled()) {
      try {
        interceptorOps.publishStatistics(request, requestTime, true);
      } catch (APIManagementException e) {
        log.error("Error occured when publishing stats", e);
      }
    }
  }
  /**
   * Return the SecurityConstraints configured to guard the request URI for this request, or <code>
   * null</code> if there is no such constraint.
   *
   * @param request Request we are processing
   * @param context Context the Request is mapped to
   */
  @Override
  public SecurityConstraint[] findSecurityConstraints(Request request, Context context) {

    ArrayList<SecurityConstraint> results = null;
    // Are there any defined security constraints?
    SecurityConstraint constraints[] = context.findConstraints();
    if ((constraints == null) || (constraints.length == 0)) {
      if (log.isDebugEnabled()) log.debug("  No applicable constraints defined");
      return (null);
    }

    // Check each defined security constraint
    String uri = request.getRequestPathMB().toString();
    // Bug47080 - in rare cases this may be null
    // Mapper treats as '/' do the same to prevent NPE
    if (uri == null) {
      uri = "/";
    }

    String method = request.getMethod();
    int i;
    boolean found = false;
    for (i = 0; i < constraints.length; i++) {
      SecurityCollection[] collection = constraints[i].findCollections();

      // If collection is null, continue to avoid an NPE
      // See Bugzilla 30624
      if (collection == null) {
        continue;
      }

      if (log.isDebugEnabled()) {
        log.debug(
            "  Checking constraint '"
                + constraints[i]
                + "' against "
                + method
                + " "
                + uri
                + " --> "
                + constraints[i].included(uri, method));
      }

      for (int j = 0; j < collection.length; j++) {
        String[] patterns = collection[j].findPatterns();

        // If patterns is null, continue to avoid an NPE
        // See Bugzilla 30624
        if (patterns == null) {
          continue;
        }

        for (int k = 0; k < patterns.length; k++) {
          if (uri.equals(patterns[k])) {
            found = true;
            if (collection[j].findMethod(method)) {
              if (results == null) {
                results = new ArrayList<SecurityConstraint>();
              }
              results.add(constraints[i]);
            }
          }
        }
      }
    }

    if (found) {
      return resultsToArray(results);
    }

    int longest = -1;

    for (i = 0; i < constraints.length; i++) {
      SecurityCollection[] collection = constraints[i].findCollections();

      // If collection is null, continue to avoid an NPE
      // See Bugzilla 30624
      if (collection == null) {
        continue;
      }

      if (log.isDebugEnabled()) {
        log.debug(
            "  Checking constraint '"
                + constraints[i]
                + "' against "
                + method
                + " "
                + uri
                + " --> "
                + constraints[i].included(uri, method));
      }

      for (int j = 0; j < collection.length; j++) {
        String[] patterns = collection[j].findPatterns();

        // If patterns is null, continue to avoid an NPE
        // See Bugzilla 30624
        if (patterns == null) {
          continue;
        }

        boolean matched = false;
        int length = -1;
        for (int k = 0; k < patterns.length; k++) {
          String pattern = patterns[k];
          if (pattern.startsWith("/") && pattern.endsWith("/*") && pattern.length() >= longest) {

            if (pattern.length() == 2) {
              matched = true;
              length = pattern.length();
            } else if (pattern.regionMatches(0, uri, 0, pattern.length() - 1)
                || (pattern.length() - 2 == uri.length()
                    && pattern.regionMatches(0, uri, 0, pattern.length() - 2))) {
              matched = true;
              length = pattern.length();
            }
          }
        }
        if (matched) {
          found = true;
          if (length > longest) {
            if (results != null) {
              results.clear();
            }
            longest = length;
          }
          if (collection[j].findMethod(method)) {
            if (results == null) {
              results = new ArrayList<SecurityConstraint>();
            }
            results.add(constraints[i]);
          }
        }
      }
    }

    if (found) {
      return resultsToArray(results);
    }

    for (i = 0; i < constraints.length; i++) {
      SecurityCollection[] collection = constraints[i].findCollections();

      // If collection is null, continue to avoid an NPE
      // See Bugzilla 30624
      if (collection == null) {
        continue;
      }

      if (log.isDebugEnabled()) {
        log.debug(
            "  Checking constraint '"
                + constraints[i]
                + "' against "
                + method
                + " "
                + uri
                + " --> "
                + constraints[i].included(uri, method));
      }

      boolean matched = false;
      int pos = -1;
      for (int j = 0; j < collection.length; j++) {
        String[] patterns = collection[j].findPatterns();

        // If patterns is null, continue to avoid an NPE
        // See Bugzilla 30624
        if (patterns == null) {
          continue;
        }

        for (int k = 0; k < patterns.length && !matched; k++) {
          String pattern = patterns[k];
          if (pattern.startsWith("*.")) {
            int slash = uri.lastIndexOf("/");
            int dot = uri.lastIndexOf(".");
            if (slash >= 0
                && dot > slash
                && dot != uri.length() - 1
                && uri.length() - dot == pattern.length() - 1) {
              if (pattern.regionMatches(1, uri, dot, uri.length() - dot)) {
                matched = true;
                pos = j;
              }
            }
          }
        }
      }
      if (matched) {
        found = true;
        if (collection[pos].findMethod(method)) {
          if (results == null) {
            results = new ArrayList<SecurityConstraint>();
          }
          results.add(constraints[i]);
        }
      }
    }

    if (found) {
      return resultsToArray(results);
    }

    for (i = 0; i < constraints.length; i++) {
      SecurityCollection[] collection = constraints[i].findCollections();

      // If collection is null, continue to avoid an NPE
      // See Bugzilla 30624
      if (collection == null) {
        continue;
      }

      if (log.isDebugEnabled()) {
        log.debug(
            "  Checking constraint '"
                + constraints[i]
                + "' against "
                + method
                + " "
                + uri
                + " --> "
                + constraints[i].included(uri, method));
      }

      for (int j = 0; j < collection.length; j++) {
        String[] patterns = collection[j].findPatterns();

        // If patterns is null, continue to avoid an NPE
        // See Bugzilla 30624
        if (patterns == null) {
          continue;
        }

        boolean matched = false;
        for (int k = 0; k < patterns.length && !matched; k++) {
          String pattern = patterns[k];
          if (pattern.equals("/")) {
            matched = true;
          }
        }
        if (matched) {
          if (results == null) {
            results = new ArrayList<SecurityConstraint>();
          }
          results.add(constraints[i]);
        }
      }
    }

    if (results == null) {
      // No applicable security constraint was found
      if (log.isDebugEnabled()) log.debug("  No applicable constraint located");
    }
    return resultsToArray(results);
  }