diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index aa8818991b..c195d2782a 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -41,6 +41,26 @@ if [ "${LOCALSTACK_PARITY:-true}" != "false" ]; then . /usr/local/bin/localstack-parity.sh fi +# Probe the state dir as the unprivileged user and warn loudly when it is not +# writable (read-only or root-owned bind mounts the chown above could not fix). +# The container still starts: with the default in-memory storage the dir is +# unused, and non-memory modes fail fast at boot with an actionable error. +data_dir="${FLOCI_STORAGE_PERSISTENT_PATH:-/app/data}" +if [ -d "$data_dir" ]; then + probe="$data_dir/.floci-write-probe.$$" + if ! ( touch "$probe" && rm -f "$probe" ) 2>/dev/null; then + cat >&2 <"${RO_ERR}")" +if grep -q 'not writable' "${RO_ERR}"; then + printf '[PASS] unwritable state dir prints a loud warning\n' + PASS=$((PASS + 1)) +else + printf '[FAIL] unwritable state dir prints a loud warning\n stderr was:\n%s\n' "$(cat "${RO_ERR}")" + FAIL=$((FAIL + 1)) +fi +chmod 755 "${RO_DIR}" + +# --- writable state dir stays quiet and leaves no probe behind --- +RW_DIR="${WORK}/rw-data" +mkdir -p "${RW_DIR}" +RW_ERR="${WORK}/rw-err.txt" +FLOCI_STORAGE_PERSISTENT_PATH="${RW_DIR}" LOCALSTACK_PARITY=false sh "${SCRIPT}" echo ok >/dev/null 2>"${RW_ERR}" +if ! grep -q 'not writable' "${RW_ERR}" && [ -z "$(ls -A "${RW_DIR}")" ]; then + printf '[PASS] writable state dir stays quiet and leaves no probe file\n' + PASS=$((PASS + 1)) +else + printf '[FAIL] writable state dir stays quiet and leaves no probe file\n' + FAIL=$((FAIL + 1)) +fi + printf '\n%d passed, %d failed\n' "${PASS}" "${FAIL}" [ "${FAIL}" -eq 0 ] diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/PersistentPathValidator.java b/src/main/java/io/github/hectorvent/floci/core/storage/PersistentPathValidator.java new file mode 100644 index 0000000000..f049f2b83c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/storage/PersistentPathValidator.java @@ -0,0 +1,77 @@ +package io.github.hectorvent.floci.core.storage; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.ResolvedServiceCatalog; +import io.github.hectorvent.floci.core.common.ServiceDescriptor; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +/** + * Validates at boot that the persistent storage path is usable whenever any enabled service + * runs with a non-memory storage mode. Without this check the failure surfaces lazily and + * confusingly: S3 answers every request with an opaque 500 (its service bean creates its data + * directory in the constructor), while other services silently lose data at flush time. + */ +@ApplicationScoped +public class PersistentPathValidator { + + private final ResolvedServiceCatalog catalog; + private final EmulatorConfig config; + + @Inject + public PersistentPathValidator(ResolvedServiceCatalog catalog, EmulatorConfig config) { + this.catalog = catalog; + this.config = config; + } + + /** + * @throws IllegalStateException when persistence is enabled but the path is unusable + */ + public void validateAtBoot() { + List persistent = catalog.all().stream() + .filter(d -> d.enabled() && d.supportsStorage() && !"memory".equals(d.storageMode())) + .toList(); + if (persistent.isEmpty()) { + return; + } + + Path root = Path.of(config.storage().persistentPath()); + try { + probeWritable(root); + Path s3Root = root.resolve("s3"); + boolean s3Persistent = persistent.stream().anyMatch(d -> "s3".equals(d.storageKey())); + if (s3Persistent && Files.isDirectory(s3Root)) { + probeWritable(s3Root); + } + } catch (IOException | SecurityException e) { + String services = persistent.stream() + .map(d -> d.storageKey() + "=" + d.storageMode()) + .distinct() + .limit(8) + .reduce((a, b) -> a + ", " + b) + .orElse(""); + throw new IllegalStateException( + "Persistent storage path '" + root.toAbsolutePath() + + "' is not writable, but non-memory storage is enabled (" + services + + "). Fix the volume mount permissions (it may be read-only or root-owned)," + + " or point FLOCI_STORAGE_PERSISTENT_PATH at a writable directory.", e); + } + } + + static void probeWritable(Path dir) throws IOException { + Files.createDirectories(dir); + Path probe = Files.createTempFile(dir, ".floci-write-probe", null); + try { + Files.deleteIfExists(probe); + } catch (IOException e) { + // The write itself succeeded, so the path is writable; a failed cleanup + // must not abort boot as a false "not writable". + probe.toFile().deleteOnExit(); + } + } +} 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 5c1cb5f51c..9d554a8629 100644 --- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.lifecycle; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.ContainerTeardown; import io.github.hectorvent.floci.core.common.ServiceRegistry; +import io.github.hectorvent.floci.core.storage.PersistentPathValidator; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook; import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner; @@ -85,6 +86,7 @@ public class EmulatorLifecycle { private final InitLifecycleState initLifecycleState; private final SchemaCreationWorker schemaCreationWorker; private final jakarta.enterprise.inject.Instance containerTeardowns; + private final PersistentPathValidator persistentPathValidator; @Inject public EmulatorLifecycle(StorageFactory storageFactory, ServiceRegistry serviceRegistry, @@ -111,7 +113,8 @@ public class EmulatorLifecycle { FlociUiManager flociUiManager, InitLifecycleState initLifecycleState, SchemaCreationWorker schemaCreationWorker, - jakarta.enterprise.inject.Instance containerTeardowns) { + jakarta.enterprise.inject.Instance containerTeardowns, + PersistentPathValidator persistentPathValidator) { this.storageFactory = storageFactory; this.serviceRegistry = serviceRegistry; this.config = config; @@ -138,6 +141,7 @@ public class EmulatorLifecycle { this.initLifecycleState = initLifecycleState; this.schemaCreationWorker = schemaCreationWorker; this.containerTeardowns = containerTeardowns; + this.persistentPathValidator = persistentPathValidator; } void onStart(@Observes StartupEvent ignored) { @@ -158,6 +162,8 @@ public class EmulatorLifecycle { } initLifecycleState.markBootCompleted(); + persistentPathValidator.validateAtBoot(); + serviceRegistry.logEnabledServices(); storageFactory.loadAll(); schemaCreationWorker.recoverOrphans(); diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3ControlController.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3ControlController.java index 0be51c211a..945077dbf3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3ControlController.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3ControlController.java @@ -15,6 +15,8 @@ import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.MediaType; +import org.jboss.logging.Logger; +import org.jboss.resteasy.reactive.server.ServerExceptionMapper; import jakarta.ws.rs.core.Response; import java.net.URLDecoder; @@ -35,6 +37,8 @@ import java.util.UUID; @Produces(MediaType.APPLICATION_XML) public class S3ControlController { + private static final Logger LOG = Logger.getLogger(S3ControlController.class); + private static final String AMZ_REQUEST_ID = "x-amz-request-id"; private static final String AMZN_REQUEST_ID = "x-amzn-RequestId"; private static final String AMZ_ID_2 = "x-amz-id-2"; @@ -213,6 +217,20 @@ public class S3ControlController { * bare {@code } collapses to "UnknownError" at the SDK layer. * See issue #557. */ + // Same protocol safety net as S3Controller: unhandled failures on S3 Control routes + // must render the REST-XML error contract, not Quarkus's plain-text error page. + @ServerExceptionMapper + public Response mapUnhandledThrowable(Throwable t) { + LOG.error("Unhandled exception processing S3 Control request", t); + return xmlErrorResponse(new AwsException("InternalError", + "We encountered an internal error. Please try again.", 500)); + } + + @ServerExceptionMapper + public Response mapEscapedAwsException(AwsException e) { + return xmlErrorResponse(e); + } + private Response xmlErrorResponse(AwsException e) { String requestId = UUID.randomUUID().toString(); String xml = new XmlBuilder() diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java index 3b1a1c75ce..871422a9b2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java @@ -60,6 +60,7 @@ import javax.xml.stream.XMLStreamReader; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.jboss.logging.Logger; +import org.jboss.resteasy.reactive.server.ServerExceptionMapper; /** * S3 controller handling REST-style S3 API requests. @@ -2145,6 +2146,23 @@ public class S3Controller { + "
  • Code: " + code + "
  • Message: " + message + "
"; } + // Unhandled failures on S3 routes (e.g. lazy CDI bean instantiation throwing inside an + // endpoint body) must render S3's InternalError XML contract, never Quarkus's plain-text + // error page, which SDK REST-XML parsers cannot read. Class-scoped: S3 endpoints only. + @ServerExceptionMapper + public Response mapUnhandledThrowable(Throwable t) { + LOG.error("Unhandled exception processing S3 request", t); + return xmlErrorResponse(new AwsException("InternalError", + "We encountered an internal error. Please try again.", 500)); + } + + // An AwsException escaping an endpoint body would otherwise hit the global JSON + // AwsExceptionMapper (exact-type match wins over the class-scoped Throwable mapper). + @ServerExceptionMapper + public Response mapEscapedAwsException(AwsException e) { + return xmlErrorResponse(e); + } + private Response xmlErrorResponse(AwsException e) { String condition = e instanceof S3PreconditionFailedException preconditionFailedException ? preconditionFailedException.condition() diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/PersistentPathValidatorTest.java b/src/test/java/io/github/hectorvent/floci/core/storage/PersistentPathValidatorTest.java new file mode 100644 index 0000000000..2523441cdc --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/storage/PersistentPathValidatorTest.java @@ -0,0 +1,114 @@ +package io.github.hectorvent.floci.core.storage; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.ResolvedServiceCatalog; +import io.github.hectorvent.floci.core.common.ServiceDescriptor; +import io.github.hectorvent.floci.core.common.ServiceProtocol; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class PersistentPathValidatorTest { + + @TempDir + Path tempDir; + + @Mock private ResolvedServiceCatalog catalog; + @Mock private EmulatorConfig config; + @Mock private EmulatorConfig.StorageConfig storageConfig; + + private PersistentPathValidator validator() { + lenient().when(config.storage()).thenReturn(storageConfig); + return new PersistentPathValidator(catalog, config); + } + + private static ServiceDescriptor descriptor(String key, boolean enabled, String storageKey, String mode) { + return new ServiceDescriptor(key, key, enabled, true, storageKey, mode, 0L, + null, ServiceProtocol.REST_XML, Set.of(ServiceProtocol.REST_XML), + Set.of(), Set.of(), Set.of(), Set.of()); + } + + @Test + void memoryOnlyBootDoesNotTouchTheFilesystem() { + when(catalog.all()).thenReturn(List.of( + descriptor("s3", true, "s3", "memory"), + descriptor("sqs", true, "sqs", "memory"))); + + PersistentPathValidator validator = validator(); + validator.validateAtBoot(); + } + + @Test + void nonMemoryModeCreatesPathAndLeavesNoProbeBehind() throws IOException { + Path root = tempDir.resolve("data"); + when(catalog.all()).thenReturn(List.of(descriptor("sqs", true, "sqs", "hybrid"))); + when(storageConfig.persistentPath()).thenReturn(root.toString()); + + validator().validateAtBoot(); + + assertTrue(Files.isDirectory(root)); + try (var entries = Files.list(root)) { + assertEquals(0, entries.count(), "write probe must not be left behind"); + } + } + + @Test + @DisabledOnOs(OS.WINDOWS) + void unwritablePathFailsWithActionableMessage() throws IOException { + Assumptions.assumeFalse("root".equals(System.getProperty("user.name")), + "root ignores directory write permissions"); + Path readOnlyParent = tempDir.resolve("ro"); + Files.createDirectories(readOnlyParent); + assertTrue(readOnlyParent.toFile().setWritable(false)); + try { + Path root = readOnlyParent.resolve("data"); + when(catalog.all()).thenReturn(List.of(descriptor("s3", true, "s3", "hybrid"))); + when(storageConfig.persistentPath()).thenReturn(root.toString()); + + IllegalStateException e = assertThrows(IllegalStateException.class, + () -> validator().validateAtBoot()); + assertTrue(e.getMessage().contains(root.toAbsolutePath().toString())); + assertTrue(e.getMessage().contains("FLOCI_STORAGE_PERSISTENT_PATH")); + assertTrue(e.getMessage().contains("s3=hybrid")); + } finally { + assertTrue(readOnlyParent.toFile().setWritable(true)); + } + } + + @Test + void persistentPathThatIsAFileFailsClearly() throws IOException { + Path root = tempDir.resolve("data"); + Files.writeString(root, "not a directory"); + when(catalog.all()).thenReturn(List.of(descriptor("s3", true, "s3", "persistent"))); + when(storageConfig.persistentPath()).thenReturn(root.toString()); + + IllegalStateException e = assertThrows(IllegalStateException.class, + () -> validator().validateAtBoot()); + assertTrue(e.getMessage().contains(root.toAbsolutePath().toString())); + } + + @Test + void disabledServicesDoNotTriggerValidation() { + when(catalog.all()).thenReturn(List.of(descriptor("s3", false, "s3", "hybrid"))); + + validator().validateAtBoot(); + } +} 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 d12429116b..ea3473abdd 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java @@ -2,6 +2,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.PersistentPathValidator; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.lifecycle.InitLifecycleState; import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook; @@ -39,6 +40,7 @@ import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.doThrow; @@ -76,6 +78,7 @@ class EmulatorLifecycleTest { @Mock private EcrRegistryManager ecrRegistryManager; @Mock private io.github.hectorvent.floci.services.floci.ui.FlociUiManager flociUiManager; @Mock private InitLifecycleState initLifecycleState; + @Mock private PersistentPathValidator persistentPathValidator; @Mock private EmulatorConfig.TlsConfig tlsConfig; @Mock private io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker schemaCreationWorker; @Mock private jakarta.enterprise.inject.Instance containerTeardowns; @@ -99,7 +102,7 @@ class EmulatorLifecycleTest { rabbitMqManager, rdsService, initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller, pipesService, ec2MetadataServer, ecrRegistryManager, flociUiManager, initLifecycleState, - schemaCreationWorker, containerTeardowns); + schemaCreationWorker, containerTeardowns, persistentPathValidator); Mockito.lenient().when(containerTeardowns.iterator()) .thenReturn(java.util.Collections.emptyIterator()); } @@ -126,6 +129,33 @@ class EmulatorLifecycleTest { inOrder.verify(rdsService).restorePersistedRuntime(); } + @Test + @DisplayName("Should validate the persistent path after BOOT hooks and before loading storage") + void shouldValidatePersistentPathBeforeStorageLoad() { + 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(initLifecycleState, persistentPathValidator, storageFactory); + inOrder.verify(initLifecycleState).markBootCompleted(); + inOrder.verify(persistentPathValidator).validateAtBoot(); + inOrder.verify(storageFactory).loadAll(); + } + + @Test + @DisplayName("Should abort startup when the persistent path validation fails") + void shouldAbortStartupWhenPersistentPathValidationFails() { + stubStorageConfig(); + doThrow(new IllegalStateException("Persistent storage path '/app/data' is not writable")) + .when(persistentPathValidator).validateAtBoot(); + + assertThrows(IllegalStateException.class, + () -> emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class))); + Mockito.verify(storageFactory, Mockito.never()).loadAll(); + } + @Test @DisplayName("Should log Ready immediately when no startup or ready hooks exist") void shouldLogReadyImmediatelyWhenNoHooksExist() throws IOException, InterruptedException { diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3InternalErrorIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3InternalErrorIntegrationTest.java new file mode 100644 index 0000000000..0b9df6e503 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3InternalErrorIntegrationTest.java @@ -0,0 +1,54 @@ +package io.github.hectorvent.floci.services.s3; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.emptyOrNullString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.mockito.Mockito.when; + +/** + * S3 routes must never surface Quarkus's plain-text 500 page: SDK REST-XML parsers choke on + * it (issue #1664 — a lazily-instantiated S3Service whose constructor throws turned every S3 + * call into an opaque 500). Unhandled throwables map to AWS's InternalError XML contract. + */ +@QuarkusTest +class S3InternalErrorIntegrationTest { + + @InjectMock + S3Service s3Service; + + @Test + void unhandledThrowableRendersInternalErrorXml() { + when(s3Service.listBuckets()).thenThrow(new RuntimeException("simulated bean failure")); + + given() + .when() + .get("/") + .then() + .statusCode(500) + .contentType(containsString("application/xml")) + .body("Error.Code", equalTo("InternalError")) + .body("Error.Message", equalTo("We encountered an internal error. Please try again.")) + .body("Error.RequestId", not(emptyOrNullString())); + } + + @Test + void awsExceptionStillRendersItsOwnXmlError() { + when(s3Service.listBuckets()).thenThrow(new AwsException("AccessDenied", "Access Denied", 403)); + + given() + .when() + .get("/") + .then() + .statusCode(403) + .contentType(containsString("application/xml")) + .body("Error.Code", equalTo("AccessDenied")) + .body("Error.Message", equalTo("Access Denied")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java index ecbeb69968..bb77686eb2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java @@ -38,6 +38,23 @@ class S3ServiceTest { s3Service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), dataRoot, false); } + @Test + @org.junit.jupiter.api.condition.DisabledOnOs(org.junit.jupiter.api.condition.OS.WINDOWS) + void constructorThrowsWhenDataRootUncreatable() throws Exception { + org.junit.jupiter.api.Assumptions.assumeFalse("root".equals(System.getProperty("user.name")), + "root ignores directory write permissions"); + Path readOnlyParent = tempDir.resolve("ro"); + Files.createDirectories(readOnlyParent); + assertTrue(readOnlyParent.toFile().setWritable(false)); + try { + Path dataRoot = readOnlyParent.resolve("s3"); + assertThrows(java.io.UncheckedIOException.class, + () -> new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), dataRoot, false)); + } finally { + assertTrue(readOnlyParent.toFile().setWritable(true)); + } + } + @Test void createBucket() { Bucket bucket = s3Service.createBucket("test-bucket", "us-east-1");