fix(ecr): never start the registry container while ECR is disabled (#6281)

This commit is contained in:
floverfelt authored and GitHub committed 2026-10-22 21:29:53 -04:00
1 parent 7635345474
commit a29df66d33
13 files changed
+420 -8

No files matched your search

@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@@ -17,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@@ -30,6 +32,31 @@ class CloudFormationTemplateEngineTest {
(Function<String, String>) name -> null);
}
private CloudFormationTemplateEngine engineWithAttributes(Map<String, Map<String, String>> attributes) {
return new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",
"stack/id", Map.of(), Map.of(), attributes, Map.of(), Map.of(), mapper,
(Function<String, String>) name -> null);
}
@Test
void getAttOnAMissingAttributeOfAStubbedDisabledServiceIsRefused() {
CloudFormationTemplateEngine e = engineWithAttributes(Map.of("Repo", Map.of(
"Arn", "arn:aws:stub:::Repo", CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR, "true")));
AwsException failure = assertThrows(AwsException.class,
() -> e.resolve(json("{\"Fn::GetAtt\": [\"Repo\", \"RepositoryUri\"]}")));
assertEquals("ValidationError", failure.getErrorCode());
assertEquals("arn:aws:stub:::Repo", e.resolve(json("{\"Fn::GetAtt\": [\"Repo\", \"Arn\"]}")));
}
@Test
void getAttOnAMissingAttributeOfAnOrdinaryStubStillResolvesToThePlaceholder() {
CloudFormationTemplateEngine e = engineWithAttributes(Map.of("Thing", Map.of("Arn", "arn:aws:stub:::Thing")));
assertEquals("Thing.Missing", e.resolve(json("{\"Fn::GetAtt\": [\"Thing\", \"Missing\"]}")));
}
private JsonNode json(String s) {
try {
return mapper.readTree(s);
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
import io.github.hectorvent.floci.services.ecr.EcrService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -131,6 +132,54 @@ class CloudFormationUnsupportedResourceTypeTest {
"expected the skipped delete to be reported at warn, got: " + rendered(logged));
}
private static final String ECR_TYPE = "AWS::ECR::Repository";
private static final String ECR_DISABLED_HINT =
"Resource type AWS::ECR::Repository is not provisioned because its Floci service is disabled. "
+ "Set floci.services.ecr.enabled=true to provision it.";
@Test
void disabledEcrIsStubbedWithADisabledReasonAndWarningNamingItsFlag() {
CfnResourceDispatcher ecrDisabled = ecrDisabledDispatcher(true);
List<LogRecord> logged = new CopyOnWriteArrayList<>();
StackResource resource = whileCapturingProvisionerLogs(logged, () -> ecrDisabled
.provision("Repo", ECR_TYPE, props(), engine(), REGION, ACCOUNT_ID, STACK_NAME));
assertEquals("CREATE_COMPLETE", resource.getStatus());
assertEquals(ECR_DISABLED_HINT + " It was stubbed and nothing was created for it.",
resource.getStatusReason());
assertTrue(logged.stream().anyMatch(r -> r.getLevel().intValue() >= Level.WARNING.intValue()
&& ("Stubbing resource type AWS::ECR::Repository (Repo): its service is disabled, "
+ "so nothing is created for it. Set floci.services.ecr.enabled=true to provision it.")
.equals(formatted(r))),
"expected the disabled-service warning, got: " + rendered(logged));
assertTrue(logged.stream().noneMatch(r -> formatted(r).contains("allow-stub-unsupported-resource-types")),
"the warning must not blame the unsupported-type flag: " + rendered(logged));
}
@Test
void disabledEcrFailsWithTheDisabledReasonWhenTheStubIsDisallowed() {
StackResource resource = ecrDisabledDispatcher(false)
.provision("Repo", ECR_TYPE, props(), engine(), REGION, ACCOUNT_ID, STACK_NAME);
assertEquals("CREATE_FAILED", resource.getStatus());
assertEquals(ECR_DISABLED_HINT, resource.getStatusReason());
assertNull(resource.getPhysicalId());
}
private CfnResourceDispatcher ecrDisabledDispatcher(boolean stubAllowed) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.CloudFormationServiceConfig cloudformation =
mock(EmulatorConfig.CloudFormationServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.cloudformation()).thenReturn(cloudformation);
when(cloudformation.allowStubUnsupportedResourceTypes()).thenReturn(stubAllowed);
EcrService ecr = mock(EcrService.class);
when(ecr.isDisabled()).thenReturn(true);
return CfnProvisionerFixture.builder().objectMapper(mapper).config(config).ecr(ecr).build();
}
private CfnResourceDispatcher provisionerWithStubAllowed(boolean allowed) {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
@@ -2,7 +2,9 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.junit.jupiter.api.Test;
@@ -13,12 +15,15 @@ import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -162,6 +167,22 @@ class CfnResourceDispatcherTest {
assertEquals("CREATE_COMPLETE", resource.getStatus());
}
@Test
void aProvisionerThatMigratesAStubOfADisabledServiceDropsTheDisabledMarker() {
when(registry.forType(TYPE)).thenReturn(Optional.of(provisioner((resource, ctx) -> {
resource.setPhysicalId("dash-real");
resource.getAttributes().put("Arn", "arn:aws:ecr:us-east-1:000000000000:repository/dash-real");
})));
StackResource resource = dispatcher.provision("Dash", TYPE, mapper.createObjectNode(), null,
"us-east-1", "000000000000", "my-stack", "Dash-1a2b3c4d",
Map.of("Arn", "arn:aws:stub:::Dash", CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR, "true"));
assertFalse(resource.getAttributes().containsKey(CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR),
"the real resource must not keep refusing its own attributes");
assertEquals("dash-real", resource.getPhysicalId());
}
@Test
void aProvisionerThatMigratesAStubAndWritesOtherAttributesStillDropsTheStubArn() {
when(registry.forType(TYPE)).thenReturn(Optional.of(provisioner((resource, ctx) ->
@@ -226,6 +247,167 @@ class CfnResourceDispatcherTest {
"thing-1".equals(r.getPhysicalId()) && "r".equals(r.getAttributes().get("Role"))), any());
}
/**
* A provisioner whose service is turned off serves none of its types: the dispatcher stubs
* the resource instead of provisioning it, so a disabled service is never reached.
*/
@Test
void aProvisionerWhoseServiceIsDisabledIsStubbedNotProvisioned() {
DisabledServiceProvisioner disabled = new DisabledServiceProvisioner(TYPE);
CfnResourceDispatcher routed = new CfnResourceDispatcher(mapper, new CloudFormationResourceRegistry(
List.of(disabled)), dynamicReferences, null);
StackResource resource = routed.provision("Thing", TYPE, mapper.createObjectNode(), null,
"us-east-1", "000000000000", "my-stack");
assertFalse(disabled.provisioned, "a disabled service must not be provisioned");
assertEquals("CREATE_COMPLETE", resource.getStatus());
assertEquals("arn:aws:stub:::Thing", resource.getAttributes().get("Arn"));
}
@Test
void deletingAResourceOfADisabledServiceReachesNoProvisioner() {
DisabledServiceProvisioner disabled = new DisabledServiceProvisioner(TYPE);
CfnResourceDispatcher routed = new CfnResourceDispatcher(mapper, new CloudFormationResourceRegistry(
List.of(disabled)), dynamicReferences, null);
routed.delete(TYPE, "thing-1", "us-east-1");
assertFalse(disabled.deleted, "a disabled service must not be deleted from");
}
@Test
void aStubbedResourceOfADisabledServiceIsMarkedSoItsMissingAttributesAreRefused() {
CfnResourceDispatcher routed = disabledDispatcher(new DisabledServiceProvisioner(TYPE));
StackResource resource = routed.provision("Thing", TYPE, mapper.createObjectNode(), null,
"us-east-1", "000000000000", "my-stack");
assertEquals("true", resource.getAttributes().get(CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR));
}
@Test
void updatingARealResourceWhileItsServiceIsDisabledFailsAndKeepsItsPhysicalId() {
DisabledServiceProvisioner disabled = new DisabledServiceProvisioner(TYPE);
CfnResourceDispatcher routed = disabledDispatcher(disabled);
StackResource resource = routed.provision("Thing", TYPE, mapper.createObjectNode(), null,
"us-east-1", "000000000000", "my-stack", "real-repo",
Map.of("Arn", "arn:aws:ecr:us-east-1:000000000000:repository/real-repo"));
assertEquals("CREATE_FAILED", resource.getStatus());
assertEquals("real-repo", resource.getPhysicalId());
assertFalse(resource.getAttributes().containsKey(CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR));
assertFalse(disabled.provisioned);
}
@Test
void updatingAStubWhileItsServiceIsDisabledStaysStubbed() {
CfnResourceDispatcher routed = disabledDispatcher(new DisabledServiceProvisioner(TYPE));
StackResource resource = routed.provision("Thing", TYPE, mapper.createObjectNode(), null,
"us-east-1", "000000000000", "my-stack", "Thing-1a2b3c4d",
Map.of("Arn", "arn:aws:stub:::Thing", CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR, "true"));
assertEquals("CREATE_COMPLETE", resource.getStatus());
assertEquals("arn:aws:stub:::Thing", resource.getAttributes().get("Arn"));
}
@Test
void deletingARealResourceWhileItsServiceIsDisabledFailsInsteadOfDroppingIt() {
DisabledServiceProvisioner disabled = new DisabledServiceProvisioner(TYPE);
CfnResourceDispatcher routed = disabledDispatcher(disabled);
StackResource real = new StackResource();
real.setResourceType(TYPE);
real.setPhysicalId("real-repo");
real.setAttributes(Map.of("Arn", "arn:aws:ecr:us-east-1:000000000000:repository/real-repo"));
AwsException failure = assertThrows(AwsException.class, () -> routed.delete(real, "us-east-1"));
assertEquals(400, failure.getHttpStatus());
assertFalse(disabled.deleted);
}
@Test
void deletingAStubWhileItsServiceIsDisabledSucceeds() {
CfnResourceDispatcher routed = disabledDispatcher(new DisabledServiceProvisioner(TYPE));
StackResource stub = new StackResource();
stub.setResourceType(TYPE);
stub.setPhysicalId("Thing-1a2b3c4d");
stub.setAttributes(Map.of("Arn", "arn:aws:stub:::Thing",
CloudFormationTemplateEngine.SERVICE_DISABLED_ATTR, "true"));
assertDoesNotThrow(() -> routed.delete(stub, "us-east-1"));
}
@Test
void aStubbedResourceOfADisabledServiceSaysTheServiceIsDisabledAndNamesItsFlag() {
CfnResourceDispatcher routed = disabledDispatcher(new DisabledServiceProvisioner(TYPE));
StackResource resource = routed.provision("Thing", TYPE, mapper.createObjectNode(), null,
"us-east-1", "000000000000", "my-stack");
assertEquals("Resource type " + TYPE + " is not provisioned because its Floci service is disabled. "
+ "Set floci.services.thing.enabled=true to provision it. "
+ "It was stubbed and nothing was created for it.", resource.getStatusReason());
}
@Test
void aDisabledServiceFailsWithTheDisabledMessageWhenStubbingIsOff() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().cloudformation().allowStubUnsupportedResourceTypes()).thenReturn(false);
CfnResourceDispatcher strict = new CfnResourceDispatcher(mapper, new CloudFormationResourceRegistry(
List.of(new DisabledServiceProvisioner(TYPE))), dynamicReferences, config);
StackResource resource = strict.provision("Thing", TYPE, mapper.createObjectNode(), null,
"us-east-1", "000000000000", "my-stack");
assertEquals("CREATE_FAILED", resource.getStatus());
assertEquals("Resource type " + TYPE + " is not provisioned because its Floci service is disabled. "
+ "Set floci.services.thing.enabled=true to provision it.", resource.getStatusReason());
}
private CfnResourceDispatcher disabledDispatcher(DisabledServiceProvisioner disabled) {
return new CfnResourceDispatcher(mapper, new CloudFormationResourceRegistry(List.of(disabled)),
dynamicReferences, null);
}
/** A provisioner whose service is disabled, recording whether it was ever asked to act. */
private static final class DisabledServiceProvisioner implements CfnResourceProvisioner {
private final String type;
private boolean provisioned;
private boolean deleted;
private DisabledServiceProvisioner(String type) {
this.type = type;
}
@Override
public Set<String> resourceTypes() {
return Set.of(type);
}
@Override
public boolean serviceDisabled() {
return true;
}
@Override
public String serviceEnabledFlag() {
return "floci.services.thing.enabled";
}
@Override
public void provision(StackResource resource, JsonNode properties, ProvisionContext ctx) {
provisioned = true;
}
@Override
public void delete(String resourceType, String physicalId, String region) {
deleted = true;
}
}
/** A provisioner that serves {@code type} and does nothing, for routing through a real registry. */
private static CfnResourceProvisioner serving(String type) {
return new CfnResourceProvisioner() {
@@ -21,6 +21,7 @@ import java.util.List;
import java.util.Map;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -211,6 +212,16 @@ class LeafCfnProvisionerTest {
return repository;
}
@Test
void servesNothingWhileTheEcrServiceIsDisabled() {
assertFalse(provisioner.serviceDisabled());
when(ecr.isDisabled()).thenReturn(true);
assertTrue(provisioner.serviceDisabled());
assertEquals("floci.services.ecr.enabled", provisioner.serviceEnabledFlag());
}
@Test
void refIsTheRepositoryNameAndGetAttExposesArnAndUri() {
when(ecr.createRepository(eq("app"), any(), any(), any(), any(), any(), any(), eq(REGION)))
@@ -125,6 +125,7 @@ class EcrRegistryManagerTest {
when(ecr.registryMaxPort()).thenReturn(MAX_PORT);
when(ecr.dockerNetwork()).thenReturn(Optional.empty());
when(ecr.preferLocalImages()).thenReturn(true);
when(ecr.enabled()).thenReturn(true);
manager = new EcrRegistryManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, currentContainerNetworkResolver, portAllocator, config, regionResolver);
@@ -216,6 +217,37 @@ class EcrRegistryManagerTest {
assertFalse(manager.isStarted());
}
@Test
void tryEnsureStarted_ecrDisabled_reportsUnavailableWithoutCreatingTheContainer() {
when(ecr.enabled()).thenReturn(false);
assertFalse(manager.tryEnsureStarted());
assertFalse(manager.isStarted());
verify(lifecycleManager, never()).findByName(anyString());
verify(lifecycleManager, never()).createAndStart(any());
}
@Test
void ensureStarted_ecrDisabled_refusesWithoutCreatingTheContainer() {
when(ecr.enabled()).thenReturn(false);
assertThrows(IllegalStateException.class, () -> manager.ensureStarted());
verify(lifecycleManager, never()).createAndStart(any());
}
@Test
void rewriteImageUri_ecrDisabled_returnsAwsEcrUriUnchangedWithoutStartingRegistry() {
when(ecr.enabled()).thenReturn(false);
String rewritten = manager.rewriteImageUri(AWS_ECR_IMAGE);
assertEquals(AWS_ECR_IMAGE, rewritten);
verify(lifecycleManager, never()).findByName(anyString());
verify(lifecycleManager, never()).createAndStart(any());
}
@Test
void tryEnsureStarted_reportsSuccessOnceTheRegistryStarts() {
when(lifecycleManager.createAndStart(any()))
@@ -109,6 +109,7 @@ class EcrRegistryPortConflictDockerIntegrationTest {
// Empty host-persistent-path selects a named volume, which memory mode removes on shutdown.
when(config.storage().hostPersistentPath()).thenReturn("");
when(config.storage().mode()).thenReturn("memory");
when(config.services().ecr().enabled()).thenReturn(true);
when(config.services().ecr().registryContainerName()).thenReturn("ecr-registry");
when(config.services().ecr().registryImage()).thenReturn(TestImages.REGISTRY);
when(config.services().ecr().registryBasePort()).thenReturn(basePort);