Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(amazonmq): add Amazon MQ broker control plane backed by RabbitMQ (#1642)

Ahmed khaled188854f2dff7
diff --git a/README.md b/README.md
index 8ff903b7f5..71e004db0f 100644
--- a/README.md
+++ b/README.md
@@ -178,7 +178,7 @@ LocalStack's community edition [sunset in March 2026](https://blog.localstack.cl
| CodeBuild | Real Docker execution | No |
| Native binary | ~40 MB | No |
-**65 AWS services. Broad coverage. Free forever.**
+**66 AWS services. Broad coverage. Free forever.**
## Architecture Overview
@@ -225,7 +225,7 @@ Floci supports local emulation for application services, data services, eventing
| Containers and compute | ECS, EC2, EKS, ECR, CodeBuild, CodeDeploy, CodePipeline, AWS Batch, Auto Scaling, Elastic Beanstalk, ELB v2 |
| Data, analytics, and AI | Athena, Glue, EMR, Firehose, OpenSearch, S3 Vectors, Textract, Transcribe, Bedrock Runtime |
| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache |
-| Messaging and transfer | SES, Kinesis, MSK, Transfer Family |
+| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family |
| Security and governance | WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API |
| Cost and billing | Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
| Backup and config | AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation |
@@ -266,6 +266,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| Neptune | Real Docker | Graph DB via TinkerPop Gremlin Server (default) or Neo4j for openCypher/Bolt (`NEPTUNE_DB_TYPE`); RDS-shaped control plane; SigV4 proxy on port 8182 |
| DocumentDB | Real Docker, mock mode available | MongoDB-compatible cluster via real MongoDB containers; RDS-shaped control plane; MongoDB wire protocol on port 27017 |
| MSK | Real Docker | Kafka-compatible broker via Redpanda |
+| Amazon MQ | Real Docker | RabbitMQ broker via rabbitmq:3-management; AMQP + management console |
| Athena | In-process with DuckDB sidecar | Real SQL execution over S3 and Glue-backed views |
| Glue | In-process | Data Catalog, Schema Registry, tables consumed by Athena |
| EMR | In-process | Cluster (job flow) lifecycle, instance groups and fleets, steps, security configurations, tagging |
@@ -320,6 +321,7 @@ Floci uses real Docker containers when in-process emulation would reduce fidelit
| Neptune (openCypher) | `neo4j:5-community` | Neo4j backend when `FLOCI_SERVICES_NEPTUNE_DB_TYPE=neo4j`; openCypher over Bolt |
| DocumentDB | `mongo:7.0` | MongoDB engine; MongoDB wire protocol on port 27017 |
| MSK | `redpandadata/redpanda:latest` | Kafka-compatible broker via Redpanda |
+| Amazon MQ | `rabbitmq:3-management` | RabbitMQ broker; AMQP on port 5672, management console on 15672 |
| EC2 | AMI-mapped Linux images | Linux containers, SSH key injection, UserData, IMDS, IAM credentials |
| ECS | User-specified task image | Container lifecycle, start, stop, health checks |
| EKS | `rancher/k3s:latest` | Kubernetes API server via k3s |
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index 4b1c137aa9..792bd23ddb 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -140,6 +140,10 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>kafka</artifactId>
</dependency>
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>mq</artifactId>
+ </dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>athena</artifactId>
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index 0f2246aae6..d109d3307c 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -37,6 +37,7 @@ import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.kafka.KafkaClient;
+import software.amazon.awssdk.services.mq.MqClient;
import software.amazon.awssdk.services.athena.AthenaClient;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.firehose.FirehoseClient;
@@ -383,6 +384,14 @@ public final class TestFixtures {
.build();
}
+ public static MqClient mqClient() {
+ return MqClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
public static AthenaClient athenaClient() {
return AthenaClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AmazonMqTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AmazonMqTest.java
new file mode 100644
index 0000000000..ffffdd3661
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AmazonMqTest.java
@@ -0,0 +1,161 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import software.amazon.awssdk.services.mq.MqClient;
+import software.amazon.awssdk.services.mq.model.BrokerState;
+import software.amazon.awssdk.services.mq.model.CreateBrokerRequest;
+import software.amazon.awssdk.services.mq.model.CreateBrokerResponse;
+import software.amazon.awssdk.services.mq.model.CreateUserRequest;
+import software.amazon.awssdk.services.mq.model.DeleteBrokerRequest;
+import software.amazon.awssdk.services.mq.model.DeploymentMode;
+import software.amazon.awssdk.services.mq.model.DescribeBrokerRequest;
+import software.amazon.awssdk.services.mq.model.DescribeBrokerResponse;
+import software.amazon.awssdk.services.mq.model.EngineType;
+import software.amazon.awssdk.services.mq.model.ListBrokersRequest;
+import software.amazon.awssdk.services.mq.model.MqException;
+import software.amazon.awssdk.services.mq.model.User;
+
+import java.time.Duration;
+import java.time.Instant;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * Exercises the real RabbitMQ container path: CreateBroker provisions a
+ * rabbitmq:3-management container, the broker transitions to RUNNING once its
+ * management API answers, and the AMQP/console endpoints are published. Also
+ * confirms the AWS-faithful rejection of the ActiveMQ-only User API on RabbitMQ.
+ *
+ * <p>Requires a running Floci with {@code amazonmq.mock=false} and a working
+ * Docker daemon. When the broker never reaches RUNNING (Docker unavailable in
+ * CI), the dependent assertions skip rather than fail.
+ */
+@DisplayName("Amazon MQ (RabbitMQ)")
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class AmazonMqTest {
+
+ private static MqClient mq;
+ private static String brokerId;
+ private static boolean reachedRunning;
+ private static final String BROKER_NAME = TestFixtures.uniqueName("mq-broker");
+
+ @BeforeAll
+ static void setup() {
+ mq = TestFixtures.mqClient();
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (mq != null) {
+ if (brokerId != null) {
+ try {
+ mq.deleteBroker(DeleteBrokerRequest.builder().brokerId(brokerId).build());
+ } catch (Exception ignored) {}
+ }
+ mq.close();
+ }
+ }
+
+ @Test
+ @Order(1)
+ void createBroker() {
+ CreateBrokerResponse response = mq.createBroker(CreateBrokerRequest.builder()
+ .brokerName(BROKER_NAME)
+ .engineType(EngineType.RABBITMQ)
+ .engineVersion("3.13")
+ .deploymentMode(DeploymentMode.SINGLE_INSTANCE)
+ .hostInstanceType("mq.t3.micro")
+ .publiclyAccessible(false)
+ .autoMinorVersionUpgrade(true)
+ .users(User.builder()
+ .username("admin")
+ .password("AdminPass123")
+ .consoleAccess(true)
+ .build())
+ .build());
+
+ assertThat(response.brokerId()).isNotNull();
+ assertThat(response.brokerArn()).contains(":mq:");
+ brokerId = response.brokerId();
+ }
+
+ @Test
+ @Order(2)
+ void brokerReachesRunningWithEndpoints() {
+ requireBroker();
+
+ DescribeBrokerResponse describe = waitForState(BrokerState.RUNNING, Duration.ofSeconds(120));
+ Assumptions.assumeTrue(describe != null,
+ "Broker did not reach RUNNING (Docker likely unavailable); skipping endpoint checks");
+
+ reachedRunning = true;
+ assertThat(describe.brokerName()).isEqualTo(BROKER_NAME);
+ assertThat(describe.engineType()).isEqualTo(EngineType.RABBITMQ);
+ assertThat(describe.brokerInstances()).isNotEmpty();
+ assertThat(describe.brokerInstances().get(0).endpoints().get(0)).startsWith("amqp://");
+ assertThat(describe.brokerInstances().get(0).consoleURL()).startsWith("http://");
+ }
+
+ @Test
+ @Order(3)
+ void listBrokersIncludesCreated() {
+ requireBroker();
+
+ var response = mq.listBrokers(ListBrokersRequest.builder().build());
+ assertThat(response.brokerSummaries()).anyMatch(b -> b.brokerId().equals(brokerId));
+ }
+
+ @Test
+ @Order(4)
+ void userApiRejectedForRabbitMq() {
+ requireBroker();
+
+ // The standalone User API is ActiveMQ-only; AWS rejects it for RabbitMQ.
+ assertThatThrownBy(() -> mq.createUser(CreateUserRequest.builder()
+ .brokerId(brokerId)
+ .username("alice")
+ .password("AnotherPass99")
+ .build()))
+ .isInstanceOf(MqException.class);
+ }
+
+ @Test
+ @Order(5)
+ void deleteBroker() {
+ requireBroker();
+
+ var response = mq.deleteBroker(DeleteBrokerRequest.builder().brokerId(brokerId).build());
+ assertThat(response.brokerId()).isEqualTo(brokerId);
+ brokerId = null;
+ }
+
+ private DescribeBrokerResponse waitForState(BrokerState target, Duration timeout) {
+ Instant deadline = Instant.now().plus(timeout);
+ while (Instant.now().isBefore(deadline)) {
+ DescribeBrokerResponse describe = mq.describeBroker(
+ DescribeBrokerRequest.builder().brokerId(brokerId).build());
+ if (describe.brokerState() == target) {
+ return describe;
+ }
+ try {
+ Thread.sleep(2000);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ break;
+ }
+ }
+ return null;
+ }
+
+ private static void requireBroker() {
+ Assumptions.assumeTrue(brokerId != null, "Broker must exist from earlier ordered test");
+ }
+}
diff --git a/docs/index.md b/docs/index.md
index 719d3098f5..b44de44433 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -12,7 +12,7 @@ Floci is a fast, free, and open-source local AWS service emulator built for deve
## Supported Services
-Floci emulates 65 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.
+Floci emulates 66 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.
| Service | Protocol |
|---|---|
@@ -40,6 +40,7 @@ Floci emulates 65 AWS services. See the [Services Overview](services/index.md) f
| Neptune (graph DB / Gremlin) | Query + WebSocket proxy |
| DocumentDB (MongoDB-compatible) | Query + MongoDB wire |
| MSK (Kafka / Redpanda) | REST JSON + Kafka |
+| Amazon MQ (RabbitMQ) | REST JSON + AMQP |
| Athena | JSON 1.1 |
| Glue Data Catalog + Schema Registry | JSON 1.1 |
| Data Firehose | JSON 1.1 |
@@ -109,7 +110,7 @@ docker compose up -d
aws --endpoint-url http://localhost:4566 s3 mb s3://my-bucket
```
-All 65 AWS services are immediately available at `http://localhost:4566`.
+All 66 AWS services are immediately available at `http://localhost:4566`.
[Get started →](getting-started/quick-start.md){ .md-button .md-button--primary }
[View services →](services/index.md){ .md-button }
diff --git a/docs/services/amazonmq.md b/docs/services/amazonmq.md
new file mode 100644
index 0000000000..c88eccbf47
--- /dev/null
+++ b/docs/services/amazonmq.md
@@ -0,0 +1,81 @@
+# Amazon MQ (RabbitMQ)
+
+**Protocol:** REST-JSON
+**Endpoint:** `http://localhost:4566/`
+
+Floci emulates Amazon MQ by orchestrating **RabbitMQ** containers. Each broker is
+backed by a real `rabbitmq:3-management` container, so AMQP clients and the RabbitMQ
+management console work against the published endpoints.
+
+Only the **RabbitMQ** engine and the `SINGLE_INSTANCE` deployment mode are supported;
+`CreateBroker` rejects `ACTIVEMQ` and the multi-AZ deployment modes.
+
+## Supported Actions
+
+| Action | Description |
+|---|---|
+| `CreateBroker` | Provisions a RabbitMQ container and seeds the admin user |
+| `DescribeBroker` | Get broker metadata, state, and connection endpoints |
+| `ListBrokers` | List all emulated brokers |
+| `DeleteBroker` | Stops and removes the RabbitMQ container |
+| `RebootBroker` | Reboots the broker |
+
+### User management
+
+Amazon MQ's user API (`CreateUser`, `DescribeUser`, `ListUsers`, `UpdateUser`,
+`DeleteUser`) applies **only to ActiveMQ** brokers. As on real AWS, Floci rejects these
+operations for RabbitMQ brokers with a `BadRequestException`. Manage RabbitMQ users
+through the RabbitMQ management console. The broker's initial administrator is supplied
+in the `CreateBroker` `Users` list (exactly one user is required) and seeded into the
+container.
+
+## Configuration
+
+| Variable | Default | Description |
+|---|---|---|
+| `FLOCI_SERVICES_AMAZONMQ_ENABLED` | `true` | Enable or disable the service |
+| `FLOCI_SERVICES_AMAZONMQ_MOCK` | `false` | `true` = metadata-only CRUD, no Docker containers |
+| `FLOCI_SERVICES_AMAZONMQ_DEFAULT_IMAGE` | `rabbitmq:3-management` | Docker image for RabbitMQ broker containers |
+
+## How it works
+
+When `mock` is set to `false` (default), Floci uses the Docker API to start a RabbitMQ
+container for each created broker. For Docker socket setup, private registry
+authentication, and other Docker settings see [Docker Configuration](../configuration/docker.md).
+
+- **Port Mapping**: The AMQP port (5672) and the management UI (15672) are each mapped to
+ a dynamic host port. Use the endpoints returned by `DescribeBroker` rather than a fixed
+ port.
+- **Admin user**: The `CreateBroker` user is seeded via `RABBITMQ_DEFAULT_USER` /
+ `RABBITMQ_DEFAULT_PASS`. Unlike the built-in `guest` user (which RabbitMQ restricts to
+ loopback connections), this user can authenticate over the mapped port.
+- **Persistence**: Each broker gets a named Docker volume. In memory mode the volume is
+ removed on broker delete; in persistent modes it is retained unless
+ `FLOCI_STORAGE_PRUNE_VOLUMES_ON_DELETE=true`.
+- **Readiness**: The broker state transitions to `RUNNING` once the RabbitMQ management
+ API answers on its port.
+
+## Examples
+
+```bash
+export AWS_ENDPOINT_URL=http://localhost:4566
+
+# Create a broker (exactly one admin user is required for RabbitMQ)
+aws mq create-broker \
+ --broker-name my-broker \
+ --engine-type RABBITMQ \
+ --engine-version "3.13" \
+ --deployment-mode SINGLE_INSTANCE \
+ --host-instance-type mq.t3.micro \
+ --no-publicly-accessible \
+ --auto-minor-version-upgrade \
+ --users '[{"Username":"admin","Password":"AdminPass123","ConsoleAccess":true}]' \
+ --endpoint-url $AWS_ENDPOINT_URL
+
+# Describe a broker (poll until BrokerState is RUNNING)
+BROKER_ID=$(aws mq list-brokers --query 'BrokerSummaries[0].BrokerId' --output text --endpoint-url $AWS_ENDPOINT_URL)
+aws mq describe-broker --broker-id $BROKER_ID --endpoint-url $AWS_ENDPOINT_URL
+
+# Delete a broker
+aws mq delete-broker --broker-id $BROKER_ID --endpoint-url $AWS_ENDPOINT_URL
+```
diff --git a/docs/services/index.md b/docs/services/index.md
index c92330aef4..213f539d29 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -1,6 +1,6 @@
# Services Overview
-Floci emulates 65 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.
+Floci emulates 66 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.
This page is the canonical reference for supported service and operation counts. Some services expose separate control-plane and data-plane rows below. Other docs (and the README) should link here rather than duplicating the table.
@@ -37,6 +37,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 14 |
| [RDS Data API](rds-data.md) | `/Execute`, `/BeginTransaction`, `/CommitTransaction`, `/RollbackTransaction` | REST JSON | 4 |
| [MSK](msk.md) | `/v1/clusters/...`, `/api/v2/clusters/...` + Redpanda broker | REST JSON + Kafka | 8 |
+| [Amazon MQ](amazonmq.md) | `/v1/brokers/...` + RabbitMQ broker | REST JSON + AMQP | 5 |
| [Athena](athena.md) | `POST /` + `X-Amz-Target: AmazonAthena.*` | JSON 1.1 | 4 |
| [Glue](glue.md) | `POST /` + `X-Amz-Target: AWSGlue.*` | JSON 1.1 | 38 |
| [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 8 |
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index fa4ca09960..35f1503ed0 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -416,6 +416,7 @@ public interface EmulatorConfig {
ApiGatewayServiceConfig apigateway();
IamServiceConfig iam();
MskServiceConfig msk();
+ AmazonMqServiceConfig amazonmq();
ElastiCacheServiceConfig elasticache();
MemoryDbServiceConfig memorydb();
RdsServiceConfig rds();
@@ -659,6 +660,17 @@ public interface EmulatorConfig {
int kafkaHostPortMax();
}
+ interface AmazonMqServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+
+ @WithDefault("false")
+ boolean mock();
+
+ @WithDefault("rabbitmq:3-management")
+ String defaultImage();
+ }
+
interface ElastiCacheServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 007651918a..ee3b3d0252 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -80,6 +80,10 @@ public class ResolvedServiceCatalog {
"msk", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("kafka"), Set.of(), Set.of(io.github.hectorvent.floci.services.msk.MskController.class)),
+ descriptor("mq", "amazonmq", config.services().amazonmq().enabled(), true,
+ "amazonmq", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
+ protocols(ServiceProtocol.REST_JSON),
+ Set.of(), Set.of("mq"), Set.of(), Set.of(io.github.hectorvent.floci.services.amazonmq.AmazonMqController.class)),
descriptor("sts", "iam", config.services().iam().enabled(), false,
null, null, 5000L, AwsNamespaces.STS, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY),
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
index fe36bf14dd..effbe02fc0 100644
--- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner;
import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.floci.ui.FlociUiManager;
+import io.github.hectorvent.floci.services.amazonmq.container.RabbitMqManager;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheMemcachedContainerManager;
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
@@ -69,6 +70,7 @@ public class EmulatorLifecycle {
private final DocDbContainerManager docDbContainerManager;
private final NeptuneContainerManager neptuneContainerManager;
private final NeptuneProxyManager neptuneProxyManager;
+ private final RabbitMqManager rabbitMqManager;
private final RdsService rdsService;
private final InitializationHooksRunner initializationHooksRunner;
private final SqsEventSourcePoller sqsPoller;
@@ -93,6 +95,7 @@ public class EmulatorLifecycle {
DocDbContainerManager docDbContainerManager,
NeptuneContainerManager neptuneContainerManager,
NeptuneProxyManager neptuneProxyManager,
+ RabbitMqManager rabbitMqManager,
RdsService rdsService,
InitializationHooksRunner initializationHooksRunner,
SqsEventSourcePoller sqsPoller,
@@ -116,6 +119,7 @@ public class EmulatorLifecycle {
this.docDbContainerManager = docDbContainerManager;
this.neptuneContainerManager = neptuneContainerManager;
this.neptuneProxyManager = neptuneProxyManager;
+ this.rabbitMqManager = rabbitMqManager;
this.rdsService = rdsService;
this.initializationHooksRunner = initializationHooksRunner;
this.sqsPoller = sqsPoller;
@@ -252,6 +256,7 @@ public class EmulatorLifecycle {
memoryDbContainerManager.stopAll();
docDbContainerManager.stopAll();
neptuneContainerManager.stopAll();
+ rabbitMqManager.stopAll();
ecrRegistryManager.shutdown();
flociUiManager.shutdown();
storageFactory.shutdownAll();
diff --git a/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqController.java b/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqController.java
new file mode 100644
index 0000000000..e836c5d952
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqController.java
@@ -0,0 +1,211 @@
+package io.github.hectorvent.floci.services.amazonmq;
+
+import io.github.hectorvent.floci.services.amazonmq.model.Broker;
+import io.github.hectorvent.floci.services.amazonmq.model.MqUser;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.*;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Amazon MQ control plane (REST JSON). Paths and wire keys mirror the AWS
+ * {@code mq} API (camelCase bodies under {@code /v1/brokers}).
+ */
+@Path("/")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public class AmazonMqController {
+
+ private final AmazonMqService service;
+
+ @Inject
+ public AmazonMqController(AmazonMqService service) {
+ this.service = service;
+ }
+
+ @POST
+ @Path("/v1/brokers")
+ public Response createBroker(Map<String, Object> request) {
+ CreateBrokerParams params = new CreateBrokerParams(
+ str(request, "brokerName"),
+ str(request, "engineType"),
+ str(request, "engineVersion"),
+ str(request, "deploymentMode"),
+ str(request, "hostInstanceType"),
+ bool(request, "publiclyAccessible"),
+ bool(request, "autoMinorVersionUpgrade"),
+ parseUsers(request.get("users")),
+ tags(request.get("tags")));
+ Broker broker = service.createBroker(params);
+ return Response.ok(Map.of(
+ "brokerArn", broker.getBrokerArn(),
+ "brokerId", broker.getBrokerId())).build();
+ }
+
+ @GET
+ @Path("/v1/brokers")
+ public Response listBrokers() {
+ List<Map<String, Object>> summaries = new ArrayList<>();
+ for (Broker b : service.listBrokers()) {
+ Map<String, Object> summary = new LinkedHashMap<>();
+ summary.put("brokerArn", b.getBrokerArn());
+ summary.put("brokerId", b.getBrokerId());
+ summary.put("brokerName", b.getBrokerName());
+ summary.put("brokerState", b.getBrokerState());
+ summary.put("created", b.getCreated());
+ summary.put("deploymentMode", b.getDeploymentMode());
+ summary.put("engineType", b.getEngineType());
+ summary.put("hostInstanceType", b.getHostInstanceType());
+ summaries.add(summary);
+ }
+ return Response.ok(Map.of("brokerSummaries", summaries)).build();
+ }
+
+ @GET
+ @Path("/v1/brokers/{broker-id}")
+ public Response describeBroker(@PathParam("broker-id") String brokerId) {
+ return Response.ok(brokerResponse(service.describeBroker(brokerId))).build();
+ }
+
+ // Builds the DescribeBroker response explicitly. The Broker model persists
+ // internal bookkeeping (containerId, accountId, volumeId) so the broker can be
+ // managed after a restart, but those fields are not part of the AWS shape — hand-
+ // building the response keeps them out of the client-facing payload.
+ private static Map<String, Object> brokerResponse(Broker b) {
+ Map<String, Object> body = new LinkedHashMap<>();
+ body.put("brokerId", b.getBrokerId());
+ body.put("brokerArn", b.getBrokerArn());
+ body.put("brokerName", b.getBrokerName());
+ body.put("brokerState", b.getBrokerState());
+ body.put("engineType", b.getEngineType());
+ body.put("engineVersion", b.getEngineVersion());
+ body.put("deploymentMode", b.getDeploymentMode());
+ body.put("hostInstanceType", b.getHostInstanceType());
+ body.put("publiclyAccessible", b.isPubliclyAccessible());
+ body.put("autoMinorVersionUpgrade", b.isAutoMinorVersionUpgrade());
+ body.put("created", b.getCreated());
+ body.put("brokerInstances", b.getBrokerInstances());
+ body.put("users", b.getUsers());
+ body.put("tags", b.getTags());
+ return body;
+ }
+
+ @DELETE
+ @Path("/v1/brokers/{broker-id}")
+ public Response deleteBroker(@PathParam("broker-id") String brokerId) {
+ service.deleteBroker(brokerId);
+ return Response.ok(Map.of("brokerId", brokerId)).build();
+ }
+
+ @POST
+ @Path("/v1/brokers/{broker-id}/reboot")
+ public Response rebootBroker(@PathParam("broker-id") String brokerId) {
+ service.rebootBroker(brokerId);
+ return Response.ok(Map.of()).build();
+ }
+
+ @POST
+ @Path("/v1/brokers/{broker-id}/users/{username}")
+ public Response createUser(@PathParam("broker-id") String brokerId,
+ @PathParam("username") String username,
+ Map<String, Object> request) {
+ MqUser user = new MqUser(
+ username,
+ str(request, "password"),
+ bool(request, "consoleAccess"),
+ strList(request.get("groups")));
+ service.createUser(brokerId, user);
+ return Response.ok(Map.of()).build();
+ }
+
+ @GET
+ @Path("/v1/brokers/{broker-id}/users/{username}")
+ public Response describeUser(@PathParam("broker-id") String brokerId,
+ @PathParam("username") String username) {
+ MqUser user = service.describeUser(brokerId, username);
+ Map<String, Object> body = new LinkedHashMap<>();
+ body.put("brokerId", brokerId);
+ body.put("username", user.getUsername());
+ body.put("consoleAccess", user.isConsoleAccess());
+ body.put("groups", user.getGroups());
+ return Response.ok(body).build();
+ }
+
+ @GET
+ @Path("/v1/brokers/{broker-id}/users")
+ public Response listUsers(@PathParam("broker-id") String brokerId) {
+ List<Map<String, Object>> users = new ArrayList<>();
+ for (MqUser u : service.listUsers(brokerId)) {
+ users.add(Map.of("username", u.getUsername()));
+ }
+ Map<String, Object> body = new LinkedHashMap<>();
+ body.put("brokerId", brokerId);
+ body.put("users", users);
+ return Response.ok(body).build();
+ }
+
+ @DELETE
+ @Path("/v1/brokers/{broker-id}/users/{username}")
+ public Response deleteUser(@PathParam("broker-id") String brokerId,
+ @PathParam("username") String username) {
+ service.deleteUser(brokerId, username);
+ return Response.ok(Map.of()).build();
+ }
+
+ // --- request parsing helpers ---
+
+ private static String str(Map<String, Object> request, String key) {
+ Object value = request.get(key);
+ return value == null ? null : value.toString();
+ }
+
+ private static boolean bool(Map<String, Object> request, String key) {
+ return Boolean.TRUE.equals(request.get(key));
+ }
+
+ @SuppressWarnings("unchecked")
+ private static List<String> strList(Object raw) {
+ if (raw instanceof List<?> list) {
+ List<String> result = new ArrayList<>();
+ for (Object o : list) {
+ result.add(String.valueOf(o));
+ }
+ return result;
+ }
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Map<String, String> tags(Object raw) {
+ if (raw instanceof Map<?, ?> map) {
+ Map<String, String> result = new LinkedHashMap<>();
+ map.forEach((k, v) -> result.put(String.valueOf(k), String.valueOf(v)));
+ return result;
+ }
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ private static List<MqUser> parseUsers(Object raw) {
+ if (!(raw instanceof List<?> list)) {
+ return null;
+ }
+ List<MqUser> users = new ArrayList<>();
+ for (Object item : list) {
+ if (item instanceof Map<?, ?> map) {
+ Map<String, Object> u = (Map<String, Object>) map;
+ users.add(new MqUser(
+ str(u, "username"),
+ str(u, "password"),
+ bool(u, "consoleAccess"),
+ strList(u.get("groups"))));
+ }
+ }
+ return users;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqService.java b/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqService.java
new file mode 100644
index 0000000000..3308dc3d43
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqService.java
@@ -0,0 +1,274 @@
+package io.github.hectorvent.floci.services.amazonmq;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.amazonmq.container.RabbitMqManager;
+import io.github.hectorvent.floci.services.amazonmq.model.Broker;
+import io.github.hectorvent.floci.services.amazonmq.model.BrokerInstance;
+import io.github.hectorvent.floci.services.amazonmq.model.BrokerState;
+import io.github.hectorvent.floci.services.amazonmq.model.MqUser;
+import jakarta.annotation.PostConstruct;
+import jakarta.annotation.PreDestroy;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.security.SecureRandom;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+@ApplicationScoped
+public class AmazonMqService {
+
+ private static final Logger LOG = Logger.getLogger(AmazonMqService.class);
+ private static final String ENGINE_RABBITMQ = "RABBITMQ";
+ private static final String DEFAULT_ENGINE_VERSION = "3.13";
+ private static final String DEPLOYMENT_SINGLE_INSTANCE = "SINGLE_INSTANCE";
+
+ private final StorageBackend<String, Broker> storage;
+ private final EmulatorConfig config;
+ private final RegionResolver regionResolver;
+ private final RabbitMqManager rabbitMqManager;
+ private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
+
+ @Inject
+ public AmazonMqService(StorageFactory storageFactory, EmulatorConfig config,
+ RegionResolver regionResolver, RabbitMqManager rabbitMqManager) {
+ this.storage = storageFactory.create("amazonmq", "amazonmq-brokers.json",
+ new TypeReference<Map<String, Broker>>() {});
+ this.config = config;
+ this.regionResolver = regionResolver;
+ this.rabbitMqManager = rabbitMqManager;
+ }
+
+ @PostConstruct
+ public void init() {
+ startReadinessPoller();
+ }
+
+ @PreDestroy
+ public void shutdown() {
+ // Container teardown is wired into EmulatorLifecycle.onStop() via
+ // RabbitMqManager.stopAll() (ordered with the other container managers);
+ // here we only stop the readiness poller.
+ poller.shutdown();
+ }
+
+ public Broker createBroker(CreateBrokerParams params) {
+ String name = params.brokerName();
+ if (name == null || name.isBlank()) {
+ throw new AwsException("BadRequestException", "BrokerName is required", 400);
+ }
+ if (!ENGINE_RABBITMQ.equals(params.engineType())) {
+ throw new AwsException("BadRequestException",
+ "Only RABBITMQ EngineType is supported", 400);
+ }
+ String deploymentMode = params.deploymentMode() == null
+ ? DEPLOYMENT_SINGLE_INSTANCE : params.deploymentMode();
+ if (!DEPLOYMENT_SINGLE_INSTANCE.equals(deploymentMode)) {
+ throw new AwsException("BadRequestException",
+ "Only SINGLE_INSTANCE DeploymentMode is supported", 400);
+ }
+ // RabbitMQ brokers require exactly one user at creation; that user becomes the
+ // broker's RabbitMQ administrator (seeded into the container). This mirrors AWS,
+ // which rejects CreateBroker for RabbitMQ unless exactly one user is supplied.
+ List<MqUser> requestedUsers = params.users() == null ? List.of() : params.users();
+ if (requestedUsers.size() != 1) {
+ throw new AwsException("BadRequestException",
+ "Exactly one broker user is required for a RabbitMQ broker", 400);
+ }
+ MqUser admin = requestedUsers.get(0);
+ if (admin.getUsername() == null || admin.getUsername().isBlank()) {
+ throw new AwsException("BadRequestException", "Broker user username is required", 400);
+ }
+ validateUserPassword(admin.getPassword());
+
+ if (storage.scan(k -> true).stream().anyMatch(b -> name.equals(b.getBrokerName()))) {
+ throw new AwsException("ConflictException", "Broker already exists: " + name, 409);
+ }
+
+ String brokerId = "b-" + UUID.randomUUID();
+ String accountId = regionResolver.getAccountId();
+ String brokerArn = AwsArnUtils.Arn.of("mq", config.defaultRegion(), accountId,
+ "broker:" + name + ":" + brokerId).toString();
+ String engineVersion = (params.engineVersion() == null || params.engineVersion().isBlank())
+ ? DEFAULT_ENGINE_VERSION : params.engineVersion();
+
+ Broker broker = new Broker(brokerId, brokerArn, name, ENGINE_RABBITMQ,
+ engineVersion, deploymentMode, params.hostInstanceType());
+ broker.setAccountId(accountId);
+ broker.setVolumeId(String.format("%06x", new SecureRandom().nextInt(0xFFFFFF)));
+ broker.setPubliclyAccessible(params.publiclyAccessible());
+ broker.setAutoMinorVersionUpgrade(params.autoMinorVersionUpgrade());
+ if (params.users() != null) {
+ broker.setUsers(new ArrayList<>(params.users()));
+ }
+ if (params.tags() != null) {
+ broker.setTags(new HashMap<>(params.tags()));
+ }
+
+ if (config.services().amazonmq().mock()) {
+ // No backing container: come up immediately with synthetic endpoints.
+ applyLocalEndpoints(broker);
+ broker.setBrokerState(BrokerState.RUNNING);
+ } else {
+ try {
+ // Start the container; the broker stays CREATION_IN_PROGRESS until
+ // the readiness poller observes the management API answering.
+ rabbitMqManager.startContainer(broker);
+ } catch (RuntimeException e) {
+ broker.setBrokerState(BrokerState.CREATION_FAILED);
+ storage.put(brokerId, broker);
+ // Keep the cause in the logs; don't leak internal details (or a null
+ // message) into the AWS error envelope returned to the client.
+ LOG.errorv(e, "Failed to provision broker {0} ({1})", name, brokerId);
+ throw new AwsException("InternalServerErrorException",
+ "Failed to provision broker " + name, 500);
+ }
+ }
+
+ storage.put(brokerId, broker);
+ LOG.infov("Created Amazon MQ broker {0} ({1})", name, brokerId);
+ return broker;
+ }
+
+ public Broker describeBroker(String brokerId) {
+ return storage.get(brokerId)
+ .orElseThrow(() -> new AwsException("NotFoundException",
+ "Broker not found: " + brokerId, 404));
+ }
+
+ public List<Broker> listBrokers() {
+ return storage.scan(k -> true);
+ }
+
+ public void deleteBroker(String brokerId) {
+ Broker broker = describeBroker(brokerId);
+ broker.setBrokerState(BrokerState.DELETION_IN_PROGRESS);
+ if (!config.services().amazonmq().mock()) {
+ rabbitMqManager.stopContainer(broker);
+ rabbitMqManager.removeBrokerStorage(broker);
+ }
+ storage.delete(brokerId);
+ LOG.infov("Deleted Amazon MQ broker {0}", brokerId);
+ }
+
+ public Broker rebootBroker(String brokerId) {
+ Broker broker = describeBroker(brokerId);
+ // AWS allows RebootBroker only on a broker in the RUNNING state. Without
+ // this guard a non-RUNNING broker (e.g. CREATION_FAILED, which has no
+ // backing container) would be silently promoted to RUNNING and never
+ // reconciled by the readiness poller.
+ if (broker.getBrokerState() != BrokerState.RUNNING) {
+ throw new AwsException("BadRequestException",
+ "Broker " + brokerId + " cannot be rebooted while in state "
+ + broker.getBrokerState() + "; it must be RUNNING", 400);
+ }
+ // RebootBroker is asynchronous and returns the broker to RUNNING. This tier
+ // does not cycle the container, so the broker simply stays RUNNING.
+ return broker;
+ }
+
+ private void applyLocalEndpoints(Broker broker) {
+ BrokerInstance instance = new BrokerInstance(
+ "http://localhost:15672",
+ List.of("amqp://localhost:5672"),
+ "localhost");
+ broker.setBrokerInstances(new ArrayList<>(List.of(instance)));
+ }
+
+ private void startReadinessPoller() {
+ poller.scheduleAtFixedRate(() -> {
+ try {
+ if (config.services().amazonmq().mock()) {
+ return;
+ }
+ for (Broker broker : allBrokers()) {
+ if (broker.getBrokerState() == BrokerState.CREATION_IN_PROGRESS
+ && rabbitMqManager.isReady(broker)) {
+ LOG.infov("Amazon MQ broker {0} is now RUNNING", broker.getBrokerName());
+ broker.setBrokerState(BrokerState.RUNNING);
+ putBroker(broker);
+ }
+ }
+ } catch (Exception e) {
+ LOG.error("Error in Amazon MQ readiness poller", e);
+ }
+ }, 1, 2, TimeUnit.SECONDS);
+ }
+
+ private List<Broker> allBrokers() {
+ if (storage instanceof AccountAwareStorageBackend<Broker> aware) {
+ return aware.scanAllAccounts();
+ }
+ return storage.scan(k -> true);
+ }
+
+ private void putBroker(Broker broker) {
+ if (broker.getAccountId() != null && storage instanceof AccountAwareStorageBackend<Broker> aware) {
+ aware.putForAccount(broker.getAccountId(), broker.getBrokerId(), broker);
+ } else {
+ storage.put(broker.getBrokerId(), broker);
+ }
+ }
+
+ // --- Users ---
+ // Amazon MQ's standalone User API (CreateUser/DescribeUser/ListUsers/UpdateUser/
+ // DeleteUser) applies only to ActiveMQ brokers. For RabbitMQ, AWS rejects these
+ // operations and directs callers to the RabbitMQ web console. Every broker we host
+ // is RabbitMQ, so they always reject. The broker's admin user is seeded once at
+ // CreateBroker time; additional users are managed through the RabbitMQ console.
+
+ public MqUser createUser(String brokerId, MqUser user) {
+ throw userApiNotSupported();
+ }
+
+ public MqUser describeUser(String brokerId, String username) {
+ throw userApiNotSupported();
+ }
+
+ public List<MqUser> listUsers(String brokerId) {
+ throw userApiNotSupported();
+ }
+
+ public void deleteUser(String brokerId, String username) {
+ throw userApiNotSupported();
+ }
+
+ private static AwsException userApiNotSupported() {
+ return new AwsException("BadRequestException",
+ "User management API operations do not apply to RabbitMQ brokers. "
+ + "Manage users through the RabbitMQ web console.", 400);
+ }
+
+ /**
+ * Enforces Amazon MQ's broker-user password rule: at least 12 characters, at
+ * least 4 unique characters, and no commas, colons, or equal signs.
+ */
+ private static void validateUserPassword(String password) {
+ if (password == null || password.length() < 12) {
+ throw new AwsException("BadRequestException",
+ "Broker user password must be at least 12 characters long", 400);
+ }
+ if (password.chars().distinct().count() < 4) {
+ throw new AwsException("BadRequestException",
+ "Broker user password must contain at least 4 unique characters", 400);
+ }
+ if (password.contains(",") || password.contains(":") || password.contains("=")) {
+ throw new AwsException("BadRequestException",
+ "Broker user password must not contain commas, colons, or equal signs", 400);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/amazonmq/CreateBrokerParams.java b/src/main/java/io/github/hectorvent/floci/services/amazonmq/CreateBrokerParams.java
new file mode 100644
index 0000000000..0d988462cb
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/amazonmq/CreateBrokerParams.java
@@ -0,0 +1,24 @@
+package io.github.hectorvent.floci.services.amazonmq;
+
+import io.github.hectorvent.floci.services.amazonmq.model.MqUser;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Immutable carrier for the fields the controller parses out of a CreateBroker
+ * request body. A record fits here because the request is read once and never
+ * mutated — the opposite of {@link io.github.hectorvent.floci.services.amazonmq.model.Broker},
+ * whose state evolves after creation.
+ */
+public record CreateBrokerParams(
+ String brokerName,
+ String engineType,
+ String engineVersion,
+ String deploymentMode,
+ String hostInstanceType,
+ boolean publiclyAccessible,
+ boolean autoMinorVersionUpgrade,
+ List<MqUser> users,
+ Map<String, String> tags) {
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManager.java b/src/main/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManager.java
new file mode 100644
index 0000000000..ed9f6137c3
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManager.java
@@ -0,0 +1,235 @@
+package io.github.hectorvent.floci.services.amazonmq.container;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
+import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
+import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
+import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
+import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
+import io.github.hectorvent.floci.services.amazonmq.model.Broker;
+import io.github.hectorvent.floci.services.amazonmq.model.BrokerInstance;
+import io.github.hectorvent.floci.services.amazonmq.model.MqUser;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.io.Closeable;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Manages the backing RabbitMQ Docker container for an Amazon MQ broker.
+ * In native (dev) mode it publishes the AMQP (5672) and management (15672)
+ * ports to dynamic host ports; in Docker mode sibling containers reach the
+ * broker over the docker network.
+ *
+ * <p>Unlike {@code RedpandaManager}, RabbitMQ does not advertise a self-perceived
+ * address back to clients, so no pre-allocated/advertised port is needed —
+ * dynamic ports (the ElastiCache pattern) are enough.
+ */
+@ApplicationScoped
+public class RabbitMqManager {
+
+ private static final Logger LOG = Logger.getLogger(RabbitMqManager.class);
+ private static final int AMQP_PORT = 5672;
+ private static final int MGMT_PORT = 15672;
+
+ private final ContainerBuilder containerBuilder;
+ private final ContainerLifecycleManager lifecycleManager;
+ private final ContainerLogStreamer logStreamer;
+ private final ContainerDetector containerDetector;
+ private final EmulatorConfig config;
+ private final RegionResolver regionResolver;
+ private final Map<String, Closeable> logStreams = new ConcurrentHashMap<>();
+ private final Map<String, String> containerIds = new ConcurrentHashMap<>();
+
+ @Inject
+ public RabbitMqManager(ContainerBuilder containerBuilder,
+ ContainerLifecycleManager lifecycleManager,
+ ContainerLogStreamer logStreamer,
+ ContainerDetector containerDetector,
+ EmulatorConfig config,
+ RegionResolver regionResolver) {
+ this.containerBuilder = containerBuilder;
+ this.lifecycleManager = lifecycleManager;
+ this.logStreamer = logStreamer;
+ this.containerDetector = containerDetector;
+ this.config = config;
+ this.regionResolver = regionResolver;
+ }
+
+ /** Deterministic container name for a broker, stable across emulator restarts. */
+ private static String containerName(String brokerId) {
+ return "floci-amazonmq-" + brokerId;
+ }
+
+ public void startContainer(Broker broker) {
+ String image = config.services().amazonmq().defaultImage();
+ String containerName = containerName(broker.getBrokerId());
+ LOG.infov("Starting RabbitMQ container for broker {0} using image {1}",
+ broker.getBrokerName(), image);
+
+ // Remove any stale container with the same name (e.g. leftover from a crash).
+ lifecycleManager.removeIfExists(containerName);
+
+ ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
+ .withName(containerName)
+ .withDockerNetwork(config.services().dockerNetwork())
+ .withLogRotation();
+
+ // Seed the broker's admin user. RabbitMQ's built-in `guest` user is
+ // loopback-only, so it cannot authenticate over the mapped host port; a user
+ // created via RABBITMQ_DEFAULT_USER/PASS is not loopback-restricted and can.
+ if (!broker.getUsers().isEmpty()) {
+ MqUser admin = broker.getUsers().get(0);
+ if (admin.getPassword() == null) {
+ // The password is in-memory only (a secret we do not persist). It is
+ // present when CreateBroker provisions the container but null for a
+ // broker reloaded from persistent storage. Fail loudly rather than
+ // create a container seeded with a null credential.
+ throw new IllegalStateException("Admin password unavailable for broker "
+ + broker.getBrokerId() + " (secrets are not persisted); cannot "
+ + "provision the RabbitMQ container");
+ }
+ specBuilder.withEnv("RABBITMQ_DEFAULT_USER", admin.getUsername());
+ specBuilder.withEnv("RABBITMQ_DEFAULT_PASS", admin.getPassword());
+ }
+
+ if (!containerDetector.isRunningInContainer()) {
+ specBuilder.withDynamicPort(AMQP_PORT).withDynamicPort(MGMT_PORT);
+ } else {
+ specBuilder.withExposedPort(AMQP_PORT).withExposedPort(MGMT_PORT);
+ }
+
+ if (ContainerStorageHelper.isNamedVolumeMode(config)) {
+ ContainerStorageHelper.applyStorage(specBuilder, lifecycleManager,
+ "amazonmq", broker.getVolumeId(), broker.getBrokerId(),
+ "/var/lib/rabbitmq");
+ } else {
+ String hostDataPath = Path.of(config.storage().hostPersistentPath(), "amazonmq", broker.getBrokerId())
+ .toAbsolutePath().toString();
+ ContainerStorageHelper.ensureHostDir(hostDataPath);
+ specBuilder.withBind(hostDataPath, "/var/lib/rabbitmq");
+ }
+
+ ContainerSpec spec = specBuilder.build();
+
+ ContainerInfo info;
+ try {
+ info = lifecycleManager.createAndStart(spec);
+ } catch (RuntimeException e) {
+ // Roll back a partially-created container so a failed CreateBroker
+ // does not leave an orphaned container behind.
+ lifecycleManager.removeIfExists(containerName);
+ throw e;
+ }
+ broker.setContainerId(info.containerId());
+ containerIds.put(broker.getBrokerId(), info.containerId());
+
+ EndpointInfo amqp = info.getEndpoint(AMQP_PORT);
+ EndpointInfo mgmt = info.getEndpoint(MGMT_PORT);
+ BrokerInstance instance = new BrokerInstance(
+ "http://" + mgmt.host() + ":" + mgmt.port(),
+ List.of("amqp://" + amqp.host() + ":" + amqp.port()),
+ amqp.host());
+ broker.setBrokerInstances(new java.util.ArrayList<>(List.of(instance)));
+ LOG.infov("RabbitMQ container {0} started for broker {1}: amqp={2}",
+ info.containerId(), broker.getBrokerName(), instance.getEndpoints().get(0));
+
+ String shortId = info.containerId().length() >= 8
+ ? info.containerId().substring(0, 8)
+ : info.containerId();
+ String logGroup = "/aws/amazonmq/broker/" + broker.getBrokerId();
+ String logStream = logStreamer.generateLogStreamName(shortId);
+ String region = regionResolver.getDefaultRegion();
+ Closeable logHandle = logStreamer.attach(
+ info.containerId(), logGroup, logStream, region, "amazonmq:" + broker.getBrokerId());
+ if (logHandle != null) {
+ logStreams.put(broker.getBrokerId(), logHandle);
+ }
+ }
+
+ /**
+ * Ready once the RabbitMQ management UI answers on its port. The management
+ * plugin starts after the broker core, so a 200 here implies AMQP is also up.
+ * The root path needs no auth, sidestepping RabbitMQ's loopback-only guest user.
+ */
+ public boolean isReady(Broker broker) {
+ if (broker.getBrokerInstances().isEmpty()) {
+ return false;
+ }
+ String consoleUrl = broker.getBrokerInstances().get(0).getConsoleURL();
+ if (consoleUrl == null) {
+ return false;
+ }
+ HttpURLConnection conn = null;
+ try {
+ conn = (HttpURLConnection) URI.create(consoleUrl).toURL().openConnection();
+ conn.setRequestMethod("GET");
+ conn.setConnectTimeout(1000);
+ conn.setReadTimeout(1000);
+ return conn.getResponseCode() == 200;
+ } catch (Exception e) {
+ // Expected while the broker is still booting (connection refused/timeout).
+ // Logged at debug so a genuinely stuck probe is diagnosable without
+ // spamming this 2s-interval hot path (AGENTS.md: no empty catch).
+ LOG.debugf("Readiness probe for broker %s at %s not ready: %s",
+ broker.getBrokerId(), consoleUrl, e.toString());
+ return false;
+ } finally {
+ // Release the socket; isReady() is polled every 2s per pending broker.
+ if (conn != null) {
+ conn.disconnect();
+ }
+ }
+ }
+
+ public void stopContainer(Broker broker) {
+ containerIds.remove(broker.getBrokerId());
+ Closeable logHandle = logStreams.remove(broker.getBrokerId());
+ String containerId = broker.getContainerId();
+ if (containerId != null) {
+ lifecycleManager.stopAndRemove(containerId, logHandle);
+ LOG.infov("RabbitMQ container {0} stopped and removed", containerId);
+ } else {
+ // containerId is in-memory bookkeeping and is null after an emulator
+ // restart (it is intentionally not persisted; see Broker). Fall back to
+ // the deterministic container name so an explicit DeleteBroker still
+ // removes a container left running from a previous run.
+ lifecycleManager.removeIfExists(containerName(broker.getBrokerId()));
+ }
+ }
+
+ /**
+ * Stops and removes every running broker container. Wired into
+ * {@code EmulatorLifecycle.onStop()} so containers are torn down on shutdown
+ * alongside the other container managers.
+ */
+ public void stopAll() {
+ if (!containerIds.isEmpty()) {
+ LOG.infov("Stopping {0} RabbitMQ container(s) on shutdown", containerIds.size());
+ }
+ for (String brokerId : new ArrayList<>(containerIds.keySet())) {
+ String containerId = containerIds.remove(brokerId);
+ if (containerId == null) {
+ continue;
+ }
+ Closeable logHandle = logStreams.remove(brokerId);
+ lifecycleManager.stopAndRemove(containerId, logHandle);
+ }
+ }
+
+ public void removeBrokerStorage(Broker broker) {
+ ContainerStorageHelper.removeStorage(config, lifecycleManager,
+ "amazonmq", broker.getVolumeId(), broker.getBrokerId());
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/amazonmq/model/Broker.java b/src/main/java/io/github/hectorvent/floci/services/amazonmq/model/Broker.java
new file mode 100644
index 0000000000..70e7214628
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/amazonmq/model/Broker.java
@@ -0,0 +1,146 @@
+package io.github.hectorvent.floci.services.amazonmq.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * In-memory representation of an Amazon MQ broker. Mirrors the
+ * {@code msk/model/MskCluster} shape: a mutable POJO whose state transitions
+ * in place (CREATION_IN_PROGRESS -> RUNNING) as the backing container comes up.
+ *
+ * <p>Wire keys are camelCase to match the Amazon MQ REST-JSON protocol
+ * (e.g. {@code brokerName}, {@code brokerInstances}).
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Broker {
+
+ @JsonProperty("brokerId")
+ private String brokerId;
+
+ @JsonProperty("brokerArn")
+ private String brokerArn;
+
+ @JsonProperty("brokerName")
+ private String brokerName;
+
+ @JsonProperty("brokerState")
+ private BrokerState brokerState;
+
+ @JsonProperty("engineType")
+ private String engineType;
+
+ @JsonProperty("engineVersion")
+ private String engineVersion;
+
+ @JsonProperty("deploymentMode")
+ private String deploymentMode;
+
+ @JsonProperty("hostInstanceType")
+ private String hostInstanceType;
+
+ @JsonProperty("publiclyAccessible")
+ private boolean publiclyAccessible;
+
+ @JsonProperty("autoMinorVersionUpgrade")
+ private boolean autoMinorVersionUpgrade;
+
+ @JsonProperty("created")
+ private Instant created;
+
+ @JsonProperty("brokerInstances")
+ private List<BrokerInstance> brokerInstances = new ArrayList<>();
+
+ @JsonProperty("users")
+ private List<MqUser> users = new ArrayList<>();
+
+ @JsonProperty("tags")
+ private Map<String, String> tags;
+
+ // Internal bookkeeping. These are NOT part of the AWS response shape, but they ARE
+ // persisted so the broker stays manageable after an emulator restart in persistent
+ // mode (container teardown, volume cleanup, account-aware storage routing). The
+ // controller builds the DescribeBroker response explicitly, so these are never
+ // exposed to clients despite being written to storage.
+ private String containerId;
+
+ private String accountId;
+
+ // 6-char hex generated once at creation for stable, collision-free volume/container
+ // naming (same convention as MskCluster.volumeId, which is likewise persisted so
+ // removeBrokerStorage can locate the named volume after a restart).
+ private String volumeId;
+
+ public Broker() {}
+
+ public Broker(String brokerId, String brokerArn, String brokerName,
+ String engineType, String engineVersion, String deploymentMode,
+ String hostInstanceType) {
+ this.brokerId = brokerId;
+ this.brokerArn = brokerArn;
+ this.brokerName = brokerName;
+ this.engineType = engineType;
+ this.engineVersion = engineVersion;
+ this.deploymentMode = deploymentMode;
+ this.hostInstanceType = hostInstanceType;
+ this.brokerState = BrokerState.CREATION_IN_PROGRESS;
+ this.created = Instant.now();
+ }
+
+ public String getBrokerId() { return brokerId; }
+ public void setBrokerId(String brokerId) { this.brokerId = brokerId; }
+
+ public String getBrokerArn() { return brokerArn; }
+ public void setBrokerArn(String brokerArn) { this.brokerArn = brokerArn; }
+
+ public String getBrokerName() { return brokerName; }
+ public void setBrokerName(String brokerName) { this.brokerName = brokerName; }
+
+ public BrokerState getBrokerState() { return brokerState; }
+ public void setBrokerState(BrokerState brokerState) { this.brokerState = brokerState; }
+
+ public String getEngineType() { return engineType; }
+ public void setEngineType(String engineType) { this.engineType = engineType; }
+
+ public String getEngineVersion() { return engineVersion; }
+ public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; }
+
+ public String getDeploymentMode() { return deploymentMode; }
+ public void setDeploymentMode(String deploymentMode) { this.deploymentMode = deploymentMode; }
+
+ public String getHostInstanceType() { return hostInstanceType; }
+ public void setHostInstanceType(String hostInstanceType) { this.hostInstanceType = hostInstanceType; }
+
+ public boolean isPubliclyAccessible() { return publiclyAccessible; }
+ public void setPubliclyAccessible(boolean publiclyAccessible) { this.publiclyAccessible = publiclyAccessible; }
+
+ public boolean isAutoMinorVersionUpgrade() { return autoMinorVersionUpgrade; }
+ public void setAutoMinorVersionUpgrade(boolean autoMinorVersionUpgrade) { this.autoMinorVersionUpgrade = autoMinorVersionUpgrade; }
+
+ public Instant getCreated() { return created; }
+ public void setCreated(Instant created) { this.created = created; }
+
+ public List<BrokerInstance> getBrokerInstances() { return brokerInstances; }
+ public void setBrokerInstances(List<BrokerInstance> brokerInstances) { this.brokerInstances = brokerInstances; }
+
+ public List<MqUser> getUsers() { return users; }
+ public void setUsers(List<MqUser> users) { this.users = users; }
+
+ public Map<String, String> getTags() { return tags; }
+ public void setTags(Map<String, String> tags) { this.tags = tags; }
+
+ public String getContainerId() { return containerId; }
+ public void setContainerId(String containerId) { this.containerId = containerId; }
+
+ public String getAccountId() { return accountId; }
+ public void setAccountId(String accountId) { this.accountId = accountId; }
+
+ public String getVolumeId() { return volumeId; }
+ public void setVolumeId(String volumeId) { this.volumeId = volumeId; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/amazonmq/model/BrokerInstance.java b/src/main/java/io/github/hectorvent/floci/services/amazonmq/model/BrokerInstance.java
new file mode 100644
index 0000000000..2ab116af58
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/amazonmq/model/BrokerInstance.java
@@ -0,0 +1,43 @@
+package io.github.hectorvent.floci.services.amazonmq.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.List;
+
+/**
+ * A single broker instance's connection info, as returned inside
+ * {@code DescribeBroker.BrokerInstances[]}. Clients read {@code Endpoints}
+ * to connect (AMQP) and {@code ConsoleURL} to open the management UI.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class BrokerInstance {
+
+ @JsonProperty("consoleURL")
+ private String consoleURL;
+
+ @JsonProperty("endpoints")
+ private List<String> endpoints;
+
+ @JsonProperty("ipAddress")
+ private String ipAddress;
+
+ public BrokerInstance() {}
+
+ public BrokerInstance(String consoleURL, List<String> endpoints, String ipAddress) {
+ this.consoleURL = consoleURL;
+ this.endpoints = endpoints;
+ this.ipAddress = ipAddress;
+ }
+
+ public String getConsoleURL() { return consoleURL; }
+ public void setConsoleURL(String consoleURL) { this.consoleURL = consoleURL; }
+
+ public List<String> getEndpoints() { return endpoints; }
+ public void setEndpoints(List<String> endpoints) { this.endpoints = endpoints; }
+
+ public String getIpAddress() { return ipAddress; }
+ public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/amazonmq/model/BrokerState.java b/src/main/java/io/github/hectorvent/floci/services/amazonmq/model/BrokerState.java
new file mode 100644
index 0000000000..774623caac
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/amazonmq/model/BrokerState.java
@@ -0,0 +1,22 @@
+package io.github.hectorvent.floci.services.amazonmq.model;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+public enum BrokerState {
+ @JsonProperty("CREATION_IN_PROGRESS")
+ CREATION_IN_PROGRESS,
+ @JsonProperty("CREATION_FAILED")
+ CREATION_FAILED,
+ @JsonProperty("DELETION_IN_PROGRESS")
+ DELETION_IN_PROGRESS,
+ @JsonProperty("RUNNING")
+ RUNNING,
+ @JsonProperty("REBOOT_IN_PROGRESS")
+ REBOOT_IN_PROGRESS,
+ @JsonProperty("CRITICAL_ACTION_REQUIRED")
+ CRITICAL_ACTION_REQUIRED,
+ @JsonProperty("REPLICA")
+ REPLICA
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/amazonmq/model/MqUser.java b/src/main/java/io/github/hectorvent/floci/services/amazonmq/model/MqUser.java
new file mode 100644
index 0000000000..0875d84613
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/amazonmq/model/MqUser.java
@@ -0,0 +1,59 @@
+package io.github.hectorvent.floci.services.amazonmq.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.List;
+
+/**
+ * A broker user. Amazon MQ never returns the password in any response
+ * (DescribeUser / ListUsers omit it), so the password is stored for later
+ * projection into the real broker but is never serialized back to the client.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class MqUser {
+
+ @JsonProperty("username")
+ private String username;
+
+ // The admin password is a secret used only to seed the RabbitMQ container at
+ // create time (RABBITMQ_DEFAULT_USER/PASS). It is deliberately kept in memory
+ // only and never serialized — to the API or to StorageBackend — so it is not
+ // written in cleartext to amazonmq-brokers.json (per the project rule against
+ // persisting secrets). A broker reloaded from persistent storage therefore has a
+ // null password; RabbitMqManager#startContainer fails loudly rather than seed a
+ // null credential.
+ @JsonIgnore
+ private String password;
+
+ @JsonProperty("consoleAccess")
+ private boolean consoleAccess;
+
+ @JsonProperty("groups")
+ private List<String> groups;
+
+ public MqUser() {}
+
+ public MqUser(String username, String password, boolean consoleAccess, List<String> groups) {
+ this.username = username;
+ this.password = password;
+ this.consoleAccess = consoleAccess;
+ this.groups = groups;
+ }
+
+ public String getUsername() { return username; }
+ public void setUsername(String username) { this.username = username; }
+
+ @JsonIgnore
+ public String getPassword() { return password; }
+ public void setPassword(String password) { this.password = password; }
+
+ public boolean isConsoleAccess() { return consoleAccess; }
+ public void setConsoleAccess(boolean consoleAccess) { this.consoleAccess = consoleAccess; }
+
+ public List<String> getGroups() { return groups; }
+ public void setGroups(List<String> groups) { this.groups = groups; }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 4880f75808..b12432d201 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -210,6 +210,10 @@ floci:
default-image: "redpandadata/redpanda:latest"
kafka-host-port-base: 9300
kafka-host-port-max: 9399
+ amazonmq:
+ enabled: true
+ mock: false
+ default-image: "rabbitmq:3-management"
elasticache:
enabled: true
proxy-base-port: 6379
diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java
index b085f9c110..6cac5cd364 100644
--- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java
+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java
@@ -65,6 +65,7 @@ class EmulatorLifecycleTest {
@Mock private DocDbContainerManager docDbContainerManager;
@Mock private NeptuneContainerManager neptuneContainerManager;
@Mock private NeptuneProxyManager neptuneProxyManager;
+ @Mock private io.github.hectorvent.floci.services.amazonmq.container.RabbitMqManager rabbitMqManager;
@Mock private RdsService rdsService;
@Mock private InitializationHooksRunner initializationHooksRunner;
@Mock private SqsEventSourcePoller sqsPoller;
@@ -92,7 +93,8 @@ class EmulatorLifecycleTest {
elastiCacheContainerManager, elastiCacheMemcachedContainerManager,
elastiCacheProxyManager, rdsContainerManager, rdsProxyManager,
memoryDbContainerManager, memoryDbProxyManager,
- docDbContainerManager, neptuneContainerManager, neptuneProxyManager, rdsService,
+ docDbContainerManager, neptuneContainerManager, neptuneProxyManager,
+ rabbitMqManager, rdsService,
initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller,
pipesService, ec2MetadataServer, ecrRegistryManager, flociUiManager, initLifecycleState);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqControllerIntegrationTest.java
new file mode 100644
index 0000000000..48cafc2a59
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqControllerIntegrationTest.java
@@ -0,0 +1,114 @@
+package io.github.hectorvent.floci.services.amazonmq;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.nullValue;
+import static org.hamcrest.Matchers.startsWith;
+
+@QuarkusTest
+class AmazonMqControllerIntegrationTest {
+
+ private String createRabbitBroker(String name) {
+ return given()
+ .contentType("application/json")
+ .body("""
+ {"brokerName": "%s", "engineType": "RABBITMQ",
+ "deploymentMode": "SINGLE_INSTANCE", "hostInstanceType": "mq.t3.micro",
+ "publiclyAccessible": false,
+ "users": [{"username": "admin", "password": "AdminPass123", "consoleAccess": true}]}
+ """.formatted(name))
+ .when()
+ .post("/v1/brokers")
+ .then()
+ .statusCode(200)
+ .extract().path("brokerId");
+ }
+
+ @Test
+ void createThenDescribeBroker() {
+ String brokerId = createRabbitBroker("it-describe");
+
+ given()
+ .when()
+ .get("/v1/brokers/{id}", brokerId)
+ .then()
+ .statusCode(200)
+ .body("brokerName", equalTo("it-describe"))
+ .body("engineType", equalTo("RABBITMQ"))
+ .body("brokerState", equalTo("RUNNING"))
+ .body("brokerInstances[0].endpoints[0]", startsWith("amqp://"))
+ // internal bookkeeping is persisted but must never leak into the API
+ .body("containerId", nullValue())
+ .body("accountId", nullValue())
+ .body("volumeId", nullValue());
+ }
+
+ @Test
+ void listBrokersIncludesCreated() {
+ createRabbitBroker("it-list");
+
+ given()
+ .when()
+ .get("/v1/brokers")
+ .then()
+ .statusCode(200)
+ .body("brokerSummaries.brokerName", hasItem("it-list"));
+ }
+
+ @Test
+ void userApiRejectedForRabbitMq() {
+ // The standalone User API applies only to ActiveMQ; AWS rejects it for
+ // RabbitMQ brokers. Users are managed through the RabbitMQ web console.
+ String brokerId = createRabbitBroker("it-users");
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {"password": "AnotherPass99", "consoleAccess": false}
+ """)
+ .when()
+ .post("/v1/brokers/{id}/users/alice", brokerId)
+ .then()
+ .statusCode(400);
+
+ given()
+ .when()
+ .get("/v1/brokers/{id}/users", brokerId)
+ .then()
+ .statusCode(400);
+ }
+
+ @Test
+ void rejectsBrokerWithoutUser() {
+ given()
+ .contentType("application/json")
+ .body("""
+ {"brokerName": "it-nouser", "engineType": "RABBITMQ",
+ "deploymentMode": "SINGLE_INSTANCE", "hostInstanceType": "mq.t3.micro",
+ "publiclyAccessible": false}
+ """)
+ .when()
+ .post("/v1/brokers")
+ .then()
+ .statusCode(400);
+ }
+
+ @Test
+ void rejectsActiveMqEngine() {
+ given()
+ .contentType("application/json")
+ .body("""
+ {"brokerName": "it-activemq", "engineType": "ACTIVEMQ",
+ "deploymentMode": "SINGLE_INSTANCE", "hostInstanceType": "mq.t3.micro",
+ "publiclyAccessible": false}
+ """)
+ .when()
+ .post("/v1/brokers")
+ .then()
+ .statusCode(400);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqServiceTest.java
new file mode 100644
index 0000000000..0c7efff3e2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqServiceTest.java
@@ -0,0 +1,192 @@
+package io.github.hectorvent.floci.services.amazonmq;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.amazonmq.container.RabbitMqManager;
+import io.github.hectorvent.floci.services.amazonmq.model.Broker;
+import io.github.hectorvent.floci.services.amazonmq.model.BrokerState;
+import io.github.hectorvent.floci.services.amazonmq.model.MqUser;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.when;
+
+class AmazonMqServiceTest {
+
+ private AmazonMqService service;
+
+ @BeforeEach
+ void setUp() {
+ StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
+ when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
+ .thenReturn(new InMemoryStorage<>());
+
+ EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
+ var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
+ var 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);
+ }
+
+ private CreateBrokerParams rabbitParams(String name) {
+ return new CreateBrokerParams(name, "RABBITMQ", null, "SINGLE_INSTANCE",
+ "mq.t3.micro", false, false,
+ List.of(new MqUser("admin", "AdminPass123", true, null)), null);
+ }
+
+ @Test
+ void createBrokerComesUpRunningWithEndpoints() {
+ Broker broker = service.createBroker(rabbitParams("orders"));
+
+ assertEquals("orders", broker.getBrokerName());
+ assertEquals("RABBITMQ", broker.getEngineType());
+ assertEquals(BrokerState.RUNNING, broker.getBrokerState());
+ assertTrue(broker.getBrokerId().startsWith("b-"));
+ assertTrue(broker.getBrokerArn().contains(":mq:"));
+ assertTrue(broker.getBrokerArn().contains("orders"));
+ assertFalse(broker.getBrokerInstances().isEmpty());
+ assertFalse(broker.getBrokerInstances().get(0).getEndpoints().isEmpty());
+ }
+
+ @Test
+ void createBrokerDefaultsEngineVersionWhenAbsent() {
+ Broker broker = service.createBroker(rabbitParams("orders"));
+ assertEquals("3.13", broker.getEngineVersion());
+ }
+
+ @Test
+ void createBrokerRejectsNonRabbitEngine() {
+ CreateBrokerParams activeMq = new CreateBrokerParams("legacy", "ACTIVEMQ", null,
+ "SINGLE_INSTANCE", "mq.t3.micro", false, false, null, null);
+ assertThrows(AwsException.class, () -> service.createBroker(activeMq));
+ }
+
+ @Test
+ void createBrokerRejectsNonSingleInstanceDeployment() {
+ CreateBrokerParams cluster = new CreateBrokerParams("ha", "RABBITMQ", null,
+ "CLUSTER_MULTI_AZ", "mq.t3.micro", false, false, null, null);
+ assertThrows(AwsException.class, () -> service.createBroker(cluster));
+ }
+
+ @Test
+ void createBrokerRejectsDuplicateName() {
+ service.createBroker(rabbitParams("orders"));
+ assertThrows(AwsException.class, () -> service.createBroker(rabbitParams("orders")));
+ }
+
+ @Test
+ void describeBrokerThrowsWhenMissing() {
+ assertThrows(AwsException.class, () -> service.describeBroker("b-does-not-exist"));
+ }
+
+ @Test
+ void deleteBrokerRemovesIt() {
+ Broker broker = service.createBroker(rabbitParams("orders"));
+ service.deleteBroker(broker.getBrokerId());
+ assertTrue(service.listBrokers().isEmpty());
+ }
+
+ @Test
+ void userApiRejectedForRabbitMq() {
+ // The standalone User API applies only to ActiveMQ; AWS rejects it for
+ // RabbitMQ brokers, and every broker we host is RabbitMQ.
+ Broker broker = service.createBroker(rabbitParams("orders"));
+ String id = broker.getBrokerId();
+
+ assertThrows(AwsException.class,
+ () -> service.createUser(id, new MqUser("alice", "AnotherPass99", false, null)));
+ assertThrows(AwsException.class, () -> service.listUsers(id));
+ assertThrows(AwsException.class, () -> service.describeUser(id, "alice"));
+ assertThrows(AwsException.class, () -> service.deleteUser(id, "alice"));
+ }
+
+ @Test
+ void createBrokerSeedsAdminUser() {
+ Broker broker = service.createBroker(rabbitParams("orders"));
+ assertEquals(1, broker.getUsers().size());
+ assertEquals("admin", broker.getUsers().get(0).getUsername());
+ assertEquals("AdminPass123", broker.getUsers().get(0).getPassword());
+ }
+
+ @Test
+ void createBrokerRequiresExactlyOneUser() {
+ CreateBrokerParams noUsers = new CreateBrokerParams("orders", "RABBITMQ", null,
+ "SINGLE_INSTANCE", "mq.t3.micro", false, false, null, null);
+ assertThrows(AwsException.class, () -> service.createBroker(noUsers));
+ }
+
+ @Test
+ void createBrokerRejectsWeakPassword() {
+ CreateBrokerParams weak = new CreateBrokerParams("orders", "RABBITMQ", null,
+ "SINGLE_INSTANCE", "mq.t3.micro", false, false,
+ List.of(new MqUser("admin", "short", true, null)), null);
+ assertThrows(AwsException.class, () -> service.createBroker(weak));
+ }
+
+ @Test
+ void createBrokerMarksFailedWhenProvisioningThrows() {
+ AmazonMqService realModeService = realModeServiceWithFailingManager();
+
+ assertThrows(AwsException.class,
+ () -> realModeService.createBroker(rabbitParams("orders")));
+
+ // The failed broker is persisted as CREATION_FAILED, not left dangling.
+ List<Broker> brokers = realModeService.listBrokers();
+ assertEquals(1, brokers.size());
+ assertEquals(BrokerState.CREATION_FAILED, brokers.get(0).getBrokerState());
+ }
+
+ @Test
+ void rebootRunningBrokerStaysRunning() {
+ Broker broker = service.createBroker(rabbitParams("orders"));
+ Broker rebooted = service.rebootBroker(broker.getBrokerId());
+ assertEquals(BrokerState.RUNNING, rebooted.getBrokerState());
+ }
+
+ @Test
+ void rebootRejectsNonRunningBroker() {
+ // A failed-provisioning broker is CREATION_FAILED; AWS allows RebootBroker
+ // only on a RUNNING broker, so rebooting it must throw rather than promote
+ // it (with no backing container) to RUNNING.
+ AmazonMqService realModeService = realModeServiceWithFailingManager();
+ assertThrows(AwsException.class,
+ () -> realModeService.createBroker(rabbitParams("orders")));
+ Broker failed = realModeService.listBrokers().get(0);
+ assertEquals(BrokerState.CREATION_FAILED, failed.getBrokerState());
+
+ assertThrows(AwsException.class, () -> realModeService.rebootBroker(failed.getBrokerId()));
+ }
+
+ private AmazonMqService realModeServiceWithFailingManager() {
+ StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
+ when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
+ .thenReturn(new InMemoryStorage<>());
+
+ EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
+ var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
+ var 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");
+
+ 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);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManagerTest.java
new file mode 100644
index 0000000000..33c56f3543
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/amazonmq/container/RabbitMqManagerTest.java
@@ -0,0 +1,61 @@
+package io.github.hectorvent.floci.services.amazonmq.container;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
+import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
+import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
+import io.github.hectorvent.floci.services.amazonmq.model.Broker;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+
+class RabbitMqManagerTest {
+
+ private ContainerLifecycleManager lifecycleManager;
+ private RabbitMqManager manager;
+
+ @BeforeEach
+ void setUp() {
+ lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
+ manager = new RabbitMqManager(
+ Mockito.mock(ContainerBuilder.class),
+ lifecycleManager,
+ Mockito.mock(ContainerLogStreamer.class),
+ Mockito.mock(ContainerDetector.class),
+ Mockito.mock(EmulatorConfig.class),
+ Mockito.mock(RegionResolver.class));
+ }
+
+ private Broker broker(String brokerId) {
+ return new Broker(brokerId, "arn", "name", "RABBITMQ", "3.13",
+ "SINGLE_INSTANCE", "mq.t3.micro");
+ }
+
+ @Test
+ void stopContainerUsesContainerIdWhenPresent() {
+ Broker broker = broker("b-1");
+ broker.setContainerId("container-abc");
+
+ manager.stopContainer(broker);
+
+ verify(lifecycleManager).stopAndRemove(Mockito.eq("container-abc"), Mockito.any());
+ verifyNoMoreInteractions(lifecycleManager);
+ }
+
+ @Test
+ void stopContainerFallsBackToDeterministicNameWhenIdMissing() {
+ // After an emulator restart containerId is null (not persisted); teardown
+ // must still remove the container by its deterministic name.
+ Broker broker = broker("b-2");
+
+ manager.stopContainer(broker);
+
+ verify(lifecycleManager).removeIfExists("floci-amazonmq-b-2");
+ verifyNoMoreInteractions(lifecycleManager);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/amazonmq/model/BrokerTest.java b/src/test/java/io/github/hectorvent/floci/services/amazonmq/model/BrokerTest.java
new file mode 100644
index 0000000000..b52b9f0498
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/amazonmq/model/BrokerTest.java
@@ -0,0 +1,32 @@
+package io.github.hectorvent.floci.services.amazonmq.model;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class BrokerTest {
+
+ /**
+ * containerId / accountId / volumeId are internal bookkeeping but must survive a
+ * serialize -> deserialize round-trip so the broker stays manageable after an
+ * emulator restart (volume cleanup, container teardown, account-aware routing).
+ * They are kept out of the API by the controller's explicit DescribeBroker
+ * response, not by dropping them from storage.
+ */
+ @Test
+ void internalFieldsPersistAcrossSerialization() throws Exception {
+ ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
+ Broker broker = new Broker("b-1", "arn:aws:mq:us-east-1:000000000000:broker:n:b-1",
+ "n", "RABBITMQ", "3.13", "SINGLE_INSTANCE", "mq.t3.micro");
+ broker.setContainerId("container-xyz");
+ broker.setAccountId("000000000000");
+ broker.setVolumeId("a1b2c3");
+
+ Broker roundTripped = mapper.readValue(mapper.writeValueAsString(broker), Broker.class);
+
+ assertEquals("container-xyz", roundTripped.getContainerId());
+ assertEquals("000000000000", roundTripped.getAccountId());
+ assertEquals("a1b2c3", roundTripped.getVolumeId());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/amazonmq/model/MqUserTest.java b/src/test/java/io/github/hectorvent/floci/services/amazonmq/model/MqUserTest.java
new file mode 100644
index 0000000000..4a808d1070
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/amazonmq/model/MqUserTest.java
@@ -0,0 +1,36 @@
+package io.github.hectorvent.floci.services.amazonmq.model;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+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.assertTrue;
+
+class MqUserTest {
+
+ /**
+ * The admin password is a secret: it must never be written to JSON (neither the
+ * API response nor StorageBackend's amazonmq-brokers.json). A serialize ->
+ * deserialize round-trip therefore drops it, by design — persisting it would
+ * store the credential in cleartext.
+ */
+ @Test
+ void passwordIsNeverSerialized() throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ MqUser user = new MqUser("admin", "AdminPass123", true, List.of("admin"));
+
+ String json = mapper.writeValueAsString(user);
+ assertFalse(json.contains("AdminPass123"), "password value must not be serialized");
+ assertFalse(json.toLowerCase().contains("password"), "password key must not be serialized");
+
+ MqUser roundTripped = mapper.readValue(json, MqUser.class);
+ assertNull(roundTripped.getPassword(), "password is in-memory only; not restored from JSON");
+ assertEquals("admin", roundTripped.getUsername());
+ assertTrue(roundTripped.isConsoleAccess());
+ assertEquals(List.of("admin"), roundTripped.getGroups());
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index f1cdbf04a9..d9847fb5a9 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -108,6 +108,9 @@ floci:
enabled: true
mock: true
default-image: "redpandadata/redpanda:latest"
+ amazonmq:
+ enabled: true
+ mock: true
elasticache:
enabled: true
proxy-base-port: 6379