fix(s3): fail fast on unwritable data root instead of opaque 500s (#1868)

When the persistent path is not writable (read-only or root-owned bind
mounts), S3Service's constructor failed lazily and every S3 request
surfaced as an opaque plain-text 500 that REST-XML SDK parsers cannot
read.

- validate the persistent path at boot and refuse to start with an
  actionable error when any enabled service uses non-memory storage
- add class-scoped exception mappers so unhandled failures on S3 and
  S3-Control routes render the S3 InternalError XML contract instead of
  Quarkus's plain-text error page
- warn loudly from the container entrypoint when the state dir is not
  writable by the runtime user

Fixes #1664
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-07-15 00:43:11 -04:00
1 parent 1ba15f0ce7
commit fe49bee41e
10 files changed
+386 -2

No files matched your search

@@ -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();
}
}
@@ -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<io.github.hectorvent.floci.core.common.ContainerTeardown> 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 {
@@ -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"));
}
}
@@ -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");