fix(mq): scope brokers by account and Region (#8433)

* fix(mq): scope brokers by account and Region
* fix(mq): write a ready broker back under the account and key it is stored under
* test(mq): check broker Regions over HTTP in an account of its own
* fix(mq): check a broker's name and store the broker under one lock
* fix(mq): keep a broker name unique across the account's Regions
* refactor(mq): derive a broker's Region in one place
* test(mq): race two broker creates on the shared parked-store helper
* refactor(mq): run the readiness poller's pass from a method tests can call
* test(mq): check the error type of each refusal from another Region
* test(mq): run the other Region's refusals through one loop
* refactor(storage): name the all-accounts migration like its neighbours
* docs(mq): say that brokers are Regional and names unique in the account
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-15 08:33:24 -04:00
1 parent adfe173764
commit e9f842765d
11 files changed
+424 -140

No files matched your search

@@ -4,6 +4,7 @@ import io.floci.aws.core.common.RequestContext;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -363,6 +364,48 @@ class AccountAwareStorageBackendTest {
assertFalse(raw.get("111111111111/legacy").isPresent());
}
/**
* Every account's legacy entries move within that account, an unprefixed one counting as the default's,
* and the owner check is handed the account holding each legacy entry.
*/
@Test
void migrateLegacyEntriesInAllAccountsMovesEachWithinItsOwnAccount() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
raw.put("gen0", "default-owned");
raw.put("123456789012/gen1", "account-owned");
raw.put("123456789012/kept", "not-owned");
raw.put("123456789012/us-east-1::current", "current");
AccountAwareStorageBackend<String> storage =
new AccountAwareStorageBackend<>(raw, null, "000000000000");
List<String> ownerChecks = new ArrayList<>();
storage.migrateLegacyEntriesInAllAccounts(key -> !key.contains("::"), value -> "us-east-1::" + value,
(account, value) -> {
ownerChecks.add(account + " " + value);
return !value.equals("not-owned");
});
assertEquals(List.of("000000000000 default-owned", "123456789012 account-owned", "123456789012 not-owned"),
ownerChecks.stream().sorted().toList());
assertEquals(Set.of("000000000000/us-east-1::default-owned", "123456789012/us-east-1::account-owned",
"123456789012/kept", "123456789012/us-east-1::current"), Set.copyOf(raw.keys()));
}
/** Without an owner check, every account's legacy entries move. */
@Test
void migrateLegacyEntriesInAllAccountsWithoutAnOwnerCheckMovesEveryLegacyEntry() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
raw.put("gen0", "default");
raw.put("123456789012/gen1", "account");
AccountAwareStorageBackend<String> storage =
new AccountAwareStorageBackend<>(raw, null, "000000000000");
storage.migrateLegacyEntriesInAllAccounts(key -> !key.contains("::"), value -> "us-east-1::" + value);
assertEquals(Set.of("000000000000/us-east-1::default", "123456789012/us-east-1::account"),
Set.copyOf(raw.keys()));
}
/**
* {@code get} and {@code getForAccountMigratingLegacy} both migrate a pre-multi-account entry, and
* both delete the legacy key once they have copied it. Unless they hold the same monitor, two readers
@@ -1,10 +1,18 @@
package io.floci.aws.services.amazonmq;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
@@ -16,8 +24,34 @@ import static org.hamcrest.Matchers.startsWith;
@QuarkusTest
class AmazonMqControllerIntegrationTest {
private static final AtomicLong ACCOUNTS = new AtomicLong(731300000000L);
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
private String createRabbitBroker(String name) {
return given()
return createRabbitBroker(given(), name);
}
/** A broker created for {@code account} in {@code region}, deleted after the test unless the test did. */
private String createRabbitBroker(String account, String region, String name) {
String brokerId = createRabbitBroker(mq(account, region), name);
cleanup.register(() -> mq(account, region).when().delete("/v1/brokers/{id}", brokerId));
return brokerId;
}
private static RequestSpecification mq(String account, String region) {
return given().header("Authorization", auth(account, region, "mq"));
}
private static String createRabbitBroker(RequestSpecification request, String name) {
return postRabbitBroker(request, name)
.statusCode(200)
.extract().path("brokerId");
}
private static ValidatableResponse postRabbitBroker(RequestSpecification request, String name) {
return request
.contentType("application/json")
.body("""
{"brokerName": "%s", "engineType": "RABBITMQ",
@@ -27,9 +61,7 @@ class AmazonMqControllerIntegrationTest {
""".formatted(name))
.when()
.post("/v1/brokers")
.then()
.statusCode(200)
.extract().path("brokerId");
.then();
}
@Test
@@ -202,4 +234,50 @@ class AmazonMqControllerIntegrationTest {
.then()
.statusCode(400);
}
/**
* Brokers are Regional: another Region of the account neither lists, describes, reboots nor deletes
* one, nor describes its shared resources. Its name is unique in the account, so another Region refuses
* it too. The test works in an account of its own, so each listing holds only its brokers.
*/
@Test
void aBrokerIsSeenOnlyInTheRegionItWasCreatedIn() {
String account = Long.toString(ACCOUNTS.incrementAndGet());
String inIreland = createRabbitBroker(account, "eu-west-1", "it-regional");
mq(account, "us-east-1")
.when()
.get("/v1/brokers")
.then()
.statusCode(200)
.body("brokerSummaries.brokerId", equalTo(List.of()));
for (Function<RequestSpecification, Response> call : List.<Function<RequestSpecification, Response>>of(
request -> request.get("/v1/brokers/{id}", inIreland),
request -> request.get("/v1/brokers/{id}/shared-resources", inIreland),
request -> request.contentType("application/json").post("/v1/brokers/{id}/reboot", inIreland),
request -> request.delete("/v1/brokers/{id}", inIreland))) {
call.apply(mq(account, "us-east-1"))
.then()
.statusCode(404)
.body("__type", equalTo("NotFoundException"));
}
postRabbitBroker(mq(account, "us-east-1"), "it-regional")
.statusCode(409)
.body("__type", equalTo("ConflictException"));
String inVirginia = createRabbitBroker(account, "us-east-1", "it-regional-virginia");
mq(account, "eu-west-1")
.when()
.get("/v1/brokers")
.then()
.statusCode(200)
.body("brokerSummaries.brokerId", equalTo(List.of(inIreland)));
mq(account, "us-east-1")
.when()
.get("/v1/brokers")
.then()
.statusCode(200)
.body("brokerSummaries.brokerId", equalTo(List.of(inVirginia)));
}
}
@@ -4,42 +4,42 @@ import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.amazonmq.container.RabbitMqManager;
import io.floci.aws.services.amazonmq.model.Broker;
import io.floci.aws.services.amazonmq.model.BrokerState;
import io.floci.aws.services.amazonmq.model.MqUser;
import io.floci.aws.testing.ParkingStore;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.mockito.Mockito;
import java.util.List;
import static io.floci.aws.testing.ParkingStoreAssertions.assertOperationWaitsForParkedStore;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
class AmazonMqServiceTest {
private static final String ACCOUNT = "000000000000";
private AccountAwareStorageBackend<Broker> brokers;
private RegionResolver regionResolver;
private AmazonMqService service;
@BeforeEach
void setUp() {
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
.thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));
brokers = AccountAwareStorageBackend.inMemory(ACCOUNT);
regionResolver = Mockito.spy(new RegionResolver("us-east-1", ACCOUNT));
service = newService(true, Mockito.mock(RabbitMqManager.class));
}
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.AmazonMqServiceConfig mqConfig = Mockito.mock(EmulatorConfig.AmazonMqServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.amazonmq()).thenReturn(mqConfig);
when(mqConfig.mock()).thenReturn(true);
when(config.defaultRegion()).thenReturn("us-east-1");
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
RabbitMqManager rabbitMqManager = Mockito.mock(RabbitMqManager.class);
service = new AmazonMqService(storageFactory, config, regionResolver, rabbitMqManager);
@AfterEach
void stopPoller() {
service.shutdown();
}
private CreateBrokerParams rabbitParams(String name) {
@@ -185,23 +185,123 @@ class AmazonMqServiceTest {
assertThrows(AwsException.class, () -> realModeService.rebootBroker(failed.getBrokerId()));
}
/** Brokers are Regional: another Region of the account neither lists, describes, reboots nor deletes one. */
@Test
void aBrokerIsSeenOnlyInItsOwnRegion() {
String brokerId = service.createBroker(rabbitParams("orders")).getBrokerId();
inRegion("eu-west-1");
assertEquals(List.of(), service.listBrokers());
for (Executable call : List.<Executable>of(
() -> service.describeBroker(brokerId),
() -> service.rebootBroker(brokerId),
() -> service.deleteBroker(brokerId))) {
assertEquals("NotFoundException", assertThrows(AwsException.class, call).getErrorCode());
}
inRegion("us-east-1");
assertEquals(List.of(brokerId), service.listBrokers().stream().map(Broker::getBrokerId).toList());
assertEquals("orders", service.describeBroker(brokerId).getBrokerName());
}
/**
* A broker name is unique in the account, across its Regions, as the CreateBroker reference documents: another
* Region refuses it, and a broker created there under another name carries that Region's ARN.
*/
@Test
void aBrokerNameIsUniqueAcrossTheAccountsRegions() {
service.createBroker(rabbitParams("orders"));
inRegion("eu-west-1");
assertEquals("ConflictException",
assertThrows(AwsException.class, () -> service.createBroker(rabbitParams("orders"))).getErrorCode());
assertEquals(List.of(), service.listBrokers());
Broker inIreland = service.createBroker(rabbitParams("payments"));
assertEquals("arn:aws:mq:eu-west-1:" + ACCOUNT + ":broker:payments:" + inIreland.getBrokerId(),
inIreland.getBrokerArn());
}
/** A broker stored before brokers were keyed by Region moves, at startup, to the Region its ARN names. */
@Test
void aBrokerStoredUnderItsBareIdMovesToItsArnsRegionOnStartup() {
Broker legacy = new Broker("b-legacy", "arn:aws:mq:eu-west-1:" + ACCOUNT + ":broker:legacy:b-legacy",
"legacy", "RABBITMQ", "3.13", "SINGLE_INSTANCE", "mq.t3.micro");
legacy.setAccountId(ACCOUNT);
legacy.setBrokerState(BrokerState.RUNNING);
brokers.put("b-legacy", legacy);
service.init();
assertEquals(List.of(AmazonMqService.brokerKey("eu-west-1", "b-legacy")),
List.copyOf(brokers.keys()));
inRegion("eu-west-1");
assertEquals("legacy", service.describeBroker("b-legacy").getBrokerName());
inRegion("us-east-1");
assertEquals(List.of(), service.listBrokers());
}
/**
* The readiness poller writes a broker back under the account and the key it is stored under, even
* for a record that names no account, as one written before brokers carried theirs.
*/
@Test
void aBrokerTurningReadyStaysInItsAccountAndRegion() {
RabbitMqManager readyManager = Mockito.mock(RabbitMqManager.class);
when(readyManager.isReady(Mockito.any())).thenReturn(true);
service = newService(false, readyManager);
Broker starting = new Broker("b-starting", "arn:aws:mq:eu-west-1:111111111111:broker:starting:b-starting",
"starting", "RABBITMQ", "3.13", "SINGLE_INSTANCE", "mq.t3.micro");
starting.setBrokerState(BrokerState.CREATION_IN_PROGRESS);
String key = AmazonMqService.brokerKey("eu-west-1", "b-starting");
brokers.putForAccount("111111111111", key, starting);
service.pollReadiness();
assertEquals(BrokerState.RUNNING,
brokers.getForAccount("111111111111", key).map(Broker::getBrokerState).orElse(null));
assertEquals(1, brokers.scanAllAccounts().size());
}
/**
* Two creates of one broker name in an account: the second waits for the first, parked as it stores its
* broker, and then finds the name taken, so only one broker has it.
*/
@Test
void aSecondCreateOfANameWaitsForTheFirstAndIsRefused() throws Exception {
ParkingStore<Broker> parking = new ParkingStore<>();
brokers = new AccountAwareStorageBackend<>(parking, null, ACCOUNT);
service = newService(true, Mockito.mock(RabbitMqManager.class));
parking.parkNextWrite();
assertOperationWaitsForParkedStore(parking,
() -> service.createBroker(rabbitParams("orders")),
() -> assertEquals("ConflictException", assertThrows(AwsException.class,
() -> service.createBroker(rabbitParams("orders"))).getErrorCode()));
assertEquals(1, service.listBrokers().size());
}
private AmazonMqService realModeServiceWithFailingManager() {
RabbitMqManager failingManager = Mockito.mock(RabbitMqManager.class);
Mockito.doThrow(new RuntimeException("docker unavailable"))
.when(failingManager).startContainer(Mockito.any());
return newService(false, failingManager);
}
/** A service over {@link #brokers} answering in the Region {@link #regionResolver} gives. */
private AmazonMqService newService(boolean mock, RabbitMqManager rabbitMqManager) {
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
.thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));
Mockito.doReturn(brokers).when(storageFactory).create(Mockito.anyString(), Mockito.anyString(), Mockito.any());
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.AmazonMqServiceConfig mqConfig = Mockito.mock(EmulatorConfig.AmazonMqServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.amazonmq()).thenReturn(mqConfig);
when(mqConfig.mock()).thenReturn(false);
when(config.defaultRegion()).thenReturn("us-east-1");
when(mqConfig.mock()).thenReturn(mock);
return new AmazonMqService(storageFactory, config, regionResolver, rabbitMqManager);
}
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
RabbitMqManager failingManager = Mockito.mock(RabbitMqManager.class);
Mockito.doThrow(new RuntimeException("docker unavailable"))
.when(failingManager).startContainer(Mockito.any());
return new AmazonMqService(storageFactory, config, regionResolver, failingManager);
private void inRegion(String region) {
Mockito.doReturn(region).when(regionResolver).getRegion();
}
}
@@ -51,6 +51,17 @@ class BrokerTest {
assertEquals("EBS", roundTripped.getStorageType());
}
/** A broker's Region is the one its ARN names, and the default Region's for a broker recorded without one. */
@Test
void aBrokersRegionIsTheOneItsArnNames() {
Broker inIreland = new Broker("b-1", "arn:aws:mq:eu-west-1:000000000000:broker:n:b-1",
"n", "RABBITMQ", "3.13", "SINGLE_INSTANCE", "mq.t3.micro");
Broker withoutArn = new Broker("b-2", null, "m", "RABBITMQ", "3.13", "SINGLE_INSTANCE", "mq.t3.micro");
assertEquals("eu-west-1", inIreland.region("us-east-1"));
assertEquals("us-east-1", withoutArn.region("us-east-1"));
}
/** A broker persisted before these members existed must still load, with them absent. */
@Test
void brokerPersistedWithoutNewMembersStillLoads() throws Exception {