index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/TestVectors/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb | Create_ds/aws-database-encryption-sdk-dynamodb-java/TestVectors/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/wrapped/TestDynamoDbEncryption.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.dynamodb.wrapped;
import Wrappers_Compile.Result;
import java.lang.IllegalArgumentException;
import java.lang.RuntimeException;
import java.util.Objects;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryption;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.ToDafny;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.ToNative;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.CreateDynamoDbEncryptionBranchKeyIdSupplierInput;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.CreateDynamoDbEncryptionBranchKeyIdSupplierOutput;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.Error;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.IDynamoDbEncryptionClient;
public class TestDynamoDbEncryption implements IDynamoDbEncryptionClient {
private final DynamoDbEncryption _impl;
protected TestDynamoDbEncryption(BuilderImpl builder) {
this._impl = builder.impl();
}
public static Builder builder() {
return new BuilderImpl();
}
public Result<CreateDynamoDbEncryptionBranchKeyIdSupplierOutput, Error> CreateDynamoDbEncryptionBranchKeyIdSupplier(
CreateDynamoDbEncryptionBranchKeyIdSupplierInput dafnyInput) {
software.amazon.cryptography.dbencryptionsdk.dynamodb.model.CreateDynamoDbEncryptionBranchKeyIdSupplierInput nativeInput = ToNative.CreateDynamoDbEncryptionBranchKeyIdSupplierInput(dafnyInput);
try {
software.amazon.cryptography.dbencryptionsdk.dynamodb.model.CreateDynamoDbEncryptionBranchKeyIdSupplierOutput nativeOutput = this._impl.CreateDynamoDbEncryptionBranchKeyIdSupplier(nativeInput);
CreateDynamoDbEncryptionBranchKeyIdSupplierOutput dafnyOutput = ToDafny.CreateDynamoDbEncryptionBranchKeyIdSupplierOutput(nativeOutput);
return Result.create_Success(dafnyOutput);
} catch (RuntimeException ex) {
return Result.create_Failure(ToDafny.Error(ex));
}
}
public interface Builder {
Builder impl(DynamoDbEncryption impl);
DynamoDbEncryption impl();
TestDynamoDbEncryption build();
}
static class BuilderImpl implements Builder {
protected DynamoDbEncryption impl;
protected BuilderImpl() {
}
public Builder impl(DynamoDbEncryption impl) {
this.impl = impl;
return this;
}
public DynamoDbEncryption impl() {
return this.impl;
}
public TestDynamoDbEncryption build() {
if (Objects.isNull(this.impl())) {
throw new IllegalArgumentException("Missing value for required field `impl`");
}
return new TestDynamoDbEncryption(this);
}
}
}
| 5,300 |
0 | Create_ds/dgs-examples-java.latest/.mvn | Create_ds/dgs-examples-java.latest/.mvn/wrapper/MavenWrapperDownloader.java | /*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
| 5,301 |
0 | Create_ds/dgs-examples-java.latest/src/test/java/com/example | Create_ds/dgs-examples-java.latest/src/test/java/com/example/dgsjava16maven/DemoApplicationTests.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dgsjava16maven;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
}
}
| 5,302 |
0 | Create_ds/dgs-examples-java.latest/src/main/java/com/example | Create_ds/dgs-examples-java.latest/src/main/java/com/example/dgsjava16maven/ShowsDataFetcher.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dgsjava16maven;
import com.example.dgsjava16maven.records.Show;
import com.netflix.graphql.dgs.DgsComponent;
import com.netflix.graphql.dgs.DgsData;
import com.netflix.graphql.dgs.InputArgument;
import java.util.List;
@DgsComponent
public class ShowsDataFetcher {
private final List<Show> showData = List.of(
new Show(1, "Stringer Things", 2016),
new Show(2, "Ozark", 2017)
);
@DgsData(parentType = "Query", field = "shows")
public List<Show> shows(@InputArgument String titleFilter) {
if(titleFilter != null) {
return showData.stream().filter(s -> s.title().startsWith(titleFilter)).toList();
} else {
return showData;
}
}
}
| 5,303 |
0 | Create_ds/dgs-examples-java.latest/src/main/java/com/example | Create_ds/dgs-examples-java.latest/src/main/java/com/example/dgsjava16maven/DemoApplication.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dgsjava16maven;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
| 5,304 |
0 | Create_ds/dgs-examples-java.latest/src/main/java/com/example/dgsjava16maven | Create_ds/dgs-examples-java.latest/src/main/java/com/example/dgsjava16maven/records/Show.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dgsjava16maven.records;
public record Show(Integer id, String title, Integer releaseYear) {
}
| 5,305 |
0 | Create_ds/aws-secretsmanager-caching-java/src/test/java/com/amazonaws/secretsmanager | Create_ds/aws-secretsmanager-caching-java/src/test/java/com/amazonaws/secretsmanager/caching/SecretCacheTest.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.secretsmanager.caching;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.IntConsumer;
import org.mockito.ArgumentMatcher;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClientBuilder;
import software.amazon.awssdk.services.secretsmanager.model.DescribeSecretRequest;
import software.amazon.awssdk.services.secretsmanager.model.DescribeSecretResponse;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
/**
* SecretCacheTest.
*/
public class SecretCacheTest {
@Mock
private SecretsManagerClient asm;
@Mock
private DescribeSecretResponse describeSecretResponse;
private GetSecretValueResponse getSecretValueResponse = GetSecretValueResponse.builder()
.versionStages(Arrays.asList("v1")).build();
@Mock
private SecretCacheConfiguration secretCacheConfiguration;
@BeforeMethod
public void setUp() {
MockitoAnnotations.openMocks(this);
}
private static void repeat(int number, IntConsumer c) {
for (int n = 0; n < number; ++n) {
c.accept(n);
}
}
@Test
public void secretCacheConstructorTest() {
// coverage for null parameters to constructor
SecretCache sc1 = null;
SecretCache sc2 = null;
try {
sc1 = new SecretCache((SecretCacheConfiguration) null);
sc1.close();
} catch (Exception e) {
}
try {
sc2 = new SecretCache((SecretsManagerClientBuilder) null);
sc2.close();
} catch (Exception e) {
}
}
@Test
public void basicSecretCacheTest() {
final String secret = "basicSecretCacheTest";
Map<String, List<String>> versionMap = new HashMap<String, List<String>>();
versionMap.put("versionId", Arrays.asList("AWSCURRENT"));
Mockito.when(describeSecretResponse.versionIdsToStages()).thenReturn(versionMap);
GetSecretValueResponse.Builder resBuilder = GetSecretValueResponse.builder().secretString(secret)
.secretBinary(SdkBytes.fromByteArray(secret.getBytes()));
getSecretValueResponse = resBuilder.build();
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenReturn(describeSecretResponse);
Mockito.when(asm.getSecretValue(Mockito.any(GetSecretValueRequest.class))).thenReturn(getSecretValueResponse);
SecretCache sc = new SecretCache(asm);
// Request the secret multiple times and verify the correct result
repeat(10, n -> Assert.assertEquals(sc.getSecretString(""), secret));
// Verify that multiple requests did not call the API
Mockito.verify(asm, Mockito.times(1)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(1)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
repeat(10, n -> Assert.assertEquals(sc.getSecretBinary(""),
ByteBuffer.wrap(secret.getBytes())));
sc.close();
}
@Test
public void hookSecretCacheTest() {
final String secret = "hookSecretCacheTest";
Map<String, List<String>> versionMap = new HashMap<String, List<String>>();
versionMap.put("versionId", Arrays.asList("AWSCURRENT"));
Mockito.when(describeSecretResponse.versionIdsToStages()).thenReturn(versionMap);
GetSecretValueResponse.Builder resBuilder = GetSecretValueResponse.builder().secretString(secret)
.secretBinary(SdkBytes.fromByteArray(secret.getBytes()));
getSecretValueResponse = resBuilder.build();
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenReturn(describeSecretResponse);
Mockito.when(asm.getSecretValue(Mockito.any(GetSecretValueRequest.class))).thenReturn(getSecretValueResponse);
class Hook implements SecretCacheHook {
private HashMap<Integer, Object> map = new HashMap<Integer, Object>();
public Object put(final Object o) {
Integer key = map.size();
map.put(key, o);
return key;
}
public Object get(final Object o) {
return map.get((Integer) o);
}
public int getCount() {
return map.size();
}
}
Hook hook = new Hook();
SecretCache sc = new SecretCache(new SecretCacheConfiguration()
.withClient(asm)
.withCacheHook(hook));
// Request the secret multiple times and verify the correct result
repeat(10, n -> Assert.assertEquals(sc.getSecretString(""), secret));
// Verify that multiple requests did not call the API
Mockito.verify(asm, Mockito.times(1)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(1)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
repeat(10, n -> Assert.assertEquals(sc.getSecretBinary(""),
ByteBuffer.wrap(secret.getBytes())));
Assert.assertEquals(hook.getCount(), 2);
sc.close();
}
@Test
public void secretCacheNullStagesTest() {
final String secret = "basicSecretCacheTest";
Map<String, List<String>> versionMap = new HashMap<String, List<String>>();
versionMap.put("versionId", Arrays.asList("AWSCURRENT"));
Mockito.when(describeSecretResponse.versionIdsToStages()).thenReturn(versionMap);
GetSecretValueResponse.Builder resBuilder = GetSecretValueResponse.builder().secretString(secret)
.secretBinary(SdkBytes.fromByteArray(secret.getBytes())).versionStages((Collection<String>) null);
getSecretValueResponse = resBuilder.build();
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenReturn(describeSecretResponse);
Mockito.when(asm.getSecretValue(Mockito.any(GetSecretValueRequest.class))).thenReturn(getSecretValueResponse);
SecretCache sc = new SecretCache(asm);
// Request the secret multiple times and verify the correct result
repeat(10, n -> Assert.assertEquals(sc.getSecretString(""), secret));
// Verify that multiple requests did not call the API
Mockito.verify(asm, Mockito.times(1)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(1)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
repeat(10, n -> Assert.assertEquals(sc.getSecretBinary(""),
ByteBuffer.wrap(secret.getBytes())));
sc.close();
}
@Test
public void basicSecretCacheRefreshNowTest() throws Throwable {
final String secret = "basicSecretCacheRefreshNowTest";
Map<String, List<String>> versionMap = new HashMap<String, List<String>>();
versionMap.put("versionId", Arrays.asList("AWSCURRENT"));
Mockito.when(describeSecretResponse.versionIdsToStages()).thenReturn(versionMap);
GetSecretValueResponse.Builder resBuilder = GetSecretValueResponse.builder().secretString(secret)
.secretBinary(SdkBytes.fromByteArray(secret.getBytes()));
getSecretValueResponse = resBuilder.build();
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenReturn(describeSecretResponse);
Mockito.when(asm.getSecretValue(Mockito.any(GetSecretValueRequest.class))).thenReturn(getSecretValueResponse);
SecretCache sc = new SecretCache(asm);
// Request the secret multiple times and verify the correct result
repeat(10, n -> Assert.assertEquals(sc.getSecretString(""), secret));
// Verify that multiple requests did not call the API
Mockito.verify(asm, Mockito.times(1)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(1)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
sc.refreshNow("");
Mockito.verify(asm, Mockito.times(2)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(1)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
repeat(10, n -> Assert.assertEquals(sc.getSecretString(""), secret));
Mockito.verify(asm, Mockito.times(2)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(1)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
sc.close();
}
@Test
public void basicSecretCacheByteBufferTest() {
final String secret = "basicSecretCacheByteBufferTest";
Map<String, List<String>> versionMap = new HashMap<String, List<String>>();
ByteBuffer buffer = ByteBuffer.allocate(secret.getBytes(StandardCharsets.UTF_8).length);
buffer.put(secret.getBytes(StandardCharsets.UTF_8)).rewind();
versionMap.put("versionId", Arrays.asList("AWSCURRENT"));
Mockito.when(describeSecretResponse.versionIdsToStages()).thenReturn(versionMap);
GetSecretValueResponse diff = GetSecretValueResponse.builder().secretBinary(SdkBytes.fromByteBuffer(buffer))
.build();
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenReturn(describeSecretResponse);
Mockito.when(asm.getSecretValue(Mockito.any(GetSecretValueRequest.class))).thenReturn(diff);
SecretCache sc = new SecretCache(asm);
// Request the secret multiple times and verify the correct result
repeat(10, n -> Assert.assertEquals(StandardCharsets.UTF_8.decode(sc.getSecretBinary("")).toString(), secret));
// Verify that multiple requests did not call the API
Mockito.verify(asm, Mockito.times(1)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(1)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
Assert.assertEquals(sc.getSecretBinary(""), ByteBuffer.wrap(secret.getBytes()));
sc.close();
}
@Test
public void basicSecretCacheMultipleTest() {
final String secretA = "basicSecretCacheMultipleTestA";
final String secretB = "basicSecretCacheMultipleTestB";
Map<String, List<String>> versionMap = new HashMap<String, List<String>>();
versionMap.put("versionId", Arrays.asList("AWSCURRENT"));
Mockito.when(describeSecretResponse.versionIdsToStages()).thenReturn(versionMap);
getSecretValueResponse = GetSecretValueResponse.builder().secretString(secretA).build();
GetSecretValueResponse res2 = GetSecretValueResponse.builder().secretString(secretB).build();
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenReturn(describeSecretResponse);
Mockito.when(asm.getSecretValue(ArgumentMatchers.argThat(new ArgumentMatcher<GetSecretValueRequest>() {
@Override
public boolean matches(GetSecretValueRequest argument) {
if (argument == null) {
return false;
}
return argument.secretId().equals("SecretA");
}
}))).thenReturn(getSecretValueResponse);
Mockito.when(asm.getSecretValue(ArgumentMatchers.argThat(new ArgumentMatcher<GetSecretValueRequest>() {
@Override
public boolean matches(GetSecretValueRequest argument) {
if (argument == null) {
return false;
}
return argument.secretId().equals("SecretB");
}
}))).thenReturn(res2);
SecretCache sc = new SecretCache(asm);
// Request the secret multiple times and verify the correct result
repeat(10, n -> Assert.assertEquals(sc.getSecretString("SecretA"), secretA));
repeat(10, n -> Assert.assertEquals(sc.getSecretString("SecretB"), secretB));
// Verify that multiple requests did not call the API
Mockito.verify(asm, Mockito.times(2)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(2)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
sc.close();
}
@Test
public void basicSecretCacheRefreshTest() throws Throwable {
final String secret = "basicSecretCacheRefreshTest";
Map<String, List<String>> versionMap = new HashMap<String, List<String>>();
versionMap.put("versionId", Arrays.asList("AWSCURRENT"));
Mockito.when(describeSecretResponse.versionIdsToStages()).thenReturn(versionMap);
getSecretValueResponse = GetSecretValueResponse.builder().secretString(secret).build();
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenReturn(describeSecretResponse);
Mockito.when(asm.getSecretValue(Mockito.any(GetSecretValueRequest.class))).thenReturn(getSecretValueResponse);
SecretCache sc = new SecretCache(new SecretCacheConfiguration()
.withClient(asm)
.withCacheItemTTL(500));
// Request the secret multiple times and verify the correct result
repeat(10, n -> Assert.assertEquals(sc.getSecretString(""), secret));
// Verify that multiple requests did not call the API
Mockito.verify(asm, Mockito.times(1)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(1)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
// Wait long enough to expire the TTL on the cached item.
Thread.sleep(600);
repeat(10, n -> Assert.assertEquals(sc.getSecretString(""), secret));
// Verify that the refresh occurred after the ttl
Mockito.verify(asm, Mockito.times(2)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(1)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
}
@Test
public void secretCacheRefreshAfterVersionChangeTest() throws Throwable {
final String secret = "secretCacheRefreshAfterVersionChangeTest";
Map<String, List<String>> versionMap = new HashMap<String, List<String>>();
versionMap.put("versionId", Arrays.asList("AWSCURRENT"));
Mockito.when(describeSecretResponse.versionIdsToStages()).thenReturn(versionMap);
getSecretValueResponse = GetSecretValueResponse.builder().secretString(secret).build();
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenReturn(describeSecretResponse);
Mockito.when(asm.getSecretValue(Mockito.any(GetSecretValueRequest.class))).thenReturn(getSecretValueResponse);
SecretCache sc = new SecretCache(new SecretCacheConfiguration()
.withClient(asm)
.withCacheItemTTL(500));
// Request the secret multiple times and verify the correct result
repeat(5, n -> Assert.assertEquals(sc.getSecretString(""), secret));
// Verify that multiple requests did not call the API
Mockito.verify(asm, Mockito.times(1)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(1)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
// Wait long enough to expire the TTL on the cached item.
Thread.sleep(600);
versionMap.clear();
// Simulate a change in secret version values
versionMap.put("versionIdNew", Arrays.asList("AWSCURRENT"));
repeat(5, n -> Assert.assertEquals(sc.getSecretString(""), secret));
// Verify that the refresh occurred after the ttl
Mockito.verify(asm, Mockito.times(2)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(2)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
}
@Test
public void basicSecretCacheTestNoVersions() {
final String secret = "basicSecretCacheTestNoVersion";
getSecretValueResponse = GetSecretValueResponse.builder().secretString(secret).build();
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenReturn(describeSecretResponse);
Mockito.when(asm.getSecretValue(Mockito.any(GetSecretValueRequest.class))).thenReturn(getSecretValueResponse);
SecretCache sc = new SecretCache(asm);
// Request the secret multiple times and verify the correct result
repeat(10, m -> Assert.assertNull(sc.getSecretString("")));
repeat(10, m -> Assert.assertNull(sc.getSecretBinary("")));
// Verify that multiple requests did not call the API
Mockito.verify(asm, Mockito.times(1)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(0)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
sc.close();
}
@Test(expectedExceptions = { RuntimeException.class })
public void basicSecretCacheExceptionTest() {
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenThrow(new RuntimeException());
SecretCache sc = new SecretCache(asm);
sc.getSecretString("");
sc.close();
}
@Test
public void basicSecretCacheExceptionRefreshNowTest() throws Throwable {
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenThrow(new RuntimeException());
SecretCache sc = new SecretCache(asm);
Assert.assertFalse(sc.refreshNow(""));
Mockito.verify(asm, Mockito.times(1)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Assert.assertFalse(sc.refreshNow(""));
Mockito.verify(asm, Mockito.times(2)).describeSecret(Mockito.any(DescribeSecretRequest.class));
sc.close();
}
@Test
public void basicSecretCacheExceptionRetryTest() throws Throwable {
final int retryCount = 10;
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenThrow(new RuntimeException());
SecretCache sc = new SecretCache(asm);
for (int n = 0; n < retryCount; ++n) {
try {
sc.getSecretString("");
Assert.fail("Exception should have been thrown!");
} catch (RuntimeException ex) {
}
}
Mockito.verify(asm, Mockito.times(1)).describeSecret(Mockito.any(DescribeSecretRequest.class));
// Wait the backoff interval before retrying failed requests to verify
// a retry will be performed.
Thread.sleep(2100);
try {
sc.getSecretString("");
Assert.fail("Exception should have been thrown!");
} catch (RuntimeException ex) {
}
// The api call should have been retried after the delay.
Mockito.verify(asm, Mockito.times(2)).describeSecret(Mockito.any(DescribeSecretRequest.class));
sc.close();
}
@Test
public void basicSecretCacheNullTest() {
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenReturn(null);
SecretCache sc = new SecretCache(asm);
Assert.assertNull(sc.getSecretString(""));
sc.close();
}
@Test
public void basicSecretCacheNullStagesTest() {
Mockito.when(describeSecretResponse.versionIdsToStages()).thenReturn(null);
SecretCache sc = new SecretCache(asm);
Assert.assertNull(sc.getSecretString(""));
sc.close();
}
@Test
public void basicSecretCacheVersionWithNullStageTest() {
final String secret = "basicSecretCacheTest";
Map<String, List<String>> versionMap = new HashMap<String, List<String>>();
versionMap.put("versionId", null);
Mockito.when(describeSecretResponse.versionIdsToStages()).thenReturn(versionMap);
getSecretValueResponse = GetSecretValueResponse.builder().secretString(secret).build();
Mockito.when(asm.describeSecret(Mockito.any(DescribeSecretRequest.class))).thenReturn(describeSecretResponse);
Mockito.when(asm.getSecretValue(Mockito.any(GetSecretValueRequest.class))).thenReturn(getSecretValueResponse);
SecretCache sc = new SecretCache(asm);
// Request the secret multiple times and verify the correct result
repeat(10, n -> Assert.assertEquals(sc.getSecretString(""), null));
// Verify that multiple requests did not call the API
Mockito.verify(asm, Mockito.times(1)).describeSecret(Mockito.any(DescribeSecretRequest.class));
Mockito.verify(asm, Mockito.times(0)).getSecretValue(Mockito.any(GetSecretValueRequest.class));
sc.close();
}
}
| 5,306 |
0 | Create_ds/aws-secretsmanager-caching-java/src/test/java/com/amazonaws/secretsmanager/caching | Create_ds/aws-secretsmanager-caching-java/src/test/java/com/amazonaws/secretsmanager/caching/cache/SecretCacheItemTest.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.secretsmanager.caching.cache;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SecretCacheItemTest {
@Test
public void cacheItemEqualsTest() {
SecretCacheItem i1 = new SecretCacheItem("test", null, null);
SecretCacheItem i2 = new SecretCacheItem("test", null, null);
SecretCacheItem i3 = new SecretCacheItem("test3", null, null);
Assert.assertEquals(i1, i2);
Assert.assertNotEquals(i1, null);
Assert.assertNotEquals(i1, i3);
Assert.assertFalse(i1.equals(null));
Assert.assertEquals(i1.hashCode(), i2.hashCode());
Assert.assertNotEquals(i1.hashCode(), i3.hashCode());
Assert.assertEquals(i3.toString(), "SecretCacheItem: test3");
}
}
| 5,307 |
0 | Create_ds/aws-secretsmanager-caching-java/src/test/java/com/amazonaws/secretsmanager/caching | Create_ds/aws-secretsmanager-caching-java/src/test/java/com/amazonaws/secretsmanager/caching/cache/LRUCacheTest.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.secretsmanager.caching.cache;
import java.util.HashMap;
import org.testng.annotations.Test;
import org.testng.Assert;
public class LRUCacheTest {
@Test
public void putIntTest() {
LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>();
cache.put(1, 1);
Assert.assertTrue(cache.containsKey(1));
Assert.assertEquals(cache.get(1), new Integer(1));
}
@Test
public void removeTest() {
LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>();
cache.put(1, 1);
Assert.assertNotNull(cache.get(1));
Assert.assertTrue(cache.remove(1));
Assert.assertNull(cache.get(1));
Assert.assertFalse(cache.remove(1));
Assert.assertNull(cache.get(1));
}
@Test
public void removeAllTest() {
int max = 100;
LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>();
for (int n = 0; n < max; ++n) {
cache.put(n, n);
}
cache.removeAll();
for (int n = 0; n < max; ++n) {
Assert.assertNull(cache.get(n));
}
}
@Test
public void clearTest() {
int max = 100;
LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>();
for (int n = 0; n < max; ++n) {
cache.put(n, n);
}
cache.clear();
for (int n = 0; n < max; ++n) {
Assert.assertNull(cache.get(n));
}
}
@Test
public void getAndRemoveTest() {
LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>();
cache.put(1, 1);
Assert.assertNotNull(cache.get(1));
Assert.assertEquals(cache.getAndRemove(1), new Integer(1));
Assert.assertNull(cache.get(1));
}
@Test
public void removeWithValueTest() {
LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>();
cache.put(1, 1);
Assert.assertNotNull(cache.get(1));
Assert.assertFalse(cache.remove(1, 2));
Assert.assertNotNull(cache.get(1));
Assert.assertTrue(cache.remove(1, 1));
Assert.assertNull(cache.get(1));
}
@Test
public void putStringTest() {
LRUCache<String, String> cache = new LRUCache<String, String>();
cache.put("a", "a");
Assert.assertTrue(cache.containsKey("a"));
Assert.assertEquals(cache.get("a"), "a");
}
@Test
public void putIfAbsentTest() {
LRUCache<String, String> cache = new LRUCache<String, String>();
Assert.assertTrue(cache.putIfAbsent("a", "a"));
Assert.assertFalse(cache.putIfAbsent("a", "a"));
}
@Test
public void maxSizeTest() {
int maxCache = 5;
int max = 100;
LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(maxCache);
for (int n = 0; n < max; ++n) {
cache.put(n, n);
}
for (int n = 0; n < max - maxCache; ++n) {
Assert.assertNull(cache.get(n));
}
for (int n = max - maxCache; n < max; ++n) {
Assert.assertNotNull(cache.get(n));
Assert.assertEquals(cache.get(n), new Integer(n));
}
}
@Test
public void maxSizeLRUTest() {
int maxCache = 5;
int max = 100;
LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>(maxCache);
for (int n = 0; n < max; ++n) {
cache.put(n, n);
Assert.assertEquals(cache.get(0), new Integer(0));
}
for (int n = 1; n < max - maxCache; ++n) {
Assert.assertNull(cache.get(n));
}
for (int n = max - maxCache + 1; n < max; ++n) {
Assert.assertNotNull(cache.get(n));
Assert.assertEquals(cache.get(n), new Integer(n));
}
Assert.assertEquals(cache.get(0), new Integer(0));
}
@Test
public void getAndPutTest() {
int max = 100;
Integer prev = null;
LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>();
for (int n = 0; n < max; ++n) {
Assert.assertEquals(cache.getAndPut(1, n), prev);
prev = n;
}
}
@Test
public void putAllTest() {
int max = 100;
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
LRUCache<Integer, Integer> cache = new LRUCache<Integer, Integer>();
for (int n = 0; n < max; ++n) {
m.put(n, n);
}
cache.putAll(m);
for (int n = 0; n < max; ++n) {
Assert.assertEquals(cache.get(n), new Integer(n));
}
}
}
| 5,308 |
0 | Create_ds/aws-secretsmanager-caching-java/src/test/java/com/amazonaws/secretsmanager/caching | Create_ds/aws-secretsmanager-caching-java/src/test/java/com/amazonaws/secretsmanager/caching/cache/SecretCacheVersionTest.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.secretsmanager.caching.cache;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SecretCacheVersionTest {
@Test
public void cacheVersionEqualsTest() {
SecretCacheVersion i1 = new SecretCacheVersion("test", "version", null, null);
SecretCacheVersion i2 = new SecretCacheVersion("test", "version", null, null);
SecretCacheVersion i3 = new SecretCacheVersion("test3", "version", null, null);
SecretCacheVersion i4 = new SecretCacheVersion("test", "version4", null, null);
Assert.assertEquals(i1, i2);
Assert.assertNotEquals(i1, null);
Assert.assertNotEquals(i1, i3);
Assert.assertNotEquals(i1, i4);
Assert.assertFalse(i1.equals(null));
Assert.assertEquals(i1.hashCode(), i2.hashCode());
Assert.assertNotEquals(i1.hashCode(), i3.hashCode());
Assert.assertNotEquals(i1.hashCode(), i4.hashCode());
Assert.assertEquals(i1.toString(), "SecretCacheVersion: test version");
}
}
| 5,309 |
0 | Create_ds/aws-secretsmanager-caching-java/src/test/java/com/amazonaws/secretsmanager/caching | Create_ds/aws-secretsmanager-caching-java/src/test/java/com/amazonaws/secretsmanager/caching/internal/VersionInfoTest.java | package com.amazonaws.secretsmanager.caching.internal;
import java.util.regex.Pattern;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.amazonaws.secretsmanager.caching.cache.internal.VersionInfo;
public class VersionInfoTest {
@Test
public void versionInfoIsValid() {
String ua = VersionInfo.USER_AGENT;
Pattern p = Pattern.compile("AwsSecretCache/\\d+.\\d+.\\d+");
Assert.assertTrue(p.matcher(ua).matches(), "User agent " + ua + " is not valid");
}
}
| 5,310 |
0 | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching/SecretCacheHook.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.secretsmanager.caching;
/**
* Interface to hook the local in-memory cache. This interface will allow
* for clients to perform actions on the items being stored in the in-memory
* cache. One example would be encrypting/decrypting items stored in the
* in-memory cache.
*/
public interface SecretCacheHook{
/**
* Prepare the object for storing in the cache
*
* @param o The object being stored in the cache
* @return The object that should be stored in the cached
*/
Object put(final Object o);
/**
* Derive the object from the cached object.
*
* @param cachedObject The object stored in the cache
* @return The object that should be returned from the cache
*/
Object get(final Object cachedObject);
} | 5,311 |
0 | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching/SecretCacheConfiguration.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.secretsmanager.caching;
import java.util.concurrent.TimeUnit;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
/**
* Cache configuration options such as max cache size, ttl for cached items, etc.
*
*/
public class SecretCacheConfiguration {
/** The default cache size. */
public static final int DEFAULT_MAX_CACHE_SIZE = 1024;
/** The default TTL for an item stored in cache before access causing a refresh. */
public static final long DEFAULT_CACHE_ITEM_TTL = TimeUnit.HOURS.toMillis(1);
/** The default version stage to use when retrieving secret values. */
public static final String DEFAULT_VERSION_STAGE = "AWSCURRENT";
/** The client this cache instance will use for accessing AWS Secrets Manager. */
private SecretsManagerClient client = null;
/** Used to hook in-memory cache updates. */
private SecretCacheHook cacheHook = null;
/**
* The maximum number of cached secrets to maintain before evicting secrets that
* have not been accessed recently.
*/
private int maxCacheSize = DEFAULT_MAX_CACHE_SIZE;
/**
* The number of milliseconds that a cached item is considered valid before
* requiring a refresh of the secret state. Items that have exceeded this
* TTL will be refreshed synchronously when requesting the secret value. If
* the synchronous refresh failed, the stale secret will be returned.
*/
private long cacheItemTTL = DEFAULT_CACHE_ITEM_TTL;
/**
* The version stage that will be used when requesting the secret values for
* this cache.
*/
private String versionStage = DEFAULT_VERSION_STAGE;
/**
* Default constructor for the SecretCacheConfiguration object.
*
*/
public SecretCacheConfiguration() {
}
/**
* Returns the AWS Secrets Manager client that is used for requesting secret values.
*
* @return The AWS Secrets Manager client.
*/
public SecretsManagerClient getClient() {
return client;
}
/**
* Sets the AWS Secrets Manager client that should be used by the cache for requesting
* secrets.
*
* @param client
* The AWS Secrets Manager client.
*/
public void setClient(SecretsManagerClient client) {
this.client = client;
}
/**
* Sets the AWS Secrets Manager client that should be used by the cache for requesting
* secrets.
*
* @param client
* The AWS Secrets Manager client.
* @return The updated ClientConfiguration object with the new client setting.
*/
public SecretCacheConfiguration withClient(SecretsManagerClient client) {
this.setClient(client);
return this;
}
/**
* Returns the interface used to hook in-memory cache updates.
*
* @return The object used to hook in-memory cache updates.
*/
public SecretCacheHook getCacheHook() {
return cacheHook;
}
/**
* Sets the interface used to hook the in-memory cache.
*
* @param cacheHook
* The interface used to hook the in-memory cache.
*/
public void setCacheHook(SecretCacheHook cacheHook) {
this.cacheHook = cacheHook;
}
/**
* Sets the interface used to hook the in-memory cache.
*
* @param cacheHook
* The interface used to hook in-memory cache.
* @return The updated ClientConfiguration object with the new setting.
*/
public SecretCacheConfiguration withCacheHook(SecretCacheHook cacheHook) {
this.setCacheHook(cacheHook);
return this;
}
/**
* Returns the max cache size that should be used for creating the cache.
*
* @return The max cache size.
*/
public int getMaxCacheSize() {
return this.maxCacheSize;
}
/**
* Sets the max cache size.
*
* @param maxCacheSize
* The max cache size.
*/
public void setMaxCacheSize(int maxCacheSize) {
this.maxCacheSize = maxCacheSize;
}
/**
* Sets the max cache size.
*
* @param maxCacheSize
* The max cache size.
* @return The updated ClientConfiguration object with the new max setting.
*/
public SecretCacheConfiguration withMaxCacheSize(int maxCacheSize) {
this.setMaxCacheSize(maxCacheSize);
return this;
}
/**
* Returns the TTL for the cached items.
*
* @return The TTL in milliseconds before refreshing cached items.
*/
public long getCacheItemTTL() {
return this.cacheItemTTL;
}
/**
* Sets the TTL in milliseconds for the cached items. Once cached items exceed this
* TTL, the item will be refreshed using the AWS Secrets Manager client.
*
* @param cacheItemTTL
* The TTL for cached items before requiring a refresh.
*/
public void setCacheItemTTL(long cacheItemTTL) {
this.cacheItemTTL = cacheItemTTL;
}
/**
* Sets the TTL in milliseconds for the cached items. Once cached items exceed this
* TTL, the item will be refreshed using the AWS Secrets Manager client.
*
* @param cacheItemTTL
* The TTL for cached items before requiring a refresh.
* @return The updated ClientConfiguration object with the new TTL setting.
*/
public SecretCacheConfiguration withCacheItemTTL(long cacheItemTTL) {
this.setCacheItemTTL(cacheItemTTL);
return this;
}
/**
* Returns the version stage that is used for requesting secret values.
*
* @return The version stage used in requesting secret values.
*/
public String getVersionStage() {
return this.versionStage;
}
/**
* Sets the version stage that should be used for requesting secret values
* from AWS Secrets Manager
*
* @param versionStage
* The version stage used for requesting secret values.
*/
public void setVersionStage(String versionStage) {
this.versionStage = versionStage;
}
/**
* Sets the version stage that should be used for requesting secret values
* from AWS Secrets Manager
*
* @param versionStage
* The version stage used for requesting secret values.
* @return The updated ClientConfiguration object with the new version stage setting.
*/
public SecretCacheConfiguration withVersionStage(String versionStage) {
this.setVersionStage(versionStage);
return this;
}
}
| 5,312 |
0 | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching/SecretCache.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.secretsmanager.caching;
import java.nio.ByteBuffer;
import com.amazonaws.secretsmanager.caching.cache.LRUCache;
import com.amazonaws.secretsmanager.caching.cache.SecretCacheItem;
import com.amazonaws.secretsmanager.caching.cache.internal.VersionInfo;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClientBuilder;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
/**
* Provides the primary entry-point to the AWS Secrets Manager client cache SDK.
* Most people will want to use either
* {@link #getSecretString(String)} or
* {@link #getSecretBinary(String)} to retrieve a secret from the cache.
*
* <P>
* The core concepts (and classes) in this SDK are:
* <ul>
* <li>{@link SecretCache}
* <li>{@link SecretCacheConfiguration}
* </ul>
*
* <p>
* {@link SecretCache} provides an in-memory cache for secrets requested from
* AWS Secrets Manager.
*
*/
public class SecretCache implements AutoCloseable {
/** The cached secret items. */
private final LRUCache<String, SecretCacheItem> cache;
/** The cache configuration. */
private final SecretCacheConfiguration config;
/** The AWS Secrets Manager client to use when requesting secrets. */
private final SecretsManagerClient client;
/**
* Constructs a new secret cache using the standard AWS Secrets Manager client
* with default options.
*/
public SecretCache() {
this(SecretsManagerClient.builder());
}
/**
* Constructs a new secret cache using an AWS Secrets Manager client created
* using the
* provided builder.
*
* @param builder The builder to use for creating the AWS Secrets Manager
* client.
*/
public SecretCache(SecretsManagerClientBuilder builder) {
this(new SecretCacheConfiguration().withClient(builder
.overrideConfiguration(
builder.overrideConfiguration().toBuilder()
.putAdvancedOption(SdkAdvancedClientOption.USER_AGENT_SUFFIX, VersionInfo.USER_AGENT)
.build())
.build()));
}
/**
* Constructs a new secret cache using the provided AWS Secrets Manager client.
*
* @param client The AWS Secrets Manager client to use for requesting secret
* values.
*/
public SecretCache(SecretsManagerClient client) {
this(new SecretCacheConfiguration().withClient(client));
}
/**
* Constructs a new secret cache using the provided cache configuration.
*
* @param config The secret cache configuration.
*/
public SecretCache(SecretCacheConfiguration config) {
if (null == config) {
config = new SecretCacheConfiguration();
}
this.cache = new LRUCache<String, SecretCacheItem>(config.getMaxCacheSize());
this.config = config;
ClientOverrideConfiguration defaultOverride = ClientOverrideConfiguration.builder()
.putAdvancedOption(SdkAdvancedClientOption.USER_AGENT_SUFFIX, VersionInfo.USER_AGENT).build();
this.client = config.getClient() != null ? config.getClient()
: SecretsManagerClient.builder().overrideConfiguration(defaultOverride).build();
}
/**
* Method to retrieve the cached secret item.
*
* @param secretId The identifier for the secret being requested.
* @return The cached secret item
*/
private SecretCacheItem getCachedSecret(final String secretId) {
SecretCacheItem secret = this.cache.get(secretId);
if (null == secret) {
this.cache.putIfAbsent(secretId,
new SecretCacheItem(secretId, this.client, this.config));
secret = this.cache.get(secretId);
}
return secret;
}
/**
* Method to retrieve a string secret from AWS Secrets Manager.
*
* @param secretId The identifier for the secret being requested.
* @return The string secret
*/
public String getSecretString(final String secretId) {
SecretCacheItem secret = this.getCachedSecret(secretId);
GetSecretValueResponse gsv = secret.getSecretValue();
if (null == gsv) {
return null;
}
return gsv.secretString();
}
/**
* Method to retrieve a binary secret from AWS Secrets Manager.
*
* @param secretId The identifier for the secret being requested.
* @return The binary secret
*/
public ByteBuffer getSecretBinary(final String secretId) {
SecretCacheItem secret = this.getCachedSecret(secretId);
GetSecretValueResponse gsv = secret.getSecretValue();
if (null == gsv) {
return null;
}
return gsv.secretBinary().asByteBuffer();
}
/**
* Method to force the refresh of a cached secret state.
*
* @param secretId The identifier for the secret being refreshed.
* @return True if the refresh completed without error.
* @throws InterruptedException If the thread is interrupted while waiting for
* the refresh.
*/
public boolean refreshNow(final String secretId) throws InterruptedException {
SecretCacheItem secret = this.getCachedSecret(secretId);
return secret.refreshNow();
}
/**
* Method to close the cache.
*/
@Override
public void close() {
this.cache.clear();
}
}
| 5,313 |
0 | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching/cache/SecretCacheItem.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.secretsmanager.caching.cache;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import com.amazonaws.secretsmanager.caching.SecretCacheConfiguration;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.DescribeSecretRequest;
import software.amazon.awssdk.services.secretsmanager.model.DescribeSecretResponse;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
/**
* The cached secret item which contains information from the DescribeSecret
* request to AWS Secrets Manager along with any associated GetSecretValue
* results.
*
*/
public class SecretCacheItem extends SecretCacheObject<DescribeSecretResponse> {
/** The cached secret value versions for this cached secret. */
private LRUCache<String, SecretCacheVersion> versions = new LRUCache<String, SecretCacheVersion>(10);
/**
* The next scheduled refresh time for this item. Once the item is accessed
* after this time, the item will be synchronously refreshed.
*/
private long nextRefreshTime = 0;
/**
* Construct a new cached item for the secret.
*
* @param secretId
* The secret identifier. This identifier could be the full ARN
* or the friendly name for the secret.
* @param client
* The AWS Secrets Manager client to use for requesting the secret.
* @param config
* Cache configuration.
*/
public SecretCacheItem(final String secretId,
final SecretsManagerClient client,
final SecretCacheConfiguration config) {
super(secretId, client, config);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SecretCacheItem) {
return Objects.equals(this.secretId, ((SecretCacheItem)obj).secretId);
}
return false;
}
@Override
public int hashCode() {
return String.format("%s", this.secretId).hashCode();
}
@Override
public String toString() {
return String.format("SecretCacheItem: %s", this.secretId);
}
/**
* Determine if the secret object should be refreshed. This method
* extends the base class functionality to check if a refresh is
* needed based on the configured TTL for the item.
*
* @return True if the secret item should be refreshed.
*/
@Override
protected boolean isRefreshNeeded() {
if (super.isRefreshNeeded()) { return true; }
if (null != this.exception) { return false; }
if (System.currentTimeMillis() >= this.nextRefreshTime) {
return true;
}
return false;
}
/**
* Execute the logic to perform the actual refresh of the item.
*
* @return The result from AWS Secrets Manager for the refresh.
*/
@Override
protected DescribeSecretResponse executeRefresh() {
DescribeSecretResponse describeSecretResponse = client.describeSecret(DescribeSecretRequest.builder().secretId(this.secretId).build());
long ttl = this.config.getCacheItemTTL();
this.nextRefreshTime = System.currentTimeMillis() +
ThreadLocalRandom.current().nextLong(ttl / 2,ttl + 1) ;
return describeSecretResponse;
}
/**
* Return the secret version based on the current state of the secret.
*
* @param describeResponse
* The result of the Describe Secret request to AWS Secrets Manager.
* @return The cached secret version.
*/
private SecretCacheVersion getVersion(DescribeSecretResponse describeResponse) {
if (null == describeResponse) { return null; }
if (null == describeResponse.versionIdsToStages()) { return null; }
Optional<String> currentVersionId = describeResponse.versionIdsToStages().entrySet()
.stream()
.filter(Objects::nonNull)
.filter(x -> x.getValue() != null)
.filter(x -> x.getValue().contains(this.config.getVersionStage()))
.map(x -> x.getKey())
.findFirst();
if (currentVersionId.isPresent()) {
SecretCacheVersion version = versions.get(currentVersionId.get());
if (null == version) {
versions.putIfAbsent(currentVersionId.get(),
new SecretCacheVersion(this.secretId, currentVersionId.get(), this.client, this.config));
version = versions.get(currentVersionId.get());
}
return version;
}
return null;
}
/**
* Return the cached result from AWS Secrets Manager for GetSecretValue.
*
* @param describeResponse
* The result of the Describe Secret request to AWS Secrets Manager.
* @return The cached GetSecretValue result.
*/
@Override
protected GetSecretValueResponse getSecretValue(DescribeSecretResponse describeResponse) {
SecretCacheVersion version = getVersion(describeResponse);
if (null == version) { return null; }
return version.getSecretValue();
}
}
| 5,314 |
0 | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching/cache/SecretCacheVersion.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.secretsmanager.caching.cache;
import java.util.Objects;
import com.amazonaws.secretsmanager.caching.SecretCacheConfiguration;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
/**
* The cached secret version item which contains information from the
* GetSecretValue AWS Secrets Manager request.
*/
public class SecretCacheVersion extends SecretCacheObject<GetSecretValueResponse> {
/** The version identifier to use when requesting the secret value. */
private final String versionId;
/** The calculated hash for this item based on the secret and version. */
private final int hash;
/**
* Construct a new cached version for the secret.
*
* @param secretId
* The secret identifier. This identifier could be the full ARN
* or the friendly name for the secret.
* @param versionId
* The version identifier that should be used when requesting the
* secret value from AWS Secrets Manager.
* @param client
* The AWS Secrets Manager client to use for requesting the secret.
* @param config
* The secret cache configuration.
*/
public SecretCacheVersion(final String secretId,
final String versionId,
final SecretsManagerClient client,
final SecretCacheConfiguration config) {
super(secretId, client, config);
this.versionId = versionId;
hash = String.format("%s %s", secretId, versionId).hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SecretCacheVersion) {
return Objects.equals(this.secretId,((SecretCacheVersion)obj).secretId) &&
Objects.equals(this.versionId, ((SecretCacheVersion)obj).versionId);
}
return false;
}
@Override
public int hashCode() {
return hash;
}
@Override
public String toString() {
return String.format("SecretCacheVersion: %s %s", secretId, versionId);
}
/**
* Execute the logic to perform the actual refresh of the item.
*
* @return The result from AWS Secrets Manager for the refresh.
*/
@Override
protected GetSecretValueResponse executeRefresh() {
return client.getSecretValue(
GetSecretValueRequest.builder().secretId(this.secretId).versionId(this.versionId).build());
}
/**
* Return the cached result from AWS Secrets Manager for GetSecretValue.
*
* @param gsvResult
* The result of the Get Secret Value request to AWS Secrets Manager.
* @return The cached GetSecretValue result.
*/
@Override
protected GetSecretValueResponse getSecretValue(GetSecretValueResponse gsvResult) {
return gsvResult;
}
}
| 5,315 |
0 | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching/cache/LRUCache.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.secretsmanager.caching.cache;
import java.util.Map;
import java.util.LinkedHashMap;
/**
* An LRU cache based on the Java LinkedHashMap.
*
*/
public class LRUCache<K, V> {
private static class LRULinkedHashMap<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 16L;
private final int maxSize;
LRULinkedHashMap(int maxSize) {
super(16, .75f, true);
this.maxSize = maxSize;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return (this.size() > this.maxSize);
}
}
/** The hash map used to hold the cached items. */
private final LRULinkedHashMap<K, V> map;
/** The default max size for the cache */
private static final int DEFAULT_MAX_SIZE = 1024;
/**
* Construct a new cache with default settings.
*/
public LRUCache() {
this(DEFAULT_MAX_SIZE);
}
/**
* Construct a new cache based on the given max size.
*
* @param maxSize
* The maximum number of items to store in the cache.
*/
public LRUCache(int maxSize) {
this.map = new LRULinkedHashMap<K, V>(maxSize);
}
/**
* Return the value mapped to the given key.
*
* @param key
* The key used to return the mapped value.
* @return The value mapped to the given key.
*/
public V get(final K key) {
synchronized (map) {
return map.get(key);
}
}
/**
* Determine if the cache contains the given key.
*
* @param key
* The key used to determine it there is a mapped value.
* @return True if a value is mapped to the given key.
*/
public boolean containsKey(final K key) {
synchronized (map) {
return map.containsKey(key);
}
}
/**
* Map a given key to the given value.
*
* @param key
* The key to map to the given value.
* @param value
* The value to map to the given key.
*/
public void put(final K key, final V value) {
synchronized (map) {
map.put(key, value);
}
}
/**
* Return the previously mapped value and map a new value.
*
* @param key
* The key to map to the given value.
* @param value
* The value to map to the given key.
* @return The previously mapped value to the given key.
*/
public V getAndPut(final K key, final V value) {
synchronized (map) {
return map.put(key, value);
}
}
/**
* Copies all of the mappings from the provided map to this cache.
* These mappings will replace any keys currently in the cache.
*
* @param map
* The mappings to copy.
*/
public void putAll(final Map<? extends K, ? extends V> map) {
synchronized (map) {
this.map.putAll(map);
}
}
/**
* Map a given key to the given value if not already mapped.
*
* @param key
* The key to map to the given value.
* @param value
* The value to map to the given key.
* @return True if the mapping has been made.
*/
public boolean putIfAbsent(final K key, final V value) {
synchronized (map) {
return map.putIfAbsent(key, value) == null;
}
}
/**
* Remove a given key from the cache.
*
* @param key
* The key to remove.
* @return True if the key has been removed.
*/
public boolean remove(final K key) {
synchronized (map) {
return map.remove(key) != null;
}
}
/**
* Remove a given key and value from the cache.
*
* @param key
* The key to remove.
* @param oldValue
* The value to remove.
* @return True if the key and oldValue has been removed.
*/
public boolean remove(final K key, final V oldValue) {
synchronized (map) {
return map.remove(key, oldValue);
}
}
/**
* Return the previously mapped value and remove the key.
*
* @param key
* The key to remove.
* @return The previously mapped value to the given key.
*/
public V getAndRemove(final K key) {
synchronized (map) {
return map.remove(key);
}
}
/**
* Remove all of the cached items.
*/
public void removeAll() {
synchronized (map) {
map.clear();
}
}
/**
* Clear the cache.
*/
public void clear() {
synchronized (map) {
map.clear();
}
}
}
| 5,316 |
0 | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching/cache/SecretCacheObject.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.secretsmanager.caching.cache;
import java.util.concurrent.ThreadLocalRandom;
import com.amazonaws.secretsmanager.caching.SecretCacheConfiguration;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
/**
* Basic secret caching object.
*/
public abstract class SecretCacheObject<T> {
/** The number of milliseconds to wait after an exception. */
private static final long EXCEPTION_BACKOFF = 1000;
/** The growth factor of the backoff duration. */
private static final long EXCEPTION_BACKOFF_GROWTH_FACTOR = 2;
/**
* The maximum number of milliseconds to wait before retrying a failed
* request.
*/
private static final long BACKOFF_PLATEAU = EXCEPTION_BACKOFF * 128;
/**
* When forcing a refresh using the refreshNow method, a random sleep
* will be performed using this value. This helps prevent code from
* executing a refreshNow in a continuous loop without waiting.
*/
private static final long FORCE_REFRESH_JITTER_SLEEP = 5000;
/** The secret identifier for this cached object. */
protected final String secretId;
/** A private object to synchronize access to certain methods. */
protected final Object lock = new Object();
/** The AWS Secrets Manager client to use for requesting secrets. */
protected final SecretsManagerClient client;
/** The Secret Cache Configuration. */
protected final SecretCacheConfiguration config;
/** A flag to indicate a refresh is needed. */
private boolean refreshNeeded = true;
/** The result of the last AWS Secrets Manager request for this item. */
private Object data = null;
/**
* If the last request to AWS Secrets Manager resulted in an exception,
* that exception will be thrown back to the caller when requesting
* secret data.
*/
protected RuntimeException exception = null;
/**
* The number of exceptions encountered since the last successfully
* AWS Secrets Manager request. This is used to calculate an exponential
* backoff.
*/
private long exceptionBackoffPower = 0;
/**
* The time to wait before retrying a failed AWS Secrets Manager request.
*/
private long nextRetryTime = 0;
/**
* Construct a new cached item for the secret.
*
* @param secretId
* The secret identifier. This identifier could be the full ARN
* or the friendly name for the secret.
* @param client
* The AWS Secrets Manager client to use for requesting the secret.
* @param config
* The secret cache configuration.
*/
public SecretCacheObject(final String secretId,
final SecretsManagerClient client,
final SecretCacheConfiguration config) {
this.secretId = secretId;
this.client = client;
this.config = config;
}
/**
* Execute the actual refresh of the cached secret state.
*
* @return The result of the refresh
*/
protected abstract T executeRefresh();
/**
* Execute the actual refresh of the cached secret state.
*
* @param result
* The AWS Secrets Manager result for the secret state.
* @return The cached GetSecretValue result based on the current
* cached state.
*/
protected abstract GetSecretValueResponse getSecretValue(T result);
public abstract boolean equals(Object obj);
public abstract int hashCode();
public abstract String toString();
/**
* Return the typed result object
*
* @return the result object
*/
@SuppressWarnings("unchecked")
private T getResult() {
if (null != this.config.getCacheHook()) {
return (T)this.config.getCacheHook().get(this.data);
}
return (T)this.data;
}
/**
* Store the result data.
*/
private void setResult(T result) {
if (null != this.config.getCacheHook()) {
this.data = this.config.getCacheHook().put(result);
} else {
this.data = result;
}
}
/**
* Determine if the secret object should be refreshed.
*
* @return True if the secret item should be refreshed.
*/
protected boolean isRefreshNeeded() {
if (this.refreshNeeded) { return true; }
if (null != this.exception) {
// If we encountered an exception on the last attempt
// we do not want to keep retrying without a pause between
// the refresh attempts.
//
// If we have exceeded our backoff time we will refresh
// the secret now.
if (System.currentTimeMillis() >= this.nextRetryTime) {
return true;
}
// Don't keep trying to refresh a secret that previously threw
// an exception.
return false;
}
return false;
}
/**
* Refresh the cached secret state only when needed.
*/
private void refresh() {
if (!this.isRefreshNeeded()) { return; }
this.refreshNeeded = false;
try {
this.setResult(this.executeRefresh());
this.exception = null;
this.exceptionBackoffPower = 0;
} catch (RuntimeException ex) {
this.exception = ex;
// Determine the amount of growth in exception backoff time based on the growth
// factor and default backoff duration.
Long growth = 1L;
if (this.exceptionBackoffPower > 0) {
growth = (long)Math.pow(EXCEPTION_BACKOFF_GROWTH_FACTOR, this.exceptionBackoffPower);
}
growth *= EXCEPTION_BACKOFF;
// Add in EXCEPTION_BACKOFF time to make sure the random jitter will not reduce
// the wait time too low.
Long retryWait = Math.min(EXCEPTION_BACKOFF + growth, BACKOFF_PLATEAU);
if ( retryWait < BACKOFF_PLATEAU ) {
// Only increase the backoff power if we haven't hit the backoff plateau yet.
this.exceptionBackoffPower += 1;
}
// Use random jitter with the wait time
retryWait = ThreadLocalRandom.current().nextLong(retryWait / 2, retryWait + 1);
this.nextRetryTime = System.currentTimeMillis() + retryWait;
}
}
/**
* Method to force the refresh of a cached secret state.
*
* @return True if the refresh completed without error.
* @throws InterruptedException
* If the thread is interrupted while waiting for the refresh.
*/
public boolean refreshNow() throws InterruptedException {
this.refreshNeeded = true;
// When forcing a refresh, always sleep with a random jitter
// to prevent coding errors that could be calling refreshNow
// in a loop.
long sleep = ThreadLocalRandom.current()
.nextLong(
FORCE_REFRESH_JITTER_SLEEP / 2,
FORCE_REFRESH_JITTER_SLEEP + 1);
// Make sure we are not waiting for the next refresh after an
// exception. If we are, sleep based on the retry delay of
// the refresh to prevent a hard loop in attempting to refresh a
// secret that continues to throw an exception such as AccessDenied.
if (null != this.exception) {
long wait = this.nextRetryTime - System.currentTimeMillis();
sleep = Math.max(wait, sleep);
}
Thread.sleep(sleep);
// Perform the requested refresh
synchronized (lock) {
refresh();
return (null == this.exception);
}
}
/**
* Return the cached result from AWS Secrets Manager for GetSecretValue.
*
* @return The cached GetSecretValue result.
*/
public GetSecretValueResponse getSecretValue() {
synchronized (lock) {
refresh();
if (null == this.data) {
if (null != this.exception) { throw this.exception; }
}
return this.getSecretValue(this.getResult());
}
}
}
| 5,317 |
0 | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching/cache | Create_ds/aws-secretsmanager-caching-java/src/main/java/com/amazonaws/secretsmanager/caching/cache/internal/VersionInfo.java | /*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.secretsmanager.caching.cache.internal;
/**
* This class specifies the versioning system for the AWS SecretsManager caching
* client.
*/
public class VersionInfo {
public static final String VERSION_NUM = "2";
// incremented for design changes that break backward compatibility.
public static final String MAJOR_REVISION_NUM = VERSION_NUM;
// incremented for minor changes to the implementation
public static final String MINOR_REVISION_NUM = "0";
// incremented for releases containing an immediate bug fix.
public static final String BUGFIX_REVISION_NUM = "0";
public static final String RELEASE_VERSION = MAJOR_REVISION_NUM + "." + MINOR_REVISION_NUM
+ "." + BUGFIX_REVISION_NUM;
public static final String USER_AGENT = "AwsSecretCache/" + RELEASE_VERSION;
private VersionInfo() {
}
} | 5,318 |
0 | Create_ds/amazon-sagemaker-examples/reinforcement_learning/rl_hvac_coach_energyplus/src/eplus/envs/bcvtb/lib/xml | Create_ds/amazon-sagemaker-examples/reinforcement_learning/rl_hvac_coach_energyplus/src/eplus/envs/bcvtb/lib/xml/src/DTDValidator.java | import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.ErrorHandler;
/** Class to validate xml files.
*
* @author Michael Wetter
* @since BCVTB 0.3
*/
public class DTDValidator {
/** The xml file name */
static String fil;
/** Main method.
*
*@param args Argument list, args[0] must be the xml file name
* that will be parsed, arg[1] must be the path to the dtd file.
*/
public static void main(String[] args) {
fil = args[0];
// Document builder factory
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
fac.setValidating(true);
try {
// Document builder and error handler
DocumentBuilder b = fac.newDocumentBuilder();
b.setErrorHandler(new MyErrorHandler());
// Parse document
// Document d = b.parse(args[0]);
Document d = b.parse(new java.io.FileInputStream(fil),
args[1] + File.separator);
}
catch(SAXException e) {
System.err.println(e.getMessage());
}
catch(IOException e) {
System.err.println(e.getMessage());
}
catch (ParserConfigurationException e) {
System.err.println(e.getMessage());
}
}
/** Inner class for error handling
*/
private static class MyErrorHandler implements ErrorHandler {
/** Writes warning messages to <code>System.err</code>
*
*@param e The exception
*@exception SAXException If a SAXException occurs
*/
public void warning(SAXParseException e) throws SAXException {
printInfo("Warning: ", e);
System.exit(1);
}
/** Writes error messages to <code>System.err</code>
*
*@param e The exception
*@exception SAXException If a SAXException occurs
*/
public void error(SAXParseException e) throws SAXException {
printInfo("Error: ", e);
System.exit(1);
}
/** Writes error messages to <code>System.err</code>
*
*@param e The exception
*@exception SAXException If a SAXException occurs
*/
public void fatalError(SAXParseException e) throws SAXException {
error(e);
}
/** Prints the error message to <code>System.err</code>
*@param s The string that will be added in front of the exception
* message
*@param e The exception
*/
private void printInfo(String s, SAXParseException e) {
System.err.println(s +
fil + ":"
+ e.getLineNumber() + ": "
+ e.getMessage());
}
}
}
/********************************************************************
Copyright Notice
----------------
Building Controls Virtual Test Bed (BCVTB) Copyright (c) 2008-2009, The
Regents of the University of California, through Lawrence Berkeley
National Laboratory (subject to receipt of any required approvals from
the U.S. Dept. of Energy). All rights reserved.
If you have questions about your rights to use or distribute this
software, please contact Berkeley Lab's Technology Transfer Department
at TTD@lbl.gov
NOTICE. This software was developed under partial funding from the U.S.
Department of Energy. As such, the U.S. Government has been granted for
itself and others acting on its behalf a paid-up, nonexclusive,
irrevocable, worldwide license in the Software to reproduce, prepare
derivative works, and perform publicly and display publicly. Beginning
five (5) years after the date permission to assert copyright is obtained
from the U.S. Department of Energy, and subject to any subsequent five
(5) year renewals, the U.S. Government is granted for itself and others
acting on its behalf a paid-up, nonexclusive, irrevocable, worldwide
license in the Software to reproduce, prepare derivative works,
distribute copies to the public, perform publicly and display publicly,
and to permit others to do so.
Modified BSD License agreement
------------------------------
Building Controls Virtual Test Bed (BCVTB) Copyright (c) 2008-2009, The
Regents of the University of California, through Lawrence Berkeley
National Laboratory (subject to receipt of any required approvals from
the U.S. Dept. of Energy). All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. Neither the name of the University of California, Lawrence
Berkeley National Laboratory, U.S. Dept. of Energy nor the names
of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You are under no obligation whatsoever to provide any bug fixes,
patches, or upgrades to the features, functionality or performance of
the source code ("Enhancements") to anyone; however, if you choose to
make your Enhancements available either publicly, or directly to
Lawrence Berkeley National Laboratory, without imposing a separate
written license agreement for such Enhancements, then you hereby grant
the following license: a non-exclusive, royalty-free perpetual license
to install, use, modify, prepare derivative works, incorporate into
other computer software, distribute, and sublicense such enhancements or
derivative works thereof, in binary and source code form.
********************************************************************
*/
| 5,319 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/handler/InferenceHandlerInf.java | package ro.edu.aws.sgm.inference.pmml.randomforest.handler;
import java.util.List;
import org.springframework.stereotype.Component;
import ro.edu.aws.sgm.inference.pmml.randomforest.pojo.Features;
public interface InferenceHandlerInf {
public String predict(List <Features> data, Object model);
}
| 5,320 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/handler/JPMMLInferenceHandlerImpl.java | package ro.edu.aws.sgm.inference.pmml.randomforest.handler;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.xml.bind.JAXBException;
import javax.xml.transform.sax.SAXSource;
import org.dmg.pmml.FieldName;
import org.dmg.pmml.MiningModel;
import org.dmg.pmml.PMML;
import org.jpmml.evaluator.FieldValue;
import org.jpmml.evaluator.MiningModelEvaluator;
import org.jpmml.evaluator.ModelEvaluator;
import org.jpmml.evaluator.ProbabilityClassificationMap;
import org.jpmml.model.ImportFilter;
import org.jpmml.model.JAXBUtil;
import org.springframework.stereotype.Service;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import ro.edu.aws.sgm.inference.pmml.randomforest.pojo.Features;
@Service("jpmmlInferenceImpl")
public class JPMMLInferenceHandlerImpl implements InferenceHandlerInf {
public String predict(List <Features> data, Object model){
File modelFile = (File)model;
PMML pmmlFile = null;
try {
pmmlFile = createPMMLfromFile(modelFile);
} catch (SAXException | IOException | JAXBException e) {
e.printStackTrace();
}
List <Features> featuresList = data;
StringBuilder sb = new StringBuilder();
for( Features feature: featuresList){
List <String> featureString = feature.getFeatures();
String features = String.join(",", featureString).concat("\n");
sb.append(features);
}
ModelEvaluator<MiningModel> modelEvaluator = new MiningModelEvaluator(pmmlFile);
return predict(sb.toString().lines(), modelEvaluator);
}
private static String predict(Stream<String> inputData,
ModelEvaluator<MiningModel> modelEvaluator) {
String returns = inputData.map(dataLine -> {
System.out.println("Predicting for input data: " + dataLine);
Map<FieldName, FieldValue> arguments = readArgumentsFromLine(dataLine, modelEvaluator);
modelEvaluator.verify();
Map<FieldName, ?> results = modelEvaluator.evaluate(arguments);
FieldName targetName = modelEvaluator.getTargetField();
Object targetValue = results.get(targetName);
ProbabilityClassificationMap nodeMap = (ProbabilityClassificationMap) targetValue;
return ( nodeMap != null && nodeMap.getResult() != null) ? nodeMap.getResult().toString() : "NA for input->"+dataLine;
}).collect(Collectors.joining(System.lineSeparator()));
System.out.println("Prediction results: " + returns);
return returns;
}
private static Map<FieldName, FieldValue> readArgumentsFromLine(String line,
ModelEvaluator<MiningModel> modelEvaluator) {
Map<FieldName, FieldValue> arguments = new LinkedHashMap<FieldName, FieldValue>();
String[] lineArgs = line.split(",");
if (lineArgs.length != 5)
return arguments;
FieldValue sepalLength = modelEvaluator.prepare(new FieldName("Sepal.Length"),
lineArgs[0].isEmpty() ? 0 : lineArgs[0]);
FieldValue sepalWidth = modelEvaluator.prepare(new FieldName("Sepal.Width"),
lineArgs[1].isEmpty() ? 0 : lineArgs[1]);
FieldValue petalLength = modelEvaluator.prepare(new FieldName("Petal.Length"),
lineArgs[2].isEmpty() ? 0 : lineArgs[2]);
FieldValue petalWidth = modelEvaluator.prepare(new FieldName("Petal.Width"),
lineArgs[3].isEmpty() ? 0 : lineArgs[3]);
arguments.put(new FieldName("Sepal.Length"), sepalLength);
arguments.put(new FieldName("Sepal.Width"), sepalWidth);
arguments.put(new FieldName("Petal.Length"), petalLength);
arguments.put(new FieldName("Petal.Width"), petalWidth);
return arguments;
}
private static PMML createPMMLfromFile(File pmmlFile)
throws SAXException, IOException, JAXBException{
// File pmmlFile = new File(SGMController.class.getResource(fileName).getPath());
String pmmlString = new Scanner(pmmlFile).useDelimiter("\\Z").next();
InputStream is = new ByteArrayInputStream(pmmlString.getBytes());
InputSource source = new InputSource(is);
SAXSource transformedSource = ImportFilter.apply(source);
return JAXBUtil.unmarshalPMML(transformedSource);
}
}
| 5,321 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/app/SGMLauncher.java | package ro.edu.aws.sgm.inference.pmml.randomforest.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(basePackages = "ro.edu.aws.sgm.inference.pmml.randomforest")
public class SGMLauncher {
public static void main(String[] args) {
serve();
}
public static void serve() {
SpringApplication.run(SGMLauncher.class);
}
}
| 5,322 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/entrypoint/SGMController.java | package ro.edu.aws.sgm.inference.pmml.randomforest.entrypoint;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import ro.edu.aws.sgm.inference.pmml.randomforest.exception.InsufficientMemoryException;
import ro.edu.aws.sgm.inference.pmml.randomforest.exception.ModelAlreadyPresentException;
import ro.edu.aws.sgm.inference.pmml.randomforest.exception.ModelNotFoundException;
import ro.edu.aws.sgm.inference.pmml.randomforest.handler.InferenceHandlerInf;
import ro.edu.aws.sgm.inference.pmml.randomforest.pojo.Features;
import ro.edu.aws.sgm.inference.pmml.randomforest.pojo.InputData;
import ro.edu.aws.sgm.inference.pmml.randomforest.pojo.MemoryStats;
import ro.edu.aws.sgm.inference.pmml.randomforest.pojo.Model;
@RestController
public class SGMController {
private ConcurrentHashMap<String, File> concurrentHashMap;
@Autowired
@Qualifier("jpmmlInferenceImpl")
private InferenceHandlerInf jpmmlInferenceHandlerImpl;
@Value("${java.memory.threshold.percentage}")
private String memoryThresholdValue;
@PostConstruct
public void init() {
concurrentHashMap = new ConcurrentHashMap<String, File>();
}
@RequestMapping(value = "/ping", method = RequestMethod.GET)
public String ping() {
System.out.println("[Ping] Pinging the container.");
return "";
}
@PostMapping(value = "/models/{model_name}/invoke")
public ResponseEntity<String> invoke(HttpServletRequest request,
@RequestHeader(value = "X-Amzn-SageMaker-Target-Model") String targetModel,
@PathVariable @NonNull String model_name, @RequestBody @NonNull InputData inputData) throws IOException {
System.out.println("[Invoke Model] Target model header value: "+ targetModel);
String predictions = null;
if(isModelLoaded(model_name)){
System.out.println("[Invoke Model] Found model " +model_name+" in memory.");
List <Features> data = inputData.getFeatureList();
predictions = jpmmlInferenceHandlerImpl.predict(data, concurrentHashMap.get(model_name));
}
return new ResponseEntity <String>(predictions, HttpStatus.OK);
}
@PostMapping(value = "/models")
public ResponseEntity <?>loadModel(@RequestBody @NonNull Model model) throws Exception{
String model_name = model.getModel_name();
String url = model.getUrl();
System.out.println("[Load Model] model_name: "+ model_name);
System.out.println("[Load Model] url: "+ url);
// Throw exception when enough memory is not available to load the model
if(!isMemoryAvailable()){
throw new InsufficientMemoryException("Insufficient memory. Cannot load model: " + model_name);
}
File modelFile = Paths.get(url).toFile();
File retVal = concurrentHashMap.putIfAbsent(model_name, modelFile);
if(null!= retVal){
System.out.println("Error!! Model already loaded in memory");
throw new ModelAlreadyPresentException("Model Name: " + model_name + "already loaded in memory.");
}
System.out.println("[Load Model] model_name: "+ model_name + " loaded in memory.");
return new ResponseEntity<>("Model: "+ model_name + " loaded in memory", HttpStatus.OK);
}
@GetMapping("/models")
public ResponseEntity<List<Model>> listModels(HttpServletRequest request) throws IOException{
List <Model> modelList = new ArrayList<Model>();
for (String key: concurrentHashMap.keySet()){
Model model = new Model(key, "opt/ml/models/" +key+"/model");
modelList.add(model);
}
System.out.println("[List Models] Returning a list of "+modelList.size()+" models.");
return ResponseEntity.ok(modelList);
}
@GetMapping("/models/{model_name}")
public ResponseEntity<Model> getModel(@PathVariable String model_name){
Model model = null;
if(isModelLoaded(model_name)){
model = new Model(model_name, "opt/ml/models/" +model_name+"/model");
System.out.println("[Get Model] Returning model name" +model.getModel_name()+" and Model URL " +model.getUrl());
}
return ResponseEntity.ok(model);
}
@DeleteMapping("/models/{model_name}")
public ResponseEntity <?> deleteModel(@PathVariable @NonNull String model_name){
if(isModelLoaded(model_name)){
concurrentHashMap.remove(model_name);
System.out.println("[Delete Model] Deleting model: "+model_name+" from the memory");
}
return new ResponseEntity<String>("Model: " + model_name + " removed from the memory.", HttpStatus.OK);
}
@GetMapping("memory-status")
public MemoryStats getMemoryStatistics() {
MemoryStats stats = new MemoryStats();
stats.setHeapSize(Runtime.getRuntime().totalMemory());
stats.setHeapMaxSize(Runtime.getRuntime().maxMemory());
stats.setHeapFreeSize(Runtime.getRuntime().freeMemory());
return stats;
}
private boolean isModelLoaded(String model_name){
if(!concurrentHashMap.containsKey(model_name)){
throw new ModelNotFoundException("Model name: "+ model_name + "not loaded in memory");
}
return true;
}
private boolean isMemoryAvailable(){
long freeMemory = Runtime.getRuntime().freeMemory();
long maxMemory = Runtime.getRuntime().maxMemory();
System.out.println("Current runtime free memory: "+ freeMemory);
System.out.println("Max memory available: "+maxMemory);
double availableMemory = ((double)freeMemory/maxMemory) * 100;
System.out.println("Current heap memory available: "+ availableMemory+"%");
System.out.println("Memory threshold value: "+memoryThresholdValue+"%");
if( availableMemory >= Integer.parseInt(memoryThresholdValue))
return false;
return true;
}
}
| 5,323 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/exception/InsufficientMemoryException.java | package ro.edu.aws.sgm.inference.pmml.randomforest.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.INSUFFICIENT_STORAGE)
public class InsufficientMemoryException extends RuntimeException {
public InsufficientMemoryException(String exception){
super(exception);
}
}
| 5,324 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/exception/ModelAlreadyPresentException.java |
package ro.edu.aws.sgm.inference.pmml.randomforest.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.CONFLICT)
public class ModelAlreadyPresentException extends RuntimeException{
public ModelAlreadyPresentException(String exception){
super(exception);
}
} | 5,325 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/exception/ModelNotFoundException.java | package ro.edu.aws.sgm.inference.pmml.randomforest.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ModelNotFoundException extends RuntimeException{
public ModelNotFoundException(String exception){
super(exception);
}
}
| 5,326 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/exception/CustomizedResponseEntityExceptionHandler.java | package ro.edu.aws.sgm.inference.pmml.randomforest.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
public final ResponseEntity<ErrorDetails> handleModelNotFoundException(ModelNotFoundException ex, WebRequest request){
ErrorDetails errorDetails = new ErrorDetails(ex.getMessage(), request.getDescription(false));
return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.NOT_FOUND);
}
public final ResponseEntity<ErrorDetails> handleModelAlreadyPresentFoundException(ModelAlreadyPresentException ex, WebRequest request){
ErrorDetails errorDetails = new ErrorDetails(ex.getMessage(), request.getDescription(false));
return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.NOT_FOUND);
}
public final ResponseEntity<ErrorDetails> handleInsufficientMemoryException(InsufficientMemoryException ex, WebRequest request){
ErrorDetails errorDetails = new ErrorDetails(ex.getMessage(), request.getDescription(false));
return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.NOT_FOUND);
}
}
| 5,327 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/exception/ErrorDetails.java | package ro.edu.aws.sgm.inference.pmml.randomforest.exception;
import java.time.LocalDateTime;
import com.fasterxml.jackson.annotation.JsonFormat;
public class ErrorDetails {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private LocalDateTime timestamp;
private String message;
private String details;
private ErrorDetails(){
timestamp = LocalDateTime.now();
}
/**
* @param message
* @param details
*/
public ErrorDetails(String message, String details) {
this();
this.message = message;
this.details = details;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
| 5,328 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/pojo/InputData.java | package ro.edu.aws.sgm.inference.pmml.randomforest.pojo;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class InputData {
@JsonProperty("data")
private List<Features> featureList;
@JsonCreator
public InputData(List<Features> featureList) {
super();
this.featureList = featureList;
}
public List<Features> getFeatureList() {
return featureList;
}
public void setFeatureList(List<Features> featureList) {
this.featureList = featureList;
}
}
| 5,329 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/pojo/Features.java | package ro.edu.aws.sgm.inference.pmml.randomforest.pojo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class Features {
@JsonProperty("features")
private List<String> features;
@JsonCreator
public Features(List<String> features) {
super();
this.features = features;
}
public List<String> getFeatures() {
return features;
}
public void setFeatures(List<String> features) {
this.features = features;
}
}
| 5,330 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/pojo/MemoryStats.java | package ro.edu.aws.sgm.inference.pmml.randomforest.pojo;
public class MemoryStats{
private long heapSize;
private long heapMaxSize;
private long heapFreeSize;
public long getHeapSize() {
return heapSize;
}
public void setHeapSize(long heapSize) {
this.heapSize = heapSize;
}
public long getHeapMaxSize() {
return heapMaxSize;
}
public void setHeapMaxSize(long heapMaxSize) {
this.heapMaxSize = heapMaxSize;
}
public long getHeapFreeSize() {
return heapFreeSize;
}
public void setHeapFreeSize(long heapFreeSize) {
this.heapFreeSize = heapFreeSize;
}
} | 5,331 |
0 | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest | Create_ds/amazon-sagemaker-examples/inference/structured/realtime/byoc/byoc-mme-java/src/main/java/ro/edu/aws/sgm/inference/pmml/randomforest/pojo/Model.java | package ro.edu.aws.sgm.inference.pmml.randomforest.pojo;
public class Model{
private String model_name;
private String url;
public Model(String model_name, String url) {
this.model_name = model_name;
this.url = url;
}
public String getModel_name() {
return model_name;
}
public void setModel_name(String model_name) {
this.model_name = model_name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
} | 5,332 |
0 | Create_ds/aws-health-tools/high-availability-endpoint/java/src/main/java/aws/health/high/availability/endpoint | Create_ds/aws-health-tools/high-availability-endpoint/java/src/main/java/aws/health/high/availability/endpoint/demo/RegionLookup.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package aws.health.high.availability.endpoint.demo;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.CNAMERecord;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;
import org.xbill.DNS.Record;
public final class RegionLookup {
public static final String GLOBAL_HEALTH_ENDPOINT = "global.health.amazonaws.com";
public static String getCurrentActiveRegion() throws RegionLookupException {
// Init lookup object
Lookup dnsLookup = null;
try {
dnsLookup = new Lookup(GLOBAL_HEALTH_ENDPOINT, Type.CNAME);
} catch (TextParseException e) {
throw new RegionLookupException("Failed to parse DNS name [" + GLOBAL_HEALTH_ENDPOINT + "]", e);
}
dnsLookup.setCache(null); // Never use caching, always do a full a DNS lookup
// Do the DNS lookup
Record[] records = dnsLookup.run();
if (records == null || records.length == 0) {
throw new RegionLookupException("Failed to resolve the DNS name [" + GLOBAL_HEALTH_ENDPOINT + "]");
}
CNAMERecord cnameRecord = (CNAMERecord)records[0];
String regionalDNSName = cnameRecord.getTarget().toString(true);
// The CNAME will look something like: "health.us-east-1.amazonaws.com"
// Extract the region name (e.g. us-east-1) to use for SigV4 signing
String[] cnameParts = regionalDNSName.split("\\.");
String regionName = cnameParts[1].toLowerCase(); // The region is always the second item in the array
return regionName;
}
}
| 5,333 |
0 | Create_ds/aws-health-tools/high-availability-endpoint/java/src/main/java/aws/health/high/availability/endpoint | Create_ds/aws-health-tools/high-availability-endpoint/java/src/main/java/aws/health/high/availability/endpoint/demo/RegionLookupException.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package aws.health.high.availability.endpoint.demo;
public final class RegionLookupException extends Exception {
public RegionLookupException(String message) {
super(message);
}
public RegionLookupException(String message, Throwable cause) {
super(message, cause);
}
} | 5,334 |
0 | Create_ds/aws-health-tools/high-availability-endpoint/java/src/main/java/aws/health/high/availability/endpoint | Create_ds/aws-health-tools/high-availability-endpoint/java/src/main/java/aws/health/high/availability/endpoint/demo/HighAvailabilityV2HealthClient.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package aws.health.high.availability.endpoint.demo;
import software.amazon.awssdk.services.health.HealthClient;
import software.amazon.awssdk.services.health.HealthClientBuilder;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is an example of using the Health API endpoint DNS lookup strategy
* with the AWS Java SDK V2 Health client.
*/
public final class HighAvailabilityV2HealthClient {
private static String activeRegion;
private static HealthClient healthClient;
private HighAvailabilityV2HealthClient() {}
public static synchronized HealthClient getHealthClient() throws RegionLookupException, ActiveRegionHasChangedException {
String currentActiveRegion = RegionLookup.getCurrentActiveRegion();
if (activeRegion == null) {
// This is the first time we've done the DNS lookup
activeRegion = currentActiveRegion;
} else {
// If the active region has changed since the last time we did the
// DNS lookup we throw an exception to let the calling code know
// abount the change
if (!currentActiveRegion.equals(activeRegion)) {
String oldActiveRegion = activeRegion;
activeRegion = currentActiveRegion;
if (healthClient != null) {
// Close the existing client so that the next call to this
// method will create a new client using the new active
// region
healthClient.close();
healthClient = null;
}
throw new ActiveRegionHasChangedException("Active region has changed from [" + oldActiveRegion + "] to [" + currentActiveRegion + "]");
}
}
if (healthClient == null) {
// Create the Health client using the region extraced from the global
// endpoint CNAME
healthClient = HealthClient.builder()
.region(Region.of(activeRegion))
.credentialsProvider(
// See https://docs.aws.amazon.com/sdk-for-java/v2/developer-guide/setup-credentials.html
DefaultCredentialsProvider.builder().build()
)
.build();
}
return healthClient;
}
} | 5,335 |
0 | Create_ds/aws-health-tools/high-availability-endpoint/java/src/main/java/aws/health/high/availability/endpoint | Create_ds/aws-health-tools/high-availability-endpoint/java/src/main/java/aws/health/high/availability/endpoint/demo/ActiveRegionHasChangedException.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package aws.health.high.availability.endpoint.demo;
public final class ActiveRegionHasChangedException extends Exception {
public ActiveRegionHasChangedException(String message) {
super(message);
}
public ActiveRegionHasChangedException(String message, Throwable cause) {
super(message, cause);
}
} | 5,336 |
0 | Create_ds/aws-health-tools/high-availability-endpoint/java/src/main/java/aws/health/high/availability/endpoint | Create_ds/aws-health-tools/high-availability-endpoint/java/src/main/java/aws/health/high/availability/endpoint/demo/App.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package aws.health.high.availability.endpoint.demo;
/**
* Sample workflow for using the AWS Health API high availability endpoint
*/
public class App {
public static void main(String[] args) throws RegionLookupException {
// Example using the HealthClient from the AWS Java SDK V2
HighAvailabilityV2Workflow v2Workflow = new HighAvailabilityV2Workflow();
v2Workflow.doWorkflow();
}
}
| 5,337 |
0 | Create_ds/aws-health-tools/high-availability-endpoint/java/src/main/java/aws/health/high/availability/endpoint | Create_ds/aws-health-tools/high-availability-endpoint/java/src/main/java/aws/health/high/availability/endpoint/demo/HighAvailabilityV2Workflow.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package aws.health.high.availability.endpoint.demo;
import software.amazon.awssdk.services.health.HealthClient;
import software.amazon.awssdk.services.health.model.DateTimeRange;
import software.amazon.awssdk.services.health.model.DescribeEventDetailsRequest;
import software.amazon.awssdk.services.health.model.DescribeEventDetailsResponse;
import software.amazon.awssdk.services.health.model.DescribeEventsRequest;
import software.amazon.awssdk.services.health.model.DescribeEventsResponse;
import software.amazon.awssdk.services.health.model.Event;
import software.amazon.awssdk.services.health.model.EventFilter;
import software.amazon.awssdk.services.health.model.EventStatusCode;
import software.amazon.awssdk.services.health.paginators.DescribeEventsIterable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Example workflow when using the AWS Health API high availability endpoint
* and the AWS Java V2 SDK.
*/
public class HighAvailabilityV2Workflow {
private static final Logger log = LoggerFactory.getLogger(HighAvailabilityV2Workflow.class);
/**
* Helper method to provide a shorter way of referring to the singleton
* client method
*/
private HealthClient getV2Client() throws RegionLookupException, ActiveRegionHasChangedException {
return HighAvailabilityV2HealthClient.getHealthClient();
}
/**
* Log the details of an event
*/
private void eventDetails(Event event) throws RegionLookupException, ActiveRegionHasChangedException {
// NOTE: It is more efficient to call describeEventDetails with a batch
// of eventArns, but for simplicitly of this demo we call it with a
// single eventArn
DescribeEventDetailsRequest detailsRequest = DescribeEventDetailsRequest.builder()
.eventArns(Collections.singleton(event.arn()))
.build();
DescribeEventDetailsResponse detailsResponse = getV2Client().describeEventDetails(detailsRequest);
detailsResponse.successfulSet().stream().forEach(detail -> log.info(detail.toString()));
}
private void describeEvents() throws RegionLookupException, ActiveRegionHasChangedException {
// Describe events using the same default filters as the Personal Health Dashboard (PHD). i.e
//
// Return all open or upcoming events which started in the last 7 days, ordered by event lastUpdatedTime
List<EventStatusCode> eventStatusCodes = new ArrayList<>();
eventStatusCodes.add(EventStatusCode.OPEN);
eventStatusCodes.add(EventStatusCode.UPCOMING);
DateTimeRange sevenDaysAgo = DateTimeRange.builder().from(Instant.now().minus(Duration.ofDays(7))).build();
DescribeEventsRequest describeEventsRequest = DescribeEventsRequest.builder()
.filter(EventFilter.builder().eventStatusCodes(eventStatusCodes).startTimes(Collections.singleton(sevenDaysAgo)).build())
.build();
int numberOfMatchingEvents = 0;
DescribeEventsIterable describeEventsResponses = getV2Client().describeEventsPaginator(describeEventsRequest);
for (DescribeEventsResponse eventsResponse : describeEventsResponses) {
for (Event event: eventsResponse.events()) {
eventDetails(event);
numberOfMatchingEvents++;
}
}
if (numberOfMatchingEvents == 0) {
log.info("There are no AWS Health events that match the given filters");
}
}
public void doWorkflow() throws RegionLookupException {
// An example workflow using the AWS Health API's high availability
// endpoint and the AWS Java SDK V2
// If the active endpoint changes we recommend you restart any
// workflows.
//
// In this sample code we throw an exception if the active
// endpoint changes in the middle of a workflow and restart the
// workflow using the new active endpoint.
boolean restartWorkflow = true;
while (restartWorkflow) {
try {
// Describe events for the account
describeEvents();
restartWorkflow = false;
} catch (ActiveRegionHasChangedException ex) {
log.info("The AWS Health API active region has changed. Restarting the workflow using the new active region!" + ex);
}
}
}
} | 5,338 |
0 | Create_ds/aws-encryption-sdk-java | Create_ds/aws-encryption-sdk-java/compliance_exceptions/aws-kms-mrk-aware-multi-keyrings.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// The AWS Encryption SDK - Java does not implement
// any of the Keyring interface at this time.
//= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5
//= type=exception
//# The caller MUST provide:
//#
//# * A set of Region strings
//#
//# * An optional discovery filter that is an AWS partition and a set of
//# AWS accounts
//#
//# * An optional method that can take a region string and return an AWS
//# KMS client e.g. a regional client supplier
//#
//# * An optional list of AWS KMS grant tokens
//#
//# If an empty set of Region is provided this function MUST fail. If
//# any element of the set of regions is null or an empty string this
//# function MUST fail. If a regional client supplier is not passed,
//# then a default MUST be created that takes a region string and
//# generates a default AWS SDK client for the given region.
//#
//# A set of AWS KMS clients MUST be created by calling regional client
//# supplier for each region in the input set of regions.
//#
//# Then a set of AWS KMS MRK Aware Symmetric Region Discovery Keyring
//# (aws-kms-mrk-aware-symmetric-region-discovery-keyring.md) MUST be
//# created for each AWS KMS client by initializing each keyring with
//#
//# * The AWS KMS client
//#
//# * The input discovery filter
//#
//# * The input AWS KMS grant tokens
//#
//# Then a Multi-Keyring (../multi-keyring.md#inputs) MUST be initialize
//# by using this set of discovery keyrings as the child keyrings
//# (../multi-keyring.md#child-keyrings). This Multi-Keyring MUST be
//# this functions output.
//= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6
//= type=exception
//# The caller MUST provide:
//#
//# * An optional AWS KMS key identifiers to use as the generator.
//#
//# * An optional set of AWS KMS key identifiers to us as child
//# keyrings.
//#
//# * An optional method that can take a region string and return an AWS
//# KMS client e.g. a regional client supplier
//#
//# * An optional list of AWS KMS grant tokens
//#
//# If any of the AWS KMS key identifiers is null or an empty string this
//# function MUST fail. At least one non-null or non-empty string AWS
//# KMS key identifiers exists in the input this function MUST fail. All
//# AWS KMS identifiers are passed to Assert AWS KMS MRK are unique (aws-
//# kms-mrk-are-unique.md#Implementation) and the function MUST return
//# success otherwise this MUST fail. If a regional client supplier is
//# not passed, then a default MUST be created that takes a region string
//# and generates a default AWS SDK client for the given region.
//#
//# If there is a generator input then the generator keyring MUST be a
//# AWS KMS MRK Aware Symmetric Keyring (aws-kms-mrk-aware-symmetric-
//# keyring.md) initialized with
//#
//# * The generator input.
//#
//# * The AWS KMS client that MUST be created by the regional client
//# supplier when called with the region part of the generator ARN or
//# a signal for the AWS SDK to select the default region.
//#
//# * The input list of AWS KMS grant tokens
//#
//# If there is a set of child identifiers then a set of AWS KMS MRK
//# Aware Symmetric Keyring (aws-kms-mrk-aware-symmetric-keyring.md) MUST
//# be created for each AWS KMS key identifier by initialized each
//# keyring with
//#
//# * AWS KMS key identifier.
//#
//# * The AWS KMS client that MUST be created by the regional client
//# supplier when called with the region part of the AWS KMS key
//# identifier or a signal for the AWS SDK to select the default
//# region.
//#
//# * The input list of AWS KMS grant tokens
//#
//# NOTE: The AWS Encryption SDK SHOULD NOT attempt to evaluate its own
//# default region.
//#
//# Then a Multi-Keyring (../multi-keyring.md#inputs) MUST be initialize
//# by using this generator keyring as the generator keyring (../multi-
//# keyring.md#generator-keyring) and this set of child keyrings as the
//# child keyrings (../multi-keyring.md#child-keyrings). This Multi-
//# Keyring MUST be this functions output.
| 5,339 |
0 | Create_ds/aws-encryption-sdk-java | Create_ds/aws-encryption-sdk-java/compliance_exceptions/aws-kms-mrk-aware-symmetric-region-discovery-keyring.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// The AWS Encryption SDK - Java does not implement
// any of the Keyring interface at this time.
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.5
//= type=exception
//# MUST implement that AWS Encryption SDK Keyring interface (../keyring-
//# interface.md#interface)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.6
//= type=exception
//# On initialization the caller MUST provide:
//#
//# * An AWS KMS client
//#
//# * An optional discovery filter that is an AWS partition and a set of
//# AWS accounts
//#
//# * An optional list of AWS KMS grant tokens
//#
//# The keyring MUST know what Region the AWS KMS client is in. It
//# SHOULD obtain this information directly from the client as opposed to
//# having an additional parameter. However if it can not, then it MUST
//# NOT create the client itself. It SHOULD have a Region parameter and
//# SHOULD try to identify mismatched configurations. i.e. The client is
//# in Region A and the Region parameter is B.
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.7
//= type=exception
//# This function MUST fail.
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//= type=exception
//# OnDecrypt MUST take decryption materials (structures.md#decryption-
//# materials) and a list of encrypted data keys
//# (structures.md#encrypted-data-key) as input.
//#
//# If the decryption materials (structures.md#decryption-materials)
//# already contained a valid plaintext data key OnDecrypt MUST
//# immediately return the unmodified decryption materials
//# (structures.md#decryption-materials).
//#
//# The set of encrypted data keys MUST first be filtered to match this
//# keyring's configuration. For the encrypted data key to match
//#
//# * Its provider ID MUST exactly match the value "aws-kms".
//#
//# * The provider info MUST be a valid AWS KMS ARN (aws-kms-key-
//# arn.md#a-valid-aws-kms-arn) with a resource type of "key" or
//# OnDecrypt MUST fail.
//#
//# * If a discovery filter is configured, its partition and the
//# provider info partition MUST match.
//#
//# * If a discovery filter is configured, its set of accounts MUST
//# contain the provider info account.
//#
//# * If the provider info is not identified as a multi-Region key (aws-
//# kms-key-arn.md#identifying-an-aws-kms-multi-region-key), then the
//# provider info's Region MUST match the AWS KMS client region.
//#
//# For each encrypted data key in the filtered set, one at a time, the
//# OnDecrypt MUST attempt to decrypt the data key. If this attempt
//# results in an error, then these errors are collected.
//#
//# To attempt to decrypt a particular encrypted data key
//# (structures.md#encrypted-data-key), OnDecrypt MUST call AWS KMS
//# Decrypt (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html) with the configured AWS KMS client.
//#
//# When calling AWS KMS Decrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html), the keyring MUST call with a request constructed
//# as follows:
//#
//# * "KeyId": If the provider info's resource type is "key" and its
//# resource is a multi-Region key then a new ARN MUST be created
//# where the region part MUST equal the AWS KMS client region and
//# every other part MUST equal the provider info. Otherwise it MUST
//# be the provider info.
//#
//# * "CiphertextBlob": The encrypted data key ciphertext
//# (structures.md#ciphertext).
//#
//# * "EncryptionContext": The encryption context
//# (structures.md#encryption-context) included in the input
//# decryption materials (structures.md#decryption-materials).
//#
//# * "GrantTokens": this keyring's grant tokens
//# (https://docs.aws.amazon.com/kms/latest/developerguide/
//# concepts.html#grant_token)
//#
//# If the call to AWS KMS Decrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html) succeeds OnDecrypt verifies
//#
//# * The "KeyId" field in the response MUST equal the requested "KeyId"
//#
//# * The length of the response's "Plaintext" MUST equal the key
//# derivation input length (algorithm-suites.md#key-derivation-input-
//# length) specified by the algorithm suite (algorithm-suites.md)
//# included in the input decryption materials
//# (structures.md#decryption-materials).
//#
//# If the response does not satisfies these requirements then an error
//# is collected and the next encrypted data key in the filtered set MUST
//# be attempted.
//#
//# Since the response does satisfies these requirements then OnDecrypt
//# MUST do the following with the response:
//#
//# * set the plaintext data key on the decryption materials
//# (structures.md#decryption-materials) as the response "Plaintext".
//#
//# * immediately return the modified decryption materials
//# (structures.md#decryption-materials).
//#
//# If OnDecrypt fails to successfully decrypt any encrypted data key
//# (structures.md#encrypted-data-key), then it MUST yield an error that
//# includes all collected errors.
| 5,340 |
0 | Create_ds/aws-encryption-sdk-java | Create_ds/aws-encryption-sdk-java/compliance_exceptions/aws-kms-mrk-aware-symmetric-keyring.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// The AWS Encryption SDK - Java does not implement
// any of the Keyring interface at this time.
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.5
//= type=exception
//# MUST implement the AWS Encryption SDK Keyring interface (../keyring-
//# interface.md#interface)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.6
//= type=exception
//# On initialization the caller MUST provide:
//#
//# * An AWS KMS key identifier
//#
//# * An AWS KMS SDK client
//#
//# * An optional list of Grant Tokens
//#
//# The AWS KMS key identifier MUST NOT be null or empty. The AWS KMS
//# key identifier MUST be a valid identifier (aws-kms-key-arn.md#a-
//# valid-aws-kms-identifier). The AWS KMS SDK client MUST NOT be null.
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=exception
//# OnEncrypt MUST take encryption materials (structures.md#encryption-
//# materials) as input.
//#
//# If the input encryption materials (structures.md#encryption-
//# materials) do not contain a plaintext data key OnEncrypt MUST attempt
//# to generate a new plaintext data key by calling AWS KMS
//# GenerateDataKey (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_GenerateDataKey.html).
//#
//# If the keyring calls AWS KMS GenerateDataKeys, it MUST use the
//# configured AWS KMS client to make the call. The keyring MUST call
//# AWS KMS GenerateDataKeys with a request constructed as follows:
//#
//# * "KeyId": this keyring's KMS key identifier.
//#
//# * "NumberOfBytes": the key derivation input length (algorithm-
//# suites.md#key-derivation-input-length) specified by the algorithm
//# suite (algorithm-suites.md) included in the input encryption
//# materials (structures.md#encryption-materials).
//#
//# * "EncryptionContext": the encryption context
//# (structures.md#encryption-context) included in the input
//# encryption materials (structures.md#encryption-materials).
//#
//# * "GrantTokens": this keyring's grant tokens
//# (https://docs.aws.amazon.com/kms/latest/developerguide/
//# concepts.html#grant_token)
//#
//# If the call to AWS KMS GenerateDataKey
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_GenerateDataKey.html) does not succeed, OnEncrypt MUST NOT modify
//# the encryption materials (structures.md#encryption-materials) and
//# MUST fail.
//#
//# If the Generate Data Key call succeeds, OnEncrypt MUST verify that
//# the response "Plaintext" length matches the specification of the
//# algorithm suite (algorithm-suites.md)'s Key Derivation Input Length
//# field. The Generate Data Key response's "KeyId" MUST be A valid AWS
//# KMS key ARN (aws-kms-key-arn.md#identifying-an-aws-kms-multi-region-
//# key). If verified, OnEncrypt MUST do the following with the response
//# from AWS KMS GenerateDataKey
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_GenerateDataKey.html):
//#
//# * set the plaintext data key on the encryption materials
//# (structures.md#encryption-materials) as the response "Plaintext".
//#
//# * append a new encrypted data key (structures.md#encrypted-data-key)
//# to the encrypted data key list in the encryption materials
//# (structures.md#encryption-materials), constructed as follows:
//#
//# - the ciphertext (structures.md#ciphertext) is the response
//# "CiphertextBlob".
//#
//# - the key provider id (structures.md#key-provider-id) is "aws-
//# kms".
//#
//# - the key provider information (structures.md#key-provider-
//# information) is the response "KeyId".
//#
//# * OnEncrypt MUST output the modified encryption materials
//# (structures.md#encryption-materials)
//#
//# Given a plaintext data key in the encryption materials
//# (structures.md#encryption-materials), OnEncrypt MUST attempt to
//# encrypt the plaintext data key using the configured AWS KMS key
//# identifier.
//#
//# The keyring MUST call AWS KMS Encrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Encrypt.html) using the configured AWS KMS client. The keyring
//# MUST AWS KMS Encrypt call with a request constructed as follows:
//#
//# * "KeyId": The configured AWS KMS key identifier.
//#
//# * "PlaintextDataKey": the plaintext data key in the encryption
//# materials (structures.md#encryption-materials).
//#
//# * "EncryptionContext": the encryption context
//# (structures.md#encryption-context) included in the input
//# encryption materials (structures.md#encryption-materials).
//#
//# * "GrantTokens": this keyring's grant tokens
//# (https://docs.aws.amazon.com/kms/latest/developerguide/
//# concepts.html#grant_token)
//#
//# If the call to AWS KMS Encrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Encrypt.html) does not succeed, OnEncrypt MUST fail.
//#
//# If the Encrypt call succeeds The response's "KeyId" MUST be A valid
//# AWS KMS key ARN (aws-kms-key-arn.md#identifying-an-aws-kms-multi-
//# region-key). If verified, OnEncrypt MUST do the following with the
//# response from AWS KMS Encrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Encrypt.html):
//#
//# * append a new encrypted data key (structures.md#encrypted-data-key)
//# to the encrypted data key list in the encryption materials
//# (structures.md#encryption-materials), constructed as follows:
//#
//# - The ciphertext (structures.md#ciphertext) is the response
//# "CiphertextBlob".
//#
//# - The key provider id (structures.md#key-provider-id) is "aws-
//# kms".
//#
//# - The key provider information (structures.md#key-provider-
//# information) is the response "KeyId". Note that the "KeyId" in
//# the response is always in key ARN format.
//#
//# If all Encrypt calls succeed, OnEncrypt MUST output the modified
//# encryption materials (structures.md#encryption-materials).
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//= type=exception
//# OnDecrypt MUST take decryption materials (structures.md#decryption-
//# materials) and a list of encrypted data keys
//# (structures.md#encrypted-data-key) as input.
//#
//# If the decryption materials (structures.md#decryption-materials)
//# already contained a valid plaintext data key OnDecrypt MUST
//# immediately return the unmodified decryption materials
//# (structures.md#decryption-materials).
//#
//# The set of encrypted data keys MUST first be filtered to match this
//# keyring's configuration. For the encrypted data key to match
//#
//# * Its provider ID MUST exactly match the value "aws-kms".
//#
//# * The provider info MUST be a valid AWS KMS ARN (aws-kms-key-
//# arn.md#a-valid-aws-kms-arn) with a resource type of "key" or
//# OnDecrypt MUST fail.
//#
//# * The the function AWS KMS MRK Match for Decrypt (aws-kms-mrk-match-
//# for-decrypt.md#implementation) called with the configured AWS KMS
//# key identifier and the provider info MUST return "true".
//#
//# For each encrypted data key in the filtered set, one at a time, the
//# OnDecrypt MUST attempt to decrypt the data key. If this attempt
//# results in an error, then these errors MUST be collected.
//#
//# To attempt to decrypt a particular encrypted data key
//# (structures.md#encrypted-data-key), OnDecrypt MUST call AWS KMS
//# Decrypt (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html) with the configured AWS KMS client.
//#
//# When calling AWS KMS Decrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html), the keyring MUST call with a request constructed
//# as follows:
//#
//# * "KeyId": The configured AWS KMS key identifier.
//#
//# * "CiphertextBlob": the encrypted data key ciphertext
//# (structures.md#ciphertext).
//#
//# * "EncryptionContext": the encryption context
//# (structures.md#encryption-context) included in the input
//# decryption materials (structures.md#decryption-materials).
//#
//# * "GrantTokens": this keyring's grant tokens
//# (https://docs.aws.amazon.com/kms/latest/developerguide/
//# concepts.html#grant_token)
//#
//# If the call to AWS KMS Decrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html) succeeds OnDecrypt verifies
//#
//# * The "KeyId" field in the response MUST equal the configured AWS
//# KMS key identifier.
//#
//# * The length of the response's "Plaintext" MUST equal the key
//# derivation input length (algorithm-suites.md#key-derivation-input-
//# length) specified by the algorithm suite (algorithm-suites.md)
//# included in the input decryption materials
//# (structures.md#decryption-materials).
//#
//# If the response does not satisfies these requirements then an error
//# MUST be collected and the next encrypted data key in the filtered set
//# MUST be attempted.
//#
//# If the response does satisfies these requirements then OnDecrypt MUST
//# do the following with the response:
//#
//# * set the plaintext data key on the decryption materials
//# (structures.md#decryption-materials) as the response "Plaintext".
//#
//# * immediately return the modified decryption materials
//# (structures.md#decryption-materials).
//#
//# If OnDecrypt fails to successfully decrypt any encrypted data key
//# (structures.md#encrypted-data-key), then it MUST yield an error that
//# includes all the collected errors.
| 5,341 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/DiscoveryMultiRegionDecryptionExampleTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.crypto.examples;
import com.amazonaws.encryptionsdk.kms.KMSTestFixtures;
import org.junit.Test;
import software.amazon.awssdk.regions.Region;
public class DiscoveryMultiRegionDecryptionExampleTest {
@Test
public void testEncryptAndDecrypt() {
DiscoveryMultiRegionDecryptionExample.encryptAndDecrypt(
KMSTestFixtures.US_EAST_1_MULTI_REGION_KEY_ID,
KMSTestFixtures.PARTITION,
KMSTestFixtures.ACCOUNT_ID,
Region.US_WEST_2);
}
}
| 5,342 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/RestrictRegionExampleTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.crypto.examples;
import com.amazonaws.encryptionsdk.kms.KMSTestFixtures;
import org.junit.Test;
import software.amazon.awssdk.regions.Region;
public class RestrictRegionExampleTest {
@Test
public void testEncryptAndDecrypt() {
RestrictRegionExample.encryptAndDecrypt(
KMSTestFixtures.US_WEST_2_KEY_ID,
KMSTestFixtures.PARTITION,
KMSTestFixtures.ACCOUNT_ID,
Region.US_WEST_2);
}
}
| 5,343 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/MultipleCmkEncryptExampleTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.crypto.examples;
import com.amazonaws.encryptionsdk.kms.KMSTestFixtures;
import org.junit.Test;
public class MultipleCmkEncryptExampleTest {
@Test
public void testEncryptAndDecrypt() {
MultipleCmkEncryptExample.encryptAndDecrypt(
KMSTestFixtures.TEST_KEY_IDS[0], KMSTestFixtures.TEST_KEY_IDS[1]);
}
}
| 5,344 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/SimpleDataKeyCachingExampleTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.crypto.examples;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import com.amazonaws.encryptionsdk.ParsedCiphertext;
import com.amazonaws.encryptionsdk.kms.KMSTestFixtures;
import org.junit.Test;
public class SimpleDataKeyCachingExampleTest {
private static final int MAX_ENTRY_AGE = 100;
private static final int CACHE_CAPACITY = 1000;
@Test
public void testEncryptWithCaching() {
final byte[] result =
SimpleDataKeyCachingExample.encryptWithCaching(
KMSTestFixtures.TEST_KEY_IDS[0], MAX_ENTRY_AGE, CACHE_CAPACITY);
assertNotNull(result);
final ParsedCiphertext parsedResult = new ParsedCiphertext(result);
assertEquals(1, parsedResult.getEncryptedKeyBlobs().size());
assertArrayEquals(
KMSTestFixtures.TEST_KEY_IDS[0].getBytes(),
parsedResult.getEncryptedKeyBlobs().get(0).getProviderInformation());
}
}
| 5,345 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/SetEncryptionAlgorithmExampleTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.crypto.examples;
import com.amazonaws.encryptionsdk.kms.KMSTestFixtures;
import org.junit.Test;
public class SetEncryptionAlgorithmExampleTest {
@Test
public void testEncryptAndDecrypt() {
SetEncryptionAlgorithmExample.encryptAndDecrypt(KMSTestFixtures.TEST_KEY_IDS[0]);
}
}
| 5,346 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/BasicEncryptionExampleTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.crypto.examples;
import com.amazonaws.encryptionsdk.kms.KMSTestFixtures;
import org.junit.Test;
public class BasicEncryptionExampleTest {
@Test
public void testEncryptAndDecrypt() {
BasicEncryptionExample.encryptAndDecrypt(KMSTestFixtures.TEST_KEY_IDS[0]);
}
}
| 5,347 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/BasicMultiRegionKeyEncryptionExampleTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.crypto.examples;
import com.amazonaws.encryptionsdk.kms.KMSTestFixtures;
import org.junit.Test;
public class BasicMultiRegionKeyEncryptionExampleTest {
@Test
public void testEncryptAndDecrypt() {
BasicMultiRegionKeyEncryptionExample.encryptAndDecrypt(
KMSTestFixtures.US_EAST_1_MULTI_REGION_KEY_ID,
KMSTestFixtures.US_WEST_2_MULTI_REGION_KEY_ID);
}
}
| 5,348 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/SetCommitmentPolicyExampleTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.crypto.examples;
import com.amazonaws.encryptionsdk.kms.KMSTestFixtures;
import org.junit.Test;
public class SetCommitmentPolicyExampleTest {
@Test
public void testEncryptAndDecrypt() {
SetCommitmentPolicyExample.encryptAndDecrypt(KMSTestFixtures.TEST_KEY_IDS[0]);
}
}
| 5,349 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/DiscoveryDecryptionExampleTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.crypto.examples;
import com.amazonaws.encryptionsdk.kms.KMSTestFixtures;
import org.junit.Test;
public class DiscoveryDecryptionExampleTest {
@Test
public void testEncryptAndDecrypt() {
DiscoveryDecryptionExample.encryptAndDecrypt(
KMSTestFixtures.TEST_KEY_IDS[0], KMSTestFixtures.PARTITION, KMSTestFixtures.ACCOUNT_ID);
}
}
| 5,350 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/DefaultCryptoMaterialsManagerTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import static com.amazonaws.encryptionsdk.multi.MultipleProviderFactory.buildMultiProvider;
import static java.util.Collections.singletonMap;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import com.amazonaws.encryptionsdk.exception.AwsCryptoException;
import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException;
import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException;
import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException;
import com.amazonaws.encryptionsdk.internal.Constants;
import com.amazonaws.encryptionsdk.internal.StaticMasterKey;
import com.amazonaws.encryptionsdk.internal.TrailingSignatureAlgorithm;
import com.amazonaws.encryptionsdk.model.DecryptionMaterials;
import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest;
import com.amazonaws.encryptionsdk.model.EncryptionMaterials;
import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest;
import java.nio.charset.StandardCharsets;
import java.security.Signature;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import org.junit.Test;
public class DefaultCryptoMaterialsManagerTest {
private static final MasterKey<?> mk1 = new StaticMasterKey("mk1");
private static final MasterKey<?> mk2 = new StaticMasterKey("mk2");
private static final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY;
@Test
public void encrypt_testBasicFunctionality() throws Exception {
EncryptionMaterialsRequest req =
EncryptionMaterialsRequest.newBuilder().setCommitmentPolicy(commitmentPolicy).build();
EncryptionMaterials result = new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(req);
assertNotNull(result.getCleartextDataKey());
assertNotNull(result.getEncryptionContext());
assertEquals(
CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, result.getAlgorithm());
assertEquals(1, result.getEncryptedDataKeys().size());
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk1, result.getMasterKeys().get(0));
}
@Test
public void encrypt_testNonCommittingDefaultAlgorithm() throws Exception {
EncryptionMaterialsRequest req =
EncryptionMaterialsRequest.newBuilder()
.setCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt)
.build();
EncryptionMaterials result = new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(req);
assertEquals(
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, result.getAlgorithm());
}
@Test
public void encrypt_testCommittingDefaultAlgorithm() throws Exception {
final List<CommitmentPolicy> requireWritePolicies =
Arrays.asList(
CommitmentPolicy.RequireEncryptRequireDecrypt,
CommitmentPolicy.RequireEncryptAllowDecrypt);
for (CommitmentPolicy policy : requireWritePolicies) {
EncryptionMaterialsRequest req =
EncryptionMaterialsRequest.newBuilder().setCommitmentPolicy(policy).build();
EncryptionMaterials result =
new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(req);
assertEquals(
CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, result.getAlgorithm());
}
}
@Test
public void encrypt_noSignatureKeyOnUnsignedAlgo() throws Exception {
CryptoAlgorithm[] algorithms =
new CryptoAlgorithm[] {
CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256,
CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_NO_KDF,
CryptoAlgorithm.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256,
CryptoAlgorithm.ALG_AES_192_GCM_IV12_TAG16_NO_KDF,
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256,
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_NO_KDF,
CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY
};
for (CryptoAlgorithm algo : algorithms) {
EncryptionMaterialsRequest req =
EncryptionMaterialsRequest.newBuilder()
.setCommitmentPolicy(commitmentPolicy)
.setRequestedAlgorithm(algo)
.build();
EncryptionMaterials result =
new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(req);
assertNull(result.getTrailingSignatureKey());
assertEquals(0, result.getEncryptionContext().size());
assertEquals(algo, result.getAlgorithm());
}
}
@Test
public void encrypt_hasSignatureKeyForSignedAlgo() throws Exception {
CryptoAlgorithm[] algorithms =
new CryptoAlgorithm[] {
CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256,
CryptoAlgorithm.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384,
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384,
CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384
};
for (CryptoAlgorithm algo : algorithms) {
EncryptionMaterialsRequest req =
EncryptionMaterialsRequest.newBuilder()
.setCommitmentPolicy(commitmentPolicy)
.setRequestedAlgorithm(algo)
.build();
EncryptionMaterials result =
new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(req);
assertNotNull(result.getTrailingSignatureKey());
assertEquals(1, result.getEncryptionContext().size());
assertNotNull(result.getEncryptionContext().get(Constants.EC_PUBLIC_KEY_FIELD));
assertEquals(algo, result.getAlgorithm());
}
}
@Test
public void encrypt_dispatchesMultipleMasterKeys() throws Exception {
MasterKey<?> mk1_spy = spy(mk1);
MasterKey<?> mk2_spy = spy(mk2);
DataKey[] mk1_datakey = new DataKey[1];
doAnswer(
invocation -> {
Object dk = invocation.callRealMethod();
mk1_datakey[0] = (DataKey) dk;
return dk;
})
.when(mk1_spy)
.generateDataKey(any(), any());
MasterKeyProvider<?> mkp = buildMultiProvider(mk1_spy, mk2_spy);
EncryptionMaterialsRequest req =
EncryptionMaterialsRequest.newBuilder()
.setCommitmentPolicy(commitmentPolicy)
.setContext(singletonMap("foo", "bar"))
.build();
EncryptionMaterials result = new DefaultCryptoMaterialsManager(mkp).getMaterialsForEncrypt(req);
//noinspection unchecked
verify(mk1_spy)
.generateDataKey(
any(),
// there's a weird generics issue here without downcasting to (Map)
(Map) argThat((Map m) -> Objects.equals(m.get("foo"), "bar")));
//noinspection unchecked
verify(mk2_spy)
.encryptDataKey(
any(),
(Map) argThat((Map m) -> Objects.equals(m.get("foo"), "bar")),
same(mk1_datakey[0]));
assertArrayEquals(
mk1_datakey[0].getKey().getEncoded(), result.getCleartextDataKey().getEncoded());
}
@Test
public void encrypt_forwardsPlaintextWhenAvailable() throws Exception {
MasterKey<?> mk1_spy = spy(mk1);
EncryptionMaterialsRequest request =
EncryptionMaterialsRequest.newBuilder()
.setCommitmentPolicy(commitmentPolicy)
.setPlaintext(new byte[1])
.build();
new DefaultCryptoMaterialsManager(mk1_spy).getMaterialsForEncrypt(request);
verify(mk1_spy)
.getMasterKeysForEncryption(
argThat(req -> Arrays.equals(req.getPlaintext(), new byte[1]) && !req.isStreaming()));
}
@Test
public void encrypt_forwardsPlaintextSizeWhenAvailable() throws Exception {
MasterKey<?> mk1_spy = spy(mk1);
EncryptionMaterialsRequest request =
EncryptionMaterialsRequest.newBuilder()
.setCommitmentPolicy(commitmentPolicy)
.setPlaintextSize(1)
.build();
new DefaultCryptoMaterialsManager(mk1_spy).getMaterialsForEncrypt(request);
verify(mk1_spy)
.getMasterKeysForEncryption(argThat(req -> req.getSize() == 1 && !req.isStreaming()));
}
@Test
public void encrypt_setsStreamingWhenNoSizeAvailable() throws Exception {
MasterKey<?> mk1_spy = spy(mk1);
EncryptionMaterialsRequest request =
EncryptionMaterialsRequest.newBuilder().setCommitmentPolicy(commitmentPolicy).build();
new DefaultCryptoMaterialsManager(mk1_spy).getMaterialsForEncrypt(request);
verify(mk1_spy).getMasterKeysForEncryption(argThat(MasterKeyRequest::isStreaming));
}
@Test(expected = IllegalArgumentException.class)
public void encrypt_whenECContextKeyPresent_throws() throws Exception {
EncryptionMaterialsRequest req =
EncryptionMaterialsRequest.newBuilder()
.setCommitmentPolicy(commitmentPolicy)
.setRequestedAlgorithm(
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384)
.setContext(singletonMap(Constants.EC_PUBLIC_KEY_FIELD, "some EC key"))
.build();
new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(req);
}
@Test(expected = IllegalArgumentException.class)
public void encrypt_whenNoMasterKeys_throws() throws Exception {
EncryptionMaterialsRequest req =
EncryptionMaterialsRequest.newBuilder().setCommitmentPolicy(commitmentPolicy).build();
new DefaultCryptoMaterialsManager(
new MasterKeyProvider() {
@Override
public String getDefaultProviderId() {
return "provider ID";
}
@Override
public MasterKey getMasterKey(String provider, String keyId)
throws UnsupportedProviderException, NoSuchMasterKeyException {
throw new NoSuchMasterKeyException();
}
@Override
public List getMasterKeysForEncryption(MasterKeyRequest request) {
return Collections.emptyList();
}
@Override
public DataKey decryptDataKey(
CryptoAlgorithm algorithm, Collection encryptedDataKeys, Map encryptionContext)
throws UnsupportedProviderException, AwsCryptoException {
return null;
}
})
.getMaterialsForEncrypt(req);
}
private EncryptionMaterials easyGenMaterials(
Consumer<EncryptionMaterialsRequest.Builder> customizer) {
EncryptionMaterialsRequest.Builder request =
EncryptionMaterialsRequest.newBuilder().setCommitmentPolicy(commitmentPolicy);
customizer.accept(request);
return new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(request.build());
}
private DecryptionMaterialsRequest decryptReqFromMaterials(EncryptionMaterials result) {
return DecryptionMaterialsRequest.newBuilder()
.setEncryptionContext(result.getEncryptionContext())
.setEncryptedDataKeys(result.getEncryptedDataKeys())
.setAlgorithm(result.getAlgorithm())
.build();
}
@Test
public void decrypt_testSimpleRoundTrip() throws Exception {
for (CryptoAlgorithm algorithm : CryptoAlgorithm.values()) {
CommitmentPolicy policy =
algorithm.isCommitting()
? CommitmentPolicy.RequireEncryptRequireDecrypt
: CommitmentPolicy.ForbidEncryptAllowDecrypt;
EncryptionMaterials encryptMaterials =
easyGenMaterials(builder -> builder.setRequestedAlgorithm(algorithm));
DecryptionMaterials decryptMaterials =
new DefaultCryptoMaterialsManager(mk1)
.decryptMaterials(decryptReqFromMaterials(encryptMaterials));
assertArrayEquals(
decryptMaterials.getDataKey().getKey().getEncoded(),
encryptMaterials.getCleartextDataKey().getEncoded());
if (encryptMaterials.getTrailingSignatureKey() == null) {
assertNull(decryptMaterials.getTrailingSignatureKey());
} else {
Signature sig =
Signature.getInstance(
TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).getHashAndSignAlgorithm());
sig.initSign(encryptMaterials.getTrailingSignatureKey());
byte[] data = "hello world".getBytes(StandardCharsets.UTF_8);
sig.update(data);
byte[] signature = sig.sign();
sig.initVerify(decryptMaterials.getTrailingSignatureKey());
sig.update(data);
sig.verify(signature);
}
}
}
@Test(expected = CannotUnwrapDataKeyException.class)
public void decrypt_onDecryptFailure() throws Exception {
new DefaultCryptoMaterialsManager(mock(MasterKeyProvider.class))
.decryptMaterials(decryptReqFromMaterials(easyGenMaterials(ignored -> {})));
}
@Test
public void decrypt_whenTrailingSigMissing_throwsException() throws Exception {
for (CryptoAlgorithm algorithm : CryptoAlgorithm.values()) {
// Only test algorithms without key commitment
if (algorithm.getMessageFormatVersion() != 1) {
continue;
}
if (algorithm.getTrailingSignatureLength() == 0) {
continue;
}
EncryptionMaterials encryptMaterials =
easyGenMaterials(builder -> builder.setRequestedAlgorithm(algorithm));
DecryptionMaterialsRequest request =
DecryptionMaterialsRequest.newBuilder()
.setEncryptedDataKeys(encryptMaterials.getEncryptedDataKeys())
.setAlgorithm(algorithm)
.setEncryptionContext(Collections.emptyMap())
.build();
try {
new DefaultCryptoMaterialsManager(mk1).decryptMaterials(request);
fail("expected exception");
} catch (AwsCryptoException e) {
// ok
continue;
}
}
}
}
| 5,351 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/FastTestsOnlySuite.java | package com.amazonaws.encryptionsdk;
import java.util.concurrent.TimeUnit;
import org.junit.ClassRule;
import org.junit.experimental.categories.Categories;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runner.Runner;
import org.junit.runners.Suite;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.RunnerBuilder;
import org.junit.runners.model.Statement;
/**
* This test suite is intended to assist in rapid development; it filters out some of the slower,
* more exhaustive tests in the overall test suite to allow for a rapid edit-test cycle.
*/
@RunWith(FastTestsOnlySuite.CustomRunner.class)
@Suite.SuiteClasses({AllTestsSuite.class})
@Categories.ExcludeCategory(SlowTestCategory.class)
public class FastTestsOnlySuite {
private static InheritableThreadLocal<Boolean> IS_FAST_TEST_SUITE_ACTIVE =
new InheritableThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return false;
}
};
// This method is used to adjust DataProviders to provide a smaller subset of their test cases
// when the fast tests
// are selected
public static boolean isFastTestSuiteActive() {
return IS_FAST_TEST_SUITE_ACTIVE.get();
}
// Require that this fast suite completes relatively quickly. If you're seeing this timeout get
// hit, it's time to
// pare down tests some more. As a general rule of thumb, we should avoid any single test taking
// more than 10s, and
// try to keep the number of such slow tests to a minimum.
@ClassRule public static Timeout timeout = new Timeout(2, TimeUnit.MINUTES);
@ClassRule public static EnableFastSuite enableFastSuite = new EnableFastSuite();
// TestRules run over the execution of tests, but not over the generation of parameterized test
// data...
private static class EnableFastSuite implements TestRule {
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
Boolean oldValue = IS_FAST_TEST_SUITE_ACTIVE.get();
try {
IS_FAST_TEST_SUITE_ACTIVE.set(true);
base.evaluate();
} finally {
IS_FAST_TEST_SUITE_ACTIVE.set(oldValue);
}
}
};
}
}
// ... so we also need a custom TestRunner that will pass the flag on to the parameterized test
// data generators.
public static class CustomRunner extends Categories {
public CustomRunner(Class<?> klass, RunnerBuilder builder) throws InitializationError {
super(
klass,
new RunnerBuilder() {
@Override
public Runner runnerForClass(Class<?> testClass) throws Throwable {
Boolean oldValue = IS_FAST_TEST_SUITE_ACTIVE.get();
try {
IS_FAST_TEST_SUITE_ACTIVE.set(true);
Runner r = builder.runnerForClass(testClass);
return r;
} finally {
IS_FAST_TEST_SUITE_ACTIVE.set(oldValue);
}
}
});
}
}
}
| 5,352 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/AwsCryptoTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import static com.amazonaws.encryptionsdk.FastTestsOnlySuite.isFastTestSuiteActive;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static java.util.Collections.singletonMap;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import com.amazonaws.encryptionsdk.caching.CachingCryptoMaterialsManager;
import com.amazonaws.encryptionsdk.caching.LocalCryptoMaterialsCache;
import com.amazonaws.encryptionsdk.exception.AwsCryptoException;
import com.amazonaws.encryptionsdk.exception.BadCiphertextException;
import com.amazonaws.encryptionsdk.internal.StaticMasterKey;
import com.amazonaws.encryptionsdk.internal.TestIOUtils;
import com.amazonaws.encryptionsdk.internal.Utils;
import com.amazonaws.encryptionsdk.jce.JceMasterKey;
import com.amazonaws.encryptionsdk.model.CiphertextType;
import com.amazonaws.encryptionsdk.model.DecryptionMaterials;
import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest;
import com.amazonaws.encryptionsdk.model.EncryptionMaterials;
import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest;
import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory;
import com.amazonaws.util.IOUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
public class AwsCryptoTest {
private StaticMasterKey masterKeyProvider;
private AwsCrypto forbidCommitmentClient_;
private AwsCrypto encryptionClient_;
private AwsCrypto noMaxEdksClient_;
private AwsCrypto maxEdksClient_;
private static final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY;
private static final int MESSAGE_FORMAT_MAX_EDKS = (1 << 16) - 1;
List<CommitmentPolicy> requireWriteCommitmentPolicies =
Arrays.asList(
CommitmentPolicy.RequireEncryptAllowDecrypt,
CommitmentPolicy.RequireEncryptRequireDecrypt);
@Before
public void init() {
masterKeyProvider = spy(new StaticMasterKey("testmaterial"));
forbidCommitmentClient_ =
AwsCrypto.builder()
.withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt)
.build();
forbidCommitmentClient_.setEncryptionAlgorithm(
CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256);
encryptionClient_ = AwsCrypto.standard();
encryptionClient_.setEncryptionAlgorithm(
CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY);
noMaxEdksClient_ =
AwsCrypto.builder()
.withCommitmentPolicy(CommitmentPolicy.RequireEncryptAllowDecrypt)
.withEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY)
.build();
maxEdksClient_ =
AwsCrypto.builder()
.withMaxEncryptedDataKeys(3)
.withCommitmentPolicy(CommitmentPolicy.RequireEncryptAllowDecrypt)
.withEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY)
.build();
}
private void doEncryptDecrypt(
final CryptoAlgorithm cryptoAlg, final int byteSize, final int frameSize) {
final byte[] plaintextBytes = new byte[byteSize];
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC1", "Encrypt-decrypt test with %d" + byteSize);
AwsCrypto client = cryptoAlg.isCommitting() ? encryptionClient_ : forbidCommitmentClient_;
client.setEncryptionAlgorithm(cryptoAlg);
client.setEncryptionFrameSize(frameSize);
final byte[] cipherText =
client.encryptData(masterKeyProvider, plaintextBytes, encryptionContext).getResult();
final byte[] decryptedText = client.decryptData(masterKeyProvider, cipherText).getResult();
assertArrayEquals("Bad encrypt/decrypt for " + cryptoAlg, plaintextBytes, decryptedText);
}
private void doTamperedEncryptDecrypt(
final CryptoAlgorithm cryptoAlg, final int byteSize, final int frameSize) {
final byte[] plaintextBytes = new byte[byteSize];
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC1", "Encrypt-decrypt test with %d" + byteSize);
AwsCrypto client = cryptoAlg.isCommitting() ? encryptionClient_ : forbidCommitmentClient_;
client.setEncryptionAlgorithm(cryptoAlg);
client.setEncryptionFrameSize(frameSize);
final byte[] cipherText =
client.encryptData(masterKeyProvider, plaintextBytes, encryptionContext).getResult();
cipherText[cipherText.length - 2] ^= (byte) 0xff;
try {
client.decryptData(masterKeyProvider, cipherText).getResult();
fail("Expected BadCiphertextException");
} catch (final BadCiphertextException ex) {
// Expected exception
}
}
private void doTruncatedEncryptDecrypt(
final CryptoAlgorithm cryptoAlg, final int byteSize, final int frameSize) {
final byte[] plaintextBytes = new byte[byteSize];
final Map<String, String> encryptionContext = new HashMap<>(1);
encryptionContext.put("ENC1", "Encrypt-decrypt test with %d" + byteSize);
AwsCrypto client = cryptoAlg.isCommitting() ? encryptionClient_ : forbidCommitmentClient_;
client.setEncryptionAlgorithm(cryptoAlg);
client.setEncryptionFrameSize(frameSize);
final byte[] cipherText =
client.encryptData(masterKeyProvider, plaintextBytes, encryptionContext).getResult();
final byte[] truncatedCipherText = Arrays.copyOf(cipherText, cipherText.length - 1);
try {
client.decryptData(masterKeyProvider, truncatedCipherText).getResult();
fail("Expected BadCiphertextException");
} catch (final BadCiphertextException ex) {
// Expected exception
}
}
private void doEncryptDecryptWithParsedCiphertext(
final CryptoAlgorithm cryptoAlg, final int byteSize, final int frameSize) {
final byte[] plaintextBytes = new byte[byteSize];
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC1", "Encrypt-decrypt test with %d" + byteSize);
AwsCrypto client = cryptoAlg.isCommitting() ? encryptionClient_ : forbidCommitmentClient_;
client.setEncryptionAlgorithm(cryptoAlg);
client.setEncryptionFrameSize(frameSize);
final byte[] cipherText =
client.encryptData(masterKeyProvider, plaintextBytes, encryptionContext).getResult();
ParsedCiphertext pCt = new ParsedCiphertext(cipherText);
assertEquals(client.getEncryptionAlgorithm(), pCt.getCryptoAlgoId());
assertEquals(CiphertextType.CUSTOMER_AUTHENTICATED_ENCRYPTED_DATA, pCt.getType());
assertEquals(1, pCt.getEncryptedKeyBlobCount());
assertEquals(pCt.getEncryptedKeyBlobCount(), pCt.getEncryptedKeyBlobs().size());
assertEquals(
masterKeyProvider.getProviderId(), pCt.getEncryptedKeyBlobs().get(0).getProviderId());
for (Map.Entry<String, String> e : encryptionContext.entrySet()) {
assertEquals(e.getValue(), pCt.getEncryptionContextMap().get(e.getKey()));
}
final byte[] decryptedText = client.decryptData(masterKeyProvider, pCt).getResult();
assertArrayEquals(plaintextBytes, decryptedText);
}
@Test
public void encryptDecrypt() {
for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) {
// Only test with crypto algs without commitment, since those
// are the only ones we can encrypt with
if (cryptoAlg.getMessageFormatVersion() != 1) {
continue;
}
final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg);
for (int i = 0; i < frameSizeToTest.length; i++) {
final int frameSize = frameSizeToTest[i];
int[] bytesToTest = {
0,
1,
frameSize - 1,
frameSize,
frameSize + 1,
(int) (frameSize * 1.5),
frameSize * 2,
1000000
};
for (int j = 0; j < bytesToTest.length; j++) {
final int byteSize = bytesToTest[j];
if (byteSize > 500_000 && isFastTestSuiteActive()) {
continue;
}
if (byteSize >= 0) {
doEncryptDecrypt(cryptoAlg, byteSize, frameSize);
}
}
}
}
}
@Test
public void encryptDecryptWithBadSignature() {
for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) {
// Only test with crypto algs without commitment, since those
// are the only ones we can encrypt with
if (cryptoAlg.getMessageFormatVersion() != 1) {
continue;
}
if (cryptoAlg.getTrailingSignatureAlgo() == null) {
continue;
}
final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg);
for (int i = 0; i < frameSizeToTest.length; i++) {
final int frameSize = frameSizeToTest[i];
int[] bytesToTest = {
0,
1,
frameSize - 1,
frameSize,
frameSize + 1,
(int) (frameSize * 1.5),
frameSize * 2,
1000000
};
for (int j = 0; j < bytesToTest.length; j++) {
final int byteSize = bytesToTest[j];
if (byteSize > 500_000 && isFastTestSuiteActive()) {
continue;
}
if (byteSize >= 0) {
doTamperedEncryptDecrypt(cryptoAlg, byteSize, frameSize);
}
}
}
}
}
@Test
public void encryptDecryptWithTruncatedCiphertext() {
for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) {
// Only test with crypto algs without commitment, since those
// are the only ones we can encrypt with
if (cryptoAlg.getMessageFormatVersion() != 1) {
continue;
}
final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg);
for (int i = 0; i < frameSizeToTest.length; i++) {
final int frameSize = frameSizeToTest[i];
int[] bytesToTest = {
0,
1,
frameSize - 1,
frameSize,
frameSize + 1,
(int) (frameSize * 1.5),
frameSize * 2,
1000000
};
for (int j = 0; j < bytesToTest.length; j++) {
final int byteSize = bytesToTest[j];
if (byteSize > 500_000) {
continue;
}
if (byteSize >= 0) {
doTruncatedEncryptDecrypt(cryptoAlg, byteSize, frameSize);
}
}
}
}
}
@Test
public void encryptDecryptWithParsedCiphertext() {
for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) {
final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg);
for (int i = 0; i < frameSizeToTest.length; i++) {
final int frameSize = frameSizeToTest[i];
int[] bytesToTest = {
0,
1,
frameSize - 1,
frameSize,
frameSize + 1,
(int) (frameSize * 1.5),
frameSize * 2,
1000000
};
for (int j = 0; j < bytesToTest.length; j++) {
final int byteSize = bytesToTest[j];
if (byteSize > 500_000 && isFastTestSuiteActive()) {
continue;
}
if (byteSize >= 0) {
doEncryptDecryptWithParsedCiphertext(cryptoAlg, byteSize, frameSize);
}
}
}
}
}
@Test
public void encryptDecryptWithCustomManager() throws Exception {
boolean[] didDecrypt = new boolean[] {false};
CryptoMaterialsManager manager =
new CryptoMaterialsManager() {
@Override
public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) {
request = request.toBuilder().setContext(singletonMap("foo", "bar")).build();
EncryptionMaterials encryptionMaterials =
new DefaultCryptoMaterialsManager(masterKeyProvider)
.getMaterialsForEncrypt(request);
return encryptionMaterials;
}
@Override
public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) {
didDecrypt[0] = true;
return new DefaultCryptoMaterialsManager(masterKeyProvider).decryptMaterials(request);
}
};
byte[] plaintext = new byte[100];
CryptoResult<byte[], ?> ciphertext = encryptionClient_.encryptData(manager, plaintext);
assertEquals("bar", ciphertext.getEncryptionContext().get("foo"));
// TODO decrypt
assertFalse(didDecrypt[0]);
CryptoResult<byte[], ?> plaintextResult =
encryptionClient_.decryptData(manager, ciphertext.getResult());
assertArrayEquals(plaintext, plaintextResult.getResult());
assertTrue(didDecrypt[0]);
}
@Test
public void whenCustomCMMIgnoresAlgorithm_throws() throws Exception {
boolean[] didDecrypt = new boolean[] {false};
CryptoMaterialsManager manager =
new CryptoMaterialsManager() {
@Override
public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) {
request = request.toBuilder().setRequestedAlgorithm(null).build();
EncryptionMaterials encryptionMaterials =
new DefaultCryptoMaterialsManager(masterKeyProvider)
.getMaterialsForEncrypt(request);
return encryptionMaterials;
}
@Override
public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) {
didDecrypt[0] = true;
return new DefaultCryptoMaterialsManager(masterKeyProvider).decryptMaterials(request);
}
};
encryptionClient_.setEncryptionAlgorithm(
CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY);
byte[] plaintext = new byte[100];
assertThrows(AwsCryptoException.class, () -> encryptionClient_.encryptData(manager, plaintext));
assertThrows(
AwsCryptoException.class, () -> encryptionClient_.estimateCiphertextSize(manager, 12345));
assertThrows(
AwsCryptoException.class,
() ->
encryptionClient_
.createEncryptingStream(manager, new ByteArrayOutputStream())
.write(0));
assertThrows(
AwsCryptoException.class,
() ->
encryptionClient_
.createEncryptingStream(manager, new ByteArrayInputStream(new byte[1024 * 1024]))
.read());
}
@Test
public void whenCustomCMMUsesCommittingAlgorithmWithForbidPolicy_throws() throws Exception {
CryptoMaterialsManager manager =
new CryptoMaterialsManager() {
@Override
public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) {
EncryptionMaterials encryptionMaterials =
new DefaultCryptoMaterialsManager(masterKeyProvider)
.getMaterialsForEncrypt(request);
return encryptionMaterials.toBuilder()
.setAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384)
.build();
}
@Override
public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) {
return new DefaultCryptoMaterialsManager(masterKeyProvider).decryptMaterials(request);
}
};
// create client with null encryption algorithm and ForbidEncrypt policy
final AwsCrypto client =
AwsCrypto.builder()
.withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt)
.build();
byte[] plaintext = new byte[100];
assertThrows(AwsCryptoException.class, () -> client.encryptData(manager, plaintext));
assertThrows(AwsCryptoException.class, () -> client.estimateCiphertextSize(manager, 12345));
assertThrows(
AwsCryptoException.class,
() -> client.createEncryptingStream(manager, new ByteArrayOutputStream()).write(0));
assertThrows(
AwsCryptoException.class,
() ->
client
.createEncryptingStream(manager, new ByteArrayInputStream(new byte[1024 * 1024]))
.read());
}
@Test
public void whenDecrypting_invokesMKPOnce() throws Exception {
byte[] data = encryptionClient_.encryptData(masterKeyProvider, new byte[1]).getResult();
reset(masterKeyProvider);
encryptionClient_.decryptData(masterKeyProvider, data);
verify(masterKeyProvider, times(1)).decryptDataKey(any(), any(), any());
}
private void doEstimateCiphertextSize(
final CryptoAlgorithm cryptoAlg, final int inLen, final int frameSize) {
final byte[] plaintext = TestIOUtils.generateRandomPlaintext(inLen);
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC1", "Ciphertext size estimation test with " + inLen);
AwsCrypto client = cryptoAlg.isCommitting() ? encryptionClient_ : forbidCommitmentClient_;
client.setEncryptionAlgorithm(cryptoAlg);
client.setEncryptionFrameSize(frameSize);
final long estimatedCiphertextSize =
client.estimateCiphertextSize(masterKeyProvider, inLen, encryptionContext);
final byte[] cipherText =
client.encryptData(masterKeyProvider, plaintext, encryptionContext).getResult();
// The estimate should be close (within 16 bytes) and never less than reality
final String errMsg =
"Bad estimation for "
+ cryptoAlg
+ " expected: <"
+ estimatedCiphertextSize
+ "> but was: <"
+ cipherText.length
+ ">";
assertTrue(errMsg, estimatedCiphertextSize - cipherText.length >= 0);
assertTrue(errMsg, estimatedCiphertextSize - cipherText.length <= 16);
}
@Test
public void estimateCiphertextSize() {
for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) {
// Only test with crypto algs without commitment, since those
// are the only ones we can encrypt with
if (cryptoAlg.getMessageFormatVersion() != 1) {
continue;
}
final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg);
for (int i = 0; i < frameSizeToTest.length; i++) {
final int frameSize = frameSizeToTest[i];
int[] bytesToTest = {
0,
1,
frameSize - 1,
frameSize,
frameSize + 1,
(int) (frameSize * 1.5),
frameSize * 2,
1000000
};
for (int j = 0; j < bytesToTest.length; j++) {
final int byteSize = bytesToTest[j];
if (byteSize > 500_000 && isFastTestSuiteActive()) {
continue;
}
if (byteSize >= 0) {
doEstimateCiphertextSize(cryptoAlg, byteSize, frameSize);
}
}
}
}
}
@Test
public void estimateCiphertextSizeWithoutEncContext() {
final int inLen = 1000000;
final byte[] plaintext = TestIOUtils.generateRandomPlaintext(inLen);
encryptionClient_.setEncryptionFrameSize(AwsCrypto.getDefaultFrameSize());
final long estimatedCiphertextSize =
encryptionClient_.estimateCiphertextSize(masterKeyProvider, inLen);
final byte[] cipherText =
encryptionClient_.encryptData(masterKeyProvider, plaintext).getResult();
final String errMsg =
"Bad estimation expected: <"
+ estimatedCiphertextSize
+ "> but was: <"
+ cipherText.length
+ ">";
assertTrue(errMsg, estimatedCiphertextSize - cipherText.length >= 0);
assertTrue(errMsg, estimatedCiphertextSize - cipherText.length <= 16);
}
@Test
public void estimateCiphertextSize_usesCachedKeys() throws Exception {
// Make sure estimateCiphertextSize works with cached CMMs
CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(masterKeyProvider));
CachingCryptoMaterialsManager cache =
CachingCryptoMaterialsManager.newBuilder()
.withBackingMaterialsManager(cmm)
.withMaxAge(Long.MAX_VALUE, TimeUnit.SECONDS)
.withCache(new LocalCryptoMaterialsCache(1))
.withMessageUseLimit(9999)
.withByteUseLimit(501)
.build();
// These estimates should be cached, and should not consume any bytes from the byte use limit.
encryptionClient_.estimateCiphertextSize(cache, 500, new HashMap<>());
encryptionClient_.estimateCiphertextSize(cache, 500, new HashMap<>());
encryptionClient_.encryptData(cache, new byte[500]);
verify(cmm, times(1)).getMaterialsForEncrypt(any());
}
@Test
public void encryptDecryptWithoutEncContext() {
final int ptSize = 1000000; // 1MB
final byte[] plaintextBytes = TestIOUtils.generateRandomPlaintext(ptSize);
final byte[] cipherText =
encryptionClient_.encryptData(masterKeyProvider, plaintextBytes).getResult();
final byte[] decryptedText =
encryptionClient_.decryptData(masterKeyProvider, cipherText).getResult();
assertArrayEquals(plaintextBytes, decryptedText);
}
@Test
public void encryptDecryptString() {
final int ptSize = 1000000; // 1MB
final String plaintextString = TestIOUtils.generateRandomString(ptSize);
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC1", "Test Encryption Context");
final String ciphertext =
encryptionClient_
.encryptString(masterKeyProvider, plaintextString, encryptionContext)
.getResult();
final String decryptedText =
encryptionClient_.decryptString(masterKeyProvider, ciphertext).getResult();
assertEquals(plaintextString, decryptedText);
}
@Test
public void encryptDecryptStringWithoutEncContext() {
final int ptSize = 1000000; // 1MB
final String plaintextString = TestIOUtils.generateRandomString(ptSize);
final String cipherText =
encryptionClient_.encryptString(masterKeyProvider, plaintextString).getResult();
final String decryptedText =
encryptionClient_.decryptString(masterKeyProvider, cipherText).getResult();
assertEquals(plaintextString, decryptedText);
}
@Test
public void encryptBytesDecryptString() {
final int ptSize = 1000000; // 1MB
final String plaintext = TestIOUtils.generateRandomString(ptSize);
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC1", "Test Encryption Context");
final byte[] cipherText =
encryptionClient_
.encryptData(
masterKeyProvider, plaintext.getBytes(StandardCharsets.UTF_8), encryptionContext)
.getResult();
final String decryptedText =
encryptionClient_
.decryptString(masterKeyProvider, Utils.encodeBase64String(cipherText))
.getResult();
assertEquals(plaintext, decryptedText);
}
@Test
public void encryptStringDecryptBytes() {
final int ptSize = 1000000; // 1MB
final byte[] plaintextBytes = TestIOUtils.generateRandomPlaintext(ptSize);
final String plaintextString = new String(plaintextBytes, StandardCharsets.UTF_8);
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC1", "Test Encryption Context");
final String ciphertext =
encryptionClient_
.encryptString(masterKeyProvider, plaintextString, encryptionContext)
.getResult();
final byte[] decryptedText =
encryptionClient_
.decryptData(masterKeyProvider, Utils.decodeBase64String(ciphertext))
.getResult();
assertArrayEquals(plaintextString.getBytes(StandardCharsets.UTF_8), decryptedText);
}
@Test
public void emptyEncryptionContext() {
final int ptSize = 1000000; // 1MB
final byte[] plaintextBytes = TestIOUtils.generateRandomPlaintext(ptSize);
final Map<String, String> encryptionContext = new HashMap<String, String>(0);
final byte[] cipherText =
encryptionClient_
.encryptData(masterKeyProvider, plaintextBytes, encryptionContext)
.getResult();
final byte[] decryptedText =
encryptionClient_.decryptData(masterKeyProvider, cipherText).getResult();
assertArrayEquals(plaintextBytes, decryptedText);
}
@Test
public void decryptMessageWithKeyCommitment() {
final byte[] cipherText = Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64);
JceMasterKey masterKey = TestUtils.messageWithCommitKeyMasterKey;
final CryptoResult decryptedText = encryptionClient_.decryptData(masterKey, cipherText);
assertEquals(TestUtils.messageWithCommitKeyCryptoAlgorithm, decryptedText.getCryptoAlgorithm());
assertArrayEquals(
Utils.decodeBase64String(TestUtils.messageWithCommitKeyMessageIdBase64),
decryptedText.getHeaders().getMessageId());
assertArrayEquals(
Utils.decodeBase64String(TestUtils.messageWithCommitKeyCommitmentBase64),
decryptedText.getHeaders().getSuiteData());
assertArrayEquals(
TestUtils.messageWithCommitKeyExpectedResult.getBytes(),
(byte[]) decryptedText.getResult());
}
@Test
public void decryptMessageWithInvalidKeyCommitment() {
final byte[] cipherText = Utils.decodeBase64String(TestUtils.invalidMessageWithCommitKeyBase64);
JceMasterKey masterKey = TestUtils.invalidMessageWithCommitKeyMasterKey;
assertThrows(
BadCiphertextException.class,
"Key commitment validation failed. Key identity does not "
+ "match the identity asserted in the message. Halting processing of this message.",
() -> encryptionClient_.decryptData(masterKey, cipherText));
}
// Test that all the parameters that aren't allowed to be null (i.e. all of them) result in
// immediate NPEs if
// invoked with null args
@Test
public void assertNullChecks() throws Exception {
byte[] buf = new byte[1];
HashMap<String, String> context = new HashMap<>();
MasterKeyProvider provider = masterKeyProvider;
CryptoMaterialsManager cmm = new DefaultCryptoMaterialsManager(masterKeyProvider);
InputStream is = new ByteArrayInputStream(new byte[0]);
OutputStream os = new ByteArrayOutputStream();
byte[] ciphertext = encryptionClient_.encryptData(cmm, buf).getResult();
String stringCiphertext = encryptionClient_.encryptString(cmm, "hello, world").getResult();
TestUtils.assertNullChecks(
encryptionClient_,
"estimateCiphertextSize",
MasterKeyProvider.class,
provider,
Integer.TYPE,
42,
Map.class,
context);
TestUtils.assertNullChecks(
encryptionClient_,
"estimateCiphertextSize",
CryptoMaterialsManager.class,
cmm,
Integer.TYPE,
42,
Map.class,
context);
TestUtils.assertNullChecks(
encryptionClient_,
"estimateCiphertextSize",
MasterKeyProvider.class,
provider,
Integer.TYPE,
42);
TestUtils.assertNullChecks(
encryptionClient_,
"estimateCiphertextSize",
CryptoMaterialsManager.class,
cmm,
Integer.TYPE,
42);
TestUtils.assertNullChecks(
encryptionClient_,
"encryptData",
MasterKeyProvider.class,
provider,
byte[].class,
buf,
Map.class,
context);
TestUtils.assertNullChecks(
encryptionClient_,
"encryptData",
CryptoMaterialsManager.class,
cmm,
byte[].class,
buf,
Map.class,
context);
TestUtils.assertNullChecks(
encryptionClient_, "encryptData", MasterKeyProvider.class, provider, byte[].class, buf);
TestUtils.assertNullChecks(
encryptionClient_, "encryptData", CryptoMaterialsManager.class, cmm, byte[].class, buf);
TestUtils.assertNullChecks(
encryptionClient_,
"encryptString",
MasterKeyProvider.class,
provider,
String.class,
"",
Map.class,
context);
TestUtils.assertNullChecks(
encryptionClient_,
"encryptString",
CryptoMaterialsManager.class,
cmm,
String.class,
"",
Map.class,
context);
TestUtils.assertNullChecks(
encryptionClient_, "encryptString", MasterKeyProvider.class, provider, String.class, "");
TestUtils.assertNullChecks(
encryptionClient_, "encryptString", CryptoMaterialsManager.class, cmm, String.class, "");
TestUtils.assertNullChecks(
encryptionClient_,
"decryptData",
MasterKeyProvider.class,
provider,
byte[].class,
ciphertext);
TestUtils.assertNullChecks(
encryptionClient_,
"decryptData",
CryptoMaterialsManager.class,
cmm,
byte[].class,
ciphertext);
TestUtils.assertNullChecks(
encryptionClient_,
"decryptData",
MasterKeyProvider.class,
provider,
ParsedCiphertext.class,
new ParsedCiphertext(ciphertext));
TestUtils.assertNullChecks(
encryptionClient_,
"decryptData",
CryptoMaterialsManager.class,
cmm,
ParsedCiphertext.class,
new ParsedCiphertext(ciphertext));
TestUtils.assertNullChecks(
encryptionClient_,
"decryptString",
MasterKeyProvider.class,
provider,
String.class,
stringCiphertext);
TestUtils.assertNullChecks(
encryptionClient_,
"decryptString",
CryptoMaterialsManager.class,
cmm,
String.class,
stringCiphertext);
TestUtils.assertNullChecks(
encryptionClient_,
"createEncryptingStream",
MasterKeyProvider.class,
provider,
OutputStream.class,
os,
Map.class,
context);
TestUtils.assertNullChecks(
encryptionClient_,
"createEncryptingStream",
CryptoMaterialsManager.class,
cmm,
OutputStream.class,
os,
Map.class,
context);
TestUtils.assertNullChecks(
encryptionClient_,
"createEncryptingStream",
MasterKeyProvider.class,
provider,
OutputStream.class,
os);
TestUtils.assertNullChecks(
encryptionClient_,
"createEncryptingStream",
CryptoMaterialsManager.class,
cmm,
OutputStream.class,
os);
TestUtils.assertNullChecks(
encryptionClient_,
"createEncryptingStream",
MasterKeyProvider.class,
provider,
InputStream.class,
is,
Map.class,
context);
TestUtils.assertNullChecks(
encryptionClient_,
"createEncryptingStream",
CryptoMaterialsManager.class,
cmm,
InputStream.class,
is,
Map.class,
context);
TestUtils.assertNullChecks(
encryptionClient_,
"createEncryptingStream",
MasterKeyProvider.class,
provider,
InputStream.class,
is);
TestUtils.assertNullChecks(
encryptionClient_,
"createEncryptingStream",
CryptoMaterialsManager.class,
cmm,
InputStream.class,
is);
TestUtils.assertNullChecks(
encryptionClient_,
"createDecryptingStream",
MasterKeyProvider.class,
provider,
OutputStream.class,
os);
TestUtils.assertNullChecks(
encryptionClient_,
"createDecryptingStream",
CryptoMaterialsManager.class,
cmm,
OutputStream.class,
os);
TestUtils.assertNullChecks(
encryptionClient_,
"createDecryptingStream",
MasterKeyProvider.class,
provider,
InputStream.class,
is);
TestUtils.assertNullChecks(
encryptionClient_,
"createDecryptingStream",
CryptoMaterialsManager.class,
cmm,
InputStream.class,
is);
}
@Test
public void setValidFrameSize() throws IOException {
final int setFrameSize = TestUtils.DEFAULT_TEST_CRYPTO_ALG.getBlockSize() * 2;
encryptionClient_.setEncryptionFrameSize(setFrameSize);
final int getFrameSize = encryptionClient_.getEncryptionFrameSize();
assertEquals(setFrameSize, getFrameSize);
}
@Test
public void unalignedFrameSizesAreAccepted() throws IOException {
final int frameSize = TestUtils.DEFAULT_TEST_CRYPTO_ALG.getBlockSize() - 1;
encryptionClient_.setEncryptionFrameSize(frameSize);
assertEquals(frameSize, encryptionClient_.getEncryptionFrameSize());
}
@Test(expected = IllegalArgumentException.class)
public void setNegativeFrameSize() throws IOException {
encryptionClient_.setEncryptionFrameSize(-1);
}
@Test
public void setCryptoAlgorithm() throws IOException {
final CryptoAlgorithm setCryptoAlgorithm =
CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY;
encryptionClient_.setEncryptionAlgorithm(setCryptoAlgorithm);
final CryptoAlgorithm getCryptoAlgorithm = encryptionClient_.getEncryptionAlgorithm();
assertEquals(setCryptoAlgorithm, getCryptoAlgorithm);
}
@Test(expected = NullPointerException.class)
public void buildWithNullCommitmentPolicy() throws IOException {
AwsCrypto.builder().withCommitmentPolicy(null).build();
}
@Test
public void forbidAndSetCommittingCryptoAlgorithm() throws IOException {
final CryptoAlgorithm setCryptoAlgorithm =
CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY;
assertThrows(
AwsCryptoException.class,
() ->
AwsCrypto.builder()
.withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt)
.build()
.setEncryptionAlgorithm(setCryptoAlgorithm));
}
@Test
public void requireAndSetNonCommittingCryptoAlgorithm() throws IOException {
final CryptoAlgorithm setCryptoAlgorithm =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384;
// Default case
assertThrows(
AwsCryptoException.class,
() -> AwsCrypto.standard().setEncryptionAlgorithm(setCryptoAlgorithm));
// Test explicitly for every relevant policy
for (CommitmentPolicy policy : requireWriteCommitmentPolicies) {
assertThrows(
AwsCryptoException.class,
() ->
AwsCrypto.builder()
.withCommitmentPolicy(policy)
.build()
.setEncryptionAlgorithm(setCryptoAlgorithm));
}
}
@Test
public void forbidAndBuildWithCommittingCryptoAlgorithm() throws IOException {
final CryptoAlgorithm setCryptoAlgorithm =
CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY;
assertThrows(
AwsCryptoException.class,
() ->
AwsCrypto.builder()
.withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt)
.withEncryptionAlgorithm(setCryptoAlgorithm)
.build());
}
@Test
public void requireAndBuildWithNonCommittingCryptoAlgorithm() throws IOException {
final CryptoAlgorithm setCryptoAlgorithm =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384;
// Test default case
assertThrows(
AwsCryptoException.class,
() -> AwsCrypto.builder().withEncryptionAlgorithm(setCryptoAlgorithm).build());
// Test explicitly for every relevant policy
for (CommitmentPolicy policy : requireWriteCommitmentPolicies) {
assertThrows(
AwsCryptoException.class,
() ->
AwsCrypto.builder()
.withCommitmentPolicy(policy)
.withEncryptionAlgorithm(setCryptoAlgorithm)
.build());
}
}
@Test
public void requireCommitmentOnDecryptFailsNonCommitting() throws IOException {
// Create non-committing ciphertext
forbidCommitmentClient_.setEncryptionAlgorithm(
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384);
final byte[] cipherText =
forbidCommitmentClient_
.encryptData(masterKeyProvider, new byte[1], new HashMap<>())
.getResult();
// Test explicit policy set
assertThrows(
AwsCryptoException.class,
() ->
AwsCrypto.builder()
.withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt)
.build()
.decryptData(masterKeyProvider, cipherText));
// Test default builder behavior
assertThrows(
AwsCryptoException.class,
() -> AwsCrypto.builder().build().decryptData(masterKeyProvider, cipherText));
// Test input stream
assertThrows(
AwsCryptoException.class,
() ->
AwsCrypto.builder()
.build()
.createDecryptingStream(masterKeyProvider, new ByteArrayInputStream(cipherText))
.read());
// Test output stream
assertThrows(
AwsCryptoException.class,
() ->
AwsCrypto.builder()
.build()
.createDecryptingStream(masterKeyProvider, new ByteArrayOutputStream())
.write(cipherText));
}
@Test
public void whenCustomCMMUsesNonCommittingAlgorithmWithRequirePolicy_throws() throws Exception {
CryptoMaterialsManager manager =
new CryptoMaterialsManager() {
@Override
public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) {
EncryptionMaterials encryptionMaterials =
new DefaultCryptoMaterialsManager(masterKeyProvider)
.getMaterialsForEncrypt(request);
return encryptionMaterials.toBuilder()
.setAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384)
.build();
}
@Override
public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) {
return new DefaultCryptoMaterialsManager(masterKeyProvider).decryptMaterials(request);
}
};
for (CommitmentPolicy policy : requireWriteCommitmentPolicies) {
// create client with null encryption algorithm and a policy that requires encryption
final AwsCrypto client = AwsCrypto.builder().withCommitmentPolicy(policy).build();
byte[] plaintext = new byte[100];
assertThrows(AwsCryptoException.class, () -> client.encryptData(manager, plaintext));
assertThrows(AwsCryptoException.class, () -> client.estimateCiphertextSize(manager, 12345));
assertThrows(
AwsCryptoException.class,
() -> client.createEncryptingStream(manager, new ByteArrayOutputStream()).write(0));
assertThrows(
AwsCryptoException.class,
() ->
client
.createEncryptingStream(manager, new ByteArrayInputStream(new byte[1024 * 1024]))
.read());
}
}
@Test
public void testDecryptMessageWithInvalidCommitment() {
for (final CryptoAlgorithm cryptoAlg : CryptoAlgorithm.values()) {
if (!cryptoAlg.isCommitting()) {
continue;
}
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("Commitment", "Commitment test for %s" + cryptoAlg);
encryptionClient_.setEncryptionAlgorithm(cryptoAlg);
byte[] plaintextBytes = new byte[16]; // Actual content doesn't matter
final byte[] cipherText =
encryptionClient_
.encryptData(masterKeyProvider, plaintextBytes, encryptionContext)
.getResult();
// Find the commitment value
ParsedCiphertext parsed = new ParsedCiphertext(cipherText);
final int headerLength = parsed.getOffset();
// The commitment value is immediately prior to the header tag for v2 encrypted messages
final int endOfCommitment = headerLength - parsed.getHeaderTag().length;
// The commitment is 32 bytes long, but if we just index one back from the endOfCommitment we
// know
// that we are within it.
cipherText[endOfCommitment - 1] ^= 0x01; // Tamper with the commitment value
// Since commitment is verified prior to the header tag, we don't need to worry about actually
// creating a colliding tag but can just verify that the exception indicates an incorrect
// commitment
// value.
assertThrows(
BadCiphertextException.class,
"Key commitment validation failed. Key identity does "
+ "not match the identity asserted in the message. Halting processing of this message.",
() -> encryptionClient_.decryptData(masterKeyProvider, cipherText));
}
}
@Test(expected = IllegalArgumentException.class)
public void setNegativeMaxEdks() {
AwsCrypto.builder().withMaxEncryptedDataKeys(-1);
}
@Test(expected = IllegalArgumentException.class)
public void setZeroMaxEdks() {
AwsCrypto.builder().withMaxEncryptedDataKeys(0);
}
@Test
public void setValidMaxEdks() {
for (final int i :
new int[] {
1, 10, MESSAGE_FORMAT_MAX_EDKS, MESSAGE_FORMAT_MAX_EDKS + 1, Integer.MAX_VALUE
}) {
AwsCrypto.builder().withMaxEncryptedDataKeys(i);
}
}
private MasterKeyProvider<?> providerWithEdks(int numEdks) {
List<MasterKeyProvider<?>> providers = new ArrayList<>();
for (int i = 0; i < numEdks; i++) {
providers.add(masterKeyProvider);
}
return MultipleProviderFactory.buildMultiProvider(providers);
}
@Test
public void encryptDecryptWithLessThanMaxEdks() {
MasterKeyProvider<?> provider = providerWithEdks(2);
CryptoResult<byte[], ?> result = maxEdksClient_.encryptData(provider, new byte[] {1});
ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult());
assertEquals(ciphertext.getEncryptedKeyBlobCount(), 2);
maxEdksClient_.decryptData(provider, ciphertext);
}
@Test
public void encryptDecryptWithMaxEdks() {
MasterKeyProvider<?> provider = providerWithEdks(3);
CryptoResult<byte[], ?> result = maxEdksClient_.encryptData(provider, new byte[] {1});
ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult());
assertEquals(ciphertext.getEncryptedKeyBlobCount(), 3);
maxEdksClient_.decryptData(provider, ciphertext);
}
@Test
public void noEncryptWithMoreThanMaxEdks() {
MasterKeyProvider<?> provider = providerWithEdks(4);
assertThrows(
AwsCryptoException.class,
"Encrypted data keys exceed maxEncryptedDataKeys",
() -> maxEdksClient_.encryptData(provider, new byte[] {1}));
}
@Test
public void noDecryptWithMoreThanMaxEdks() {
MasterKeyProvider<?> provider = providerWithEdks(4);
CryptoResult<byte[], ?> result = noMaxEdksClient_.encryptData(provider, new byte[] {1});
ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult());
assertThrows(
AwsCryptoException.class,
"Ciphertext encrypted data keys exceed maxEncryptedDataKeys",
() -> maxEdksClient_.decryptData(provider, ciphertext));
}
@Test
public void encryptDecryptWithNoMaxEdks() {
MasterKeyProvider<?> provider = providerWithEdks(MESSAGE_FORMAT_MAX_EDKS);
CryptoResult<byte[], ?> result = noMaxEdksClient_.encryptData(provider, new byte[] {1});
ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult());
assertEquals(ciphertext.getEncryptedKeyBlobCount(), MESSAGE_FORMAT_MAX_EDKS);
noMaxEdksClient_.decryptData(provider, ciphertext);
}
@Test
public void encryptDecryptStreamWithLessThanMaxEdks() throws IOException {
MasterKeyProvider<?> provider = providerWithEdks(2);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
CryptoOutputStream<?> encryptStream =
maxEdksClient_.createEncryptingStream(provider, byteArrayOutputStream);
IOUtils.copy(new ByteArrayInputStream(new byte[] {1}), encryptStream);
encryptStream.close();
byte[] ciphertext = byteArrayOutputStream.toByteArray();
assertEquals(new ParsedCiphertext(ciphertext).getEncryptedKeyBlobCount(), 2);
byteArrayOutputStream.reset();
CryptoOutputStream<?> decryptStream =
maxEdksClient_.createDecryptingStream(provider, byteArrayOutputStream);
IOUtils.copy(new ByteArrayInputStream(ciphertext), decryptStream);
decryptStream.close();
}
@Test
public void encryptDecryptStreamWithMaxEdks() throws IOException {
MasterKeyProvider<?> provider = providerWithEdks(3);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
CryptoOutputStream<?> encryptStream =
maxEdksClient_.createEncryptingStream(provider, byteArrayOutputStream);
IOUtils.copy(new ByteArrayInputStream(new byte[] {1}), encryptStream);
encryptStream.close();
byte[] ciphertext = byteArrayOutputStream.toByteArray();
assertEquals(new ParsedCiphertext(ciphertext).getEncryptedKeyBlobCount(), 3);
byteArrayOutputStream.reset();
CryptoOutputStream<?> decryptStream =
maxEdksClient_.createDecryptingStream(provider, byteArrayOutputStream);
IOUtils.copy(new ByteArrayInputStream(ciphertext), decryptStream);
decryptStream.close();
}
@Test
public void noEncryptStreamWithMoreThanMaxEdks() {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
CryptoOutputStream<?> encryptStream =
maxEdksClient_.createEncryptingStream(providerWithEdks(4), byteArrayOutputStream);
assertThrows(
AwsCryptoException.class,
"Encrypted data keys exceed maxEncryptedDataKeys",
() -> IOUtils.copy(new ByteArrayInputStream(new byte[] {1}), encryptStream));
}
@Test
public void noDecryptStreamWithMoreThanMaxEdks() throws IOException {
MasterKeyProvider<?> provider = providerWithEdks(4);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
CryptoOutputStream<?> encryptStream =
noMaxEdksClient_.createEncryptingStream(provider, byteArrayOutputStream);
IOUtils.copy(new ByteArrayInputStream(new byte[] {1}), encryptStream);
encryptStream.close();
byte[] ciphertext = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.reset();
CryptoOutputStream<?> decryptStream =
maxEdksClient_.createDecryptingStream(provider, byteArrayOutputStream);
assertThrows(
AwsCryptoException.class,
"Ciphertext encrypted data keys exceed maxEncryptedDataKeys",
() -> IOUtils.copy(new ByteArrayInputStream(ciphertext), decryptStream));
}
@Test
public void encryptDecryptStreamWithNoMaxEdks() throws IOException {
MasterKeyProvider<?> provider = providerWithEdks(MESSAGE_FORMAT_MAX_EDKS);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
CryptoOutputStream<?> encryptStream =
noMaxEdksClient_.createEncryptingStream(provider, byteArrayOutputStream);
IOUtils.copy(new ByteArrayInputStream(new byte[] {1}), encryptStream);
encryptStream.close();
byte[] ciphertext = byteArrayOutputStream.toByteArray();
assertEquals(
new ParsedCiphertext(ciphertext).getEncryptedKeyBlobCount(), MESSAGE_FORMAT_MAX_EDKS);
byteArrayOutputStream.reset();
CryptoOutputStream<?> decryptStream =
noMaxEdksClient_.createDecryptingStream(provider, byteArrayOutputStream);
IOUtils.copy(new ByteArrayInputStream(ciphertext), decryptStream);
decryptStream.close();
}
}
| 5,353 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/TestUtils.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import static java.lang.String.format;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.amazonaws.encryptionsdk.jce.JceMasterKey;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicReference;
import javax.crypto.spec.SecretKeySpec;
public class TestUtils {
public static final CryptoAlgorithm DEFAULT_TEST_CRYPTO_ALG =
CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384;
public static final CommitmentPolicy DEFAULT_TEST_COMMITMENT_POLICY =
CommitmentPolicy.RequireEncryptRequireDecrypt;
// Handcrafted message for testing decryption of messages with committed keys
public static final String messageWithCommitKeyBase64 =
"AgR4TfvRMU2dVZJbgXIyxeNtbj"
+ "5eIw8BiTDiwsHyQ/Z9wXkAAAABAAxQcm92aWRlck5hbWUAGUtleUlkAAAAgAAAAAz45sc3cDvJZ7D4P3sAM"
+ "KE7d/w8ziQt2C0qHsy1Qu2E2q92eIGE/kLnF/Y003HKvTxx7xv2Zv83YuOdwHML5QIAABAAF88I9zPbUQSf"
+ "OlzLXv+uIY2+m/E6j2PMsbgeHVH/L0wLqQlY+5CL0z3xnNOMIZae/////wAAAAEAAAAAAAAAAAAAAAEAAAA"
+ "OSZBKHHRpTwXOFTQVGapXXj5CwXBMouBB2ucaIJVm";
public static final JceMasterKey messageWithCommitKeyMasterKey =
JceMasterKey.getInstance(
new SecretKeySpec(new byte[32], "AES"), "ProviderName", "KeyId", "AES/GCM/NoPadding");
public static final String messageWithCommitKeyMessageIdBase64 =
"TfvRMU2dVZJbgXIyxeNtbj5eIw8BiTDiwsHyQ/Z9wXk=";
public static final String messageWithCommitKeyCommitmentBase64 =
"F88I9zPbUQSfOlzLXv+uIY2+m/E6j2PMsbgeHVH/L0w=";
public static final String messageWithCommitKeyDEKBase64 =
"+p6+whPVw9kOrYLZFMRBJ2n6Vli6T/7TkjDouS+25s0=";
public static final CryptoAlgorithm messageWithCommitKeyCryptoAlgorithm =
CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY;
public static final String messageWithCommitKeyExpectedResult = "GoodCommitment";
// Handcrafted message for testing decryption of messages with invalid committed keys
public static final String invalidMessageWithCommitKeyBase64 =
"AgR4b1/73X5ErILpj0aSQIx6wNnH"
+ "LEcNLxPzA0m6vYRr7kAAAAABAAxQcm92aWRlck5hbWUAGUtleUlkAAAAgAAAAAypJmXwyizUr3/pyvIAMHL"
+ "U/i5GhZlGayeYC5w/CjUobyGwN4QpeMB0XpNDGTM0f1Zx72V4uM2H5wMjy/hm2wIAABAAAAECAwQFBgcICQ"
+ "oLDA0ODxAREhMUFRYXGBkaGxwdHh/pQM2VSvliz2Qgi5JZf2ta/////wAAAAEAAAAAAAAAAAAAAAEAAAANS"
+ "4Id4+dVHhPrvuJHEiOswo6YGSRjSGX3VDrt+0s=";
public static final JceMasterKey invalidMessageWithCommitKeyMasterKey =
JceMasterKey.getInstance(
new SecretKeySpec(new byte[32], "AES"), "ProviderName", "KeyId", "AES/GCM/NoPadding");
// avoid spending time generating random data on every test case by caching some random test
// vectors
private static final AtomicReference<byte[]> RANDOM_CACHE = new AtomicReference<>(new byte[0]);
private static byte[] ensureRandomCached(int length) {
byte[] buf = RANDOM_CACHE.get();
if (buf.length >= length) {
return buf;
}
byte[] newBuf = new byte[length];
ThreadLocalRandom.current().nextBytes(newBuf);
return RANDOM_CACHE.updateAndGet(
oldBuf -> {
if (oldBuf.length < newBuf.length) {
return newBuf;
} else {
return oldBuf;
}
});
}
@FunctionalInterface
public interface ThrowingRunnable {
void run() throws Throwable;
}
public static void assertThrows(
Class<? extends Throwable> throwableClass, ThrowingRunnable callback) {
try {
callback.run();
} catch (Throwable t) {
if (throwableClass.isAssignableFrom(t.getClass())) {
// ok
return;
}
}
fail("Expected exception of type " + throwableClass);
}
/**
* Asserts that calling {@code callback} results in a {@code throwableClass} (or sub-class) being
* thrown which has {@link Throwable#getMessage()} containing {@code message}.
*/
public static void assertThrows(
Class<? extends Throwable> throwableClass, String message, ThrowingRunnable callback) {
try {
callback.run();
fail("Expected exception of type " + throwableClass);
} catch (Throwable t) {
assertTrue(
format("Exception of wrong type. Was %s but expected %s", t.getClass(), throwableClass),
throwableClass.isAssignableFrom(t.getClass()));
assertTrue(
format(
"Exception did not contain the expected message. Actual: \"%s\" did not contain \"%s\"",
t.getMessage(), message),
t.getMessage().contains(message));
}
}
public static void assertThrows(ThrowingRunnable callback) {
assertThrows(Throwable.class, callback);
}
/**
* Asserts that substituting any argument with null causes a NPE to be thrown.
*
* <p>Usage:
*
* <pre>{@code
* assertNullChecks(
* myAwsCrypto,
* "createDecryptingStream",
* CryptoMaterialsManager.class, myCMM,
* InputStream.class, myIS
* );
* }</pre>
*
* @param callee
* @param methodName
* @param args
* @throws Exception
*/
public static void assertNullChecks(
Object callee,
String methodName,
// Class, value
Object... args)
throws Exception {
ArrayList<Class> parameterTypes = new ArrayList<>();
for (int i = 0; i < args.length; i += 2) {
parameterTypes.add((Class) args[i]);
}
Method m = callee.getClass().getMethod(methodName, parameterTypes.toArray(new Class[0]));
for (int i = 0; i < args.length / 2; i++) {
if (args[i * 2 + 1] == null) {
// already null, which means null is ok here
continue;
}
if (parameterTypes.get(i).isPrimitive()) {
// can't be null
continue;
}
Object[] modifiedArgs = new Object[args.length / 2];
for (int j = 0; j < args.length / 2; j++) {
modifiedArgs[j] = args[j * 2 + 1];
if (j == i) {
modifiedArgs[j] = null;
}
}
try {
m.invoke(callee, modifiedArgs);
fail("Expected NullPointerException");
} catch (InvocationTargetException e) {
if (e.getCause().getClass() == NullPointerException.class) {
continue;
}
fail("Expected NullPointerException, got: " + e.getCause());
}
}
}
public static byte[] toByteArray(InputStream is) throws IOException {
byte[] buffer = new byte[4096];
int offset = 0;
int rv;
while (true) {
rv = is.read(buffer, offset, buffer.length - offset);
if (rv <= 0) {
break;
}
offset += rv;
if (offset == buffer.length) {
if (buffer.length == Integer.MAX_VALUE) {
throw new IOException("Input data exceeds maximum array size");
}
int newSize = Math.toIntExact(Math.min(Integer.MAX_VALUE, 2L * buffer.length));
byte[] newBuffer = new byte[newSize];
System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
buffer = newBuffer;
}
}
return Arrays.copyOfRange(buffer, 0, offset);
}
public static byte[] insecureRandomBytes(int length) {
byte[] buf = new byte[length];
System.arraycopy(ensureRandomCached(length), 0, buf, 0, length);
return buf;
}
public static ByteArrayInputStream insecureRandomStream(int length) {
return new ByteArrayInputStream(ensureRandomCached(length), 0, length);
}
public static int[] getFrameSizesToTest(final CryptoAlgorithm cryptoAlg) {
final int blockSize = cryptoAlg.getBlockSize();
final int[] frameSizeToTest = {
0,
blockSize - 1,
blockSize,
blockSize + 1,
blockSize * 2,
blockSize * 10,
blockSize * 10 + 1,
AwsCrypto.getDefaultFrameSize()
};
return frameSizeToTest;
}
/**
* Converts an array of unsigned bytes (represented as int values between 0 and 255 inclusive) to
* an array of Java primitive type byte, which are by definition signed.
*
* @param unsignedBytes An array on unsigned bytes
* @return An array of signed bytes
*/
public static byte[] unsignedBytesToSignedBytes(final int[] unsignedBytes) {
byte[] signedBytes = new byte[unsignedBytes.length];
for (int i = 0; i < unsignedBytes.length; i++) {
if (unsignedBytes[i] > 255) {
throw new IllegalArgumentException("Encountered unsigned byte value > 255");
}
signedBytes[i] = (byte) (unsignedBytes[i] & 0xff);
}
return signedBytes;
}
/**
* Converts an array of Java primitive type bytes (which are by definition signed) to an array of
* unsigned bytes (represented as int values between 0 and 255 inclusive).
*
* @param signedBytes An array of signed bytes
* @return An array of unsigned bytes
*/
public static int[] signedBytesToUnsignedBytes(final byte[] signedBytes) {
int[] unsignedBytes = new int[signedBytes.length];
for (int i = 0; i < signedBytes.length; i++) {
unsignedBytes[i] = ((int) signedBytes[i]) & 0xff;
}
return unsignedBytes;
}
}
| 5,354 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/IntegrationTestSuite.java | package com.amazonaws.encryptionsdk;
import com.amazonaws.encryptionsdk.kms.KMSProviderBuilderIntegrationTests;
import com.amazonaws.encryptionsdk.kms.MaxEncryptedDataKeysIntegrationTest;
import com.amazonaws.encryptionsdk.kms.XCompatKmsDecryptTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
XCompatKmsDecryptTest.class,
KMSProviderBuilderIntegrationTests.class,
MaxEncryptedDataKeysIntegrationTest.class,
com.amazonaws.encryptionsdk.kms.KMSProviderBuilderIntegrationTests.class,
com.amazonaws.encryptionsdk.kms.MaxEncryptedDataKeysIntegrationTest.class,
com.amazonaws.encryptionsdk.kms.XCompatKmsDecryptTest.class
})
public class IntegrationTestSuite {}
| 5,355 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/SlowTestCategory.java | package com.amazonaws.encryptionsdk;
/**
* JUnit category marking tests to be excluded from the FastTestsOnlySuite. Usage: <code>
* @Category(SlowTestCategory.class)
* @Test
* public void mySlowTest() {
* // encrypt a couple terabytes of test data
* }
* </code>
*/
public interface SlowTestCategory {}
| 5,356 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/CryptoAlgorithmTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import com.amazonaws.encryptionsdk.exception.BadCiphertextException;
import com.amazonaws.encryptionsdk.internal.EncryptionHandler;
import com.amazonaws.encryptionsdk.internal.StaticMasterKey;
import com.amazonaws.encryptionsdk.internal.Utils;
import com.amazonaws.encryptionsdk.model.CiphertextHeaders;
import com.amazonaws.encryptionsdk.model.EncryptionMaterials;
import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest;
import java.security.InvalidKeyException;
import java.util.Collections;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
public class CryptoAlgorithmTest {
@Test
public void testDeserialization() {
for (CryptoAlgorithm algorithm : CryptoAlgorithm.values()) {
assertEquals(
algorithm.toString(),
algorithm,
CryptoAlgorithm.deserialize(algorithm.getMessageFormatVersion(), algorithm.getValue()));
}
}
@Test
public void testGetCommittedEncryptionKey() throws InvalidKeyException {
CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm;
SecretKeySpec secretKey =
new SecretKeySpec(
Utils.decodeBase64String(TestUtils.messageWithCommitKeyDEKBase64),
algorithm.getDataKeyAlgo());
CiphertextHeaders headers =
new ParsedCiphertext(Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64));
SecretKey key = algorithm.getEncryptionKeyFromDataKey(secretKey, headers);
assertNotNull(key);
assertEquals(algorithm.getKeyAlgo(), key.getAlgorithm());
}
@Test
public void testGetCommittedEncryptionKeyIncorrectCommitment() throws InvalidKeyException {
CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm;
SecretKeySpec secretKey =
new SecretKeySpec(
Utils.decodeBase64String(TestUtils.messageWithCommitKeyDEKBase64),
algorithm.getDataKeyAlgo());
CiphertextHeaders headers =
new ParsedCiphertext(Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64));
// Set header to an incorrect commitment value
headers.setSuiteData(new byte[algorithm.getSuiteDataLength()]);
assertThrows(
BadCiphertextException.class,
"Key commitment validation failed. Key identity does not match the "
+ "identity asserted in the message. Halting processing of this message.",
() -> algorithm.getEncryptionKeyFromDataKey(secretKey, headers));
}
@Test
public void testGetCommittedEncryptionKeyIncorrectKeySpecAlgorithm() throws InvalidKeyException {
CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm;
SecretKeySpec secretKey =
new SecretKeySpec(new byte[algorithm.getDataKeyLength()], "incorrectAlgorithm");
CiphertextHeaders headers =
new ParsedCiphertext(Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64));
assertThrows(
InvalidKeyException.class,
"DataKey of incorrect algorithm.",
() -> algorithm.getEncryptionKeyFromDataKey(secretKey, headers));
}
@Test
public void testGetCommittedEncryptionKeyIncorrectLength() throws InvalidKeyException {
CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm;
SecretKeySpec secretKey = new SecretKeySpec(new byte[1], "HkdfSHA512");
CiphertextHeaders headers =
new ParsedCiphertext(Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64));
assertThrows(
IllegalArgumentException.class,
"DataKey of incorrect length.",
() -> algorithm.getEncryptionKeyFromDataKey(secretKey, headers));
}
@Test
public void testGetUnCommittedEncryptionKey() throws InvalidKeyException {
CryptoAlgorithm algo = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
SecretKeySpec secretKey =
new SecretKeySpec(new byte[algo.getDataKeyLength()], algo.getDataKeyAlgo());
CiphertextHeaders headers = getTestHeaders(algo);
SecretKey key = algo.getEncryptionKeyFromDataKey(secretKey, headers);
assertNotNull(key);
assertEquals(algo.getKeyAlgo(), key.getAlgorithm());
}
@Test
public void testGetUnCommittedEncryptionKeyFromDataKeyIncorrectKeySpecAlgorithm()
throws InvalidKeyException {
CryptoAlgorithm algo = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
SecretKeySpec secretKey =
new SecretKeySpec(new byte[algo.getDataKeyLength()], "incorrectAlgorithm");
CiphertextHeaders headers = getTestHeaders(algo);
assertThrows(
InvalidKeyException.class,
"DataKey of incorrect algorithm.",
() ->
TestUtils.messageWithCommitKeyCryptoAlgorithm.getEncryptionKeyFromDataKey(
secretKey, headers));
}
@Test
public void testGetUnCommittedEncryptionKeyIncorrectLength() throws InvalidKeyException {
SecretKeySpec secretKey = new SecretKeySpec(new byte[1], "HkdfSHA512");
CiphertextHeaders headers =
new ParsedCiphertext(Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64));
assertThrows(
IllegalArgumentException.class,
"DataKey of incorrect length.",
() ->
TestUtils.messageWithCommitKeyCryptoAlgorithm.getEncryptionKeyFromDataKey(
secretKey, headers));
}
private ParsedCiphertext getTestHeaders(CryptoAlgorithm algo) {
// Generate test headers
final int frameSize_ = AwsCrypto.getDefaultFrameSize();
final Map<String, String> encryptionContext = Collections.<String, String>emptyMap();
final CommitmentPolicy policy = CommitmentPolicy.ForbidEncryptAllowDecrypt;
final EncryptionMaterialsRequest encryptionMaterialsRequest =
EncryptionMaterialsRequest.newBuilder()
.setContext(encryptionContext)
.setRequestedAlgorithm(algo)
.setCommitmentPolicy(policy)
.build();
final StaticMasterKey masterKeyProvider = new StaticMasterKey("mock");
final EncryptionMaterials encryptionMaterials =
new DefaultCryptoMaterialsManager(masterKeyProvider)
.getMaterialsForEncrypt(encryptionMaterialsRequest);
final EncryptionHandler encryptionHandler =
new EncryptionHandler(frameSize_, encryptionMaterials, policy);
final byte[] in = new byte[0];
final int ciphertextLen = encryptionHandler.estimateOutputSize(in.length);
final byte[] ciphertext = new byte[ciphertextLen];
encryptionHandler.processBytes(in, 0, in.length, ciphertext, 0);
return new ParsedCiphertext(ciphertext);
}
}
| 5,357 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/XCompatDecryptTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import static org.junit.Assert.assertArrayEquals;
import com.amazonaws.encryptionsdk.internal.Utils;
import com.amazonaws.encryptionsdk.jce.JceMasterKey;
import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.util.io.pem.PemReader;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class XCompatDecryptTest {
private static final String STATIC_XCOMPAT_NAME = "static-aws-xcompat";
private static final String AES_GCM = "AES/GCM/NoPadding";
private static final byte XCOMPAT_MESSAGE_VERSION = 1;
private String plaintextFileName;
private String ciphertextFileName;
private MasterKeyProvider masterKeyProvider;
public XCompatDecryptTest(
String plaintextFileName, String ciphertextFileName, MasterKeyProvider masterKeyProvider)
throws Exception {
this.plaintextFileName = plaintextFileName;
this.ciphertextFileName = ciphertextFileName;
this.masterKeyProvider = masterKeyProvider;
}
@Parameters(name = "{index}: testDecryptFromFile({0}, {1}, {2})")
public static Collection<Object[]> data() throws Exception {
String baseDirName;
baseDirName = System.getProperty("staticCompatibilityResourcesDir");
if (baseDirName == null) {
baseDirName =
XCompatDecryptTest.class.getProtectionDomain().getCodeSource().getLocation().getPath()
+ "aws_encryption_sdk_resources";
}
List<Object[]> testCases_ = new ArrayList<Object[]>();
String ciphertextManifestName =
StringUtils.join(
new String[] {baseDirName, "manifests", "ciphertext.manifest"}, File.separator);
File ciphertextManifestFile = new File(ciphertextManifestName);
if (!ciphertextManifestFile.exists()) {
return Collections.emptySet();
}
ObjectMapper ciphertextManifestMapper = new ObjectMapper();
Map<String, Object> ciphertextManifest =
ciphertextManifestMapper.readValue(
ciphertextManifestFile, new TypeReference<Map<String, Object>>() {});
HashMap<String, HashMap<String, byte[]>> staticKeyMap =
new HashMap<String, HashMap<String, byte[]>>();
Map<String, Object> testKeys = (Map<String, Object>) ciphertextManifest.get("test_keys");
for (Map.Entry<String, Object> keyType : testKeys.entrySet()) {
Map<String, Object> keys = (Map<String, Object>) keyType.getValue();
HashMap<String, byte[]> thisKeyType = new HashMap<String, byte[]>();
for (Map.Entry<String, Object> key : keys.entrySet()) {
Map<String, Object> thisKey = (Map<String, Object>) key.getValue();
String keyRaw =
new String(
StringUtils.join(
(List<String>) thisKey.get("key"),
(String) thisKey.getOrDefault("line_separator", ""))
.getBytes(),
StandardCharsets.UTF_8);
byte[] keyBytes;
switch ((String) thisKey.get("encoding")) {
case "base64":
keyBytes = Utils.decodeBase64String(keyRaw);
break;
case "pem":
PemReader pemReader = new PemReader(new StringReader(keyRaw));
keyBytes = pemReader.readPemObject().getContent();
break;
case "raw":
default:
keyBytes = keyRaw.getBytes();
}
thisKeyType.put((String) key.getKey(), keyBytes);
}
staticKeyMap.put((String) keyType.getKey(), thisKeyType);
}
final KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA");
List<Map<String, Object>> testCases =
(List<Map<String, Object>>) ciphertextManifest.get("test_cases");
for (Map<String, Object> testCase : testCases) {
Map<String, String> plaintext = (Map<String, String>) testCase.get("plaintext");
Map<String, String> ciphertext = (Map<String, String>) testCase.get("ciphertext");
short algId = (short) Integer.parseInt((String) testCase.get("algorithm"), 16);
CryptoAlgorithm encryptionAlgorithm =
CryptoAlgorithm.deserialize(XCOMPAT_MESSAGE_VERSION, algId);
List<Map<String, Object>> masterKeys =
(List<Map<String, Object>>) testCase.get("master_keys");
List<JceMasterKey> allMasterKeys = new ArrayList<JceMasterKey>();
for (Map<String, Object> aMasterKey : masterKeys) {
String providerId = (String) aMasterKey.get("provider_id");
if (providerId.equals(STATIC_XCOMPAT_NAME) && (boolean) aMasterKey.get("decryptable")) {
String paddingAlgorithm = (String) aMasterKey.getOrDefault("padding_algorithm", "");
String paddingHash = (String) aMasterKey.getOrDefault("padding_hash", "");
Integer keyBits =
(Integer)
aMasterKey.getOrDefault("key_bits", encryptionAlgorithm.getDataKeyLength() * 8);
String keyId =
(String) aMasterKey.get("encryption_algorithm")
+ "."
+ keyBits.toString()
+ "."
+ paddingAlgorithm
+ "."
+ paddingHash;
String encAlg = (String) aMasterKey.get("encryption_algorithm");
switch (encAlg.toUpperCase()) {
case "RSA":
String cipherBase = "RSA/ECB/";
String cipherName;
switch (paddingAlgorithm) {
case "OAEP-MGF1":
cipherName = cipherBase + "OAEPWith" + paddingHash + "AndMGF1Padding";
break;
case "PKCS1":
cipherName = cipherBase + paddingAlgorithm + "Padding";
break;
default:
throw new IllegalArgumentException(
"Unknown padding algorithm: " + paddingAlgorithm);
}
PrivateKey privKey =
rsaKeyFactory.generatePrivate(
new PKCS8EncodedKeySpec(staticKeyMap.get("RSA").get(keyBits.toString())));
allMasterKeys.add(
JceMasterKey.getInstance(null, privKey, STATIC_XCOMPAT_NAME, keyId, cipherName));
break;
case "AES":
SecretKeySpec spec =
new SecretKeySpec(
staticKeyMap.get("AES").get(keyBits.toString()),
0,
encryptionAlgorithm.getDataKeyLength(),
encryptionAlgorithm.getDataKeyAlgo());
allMasterKeys.add(
JceMasterKey.getInstance(spec, STATIC_XCOMPAT_NAME, keyId, AES_GCM));
break;
default:
throw new IllegalArgumentException(
"Unknown encryption algorithm: " + encAlg.toUpperCase());
}
}
}
if (allMasterKeys.size() > 0) {
final MasterKeyProvider<?> provider =
MultipleProviderFactory.buildMultiProvider(allMasterKeys);
testCases_.add(
new Object[] {
baseDirName + File.separator + plaintext.get("filename"),
baseDirName + File.separator + ciphertext.get("filename"),
provider
});
}
}
return testCases_;
}
@Test
public void testDecryptFromFile() throws Exception {
AwsCrypto crypto = AwsCrypto.standard();
byte ciphertextBytes[] = Files.readAllBytes(Paths.get(ciphertextFileName));
byte plaintextBytes[] = Files.readAllBytes(Paths.get(plaintextFileName));
final CryptoResult decryptResult = crypto.decryptData(masterKeyProvider, ciphertextBytes);
assertArrayEquals(plaintextBytes, (byte[]) decryptResult.getResult());
}
}
| 5,358 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/AllTestsSuite.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import com.amazonaws.crypto.examples.BasicEncryptionExampleTest;
import com.amazonaws.crypto.examples.BasicMultiRegionKeyEncryptionExampleTest;
import com.amazonaws.crypto.examples.DiscoveryDecryptionExampleTest;
import com.amazonaws.crypto.examples.DiscoveryMultiRegionDecryptionExampleTest;
import com.amazonaws.crypto.examples.MultipleCmkEncryptExampleTest;
import com.amazonaws.crypto.examples.RestrictRegionExampleTest;
import com.amazonaws.crypto.examples.SetCommitmentPolicyExampleTest;
import com.amazonaws.crypto.examples.SetEncryptionAlgorithmExampleTest;
import com.amazonaws.crypto.examples.SimpleDataKeyCachingExampleTest;
import com.amazonaws.encryptionsdk.caching.CacheIdentifierTests;
import com.amazonaws.encryptionsdk.caching.CachingCryptoMaterialsManagerTest;
import com.amazonaws.encryptionsdk.caching.LocalCryptoMaterialsCacheTest;
import com.amazonaws.encryptionsdk.caching.LocalCryptoMaterialsCacheThreadStormTest;
import com.amazonaws.encryptionsdk.caching.NullCryptoMaterialsCacheTest;
import com.amazonaws.encryptionsdk.internal.*;
import com.amazonaws.encryptionsdk.jce.JceMasterKeyTest;
import com.amazonaws.encryptionsdk.jce.KeyStoreProviderTest;
import com.amazonaws.encryptionsdk.kms.AwsKmsMrkAwareMasterKeyProviderTest;
import com.amazonaws.encryptionsdk.kms.AwsKmsMrkAwareMasterKeyTest;
import com.amazonaws.encryptionsdk.kms.DiscoveryFilterTest;
import com.amazonaws.encryptionsdk.kms.KMSProviderBuilderMockTests;
import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProviderTest;
import com.amazonaws.encryptionsdk.kms.KmsMasterKeyTest;
import com.amazonaws.encryptionsdk.model.CipherBlockHeadersTest;
import com.amazonaws.encryptionsdk.model.CipherFrameHeadersTest;
import com.amazonaws.encryptionsdk.model.CiphertextHeadersTest;
import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequestTest;
import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequestTest;
import com.amazonaws.encryptionsdk.model.KeyBlobTest;
import com.amazonaws.encryptionsdk.multi.MultipleMasterKeyTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
CryptoAlgorithmTest.class,
CiphertextHeadersTest.class,
BlockDecryptionHandlerTest.class,
BlockEncryptionHandlerTest.class,
CipherHandlerTest.class,
DecryptionHandlerTest.class,
EncContextSerializerTest.class,
EncryptionHandlerTest.class,
FrameDecryptionHandlerTest.class,
FrameEncryptionHandlerTest.class,
PrimitivesParserTest.class,
KeyStoreProviderTest.class,
CipherBlockHeadersTest.class,
CipherFrameHeadersTest.class,
KeyBlobTest.class,
DecryptionMaterialsRequestTest.class,
MultipleMasterKeyTest.class,
AwsCryptoTest.class,
CryptoInputStreamTest.class,
CryptoOutputStreamTest.class,
TestVectorRunner.class,
XCompatDecryptTest.class,
DefaultCryptoMaterialsManagerTest.class,
NullCryptoMaterialsCacheTest.class,
AwsKmsCmkArnInfoTest.class,
CacheIdentifierTests.class,
CachingCryptoMaterialsManagerTest.class,
LocalCryptoMaterialsCacheTest.class,
LocalCryptoMaterialsCacheThreadStormTest.class,
UtilsTest.class,
MultipleMasterKeyTest.class,
KMSProviderBuilderMockTests.class,
JceMasterKeyTest.class,
KmsMasterKeyProviderTest.class,
KmsMasterKeyTest.class,
DiscoveryFilterTest.class,
CommittedKeyTest.class,
EncryptionMaterialsRequestTest.class,
CommitmentKATRunner.class,
BasicEncryptionExampleTest.class,
BasicMultiRegionKeyEncryptionExampleTest.class,
DiscoveryDecryptionExampleTest.class,
DiscoveryMultiRegionDecryptionExampleTest.class,
MultipleCmkEncryptExampleTest.class,
RestrictRegionExampleTest.class,
SimpleDataKeyCachingExampleTest.class,
SetEncryptionAlgorithmExampleTest.class,
SetCommitmentPolicyExampleTest.class,
ParsedCiphertextTest.class,
AwsKmsMrkAwareMasterKeyProviderTest.class,
AwsKmsMrkAwareMasterKeyTest.class,
VersionInfoTest.class,
com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyProviderTest.class,
com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyTest.class,
com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProviderTest.class,
com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyTest.class,
})
public class AllTestsSuite {}
| 5,359 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/CryptoInputStreamTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static com.amazonaws.encryptionsdk.TestUtils.insecureRandomBytes;
import static com.amazonaws.encryptionsdk.internal.TestIOUtils.getSha256Hash;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import com.amazonaws.encryptionsdk.exception.BadCiphertextException;
import com.amazonaws.encryptionsdk.internal.TestIOUtils;
import com.amazonaws.encryptionsdk.jce.JceMasterKey;
import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.ArgumentCaptor;
@RunWith(Enclosed.class)
public class CryptoInputStreamTest {
private static final SecureRandom RND = new SecureRandom();
private static final MasterKey<JceMasterKey> customerMasterKey;
private static final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY;
static {
byte[] rawKey = new byte[16];
RND.nextBytes(rawKey);
customerMasterKey =
JceMasterKey.getInstance(
new SecretKeySpec(rawKey, "AES"), "mockProvider", "mockKey", "AES/GCM/NoPadding");
}
private static void testRoundTrip(
int dataSize,
Consumer<AwsCrypto> customizer,
Callback onEncrypt,
Callback onDecrypt,
CommitmentPolicy commitmentPolicy)
throws Exception {
AwsCrypto awsCrypto = AwsCrypto.builder().withCommitmentPolicy(commitmentPolicy).build();
customizer.accept(awsCrypto);
byte[] plaintext = insecureRandomBytes(dataSize);
ByteArrayInputStream inputStream = new ByteArrayInputStream(plaintext);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
onEncrypt.process(awsCrypto, inputStream, outputStream);
inputStream = new ByteArrayInputStream(outputStream.toByteArray());
outputStream = new ByteArrayOutputStream();
onDecrypt.process(awsCrypto, inputStream, outputStream);
assertArrayEquals(getSha256Hash(plaintext), getSha256Hash(outputStream.toByteArray()));
}
private interface Callback {
void process(AwsCrypto crypto, InputStream inStream, OutputStream outStream) throws Exception;
}
private static Callback encryptWithContext(Map<String, String> encryptionContext) {
return (awsCrypto, inStream, outStream) -> {
final InputStream cryptoStream =
awsCrypto.createEncryptingStream(customerMasterKey, inStream, encryptionContext);
TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream);
};
}
private static Callback encryptWithoutContext() {
return (awsCrypto, inStream, outStream) -> {
final InputStream cryptoStream =
awsCrypto.createEncryptingStream(customerMasterKey, inStream);
TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream);
};
}
private static Callback basicDecrypt(int readLen) {
return (awsCrypto, inStream, outStream) -> {
final InputStream cryptoStream =
awsCrypto.createDecryptingStream(customerMasterKey, inStream);
TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream, readLen);
};
}
private static Callback basicDecrypt() {
return (awsCrypto, inStream, outStream) -> {
final InputStream cryptoStream =
awsCrypto.createDecryptingStream(customerMasterKey, inStream);
TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream);
};
}
@RunWith(Parameterized.class)
public static class ParameterizedEncryptDecryptTest {
private final CryptoAlgorithm cryptoAlg;
private final int byteSize, frameSize, readLen;
public ParameterizedEncryptDecryptTest(
CryptoAlgorithm cryptoAlg, int byteSize, int frameSize, int readLen) {
this.cryptoAlg = cryptoAlg;
this.byteSize = byteSize;
this.frameSize = frameSize;
this.readLen = readLen;
}
@Parameterized.Parameters(
name = "{index}: encryptDecrypt(algorithm={0}, byteSize={1}, frameSize={2}, readLen={3})")
public static Collection<Object[]> encryptDecryptParams() {
ArrayList<Object[]> testCases = new ArrayList<>();
// We'll run more exhaustive tests on the first algorithm, then go lighter weight on the rest.
boolean firstAlgorithm = true;
for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) {
final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg);
// Our bytesToTest and readLenVals arrays tend to have the bigger numbers towards the end -
// we'll chop off
// the last few as they take the longest and don't really add that much more coverage.
int skipLastNSizes;
if (!FastTestsOnlySuite.isFastTestSuiteActive()) {
skipLastNSizes = 0;
} else if (firstAlgorithm) {
// We'll run more tests for the first algorithm in the list - but not go quite so far as
// running the
// 1MB tests.
skipLastNSizes = 1;
} else {
skipLastNSizes = 2;
}
// iterate over frame size to test
for (final int frameSize : frameSizeToTest) {
int[] bytesToTest = {
0,
1,
frameSize - 1,
frameSize,
frameSize + 1,
(int) (frameSize * 1.5),
frameSize * 2,
1000000
};
bytesToTest = Arrays.copyOfRange(bytesToTest, 0, bytesToTest.length - skipLastNSizes);
// iterate over byte size to test
for (final int byteSize : bytesToTest) {
int[] readLenVals = {1, byteSize - 1, byteSize, byteSize + 1, byteSize * 2, 1000000};
readLenVals = Arrays.copyOfRange(readLenVals, 0, readLenVals.length - skipLastNSizes);
// iterate over read lengths to test
for (final int readLen : readLenVals) {
if (byteSize >= 0 && readLen > 0) {
testCases.add(new Object[] {cryptoAlg, byteSize, frameSize, readLen});
}
}
}
}
firstAlgorithm = false;
}
return testCases;
}
@Test
public void encryptDecrypt() throws Exception {
final CommitmentPolicy commitmentPolicy =
cryptoAlg.isCommitting()
? CommitmentPolicy.RequireEncryptRequireDecrypt
: CommitmentPolicy.ForbidEncryptAllowDecrypt;
testRoundTrip(
byteSize,
awsCrypto -> {
awsCrypto.setEncryptionAlgorithm(cryptoAlg);
awsCrypto.setEncryptionFrameSize(frameSize);
},
encryptWithoutContext(),
basicDecrypt(readLen),
commitmentPolicy);
}
}
public static class NonParameterized {
private AwsCrypto encryptionClient_;
@Before
public void setup() throws IOException {
encryptionClient_ = AwsCrypto.standard();
}
@Test
public void doEncryptDecryptWithoutEncContext() throws Exception {
testRoundTrip(
1_000_000,
awsCrypto -> {},
encryptWithoutContext(),
basicDecrypt(),
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void encryptBytesDecryptStream() throws Exception {
Map<String, String> encryptionContext = new HashMap<>(1);
encryptionContext.put("ENC", "encryptBytesDecryptStream");
testRoundTrip(
1_000_000,
awsCrypto -> {},
(AwsCrypto awsCrypto, InputStream inStream, OutputStream outStream) -> {
ByteArrayOutputStream inbuf = new ByteArrayOutputStream();
TestIOUtils.copyInStreamToOutStream(inStream, inbuf);
CryptoResult<byte[], ?> ciphertext =
awsCrypto.encryptData(customerMasterKey, inbuf.toByteArray(), encryptionContext);
outStream.write(ciphertext.getResult());
},
basicDecrypt(),
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void encryptStreamDecryptBytes() throws Exception {
Map<String, String> encryptionContext = new HashMap<>(1);
encryptionContext.put("ENC", "encryptStreamDecryptBytes");
testRoundTrip(
1_000_000,
awsCrypto -> {},
encryptWithContext(encryptionContext),
(AwsCrypto awsCrypto, InputStream inStream, OutputStream outStream) -> {
ByteArrayOutputStream inbuf = new ByteArrayOutputStream();
TestIOUtils.copyInStreamToOutStream(inStream, inbuf);
CryptoResult<byte[], ?> ciphertext =
awsCrypto.decryptData(customerMasterKey, inbuf.toByteArray());
outStream.write(ciphertext.getResult());
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void encryptOSDecryptIS() throws Exception {
Map<String, String> encryptionContext = new HashMap<>(1);
encryptionContext.put("ENC", "encryptOSDecryptIS");
testRoundTrip(
1_000_000,
awsCrypto -> {},
(awsCrypto, inStream, outStream) -> {
OutputStream cryptoOS =
awsCrypto.createEncryptingStream(customerMasterKey, outStream, encryptionContext);
TestIOUtils.copyInStreamToOutStream(inStream, cryptoOS);
},
basicDecrypt(),
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
private void singleByteCopyLoop(InputStream is, OutputStream os) throws Exception {
int rv;
while (-1 != (rv = is.read())) {
os.write(rv);
}
is.close();
os.close();
}
@Test
public void singleByteRead() throws Exception {
Map<String, String> encryptionContext = new HashMap<>(1);
encryptionContext.put("ENC", "singleByteRead");
testRoundTrip(
1_000_000,
awsCrypto -> {},
(awsCrypto, inStream, outStream) -> {
InputStream is =
awsCrypto.createEncryptingStream(customerMasterKey, inStream, encryptionContext);
singleByteCopyLoop(is, outStream);
},
(awsCrypto, inStream, outStream) -> {
InputStream is = awsCrypto.createDecryptingStream(customerMasterKey, inStream);
singleByteCopyLoop(is, outStream);
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@SuppressWarnings({"ConstantConditions", "ResultOfMethodCallIgnored"})
@Test(expected = NullPointerException.class)
public void whenNullBufferPassed_andNoOffsetArgs_readThrowsNPE()
throws BadCiphertextException, IOException {
final Map<String, String> encryptionContext = new HashMap<>(1);
encryptionContext.put("ENC", "nullReadBuffer");
final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048));
final InputStream encryptionInStream =
encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext);
encryptionInStream.read(null);
}
@SuppressWarnings({"ConstantConditions", "ResultOfMethodCallIgnored"})
@Test(expected = NullPointerException.class)
public void whenNullBufferPassed_andOffsetArgsPassed_readThrowsNPE()
throws BadCiphertextException, IOException {
final Map<String, String> encryptionContext = new HashMap<>(1);
encryptionContext.put("ENC", "nullReadBuffer2");
final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048));
final InputStream encryptionInStream =
encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext);
encryptionInStream.read(null, 0, 0);
}
@Test
public void zeroReadLen() throws BadCiphertextException, IOException {
final Map<String, String> encryptionContext = new HashMap<>(1);
encryptionContext.put("ENC", "zeroReadLen");
final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048));
final InputStream encryptionInStream =
encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext);
final byte[] tempBytes = new byte[0];
final int readLen = encryptionInStream.read(tempBytes);
assertEquals(readLen, 0);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test(expected = IllegalArgumentException.class)
public void negativeReadLen() throws BadCiphertextException, IOException {
final Map<String, String> encryptionContext = new HashMap<>(1);
encryptionContext.put("ENC", "negativeReadLen");
final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048));
final InputStream encryptionInStream =
encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext);
final byte[] tempBytes = new byte[1];
encryptionInStream.read(tempBytes, 0, -1);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test(expected = IllegalArgumentException.class)
public void negativeReadOffset() throws BadCiphertextException, IOException {
final Map<String, String> encryptionContext = new HashMap<>(1);
encryptionContext.put("ENC", "negativeReadOffset");
final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048));
final InputStream encryptionInStream =
encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext);
byte[] tempBytes = new byte[1];
encryptionInStream.read(tempBytes, -1, tempBytes.length);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void invalidReadOffset() throws BadCiphertextException, IOException {
final Map<String, String> encryptionContext = new HashMap<>(1);
encryptionContext.put("ENC", "invalidReadOffset");
final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048));
final InputStream encryptionInStream =
encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext);
final byte[] tempBytes = new byte[100];
encryptionInStream.read(tempBytes, tempBytes.length + 1, tempBytes.length);
}
@Test
public void noOpStream() throws IOException {
final Map<String, String> encryptionContext = new HashMap<>(1);
encryptionContext.put("ENC", "noOpStream");
final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048));
final InputStream encryptionInStream =
encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext);
encryptionInStream.close();
}
@Test
public void decryptEmptyFile() throws IOException {
final InputStream inStream = new ByteArrayInputStream(new byte[0]);
final InputStream decryptionInStream =
encryptionClient_.createDecryptingStream(customerMasterKey, inStream);
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
TestIOUtils.copyInStreamToOutStream(decryptionInStream, outStream);
assertEquals(0, outStream.size());
}
@Test
public void checkEncContext() throws Exception {
Map<String, String> setEncryptionContext = new HashMap<>(1);
setEncryptionContext.put("ENC", "checkEncContext");
testRoundTrip(
4096,
awsCrypto -> {},
encryptWithContext(setEncryptionContext),
(crypto, inStream, outStream) -> {
CryptoInputStream<?> cis = crypto.createDecryptingStream(customerMasterKey, inStream);
TestIOUtils.copyInStreamToOutStream(cis, outStream);
// Note that the crypto result might have additional entries in its context, so only
// check that
// the entries we set were present, not that the entire map is equal
CryptoResult<? extends CryptoInputStream<?>, ?> cryptoResult = cis.getCryptoResult();
setEncryptionContext.forEach(
(k, v) -> assertEquals(v, cryptoResult.getEncryptionContext().get(k)));
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void checkKeyId() throws Exception {
testRoundTrip(
4096,
awsCrypto -> {},
encryptWithoutContext(),
(crypto, inStream, outStream) -> {
CryptoInputStream<?> cis = crypto.createDecryptingStream(customerMasterKey, inStream);
TestIOUtils.copyInStreamToOutStream(cis, outStream);
CryptoResult<? extends CryptoInputStream<?>, ?> cryptoResult = cis.getCryptoResult();
final String returnedKeyId = cryptoResult.getMasterKeys().get(0).getKeyId();
assertEquals("mockKey", returnedKeyId);
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void checkAvailable() throws IOException {
final int byteSize = 128;
final byte[] inBytes = TestIOUtils.generateRandomPlaintext(byteSize);
final InputStream inStream = new ByteArrayInputStream(inBytes);
final int frameSize = AwsCrypto.getDefaultFrameSize();
encryptionClient_.setEncryptionFrameSize(frameSize);
Map<String, String> setEncryptionContext = new HashMap<>(1);
setEncryptionContext.put("ENC", "Streaming Test");
// encryption
final InputStream encryptionInStream =
encryptionClient_.createEncryptingStream(
customerMasterKey, inStream, setEncryptionContext);
assertEquals(byteSize, encryptionInStream.available());
}
@Test
public void whenGetResultCalledTooEarly_noExceptionThrown() throws Exception {
testRoundTrip(
1024,
awsCrypto -> {},
(awsCrypto, inStream, outStream) -> {
final CryptoInputStream<?> cryptoStream =
awsCrypto.createEncryptingStream(customerMasterKey, inStream);
// can invoke at any time on encrypt
cryptoStream.getCryptoResult();
TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream);
cryptoStream.getCryptoResult();
},
(awsCrypto, inStream, outStream) -> {
final CryptoInputStream<?> cryptoStream =
awsCrypto.createDecryptingStream(customerMasterKey, inStream);
// this will implicitly read the crypto headers
cryptoStream.getCryptoResult();
TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream);
// still works
cryptoStream.getCryptoResult();
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test(expected = BadCiphertextException.class)
public void whenGetResultInvokedOnEmptyStream_exceptionThrown() throws IOException {
final CryptoInputStream<?> cryptoStream =
encryptionClient_.createDecryptingStream(
customerMasterKey, new ByteArrayInputStream(new byte[0]));
cryptoStream.getCryptoResult();
}
@Test()
public void encryptUsingCryptoMaterialsManager() throws Exception {
RecordingMaterialsManager cmm = new RecordingMaterialsManager(customerMasterKey);
testRoundTrip(
1024,
awsCrypto -> {},
(crypto, inStream, outStream) -> {
final CryptoInputStream<?> cryptoStream = crypto.createEncryptingStream(cmm, inStream);
TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream);
assertEquals("bar", cryptoStream.getCryptoResult().getEncryptionContext().get("foo"));
},
basicDecrypt(),
commitmentPolicy);
}
@Test
public void decryptUsingCryptoMaterialsManager() throws Exception {
RecordingMaterialsManager cmm = new RecordingMaterialsManager(customerMasterKey);
testRoundTrip(
1024,
awsCrypto -> {},
encryptWithoutContext(),
(crypto, inStream, outStream) -> {
final CryptoInputStream<?> cryptoStream = crypto.createDecryptingStream(cmm, inStream);
assertFalse(cmm.didDecrypt);
TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream);
assertTrue(cmm.didDecrypt);
},
commitmentPolicy);
}
@Test
public void whenStreamSizeSetEarly_streamSizePassedToCMM() throws Exception {
CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey));
CryptoInputStream<?> is =
AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayInputStream(new byte[1]));
is.setMaxInputLength(1);
is.read();
ArgumentCaptor<EncryptionMaterialsRequest> captor =
ArgumentCaptor.forClass(EncryptionMaterialsRequest.class);
verify(cmm).getMaterialsForEncrypt(captor.capture());
assertEquals(1L, captor.getValue().getPlaintextSize());
}
@Test
public void whenStreamSizeSetEarly_andExceeded_exceptionThrown() throws Exception {
CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey));
CryptoInputStream<?> is =
AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayInputStream(new byte[2]));
is.setMaxInputLength(1);
assertThrows(() -> is.read(new byte[65536]));
}
@Test
public void whenStreamSizeSetLate_andExceeded_exceptionThrown() throws Exception {
CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey));
CryptoInputStream<?> is =
AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayInputStream(new byte[2]));
assertThrows(
() -> {
is.read();
is.setMaxInputLength(1);
is.read(new byte[65536]);
});
}
@Test
public void whenStreamSizeSet_afterBeingExceeded_exceptionThrown() throws Exception {
CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey));
CryptoInputStream<?> is =
AwsCrypto.standard()
.createEncryptingStream(cmm, new ByteArrayInputStream(new byte[1024 * 1024]));
assertThrows(
() -> {
is.read();
is.setMaxInputLength(1);
});
}
@Test
public void whenStreamSizeNegative_setSizeThrows() throws Exception {
CryptoInputStream<?> is =
AwsCrypto.standard()
.createEncryptingStream(customerMasterKey, new ByteArrayInputStream(new byte[0]));
assertThrows(() -> is.setMaxInputLength(-1));
}
@Test
public void whenStreamSizeSet_roundTripSucceeds() throws Exception {
testRoundTrip(
1024,
awsCrypto -> {},
(awsCrypto, inStream, outStream) -> {
final CryptoInputStream<?> cryptoStream =
awsCrypto.createEncryptingStream(customerMasterKey, inStream);
// we happen to know inStream is a ByteArrayInputStream which will give an accurate
// number
// of bytes remaining on .available()
cryptoStream.setMaxInputLength(inStream.available());
TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream);
},
(awsCrypto, inStream, outStream) -> {
final CryptoInputStream<?> cryptoStream =
awsCrypto.createDecryptingStream(customerMasterKey, inStream);
cryptoStream.setMaxInputLength(inStream.available());
TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream);
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
}
}
| 5,360 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/CryptoOutputStreamTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import static com.amazonaws.encryptionsdk.AwsCrypto.getDefaultFrameSize;
import static com.amazonaws.encryptionsdk.FastTestsOnlySuite.isFastTestSuiteActive;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static com.amazonaws.encryptionsdk.TestUtils.insecureRandomBytes;
import static com.amazonaws.encryptionsdk.TestUtils.toByteArray;
import static com.amazonaws.encryptionsdk.internal.TestIOUtils.getSha256Hash;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import com.amazonaws.encryptionsdk.exception.BadCiphertextException;
import com.amazonaws.encryptionsdk.internal.TestIOUtils;
import com.amazonaws.encryptionsdk.jce.JceMasterKey;
import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.ArgumentCaptor;
@RunWith(Enclosed.class)
public class CryptoOutputStreamTest {
private static final SecureRandom RND = new SecureRandom();
private static final MasterKey<JceMasterKey> customerMasterKey;
private static final AtomicReference<byte[]> RANDOM_BUFFER = new AtomicReference<>(new byte[0]);
private static final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY;
static {
byte[] rawKey = new byte[16];
RND.nextBytes(rawKey);
customerMasterKey =
JceMasterKey.getInstance(
new SecretKeySpec(rawKey, "AES"), "mockProvider", "mockKey", "AES/GCM/NoPadding");
}
private static void testRoundTrip(
int dataSize,
Consumer<AwsCrypto> customizer,
Callback onEncrypt,
Callback onDecrypt,
CommitmentPolicy commitmentPolicy)
throws Exception {
AwsCrypto awsCrypto = AwsCrypto.builder().withCommitmentPolicy(commitmentPolicy).build();
customizer.accept(awsCrypto);
byte[] plaintext = insecureRandomBytes(dataSize);
ByteArrayInputStream inputStream = new ByteArrayInputStream(plaintext);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
onEncrypt.process(awsCrypto, inputStream, outputStream);
inputStream = new ByteArrayInputStream(outputStream.toByteArray());
outputStream = new ByteArrayOutputStream();
onDecrypt.process(awsCrypto, inputStream, outputStream);
assertArrayEquals(getSha256Hash(plaintext), getSha256Hash(outputStream.toByteArray()));
}
private interface Callback {
void process(AwsCrypto crypto, InputStream inStream, OutputStream outStream) throws Exception;
}
private static Callback encryptWithContext(Map<String, String> encryptionContext) {
return (awsCrypto, inStream, outStream) -> {
final OutputStream encryptionOutStream =
awsCrypto.createEncryptingStream(customerMasterKey, outStream, encryptionContext);
TestIOUtils.copyInStreamToOutStream(inStream, encryptionOutStream);
};
}
private static Callback encryptWithoutContext() {
return (awsCrypto, inStream, outStream) -> {
final OutputStream encryptionOutStream =
awsCrypto.createEncryptingStream(customerMasterKey, outStream);
TestIOUtils.copyInStreamToOutStream(inStream, encryptionOutStream);
};
}
private static Callback basicDecrypt(int readLen) {
return (awsCrypto, inStream, outStream) -> {
final OutputStream decryptionOutStream =
awsCrypto.createDecryptingStream(customerMasterKey, outStream);
TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream, readLen);
};
}
private static Callback basicDecrypt() {
return (awsCrypto, inStream, outStream) -> {
final OutputStream decryptionOutStream =
awsCrypto.createDecryptingStream(customerMasterKey, outStream);
TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream);
};
}
@RunWith(Parameterized.class)
public static class ParameterizedEncryptDecryptTest {
private final CryptoAlgorithm cryptoAlg;
private final int byteSize, frameSize, readLen;
public ParameterizedEncryptDecryptTest(
CryptoAlgorithm cryptoAlg, int byteSize, int frameSize, int readLen) {
this.cryptoAlg = cryptoAlg;
this.byteSize = byteSize;
this.frameSize = frameSize;
this.readLen = readLen;
}
@Parameterized.Parameters(
name = "{index}: encryptDecrypt(algorithm={0}, byteSize={1}, frameSize={2}, readLen={3})")
public static Collection<Object[]> encryptDecryptParams() {
ArrayList<Object[]> cases = new ArrayList<>();
for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) {
final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg);
// iterate over frame size to test
for (int i = 0; i < frameSizeToTest.length; i++) {
final int frameSize = frameSizeToTest[i];
int[] bytesToTest = {
0,
1,
frameSize - 1,
frameSize,
frameSize + 1,
(int) (frameSize * 1.5),
frameSize * 2,
1000000
};
if (isFastTestSuiteActive()) {
// Exclude the last two sizes, as they're the slowest
bytesToTest = Arrays.copyOfRange(bytesToTest, 0, bytesToTest.length - 2);
}
// iterate over byte size to test
for (int j = 0; j < bytesToTest.length; j++) {
final int byteSize = bytesToTest[j];
int[] readLenVals = {byteSize - 1, byteSize, byteSize + 1, byteSize * 2, 1000000};
if (isFastTestSuiteActive()) {
// Only test one read() call buffer length in the fast tests. This greatly cuts down
// on
// the combinatorial explosion of test cases here.
readLenVals = Arrays.copyOfRange(readLenVals, 0, 1);
}
// iterate over read lengths to test
for (int k = 0; k < readLenVals.length; k++) {
final int readLen = readLenVals[k];
if (byteSize >= 0 && readLen > 0) {
cases.add(new Object[] {cryptoAlg, byteSize, frameSize, readLen});
}
}
}
}
}
return cases;
}
@Test
public void encryptDecrypt() throws Exception {
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC", "Streaming Test");
final CommitmentPolicy commitmentPolicy =
cryptoAlg.isCommitting()
? CommitmentPolicy.RequireEncryptRequireDecrypt
: CommitmentPolicy.ForbidEncryptAllowDecrypt;
testRoundTrip(
byteSize,
awsCrypto -> {
awsCrypto.setEncryptionFrameSize(frameSize);
awsCrypto.setEncryptionAlgorithm(cryptoAlg);
},
encryptWithContext(encryptionContext),
basicDecrypt(readLen),
commitmentPolicy);
}
}
public static class NonParameterized {
private AwsCrypto encryptionClient_;
public NonParameterized() {}
@Before
public void setup() throws IOException {
encryptionClient_ = AwsCrypto.standard();
}
@Test
public void singleByteWrite() throws Exception {
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC", "Streaming Test");
testRoundTrip(
10_000,
awsCrypto -> {},
(awsCrypto, inStream, outStream) -> {
final OutputStream encryptionOutStream =
awsCrypto.createEncryptingStream(customerMasterKey, outStream, encryptionContext);
// write a single plaintext byte at a time
final byte[] writeBytes = new byte[2048];
int read_len = 0;
while (read_len >= 0) {
read_len = inStream.read(writeBytes);
if (read_len > 0) {
for (int i = 0; i < read_len; i++) {
encryptionOutStream.write(writeBytes[i]);
}
}
}
encryptionOutStream.close();
},
(awsCrypto, inStream, outStream) -> {
final OutputStream decryptionOutStream =
awsCrypto.createDecryptingStream(customerMasterKey, outStream);
// write a single decrypted byte at a time
final byte[] writeBytes = new byte[2048];
int read_len = 0;
while (read_len >= 0) {
read_len = inStream.read(writeBytes);
if (read_len > 0) {
for (int i = 0; i < read_len; i++) {
decryptionOutStream.write(writeBytes[i]);
}
}
}
decryptionOutStream.close();
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void doEncryptDecryptWithoutEncContext() throws Exception {
testRoundTrip(
1_000_000,
awsCrypto -> {},
encryptWithoutContext(),
basicDecrypt(),
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void doEncryptDecryptWithContext() throws Exception {
Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC", "Streaming Test: inputStreamCompatiblilty");
testRoundTrip(
1_000_000,
awsCrypto -> awsCrypto.setEncryptionFrameSize(getDefaultFrameSize()),
encryptWithContext(encryptionContext),
basicDecrypt(),
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void encryptOneShotDecryptStream() throws Exception {
Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC", "encryptAPICompatibility");
testRoundTrip(
1_000_000,
awsCrypto -> {},
(crypto, inStream, outStream) -> {
outStream.write(
encryptionClient_
.encryptData(customerMasterKey, toByteArray(inStream), encryptionContext)
.getResult());
},
(crypto, inStream, outStream) -> {
final OutputStream decryptionOutStream =
encryptionClient_.createDecryptingStream(customerMasterKey, outStream);
decryptionOutStream.write(toByteArray(inStream));
decryptionOutStream.close();
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void encryptStreamDecryptOneShot() throws Exception {
Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC", "decryptAPICompatibility");
testRoundTrip(
1_000_000,
awsCrypto -> {},
(crypto, inStream, outStream) -> {
final OutputStream encryptionOutStream =
encryptionClient_.createEncryptingStream(
customerMasterKey, outStream, encryptionContext);
TestIOUtils.copyInStreamToOutStream(inStream, encryptionOutStream);
},
(crypto, inStream, outStream) -> {
outStream.write(
encryptionClient_
.decryptData(customerMasterKey, toByteArray(inStream))
.getResult());
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test(expected = IllegalArgumentException.class)
public void nullWrite() throws IOException {
final OutputStream outStream = new ByteArrayOutputStream();
final OutputStream encryptionOutStream =
encryptionClient_.createEncryptingStream(customerMasterKey, outStream);
encryptionOutStream.write(null);
}
@Test(expected = IllegalArgumentException.class)
public void nullWrite2() throws BadCiphertextException, IOException {
final OutputStream outStream = new ByteArrayOutputStream();
final OutputStream encryptionOutStream =
encryptionClient_.createEncryptingStream(customerMasterKey, outStream);
encryptionOutStream.write(null, 0, 0);
}
@Test(expected = IllegalArgumentException.class)
public void negativeWriteLen() throws BadCiphertextException, IOException {
final OutputStream outStream = new ByteArrayOutputStream();
final OutputStream encryptionOutStream =
encryptionClient_.createEncryptingStream(customerMasterKey, outStream);
final byte[] writeBytes = new byte[0];
encryptionOutStream.write(writeBytes, 0, -1);
}
@Test(expected = IllegalArgumentException.class)
public void negativeWriteOffset() throws BadCiphertextException, IOException {
final OutputStream outStream = new ByteArrayOutputStream();
final OutputStream encryptionOutStream =
encryptionClient_.createEncryptingStream(customerMasterKey, outStream);
final byte[] writeBytes = new byte[2048];
encryptionOutStream.write(writeBytes, -1, writeBytes.length);
}
@Test
public void checkInvalidValues() throws Exception {
// test for the two formats - single-block and frame.
final int[] frameSizeToTest = {0, getDefaultFrameSize()};
// iterate over frame size to test
for (int i = 0; i < frameSizeToTest.length; i++) {
final int frameSize = frameSizeToTest[i];
invalidWriteLen(frameSize);
invalidWriteOffset(frameSize);
noOpStream(frameSize);
}
}
private void invalidWriteLen(final int frameSize) throws BadCiphertextException, IOException {
AwsCrypto awsCrypto = AwsCrypto.standard();
awsCrypto.setEncryptionFrameSize(frameSize);
final OutputStream outStream = new ByteArrayOutputStream();
final OutputStream encryptionOutStream =
awsCrypto.createEncryptingStream(customerMasterKey, outStream);
final byte[] writeBytes = new byte[2048];
assertThrows(
IndexOutOfBoundsException.class,
() -> encryptionOutStream.write(writeBytes, 0, 2 * writeBytes.length));
}
private void invalidWriteOffset(final int frameSize)
throws BadCiphertextException, IOException {
AwsCrypto awsCrypto = AwsCrypto.standard();
awsCrypto.setEncryptionFrameSize(frameSize);
final OutputStream outStream = new ByteArrayOutputStream();
final OutputStream encryptionOutStream =
awsCrypto.createEncryptingStream(customerMasterKey, outStream);
final byte[] writeBytes = new byte[2048];
assertThrows(
IndexOutOfBoundsException.class,
() -> encryptionOutStream.write(writeBytes, writeBytes.length + 1, writeBytes.length));
}
private void noOpStream(final int frameSize) throws Exception {
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC", "noOpStream size " + frameSize);
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
final OutputStream encryptionOutStream =
encryptionClient_.createEncryptingStream(customerMasterKey, outStream, encryptionContext);
encryptionOutStream.close();
testRoundTrip(
0,
crypto -> crypto.setEncryptionFrameSize(frameSize),
encryptWithContext(encryptionContext),
basicDecrypt(),
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void decryptEmptyFile() throws IOException {
final InputStream inStream = new ByteArrayInputStream(new byte[0]);
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
final OutputStream decryptionOutStream =
encryptionClient_.createDecryptingStream(customerMasterKey, outStream);
TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream);
inStream.close();
decryptionOutStream.close();
assertEquals(0, outStream.size());
}
@Test
public void checkEncContext() throws Exception {
Map<String, String> context = new HashMap<String, String>(1);
context.put("ENC", "Streaming Test " + UUID.randomUUID());
testRoundTrip(
1,
awsCrypto -> {},
encryptWithContext(context),
(crypto, inStream, outStream) -> {
final CryptoOutputStream<JceMasterKey> decryptionOutStream =
encryptionClient_.createDecryptingStream(customerMasterKey, outStream);
TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream);
Map<String, String> getEncryptionContext =
decryptionOutStream.getCryptoResult().getEncryptionContext();
// Since more values may have been added, we need to check to ensure that all
// of setEncryptionContext is present, not that there is nothing else
for (final Map.Entry<String, String> e : context.entrySet()) {
assertEquals(e.getValue(), getEncryptionContext.get(e.getKey()));
}
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void checkKeyId() throws Exception {
Map<String, String> context = new HashMap<String, String>(1);
context.put("ENC", "Streaming Test " + UUID.randomUUID());
testRoundTrip(
1,
awsCrypto -> {},
encryptWithContext(context),
(crypto, inStream, outStream) -> {
final CryptoOutputStream<JceMasterKey> decryptionOutStream =
encryptionClient_.createDecryptingStream(customerMasterKey, outStream);
TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream);
final String returnedKeyId =
decryptionOutStream.getCryptoResult().getMasterKeys().get(0).getKeyId();
assertEquals("mockKey", returnedKeyId);
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void whenGetResultCalledTooEarly_exceptionThrown() throws Exception {
testRoundTrip(
1024,
awsCrypto -> {},
(awsCrypto2, inStream, outStream) -> {
final CryptoOutputStream<?> encryptionOutStream =
awsCrypto2.createEncryptingStream(customerMasterKey, outStream);
// we should be able to get the cryptoResult on the encrypt path immediately
encryptionOutStream.getCryptoResult();
TestIOUtils.copyInStreamToOutStream(inStream, encryptionOutStream);
},
(awsCrypto1, inStream, outStream) -> {
final CryptoOutputStream<?> decryptionOutStream =
awsCrypto1.createDecryptingStream(customerMasterKey, outStream);
// Can't get headers until we write them to the outstream
assertThrows(IllegalStateException.class, decryptionOutStream::getCryptoResult);
TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream);
// Now we can get headers
decryptionOutStream.getCryptoResult();
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
@Test
public void encryptUsingCryptoMaterialsManager() throws Exception {
RecordingMaterialsManager cmm = new RecordingMaterialsManager(customerMasterKey);
testRoundTrip(
1024,
awsCrypto -> {},
(crypto, inStream, outStream) -> {
final CryptoOutputStream<?> cryptoStream =
crypto.createEncryptingStream(cmm, outStream);
TestIOUtils.copyInStreamToOutStream(inStream, cryptoStream);
assertEquals("bar", cryptoStream.getCryptoResult().getEncryptionContext().get("foo"));
},
basicDecrypt(),
commitmentPolicy);
}
@Test
public void decryptUsingCryptoMaterialsManager() throws Exception {
RecordingMaterialsManager cmm = new RecordingMaterialsManager(customerMasterKey);
testRoundTrip(
1024,
awsCrypto -> {},
encryptWithoutContext(),
(crypto, inStream, outStream) -> {
final CryptoOutputStream<?> cryptoStream =
crypto.createDecryptingStream(cmm, outStream);
assertFalse(cmm.didDecrypt);
TestIOUtils.copyInStreamToOutStream(inStream, cryptoStream);
assertTrue(cmm.didDecrypt);
},
commitmentPolicy);
}
@Test
public void whenStreamSizeSetEarly_streamSizePassedToCMM() throws Exception {
CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey));
CryptoOutputStream<?> os =
AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayOutputStream());
os.setMaxInputLength(1);
os.write(0);
ArgumentCaptor<EncryptionMaterialsRequest> captor =
ArgumentCaptor.forClass(EncryptionMaterialsRequest.class);
verify(cmm).getMaterialsForEncrypt(captor.capture());
assertEquals(1L, captor.getValue().getPlaintextSize());
}
@Test
public void whenStreamSizeSetEarly_andExceeded_exceptionThrown() throws Exception {
CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey));
CryptoOutputStream<?> os =
AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayOutputStream());
os.setMaxInputLength(1);
os.write(0);
assertThrows(() -> os.write(0));
}
@Test
public void whenStreamSizeSetLate_andExceeded_exceptionThrown() throws Exception {
CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey));
CryptoOutputStream<?> os =
AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayOutputStream());
os.write(0);
os.setMaxInputLength(1);
assertThrows(() -> os.write(0));
}
@Test
public void whenStreamSizeSet_afterBeingExceeded_exceptionThrown() throws Exception {
CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey));
CryptoOutputStream<?> os =
AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayOutputStream());
os.write(0);
os.write(0);
assertThrows(() -> os.setMaxInputLength(1));
}
@Test
public void whenStreamSizeNegative_setSizeThrows() throws Exception {
CryptoOutputStream<?> is =
AwsCrypto.standard()
.createEncryptingStream(customerMasterKey, new ByteArrayOutputStream());
assertThrows(() -> is.setMaxInputLength(-1));
}
@Test
public void whenStreamSizeSet_roundTripSucceeds() throws Exception {
testRoundTrip(
1024,
ignored -> {},
(awsCrypto, inStream, outStream) -> {
final CryptoOutputStream<?> encryptionOutStream =
awsCrypto.createEncryptingStream(customerMasterKey, outStream);
encryptionOutStream.setMaxInputLength(1024);
TestIOUtils.copyInStreamToOutStream(inStream, encryptionOutStream);
},
(awsCrypto, inStream, outStream) -> {
final CryptoOutputStream<?> decryptionOutStream =
awsCrypto.createDecryptingStream(customerMasterKey, outStream);
// we happen to know inStream is a ByteArrayInputStream which will give an accurate
// number
// of bytes remaining on .available()
decryptionOutStream.setMaxInputLength(inStream.available());
TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream);
},
CommitmentPolicy.RequireEncryptRequireDecrypt);
}
}
}
| 5,361 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/RecordingMaterialsManager.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import com.amazonaws.encryptionsdk.model.DecryptionMaterials;
import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest;
import com.amazonaws.encryptionsdk.model.EncryptionMaterials;
import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest;
import java.util.Collections;
public class RecordingMaterialsManager implements CryptoMaterialsManager {
private final CryptoMaterialsManager delegate;
private final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY;
public boolean didDecrypt = false;
public RecordingMaterialsManager(CryptoMaterialsManager delegate) {
this.delegate = delegate;
}
public RecordingMaterialsManager(MasterKeyProvider<?> delegate) {
this.delegate = new DefaultCryptoMaterialsManager(delegate);
}
@Override
public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) {
request = request.toBuilder().setContext(Collections.singletonMap("foo", "bar")).build();
EncryptionMaterials result = delegate.getMaterialsForEncrypt(request);
return result;
}
@Override
public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) {
didDecrypt = true;
return delegate.decryptMaterials(request);
}
}
| 5,362 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/DecryptionMethod.java | package com.amazonaws.encryptionsdk;
import com.amazonaws.encryptionsdk.internal.SignaturePolicy;
import com.amazonaws.encryptionsdk.internal.TestIOUtils;
import java.io.*;
enum DecryptionMethod {
OneShot {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext)
throws IOException {
return crypto.decryptData(masterKeyProvider, ciphertext).getResult();
}
},
// Note for the record that changing the readLen parameter of copyInStreamToOutStream has minimal
// effect on the actual data flow when copying from a CryptoInputStream: it will always read from
// the
// underlying input stream with a fixed chunk size (4096 bytes at the time of writing this),
// independently
// of how many bytes its asked to read of the decryption result. It's still useful to vary the
// length to
// ensure the buffering in the CryptoInputStream works correctly though.
InputStreamSingleByteChunks {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext)
throws IOException {
InputStream in =
crypto.createDecryptingStream(masterKeyProvider, new ByteArrayInputStream(ciphertext));
ByteArrayOutputStream out = new ByteArrayOutputStream();
TestIOUtils.copyInStreamToOutStream(in, out, 1);
return out.toByteArray();
}
},
InputStreamSmallByteChunks {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext)
throws IOException {
InputStream in =
crypto.createDecryptingStream(masterKeyProvider, new ByteArrayInputStream(ciphertext));
ByteArrayOutputStream out = new ByteArrayOutputStream();
TestIOUtils.copyInStreamToOutStream(in, out, SMALL_CHUNK_SIZE);
return out.toByteArray();
}
},
InputStreamWholeMessageChunks {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext)
throws IOException {
InputStream in =
crypto.createDecryptingStream(masterKeyProvider, new ByteArrayInputStream(ciphertext));
ByteArrayOutputStream out = new ByteArrayOutputStream();
TestIOUtils.copyInStreamToOutStream(in, out, ciphertext.length);
return out.toByteArray();
}
},
UnsignedMessageInputStreamSingleByteChunks {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext)
throws IOException {
InputStream in =
crypto.createUnsignedMessageDecryptingStream(
masterKeyProvider, new ByteArrayInputStream(ciphertext));
ByteArrayOutputStream out = new ByteArrayOutputStream();
TestIOUtils.copyInStreamToOutStream(in, out, 1);
return out.toByteArray();
}
@Override
public SignaturePolicy signaturePolicy() {
return SignaturePolicy.AllowEncryptForbidDecrypt;
}
},
UnsignedMessageInputStreamSmallByteChunks {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext)
throws IOException {
InputStream in =
crypto.createUnsignedMessageDecryptingStream(
masterKeyProvider, new ByteArrayInputStream(ciphertext));
ByteArrayOutputStream out = new ByteArrayOutputStream();
TestIOUtils.copyInStreamToOutStream(in, out, SMALL_CHUNK_SIZE);
return out.toByteArray();
}
@Override
public SignaturePolicy signaturePolicy() {
return SignaturePolicy.AllowEncryptForbidDecrypt;
}
},
UnsignedMessageInputStreamWholeMessageChunks {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext)
throws IOException {
InputStream in =
crypto.createUnsignedMessageDecryptingStream(
masterKeyProvider, new ByteArrayInputStream(ciphertext));
ByteArrayOutputStream out = new ByteArrayOutputStream();
TestIOUtils.copyInStreamToOutStream(in, out, ciphertext.length);
return out.toByteArray();
}
@Override
public SignaturePolicy signaturePolicy() {
return SignaturePolicy.AllowEncryptForbidDecrypt;
}
},
OutputStreamSingleByteChunks {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext)
throws IOException {
InputStream in = new ByteArrayInputStream(ciphertext);
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream decryptingOut = crypto.createDecryptingStream(masterKeyProvider, out);
TestIOUtils.copyInStreamToOutStream(in, decryptingOut, 1);
return out.toByteArray();
}
},
OutputStreamSmallByteChunks {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext)
throws IOException {
InputStream in = new ByteArrayInputStream(ciphertext);
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream decryptingOut = crypto.createDecryptingStream(masterKeyProvider, out);
TestIOUtils.copyInStreamToOutStream(in, decryptingOut, SMALL_CHUNK_SIZE);
return out.toByteArray();
}
},
OutputStreamWholeMessageChunks {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext)
throws IOException {
InputStream in = new ByteArrayInputStream(ciphertext);
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream decryptingOut = crypto.createDecryptingStream(masterKeyProvider, out);
TestIOUtils.copyInStreamToOutStream(in, decryptingOut, ciphertext.length);
return out.toByteArray();
}
},
UnsignedMessageOutputStreamSingleByteChunks {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider masterKeyProvider, byte[] ciphertext)
throws IOException {
InputStream in = new ByteArrayInputStream(ciphertext);
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream decryptingOut =
crypto.createUnsignedMessageDecryptingStream(masterKeyProvider, out);
TestIOUtils.copyInStreamToOutStream(in, decryptingOut, 1);
return out.toByteArray();
}
@Override
public SignaturePolicy signaturePolicy() {
return SignaturePolicy.AllowEncryptForbidDecrypt;
}
},
UnsignedMessageOutputStreamSmallByteChunks {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider masterKeyProvider, byte[] ciphertext)
throws IOException {
InputStream in = new ByteArrayInputStream(ciphertext);
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream decryptingOut =
crypto.createUnsignedMessageDecryptingStream(masterKeyProvider, out);
TestIOUtils.copyInStreamToOutStream(in, decryptingOut, SMALL_CHUNK_SIZE);
return out.toByteArray();
}
@Override
public SignaturePolicy signaturePolicy() {
return SignaturePolicy.AllowEncryptForbidDecrypt;
}
},
UnsignedMessageOutputStreamWholeMessageChunks {
@Override
public byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider masterKeyProvider, byte[] ciphertext)
throws IOException {
InputStream in = new ByteArrayInputStream(ciphertext);
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream decryptingOut =
crypto.createUnsignedMessageDecryptingStream(masterKeyProvider, out);
TestIOUtils.copyInStreamToOutStream(in, decryptingOut, ciphertext.length);
return out.toByteArray();
}
@Override
public SignaturePolicy signaturePolicy() {
return SignaturePolicy.AllowEncryptForbidDecrypt;
}
};
// A semi-arbitrary chunk size just to have at least one non-boundary input, and something
// that will span at least some message segments.
private static final int SMALL_CHUNK_SIZE = 100;
public abstract byte[] decryptMessage(
AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext)
throws IOException;
public SignaturePolicy signaturePolicy() {
return SignaturePolicy.AllowEncryptAllowDecrypt;
}
}
| 5,363 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/TestVectorRunner.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import static java.lang.String.format;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.encryptionsdk.internal.SignaturePolicy;
import com.amazonaws.encryptionsdk.jce.JceMasterKey;
import com.amazonaws.encryptionsdk.kms.AwsKmsMrkAwareMasterKeyProvider;
import com.amazonaws.encryptionsdk.kms.DiscoveryFilter;
import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider;
import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory;
import com.amazonaws.util.IOUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.function.Supplier;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.util.encoders.Base64;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import software.amazon.awssdk.regions.Region;
@RunWith(Parameterized.class)
public class TestVectorRunner {
private static final int MANIFEST_VERSION = 2;
// We save the files in memory to avoid repeatedly retrieving them. This won't work if the
// plaintexts are too
// large or numerous
private static final Map<String, byte[]> cachedData = new HashMap<>();
private final String testName;
private final TestCase testCase;
private final DecryptionMethod decryptionMethod;
public TestVectorRunner(
final String testName, TestCase testCase, DecryptionMethod decryptionMethod) {
this.testName = testName;
this.testCase = testCase;
this.decryptionMethod = decryptionMethod;
}
@Test
public void decrypt() throws Exception {
AwsCrypto crypto =
AwsCrypto.builder()
.withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt)
.build();
Callable<byte[]> decryptor =
() ->
decryptionMethod.decryptMessage(
crypto, testCase.mkpSupplier.get(), cachedData.get(testCase.ciphertextPath));
testCase.matcher.Match(decryptor);
}
@Parameterized.Parameters(name = "Compatibility Test: {0} - {2}")
@SuppressWarnings("unchecked")
public static Collection<Object[]> data() throws Exception {
final String zipPath = System.getProperty("testVectorZip");
if (zipPath == null) {
return Collections.emptyList();
}
final JarURLConnection jarConnection =
(JarURLConnection) new URL("jar:" + zipPath + "!/").openConnection();
try (JarFile jar = jarConnection.getJarFile()) {
final Map<String, Object> manifest = readJsonMapFromJar(jar, "manifest.json");
final Map<String, Object> metaData = (Map<String, Object>) manifest.get("manifest");
// We only support "awses-decrypt" type manifests right now
if (!"awses-decrypt".equals(metaData.get("type"))) {
throw new IllegalArgumentException("Unsupported manifest type: " + metaData.get("type"));
}
if (!Integer.valueOf(MANIFEST_VERSION).equals(metaData.get("version"))) {
throw new IllegalArgumentException(
"Unsupported manifest version: " + metaData.get("version"));
}
final Map<String, KeyEntry> keys =
parseKeyManifest(readJsonMapFromJar(jar, (String) manifest.get("keys")));
final KmsMasterKeyProvider kmsProvV1 =
KmsMasterKeyProvider.builder()
.withCredentials(new DefaultAWSCredentialsProviderChain())
.buildDiscovery();
final com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider kmsProvV2 =
com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider.builder().buildDiscovery();
List<Object[]> testCases = new ArrayList<>();
for (Map.Entry<String, Map<String, Object>> testEntry :
((Map<String, Map<String, Object>>) manifest.get("tests")).entrySet()) {
String testName = testEntry.getKey();
TestCase testCaseV1 =
parseTest(testEntry.getKey(), testEntry.getValue(), keys, jar, kmsProvV1);
TestCase testCaseV2 =
parseTest(testEntry.getKey(), testEntry.getValue(), keys, jar, kmsProvV2);
for (DecryptionMethod decryptionMethod : DecryptionMethod.values()) {
if (testCaseV1.signaturePolicy.equals(decryptionMethod.signaturePolicy())) {
testCases.add(new Object[] {testName, testCaseV1, decryptionMethod});
testCases.add(new Object[] {testName + "-V2", testCaseV2, decryptionMethod});
}
}
}
return testCases;
}
}
@AfterClass
public static void teardown() {
cachedData.clear();
}
private static byte[] readBytesFromJar(JarFile jar, String fileName) throws IOException {
try (InputStream is = readFromJar(jar, fileName)) {
return IOUtils.toByteArray(is);
}
}
private static Map<String, Object> readJsonMapFromJar(JarFile jar, String fileName)
throws IOException {
try (InputStream is = readFromJar(jar, fileName)) {
final ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(is, new TypeReference<Map<String, Object>>() {});
}
}
private static InputStream readFromJar(JarFile jar, String name) throws IOException {
// Our manifest URIs incorrectly start with file:// rather than just file: so we need to strip
// this
ZipEntry entry = jar.getEntry(name.replaceFirst("^file://(?!/)", ""));
return jar.getInputStream(entry);
}
private static void cacheData(JarFile jar, String url) throws IOException {
if (!cachedData.containsKey(url)) {
cachedData.put(url, readBytesFromJar(jar, url));
}
}
@SuppressWarnings("unchecked")
private static <T> TestCase parseTest(
String testName,
Map<String, Object> data,
Map<String, KeyEntry> keys,
JarFile jar,
KmsMasterKeyProvider kmsProv)
throws IOException {
final String ciphertextURL = (String) data.get("ciphertext");
cacheData(jar, ciphertextURL);
Supplier<MasterKeyProvider<?>> mkpSupplier =
() -> {
@SuppressWarnings("generic")
final List<MasterKey<?>> mks = new ArrayList<>();
for (Map<String, Object> mkEntry : (List<Map<String, Object>>) data.get("master-keys")) {
final String type = (String) mkEntry.get("type");
final String keyName = (String) mkEntry.get("key");
final KeyEntry key = keys.get(keyName);
if ("aws-kms".equals(type)) {
mks.add(kmsProv.getMasterKey(key.keyId));
} else if ("aws-kms-mrk-aware".equals(type)) {
AwsKmsMrkAwareMasterKeyProvider provider =
AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(key.keyId);
mks.add(provider.getMasterKey(key.keyId));
} else if ("aws-kms-mrk-aware-discovery".equals(type)) {
final String defaultMrkRegion = (String) mkEntry.get("default-mrk-region");
final Map<String, Object> discoveryFilterSpec =
(Map<String, Object>) mkEntry.get("aws-kms-discovery-filter");
final DiscoveryFilter discoveryFilter;
if (discoveryFilterSpec != null) {
discoveryFilter =
new DiscoveryFilter(
(String) discoveryFilterSpec.get("partition"),
(List<String>) discoveryFilterSpec.get("account-ids"));
} else {
discoveryFilter = null;
}
return AwsKmsMrkAwareMasterKeyProvider.builder()
.withDiscoveryMrkRegion(defaultMrkRegion)
.buildDiscovery(discoveryFilter);
} else if ("raw".equals(type)) {
final String provId = (String) mkEntry.get("provider-id");
final String algorithm = (String) mkEntry.get("encryption-algorithm");
if ("aes".equals(algorithm)) {
mks.add(
JceMasterKey.getInstance(
(SecretKey) key.key, provId, key.keyId, "AES/GCM/NoPadding"));
} else if ("rsa".equals(algorithm)) {
String transformation = "RSA/ECB/";
final String padding = (String) mkEntry.get("padding-algorithm");
if ("pkcs1".equals(padding)) {
transformation += "PKCS1Padding";
} else if ("oaep-mgf1".equals(padding)) {
final String hashName =
((String) mkEntry.get("padding-hash")).replace("sha", "sha-").toUpperCase();
transformation += "OAEPWith" + hashName + "AndMGF1Padding";
} else {
throw new IllegalArgumentException("Unsupported padding:" + padding);
}
final PublicKey wrappingKey;
final PrivateKey unwrappingKey;
if (key.key instanceof PublicKey) {
wrappingKey = (PublicKey) key.key;
unwrappingKey = null;
} else {
wrappingKey = null;
unwrappingKey = (PrivateKey) key.key;
}
mks.add(
JceMasterKey.getInstance(
wrappingKey, unwrappingKey, provId, key.keyId, transformation));
} else {
throw new IllegalArgumentException("Unsupported algorithm: " + algorithm);
}
} else {
throw new IllegalArgumentException("Unsupported Key Type: " + type);
}
}
return MultipleProviderFactory.buildMultiProvider(mks);
};
@SuppressWarnings("unchecked")
final Map<String, Object> resultSpec = (Map<String, Object>) data.get("result");
final ResultMatcher matcher = parseResultMatcher(jar, resultSpec);
String decryptionMethodSpec = (String) data.get("decryption-method");
SignaturePolicy signaturePolicy = SignaturePolicy.AllowEncryptAllowDecrypt;
if (decryptionMethodSpec != null) {
if ("streaming-unsigned-only".equals(decryptionMethodSpec)) {
signaturePolicy = SignaturePolicy.AllowEncryptForbidDecrypt;
} else {
throw new IllegalArgumentException(
"Unsupported Decryption Method: " + decryptionMethodSpec);
}
}
return new TestCase(testName, ciphertextURL, mkpSupplier, matcher, signaturePolicy);
}
@SuppressWarnings("unchecked")
private static TestCase parseTest(
String testName,
Map<String, Object> data,
Map<String, KeyEntry> keys,
JarFile jar,
com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider kmsProv)
throws IOException {
final String ciphertextURL = (String) data.get("ciphertext");
cacheData(jar, ciphertextURL);
Supplier<MasterKeyProvider<?>> mkpSupplier =
() -> {
@SuppressWarnings("generic")
final List<MasterKey<?>> mks = new ArrayList<>();
for (Map<String, Object> mkEntry : (List<Map<String, Object>>) data.get("master-keys")) {
final String type = (String) mkEntry.get("type");
final String keyName = (String) mkEntry.get("key");
final KeyEntry key = keys.get(keyName);
if ("aws-kms".equals(type)) {
mks.add(kmsProv.getMasterKey(key.keyId));
} else if ("aws-kms-mrk-aware".equals(type)) {
com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyProvider provider =
com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyProvider.builder()
.buildStrict(key.keyId);
mks.add(provider.getMasterKey(key.keyId));
} else if ("aws-kms-mrk-aware-discovery".equals(type)) {
final String defaultMrkRegion = (String) mkEntry.get("default-mrk-region");
final Map<String, Object> discoveryFilterSpec =
(Map<String, Object>) mkEntry.get("aws-kms-discovery-filter");
final DiscoveryFilter discoveryFilter;
if (discoveryFilterSpec != null) {
discoveryFilter =
new DiscoveryFilter(
(String) discoveryFilterSpec.get("partition"),
(List<String>) discoveryFilterSpec.get("account-ids"));
} else {
discoveryFilter = null;
}
return com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyProvider.builder()
.discoveryMrkRegion(Region.of(defaultMrkRegion))
.buildDiscovery(discoveryFilter);
} else if ("raw".equals(type)) {
final String provId = (String) mkEntry.get("provider-id");
final String algorithm = (String) mkEntry.get("encryption-algorithm");
if ("aes".equals(algorithm)) {
mks.add(
JceMasterKey.getInstance(
(SecretKey) key.key, provId, key.keyId, "AES/GCM/NoPadding"));
} else if ("rsa".equals(algorithm)) {
String transformation = "RSA/ECB/";
final String padding = (String) mkEntry.get("padding-algorithm");
if ("pkcs1".equals(padding)) {
transformation += "PKCS1Padding";
} else if ("oaep-mgf1".equals(padding)) {
final String hashName =
((String) mkEntry.get("padding-hash")).replace("sha", "sha-").toUpperCase();
transformation += "OAEPWith" + hashName + "AndMGF1Padding";
} else {
throw new IllegalArgumentException("Unsupported padding:" + padding);
}
final PublicKey wrappingKey;
final PrivateKey unwrappingKey;
if (key.key instanceof PublicKey) {
wrappingKey = (PublicKey) key.key;
unwrappingKey = null;
} else {
wrappingKey = null;
unwrappingKey = (PrivateKey) key.key;
}
mks.add(
JceMasterKey.getInstance(
wrappingKey, unwrappingKey, provId, key.keyId, transformation));
} else {
throw new IllegalArgumentException("Unsupported algorithm: " + algorithm);
}
} else {
throw new IllegalArgumentException("Unsupported Key Type: " + type);
}
}
return MultipleProviderFactory.buildMultiProvider(mks);
};
@SuppressWarnings("unchecked")
final Map<String, Object> resultSpec = (Map<String, Object>) data.get("result");
final ResultMatcher matcher = parseResultMatcher(jar, resultSpec);
String decryptionMethodSpec = (String) data.get("decryption-method");
SignaturePolicy signaturePolicy = SignaturePolicy.AllowEncryptAllowDecrypt;
if (decryptionMethodSpec != null) {
if ("streaming-unsigned-only".equals(decryptionMethodSpec)) {
signaturePolicy = SignaturePolicy.AllowEncryptForbidDecrypt;
} else {
throw new IllegalArgumentException(
"Unsupported Decryption Method: " + decryptionMethodSpec);
}
}
return new TestCase(testName, ciphertextURL, mkpSupplier, matcher, signaturePolicy);
}
private static ResultMatcher parseResultMatcher(
final JarFile jar, final Map<String, Object> result) throws IOException {
if (result.size() != 1) {
throw new IllegalArgumentException("Unsupported result specification: " + result);
}
Map.Entry<String, Object> pair = result.entrySet().iterator().next();
if (pair.getKey().equals("output")) {
Map<String, String> outputSpec = (Map<String, String>) pair.getValue();
String plaintextUrl = outputSpec.get("plaintext");
cacheData(jar, plaintextUrl);
return new OutputResultMatcher(plaintextUrl);
} else if (pair.getKey().equals("error")) {
Map<String, String> errorSpec = (Map<String, String>) pair.getValue();
String errorDescription = errorSpec.get("error-description");
return new ErrorResultMatcher(errorDescription);
} else {
throw new IllegalArgumentException("Unsupported result specification: " + result);
}
}
@SuppressWarnings("unchecked")
private static Map<String, KeyEntry> parseKeyManifest(final Map<String, Object> keysManifest)
throws GeneralSecurityException {
// check our type
final Map<String, Object> metaData = (Map<String, Object>) keysManifest.get("manifest");
if (!"keys".equals(metaData.get("type"))) {
throw new IllegalArgumentException("Invalid manifest type: " + metaData.get("type"));
}
if (!Integer.valueOf(3).equals(metaData.get("version"))) {
throw new IllegalArgumentException("Invalid manifest version: " + metaData.get("version"));
}
final Map<String, KeyEntry> result = new HashMap<>();
Map<String, Object> keys = (Map<String, Object>) keysManifest.get("keys");
for (Map.Entry<String, Object> entry : keys.entrySet()) {
final String name = entry.getKey();
final Map<String, Object> data = (Map<String, Object>) entry.getValue();
final String keyType = (String) data.get("type");
final String encoding = (String) data.get("encoding");
final String keyId = (String) data.get("key-id");
final String material = (String) data.get("material"); // May be null
final String algorithm = (String) data.get("algorithm"); // May be null
final KeyEntry keyEntry;
final KeyFactory kf;
switch (keyType) {
case "symmetric":
if (!"base64".equals(encoding)) {
throw new IllegalArgumentException(
format("Key %s is symmetric but has encoding %s", keyId, encoding));
}
keyEntry =
new KeyEntry(
name,
keyId,
keyType,
new SecretKeySpec(Base64.decode(material), algorithm.toUpperCase()));
break;
case "private":
kf = KeyFactory.getInstance(algorithm);
if (!"pem".equals(encoding)) {
throw new IllegalArgumentException(
format("Key %s is private but has encoding %s", keyId, encoding));
}
byte[] pkcs8Key = parsePem(material);
keyEntry =
new KeyEntry(
name, keyId, keyType, kf.generatePrivate(new PKCS8EncodedKeySpec(pkcs8Key)));
break;
case "public":
kf = KeyFactory.getInstance(algorithm);
if (!"pem".equals(encoding)) {
throw new IllegalArgumentException(
format("Key %s is private but has encoding %s", keyId, encoding));
}
byte[] x509Key = parsePem(material);
keyEntry =
new KeyEntry(
name, keyId, keyType, kf.generatePublic(new X509EncodedKeySpec(x509Key)));
break;
case "aws-kms":
keyEntry = new KeyEntry(name, keyId, keyType, null);
break;
default:
throw new IllegalArgumentException("Unsupported key type: " + keyType);
}
result.put(name, keyEntry);
}
return result;
}
private static byte[] parsePem(String pem) {
final String stripped = pem.replaceAll("-+[A-Z ]+-+", "");
return Base64.decode(stripped);
}
private static class KeyEntry {
final String name;
final String keyId;
final String type;
final Key key;
private KeyEntry(String name, String keyId, String type, Key key) {
this.name = name;
this.keyId = keyId;
this.type = type;
this.key = key;
}
}
private static class TestCase {
private final String name;
private final String ciphertextPath;
private final ResultMatcher matcher;
private final Supplier<MasterKeyProvider<?>> mkpSupplier;
private final SignaturePolicy signaturePolicy;
private TestCase(
String name,
String ciphertextPath,
Supplier<MasterKeyProvider<?>> mkpSupplier,
ResultMatcher matcher,
SignaturePolicy signaturePolicy) {
this.name = name;
this.ciphertextPath = ciphertextPath;
this.matcher = matcher;
this.mkpSupplier = mkpSupplier;
this.signaturePolicy = signaturePolicy;
}
}
private interface ResultMatcher {
void Match(Callable<byte[]> decryptor) throws Exception;
}
private static class OutputResultMatcher implements ResultMatcher {
private final String plaintextPath;
private OutputResultMatcher(String plaintextPath) {
this.plaintextPath = plaintextPath;
}
@Override
public void Match(Callable<byte[]> decryptor) throws Exception {
final byte[] plaintext = decryptor.call();
final byte[] expectedPlaintext = cachedData.get(plaintextPath);
Assert.assertArrayEquals(expectedPlaintext, plaintext);
}
}
private static class ErrorResultMatcher implements ResultMatcher {
private final String errorDescription;
private ErrorResultMatcher(String errorDescription) {
this.errorDescription = errorDescription;
}
@Override
public void Match(Callable<byte[]> decryptor) {
Assert.assertThrows(
"Decryption expected to fail (" + errorDescription + ") but succeeded",
Exception.class,
decryptor::call);
}
}
}
| 5,364 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/CommitmentKATRunner.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.amazonaws.encryptionsdk.exception.BadCiphertextException;
import com.amazonaws.encryptionsdk.internal.Utils;
import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class CommitmentKATRunner {
private String comment;
private String keyringType;
private byte[] ciphertext;
private byte[] commitment;
private byte[] plaintext;
private byte[] decryptedDEK;
private byte[] messageId;
private byte[] header;
private Map<String, String> encryptionContext;
private boolean status;
private static final String TEST_VECTOR_RESOURCE_PATH = "/commitment-test-vectors.json";
public CommitmentKATRunner(
String comment,
String keyringType,
byte[] ciphertext,
byte[] commitment,
byte[] plaintext,
byte[] decryptedDEK,
byte[] messageId,
byte[] header,
Map<String, String> encryptionContext,
boolean status)
throws Exception {
this.comment = comment;
this.keyringType = keyringType;
this.ciphertext = ciphertext;
this.commitment = commitment;
this.plaintext = plaintext;
this.decryptedDEK = decryptedDEK;
this.messageId = messageId;
this.header = header;
this.encryptionContext = encryptionContext;
this.status = status;
}
@Parameters(
name = "{index}: testDecryptCommitment({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9})")
public static Collection<Object[]> data() throws Exception {
final String testVectorsName =
CommitmentKATRunner.class.getResource(TEST_VECTOR_RESOURCE_PATH).getPath();
final File ciphertextManifestFile = new File(testVectorsName);
final List<Object[]> testCases_ = new ArrayList<Object[]>();
if (!ciphertextManifestFile.exists()) {
throw new IllegalStateException(
"Missing commitment test vectors file from src/test/resources.");
}
final ObjectMapper ciphertextManifestMapper = new ObjectMapper();
final Map<String, Object> ciphertextManifest =
ciphertextManifestMapper.readValue(
ciphertextManifestFile, new TypeReference<Map<String, Object>>() {});
final List<Map<String, Object>> testCases =
(List<Map<String, Object>>) ciphertextManifest.get("tests");
for (Map<String, Object> test : testCases) {
final String keyringType = (String) test.get("keyring-type");
final byte[] decryptedDEK = Utils.decodeBase64String((String) test.get("decrypted-dek"));
final byte[] ciphertext = Utils.decodeBase64String((String) test.get("ciphertext"));
final byte[] commitment = Utils.decodeBase64String((String) test.get("commitment"));
final byte[] messageId = Utils.decodeBase64String((String) test.get("message-id"));
final byte[] header = Utils.decodeBase64String((String) test.get("header"));
final boolean status = (boolean) test.get("status");
final String comment = (String) test.get("comment");
final Map<String, String> encryptionContext =
(Map<String, String>) test.get("encryption-context");
// plaintext is available for cases which succeed decryption
byte[] plaintext = null;
if (status) {
final List<String> plaintextFrames = (List<String>) test.get("plaintext-frames");
plaintext = String.join("", plaintextFrames).getBytes(StandardCharsets.UTF_8);
}
testCases_.add(
new Object[] {
comment,
keyringType,
ciphertext,
commitment,
plaintext,
decryptedDEK,
messageId,
header,
encryptionContext,
status
});
}
return testCases_;
}
@Test
public void testDecryptCommitment() throws Exception {
final AwsCrypto crypto =
AwsCrypto.builder()
.withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt)
.build();
// Determine what MKP to test with based on whether the test case was create using kms or not.
// If it was, we can test decryption of the message completely end to end by using a
// Discovery KMS MKP.
// Otherwise, we must mock out a provider that just returns the data encryption key associated
// with the test case.
final MasterKeyProvider mkp;
switch (keyringType) {
case "aws-kms":
mkp = KmsMasterKeyProvider.builder().buildDiscovery();
break;
case "static":
default:
mkp = mock(MasterKeyProvider.class);
DataKey dataKey =
new DataKey(
// All committing algorithms use HkdfSHA512 for
// the kdf. If this changes, the test vectors
// will need to indicate what algorithm suite
// was used in order for this test to
// appropriately set the secret key spec's algorithm
new SecretKeySpec(decryptedDEK, "HkdfSHA512"), new byte[0], new byte[0], null);
when(mkp.decryptDataKey(any(), any(), any())).thenReturn(dataKey);
break;
}
// Ensure tests that are expected to fail do so with the right exception and error message
if (!status) {
assertThrows(
BadCiphertextException.class,
"Key commitment validation failed. Key identity does not "
+ "match the identity asserted in the message. Halting processing of this message.",
() -> crypto.decryptData(mkp, ciphertext));
return;
}
// Otherwise ensure our result matches the expected commitment data
final CryptoResult decryptResult = crypto.decryptData(mkp, ciphertext);
assertArrayEquals(decryptResult.getHeaders().getSuiteData(), commitment);
assertArrayEquals(decryptResult.getHeaders().getMessageId(), messageId);
assertArrayEquals(decryptResult.getHeaders().toByteArray(), header);
assertTrue(decryptResult.getEncryptionContext().equals(encryptionContext));
assertArrayEquals((byte[]) decryptResult.getResult(), plaintext);
}
}
| 5,365 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/ParsedCiphertextTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static org.junit.Assert.*;
import static org.mockito.Mockito.spy;
import com.amazonaws.encryptionsdk.exception.AwsCryptoException;
import com.amazonaws.encryptionsdk.exception.BadCiphertextException;
import com.amazonaws.encryptionsdk.internal.StaticMasterKey;
import com.amazonaws.encryptionsdk.model.CiphertextHeaders;
import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
public class ParsedCiphertextTest extends CiphertextHeaders {
private static final int MESSAGE_FORMAT_MAX_EDKS = (1 << 16) - 1;
private StaticMasterKey masterKeyProvider;
private AwsCrypto encryptionClient_;
@Before
public void init() {
masterKeyProvider = spy(new StaticMasterKey("testmaterial"));
encryptionClient_ =
AwsCrypto.builder()
.withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt)
.build();
encryptionClient_.setEncryptionAlgorithm(
CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256);
}
@Test()
public void goodParsedCiphertext() {
final int byteSize = 0;
final int frameSize = 0;
final byte[] plaintextBytes = new byte[byteSize];
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC1", "ParsedCiphertext test with %d" + byteSize);
encryptionClient_.setEncryptionFrameSize(frameSize);
final byte[] cipherText =
encryptionClient_
.encryptData(masterKeyProvider, plaintextBytes, encryptionContext)
.getResult();
final ParsedCiphertext pCt = new ParsedCiphertext(cipherText);
assertNotNull(pCt.getCiphertext());
assertTrue(pCt.getOffset() > 0);
}
@Test(expected = BadCiphertextException.class)
public void incompleteZeroByteCiphertext() {
final byte[] cipherText = {};
ParsedCiphertext pCt = new ParsedCiphertext(cipherText);
}
@Test(expected = BadCiphertextException.class)
public void incompleteSingleByteCiphertext() {
final byte[] cipherText = {1 /* Original ciphertext version number */};
ParsedCiphertext pCt = new ParsedCiphertext(cipherText);
}
@Test(expected = BadCiphertextException.class)
public void incompleteCiphertext() {
final int byteSize = 0;
final int frameSize = 0;
final byte[] plaintextBytes = new byte[byteSize];
final Map<String, String> encryptionContext = new HashMap<String, String>(1);
encryptionContext.put("ENC1", "ParsedCiphertext test with %d" + byteSize);
encryptionClient_.setEncryptionFrameSize(frameSize);
final byte[] cipherText =
encryptionClient_
.encryptData(masterKeyProvider, plaintextBytes, encryptionContext)
.getResult();
ParsedCiphertext pCt = new ParsedCiphertext(cipherText);
byte[] incompleteCiphertext = Arrays.copyOf(pCt.getCiphertext(), pCt.getOffset() - 1);
ParsedCiphertext badPCt = new ParsedCiphertext(incompleteCiphertext);
}
private MasterKeyProvider<?> providerWithEdks(int numEdks) {
List<MasterKeyProvider<?>> providers = new ArrayList<>();
for (int i = 0; i < numEdks; i++) {
providers.add(masterKeyProvider);
}
return MultipleProviderFactory.buildMultiProvider(providers);
}
@Test
public void lessThanMaxEdks() {
MasterKeyProvider<?> provider = providerWithEdks(2);
CryptoResult<byte[], ?> result = encryptionClient_.encryptData(provider, new byte[] {1});
ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult(), 3);
assertEquals(ciphertext.getEncryptedKeyBlobCount(), 2);
}
@Test
public void equalToMaxEdks() {
MasterKeyProvider<?> provider = providerWithEdks(3);
CryptoResult<byte[], ?> result = encryptionClient_.encryptData(provider, new byte[] {1});
ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult(), 3);
assertEquals(ciphertext.getEncryptedKeyBlobCount(), 3);
}
@Test
public void failMoreThanMaxEdks() {
MasterKeyProvider<?> provider = providerWithEdks(4);
CryptoResult<byte[], ?> result = encryptionClient_.encryptData(provider, new byte[] {1});
assertThrows(
AwsCryptoException.class,
"Ciphertext encrypted data keys exceed maxEncryptedDataKeys",
() -> new ParsedCiphertext(result.getResult(), 3));
}
@Test
public void noMaxEdks() {
MasterKeyProvider<?> provider = providerWithEdks(MESSAGE_FORMAT_MAX_EDKS);
CryptoResult<byte[], ?> result = encryptionClient_.encryptData(provider, new byte[] {1});
// explicit no-max
ParsedCiphertext ciphertext =
new ParsedCiphertext(result.getResult(), CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS);
assertEquals(ciphertext.getEncryptedKeyBlobCount(), MESSAGE_FORMAT_MAX_EDKS);
// implicit no-max
ciphertext = new ParsedCiphertext(result.getResult());
assertEquals(ciphertext.getEncryptedKeyBlobCount(), MESSAGE_FORMAT_MAX_EDKS);
}
}
| 5,366 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/MockKMSClient.java | /*
* Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except
* in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.amazonaws.encryptionsdk.kms;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.ResponseMetadata;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.kms.AWSKMSClient;
import com.amazonaws.services.kms.model.CreateAliasRequest;
import com.amazonaws.services.kms.model.CreateAliasResult;
import com.amazonaws.services.kms.model.CreateGrantRequest;
import com.amazonaws.services.kms.model.CreateGrantResult;
import com.amazonaws.services.kms.model.CreateKeyRequest;
import com.amazonaws.services.kms.model.CreateKeyResult;
import com.amazonaws.services.kms.model.DecryptRequest;
import com.amazonaws.services.kms.model.DecryptResult;
import com.amazonaws.services.kms.model.DeleteAliasRequest;
import com.amazonaws.services.kms.model.DeleteAliasResult;
import com.amazonaws.services.kms.model.DescribeKeyRequest;
import com.amazonaws.services.kms.model.DescribeKeyResult;
import com.amazonaws.services.kms.model.DisableKeyRequest;
import com.amazonaws.services.kms.model.DisableKeyResult;
import com.amazonaws.services.kms.model.DisableKeyRotationRequest;
import com.amazonaws.services.kms.model.DisableKeyRotationResult;
import com.amazonaws.services.kms.model.EnableKeyRequest;
import com.amazonaws.services.kms.model.EnableKeyResult;
import com.amazonaws.services.kms.model.EnableKeyRotationRequest;
import com.amazonaws.services.kms.model.EnableKeyRotationResult;
import com.amazonaws.services.kms.model.EncryptRequest;
import com.amazonaws.services.kms.model.EncryptResult;
import com.amazonaws.services.kms.model.GenerateDataKeyRequest;
import com.amazonaws.services.kms.model.GenerateDataKeyResult;
import com.amazonaws.services.kms.model.GenerateDataKeyWithoutPlaintextRequest;
import com.amazonaws.services.kms.model.GenerateDataKeyWithoutPlaintextResult;
import com.amazonaws.services.kms.model.GenerateRandomRequest;
import com.amazonaws.services.kms.model.GenerateRandomResult;
import com.amazonaws.services.kms.model.GetKeyPolicyRequest;
import com.amazonaws.services.kms.model.GetKeyPolicyResult;
import com.amazonaws.services.kms.model.GetKeyRotationStatusRequest;
import com.amazonaws.services.kms.model.GetKeyRotationStatusResult;
import com.amazonaws.services.kms.model.InvalidCiphertextException;
import com.amazonaws.services.kms.model.KeyMetadata;
import com.amazonaws.services.kms.model.KeyUsageType;
import com.amazonaws.services.kms.model.ListAliasesRequest;
import com.amazonaws.services.kms.model.ListAliasesResult;
import com.amazonaws.services.kms.model.ListGrantsRequest;
import com.amazonaws.services.kms.model.ListGrantsResult;
import com.amazonaws.services.kms.model.ListKeyPoliciesRequest;
import com.amazonaws.services.kms.model.ListKeyPoliciesResult;
import com.amazonaws.services.kms.model.ListKeysRequest;
import com.amazonaws.services.kms.model.ListKeysResult;
import com.amazonaws.services.kms.model.NotFoundException;
import com.amazonaws.services.kms.model.PutKeyPolicyRequest;
import com.amazonaws.services.kms.model.PutKeyPolicyResult;
import com.amazonaws.services.kms.model.ReEncryptRequest;
import com.amazonaws.services.kms.model.ReEncryptResult;
import com.amazonaws.services.kms.model.RetireGrantRequest;
import com.amazonaws.services.kms.model.RetireGrantResult;
import com.amazonaws.services.kms.model.RevokeGrantRequest;
import com.amazonaws.services.kms.model.RevokeGrantResult;
import com.amazonaws.services.kms.model.UpdateKeyDescriptionRequest;
import com.amazonaws.services.kms.model.UpdateKeyDescriptionResult;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class MockKMSClient extends AWSKMSClient {
private static final SecureRandom rnd = new SecureRandom();
private static final String ACCOUNT_ID = "01234567890";
private final Map<DecryptMapKey, DecryptResult> results_ = new HashMap<>();
private final Set<String> activeKeys = new HashSet<>();
private final Map<String, String> keyAliases = new HashMap<>();
private Region region_ = Region.getRegion(Regions.DEFAULT_REGION);
@Override
public CreateAliasResult createAlias(CreateAliasRequest arg0)
throws AmazonServiceException, AmazonClientException {
assertExists(arg0.getTargetKeyId());
keyAliases.put("alias/" + arg0.getAliasName(), keyAliases.get(arg0.getTargetKeyId()));
return new CreateAliasResult();
}
@Override
public CreateGrantResult createGrant(CreateGrantRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public CreateKeyResult createKey() throws AmazonServiceException, AmazonClientException {
return createKey(new CreateKeyRequest());
}
@Override
public CreateKeyResult createKey(CreateKeyRequest req)
throws AmazonServiceException, AmazonClientException {
String keyId = UUID.randomUUID().toString();
String arn = "arn:aws:kms:" + region_.getName() + ":" + ACCOUNT_ID + ":key/" + keyId;
activeKeys.add(arn);
keyAliases.put(keyId, arn);
keyAliases.put(arn, arn);
CreateKeyResult result = new CreateKeyResult();
result.setKeyMetadata(
new KeyMetadata()
.withAWSAccountId(ACCOUNT_ID)
.withCreationDate(new Date())
.withDescription(req.getDescription())
.withEnabled(true)
.withKeyId(keyId)
.withKeyUsage(KeyUsageType.ENCRYPT_DECRYPT)
.withArn(arn));
return result;
}
@Override
public DecryptResult decrypt(DecryptRequest req)
throws AmazonServiceException, AmazonClientException {
DecryptResult result = results_.get(new DecryptMapKey(req));
if (result != null) {
// Copy it to avoid external modification
DecryptResult copy = new DecryptResult();
copy.setKeyId(retrieveArn(result.getKeyId()));
byte[] pt = new byte[result.getPlaintext().limit()];
result.getPlaintext().get(pt);
result.getPlaintext().rewind();
copy.setPlaintext(ByteBuffer.wrap(pt));
return copy;
} else {
throw new InvalidCiphertextException("Invalid Ciphertext");
}
}
@Override
public DeleteAliasResult deleteAlias(DeleteAliasRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public DescribeKeyResult describeKey(DescribeKeyRequest arg0)
throws AmazonServiceException, AmazonClientException {
final String arn = retrieveArn(arg0.getKeyId());
final KeyMetadata keyMetadata = new KeyMetadata().withArn(arn).withKeyId(arn);
final DescribeKeyResult describeKeyResult =
new DescribeKeyResult().withKeyMetadata(keyMetadata);
return describeKeyResult;
}
@Override
public DisableKeyResult disableKey(DisableKeyRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public DisableKeyRotationResult disableKeyRotation(DisableKeyRotationRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public EnableKeyResult enableKey(EnableKeyRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public EnableKeyRotationResult enableKeyRotation(EnableKeyRotationRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public EncryptResult encrypt(EncryptRequest req)
throws AmazonServiceException, AmazonClientException {
// We internally delegate to encrypt, so as to avoid mockito detecting extra calls to encrypt
// when spying on the
// MockKMSClient, we put the real logic into a separate function.
return encrypt0(req);
}
private EncryptResult encrypt0(EncryptRequest req)
throws AmazonServiceException, AmazonClientException {
final byte[] cipherText = new byte[512];
rnd.nextBytes(cipherText);
DecryptResult dec = new DecryptResult();
dec.withKeyId(retrieveArn(req.getKeyId())).withPlaintext(req.getPlaintext().asReadOnlyBuffer());
ByteBuffer ctBuff = ByteBuffer.wrap(cipherText);
results_.put(new DecryptMapKey(ctBuff, req.getEncryptionContext()), dec);
String arn = retrieveArn(req.getKeyId());
return new EncryptResult().withCiphertextBlob(ctBuff).withKeyId(arn);
}
@Override
public GenerateDataKeyResult generateDataKey(GenerateDataKeyRequest req)
throws AmazonServiceException, AmazonClientException {
byte[] pt;
if (req.getKeySpec() != null) {
if (req.getKeySpec().contains("256")) {
pt = new byte[32];
} else if (req.getKeySpec().contains("128")) {
pt = new byte[16];
} else {
throw new java.lang.UnsupportedOperationException();
}
} else {
pt = new byte[req.getNumberOfBytes()];
}
rnd.nextBytes(pt);
ByteBuffer ptBuff = ByteBuffer.wrap(pt);
EncryptResult encryptResult =
encrypt0(
new EncryptRequest()
.withKeyId(req.getKeyId())
.withPlaintext(ptBuff)
.withEncryptionContext(req.getEncryptionContext()));
String arn = retrieveArn(req.getKeyId());
return new GenerateDataKeyResult()
.withKeyId(arn)
.withCiphertextBlob(encryptResult.getCiphertextBlob())
.withPlaintext(ptBuff);
}
@Override
public GenerateDataKeyWithoutPlaintextResult generateDataKeyWithoutPlaintext(
GenerateDataKeyWithoutPlaintextRequest req)
throws AmazonServiceException, AmazonClientException {
GenerateDataKeyRequest generateDataKeyRequest =
new GenerateDataKeyRequest()
.withEncryptionContext(req.getEncryptionContext())
.withGrantTokens(req.getGrantTokens())
.withKeyId(req.getKeyId())
.withKeySpec(req.getKeySpec())
.withNumberOfBytes(req.getNumberOfBytes());
GenerateDataKeyResult generateDataKey = generateDataKey(generateDataKeyRequest);
String arn = retrieveArn(req.getKeyId());
return new GenerateDataKeyWithoutPlaintextResult()
.withCiphertextBlob(generateDataKey.getCiphertextBlob())
.withKeyId(arn);
}
@Override
public GenerateRandomResult generateRandom()
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public GenerateRandomResult generateRandom(GenerateRandomRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest arg0) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public GetKeyPolicyResult getKeyPolicy(GetKeyPolicyRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public GetKeyRotationStatusResult getKeyRotationStatus(GetKeyRotationStatusRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public ListAliasesResult listAliases() throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public ListAliasesResult listAliases(ListAliasesRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public ListGrantsResult listGrants(ListGrantsRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public ListKeyPoliciesResult listKeyPolicies(ListKeyPoliciesRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public ListKeysResult listKeys() throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public ListKeysResult listKeys(ListKeysRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public PutKeyPolicyResult putKeyPolicy(PutKeyPolicyRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public ReEncryptResult reEncrypt(ReEncryptRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public RetireGrantResult retireGrant(RetireGrantRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public RevokeGrantResult revokeGrant(RevokeGrantRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public void setEndpoint(String arg0) {
// Do nothing
}
@Override
public void setRegion(Region arg0) {
region_ = arg0;
}
@Override
public void shutdown() {
// Do nothing
}
@Override
public UpdateKeyDescriptionResult updateKeyDescription(UpdateKeyDescriptionRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new java.lang.UnsupportedOperationException();
}
public void deleteKey(final String keyId) {
final String arn = retrieveArn(keyId);
activeKeys.remove(arn);
}
private String retrieveArn(final String keyId) {
String arn = keyAliases.get(keyId);
assertExists(arn);
return arn;
}
private void assertExists(String keyId) {
if (keyAliases.containsKey(keyId)) {
keyId = keyAliases.get(keyId);
}
if (keyId == null || !activeKeys.contains(keyId)) {
throw new NotFoundException("Key doesn't exist: " + keyId);
}
}
private static class DecryptMapKey {
private final ByteBuffer cipherText;
private final Map<String, String> ec;
public DecryptMapKey(DecryptRequest req) {
cipherText = req.getCiphertextBlob().asReadOnlyBuffer();
if (req.getEncryptionContext() != null) {
ec = Collections.unmodifiableMap(new HashMap<String, String>(req.getEncryptionContext()));
} else {
ec = Collections.emptyMap();
}
}
public DecryptMapKey(ByteBuffer ctBuff, Map<String, String> ec) {
cipherText = ctBuff.asReadOnlyBuffer();
if (ec != null) {
this.ec = Collections.unmodifiableMap(new HashMap<String, String>(ec));
} else {
this.ec = Collections.emptyMap();
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cipherText == null) ? 0 : cipherText.hashCode());
result = prime * result + ((ec == null) ? 0 : ec.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
DecryptMapKey other = (DecryptMapKey) obj;
if (cipherText == null) {
if (other.cipherText != null) return false;
} else if (!cipherText.equals(other.cipherText)) return false;
if (ec == null) {
if (other.ec != null) return false;
} else if (!ec.equals(other.ec)) return false;
return true;
}
@Override
public String toString() {
return "DecryptMapKey [cipherText=" + cipherText + ", ec=" + ec + "]";
}
}
}
| 5,367 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/KMSProviderBuilderMockTests.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kms;
import static com.amazonaws.encryptionsdk.multi.MultipleProviderFactory.buildMultiProvider;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.notNull;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.RequestClientOptions;
import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.MasterKeyProvider;
import com.amazonaws.encryptionsdk.internal.VersionInfo;
import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider.RegionalClientSupplier;
import com.amazonaws.services.kms.model.CreateAliasRequest;
import com.amazonaws.services.kms.model.DecryptRequest;
import com.amazonaws.services.kms.model.EncryptRequest;
import com.amazonaws.services.kms.model.GenerateDataKeyRequest;
import java.util.Arrays;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
public class KMSProviderBuilderMockTests {
@Test
public void testBareAliasMapping() {
MockKMSClient client = spy(new MockKMSClient());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(notNull())).thenReturn(client);
String key1 = client.createKey().getKeyMetadata().getKeyId();
client.createAlias(new CreateAliasRequest().withAliasName("foo").withTargetKeyId(key1));
KmsMasterKeyProvider mkp0 =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.withDefaultRegion("us-west-2")
.buildStrict("alias/foo");
AwsCrypto.standard().encryptData(mkp0, new byte[0]);
}
@Test
public void testGrantTokenPassthrough_usingMKsetCall() throws Exception {
MockKMSClient client = spy(new MockKMSClient());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
String key1 = client.createKey().getKeyMetadata().getArn();
String key2 = client.createKey().getKeyMetadata().getArn();
KmsMasterKeyProvider mkp0 =
KmsMasterKeyProvider.builder()
.withDefaultRegion("us-west-2")
.withCustomClientFactory(supplier)
.buildStrict(key1, key2);
KmsMasterKey mk1 = mkp0.getMasterKey(key1);
KmsMasterKey mk2 = mkp0.getMasterKey(key2);
mk1.setGrantTokens(singletonList("foo"));
mk2.setGrantTokens(singletonList("foo"));
MasterKeyProvider<?> mkp = buildMultiProvider(mk1, mk2);
byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[0]).getResult();
ArgumentCaptor<GenerateDataKeyRequest> gdkr =
ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
verify(client, times(1)).generateDataKey(gdkr.capture());
assertEquals(key1, gdkr.getValue().getKeyId());
assertEquals(1, gdkr.getValue().getGrantTokens().size());
assertEquals("foo", gdkr.getValue().getGrantTokens().get(0));
ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class);
verify(client, times(1)).encrypt(er.capture());
assertEquals(key2, er.getValue().getKeyId());
assertEquals(1, er.getValue().getGrantTokens().size());
assertEquals("foo", er.getValue().getGrantTokens().get(0));
AwsCrypto.standard().decryptData(mkp, ciphertext);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decrypt.capture());
assertEquals(1, decrypt.getValue().getGrantTokens().size());
assertEquals("foo", decrypt.getValue().getGrantTokens().get(0));
verify(supplier, atLeastOnce()).getClient("us-west-2");
verifyNoMoreInteractions(supplier);
}
@Test
public void testGrantTokenPassthrough_usingMKPWithers() throws Exception {
MockKMSClient client = spy(new MockKMSClient());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
String key1 = client.createKey().getKeyMetadata().getArn();
String key2 = client.createKey().getKeyMetadata().getArn();
KmsMasterKeyProvider mkp0 =
KmsMasterKeyProvider.builder()
.withDefaultRegion("us-west-2")
.withCustomClientFactory(supplier)
.buildStrict(key1, key2);
MasterKeyProvider<?> mkp = mkp0.withGrantTokens("foo");
byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[0]).getResult();
ArgumentCaptor<GenerateDataKeyRequest> gdkr =
ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
verify(client, times(1)).generateDataKey(gdkr.capture());
assertEquals(key1, gdkr.getValue().getKeyId());
assertEquals(1, gdkr.getValue().getGrantTokens().size());
assertEquals("foo", gdkr.getValue().getGrantTokens().get(0));
ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class);
verify(client, times(1)).encrypt(er.capture());
assertEquals(key2, er.getValue().getKeyId());
assertEquals(1, er.getValue().getGrantTokens().size());
assertEquals("foo", er.getValue().getGrantTokens().get(0));
mkp = mkp0.withGrantTokens(Arrays.asList("bar"));
AwsCrypto.standard().decryptData(mkp, ciphertext);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decrypt.capture());
assertEquals(1, decrypt.getValue().getGrantTokens().size());
assertEquals("bar", decrypt.getValue().getGrantTokens().get(0));
verify(supplier, atLeastOnce()).getClient("us-west-2");
verifyNoMoreInteractions(supplier);
}
@Test
public void testUserAgentPassthrough() throws Exception {
MockKMSClient client = spy(new MockKMSClient());
String key1 = client.createKey().getKeyMetadata().getArn();
String key2 = client.createKey().getKeyMetadata().getArn();
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(ignored -> client)
.buildStrict(key1, key2);
AwsCrypto.standard()
.decryptData(mkp, AwsCrypto.standard().encryptData(mkp, new byte[0]).getResult());
ArgumentCaptor<GenerateDataKeyRequest> gdkr =
ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
verify(client, times(1)).generateDataKey(gdkr.capture());
assertTrue(getUA(gdkr.getValue()).contains(VersionInfo.loadUserAgent()));
ArgumentCaptor<EncryptRequest> encr = ArgumentCaptor.forClass(EncryptRequest.class);
verify(client, times(1)).encrypt(encr.capture());
assertTrue(getUA(encr.getValue()).contains(VersionInfo.loadUserAgent()));
ArgumentCaptor<DecryptRequest> decr = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decr.capture());
assertTrue(getUA(decr.getValue()).contains(VersionInfo.loadUserAgent()));
}
private String getUA(AmazonWebServiceRequest request) {
// Note: This test may break in future versions of the AWS SDK, as Marker is documented as being
// for internal
// use only.
return request
.getRequestClientOptions()
.getClientMarker(RequestClientOptions.Marker.USER_AGENT);
}
}
| 5,368 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/KMSTestFixtures.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kms;
public final class KMSTestFixtures {
private KMSTestFixtures() {
throw new UnsupportedOperationException(
"This class exists to hold static constants and cannot be instantiated.");
}
/**
* These special test keys have been configured to allow Encrypt, Decrypt, and GenerateDataKey
* operations from any AWS principal and should be used when adding new KMS tests.
*
* <p>This should go without saying, but never use these keys for production purposes (as anyone
* in the world can decrypt data encrypted using them).
*/
public static final String US_WEST_2_KEY_ID =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
public static final String EU_CENTRAL_1_KEY_ID =
"arn:aws:kms:eu-central-1:658956600833:key/75414c93-5285-4b57-99c9-30c1cf0a22c2";
public static final String US_EAST_1_MULTI_REGION_KEY_ID =
"arn:aws:kms:us-east-1:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7";
public static final String US_WEST_2_MULTI_REGION_KEY_ID =
"arn:aws:kms:us-west-2:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7";
public static final String ACCOUNT_ID = "658956600833";
public static final String PARTITION = "aws";
public static final String US_WEST_2 = "us-west-2";
public static final String[] TEST_KEY_IDS = new String[] {US_WEST_2_KEY_ID, EU_CENTRAL_1_KEY_ID};
}
| 5,369 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/DiscoveryFilterTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kms;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static org.junit.Assert.assertNotNull;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
public class DiscoveryFilterTest {
@Test
public void testValidConstruct() throws Exception {
DiscoveryFilter filter = new DiscoveryFilter("partition", Arrays.asList("accountId"));
assertNotNull(filter);
DiscoveryFilter filter2 = new DiscoveryFilter("partition", "accountId1", "accountId2");
assertNotNull(filter2);
}
@Test
public void testConstructWithEmptyPartition() throws Exception {
assertThrows(
IllegalArgumentException.class, () -> new DiscoveryFilter("", Arrays.asList("accountId")));
assertThrows(IllegalArgumentException.class, () -> new DiscoveryFilter("", "accountId"));
}
@Test
public void testConstructWithNullPartition() throws Exception {
assertThrows(
IllegalArgumentException.class,
() -> new DiscoveryFilter(null, Arrays.asList("accountId")));
assertThrows(IllegalArgumentException.class, () -> new DiscoveryFilter(null, "accountId"));
}
@Test
public void testConstructWithEmptyIds() throws Exception {
assertThrows(
IllegalArgumentException.class, () -> new DiscoveryFilter("aws", Collections.emptyList()));
}
@Test
public void testConstructWithNullIds() throws Exception {
assertThrows(
IllegalArgumentException.class, () -> new DiscoveryFilter("aws", (List<String>) null));
}
@Test
public void testConstructWithIdsContainingEmptyId() throws Exception {
assertThrows(
IllegalArgumentException.class,
() -> new DiscoveryFilter("aws", Arrays.asList("accountId", "")));
assertThrows(IllegalArgumentException.class, () -> new DiscoveryFilter("aws", "accountId", ""));
}
@Test
public void testConstructWithIdsContainingNullId() throws Exception {
assertThrows(
IllegalArgumentException.class,
() -> new DiscoveryFilter("aws", Arrays.asList("accountId", null)));
assertThrows(
IllegalArgumentException.class, () -> new DiscoveryFilter("aws", "accountId", null));
}
}
| 5,370 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/MaxEncryptedDataKeysIntegrationTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kms;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.TestUtils;
import com.amazonaws.encryptionsdk.exception.AwsCryptoException;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.AWSKMSClientBuilder;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class MaxEncryptedDataKeysIntegrationTest {
private static final byte[] PLAINTEXT = {1, 2, 3, 4};
private static final int MAX_EDKS = 3;
private AWSKMS testClient_;
private KmsMasterKeyProvider.RegionalClientSupplier testClientSupplier_;
private AwsCrypto testCryptoClient_;
@Before
public void setup() {
testClient_ = spy(AWSKMSClientBuilder.standard().withRegion("us-west-2").build());
testClientSupplier_ =
regionName -> {
if (regionName.equals("us-west-2")) {
return testClient_;
}
throw new AwsCryptoException(
"test supplier only configured for us-west-2 and eu-central-1");
};
testCryptoClient_ = AwsCrypto.standard().toBuilder().withMaxEncryptedDataKeys(MAX_EDKS).build();
}
private KmsMasterKeyProvider providerWithEdks(int numKeys) {
List<String> keyIds = new ArrayList<>(numKeys);
for (int i = 0; i < numKeys; i++) {
keyIds.add(KMSTestFixtures.US_WEST_2_KEY_ID);
}
return KmsMasterKeyProvider.builder()
.withCustomClientFactory(testClientSupplier_)
.buildStrict(keyIds);
}
@Test
public void encryptDecryptWithLessThanMaxEdks() {
KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS - 1);
byte[] ciphertext = testCryptoClient_.encryptData(provider, PLAINTEXT).getResult();
byte[] decrypted = testCryptoClient_.decryptData(provider, ciphertext).getResult();
assertArrayEquals(decrypted, PLAINTEXT);
}
@Test
public void encryptDecryptWithMaxEdks() {
KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS);
byte[] ciphertext = testCryptoClient_.encryptData(provider, PLAINTEXT).getResult();
byte[] decrypted = testCryptoClient_.decryptData(provider, ciphertext).getResult();
assertArrayEquals(decrypted, PLAINTEXT);
}
@Test
public void noEncryptWithMoreThanMaxEdks() {
KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS + 1);
TestUtils.assertThrows(
AwsCryptoException.class,
"Encrypted data keys exceed maxEncryptedDataKeys",
() -> testCryptoClient_.encryptData(provider, PLAINTEXT));
}
@Test
public void noDecryptWithMoreThanMaxEdks() {
KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS + 1);
byte[] ciphertext = AwsCrypto.standard().encryptData(provider, PLAINTEXT).getResult();
TestUtils.assertThrows(
AwsCryptoException.class,
"Ciphertext encrypted data keys exceed maxEncryptedDataKeys",
() -> testCryptoClient_.decryptData(provider, ciphertext));
verify(testClient_, never()).decrypt(any());
}
}
| 5,371 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/AwsKmsMrkAwareMasterKeyTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kms;
import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate;
import static org.junit.Assert.*;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.RequestClientOptions;
import com.amazonaws.encryptionsdk.*;
import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException;
import com.amazonaws.encryptionsdk.internal.VersionInfo;
import com.amazonaws.encryptionsdk.model.KeyBlob;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.model.*;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
@RunWith(Enclosed.class)
public class AwsKmsMrkAwareMasterKeyTest {
public static class getInstance {
@Test
public void basic_use() {
AWSKMS client = spy(new MockKMSClient());
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6
// = type=test
// # On initialization, the caller MUST provide:
final AwsKmsMrkAwareMasterKey test =
AwsKmsMrkAwareMasterKey.getInstance(
client,
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f",
mkp);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.5
// = type=test
// # MUST implement the Master Key Interface (../master-key-
// # interface.md#interface)
assertTrue(MasterKey.class.isInstance(test));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6
// = type=test
// # The AWS KMS key identifier MUST NOT be null or empty.
public void requires_valid_identifiers() {
AWSKMS client = spy(new MockKMSClient());
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
assertThrows(
IllegalArgumentException.class,
() -> AwsKmsMrkAwareMasterKey.getInstance(client, "", mkp));
assertThrows(
IllegalArgumentException.class,
() -> AwsKmsMrkAwareMasterKey.getInstance(client, null, mkp));
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6
// = type=test
// # The AWS KMS
// # key identifier MUST be a valid identifier (aws-kms-key-arn.md#a-
// # valid-aws-kms-identifier).
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKey.getInstance(
client, "arn:aws:dynamodb:us-east-2:123456789012:table/myDynamoDBTable", mkp));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6
// = type=test
// # The AWS KMS SDK client MUST not be null.
public void requires_valid_client() {
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKey.getInstance(
null,
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f",
mkp));
}
@Test
public void requires_valid_provider() {
AWSKMS client = spy(new MockKMSClient());
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKey.getInstance(
client,
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f",
null));
}
}
public static class generateDataKey {
@Test
public void basic_use() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final ByteBuffer udk = ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength());
final ByteBuffer ciphertext = ByteBuffer.allocate(10);
final AWSKMS client = mock(AWSKMS.class);
when(client.generateDataKey(any()))
.thenReturn(
new GenerateDataKeyResult()
.withPlaintext(udk)
.withKeyId(keyIdentifier)
.withCiphertextBlob(ciphertext));
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn("aws-kms");
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6
// = type=test
// # The master key MUST be able to be configured with an optional list of
// # Grant Tokens.
masterKey.setGrantTokens(GRANT_TOKENS);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # The inputs MUST be the same as the Master Key Generate Data Key
// # (../master-key-interface.md#generate-data-key) interface.
DataKey<AwsKmsMrkAwareMasterKey> test =
masterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT);
ArgumentCaptor<GenerateDataKeyRequest> gr =
ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # This
// # master key MUST use the configured AWS KMS client to make an AWS KMS
// # GenerateDatakey (https://docs.aws.amazon.com/kms/latest/APIReference/
// # API_GenerateDataKey.html) request constructed as follows:
verify(client, times(1)).generateDataKey(gr.capture());
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # The output MUST be the same as the Master Key Generate Data Key
// # (../master-key-interface.md#generate-data-key) interface.
assertTrue(DataKey.class.isInstance(test));
GenerateDataKeyRequest actualRequest = gr.getValue();
assertEquals(keyIdentifier, actualRequest.getKeyId());
assertEquals(GRANT_TOKENS, actualRequest.getGrantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext());
assertEquals(
ALGORITHM_SUITE.getDataKeyLength(), actualRequest.getNumberOfBytes().longValue());
assertTrue(
actualRequest
.getRequestClientOptions()
.getClientMarker(RequestClientOptions.Marker.USER_AGENT)
.contains(VersionInfo.loadUserAgent()));
assertNotNull(test.getKey());
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # The response's "Plaintext" MUST be the plaintext in
// # the output.
assertEquals(ALGORITHM_SUITE.getDataKeyLength(), test.getKey().getEncoded().length);
assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), test.getKey().getAlgorithm());
assertNotNull(test.getEncryptedDataKey());
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # The response's cipher text blob MUST be used as the
// # returned as the ciphertext for the encrypted data key in the output.
assertEquals(10, test.getEncryptedDataKey().length);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # If the call succeeds the AWS KMS Generate Data Key response's
// # "Plaintext" MUST match the key derivation input length specified by
// # the algorithm suite included in the input.
public void length_must_match() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
// I use more, because less _should_ trigger an underflow... but the condition should _always_
// fail
final int wrongLength = ALGORITHM_SUITE.getDataKeyLength() + 1;
final AWSKMS client = mock(AWSKMS.class);
when(client.generateDataKey(any()))
.thenReturn(
new GenerateDataKeyResult()
.withPlaintext(ByteBuffer.allocate(wrongLength))
.withKeyId(keyIdentifier)
.withCiphertextBlob(ByteBuffer.allocate(10)));
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn("aws-kms");
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
assertThrows(
IllegalStateException.class,
() -> masterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT));
}
@Test
public void need_an_arn() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final AWSKMS client = mock(AWSKMS.class);
when(client.generateDataKey(any()))
.thenReturn(
new GenerateDataKeyResult()
.withPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()))
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # The response's "KeyId"
// # MUST be valid.
.withKeyId("b3537ef1-d8dc-4780-9f5a-55776cbb2f7f")
.withCiphertextBlob(ByteBuffer.allocate(10)));
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn("aws-kms");
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
assertThrows(
IllegalStateException.class,
() -> masterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT));
}
}
public static class encryptDataKey {
@Test
public void basic_use() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final SecretKey SECRET_KEY =
new SecretKeySpec(
generate(ALGORITHM_SUITE.getDataKeyLength()), ALGORITHM_SUITE.getDataKeyAlgo());
final MasterKeyProvider<AwsKmsMrkAwareMasterKey> mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn("aws-kms");
final DataKey dataKey =
new DataKey(
SECRET_KEY,
new byte[0],
"aws-kms".getBytes(StandardCharsets.UTF_8),
mock(MasterKey.class));
final AWSKMS client = mock(AWSKMS.class);
when(client.encrypt(any()))
.thenReturn(
new EncryptResult()
.withKeyId(keyIdentifier)
.withCiphertextBlob(ByteBuffer.allocate(10)));
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
// = type=test
// # The inputs MUST be the same as the Master Key Encrypt Data Key
// # (../master-key-interface.md#encrypt-data-key) interface.
DataKey<AwsKmsMrkAwareMasterKey> test =
masterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
// = type=test
// # The output MUST be the same as the Master Key Encrypt Data Key
// # (../master-key-interface.md#encrypt-data-key) interface.
assertTrue(DataKey.class.isInstance(test));
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
// = type=test
// # The master
// # key MUST use the configured AWS KMS client to make an AWS KMS Encrypt
// # (https://docs.aws.amazon.com/kms/latest/APIReference/
// # API_Encrypt.html) request constructed as follows:
verify(client, times(1)).encrypt(any());
ArgumentCaptor<EncryptRequest> gr = ArgumentCaptor.forClass(EncryptRequest.class);
verify(client, times(1)).encrypt(gr.capture());
final EncryptRequest actualRequest = gr.getValue();
assertEquals(keyIdentifier, actualRequest.getKeyId());
assertEquals(GRANT_TOKENS, actualRequest.getGrantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext());
assertTrue(
actualRequest
.getRequestClientOptions()
.getClientMarker(RequestClientOptions.Marker.USER_AGENT)
.contains(VersionInfo.loadUserAgent()));
assertNotNull(test.getKey());
assertEquals(ALGORITHM_SUITE.getDataKeyLength(), test.getKey().getEncoded().length);
assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), test.getKey().getAlgorithm());
assertNotNull(test.getEncryptedDataKey());
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
// = type=test
// # The
// # response's cipher text blob MUST be used as the "ciphertext" for the
// # encrypted data key.
assertEquals(10, test.getEncryptedDataKey().length);
}
@Test
public void secret_key_must_be_raw() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final MasterKeyProvider<AwsKmsMrkAwareMasterKey> mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn("aws-kms");
// Test "stuff" here
final SecretKey SECRET_KEY = mock(SecretKeySpec.class);
when(SECRET_KEY.getFormat()).thenReturn("NOT-RAW");
final DataKey dataKey =
new DataKey(
SECRET_KEY,
new byte[0],
"aws-kms".getBytes(StandardCharsets.UTF_8),
mock(MasterKey.class));
final AWSKMS client = mock(AWSKMS.class);
when(client.encrypt(any()))
.thenReturn(
new EncryptResult()
.withKeyId(keyIdentifier)
.withCiphertextBlob(ByteBuffer.allocate(10)));
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
assertThrows(
"Only RAW encoded keys are supported",
IllegalArgumentException.class,
() -> masterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey));
}
@Test
public void need_an_arn() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final SecretKey SECRET_KEY =
new SecretKeySpec(
generate(ALGORITHM_SUITE.getDataKeyLength()), ALGORITHM_SUITE.getDataKeyAlgo());
final MasterKeyProvider<AwsKmsMrkAwareMasterKey> mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn("aws-kms");
final DataKey dataKey =
new DataKey(
SECRET_KEY,
new byte[0],
"aws-kms".getBytes(StandardCharsets.UTF_8),
mock(MasterKey.class));
final AWSKMS client = mock(AWSKMS.class);
when(client.encrypt(any()))
.thenReturn(
new EncryptResult()
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
// = type=test
// # The AWS KMS Encrypt response MUST contain a valid "KeyId".
.withKeyId("b3537ef1-d8dc-4780-9f5a-55776cbb2f7f")
.withCiphertextBlob(ByteBuffer.allocate(10)));
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
assertThrows(
IllegalStateException.class,
() -> masterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey));
}
}
public static class filterEncryptedDataKeys {
@Test
public void basic_use() {
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
assertTrue(AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(providerId, keyIdentifier, edk));
}
@Test
public void mrk_specific() {
/* This may be overkill,
* but the whole point
* of multi-region optimization
* is this fuzzy match.
*/
final String configuredIdentifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String ekdIdentifier =
"arn:aws:kms:us-east-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String providerId = "aws-kms";
final EncryptedDataKey edk =
new KeyBlob(providerId, ekdIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
assertTrue(
AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(providerId, configuredIdentifier, edk));
}
@Test
public void provider_info_must_be_arn() {
final String configuredIdentifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String rawKeyId = "mrk-edb7fe6942894d32ac46dbb1c922d574";
final String alias =
"arn:aws:kms:us-west-2:111122223333:alias/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String providerId = "aws-kms";
final EncryptedDataKey edkNotArn =
new KeyBlob(providerId, rawKeyId.getBytes(StandardCharsets.UTF_8), new byte[10]);
final EncryptedDataKey edkAliasArn =
new KeyBlob(providerId, rawKeyId.getBytes(StandardCharsets.UTF_8), new byte[10]);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # Additionally each provider info MUST be a valid AWS KMS ARN
// # (aws-kms-key-arn.md#a-valid-aws-kms-arn) with a resource type of
// # "key".
assertThrows(
IllegalStateException.class,
() ->
AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(
providerId, configuredIdentifier, edkNotArn));
assertThrows(
IllegalStateException.class,
() ->
AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(
providerId, configuredIdentifier, edkAliasArn));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # To match the encrypted data key's
// # provider ID MUST exactly match the value "aws-kms" and the the
// # function AWS KMS MRK Match for Decrypt (aws-kms-mrk-match-for-
// # decrypt.md#implementation) called with the configured AWS KMS key
// # identifier and the encrypted data key's provider info MUST return
// # "true".
public void may_not_match() {
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
assertFalse(
AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys("not-aws-kms", keyIdentifier, edk));
assertFalse(
AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(
providerId,
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
edk));
}
}
public static class decryptSingleEncryptedDataKey {
@Test
public void basic_use() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final AWSKMS client = mock(AWSKMS.class);
when(client.decrypt(any()))
.thenReturn(
new DecryptResult()
.withKeyId(keyIdentifier)
.withPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength())));
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
DataKey<AwsKmsMrkAwareMasterKey> test =
AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey(
any(), client, keyIdentifier, GRANT_TOKENS, ALGORITHM_SUITE, edk, ENCRYPTION_CONTEXT);
verify(client, times(1)).decrypt(any());
ArgumentCaptor<DecryptRequest> gr = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(gr.capture());
final DecryptRequest actualRequest = gr.getValue();
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # To decrypt the encrypted data key this master key MUST use the
// # configured AWS KMS client to make an AWS KMS Decrypt
// # (https://docs.aws.amazon.com/kms/latest/APIReference/
// # API_Decrypt.html) request constructed as follows:
assertEquals(keyIdentifier, actualRequest.getKeyId());
assertEquals(GRANT_TOKENS, actualRequest.getGrantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext());
assertTrue(
actualRequest
.getRequestClientOptions()
.getClientMarker(RequestClientOptions.Marker.USER_AGENT)
.contains(VersionInfo.loadUserAgent()));
assertNotNull(test.getKey());
assertEquals(ALGORITHM_SUITE.getDataKeyLength(), test.getKey().getEncoded().length);
assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), test.getKey().getAlgorithm());
}
@Test
public void expect_key_arn() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final AWSKMS client = mock(AWSKMS.class);
when(client.decrypt(any()))
.thenReturn(
new DecryptResult()
.withKeyId(null)
.withPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength())));
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
assertThrows(
IllegalStateException.class,
() ->
AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey(
any(),
client,
keyIdentifier,
GRANT_TOKENS,
ALGORITHM_SUITE,
edk,
ENCRYPTION_CONTEXT));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # If the call succeeds then the response's "KeyId" MUST be equal to the
// # configured AWS KMS key identifier otherwise the function MUST collect
// # an error.
public void returned_arn_must_match() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final AWSKMS client = mock(AWSKMS.class);
when(client.decrypt(any()))
.thenReturn(
new DecryptResult()
.withKeyId("arn:aws:kms:us-west-2:658956600833:key/something-else")
.withPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength())));
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
assertThrows(
IllegalStateException.class,
() ->
AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey(
any(),
client,
keyIdentifier,
GRANT_TOKENS,
ALGORITHM_SUITE,
edk,
ENCRYPTION_CONTEXT));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # The response's "Plaintext"'s length MUST equal the length
// # required by the requested algorithm suite otherwise the function MUST
// # collect an error.
public void key_length_must_match() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
// I use more, because less _should_ trigger an underflow... but the condition should _always_
// fail
final int wrongLength = ALGORITHM_SUITE.getDataKeyLength() + 1;
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final AWSKMS client = mock(AWSKMS.class);
when(client.decrypt(any()))
.thenReturn(
new DecryptResult()
.withKeyId(keyIdentifier)
.withPlaintext(ByteBuffer.allocate(wrongLength)));
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
assertThrows(
IllegalStateException.class,
() ->
AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey(
any(),
client,
keyIdentifier,
GRANT_TOKENS,
ALGORITHM_SUITE,
edk,
ENCRYPTION_CONTEXT));
}
}
public static class decryptDataKey {
@Test
public void basic_use() {
final String keyIdentifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final byte[] cipherText = new byte[10];
final String providerId = "aws-kms";
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final EncryptedDataKey edk1 =
new KeyBlob("aws-kms", keyIdentifier.getBytes(StandardCharsets.UTF_8), cipherText);
final EncryptedDataKey edk2 =
new KeyBlob("aws-kms", keyIdentifier.getBytes(StandardCharsets.UTF_8), cipherText);
final AWSKMS client = mock(AWSKMS.class);
when(client.decrypt(any()))
.thenReturn(
new DecryptResult()
.withKeyId(keyIdentifier)
.withPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength())));
final AwsKmsMrkAwareMasterKey mk =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
mk.setGrantTokens(GRANT_TOKENS);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # The inputs MUST be the same as the Master Key Decrypt Data Key
// # (../master-key-interface.md#decrypt-data-key) interface.
final DataKey<AwsKmsMrkAwareMasterKey> test =
mk.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk1, edk2), ENCRYPTION_CONTEXT);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # For each encrypted data key in the filtered set, one at a time, the
// # master key MUST attempt to decrypt the data key.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # If the AWS KMS response satisfies the requirements then it MUST be
// # use and this function MUST return and not attempt to decrypt any more
// # encrypted data keys.
verify(client, times((1)))
.decrypt(
new DecryptRequest()
.withGrantTokens(GRANT_TOKENS)
.withEncryptionContext(ENCRYPTION_CONTEXT)
.withKeyId(keyIdentifier)
.withCiphertextBlob(ByteBuffer.wrap(cipherText)));
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # The output MUST be the same as the Master Key Decrypt Data Key
// # (../master-key-interface.md#decrypt-data-key) interface.
assertTrue(DataKey.class.isInstance(test));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # The set of encrypted data keys MUST first be filtered to match this
// # master key's configuration.
public void edk_match() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final String clientErrMsg = "asdf";
final EncryptedDataKey edk1 =
new KeyBlob("not-aws-kms", keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final EncryptedDataKey edk2 =
new KeyBlob(
providerId, "not-key-identifier".getBytes(StandardCharsets.UTF_8), new byte[10]);
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final AWSKMS client = mock(AWSKMS.class);
when(client.decrypt(any())).thenThrow(new AmazonServiceException(clientErrMsg));
final KmsMasterKeyProvider.RegionalClientSupplier supplier =
mock(KmsMasterKeyProvider.RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
final AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
final CannotUnwrapDataKeyException testProviderNotMatch =
assertThrows(
"Unable to decrypt any data keys",
CannotUnwrapDataKeyException.class,
() ->
masterKey.decryptDataKey(
ALGORITHM_SUITE, Arrays.asList(edk1), ENCRYPTION_CONTEXT));
assertEquals(0, testProviderNotMatch.getSuppressed().length);
final IllegalStateException testArnNotMatch =
assertThrows(
"Unable to decrypt any data keys",
IllegalStateException.class,
() ->
masterKey.decryptDataKey(
ALGORITHM_SUITE, Arrays.asList(edk2), ENCRYPTION_CONTEXT));
assertEquals(0, testArnNotMatch.getSuppressed().length);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # If this attempt
// # results in an error, then these errors MUST be collected.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # If all the input encrypted data keys have been processed then this
// # function MUST yield an error that includes all the collected errors.
public void exception_wrapped() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final String clientErrMsg = "asdf";
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final AWSKMS client = mock(AWSKMS.class);
when(client.decrypt(any())).thenThrow(new AmazonServiceException(clientErrMsg));
KmsMasterKeyProvider.RegionalClientSupplier supplier =
mock(KmsMasterKeyProvider.RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
final CannotUnwrapDataKeyException test =
assertThrows(
"Unable to decrypt any data keys",
CannotUnwrapDataKeyException.class,
() ->
masterKey.decryptDataKey(
ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT));
assertEquals(1, test.getSuppressed().length);
Throwable fromClient = Arrays.stream(test.getSuppressed()).findFirst().get();
assertTrue(fromClient instanceof AmazonServiceException);
assertTrue(fromClient.getMessage().startsWith(clientErrMsg));
}
}
public static class getMasterKey {
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.7
// = type=test
// # MUST be unchanged from the Master Key interface.
public void test_get_master_key() throws NoSuchMethodException {
String methodName = "getMasterKey";
Class<?>[] parameterTypes = new Class<?>[] {String.class, String.class};
// Make sure the signature is correct by fetching the base method
Method baseMethod = MasterKey.class.getDeclaredMethod(methodName, parameterTypes);
assertNotNull(baseMethod);
// Assert AwsKmsMrkAwareMasterKey does not declare the same method directly
assertThrows(
NoSuchMethodException.class,
() -> AwsKmsMrkAwareMasterKey.class.getDeclaredMethod(methodName, parameterTypes));
}
}
public static class getMasterKeysForEncryption {
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.8
// = type=test
// # MUST be unchanged from the Master Key interface.
public void test_getMasterKeysForEncryption() throws NoSuchMethodException {
String methodName = "getMasterKeysForEncryption";
Class<?>[] parameterTypes = new Class<?>[] {MasterKeyRequest.class};
// Make sure the signature is correct by fetching the base method
Method baseMethod = MasterKey.class.getDeclaredMethod(methodName, parameterTypes);
assertNotNull(baseMethod);
// Assert AwsKmsMrkAwareMasterKey does no declare the same method directly
assertThrows(
NoSuchMethodException.class,
() -> AwsKmsMrkAwareMasterKey.class.getDeclaredMethod(methodName, parameterTypes));
}
}
}
| 5,372 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/XCompatKmsDecryptTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kms;
import static org.junit.Assert.assertArrayEquals;
import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.CryptoResult;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class XCompatKmsDecryptTest {
private String plaintextFileName;
private String ciphertextFileName;
private String kmsKeyId;
public XCompatKmsDecryptTest(
String plaintextFileName, String ciphertextFileName, String kmsKeyId) {
this.plaintextFileName = plaintextFileName;
this.ciphertextFileName = ciphertextFileName;
this.kmsKeyId = kmsKeyId;
}
@Parameters(name = "{index}: testDecryptFromFile({0}, {1}, {2})")
public static Collection<Object[]> data() throws Exception {
String baseDirName;
baseDirName = System.getProperty("staticCompatibilityResourcesDir");
if (baseDirName == null) {
baseDirName =
XCompatKmsDecryptTest.class.getProtectionDomain().getCodeSource().getLocation().getPath()
+ "aws_encryption_sdk_resources";
}
List<Object[]> testCases_ = new ArrayList<Object[]>();
String ciphertextManifestName =
StringUtils.join(
new String[] {baseDirName, "manifests", "ciphertext.manifest"}, File.separator);
File ciphertextManifestFile = new File(ciphertextManifestName);
if (!ciphertextManifestFile.exists()) {
return Collections.emptyList();
}
ObjectMapper ciphertextManifestMapper = new ObjectMapper();
Map<String, Object> ciphertextManifest =
ciphertextManifestMapper.readValue(
ciphertextManifestFile, new TypeReference<Map<String, Object>>() {});
List<Map<String, Object>> testCases =
(List<Map<String, Object>>) ciphertextManifest.get("test_cases");
for (Map<String, Object> testCase : testCases) {
Map<String, String> plaintext = (Map<String, String>) testCase.get("plaintext");
Map<String, String> ciphertext = (Map<String, String>) testCase.get("ciphertext");
List<Map<String, Object>> masterKeys =
(List<Map<String, Object>>) testCase.get("master_keys");
for (Map<String, Object> masterKey : masterKeys) {
String providerId = (String) masterKey.get("provider_id");
if (providerId.equals("aws-kms") && (boolean) masterKey.get("decryptable")) {
testCases_.add(
new Object[] {
baseDirName + File.separator + plaintext.get("filename"),
baseDirName + File.separator + ciphertext.get("filename"),
(String) masterKey.get("key_id")
});
break;
}
}
}
return testCases_;
}
@Test
public void testDecryptFromFile() throws Exception {
AwsCrypto crypto = AwsCrypto.standard();
final KmsMasterKeyProvider masterKeyProvider =
KmsMasterKeyProvider.builder().buildStrict(kmsKeyId);
byte ciphertextBytes[] = Files.readAllBytes(Paths.get(ciphertextFileName));
byte plaintextBytes[] = Files.readAllBytes(Paths.get(plaintextFileName));
final CryptoResult decryptResult = crypto.decryptData(masterKeyProvider, ciphertextBytes);
assertArrayEquals(plaintextBytes, (byte[]) decryptResult.getResult());
}
}
| 5,373 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/KMSProviderBuilderIntegrationTests.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kms;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import com.amazonaws.AbortedException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Request;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.CryptoAlgorithm;
import com.amazonaws.encryptionsdk.CryptoResult;
import com.amazonaws.encryptionsdk.EncryptedDataKey;
import com.amazonaws.encryptionsdk.MasterKeyProvider;
import com.amazonaws.encryptionsdk.exception.AwsCryptoException;
import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException;
import com.amazonaws.encryptionsdk.internal.VersionInfo;
import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider.RegionalClientSupplier;
import com.amazonaws.encryptionsdk.model.KeyBlob;
import com.amazonaws.handlers.RequestHandler2;
import com.amazonaws.http.exception.HttpRequestTimeoutException;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.AWSKMSClientBuilder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
public class KMSProviderBuilderIntegrationTests {
private static final String AWS_KMS_PROVIDER_ID = "aws-kms";
private AWSKMS testUSWestClient__;
private AWSKMS testEUCentralClient__;
private RegionalClientSupplier testClientSupplier__;
@Before
public void setup() {
testUSWestClient__ = spy(AWSKMSClientBuilder.standard().withRegion("us-west-2").build());
testEUCentralClient__ = spy(AWSKMSClientBuilder.standard().withRegion("eu-central-1").build());
testClientSupplier__ =
regionName -> {
if (regionName.equals("us-west-2")) {
return testUSWestClient__;
} else if (regionName.equals("eu-central-1")) {
return testEUCentralClient__;
} else {
throw new AwsCryptoException(
"test supplier only configured for us-west-2 and eu-central-1");
}
};
}
@Test
public void whenBogusRegionsDecrypted_doesNotLeakClients() throws Exception {
AtomicReference<ConcurrentHashMap<String, AWSKMS>> kmsCache = new AtomicReference<>();
KmsMasterKeyProvider mkp =
(new KmsMasterKeyProvider.Builder() {
@Override
protected void snoopClientCache(final ConcurrentHashMap<String, AWSKMS> map) {
kmsCache.set(map);
}
})
.buildDiscovery();
try {
mkp.decryptDataKey(
CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256,
Collections.singleton(
new KeyBlob(
"aws-kms",
"arn:aws:kms:us-bogus-1:123456789010:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"
.getBytes(StandardCharsets.UTF_8),
new byte[40])),
new HashMap<>());
fail("Expected CannotUnwrapDataKeyException");
} catch (CannotUnwrapDataKeyException e) {
// ok
}
assertTrue(kmsCache.get().isEmpty());
}
@Test
public void whenOperationSuccessful_clientIsCached() {
AtomicReference<ConcurrentHashMap<String, AWSKMS>> kmsCache = new AtomicReference<>();
KmsMasterKeyProvider mkp =
(new KmsMasterKeyProvider.Builder() {
@Override
protected void snoopClientCache(final ConcurrentHashMap<String, AWSKMS> map) {
kmsCache.set(map);
}
})
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
AwsCrypto.standard().encryptData(mkp, new byte[1]);
AWSKMS kms = kmsCache.get().get("us-west-2");
assertNotNull(kms);
AwsCrypto.standard().encryptData(mkp, new byte[1]);
// Cache entry should stay the same
assertEquals(kms, kmsCache.get().get("us-west-2"));
}
@Test
public void whenConstructedWithoutArguments_canUseMultipleRegions() throws Exception {
KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder().buildDiscovery();
for (String key : KMSTestFixtures.TEST_KEY_IDS) {
byte[] ciphertext =
AwsCrypto.standard()
.encryptData(KmsMasterKeyProvider.builder().buildStrict(key), new byte[1])
.getResult();
AwsCrypto.standard().decryptData(mkp, ciphertext);
}
}
@Test
public void whenConstructedInStrictMode_encryptDecrypt() throws Exception {
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(testClientSupplier__)
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[1]).getResult();
verify(testUSWestClient__, times(1)).generateDataKey(any());
AwsCrypto.standard().decryptData(mkp, ciphertext);
verify(testUSWestClient__, times(1)).decrypt(any());
}
@Test
public void whenConstructedInStrictMode_encryptDecryptMultipleCmks() throws Exception {
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(testClientSupplier__)
.buildStrict(KMSTestFixtures.US_WEST_2_KEY_ID, KMSTestFixtures.EU_CENTRAL_1_KEY_ID);
byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[1]).getResult();
verify(testUSWestClient__, times(1)).generateDataKey(any());
verify(testEUCentralClient__, times(1)).encrypt(any());
AwsCrypto.standard().decryptData(mkp, ciphertext);
verify(testUSWestClient__, times(1)).decrypt(any());
}
@Test
public void whenConstructedInStrictMode_encryptSingleBadKeyIdFails() throws Exception {
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(testClientSupplier__)
.withDefaultRegion("us-west-2")
.buildStrict(KMSTestFixtures.US_WEST_2_KEY_ID, "badKeyId");
assertThrows(
AwsCryptoException.class,
() -> AwsCrypto.standard().encryptData(mkp, new byte[1]).getResult());
verify(testUSWestClient__, times(1)).generateDataKey(any());
verify(testUSWestClient__, times(1)).encrypt(any());
}
@Test
public void whenConstructedInStrictMode_decryptBadEDKFails() throws Exception {
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(testClientSupplier__)
.withDefaultRegion("us-west-2")
.buildStrict("badKeyId");
final CryptoAlgorithm algSuite = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> encCtx = Collections.singletonMap("myKey", "myValue");
final EncryptedDataKey badEDK =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
"badKeyId".getBytes(StandardCharsets.UTF_8),
new byte[algSuite.getDataKeyLength()]);
assertThrows(
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(algSuite, Collections.singletonList(badEDK), encCtx));
verify(testUSWestClient__, times(1)).decrypt(any());
}
@Test
public void whenConstructedInDiscoveryMode_decrypt() throws Exception {
KmsMasterKeyProvider singleCmkMkp =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(testClientSupplier__)
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
byte[] singleCmkCiphertext =
AwsCrypto.standard().encryptData(singleCmkMkp, new byte[1]).getResult();
KmsMasterKeyProvider mkpToTest =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(testClientSupplier__)
.buildDiscovery();
AwsCrypto.standard().decryptData(mkpToTest, singleCmkCiphertext);
verify(testUSWestClient__, times(1)).decrypt(any());
}
@Test
public void whenConstructedInDiscoveryMode_decryptBadEDKFails() throws Exception {
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(testClientSupplier__)
.withDefaultRegion("us-west-2")
.buildDiscovery();
final CryptoAlgorithm algSuite = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> encCtx = Collections.singletonMap("myKey", "myValue");
final EncryptedDataKey badEDK =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
"badKeyId".getBytes(StandardCharsets.UTF_8),
new byte[algSuite.getDataKeyLength()]);
assertThrows(
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(algSuite, Collections.singletonList(badEDK), encCtx));
verify(testUSWestClient__, times(1)).decrypt(any());
}
@Test
public void whenConstructedWithDiscoveryFilter_decrypt() throws Exception {
KmsMasterKeyProvider singleCmkMkp =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(testClientSupplier__)
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
byte[] singleCmkCiphertext =
AwsCrypto.standard().encryptData(singleCmkMkp, new byte[1]).getResult();
KmsMasterKeyProvider mkpToTest =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(testClientSupplier__)
.buildDiscovery(
new DiscoveryFilter(
KMSTestFixtures.PARTITION, Arrays.asList(KMSTestFixtures.ACCOUNT_ID)));
AwsCrypto.standard().decryptData(mkpToTest, singleCmkCiphertext);
verify(testUSWestClient__, times(1)).decrypt(any());
}
@Test
public void whenConstructedWithDiscoveryFilter_decryptBadEDKFails() throws Exception {
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(testClientSupplier__)
.withDefaultRegion("us-west-2")
.buildDiscovery(
new DiscoveryFilter(
KMSTestFixtures.PARTITION, Arrays.asList(KMSTestFixtures.ACCOUNT_ID)));
final CryptoAlgorithm algSuite = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> encCtx = Collections.singletonMap("myKey", "myValue");
final String badARN = "arn:aws:kms:us-west-2:658956600833:key/badID";
final EncryptedDataKey badEDK =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
badARN.getBytes(StandardCharsets.UTF_8),
new byte[algSuite.getDataKeyLength()]);
assertThrows(
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(algSuite, Collections.singletonList(badEDK), encCtx));
verify(testUSWestClient__, times(1)).decrypt(any());
}
@Test
public void whenHandlerConfigured_handlerIsInvoked() throws Exception {
RequestHandler2 handler = spy(new RequestHandler2() {});
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.withClientBuilder(AWSKMSClientBuilder.standard().withRequestHandlers(handler))
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
AwsCrypto.standard().encryptData(mkp, new byte[1]);
verify(handler).beforeRequest(any());
}
@Test
public void whenShortTimeoutSet_timesOut() throws Exception {
// By setting a timeout of 1ms, it's not physically possible to complete both the us-west-2 and
// eu-central-1
// requests due to speed of light limits.
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.withClientBuilder(
AWSKMSClientBuilder.standard()
.withClientConfiguration(new ClientConfiguration().withRequestTimeout(1)))
.buildStrict(Arrays.asList(KMSTestFixtures.TEST_KEY_IDS));
try {
AwsCrypto.standard().encryptData(mkp, new byte[1]);
fail("Expected exception");
} catch (Exception e) {
if (e instanceof AbortedException) {
// ok - one manifestation of a timeout
} else if (e.getCause() instanceof HttpRequestTimeoutException) {
// ok - another kind of timeout
} else {
throw e;
}
}
}
@Test
public void whenCustomCredentialsSet_theyAreUsed() throws Exception {
AWSCredentialsProvider customProvider = spy(new DefaultAWSCredentialsProviderChain());
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.withCredentials(customProvider)
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
AwsCrypto.standard().encryptData(mkp, new byte[1]);
verify(customProvider, atLeastOnce()).getCredentials();
AWSCredentials customCredentials = spy(customProvider.getCredentials());
mkp =
KmsMasterKeyProvider.builder()
.withCredentials(customCredentials)
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
AwsCrypto.standard().encryptData(mkp, new byte[1]);
verify(customCredentials, atLeastOnce()).getAWSSecretKey();
}
@Test
public void whenBuilderCloned_configurationIsRetained() throws Exception {
AWSCredentialsProvider customProvider1 = spy(new DefaultAWSCredentialsProviderChain());
AWSCredentialsProvider customProvider2 = spy(new DefaultAWSCredentialsProviderChain());
KmsMasterKeyProvider.Builder builder =
KmsMasterKeyProvider.builder().withCredentials(customProvider1);
KmsMasterKeyProvider.Builder builder2 = builder.clone();
// This will mutate the first builder to change the creds, but leave the clone unchanged.
MasterKeyProvider<?> mkp2 =
builder.withCredentials(customProvider2).buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
MasterKeyProvider<?> mkp1 = builder2.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
CryptoResult<byte[], ?> result = AwsCrypto.standard().encryptData(mkp1, new byte[0]);
verify(customProvider1, atLeastOnce()).getCredentials();
verify(customProvider2, never()).getCredentials();
reset(customProvider1, customProvider2);
result = AwsCrypto.standard().encryptData(mkp2, new byte[0]);
verify(customProvider1, never()).getCredentials();
verify(customProvider2, atLeastOnce()).getCredentials();
}
@Test
public void whenBuilderCloned_clientBuilderCustomizationIsRetained() throws Exception {
RequestHandler2 handler = spy(new RequestHandler2() {});
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.withClientBuilder(AWSKMSClientBuilder.standard().withRequestHandlers(handler))
.clone()
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
AwsCrypto.standard().encryptData(mkp, new byte[0]);
verify(handler, atLeastOnce()).beforeRequest(any());
}
@Test(expected = IllegalArgumentException.class)
public void whenBogusEndpointIsSet_constructionFails() throws Exception {
KmsMasterKeyProvider.builder()
.withClientBuilder(
AWSKMSClientBuilder.standard()
.withEndpointConfiguration(
new AwsClientBuilder.EndpointConfiguration(
"https://this.does.not.exist.example.com", "bad-region")));
}
@Test
public void whenUserAgentsOverridden_originalUAsPreserved() throws Exception {
RequestHandler2 handler = spy(new RequestHandler2() {});
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.withClientBuilder(
AWSKMSClientBuilder.standard()
.withRequestHandlers(handler)
.withClientConfiguration(
new ClientConfiguration()
.withUserAgentPrefix("TEST-UA-PREFIX")
.withUserAgentSuffix("TEST-UA-SUFFIX")))
.clone()
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
AwsCrypto.standard().encryptData(mkp, new byte[0]);
ArgumentCaptor<Request> captor = ArgumentCaptor.forClass(Request.class);
verify(handler, atLeastOnce()).beforeRequest(captor.capture());
String ua = (String) captor.getValue().getHeaders().get("User-Agent");
assertTrue(ua.contains("TEST-UA-PREFIX"));
assertTrue(ua.contains("TEST-UA-SUFFIX"));
assertTrue(ua.contains(VersionInfo.loadUserAgent()));
}
@Test
public void whenDefaultRegionSet_itIsUsedForBareKeyIds() throws Exception {
// TODO: Need to set up a role to assume as bare key IDs are relative to the caller account
}
}
| 5,374 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/AwsKmsMrkAwareMasterKeyProviderTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kms;
import static com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo.parseInfoFromKeyArn;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.spy;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.encryptionsdk.*;
import com.amazonaws.encryptionsdk.exception.AwsCryptoException;
import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException;
import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException;
import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException;
import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider.RegionalClientSupplier;
import com.amazonaws.encryptionsdk.model.KeyBlob;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.AWSKMSClientBuilder;
import com.amazonaws.services.kms.model.DecryptRequest;
import com.amazonaws.services.kms.model.DecryptResult;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
@RunWith(Enclosed.class)
public class AwsKmsMrkAwareMasterKeyProviderTest {
public static class getResourceForResourceTypeKey {
@Test
public void basic_use() {
assertEquals(
"mrk-edb7fe6942894d32ac46dbb1c922d574",
AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"));
}
@Test
public void not_an_arn() {
assertEquals(
"mrk-edb7fe6942894d32ac46dbb1c922d574",
AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey(
"mrk-edb7fe6942894d32ac46dbb1c922d574"));
final String malformed = "aws:kms:us-west-2::key/garbage";
assertEquals(
malformed, AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey(malformed));
}
@Test
public void not_a_key() {
final String alias = "arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt";
assertEquals(alias, AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey(alias));
}
}
public static class assertMrksAreUnique {
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5
// = type=test
// # The caller MUST provide:
public void basic_use() {
AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique(
Arrays.asList(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"));
}
@Test
public void no_duplicates() {
// = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5
// = type=test
// # If there are zero duplicate resource ids between the multi-region
// # keys, this function MUST exit successfully
AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique(
Arrays.asList(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5
// = type=test
// # If the list does not contain any multi-Region keys (aws-kms-key-
// # arn.md#identifying-an-aws-kms-multi-region-key) this function MUST
// # exit successfully.
public void no_mrks_at_all() {
AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique(
Arrays.asList(
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f",
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"));
}
@Test
public void non_mrk_duplicates_ok() {
AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique(
Arrays.asList(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f",
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f",
"arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt",
"arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt"));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5
// = type=test
// # If any duplicate multi-region resource ids exist, this function MUST
// # yield an error that includes all identifiers with duplicate resource
// # ids not only the first duplicate found.
public void no_duplicate_mrks() {
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique(
Arrays.asList(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
"arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574")));
}
}
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # On initialization the caller MUST provide:
public static class AwsKmsMrkAwareMasterKeyProviderBuilderTests {
@Test
public void basic_use() {
final AwsKmsMrkAwareMasterKeyProvider strict =
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildStrict(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574");
final AwsKmsMrkAwareMasterKeyProvider discovery =
AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery();
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.5
// = type=test
// # MUST implement the Master Key Provider Interface (../master-key-
// # provider-interface.md#interface)
assertTrue(MasterKeyProvider.class.isInstance(strict));
assertTrue(MasterKeyProvider.class.isInstance(discovery));
// These are not testable because of how the builder is structured.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # A discovery filter MUST NOT be configured in strict mode.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # A default MRK Region MUST NOT be configured in strict mode.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # In
// # discovery mode if a default MRK Region is not configured the AWS SDK
// # Default Region MUST be used.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # The key id list MUST be empty in discovery mode.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # The regional client
// # supplier MUST be defined in discovery mode.
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # The key id list MUST NOT be empty or null in strict mode.
public void no_noop() {
assertThrows(
IllegalArgumentException.class,
() -> AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict());
assertThrows(
IllegalArgumentException.class,
() -> AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(new ArrayList<String>()));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # The key id
// # list MUST NOT contain any null or empty string values.
public void no_null_identifiers() {
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildStrict(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
""));
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildStrict(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
null));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # All AWS KMS
// # key identifiers are be passed to Assert AWS KMS MRK are unique (aws-
// # kms-mrk-are-unique.md#Implementation) and the function MUST return
// # success.
public void no_duplicate_mrks() {
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildStrict(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
"arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"));
}
@Test
public void always_need_a_region() {
assertThrows(
AwsCryptoException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
.withDefaultRegion(null)
.buildStrict("mrk-edb7fe6942894d32ac46dbb1c922d574"));
AwsKmsMrkAwareMasterKeyProvider.builder()
.withDefaultRegion("us-east-1")
.buildStrict("mrk-edb7fe6942894d32ac46dbb1c922d574");
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # If an AWS SDK Default Region can not be
// # obtained initialization MUST fail.
public void discovery_region_can_not_be_null() {
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
// need to force the default region to `null`
// otherwise it may pick one up from the environment.
.withDefaultRegion(null)
.withDiscoveryMrkRegion(null)
.buildDiscovery());
}
@Test
public void basic_credentials_and_builder() {
BasicAWSCredentials creds = new BasicAWSCredentials("asdf", "qwer");
AwsKmsMrkAwareMasterKeyProvider.builder()
.withClientBuilder(AWSKMSClientBuilder.standard())
.withCredentials(creds)
.buildDiscovery();
}
}
public static class extractRegion {
@Test
public void basic_use() {
final String test =
AwsKmsMrkAwareMasterKeyProvider.extractRegion(
"us-east-1",
"us-east-2",
Optional.of(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"),
parseInfoFromKeyArn(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"),
false);
assertEquals("us-west-2", test);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # If the requested AWS KMS key identifier is not a well formed ARN the
// # AWS Region MUST be the configured default region this SHOULD be
// # obtained from the AWS SDK.
public void not_an_arn() {
final String test =
AwsKmsMrkAwareMasterKeyProvider.extractRegion(
"us-east-1",
"us-east-2",
Optional.empty(),
parseInfoFromKeyArn("mrk-edb7fe6942894d32ac46dbb1c922d574"),
false);
assertEquals("us-east-1", test);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # Otherwise if the requested AWS KMS key
// # identifier is identified as a multi-Region key (aws-kms-key-
// # arn.md#identifying-an-aws-kms-multi-region-key), then AWS Region MUST
// # be the region from the AWS KMS key ARN stored in the provider info
// # from the encrypted data key.
public void not_an_mrk() {
final String test =
AwsKmsMrkAwareMasterKeyProvider.extractRegion(
"us-east-1",
"us-east-2",
Optional.of(
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"),
parseInfoFromKeyArn(
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"),
false);
assertEquals("us-west-2", test);
final String test2 =
AwsKmsMrkAwareMasterKeyProvider.extractRegion(
"us-east-1",
"us-east-2",
Optional.of("arn:aws:kms:us-west-2:658956600833:alias/mrk-nasty"),
parseInfoFromKeyArn("arn:aws:kms:us-west-2:658956600833:alias/mrk-nasty"),
false);
assertEquals("us-west-2", test2);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # Otherwise if the mode is discovery then
// # the AWS Region MUST be the discovery MRK region.
public void mrk_in_discovery() {
final String test =
AwsKmsMrkAwareMasterKeyProvider.extractRegion(
"us-east-1",
"us-east-2",
Optional.empty(),
parseInfoFromKeyArn(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"),
true);
assertEquals("us-east-2", test);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # Finally if the
// # provider info is identified as a multi-Region key (aws-kms-key-
// # arn.md#identifying-an-aws-kms-multi-region-key) the AWS Region MUST
// # be the region from the AWS KMS key in the configured key ids matched
// # to the requested AWS KMS key by using AWS KMS MRK Match for Decrypt
// # (aws-kms-mrk-match-for-decrypt.md#implementation).
public void fuzzy_match_mrk() {
final String test =
AwsKmsMrkAwareMasterKeyProvider.extractRegion(
"us-east-1",
"us-east-2",
Optional.of(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"),
parseInfoFromKeyArn(
"arn:aws:kms:us-west-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"),
false);
assertEquals("us-west-2", test);
}
}
public static class getMasterKey {
@Test
public void basic_use() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final AWSKMS client = spy(new MockKMSClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict(identifier);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # The input MUST be the same as the Master Key Provider Get Master Key
// # (../master-key-provider-interface.md#get-master-key) interface.
AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", identifier);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # The output MUST be the same as the Master Key Provider Get Master Key
// # (../master-key-provider-interface.md#get-master-key) interface.
assertTrue(AwsKmsMrkAwareMasterKey.class.isInstance((test)));
assertEquals(identifier, test.getKeyId());
verify(supplier, times(1)).getClient("us-west-2");
}
@Test
public void basic_mrk_use() {
final String configuredIdentifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String requestedIdentifier =
"arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final AWSKMS client = spy(new MockKMSClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict(configuredIdentifier);
AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", requestedIdentifier);
assertEquals(configuredIdentifier, test.getKeyId());
verify(supplier, times(1)).getClient("us-west-2");
}
@Test
public void other_basic_uses() {
final AWSKMS client = spy(new MockKMSClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
// A raw alias is a valid configuration for encryption
final String rawAliasIdentifier = "alias/my-alias";
AwsKmsMrkAwareMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict(rawAliasIdentifier)
.getMasterKey("aws-kms", rawAliasIdentifier);
// A raw alias is a valid configuration for encryption
final String rawKeyIdentifier = "mrk-edb7fe6942894d32ac46dbb1c922d574";
AwsKmsMrkAwareMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict(rawKeyIdentifier)
.getMasterKey("aws-kms", rawKeyIdentifier);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # The function MUST only provide master keys if the input provider id
// # equals "aws-kms".
public void only_this_provider() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final AWSKMS client = spy(new MockKMSClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict(identifier);
assertThrows(
UnsupportedProviderException.class, () -> mkp.getMasterKey("not-aws-kms", identifier));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # In strict mode, the requested AWS KMS key ARN MUST
// # match a member of the configured key ids by using AWS KMS MRK Match
// # for Decrypt (aws-kms-mrk-match-for-decrypt.md#implementation)
// # otherwise this function MUST error.
public void no_key_id_match() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final AWSKMS client = spy(new MockKMSClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
final AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict(identifier);
assertThrows(
NoSuchMasterKeyException.class,
() -> mkp.getMasterKey("aws-kms", "does-not-match-configured"));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # In discovery mode, the requested
// # AWS KMS key identifier MUST be a well formed AWS KMS ARN.
public void discovery_request_must_be_arn() {
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery();
assertThrows(
NoSuchMasterKeyException.class,
() -> mkp.getMasterKey("aws-kms", "mrk-edb7fe6942894d32ac46dbb1c922d574"));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # In
// # discovery mode if a discovery filter is configured the requested AWS
// # KMS key ARN's "partition" MUST match the discovery filter's
// # "partition" and the AWS KMS key ARN's "account" MUST exist in the
// # discovery filter's account id set.
public void discovery_filter_must_match() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final AWSKMS client = spy(new MockKMSClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
assertThrows(
NoSuchMasterKeyException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildDiscovery(new DiscoveryFilter("aws", Arrays.asList("not-111122223333")))
.getMasterKey("aws-kms", identifier));
assertThrows(
NoSuchMasterKeyException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildDiscovery(new DiscoveryFilter("not-aws", Arrays.asList("111122223333")))
.getMasterKey("aws-kms", identifier));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # In discovery mode a AWS KMS MRK Aware Master Key (aws-kms-mrk-aware-
// # master-key.md) MUST be returned configured with
public void discovery_magic_to_make_the_region_match() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final AWSKMS client = spy(new MockKMSClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.withDiscoveryMrkRegion("my-region")
.buildDiscovery();
AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", identifier);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # An AWS KMS client
// # MUST be obtained by calling the regional client supplier with this
// # AWS Region.
assertEquals(
"arn:aws:kms:my-region:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
test.getKeyId());
verify(supplier, times(1)).getClient("my-region");
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # In strict mode a AWS KMS MRK Aware Master Key (aws-kms-mrk-aware-
// # master-key.md) MUST be returned configured with
public void strict_mrk_region_match() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String configIdentifier =
"arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final AWSKMS client = spy(new MockKMSClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict(configIdentifier);
AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", identifier);
assertEquals(configIdentifier, test.getKeyId());
verify(supplier, times(1)).getClient("us-east-1");
}
}
public static class decryptDataKey {
@Test
public void basic_use() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final byte[] cipherText = new byte[10];
final EncryptedDataKey edk1 =
new KeyBlob("aws-kms", identifier.getBytes(StandardCharsets.UTF_8), cipherText);
final EncryptedDataKey edk2 =
new KeyBlob("aws-kms", identifier.getBytes(StandardCharsets.UTF_8), cipherText);
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
final AWSKMS client = mock(AWSKMS.class);
when(client.decrypt(any()))
.thenReturn(
new DecryptResult()
.withKeyId(identifier)
.withPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength())));
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict(identifier)
.withGrantTokens(GRANT_TOKENS);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # The input MUST be the same as the Master Key Provider Decrypt Data
// # Key (../master-key-provider-interface.md#decrypt-data-key) interface.
final DataKey<AwsKmsMrkAwareMasterKey> test =
mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk1, edk2), ENCRYPTION_CONTEXT);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # For each encrypted data key in the filtered set, one at a time, the
// # master key provider MUST call Get Master Key (aws-kms-mrk-aware-
// # master-key-provider.md#get-master-key) with the encrypted data key's
// # provider info as the AWS KMS key ARN.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # It MUST call Decrypt Data Key
// # (aws-kms-mrk-aware-master-key.md#decrypt-data-key) on this master key
// # with the input algorithm, this single encrypted data key, and the
// # input encryption context.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # If the decrypt data key call is
// # successful, then this function MUST return this result and not
// # attempt to decrypt any more encrypted data keys.
verify(client, times((1)))
.decrypt(
new DecryptRequest()
.withGrantTokens(GRANT_TOKENS)
.withEncryptionContext(ENCRYPTION_CONTEXT)
.withKeyId(identifier)
.withCiphertextBlob(ByteBuffer.wrap(cipherText)));
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # The output MUST be the same as the Master Key Provider Decrypt Data
// # Key (../master-key-provider-interface.md#decrypt-data-key) interface.
assertTrue(DataKey.class.isInstance(test));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # The set of encrypted data keys MUST first be filtered to match this
// # master key's configuration.
public void only_if_providers_match() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final EncryptedDataKey edk =
new KeyBlob(
"not-aws-kms", "not the identifier".getBytes(StandardCharsets.UTF_8), new byte[10]);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(identifier);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # To match the encrypted data key's
// # provider ID MUST exactly match the value "aws-kms".
final CannotUnwrapDataKeyException test =
assertThrows(
"Unable to decrypt any data keys",
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT));
assertEquals(0, test.getSuppressed().length);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # Additionally
// # each provider info MUST be a valid AWS KMS ARN (aws-kms-key-arn.md#a-
// # valid-aws-kms-arn) with a resource type of "key".
public void provider_info_must_be_arn() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String aliasArn =
"arn:aws:kms:us-west-2:111122223333:alias/mrk-edb7fe6942894d32ac46dbb1c922d574";
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final EncryptedDataKey edk =
new KeyBlob("aws-kms", aliasArn.getBytes(StandardCharsets.UTF_8), new byte[10]);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(identifier);
final IllegalStateException test =
assertThrows(
"Invalid provider info in message.",
IllegalStateException.class,
() -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT));
assertEquals(0, test.getSuppressed().length);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # If this attempt results in an error, then
// # these errors MUST be collected.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # If all the input encrypted data keys have been processed then this
// # function MUST yield an error that includes all the collected errors.
public void exception_wrapped() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final EncryptedDataKey edk =
new KeyBlob("aws-kms", identifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
final AWSKMS client = mock(AWSKMS.class);
final String clientErrMsg = "asdf";
when(client.decrypt(any())).thenThrow(new AmazonServiceException(clientErrMsg));
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict(identifier);
CannotUnwrapDataKeyException test =
assertThrows(
"Unable to decrypt any data keys",
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT));
assertEquals(1, test.getSuppressed().length);
Throwable fromMasterKey = Arrays.stream(test.getSuppressed()).findFirst().get();
assertTrue(fromMasterKey instanceof CannotUnwrapDataKeyException);
assertEquals(1, fromMasterKey.getSuppressed().length);
Throwable fromClient = Arrays.stream(fromMasterKey.getSuppressed()).findFirst().get();
assertTrue(fromClient instanceof AmazonServiceException);
assertTrue(fromClient.getMessage().startsWith(clientErrMsg));
}
}
public static class clientFactory {
@Test
public void basic_use() {
final ConcurrentHashMap<String, AWSKMS> cache = spy(new ConcurrentHashMap<>());
final AWSKMS test =
AwsKmsMrkAwareMasterKeyProvider.Builder.clientFactory(cache, null).getClient("asdf");
assertNotEquals(null, test);
verify(cache, times(1)).containsKey("asdf");
}
@Test
public void use_clients_that_exist() {
final String region = "asdf";
final ConcurrentHashMap<String, AWSKMS> cache = spy(new ConcurrentHashMap<>());
// Add something so we can verify that we get it
final AWSKMS client = mock(AWSKMS.class);
cache.put(region, client);
final AWSKMS test =
AwsKmsMrkAwareMasterKeyProvider.Builder.clientFactory(cache, null).getClient(region);
assertEquals(client, test);
}
}
public static class getMasterKeysForEncryption {
@Test
public void basic_use() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final AWSKMS client = spy(new MockKMSClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient("us-west-2")).thenReturn(client);
final MasterKeyRequest request = MasterKeyRequest.newBuilder().build();
final AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict(identifier);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8
// = type=test
// # The input MUST be the same as the Master Key Provider Get Master Keys
// # For Encryption (../master-key-provider-interface.md#get-master-keys-
// # for-encryption) interface.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8
// = type=test
// # The output MUST be the same as the Master Key Provider Get Master
// # Keys For Encryption (../master-key-provider-interface.md#get-master-
// # keys-for-encryption) interface.
final List<AwsKmsMrkAwareMasterKey> test = mkp.getMasterKeysForEncryption(request);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8
// = type=test
// # If the configured mode is strict this function MUST return a
// # list of master keys obtained by calling Get Master Key (aws-kms-mrk-
// # aware-master-key-provider.md#get-master-key) for each AWS KMS key
// # identifier in the configured key ids
assertEquals(1, test.size());
assertEquals(identifier, test.get(0).getKeyId());
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8
// = type=test
// # If the configured mode is discovery the function MUST return an empty
// # list.
public void no_keys_is_empty_list() {
final AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery();
final List<AwsKmsMrkAwareMasterKey> test =
mkp.getMasterKeysForEncryption(MasterKeyRequest.newBuilder().build());
assertEquals(0, test.size());
}
}
}
| 5,375 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/KmsMasterKeyTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kms;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.RequestClientOptions;
import com.amazonaws.encryptionsdk.CryptoAlgorithm;
import com.amazonaws.encryptionsdk.DataKey;
import com.amazonaws.encryptionsdk.EncryptedDataKey;
import com.amazonaws.encryptionsdk.MasterKey;
import com.amazonaws.encryptionsdk.MasterKeyProvider;
import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException;
import com.amazonaws.encryptionsdk.internal.VersionInfo;
import com.amazonaws.encryptionsdk.model.KeyBlob;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.model.DecryptRequest;
import com.amazonaws.services.kms.model.DecryptResult;
import com.amazonaws.services.kms.model.EncryptRequest;
import com.amazonaws.services.kms.model.GenerateDataKeyRequest;
import com.amazonaws.services.kms.model.GenerateDataKeyResult;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
public class KmsMasterKeyTest {
private static final String AWS_KMS_PROVIDER_ID = "aws-kms";
private static final String OTHER_PROVIDER_ID = "not-aws-kms";
private static final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
private static final SecretKey DATA_KEY =
new SecretKeySpec(
generate(ALGORITHM_SUITE.getDataKeyLength()), ALGORITHM_SUITE.getDataKeyAlgo());
private static final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
private static final Map<String, String> ENCRYPTION_CONTEXT =
Collections.singletonMap("myKey", "myValue");
@Test
public void testEncryptAndDecrypt() {
AWSKMS client = spy(new MockKMSClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKey otherMasterKey = mock(MasterKey.class);
when(otherMasterKey.getProviderId()).thenReturn(OTHER_PROVIDER_ID);
when(otherMasterKey.getKeyId()).thenReturn("someOtherId");
DataKey dataKey =
new DataKey(
DATA_KEY,
new byte[0],
OTHER_PROVIDER_ID.getBytes(StandardCharsets.UTF_8),
otherMasterKey);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().getKeyMetadata().getArn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
kmsMasterKey.setGrantTokens(GRANT_TOKENS);
DataKey<KmsMasterKey> encryptDataKeyResult =
kmsMasterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey);
ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class);
verify(client, times(1)).encrypt(er.capture());
EncryptRequest actualRequest = er.getValue();
assertEquals(keyId, actualRequest.getKeyId());
assertEquals(GRANT_TOKENS, actualRequest.getGrantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext());
assertArrayEquals(DATA_KEY.getEncoded(), actualRequest.getPlaintext().array());
assertUserAgent(actualRequest);
assertEquals(encryptDataKeyResult.getMasterKey(), kmsMasterKey);
assertEquals(AWS_KMS_PROVIDER_ID, encryptDataKeyResult.getProviderId());
assertArrayEquals(
keyId.getBytes(StandardCharsets.UTF_8), encryptDataKeyResult.getProviderInformation());
assertNotNull(encryptDataKeyResult.getEncryptedDataKey());
DataKey<KmsMasterKey> decryptDataKeyResult =
kmsMasterKey.decryptDataKey(
ALGORITHM_SUITE, Collections.singletonList(encryptDataKeyResult), ENCRYPTION_CONTEXT);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decrypt.capture());
DecryptRequest actualDecryptRequest = decrypt.getValue();
assertArrayEquals(
encryptDataKeyResult.getProviderInformation(),
actualDecryptRequest.getKeyId().getBytes(StandardCharsets.UTF_8));
assertEquals(GRANT_TOKENS, actualDecryptRequest.getGrantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualDecryptRequest.getEncryptionContext());
assertArrayEquals(
encryptDataKeyResult.getEncryptedDataKey(),
actualDecryptRequest.getCiphertextBlob().array());
assertUserAgent(actualDecryptRequest);
assertEquals(DATA_KEY, decryptDataKeyResult.getKey());
assertArrayEquals(
keyId.getBytes(StandardCharsets.UTF_8), decryptDataKeyResult.getProviderInformation());
}
@Test
public void testGenerateAndDecrypt() {
AWSKMS client = spy(new MockKMSClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().getKeyMetadata().getArn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
kmsMasterKey.setGrantTokens(GRANT_TOKENS);
DataKey<KmsMasterKey> generateDataKeyResult =
kmsMasterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT);
ArgumentCaptor<GenerateDataKeyRequest> gr =
ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
verify(client, times(1)).generateDataKey(gr.capture());
GenerateDataKeyRequest actualRequest = gr.getValue();
assertEquals(keyId, actualRequest.getKeyId());
assertEquals(GRANT_TOKENS, actualRequest.getGrantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext());
assertEquals(ALGORITHM_SUITE.getDataKeyLength(), actualRequest.getNumberOfBytes().longValue());
assertUserAgent(actualRequest);
assertNotNull(generateDataKeyResult.getKey());
assertEquals(
ALGORITHM_SUITE.getDataKeyLength(), generateDataKeyResult.getKey().getEncoded().length);
assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), generateDataKeyResult.getKey().getAlgorithm());
assertNotNull(generateDataKeyResult.getEncryptedDataKey());
DataKey<KmsMasterKey> decryptDataKeyResult =
kmsMasterKey.decryptDataKey(
ALGORITHM_SUITE, Collections.singletonList(generateDataKeyResult), ENCRYPTION_CONTEXT);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decrypt.capture());
DecryptRequest actualDecryptRequest = decrypt.getValue();
assertArrayEquals(
generateDataKeyResult.getProviderInformation(),
actualDecryptRequest.getKeyId().getBytes(StandardCharsets.UTF_8));
assertEquals(GRANT_TOKENS, actualDecryptRequest.getGrantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualDecryptRequest.getEncryptionContext());
assertArrayEquals(
generateDataKeyResult.getEncryptedDataKey(),
actualDecryptRequest.getCiphertextBlob().array());
assertUserAgent(actualDecryptRequest);
assertEquals(generateDataKeyResult.getKey(), decryptDataKeyResult.getKey());
assertArrayEquals(
keyId.getBytes(StandardCharsets.UTF_8), decryptDataKeyResult.getProviderInformation());
}
@Test
public void testEncryptWithRawKeyId() {
AWSKMS client = spy(new MockKMSClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKey otherMasterKey = mock(MasterKey.class);
when(otherMasterKey.getProviderId()).thenReturn(OTHER_PROVIDER_ID);
when(otherMasterKey.getKeyId()).thenReturn("someOtherId");
DataKey dataKey =
new DataKey(
DATA_KEY,
new byte[0],
OTHER_PROVIDER_ID.getBytes(StandardCharsets.UTF_8),
otherMasterKey);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().getKeyMetadata().getArn();
String rawKeyId = keyId.split("/")[1];
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, rawKeyId, mkp);
kmsMasterKey.setGrantTokens(GRANT_TOKENS);
DataKey<KmsMasterKey> encryptDataKeyResult =
kmsMasterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey);
ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class);
verify(client, times(1)).encrypt(er.capture());
EncryptRequest actualRequest = er.getValue();
assertEquals(rawKeyId, actualRequest.getKeyId());
assertEquals(GRANT_TOKENS, actualRequest.getGrantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext());
assertArrayEquals(DATA_KEY.getEncoded(), actualRequest.getPlaintext().array());
assertUserAgent(actualRequest);
assertEquals(AWS_KMS_PROVIDER_ID, encryptDataKeyResult.getProviderId());
assertArrayEquals(
keyId.getBytes(StandardCharsets.UTF_8), encryptDataKeyResult.getProviderInformation());
assertNotNull(encryptDataKeyResult.getEncryptedDataKey());
}
@Test
public void testEncryptWrongKeyFormat() {
SecretKey key = mock(SecretKey.class);
when(key.getFormat()).thenReturn("BadFormat");
AWSKMS client = spy(new MockKMSClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKey otherMasterKey = mock(MasterKey.class);
when(otherMasterKey.getProviderId()).thenReturn(OTHER_PROVIDER_ID);
when(otherMasterKey.getKeyId()).thenReturn("someOtherId");
DataKey dataKey =
new DataKey(
key, new byte[0], OTHER_PROVIDER_ID.getBytes(StandardCharsets.UTF_8), otherMasterKey);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().getKeyMetadata().getArn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
assertThrows(
IllegalArgumentException.class,
() -> kmsMasterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey));
}
@Test
public void testGenerateBadKmsKeyLength() {
AWSKMS client = spy(new MockKMSClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().getKeyMetadata().getArn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
GenerateDataKeyResult badResult = new GenerateDataKeyResult();
badResult.setKeyId(keyId);
badResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength() + 1));
doReturn(badResult).when(client).generateDataKey(isA(GenerateDataKeyRequest.class));
assertThrows(
IllegalStateException.class,
() -> kmsMasterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT));
}
@Test
public void testDecryptBadKmsKeyLength() {
AWSKMS client = spy(new MockKMSClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().getKeyMetadata().getArn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
DecryptResult badResult = new DecryptResult();
badResult.setKeyId(keyId);
badResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength() + 1));
doReturn(badResult).when(client).decrypt(isA(DecryptRequest.class));
EncryptedDataKey edk =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
keyId.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
assertThrows(
IllegalStateException.class,
() ->
kmsMasterKey.decryptDataKey(
ALGORITHM_SUITE, Collections.singletonList(edk), ENCRYPTION_CONTEXT));
}
@Test
public void testDecryptMissingKmsKeyId() {
AWSKMS client = spy(new MockKMSClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().getKeyMetadata().getArn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
DecryptResult badResult = new DecryptResult();
badResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()));
doReturn(badResult).when(client).decrypt(isA(DecryptRequest.class));
EncryptedDataKey edk =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
keyId.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
assertThrows(
IllegalStateException.class,
"Received an empty keyId from KMS",
() ->
kmsMasterKey.decryptDataKey(
ALGORITHM_SUITE, Collections.singletonList(edk), ENCRYPTION_CONTEXT));
}
@Test
public void testDecryptMismatchedKmsKeyId() {
AWSKMS client = spy(new MockKMSClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().getKeyMetadata().getArn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
DecryptResult badResult = new DecryptResult();
badResult.setKeyId("mismatchedID");
badResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()));
doReturn(badResult).when(client).decrypt(isA(DecryptRequest.class));
EncryptedDataKey edk =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
keyId.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
assertThrows(
CannotUnwrapDataKeyException.class,
() ->
kmsMasterKey.decryptDataKey(
ALGORITHM_SUITE, Collections.singletonList(edk), ENCRYPTION_CONTEXT));
}
@Test
public void testDecryptSkipsMismatchedIdEDK() {
AWSKMS client = spy(new MockKMSClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().getKeyMetadata().getArn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
// Mock expected KMS response to verify success if second EDK is ok,
// and the mismatched EDK is skipped vs failing outright
DecryptResult kmsResponse = new DecryptResult();
kmsResponse.setKeyId(keyId);
kmsResponse.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()));
doReturn(kmsResponse).when(client).decrypt(isA(DecryptRequest.class));
EncryptedDataKey edk =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
keyId.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
EncryptedDataKey mismatchedEDK =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
"mismatchedID".getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
DataKey<KmsMasterKey> decryptDataKeyResult =
kmsMasterKey.decryptDataKey(
ALGORITHM_SUITE, Arrays.asList(mismatchedEDK, edk), ENCRYPTION_CONTEXT);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decrypt.capture());
DecryptRequest actualDecryptRequest = decrypt.getValue();
assertArrayEquals(
edk.getProviderInformation(),
actualDecryptRequest.getKeyId().getBytes(StandardCharsets.UTF_8));
}
private void assertUserAgent(AmazonWebServiceRequest request) {
assertTrue(
request
.getRequestClientOptions()
.getClientMarker(RequestClientOptions.Marker.USER_AGENT)
.contains(VersionInfo.loadUserAgent()));
}
}
| 5,376 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/KmsMasterKeyProviderTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kms;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.RequestClientOptions;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.encryptionsdk.CryptoAlgorithm;
import com.amazonaws.encryptionsdk.DataKey;
import com.amazonaws.encryptionsdk.EncryptedDataKey;
import com.amazonaws.encryptionsdk.MasterKeyProvider;
import com.amazonaws.encryptionsdk.MasterKeyRequest;
import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException;
import com.amazonaws.encryptionsdk.internal.VersionInfo;
import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider.Builder;
import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider.RegionalClientSupplier;
import com.amazonaws.encryptionsdk.model.KeyBlob;
import com.amazonaws.services.kms.model.DecryptRequest;
import com.amazonaws.services.kms.model.DecryptResult;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.ArgumentCaptor;
@RunWith(Enclosed.class)
public class KmsMasterKeyProviderTest {
private static final String AWS_PARTITION = "aws";
private static final String AWS_KMS_PROVIDER_ID = "aws-kms";
private static final String OTHER_PARTITION = "not-aws";
private static final String OTHER_PROVIDER_ID = "not-aws-kms";
private static final String ACCOUNT_ID = "999999999999";
private static final String OTHER_ACCOUNT_ID = "000000000000";
private static final String KEY_ID_1 =
"arn:"
+ AWS_PARTITION
+ ":kms:us-east-1:"
+ ACCOUNT_ID
+ ":key/01234567-89ab-cdef-fedc-ba9876543210";
private static final String KEY_ID_2 =
"arn:"
+ AWS_PARTITION
+ ":kms:us-east-1:"
+ ACCOUNT_ID
+ ":key/01234567-89ab-cdef-fedc-ba9876543211";
private static final String KEY_ID_3 =
"arn:"
+ AWS_PARTITION
+ ":kms:us-east-1:"
+ ACCOUNT_ID
+ ":key/01234567-89ab-cdef-fedc-ba9876543212";
private static final String KEY_ID_4 =
"arn:"
+ AWS_PARTITION
+ ":kms:us-east-1:"
+ OTHER_ACCOUNT_ID
+ ":key/01234567-89ab-cdef-fedc-ba9876543210";
private static final String KEY_ID_5 =
"arn:"
+ OTHER_PARTITION
+ ":kms:us-east-1:"
+ ACCOUNT_ID
+ ":key/01234567-89ab-cdef-fedc-ba9876543210";
private static final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
private static final Map<String, String> ENCRYPTION_CONTEXT =
Collections.singletonMap("myKey", "myValue");
private static final EncryptedDataKey EDK_ID_1 =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
KEY_ID_1.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_ID_1_OTHER_CIPHERTEXT =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
KEY_ID_1.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_ID_2 =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
KEY_ID_2.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_ID_3 =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
KEY_ID_3.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_NON_ARN =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
"someAlias".getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_EMPTY_PROVIDER =
new KeyBlob(
"",
"someId".getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_OTHER_PROVIDER =
new KeyBlob(
OTHER_PROVIDER_ID,
"someId".getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_OTHER_ACCOUNT =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
KEY_ID_4.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_OTHER_PARTITION =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
KEY_ID_5.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
@RunWith(Parameterized.class)
public static class ParameterizedDecryptTest {
MKPTestConfiguration mkpConfig;
List<EncryptedDataKey> inputEDKs;
List<EncryptedDataKey> decryptableEDKs;
private static class MKPTestConfiguration {
// instance vars are public for easier access during testing
public boolean isDiscovery;
public DiscoveryFilter discoveryFilter;
public List<String> keyIds;
public MKPTestConfiguration(
boolean isDiscovery, DiscoveryFilter discoveryFilter, List<String> keyIds) {
this.isDiscovery = isDiscovery;
this.discoveryFilter = discoveryFilter;
this.keyIds = keyIds;
}
}
public ParameterizedDecryptTest(
MKPTestConfiguration mkpConfig,
List<EncryptedDataKey> inputEDKs,
List<EncryptedDataKey> decryptableEDKs) {
this.mkpConfig = mkpConfig;
this.inputEDKs = inputEDKs;
this.decryptableEDKs = decryptableEDKs;
}
@Parameterized.Parameters(name = "{index}: mkpConfig={0}, inputEDKs={1}, decryptableEDKs={2}")
public static Collection<Object[]> testCases() {
// Create MKP configuration options to test against
MKPTestConfiguration strict_oneCMK =
new MKPTestConfiguration(false, null, Arrays.asList(KEY_ID_1));
MKPTestConfiguration strict_twoCMKs =
new MKPTestConfiguration(false, null, Arrays.asList(KEY_ID_1, KEY_ID_2));
MKPTestConfiguration explicitDiscovery = new MKPTestConfiguration(true, null, null);
MKPTestConfiguration explicitDiscovery_filter =
new MKPTestConfiguration(
true, new DiscoveryFilter(AWS_PARTITION, Arrays.asList(ACCOUNT_ID)), null);
// Define all test cases
Collection<Object[]> testCases =
Arrays.asList(
new Object[][] {
// Test cases where no EDKs are expected to be decrypted
{strict_oneCMK, Collections.emptyList(), Collections.emptyList()},
{strict_oneCMK, Arrays.asList(EDK_ID_2), Collections.emptyList()},
{strict_oneCMK, Arrays.asList(EDK_ID_2, EDK_ID_3), Collections.emptyList()},
{strict_twoCMKs, Collections.emptyList(), Collections.emptyList()},
{strict_twoCMKs, Arrays.asList(EDK_ID_3), Collections.emptyList()},
{
strict_twoCMKs,
Arrays.asList(EDK_ID_3, EDK_OTHER_PROVIDER),
Collections.emptyList()
},
{explicitDiscovery, Collections.emptyList(), Collections.emptyList()},
{explicitDiscovery, Arrays.asList(EDK_OTHER_PROVIDER), Collections.emptyList()},
{explicitDiscovery, Arrays.asList(EDK_EMPTY_PROVIDER), Collections.emptyList()},
{
explicitDiscovery,
Arrays.asList(EDK_OTHER_PROVIDER, EDK_EMPTY_PROVIDER),
Collections.emptyList()
},
{explicitDiscovery_filter, Collections.emptyList(), Collections.emptyList()},
{
explicitDiscovery_filter,
Arrays.asList(EDK_OTHER_PROVIDER),
Collections.emptyList()
},
{
explicitDiscovery_filter,
Arrays.asList(EDK_EMPTY_PROVIDER),
Collections.emptyList()
},
{explicitDiscovery_filter, Arrays.asList(EDK_NON_ARN), Collections.emptyList()},
{
explicitDiscovery_filter,
Arrays.asList(EDK_OTHER_PARTITION),
Collections.emptyList()
},
{
explicitDiscovery_filter,
Arrays.asList(EDK_OTHER_ACCOUNT),
Collections.emptyList()
},
{
explicitDiscovery_filter,
Arrays.asList(EDK_OTHER_PROVIDER, EDK_EMPTY_PROVIDER),
Collections.emptyList()
},
// Test cases where one EDK is expected to be decryptable
{strict_oneCMK, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)},
{strict_oneCMK, Arrays.asList(EDK_ID_2, EDK_ID_1), Arrays.asList(EDK_ID_1)},
{strict_oneCMK, Arrays.asList(EDK_ID_1, EDK_ID_2), Arrays.asList(EDK_ID_1)},
{strict_twoCMKs, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)},
{strict_twoCMKs, Arrays.asList(EDK_ID_2), Arrays.asList(EDK_ID_2)},
{strict_twoCMKs, Arrays.asList(EDK_ID_3, EDK_ID_1), Arrays.asList(EDK_ID_1)},
{strict_twoCMKs, Arrays.asList(EDK_ID_1, EDK_ID_3), Arrays.asList(EDK_ID_1)},
{explicitDiscovery, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)},
{
explicitDiscovery,
Arrays.asList(EDK_OTHER_PROVIDER, EDK_ID_1),
Arrays.asList(EDK_ID_1)
},
{
explicitDiscovery,
Arrays.asList(EDK_ID_1, EDK_OTHER_PROVIDER),
Arrays.asList(EDK_ID_1)
},
{explicitDiscovery_filter, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)},
{
explicitDiscovery_filter,
Arrays.asList(EDK_OTHER_ACCOUNT, EDK_ID_1),
Arrays.asList(EDK_ID_1)
},
{
explicitDiscovery_filter,
Arrays.asList(EDK_ID_1, EDK_OTHER_ACCOUNT),
Arrays.asList(EDK_ID_1)
},
// Test cases where multiple EDKs are expected to be decryptable
{
strict_oneCMK,
Arrays.asList(EDK_ID_1, EDK_ID_1_OTHER_CIPHERTEXT),
Arrays.asList(EDK_ID_1, EDK_ID_1_OTHER_CIPHERTEXT)
},
{
strict_twoCMKs,
Arrays.asList(EDK_ID_1, EDK_ID_2),
Arrays.asList(EDK_ID_1, EDK_ID_2)
},
{
explicitDiscovery,
Arrays.asList(EDK_ID_1, EDK_ID_2),
Arrays.asList(EDK_ID_1, EDK_ID_2)
},
{
explicitDiscovery_filter,
Arrays.asList(EDK_ID_1, EDK_ID_2),
Arrays.asList(EDK_ID_1, EDK_ID_2)
},
});
return testCases;
}
@SuppressWarnings("deprecation")
private KmsMasterKeyProvider constructMKPForTest(
MKPTestConfiguration mkpConfig, RegionalClientSupplier supplier) {
Builder builder = KmsMasterKeyProvider.builder().withCustomClientFactory(supplier);
KmsMasterKeyProvider mkp;
if (mkpConfig.isDiscovery && mkpConfig.discoveryFilter == null) {
mkp = builder.buildDiscovery();
} else if (mkpConfig.isDiscovery) {
mkp = builder.buildDiscovery(mkpConfig.discoveryFilter);
} else {
mkp = builder.buildStrict(mkpConfig.keyIds);
}
return mkp;
}
@Test
public void testDecrypt() throws Exception {
MockKMSClient client = spy(new MockKMSClient());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
// create MKP to test
KmsMasterKeyProvider mkp = constructMKPForTest(mkpConfig, supplier);
// if we expect none of them to decrypt, just test that we get the correct
// failure and KMS was not called
if (decryptableEDKs.size() <= 0) {
assertThrows(
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT));
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verifyNoInteractions(client);
return;
}
// Test that the mkp calls KMS for the first expected EDK
EncryptedDataKey expectedEDK = decryptableEDKs.get(0);
// mock KMS to return the KeyId for the expected EDK,
// we verify that we call KMS with this KeyId, so this is ok
DecryptResult decryptResult = new DecryptResult();
decryptResult.setKeyId(
new String(expectedEDK.getProviderInformation(), StandardCharsets.UTF_8));
decryptResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()));
doReturn(decryptResult).when(client).decrypt(isA(DecryptRequest.class));
DataKey<KmsMasterKey> dataKeyResult =
mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decrypt.capture());
verifyNoMoreInteractions(client);
DecryptRequest actualRequest = decrypt.getValue();
assertArrayEquals(
expectedEDK.getProviderInformation(),
actualRequest.getKeyId().getBytes(StandardCharsets.UTF_8));
assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext());
assertArrayEquals(
expectedEDK.getEncryptedDataKey(), actualRequest.getCiphertextBlob().array());
assertUserAgent(actualRequest);
assertArrayEquals(
expectedEDK.getProviderInformation(), dataKeyResult.getProviderInformation());
assertArrayEquals(expectedEDK.getEncryptedDataKey(), dataKeyResult.getEncryptedDataKey());
}
@Test
public void testDecryptKMSFailsOnce() throws Exception {
MockKMSClient client = spy(new MockKMSClient());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
// create MKP to test
KmsMasterKeyProvider mkp = constructMKPForTest(mkpConfig, supplier);
// if we expect one or less KMS call, just test that we get the correct
// failure and KMS was called the expected number of times
if (decryptableEDKs.size() <= 1) {
// Mock KMS to fail
doThrow(new AmazonServiceException("fail")).when(client).decrypt(isA(DecryptRequest.class));
assertThrows(
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT));
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(decryptableEDKs.size())).decrypt(decrypt.capture());
return;
}
EncryptedDataKey expectedFailedEDK = decryptableEDKs.get(0);
EncryptedDataKey expectedSuccessfulEDK = decryptableEDKs.get(1);
// Mock KMS to fail the first call then succeed for the second call
DecryptResult decryptResult = new DecryptResult();
decryptResult.setKeyId(
new String(expectedSuccessfulEDK.getProviderInformation(), StandardCharsets.UTF_8));
decryptResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()));
doThrow(new AmazonServiceException("fail"))
.doReturn(decryptResult)
.when(client)
.decrypt(isA(DecryptRequest.class));
DataKey<KmsMasterKey> dataKeyResult =
mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(2)).decrypt(decrypt.capture());
verifyNoMoreInteractions(client);
List<DecryptRequest> actualRequests = decrypt.getAllValues();
DecryptRequest failedRequest = actualRequests.get(0);
assertArrayEquals(
expectedFailedEDK.getProviderInformation(),
failedRequest.getKeyId().getBytes(StandardCharsets.UTF_8));
assertEquals(ENCRYPTION_CONTEXT, failedRequest.getEncryptionContext());
assertArrayEquals(
expectedFailedEDK.getEncryptedDataKey(), failedRequest.getCiphertextBlob().array());
assertUserAgent(failedRequest);
DecryptRequest successfulRequest = actualRequests.get(1);
assertArrayEquals(
expectedSuccessfulEDK.getProviderInformation(),
successfulRequest.getKeyId().getBytes(StandardCharsets.UTF_8));
assertEquals(ENCRYPTION_CONTEXT, successfulRequest.getEncryptionContext());
assertArrayEquals(
expectedSuccessfulEDK.getEncryptedDataKey(),
successfulRequest.getCiphertextBlob().array());
assertUserAgent(successfulRequest);
assertArrayEquals(
expectedSuccessfulEDK.getProviderInformation(), dataKeyResult.getProviderInformation());
assertArrayEquals(
expectedSuccessfulEDK.getEncryptedDataKey(), dataKeyResult.getEncryptedDataKey());
}
private void assertUserAgent(AmazonWebServiceRequest request) {
assertTrue(
request
.getRequestClientOptions()
.getClientMarker(RequestClientOptions.Marker.USER_AGENT)
.contains(VersionInfo.loadUserAgent()));
}
}
public static class NonParameterized {
@Test
public void testBuildStrictWithNoCMKs() throws Exception {
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
assertThrows(
IllegalArgumentException.class,
() -> KmsMasterKeyProvider.builder().withCustomClientFactory(supplier).buildStrict());
assertThrows(
IllegalArgumentException.class,
() ->
KmsMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict(Collections.emptyList()));
assertThrows(
IllegalArgumentException.class,
() ->
KmsMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict((List) null));
}
@Test
public void testBuildStrictWithNullCMK() throws Exception {
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
assertThrows(
IllegalArgumentException.class,
() ->
KmsMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict((String) null));
assertThrows(
IllegalArgumentException.class,
() ->
KmsMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildStrict(Arrays.asList((String) null)));
}
@Test
public void testBuildDiscoveryWithFilter() throws Exception {
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
KmsMasterKeyProvider mkp1 =
KmsMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildDiscovery(new DiscoveryFilter("aws", Arrays.asList("accountId")));
assertNotNull(mkp1);
}
@Test
public void testBuildDiscoveryWithNullFilter() throws Exception {
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
assertThrows(
IllegalArgumentException.class,
() ->
KmsMasterKeyProvider.builder()
.withCustomClientFactory(supplier)
.buildDiscovery(null));
}
@Test
public void testDecryptMismatchedKMSKeyIdResponse() throws Exception {
MockKMSClient client = spy(new MockKMSClient());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
DecryptResult badResult = new DecryptResult();
badResult.setKeyId(KEY_ID_2);
badResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()));
doReturn(badResult).when(client).decrypt(isA(DecryptRequest.class));
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder().withCustomClientFactory(supplier).buildDiscovery();
assertThrows(
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(EDK_ID_1), ENCRYPTION_CONTEXT));
}
}
@Test
public void testExplicitCredentials() throws Exception {
AWSCredentials creds =
new AWSCredentials() {
@Override
public String getAWSAccessKeyId() {
throw new UsedExplicitCredentials();
}
@Override
public String getAWSSecretKey() {
throw new UsedExplicitCredentials();
}
};
MasterKeyProvider<KmsMasterKey> mkp =
KmsMasterKeyProvider.builder()
.withCredentials(creds)
.buildStrict("arn:aws:kms:us-east-1:012345678901:key/foo-bar");
assertExplicitCredentialsUsed(mkp);
mkp =
KmsMasterKeyProvider.builder()
.withCredentials(new AWSStaticCredentialsProvider(creds))
.buildStrict("arn:aws:kms:us-east-1:012345678901:key/foo-bar");
assertExplicitCredentialsUsed(mkp);
}
private void assertExplicitCredentialsUsed(final MasterKeyProvider<KmsMasterKey> mkp) {
try {
MasterKeyRequest mkr =
MasterKeyRequest.newBuilder()
.setEncryptionContext(Collections.emptyMap())
.setStreaming(true)
.build();
mkp.getMasterKeysForEncryption(mkr)
.forEach(mk -> mk.generateDataKey(ALGORITHM_SUITE, Collections.emptyMap()));
fail("Expected exception");
} catch (UsedExplicitCredentials e) {
// ok
}
}
private static class UsedExplicitCredentials extends RuntimeException {}
}
| 5,377 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/jce/JceMasterKeyTest.java | package com.amazonaws.encryptionsdk.jce;
import java.security.*;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
public class JceMasterKeyTest {
private static final SecretKey SECRET_KEY = new SecretKeySpec(new byte[1], "AES");
private static final PrivateKey PRIVATE_KEY;
private static final PublicKey PUBLIC_KEY;
static {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PUBLIC_KEY = keyPair.getPublic();
PRIVATE_KEY = keyPair.getPrivate();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private JceMasterKey jceGetInstance(final String algorithmName) {
return JceMasterKey.getInstance(SECRET_KEY, "mockProvider", "mockKey", algorithmName);
}
private JceMasterKey jceGetInstanceAsymmetric(final String algorithmName) {
return JceMasterKey.getInstance(
PUBLIC_KEY, PRIVATE_KEY, "mockProvider", "mockKey", algorithmName);
}
@Test(expected = IllegalArgumentException.class)
public void testGetInstanceInvalidWrappingAlgorithm() {
jceGetInstance("blatently/unsupported/algorithm");
}
@Test(expected = UnsupportedOperationException.class)
public void testGetInstanceAsymmetricInvalidWrappingAlgorithm() {
jceGetInstanceAsymmetric("rsa/ec/unsupportedAlgorithm");
}
/**
* Calls JceMasterKey.getInstance with differently cased wrappingAlgorithm names. Passes if no
* Exception is thrown. Relies on passing an invalid algorithm name to result in an Exception.
*/
@Test
public void testGetInstanceAllLowercase() {
jceGetInstance("aes/gcm/nopadding");
}
@Test
public void testGetInstanceMixedCasing() {
jceGetInstance("AES/GCm/NOpadding");
}
@Test
public void testGetInstanceAsymmetricAllLowercase() {
jceGetInstanceAsymmetric("rsa/ecb/oaepwithsha-256andmgf1padding");
}
@Test
public void testGetInstanceAsymmetricMixedCasing() {
jceGetInstanceAsymmetric("RSA/ECB/OAepwithsha-256andmgf1padding");
}
}
| 5,378 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/jce/KeyStoreProviderTest.java | /*
* Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except
* in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.amazonaws.encryptionsdk.jce;
import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.CryptoResult;
import com.amazonaws.encryptionsdk.MasterKeyProvider;
import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException;
import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStore.PasswordProtection;
import java.security.KeyStoreException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Before;
import org.junit.Test;
import sun.security.x509.AlgorithmId;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateValidity;
import sun.security.x509.CertificateX509Key;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
/* These internal sun classes are included solely for test purposes as
this test cannot use BouncyCastle cert generation, as there are incompatibilities
between how standard BC and FIPS BC perform cert generation. */
public class KeyStoreProviderTest {
private static final SecureRandom RND = new SecureRandom();
private static final KeyPairGenerator KG;
private static final byte[] PLAINTEXT = generate(1024);
private static final char[] PASSWORD = "Password".toCharArray();
private static final KeyStore.PasswordProtection PP = new PasswordProtection(PASSWORD);
private KeyStore ks;
static {
try {
KG = KeyPairGenerator.getInstance("RSA");
KG.initialize(2048);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Before
public void setup() throws Exception {
ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, PASSWORD);
}
@Test
public void singleKeyPkcs1() throws Exception {
addEntry("key1");
final KeyStoreProvider mkp =
new KeyStoreProvider(ks, PP, "KeyStore", "RSA/ECB/PKCS1Padding", "key1");
final JceMasterKey mk1 = mkp.getMasterKey("key1");
final AwsCrypto crypto = AwsCrypto.standard();
final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT);
assertEquals(1, ct.getMasterKeyIds().size());
final CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only the first found key should be used
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk1, result.getMasterKeys().get(0));
}
@Test
public void singleKeyOaepSha1() throws Exception {
addEntry("key1");
final KeyStoreProvider mkp =
new KeyStoreProvider(ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-1AndMGF1Padding", "key1");
final JceMasterKey mk1 = mkp.getMasterKey("key1");
final AwsCrypto crypto = AwsCrypto.standard();
final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT);
assertEquals(1, ct.getMasterKeyIds().size());
final CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only the first found key should be used
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk1, result.getMasterKeys().get(0));
}
@Test
public void singleKeyOaepSha256() throws Exception {
addEntry("key1");
final KeyStoreProvider mkp =
new KeyStoreProvider(ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1");
final JceMasterKey mk1 = mkp.getMasterKey("key1");
final AwsCrypto crypto = AwsCrypto.standard();
final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT);
assertEquals(1, ct.getMasterKeyIds().size());
final CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only the first found key should be used
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk1, result.getMasterKeys().get(0));
}
@Test
public void multipleKeys() throws Exception {
addEntry("key1");
addEntry("key2");
final KeyStoreProvider mkp =
new KeyStoreProvider(
ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1", "key2");
@SuppressWarnings("unused")
final JceMasterKey mk1 = mkp.getMasterKey("key1");
final JceMasterKey mk2 = mkp.getMasterKey("key2");
final AwsCrypto crypto = AwsCrypto.standard();
final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT);
assertEquals(2, ct.getMasterKeyIds().size());
CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Order is non-deterministic
assertEquals(1, result.getMasterKeys().size());
// Delete the first key and see if it works
ks.deleteEntry("key1");
result = crypto.decryptData(mkp, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only the first found key should be used
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk2, result.getMasterKeys().get(0));
}
@Test(expected = CannotUnwrapDataKeyException.class)
public void encryptOnly() throws Exception {
addPublicEntry("key1");
final KeyStoreProvider mkp =
new KeyStoreProvider(ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1");
final AwsCrypto crypto = AwsCrypto.standard();
final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT);
assertEquals(1, ct.getMasterKeyIds().size());
crypto.decryptData(mkp, ct.getResult());
}
@Test
public void escrowAndSymmetric() throws Exception {
addPublicEntry("key1");
addEntry("key2");
final KeyStoreProvider mkp =
new KeyStoreProvider(
ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1", "key2");
@SuppressWarnings("unused")
final JceMasterKey mk1 = mkp.getMasterKey("key1");
final JceMasterKey mk2 = mkp.getMasterKey("key2");
final AwsCrypto crypto = AwsCrypto.standard();
final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT);
assertEquals(2, ct.getMasterKeyIds().size());
CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only could have decrypted with the keypair
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk2, result.getMasterKeys().get(0));
// Delete the first key and see if it works
ks.deleteEntry("key1");
result = crypto.decryptData(mkp, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only the first found key should be used
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk2, result.getMasterKeys().get(0));
}
@Test
public void escrowAndSymmetricSecondProvider() throws GeneralSecurityException, IOException {
addPublicEntry("key1");
addEntry("key2");
final KeyStoreProvider mkp =
new KeyStoreProvider(
ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1", "key2");
@SuppressWarnings("unused")
final JceMasterKey mk1 = mkp.getMasterKey("key1");
final JceMasterKey mk2 = mkp.getMasterKey("key2");
final AwsCrypto crypto = AwsCrypto.standard();
final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT);
assertEquals(2, ct.getMasterKeyIds().size());
final KeyStoreProvider mkp2 =
new KeyStoreProvider(ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1");
CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp2, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only could have decrypted with the keypair
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk2, result.getMasterKeys().get(0));
}
@Test
public void escrowCase() throws GeneralSecurityException, IOException {
addEntry("escrowKey");
KeyStore ks2 = KeyStore.getInstance(KeyStore.getDefaultType());
ks2.load(null, PASSWORD);
copyPublicPart(ks, ks2, "escrowKey");
final KeyStoreProvider mkp =
new KeyStoreProvider(
ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "escrowKey");
final KeyStoreProvider escrowProvider =
new KeyStoreProvider(
ks2, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "escrowKey");
final JceMasterKey mk1 = escrowProvider.getMasterKey("escrowKey");
final AwsCrypto crypto = AwsCrypto.standard();
final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(escrowProvider, PLAINTEXT);
assertEquals(1, ct.getMasterKeyIds().size());
try {
crypto.decryptData(escrowProvider, ct.getResult());
fail("Expected CannotUnwrapDataKeyException");
} catch (final CannotUnwrapDataKeyException ex) {
// expected
}
CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only could have decrypted with the keypair
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk1, result.getMasterKeys().get(0));
}
@Test
public void keystoreAndRawProvider() throws GeneralSecurityException, IOException {
addEntry("key1");
final SecretKeySpec k1 = new SecretKeySpec(generate(32), "AES");
final JceMasterKey jcep = JceMasterKey.getInstance(k1, "jce", "1", "AES/GCM/NoPadding");
final KeyStoreProvider ksp =
new KeyStoreProvider(ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1");
MasterKeyProvider<JceMasterKey> multiProvider =
MultipleProviderFactory.buildMultiProvider(JceMasterKey.class, jcep, ksp);
assertEquals(jcep, multiProvider.getMasterKey("jce", "1"));
final AwsCrypto crypto = AwsCrypto.standard();
final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(multiProvider, PLAINTEXT);
assertEquals(2, ct.getMasterKeyIds().size());
CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(multiProvider, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
assertEquals(jcep, result.getMasterKeys().get(0));
// Decrypt just using each individually
assertArrayEquals(PLAINTEXT, crypto.decryptData(jcep, ct.getResult()).getResult());
assertArrayEquals(PLAINTEXT, crypto.decryptData(ksp, ct.getResult()).getResult());
}
private void addEntry(final String alias) throws GeneralSecurityException, IOException {
final KeyPair pair = KG.generateKeyPair();
ks.setEntry(
alias,
new KeyStore.PrivateKeyEntry(
pair.getPrivate(), new X509Certificate[] {generateCertificate(pair, alias)}),
PP);
}
private void addPublicEntry(final String alias) throws GeneralSecurityException, IOException {
final KeyPair pair = KG.generateKeyPair();
ks.setEntry(
alias, new KeyStore.TrustedCertificateEntry(generateCertificate(pair, alias)), null);
}
private X509Certificate generateCertificate(final KeyPair pair, final String alias)
throws GeneralSecurityException, IOException {
final X509CertInfo info = new X509CertInfo();
final X500Name name = new X500Name("dc=" + alias);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(256, RND)));
info.set(X509CertInfo.SUBJECT, name);
info.set(X509CertInfo.ISSUER, name);
info.set(
X509CertInfo.VALIDITY,
new CertificateValidity(
Date.from(Instant.now().minus(1, ChronoUnit.DAYS)),
Date.from(Instant.now().plus(730, ChronoUnit.DAYS))));
info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
info.set(
X509CertInfo.ALGORITHM_ID,
new CertificateAlgorithmId(new AlgorithmId(AlgorithmId.sha256WithRSAEncryption_oid)));
final X509CertImpl cert = new X509CertImpl(info);
cert.sign(pair.getPrivate(), AlgorithmId.sha256WithRSAEncryption_oid.toString());
return cert;
}
private void copyPublicPart(final KeyStore src, final KeyStore dst, final String alias)
throws KeyStoreException {
Certificate cert = src.getCertificate(alias);
dst.setCertificateEntry(alias, cert);
}
}
| 5,379 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/MockKmsClient.java | /*
* Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except
* in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.amazonaws.encryptionsdk.kmssdkv2;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.*;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.*;
import software.amazon.awssdk.services.kms.model.UnsupportedOperationException;
public class MockKmsClient implements KmsClient {
private static final SecureRandom rnd = new SecureRandom();
private static final String ACCOUNT_ID = "01234567890";
private final Map<DecryptMapKey, DecryptResponse> responses_ = new HashMap<>();
private final Set<String> activeKeys = new HashSet<>();
private final Map<String, String> keyAliases = new HashMap<>();
private Region region_ = Region.US_WEST_2;
@Override
public final String serviceName() {
return SERVICE_NAME;
}
@Override
public void close() {}
@Override
public CreateAliasResponse createAlias(CreateAliasRequest req) {
assertExists(req.targetKeyId());
keyAliases.put("alias/" + req.aliasName(), keyAliases.get(req.targetKeyId()));
return CreateAliasResponse.builder().build();
}
@Override
public CreateKeyResponse createKey() {
return createKey(CreateKeyRequest.builder().build());
}
@Override
public CreateKeyResponse createKey(CreateKeyRequest req) {
String keyId = UUID.randomUUID().toString();
String arn = "arn:aws:kms:" + region_.id() + ":" + ACCOUNT_ID + ":key/" + keyId;
activeKeys.add(arn);
keyAliases.put(keyId, arn);
keyAliases.put(arn, arn);
return CreateKeyResponse.builder()
.keyMetadata(
KeyMetadata.builder()
.awsAccountId(ACCOUNT_ID)
.creationDate(Instant.now())
.description(req.description())
.enabled(true)
.keyId(keyId)
.keyUsage(KeyUsageType.ENCRYPT_DECRYPT)
.arn(arn)
.build())
.build();
}
@Override
public DecryptResponse decrypt(DecryptRequest req) {
DecryptResponse response = responses_.get(new DecryptMapKey(req));
if (response != null) {
// Copy it to avoid external modification
return DecryptResponse.builder()
.keyId(retrieveArn(response.keyId()))
.plaintext(SdkBytes.fromByteArray(response.plaintext().asByteArray()))
.build();
} else {
throw InvalidCiphertextException.builder().message("Invalid Ciphertext").build();
}
}
@Override
public DescribeKeyResponse describeKey(DescribeKeyRequest req) {
final String arn = retrieveArn(req.keyId());
return DescribeKeyResponse.builder()
.keyMetadata(KeyMetadata.builder().arn(arn).keyId(arn).build())
.build();
}
@Override
public EncryptResponse encrypt(EncryptRequest req) {
// We internally delegate to encrypt, so as to avoid mockito detecting extra calls to encrypt
// when spying on the
// MockKMSClient, we put the real logic into a separate function.
return encrypt0(req);
}
private EncryptResponse encrypt0(EncryptRequest req) {
String arn = retrieveArn(req.keyId());
final byte[] cipherText = new byte[512];
rnd.nextBytes(cipherText);
DecryptResponse dec =
DecryptResponse.builder()
.keyId(retrieveArn(arn))
.plaintext(SdkBytes.fromByteArray(req.plaintext().asByteArray()))
.build();
ByteBuffer ctBuff = ByteBuffer.wrap(cipherText);
responses_.put(new DecryptMapKey(ctBuff, req.encryptionContext()), dec);
return EncryptResponse.builder()
.ciphertextBlob(SdkBytes.fromByteBuffer(ctBuff))
.keyId(arn)
.build();
}
@Override
public GenerateDataKeyResponse generateDataKey(GenerateDataKeyRequest req) {
byte[] pt;
DataKeySpec keySpec = req.keySpec();
if (keySpec == null) {
pt = new byte[req.numberOfBytes()];
} else {
switch (keySpec) {
case AES_256:
pt = new byte[32];
break;
case AES_128:
pt = new byte[16];
break;
default:
throw UnsupportedOperationException.builder().build();
}
}
rnd.nextBytes(pt);
String arn = retrieveArn(req.keyId());
EncryptResponse encryptResponse =
encrypt0(
EncryptRequest.builder()
.keyId(arn)
.plaintext(SdkBytes.fromByteArray(pt))
.encryptionContext(req.encryptionContext())
.build());
return GenerateDataKeyResponse.builder()
.keyId(arn)
.ciphertextBlob(encryptResponse.ciphertextBlob())
.plaintext(SdkBytes.fromByteArray(pt))
.build();
}
public GenerateDataKeyWithoutPlaintextResponse generateDataKeyWithoutPlaintext(
GenerateDataKeyWithoutPlaintextRequest req) {
String arn = retrieveArn(req.keyId());
GenerateDataKeyRequest generateDataKeyRequest =
GenerateDataKeyRequest.builder()
.encryptionContext(req.encryptionContext())
.grantTokens(req.grantTokens())
.keyId(arn)
.keySpec(req.keySpec())
.numberOfBytes(req.numberOfBytes())
.build();
GenerateDataKeyResponse generateDataKey = generateDataKey(generateDataKeyRequest);
return GenerateDataKeyWithoutPlaintextResponse.builder()
.ciphertextBlob(generateDataKey.ciphertextBlob())
.keyId(arn)
.build();
}
public void setRegion(Region req) {
region_ = req;
}
public void deleteKey(final String keyId) {
final String arn = retrieveArn(keyId);
activeKeys.remove(arn);
}
private String retrieveArn(final String keyId) {
String arn = keyAliases.get(keyId);
assertExists(arn);
return arn;
}
private void assertExists(String keyId) {
if (keyAliases.containsKey(keyId)) {
keyId = keyAliases.get(keyId);
}
if (keyId == null || !activeKeys.contains(keyId)) {
throw NotFoundException.builder().message("Key doesn't exist: " + keyId).build();
}
}
private static class DecryptMapKey {
private final ByteBuffer cipherText;
private final Map<String, String> ec;
public DecryptMapKey(DecryptRequest req) {
cipherText = req.ciphertextBlob().asByteBuffer();
if (req.encryptionContext() != null) {
ec = Collections.unmodifiableMap(new HashMap<>(req.encryptionContext()));
} else {
ec = Collections.emptyMap();
}
}
public DecryptMapKey(ByteBuffer ctBuff, Map<String, String> ec) {
cipherText = ctBuff.asReadOnlyBuffer();
if (ec != null) {
this.ec = Collections.unmodifiableMap(new HashMap<>(ec));
} else {
this.ec = Collections.emptyMap();
}
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cipherText == null) ? 0 : cipherText.hashCode());
result = prime * result + ((ec == null) ? 0 : ec.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
DecryptMapKey other = (DecryptMapKey) obj;
if (cipherText == null) {
if (other.cipherText != null) return false;
} else if (!cipherText.equals(other.cipherText)) return false;
if (ec == null) {
if (other.ec != null) return false;
} else if (!ec.equals(other.ec)) return false;
return true;
}
public String toString() {
return "DecryptMapKey [cipherText=" + cipherText + ", ec=" + ec + "]";
}
}
}
| 5,380 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/KMSProviderBuilderMockTests.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kmssdkv2;
import static com.amazonaws.encryptionsdk.multi.MultipleProviderFactory.buildMultiProvider;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.notNull;
import static org.mockito.Mockito.*;
import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.MasterKeyProvider;
import com.amazonaws.encryptionsdk.internal.VersionInfo;
import java.util.Arrays;
import java.util.Optional;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.awscore.AwsRequest;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kms.model.CreateAliasRequest;
import software.amazon.awssdk.services.kms.model.DecryptRequest;
import software.amazon.awssdk.services.kms.model.EncryptRequest;
import software.amazon.awssdk.services.kms.model.GenerateDataKeyRequest;
public class KMSProviderBuilderMockTests {
@Test
public void testBareAliasMapping() {
MockKmsClient client = spy(new MockKmsClient());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(notNull())).thenReturn(client);
String key1 = client.createKey().keyMetadata().keyId();
client.createAlias(CreateAliasRequest.builder().aliasName("foo").targetKeyId(key1).build());
KmsMasterKeyProvider mkp0 =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.defaultRegion(Region.US_WEST_2)
.buildStrict("alias/foo");
AwsCrypto.standard().encryptData(mkp0, new byte[0]);
}
@Test
public void testGrantTokenPassthrough_usingMKsetCall() throws Exception {
MockKmsClient client = spy(new MockKmsClient());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
String key1 = client.createKey().keyMetadata().arn();
String key2 = client.createKey().keyMetadata().arn();
KmsMasterKeyProvider mkp0 =
KmsMasterKeyProvider.builder()
.defaultRegion(Region.US_WEST_2)
.customRegionalClientSupplier(supplier)
.buildStrict(key1, key2);
KmsMasterKey mk1 = mkp0.getMasterKey(key1);
KmsMasterKey mk2 = mkp0.getMasterKey(key2);
mk1.setGrantTokens(singletonList("foo"));
mk2.setGrantTokens(singletonList("foo"));
MasterKeyProvider<?> mkp = buildMultiProvider(mk1, mk2);
byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[0]).getResult();
ArgumentCaptor<GenerateDataKeyRequest> gdkr =
ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
verify(client, times(1)).generateDataKey(gdkr.capture());
assertEquals(key1, gdkr.getValue().keyId());
assertEquals(1, gdkr.getValue().grantTokens().size());
assertEquals("foo", gdkr.getValue().grantTokens().get(0));
ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class);
verify(client, times(1)).encrypt(er.capture());
assertEquals(key2, er.getValue().keyId());
assertEquals(1, er.getValue().grantTokens().size());
assertEquals("foo", er.getValue().grantTokens().get(0));
AwsCrypto.standard().decryptData(mkp, ciphertext);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decrypt.capture());
assertEquals(1, decrypt.getValue().grantTokens().size());
assertEquals("foo", decrypt.getValue().grantTokens().get(0));
verify(supplier, atLeastOnce()).getClient(Region.US_WEST_2);
verifyNoMoreInteractions(supplier);
}
@Test
public void testGrantTokenPassthrough_usingMKPWithers() throws Exception {
MockKmsClient client = spy(new MockKmsClient());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
String key1 = client.createKey().keyMetadata().arn();
String key2 = client.createKey().keyMetadata().arn();
KmsMasterKeyProvider mkp0 =
KmsMasterKeyProvider.builder()
.defaultRegion(Region.US_WEST_2)
.customRegionalClientSupplier(supplier)
.buildStrict(key1, key2);
MasterKeyProvider<?> mkp = mkp0.withGrantTokens("foo");
byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[0]).getResult();
ArgumentCaptor<GenerateDataKeyRequest> gdkr =
ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
verify(client, times(1)).generateDataKey(gdkr.capture());
assertEquals(key1, gdkr.getValue().keyId());
assertEquals(1, gdkr.getValue().grantTokens().size());
assertEquals("foo", gdkr.getValue().grantTokens().get(0));
ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class);
verify(client, times(1)).encrypt(er.capture());
assertEquals(key2, er.getValue().keyId());
assertEquals(1, er.getValue().grantTokens().size());
assertEquals("foo", er.getValue().grantTokens().get(0));
mkp = mkp0.withGrantTokens(Arrays.asList("bar"));
AwsCrypto.standard().decryptData(mkp, ciphertext);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decrypt.capture());
assertEquals(1, decrypt.getValue().grantTokens().size());
assertEquals("bar", decrypt.getValue().grantTokens().get(0));
verify(supplier, atLeastOnce()).getClient(Region.US_WEST_2);
verifyNoMoreInteractions(supplier);
}
@Test
public void testUserAgentPassthrough() throws Exception {
MockKmsClient client = spy(new MockKmsClient());
String key1 = client.createKey().keyMetadata().arn();
String key2 = client.createKey().keyMetadata().arn();
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(ignored -> client)
.buildStrict(key1, key2);
AwsCrypto.standard()
.decryptData(mkp, AwsCrypto.standard().encryptData(mkp, new byte[0]).getResult());
ArgumentCaptor<GenerateDataKeyRequest> gdkr =
ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
verify(client, times(1)).generateDataKey(gdkr.capture());
assertApiName(gdkr.getValue());
ArgumentCaptor<EncryptRequest> encr = ArgumentCaptor.forClass(EncryptRequest.class);
verify(client, times(1)).encrypt(encr.capture());
assertApiName(encr.getValue());
ArgumentCaptor<DecryptRequest> decr = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decr.capture());
assertApiName(decr.getValue());
}
private void assertApiName(AwsRequest request) {
Optional<AwsRequestOverrideConfiguration> overrideConfig = request.overrideConfiguration();
assertTrue(overrideConfig.isPresent());
assertTrue(
overrideConfig.get().apiNames().stream()
.anyMatch(
api ->
api.name().equals(VersionInfo.apiName())
&& api.version().equals(VersionInfo.versionNumber())));
}
}
| 5,381 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/MaxEncryptedDataKeysIntegrationTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kmssdkv2;
import static org.junit.Assert.assertArrayEquals;
import static org.mockito.Mockito.*;
import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.TestUtils;
import com.amazonaws.encryptionsdk.exception.AwsCryptoException;
import com.amazonaws.encryptionsdk.kms.KMSTestFixtures;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.DecryptRequest;
public class MaxEncryptedDataKeysIntegrationTest {
private static final byte[] PLAINTEXT = {1, 2, 3, 4};
private static final int MAX_EDKS = 3;
private KmsClient testClient_;
private RegionalClientSupplier testClientSupplier_;
private AwsCrypto testCryptoClient_;
@Before
public void setup() {
testClient_ = spy(new ProxyKmsClient(KmsClient.builder().region(Region.US_WEST_2).build()));
testClientSupplier_ =
region -> {
if (region == Region.US_WEST_2) {
return testClient_;
}
throw new AwsCryptoException(
"test supplier only configured for us-west-2 and eu-central-1");
};
testCryptoClient_ = AwsCrypto.standard().toBuilder().withMaxEncryptedDataKeys(MAX_EDKS).build();
}
private KmsMasterKeyProvider providerWithEdks(int numKeys) {
List<String> keyIds = new ArrayList<>(numKeys);
for (int i = 0; i < numKeys; i++) {
keyIds.add(KMSTestFixtures.US_WEST_2_KEY_ID);
}
return KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(testClientSupplier_)
.buildStrict(keyIds);
}
@Test
public void encryptDecryptWithLessThanMaxEdks() {
KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS - 1);
byte[] ciphertext = testCryptoClient_.encryptData(provider, PLAINTEXT).getResult();
byte[] decrypted = testCryptoClient_.decryptData(provider, ciphertext).getResult();
assertArrayEquals(decrypted, PLAINTEXT);
}
@Test
public void encryptDecryptWithMaxEdks() {
KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS);
byte[] ciphertext = testCryptoClient_.encryptData(provider, PLAINTEXT).getResult();
byte[] decrypted = testCryptoClient_.decryptData(provider, ciphertext).getResult();
assertArrayEquals(decrypted, PLAINTEXT);
}
@Test
public void noEncryptWithMoreThanMaxEdks() {
KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS + 1);
TestUtils.assertThrows(
AwsCryptoException.class,
"Encrypted data keys exceed maxEncryptedDataKeys",
() -> testCryptoClient_.encryptData(provider, PLAINTEXT));
}
@Test
public void noDecryptWithMoreThanMaxEdks() {
KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS + 1);
byte[] ciphertext = AwsCrypto.standard().encryptData(provider, PLAINTEXT).getResult();
TestUtils.assertThrows(
AwsCryptoException.class,
"Ciphertext encrypted data keys exceed maxEncryptedDataKeys",
() -> testCryptoClient_.decryptData(provider, ciphertext));
verify(testClient_, never()).decrypt((DecryptRequest) any());
}
}
| 5,382 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/AwsKmsMrkAwareMasterKeyTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kmssdkv2;
import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import com.amazonaws.encryptionsdk.*;
import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException;
import com.amazonaws.encryptionsdk.model.KeyBlob;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.jupiter.api.DisplayName;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.*;
@RunWith(Enclosed.class)
public class AwsKmsMrkAwareMasterKeyTest {
public static class getInstance {
@Test
public void basic_use() {
KmsClient client = spy(new MockKmsClient());
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6
// = type=test
// # On initialization, the caller MUST provide:
final AwsKmsMrkAwareMasterKey test =
AwsKmsMrkAwareMasterKey.getInstance(
client,
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f",
mkp);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.5
// = type=test
// # MUST implement the Master Key Interface (../master-key-
// # interface.md#interface)
assertTrue(MasterKey.class.isInstance(test));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6
// = type=test
// # The AWS KMS key identifier MUST NOT be null or empty.
public void requires_valid_identifiers() {
KmsClient client = spy(new MockKmsClient());
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
assertThrows(
IllegalArgumentException.class,
() -> AwsKmsMrkAwareMasterKey.getInstance(client, "", mkp));
assertThrows(
IllegalArgumentException.class,
() -> AwsKmsMrkAwareMasterKey.getInstance(client, null, mkp));
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6
// = type=test
// # The AWS KMS
// # key identifier MUST be a valid identifier (aws-kms-key-arn.md#a-
// # valid-aws-kms-identifier).
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKey.getInstance(
client, "arn:aws:dynamodb:us-east-2:123456789012:table/myDynamoDBTable", mkp));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6
// = type=test
// # The AWS KMS SDK client MUST not be null.
public void requires_valid_client() {
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKey.getInstance(
null,
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f",
mkp));
}
@Test
@DisplayName("Precondition: A provider is required.")
public void requires_valid_provider() {
KmsClient client = spy(new MockKmsClient());
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKey.getInstance(
client,
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f",
null));
}
}
public static class generateDataKey {
@Test
public void basic_use() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final KmsClient client = mock(KmsClient.class);
when(client.generateDataKey((GenerateDataKeyRequest) any()))
.thenReturn(
GenerateDataKeyResponse.builder()
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
.keyId(keyIdentifier)
.ciphertextBlob(SdkBytes.fromByteArray(new byte[10]))
.build());
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn("aws-kms");
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6
// = type=test
// # The master key MUST be able to be configured with an optional list of
// # Grant Tokens.
masterKey.setGrantTokens(GRANT_TOKENS);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # The inputs MUST be the same as the Master Key Generate Data Key
// # (../master-key-interface.md#generate-data-key) interface.
DataKey<AwsKmsMrkAwareMasterKey> test =
masterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT);
ArgumentCaptor<GenerateDataKeyRequest> gr =
ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # This
// # master key MUST use the configured AWS KMS client to make an AWS KMS
// # GenerateDatakey (https://docs.aws.amazon.com/kms/latest/APIReference/
// # API_GenerateDataKey.html) request constructed as follows:
verify(client, times(1)).generateDataKey(gr.capture());
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # The output MUST be the same as the Master Key Generate Data Key
// # (../master-key-interface.md#generate-data-key) interface.
assertTrue(DataKey.class.isInstance(test));
GenerateDataKeyRequest actualRequest = gr.getValue();
assertEquals(keyIdentifier, actualRequest.keyId());
assertEquals(GRANT_TOKENS, actualRequest.grantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext());
assertEquals(ALGORITHM_SUITE.getDataKeyLength(), actualRequest.numberOfBytes().longValue());
assertTrue(actualRequest.overrideConfiguration().isPresent());
assertTrue(
actualRequest
.overrideConfiguration()
.get()
.apiNames()
.contains(AwsKmsMrkAwareMasterKey.API_NAME));
assertNotNull(test.getKey());
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # The response's "Plaintext" MUST be the plaintext in
// # the output.
assertEquals(ALGORITHM_SUITE.getDataKeyLength(), test.getKey().getEncoded().length);
assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), test.getKey().getAlgorithm());
assertNotNull(test.getEncryptedDataKey());
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # The response's cipher text blob MUST be used as the
// # returned as the ciphertext for the encrypted data key in the output.
assertEquals(10, test.getEncryptedDataKey().length);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # If the call succeeds the AWS KMS Generate Data Key response's
// # "Plaintext" MUST match the key derivation input length specified by
// # the algorithm suite included in the input.
public void length_must_match() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
// I use more, because less _should_ trigger an underflow... but the condition should _always_
// fail
final int wrongLength = ALGORITHM_SUITE.getDataKeyLength() + 1;
final KmsClient client = mock(KmsClient.class);
when(client.generateDataKey((GenerateDataKeyRequest) any()))
.thenReturn(
GenerateDataKeyResponse.builder()
.plaintext(SdkBytes.fromByteArray(new byte[wrongLength]))
.keyId(keyIdentifier)
.ciphertextBlob(SdkBytes.fromByteArray(new byte[10]))
.build());
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn("aws-kms");
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
assertThrows(
IllegalStateException.class,
() -> masterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT));
}
@Test
@DisplayName(
"Exceptional Postcondition: Must have an AWS KMS ARN from AWS KMS generateDataKey.")
public void need_an_arn() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final KmsClient client = mock(KmsClient.class);
when(client.generateDataKey((GenerateDataKeyRequest) any()))
.thenReturn(
GenerateDataKeyResponse.builder()
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10
// = type=test
// # The response's "KeyId"
// # MUST be valid.
.keyId("b3537ef1-d8dc-4780-9f5a-55776cbb2f7f")
.ciphertextBlob(SdkBytes.fromByteArray(new byte[10]))
.build());
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn("aws-kms");
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
assertThrows(
IllegalStateException.class,
() -> masterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT));
}
}
public static class encryptDataKey {
@Test
public void basic_use() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final SecretKey SECRET_KEY =
new SecretKeySpec(
generate(ALGORITHM_SUITE.getDataKeyLength()), ALGORITHM_SUITE.getDataKeyAlgo());
final MasterKeyProvider<AwsKmsMrkAwareMasterKey> mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn("aws-kms");
final DataKey dataKey =
new DataKey(
SECRET_KEY,
new byte[0],
"aws-kms".getBytes(StandardCharsets.UTF_8),
mock(MasterKey.class));
final KmsClient client = mock(KmsClient.class);
when(client.encrypt((EncryptRequest) any()))
.thenReturn(
EncryptResponse.builder()
.keyId(keyIdentifier)
.ciphertextBlob(SdkBytes.fromByteArray(new byte[10]))
.build());
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
// = type=test
// # The inputs MUST be the same as the Master Key Encrypt Data Key
// # (../master-key-interface.md#encrypt-data-key) interface.
DataKey<AwsKmsMrkAwareMasterKey> test =
masterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
// = type=test
// # The output MUST be the same as the Master Key Encrypt Data Key
// # (../master-key-interface.md#encrypt-data-key) interface.
assertTrue(DataKey.class.isInstance(test));
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
// = type=test
// # The master
// # key MUST use the configured AWS KMS client to make an AWS KMS Encrypt
// # (https://docs.aws.amazon.com/kms/latest/APIReference/
// # API_Encrypt.html) request constructed as follows:
verify(client, times(1)).encrypt((EncryptRequest) any());
ArgumentCaptor<EncryptRequest> gr = ArgumentCaptor.forClass(EncryptRequest.class);
verify(client, times(1)).encrypt(gr.capture());
final EncryptRequest actualRequest = gr.getValue();
assertEquals(keyIdentifier, actualRequest.keyId());
assertEquals(GRANT_TOKENS, actualRequest.grantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext());
assertTrue(actualRequest.overrideConfiguration().isPresent());
assertTrue(
actualRequest
.overrideConfiguration()
.get()
.apiNames()
.contains(AwsKmsMrkAwareMasterKey.API_NAME));
assertNotNull(test.getKey());
assertEquals(ALGORITHM_SUITE.getDataKeyLength(), test.getKey().getEncoded().length);
assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), test.getKey().getAlgorithm());
assertNotNull(test.getEncryptedDataKey());
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
// = type=test
// # The
// # response's cipher text blob MUST be used as the "ciphertext" for the
// # encrypted data key.
assertEquals(10, test.getEncryptedDataKey().length);
}
@Test
@DisplayName("Precondition: The key format MUST be RAW.")
public void secret_key_must_be_raw() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final MasterKeyProvider<AwsKmsMrkAwareMasterKey> mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn("aws-kms");
// Test "stuff" here
final SecretKey SECRET_KEY = mock(SecretKeySpec.class);
when(SECRET_KEY.getFormat()).thenReturn("NOT-RAW");
final DataKey dataKey =
new DataKey(
SECRET_KEY,
new byte[0],
"aws-kms".getBytes(StandardCharsets.UTF_8),
mock(MasterKey.class));
final KmsClient client = mock(KmsClient.class);
when(client.encrypt((EncryptRequest) any()))
.thenReturn(
EncryptResponse.builder()
.keyId(keyIdentifier)
.ciphertextBlob(SdkBytes.fromByteArray(new byte[10]))
.build());
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
assertThrows(
"Only RAW encoded keys are supported",
IllegalArgumentException.class,
() -> masterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey));
}
@Test
@DisplayName("Postcondition: Must have an AWS KMS ARN from AWS KMS encrypt.")
public void need_an_arn() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final SecretKey SECRET_KEY =
new SecretKeySpec(
generate(ALGORITHM_SUITE.getDataKeyLength()), ALGORITHM_SUITE.getDataKeyAlgo());
final MasterKeyProvider<AwsKmsMrkAwareMasterKey> mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn("aws-kms");
final DataKey dataKey =
new DataKey(
SECRET_KEY,
new byte[0],
"aws-kms".getBytes(StandardCharsets.UTF_8),
mock(MasterKey.class));
final KmsClient client = mock(KmsClient.class);
when(client.encrypt((EncryptRequest) any()))
.thenReturn(
EncryptResponse.builder()
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
// = type=test
// # The AWS KMS Encrypt response MUST contain a valid "KeyId".
.keyId("b3537ef1-d8dc-4780-9f5a-55776cbb2f7f")
.ciphertextBlob(SdkBytes.fromByteArray(new byte[10]))
.build());
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
assertThrows(
IllegalStateException.class,
() -> masterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey));
}
}
public static class filterEncryptedDataKeys {
@Test
public void basic_use() {
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
assertTrue(AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(providerId, keyIdentifier, edk));
}
@Test
public void mrk_specific() {
/* This may be overkill,
* but the whole point
* of multi-region optimization
* is this fuzzy match.
*/
final String configuredIdentifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String ekdIdentifier =
"arn:aws:kms:us-east-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String providerId = "aws-kms";
final EncryptedDataKey edk =
new KeyBlob(providerId, ekdIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
assertTrue(
AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(providerId, configuredIdentifier, edk));
}
@Test
public void provider_info_must_be_arn() {
final String configuredIdentifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String rawKeyId = "mrk-edb7fe6942894d32ac46dbb1c922d574";
final String alias =
"arn:aws:kms:us-west-2:111122223333:alias/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String providerId = "aws-kms";
final EncryptedDataKey edkNotArn =
new KeyBlob(providerId, rawKeyId.getBytes(StandardCharsets.UTF_8), new byte[10]);
final EncryptedDataKey edkAliasArn =
new KeyBlob(providerId, rawKeyId.getBytes(StandardCharsets.UTF_8), new byte[10]);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # Additionally each provider info MUST be a valid AWS KMS ARN
// # (aws-kms-key-arn.md#a-valid-aws-kms-arn) with a resource type of
// # "key".
assertThrows(
IllegalStateException.class,
() ->
AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(
providerId, configuredIdentifier, edkNotArn));
assertThrows(
IllegalStateException.class,
() ->
AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(
providerId, configuredIdentifier, edkAliasArn));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # To match the encrypted data key's
// # provider ID MUST exactly match the value "aws-kms" and the the
// # function AWS KMS MRK Match for Decrypt (aws-kms-mrk-match-for-
// # decrypt.md#implementation) called with the configured AWS KMS key
// # identifier and the encrypted data key's provider info MUST return
// # "true".
public void may_not_match() {
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
assertFalse(
AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys("not-aws-kms", keyIdentifier, edk));
assertFalse(
AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(
providerId,
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
edk));
}
}
public static class decryptSingleEncryptedDataKey {
@Test
public void basic_use() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final KmsClient client = mock(KmsClient.class);
when(client.decrypt((DecryptRequest) any()))
.thenReturn(
DecryptResponse.builder()
.keyId(keyIdentifier)
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
.build());
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
DataKey<AwsKmsMrkAwareMasterKey> test =
AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey(
any(), client, keyIdentifier, GRANT_TOKENS, ALGORITHM_SUITE, edk, ENCRYPTION_CONTEXT);
verify(client, times(1)).decrypt((DecryptRequest) any());
ArgumentCaptor<DecryptRequest> gr = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(gr.capture());
final DecryptRequest actualRequest = gr.getValue();
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # To decrypt the encrypted data key this master key MUST use the
// # configured AWS KMS client to make an AWS KMS Decrypt
// # (https://docs.aws.amazon.com/kms/latest/APIReference/
// # API_Decrypt.html) request constructed as follows:
assertEquals(keyIdentifier, actualRequest.keyId());
assertEquals(GRANT_TOKENS, actualRequest.grantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext());
assertTrue(actualRequest.overrideConfiguration().isPresent());
assertTrue(
actualRequest
.overrideConfiguration()
.get()
.apiNames()
.contains(AwsKmsMrkAwareMasterKey.API_NAME));
assertNotNull(test.getKey());
assertEquals(ALGORITHM_SUITE.getDataKeyLength(), test.getKey().getEncoded().length);
assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), test.getKey().getAlgorithm());
}
@Test
@DisplayName("Exceptional Postcondition: Must have a CMK ARN from AWS KMS to match.")
public void expect_key_arn() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final KmsClient client = mock(KmsClient.class);
when(client.decrypt((DecryptRequest) any()))
.thenReturn(
DecryptResponse.builder()
.keyId(null)
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
.build());
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
assertThrows(
IllegalStateException.class,
() ->
AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey(
any(),
client,
keyIdentifier,
GRANT_TOKENS,
ALGORITHM_SUITE,
edk,
ENCRYPTION_CONTEXT));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # If the call succeeds then the response's "KeyId" MUST be equal to the
// # configured AWS KMS key identifier otherwise the function MUST collect
// # an error.
public void returned_arn_must_match() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final KmsClient client = mock(KmsClient.class);
when(client.decrypt((DecryptRequest) any()))
.thenReturn(
DecryptResponse.builder()
.keyId("arn:aws:kms:us-west-2:658956600833:key/something-else")
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
.build());
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
assertThrows(
IllegalStateException.class,
() ->
AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey(
any(),
client,
keyIdentifier,
GRANT_TOKENS,
ALGORITHM_SUITE,
edk,
ENCRYPTION_CONTEXT));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # The response's "Plaintext"'s length MUST equal the length
// # required by the requested algorithm suite otherwise the function MUST
// # collect an error.
public void key_length_must_match() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
// I use more, because less _should_ trigger an underflow... but the condition should _always_
// fail
final int wrongLength = ALGORITHM_SUITE.getDataKeyLength() + 1;
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final KmsClient client = mock(KmsClient.class);
when(client.decrypt((DecryptRequest) any()))
.thenReturn(
DecryptResponse.builder()
.keyId(keyIdentifier)
.plaintext(SdkBytes.fromByteArray(new byte[wrongLength]))
.build());
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
assertThrows(
IllegalStateException.class,
() ->
AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey(
any(),
client,
keyIdentifier,
GRANT_TOKENS,
ALGORITHM_SUITE,
edk,
ENCRYPTION_CONTEXT));
}
}
public static class decryptDataKey {
@Test
public void basic_use() {
final String keyIdentifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final byte[] cipherText = new byte[10];
final String providerId = "aws-kms";
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final EncryptedDataKey edk1 =
new KeyBlob("aws-kms", keyIdentifier.getBytes(StandardCharsets.UTF_8), cipherText);
final EncryptedDataKey edk2 =
new KeyBlob("aws-kms", keyIdentifier.getBytes(StandardCharsets.UTF_8), cipherText);
final KmsClient client = mock(KmsClient.class);
when(client.decrypt((DecryptRequest) any()))
.thenReturn(
DecryptResponse.builder()
.keyId(keyIdentifier)
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
.build());
final AwsKmsMrkAwareMasterKey mk =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
mk.setGrantTokens(GRANT_TOKENS);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # The inputs MUST be the same as the Master Key Decrypt Data Key
// # (../master-key-interface.md#decrypt-data-key) interface.
final DataKey<AwsKmsMrkAwareMasterKey> test =
mk.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk1, edk2), ENCRYPTION_CONTEXT);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # For each encrypted data key in the filtered set, one at a time, the
// # master key MUST attempt to decrypt the data key.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # If the AWS KMS response satisfies the requirements then it MUST be
// # use and this function MUST return and not attempt to decrypt any more
// # encrypted data keys.
verify(client, times((1)))
.decrypt(
DecryptRequest.builder()
.overrideConfiguration(
builder -> builder.addApiName(AwsKmsMrkAwareMasterKey.API_NAME))
.grantTokens(GRANT_TOKENS)
.encryptionContext(ENCRYPTION_CONTEXT)
.keyId(keyIdentifier)
.ciphertextBlob(SdkBytes.fromByteArray(cipherText))
.build());
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # The output MUST be the same as the Master Key Decrypt Data Key
// # (../master-key-interface.md#decrypt-data-key) interface.
assertTrue(DataKey.class.isInstance(test));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # The set of encrypted data keys MUST first be filtered to match this
// # master key's configuration.
public void edk_match() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final String clientErrMsg = "asdf";
final EncryptedDataKey edk1 =
new KeyBlob("not-aws-kms", keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final EncryptedDataKey edk2 =
new KeyBlob(
providerId, "not-key-identifier".getBytes(StandardCharsets.UTF_8), new byte[10]);
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final KmsClient client = mock(KmsClient.class);
when(client.decrypt((DecryptRequest) any()))
.thenThrow(AwsServiceException.builder().message(clientErrMsg).build());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
final AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
final CannotUnwrapDataKeyException testProviderNotMatch =
assertThrows(
"Unable to decrypt any data keys",
CannotUnwrapDataKeyException.class,
() ->
masterKey.decryptDataKey(
ALGORITHM_SUITE, Arrays.asList(edk1), ENCRYPTION_CONTEXT));
assertEquals(0, testProviderNotMatch.getSuppressed().length);
final IllegalStateException testArnNotMatch =
assertThrows(
"Unable to decrypt any data keys",
IllegalStateException.class,
() ->
masterKey.decryptDataKey(
ALGORITHM_SUITE, Arrays.asList(edk2), ENCRYPTION_CONTEXT));
assertEquals(0, testArnNotMatch.getSuppressed().length);
}
@Test
@DisplayName("Exceptional Postcondition: Master key was unable to decrypt.")
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # If this attempt
// # results in an error, then these errors MUST be collected.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// = type=test
// # If all the input encrypted data keys have been processed then this
// # function MUST yield an error that includes all the collected errors.
public void exception_wrapped() {
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final String keyIdentifier =
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f";
final String providerId = "aws-kms";
final String clientErrMsg = "asdf";
final EncryptedDataKey edk =
new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(providerId);
final KmsClient client = mock(KmsClient.class);
when(client.decrypt((DecryptRequest) any()))
.thenThrow(AwsServiceException.builder().message(clientErrMsg).build());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKey masterKey =
AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp);
masterKey.setGrantTokens(GRANT_TOKENS);
final CannotUnwrapDataKeyException test =
assertThrows(
"Unable to decrypt any data keys",
CannotUnwrapDataKeyException.class,
() ->
masterKey.decryptDataKey(
ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT));
assertEquals(1, test.getSuppressed().length);
Throwable fromClient = Arrays.stream(test.getSuppressed()).findFirst().get();
assertTrue(fromClient instanceof AwsServiceException);
assertTrue(fromClient.getMessage().startsWith(clientErrMsg));
}
}
public static class getMasterKey {
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.7
// = type=test
// # MUST be unchanged from the Master Key interface.
public void test_get_master_key() throws NoSuchMethodException {
String methodName = "getMasterKey";
Class<?>[] parameterTypes = new Class<?>[] {String.class, String.class};
// Make sure the signature is correct by fetching the base method
Method baseMethod = MasterKey.class.getDeclaredMethod(methodName, parameterTypes);
assertNotNull(baseMethod);
// Assert AwsKmsMrkAwareMasterKey does not declare the same method directly
assertThrows(
NoSuchMethodException.class,
() -> AwsKmsMrkAwareMasterKey.class.getDeclaredMethod(methodName, parameterTypes));
}
}
public static class getMasterKeysForEncryption {
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.8
// = type=test
// # MUST be unchanged from the Master Key interface.
public void test_getMasterKeysForEncryption() throws NoSuchMethodException {
String methodName = "getMasterKeysForEncryption";
Class<?>[] parameterTypes = new Class<?>[] {MasterKeyRequest.class};
// Make sure the signature is correct by fetching the base method
Method baseMethod = MasterKey.class.getDeclaredMethod(methodName, parameterTypes);
assertNotNull(baseMethod);
// Assert AwsKmsMrkAwareMasterKey does no declare the same method directly
assertThrows(
NoSuchMethodException.class,
() -> AwsKmsMrkAwareMasterKey.class.getDeclaredMethod(methodName, parameterTypes));
}
}
}
| 5,383 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/XCompatKmsDecryptTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kmssdkv2;
import static org.junit.Assert.assertArrayEquals;
import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.CryptoResult;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class XCompatKmsDecryptTest {
private final String plaintextFileName;
private final String ciphertextFileName;
private final String kmsKeyId;
public XCompatKmsDecryptTest(
String plaintextFileName, String ciphertextFileName, String kmsKeyId) {
this.plaintextFileName = plaintextFileName;
this.ciphertextFileName = ciphertextFileName;
this.kmsKeyId = kmsKeyId;
}
@Parameters(name = "{index}: testDecryptFromFile({0}, {1}, {2})")
public static Collection<Object[]> data() throws Exception {
String baseDirName;
baseDirName = System.getProperty("staticCompatibilityResourcesDir");
if (baseDirName == null) {
baseDirName =
XCompatKmsDecryptTest.class.getProtectionDomain().getCodeSource().getLocation().getPath()
+ "aws_encryption_sdk_resources";
}
List<Object[]> testCases_ = new ArrayList<>();
String ciphertextManifestName =
StringUtils.join(
new String[] {baseDirName, "manifests", "ciphertext.manifest"}, File.separator);
File ciphertextManifestFile = new File(ciphertextManifestName);
if (!ciphertextManifestFile.exists()) {
return Collections.emptyList();
}
ObjectMapper ciphertextManifestMapper = new ObjectMapper();
Map<String, Object> ciphertextManifest =
ciphertextManifestMapper.readValue(
ciphertextManifestFile, new TypeReference<Map<String, Object>>() {});
List<Map<String, Object>> testCases =
(List<Map<String, Object>>) ciphertextManifest.get("test_cases");
for (Map<String, Object> testCase : testCases) {
Map<String, String> plaintext = (Map<String, String>) testCase.get("plaintext");
Map<String, String> ciphertext = (Map<String, String>) testCase.get("ciphertext");
List<Map<String, Object>> masterKeys =
(List<Map<String, Object>>) testCase.get("master_keys");
for (Map<String, Object> masterKey : masterKeys) {
String providerId = (String) masterKey.get("provider_id");
if (providerId.equals("aws-kms") && (boolean) masterKey.get("decryptable")) {
testCases_.add(
new Object[] {
baseDirName + File.separator + plaintext.get("filename"),
baseDirName + File.separator + ciphertext.get("filename"),
(String) masterKey.get("key_id")
});
break;
}
}
}
return testCases_;
}
@Test
public void testDecryptFromFile() throws Exception {
AwsCrypto crypto = AwsCrypto.standard();
final KmsMasterKeyProvider masterKeyProvider =
KmsMasterKeyProvider.builder().buildStrict(kmsKeyId);
byte[] ciphertextBytes = Files.readAllBytes(Paths.get(ciphertextFileName));
byte[] plaintextBytes = Files.readAllBytes(Paths.get(plaintextFileName));
final CryptoResult<byte[], KmsMasterKey> decryptResult =
crypto.decryptData(masterKeyProvider, ciphertextBytes);
assertArrayEquals(plaintextBytes, decryptResult.getResult());
}
}
| 5,384 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/KMSProviderBuilderIntegrationTests.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kmssdkv2;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import com.amazonaws.encryptionsdk.*;
import com.amazonaws.encryptionsdk.exception.AwsCryptoException;
import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException;
import com.amazonaws.encryptionsdk.internal.VersionInfo;
import com.amazonaws.encryptionsdk.kms.DiscoveryFilter;
import com.amazonaws.encryptionsdk.kms.KMSTestFixtures;
import com.amazonaws.encryptionsdk.model.KeyBlob;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.awscore.AwsRequest;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.ApiName;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException;
import software.amazon.awssdk.core.exception.ApiCallTimeoutException;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.DecryptRequest;
import software.amazon.awssdk.services.kms.model.EncryptRequest;
import software.amazon.awssdk.services.kms.model.GenerateDataKeyRequest;
public class KMSProviderBuilderIntegrationTests {
private static final String AWS_KMS_PROVIDER_ID = "aws-kms";
private KmsClient testUSWestClient__;
private KmsClient testEUCentralClient__;
private RegionalClientSupplier testClientSupplier__;
@Before
public void setup() {
testUSWestClient__ =
spy(new ProxyKmsClient(KmsClient.builder().region(Region.US_WEST_2).build()));
testEUCentralClient__ =
spy(new ProxyKmsClient(KmsClient.builder().region(Region.EU_CENTRAL_1).build()));
testClientSupplier__ =
region -> {
if (region == Region.US_WEST_2) {
return testUSWestClient__;
} else if (region == Region.EU_CENTRAL_1) {
return testEUCentralClient__;
} else {
throw new AwsCryptoException(
"test supplier only configured for us-west-2 and eu-central-1");
}
};
}
@Test
public void whenBogusRegionsDecrypted_doesNotLeakClients() throws Exception {
AtomicReference<ConcurrentHashMap<Region, KmsClient>> kmsCache = new AtomicReference<>();
KmsMasterKeyProvider mkp =
(new KmsMasterKeyProvider.Builder() {
@Override
protected void snoopClientCache(final ConcurrentHashMap<Region, KmsClient> map) {
kmsCache.set(map);
}
})
.buildDiscovery();
try {
mkp.decryptDataKey(
CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256,
Collections.singleton(
new KeyBlob(
"aws-kms",
"arn:aws:kms:us-bogus-1:123456789010:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"
.getBytes(StandardCharsets.UTF_8),
new byte[40])),
new HashMap<>());
fail("Expected CannotUnwrapDataKeyException");
} catch (CannotUnwrapDataKeyException e) {
// ok
}
assertTrue(kmsCache.get().isEmpty());
}
@Test
public void whenOperationSuccessful_clientIsCached() {
AtomicReference<ConcurrentHashMap<Region, KmsClient>> kmsCache = new AtomicReference<>();
KmsMasterKeyProvider mkp =
(new KmsMasterKeyProvider.Builder() {
@Override
protected void snoopClientCache(final ConcurrentHashMap<Region, KmsClient> map) {
kmsCache.set(map);
}
})
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
AwsCrypto.standard().encryptData(mkp, new byte[1]);
KmsClient kms = kmsCache.get().get(Region.US_WEST_2);
assertNotNull(kms);
AwsCrypto.standard().encryptData(mkp, new byte[1]);
// Cache entry should stay the same
assertEquals(kms, kmsCache.get().get(Region.US_WEST_2));
}
// ============================================================================== GOOD
@Test
public void whenConstructedWithoutArguments_canUseMultipleRegions() throws Exception {
KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder().buildDiscovery();
for (String key : KMSTestFixtures.TEST_KEY_IDS) {
byte[] ciphertext =
AwsCrypto.standard()
.encryptData(KmsMasterKeyProvider.builder().buildStrict(key), new byte[1])
.getResult();
AwsCrypto.standard().decryptData(mkp, ciphertext);
}
}
@Test
public void whenConstructedInStrictMode_encryptDecrypt() throws Exception {
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(testClientSupplier__)
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[1]).getResult();
verify(testUSWestClient__, times(1)).generateDataKey((GenerateDataKeyRequest) any());
AwsCrypto.standard().decryptData(mkp, ciphertext);
verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any());
}
@Test
public void whenConstructedInStrictMode_encryptDecryptMultipleCmks() throws Exception {
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(testClientSupplier__)
.buildStrict(KMSTestFixtures.US_WEST_2_KEY_ID, KMSTestFixtures.EU_CENTRAL_1_KEY_ID);
byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[1]).getResult();
verify(testUSWestClient__, times(1)).generateDataKey((GenerateDataKeyRequest) any());
verify(testEUCentralClient__, times(1)).encrypt((EncryptRequest) any());
AwsCrypto.standard().decryptData(mkp, ciphertext);
verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any());
}
@Test
public void whenConstructedInStrictMode_encryptSingleBadKeyIdFails() throws Exception {
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(testClientSupplier__)
.defaultRegion(Region.US_WEST_2)
.buildStrict(KMSTestFixtures.US_WEST_2_KEY_ID, "badKeyId");
assertThrows(
AwsCryptoException.class,
() -> AwsCrypto.standard().encryptData(mkp, new byte[1]).getResult());
verify(testUSWestClient__, times(1)).generateDataKey((GenerateDataKeyRequest) any());
verify(testUSWestClient__, times(1)).encrypt((EncryptRequest) any());
}
@Test
public void whenConstructedInStrictMode_decryptBadEDKFails() throws Exception {
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(testClientSupplier__)
.defaultRegion(Region.US_WEST_2)
.buildStrict("badKeyId");
final CryptoAlgorithm algSuite = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> encCtx = Collections.singletonMap("myKey", "myValue");
final EncryptedDataKey badEDK =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
"badKeyId".getBytes(StandardCharsets.UTF_8),
new byte[algSuite.getDataKeyLength()]);
assertThrows(
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(algSuite, Collections.singletonList(badEDK), encCtx));
verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any());
}
@Test
public void whenConstructedInDiscoveryMode_decrypt() throws Exception {
KmsMasterKeyProvider singleCmkMkp =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(testClientSupplier__)
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
byte[] singleCmkCiphertext =
AwsCrypto.standard().encryptData(singleCmkMkp, new byte[1]).getResult();
KmsMasterKeyProvider mkpToTest =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(testClientSupplier__)
.buildDiscovery();
AwsCrypto.standard().decryptData(mkpToTest, singleCmkCiphertext);
verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any());
}
@Test
public void whenConstructedInDiscoveryMode_decryptBadEDKFails() throws Exception {
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(testClientSupplier__)
.defaultRegion(Region.US_WEST_2)
.buildDiscovery();
final CryptoAlgorithm algSuite = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> encCtx = Collections.singletonMap("myKey", "myValue");
final EncryptedDataKey badEDK =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
"badKeyId".getBytes(StandardCharsets.UTF_8),
new byte[algSuite.getDataKeyLength()]);
assertThrows(
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(algSuite, Collections.singletonList(badEDK), encCtx));
verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any());
}
@Test
public void whenConstructedWithDiscoveryFilter_decrypt() throws Exception {
KmsMasterKeyProvider singleCmkMkp =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(testClientSupplier__)
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
byte[] singleCmkCiphertext =
AwsCrypto.standard().encryptData(singleCmkMkp, new byte[1]).getResult();
KmsMasterKeyProvider mkpToTest =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(testClientSupplier__)
.buildDiscovery(
new DiscoveryFilter(
KMSTestFixtures.PARTITION, Arrays.asList(KMSTestFixtures.ACCOUNT_ID)));
AwsCrypto.standard().decryptData(mkpToTest, singleCmkCiphertext);
verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any());
}
@Test
public void whenConstructedWithDiscoveryFilter_decryptBadEDKFails() throws Exception {
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(testClientSupplier__)
.defaultRegion(Region.US_WEST_2)
.buildDiscovery(
new DiscoveryFilter(
KMSTestFixtures.PARTITION, Arrays.asList(KMSTestFixtures.ACCOUNT_ID)));
final CryptoAlgorithm algSuite = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> encCtx = Collections.singletonMap("myKey", "myValue");
final String badARN = "arn:aws:kms:us-west-2:658956600833:key/badID";
final EncryptedDataKey badEDK =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
badARN.getBytes(StandardCharsets.UTF_8),
new byte[algSuite.getDataKeyLength()]);
assertThrows(
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(algSuite, Collections.singletonList(badEDK), encCtx));
verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any());
}
@Test
public void whenHandlerConfigured_handlerIsInvoked() throws Exception {
ExecutionInterceptor interceptor =
spy(
new ExecutionInterceptor() {
@Override
public void beforeExecution(
Context.BeforeExecution context, ExecutionAttributes executionAttributes) {}
});
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.builderSupplier(
() ->
KmsClient.builder()
.overrideConfiguration(
ClientOverrideConfiguration.builder()
.addExecutionInterceptor(interceptor)
.build()))
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
AwsCrypto.standard().encryptData(mkp, new byte[1]);
verify(interceptor).beforeExecution(any(), any());
}
@Test
public void whenShortTimeoutSet_timesOut() throws Exception {
// By setting a timeout of 1ms, it's not physically possible to complete both the us-west-2 and
// eu-central-1
// requests due to speed of light limits.
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.builderSupplier(
() ->
KmsClient.builder()
.overrideConfiguration(
ClientOverrideConfiguration.builder()
.apiCallTimeout(Duration.ofMillis(1))
.build()))
.buildStrict(Arrays.asList(KMSTestFixtures.TEST_KEY_IDS));
try {
AwsCrypto.standard().encryptData(mkp, new byte[1]);
fail("Expected exception");
} catch (Exception e) {
if (!(e instanceof ApiCallAttemptTimeoutException)
&& !(e instanceof ApiCallTimeoutException)) {
throw e;
}
}
}
// ================================================= BAD
@Test
public void whenBuilderCloned_configurationIsRetained() throws Exception {
// TODO: remove test of credentials provider since no longer domain of builder supplier
AwsCredentialsProvider customProvider1 =
spy(new ProxyCredentialsProvider(DefaultCredentialsProvider.builder().build()));
AwsCredentialsProvider customProvider2 =
spy(new ProxyCredentialsProvider(DefaultCredentialsProvider.builder().build()));
KmsMasterKeyProvider.Builder builder =
KmsMasterKeyProvider.builder()
.builderSupplier(() -> KmsClient.builder().credentialsProvider(customProvider1));
KmsMasterKeyProvider.Builder builder2 = builder.clone();
// This will mutate the first builder to change the creds, but leave the clone unchanged.
MasterKeyProvider<?> mkp2 =
builder
.builderSupplier(() -> KmsClient.builder().credentialsProvider(customProvider2))
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
MasterKeyProvider<?> mkp1 = builder2.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
CryptoResult<byte[], ?> result = AwsCrypto.standard().encryptData(mkp1, new byte[0]);
verify(customProvider1, atLeastOnce()).resolveCredentials();
verify(customProvider2, never()).resolveCredentials();
reset(customProvider1, customProvider2);
result = AwsCrypto.standard().encryptData(mkp2, new byte[0]);
verify(customProvider1, never()).resolveCredentials();
verify(customProvider2, atLeastOnce()).resolveCredentials();
}
@Test
public void whenBuilderCloned_clientBuilderCustomizationIsRetained() throws Exception {
ExecutionInterceptor interceptor =
spy(
new ExecutionInterceptor() {
@Override
public void beforeExecution(
Context.BeforeExecution context, ExecutionAttributes executionAttributes) {}
});
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.builderSupplier(
() ->
KmsClient.builder()
.overrideConfiguration(
builder -> builder.addExecutionInterceptor(interceptor)))
.clone()
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
AwsCrypto.standard().encryptData(mkp, new byte[0]);
verify(interceptor, atLeastOnce()).beforeExecution(any(), any());
}
@Test
public void whenUserAgentsOverridden_originalUAsPreserved() throws Exception {
ExecutionInterceptor interceptor =
spy(
new ExecutionInterceptor() {
@Override
public SdkRequest modifyRequest(
Context.ModifyRequest context, ExecutionAttributes executionAttributes) {
if (!(context.request() instanceof AwsRequest)) {
return context.request();
}
AwsRequest awsRequest = (AwsRequest) context.request();
AwsRequestOverrideConfiguration.Builder overrideConfiguration;
if (awsRequest.overrideConfiguration().isPresent()) {
overrideConfiguration = awsRequest.overrideConfiguration().get().toBuilder();
} else {
overrideConfiguration = AwsRequestOverrideConfiguration.builder();
}
AwsRequestOverrideConfiguration newConfig =
overrideConfiguration
.addApiName(ApiName.builder().name("NEW_API").version("0.0.1").build())
.build();
awsRequest = awsRequest.toBuilder().overrideConfiguration(newConfig).build();
return awsRequest;
}
@Override
public void beforeTransmission(
Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
// Just for spying
}
});
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder()
.builderSupplier(
() ->
KmsClient.builder()
.overrideConfiguration(
ClientOverrideConfiguration.builder()
.addExecutionInterceptor(interceptor)
.build()))
.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]);
AwsCrypto.standard().encryptData(mkp, new byte[0]);
verify(interceptor, atLeastOnce()).modifyRequest(any(), any());
ArgumentCaptor<Context.BeforeTransmission> captor =
ArgumentCaptor.forClass(Context.BeforeTransmission.class);
verify(interceptor, atLeastOnce()).beforeTransmission(captor.capture(), any());
String ua = captor.getValue().httpRequest().headers().get("User-Agent").get(0);
assertTrue(ua.contains("NEW_API/0.0.1"));
assertTrue(ua.contains(VersionInfo.loadUserAgent()));
}
@Test
public void whenDefaultRegionSet_itIsUsedForBareKeyIds() throws Exception {
// TODO: Need to set up a role to assume as bare key IDs are relative to the caller account
}
}
| 5,385 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/ProxyKmsClient.java | package com.amazonaws.encryptionsdk.kmssdkv2;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.DecryptRequest;
import software.amazon.awssdk.services.kms.model.DecryptResponse;
import software.amazon.awssdk.services.kms.model.DependencyTimeoutException;
import software.amazon.awssdk.services.kms.model.DisabledException;
import software.amazon.awssdk.services.kms.model.EncryptRequest;
import software.amazon.awssdk.services.kms.model.EncryptResponse;
import software.amazon.awssdk.services.kms.model.GenerateDataKeyRequest;
import software.amazon.awssdk.services.kms.model.GenerateDataKeyResponse;
import software.amazon.awssdk.services.kms.model.IncorrectKeyException;
import software.amazon.awssdk.services.kms.model.InvalidCiphertextException;
import software.amazon.awssdk.services.kms.model.InvalidGrantTokenException;
import software.amazon.awssdk.services.kms.model.InvalidKeyUsageException;
import software.amazon.awssdk.services.kms.model.KeyUnavailableException;
import software.amazon.awssdk.services.kms.model.KmsException;
import software.amazon.awssdk.services.kms.model.KmsInternalException;
import software.amazon.awssdk.services.kms.model.KmsInvalidStateException;
import software.amazon.awssdk.services.kms.model.NotFoundException;
/** This wraps KmsClient since the default implementation is final. */
class ProxyKmsClient implements KmsClient {
private final KmsClient proxiedClient_;
ProxyKmsClient(KmsClient kmsClient) {
proxiedClient_ = kmsClient;
}
@Override
public String serviceName() {
return proxiedClient_.serviceName();
}
@Override
public void close() {
proxiedClient_.close();
}
@Override
public DecryptResponse decrypt(DecryptRequest decryptRequest)
throws NotFoundException, DisabledException, InvalidCiphertextException,
KeyUnavailableException, IncorrectKeyException, InvalidKeyUsageException,
DependencyTimeoutException, InvalidGrantTokenException, KmsInternalException,
KmsInvalidStateException, AwsServiceException, SdkClientException, KmsException {
return proxiedClient_.decrypt(decryptRequest);
}
@Override
public EncryptResponse encrypt(EncryptRequest encryptRequest)
throws NotFoundException, DisabledException, KeyUnavailableException,
DependencyTimeoutException, InvalidKeyUsageException, InvalidGrantTokenException,
KmsInternalException, KmsInvalidStateException, AwsServiceException, SdkClientException,
KmsException {
return proxiedClient_.encrypt(encryptRequest);
}
@Override
public GenerateDataKeyResponse generateDataKey(GenerateDataKeyRequest generateDataKeyRequest)
throws NotFoundException, DisabledException, KeyUnavailableException,
DependencyTimeoutException, InvalidKeyUsageException, InvalidGrantTokenException,
KmsInternalException, KmsInvalidStateException, AwsServiceException, SdkClientException,
KmsException {
return proxiedClient_.generateDataKey(generateDataKeyRequest);
}
}
| 5,386 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/ProxyCredentialsProvider.java | package com.amazonaws.encryptionsdk.kmssdkv2;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
class ProxyCredentialsProvider implements AwsCredentialsProvider {
private final AwsCredentialsProvider proxiedProvider_;
ProxyCredentialsProvider(AwsCredentialsProvider credentialsProvider) {
proxiedProvider_ = credentialsProvider;
}
@Override
public AwsCredentials resolveCredentials() {
return proxiedProvider_.resolveCredentials();
}
}
| 5,387 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/AwsKmsMrkAwareMasterKeyProviderTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kmssdkv2;
import static com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo.parseInfoFromKeyArn;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import com.amazonaws.encryptionsdk.*;
import com.amazonaws.encryptionsdk.exception.AwsCryptoException;
import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException;
import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException;
import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException;
import com.amazonaws.encryptionsdk.kms.DiscoveryFilter;
import com.amazonaws.encryptionsdk.model.KeyBlob;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.jupiter.api.DisplayName;
import org.junit.runner.RunWith;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.KmsClientBuilder;
import software.amazon.awssdk.services.kms.model.DecryptRequest;
import software.amazon.awssdk.services.kms.model.DecryptResponse;
@RunWith(Enclosed.class)
public class AwsKmsMrkAwareMasterKeyProviderTest {
public static class getResourceForResourceTypeKey {
@Test
@DisplayName("Postcondition: Return the key id.")
public void basic_use() {
assertEquals(
"mrk-edb7fe6942894d32ac46dbb1c922d574",
AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"));
}
@Test
@DisplayName("Check for early return (Postcondition): Non-ARNs may be raw resources.")
public void not_an_arn() {
assertEquals(
"mrk-edb7fe6942894d32ac46dbb1c922d574",
AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey(
"mrk-edb7fe6942894d32ac46dbb1c922d574"));
final String malformed = "aws:kms:us-west-2::key/garbage";
assertEquals(
malformed, AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey(malformed));
}
@Test
@DisplayName(
"Check for early return (Postcondition): Return the identifier for non-key resource types.")
public void not_a_key() {
final String alias = "arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt";
assertEquals(alias, AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey(alias));
}
}
public static class assertMrksAreUnique {
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5
// = type=test
// # The caller MUST provide:
public void basic_use() {
AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique(
Arrays.asList(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"));
}
@Test
public void no_duplicates() {
// = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5
// = type=test
// # If there are zero duplicate resource ids between the multi-region
// # keys, this function MUST exit successfully
AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique(
Arrays.asList(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5
// = type=test
// # If the list does not contain any multi-Region keys (aws-kms-key-
// # arn.md#identifying-an-aws-kms-multi-region-key) this function MUST
// # exit successfully.
public void no_mrks_at_all() {
AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique(
Arrays.asList(
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f",
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"));
}
@Test
@DisplayName("Postcondition: Filter out duplicate resources that are not multi-region keys.")
public void non_mrk_duplicates_ok() {
AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique(
Arrays.asList(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f",
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f",
"arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt",
"arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt"));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5
// = type=test
// # If any duplicate multi-region resource ids exist, this function MUST
// # yield an error that includes all identifiers with duplicate resource
// # ids not only the first duplicate found.
public void no_duplicate_mrks() {
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique(
Arrays.asList(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
"arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574")));
}
}
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # On initialization the caller MUST provide:
public static class AwsKmsMrkAwareMasterKeyProviderBuilderTests {
@Test
public void basic_use() {
final AwsKmsMrkAwareMasterKeyProvider strict =
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildStrict(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574");
final AwsKmsMrkAwareMasterKeyProvider discovery =
AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery();
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.5
// = type=test
// # MUST implement the Master Key Provider Interface (../master-key-
// # provider-interface.md#interface)
assertTrue(MasterKeyProvider.class.isInstance(strict));
assertTrue(MasterKeyProvider.class.isInstance(discovery));
// These are not testable because of how the builder is structured.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # A discovery filter MUST NOT be configured in strict mode.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # A default MRK Region MUST NOT be configured in strict mode.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # In
// # discovery mode if a default MRK Region is not configured the AWS SDK
// # Default Region MUST be used.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # The key id list MUST be empty in discovery mode.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # The regional client
// # supplier MUST be defined in discovery mode.
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # The key id list MUST NOT be empty or null in strict mode.
public void no_noop() {
assertThrows(
IllegalArgumentException.class,
() -> AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict());
assertThrows(
IllegalArgumentException.class,
() -> AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(new ArrayList<String>()));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # The key id
// # list MUST NOT contain any null or empty string values.
public void no_null_identifiers() {
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildStrict(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
""));
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildStrict(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
null));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # All AWS KMS
// # key identifiers are be passed to Assert AWS KMS MRK are unique (aws-
// # kms-mrk-are-unique.md#Implementation) and the function MUST return
// # success.
public void no_duplicate_mrks() {
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildStrict(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
"arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"));
}
@Test
@DisplayName("Precondition: A region is required to contact AWS KMS.")
public void always_need_a_region() {
assertThrows(
AwsCryptoException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
.defaultRegion(null)
.buildStrict("mrk-edb7fe6942894d32ac46dbb1c922d574"));
AwsKmsMrkAwareMasterKeyProvider.builder()
.defaultRegion(Region.US_EAST_1)
.buildStrict("mrk-edb7fe6942894d32ac46dbb1c922d574");
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6
// = type=test
// # If an AWS SDK Default Region can not be
// # obtained initialization MUST fail.
public void discovery_region_can_not_be_null() {
assertThrows(
IllegalArgumentException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
// need to force the default region to `null`
// otherwise it may pick one up from the environment.
.defaultRegion(null)
.discoveryMrkRegion(null)
.buildDiscovery());
}
@Test
@DisplayName("Precondition: Discovery filter is only valid in discovery mode.")
public void strict_cannot_have_discovery_filter() {
assertThrows(
IllegalArgumentException.class,
() -> {
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildStrict(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574");
Field field = mkp.getClass().getDeclaredField("discoveryFilter_");
field.setAccessible(true);
DiscoveryFilter filter = new DiscoveryFilter("partition", "accountId1");
field.set(mkp, filter);
field.setAccessible(false);
mkp.withGrantTokens("token1", "token2");
});
}
@Test
@DisplayName("Precondition: Discovery mode can not have any keys to filter.")
public void discovery_cannot_have_any_keys() {
assertThrows(
IllegalArgumentException.class,
() -> {
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery();
Field field = mkp.getClass().getDeclaredField("keyIds_");
field.setAccessible(true);
List<String> keyIds = Arrays.asList("keyId1", "keyId2");
field.set(mkp, keyIds);
field.setAccessible(false);
mkp.withGrantTokens("token1", "token2");
});
}
@Test
public void get_grant_tokens() {
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery();
mkp = mkp.withGrantTokens("token1", "token2");
assert (mkp.getGrantTokens()).contains("token1");
assert (mkp.getGrantTokens()).contains("token2");
}
@Test
public void basic_credentials_and_builder() {
AwsCredentialsProvider credsProvider =
StaticCredentialsProvider.create(AwsBasicCredentials.create("asdf", "qwer"));
AwsKmsMrkAwareMasterKeyProvider.builder()
.builderSupplier(() -> KmsClient.builder().credentialsProvider(credsProvider))
.buildDiscovery();
}
}
public static class extractRegion {
@Test
public void basic_use() {
final Region test =
AwsKmsMrkAwareMasterKeyProvider.extractRegion(
Region.US_EAST_1,
Region.US_EAST_2,
Optional.of(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"),
parseInfoFromKeyArn(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"),
false);
assertEquals(Region.US_WEST_2, test);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # If the requested AWS KMS key identifier is not a well formed ARN the
// # AWS Region MUST be the configured default region this SHOULD be
// # obtained from the AWS SDK.
public void not_an_arn() {
final Region test =
AwsKmsMrkAwareMasterKeyProvider.extractRegion(
Region.US_EAST_1,
Region.US_EAST_2,
Optional.empty(),
parseInfoFromKeyArn("mrk-edb7fe6942894d32ac46dbb1c922d574"),
false);
assertEquals(Region.US_EAST_1, test);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # Otherwise if the requested AWS KMS key
// # identifier is identified as a multi-Region key (aws-kms-key-
// # arn.md#identifying-an-aws-kms-multi-region-key), then AWS Region MUST
// # be the region from the AWS KMS key ARN stored in the provider info
// # from the encrypted data key.
public void not_an_mrk() {
final Region test =
AwsKmsMrkAwareMasterKeyProvider.extractRegion(
Region.US_EAST_1,
Region.US_EAST_2,
Optional.of(
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"),
parseInfoFromKeyArn(
"arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"),
false);
assertEquals(Region.US_WEST_2, test);
final Region test2 =
AwsKmsMrkAwareMasterKeyProvider.extractRegion(
Region.US_EAST_1,
Region.US_EAST_2,
Optional.of("arn:aws:kms:us-west-2:658956600833:alias/mrk-nasty"),
parseInfoFromKeyArn("arn:aws:kms:us-west-2:658956600833:alias/mrk-nasty"),
false);
assertEquals(Region.US_WEST_2, test2);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # Otherwise if the mode is discovery then
// # the AWS Region MUST be the discovery MRK region.
public void mrk_in_discovery() {
final Region test =
AwsKmsMrkAwareMasterKeyProvider.extractRegion(
Region.US_EAST_1,
Region.US_EAST_2,
Optional.empty(),
parseInfoFromKeyArn(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"),
true);
assertEquals(Region.US_EAST_2, test);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # Finally if the
// # provider info is identified as a multi-Region key (aws-kms-key-
// # arn.md#identifying-an-aws-kms-multi-region-key) the AWS Region MUST
// # be the region from the AWS KMS key in the configured key ids matched
// # to the requested AWS KMS key by using AWS KMS MRK Match for Decrypt
// # (aws-kms-mrk-match-for-decrypt.md#implementation).
public void fuzzy_match_mrk() {
final Region test =
AwsKmsMrkAwareMasterKeyProvider.extractRegion(
Region.US_EAST_1,
Region.US_EAST_2,
Optional.of(
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"),
parseInfoFromKeyArn(
"arn:aws:kms:us-west-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"),
false);
assertEquals(Region.US_WEST_2, test);
}
}
public static class getMasterKey {
@Test
public void basic_use() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final KmsClient client = spy(new MockKmsClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict(identifier);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # The input MUST be the same as the Master Key Provider Get Master Key
// # (../master-key-provider-interface.md#get-master-key) interface.
AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", identifier);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # The output MUST be the same as the Master Key Provider Get Master Key
// # (../master-key-provider-interface.md#get-master-key) interface.
assertTrue(AwsKmsMrkAwareMasterKey.class.isInstance((test)));
assertEquals(identifier, test.getKeyId());
verify(supplier, times(1)).getClient(Region.US_WEST_2);
}
@Test
public void basic_mrk_use() {
final String configuredIdentifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String requestedIdentifier =
"arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final KmsClient client = spy(new MockKmsClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict(configuredIdentifier);
AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", requestedIdentifier);
assertEquals(configuredIdentifier, test.getKeyId());
verify(supplier, times(1)).getClient(Region.US_WEST_2);
}
@Test
public void other_basic_uses() {
final KmsClient client = spy(new MockKmsClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
// A raw alias is a valid configuration for encryption
final String rawAliasIdentifier = "alias/my-alias";
AwsKmsMrkAwareMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict(rawAliasIdentifier)
.getMasterKey("aws-kms", rawAliasIdentifier);
// A raw alias is a valid configuration for encryption
final String rawKeyIdentifier = "mrk-edb7fe6942894d32ac46dbb1c922d574";
AwsKmsMrkAwareMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict(rawKeyIdentifier)
.getMasterKey("aws-kms", rawKeyIdentifier);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # The function MUST only provide master keys if the input provider id
// # equals "aws-kms".
public void only_this_provider() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final KmsClient client = spy(new MockKmsClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict(identifier);
assertThrows(
UnsupportedProviderException.class, () -> mkp.getMasterKey("not-aws-kms", identifier));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # In strict mode, the requested AWS KMS key ARN MUST
// # match a member of the configured key ids by using AWS KMS MRK Match
// # for Decrypt (aws-kms-mrk-match-for-decrypt.md#implementation)
// # otherwise this function MUST error.
public void no_key_id_match() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final KmsClient client = spy(new MockKmsClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
final AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict(identifier);
assertThrows(
NoSuchMasterKeyException.class,
() -> mkp.getMasterKey("aws-kms", "does-not-match-configured"));
}
@Test
@DisplayName("Precondition: Discovery mode requires requestedKeyArn be an ARN.")
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # In discovery mode, the requested
// # AWS KMS key identifier MUST be a well formed AWS KMS ARN.
public void discovery_request_must_be_arn() {
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery();
assertThrows(
NoSuchMasterKeyException.class,
() -> mkp.getMasterKey("aws-kms", "mrk-edb7fe6942894d32ac46dbb1c922d574"));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # In
// # discovery mode if a discovery filter is configured the requested AWS
// # KMS key ARN's "partition" MUST match the discovery filter's
// # "partition" and the AWS KMS key ARN's "account" MUST exist in the
// # discovery filter's account id set.
public void discovery_filter_must_match() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final KmsClient client = spy(new MockKmsClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
assertThrows(
NoSuchMasterKeyException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildDiscovery(new DiscoveryFilter("aws", Arrays.asList("not-111122223333")))
.getMasterKey("aws-kms", identifier));
assertThrows(
NoSuchMasterKeyException.class,
() ->
AwsKmsMrkAwareMasterKeyProvider.builder()
.buildDiscovery(new DiscoveryFilter("not-aws", Arrays.asList("111122223333")))
.getMasterKey("aws-kms", identifier));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # In discovery mode a AWS KMS MRK Aware Master Key (aws-kms-mrk-aware-
// # master-key.md) MUST be returned configured with
public void discovery_magic_to_make_the_region_match() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final KmsClient client = spy(new MockKmsClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.discoveryMrkRegion(Region.of("my-region"))
.buildDiscovery();
AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", identifier);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # An AWS KMS client
// # MUST be obtained by calling the regional client supplier with this
// # AWS Region.
assertEquals(
"arn:aws:kms:my-region:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574",
test.getKeyId());
verify(supplier, times(1)).getClient(Region.of("my-region"));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7
// = type=test
// # In strict mode a AWS KMS MRK Aware Master Key (aws-kms-mrk-aware-
// # master-key.md) MUST be returned configured with
public void strict_mrk_region_match() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String configIdentifier =
"arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final KmsClient client = spy(new MockKmsClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict(configIdentifier);
AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", identifier);
assertEquals(configIdentifier, test.getKeyId());
verify(supplier, times(1)).getClient(Region.US_EAST_1);
}
}
public static class decryptDataKey {
@Test
public void basic_use() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final byte[] cipherText = new byte[10];
final EncryptedDataKey edk1 =
new KeyBlob("aws-kms", identifier.getBytes(StandardCharsets.UTF_8), cipherText);
final EncryptedDataKey edk2 =
new KeyBlob("aws-kms", identifier.getBytes(StandardCharsets.UTF_8), cipherText);
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
final KmsClient client = mock(KmsClient.class);
when(client.decrypt((DecryptRequest) any()))
.thenReturn(
DecryptResponse.builder()
.keyId(identifier)
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
.build());
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict(identifier)
.withGrantTokens(GRANT_TOKENS);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # The input MUST be the same as the Master Key Provider Decrypt Data
// # Key (../master-key-provider-interface.md#decrypt-data-key) interface.
final DataKey<AwsKmsMrkAwareMasterKey> test =
mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk1, edk2), ENCRYPTION_CONTEXT);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # For each encrypted data key in the filtered set, one at a time, the
// # master key provider MUST call Get Master Key (aws-kms-mrk-aware-
// # master-key-provider.md#get-master-key) with the encrypted data key's
// # provider info as the AWS KMS key ARN.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # It MUST call Decrypt Data Key
// # (aws-kms-mrk-aware-master-key.md#decrypt-data-key) on this master key
// # with the input algorithm, this single encrypted data key, and the
// # input encryption context.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # If the decrypt data key call is
// # successful, then this function MUST return this result and not
// # attempt to decrypt any more encrypted data keys.
verify(client, times((1)))
.decrypt(
DecryptRequest.builder()
.overrideConfiguration(
builder -> builder.addApiName(AwsKmsMrkAwareMasterKey.API_NAME))
.grantTokens(GRANT_TOKENS)
.encryptionContext(ENCRYPTION_CONTEXT)
.keyId(identifier)
.ciphertextBlob(SdkBytes.fromByteArray(cipherText))
.build());
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # The output MUST be the same as the Master Key Provider Decrypt Data
// # Key (../master-key-provider-interface.md#decrypt-data-key) interface.
assertTrue(DataKey.class.isInstance(test));
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # The set of encrypted data keys MUST first be filtered to match this
// # master key's configuration.
public void only_if_providers_match() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final EncryptedDataKey edk =
new KeyBlob(
"not-aws-kms", "not the identifier".getBytes(StandardCharsets.UTF_8), new byte[10]);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(identifier);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # To match the encrypted data key's
// # provider ID MUST exactly match the value "aws-kms".
final CannotUnwrapDataKeyException test =
assertThrows(
"Unable to decrypt any data keys",
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT));
assertEquals(0, test.getSuppressed().length);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # Additionally
// # each provider info MUST be a valid AWS KMS ARN (aws-kms-key-arn.md#a-
// # valid-aws-kms-arn) with a resource type of "key".
public void provider_info_must_be_arn() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final String aliasArn =
"arn:aws:kms:us-west-2:111122223333:alias/mrk-edb7fe6942894d32ac46dbb1c922d574";
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final EncryptedDataKey edk =
new KeyBlob("aws-kms", aliasArn.getBytes(StandardCharsets.UTF_8), new byte[10]);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(identifier);
final IllegalStateException test =
assertThrows(
"Invalid provider info in message.",
IllegalStateException.class,
() -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT));
assertEquals(0, test.getSuppressed().length);
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # If this attempt results in an error, then
// # these errors MUST be collected.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9
// = type=test
// # If all the input encrypted data keys have been processed then this
// # function MUST yield an error that includes all the collected errors.
public void exception_wrapped() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue");
final EncryptedDataKey edk =
new KeyBlob("aws-kms", identifier.getBytes(StandardCharsets.UTF_8), new byte[10]);
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
final KmsClient client = mock(KmsClient.class);
final String clientErrMsg = "asdf";
when(client.decrypt((DecryptRequest) any()))
.thenThrow(AwsServiceException.builder().message(clientErrMsg).build());
when(supplier.getClient(any())).thenReturn(client);
AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict(identifier);
CannotUnwrapDataKeyException test =
assertThrows(
"Unable to decrypt any data keys",
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT));
assertEquals(1, test.getSuppressed().length);
Throwable fromMasterKey = Arrays.stream(test.getSuppressed()).findFirst().get();
assertTrue(fromMasterKey instanceof CannotUnwrapDataKeyException);
assertEquals(1, fromMasterKey.getSuppressed().length);
Throwable fromClient = Arrays.stream(fromMasterKey.getSuppressed()).findFirst().get();
assertTrue(fromClient instanceof AwsServiceException);
assertTrue(fromClient.getMessage().startsWith(clientErrMsg));
}
}
public static class clientFactory {
@Test
public void basic_use() {
final ConcurrentHashMap<Region, KmsClient> cache = spy(new ConcurrentHashMap<>());
final Region region = Region.of("asdf");
final KmsClient test =
AwsKmsMrkAwareMasterKeyProvider.Builder.clientFactory(cache, null).getClient(region);
assertNotEquals(null, test);
verify(cache, times(1)).containsKey(region);
}
@Test
@DisplayName("Check for early return (Postcondition): If a client already exists, use that.")
public void use_clients_that_exist() {
final Region region = Region.of("asdf");
final ConcurrentHashMap<Region, KmsClient> cache = spy(new ConcurrentHashMap<>());
// Add something so we can verify that we get it
final KmsClient client = mock(KmsClient.class);
cache.put(region, client);
final KmsClient test =
AwsKmsMrkAwareMasterKeyProvider.Builder.clientFactory(cache, null).getClient(region);
assertEquals(client, test);
}
@Test
public void uses_builder_supplier() {
final ConcurrentHashMap<Region, KmsClient> cache = spy(new ConcurrentHashMap<>());
final Region region = Region.of("asdf");
KmsClientBuilder builder = mock(KmsClientBuilder.class);
KmsClient client = mock(KmsClient.class);
ClientOverrideConfiguration.Builder overrideBuilder =
mock(ClientOverrideConfiguration.Builder.class);
when(builder.region(any())).thenReturn(builder);
when(builder.build()).thenReturn(client);
doAnswer(
ans -> {
Consumer<ClientOverrideConfiguration.Builder> consumer = ans.getArgument(0);
consumer.accept(overrideBuilder);
return builder;
})
.when(builder)
.overrideConfiguration((Consumer<ClientOverrideConfiguration.Builder>) any());
final KmsClient test =
AwsKmsMrkAwareMasterKeyProvider.Builder.clientFactory(cache, () -> builder)
.getClient(region);
verify(builder, times(1)).build();
verify(overrideBuilder, times(1)).addExecutionInterceptor(any());
assertEquals(client, test);
}
}
public static class getMasterKeysForEncryption {
@Test
public void basic_use() {
final String identifier =
"arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574";
final KmsClient client = spy(new MockKmsClient());
final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(Region.US_WEST_2)).thenReturn(client);
final MasterKeyRequest request = MasterKeyRequest.newBuilder().build();
final AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder()
.defaultRegion(Region.US_WEST_2)
.customRegionalClientSupplier(supplier)
.buildStrict(identifier);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8
// = type=test
// # The input MUST be the same as the Master Key Provider Get Master Keys
// # For Encryption (../master-key-provider-interface.md#get-master-keys-
// # for-encryption) interface.
//
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8
// = type=test
// # The output MUST be the same as the Master Key Provider Get Master
// # Keys For Encryption (../master-key-provider-interface.md#get-master-
// # keys-for-encryption) interface.
final List<AwsKmsMrkAwareMasterKey> test = mkp.getMasterKeysForEncryption(request);
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8
// = type=test
// # If the configured mode is strict this function MUST return a
// # list of master keys obtained by calling Get Master Key (aws-kms-mrk-
// # aware-master-key-provider.md#get-master-key) for each AWS KMS key
// # identifier in the configured key ids
assertEquals(1, test.size());
assertEquals(identifier, test.get(0).getKeyId());
}
@Test
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8
// = type=test
// # If the configured mode is discovery the function MUST return an empty
// # list.
public void no_keys_is_empty_list() {
final AwsKmsMrkAwareMasterKeyProvider mkp =
AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery();
final List<AwsKmsMrkAwareMasterKey> test =
mkp.getMasterKeysForEncryption(MasterKeyRequest.newBuilder().build());
assertEquals(0, test.size());
}
}
}
| 5,388 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/KmsMasterKeyTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kmssdkv2;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.*;
import com.amazonaws.encryptionsdk.*;
import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException;
import com.amazonaws.encryptionsdk.internal.VersionInfo;
import com.amazonaws.encryptionsdk.model.KeyBlob;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Supplier;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.awscore.AwsRequest;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.*;
public class KmsMasterKeyTest {
private static final String AWS_KMS_PROVIDER_ID = "aws-kms";
private static final String OTHER_PROVIDER_ID = "not-aws-kms";
private static final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
private static final SecretKey DATA_KEY =
new SecretKeySpec(
generate(ALGORITHM_SUITE.getDataKeyLength()), ALGORITHM_SUITE.getDataKeyAlgo());
private static final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken");
private static final Map<String, String> ENCRYPTION_CONTEXT =
Collections.singletonMap("myKey", "myValue");
@Test
public void testEncryptAndDecrypt() {
KmsClient client = spy(new MockKmsClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKey otherMasterKey = mock(MasterKey.class);
when(otherMasterKey.getProviderId()).thenReturn(OTHER_PROVIDER_ID);
when(otherMasterKey.getKeyId()).thenReturn("someOtherId");
DataKey dataKey =
new DataKey(
DATA_KEY,
new byte[0],
OTHER_PROVIDER_ID.getBytes(StandardCharsets.UTF_8),
otherMasterKey);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().keyMetadata().arn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
kmsMasterKey.setGrantTokens(GRANT_TOKENS);
DataKey<KmsMasterKey> encryptDataKeyResponse =
kmsMasterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey);
ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class);
verify(client, times(1)).encrypt(er.capture());
EncryptRequest actualRequest = er.getValue();
assertEquals(keyId, actualRequest.keyId());
assertEquals(GRANT_TOKENS, actualRequest.grantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext());
assertArrayEquals(DATA_KEY.getEncoded(), actualRequest.plaintext().asByteArray());
assertApiName(actualRequest);
assertEquals(encryptDataKeyResponse.getMasterKey(), kmsMasterKey);
assertEquals(AWS_KMS_PROVIDER_ID, encryptDataKeyResponse.getProviderId());
assertArrayEquals(
keyId.getBytes(StandardCharsets.UTF_8), encryptDataKeyResponse.getProviderInformation());
assertNotNull(encryptDataKeyResponse.getEncryptedDataKey());
DataKey<KmsMasterKey> decryptDataKeyResponse =
kmsMasterKey.decryptDataKey(
ALGORITHM_SUITE, Collections.singletonList(encryptDataKeyResponse), ENCRYPTION_CONTEXT);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decrypt.capture());
DecryptRequest actualDecryptRequest = decrypt.getValue();
assertArrayEquals(
encryptDataKeyResponse.getProviderInformation(),
actualDecryptRequest.keyId().getBytes(StandardCharsets.UTF_8));
assertEquals(GRANT_TOKENS, actualDecryptRequest.grantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualDecryptRequest.encryptionContext());
assertArrayEquals(
encryptDataKeyResponse.getEncryptedDataKey(),
actualDecryptRequest.ciphertextBlob().asByteArray());
assertApiName(actualDecryptRequest);
assertEquals(DATA_KEY, decryptDataKeyResponse.getKey());
assertArrayEquals(
keyId.getBytes(StandardCharsets.UTF_8), decryptDataKeyResponse.getProviderInformation());
}
@Test
public void testGenerateAndDecrypt() {
KmsClient client = spy(new MockKmsClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().keyMetadata().arn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
kmsMasterKey.setGrantTokens(GRANT_TOKENS);
DataKey<KmsMasterKey> generateDataKeyResponse =
kmsMasterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT);
ArgumentCaptor<GenerateDataKeyRequest> gr =
ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
verify(client, times(1)).generateDataKey(gr.capture());
GenerateDataKeyRequest actualRequest = gr.getValue();
assertEquals(keyId, actualRequest.keyId());
assertEquals(GRANT_TOKENS, actualRequest.grantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext());
assertEquals(ALGORITHM_SUITE.getDataKeyLength(), actualRequest.numberOfBytes().longValue());
assertApiName(actualRequest);
assertNotNull(generateDataKeyResponse.getKey());
assertEquals(
ALGORITHM_SUITE.getDataKeyLength(), generateDataKeyResponse.getKey().getEncoded().length);
assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), generateDataKeyResponse.getKey().getAlgorithm());
assertNotNull(generateDataKeyResponse.getEncryptedDataKey());
DataKey<KmsMasterKey> decryptDataKeyResponse =
kmsMasterKey.decryptDataKey(
ALGORITHM_SUITE,
Collections.singletonList(generateDataKeyResponse),
ENCRYPTION_CONTEXT);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decrypt.capture());
DecryptRequest actualDecryptRequest = decrypt.getValue();
assertArrayEquals(
generateDataKeyResponse.getProviderInformation(),
actualDecryptRequest.keyId().getBytes(StandardCharsets.UTF_8));
assertEquals(GRANT_TOKENS, actualDecryptRequest.grantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualDecryptRequest.encryptionContext());
assertArrayEquals(
generateDataKeyResponse.getEncryptedDataKey(),
actualDecryptRequest.ciphertextBlob().asByteArray());
assertApiName(actualDecryptRequest);
assertEquals(generateDataKeyResponse.getKey(), decryptDataKeyResponse.getKey());
assertArrayEquals(
keyId.getBytes(StandardCharsets.UTF_8), decryptDataKeyResponse.getProviderInformation());
}
@Test
public void testEncryptWithRawKeyId() {
KmsClient client = spy(new MockKmsClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKey otherMasterKey = mock(MasterKey.class);
when(otherMasterKey.getProviderId()).thenReturn(OTHER_PROVIDER_ID);
when(otherMasterKey.getKeyId()).thenReturn("someOtherId");
DataKey dataKey =
new DataKey(
DATA_KEY,
new byte[0],
OTHER_PROVIDER_ID.getBytes(StandardCharsets.UTF_8),
otherMasterKey);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().keyMetadata().arn();
String rawKeyId = keyId.split("/")[1];
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, rawKeyId, mkp);
kmsMasterKey.setGrantTokens(GRANT_TOKENS);
DataKey<KmsMasterKey> encryptDataKeyResponse =
kmsMasterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey);
ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class);
verify(client, times(1)).encrypt(er.capture());
EncryptRequest actualRequest = er.getValue();
assertEquals(rawKeyId, actualRequest.keyId());
assertEquals(GRANT_TOKENS, actualRequest.grantTokens());
assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext());
assertArrayEquals(DATA_KEY.getEncoded(), actualRequest.plaintext().asByteArray());
assertApiName(actualRequest);
assertEquals(AWS_KMS_PROVIDER_ID, encryptDataKeyResponse.getProviderId());
assertArrayEquals(
keyId.getBytes(StandardCharsets.UTF_8), encryptDataKeyResponse.getProviderInformation());
assertNotNull(encryptDataKeyResponse.getEncryptedDataKey());
}
@Test
public void testEncryptWrongKeyFormat() {
SecretKey key = mock(SecretKey.class);
when(key.getFormat()).thenReturn("BadFormat");
KmsClient client = spy(new MockKmsClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKey otherMasterKey = mock(MasterKey.class);
when(otherMasterKey.getProviderId()).thenReturn(OTHER_PROVIDER_ID);
when(otherMasterKey.getKeyId()).thenReturn("someOtherId");
DataKey dataKey =
new DataKey(
key, new byte[0], OTHER_PROVIDER_ID.getBytes(StandardCharsets.UTF_8), otherMasterKey);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().keyMetadata().arn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
assertThrows(
IllegalArgumentException.class,
() -> kmsMasterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey));
}
@Test
public void testGenerateBadKmsKeyLength() {
KmsClient client = spy(new MockKmsClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().keyMetadata().arn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
GenerateDataKeyResponse badResponse =
GenerateDataKeyResponse.builder()
.keyId(keyId)
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength() + 1]))
.build();
doReturn(badResponse).when(client).generateDataKey(isA(GenerateDataKeyRequest.class));
assertThrows(
IllegalStateException.class,
() -> kmsMasterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT));
}
@Test
public void testDecryptBadKmsKeyLength() {
KmsClient client = spy(new MockKmsClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().keyMetadata().arn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
DecryptResponse badResponse =
DecryptResponse.builder()
.keyId(keyId)
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength() + 1]))
.build();
doReturn(badResponse).when(client).decrypt(isA(DecryptRequest.class));
EncryptedDataKey edk =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
keyId.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
assertThrows(
IllegalStateException.class,
() ->
kmsMasterKey.decryptDataKey(
ALGORITHM_SUITE, Collections.singletonList(edk), ENCRYPTION_CONTEXT));
}
@Test
public void testDecryptMissingKmsKeyId() {
KmsClient client = spy(new MockKmsClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().keyMetadata().arn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
DecryptResponse badResponse =
DecryptResponse.builder()
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
.build();
doReturn(badResponse).when(client).decrypt(isA(DecryptRequest.class));
EncryptedDataKey edk =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
keyId.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
assertThrows(
IllegalStateException.class,
"Received an empty keyId from KMS",
() ->
kmsMasterKey.decryptDataKey(
ALGORITHM_SUITE, Collections.singletonList(edk), ENCRYPTION_CONTEXT));
}
@Test
public void testDecryptMismatchedKmsKeyId() {
KmsClient client = spy(new MockKmsClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().keyMetadata().arn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
DecryptResponse badResponse =
DecryptResponse.builder()
.keyId("mismatchedID")
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
.build();
doReturn(badResponse).when(client).decrypt(isA(DecryptRequest.class));
EncryptedDataKey edk =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
keyId.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
assertThrows(
CannotUnwrapDataKeyException.class,
() ->
kmsMasterKey.decryptDataKey(
ALGORITHM_SUITE, Collections.singletonList(edk), ENCRYPTION_CONTEXT));
}
@Test
public void testDecryptSkipsMismatchedIdEDK() {
KmsClient client = spy(new MockKmsClient());
Supplier supplier = mock(Supplier.class);
when(supplier.get()).thenReturn(client);
MasterKeyProvider mkp = mock(MasterKeyProvider.class);
when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID);
String keyId = client.createKey().keyMetadata().arn();
KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp);
// Mock expected KMS response to verify success if second EDK is ok,
// and the mismatched EDK is skipped vs failing outright
DecryptResponse kmsResponse =
DecryptResponse.builder()
.keyId(keyId)
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
.build();
doReturn(kmsResponse).when(client).decrypt(isA(DecryptRequest.class));
EncryptedDataKey edk =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
keyId.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
EncryptedDataKey mismatchedEDK =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
"mismatchedID".getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
DataKey<KmsMasterKey> decryptDataKeyResponse =
kmsMasterKey.decryptDataKey(
ALGORITHM_SUITE, Arrays.asList(mismatchedEDK, edk), ENCRYPTION_CONTEXT);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decrypt.capture());
DecryptRequest actualDecryptRequest = decrypt.getValue();
assertArrayEquals(
edk.getProviderInformation(),
actualDecryptRequest.keyId().getBytes(StandardCharsets.UTF_8));
}
private void assertApiName(AwsRequest request) {
Optional<AwsRequestOverrideConfiguration> overrideConfig = request.overrideConfiguration();
assertTrue(overrideConfig.isPresent());
assertTrue(
overrideConfig.get().apiNames().stream()
.anyMatch(
api ->
api.name().equals(VersionInfo.apiName())
&& api.version().equals(VersionInfo.versionNumber())));
}
}
| 5,389 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/KmsMasterKeyProviderTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.kmssdkv2;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import com.amazonaws.encryptionsdk.CryptoAlgorithm;
import com.amazonaws.encryptionsdk.DataKey;
import com.amazonaws.encryptionsdk.EncryptedDataKey;
import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException;
import com.amazonaws.encryptionsdk.internal.VersionInfo;
import com.amazonaws.encryptionsdk.kms.DiscoveryFilter;
import com.amazonaws.encryptionsdk.model.KeyBlob;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.awscore.AwsRequest;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.kms.model.DecryptRequest;
import software.amazon.awssdk.services.kms.model.DecryptResponse;
@RunWith(Enclosed.class)
public class KmsMasterKeyProviderTest {
private static final String AWS_PARTITION = "aws";
private static final String AWS_KMS_PROVIDER_ID = "aws-kms";
private static final String OTHER_PARTITION = "not-aws";
private static final String OTHER_PROVIDER_ID = "not-aws-kms";
private static final String ACCOUNT_ID = "999999999999";
private static final String OTHER_ACCOUNT_ID = "000000000000";
private static final String KEY_ID_1 =
"arn:"
+ AWS_PARTITION
+ ":kms:us-east-1:"
+ ACCOUNT_ID
+ ":key/01234567-89ab-cdef-fedc-ba9876543210";
private static final String KEY_ID_2 =
"arn:"
+ AWS_PARTITION
+ ":kms:us-east-1:"
+ ACCOUNT_ID
+ ":key/01234567-89ab-cdef-fedc-ba9876543211";
private static final String KEY_ID_3 =
"arn:"
+ AWS_PARTITION
+ ":kms:us-east-1:"
+ ACCOUNT_ID
+ ":key/01234567-89ab-cdef-fedc-ba9876543212";
private static final String KEY_ID_4 =
"arn:"
+ AWS_PARTITION
+ ":kms:us-east-1:"
+ OTHER_ACCOUNT_ID
+ ":key/01234567-89ab-cdef-fedc-ba9876543210";
private static final String KEY_ID_5 =
"arn:"
+ OTHER_PARTITION
+ ":kms:us-east-1:"
+ ACCOUNT_ID
+ ":key/01234567-89ab-cdef-fedc-ba9876543210";
private static final CryptoAlgorithm ALGORITHM_SUITE =
CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
private static final Map<String, String> ENCRYPTION_CONTEXT =
Collections.singletonMap("myKey", "myValue");
private static final EncryptedDataKey EDK_ID_1 =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
KEY_ID_1.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_ID_1_OTHER_CIPHERTEXT =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
KEY_ID_1.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_ID_2 =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
KEY_ID_2.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_ID_3 =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
KEY_ID_3.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_NON_ARN =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
"someAlias".getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_EMPTY_PROVIDER =
new KeyBlob(
"",
"someId".getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_OTHER_PROVIDER =
new KeyBlob(
OTHER_PROVIDER_ID,
"someId".getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_OTHER_ACCOUNT =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
KEY_ID_4.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
private static final EncryptedDataKey EDK_OTHER_PARTITION =
new KeyBlob(
AWS_KMS_PROVIDER_ID,
KEY_ID_5.getBytes(StandardCharsets.UTF_8),
generate(ALGORITHM_SUITE.getDataKeyLength()));
@RunWith(Parameterized.class)
public static class ParameterizedDecryptTest {
MKPTestConfiguration mkpConfig;
List<EncryptedDataKey> inputEDKs;
List<EncryptedDataKey> decryptableEDKs;
private static class MKPTestConfiguration {
// instance vars are public for easier access during testing
public boolean isDiscovery;
public DiscoveryFilter discoveryFilter;
public List<String> keyIds;
public MKPTestConfiguration(
boolean isDiscovery, DiscoveryFilter discoveryFilter, List<String> keyIds) {
this.isDiscovery = isDiscovery;
this.discoveryFilter = discoveryFilter;
this.keyIds = keyIds;
}
}
public ParameterizedDecryptTest(
MKPTestConfiguration mkpConfig,
List<EncryptedDataKey> inputEDKs,
List<EncryptedDataKey> decryptableEDKs) {
this.mkpConfig = mkpConfig;
this.inputEDKs = inputEDKs;
this.decryptableEDKs = decryptableEDKs;
}
@Parameterized.Parameters(name = "{index}: mkpConfig={0}, inputEDKs={1}, decryptableEDKs={2}")
public static Collection<Object[]> testCases() {
// Create MKP configuration options to test against
MKPTestConfiguration strict_oneCMK =
new MKPTestConfiguration(false, null, Arrays.asList(KEY_ID_1));
MKPTestConfiguration strict_twoCMKs =
new MKPTestConfiguration(false, null, Arrays.asList(KEY_ID_1, KEY_ID_2));
MKPTestConfiguration explicitDiscovery = new MKPTestConfiguration(true, null, null);
MKPTestConfiguration explicitDiscovery_filter =
new MKPTestConfiguration(
true, new DiscoveryFilter(AWS_PARTITION, Arrays.asList(ACCOUNT_ID)), null);
// Define all test cases
Collection<Object[]> testCases =
Arrays.asList(
new Object[][] {
// Test cases where no EDKs are expected to be decrypted
{strict_oneCMK, Collections.emptyList(), Collections.emptyList()},
{strict_oneCMK, Arrays.asList(EDK_ID_2), Collections.emptyList()},
{strict_oneCMK, Arrays.asList(EDK_ID_2, EDK_ID_3), Collections.emptyList()},
{strict_twoCMKs, Collections.emptyList(), Collections.emptyList()},
{strict_twoCMKs, Arrays.asList(EDK_ID_3), Collections.emptyList()},
{
strict_twoCMKs,
Arrays.asList(EDK_ID_3, EDK_OTHER_PROVIDER),
Collections.emptyList()
},
{explicitDiscovery, Collections.emptyList(), Collections.emptyList()},
{explicitDiscovery, Arrays.asList(EDK_OTHER_PROVIDER), Collections.emptyList()},
{explicitDiscovery, Arrays.asList(EDK_EMPTY_PROVIDER), Collections.emptyList()},
{
explicitDiscovery,
Arrays.asList(EDK_OTHER_PROVIDER, EDK_EMPTY_PROVIDER),
Collections.emptyList()
},
{explicitDiscovery_filter, Collections.emptyList(), Collections.emptyList()},
{
explicitDiscovery_filter,
Arrays.asList(EDK_OTHER_PROVIDER),
Collections.emptyList()
},
{
explicitDiscovery_filter,
Arrays.asList(EDK_EMPTY_PROVIDER),
Collections.emptyList()
},
{explicitDiscovery_filter, Arrays.asList(EDK_NON_ARN), Collections.emptyList()},
{
explicitDiscovery_filter,
Arrays.asList(EDK_OTHER_PARTITION),
Collections.emptyList()
},
{
explicitDiscovery_filter,
Arrays.asList(EDK_OTHER_ACCOUNT),
Collections.emptyList()
},
{
explicitDiscovery_filter,
Arrays.asList(EDK_OTHER_PROVIDER, EDK_EMPTY_PROVIDER),
Collections.emptyList()
},
// Test cases where one EDK is expected to be decryptable
{strict_oneCMK, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)},
{strict_oneCMK, Arrays.asList(EDK_ID_2, EDK_ID_1), Arrays.asList(EDK_ID_1)},
{strict_oneCMK, Arrays.asList(EDK_ID_1, EDK_ID_2), Arrays.asList(EDK_ID_1)},
{strict_twoCMKs, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)},
{strict_twoCMKs, Arrays.asList(EDK_ID_2), Arrays.asList(EDK_ID_2)},
{strict_twoCMKs, Arrays.asList(EDK_ID_3, EDK_ID_1), Arrays.asList(EDK_ID_1)},
{strict_twoCMKs, Arrays.asList(EDK_ID_1, EDK_ID_3), Arrays.asList(EDK_ID_1)},
{explicitDiscovery, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)},
{
explicitDiscovery,
Arrays.asList(EDK_OTHER_PROVIDER, EDK_ID_1),
Arrays.asList(EDK_ID_1)
},
{
explicitDiscovery,
Arrays.asList(EDK_ID_1, EDK_OTHER_PROVIDER),
Arrays.asList(EDK_ID_1)
},
{explicitDiscovery_filter, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)},
{
explicitDiscovery_filter,
Arrays.asList(EDK_OTHER_ACCOUNT, EDK_ID_1),
Arrays.asList(EDK_ID_1)
},
{
explicitDiscovery_filter,
Arrays.asList(EDK_ID_1, EDK_OTHER_ACCOUNT),
Arrays.asList(EDK_ID_1)
},
// Test cases where multiple EDKs are expected to be decryptable
{
strict_oneCMK,
Arrays.asList(EDK_ID_1, EDK_ID_1_OTHER_CIPHERTEXT),
Arrays.asList(EDK_ID_1, EDK_ID_1_OTHER_CIPHERTEXT)
},
{
strict_twoCMKs,
Arrays.asList(EDK_ID_1, EDK_ID_2),
Arrays.asList(EDK_ID_1, EDK_ID_2)
},
{
explicitDiscovery,
Arrays.asList(EDK_ID_1, EDK_ID_2),
Arrays.asList(EDK_ID_1, EDK_ID_2)
},
{
explicitDiscovery_filter,
Arrays.asList(EDK_ID_1, EDK_ID_2),
Arrays.asList(EDK_ID_1, EDK_ID_2)
},
});
return testCases;
}
@SuppressWarnings("deprecation")
private KmsMasterKeyProvider constructMKPForTest(
MKPTestConfiguration mkpConfig, RegionalClientSupplier supplier) {
KmsMasterKeyProvider.Builder builder =
KmsMasterKeyProvider.builder().customRegionalClientSupplier(supplier);
KmsMasterKeyProvider mkp;
if (mkpConfig.isDiscovery && mkpConfig.discoveryFilter == null) {
mkp = builder.buildDiscovery();
} else if (mkpConfig.isDiscovery) {
mkp = builder.buildDiscovery(mkpConfig.discoveryFilter);
} else {
mkp = builder.buildStrict(mkpConfig.keyIds);
}
return mkp;
}
@Test
public void testDecrypt() throws Exception {
MockKmsClient client = spy(new MockKmsClient());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
// create MKP to test
KmsMasterKeyProvider mkp = constructMKPForTest(mkpConfig, supplier);
// if we expect none of them to decrypt, just test that we get the correct
// failure and KMS was not called
if (decryptableEDKs.size() <= 0) {
assertThrows(
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT));
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verifyNoInteractions(client);
return;
}
// Test that the mkp calls KMS for the first expected EDK
EncryptedDataKey expectedEDK = decryptableEDKs.get(0);
// mock KMS to return the KeyId for the expected EDK,
// we verify that we call KMS with this KeyId, so this is ok
DecryptResponse decryptResponse =
DecryptResponse.builder()
.keyId(new String(expectedEDK.getProviderInformation(), StandardCharsets.UTF_8))
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
.build();
doReturn(decryptResponse).when(client).decrypt(isA(DecryptRequest.class));
DataKey<KmsMasterKey> dataKeyResult =
mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(1)).decrypt(decrypt.capture());
verifyNoMoreInteractions(client);
DecryptRequest actualRequest = decrypt.getValue();
assertArrayEquals(
expectedEDK.getProviderInformation(),
actualRequest.keyId().getBytes(StandardCharsets.UTF_8));
assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext());
assertArrayEquals(
expectedEDK.getEncryptedDataKey(), actualRequest.ciphertextBlob().asByteArray());
assertApiName(actualRequest);
assertArrayEquals(
expectedEDK.getProviderInformation(), dataKeyResult.getProviderInformation());
assertArrayEquals(expectedEDK.getEncryptedDataKey(), dataKeyResult.getEncryptedDataKey());
}
@Test
public void testDecryptKMSFailsOnce() throws Exception {
MockKmsClient client = spy(new MockKmsClient());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
// create MKP to test
KmsMasterKeyProvider mkp = constructMKPForTest(mkpConfig, supplier);
// if we expect one or less KMS call, just test that we get the correct
// failure and KMS was called the expected number of times
if (decryptableEDKs.size() <= 1) {
// Mock KMS to fail
doThrow(AwsServiceException.builder().message("fail").build())
.when(client)
.decrypt(isA(DecryptRequest.class));
assertThrows(
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT));
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(decryptableEDKs.size())).decrypt(decrypt.capture());
return;
}
EncryptedDataKey expectedFailedEDK = decryptableEDKs.get(0);
EncryptedDataKey expectedSuccessfulEDK = decryptableEDKs.get(1);
// Mock KMS to fail the first call then succeed for the second call
DecryptResponse decryptResponse =
DecryptResponse.builder()
.keyId(
new String(
expectedSuccessfulEDK.getProviderInformation(), StandardCharsets.UTF_8))
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
.build();
doThrow(AwsServiceException.builder().message("fail").build())
.doReturn(decryptResponse)
.when(client)
.decrypt(isA(DecryptRequest.class));
DataKey<KmsMasterKey> dataKeyResult =
mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT);
ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
verify(client, times(2)).decrypt(decrypt.capture());
verifyNoMoreInteractions(client);
List<DecryptRequest> actualRequests = decrypt.getAllValues();
DecryptRequest failedRequest = actualRequests.get(0);
assertArrayEquals(
expectedFailedEDK.getProviderInformation(),
failedRequest.keyId().getBytes(StandardCharsets.UTF_8));
assertEquals(ENCRYPTION_CONTEXT, failedRequest.encryptionContext());
assertArrayEquals(
expectedFailedEDK.getEncryptedDataKey(), failedRequest.ciphertextBlob().asByteArray());
assertApiName(failedRequest);
DecryptRequest successfulRequest = actualRequests.get(1);
assertArrayEquals(
expectedSuccessfulEDK.getProviderInformation(),
successfulRequest.keyId().getBytes(StandardCharsets.UTF_8));
assertEquals(ENCRYPTION_CONTEXT, successfulRequest.encryptionContext());
assertArrayEquals(
expectedSuccessfulEDK.getEncryptedDataKey(),
successfulRequest.ciphertextBlob().asByteArray());
assertApiName(successfulRequest);
assertArrayEquals(
expectedSuccessfulEDK.getProviderInformation(), dataKeyResult.getProviderInformation());
assertArrayEquals(
expectedSuccessfulEDK.getEncryptedDataKey(), dataKeyResult.getEncryptedDataKey());
}
private void assertApiName(AwsRequest request) {
Optional<AwsRequestOverrideConfiguration> overrideConfig = request.overrideConfiguration();
assertTrue(overrideConfig.isPresent());
assertTrue(
overrideConfig.get().apiNames().stream()
.anyMatch(
api ->
api.name().equals(VersionInfo.apiName())
&& api.version().equals(VersionInfo.versionNumber())));
}
}
public static class NonParameterized {
@Test
public void testBuildStrictWithNoCMKs() throws Exception {
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
assertThrows(
IllegalArgumentException.class,
() ->
KmsMasterKeyProvider.builder().customRegionalClientSupplier(supplier).buildStrict());
assertThrows(
IllegalArgumentException.class,
() ->
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict(Collections.emptyList()));
assertThrows(
IllegalArgumentException.class,
() ->
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict((List<String>) null));
}
@Test
public void testBuildStrictWithNullCMK() throws Exception {
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
assertThrows(
IllegalArgumentException.class,
() ->
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict((String) null));
assertThrows(
IllegalArgumentException.class,
() ->
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildStrict(Arrays.asList((String) null)));
}
@Test
public void testBuildDiscoveryWithFilter() throws Exception {
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
KmsMasterKeyProvider mkp1 =
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildDiscovery(new DiscoveryFilter("aws", Arrays.asList("accountId")));
assertNotNull(mkp1);
}
@Test
public void testBuildDiscoveryWithNullFilter() throws Exception {
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
assertThrows(
IllegalArgumentException.class,
() ->
KmsMasterKeyProvider.builder()
.customRegionalClientSupplier(supplier)
.buildDiscovery(null));
}
@Test
public void testDecryptMismatchedKMSKeyIdResponse() throws Exception {
MockKmsClient client = spy(new MockKmsClient());
RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
when(supplier.getClient(any())).thenReturn(client);
DecryptResponse badResponse =
DecryptResponse.builder()
.keyId(KEY_ID_2)
.plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()]))
.build();
doReturn(badResponse).when(client).decrypt(isA(DecryptRequest.class));
KmsMasterKeyProvider mkp =
KmsMasterKeyProvider.builder().customRegionalClientSupplier(supplier).buildDiscovery();
assertThrows(
CannotUnwrapDataKeyException.class,
() -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(EDK_ID_1), ENCRYPTION_CONTEXT));
}
}
}
| 5,390 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/multi/MultipleMasterKeyTest.java | package com.amazonaws.encryptionsdk.multi;
import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.CryptoResult;
import com.amazonaws.encryptionsdk.MasterKey;
import com.amazonaws.encryptionsdk.MasterKeyProvider;
import com.amazonaws.encryptionsdk.internal.StaticMasterKey;
import com.amazonaws.encryptionsdk.jce.JceMasterKey;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
public class MultipleMasterKeyTest {
private static final String WRAPPING_ALG = "AES/GCM/NoPadding";
private static final byte[] PLAINTEXT = generate(1024);
@Test
public void testMultipleJceKeys() {
final SecretKeySpec k1 = new SecretKeySpec(generate(32), "AES");
final JceMasterKey mk1 = JceMasterKey.getInstance(k1, "jce", "1", WRAPPING_ALG);
final SecretKeySpec k2 = new SecretKeySpec(generate(32), "AES");
final JceMasterKey mk2 = JceMasterKey.getInstance(k2, "jce", "2", WRAPPING_ALG);
final MasterKeyProvider<JceMasterKey> mkp =
MultipleProviderFactory.buildMultiProvider(JceMasterKey.class, mk1, mk2);
AwsCrypto crypto = AwsCrypto.standard();
CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT);
assertEquals(2, ct.getMasterKeyIds().size());
CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only the first found key should be used
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk1, result.getMasterKeys().get(0));
assertMultiReturnsKeys(mkp, mk1, mk2);
}
@Test
public void testMultipleJceKeysSingleDecrypt() {
final SecretKeySpec k1 = new SecretKeySpec(generate(32), "AES");
final JceMasterKey mk1 = JceMasterKey.getInstance(k1, "jce", "1", WRAPPING_ALG);
final SecretKeySpec k2 = new SecretKeySpec(generate(32), "AES");
final JceMasterKey mk2 = JceMasterKey.getInstance(k2, "jce", "2", WRAPPING_ALG);
final MasterKeyProvider<JceMasterKey> mkp =
MultipleProviderFactory.buildMultiProvider(JceMasterKey.class, mk1, mk2);
AwsCrypto crypto = AwsCrypto.standard();
CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT);
assertEquals(2, ct.getMasterKeyIds().size());
CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mk1, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only the first found key should be used
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk1, result.getMasterKeys().get(0));
result = crypto.decryptData(mk2, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only the first found key should be used
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk2, result.getMasterKeys().get(0));
}
@Test
public void testMixedKeys() {
final SecretKeySpec k1 = new SecretKeySpec(generate(32), "AES");
final JceMasterKey mk1 = JceMasterKey.getInstance(k1, "jce", "1", WRAPPING_ALG);
StaticMasterKey mk2 = new StaticMasterKey("mock1");
final MasterKeyProvider<?> mkp = MultipleProviderFactory.buildMultiProvider(mk1, mk2);
AwsCrypto crypto = AwsCrypto.standard();
CryptoResult<byte[], ?> ct = crypto.encryptData(mkp, PLAINTEXT);
assertEquals(2, ct.getMasterKeyIds().size());
CryptoResult<byte[], ?> result = crypto.decryptData(mkp, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only the first found key should be used
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk1, result.getMasterKeys().get(0));
assertMultiReturnsKeys(mkp, mk1, mk2);
}
@Test
public void testMixedKeysSingleDecrypt() {
final SecretKeySpec k1 = new SecretKeySpec(generate(32), "AES");
final JceMasterKey mk1 = JceMasterKey.getInstance(k1, "jce", "1", WRAPPING_ALG);
StaticMasterKey mk2 = new StaticMasterKey("mock1");
final MasterKeyProvider<?> mkp = MultipleProviderFactory.buildMultiProvider(mk1, mk2);
AwsCrypto crypto = AwsCrypto.standard();
CryptoResult<byte[], ?> ct = crypto.encryptData(mkp, PLAINTEXT);
assertEquals(2, ct.getMasterKeyIds().size());
CryptoResult<byte[], ?> result = crypto.decryptData(mk1, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only the first found key should be used
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk1, result.getMasterKeys().get(0));
result = crypto.decryptData(mk2, ct.getResult());
assertArrayEquals(PLAINTEXT, result.getResult());
// Only the first found key should be used
assertEquals(1, result.getMasterKeys().size());
assertEquals(mk2, result.getMasterKeys().get(0));
}
private void assertMultiReturnsKeys(MasterKeyProvider<?> mkp, MasterKey<?>... mks) {
for (MasterKey<?> mk : mks) {
assertEquals(mk, mkp.getMasterKey(mk.getKeyId()));
assertEquals(mk, mkp.getMasterKey(mk.getProviderId(), mk.getKeyId()));
}
}
}
| 5,391 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/RandomBytesGenerator.java | /*
* Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except
* in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.amazonaws.encryptionsdk.internal;
import java.security.SecureRandom;
public class RandomBytesGenerator {
private static final SecureRandom RND = new SecureRandom();
/* Some Providers (such as the FIPS certified Bouncy Castle) enforce a
* maximum number of bytes that may be requested from SecureRandom. If
* the requested len is larger than this value, the Secure Random will
* be called multiple times to achieve the requested total length. */
private static final int MAX_BYTES = 1 << 15;
/**
* Generates a byte array of random data of the given length.
*
* @param len The length of the byte array.
* @return The byte array.
*/
public static byte[] generate(final int len) {
final byte[] result = new byte[len];
int bytesGenerated = 0;
while (bytesGenerated < len) {
final int requestSize = Math.min(MAX_BYTES, len - bytesGenerated);
final byte[] request = new byte[requestSize];
RND.nextBytes(request);
System.arraycopy(request, 0, result, bytesGenerated, requestSize);
bytesGenerated += requestSize;
}
return result;
}
}
| 5,392 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/StaticMasterKey.java | package com.amazonaws.encryptionsdk.internal;
import com.amazonaws.encryptionsdk.CryptoAlgorithm;
import com.amazonaws.encryptionsdk.DataKey;
import com.amazonaws.encryptionsdk.EncryptedDataKey;
import com.amazonaws.encryptionsdk.MasterKey;
import com.amazonaws.encryptionsdk.exception.AwsCryptoException;
import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Static implementation of the {@link MasterKey} interface that should only used for unit-tests.
*
* <p>Contains a statically defined asymmetric master key-pair that can be used to encrypt and
* decrypt (randomly generated) symmetric data key.
*
* <p>
*
* @author patye
*/
@NotThreadSafe
public class StaticMasterKey extends MasterKey<StaticMasterKey> {
private static final String PROVIDER_ID = "static_provider";
/** Generates random strings that can be used to create data keys. */
private static final SecureRandom SRAND = new SecureRandom();
/** Encryption algorithm for the master key-pair */
private static final String MASTER_KEY_ENCRYPTION_ALGORITHM = "RSA/ECB/PKCS1Padding";
/** Encryption algorithm for the KeyFactory */
private static final String MASTER_KEY_ALGORITHM = "RSA";
/** Encryption algorithm for the randomly generated data key */
private static final String DATA_KEY_ENCRYPTION_ALGORITHM = "AES";
/** The ID of the master key */
@Nonnull private String keyId_;
/**
* The {@link Cipher} object created with the public part of the master-key. It's used to encrypt
* data keys.
*/
@Nonnull private final Cipher masterKeyEncryptionCipher_;
/**
* The {@link Cipher} object created with the private part of the master-key. It's used to decrypt
* encrypted data keys.
*/
@Nonnull private final Cipher masterKeyDecryptionCipher_;
/** Generates random data keys. */
@Nonnull private KeyGenerator keyGenerator_;
/**
* Creates a new object that encrypts the data key with a master key whose id is {@code keyId}.
*
* <p>The value of {@code keyId} does not affect how the data key will be generated or encrypted.
* The {@code keyId} forms part of the header of the encrypted data, and is used to ensure that
* the header cannot be tempered with.
*/
public StaticMasterKey(@Nonnull final String keyId) {
this.keyId_ = Objects.requireNonNull(keyId);
try {
KeyFactory keyFactory = KeyFactory.getInstance(MASTER_KEY_ALGORITHM);
KeySpec publicKeySpec = new X509EncodedKeySpec(publicKey_v1);
PublicKey pubKey = keyFactory.generatePublic(publicKeySpec);
KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKey_v1);
PrivateKey privKey = keyFactory.generatePrivate(privateKeySpec);
masterKeyEncryptionCipher_ = Cipher.getInstance(MASTER_KEY_ENCRYPTION_ALGORITHM);
masterKeyEncryptionCipher_.init(Cipher.ENCRYPT_MODE, pubKey);
masterKeyDecryptionCipher_ = Cipher.getInstance(MASTER_KEY_ENCRYPTION_ALGORITHM);
masterKeyDecryptionCipher_.init(Cipher.DECRYPT_MODE, privKey);
} catch (GeneralSecurityException ex) {
throw new RuntimeException(ex);
}
}
/**
* Changes the {@link #keyId_}. This method is expected to be used to test that header of an
* encrypted message cannot be tempered with.
*/
public void setKeyId(@Nonnull String keyId) {
this.keyId_ = Objects.requireNonNull(keyId);
}
@Override
public String getProviderId() {
return PROVIDER_ID;
}
@Override
public String getKeyId() {
return keyId_;
}
@Override
public DataKey<StaticMasterKey> generateDataKey(
CryptoAlgorithm algorithm, Map<String, String> encryptionContext) {
try {
this.keyGenerator_ = KeyGenerator.getInstance(DATA_KEY_ENCRYPTION_ALGORITHM);
this.keyGenerator_.init(algorithm.getDataKeyLength() * 8, SRAND);
SecretKey key =
new SecretKeySpec(keyGenerator_.generateKey().getEncoded(), algorithm.getDataKeyAlgo());
byte[] encryptedKey = masterKeyEncryptionCipher_.doFinal(key.getEncoded());
return new DataKey<>(key, encryptedKey, keyId_.getBytes(StandardCharsets.UTF_8), this);
} catch (GeneralSecurityException ex) {
throw new RuntimeException(ex);
}
}
@Override
public DataKey<StaticMasterKey> encryptDataKey(
CryptoAlgorithm algorithm, Map<String, String> encryptionContext, DataKey<?> dataKey) {
try {
byte[] unencryptedKey = dataKey.getKey().getEncoded();
byte[] encryptedKey = masterKeyEncryptionCipher_.doFinal(unencryptedKey);
SecretKey newKey =
new SecretKeySpec(dataKey.getKey().getEncoded(), algorithm.getDataKeyAlgo());
return new DataKey<>(newKey, encryptedKey, keyId_.getBytes(StandardCharsets.UTF_8), this);
} catch (GeneralSecurityException ex) {
throw new RuntimeException(ex);
}
}
@Override
public DataKey<StaticMasterKey> decryptDataKey(
CryptoAlgorithm algorithm,
Collection<? extends EncryptedDataKey> encryptedDataKeys,
Map<String, String> encryptionContext)
throws UnsupportedProviderException, AwsCryptoException {
try {
for (EncryptedDataKey edk : encryptedDataKeys) {
if (keyId_.equals(new String(edk.getProviderInformation(), StandardCharsets.UTF_8))) {
byte[] unencryptedDataKey = masterKeyDecryptionCipher_.doFinal(edk.getEncryptedDataKey());
SecretKey key = new SecretKeySpec(unencryptedDataKey, algorithm.getDataKeyAlgo());
return new DataKey<>(key, edk.getEncryptedDataKey(), edk.getProviderInformation(), this);
}
}
} catch (GeneralSecurityException ex) {
throw new RuntimeException(ex);
}
return null;
}
/** Statically configured private key. */
private static final byte[] privateKey_v1 =
Utils.decodeBase64String(
"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKLpwqjYtYExVilW/Hg0ogWv9xZ+"
+ "THj4IzvISLlPtK8W6KXMcqukfuxdYmndPv8UD1DbdHFYSSistdqoBN32vVQOQnJZyYm45i2TDOV0"
+ "M2DtHtR6aMMlBLGtdPeeaT88nQfI1ORjRDyR1byMwomvmKifZYga6FjLt/sgqfSE9BUnAgMBAAEC"
+ "gYAqnewGL2qLuVRIzDCPYXVg938zqyZmHsNYyDP+BhPGGcASX0FAFW/+dQ9hkjcAk0bOaBo17Fp3"
+ "AXcxE/Lx/bHY+GWZ0wOJfl3aJBVJOpW8J6kwu68BUCmuFtRgbLSFu5+fbey3pKafYSptbX1fAI+z"
+ "hTx+a9B8pnn79ad4ziJ2QQJBAM+YHPGAEbr5qcNkwyy0xZgR/TLlcW2NQUt8HZpmErdX6d328iBC"
+ "SPb8+whXxCXZC3Mr+35IZ1pxxf0go/zGQv0CQQDI5oH0z1CKxoT6ErswNzB0oHxq/wD5mhutyqHa"
+ "mxbG5G3fN7I2IclwaXEA2eutIKxFMQNZYsX5mNYsrveSKivzAkABiujUJpZ7JDXNvObyYxmAyslt"
+ "4mSYYs9UZ0S1DAMhl6amPpqIANYX98NJyZUsjtNV9MK2qoUSF/xXqDFvxG1lAkBhP5Ow2Zn3U1mT"
+ "Y/XQxSZjjjwr3vyt1neHjQsEMwa3iGPXJbLSmVBVZfUZoGOBDsvVQoCIiFOlGuKyBpA45MkZAkAH"
+ "ksUrS9xLrDIUOI2BzMNRsK0bH7KJ+PFxm2SBgJOF9+Uf2A9LIP4IvESZq+ufp6c8YaqgR6Id1vws"
+ "7rUyGoa5");
/** Statically configured public key. */
private static final byte[] publicKey_v1 =
Utils.decodeBase64String(
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCi6cKo2LWBMVYpVvx4NKIFr/cWfkx4+CM7yEi5"
+ "T7SvFuilzHKrpH7sXWJp3T7/FA9Q23RxWEkorLXaqATd9r1UDkJyWcmJuOYtkwzldDNg7R7UemjD"
+ "JQSxrXT3nmk/PJ0HyNTkY0Q8kdW8jMKJr5ion2WIGuhYy7f7IKn0hPQVJwIDAQAB");
}
| 5,393 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/VersionInfoTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.internal;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class VersionInfoTest {
@Test
public void basic_use() {
final String userAgent = VersionInfo.loadUserAgent();
assertTrue(userAgent.startsWith(VersionInfo.USER_AGENT_PREFIX));
assertTrue(!userAgent.equals(VersionInfo.USER_AGENT_PREFIX + VersionInfo.UNKNOWN_VERSION));
}
}
| 5,394 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/CommittedKeyTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.internal;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static com.amazonaws.encryptionsdk.TestUtils.insecureRandomBytes;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import com.amazonaws.encryptionsdk.CryptoAlgorithm;
import com.amazonaws.encryptionsdk.TestUtils;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.nio.charset.StandardCharsets;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.util.Arrays;
import org.junit.Test;
public class CommittedKeyTest {
@Test
public void testGenerate() {
final CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm;
SecretKeySpec secretKey =
new SecretKeySpec(
Utils.decodeBase64String(TestUtils.messageWithCommitKeyDEKBase64),
algorithm.getDataKeyAlgo());
CommittedKey committedKey =
CommittedKey.generate(
algorithm,
secretKey,
Utils.decodeBase64String(TestUtils.messageWithCommitKeyMessageIdBase64));
assertNotNull(committedKey);
assertEquals(
TestUtils.messageWithCommitKeyCryptoAlgorithm.getKeyAlgo(),
committedKey.getKey().getAlgorithm());
assertArrayEquals(
Utils.decodeBase64String(TestUtils.messageWithCommitKeyCommitmentBase64),
committedKey.getCommitment());
}
@Test
public void testGenerateBadNonceLen() {
final CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm;
SecretKeySpec secretKey =
new SecretKeySpec(
Utils.decodeBase64String(TestUtils.messageWithCommitKeyDEKBase64),
algorithm.getDataKeyAlgo());
assertThrows(
IllegalArgumentException.class,
"Invalid nonce size",
() ->
CommittedKey.generate(
algorithm, secretKey, new byte[algorithm.getCommitmentNonceLength() + 1]));
}
@Test
public void testGenerateIncorrectMismatchedKeySpecAlgorithm() {
final CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm;
SecretKeySpec secretKey =
new SecretKeySpec(new byte[algorithm.getDataKeyLength()], "incorrectAlgorithm");
assertThrows(
IllegalArgumentException.class,
"DataKey of incorrect algorithm.",
() ->
CommittedKey.generate(
algorithm, secretKey, new byte[algorithm.getCommitmentNonceLength()]));
}
@Test
public void testGenerateIncorrectDataKeyLenForAlgorithm() {
final CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm;
SecretKeySpec secretKey =
new SecretKeySpec(new byte[algorithm.getDataKeyLength() + 1], algorithm.getDataKeyAlgo());
assertThrows(
IllegalArgumentException.class,
"DataKey of incorrect length.",
() ->
CommittedKey.generate(
algorithm, secretKey, new byte[algorithm.getCommitmentNonceLength()]));
}
@Test
public void testGenerateNonCommittingAlgorithm() {
final CryptoAlgorithm algorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
SecretKeySpec secretKey =
new SecretKeySpec(new byte[algorithm.getDataKeyLength()], algorithm.getDataKeyAlgo());
assertThrows(
IllegalArgumentException.class,
"Algorithm does not support key commitment.",
() ->
CommittedKey.generate(
algorithm, secretKey, new byte[algorithm.getCommitmentNonceLength()]));
}
@Test
public void testGenerateCommittedKeySmokeTest() throws Exception {
// This test intentionally using different techniques
// to assemble the labels and constants.
// Commitment Nonce N1 is equal to the Message Id which is a 32 byte random value.
// Normally this needs to be cryptographically secure, but we can relax this for improved
// performance in testing.
final byte[] n1 = insecureRandomBytes(32);
// Hash for HKDF is SHA-512
final HmacKeyDerivationFunction hkdf = HmacKeyDerivationFunction.getInstance("HmacSHA512");
// K_R (Raw keying material, a.k.a. data key) is 256 bits (32 bytes)
// Normally this needs to be cryptographically secure, but we can relax this for improved
// performance in testing.
final byte[] k_r = insecureRandomBytes(32);
final SecretKey k_rKey =
new SecretKeySpec(k_r, "HkdfSHA512"); // We also need K_R in this format for later use
// Output key size for Encryption Key is 256 bits (32 bytes)
final int l_e = 32;
// Output key size for Commitment Value is 256 bits (32 bytes)
final int l_c = 32;
// KeyLabel is "DERIVEKEY" as UTF-8 encoded bytes
final byte[] keyLabel = "DERIVEKEY".getBytes(StandardCharsets.UTF_8);
// CommitLabel is "COMMITKEY" as UTF-8 encoded bytes
final byte[] commitLabel = "COMMITKEY".getBytes(StandardCharsets.UTF_8);
// PRK is HKDF-Extract(salt=N_1, initialKeyingMaterial=K_R)
hkdf.init(k_r /* IKM */, n1 /* Salt */);
// Not final because we'll rerun this with the other algorithm
CryptoAlgorithm alg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY;
// Info for K_E is Algorithm ID || KeyLabel.
// We intentionally construct this in a different manner from the tested implemention.
// This technique is harder to get wrong but less performant.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
out.writeShort(alg.getValue());
out.write(keyLabel);
out.close();
// K_E := HKDF-Expand(prk=PRK, info=Algorithm ID || KeyLabel, L=L_E)
byte[] k_e = hkdf.deriveKey(baos.toByteArray(), l_e);
// K_C = HKDF-Expand(prk=PRK, info=CommitLabel, L=LC)
final byte[] k_c = hkdf.deriveKey(commitLabel, l_c);
// Now that we have the expected values, test reality
CommittedKey committedKey = CommittedKey.generate(alg, k_rKey, n1);
assertArrayEquals("K_C for " + alg, k_c, committedKey.getCommitment());
assertArrayEquals("K_E for " + alg, k_e, committedKey.getKey().getEncoded());
// Now test it with the second algorithm.
// Since the commitment value doesn't include the algorithm Id,
// K_C should remain unchanged and only K_E should vary.
alg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384;
baos = new ByteArrayOutputStream();
out = new DataOutputStream(baos);
out.writeShort(alg.getValue());
out.write(keyLabel);
out.close();
final byte[] k_e2 = hkdf.deriveKey(baos.toByteArray(), l_e);
// Now that we have the expected values, test reality
committedKey = CommittedKey.generate(alg, k_rKey, n1);
assertArrayEquals("K_C for " + alg, k_c, committedKey.getCommitment());
assertArrayEquals("K_E for " + alg, k_e2, committedKey.getKey().getEncoded());
assertFalse("K_E must be different for different algorithms", Arrays.areEqual(k_e, k_e2));
}
}
| 5,395 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/UtilsTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.encryptionsdk.internal;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
/** Unit tests for {@link Utils} */
public class UtilsTest {
@Test
public void compareObjectIdentityTest() {
assertNotEquals(0, Utils.compareObjectIdentity(null, new Object()));
assertNotEquals(0, Utils.compareObjectIdentity(new Object(), null));
assertEquals(0, Utils.compareObjectIdentity(Utils.class, Utils.class));
assertNotEquals(0, Utils.compareObjectIdentity(new Object(), new Object()));
}
@Test
public void compareObjectIdentity_handlesHashCodeCollisions() {
// With this large of an array, it is overwhelmingly likely that we will see two objects with
// identical
// identity hash codes.
Object[] testArray = new Object[512_000];
for (int i = 0; i < testArray.length; i++) {
testArray[i] = new Object();
}
java.util.Arrays.sort(testArray, Utils::compareObjectIdentity);
// Verify that we do not have any objects that are equal (compare to zero) in the array.
// We know the primary sort is by hashcode, so we'll just do exhaustive comparison within each
// hashcode.
boolean sawCollison = false;
for (int i = 0; i < testArray.length; i++) {
int hashCode = System.identityHashCode(testArray[i]);
int endOfHashGroup = i;
while (endOfHashGroup + 1 < testArray.length
&& System.identityHashCode(testArray[endOfHashGroup + 1]) == hashCode) {
endOfHashGroup++;
}
if (i != endOfHashGroup) {
sawCollison = true;
}
for (int a = i; a <= endOfHashGroup; a++) {
for (int b = a + 1; b <= endOfHashGroup; b++) {
if (a != b) {
assertNotEquals(0, Utils.compareObjectIdentity(a, b));
}
}
}
}
assertTrue(sawCollison);
}
@Test
public void testSaturatingAdd() {
assertEquals(0, Utils.saturatingAdd(0, 0));
assertEquals(2, Utils.saturatingAdd(1, 1));
assertEquals(-2, Utils.saturatingAdd(-1, -1));
assertEquals(0, Utils.saturatingAdd(-1, +1));
assertEquals(0, Utils.saturatingAdd(+1, -1));
assertEquals(Long.MIN_VALUE, Utils.saturatingAdd(Long.MIN_VALUE + 1, -2));
assertEquals(Long.MAX_VALUE, Utils.saturatingAdd(Long.MAX_VALUE - 1, +2));
assertEquals(Long.MAX_VALUE, Utils.saturatingAdd(Long.MAX_VALUE, Long.MAX_VALUE));
assertEquals(Long.MIN_VALUE, Utils.saturatingAdd(Long.MIN_VALUE, Long.MIN_VALUE));
}
/** Basic sanity check for our Base64 helper methods. */
@Test
public void base64empty() {
assertEquals("", Utils.encodeBase64String(new byte[] {}));
assertArrayEquals(new byte[] {}, Utils.decodeBase64String(""));
}
/** Basic sanity check for our Base64 helper methods. */
@Test
public void base64something() {
byte[] data = "Lorem ipsum dolor sit amet".getBytes(StandardCharsets.UTF_8);
String encoded = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ=";
assertEquals(encoded, Utils.encodeBase64String(data));
assertArrayEquals(data, Utils.decodeBase64String(encoded));
}
@Test
public void testBigIntegerToByteArray() {
byte[] bytes = new byte[] {23, 47, 126, -42, 34};
assertArrayEquals(
new byte[] {0, 0, 0, 23, 47, 126, -42, 34},
Utils.bigIntegerToByteArray(new BigInteger(bytes), 8));
assertArrayEquals(
new byte[] {23, 47, 126, -42, 34}, Utils.bigIntegerToByteArray(new BigInteger(bytes), 5));
bytes = new byte[] {0, -47, 126, -42, 34};
assertArrayEquals(
new byte[] {-47, 126, -42, 34}, Utils.bigIntegerToByteArray(new BigInteger(bytes), 4));
}
@Test(expected = IllegalArgumentException.class)
public void testBigIntegerToByteArray_InvalidLength() {
byte[] bytes = new byte[] {0, -47, 126, -42, 34};
assertArrayEquals(bytes, Utils.bigIntegerToByteArray(new BigInteger(bytes), 3));
}
@Test
public void testArrayPrefixEquals() {
byte[] a = new byte[] {10, 11, 12, 13, 14, 15};
byte[] b = new byte[] {10, 11, 12, 13, 20, 21, 22};
assertFalse(Utils.arrayPrefixEquals(null, b, 4));
assertFalse(Utils.arrayPrefixEquals(a, null, 4));
assertFalse(Utils.arrayPrefixEquals(a, b, a.length + 1));
assertTrue(Utils.arrayPrefixEquals(a, b, 4));
assertFalse(Utils.arrayPrefixEquals(a, b, 5));
}
}
| 5,396 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/PrimitivesParserTest.java | /*
* Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except
* in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.amazonaws.encryptionsdk.internal;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.junit.Test;
public class PrimitivesParserTest {
@Test
public void testParseLong() throws IOException {
final long[] tests =
new long[] {
Long.MIN_VALUE, Long.MAX_VALUE, -1, 0, 1, Long.MIN_VALUE + 1, Long.MAX_VALUE - 1
};
for (long x : tests) {
try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final DataOutputStream dos = new DataOutputStream(baos)) {
dos.writeLong(x);
dos.close();
assertEquals(x, PrimitivesParser.parseLong(baos.toByteArray(), 0));
}
}
}
@Test
public void testParseInt() throws IOException {
final int[] tests =
new int[] {
Integer.MIN_VALUE,
Integer.MAX_VALUE,
-1,
0,
1,
Integer.MIN_VALUE + 1,
Integer.MAX_VALUE - 1
};
for (int x : tests) {
try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final DataOutputStream dos = new DataOutputStream(baos)) {
dos.writeInt(x);
dos.close();
assertEquals(x, PrimitivesParser.parseInt(baos.toByteArray(), 0));
}
}
}
@Test
public void testParseShort() throws IOException {
for (int x = Short.MIN_VALUE; x < Short.MAX_VALUE; x++) {
try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final DataOutputStream dos = new DataOutputStream(baos)) {
dos.writeShort(x);
dos.close();
assertEquals((short) x, PrimitivesParser.parseShort(baos.toByteArray(), 0));
}
}
}
@Test
public void testParseUnsignedShort() throws IOException {
for (int x = 0; x < Constants.UNSIGNED_SHORT_MAX_VAL; x++) {
try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final DataOutputStream dos = new DataOutputStream(baos)) {
PrimitivesParser.writeUnsignedShort(dos, x);
assertEquals(x, PrimitivesParser.parseUnsignedShort(baos.toByteArray(), 0));
}
}
}
@Test
public void testParseByte() throws IOException {
for (int x = Byte.MIN_VALUE; x < Byte.MAX_VALUE; x++) {
try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final DataOutputStream dos = new DataOutputStream(baos)) {
dos.writeByte(x);
dos.close();
assertEquals((byte) x, PrimitivesParser.parseByte(baos.toByteArray(), 0));
}
}
}
}
| 5,397 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/TestIOUtils.java | /*
* Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except
* in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.amazonaws.encryptionsdk.internal;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
public class TestIOUtils {
private static final SecureRandom rng_ = new SecureRandom();
public static byte[] generateRandomPlaintext(final int size) {
return RandomBytesGenerator.generate(size);
}
/**
* Generates and returns a string of the given {@code length}.
*
* <p>This function can be replaced by the RandomStringUtil class from Apache Commons.
*
* <p>This method re-implemented here to keep this library's dependency to a minimum which would
* reduce friction when it's consumed by other packages.
*/
public static String generateRandomString(final int size) {
StringBuilder sb = new StringBuilder();
Random rand = new Random();
for (int i = 0; i < size; i++) {
int c = rand.nextInt(Byte.MAX_VALUE);
c = c == 0 ? (c + 1) : c;
sb.append((char) c);
}
return sb.toString();
}
public static byte[] computeFileDigest(final String fileName) throws IOException {
try {
final FileInputStream fis = new FileInputStream(fileName);
final MessageDigest md = MessageDigest.getInstance("SHA-256");
final DigestInputStream dis = new DigestInputStream(fis, md);
final int readLen = 128;
final byte[] readBytes = new byte[readLen];
while (dis.read(readBytes) != -1) {}
dis.close();
return md.digest();
} catch (NoSuchAlgorithmException e) {
// shouldn't get here since we hardcode the algorithm.
}
return null;
}
public static byte[] getSha256Hash(final byte[] input) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
// should never get here.
}
return md.digest(input);
}
public static void generateFile(final String fileName, final long fileSize) throws IOException {
final FileOutputStream fs = new FileOutputStream(fileName);
final byte[] fileBytes = new byte[(int) fileSize];
rng_.nextBytes(fileBytes);
fs.write(fileBytes);
fs.close();
}
public static void copyInStreamToOutStream(
final InputStream inStream, final OutputStream outStream, final int readLen)
throws IOException {
final byte[] readBuffer = new byte[readLen];
int actualRead = 0;
while (actualRead >= 0) {
outStream.write(readBuffer, 0, actualRead);
actualRead = inStream.read(readBuffer);
}
inStream.close();
outStream.close();
}
public static void deleteDir(final File filePath) {
if (filePath.exists()) {
File[] files = filePath.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
files[i].delete();
} else {
deleteDir(files[i]);
}
}
}
filePath.delete();
}
public static void copyInStreamToOutStream(
final InputStream inStream, final OutputStream outStream) throws IOException {
final int readLen = 1024; // 1KB
copyInStreamToOutStream(inStream, outStream, readLen);
}
}
| 5,398 |
0 | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk | Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/FrameEncryptionHandlerTest.java | /*
* Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except
* in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.amazonaws.encryptionsdk.internal;
import static com.amazonaws.encryptionsdk.TestUtils.assertThrows;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.CryptoAlgorithm;
import com.amazonaws.encryptionsdk.TestUtils;
import com.amazonaws.encryptionsdk.model.CipherFrameHeaders;
import java.lang.reflect.Field;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Before;
import org.junit.Test;
public class FrameEncryptionHandlerTest {
private final CryptoAlgorithm cryptoAlgorithm_ = TestUtils.DEFAULT_TEST_CRYPTO_ALG;
private final byte[] messageId_ =
RandomBytesGenerator.generate(cryptoAlgorithm_.getMessageIdLength());
private final byte nonceLen_ = cryptoAlgorithm_.getNonceLen();
private final byte[] dataKeyBytes_ =
RandomBytesGenerator.generate(cryptoAlgorithm_.getKeyLength());
private final SecretKey encryptionKey_ = new SecretKeySpec(dataKeyBytes_, "AES");
private final int frameSize_ = AwsCrypto.getDefaultFrameSize();
private FrameEncryptionHandler frameEncryptionHandler_;
@Before
public void setUp() throws Exception {
frameEncryptionHandler_ =
new FrameEncryptionHandler(
encryptionKey_, nonceLen_, cryptoAlgorithm_, messageId_, frameSize_);
}
@Test
public void emptyOutBytes() {
final int outLen = 0;
final byte[] out = new byte[outLen];
final int processedLen = frameEncryptionHandler_.doFinal(out, 0);
assertEquals(outLen, processedLen);
}
@Test
public void correctIVsGenerated() throws Exception {
byte[] buf = new byte[frameSize_ + 1024];
for (int i = 0; i <= 254; i++) {
byte[] expectedNonce = {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, (byte) (i + 1)
};
generateTestBlock(buf);
assertHeaderNonce(expectedNonce, buf);
}
generateTestBlock(buf);
assertHeaderNonce(
new byte[] {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 1, 0
},
buf);
}
@Test
public void encryptionHandlerEnforcesFrameLimits() throws Exception {
// Skip to the second-to-last frame first. Actually getting there by encrypting block would take
// a very long
// time, so we'll reflect in; for a test that legitimately gets there, see the
// FrameEncryptionHandlerVeryLongTest.
Field f = FrameEncryptionHandler.class.getDeclaredField("frameNumber_");
f.setAccessible(true);
f.set(frameEncryptionHandler_, 0xFFFF_FFFEL);
byte[] buf = new byte[frameSize_ + 1024];
// Writing frame 0xFFFF_FFFE should succeed.
generateTestBlock(buf);
assertHeaderNonce(Hex.decode("0000000000000000FFFFFFFE"), buf);
byte[] oldBuf = buf.clone();
// Writing the next frame must fail
assertThrows(() -> generateTestBlock(buf));
// ... and must not produce any output
assertArrayEquals(oldBuf, buf);
// However we can still finish the encryption
frameEncryptionHandler_.doFinal(buf, 0);
assertHeaderNonce(Hex.decode("0000000000000000FFFFFFFF"), buf);
}
private void assertHeaderNonce(byte[] expectedNonce, byte[] buf) {
CipherFrameHeaders headers = new CipherFrameHeaders();
headers.setNonceLength(cryptoAlgorithm_.getNonceLen());
headers.deserialize(buf, 0);
assertArrayEquals(expectedNonce, headers.getNonce());
}
private void generateTestBlock(byte[] buf) {
frameEncryptionHandler_.processBytes(new byte[frameSize_], 0, frameSize_, buf, 0);
}
}
| 5,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.