Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(kms): add GenerateRandom action (#1036)

nblomquist30a598f080c3
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsTest.java
index 1fa05ea33f..d8b50d1276 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsTest.java
@@ -308,4 +308,13 @@ class KmsTest {
assertThat(verifyResponse.signatureValid()).isTrue();
}
+
+ @Test
+ @Order(19)
+ void generateRandom() {
+ var response = kms.generateRandom(b -> b.numberOfBytes(32));
+
+ assertThat(response.plaintext()).isNotNull();
+ assertThat(response.plaintext().asByteArray()).hasSize(32);
+ }
}
diff --git a/compatibility-tests/sdk-test-node/tests/kms.test.ts b/compatibility-tests/sdk-test-node/tests/kms.test.ts
index a0ca391a34..4a85718e75 100644
--- a/compatibility-tests/sdk-test-node/tests/kms.test.ts
+++ b/compatibility-tests/sdk-test-node/tests/kms.test.ts
@@ -11,6 +11,7 @@ import {
EncryptCommand,
DecryptCommand,
GenerateDataKeyCommand,
+ GenerateRandomCommand,
} from '@aws-sdk/client-kms';
import { makeClient, uniqueName } from './setup';
@@ -65,4 +66,10 @@ describe('KMS', () => {
expect(response.Plaintext).toBeTruthy();
expect(response.CiphertextBlob).toBeTruthy();
});
+
+ it('should generate random bytes', async () => {
+ const response = await kms.send(new GenerateRandomCommand({ NumberOfBytes: 32 }));
+ expect(response.Plaintext).toBeTruthy();
+ expect(response.Plaintext!.byteLength).toBe(32);
+ });
});
diff --git a/compatibility-tests/sdk-test-python/tests/test_kms.py b/compatibility-tests/sdk-test-python/tests/test_kms.py
index 21a37bace6..d696b334b2 100644
--- a/compatibility-tests/sdk-test-python/tests/test_kms.py
+++ b/compatibility-tests/sdk-test-python/tests/test_kms.py
@@ -256,3 +256,14 @@ class TestKMSTagging:
)
finally:
kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)
+
+
+class TestKMSGenerateRandom:
+ """Test KMS GenerateRandom operation."""
+
+ def test_generate_random(self, kms_client):
+ """Test GenerateRandom returns random bytes."""
+ response = kms_client.generate_random(NumberOfBytes=32)
+ plaintext = response["Plaintext"]
+ assert plaintext
+ assert len(plaintext) == 32
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.java
index 9f58b69a7e..a1f83ffac4 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
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.kms;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
+import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.services.kms.model.KmsAlias;
@@ -36,6 +37,7 @@ public class KmsJsonHandler {
public Response handle(String action, JsonNode request, String region) {
return switch (action) {
case "CreateKey" -> handleCreateKey(request, region);
+ case "GenerateRandom" -> handleGenerateRandom(request, region);
case "GetPublicKey" -> handleGetPublicKey(request, region);
case "DescribeKey" -> handleDescribeKey(request, region);
case "ListKeys" -> handleListKeys(request, region);
@@ -498,6 +500,24 @@ public class KmsJsonHandler {
return Response.ok(response).build();
}
+ private Response handleGenerateRandom(JsonNode request, String region) {
+ if (!request.path("Recipient").isMissingNode()) {
+ throw new AwsException("ValidationException",
+ "Recipient is not supported for GenerateRandom without Nitro Enclave support.",
+ 400);
+ }
+ if (!request.path("CustomKeyStoreId").isMissingNode()) {
+ throw new AwsException("ValidationException",
+ "Custom key stores are not supported.",
+ 400);
+ }
+ int numberOfBytes = request.path("NumberOfBytes").asInt(0);
+ byte[] randomBytes = service.generateRandom(numberOfBytes);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("Plaintext", Base64.getEncoder().encodeToString(randomBytes));
+ return Response.ok(response).build();
+ }
+
private ObjectNode keyToNode(KmsKey k) {
ObjectNode node = objectMapper.createObjectNode();
node.put("AWSAccountId", regionResolver.getAccountId());
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.java
index cfd00c5d81..6d8f969a04 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
@@ -52,6 +52,7 @@ public class KmsService {
private final StorageBackend<String, KmsAlias> aliasStore;
private final StorageBackend<String, KmsGrant> grantStore;
private final RegionResolver regionResolver;
+ private final SecureRandom secureRandom;
@Inject
public KmsService(StorageFactory storageFactory, RegionResolver regionResolver) {
@@ -65,13 +66,33 @@ public class KmsService {
}
KmsService(StorageBackend<String, KmsKey> keyStore,
- StorageBackend<String, KmsAlias> aliasStore,
+ StorageBackend<String, KmsAlias> aliasStore,
StorageBackend<String, KmsGrant> grantStore,
- RegionResolver regionResolver) {
+ RegionResolver regionResolver) {
+ this(keyStore, aliasStore, grantStore, regionResolver, new SecureRandom());
+ }
+
+ KmsService(StorageBackend<String, KmsKey> keyStore,
+ StorageBackend<String, KmsAlias> aliasStore,
+ StorageBackend<String, KmsGrant> grantStore,
+ RegionResolver regionResolver,
+ SecureRandom secureRandom) {
this.keyStore = keyStore;
this.aliasStore = aliasStore;
this.grantStore = grantStore;
this.regionResolver = regionResolver;
+ this.secureRandom = secureRandom;
+ }
+
+ public byte[] generateRandom(int numberOfBytes) {
+ if (numberOfBytes < 1 || numberOfBytes > 1024) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value '" + numberOfBytes + "' at 'numberOfBytes' failed to satisfy constraint: Member must have value greater than or equal to 1 and less than or equal to 1024",
+ 400);
+ }
+ byte[] bytes = new byte[numberOfBytes];
+ secureRandom.nextBytes(bytes);
+ return bytes;
}
private String buildDefaultKeyPolicy() {
diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java
index c438fecb19..2e704d19c4 100644
--- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java
@@ -109,6 +109,170 @@ class KmsIntegrationTest {
.body("__type", equalTo("KMSInvalidMacException"));
}
+ @Test
+ void generateRandomReturnsBase64Plaintext() {
+ // RED phase: This test is expected to fail until GenerateRandom is wired
+ // in KmsJsonHandler.handle(). Currently returns 400 UnsupportedOperation.
+ String plaintextBase64 = given()
+ .header("X-Amz-Target", "TrentService.GenerateRandom")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {
+ "NumberOfBytes": 32
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Plaintext", notNullValue())
+ .extract().jsonPath().getString("Plaintext");
+
+ assertEquals(32, Base64.getDecoder().decode(plaintextBase64).length);
+ }
+
+ @Test
+ void generateRandomMissingNumberOfBytesReturnsError() {
+ given()
+ .header("X-Amz-Target", "TrentService.GenerateRandom")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {}
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ }
+
+ @Test
+ void generateRandomZeroBytesReturnsError() {
+ given()
+ .header("X-Amz-Target", "TrentService.GenerateRandom")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {
+ "NumberOfBytes": 0
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ }
+
+ @Test
+ void generateRandomNegativeBytesReturnsError() {
+ given()
+ .header("X-Amz-Target", "TrentService.GenerateRandom")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {
+ "NumberOfBytes": -1
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ }
+
+ @Test
+ void generateRandomTooManyBytesReturnsError() {
+ given()
+ .header("X-Amz-Target", "TrentService.GenerateRandom")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {
+ "NumberOfBytes": 1025
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ }
+
+ @Test
+ void generateRandomOneByteReturnsSuccess() {
+ String plaintextBase64 = given()
+ .header("X-Amz-Target", "TrentService.GenerateRandom")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {
+ "NumberOfBytes": 1
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Plaintext", notNullValue())
+ .extract().jsonPath().getString("Plaintext");
+
+ assertEquals(1, Base64.getDecoder().decode(plaintextBase64).length);
+ }
+
+ @Test
+ void generateRandomMaxBytesReturnsSuccess() {
+ String plaintextBase64 = given()
+ .header("X-Amz-Target", "TrentService.GenerateRandom")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {
+ "NumberOfBytes": 1024
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Plaintext", notNullValue())
+ .extract().jsonPath().getString("Plaintext");
+
+ assertEquals(1024, Base64.getDecoder().decode(plaintextBase64).length);
+ }
+
+ @Test
+ void generateRandomWithRecipientReturnsError() {
+ given()
+ .header("X-Amz-Target", "TrentService.GenerateRandom")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {
+ "NumberOfBytes": 32,
+ "Recipient": {}
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ }
+
+ @Test
+ void generateRandomWithCustomKeyStoreIdReturnsError() {
+ given()
+ .header("X-Amz-Target", "TrentService.GenerateRandom")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {
+ "NumberOfBytes": 32,
+ "CustomKeyStoreId": "cks-1234567890"
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ }
+
@Test
void rotateKeyOnDemandReturnsKeyId() {
String keyId = given()