BetterCloud / vault-java-driver

Zero-dependency Java client for HashiCorp's Vault
https://bettercloud.github.io/vault-java-driver/
336 stars 223 forks source link

New feature: encrypt / decrypt in batch mode #100

Closed lidalei closed 4 years ago

lidalei commented 6 years ago

In Vault transit/encrypt or transit/decrypt rest APIs, the batch mode is supported by specifying {"batch_input":[{"ciphertext": ""}, {"ciphertext": ""}]} in the request body. However, the write function in Logical.java does not support batch mode. Could we provide a write function that takes as input a path and a body bytes, for example write(String path, byte[] body) that will support any kind of rest API call?

lidalei commented 6 years ago

A possible implementation is

  private LogicalResponse writeRequest(String path, String body) throws VaultException {
    int retryCount = 0;
    while (true) {
      try {
        final RestResponse restResponse =
            new Rest() //NOPMD
                .url(config.getAddress() + "/v1/" + path)
                .body(body.getBytes("UTF-8"))
                .header("X-Vault-Token", config.getToken())
                .connectTimeoutSeconds(config.getOpenTimeout())
                .readTimeoutSeconds(config.getReadTimeout())
                .sslVerification(config.getSslConfig().isVerify())
                .sslContext(config.getSslConfig().getSslContext())
                .post();

        // HTTP Status should be either 200 (with content - e.g. PKI write) or 204 (no content)
        final int restStatus = restResponse.getStatus();
        if (restStatus == 200 || restStatus == 204) {
          return new LogicalResponse(restResponse, retryCount);
        } else {
          throw new VaultException(
              "Expecting HTTP status 204 or 200, but instead receiving "
                  + restStatus
                  + "\nResponse body: "
                  + new String(restResponse.getBody(), "UTF-8"),
              restStatus);
        }
      } catch (Exception e) {
        // If there are retries to perform, then pause for the configured interval and then execute the loop again...
        if (retryCount < config.getMaxRetries()) {
          retryCount++;
          try {
            final int retryIntervalMilliseconds = config.getRetryIntervalMilliseconds();
            Thread.sleep(retryIntervalMilliseconds);
          } catch (InterruptedException e1) {
            e1.printStackTrace();
          }
        } else if (e instanceof VaultException) {
          // ... otherwise, give up.
          throw (VaultException) e;
        } else {
          throw new VaultException(e);
        }
      }
    }
  }

In this way, the existing writeResponse method can be simplified. So this is only a minor change providing big convenience.

dicaeffe commented 3 years ago

@lidalei how was implemented this issue?