mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(kms): reject mismatched keys in decryption requests (#1893)
* fix(kms): reject mismatched keys in decryption requests * fix(kms): reject mismatched keys in reencryption requests * fix(kms): verify if key is usable for cryptographic operations
This commit is contained in:
1 parent
15d6ce8429
commit
0cfffbea00
5 files changed
+632
-10
No files matched your search
@@ -196,3 +196,222 @@ teardown() {
|
||||
assert_failure
|
||||
[[ "$output" == *"ValidationException"* ]]
|
||||
}
|
||||
|
||||
# Issue #1844: Decrypt must enforce KeyId against wrapping key
|
||||
@test "KMS: decrypt with matching KeyId returns plaintext" {
|
||||
out=$(aws_cmd kms create-key --description "bats-1844-match")
|
||||
KEY_ID=$(json_get "$out" '.KeyMetadata.KeyId')
|
||||
|
||||
plaintext_file=$(mktemp)
|
||||
ciphertext_file=$(mktemp)
|
||||
echo -n "secret data" > "$plaintext_file"
|
||||
|
||||
run aws_cmd kms encrypt \
|
||||
--key-id "$KEY_ID" \
|
||||
--plaintext "fileb://$plaintext_file" \
|
||||
--output text \
|
||||
--query CiphertextBlob
|
||||
assert_success
|
||||
echo "$output" | base64 -d > "$ciphertext_file"
|
||||
|
||||
run aws_cmd kms decrypt \
|
||||
--ciphertext-blob "fileb://$ciphertext_file" \
|
||||
--key-id "$KEY_ID" \
|
||||
--output text \
|
||||
--query Plaintext
|
||||
assert_success
|
||||
[ "$(echo "$output" | base64 -d)" = "secret data" ]
|
||||
|
||||
rm -f "$plaintext_file" "$ciphertext_file"
|
||||
}
|
||||
|
||||
@test "KMS: decrypt with mismatched KeyId returns IncorrectKeyException" {
|
||||
out_a=$(aws_cmd kms create-key --description "bats-1844-a")
|
||||
key_a=$(json_get "$out_a" '.KeyMetadata.KeyId')
|
||||
out_b=$(aws_cmd kms create-key --description "bats-1844-b")
|
||||
key_b=$(json_get "$out_b" '.KeyMetadata.KeyId')
|
||||
|
||||
plaintext_file=$(mktemp)
|
||||
ciphertext_file=$(mktemp)
|
||||
echo -n "secret data" > "$plaintext_file"
|
||||
|
||||
run aws_cmd kms encrypt \
|
||||
--key-id "$key_a" \
|
||||
--plaintext "fileb://$plaintext_file" \
|
||||
--output text \
|
||||
--query CiphertextBlob
|
||||
assert_success
|
||||
echo "$output" | base64 -d > "$ciphertext_file"
|
||||
|
||||
run aws_cmd kms decrypt \
|
||||
--ciphertext-blob "fileb://$ciphertext_file" \
|
||||
--key-id "$key_b"
|
||||
assert_failure
|
||||
[[ "$output" == *"IncorrectKeyException"* ]]
|
||||
|
||||
rm -f "$plaintext_file" "$ciphertext_file"
|
||||
aws_cmd kms schedule-key-deletion --key-id "$key_a" --pending-window-in-days 7 >/dev/null 2>&1 || true
|
||||
aws_cmd kms schedule-key-deletion --key-id "$key_b" --pending-window-in-days 7 >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
@test "KMS: reencrypt with matching SourceKeyId re-wraps ciphertext" {
|
||||
out_a=$(aws_cmd kms create-key --description "bats-reencrypt-match-a")
|
||||
key_a=$(json_get "$out_a" '.KeyMetadata.KeyId')
|
||||
out_b=$(aws_cmd kms create-key --description "bats-reencrypt-match-b")
|
||||
key_b=$(json_get "$out_b" '.KeyMetadata.KeyId')
|
||||
|
||||
plaintext_file=$(mktemp)
|
||||
ciphertext_file=$(mktemp)
|
||||
reencrypted_file=$(mktemp)
|
||||
decrypted_file=$(mktemp)
|
||||
echo -n "reencrypt test data" > "$plaintext_file"
|
||||
|
||||
run aws_cmd kms encrypt \
|
||||
--key-id "$key_a" \
|
||||
--plaintext "fileb://$plaintext_file" \
|
||||
--output text \
|
||||
--query CiphertextBlob
|
||||
assert_success
|
||||
echo "$output" | base64 -d > "$ciphertext_file"
|
||||
|
||||
run aws_cmd kms re-encrypt \
|
||||
--ciphertext-blob "fileb://$ciphertext_file" \
|
||||
--source-key-id "$key_a" \
|
||||
--destination-key-id "$key_b" \
|
||||
--output text \
|
||||
--query CiphertextBlob
|
||||
assert_success
|
||||
echo "$output" | base64 -d > "$reencrypted_file"
|
||||
|
||||
run aws_cmd kms decrypt \
|
||||
--ciphertext-blob "fileb://$reencrypted_file" \
|
||||
--output text \
|
||||
--query Plaintext
|
||||
assert_success
|
||||
echo "$output" | base64 -d > "$decrypted_file"
|
||||
[ "$(cat "$decrypted_file")" = "reencrypt test data" ]
|
||||
|
||||
rm -f "$plaintext_file" "$ciphertext_file" "$reencrypted_file" "$decrypted_file"
|
||||
aws_cmd kms schedule-key-deletion --key-id "$key_a" --pending-window-in-days 7 >/dev/null 2>&1 || true
|
||||
aws_cmd kms schedule-key-deletion --key-id "$key_b" --pending-window-in-days 7 >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
@test "KMS: reencrypt with mismatched SourceKeyId returns IncorrectKeyException" {
|
||||
out_a=$(aws_cmd kms create-key --description "bats-reencrypt-mismatch-a")
|
||||
key_a=$(json_get "$out_a" '.KeyMetadata.KeyId')
|
||||
out_b=$(aws_cmd kms create-key --description "bats-reencrypt-mismatch-b")
|
||||
key_b=$(json_get "$out_b" '.KeyMetadata.KeyId')
|
||||
|
||||
plaintext_file=$(mktemp)
|
||||
ciphertext_file=$(mktemp)
|
||||
echo -n "reencrypt test data" > "$plaintext_file"
|
||||
|
||||
run aws_cmd kms encrypt \
|
||||
--key-id "$key_a" \
|
||||
--plaintext "fileb://$plaintext_file" \
|
||||
--output text \
|
||||
--query CiphertextBlob
|
||||
assert_success
|
||||
echo "$output" | base64 -d > "$ciphertext_file"
|
||||
|
||||
run aws_cmd kms re-encrypt \
|
||||
--ciphertext-blob "fileb://$ciphertext_file" \
|
||||
--source-key-id "$key_b" \
|
||||
--destination-key-id "$key_a"
|
||||
assert_failure
|
||||
[[ "$output" == *"IncorrectKeyException"* ]]
|
||||
|
||||
rm -f "$plaintext_file" "$ciphertext_file"
|
||||
aws_cmd kms schedule-key-deletion --key-id "$key_a" --pending-window-in-days 7 >/dev/null 2>&1 || true
|
||||
aws_cmd kms schedule-key-deletion --key-id "$key_b" --pending-window-in-days 7 >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
@test "KMS: decrypt with disabled key returns DisabledException" {
|
||||
out=$(aws_cmd kms create-key --description "bats-disabled-decrypt")
|
||||
KEY_ID=$(json_get "$out" '.KeyMetadata.KeyId')
|
||||
|
||||
plaintext_file=$(mktemp)
|
||||
ciphertext_file=$(mktemp)
|
||||
echo -n "secret data" > "$plaintext_file"
|
||||
|
||||
run aws_cmd kms encrypt \
|
||||
--key-id "$KEY_ID" \
|
||||
--plaintext "fileb://$plaintext_file" \
|
||||
--output text \
|
||||
--query CiphertextBlob
|
||||
assert_success
|
||||
echo "$output" | base64 -d > "$ciphertext_file"
|
||||
|
||||
run aws_cmd kms disable-key --key-id "$KEY_ID"
|
||||
assert_success
|
||||
|
||||
run aws_cmd kms decrypt \
|
||||
--ciphertext-blob "fileb://$ciphertext_file" \
|
||||
--key-id "$KEY_ID"
|
||||
assert_failure
|
||||
[[ "$output" == *"DisabledException"* ]]
|
||||
|
||||
rm -f "$plaintext_file" "$ciphertext_file"
|
||||
}
|
||||
|
||||
@test "KMS: encrypt with disabled key returns DisabledException" {
|
||||
out=$(aws_cmd kms create-key --description "bats-disabled-encrypt")
|
||||
KEY_ID=$(json_get "$out" '.KeyMetadata.KeyId')
|
||||
|
||||
run aws_cmd kms disable-key --key-id "$KEY_ID"
|
||||
assert_success
|
||||
|
||||
plaintext_file=$(mktemp)
|
||||
echo -n "secret data" > "$plaintext_file"
|
||||
|
||||
run aws_cmd kms encrypt --key-id "$KEY_ID" --plaintext "fileb://$plaintext_file"
|
||||
assert_failure
|
||||
[[ "$output" == *"DisabledException"* ]]
|
||||
|
||||
rm -f "$plaintext_file"
|
||||
}
|
||||
|
||||
@test "KMS: decrypt with pending deletion key returns KmsInvalidStateException" {
|
||||
out=$(aws_cmd kms create-key --description "bats-pending-decrypt")
|
||||
KEY_ID=$(json_get "$out" '.KeyMetadata.KeyId')
|
||||
|
||||
plaintext_file=$(mktemp)
|
||||
ciphertext_file=$(mktemp)
|
||||
echo -n "secret data" > "$plaintext_file"
|
||||
|
||||
run aws_cmd kms encrypt \
|
||||
--key-id "$KEY_ID" \
|
||||
--plaintext "fileb://$plaintext_file" \
|
||||
--output text \
|
||||
--query CiphertextBlob
|
||||
assert_success
|
||||
echo "$output" | base64 -d > "$ciphertext_file"
|
||||
|
||||
run aws_cmd kms schedule-key-deletion --key-id "$KEY_ID" --pending-window-in-days 7
|
||||
assert_success
|
||||
|
||||
run aws_cmd kms decrypt \
|
||||
--ciphertext-blob "fileb://$ciphertext_file" \
|
||||
--key-id "$KEY_ID"
|
||||
assert_failure
|
||||
[[ "$output" == *"KMSInvalidStateException"* ]]
|
||||
|
||||
rm -f "$plaintext_file" "$ciphertext_file"
|
||||
}
|
||||
|
||||
@test "KMS: encrypt with pending deletion key returns KmsInvalidStateException" {
|
||||
out=$(aws_cmd kms create-key --description "bats-pending-encrypt")
|
||||
KEY_ID=$(json_get "$out" '.KeyMetadata.KeyId')
|
||||
|
||||
run aws_cmd kms schedule-key-deletion --key-id "$KEY_ID" --pending-window-in-days 7
|
||||
assert_success
|
||||
|
||||
plaintext_file=$(mktemp)
|
||||
echo -n "secret data" > "$plaintext_file"
|
||||
|
||||
run aws_cmd kms encrypt --key-id "$KEY_ID" --plaintext "fileb://$plaintext_file"
|
||||
assert_failure
|
||||
[[ "$output" == *"KMSInvalidStateException"* ]]
|
||||
|
||||
rm -f "$plaintext_file"
|
||||
}
|
||||
+184
-1
@@ -1,12 +1,17 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.kms.KmsClient;
|
||||
import software.amazon.awssdk.services.kms.model.CreateKeyResponse;
|
||||
import software.amazon.awssdk.services.kms.model.DisabledException;
|
||||
import software.amazon.awssdk.services.kms.model.EncryptionAlgorithmSpec;
|
||||
import software.amazon.awssdk.services.kms.model.GetKeyPolicyResponse;
|
||||
import software.amazon.awssdk.services.kms.model.IncorrectKeyException;
|
||||
import software.amazon.awssdk.services.kms.model.KmsInvalidStateException;
|
||||
import software.amazon.awssdk.services.kms.model.ListResourceTagsResponse;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
@@ -17,8 +22,10 @@ import static org.assertj.core.api.Assertions.*;
|
||||
* #258 — GetKeyPolicy returns the stored policy
|
||||
* #259 — PutKeyPolicy updates the key policy
|
||||
* #DescribeKey — Returns proper EncryptionAlgorithms, SigningAlgorithms, and MacAlgorithms
|
||||
* #1844 — Decrypt enforces KeyId against the wrapping CMK (IncorrectKeyException)
|
||||
* #1844 — ReEncrypt enforces SourceKeyId against the wrapping CMK (IncorrectKeyException)
|
||||
*/
|
||||
@DisplayName("KMS features (#258 #259 #269)")
|
||||
@DisplayName("KMS features (#258 #259 #269 #1844)")
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class KmsFeaturesTest {
|
||||
|
||||
@@ -201,4 +208,180 @@ class KmsFeaturesTest {
|
||||
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
}
|
||||
|
||||
// ── Issue #1844: Decrypt enforces KeyId against the wrapping key ────────
|
||||
@Test
|
||||
@Order(50)
|
||||
void decryptWithMatchingKeyIdReturnsPlaintext() {
|
||||
String keyId = kms.createKey(b -> b.description("issue-1844-match")).keyMetadata().keyId();
|
||||
|
||||
try {
|
||||
SdkBytes ciphertext = kms.encrypt(b -> b
|
||||
.keyId(keyId)
|
||||
.plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))
|
||||
.ciphertextBlob();
|
||||
|
||||
SdkBytes plaintext = kms.decrypt(b -> b
|
||||
.ciphertextBlob(ciphertext)
|
||||
.keyId(keyId))
|
||||
.plaintext();
|
||||
|
||||
assertThat(plaintext.asUtf8String()).isEqualTo("secret data");
|
||||
} finally {
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(51)
|
||||
void decryptWithMismatchedKeyIdRaisesIncorrectKeyException() {
|
||||
String keyIdA = kms.createKey(b -> b.description("issue-1844-a")).keyMetadata().keyId();
|
||||
String keyIdB = kms.createKey(b -> b.description("issue-1844-b")).keyMetadata().keyId();
|
||||
|
||||
try {
|
||||
SdkBytes ciphertext = kms.encrypt(b -> b
|
||||
.keyId(keyIdA)
|
||||
.plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))
|
||||
.ciphertextBlob();
|
||||
|
||||
assertThatThrownBy(() -> kms.decrypt(b -> b
|
||||
.ciphertextBlob(ciphertext)
|
||||
.keyId(keyIdB)))
|
||||
.isInstanceOf(IncorrectKeyException.class);
|
||||
} finally {
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyIdA).pendingWindowInDays(7));
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyIdB).pendingWindowInDays(7));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(52)
|
||||
void reEncryptWithMatchingSourceKeyIdReturnsNewCiphertext() {
|
||||
String keyIdA = kms.createKey(b -> b.description("reencrypt-match-a")).keyMetadata().keyId();
|
||||
String keyIdB = kms.createKey(b -> b.description("reencrypt-match-b")).keyMetadata().keyId();
|
||||
|
||||
try {
|
||||
SdkBytes ciphertext = kms.encrypt(b -> b
|
||||
.keyId(keyIdA)
|
||||
.plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))
|
||||
.ciphertextBlob();
|
||||
|
||||
SdkBytes reEncrypted = kms.reEncrypt(b -> b
|
||||
.ciphertextBlob(ciphertext)
|
||||
.sourceKeyId(keyIdA)
|
||||
.destinationKeyId(keyIdB))
|
||||
.ciphertextBlob();
|
||||
|
||||
SdkBytes plaintext = kms.decrypt(b -> b.ciphertextBlob(reEncrypted)).plaintext();
|
||||
assertThat(plaintext.asUtf8String()).isEqualTo("secret data");
|
||||
} finally {
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyIdA).pendingWindowInDays(7));
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyIdB).pendingWindowInDays(7));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(53)
|
||||
void reEncryptWithMismatchedSourceKeyIdRaisesIncorrectKeyException() {
|
||||
String keyIdA = kms.createKey(b -> b.description("reencrypt-mismatch-a")).keyMetadata().keyId();
|
||||
String keyIdB = kms.createKey(b -> b.description("reencrypt-mismatch-b")).keyMetadata().keyId();
|
||||
|
||||
try {
|
||||
SdkBytes ciphertext = kms.encrypt(b -> b
|
||||
.keyId(keyIdA)
|
||||
.plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))
|
||||
.ciphertextBlob();
|
||||
|
||||
assertThatThrownBy(() -> kms.reEncrypt(b -> b
|
||||
.ciphertextBlob(ciphertext)
|
||||
.sourceKeyId(keyIdB)
|
||||
.destinationKeyId(keyIdA)))
|
||||
.isInstanceOf(IncorrectKeyException.class);
|
||||
} finally {
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyIdA).pendingWindowInDays(7));
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyIdB).pendingWindowInDays(7));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(60)
|
||||
void encryptWithDisabledKeyRaisesDisabledException() {
|
||||
String keyId = kms.createKey(b -> b.description("disabled-encrypt")).keyMetadata().keyId();
|
||||
|
||||
try {
|
||||
kms.disableKey(b -> b.keyId(keyId));
|
||||
|
||||
assertThatThrownBy(
|
||||
() -> kms.encrypt(b -> b
|
||||
.keyId(keyId)
|
||||
.plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))
|
||||
).isInstanceOf(DisabledException.class);
|
||||
} finally {
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(61)
|
||||
void decryptWithDisabledKeyRaisesDisabledException() {
|
||||
String keyId = kms.createKey(b -> b.description("disabled-decrypt")).keyMetadata().keyId();
|
||||
|
||||
try {
|
||||
SdkBytes ciphertext = kms.encrypt(b -> b
|
||||
.keyId(keyId)
|
||||
.plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))
|
||||
.ciphertextBlob();
|
||||
|
||||
kms.disableKey(b -> b.keyId(keyId));
|
||||
|
||||
assertThatThrownBy(
|
||||
() -> kms.decrypt(b -> b
|
||||
.ciphertextBlob(ciphertext)
|
||||
.keyId(keyId))
|
||||
).isInstanceOf(DisabledException.class);
|
||||
} finally {
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(62)
|
||||
void encryptWithPendingDeletionKeyRaisesKmsInvalidStateException() {
|
||||
String keyId = kms.createKey(b -> b.description("pending-encrypt")).keyMetadata().keyId();
|
||||
|
||||
try {
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
|
||||
assertThatThrownBy(
|
||||
() -> kms.encrypt(b -> b
|
||||
.keyId(keyId)
|
||||
.plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))
|
||||
).isInstanceOf(KmsInvalidStateException.class);
|
||||
} finally {
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(63)
|
||||
void decryptWithPendingDeletionKeyRaisesKmsInvalidStateException() {
|
||||
String keyId = kms.createKey(b -> b.description("pending-decrypt")).keyMetadata().keyId();
|
||||
|
||||
try {
|
||||
SdkBytes ciphertext = kms.encrypt(b -> b
|
||||
.keyId(keyId)
|
||||
.plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))
|
||||
.ciphertextBlob();
|
||||
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
|
||||
assertThatThrownBy(
|
||||
() -> kms.decrypt(b -> b
|
||||
.ciphertextBlob(ciphertext)
|
||||
.keyId(keyId))
|
||||
).isInstanceOf(KmsInvalidStateException.class);
|
||||
} finally {
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -261,7 +261,9 @@ public class KmsJsonHandler {
|
||||
private Response handleDecrypt(JsonNode request, String region) {
|
||||
byte[] ciphertext = decodeBlob(request, "CiphertextBlob");
|
||||
Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));
|
||||
KmsService.DecryptResult result = service.decryptAndResolveKey(ciphertext, context, region);
|
||||
String requestKeyId = request.path("KeyId").asText(null);
|
||||
|
||||
KmsService.DecryptResult result = service.decryptAndResolveKey(ciphertext, context, region, requestKeyId);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("Plaintext", Base64.getEncoder().encodeToString(result.plaintext()));
|
||||
@@ -306,7 +308,8 @@ public class KmsJsonHandler {
|
||||
Map<String, String> sourceContext = readEncryptionContext(request.path("SourceEncryptionContext"));
|
||||
Map<String, String> destContext = readEncryptionContext(request.path("DestinationEncryptionContext"));
|
||||
|
||||
KmsService.DecryptResult source = service.decryptAndResolveKey(ciphertext, sourceContext, region);
|
||||
String sourceKeyId = request.path("SourceKeyId").asText(null);
|
||||
KmsService.DecryptResult source = service.decryptAndResolveKey(ciphertext, sourceContext, region, sourceKeyId);
|
||||
byte[] newCiphertext = service.encrypt(destKeyId, source.plaintext(), destContext, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
|
||||
@@ -649,6 +649,7 @@ public class KmsService {
|
||||
|
||||
public byte[] encrypt(String keyId, byte[] plaintext, Map<String, String> encryptionContext, String region) {
|
||||
KmsKey kmsKey = resolveKey(keyId, region);
|
||||
validateKeyIsUsableForCryptoOperations(kmsKey);
|
||||
|
||||
byte[] nonceBytes = new byte[NONCE_BYTES];
|
||||
SECURE_RANDOM.nextBytes(nonceBytes);
|
||||
@@ -686,19 +687,43 @@ public class KmsService {
|
||||
* Single-pass decrypt + source-key-ARN resolution. {@link #decrypt} and
|
||||
* {@link #decryptToKeyArn} remain independent primitives — neither delegates here.
|
||||
*/
|
||||
public DecryptResult decryptAndResolveKey(byte[] ciphertext, Map<String, String> encryptionContext, String region) {
|
||||
public DecryptResult decryptAndResolveKey(
|
||||
byte[] ciphertext,
|
||||
Map<String, String> encryptionContext,
|
||||
String region,
|
||||
String requestKeyId
|
||||
) {
|
||||
ParsedBlob parsed = parseBlob(ciphertext);
|
||||
if (!parsed.contextFingerprint.equals(contextFingerprint(encryptionContext))) {
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
}
|
||||
byte[] plaintext = Base64.getDecoder().decode(parsed.payload);
|
||||
String keyArn;
|
||||
try {
|
||||
keyArn = resolveKey(parsed.keyId, region).getArn();
|
||||
} catch (AwsException e) {
|
||||
keyArn = null;
|
||||
|
||||
if (requestKeyId != null && !requestKeyId.isBlank()) {
|
||||
KmsKey requestKey = resolveKey(requestKeyId, region);
|
||||
if (!requestKey.getKeyId().equals(parsed.keyId)) {
|
||||
throw new AwsException(
|
||||
"IncorrectKeyException",
|
||||
"The request was rejected because the specified KMS key cannot decrypt the data.",
|
||||
400
|
||||
);
|
||||
}
|
||||
validateKeyIsUsableForCryptoOperations(requestKey);
|
||||
|
||||
return new DecryptResult(plaintext, requestKey.getArn());
|
||||
}
|
||||
return new DecryptResult(plaintext, keyArn);
|
||||
|
||||
KmsKey key;
|
||||
try {
|
||||
key = resolveKey(parsed.keyId, region);
|
||||
} catch (AwsException e) {
|
||||
key = null;
|
||||
}
|
||||
if (key == null) {
|
||||
return new DecryptResult(plaintext, null);
|
||||
}
|
||||
validateKeyIsUsableForCryptoOperations(key);
|
||||
return new DecryptResult(plaintext, key.getArn());
|
||||
}
|
||||
|
||||
public record DecryptResult(byte[] plaintext, String keyArn) {}
|
||||
@@ -1091,4 +1116,22 @@ public class KmsService {
|
||||
return keyStore.get(region + "::" + id)
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Key not found: " + keyIdOrArn, 404));
|
||||
}
|
||||
|
||||
private static void validateKeyIsUsableForCryptoOperations(KmsKey key) {
|
||||
if ("PendingDeletion".equals(key.getKeyState())) {
|
||||
throw new AwsException(
|
||||
"KMSInvalidStateException",
|
||||
"KMS key " + key.getKeyId() + " is pending deletion.",
|
||||
400
|
||||
);
|
||||
}
|
||||
if (!key.isEnabled()) {
|
||||
throw new AwsException(
|
||||
"DisabledException",
|
||||
"The request was rejected because the specified KMS key is not enabled.",
|
||||
400
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.kms.model.KmsMessageType;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -631,6 +632,179 @@ class KmsServiceTest {
|
||||
kmsService.decrypt("not-valid-ciphertext".getBytes(StandardCharsets.UTF_8), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void encryptWithDisabledKeyThrowsDisabledException() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
kmsService.disableKey(key.getKeyId(), REGION);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.encrypt(key.getKeyId(), "hello".getBytes(StandardCharsets.UTF_8), REGION));
|
||||
|
||||
assertEquals("DisabledException", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void encryptWithPendingDeletionKeyThrowsKmsInvalidStateException() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.encrypt(key.getKeyId(), "hello".getBytes(StandardCharsets.UTF_8), REGION));
|
||||
|
||||
assertEquals("KMSInvalidStateException", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Nested
|
||||
class DecryptAndReEncryptTests {
|
||||
|
||||
@Test
|
||||
void decryptAndResolveKeyWithMatchingKeyIdSucceeds() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] ciphertext = kmsService.encrypt(key.getKeyId(), plaintext, REGION);
|
||||
|
||||
KmsService.DecryptResult result = kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, key.getKeyId());
|
||||
|
||||
assertArrayEquals(plaintext, result.plaintext());
|
||||
assertEquals(key.getArn(), result.keyArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decryptAndResolveKeyWithMismatchedKeyIdThrowsIncorrectKeyException() {
|
||||
KmsKey keyA = kmsService.createKey(null, REGION);
|
||||
KmsKey keyB = kmsService.createKey(null, REGION);
|
||||
byte[] ciphertext = kmsService.encrypt(keyA.getKeyId(), "hello".getBytes(StandardCharsets.UTF_8), REGION);
|
||||
|
||||
AwsException ex = assertThrows(
|
||||
AwsException.class,
|
||||
() -> kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, keyB.getKeyId())
|
||||
);
|
||||
|
||||
assertEquals("IncorrectKeyException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decryptAndResolveKeyWithMismatchedAliasKeyIdThrowsIncorrectKeyException() {
|
||||
KmsKey keyA = kmsService.createKey(null, REGION);
|
||||
KmsKey keyB = kmsService.createKey(null, REGION);
|
||||
String aliasB = "alias/other-key";
|
||||
kmsService.createAlias(aliasB, keyB.getKeyId(), REGION);
|
||||
byte[] ciphertext = kmsService.encrypt(keyA.getKeyId(), "hello".getBytes(StandardCharsets.UTF_8), REGION);
|
||||
|
||||
AwsException ex = assertThrows(
|
||||
AwsException.class,
|
||||
() -> kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, aliasB)
|
||||
);
|
||||
|
||||
assertEquals("IncorrectKeyException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decryptAndResolveKeyWithMatchingAliasKeyIdSucceeds() {
|
||||
KmsKey keyA = kmsService.createKey(null, REGION);
|
||||
String aliasA = "alias/my-alias";
|
||||
kmsService.createAlias(aliasA, keyA.getKeyId(), REGION);
|
||||
byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] ciphertext = kmsService.encrypt(keyA.getKeyId(), plaintext, REGION);
|
||||
|
||||
KmsService.DecryptResult result = kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, aliasA);
|
||||
|
||||
assertArrayEquals(plaintext, result.plaintext());
|
||||
assertEquals(keyA.getArn(), result.keyArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decryptAndResolveKeyWithNullKeyIdBehavesAsSelfDescribing() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] ciphertext = kmsService.encrypt(key.getKeyId(), plaintext, REGION);
|
||||
|
||||
KmsService.DecryptResult result = kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, null);
|
||||
|
||||
assertArrayEquals(plaintext, result.plaintext());
|
||||
assertEquals(key.getArn(), result.keyArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decryptAndResolveKeyWithDisabledKeyThrowsDisabledException() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
byte[] ciphertext = kmsService.encrypt(key.getKeyId(),
|
||||
"hello".getBytes(StandardCharsets.UTF_8), REGION);
|
||||
kmsService.disableKey(key.getKeyId(), REGION);
|
||||
|
||||
AwsException ex = assertThrows(
|
||||
AwsException.class,
|
||||
() -> kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, key.getKeyId())
|
||||
);
|
||||
|
||||
assertEquals("DisabledException", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decryptAndResolveKeyWithPendingDeletionKeyThrowsKmsInvalidStateException() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
byte[] ciphertext = kmsService.encrypt(key.getKeyId(),
|
||||
"hello".getBytes(StandardCharsets.UTF_8), REGION);
|
||||
kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);
|
||||
|
||||
AwsException ex = assertThrows(
|
||||
AwsException.class,
|
||||
() -> kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, key.getKeyId())
|
||||
);
|
||||
|
||||
assertEquals("KMSInvalidStateException", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decryptAndResolveKeySelfDescribingWithDisabledKeyThrowsDisabledException() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
byte[] ciphertext = kmsService.encrypt(key.getKeyId(),
|
||||
"hello".getBytes(StandardCharsets.UTF_8), REGION);
|
||||
kmsService.disableKey(key.getKeyId(), REGION);
|
||||
|
||||
AwsException ex = assertThrows(
|
||||
AwsException.class,
|
||||
() -> kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, null)
|
||||
);
|
||||
|
||||
assertEquals("DisabledException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decryptAndResolveKeySelfDescribingWithPendingDeletionKeyThrowsKmsInvalidStateException() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
byte[] ciphertext = kmsService.encrypt(key.getKeyId(),
|
||||
"hello".getBytes(StandardCharsets.UTF_8), REGION);
|
||||
kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);
|
||||
|
||||
AwsException ex = assertThrows(
|
||||
AwsException.class,
|
||||
() -> kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, null)
|
||||
);
|
||||
|
||||
assertEquals("KMSInvalidStateException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reEncryptSourceKeyIdMismatchThrowsIncorrectKeyException() {
|
||||
KmsKey sourceKey = kmsService.createKey(null, REGION);
|
||||
KmsKey wrongKey = kmsService.createKey(null, REGION);
|
||||
byte[] ciphertext = kmsService.encrypt(sourceKey.getKeyId(),
|
||||
"hello".getBytes(StandardCharsets.UTF_8), REGION);
|
||||
|
||||
AwsException ex = assertThrows(
|
||||
AwsException.class,
|
||||
() -> kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, wrongKey.getKeyId())
|
||||
);
|
||||
|
||||
assertEquals("IncorrectKeyException", ex.getErrorCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void encryptIsNonDeterministic() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
|
||||
Reference in new issue
Block a user