1   package com.atlassian.security.auth.trustedapps;
2   
3   import java.util.StringTokenizer;
4   
5   import javax.servlet.http.HttpServletRequest;
6   
7   /**
8    * DefaultRequestValidor aggregates IP and URL matchers and throws an exception if they do not match.
9    */
10  public class DefaultRequestValidator implements RequestValidator
11  {
12      private final IPMatcher ipMatcher;
13      private final URLMatcher urlMatcher;
14  
15      public DefaultRequestValidator(IPMatcher ipMatcher, URLMatcher urlMatcher)
16      {
17          Null.not("ipMatcher", ipMatcher);
18          Null.not("urlMatcher", urlMatcher);
19  
20          this.ipMatcher = ipMatcher;
21          this.urlMatcher = urlMatcher;
22      }
23  
24      public void validate(HttpServletRequest request) throws InvalidRequestException
25      {
26          validateRemoteRequestIP(request);
27          validateXForwardedFor(request);
28          validateRequestURL(request);
29      }
30  
31      private void validateRemoteRequestIP(HttpServletRequest request) throws InvalidIPAddressException
32      {
33          final String remoteAddr = request.getRemoteAddr();
34          if (!ipMatcher.match(remoteAddr))
35          {
36              throw new InvalidRemoteAddressException(remoteAddr);
37          }
38      }
39  
40      private void validateXForwardedFor(HttpServletRequest request) throws InvalidXForwardedForAddressException
41      {
42          String forwardedFor = request.getHeader("X-Forwarded-For");
43          if (forwardedFor != null)
44          {
45              StringTokenizer tokenizer = new StringTokenizer(forwardedFor, ",");
46              while (tokenizer.hasMoreTokens())
47              {
48                  String token = tokenizer.nextToken();
49                  if (token.trim().length() > 0)
50                  {
51                      if (!ipMatcher.match(token.trim()))
52                      {
53                          throw new InvalidXForwardedForAddressException(token);
54                      }
55                  }
56              }
57          }
58      }
59  
60      private void validateRequestURL(HttpServletRequest request) throws InvalidRequestUrlException
61      {
62          final String pathInfo = getPathInfo(request);
63          if (!urlMatcher.match(pathInfo))
64          {
65              throw new InvalidRequestUrlException(pathInfo);
66          }
67      }
68  
69      private String getPathInfo(HttpServletRequest request)
70      {
71          String context = request.getContextPath();
72          String uri = request.getRequestURI();
73          if (context != null && context.length() > 0) return uri.substring(context.length());
74          else return uri;
75      }
76  }