Light, fluffy, and always free - The AWS Local Emulator alternative
fix(kms): non-deterministic Encrypt and EncryptionContext AAD validation (#825)
Ahmed Soliman6a8c44fad524
diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.javaindex 2616f683a2..60e9d9ea0c 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java@@ -139,7 +139,8 @@ public class KmsJsonHandler {private Response handleEncrypt(JsonNode request, String region) {String keyId = request.path("KeyId").asText();byte[] plaintext = Base64.getDecoder().decode(request.path("Plaintext").asText());- byte[] ciphertext = service.encrypt(keyId, plaintext, region);+ Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));+ byte[] ciphertext = service.encrypt(keyId, plaintext, context, region);ObjectNode response = objectMapper.createObjectNode();response.put("CiphertextBlob", Base64.getEncoder().encodeToString(ciphertext));@@ -149,16 +150,13 @@ public class KmsJsonHandler {private Response handleDecrypt(JsonNode request, String region) {byte[] ciphertext = Base64.getDecoder().decode(request.path("CiphertextBlob").asText());- byte[] plaintext = service.decrypt(ciphertext, region);+ Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));+ KmsService.DecryptResult result = service.decryptAndResolveKey(ciphertext, context, region);ObjectNode response = objectMapper.createObjectNode();- response.put("Plaintext", Base64.getEncoder().encodeToString(plaintext));- // In our mock, we don't strictly track which key was used for decryption from blob alone,- // but we could extract it from our mock format "kms:keyId:..."- String data = new String(ciphertext);- if (data.startsWith("kms:")) {- String keyId = data.split(":")[1];- response.put("KeyId", service.describeKey(keyId, region).getArn());+ response.put("Plaintext", Base64.getEncoder().encodeToString(result.plaintext()));+ if (result.keyArn() != null) {+ response.put("KeyId", result.keyArn());}return Response.ok(response).build();}@@ -167,8 +165,9 @@ public class KmsJsonHandler {String keyId = request.path("KeyId").asText();String spec = request.path("KeySpec").asText(null);int numberOfBytes = request.path("NumberOfBytes").asInt(0);+ Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));- Map<String, Object> result = service.generateDataKey(keyId, spec, numberOfBytes, region);+ Map<String, Object> result = service.generateDataKey(keyId, spec, numberOfBytes, context, region);ObjectNode response = objectMapper.createObjectNode();response.put("Plaintext", Base64.getEncoder().encodeToString((byte[]) result.get("Plaintext")));@@ -181,8 +180,9 @@ public class KmsJsonHandler {String keyId = request.path("KeyId").asText();String spec = request.path("KeySpec").asText(null);int numberOfBytes = request.path("NumberOfBytes").asInt(0);+ Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));- Map<String, Object> result = service.generateDataKey(keyId, spec, numberOfBytes, region);+ Map<String, Object> result = service.generateDataKey(keyId, spec, numberOfBytes, context, region);ObjectNode response = objectMapper.createObjectNode();response.put("CiphertextBlob", Base64.getEncoder().encodeToString((byte[]) result.get("CiphertextBlob")));@@ -193,17 +193,28 @@ public class KmsJsonHandler {private Response handleReEncrypt(JsonNode request, String region) {byte[] ciphertext = Base64.getDecoder().decode(request.path("CiphertextBlob").asText());String destKeyId = request.path("DestinationKeyId").asText();+ Map<String, String> sourceContext = readEncryptionContext(request.path("SourceEncryptionContext"));+ Map<String, String> destContext = readEncryptionContext(request.path("DestinationEncryptionContext"));- byte[] plaintext = service.decrypt(ciphertext, region);- byte[] newCiphertext = service.encrypt(destKeyId, plaintext, region);+ KmsService.DecryptResult source = service.decryptAndResolveKey(ciphertext, sourceContext, region);+ byte[] newCiphertext = service.encrypt(destKeyId, source.plaintext(), destContext, region);ObjectNode response = objectMapper.createObjectNode();response.put("CiphertextBlob", Base64.getEncoder().encodeToString(newCiphertext));response.put("KeyId", service.describeKey(destKeyId, region).getArn());- response.put("SourceKeyId", service.decryptToKeyArn(ciphertext, region));+ response.put("SourceKeyId", source.keyArn());return Response.ok(response).build();}+ private static Map<String, String> readEncryptionContext(JsonNode node) {+ if (node == null || node.isMissingNode() || node.isNull() || !node.isObject()) {+ return Map.of();+ }+ Map<String, String> result = new HashMap<>();+ node.fields().forEachRemaining(e -> result.put(e.getKey(), e.getValue().asText()));+ return result;+ }+private Response handleSign(JsonNode request, String region) {String keyId = request.path("KeyId").asText();byte[] message = Base64.getDecoder().decode(request.path("Message").asText());diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.javaindex 5757cabc12..89cf89ec9a 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java@@ -32,6 +32,7 @@ import org.jboss.logging.Logger;import java.io.ByteArrayOutputStream;import java.math.BigInteger;+import java.nio.ByteBuffer;import java.nio.charset.StandardCharsets;import java.security.*;import java.security.spec.*;@@ -326,31 +327,121 @@ public class KmsService {// ──────────────────────────── Crypto Ops (Mocks) ────────────────────────────+ // v2 blob: kms:v2:<keyId>:<nonceHex>:<contextFingerprintHex>:<base64(plaintext)>+ // Nonce makes Encrypt non-deterministic; contextFingerprint binds EncryptionContext as AAD.+ // Legacy v1 (kms:<keyId>:<base64>) still accepted on Decrypt for persistent-store back-compat.+ private static final String BLOB_PREFIX_V2 = "kms:v2:";+ private static final String BLOB_PREFIX_V1 = "kms:";+ private static final int NONCE_BYTES = 8;+ private static final SecureRandom SECURE_RANDOM = new SecureRandom();+public byte[] encrypt(String keyId, byte[] plaintext, String region) {+ return encrypt(keyId, plaintext, Map.of(), region);+ }++ public byte[] encrypt(String keyId, byte[] plaintext, Map<String, String> encryptionContext, String region) {KmsKey kmsKey = resolveKey(keyId, region);- // Local mock: prefix with keyId and base64- String mock = "kms:" + kmsKey.getKeyId() + ":" + Base64.getEncoder().encodeToString(plaintext);- return mock.getBytes(StandardCharsets.UTF_8);++ byte[] nonceBytes = new byte[NONCE_BYTES];+ SECURE_RANDOM.nextBytes(nonceBytes);+ String nonceHex = HexFormat.of().formatHex(nonceBytes);++ String blob = BLOB_PREFIX_V2+ + kmsKey.getKeyId() + ":"+ + nonceHex + ":"+ + contextFingerprint(encryptionContext) + ":"+ + Base64.getEncoder().encodeToString(plaintext);+ return blob.getBytes(StandardCharsets.UTF_8);}public byte[] decrypt(byte[] ciphertext, String region) {- String data = new String(ciphertext, StandardCharsets.UTF_8);- if (!data.startsWith("kms:")) {+ return decrypt(ciphertext, Map.of(), region);+ }++ public byte[] decrypt(byte[] ciphertext, Map<String, String> encryptionContext, String region) {+ ParsedBlob parsed = parseBlob(ciphertext);+ if (!parsed.contextFingerprint.equals(contextFingerprint(encryptionContext))) {throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);}- String[] parts = data.split(":", 3);- if (parts.length < 3) throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);-- return Base64.getDecoder().decode(parts[2]);+ return Base64.getDecoder().decode(parsed.payload);}public String decryptToKeyArn(byte[] ciphertext, String region) {+ try {+ return resolveKey(parseBlob(ciphertext).keyId, region).getArn();+ } catch (AwsException e) {+ return null;+ }+ }++ /**+ * 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) {+ 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;+ }+ return new DecryptResult(plaintext, keyArn);+ }++ public record DecryptResult(byte[] plaintext, String keyArn) {}++ private record ParsedBlob(String keyId, String nonce, String contextFingerprint, String payload) {}++ private static ParsedBlob parseBlob(byte[] ciphertext) {String data = new String(ciphertext, StandardCharsets.UTF_8);- if (data.startsWith("kms:")) {- String keyId = data.split(":")[1];- return resolveKey(keyId, region).getArn();+ if (data.startsWith(BLOB_PREFIX_V2)) {+ // v2: keyId, nonce, contextFingerprint, payload+ String[] parts = data.substring(BLOB_PREFIX_V2.length()).split(":", 4);+ if (parts.length < 4) {+ throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ }+ return new ParsedBlob(parts[0], parts[1], parts[2], parts[3]);+ }+ if (data.startsWith(BLOB_PREFIX_V1)) {+ // Legacy v1: kms:<keyId>:<base64>. No nonce, no context binding.+ // Decrypts only when caller supplies empty/null context (fingerprint "").+ String[] parts = data.substring(BLOB_PREFIX_V1.length()).split(":", 2);+ if (parts.length == 2) {+ return new ParsedBlob(parts[0], "", "", parts[1]);+ }+ }+ throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ }++ /**+ * Stable fingerprint of an EncryptionContext map. AWS treats EncryptionContext as a+ * case-sensitive exact match, so we hash a length-prefixed serialization of the sorted+ * (key, value) pairs. Returns "" for null / empty, so omitted-context and empty-map+ * ciphertexts are interchangeable (matches AWS).+ */+ private static String contextFingerprint(Map<String, String> ctx) {+ if (ctx == null || ctx.isEmpty()) {+ return "";+ }+ try {+ MessageDigest md = MessageDigest.getInstance("SHA-256");+ new TreeMap<>(ctx).forEach((k, v) -> {+ byte[] kb = k.getBytes(StandardCharsets.UTF_8);+ byte[] vb = (v == null ? "" : v).getBytes(StandardCharsets.UTF_8);+ md.update(ByteBuffer.allocate(4).putInt(kb.length).array());+ md.update(kb);+ md.update(ByteBuffer.allocate(4).putInt(vb.length).array());+ md.update(vb);+ });+ return HexFormat.of().formatHex(md.digest());+ } catch (NoSuchAlgorithmException e) {+ throw new AwsException("InternalFailure", "SHA-256 unavailable", 500);}- return null;}public byte[] sign(String keyId, byte[] message, String algorithm, String region) {@@ -452,14 +543,19 @@ public class KmsService {}public Map<String, Object> generateDataKey(String keyId, String keySpec, int numberOfBytes, String region) {+ return generateDataKey(keyId, keySpec, numberOfBytes, Map.of(), region);+ }++ public Map<String, Object> generateDataKey(String keyId, String keySpec, int numberOfBytes,+ Map<String, String> encryptionContext, String region) {resolveKey(keyId, region);int len = (keySpec != null && keySpec.contains("256")) ? 32 : (numberOfBytes > 0 ? numberOfBytes : 32);-+byte[] plaintext = new byte[len];ThreadLocalRandom.current().nextBytes(plaintext);-- byte[] ciphertext = encrypt(keyId, plaintext, region);-++ byte[] ciphertext = encrypt(keyId, plaintext, encryptionContext, region);+Map<String, Object> result = new HashMap<>();result.put("Plaintext", plaintext);result.put("CiphertextBlob", ciphertext);diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.javaindex ff523da0e8..30d88aacd5 100644--- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java@@ -16,7 +16,9 @@ import java.security.Security;import java.security.KeyFactory;import java.security.PublicKey;import java.security.spec.X509EncodedKeySpec;+import java.util.Arrays;import java.util.Base64;+import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import org.junit.jupiter.params.ParameterizedTest;@@ -197,6 +199,192 @@ class KmsServiceTest {kmsService.decrypt("not-valid-ciphertext".getBytes(StandardCharsets.UTF_8), REGION));}+ @Test+ void encryptIsNonDeterministic() {+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);++ byte[] c1 = kmsService.encrypt(key.getKeyId(), plaintext, REGION);+ byte[] c2 = kmsService.encrypt(key.getKeyId(), plaintext, REGION);++ assertFalse(Arrays.equals(c1, c2),+ "two Encrypt calls with identical inputs must yield different ciphertexts");+ // Both still round-trip+ assertArrayEquals(plaintext, kmsService.decrypt(c1, REGION));+ assertArrayEquals(plaintext, kmsService.decrypt(c2, REGION));+ }++ @Test+ void encryptIsNonDeterministicWithIdenticalContext() {+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);+ Map<String, String> ctx = Map.of("tenant", "1");++ byte[] c1 = kmsService.encrypt(key.getKeyId(), plaintext, ctx, REGION);+ byte[] c2 = kmsService.encrypt(key.getKeyId(), plaintext, ctx, REGION);++ assertFalse(Arrays.equals(c1, c2));+ }++ @Test+ void decryptWithMatchingContextSucceeds() {+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);+ Map<String, String> ctx = Map.of("tenant", "1", "purpose", "test");++ byte[] ciphertext = kmsService.encrypt(key.getKeyId(), plaintext, ctx, REGION);+ // Different insertion order, same logical context — must succeed (AWS is order-independent)+ Map<String, String> reordered = new LinkedHashMap<>();+ reordered.put("purpose", "test");+ reordered.put("tenant", "1");++ assertArrayEquals(plaintext, kmsService.decrypt(ciphertext, reordered, REGION));+ }++ @Test+ void decryptWithMismatchedContextValueThrows() {+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(),+ "hello".getBytes(StandardCharsets.UTF_8), Map.of("tenant", "1"), REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.decrypt(ciphertext, Map.of("tenant", "999"), REGION));+ assertEquals("InvalidCiphertextException", ex.getErrorCode());+ }++ @Test+ void decryptWithMismatchedContextKeyThrows() {+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(),+ "hello".getBytes(StandardCharsets.UTF_8), Map.of("tenant", "1"), REGION);++ // Same value under a different key — must fail+ assertThrows(AwsException.class, () ->+ kmsService.decrypt(ciphertext, Map.of("account", "1"), REGION));+ }++ @Test+ void decryptWithoutContextRejectsCiphertextEncryptedWithContext() {+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(),+ "hello".getBytes(StandardCharsets.UTF_8), Map.of("tenant", "1"), REGION);++ // Decrypt without supplying the context the ciphertext was bound to — must fail+ assertThrows(AwsException.class, () ->+ kmsService.decrypt(ciphertext, REGION));+ assertThrows(AwsException.class, () ->+ kmsService.decrypt(ciphertext, Map.of(), REGION));+ }++ @Test+ void decryptWithExtraContextKeyThrows() {+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(),+ "hello".getBytes(StandardCharsets.UTF_8), Map.of("tenant", "1"), REGION);++ assertThrows(AwsException.class, () ->+ kmsService.decrypt(ciphertext, Map.of("tenant", "1", "extra", "x"), REGION));+ }++ @Test+ void emptyContextIsInterchangeableWithNull() {+ // AWS treats omitted EncryptionContext and {} the same: both must decrypt+ // a ciphertext that was encrypted without one.+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);++ byte[] noCtx = kmsService.encrypt(key.getKeyId(), plaintext, REGION);+ assertArrayEquals(plaintext, kmsService.decrypt(noCtx, REGION));+ assertArrayEquals(plaintext, kmsService.decrypt(noCtx, Map.of(), REGION));++ byte[] emptyCtx = kmsService.encrypt(key.getKeyId(), plaintext, Map.of(), REGION);+ assertArrayEquals(plaintext, kmsService.decrypt(emptyCtx, REGION));+ assertArrayEquals(plaintext, kmsService.decrypt(emptyCtx, Map.of(), REGION));+ }++ @Test+ void contextIsCaseSensitive() {+ // AWS performs case-sensitive matching of EncryptionContext keys and values.+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(),+ "hello".getBytes(StandardCharsets.UTF_8), Map.of("Tenant", "Alpha"), REGION);++ assertThrows(AwsException.class, () ->+ kmsService.decrypt(ciphertext, Map.of("tenant", "Alpha"), REGION));+ assertThrows(AwsException.class, () ->+ kmsService.decrypt(ciphertext, Map.of("Tenant", "alpha"), REGION));+ // Exact match still works+ assertNotNull(kmsService.decrypt(ciphertext, Map.of("Tenant", "Alpha"), REGION));+ }++ @Test+ void decryptToKeyArnResolvesKeyFromBlob() {+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(),+ "hello".getBytes(StandardCharsets.UTF_8), Map.of("tenant", "1"), REGION);++ assertEquals(key.getArn(), kmsService.decryptToKeyArn(ciphertext, REGION));+ }++ @Test+ void reEncryptHonorsSourceContext() {+ // Simulates the ReEncrypt flow: decrypt under source ctx, encrypt under dest ctx.+ KmsKey src = kmsService.createKey(null, REGION);+ KmsKey dst = kmsService.createKey(null, REGION);+ byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);+ Map<String, String> sourceCtx = Map.of("tenant", "1");+ Map<String, String> destCtx = Map.of("tenant", "2");++ byte[] srcBlob = kmsService.encrypt(src.getKeyId(), plaintext, sourceCtx, REGION);++ // Wrong source context → fails on the decrypt half of ReEncrypt+ assertThrows(AwsException.class, () ->+ kmsService.decrypt(srcBlob, Map.of("tenant", "wrong"), REGION));++ // Correct source context → ReEncrypt round-trips, output is bound to destCtx+ byte[] roundtripped = kmsService.decrypt(srcBlob, sourceCtx, REGION);+ byte[] destBlob = kmsService.encrypt(dst.getKeyId(), roundtripped, destCtx, REGION);++ // New blob requires destCtx, not sourceCtx, to decrypt+ assertThrows(AwsException.class, () ->+ kmsService.decrypt(destBlob, sourceCtx, REGION));+ assertArrayEquals(plaintext, kmsService.decrypt(destBlob, destCtx, REGION));+ }++ @Test+ void v1BlobWithOverrideIdEqualToV2VersionMarkerCollidesAndFails() {+ // Documented limitation: a v1 blob with override-id "v2" looks like "kms:v2:<base64>",+ // which collides with the v2 prefix. Pinned so any change to BLOB_PREFIX_V2 or v2-branch+ // fall-through behavior fails this test loudly instead of silently changing semantics.+ KmsKey key = kmsService.createKey(null, "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT", null,+ Map.of("floci:override-id", "v2"), REGION);+ byte[] v1BlobWithV2KeyId = ("kms:v2:"+ + Base64.getEncoder().encodeToString("hello".getBytes(StandardCharsets.UTF_8)))+ .getBytes(StandardCharsets.UTF_8);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.decrypt(v1BlobWithV2KeyId, REGION));+ assertEquals("InvalidCiphertextException", ex.getErrorCode());+ assertEquals("v2", key.getKeyId());+ }++ @Test+ void legacyV1BlobDecryptsForBackCompat() {+ // Persistent stores written before this PR contain kms:<keyId>:<base64> blobs.+ // Decrypt must still accept them (no context binding on v1).+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);+ byte[] v1Blob = ("kms:" + key.getKeyId() + ":"+ + Base64.getEncoder().encodeToString(plaintext)).getBytes(StandardCharsets.UTF_8);++ assertArrayEquals(plaintext, kmsService.decrypt(v1Blob, REGION));+ assertArrayEquals(plaintext, kmsService.decrypt(v1Blob, Map.of(), REGION));+ // v1 carried no context, so any non-empty context must fail (matches AWS semantics)+ assertThrows(AwsException.class, () ->+ kmsService.decrypt(v1Blob, Map.of("tenant", "1"), REGION));+ assertEquals(key.getArn(), kmsService.decryptToKeyArn(v1Blob, REGION));+ }+@ParameterizedTest@ValueSource(strings = {"ECC_NIST_P256", "ECC_NIST_P384", "ECC_NIST_P521", "ECC_SECG_P256K1"})void signAndVerify(String keySpec) {