com.amazonaws.services.kms.AWSKMSClient Java Examples

The following examples show how to use com.amazonaws.services.kms.AWSKMSClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KmsRegionConfigurationTest.java    From spring-cloud-config-aws-kms with Apache License 2.0 6 votes vote down vote up
@Test
public void testContext() {
    assertThat(kms)
            .isNotNull()
            .isInstanceOf(AWSKMSClient.class);

    // endpoint configured based on aws.kms.region property
    AWSKMSClient client = (AWSKMSClient) kms;
    Field field = ReflectionUtils.findField(AWSKMSClient.class, "endpoint");
    ReflectionUtils.makeAccessible(Objects.requireNonNull(field));
    Object endpointObject = ReflectionUtils.getField(field, client);
    assertThat(endpointObject)
            .isNotNull()
            .isInstanceOf(URI.class);
    URI endpoint = (URI) endpointObject;
    assertThat(endpoint.toString()).contains("eu-central-1");

    // no override should occur in this configuration
    Field signerRegionField = ReflectionUtils.findField(AWSKMSClient.class, "signerRegionOverride");
    ReflectionUtils.makeAccessible(Objects.requireNonNull(signerRegionField));
    Object signerRegionObject = ReflectionUtils.getField(signerRegionField, client);
    assertThat(signerRegionObject).isNull();
}
 
Example #2
Source File: KmsMasterKeyProvider.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
private AWSKMSClientBuilder cloneClientBuilder(final AWSKMSClientBuilder builder) {
    // We need to copy all arguments out of the builder in case it's mutated later on.
    // Unfortunately AWSKMSClientBuilder doesn't support .clone() so we'll have to do it by hand.

    if (builder.getEndpoint() != null) {
        // We won't be able to set the region later if a custom endpoint is set.
        throw new IllegalArgumentException("Setting endpoint configuration is not compatible with passing a " +
                                           "builder to the KmsMasterKeyProvider. Use withCustomClientFactory" +
                                           " instead.");
    }

    final AWSKMSClientBuilder newBuilder = AWSKMSClient.builder();
    newBuilder.setClientConfiguration(builder.getClientConfiguration());
    newBuilder.setCredentials(builder.getCredentials());
    newBuilder.setEndpointConfiguration(builder.getEndpoint());
    newBuilder.setMetricsCollector(builder.getMetricsCollector());
    if (builder.getRequestHandlers() != null) {
        newBuilder.setRequestHandlers(builder.getRequestHandlers().toArray(new RequestHandler2[0]));
    }
    return newBuilder;
}
 
Example #3
Source File: KmsService.java    From cerberus with Apache License 2.0 6 votes vote down vote up
/**
 * Delete a CMK in AWS
 *
 * @param kmsKeyId - The AWS KMS Key ID
 * @param region - The KMS key region
 */
public void scheduleKmsKeyDeletion(String kmsKeyId, String region, Integer pendingWindowInDays) {

  logger.info(
      "Scheduling kms cmk id: {} in region: {} for deletion in {} days",
      kmsKeyId,
      region,
      pendingWindowInDays);

  final AWSKMSClient kmsClient = kmsClientFactory.getClient(region);
  final ScheduleKeyDeletionRequest scheduleKeyDeletionRequest =
      new ScheduleKeyDeletionRequest()
          .withKeyId(kmsKeyId)
          .withPendingWindowInDays(pendingWindowInDays);

  try {
    kmsClient.scheduleKeyDeletion(scheduleKeyDeletionRequest);
  } catch (KMSInvalidStateException e) {
    if (e.getErrorMessage().contains("pending deletion")) {
      logger.warn("The key: {} in region: {} is already pending deletion", kmsKeyId, region);
    } else {
      throw e;
    }
  }
}
 
Example #4
Source File: KmsEndpointConfigurationTest.java    From spring-cloud-config-aws-kms with Apache License 2.0 5 votes vote down vote up
@Test
public void testContext() {
    assertThat(kms)
            .isNotNull()
            .isInstanceOf(AWSKMSClient.class);

    AWSKMSClient client = (AWSKMSClient) kms;

    // prove aws.kms.endpoint.service-endpoint was used to configure the kms client
    Field endpointField = ReflectionUtils.findField(AWSKMSClient.class, "endpoint");
    ReflectionUtils.makeAccessible(Objects.requireNonNull(endpointField));
    Object endpointObject = ReflectionUtils.getField(endpointField, client);
    assertThat(endpointObject)
            .isNotNull()
            .isInstanceOf(URI.class);
    URI endpoint = (URI) endpointObject;
    assertThat(endpoint.toString()).contains("us-east-1");

    // prove override was issued via the aws.kms.endpoint.signing-region property
    Field signerRegionField = ReflectionUtils.findField(AWSKMSClient.class, "signerRegionOverride");
    ReflectionUtils.makeAccessible(Objects.requireNonNull(signerRegionField));
    Object signerRegionObject = ReflectionUtils.getField(signerRegionField, client);
    assertThat(signerRegionObject)
            .isNotNull()
            .isInstanceOf(String.class);
    String signerRegion = (String) signerRegionObject;
    assertThat(signerRegion).isEqualTo("us-east-2");
}
 
Example #5
Source File: KmsServiceTest.java    From cerberus with Apache License 2.0 5 votes vote down vote up
@Test
public void test_getKmsKeyState_happy() {
  String awsRegion = "aws region";

  String kmsKeyId = "kms key id";
  String state = "state";
  AWSKMSClient kmsClient = mock(AWSKMSClient.class);
  when(kmsClientFactory.getClient(awsRegion)).thenReturn(kmsClient);
  when(kmsClient.describeKey(anyObject()))
      .thenReturn(new DescribeKeyResult().withKeyMetadata(new KeyMetadata().withKeyState(state)));

  String result = kmsService.getKmsKeyState(kmsKeyId, awsRegion);

  assertEquals(state, result);
}
 
Example #6
Source File: KmsServiceTest.java    From cerberus with Apache License 2.0 5 votes vote down vote up
@Test
public void test_validateKeyAndPolicy_does_not_throw_error_when_cannot_validate() {
  String keyId = "key-id";
  String iamPrincipalArn = "arn";
  String kmsCMKRegion = "kmsCMKRegion";
  String policy = "policy";
  OffsetDateTime lastValidated = OffsetDateTime.of(2016, 1, 1, 1, 1, 1, 1, ZoneOffset.UTC);
  OffsetDateTime now = OffsetDateTime.now();
  when(dateTimeSupplier.get()).thenReturn(now);

  AwsIamRoleKmsKeyRecord kmsKey = mock(AwsIamRoleKmsKeyRecord.class);
  when(kmsKey.getAwsKmsKeyId()).thenReturn(keyId);
  when(kmsKey.getAwsIamRoleId()).thenReturn(iamPrincipalArn);
  when(kmsKey.getAwsRegion()).thenReturn(kmsCMKRegion);
  when(kmsKey.getLastValidatedTs()).thenReturn(lastValidated);

  AWSKMSClient client = mock(AWSKMSClient.class);
  when(kmsClientFactory.getClient(kmsCMKRegion)).thenReturn(client);

  GetKeyPolicyResult result = mock(GetKeyPolicyResult.class);
  when(result.getPolicy()).thenReturn(policy);
  when(client.getKeyPolicy(new GetKeyPolicyRequest().withKeyId(keyId).withPolicyName("default")))
      .thenThrow(AmazonServiceException.class);

  kmsService.validateKeyAndPolicy(kmsKey, iamPrincipalArn);

  verify(kmsPolicyService, never()).isPolicyValid(policy);
  verify(client, never()).putKeyPolicy(anyObject());
}
 
Example #7
Source File: KmsServiceTest.java    From cerberus with Apache License 2.0 5 votes vote down vote up
@Test
public void test_validatePolicy_validates_policy_when_validate_interval_has_passed() {
  String kmsKeyArn = "kms key arn";
  String awsIamRoleRecordId = "aws iam role record id";
  String kmsCMKRegion = "kmsCMKRegion";
  String policy = "policy";
  OffsetDateTime lastValidated = OffsetDateTime.of(2016, 1, 1, 1, 1, 1, 1, ZoneOffset.UTC);
  OffsetDateTime now = OffsetDateTime.now();

  AWSKMSClient client = mock(AWSKMSClient.class);
  when(client.describeKey(anyObject()))
      .thenReturn(
          new DescribeKeyResult()
              .withKeyMetadata(new KeyMetadata().withKeyState(KeyState.Enabled)));

  when(kmsClientFactory.getClient(kmsCMKRegion)).thenReturn(client);

  GetKeyPolicyResult result = mock(GetKeyPolicyResult.class);
  when(result.getPolicy()).thenReturn(policy);
  when(client.getKeyPolicy(
          new GetKeyPolicyRequest().withKeyId(kmsKeyArn).withPolicyName("default")))
      .thenReturn(result);
  when(kmsPolicyService.isPolicyValid(policy)).thenReturn(true);

  AwsIamRoleKmsKeyRecord kmsKey = mock(AwsIamRoleKmsKeyRecord.class);
  when(kmsKey.getAwsIamRoleId()).thenReturn(awsIamRoleRecordId);
  when(kmsKey.getAwsKmsKeyId()).thenReturn(kmsKeyArn);
  when(kmsKey.getAwsRegion()).thenReturn(kmsCMKRegion);
  when(kmsKey.getLastValidatedTs()).thenReturn(lastValidated);
  when(awsIamRoleDao.getKmsKey(awsIamRoleRecordId, kmsCMKRegion)).thenReturn(Optional.of(kmsKey));

  when(dateTimeSupplier.get()).thenReturn(now);
  kmsService.validateKeyAndPolicy(kmsKey, kmsKeyArn);

  verify(client, times(1))
      .getKeyPolicy(new GetKeyPolicyRequest().withKeyId(kmsKeyArn).withPolicyName("default"));
  verify(kmsPolicyService, times(1)).isPolicyValid(policy);
}
 
Example #8
Source File: KmsEncryptionConfiguration.java    From spring-cloud-config-aws-kms with Apache License 2.0 5 votes vote down vote up
@Bean
public AWSKMS kms() {
    final AWSKMSClientBuilder builder = AWSKMSClient.builder();

    if (Optional.ofNullable(properties.getEndpoint()).isPresent()) {
        builder.withEndpointConfiguration(new EndpointConfiguration(properties.getEndpoint().getServiceEndpoint(), properties.getEndpoint().getSigningRegion()));
    } else {
        Optional.ofNullable(properties.getRegion()).ifPresent(builder::setRegion);
    }

    return builder.build();
}
 
Example #9
Source File: JCredStashWrapper.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for the JCredStashWrapper
 *
 * @param region the aws region location of the KMS Client
 * @param tableName name of the credentials table
 * @param clientConfiguration the AWS client configuration
 */
public JCredStashWrapper(String region, String tableName, ClientConfiguration clientConfiguration)
{
    AWSCredentialsProvider provider = new DefaultAWSCredentialsProviderChain();
    AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(provider, clientConfiguration).withRegion(Regions.fromName(region));
    AWSKMSClient kms = new AWSKMSClient(provider, clientConfiguration).withRegion(Regions.fromName(region));
    credstash = new JCredStash(tableName, ddb, kms, new CredStashBouncyCastleCrypto());
}
 
Example #10
Source File: AuthenticationService.java    From cerberus with Apache License 2.0 5 votes vote down vote up
/**
 * Encrypts the data provided using KMS based on the provided region and key id.
 *
 * @param regionName Region where key is located
 * @param keyId Key id
 * @param data Data to be encrypted
 * @return encrypted data
 */
private byte[] encrypt(final String regionName, final String keyId, final byte[] data) {
  Region region;
  try {
    region = Region.getRegion(Regions.fromName(regionName));
  } catch (IllegalArgumentException iae) {
    throw ApiException.newBuilder()
        .withApiErrors(DefaultApiError.AUTH_IAM_ROLE_AWS_REGION_INVALID)
        .withExceptionCause(iae)
        .build();
  }

  final AWSKMSClient kmsClient = kmsClientFactory.getClient(region);

  try {
    final EncryptResult encryptResult =
        kmsClient.encrypt(
            new EncryptRequest().withKeyId(keyId).withPlaintext(ByteBuffer.wrap(data)));

    return encryptResult.getCiphertextBlob().array();
  } catch (NotFoundException | KMSInvalidStateException keyNotUsableException) {
    throw new KeyInvalidForAuthException(
        String.format("Failed to encrypt token using KMS key with id: %s", keyId),
        keyNotUsableException);
  } catch (AmazonClientException ace) {
    throw ApiException.newBuilder()
        .withApiErrors(DefaultApiError.INTERNAL_SERVER_ERROR)
        .withExceptionCause(ace)
        .withExceptionMessage(
            String.format(
                "Unexpected error communicating with AWS KMS for region %s.", regionName))
        .build();
  }
}
 
Example #11
Source File: KmsService.java    From cerberus with Apache License 2.0 5 votes vote down vote up
/**
 * Get the state of the KMS key
 *
 * @param kmsKeyId - The AWS KMS Key ID
 * @param region - The KMS key region
 * @return - KMS key state
 */
protected String getKmsKeyState(String kmsKeyId, String region) {

  AWSKMSClient kmsClient = kmsClientFactory.getClient(region);
  DescribeKeyRequest request = new DescribeKeyRequest().withKeyId(kmsKeyId);

  return kmsClient.describeKey(request).getKeyMetadata().getKeyState();
}
 
Example #12
Source File: KmsService.java    From cerberus with Apache License 2.0 5 votes vote down vote up
/** Updates the KMS key policy in AWS for the given CMK */
protected void updateKmsKeyPolicy(
    String updatedPolicyJson, String awsKmsKeyArn, String kmsCMKRegion) {

  AWSKMSClient kmsClient = kmsClientFactory.getClient(kmsCMKRegion);

  kmsClient.putKeyPolicy(
      new PutKeyPolicyRequest()
          .withKeyId(awsKmsKeyArn)
          .withPolicyName("default")
          .withPolicy(updatedPolicyJson));
}
 
Example #13
Source File: KmsDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public String decrypt(AwsParamsDto awsParamsDto, String base64ciphertextBlob)
{
    // Construct a new AWS KMS service client using the specified client configuration.
    // A credentials provider chain will be used that searches for credentials in this order:
    // - Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY
    // - Java System Properties - aws.accessKeyId and aws.secretKey
    // - Instance Profile Credentials - delivered through the Amazon EC2 metadata service
    AWSKMSClient awsKmsClient = new AWSKMSClient(awsHelper.getClientConfiguration(awsParamsDto));

    // Decode the base64 encoded ciphertext.
    ByteBuffer ciphertextBlob = ByteBuffer.wrap(Base64.decodeBase64(base64ciphertextBlob));

    // Create the decrypt request.
    DecryptRequest decryptRequest = new DecryptRequest().withCiphertextBlob(ciphertextBlob);

    // Call AWS KMS decrypt service method.
    DecryptResult decryptResult = kmsOperations.decrypt(awsKmsClient, decryptRequest);

    // Get decrypted plaintext data.
    ByteBuffer plainText = decryptResult.getPlaintext();

    // Return the plain text as a string.
    return new String(plainText.array(), StandardCharsets.UTF_8);
}
 
Example #14
Source File: MockKmsOperationsImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public DecryptResult decrypt(AWSKMSClient awsKmsClient, DecryptRequest decryptRequest)
{
    // Check the cipher text.
    if (decryptRequest.getCiphertextBlob().equals(ByteBuffer.wrap(Base64.decodeBase64(MOCK_CIPHER_TEXT_INVALID))))
    {
        throw new InvalidCiphertextException("(Service: AWSKMS; Status Code: 400; Error Code: InvalidCiphertextException; Request ID: NONE)");
    }

    DecryptResult decryptResult = new DecryptResult();

    // Convert the test plain text to byte buffer and set the plain text return value.
    decryptResult.setPlaintext(ByteBuffer.wrap(MOCK_PLAIN_TEXT.getBytes()));

    return decryptResult;
}
 
Example #15
Source File: KmsClientFactory.java    From cerberus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a KMS client for the given region name. Clients are cached by region.
 *
 * @param regionName Region to configure a client for
 * @return AWS KMS client
 */
public AWSKMSClient getClient(String regionName) {
  try {
    final Region region = Region.getRegion(Regions.fromName(regionName));
    return getClient(region);
  } catch (IllegalArgumentException iae) {
    throw ApiException.newBuilder()
        .withApiErrors(DefaultApiError.AUTHENTICATION_ERROR_INVALID_REGION)
        .withExceptionCause(iae.getCause())
        .withExceptionMessage("Specified region is not valid.")
        .build();
  }
}
 
Example #16
Source File: KmsClientFactory.java    From cerberus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a KMS client for the given region. Clients are cached by region.
 *
 * @param region Region to configure a client for
 * @return AWS KMS client
 */
public AWSKMSClient getClient(Region region) {
  AWSKMSClient client = kmsClientMap.get(region);

  if (client == null) {
    final AWSKMSClient newClient = new AWSKMSClient();
    newClient.setRegion(region);
    kmsClientMap.put(region, newClient);
    client = newClient;
  }

  return client;
}
 
Example #17
Source File: AwsKms.java    From sfs with Apache License 2.0 5 votes vote down vote up
public Observable<Void> start(VertxContext<Server> vertxContext,
                              JsonObject config) {
    AwsKms _this = this;
    SfsVertx sfsVertx = vertxContext.vertx();
    return Defer.aVoid()
            .filter(aVoid -> started.compareAndSet(false, true))
            .flatMap(aVoid -> {
                String keyStoreAwsKmsEndpoint = ConfigHelper.getFieldOrEnv(config, "keystore.aws.kms.endpoint");
                Preconditions.checkArgument(keyStoreAwsKmsEndpoint != null, "keystore.aws.kms.endpoint is required");

                _this.keyId = ConfigHelper.getFieldOrEnv(config, "keystore.aws.kms.key_id");
                Preconditions.checkArgument(_this.keyId != null, "keystore.aws.kms.key_id is required");

                _this.accessKeyId = ConfigHelper.getFieldOrEnv(config, "keystore.aws.kms.access_key_id");
                Preconditions.checkArgument(_this.accessKeyId != null, "keystore.aws.kms.access_key_id is required");

                _this.secretKey = ConfigHelper.getFieldOrEnv(config, "keystore.aws.kms.secret_key");
                Preconditions.checkArgument(_this.secretKey != null, "keystore.aws.kms.secret_key is required");


                return RxHelper.executeBlocking(sfsVertx.getOrCreateContext(), sfsVertx.getBackgroundPool(),
                        () -> {
                            kms = new AWSKMSClient(new AWSCredentials() {
                                @Override
                                public String getAWSAccessKeyId() {
                                    return _this.accessKeyId;
                                }

                                @Override
                                public String getAWSSecretKey() {
                                    return _this.secretKey;
                                }
                            });
                            kms.setEndpoint(keyStoreAwsKmsEndpoint);
                            return (Void) null;
                        });
            })
            .singleOrDefault(null);
}
 
Example #18
Source File: EmrOperatorFactory.java    From digdag with Apache License 2.0 5 votes vote down vote up
private TaskResult run(String tag, AmazonElasticMapReduce emr, AWSKMSClient kms, Filer filer)
        throws IOException
{
    ParameterCompiler parameterCompiler = new ParameterCompiler(kms, context);

    // Set up step compiler
    List<Config> steps = params.getListOrEmpty("steps", Config.class);
    StepCompiler stepCompiler = new StepCompiler(tag, steps, filer, parameterCompiler, objectMapper, defaultActionOnFailure);

    // Set up job submitter
    Submitter submitter;
    Config cluster = null;
    try {
        cluster = params.parseNestedOrGetEmpty("cluster");
    }
    catch (ConfigException ignore) {
    }
    if (cluster != null) {
        // Create a new cluster
        submitter = newClusterSubmitter(emr, tag, stepCompiler, cluster, filer, parameterCompiler);
    }
    else {
        // Cluster ID? Use existing cluster.
        String clusterId = params.get("cluster", String.class);
        submitter = existingClusterSubmitter(emr, tag, stepCompiler, clusterId, filer);
    }

    // Submit EMR job
    SubmissionResult submission = submitter.submit();

    // Wait for the steps to finish running
    if (!steps.isEmpty()) {
        waitForSteps(emr, submission);
    }

    return result(submission);
}
 
Example #19
Source File: IAMPolicyManagerTest.java    From strongbox with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() {
    mockCredentials = mock(AWSCredentialsProvider.class);
    mockClient = mock(AmazonIdentityManagementClient.class);
    ClientConfiguration mockConfig = mock(ClientConfiguration.class);
    IAMPolicyManager policyManager = new IAMPolicyManager(mockClient, mockCredentials, mockConfig);

    // The mockito spy acts like original object but mocks out the getAccount() method. As the getAccount() calls
    // directly rather than via a client that we can pass in we need to mock this out using a spy.
    partiallyMockedPolicyManager = spy(policyManager);
    doReturn(ACCOUNT).when(partiallyMockedPolicyManager).getAccount();

    // Set up KMSEncryptor for testing the policy creation methods. This gets a bit complicated but we need to
    // mock all the AWS dependencies from the KMSManager before using it to create the KMSEncryptor. The getAliasArn
    // needs to be mocked out with a spy to stop the call to getAccount.
    mockKMSClient = mock(AWSKMSClient.class);
    KMSManager kmsManager = new KMSManager(mockKMSClient, mockCredentials, mockConfig, group);
    KMSManager partiallyMockedKMSManager = spy(kmsManager);
    doReturn(KMS_ALIAS_ARN).when(partiallyMockedKMSManager).getAliasArn();
    kmsEncryptor = new KMSEncryptor(partiallyMockedKMSManager, mockCredentials, mockConfig, group, mock(AwsCrypto.class), EncryptionStrength.AES_256);

    // Set up store for testing the policy creation methods. Mock out the getArn method with a spy to stop the
    // call to getAccount().
    mockDynamoDBClient = mock(AmazonDynamoDBClient.class);
    DynamoDB store = new DynamoDB(mockDynamoDBClient, mockCredentials, mockConfig, group, new ReentrantReadWriteLock());
    partiallyMockedStore = spy(store);
    doReturn(DYNAMODB_ARN).when(partiallyMockedStore).getArn();
}
 
Example #20
Source File: KMSManagerTest.java    From strongbox with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
    AWSCredentialsProvider mockCredentials = mock(AWSCredentialsProvider.class);
    this.mockKMSClient = mock(AWSKMSClient.class);
    this.group = new SecretsGroupIdentifier(TEST_REGION, TEST_GROUP);
    ClientConfiguration mockConfig = mock(ClientConfiguration.class);

    KMSManager manager = new KMSManager(mockKMSClient, mockCredentials, mockConfig, group);
    this.kmsManager = spy(manager);
    doReturn(KMS_ALIAS_ARN).when(kmsManager).getAliasArn();
}
 
Example #21
Source File: KmsOperationsImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public DecryptResult decrypt(AWSKMSClient awsKmsClient, DecryptRequest decryptRequest)
{
    // Call AWS KMS decrypt service method.
    return awsKmsClient.decrypt(decryptRequest);
}
 
Example #22
Source File: EmrOperatorFactory.java    From digdag with Apache License 2.0 4 votes vote down vote up
ParameterCompiler(AWSKMSClient kms, OperatorContext context)
{
    this.kms = Preconditions.checkNotNull(kms, "kms");
    this.context = Preconditions.checkNotNull(context, "context");
}
 
Example #23
Source File: KmsServiceTest.java    From cerberus with Apache License 2.0 4 votes vote down vote up
@Test
public void test_provisionKmsKey() {

  String iamRoleId = "role-id";
  String awsRegion = "aws-region";
  String user = "user";
  OffsetDateTime dateTime = OffsetDateTime.now();

  String policy = "policy";
  String arn = "arn:aws:iam::12345678901234:role/some-role";

  String awsIamRoleKmsKeyId = "awsIamRoleKmsKeyId";

  when(uuidSupplier.get()).thenReturn(awsIamRoleKmsKeyId);
  when(kmsPolicyService.generateStandardKmsPolicy(arn)).thenReturn(policy);

  AWSKMSClient client = mock(AWSKMSClient.class);
  when(kmsClientFactory.getClient(awsRegion)).thenReturn(client);

  CreateKeyRequest request = new CreateKeyRequest();
  request.setKeyUsage(KeyUsageType.ENCRYPT_DECRYPT);
  request.setDescription("Key used by Cerberus fakeEnv for IAM role authentication. " + arn);
  request.setPolicy(policy);
  request.setTags(
      Lists.newArrayList(
          new Tag().withTagKey("created_by").withTagValue(ARTIFACT + VERSION),
          new Tag().withTagKey("created_for").withTagValue("cerberus_auth"),
          new Tag().withTagKey("auth_principal").withTagValue(arn),
          new Tag().withTagKey("cerberus_env").withTagValue(ENV)));

  CreateKeyResult createKeyResult = mock(CreateKeyResult.class);
  KeyMetadata metadata = mock(KeyMetadata.class);
  when(metadata.getArn()).thenReturn(arn);
  when(createKeyResult.getKeyMetadata()).thenReturn(metadata);
  when(client.createKey(any())).thenReturn(createKeyResult);

  // invoke method under test
  String actualResult =
      kmsService.provisionKmsKey(iamRoleId, arn, awsRegion, user, dateTime).getAwsKmsKeyId();

  assertEquals(arn, actualResult);

  CreateAliasRequest aliasRequest = new CreateAliasRequest();
  aliasRequest.setAliasName(kmsService.getAliasName(awsIamRoleKmsKeyId, arn));
  aliasRequest.setTargetKeyId(arn);
  verify(client).createAlias(aliasRequest);

  AwsIamRoleKmsKeyRecord awsIamRoleKmsKeyRecord = new AwsIamRoleKmsKeyRecord();
  awsIamRoleKmsKeyRecord.setId(awsIamRoleKmsKeyId);
  awsIamRoleKmsKeyRecord.setAwsIamRoleId(iamRoleId);
  awsIamRoleKmsKeyRecord.setAwsKmsKeyId(arn);
  awsIamRoleKmsKeyRecord.setAwsRegion(awsRegion);
  awsIamRoleKmsKeyRecord.setCreatedBy(user);
  awsIamRoleKmsKeyRecord.setLastUpdatedBy(user);
  awsIamRoleKmsKeyRecord.setCreatedTs(dateTime);
  awsIamRoleKmsKeyRecord.setLastUpdatedTs(dateTime);
  awsIamRoleKmsKeyRecord.setLastValidatedTs(dateTime);
  verify(awsIamRoleDao).createIamRoleKmsKey(awsIamRoleKmsKeyRecord);
}
 
Example #24
Source File: KmsClientFactoryTest.java    From cerberus with Apache License 2.0 4 votes vote down vote up
@Test
public void get_client_by_region_string_returns_configured_kms_client() {
  AWSKMSClient client = subject.getClient(goodRegionName);

  assertThat(client).isNotNull();
}
 
Example #25
Source File: KmsClientFactoryTest.java    From cerberus with Apache License 2.0 4 votes vote down vote up
@Test
public void get_client_by_region_returns_configured_kms_client() {
  AWSKMSClient client = subject.getClient(goodRegion);

  assertThat(client).isNotNull();
}
 
Example #26
Source File: KmsService.java    From cerberus with Apache License 2.0 4 votes vote down vote up
private String createKmsKeyInAws(
    String iamPrincipalArn, String kmsKeyRecordId, String awsRegion) {
  final AWSKMSClient kmsClient = kmsClientFactory.getClient(awsRegion);

  final String policy = kmsPolicyService.generateStandardKmsPolicy(iamPrincipalArn);

  final CreateKeyRequest request =
      new CreateKeyRequest()
          .withKeyUsage(KeyUsageType.ENCRYPT_DECRYPT)
          .withDescription(
              "Key used by Cerberus "
                  + environmentName
                  + " for IAM role authentication. "
                  + iamPrincipalArn)
          .withPolicy(policy)
          .withTags(
              createTag("created_for", "cerberus_auth"),
              createTag("auth_principal", iamPrincipalArn),
              createTag("cerberus_env", environmentName));

  CreateKeyResult result;
  try {
    result = kmsClient.createKey(request);
  } catch (Throwable t) {
    logger.error("Failed to provision KMS key using policy: {}", policy, t);
    throw t;
  }

  String kmsKeyAliasName = getAliasName(kmsKeyRecordId, iamPrincipalArn);
  String kmsKeyArn = result.getKeyMetadata().getArn();
  try {
    // alias is only used to provide extra description in AWS console
    final CreateAliasRequest aliasRequest =
        new CreateAliasRequest()
            .withAliasName(kmsKeyAliasName)
            .withTargetKeyId(result.getKeyMetadata().getArn());
    kmsClient.createAlias(aliasRequest);
  } catch (RuntimeException re) {
    logger.error("Failed to create KMS alias: {}, for keyId: {}", kmsKeyAliasName, kmsKeyArn);
  }

  return kmsKeyArn;
}
 
Example #27
Source File: JCredStash.java    From jcredstash with Apache License 2.0 4 votes vote down vote up
public JCredStash(AWSCredentialsProvider awsCredentialsProvider) {
    this.amazonDynamoDBClient = new AmazonDynamoDBClient(awsCredentialsProvider);
    this.awskmsClient = new AWSKMSClient(awsCredentialsProvider);
    this.cryptoImpl = new CredStashBouncyCastleCrypto();
}
 
Example #28
Source File: JCredStash.java    From jcredstash with Apache License 2.0 4 votes vote down vote up
public JCredStash() {
    this.amazonDynamoDBClient = new AmazonDynamoDBClient();
    this.awskmsClient = new AWSKMSClient();
    this.cryptoImpl = new CredStashBouncyCastleCrypto();
}
 
Example #29
Source File: KmsService.java    From cerberus with Apache License 2.0 3 votes vote down vote up
/** Gets the KMS key policy from AWS for the given CMK */
protected String getKmsKeyPolicy(String kmsKeyId, String kmsCMKRegion) {

  AWSKMSClient kmsClient = kmsClientFactory.getClient(kmsCMKRegion);

  GetKeyPolicyRequest request =
      new GetKeyPolicyRequest().withKeyId(kmsKeyId).withPolicyName("default");

  return kmsClient.getKeyPolicy(request).getPolicy();
}
 
Example #30
Source File: KmsOperations.java    From herd with Apache License 2.0 2 votes vote down vote up
/**
 * Executes the decrypt request by calling the AWS KMS service.
 *
 * @param awsKmsClient the client for accessing the AWS KMS service
 * @param decryptRequest the decrypt request
 *
 * @return the response from the decrypt service method, as returned by AWS KMS service
 */
public DecryptResult decrypt(AWSKMSClient awsKmsClient, DecryptRequest decryptRequest);