001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.crypto.key.kms;
019
020import org.apache.commons.codec.binary.Base64;
021import org.apache.hadoop.classification.InterfaceAudience;
022import org.apache.hadoop.conf.Configuration;
023import org.apache.hadoop.crypto.key.KeyProvider;
024import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension.EncryptedKeyVersion;
025import org.apache.hadoop.crypto.key.KeyProviderDelegationTokenExtension;
026import org.apache.hadoop.crypto.key.KeyProviderFactory;
027import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
028import org.apache.hadoop.fs.Path;
029import org.apache.hadoop.io.Text;
030import org.apache.hadoop.security.Credentials;
031import org.apache.hadoop.security.ProviderUtils;
032import org.apache.hadoop.security.SecurityUtil;
033import org.apache.hadoop.security.UserGroupInformation;
034import org.apache.hadoop.security.authentication.client.AuthenticatedURL;
035import org.apache.hadoop.security.authentication.client.AuthenticationException;
036import org.apache.hadoop.security.authentication.client.ConnectionConfigurator;
037import org.apache.hadoop.security.ssl.SSLFactory;
038import org.apache.hadoop.security.token.Token;
039import org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticatedURL;
040import org.apache.hadoop.util.HttpExceptionUtils;
041import org.apache.http.client.utils.URIBuilder;
042import org.codehaus.jackson.map.ObjectMapper;
043
044import javax.net.ssl.HttpsURLConnection;
045
046import java.io.IOException;
047import java.io.InputStream;
048import java.io.OutputStream;
049import java.io.OutputStreamWriter;
050import java.io.Writer;
051import java.lang.reflect.UndeclaredThrowableException;
052import java.net.HttpURLConnection;
053import java.net.InetSocketAddress;
054import java.net.MalformedURLException;
055import java.net.SocketTimeoutException;
056import java.net.URI;
057import java.net.URISyntaxException;
058import java.net.URL;
059import java.net.URLEncoder;
060import java.security.GeneralSecurityException;
061import java.security.NoSuchAlgorithmException;
062import java.security.PrivilegedExceptionAction;
063import java.util.ArrayList;
064import java.util.Date;
065import java.util.HashMap;
066import java.util.LinkedList;
067import java.util.List;
068import java.util.Map;
069import java.util.Queue;
070import java.util.concurrent.ExecutionException;
071
072import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension;
073import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension.CryptoExtension;
074
075import com.google.common.annotations.VisibleForTesting;
076import com.google.common.base.Preconditions;
077import com.google.common.base.Strings;
078
079/**
080 * KMS client <code>KeyProvider</code> implementation.
081 */
082@InterfaceAudience.Private
083public class KMSClientProvider extends KeyProvider implements CryptoExtension,
084    KeyProviderDelegationTokenExtension.DelegationTokenExtension {
085
086  private static final String INVALID_SIGNATURE = "Invalid signature";
087
088  private static final String ANONYMOUS_REQUESTS_DISALLOWED = "Anonymous requests are disallowed";
089
090  public static final String TOKEN_KIND = "kms-dt";
091
092  public static final String SCHEME_NAME = "kms";
093
094  private static final String UTF8 = "UTF-8";
095
096  private static final String CONTENT_TYPE = "Content-Type";
097  private static final String APPLICATION_JSON_MIME = "application/json";
098
099  private static final String HTTP_GET = "GET";
100  private static final String HTTP_POST = "POST";
101  private static final String HTTP_PUT = "PUT";
102  private static final String HTTP_DELETE = "DELETE";
103
104
105  private static final String CONFIG_PREFIX = "hadoop.security.kms.client.";
106
107  /* It's possible to specify a timeout, in seconds, in the config file */
108  public static final String TIMEOUT_ATTR = CONFIG_PREFIX + "timeout";
109  public static final int DEFAULT_TIMEOUT = 60;
110
111  /* Number of times to retry authentication in the event of auth failure
112   * (normally happens due to stale authToken) 
113   */
114  public static final String AUTH_RETRY = CONFIG_PREFIX
115      + "authentication.retry-count";
116  public static final int DEFAULT_AUTH_RETRY = 1;
117
118  private final ValueQueue<EncryptedKeyVersion> encKeyVersionQueue;
119
120  private class EncryptedQueueRefiller implements
121    ValueQueue.QueueRefiller<EncryptedKeyVersion> {
122
123    @Override
124    public void fillQueueForKey(String keyName,
125        Queue<EncryptedKeyVersion> keyQueue, int numEKVs) throws IOException {
126      checkNotNull(keyName, "keyName");
127      Map<String, String> params = new HashMap<String, String>();
128      params.put(KMSRESTConstants.EEK_OP, KMSRESTConstants.EEK_GENERATE);
129      params.put(KMSRESTConstants.EEK_NUM_KEYS, "" + numEKVs);
130      URL url = createURL(KMSRESTConstants.KEY_RESOURCE, keyName,
131          KMSRESTConstants.EEK_SUB_RESOURCE, params);
132      HttpURLConnection conn = createConnection(url, HTTP_GET);
133      conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON_MIME);
134      List response = call(conn, null,
135          HttpURLConnection.HTTP_OK, List.class);
136      List<EncryptedKeyVersion> ekvs =
137          parseJSONEncKeyVersion(keyName, response);
138      keyQueue.addAll(ekvs);
139    }
140  }
141
142  public static class KMSEncryptedKeyVersion extends EncryptedKeyVersion {
143    public KMSEncryptedKeyVersion(String keyName, String keyVersionName,
144        byte[] iv, String encryptedVersionName, byte[] keyMaterial) {
145      super(keyName, keyVersionName, iv, new KMSKeyVersion(null,
146          encryptedVersionName, keyMaterial));
147    }
148  }
149
150  @SuppressWarnings("rawtypes")
151  private static List<EncryptedKeyVersion>
152      parseJSONEncKeyVersion(String keyName, List valueList) {
153    List<EncryptedKeyVersion> ekvs = new LinkedList<EncryptedKeyVersion>();
154    if (!valueList.isEmpty()) {
155      for (Object values : valueList) {
156        Map valueMap = (Map) values;
157
158        String versionName = checkNotNull(
159                (String) valueMap.get(KMSRESTConstants.VERSION_NAME_FIELD),
160                KMSRESTConstants.VERSION_NAME_FIELD);
161
162        byte[] iv = Base64.decodeBase64(checkNotNull(
163                (String) valueMap.get(KMSRESTConstants.IV_FIELD),
164                KMSRESTConstants.IV_FIELD));
165
166        Map encValueMap = checkNotNull((Map)
167                valueMap.get(KMSRESTConstants.ENCRYPTED_KEY_VERSION_FIELD),
168                KMSRESTConstants.ENCRYPTED_KEY_VERSION_FIELD);
169
170        String encVersionName = checkNotNull((String)
171                encValueMap.get(KMSRESTConstants.VERSION_NAME_FIELD),
172                KMSRESTConstants.VERSION_NAME_FIELD);
173
174        byte[] encKeyMaterial = Base64.decodeBase64(checkNotNull((String)
175                encValueMap.get(KMSRESTConstants.MATERIAL_FIELD),
176                KMSRESTConstants.MATERIAL_FIELD));
177
178        ekvs.add(new KMSEncryptedKeyVersion(keyName, versionName, iv,
179            encVersionName, encKeyMaterial));
180      }
181    }
182    return ekvs;
183  }
184
185  private static KeyVersion parseJSONKeyVersion(Map valueMap) {
186    KeyVersion keyVersion = null;
187    if (!valueMap.isEmpty()) {
188      byte[] material = (valueMap.containsKey(KMSRESTConstants.MATERIAL_FIELD))
189          ? Base64.decodeBase64((String) valueMap.get(KMSRESTConstants.MATERIAL_FIELD))
190          : null;
191      String versionName = (String)valueMap.get(KMSRESTConstants.VERSION_NAME_FIELD);
192      String keyName = (String)valueMap.get(KMSRESTConstants.NAME_FIELD);
193      keyVersion = new KMSKeyVersion(keyName, versionName, material);
194    }
195    return keyVersion;
196  }
197
198  @SuppressWarnings("unchecked")
199  private static Metadata parseJSONMetadata(Map valueMap) {
200    Metadata metadata = null;
201    if (!valueMap.isEmpty()) {
202      metadata = new KMSMetadata(
203          (String) valueMap.get(KMSRESTConstants.CIPHER_FIELD),
204          (Integer) valueMap.get(KMSRESTConstants.LENGTH_FIELD),
205          (String) valueMap.get(KMSRESTConstants.DESCRIPTION_FIELD),
206          (Map<String, String>) valueMap.get(KMSRESTConstants.ATTRIBUTES_FIELD),
207          new Date((Long) valueMap.get(KMSRESTConstants.CREATED_FIELD)),
208          (Integer) valueMap.get(KMSRESTConstants.VERSIONS_FIELD));
209    }
210    return metadata;
211  }
212
213  private static void writeJson(Map map, OutputStream os) throws IOException {
214    Writer writer = new OutputStreamWriter(os);
215    ObjectMapper jsonMapper = new ObjectMapper();
216    jsonMapper.defaultPrettyPrintingWriter().writeValue(writer, map);
217  }
218
219  /**
220   * The factory to create KMSClientProvider, which is used by the
221   * ServiceLoader.
222   */
223  public static class Factory extends KeyProviderFactory {
224
225    /**
226     * This provider expects URIs in the following form :
227     * kms://<PROTO>@<AUTHORITY>/<PATH>
228     *
229     * where :
230     * - PROTO = http or https
231     * - AUTHORITY = <HOSTS>[:<PORT>]
232     * - HOSTS = <HOSTNAME>[;<HOSTS>]
233     * - HOSTNAME = string
234     * - PORT = integer
235     *
236     * If multiple hosts are provider, the Factory will create a
237     * {@link LoadBalancingKMSClientProvider} that round-robins requests
238     * across the provided list of hosts.
239     */
240    @Override
241    public KeyProvider createProvider(URI providerUri, Configuration conf)
242        throws IOException {
243      if (SCHEME_NAME.equals(providerUri.getScheme())) {
244        URL origUrl = new URL(extractKMSPath(providerUri).toString());
245        String authority = origUrl.getAuthority();
246        // check for ';' which delimits the backup hosts
247        if (Strings.isNullOrEmpty(authority)) {
248          throw new IOException(
249              "No valid authority in kms uri [" + origUrl + "]");
250        }
251        // Check if port is present in authority
252        // In the current scheme, all hosts have to run on the same port
253        int port = -1;
254        String hostsPart = authority;
255        if (authority.contains(":")) {
256          String[] t = authority.split(":");
257          try {
258            port = Integer.parseInt(t[1]);
259          } catch (Exception e) {
260            throw new IOException(
261                "Could not parse port in kms uri [" + origUrl + "]");
262          }
263          hostsPart = t[0];
264        }
265        return createProvider(providerUri, conf, origUrl, port, hostsPart);
266      }
267      return null;
268    }
269
270    private KeyProvider createProvider(URI providerUri, Configuration conf,
271        URL origUrl, int port, String hostsPart) throws IOException {
272      String[] hosts = hostsPart.split(";");
273      if (hosts.length == 1) {
274        return new KMSClientProvider(providerUri, conf);
275      } else {
276        KMSClientProvider[] providers = new KMSClientProvider[hosts.length];
277        for (int i = 0; i < hosts.length; i++) {
278          try {
279            providers[i] =
280                new KMSClientProvider(
281                    new URI("kms", origUrl.getProtocol(), hosts[i], port,
282                        origUrl.getPath(), null, null), conf);
283          } catch (URISyntaxException e) {
284            throw new IOException("Could not instantiate KMSProvider..", e);
285          }
286        }
287        return new LoadBalancingKMSClientProvider(providers, conf);
288      }
289    }
290  }
291
292  public static <T> T checkNotNull(T o, String name)
293      throws IllegalArgumentException {
294    if (o == null) {
295      throw new IllegalArgumentException("Parameter '" + name +
296          "' cannot be null");
297    }
298    return o;
299  }
300
301  public static String checkNotEmpty(String s, String name)
302      throws IllegalArgumentException {
303    checkNotNull(s, name);
304    if (s.isEmpty()) {
305      throw new IllegalArgumentException("Parameter '" + name +
306          "' cannot be empty");
307    }
308    return s;
309  }
310
311  private String kmsUrl;
312  private SSLFactory sslFactory;
313  private ConnectionConfigurator configurator;
314  private DelegationTokenAuthenticatedURL.Token authToken;
315  private final int authRetry;
316  private final UserGroupInformation actualUgi;
317
318  @Override
319  public String toString() {
320    final StringBuilder sb = new StringBuilder("KMSClientProvider[");
321    sb.append(kmsUrl).append("]");
322    return sb.toString();
323  }
324
325  /**
326   * This small class exists to set the timeout values for a connection
327   */
328  private static class TimeoutConnConfigurator
329          implements ConnectionConfigurator {
330    private ConnectionConfigurator cc;
331    private int timeout;
332
333    /**
334     * Sets the timeout and wraps another connection configurator
335     * @param timeout - will set both connect and read timeouts - in seconds
336     * @param cc - another configurator to wrap - may be null
337     */
338    public TimeoutConnConfigurator(int timeout, ConnectionConfigurator cc) {
339      this.timeout = timeout;
340      this.cc = cc;
341    }
342
343    /**
344     * Calls the wrapped configure() method, then sets timeouts
345     * @param conn the {@link HttpURLConnection} instance to configure.
346     * @return the connection
347     * @throws IOException
348     */
349    @Override
350    public HttpURLConnection configure(HttpURLConnection conn)
351            throws IOException {
352      if (cc != null) {
353        conn = cc.configure(conn);
354      }
355      conn.setConnectTimeout(timeout * 1000);  // conversion to milliseconds
356      conn.setReadTimeout(timeout * 1000);
357      return conn;
358    }
359  }
360
361  public KMSClientProvider(URI uri, Configuration conf) throws IOException {
362    super(conf);
363    kmsUrl = createServiceURL(extractKMSPath(uri));
364    if ("https".equalsIgnoreCase(new URL(kmsUrl).getProtocol())) {
365      sslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
366      try {
367        sslFactory.init();
368      } catch (GeneralSecurityException ex) {
369        throw new IOException(ex);
370      }
371    }
372    int timeout = conf.getInt(TIMEOUT_ATTR, DEFAULT_TIMEOUT);
373    authRetry = conf.getInt(AUTH_RETRY, DEFAULT_AUTH_RETRY);
374    configurator = new TimeoutConnConfigurator(timeout, sslFactory);
375    encKeyVersionQueue =
376        new ValueQueue<KeyProviderCryptoExtension.EncryptedKeyVersion>(
377            conf.getInt(
378                CommonConfigurationKeysPublic.KMS_CLIENT_ENC_KEY_CACHE_SIZE,
379                CommonConfigurationKeysPublic.
380                    KMS_CLIENT_ENC_KEY_CACHE_SIZE_DEFAULT),
381            conf.getFloat(
382                CommonConfigurationKeysPublic.
383                    KMS_CLIENT_ENC_KEY_CACHE_LOW_WATERMARK,
384                CommonConfigurationKeysPublic.
385                    KMS_CLIENT_ENC_KEY_CACHE_LOW_WATERMARK_DEFAULT),
386            conf.getInt(
387                CommonConfigurationKeysPublic.
388                    KMS_CLIENT_ENC_KEY_CACHE_EXPIRY_MS,
389                CommonConfigurationKeysPublic.
390                    KMS_CLIENT_ENC_KEY_CACHE_EXPIRY_DEFAULT),
391            conf.getInt(
392                CommonConfigurationKeysPublic.
393                    KMS_CLIENT_ENC_KEY_CACHE_NUM_REFILL_THREADS,
394                CommonConfigurationKeysPublic.
395                    KMS_CLIENT_ENC_KEY_CACHE_NUM_REFILL_THREADS_DEFAULT),
396            new EncryptedQueueRefiller());
397    authToken = new DelegationTokenAuthenticatedURL.Token();
398    actualUgi =
399        (UserGroupInformation.getCurrentUser().getAuthenticationMethod() ==
400        UserGroupInformation.AuthenticationMethod.PROXY) ? UserGroupInformation
401            .getCurrentUser().getRealUser() : UserGroupInformation
402            .getCurrentUser();
403  }
404
405  private static Path extractKMSPath(URI uri) throws MalformedURLException, IOException {
406    return ProviderUtils.unnestUri(uri);
407  }
408
409  private static String createServiceURL(Path path) throws IOException {
410    String str = new URL(path.toString()).toExternalForm();
411    if (str.endsWith("/")) {
412      str = str.substring(0, str.length() - 1);
413    }
414    return new URL(str + KMSRESTConstants.SERVICE_VERSION + "/").
415        toExternalForm();
416  }
417
418  private URL createURL(String collection, String resource, String subResource,
419      Map<String, ?> parameters) throws IOException {
420    try {
421      StringBuilder sb = new StringBuilder();
422      sb.append(kmsUrl);
423      if (collection != null) {
424        sb.append(collection);
425        if (resource != null) {
426          sb.append("/").append(URLEncoder.encode(resource, UTF8));
427          if (subResource != null) {
428            sb.append("/").append(subResource);
429          }
430        }
431      }
432      URIBuilder uriBuilder = new URIBuilder(sb.toString());
433      if (parameters != null) {
434        for (Map.Entry<String, ?> param : parameters.entrySet()) {
435          Object value = param.getValue();
436          if (value instanceof String) {
437            uriBuilder.addParameter(param.getKey(), (String) value);
438          } else {
439            for (String s : (String[]) value) {
440              uriBuilder.addParameter(param.getKey(), s);
441            }
442          }
443        }
444      }
445      return uriBuilder.build().toURL();
446    } catch (URISyntaxException ex) {
447      throw new IOException(ex);
448    }
449  }
450
451  private HttpURLConnection configureConnection(HttpURLConnection conn)
452      throws IOException {
453    if (sslFactory != null) {
454      HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
455      try {
456        httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
457      } catch (GeneralSecurityException ex) {
458        throw new IOException(ex);
459      }
460      httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
461    }
462    return conn;
463  }
464
465  private HttpURLConnection createConnection(final URL url, String method)
466      throws IOException {
467    HttpURLConnection conn;
468    try {
469      // if current UGI is different from UGI at constructor time, behave as
470      // proxyuser
471      UserGroupInformation currentUgi = UserGroupInformation.getCurrentUser();
472      final String doAsUser = (currentUgi.getAuthenticationMethod() ==
473          UserGroupInformation.AuthenticationMethod.PROXY)
474                              ? currentUgi.getShortUserName() : null;
475
476      // creating the HTTP connection using the current UGI at constructor time
477      conn = actualUgi.doAs(new PrivilegedExceptionAction<HttpURLConnection>() {
478        @Override
479        public HttpURLConnection run() throws Exception {
480          DelegationTokenAuthenticatedURL authUrl =
481              new DelegationTokenAuthenticatedURL(configurator);
482          return authUrl.openConnection(url, authToken, doAsUser);
483        }
484      });
485    } catch (IOException ex) {
486      throw ex;
487    } catch (UndeclaredThrowableException ex) {
488      throw new IOException(ex.getUndeclaredThrowable());
489    } catch (Exception ex) {
490      throw new IOException(ex);
491    }
492    conn.setUseCaches(false);
493    conn.setRequestMethod(method);
494    if (method.equals(HTTP_POST) || method.equals(HTTP_PUT)) {
495      conn.setDoOutput(true);
496    }
497    conn = configureConnection(conn);
498    return conn;
499  }
500
501  private <T> T call(HttpURLConnection conn, Map jsonOutput,
502      int expectedResponse, Class<T> klass) throws IOException {
503    return call(conn, jsonOutput, expectedResponse, klass, authRetry);
504  }
505
506  private <T> T call(HttpURLConnection conn, Map jsonOutput,
507      int expectedResponse, Class<T> klass, int authRetryCount)
508      throws IOException {
509    T ret = null;
510    try {
511      if (jsonOutput != null) {
512        writeJson(jsonOutput, conn.getOutputStream());
513      }
514    } catch (IOException ex) {
515      conn.getInputStream().close();
516      throw ex;
517    }
518    if ((conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN
519        && (conn.getResponseMessage().equals(ANONYMOUS_REQUESTS_DISALLOWED) ||
520            conn.getResponseMessage().contains(INVALID_SIGNATURE)))
521        || conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
522      // Ideally, this should happen only when there is an Authentication
523      // failure. Unfortunately, the AuthenticationFilter returns 403 when it
524      // cannot authenticate (Since a 401 requires Server to send
525      // WWW-Authenticate header as well)..
526      KMSClientProvider.this.authToken =
527          new DelegationTokenAuthenticatedURL.Token();
528      if (authRetryCount > 0) {
529        String contentType = conn.getRequestProperty(CONTENT_TYPE);
530        String requestMethod = conn.getRequestMethod();
531        URL url = conn.getURL();
532        conn = createConnection(url, requestMethod);
533        conn.setRequestProperty(CONTENT_TYPE, contentType);
534        return call(conn, jsonOutput, expectedResponse, klass,
535            authRetryCount - 1);
536      }
537    }
538    try {
539      AuthenticatedURL.extractToken(conn, authToken);
540    } catch (AuthenticationException e) {
541      // Ignore the AuthExceptions.. since we are just using the method to
542      // extract and set the authToken.. (Workaround till we actually fix
543      // AuthenticatedURL properly to set authToken post initialization)
544    }
545    HttpExceptionUtils.validateResponse(conn, expectedResponse);
546    if (APPLICATION_JSON_MIME.equalsIgnoreCase(conn.getContentType())
547        && klass != null) {
548      ObjectMapper mapper = new ObjectMapper();
549      InputStream is = null;
550      try {
551        is = conn.getInputStream();
552        ret = mapper.readValue(is, klass);
553      } catch (IOException ex) {
554        if (is != null) {
555          is.close();
556        }
557        throw ex;
558      } finally {
559        if (is != null) {
560          is.close();
561        }
562      }
563    }
564    return ret;
565  }
566
567  public static class KMSKeyVersion extends KeyVersion {
568    public KMSKeyVersion(String keyName, String versionName, byte[] material) {
569      super(keyName, versionName, material);
570    }
571  }
572
573  @Override
574  public KeyVersion getKeyVersion(String versionName) throws IOException {
575    checkNotEmpty(versionName, "versionName");
576    URL url = createURL(KMSRESTConstants.KEY_VERSION_RESOURCE,
577        versionName, null, null);
578    HttpURLConnection conn = createConnection(url, HTTP_GET);
579    Map response = call(conn, null, HttpURLConnection.HTTP_OK, Map.class);
580    return parseJSONKeyVersion(response);
581  }
582
583  @Override
584  public KeyVersion getCurrentKey(String name) throws IOException {
585    checkNotEmpty(name, "name");
586    URL url = createURL(KMSRESTConstants.KEY_RESOURCE, name,
587        KMSRESTConstants.CURRENT_VERSION_SUB_RESOURCE, null);
588    HttpURLConnection conn = createConnection(url, HTTP_GET);
589    Map response = call(conn, null, HttpURLConnection.HTTP_OK, Map.class);
590    return parseJSONKeyVersion(response);
591  }
592
593  @Override
594  @SuppressWarnings("unchecked")
595  public List<String> getKeys() throws IOException {
596    URL url = createURL(KMSRESTConstants.KEYS_NAMES_RESOURCE, null, null,
597        null);
598    HttpURLConnection conn = createConnection(url, HTTP_GET);
599    List response = call(conn, null, HttpURLConnection.HTTP_OK, List.class);
600    return (List<String>) response;
601  }
602
603  public static class KMSMetadata extends Metadata {
604    public KMSMetadata(String cipher, int bitLength, String description,
605        Map<String, String> attributes, Date created, int versions) {
606      super(cipher, bitLength, description, attributes, created, versions);
607    }
608  }
609
610  // breaking keyNames into sets to keep resulting URL undler 2000 chars
611  private List<String[]> createKeySets(String[] keyNames) {
612    List<String[]> list = new ArrayList<String[]>();
613    List<String> batch = new ArrayList<String>();
614    int batchLen = 0;
615    for (String name : keyNames) {
616      int additionalLen = KMSRESTConstants.KEY.length() + 1 + name.length();
617      batchLen += additionalLen;
618      // topping at 1500 to account for initial URL and encoded names
619      if (batchLen > 1500) {
620        list.add(batch.toArray(new String[batch.size()]));
621        batch = new ArrayList<String>();
622        batchLen = additionalLen;
623      }
624      batch.add(name);
625    }
626    if (!batch.isEmpty()) {
627      list.add(batch.toArray(new String[batch.size()]));
628    }
629    return list;
630  }
631
632  @Override
633  @SuppressWarnings("unchecked")
634  public Metadata[] getKeysMetadata(String ... keyNames) throws IOException {
635    List<Metadata> keysMetadata = new ArrayList<Metadata>();
636    List<String[]> keySets = createKeySets(keyNames);
637    for (String[] keySet : keySets) {
638      if (keyNames.length > 0) {
639        Map<String, Object> queryStr = new HashMap<String, Object>();
640        queryStr.put(KMSRESTConstants.KEY, keySet);
641        URL url = createURL(KMSRESTConstants.KEYS_METADATA_RESOURCE, null,
642            null, queryStr);
643        HttpURLConnection conn = createConnection(url, HTTP_GET);
644        List<Map> list = call(conn, null, HttpURLConnection.HTTP_OK, List.class);
645        for (Map map : list) {
646          keysMetadata.add(parseJSONMetadata(map));
647        }
648      }
649    }
650    return keysMetadata.toArray(new Metadata[keysMetadata.size()]);
651  }
652
653  private KeyVersion createKeyInternal(String name, byte[] material,
654      Options options)
655      throws NoSuchAlgorithmException, IOException {
656    checkNotEmpty(name, "name");
657    checkNotNull(options, "options");
658    Map<String, Object> jsonKey = new HashMap<String, Object>();
659    jsonKey.put(KMSRESTConstants.NAME_FIELD, name);
660    jsonKey.put(KMSRESTConstants.CIPHER_FIELD, options.getCipher());
661    jsonKey.put(KMSRESTConstants.LENGTH_FIELD, options.getBitLength());
662    if (material != null) {
663      jsonKey.put(KMSRESTConstants.MATERIAL_FIELD,
664          Base64.encodeBase64String(material));
665    }
666    if (options.getDescription() != null) {
667      jsonKey.put(KMSRESTConstants.DESCRIPTION_FIELD,
668          options.getDescription());
669    }
670    if (options.getAttributes() != null && !options.getAttributes().isEmpty()) {
671      jsonKey.put(KMSRESTConstants.ATTRIBUTES_FIELD, options.getAttributes());
672    }
673    URL url = createURL(KMSRESTConstants.KEYS_RESOURCE, null, null, null);
674    HttpURLConnection conn = createConnection(url, HTTP_POST);
675    conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON_MIME);
676    Map response = call(conn, jsonKey, HttpURLConnection.HTTP_CREATED,
677        Map.class);
678    return parseJSONKeyVersion(response);
679  }
680
681  @Override
682  public KeyVersion createKey(String name, Options options)
683      throws NoSuchAlgorithmException, IOException {
684    return createKeyInternal(name, null, options);
685  }
686
687  @Override
688  public KeyVersion createKey(String name, byte[] material, Options options)
689      throws IOException {
690    checkNotNull(material, "material");
691    try {
692      return createKeyInternal(name, material, options);
693    } catch (NoSuchAlgorithmException ex) {
694      throw new RuntimeException("It should not happen", ex);
695    }
696  }
697
698  private KeyVersion rollNewVersionInternal(String name, byte[] material)
699      throws NoSuchAlgorithmException, IOException {
700    checkNotEmpty(name, "name");
701    Map<String, String> jsonMaterial = new HashMap<String, String>();
702    if (material != null) {
703      jsonMaterial.put(KMSRESTConstants.MATERIAL_FIELD,
704          Base64.encodeBase64String(material));
705    }
706    URL url = createURL(KMSRESTConstants.KEY_RESOURCE, name, null, null);
707    HttpURLConnection conn = createConnection(url, HTTP_POST);
708    conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON_MIME);
709    Map response = call(conn, jsonMaterial,
710        HttpURLConnection.HTTP_OK, Map.class);
711    KeyVersion keyVersion = parseJSONKeyVersion(response);
712    encKeyVersionQueue.drain(name);
713    return keyVersion;
714  }
715
716
717  @Override
718  public KeyVersion rollNewVersion(String name)
719      throws NoSuchAlgorithmException, IOException {
720    return rollNewVersionInternal(name, null);
721  }
722
723  @Override
724  public KeyVersion rollNewVersion(String name, byte[] material)
725      throws IOException {
726    checkNotNull(material, "material");
727    try {
728      return rollNewVersionInternal(name, material);
729    } catch (NoSuchAlgorithmException ex) {
730      throw new RuntimeException("It should not happen", ex);
731    }
732  }
733
734  @Override
735  public EncryptedKeyVersion generateEncryptedKey(
736      String encryptionKeyName) throws IOException, GeneralSecurityException {
737    try {
738      return encKeyVersionQueue.getNext(encryptionKeyName);
739    } catch (ExecutionException e) {
740      if (e.getCause() instanceof SocketTimeoutException) {
741        throw (SocketTimeoutException)e.getCause();
742      }
743      throw new IOException(e);
744    }
745  }
746
747  @SuppressWarnings("rawtypes")
748  @Override
749  public KeyVersion decryptEncryptedKey(
750      EncryptedKeyVersion encryptedKeyVersion) throws IOException,
751                                                      GeneralSecurityException {
752    checkNotNull(encryptedKeyVersion.getEncryptionKeyVersionName(),
753        "versionName");
754    checkNotNull(encryptedKeyVersion.getEncryptedKeyIv(), "iv");
755    Preconditions.checkArgument(
756        encryptedKeyVersion.getEncryptedKeyVersion().getVersionName()
757            .equals(KeyProviderCryptoExtension.EEK),
758        "encryptedKey version name must be '%s', is '%s'",
759        KeyProviderCryptoExtension.EEK,
760        encryptedKeyVersion.getEncryptedKeyVersion().getVersionName()
761    );
762    checkNotNull(encryptedKeyVersion.getEncryptedKeyVersion(), "encryptedKey");
763    Map<String, String> params = new HashMap<String, String>();
764    params.put(KMSRESTConstants.EEK_OP, KMSRESTConstants.EEK_DECRYPT);
765    Map<String, Object> jsonPayload = new HashMap<String, Object>();
766    jsonPayload.put(KMSRESTConstants.NAME_FIELD,
767        encryptedKeyVersion.getEncryptionKeyName());
768    jsonPayload.put(KMSRESTConstants.IV_FIELD, Base64.encodeBase64String(
769        encryptedKeyVersion.getEncryptedKeyIv()));
770    jsonPayload.put(KMSRESTConstants.MATERIAL_FIELD, Base64.encodeBase64String(
771            encryptedKeyVersion.getEncryptedKeyVersion().getMaterial()));
772    URL url = createURL(KMSRESTConstants.KEY_VERSION_RESOURCE,
773        encryptedKeyVersion.getEncryptionKeyVersionName(),
774        KMSRESTConstants.EEK_SUB_RESOURCE, params);
775    HttpURLConnection conn = createConnection(url, HTTP_POST);
776    conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON_MIME);
777    Map response =
778        call(conn, jsonPayload, HttpURLConnection.HTTP_OK, Map.class);
779    return parseJSONKeyVersion(response);
780  }
781
782  @Override
783  public List<KeyVersion> getKeyVersions(String name) throws IOException {
784    checkNotEmpty(name, "name");
785    URL url = createURL(KMSRESTConstants.KEY_RESOURCE, name,
786        KMSRESTConstants.VERSIONS_SUB_RESOURCE, null);
787    HttpURLConnection conn = createConnection(url, HTTP_GET);
788    List response = call(conn, null, HttpURLConnection.HTTP_OK, List.class);
789    List<KeyVersion> versions = null;
790    if (!response.isEmpty()) {
791      versions = new ArrayList<KeyVersion>();
792      for (Object obj : response) {
793        versions.add(parseJSONKeyVersion((Map) obj));
794      }
795    }
796    return versions;
797  }
798
799  @Override
800  public Metadata getMetadata(String name) throws IOException {
801    checkNotEmpty(name, "name");
802    URL url = createURL(KMSRESTConstants.KEY_RESOURCE, name,
803        KMSRESTConstants.METADATA_SUB_RESOURCE, null);
804    HttpURLConnection conn = createConnection(url, HTTP_GET);
805    Map response = call(conn, null, HttpURLConnection.HTTP_OK, Map.class);
806    return parseJSONMetadata(response);
807  }
808
809  @Override
810  public void deleteKey(String name) throws IOException {
811    checkNotEmpty(name, "name");
812    URL url = createURL(KMSRESTConstants.KEY_RESOURCE, name, null, null);
813    HttpURLConnection conn = createConnection(url, HTTP_DELETE);
814    call(conn, null, HttpURLConnection.HTTP_OK, null);
815  }
816
817  @Override
818  public void flush() throws IOException {
819    // NOP
820    // the client does not keep any local state, thus flushing is not required
821    // because of the client.
822    // the server should not keep in memory state on behalf of clients either.
823  }
824
825  @Override
826  public void warmUpEncryptedKeys(String... keyNames)
827      throws IOException {
828    try {
829      encKeyVersionQueue.initializeQueuesForKeys(keyNames);
830    } catch (ExecutionException e) {
831      throw new IOException(e);
832    }
833  }
834
835  @Override
836  public void drain(String keyName) {
837    encKeyVersionQueue.drain(keyName);
838  }
839
840  @VisibleForTesting
841  public int getEncKeyQueueSize(String keyName) throws IOException {
842    try {
843      return encKeyVersionQueue.getSize(keyName);
844    } catch (ExecutionException e) {
845      throw new IOException(e);
846    }
847  }
848
849  @Override
850  public Token<?>[] addDelegationTokens(final String renewer,
851      Credentials credentials) throws IOException {
852    Token<?>[] tokens = null;
853    Text dtService = getDelegationTokenService();
854    Token<?> token = credentials.getToken(dtService);
855    if (token == null) {
856      final URL url = createURL(null, null, null, null);
857      final DelegationTokenAuthenticatedURL authUrl =
858          new DelegationTokenAuthenticatedURL(configurator);
859      try {
860        // 'actualUGI' is the UGI of the user creating the client 
861        // It is possible that the creator of the KMSClientProvier
862        // calls this method on behalf of a proxyUser (the doAsUser).
863        // In which case this call has to be made as the proxy user.
864        UserGroupInformation currentUgi = UserGroupInformation.getCurrentUser();
865        final String doAsUser = (currentUgi.getAuthenticationMethod() ==
866            UserGroupInformation.AuthenticationMethod.PROXY)
867                                ? currentUgi.getShortUserName() : null;
868
869        token = actualUgi.doAs(new PrivilegedExceptionAction<Token<?>>() {
870          @Override
871          public Token<?> run() throws Exception {
872            // Not using the cached token here.. Creating a new token here
873            // everytime.
874            return authUrl.getDelegationToken(url,
875                new DelegationTokenAuthenticatedURL.Token(), renewer, doAsUser);
876          }
877        });
878        if (token != null) {
879          credentials.addToken(token.getService(), token);
880          tokens = new Token<?>[] { token };
881        } else {
882          throw new IOException("Got NULL as delegation token");
883        }
884      } catch (InterruptedException e) {
885        Thread.currentThread().interrupt();
886      } catch (Exception e) {
887        throw new IOException(e);
888      }
889    }
890    return tokens;
891  }
892  
893  private Text getDelegationTokenService() throws IOException {
894    URL url = new URL(kmsUrl);
895    InetSocketAddress addr = new InetSocketAddress(url.getHost(),
896        url.getPort());
897    Text dtService = SecurityUtil.buildTokenService(addr);
898    return dtService;
899  }
900
901  /**
902   * Shutdown valueQueue executor threads
903   */
904  @Override
905  public void close() throws IOException {
906    try {
907      encKeyVersionQueue.shutdown();
908    } catch (Exception e) {
909      throw new IOException(e);
910    } finally {
911      if (sslFactory != null) {
912        sslFactory.destroy();
913      }
914    }
915  }
916
917  @VisibleForTesting
918  String getKMSUrl() {
919    return kmsUrl;
920  }
921}