1   package com.atlassian.security.auth.trustedapps;
2   
3   import com.atlassian.ip.Subnet;
4   
5   import java.util.Set;
6   
7   /**
8    * IPMatcher implementation that delegates to Atlassian IP.
9    * <p>
10   * Supports matching against IPv4 and IPv6 addresses, and subnets in both
11   * wildcard (IPv4 only) and CIDR notation. Examples of valid patterns:
12   * <pre>
13   * 192.168.1.1
14   * 192.168.1.0/24
15   * 192.168.1.*
16   * 0:0:0:1::1
17   * 0:0:0:1::/64
18   * </pre>
19   *
20   * @since 2.5
21   */
22  public class AtlassianIPMatcher implements IPMatcher
23  {
24      private final com.atlassian.ip.IPMatcher ipMatcher;
25  
26      /**
27       * Main ctor.
28       *
29       * @param patterns the Set<String> of allowed pattern Strings
30       * @throws com.atlassian.security.auth.trustedapps.IPAddressFormatException if the pattern does not represent a valid IP address
31       */
32      public AtlassianIPMatcher(final Set<String> patterns) throws IPAddressFormatException
33      {
34          if (!patterns.isEmpty()) {
35              final com.atlassian.ip.IPMatcher.Builder builder = com.atlassian.ip.IPMatcher.builder();
36              for (final String patternStr : patterns)
37              {
38                  builder.addPattern(patternStr);
39              }
40              ipMatcher = builder.build();
41          }
42          else
43          {
44              ipMatcher = null;
45          }
46      }
47  
48      public boolean match(final String ipAddress)
49      {
50          // Allow all if there were no patterns
51          return ipMatcher == null || ipMatcher.matches(ipAddress);
52      }
53  
54      public static void parsePatternString(String pattern) throws IPAddressFormatException
55      {
56          if (!Subnet.isValidPattern(pattern))
57          {
58              throw new IPAddressFormatException(pattern);
59          }
60      }
61  }