mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(kms): support ImportKeyMaterial for Origin=EXTERNAL keys (#3068)
CreateKey accepts Origin=EXTERNAL, GetParametersForImport issues a real RSA wrapping key, and ImportKeyMaterial unwraps and installs the material. Expiry and DeleteImportedKeyMaterial return the key to PendingImport. Fixes #1916 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
1 parent
532e27986e
commit
37faaa8abe
10 files changed
+1415
-22
No files matched your search
@@ -7,13 +7,22 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.OAEPParameterSpec;
|
||||
import javax.crypto.spec.PSource;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.MGF1ParameterSpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
@@ -1754,4 +1763,191 @@ class KmsIntegrationTest {
|
||||
.then().statusCode(200)
|
||||
.extract().path("KeyMetadata.KeyId");
|
||||
}
|
||||
|
||||
@Test
|
||||
void importKeyMaterialRoundTripEnablesAnExternalKey() throws Exception {
|
||||
String keyId = createExternalSymmetricKey();
|
||||
|
||||
describeKey(keyId)
|
||||
.body("KeyMetadata.Origin", equalTo("EXTERNAL"))
|
||||
.body("KeyMetadata.KeyState", equalTo("PendingImport"))
|
||||
.body("KeyMetadata.Enabled", equalTo(false));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.Encrypt")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\":\"%s\",\"Plaintext\":\"%s\"}"
|
||||
.formatted(keyId, Base64.getEncoder().encodeToString("hello".getBytes(StandardCharsets.UTF_8))))
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("KMSInvalidStateException"));
|
||||
|
||||
var parameters = given()
|
||||
.header("X-Amz-Target", "TrentService.GetParametersForImport")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\":\"%s\",\"WrappingAlgorithm\":\"RSAES_OAEP_SHA_256\",\"WrappingKeySpec\":\"RSA_2048\"}"
|
||||
.formatted(keyId))
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("KeyId", startsWith("arn:aws:kms:"))
|
||||
.body("PublicKey", notNullValue())
|
||||
.body("ImportToken", notNullValue())
|
||||
.body("ParametersValidTo", notNullValue())
|
||||
.extract().jsonPath();
|
||||
|
||||
byte[] material = new byte[32];
|
||||
Arrays.fill(material, (byte) 11);
|
||||
String wrapped = Base64.getEncoder().encodeToString(
|
||||
wrapWithRsaOaepSha256(parameters.getString("PublicKey"), material));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.ImportKeyMaterial")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body(("{\"KeyId\":\"%s\",\"ImportToken\":\"%s\",\"EncryptedKeyMaterial\":\"%s\","
|
||||
+ "\"ExpirationModel\":\"KEY_MATERIAL_DOES_NOT_EXPIRE\"}")
|
||||
.formatted(keyId, parameters.getString("ImportToken"), wrapped))
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("KeyId", startsWith("arn:aws:kms:"))
|
||||
.body("KeyMaterialId", matchesPattern("[a-f0-9]{64}"));
|
||||
|
||||
describeKey(keyId)
|
||||
.body("KeyMetadata.KeyState", equalTo("Enabled"))
|
||||
.body("KeyMetadata.Enabled", equalTo(true))
|
||||
.body("KeyMetadata.Origin", equalTo("EXTERNAL"))
|
||||
.body("KeyMetadata.ExpirationModel", equalTo("KEY_MATERIAL_DOES_NOT_EXPIRE"))
|
||||
.body("KeyMetadata", not(hasKey("ValidTo")));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.Encrypt")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\":\"%s\",\"Plaintext\":\"%s\"}"
|
||||
.formatted(keyId, Base64.getEncoder().encodeToString("hello".getBytes(StandardCharsets.UTF_8))))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteImportedKeyMaterialReturnsTheKeyToPendingImport() throws Exception {
|
||||
String keyId = createExternalSymmetricKey();
|
||||
importFreshMaterial(keyId);
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.DeleteImportedKeyMaterial")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\":\"%s\"}".formatted(keyId))
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("KeyId", startsWith("arn:aws:kms:"))
|
||||
.body("KeyMaterialId", matchesPattern("[a-f0-9]{64}"));
|
||||
|
||||
describeKey(keyId)
|
||||
.body("KeyMetadata.KeyState", equalTo("PendingImport"))
|
||||
.body("KeyMetadata.Enabled", equalTo(false))
|
||||
.body("KeyMetadata", not(hasKey("ExpirationModel")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeKeyReportsAwsKmsOriginForAnOrdinaryKey() {
|
||||
String keyId = given()
|
||||
.header("X-Amz-Target", "TrentService.CreateKey")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().path("KeyMetadata.KeyId");
|
||||
|
||||
describeKey(keyId)
|
||||
.body("KeyMetadata.Origin", equalTo("AWS_KMS"))
|
||||
.body("KeyMetadata", not(hasKey("ExpirationModel")))
|
||||
.body("KeyMetadata", not(hasKey("ValidTo")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void importIsRejectedForAnAsymmetricKeySpec() {
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.CreateKey")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"Origin\":\"EXTERNAL\",\"KeyUsage\":\"ENCRYPT_DECRYPT\",\"KeySpec\":\"RSA_2048\"}")
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("UnsupportedOperationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeprecatedWrappingAlgorithmIsRejected() {
|
||||
String keyId = createExternalSymmetricKey();
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.GetParametersForImport")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\":\"%s\",\"WrappingAlgorithm\":\"RSAES_PKCS1_V1_5\",\"WrappingKeySpec\":\"RSA_2048\"}"
|
||||
.formatted(keyId))
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("UnsupportedOperationException"));
|
||||
}
|
||||
|
||||
private String createExternalSymmetricKey() {
|
||||
return given()
|
||||
.header("X-Amz-Target", "TrentService.CreateKey")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"Origin\":\"EXTERNAL\",\"Description\":\"external key\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().path("KeyMetadata.KeyId");
|
||||
}
|
||||
|
||||
private io.restassured.response.ValidatableResponse describeKey(String keyId) {
|
||||
return given()
|
||||
.header("X-Amz-Target", "TrentService.DescribeKey")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\":\"%s\"}".formatted(keyId))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private void importFreshMaterial(String keyId) throws Exception {
|
||||
var parameters = given()
|
||||
.header("X-Amz-Target", "TrentService.GetParametersForImport")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body("{\"KeyId\":\"%s\",\"WrappingAlgorithm\":\"RSAES_OAEP_SHA_256\",\"WrappingKeySpec\":\"RSA_2048\"}"
|
||||
.formatted(keyId))
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().jsonPath();
|
||||
|
||||
byte[] material = new byte[32];
|
||||
Arrays.fill(material, (byte) 3);
|
||||
String wrapped = Base64.getEncoder().encodeToString(
|
||||
wrapWithRsaOaepSha256(parameters.getString("PublicKey"), material));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "TrentService.ImportKeyMaterial")
|
||||
.contentType(KMS_CONTENT_TYPE)
|
||||
.body(("{\"KeyId\":\"%s\",\"ImportToken\":\"%s\",\"EncryptedKeyMaterial\":\"%s\","
|
||||
+ "\"ExpirationModel\":\"KEY_MATERIAL_DOES_NOT_EXPIRE\"}")
|
||||
.formatted(keyId, parameters.getString("ImportToken"), wrapped))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps key material exactly as a caller would: the point of the round trip is that the
|
||||
* emulator unwraps what a standard RSAES-OAEP-SHA-256 client produces, not a shape of its own.
|
||||
*/
|
||||
private static byte[] wrapWithRsaOaepSha256(String publicKeyEncoded, byte[] material) throws Exception {
|
||||
PublicKey wrappingKey = KeyFactory.getInstance("RSA")
|
||||
.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyEncoded)));
|
||||
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, wrappingKey, new OAEPParameterSpec("SHA-256", "MGF1",
|
||||
new MGF1ParameterSpec("SHA-256"), PSource.PSpecified.DEFAULT));
|
||||
return cipher.doFinal(material);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,11 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.OAEPParameterSpec;
|
||||
import javax.crypto.spec.PSource;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.Security;
|
||||
import java.security.KeyFactory;
|
||||
@@ -25,6 +30,8 @@ import java.security.Signature;
|
||||
import java.security.spec.MGF1ParameterSpec;
|
||||
import java.security.spec.PSSParameterSpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -40,6 +47,7 @@ class KmsServiceTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private KmsService kmsService;
|
||||
private InMemoryStorage<String, KmsKey> keyStore;
|
||||
|
||||
@BeforeAll
|
||||
static void registerBouncyCastle() {
|
||||
@@ -50,8 +58,9 @@ class KmsServiceTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
keyStore = new InMemoryStorage<>();
|
||||
kmsService = new KmsService(
|
||||
new InMemoryStorage<>(),
|
||||
keyStore,
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "000000000000")
|
||||
@@ -1626,7 +1635,7 @@ class KmsServiceTest {
|
||||
|
||||
assertNotNull(publicKeyInfo.getPublicKeyEncoded());
|
||||
byte[] derBytes = Base64.getDecoder().decode(publicKeyInfo.getPublicKeyEncoded());
|
||||
|
||||
|
||||
// Verify it can be parsed as a standard Java PublicKey
|
||||
KeyFactory factory = KeyFactory.getInstance("EC");
|
||||
PublicKey pub = factory.generatePublic(new X509EncodedKeySpec(derBytes));
|
||||
@@ -2116,4 +2125,461 @@ class KmsServiceTest {
|
||||
kmsService.generateMac(keyId, message, "HMAC_SHA_256", REGION));
|
||||
assertEquals("InvalidKeyUsageException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ImportedKeyMaterial {
|
||||
|
||||
private static final String OAEP_SHA_256 = "RSAES_OAEP_SHA_256";
|
||||
|
||||
private KmsKey externalKey(String keySpec, String keyUsage) {
|
||||
return kmsService.createKey("external", keyUsage, keySpec, null, Map.of(), "EXTERNAL", REGION);
|
||||
}
|
||||
|
||||
private KmsKey externalSymmetricKey() {
|
||||
return externalKey("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT");
|
||||
}
|
||||
|
||||
private byte[] material(int length, byte seed) {
|
||||
byte[] material = new byte[length];
|
||||
Arrays.fill(material, seed);
|
||||
return material;
|
||||
}
|
||||
|
||||
/** Wraps material the way a caller would, with the public key GetParametersForImport returned. */
|
||||
private byte[] wrap(String publicKeyEncoded, String wrappingAlgorithm, byte[] material) throws Exception {
|
||||
PublicKey wrappingKey = KeyFactory.getInstance("RSA")
|
||||
.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyEncoded)));
|
||||
String digest = "RSAES_OAEP_SHA_1".equals(wrappingAlgorithm) ? "SHA-1" : "SHA-256";
|
||||
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, wrappingKey, new OAEPParameterSpec(digest, "MGF1",
|
||||
new MGF1ParameterSpec(digest), PSource.PSpecified.DEFAULT));
|
||||
return cipher.doFinal(material);
|
||||
}
|
||||
|
||||
private KmsKey importInto(KmsKey key, byte[] rawMaterial, String wrappingAlgorithm) throws Exception {
|
||||
KmsService.ImportParameters parameters =
|
||||
kmsService.getParametersForImport(key.getKeyId(), wrappingAlgorithm, "RSA_2048", REGION);
|
||||
return kmsService.importKeyMaterial(key.getKeyId(), parameters.importToken(),
|
||||
wrap(parameters.publicKeyEncoded(), wrappingAlgorithm, rawMaterial),
|
||||
"KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void externalOriginCreatesAKeyWithoutMaterial() {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
|
||||
assertEquals("EXTERNAL", key.getOrigin());
|
||||
assertEquals("PendingImport", key.getKeyState());
|
||||
assertFalse(key.isEnabled());
|
||||
assertNull(key.getPrivateKeyEncoded());
|
||||
}
|
||||
|
||||
@Test
|
||||
void encryptIsRejectedWhileTheKeyHasNoMaterial() {
|
||||
String keyId = externalSymmetricKey().getKeyId();
|
||||
byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.encrypt(keyId, plaintext, REGION));
|
||||
assertEquals("KMSInvalidStateException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"RSAES_OAEP_SHA_256", "RSAES_OAEP_SHA_1"})
|
||||
void everySupportedWrappingAlgorithmCompletesAnImport(String wrappingAlgorithm) throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
|
||||
KmsKey imported = importInto(key, material(32, (byte) 7), wrappingAlgorithm);
|
||||
|
||||
assertEquals("Enabled", imported.getKeyState());
|
||||
assertTrue(imported.isEnabled());
|
||||
assertNull(imported.getImportParameters());
|
||||
assertNotNull(kmsService.encrypt(key.getKeyId(), "hello".getBytes(StandardCharsets.UTF_8), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void materialWrappedForAnotherKeyIsRejected() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
KmsKey otherKey = externalSymmetricKey();
|
||||
KmsService.ImportParameters foreign =
|
||||
kmsService.getParametersForImport(otherKey.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
KmsService.ImportParameters own =
|
||||
kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
byte[] wrongly = wrap(foreign.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));
|
||||
|
||||
String keyId = key.getKeyId();
|
||||
String token = own.importToken();
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(
|
||||
keyId, token, wrongly, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION));
|
||||
assertEquals("InvalidCiphertextException", ex.getErrorCode());
|
||||
assertEquals("PendingImport", kmsService.describeKey(keyId, REGION).getKeyState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void materialOfTheWrongLengthIsRejected() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
importInto(key, material(16, (byte) 1), OAEP_SHA_256));
|
||||
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSupersededImportTokenIsRejected() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
KmsService.ImportParameters first =
|
||||
kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
byte[] wrapped = wrap(first.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));
|
||||
|
||||
String keyId = key.getKeyId();
|
||||
String staleToken = first.importToken();
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(
|
||||
keyId, staleToken, wrapped, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION));
|
||||
assertEquals("InvalidImportTokenException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importWithoutOutstandingParametersIsRejected() {
|
||||
String keyId = externalSymmetricKey().getKeyId();
|
||||
byte[] anything = material(32, (byte) 1);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(
|
||||
keyId, "some-token", anything, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION));
|
||||
assertEquals("InvalidImportTokenException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImportTokenIsSpentByTheImportThatUsedIt() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
KmsService.ImportParameters parameters =
|
||||
kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 3));
|
||||
kmsService.importKeyMaterial(key.getKeyId(), parameters.importToken(), wrapped,
|
||||
"KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION);
|
||||
|
||||
String keyId = key.getKeyId();
|
||||
String spentToken = parameters.importToken();
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(
|
||||
keyId, spentToken, wrapped, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION));
|
||||
assertEquals("InvalidImportTokenException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS requires ValidTo to be in the future, so the only honest way to reach an expired key
|
||||
* is to let the clock pass it. Rewinding the stored ValidTo stands in for that wait.
|
||||
*/
|
||||
@Test
|
||||
void expiringMaterialReturnsTheKeyToPendingImport() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
KmsService.ImportParameters parameters =
|
||||
kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 9));
|
||||
kmsService.importKeyMaterial(key.getKeyId(), parameters.importToken(), wrapped,
|
||||
"KEY_MATERIAL_EXPIRES", Instant.now().getEpochSecond() + 3600, null, REGION);
|
||||
|
||||
KmsKey stored = keyStore.get(REGION + "::" + key.getKeyId()).orElseThrow();
|
||||
stored.setValidTo(Instant.now().getEpochSecond() - 60);
|
||||
keyStore.put(REGION + "::" + key.getKeyId(), stored);
|
||||
|
||||
KmsKey expired = kmsService.describeKey(key.getKeyId(), REGION);
|
||||
assertEquals("PendingImport", expired.getKeyState());
|
||||
assertFalse(expired.isEnabled());
|
||||
assertNull(expired.getPrivateKeyEncoded());
|
||||
assertEquals(0, expired.getValidTo());
|
||||
assertNull(expired.getExpirationModel());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validToInThePastIsRejected() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
KmsService.ImportParameters parameters =
|
||||
kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));
|
||||
|
||||
String keyId = key.getKeyId();
|
||||
String token = parameters.importToken();
|
||||
long past = Instant.now().getEpochSecond() - 60;
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(
|
||||
keyId, token, wrapped, "KEY_MATERIAL_EXPIRES", past, null, REGION));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validToBeyondThreeHundredSixtyFiveDaysIsRejected() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
KmsService.ImportParameters parameters =
|
||||
kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));
|
||||
|
||||
String keyId = key.getKeyId();
|
||||
String token = parameters.importToken();
|
||||
long tooFar = Instant.now().plus(Duration.ofDays(366)).getEpochSecond();
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(
|
||||
keyId, token, wrapped, "KEY_MATERIAL_EXPIRES", tooFar, null, REGION));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theKeyMaterialIdIsDerivedFromTheKeyAndTheMaterial() throws Exception {
|
||||
byte[] sharedMaterial = material(32, (byte) 21);
|
||||
KmsKey first = externalSymmetricKey();
|
||||
KmsKey second = externalSymmetricKey();
|
||||
|
||||
String firstId = importInto(first, sharedMaterial, OAEP_SHA_256).getKeyMaterialId();
|
||||
String secondId = importInto(second, sharedMaterial, OAEP_SHA_256).getKeyMaterialId();
|
||||
|
||||
assertTrue(firstId.matches("[a-f0-9]{64}"));
|
||||
assertNotEquals(firstId, secondId);
|
||||
|
||||
kmsService.deleteImportedKeyMaterial(first.getKeyId(), REGION);
|
||||
assertEquals(firstId, importInto(first, sharedMaterial, OAEP_SHA_256).getKeyMaterialId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deprecatedPkcs1WrappingIsRejected() {
|
||||
String keyId = externalSymmetricKey().getKeyId();
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.getParametersForImport(keyId, "RSAES_PKCS1_V1_5", "RSA_2048", REGION));
|
||||
assertEquals("UnsupportedOperationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importingNewMaterialIntoAKeyThatAlreadyHasSomeIsRejected() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
importInto(key, material(32, (byte) 5), OAEP_SHA_256);
|
||||
KmsService.ImportParameters parameters =
|
||||
kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 6));
|
||||
|
||||
String keyId = key.getKeyId();
|
||||
String token = parameters.importToken();
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(
|
||||
keyId, token, wrapped, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, "NEW_KEY_MATERIAL", REGION));
|
||||
assertEquals("UnsupportedOperationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reimportingExistingMaterialIntoAFreshKeyIsRejected() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
KmsService.ImportParameters parameters =
|
||||
kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 6));
|
||||
|
||||
String keyId = key.getKeyId();
|
||||
String token = parameters.importToken();
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(
|
||||
keyId, token, wrapped, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, "EXISTING_KEY_MATERIAL", REGION));
|
||||
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnmodelledImportTypeIsRejected() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
KmsService.ImportParameters parameters =
|
||||
kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 6));
|
||||
|
||||
String keyId = key.getKeyId();
|
||||
String token = parameters.importToken();
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(
|
||||
keyId, token, wrapped, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, "ROTATE", REGION));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingMaterialFromAKeyPendingDeletionLeavesItPendingDeletion() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
importInto(key, material(32, (byte) 5), OAEP_SHA_256);
|
||||
kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);
|
||||
|
||||
KmsKey deleted = kmsService.deleteImportedKeyMaterial(key.getKeyId(), REGION);
|
||||
|
||||
assertEquals("PendingDeletion", deleted.getKeyState());
|
||||
assertNull(deleted.getPrivateKeyEncoded());
|
||||
}
|
||||
|
||||
@Test
|
||||
void keyMaterialExpiresRequiresValidTo() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
KmsService.ImportParameters parameters =
|
||||
kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));
|
||||
|
||||
String keyId = key.getKeyId();
|
||||
String token = parameters.importToken();
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(
|
||||
keyId, token, wrapped, "KEY_MATERIAL_EXPIRES", null, null, REGION));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void keyMaterialDoesNotExpireRejectsValidTo() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
KmsService.ImportParameters parameters =
|
||||
kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);
|
||||
byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));
|
||||
|
||||
String keyId = key.getKeyId();
|
||||
String token = parameters.importToken();
|
||||
long validTo = Instant.now().getEpochSecond() + 3600;
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(
|
||||
keyId, token, wrapped, "KEY_MATERIAL_DOES_NOT_EXPIRE", validTo, null, REGION));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingImportedMaterialReturnsTheKeyToPendingImport() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
importInto(key, material(32, (byte) 5), OAEP_SHA_256);
|
||||
|
||||
KmsKey deleted = kmsService.deleteImportedKeyMaterial(key.getKeyId(), REGION);
|
||||
|
||||
assertEquals("PendingImport", deleted.getKeyState());
|
||||
assertFalse(deleted.isEnabled());
|
||||
assertNull(deleted.getPrivateKeyEncoded());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reimportingTheSameMaterialRestoresTheKey() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
byte[] rawMaterial = material(32, (byte) 5);
|
||||
importInto(key, rawMaterial, OAEP_SHA_256);
|
||||
kmsService.deleteImportedKeyMaterial(key.getKeyId(), REGION);
|
||||
|
||||
KmsKey reimported = importInto(key, rawMaterial, OAEP_SHA_256);
|
||||
|
||||
assertEquals("Enabled", reimported.getKeyState());
|
||||
assertTrue(reimported.isEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reimportingDifferentMaterialIsRejected() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
importInto(key, material(32, (byte) 5), OAEP_SHA_256);
|
||||
kmsService.deleteImportedKeyMaterial(key.getKeyId(), REGION);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
importInto(key, material(32, (byte) 6), OAEP_SHA_256));
|
||||
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anHmacKeyMacsWithTheMaterialThatWasImported() throws Exception {
|
||||
KmsKey key = externalKey("HMAC_256", "GENERATE_VERIFY_MAC");
|
||||
byte[] rawMaterial = material(32, (byte) 42);
|
||||
byte[] message = "hello".getBytes(StandardCharsets.UTF_8);
|
||||
importInto(key, rawMaterial, OAEP_SHA_256);
|
||||
|
||||
byte[] mac = kmsService.generateMac(key.getKeyId(), message, "HMAC_SHA_256", REGION);
|
||||
|
||||
Mac expected = Mac.getInstance("HmacSHA256");
|
||||
expected.init(new SecretKeySpec(rawMaterial, "HmacSHA256"));
|
||||
assertArrayEquals(expected.doFinal(message), mac);
|
||||
}
|
||||
|
||||
@Test
|
||||
void macIsRejectedWhileTheHmacKeyHasNoMaterial() {
|
||||
String keyId = externalKey("HMAC_256", "GENERATE_VERIFY_MAC").getKeyId();
|
||||
byte[] message = "hello".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.generateMac(keyId, message, "HMAC_SHA_256", REGION));
|
||||
assertEquals("KMSInvalidStateException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancellingDeletionLeavesAKeyWithNoMaterialInPendingImport() {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);
|
||||
|
||||
kmsService.cancelKeyDeletion(key.getKeyId(), REGION);
|
||||
|
||||
KmsKey restored = kmsService.describeKey(key.getKeyId(), REGION);
|
||||
assertEquals("PendingImport", restored.getKeyState());
|
||||
assertFalse(restored.isEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancellingDeletionAfterTheMaterialWasDeletedKeepsTheKeyUnusable() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
importInto(key, material(32, (byte) 5), OAEP_SHA_256);
|
||||
kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);
|
||||
kmsService.deleteImportedKeyMaterial(key.getKeyId(), REGION);
|
||||
|
||||
kmsService.cancelKeyDeletion(key.getKeyId(), REGION);
|
||||
|
||||
String keyId = key.getKeyId();
|
||||
assertEquals("PendingImport", kmsService.describeKey(keyId, REGION).getKeyState());
|
||||
byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.encrypt(keyId, plaintext, REGION));
|
||||
assertEquals("KMSInvalidStateException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancellingDeletionRestoresAKeyThatStillHasItsMaterial() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
importInto(key, material(32, (byte) 5), OAEP_SHA_256);
|
||||
kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);
|
||||
|
||||
kmsService.cancelKeyDeletion(key.getKeyId(), REGION);
|
||||
|
||||
KmsKey restored = kmsService.describeKey(key.getKeyId(), REGION);
|
||||
assertEquals("Enabled", restored.getKeyState());
|
||||
assertTrue(restored.isEnabled());
|
||||
assertNotNull(kmsService.encrypt(key.getKeyId(), "hello".getBytes(StandardCharsets.UTF_8), REGION));
|
||||
}
|
||||
|
||||
/**
|
||||
* The AWS key state table marks DeleteImportedKeyMaterial as successful in the Pending
|
||||
* import column, so a key with nothing to delete is not an error.
|
||||
*/
|
||||
@Test
|
||||
void deletingMaterialFromAKeyThatHasNoneSucceeds() {
|
||||
String keyId = externalSymmetricKey().getKeyId();
|
||||
|
||||
KmsKey deleted = kmsService.deleteImportedKeyMaterial(keyId, REGION);
|
||||
|
||||
assertEquals("PendingImport", deleted.getKeyState());
|
||||
assertNull(deleted.getKeyMaterialId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void asymmetricKeySpecsCannotUseExternalOrigin() {
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
externalKey("RSA_2048", "ENCRYPT_DECRYPT"));
|
||||
assertEquals("UnsupportedOperationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void importIsRejectedOnAKeyWhoseMaterialKmsGenerated() {
|
||||
String keyId = kmsService.createKey("aws managed", REGION).getKeyId();
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.getParametersForImport(keyId, OAEP_SHA_256, "RSA_2048", REGION));
|
||||
assertEquals("UnsupportedOperationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void automaticRotationIsRejectedForImportedMaterial() throws Exception {
|
||||
KmsKey key = externalSymmetricKey();
|
||||
importInto(key, material(32, (byte) 5), OAEP_SHA_256);
|
||||
|
||||
String keyId = key.getKeyId();
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.enableKeyRotation(keyId, REGION));
|
||||
assertEquals("UnsupportedOperationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsupportedWrappingAlgorithmIsRejectedBeforeParametersAreIssued() {
|
||||
String keyId = externalSymmetricKey().getKeyId();
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.getParametersForImport(keyId, "RSA_AES_KEY_WRAP_SHA_256", "RSA_2048", REGION));
|
||||
assertEquals("UnsupportedOperationException", ex.getErrorCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user