mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(elasticache): keep a replication group's encryption, snapshot settings, tags and ARN (#2632)
* fix(elasticache): keep a replication group's encryption, snapshot settings, tags and ARN DescribeReplicationGroups wrote AtRestEncryptionEnabled and SnapshotRetentionLimit as constants and never emitted KmsKeyId, SnapshotWindow or ARN, so a group created with them drifted on the next Terraform plan (kms_key_id forces replacement) and its tags, given at create, could not even be asked for without an ARN. Store the four settings and the tags on the group, resolve KmsKeyId through the KMS store in the request's region to the key ARN a live account reports, apply the snapshot settings from ModifyReplicationGroup, emit them with the ARN, and answer ListTagsForResource for replicationgroup ARNs — for the record the ARN names, since the store keys groups by id alone. Delete and modify of a group now share one monitor, so a modify cannot write the group back after a delete removed it. Validation and wording follow a live account. Closes #2615 * fix(elasticache): refuse a KMS key with encryption at rest omitted, and change nothing on a refused modify An omitted AtRestEncryptionEnabled is false on a live account and a KmsKeyId is refused with it the same way as with an explicit false. ModifyReplicationGroup applied the snapshot settings to the store's own object before validating the user ids, so a request refused for an unknown user had already changed the group; every check now runs before any change. * fix(elasticache): read AtRestEncryptionEnabled as a live account does, and refuse an empty snapshot window A live account reads any AtRestEncryptionEnabled value that is not "false" as true — banana, yes and "TRUE " all created an encrypted group — so the flag is read the same way rather than parsed strictly. A snapshot window whose end equals its start was measured as a full day; a live account refuses it as shorter than an hour.
This commit is contained in:
1 parent
4affa05cea
commit
75f8f42d5f
9 files changed
+732
-35
No files matched your search
+135
-1
@@ -6,6 +6,17 @@ import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupSettings;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupStatus;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -18,13 +29,16 @@ import static org.mockito.Mockito.mock;
|
||||
class ElastiCacheQueryHandlerTest {
|
||||
|
||||
private ElastiCacheQueryHandler handler;
|
||||
private ElastiCacheService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
SigV4Validator sigV4Validator = mock(SigV4Validator.class);
|
||||
ElastiCacheService service = mock(ElastiCacheService.class);
|
||||
service = mock(ElastiCacheService.class);
|
||||
ElastiCacheMemcachedService memcachedService = mock(ElastiCacheMemcachedService.class);
|
||||
RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getRegion()).thenReturn("us-east-1");
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
handler = new ElastiCacheQueryHandler(sigV4Validator, service, memcachedService, regionResolver);
|
||||
}
|
||||
|
||||
@@ -61,4 +75,124 @@ class ElastiCacheQueryHandlerTest {
|
||||
private static MultivaluedMap<String, String> params() {
|
||||
return new MultivaluedHashMap<>();
|
||||
}
|
||||
|
||||
private static ReplicationGroup group(String id) {
|
||||
ReplicationGroup g = new ReplicationGroup(id, "d", ReplicationGroupStatus.AVAILABLE, AuthMode.NO_AUTH,
|
||||
new Endpoint("localhost", 6379), java.time.Instant.now(), 6379);
|
||||
g.setArn("arn:aws:elasticache:us-east-1:000000000000:replicationgroup:" + id);
|
||||
return g;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createReplicationGroup_passesSettingsAndTagsToService() {
|
||||
when(service.createReplicationGroup(any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(group("g1"));
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("ReplicationGroupId", "g1");
|
||||
p.add("ReplicationGroupDescription", "d");
|
||||
p.add("AtRestEncryptionEnabled", "true");
|
||||
p.add("KmsKeyId", "alias/cache");
|
||||
p.add("SnapshotRetentionLimit", "7");
|
||||
p.add("SnapshotWindow", "06:30-07:30");
|
||||
p.add("Tags.Tag.1.Key", "Name");
|
||||
p.add("Tags.Tag.1.Value", "g1");
|
||||
|
||||
assertEquals(200, handler.handle("CreateReplicationGroup", p, "us-east-1").getStatus());
|
||||
|
||||
verify(service).createReplicationGroup(eq("g1"), eq("d"), eq(AuthMode.NO_AUTH), isNull(), eq("us-east-1"),
|
||||
eq(new ReplicationGroupSettings(true, "alias/cache", 7, "06:30-07:30")), eq(Map.of("Name", "g1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createReplicationGroup_readsTheEncryptionFlagAsAwsDoes() {
|
||||
when(service.createReplicationGroup(any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(group("g1"));
|
||||
ArgumentCaptor<ReplicationGroupSettings> captor = ArgumentCaptor.forClass(ReplicationGroupSettings.class);
|
||||
// a live account reads anything but "false" as true — probed with banana, yes and "TRUE "
|
||||
for (String value : new String[] {"true", "banana", "yes", "TRUE "}) {
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("ReplicationGroupId", "g1");
|
||||
p.add("AtRestEncryptionEnabled", value);
|
||||
handler.handle("CreateReplicationGroup", p, "us-east-1");
|
||||
}
|
||||
for (String value : new String[] {"false", "FALSE"}) {
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("ReplicationGroupId", "g1");
|
||||
p.add("AtRestEncryptionEnabled", value);
|
||||
handler.handle("CreateReplicationGroup", p, "us-east-1");
|
||||
}
|
||||
MultivaluedMap<String, String> omitted = params();
|
||||
omitted.add("ReplicationGroupId", "g1");
|
||||
handler.handle("CreateReplicationGroup", omitted, "us-east-1");
|
||||
|
||||
verify(service, times(7)).createReplicationGroup(any(), any(), any(), any(), any(), captor.capture(), any());
|
||||
List<Boolean> seen = captor.getAllValues().stream().map(ReplicationGroupSettings::atRestEncryptionEnabled).toList();
|
||||
assertEquals(java.util.Arrays.asList(true, true, true, true, false, false, null), seen);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeReplicationGroups_emitsStoredSettingsAndArn() {
|
||||
ReplicationGroup g = group("g1");
|
||||
g.setAtRestEncryptionEnabled(true);
|
||||
g.setKmsKeyId("arn:aws:kms:us-east-1:000000000000:key/k1");
|
||||
g.setSnapshotRetentionLimit(7);
|
||||
g.setSnapshotWindow("06:30-07:30");
|
||||
when(service.listReplicationGroups("g1")).thenReturn(List.of(g));
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("ReplicationGroupId", "g1");
|
||||
|
||||
String body = (String) handler.handle("DescribeReplicationGroups", p, "us-east-1").getEntity();
|
||||
|
||||
assertTrue(body.contains("<AtRestEncryptionEnabled>true</AtRestEncryptionEnabled>"), body);
|
||||
assertTrue(body.contains("<KmsKeyId>arn:aws:kms:us-east-1:000000000000:key/k1</KmsKeyId>"), body);
|
||||
assertTrue(body.contains("<SnapshotRetentionLimit>7</SnapshotRetentionLimit>"), body);
|
||||
assertTrue(body.contains("<SnapshotWindow>06:30-07:30</SnapshotWindow>"), body);
|
||||
assertTrue(body.contains("<ARN>arn:aws:elasticache:us-east-1:000000000000:replicationgroup:g1</ARN>"), body);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listTagsForResource_readsAReplicationGroupByItsArn() {
|
||||
ReplicationGroup g = group("g1");
|
||||
g.setTags(new java.util.LinkedHashMap<>(Map.of("Name", "g1")));
|
||||
when(service.getReplicationGroup("g1")).thenReturn(g);
|
||||
when(service.getReplicationGroup("absent")).thenThrow(
|
||||
new AwsException("ReplicationGroupNotFoundFault", "Replication group absent not found.", 404));
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:replicationgroup:g1");
|
||||
String body = (String) handler.handle("ListTagsForResource", p, "us-east-1").getEntity();
|
||||
assertTrue(body.contains("<Key>Name</Key>"), body);
|
||||
|
||||
p = params();
|
||||
p.add("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:replicationgroup:absent");
|
||||
Response response = handler.handle("ListTagsForResource", p, "us-east-1");
|
||||
assertEquals(404, response.getStatus());
|
||||
assertTrue(((String) response.getEntity()).contains("ReplicationGroupNotFoundFault"));
|
||||
|
||||
// the store keys groups by id alone: a same-named group created under another region is
|
||||
// not the one this ARN names
|
||||
ReplicationGroup elsewhere = group("g2");
|
||||
elsewhere.setArn("arn:aws:elasticache:eu-west-1:000000000000:replicationgroup:g2");
|
||||
elsewhere.setTags(new java.util.LinkedHashMap<>(Map.of("Name", "west")));
|
||||
when(service.getReplicationGroup("g2")).thenReturn(elsewhere);
|
||||
p = params();
|
||||
p.add("ResourceName", "arn:aws:elasticache:us-east-1:000000000000:replicationgroup:g2");
|
||||
response = handler.handle("ListTagsForResource", p, "us-east-1");
|
||||
assertEquals(404, response.getStatus(), (String) response.getEntity());
|
||||
assertFalse(((String) response.getEntity()).contains("west"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyReplicationGroup_passesSnapshotSettingsOnly() {
|
||||
when(service.modifyReplicationGroup(eq("g1"), isNull(), isNull(), any())).thenReturn(group("g1"));
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("ReplicationGroupId", "g1");
|
||||
p.add("SnapshotRetentionLimit", "3");
|
||||
p.add("SnapshotWindow", "01:00-02:00");
|
||||
p.add("AtRestEncryptionEnabled", "true");
|
||||
p.add("KmsKeyId", "alias/other");
|
||||
|
||||
assertEquals(200, handler.handle("ModifyReplicationGroup", p, "us-east-1").getStatus());
|
||||
verify(service).modifyReplicationGroup("g1", null, null, new ReplicationGroupSettings(null, null, 3, "01:00-02:00"));
|
||||
}
|
||||
}
|
||||
+169
-3
@@ -6,6 +6,10 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.kms.KmsService;
|
||||
import io.github.hectorvent.floci.services.kms.model.KmsKey;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupSettings;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
|
||||
@@ -15,11 +19,13 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -36,15 +42,17 @@ import static org.mockito.Mockito.when;
|
||||
class ElastiCacheServiceTest {
|
||||
|
||||
private ElastiCacheService service;
|
||||
private KmsService kmsService;
|
||||
private ElastiCacheContainerManager containerManager;
|
||||
private ElastiCacheProxyManager proxyManager;
|
||||
private EmulatorConfig config;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
containerManager = mock(ElastiCacheContainerManager.class);
|
||||
proxyManager = mock(ElastiCacheProxyManager.class);
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
config = mock(EmulatorConfig.class);
|
||||
|
||||
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.ElastiCacheServiceConfig ecConfig = mock(EmulatorConfig.ElastiCacheServiceConfig.class);
|
||||
@@ -60,8 +68,11 @@ class ElastiCacheServiceTest {
|
||||
.thenReturn(new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379));
|
||||
doNothing().when(proxyManager).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
|
||||
Ec2Service ec2Service = org.mockito.Mockito.mock(Ec2Service.class);
|
||||
kmsService = org.mockito.Mockito.mock(KmsService.class);
|
||||
when(kmsService.describeKey(any(), any())).thenThrow(
|
||||
new AwsException("NotFoundException", "Key not found", 404));
|
||||
service = new ElastiCacheService(containerManager, proxyManager, storageFactory, config,
|
||||
ec2Service, new RegionResolver("us-east-1", "000000000000"));
|
||||
ec2Service, new RegionResolver("us-east-1", "000000000000"), kmsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -88,7 +99,8 @@ class ElastiCacheServiceTest {
|
||||
doNothing().when(pm).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
|
||||
ElastiCacheService svc = new ElastiCacheService(cm, pm, sf, cfg,
|
||||
org.mockito.Mockito.mock(Ec2Service.class),
|
||||
new RegionResolver("us-east-1", "000000000000"));
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
org.mockito.Mockito.mock(KmsService.class));
|
||||
|
||||
svc.createReplicationGroup("g1", "d", AuthMode.PASSWORD, null, "us-east-1");
|
||||
|
||||
@@ -221,4 +233,158 @@ class ElastiCacheServiceTest {
|
||||
|
||||
assertEquals("grp", service.getReplicationGroup("grp").getReplicationGroupId());
|
||||
}
|
||||
|
||||
private static final String KEY_ARN = "arn:aws:kms:us-east-1:000000000000:key/k1";
|
||||
|
||||
private KmsKey knownKey(String... forms) {
|
||||
KmsKey key = new KmsKey();
|
||||
key.setKeyId("k1");
|
||||
key.setArn(KEY_ARN);
|
||||
key.setEnabled(true);
|
||||
key.setKeyState("Enabled");
|
||||
for (String form : forms) {
|
||||
org.mockito.Mockito.doReturn(key).when(kmsService).describeKey(form, "us-east-1");
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createReplicationGroupStoresEncryptionSnapshotSettingsAndTags() {
|
||||
knownKey("alias/cache");
|
||||
ReplicationGroup group = service.createReplicationGroup("g1", "d", AuthMode.NO_AUTH, null, "us-east-1",
|
||||
new ReplicationGroupSettings(true, "alias/cache", 7, "06:30-07:30"),
|
||||
Map.of("Name", "g1", "env", "tst"));
|
||||
|
||||
ReplicationGroup stored = service.getReplicationGroup("g1");
|
||||
assertTrue(stored.isAtRestEncryptionEnabled());
|
||||
assertEquals(KEY_ARN, stored.getKmsKeyId());
|
||||
assertEquals(7, stored.getSnapshotRetentionLimit());
|
||||
assertEquals("06:30-07:30", stored.getSnapshotWindow());
|
||||
assertEquals(Map.of("Name", "g1", "env", "tst"), stored.getTags());
|
||||
assertEquals("arn:aws:elasticache:us-east-1:000000000000:replicationgroup:g1", group.getArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createReplicationGroupWithoutSettingsKeepsAwsDefaults() {
|
||||
service.createReplicationGroup("g1", "d", AuthMode.NO_AUTH, null, "us-east-1");
|
||||
ReplicationGroup stored = service.getReplicationGroup("g1");
|
||||
assertFalse(stored.isAtRestEncryptionEnabled());
|
||||
assertNull(stored.getKmsKeyId());
|
||||
assertEquals(0, stored.getSnapshotRetentionLimit());
|
||||
assertTrue(stored.getTags().isEmpty());
|
||||
assertEquals(ReplicationGroupSettings.DEFAULT_SNAPSHOT_WINDOW, stored.getSnapshotWindow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createReplicationGroupRejectsAKeyItCannotUseBeforeStartingAContainer() {
|
||||
AwsException missing = assertThrows(AwsException.class, () -> service.createReplicationGroup(
|
||||
"g1", "d", AuthMode.NO_AUTH, null, "us-east-1",
|
||||
new ReplicationGroupSettings(true, "alias/does-not-exist", null, null), Map.of()));
|
||||
assertEquals("InvalidParameterValue", missing.getErrorCode());
|
||||
assertEquals("KMS key does not exist with key id: alias/does-not-exist", missing.getMessage());
|
||||
assertThrows(AwsException.class, () -> service.getReplicationGroup("g1"));
|
||||
org.mockito.Mockito.verify(containerManager, org.mockito.Mockito.never()).start(anyString(), anyString());
|
||||
|
||||
AwsException combination = assertThrows(AwsException.class, () -> service.createReplicationGroup(
|
||||
"g1", "d", AuthMode.NO_AUTH, null, "us-east-1",
|
||||
new ReplicationGroupSettings(false, KEY_ARN, null, null), Map.of()));
|
||||
assertEquals("InvalidParameterCombination", combination.getErrorCode());
|
||||
assertEquals("Please enable encryption at rest to use Customer Managed CMK", combination.getMessage());
|
||||
// leaving AtRestEncryptionEnabled out is false on a live account, refused the same way
|
||||
AwsException omitted = assertThrows(AwsException.class, () -> service.createReplicationGroup(
|
||||
"g1", "d", AuthMode.NO_AUTH, null, "us-east-1",
|
||||
new ReplicationGroupSettings(null, KEY_ARN, null, null), Map.of()));
|
||||
assertEquals("InvalidParameterCombination", omitted.getErrorCode());
|
||||
|
||||
AwsException retention = assertThrows(AwsException.class, () -> service.createReplicationGroup(
|
||||
"g1", "d", AuthMode.NO_AUTH, null, "us-east-1",
|
||||
new ReplicationGroupSettings(null, null, 36, null), Map.of()));
|
||||
assertEquals("Invalid snapshot retention limit: 36. Retention limit must be between 0 and 35.", retention.getMessage());
|
||||
AwsException window = assertThrows(AwsException.class, () -> service.createReplicationGroup(
|
||||
"g1", "d", AuthMode.NO_AUTH, null, "us-east-1",
|
||||
new ReplicationGroupSettings(null, null, null, "25:00-26:00"), Map.of()));
|
||||
assertEquals("Invalid backup window format. Should be specified as a range hh24:mi-hh24:mi (24H Clock UTC). Example: 03:15-08:15", window.getMessage());
|
||||
AwsException shortWindow = assertThrows(AwsException.class, () -> service.createReplicationGroup(
|
||||
"g1", "d", AuthMode.NO_AUTH, null, "us-east-1",
|
||||
new ReplicationGroupSettings(null, null, null, "05:00-05:30"), Map.of()));
|
||||
assertEquals("Snapshot window must be at least 60 minutes.", shortWindow.getMessage());
|
||||
// equal start and end is an empty window, not a full day
|
||||
AwsException emptyWindow = assertThrows(AwsException.class, () -> service.createReplicationGroup(
|
||||
"g1", "d", AuthMode.NO_AUTH, null, "us-east-1",
|
||||
new ReplicationGroupSettings(null, null, null, "05:00-05:00"), Map.of()));
|
||||
assertEquals("Snapshot window must be at least 60 minutes.", emptyWindow.getMessage());
|
||||
// while a window wrapping midnight is measured across it
|
||||
service.createReplicationGroup("wrap", "d", AuthMode.NO_AUTH, null, "us-east-1",
|
||||
new ReplicationGroupSettings(null, null, null, "23:30-00:30"), Map.of());
|
||||
assertEquals("23:30-00:30", service.getReplicationGroup("wrap").getSnapshotWindow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyReplicationGroupChangesSnapshotSettingsAndKeepsEncryption() {
|
||||
knownKey(KEY_ARN);
|
||||
service.createReplicationGroup("g1", "d", AuthMode.NO_AUTH, null, "us-east-1",
|
||||
new ReplicationGroupSettings(true, KEY_ARN, 7, "06:30-07:30"), Map.of());
|
||||
|
||||
service.modifyReplicationGroup("g1", null, null, new ReplicationGroupSettings(null, null, 3, "01:00-02:00"));
|
||||
|
||||
ReplicationGroup stored = service.getReplicationGroup("g1");
|
||||
assertEquals(3, stored.getSnapshotRetentionLimit());
|
||||
assertEquals("01:00-02:00", stored.getSnapshotWindow());
|
||||
assertTrue(stored.isAtRestEncryptionEnabled());
|
||||
assertEquals(KEY_ARN, stored.getKmsKeyId());
|
||||
|
||||
assertThrows(AwsException.class, () -> service.modifyReplicationGroup("g1", null, null,
|
||||
new ReplicationGroupSettings(null, null, null, "25:00-26:00")));
|
||||
assertEquals("01:00-02:00", service.getReplicationGroup("g1").getSnapshotWindow());
|
||||
|
||||
// a refusal later in the same request must not leave the earlier part applied: the store
|
||||
// hands out its own object, so settings applied before the user check would stay visible
|
||||
AwsException unknownUser = assertThrows(AwsException.class, () -> service.modifyReplicationGroup(
|
||||
"g1", List.of("no-such-user"), null, new ReplicationGroupSettings(null, null, 9, "03:00-04:00")));
|
||||
assertEquals("UserNotFoundFault", unknownUser.getErrorCode());
|
||||
assertEquals(3, service.getReplicationGroup("g1").getSnapshotRetentionLimit());
|
||||
assertEquals("01:00-02:00", service.getReplicationGroup("g1").getSnapshotWindow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyReplicationGroupCannotWriteAGroupBackAfterDelete() throws Exception {
|
||||
// modify has read the group, delete removes it, modify writes its copy back — the store is
|
||||
// held inside modify's put so the delete can be run in exactly that window
|
||||
PausingStorageBackend<ReplicationGroup> pausing = new PausingStorageBackend<>(new InMemoryStorage<>());
|
||||
StorageFactory factory = org.mockito.Mockito.mock(StorageFactory.class);
|
||||
when(factory.create(anyString(), eq("elasticache-groups.json"), any()))
|
||||
.thenAnswer(inv -> new AccountAwareStorageBackend<>(pausing, null, "000000000000"));
|
||||
when(factory.create(anyString(), org.mockito.ArgumentMatchers.argThat(f -> !"elasticache-groups.json".equals(f)), any()))
|
||||
.thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
ElastiCacheService svc = new ElastiCacheService(containerManager, proxyManager, factory, config,
|
||||
org.mockito.Mockito.mock(Ec2Service.class), new RegionResolver("us-east-1", "000000000000"), kmsService);
|
||||
svc.createReplicationGroup("g1", "d", AuthMode.NO_AUTH, null, "us-east-1");
|
||||
|
||||
pausing.pauseOn(PausingStorageBackend.Call.PUT, "g1");
|
||||
java.util.concurrent.atomic.AtomicReference<Throwable> modifyOutcome = new java.util.concurrent.atomic.AtomicReference<>();
|
||||
Thread modify = new Thread(() -> {
|
||||
try {
|
||||
svc.modifyReplicationGroup("g1", null, null, new ReplicationGroupSettings(null, null, 3, null));
|
||||
} catch (Throwable t) {
|
||||
modifyOutcome.set(t);
|
||||
}
|
||||
});
|
||||
modify.start();
|
||||
pausing.awaitReached();
|
||||
|
||||
Thread delete = new Thread(() -> svc.deleteReplicationGroup("g1"));
|
||||
delete.start();
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
||||
while (delete.getState() != Thread.State.BLOCKED && delete.getState() != Thread.State.TERMINATED) {
|
||||
assertTrue(System.nanoTime() < deadline, "delete neither ran nor queued");
|
||||
Thread.onSpinWait();
|
||||
}
|
||||
pausing.release();
|
||||
modify.join(5000);
|
||||
delete.join(5000);
|
||||
|
||||
assertNull(modifyOutcome.get(), "modify completed before the delete");
|
||||
assertThrows(AwsException.class, () -> svc.getReplicationGroup("g1"),
|
||||
"the deleted group must not come back from the modify");
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package io.github.hectorvent.floci.services.elasticache;
|
||||
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* A store that can be stopped in the middle of an operation, so a race can be staged rather than
|
||||
* hoped for.
|
||||
*
|
||||
* <p>A concurrency test that loops and waits for an unlucky interleaving proves nothing when the
|
||||
* window is a few instructions wide: it passes with the fix and without it. Holding one thread at a
|
||||
* chosen call while another runs to completion makes the interleaving the test claims to cover the
|
||||
* one it actually runs.
|
||||
*/
|
||||
final class PausingStorageBackend<V> implements StorageBackend<String, V> {
|
||||
|
||||
/** Which call to hold, and on which key. */
|
||||
enum Call { PUT, DELETE, SCAN }
|
||||
|
||||
private final StorageBackend<String, V> delegate;
|
||||
private volatile Call pauseOn;
|
||||
private volatile String pauseKey;
|
||||
private final java.util.concurrent.atomic.AtomicInteger skip =
|
||||
new java.util.concurrent.atomic.AtomicInteger();
|
||||
private final CountDownLatch reached = new CountDownLatch(1);
|
||||
private final CountDownLatch release = new CountDownLatch(1);
|
||||
|
||||
PausingStorageBackend(StorageBackend<String, V> delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
/** Hold the next matching call until {@link #release()}; {@code key} may be null for SCAN. */
|
||||
void pauseOn(Call call, String key) {
|
||||
pauseOn(call, key, 0);
|
||||
}
|
||||
|
||||
/** As above, after letting {@code skipFirst} matching calls through untouched. */
|
||||
void pauseOn(Call call, String key, int skipFirst) {
|
||||
this.pauseOn = call;
|
||||
this.pauseKey = key;
|
||||
this.skip.set(skipFirst);
|
||||
}
|
||||
|
||||
/** Waits until the paused call has been reached. */
|
||||
void awaitReached() throws InterruptedException {
|
||||
if (!reached.await(10, TimeUnit.SECONDS)) {
|
||||
throw new IllegalStateException("the paused call was never reached");
|
||||
}
|
||||
}
|
||||
|
||||
void release() {
|
||||
release.countDown();
|
||||
}
|
||||
|
||||
private void pauseIfMatching(Call call, String key) {
|
||||
// Keys arrive account-prefixed here, since this sits underneath the account-aware layer.
|
||||
if (pauseOn != call || (pauseKey != null && (key == null || !key.endsWith(pauseKey)))) {
|
||||
return;
|
||||
}
|
||||
if (skip.getAndDecrement() > 0) {
|
||||
return;
|
||||
}
|
||||
pauseOn = null;
|
||||
reached.countDown();
|
||||
try {
|
||||
if (!release.await(10, TimeUnit.SECONDS)) {
|
||||
throw new IllegalStateException("the paused call was never released");
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void put(String key, V value) {
|
||||
pauseIfMatching(Call.PUT, key);
|
||||
delegate.put(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<V> get(String key) {
|
||||
return delegate.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String key) {
|
||||
pauseIfMatching(Call.DELETE, key);
|
||||
delegate.delete(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<V> scan(Predicate<String> keyFilter) {
|
||||
pauseIfMatching(Call.SCAN, null);
|
||||
return delegate.scan(keyFilter);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> keys() {
|
||||
return delegate.keys();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
delegate.flush();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
delegate.load();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
delegate.clear();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user