Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat: add KMS GetKeyPolicy, PutKeyPolicy and fix CreateKey Tags (#258 #259 #269) (#280)

Hector Ventura4724db97be2b
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsFeaturesTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsFeaturesTest.java
new file mode 100644
index 0000000000..5c52647d70
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsFeaturesTest.java
@@ -0,0 +1,149 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.*;
+import software.amazon.awssdk.services.kms.KmsClient;
+import software.amazon.awssdk.services.kms.model.CreateKeyResponse;
+import software.amazon.awssdk.services.kms.model.GetKeyPolicyResponse;
+import software.amazon.awssdk.services.kms.model.ListResourceTagsResponse;
+
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.*;
+
+/**
+ * Compatibility tests for KMS fixes:
+ * #269 — CreateKey applies Tags at creation time
+ * #258 — GetKeyPolicy returns the stored policy
+ * #259 — PutKeyPolicy updates the key policy
+ */
+@DisplayName("KMS features (#258 #259 #269)")
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class KmsFeaturesTest {
+
+ private static KmsClient kms;
+
+ @BeforeAll
+ static void setup() {
+ kms = TestFixtures.kmsClient();
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (kms != null) kms.close();
+ }
+
+ // ── Issue #269 — CreateKey applies Tags ───────────────────────────────────
+
+ @Test
+ @Order(10)
+ void createKeyWithTagsStoresTags() {
+ CreateKeyResponse resp = kms.createKey(b -> b
+ .description("tagged-key")
+ .tags(
+ software.amazon.awssdk.services.kms.model.Tag.builder().tagKey("env").tagValue("prod").build(),
+ software.amazon.awssdk.services.kms.model.Tag.builder().tagKey("team").tagValue("platform").build()
+ ));
+ String keyId = resp.keyMetadata().keyId();
+
+ ListResourceTagsResponse tags = kms.listResourceTags(b -> b.keyId(keyId));
+ Map<String, String> tagMap = tags.tags().stream()
+ .collect(java.util.stream.Collectors.toMap(
+ software.amazon.awssdk.services.kms.model.Tag::tagKey,
+ software.amazon.awssdk.services.kms.model.Tag::tagValue));
+
+ assertThat(tagMap).containsEntry("env", "prod");
+ assertThat(tagMap).containsEntry("team", "platform");
+
+ kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
+ }
+
+ @Test
+ @Order(11)
+ void createKeyWithoutTagsHasEmptyTagList() {
+ CreateKeyResponse resp = kms.createKey(b -> b.description("no-tags-key"));
+ String keyId = resp.keyMetadata().keyId();
+
+ ListResourceTagsResponse tags = kms.listResourceTags(b -> b.keyId(keyId));
+ assertThat(tags.tags()).isEmpty();
+
+ kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
+ }
+
+ // ── Issue #258 — GetKeyPolicy ─────────────────────────────────────────────
+
+ @Test
+ @Order(20)
+ void createKeyWithoutPolicyReturnsDefaultPolicy() {
+ CreateKeyResponse resp = kms.createKey(b -> b.description("default-policy-key"));
+ String keyId = resp.keyMetadata().keyId();
+
+ GetKeyPolicyResponse policyResp = kms.getKeyPolicy(b -> b.keyId(keyId));
+ assertThat(policyResp.policy()).isNotBlank();
+ assertThat(policyResp.policyName()).isEqualTo("default");
+ assertThat(policyResp.policy()).contains("kms:*");
+
+ kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
+ }
+
+ @Test
+ @Order(21)
+ void createKeyWithPolicyStoresAndReturnsPolicy() {
+ String customPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Custom\"," +
+ "\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::000000000000:root\"}," +
+ "\"Action\":\"kms:*\",\"Resource\":\"*\"}]}";
+
+ CreateKeyResponse resp = kms.createKey(b -> b
+ .description("custom-policy-key")
+ .policy(customPolicy));
+ String keyId = resp.keyMetadata().keyId();
+
+ GetKeyPolicyResponse policyResp = kms.getKeyPolicy(b -> b.keyId(keyId));
+ assertThat(policyResp.policy()).isEqualTo(customPolicy);
+ assertThat(policyResp.policyName()).isEqualTo("default");
+
+ kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
+ }
+
+ // ── Issue #259 — PutKeyPolicy ─────────────────────────────────────────────
+
+ @Test
+ @Order(30)
+ void putKeyPolicyUpdatesPolicy() {
+ CreateKeyResponse resp = kms.createKey(b -> b.description("put-policy-key"));
+ String keyId = resp.keyMetadata().keyId();
+
+ String newPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Updated\"," +
+ "\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::000000000000:root\"}," +
+ "\"Action\":\"kms:Decrypt\",\"Resource\":\"*\"}]}";
+
+ kms.putKeyPolicy(b -> b.keyId(keyId).policy(newPolicy));
+
+ GetKeyPolicyResponse policyResp = kms.getKeyPolicy(b -> b.keyId(keyId));
+ assertThat(policyResp.policy()).isEqualTo(newPolicy);
+
+ kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
+ }
+
+ @Test
+ @Order(31)
+ void putKeyPolicyRoundTrip() {
+ CreateKeyResponse resp = kms.createKey(b -> b.description("round-trip-key"));
+ String keyId = resp.keyMetadata().keyId();
+
+ // Get initial policy
+ String initial = kms.getKeyPolicy(b -> b.keyId(keyId)).policy();
+ assertThat(initial).isNotBlank();
+
+ // Put a new policy
+ String updated = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"RoundTrip\"," +
+ "\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::000000000000:root\"}," +
+ "\"Action\":\"kms:*\",\"Resource\":\"*\"}]}";
+ kms.putKeyPolicy(b -> b.keyId(keyId).policy(updated));
+
+ // Verify change persisted
+ assertThat(kms.getKeyPolicy(b -> b.keyId(keyId)).policy()).isEqualTo(updated);
+ assertThat(kms.getKeyPolicy(b -> b.keyId(keyId)).policy()).isNotEqualTo(initial);
+
+ kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
+ }
+}
diff --git a/compatibility-tests/sdk-test-node/tests/kms-features.test.ts b/compatibility-tests/sdk-test-node/tests/kms-features.test.ts
new file mode 100644
index 0000000000..35ca8682b1
--- /dev/null
+++ b/compatibility-tests/sdk-test-node/tests/kms-features.test.ts
@@ -0,0 +1,147 @@
+/**
+ * Compatibility tests for KMS fixes:
+ * #269 — CreateKey applies Tags at creation time
+ * #258 — GetKeyPolicy returns the stored policy
+ * #259 — PutKeyPolicy updates the key policy
+ */
+
+import { describe, it, expect, afterEach } from 'vitest';
+import {
+ KMSClient,
+ CreateKeyCommand,
+ GetKeyPolicyCommand,
+ PutKeyPolicyCommand,
+ ListResourceTagsCommand,
+ ScheduleKeyDeletionCommand,
+} from '@aws-sdk/client-kms';
+import { makeClient } from './setup';
+
+const kms = makeClient(KMSClient);
+const createdKeyIds: string[] = [];
+
+async function createKey(opts: Parameters<typeof CreateKeyCommand>[0] = {}) {
+ const resp = await kms.send(new CreateKeyCommand(opts));
+ const keyId = resp.KeyMetadata!.KeyId!;
+ createdKeyIds.push(keyId);
+ return resp;
+}
+
+afterEach(async () => {
+ // Schedule deletion for all keys created in the test
+ while (createdKeyIds.length > 0) {
+ const keyId = createdKeyIds.pop()!;
+ try {
+ await kms.send(new ScheduleKeyDeletionCommand({ KeyId: keyId, PendingWindowInDays: 7 }));
+ } catch { /* ignore */ }
+ }
+});
+
+// ── Issue #269 — CreateKey applies Tags ───────────────────────────────────────
+
+describe('KMS features (#258 #259 #269)', () => {
+
+ it('#269: CreateKey with Tags stores tags immediately', async () => {
+ const resp = await createKey({
+ Description: 'tagged-key',
+ Tags: [
+ { TagKey: 'env', TagValue: 'prod' },
+ { TagKey: 'team', TagValue: 'platform' },
+ ],
+ });
+ const keyId = resp.KeyMetadata!.KeyId!;
+
+ const tags = await kms.send(new ListResourceTagsCommand({ KeyId: keyId }));
+ const tagMap = Object.fromEntries(tags.Tags!.map(t => [t.TagKey!, t.TagValue!]));
+
+ expect(tagMap['env']).toBe('prod');
+ expect(tagMap['team']).toBe('platform');
+ });
+
+ it('#269: CreateKey without Tags has empty tag list', async () => {
+ const resp = await createKey({ Description: 'no-tags-key' });
+ const keyId = resp.KeyMetadata!.KeyId!;
+
+ const tags = await kms.send(new ListResourceTagsCommand({ KeyId: keyId }));
+ expect(tags.Tags).toHaveLength(0);
+ });
+
+ // ── Issue #258 — GetKeyPolicy ───────────────────────────────────────────────
+
+ it('#258: CreateKey without Policy returns a non-empty default policy', async () => {
+ const resp = await createKey({ Description: 'default-policy-key' });
+ const keyId = resp.KeyMetadata!.KeyId!;
+
+ const policyResp = await kms.send(new GetKeyPolicyCommand({ KeyId: keyId }));
+ expect(policyResp.Policy).toBeTruthy();
+ expect(policyResp.PolicyName).toBe('default');
+ expect(policyResp.Policy).toContain('kms:*');
+ });
+
+ it('#258: CreateKey with Policy stores and returns that policy', async () => {
+ const customPolicy = JSON.stringify({
+ Version: '2012-10-17',
+ Statement: [{
+ Sid: 'Custom',
+ Effect: 'Allow',
+ Principal: { AWS: 'arn:aws:iam::000000000000:root' },
+ Action: 'kms:*',
+ Resource: '*',
+ }],
+ });
+
+ const resp = await createKey({ Description: 'custom-policy-key', Policy: customPolicy });
+ const keyId = resp.KeyMetadata!.KeyId!;
+
+ const policyResp = await kms.send(new GetKeyPolicyCommand({ KeyId: keyId }));
+ expect(policyResp.Policy).toBe(customPolicy);
+ expect(policyResp.PolicyName).toBe('default');
+ });
+
+ // ── Issue #259 — PutKeyPolicy ───────────────────────────────────────────────
+
+ it('#259: PutKeyPolicy updates the key policy', async () => {
+ const resp = await createKey({ Description: 'put-policy-key' });
+ const keyId = resp.KeyMetadata!.KeyId!;
+
+ const newPolicy = JSON.stringify({
+ Version: '2012-10-17',
+ Statement: [{
+ Sid: 'Updated',
+ Effect: 'Allow',
+ Principal: { AWS: 'arn:aws:iam::000000000000:root' },
+ Action: 'kms:Decrypt',
+ Resource: '*',
+ }],
+ });
+
+ await kms.send(new PutKeyPolicyCommand({ KeyId: keyId, Policy: newPolicy }));
+
+ const policyResp = await kms.send(new GetKeyPolicyCommand({ KeyId: keyId }));
+ expect(policyResp.Policy).toBe(newPolicy);
+ });
+
+ it('#259: PutKeyPolicy round-trip — get, change, verify', async () => {
+ const resp = await createKey({ Description: 'round-trip-key' });
+ const keyId = resp.KeyMetadata!.KeyId!;
+
+ const initial = (await kms.send(new GetKeyPolicyCommand({ KeyId: keyId }))).Policy!;
+ expect(initial).toBeTruthy();
+
+ const updated = JSON.stringify({
+ Version: '2012-10-17',
+ Statement: [{
+ Sid: 'RoundTrip',
+ Effect: 'Allow',
+ Principal: { AWS: 'arn:aws:iam::000000000000:root' },
+ Action: 'kms:*',
+ Resource: '*',
+ }],
+ });
+
+ await kms.send(new PutKeyPolicyCommand({ KeyId: keyId, Policy: updated }));
+
+ const after = (await kms.send(new GetKeyPolicyCommand({ KeyId: keyId }))).Policy!;
+ expect(after).toBe(updated);
+ expect(after).not.toBe(initial);
+ });
+});
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 53012f7fef..5d8afb990a 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
@@ -48,6 +48,8 @@ public class KmsJsonHandler {
case "TagResource" -> handleTagResource(request, region);
case "UntagResource" -> handleUntagResource(request, region);
case "ListResourceTags" -> handleListResourceTags(request, region);
+ case "GetKeyPolicy" -> handleGetKeyPolicy(request, region);
+ case "PutKeyPolicy" -> handlePutKeyPolicy(request, region);
default -> Response.status(400)
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
.build();
@@ -56,7 +58,10 @@ public class KmsJsonHandler {
private Response handleCreateKey(JsonNode request, String region) {
String description = request.path("Description").asText(null);
- KmsKey key = service.createKey(description, region);
+ String policy = request.path("Policy").isMissingNode() ? null : request.path("Policy").asText(null);
+ Map<String, String> tags = new HashMap<>();
+ request.path("Tags").forEach(t -> tags.put(t.path("TagKey").asText(), t.path("TagValue").asText()));
+ KmsKey key = service.createKey(description, policy, tags, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("KeyMetadata", keyToNode(key));
return Response.ok(response).build();
@@ -254,6 +259,19 @@ public class KmsJsonHandler {
return Response.ok(response).build();
}
+ private Response handleGetKeyPolicy(JsonNode request, String region) {
+ Map<String, Object> result = service.getKeyPolicy(request.path("KeyId").asText(), region);
+ return Response.ok(objectMapper.valueToTree(result)).build();
+ }
+
+ private Response handlePutKeyPolicy(JsonNode request, String region) {
+ service.putKeyPolicy(
+ request.path("KeyId").asText(),
+ request.path("Policy").asText(),
+ region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
private ObjectNode keyToNode(KmsKey k) {
ObjectNode node = objectMapper.createObjectNode();
node.put("AWSAccountId", "000000000000");
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 70eca8a4ab..11e2be3fb7 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
@@ -42,7 +42,16 @@ public class KmsService {
this.regionResolver = regionResolver;
}
+ private static final String DEFAULT_KEY_POLICY =
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Enable IAM User Permissions\"," +
+ "\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::000000000000:root\"}," +
+ "\"Action\":\"kms:*\",\"Resource\":\"*\"}]}";
+
public KmsKey createKey(String description, String region) {
+ return createKey(description, null, Map.of(), region);
+ }
+
+ public KmsKey createKey(String description, String policy, Map<String, String> tags, String region) {
String keyId = UUID.randomUUID().toString();
String arn = regionResolver.buildArn("kms", region, "key/" + keyId);
@@ -50,6 +59,10 @@ public class KmsService {
key.setKeyId(keyId);
key.setArn(arn);
key.setDescription(description);
+ key.setPolicy(policy != null ? policy : DEFAULT_KEY_POLICY);
+ if (tags != null) {
+ key.getTags().putAll(tags);
+ }
keyStore.put(region + "::" + keyId, key);
LOG.infov("Created KMS key: {0} in {1}", keyId, region);
@@ -79,6 +92,21 @@ public class KmsService {
keyStore.put(region + "::" + key.getKeyId(), key);
}
+ public Map<String, Object> getKeyPolicy(String keyId, String region) {
+ KmsKey key = resolveKey(keyId, region);
+ Map<String, Object> result = new HashMap<>();
+ result.put("Policy", key.getPolicy());
+ result.put("PolicyName", "default");
+ return result;
+ }
+
+ public void putKeyPolicy(String keyId, String policy, String region) {
+ KmsKey key = resolveKey(keyId, region);
+ key.setPolicy(policy);
+ keyStore.put(region + "::" + key.getKeyId(), key);
+ LOG.infov("Updated key policy for KMS key: {0} in {1}", key.getKeyId(), region);
+ }
+
// ──────────────────────────── Aliases ────────────────────────────
public void createAlias(String aliasName, String targetKeyId, String region) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKey.java b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKey.java
index 8bdda6ce62..9372febc4d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKey.java
+++ b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKey.java
@@ -19,6 +19,7 @@ public class KmsKey {
private String customerMasterKeySpec = "SYMMETRIC_DEFAULT";
private long creationDate;
private long deletionDate;
+ private String policy;
private Map<String, String> tags = new HashMap<>();
public KmsKey() {
@@ -52,6 +53,9 @@ public class KmsKey {
public long getDeletionDate() { return deletionDate; }
public void setDeletionDate(long deletionDate) { this.deletionDate = deletionDate; }
+ public String getPolicy() { return policy; }
+ public void setPolicy(String policy) { this.policy = policy; }
+
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
}
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.java
index 4bba21e60b..607c8ac1f5 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
@@ -229,4 +229,62 @@ class KmsServiceTest {
assertFalse(updated.getTags().containsKey("env"));
assertTrue(updated.getTags().containsKey("team"));
}
+
+ // ── Issue #269 — CreateKey with Tags ────────────────────────────────────
+
+ @Test
+ void createKeyWithTagsStoresTags() {
+ KmsKey key = kmsService.createKey("tagged-key", null, Map.of("env", "prod", "team", "platform"), REGION);
+
+ KmsKey found = kmsService.describeKey(key.getKeyId(), REGION);
+ assertEquals("prod", found.getTags().get("env"));
+ assertEquals("platform", found.getTags().get("team"));
+ }
+
+ @Test
+ void createKeyWithoutTagsHasEmptyTagMap() {
+ KmsKey key = kmsService.createKey(null, REGION);
+ assertTrue(key.getTags().isEmpty());
+ }
+
+ // ── Issue #258 — GetKeyPolicy ────────────────────────────────────────────
+
+ @Test
+ void createKeyWithoutPolicyHasDefaultPolicy() {
+ KmsKey key = kmsService.createKey(null, REGION);
+ Map<String, Object> result = kmsService.getKeyPolicy(key.getKeyId(), REGION);
+
+ assertNotNull(result.get("Policy"));
+ assertEquals("default", result.get("PolicyName"));
+ assertTrue(((String) result.get("Policy")).contains("kms:*"));
+ }
+
+ @Test
+ void createKeyWithPolicyStoresPolicy() {
+ String customPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
+ KmsKey key = kmsService.createKey("policy-key", customPolicy, Map.of(), REGION);
+
+ Map<String, Object> result = kmsService.getKeyPolicy(key.getKeyId(), REGION);
+ assertEquals(customPolicy, result.get("Policy"));
+ assertEquals("default", result.get("PolicyName"));
+ }
+
+ // ── Issue #259 — PutKeyPolicy ────────────────────────────────────────────
+
+ @Test
+ void putKeyPolicyUpdatesPolicy() {
+ KmsKey key = kmsService.createKey(null, REGION);
+ String newPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}";
+
+ kmsService.putKeyPolicy(key.getKeyId(), newPolicy, REGION);
+
+ Map<String, Object> result = kmsService.getKeyPolicy(key.getKeyId(), REGION);
+ assertEquals(newPolicy, result.get("Policy"));
+ }
+
+ @Test
+ void putKeyPolicyOnNonExistentKeyThrows() {
+ assertThrows(AwsException.class, () ->
+ kmsService.putKeyPolicy("non-existent", "{}", REGION));
+ }
}
\ No newline at end of file