View Javadoc

1   package com.atlassian.asap.core.keys.privatekey;
2   
3   import com.atlassian.asap.core.keys.DataUriKeyReader;
4   import org.slf4j.Logger;
5   import org.slf4j.LoggerFactory;
6   
7   import java.net.URI;
8   import java.net.URISyntaxException;
9   import java.util.Optional;
10  
11  import static com.google.common.base.Preconditions.checkArgument;
12  
13  /**
14   * Reads private keys specified as data uri from system properties.
15   */
16  public final class SystemPropertyKeyProvider extends DataUriKeyProvider {
17      static final String URL_SCHEME = "sysprop";
18      private static final Logger logger = LoggerFactory.getLogger(SystemPropertyKeyProvider.class);
19  
20      private SystemPropertyKeyProvider(String propertyName, DataUriKeyReader keyReader) {
21          super(getDataUriFromSystemProperty(propertyName), keyReader);
22      }
23  
24      private static URI getDataUriFromSystemProperty(String propertyName) {
25          logger.debug("Reading private key from system property {}", propertyName);
26          String systemPropertyValue = Optional.ofNullable(System.getProperty(propertyName))
27                  .orElseThrow(() -> new IllegalArgumentException("Undefined system property: " + propertyName));
28          try {
29              return new URI(systemPropertyValue);
30          } catch (URISyntaxException e) {
31              throw new IllegalArgumentException("Value of system property " + propertyName +
32                      " cannot be parsed as a URI");
33          }
34      }
35  
36      /**
37       * Instantiates the class by parsing a URL with the following syntax:
38       * <code>sysprop:///[BASE_SYSTEM_PROPERTY_NAME]</code>.
39       *
40       * @param uri       URI with the syntax described above
41       * @param keyReader reader of PEM documents
42       * @return a new instance of the class
43       */
44      public static SystemPropertyKeyProvider fromUri(URI uri, DataUriKeyReader keyReader) {
45          checkArgument(uri.isAbsolute(), "URL must be absolute"); // implies that scheme != null
46          checkArgument(URL_SCHEME.equals(uri.getScheme()), "URL must have " + URL_SCHEME + " scheme");
47          checkArgument(uri.getPath() != null && uri.getPath().startsWith("/"), "URL must have a path component");
48          checkArgument(uri.getQuery() == null, "URL must not have a query component");
49          checkArgument(uri.getAuthority() == null, "URL must not have an authority component");
50  
51          String basePropertyName = uri.getPath().substring(1); // remove the trailing slash
52          return new SystemPropertyKeyProvider(basePropertyName, keyReader);
53      }
54  }