feat(parity): LocalStack drop-in compatibility (#696)

- Translate LocalStack env vars (LOCALSTACK_HOST, PERSISTENCE, LAMBDA_DOCKER_NETWORK, etc.)
  to Floci equivalents automatically at startup; opt out with LOCALSTACK_PARITY=false
- Serve /_localstack/init and /_localstack/health alongside /_floci/* equivalents
- Report executed scripts with path, state, and return_code in /_floci/init response
- Add /_aws/sqs/messages GET (non-destructive peek) and DELETE (purge) inspection endpoint
- Add /_aws/execute-api/{apiId}/{stageName} LocalStack-compat path for REST API invocation
- Add four-phase init hook lifecycle (boot/start/ready/stop) with dual-path discovery
  (/etc/floci/init/ and /etc/localstack/init/ compat paths)
- Install Python 3, AWS CLI, boto3 in standard image; wrap aws binary to pre-configure
  --endpoint-url=http://localhost:4566 so init scripts need no extra flags
- Wire entrypoint.sh + gosu privilege drop into all Dockerfile variants
- Add migration guide and update README, docker-compose, docker-images, SQS, and
  initialization-hooks docs
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-05-04 01:15:59 -05:00
1 parent b84d205b89
commit 023880b7d9
35 files changed
+1676 -272

No files matched your search

@@ -0,0 +1,122 @@
package io.github.hectorvent.floci.lifecycle;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class EmulatorInfoControllerIntegrationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String EXPECTED_SERVICES_JSON = """
{
"ssm": "running",
"sqs": "running",
"s3": "running",
"dynamodb": "running",
"sns": "running",
"lambda": "running",
"apigateway": "running",
"iam": "running",
"kafka": "running",
"elasticache": "running",
"rds": "running",
"events": "running",
"scheduler": "running",
"logs": "running",
"monitoring": "running",
"secretsmanager": "running",
"apigatewayv2": "running",
"kinesis": "running",
"kms": "running",
"cognito-idp": "running",
"states": "running",
"cloudformation": "running",
"acm": "running",
"athena": "running",
"glue": "running",
"firehose": "running",
"email": "running",
"es": "running",
"ec2": "running",
"ecs": "running",
"appconfig": "running",
"appconfigdata": "running",
"ecr": "running",
"tagging": "running",
"bedrock-runtime": "running",
"eks": "running",
"pipes": "running",
"elasticloadbalancing": "running",
"codebuild": "running",
"codedeploy": "running",
"autoscaling": "running"
}
""";
@ParameterizedTest
@ValueSource(strings = {"/_floci/health", "/_localstack/health"})
void health_returnsSameResponseOnBothPaths(String path) throws Exception {
String body = given()
.when().get(path)
.then()
.statusCode(200)
.contentType("application/json")
.extract().body().asString();
var tree = MAPPER.readTree(body);
assertEquals("community", tree.get("edition").asText());
assertEquals("floci-always-free", tree.get("original_edition").asText());
assertEquals("dev", tree.get("version").asText());
assertEquals(MAPPER.readTree(EXPECTED_SERVICES_JSON), tree.get("services"));
}
@ParameterizedTest
@ValueSource(strings = {"/_floci/init", "/_localstack/init"})
void init_returnsLifecycleStateOnBothPaths(String path) {
given()
.when().get(path)
.then()
.statusCode(200)
.contentType("application/json")
.body("completed.boot", equalTo(true))
.body("completed.start", equalTo(true))
.body("completed.ready", equalTo(true))
.body("completed.shutdown", equalTo(false))
.body("scripts.boot", hasSize(0))
.body("scripts.start", hasSize(0))
.body("scripts.ready", hasSize(0))
.body("scripts.shutdown", hasSize(0));
}
@ParameterizedTest
@ValueSource(strings = {"/_floci/info", "/_localstack/info"})
void info_returnsVersionAndEditionOnBothPaths(String path) {
given()
.when().get(path)
.then()
.statusCode(200)
.contentType("application/json")
.body("edition", equalTo("community"))
.body("version", notNullValue());
}
@ParameterizedTest
@ValueSource(strings = {"/_floci/diagnose", "/_localstack/diagnose"})
void diagnose_returns200OnBothPaths(String path) {
given().when().get(path).then().statusCode(200).contentType("application/json");
}
@ParameterizedTest
@ValueSource(strings = {"/_floci/config", "/_localstack/config"})
void config_returns200OnBothPaths(String path) {
given().when().get(path).then().statusCode(200).contentType("application/json");
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.lifecycle;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.lifecycle.InitLifecycleState;
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook;
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
@@ -51,6 +52,7 @@ class EmulatorLifecycleTest {
@Mock private DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller;
@Mock private PipesService pipesService;
@Mock private Ec2MetadataServer ec2MetadataServer;
@Mock private InitLifecycleState initLifecycleState;
private EmulatorLifecycle emulatorLifecycle;
@@ -65,7 +67,7 @@ class EmulatorLifecycleTest {
elastiCacheContainerManager, elastiCacheProxyManager,
rdsContainerManager, rdsProxyManager, initializationHooksRunner,
sqsPoller, kinesisPoller, dynamodbStreamsPoller, pipesService,
ec2MetadataServer);
ec2MetadataServer, initLifecycleState);
}
private void stubStorageConfig() {
@@ -75,15 +77,32 @@ class EmulatorLifecycleTest {
}
@Test
@DisplayName("Should log Ready immediately when no startup hooks exist")
@DisplayName("Should run BOOT hooks before loading storage, then mark boot complete")
void shouldRunBootHooksBeforeStorageLoad() throws IOException, InterruptedException {
stubStorageConfig();
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
var inOrder = Mockito.inOrder(initializationHooksRunner, storageFactory, initLifecycleState);
inOrder.verify(initializationHooksRunner).run(InitializationHook.BOOT);
inOrder.verify(initLifecycleState).markBootCompleted();
inOrder.verify(storageFactory).loadAll();
}
@Test
@DisplayName("Should log Ready immediately when no startup or ready hooks exist")
void shouldLogReadyImmediatelyWhenNoHooksExist() throws IOException, InterruptedException {
stubStorageConfig();
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
verify(storageFactory).loadAll();
verify(initializationHooksRunner).hasHooks(InitializationHook.START);
verify(initLifecycleState).markStartCompleted();
verify(initLifecycleState).markReadyCompleted();
verify(initializationHooksRunner, never()).run(InitializationHook.START);
}
@@ -92,13 +111,14 @@ class EmulatorLifecycleTest {
void shouldDeferHookExecutionWhenHooksExist() throws IOException, InterruptedException {
stubStorageConfig();
when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(true);
when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);
emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));
verify(storageFactory).loadAll();
verify(initializationHooksRunner).hasHooks(InitializationHook.START);
// run() is NOT called synchronously — it will be called by the virtual thread
// run() is NOT called synchronously from onStart — it will be called by onHttpStart
verify(initializationHooksRunner, never()).run(InitializationHook.START);
verify(initLifecycleState, never()).markStartCompleted();
}
@Test
@@ -1,90 +0,0 @@
package io.github.hectorvent.floci.lifecycle;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class HealthControllerIntegrationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String EXPECTED_HEALTH_JSON = """
{
"services": {
"ssm": "running",
"sqs": "running",
"s3": "running",
"dynamodb": "running",
"sns": "running",
"lambda": "running",
"apigateway": "running",
"iam": "running",
"kafka": "running",
"elasticache": "running",
"rds": "running",
"events": "running",
"scheduler": "running",
"logs": "running",
"monitoring": "running",
"secretsmanager": "running",
"apigatewayv2": "running",
"kinesis": "running",
"kms": "running",
"cognito-idp": "running",
"states": "running",
"cloudformation": "running",
"acm": "running",
"athena": "running",
"glue": "running",
"firehose": "running",
"email": "running",
"es": "running",
"ec2": "running",
"ecs": "running",
"appconfig": "running",
"appconfigdata": "running",
"ecr": "running",
"tagging": "running",
"bedrock-runtime": "running",
"eks": "running",
"pipes": "running",
"elasticloadbalancing": "running",
"codebuild": "running",
"codedeploy": "running",
"autoscaling": "running"
},
"edition": "floci-always-free",
"version": "dev"
}
""";
@Test
void healthEndpoint_returnsExpectedJson() throws Exception {
String body = given()
.when()
.get("/_floci/health")
.then()
.statusCode(200)
.contentType("application/json")
.extract().body().asString();
assertEquals(MAPPER.readTree(EXPECTED_HEALTH_JSON), MAPPER.readTree(body));
}
@Test
void healthEndpoint_localstackCompatPath() throws Exception {
String body = given()
.when()
.get("/_localstack/health")
.then()
.statusCode(200)
.contentType("application/json")
.extract().body().asString();
assertEquals(MAPPER.readTree(EXPECTED_HEALTH_JSON), MAPPER.readTree(body));
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.lifecycle.inithook;
import io.github.hectorvent.floci.lifecycle.InitLifecycleState;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@@ -15,6 +16,7 @@ import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
@ExtendWith(MockitoExtension.class)
class InitializationHooksRunnerTest {
@@ -22,6 +24,9 @@ class InitializationHooksRunnerTest {
@Mock
private HookScriptExecutor hookScriptExecutorMock;
@Mock
private InitLifecycleState initLifecycleStateMock;
@InjectMocks
private InitializationHooksRunner initializationHooksRunner;
@@ -156,34 +161,71 @@ class InitializationHooksRunnerTest {
}
@Test
@DisplayName("hasHooks should return true when scripts exist in hook directory")
@DisplayName("hasHooks should return true when scripts exist in a primary directory")
void hasHooksShouldReturnTrueWhenScriptsExist(@TempDir Path tempDir) throws IOException {
Files.createFile(tempDir.resolve("01-setup.sh"));
InitializationHook hook = Mockito.mock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("startup");
Mockito.when(hook.getPath()).thenReturn(tempDir.toFile());
Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(tempDir.toFile()));
Mockito.when(hook.getCompatPaths()).thenReturn(List.of());
Assertions.assertTrue(initializationHooksRunner.hasHooks(hook));
}
@Test
@DisplayName("hasHooks should return false when hook directory is empty")
@DisplayName("hasHooks should return true when scripts exist only in a compat directory")
void hasHooksShouldReturnTrueWhenScriptsExistInCompatDir(@TempDir Path tempDir) throws IOException {
Files.createFile(tempDir.resolve("01-setup.sh"));
InitializationHook hook = Mockito.mock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("startup");
Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of());
Mockito.when(hook.getCompatPaths()).thenReturn(List.of(tempDir.toFile()));
Assertions.assertTrue(initializationHooksRunner.hasHooks(hook));
}
@Test
@DisplayName("hasHooks should return false when all hook directories are empty")
void hasHooksShouldReturnFalseWhenDirectoryIsEmpty(@TempDir Path tempDir) {
InitializationHook hook = Mockito.mock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("startup");
Mockito.when(hook.getPath()).thenReturn(tempDir.toFile());
Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(tempDir.toFile()));
Mockito.when(hook.getCompatPaths()).thenReturn(List.of());
Assertions.assertFalse(initializationHooksRunner.hasHooks(hook));
}
@Test
@DisplayName("hasHooks should return false when hook directory does not exist")
@DisplayName("hasHooks should return false when hook directories do not exist")
void hasHooksShouldReturnFalseWhenDirectoryDoesNotExist() {
InitializationHook hook = Mockito.mock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("startup");
Mockito.when(hook.getPath()).thenReturn(new File("/nonexistent/path"));
Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(new File("/nonexistent/path")));
Mockito.when(hook.getCompatPaths()).thenReturn(List.of());
Assertions.assertFalse(initializationHooksRunner.hasHooks(hook));
}
@Test
@DisplayName("Primary path script should shadow same-named compat path script")
void primaryPathShouldShadowCompatPathForSameFilename(@TempDir Path primaryDir, @TempDir Path compatDir)
throws IOException, InterruptedException {
Files.createFile(primaryDir.resolve("01-seed.sh"));
Files.createFile(compatDir.resolve("01-seed.sh"));
Files.createFile(compatDir.resolve("02-extra.sh"));
InitializationHook hook = Mockito.mock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("ready");
Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(primaryDir.toFile()));
Mockito.when(hook.getCompatPaths()).thenReturn(List.of(compatDir.toFile()));
initializationHooksRunner.run(hook);
// 01-seed.sh from primaryDir wins; 02-extra.sh from compatDir is included
var inOrder = Mockito.inOrder(hookScriptExecutorMock);
inOrder.verify(hookScriptExecutorMock).run(primaryDir.resolve("01-seed.sh").toFile());
inOrder.verify(hookScriptExecutorMock).run(compatDir.resolve("02-extra.sh").toFile());
inOrder.verifyNoMoreInteractions();
}
}
@@ -0,0 +1,126 @@
package io.github.hectorvent.floci.services.apigateway;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
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 static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Verifies that the LocalStack-compatible {@code /_aws/execute-api} URL prefix
* correctly routes to the same execution logic as the standard execute-api path.
*
* <p>LocalStack URL: {@code /_aws/execute-api/{apiId}/{stageName}/{proxy+}}
* <p>Standard URL: {@code /execute-api/{apiId}/{stageName}/{proxy+}}
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ApiGatewayAwsExecuteIntegrationTest {
private static String apiId;
private static String rootId;
private static String resourceId;
private static String deploymentId;
@Test @Order(1)
void createRestApi() {
apiId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"aws-execute-test-api\"}")
.when().post("/restapis")
.then()
.statusCode(201)
.body("id", notNullValue())
.extract().path("id");
}
@Test @Order(2)
void setupMockIntegration() {
rootId = given()
.when().get("/restapis/" + apiId + "/resources")
.then()
.statusCode(200)
.extract().path("item[0].id");
resourceId = given()
.contentType(ContentType.JSON)
.body("{\"pathPart\":\"hello\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then()
.statusCode(201)
.extract().path("id");
given()
.contentType(ContentType.JSON)
.body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
.then()
.statusCode(201);
given()
.contentType(ContentType.JSON)
.body("{\"responseParameters\":{}}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/responses/200")
.then()
.statusCode(201);
given()
.contentType(ContentType.JSON)
.body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration")
.then()
.statusCode(201);
given()
.contentType(ContentType.JSON)
.body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{\\\"message\\\":\\\"ok\\\"}\"}}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration/responses/200")
.then()
.statusCode(201);
}
@Test @Order(3)
void createDeploymentAndStage() {
deploymentId = given()
.contentType(ContentType.JSON)
.body("{\"description\":\"v1\"}")
.when().post("/restapis/" + apiId + "/deployments")
.then()
.statusCode(201)
.extract().path("id");
given()
.contentType(ContentType.JSON)
.body("{\"stageName\":\"prod\",\"deploymentId\":\"" + deploymentId + "\"}")
.when().post("/restapis/" + apiId + "/stages")
.then()
.statusCode(201);
}
@Test @Order(4)
void executeViaAwsPrefix() {
given()
.when().get("/_aws/execute-api/" + apiId + "/prod/hello")
.then()
.statusCode(200)
.body("message", equalTo("ok"));
}
@Test @Order(5)
void executeViaStandardPath_stillWorks() {
given()
.when().get("/execute-api/" + apiId + "/prod/hello")
.then()
.statusCode(200)
.body("message", equalTo("ok"));
}
@Test @Order(6)
void cleanup() {
given().when().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@@ -0,0 +1,114 @@
package io.github.hectorvent.floci.services.sqs;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
class SqsInspectionControllerIntegrationTest {
private static final String QUEUE_NAME = "inspection-test-queue";
private static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
private String queueUrl;
@BeforeEach
void setUp() {
queueUrl = given()
.contentType(CONTENT_TYPE)
.formParam("Action", "CreateQueue")
.formParam("QueueName", QUEUE_NAME)
.when().post("/")
.then().statusCode(200)
.extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
given()
.contentType(CONTENT_TYPE)
.formParam("Action", "PurgeQueue")
.formParam("QueueUrl", queueUrl)
.when().post("/").then().statusCode(200);
}
@Test
@DisplayName("GET /_aws/sqs/messages returns empty list for empty queue")
void shouldReturnEmptyListForEmptyQueue() {
given()
.queryParam("QueueUrl", queueUrl)
.when().get("/_aws/sqs/messages")
.then()
.statusCode(200)
.body("messages", hasSize(0));
}
@Test
@DisplayName("GET /_aws/sqs/messages returns all messages without consuming them")
void shouldReturnMessagesWithoutConsuming() {
given().contentType(CONTENT_TYPE)
.formParam("Action", "SendMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MessageBody", "hello world")
.when().post("/").then().statusCode(200);
given().contentType(CONTENT_TYPE)
.formParam("Action", "SendMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MessageBody", "second message")
.when().post("/").then().statusCode(200);
given()
.queryParam("QueueUrl", queueUrl)
.when().get("/_aws/sqs/messages")
.then()
.statusCode(200)
.body("messages", hasSize(2))
.body("messages[0].Body", notNullValue())
.body("messages[0].MessageId", notNullValue())
.body("messages[0].MD5OfBody", notNullValue())
.body("messages[0].Attributes.SentTimestamp", notNullValue())
.body("messages[0].Attributes.ApproximateReceiveCount", equalTo("0"));
// messages must still be there after peek
given()
.queryParam("QueueUrl", queueUrl)
.when().get("/_aws/sqs/messages")
.then()
.statusCode(200)
.body("messages", hasSize(2));
}
@Test
@DisplayName("DELETE /_aws/sqs/messages purges the queue")
void shouldPurgeQueueOnDelete() {
given().contentType(CONTENT_TYPE)
.formParam("Action", "SendMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MessageBody", "to be purged")
.when().post("/").then().statusCode(200);
given()
.queryParam("QueueUrl", queueUrl)
.when().delete("/_aws/sqs/messages")
.then()
.statusCode(200);
given()
.queryParam("QueueUrl", queueUrl)
.when().get("/_aws/sqs/messages")
.then()
.statusCode(200)
.body("messages", hasSize(0));
}
@Test
@DisplayName("GET /_aws/sqs/messages returns 400 when QueueUrl is missing")
void shouldReturn400WhenQueueUrlMissing() {
given()
.when().get("/_aws/sqs/messages")
.then()
.statusCode(400);
}
}