feat(ecr): support pull time update exclusions (#6856)

* feat(ecr): support pull time update exclusions

* refactor(ecr): remove duplicate exclusion validation
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-10-29 16:20:51 -04:00
1 parent d2a5a82ca2
commit 8270cc7c41
8 files changed
+334

No files matched your search

+12
View File
@@ -8,6 +8,8 @@
| Action | Description |
| --- | --- |
| `RegisterPullTimeUpdateExclusion` / `DeregisterPullTimeUpdateExclusion` | Store or remove an IAM principal excluded from pull time updates (stored, not applied) |
| `ListPullTimeUpdateExclusions` | List the registry's excluded principal ARNs with pagination |
| `CreateRepository` | Create a new repository (lazy-starts the backing registry on first call) |
| `CreatePullThroughCacheRule` | Create and persist pull-through cache rule configuration |
| `DescribePullThroughCacheRules` | List or filter pull-through cache rules with pagination |
@@ -93,6 +95,16 @@ the optional `filter` fields.
- **Lambda and ECS integration.** Image-backed Lambda functions (`PackageType=Image`) and ECS task containers reference the same loopback `repositoryUri`. Floci rewrites real-AWS-shaped `<account>.dkr.ecr.<region>.amazonaws.com/...` URIs to the loopback registry at pull time, path style on `localhost` (`localhost:<flociPort>/<account>/<region>/<repo>`) in either URI style and with or without TLS, the one address every Docker daemon pulls from over plain HTTP, so CDK's `DockerImageFunction` (which generates AWS-shaped URIs in CloudFormation templates) works without any user-side rewriting.
- **Locally built images win.** An AWS-shaped URI that names an image already present on the Docker daemon is used as-is instead of being rewritten (`FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES`, default `true`). Build the image under the exact URI your function or task definition declares (`docker build -t <account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag> .`) and it runs without a push to the emulated registry, and without the registry container being started. The check uses the reference Floci would launch, so with `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` set the image must be present as `<base>/<account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag>`.
## Pull-time update exclusions
Exclusions are stored per account and Region, with up to 100 registered IAM role or
user ARNs per registry. Registration returns the principal ARN and creation timestamp;
a duplicate is `ExclusionAlreadyExistsException`, and removing an unknown ARN is
`ExclusionNotFoundException`. Listing accepts `maxResults` from 1 to 1000 (default 100)
and returns a scoped `nextToken` when more results remain. Registry settings and
exclusions survive storage reloads together. Floci records this metadata without
changing image pull-time tracking.
## Configuration
| Variable | Default | Description |
@@ -48,6 +48,7 @@ public class EcrJsonHandler {
/** The actions whose requests are checked against the vendored model constraints first. */
private static final Set<String> MODEL_CHECKED = Set.of(
"GetAccountSetting", "PutAccountSetting",
"RegisterPullTimeUpdateExclusion", "DeregisterPullTimeUpdateExclusion", "ListPullTimeUpdateExclusions",
"PutRegistryPolicy", "GetRegistryPolicy", "DeleteRegistryPolicy",
"PutReplicationConfiguration", "DescribeRegistry",
"PutRegistryScanningConfiguration", "GetRegistryScanningConfiguration",
@@ -106,6 +107,10 @@ public class EcrJsonHandler {
case "DescribeRegistry" -> handleDescribeRegistry(region);
case "PutRegistryScanningConfiguration" -> handlePutRegistryScanningConfiguration(request, region);
case "GetRegistryScanningConfiguration" -> handleGetRegistryScanningConfiguration(region);
case "RegisterPullTimeUpdateExclusion" -> handleRegisterPullTimeUpdateExclusion(request, region);
case "DeregisterPullTimeUpdateExclusion" -> Response.ok(objectMapper.createObjectNode().put("principalArn",
service.deregisterPullTimeUpdateExclusion(request.path("principalArn").asText(null), region))).build();
case "ListPullTimeUpdateExclusions" -> handleListPullTimeUpdateExclusions(request, region);
default -> Response.status(400)
.entity(new AwsErrorResponse("UnsupportedOperation",
"Operation " + action + " is not supported."))
@@ -718,6 +723,26 @@ public class EcrJsonHandler {
return Response.ok(response).build();
}
private Response handleRegisterPullTimeUpdateExclusion(JsonNode request, String region) {
RegistrySettings.PullTimeUpdateExclusion exclusion = service.registerPullTimeUpdateExclusion(
request.path("principalArn").asText(null), region);
ObjectNode response = objectMapper.createObjectNode();
response.put("principalArn", exclusion.principalArn());
response.put("createdAt", exclusion.createdAt().toEpochMilli() / 1000.0);
return Response.ok(response).build();
}
private Response handleListPullTimeUpdateExclusions(JsonNode request, String region) {
PaginatedResult<String> page = service.listPullTimeUpdateExclusions(parseMaxResults(request.path("maxResults")),
request.path("nextToken").asText(null), region);
ObjectNode response = objectMapper.createObjectNode();
response.set("pullTimeUpdateExclusions", objectMapper.valueToTree(page.items()));
if (page.nextToken() != null) {
response.put("nextToken", page.nextToken());
}
return Response.ok(response).build();
}
private static List<RegistrySettings.RepositoryFilter> parseRepositoryFilters(JsonNode node) {
List<RegistrySettings.RepositoryFilter> filters = new ArrayList<>();
for (JsonNode f : node) {
@@ -86,6 +86,7 @@ public class EcrService implements ResourceProvider {
private static final ObjectReader SINGLE_JSON_VALUE =
MAPPER.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
private static final int MAX_REPO_NAME_LENGTH = 256;
private static final int MAX_PULL_TIME_EXCLUSIONS = 100;
private static final int MAX_PULL_THROUGH_CACHE_PREFIX_LENGTH = 30;
private static final Map<String, String> ACCOUNT_SETTING_DEFAULTS = Map.of(
"BASIC_SCAN_TYPE_VERSION", "AWS_NATIVE", "REGISTRY_POLICY_SCOPE", "V2", "BLOB_MOUNTING", "DISABLED");
@@ -1438,6 +1439,51 @@ public class EcrService implements ResourceProvider {
});
}
public RegistrySettings.PullTimeUpdateExclusion registerPullTimeUpdateExclusion(String principalArn, String region) {
return updateRegistrySettings(region, settings -> {
List<RegistrySettings.PullTimeUpdateExclusion> exclusions = pullTimeExclusions(settings);
if (exclusions.stream().anyMatch(exclusion -> exclusion.principalArn().equals(principalArn))) {
throw new AwsException("ExclusionAlreadyExistsException", "The exclusion already exists.", 400);
}
if (exclusions.size() >= MAX_PULL_TIME_EXCLUSIONS) {
throw new AwsException("LimitExceededException", "A registry can have at most 100 exclusions.", 400);
}
RegistrySettings.PullTimeUpdateExclusion exclusion =
new RegistrySettings.PullTimeUpdateExclusion(principalArn, Instant.now());
List<RegistrySettings.PullTimeUpdateExclusion> updated = new ArrayList<>(exclusions);
updated.add(exclusion);
settings.setPullTimeUpdateExclusions(List.copyOf(updated));
return exclusion;
});
}
public String deregisterPullTimeUpdateExclusion(String principalArn, String region) {
return updateRegistrySettings(region, settings -> {
List<RegistrySettings.PullTimeUpdateExclusion> exclusions = pullTimeExclusions(settings);
List<RegistrySettings.PullTimeUpdateExclusion> remaining = exclusions.stream()
.filter(exclusion -> !exclusion.principalArn().equals(principalArn)).toList();
if (remaining.size() == exclusions.size()) {
throw new AwsException("ExclusionNotFoundException", "The exclusion was not found.", 400);
}
settings.setPullTimeUpdateExclusions(remaining);
return principalArn;
});
}
public PaginatedResult<String> listPullTimeUpdateExclusions(Integer maxResults, String nextToken, String region) {
synchronized (registryLock(region)) {
List<String> principals = pullTimeExclusions(registrySettings(region)).stream()
.map(RegistrySettings.PullTimeUpdateExclusion::principalArn).toList();
return Pagination.paginate(principals, Function.identity(), maxResults == null ? 100 : maxResults,
nextToken, "ecr-pull-time:" + registrySettingsKey(region),
token -> new AwsException("InvalidParameterException", "Invalid nextToken.", 400));
}
}
private static List<RegistrySettings.PullTimeUpdateExclusion> pullTimeExclusions(RegistrySettings settings) {
return settings.getPullTimeUpdateExclusions() == null ? List.of() : settings.getPullTimeUpdateExclusions();
}
/**
* Stores the replication rules; an empty list clears them. The rules are checked against the
* model before this is reached. Floci does not replicate images.
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ecr.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@@ -29,6 +30,11 @@ public class RegistrySettings {
@RegisterForReflection
public record ScanningRule(String scanFrequency, List<RepositoryFilter> repositoryFilters) {}
/** An excluded principal and the time its registration was created. */
@RegisterForReflection
public record PullTimeUpdateExclusion(String principalArn, Instant createdAt) {}
private List<PullTimeUpdateExclusion> pullTimeUpdateExclusions;
private String policyText;
private List<ReplicationRule> replicationRules;
private String scanType;
@@ -37,6 +43,9 @@ public class RegistrySettings {
public RegistrySettings() {}
public List<PullTimeUpdateExclusion> getPullTimeUpdateExclusions() { return pullTimeUpdateExclusions; }
public void setPullTimeUpdateExclusions(List<PullTimeUpdateExclusion> exclusions) { this.pullTimeUpdateExclusions = exclusions; }
public String getPolicyText() { return policyText; }
public void setPolicyText(String policyText) { this.policyText = policyText; }
@@ -6,6 +6,9 @@
"operations": {
"GetAccountSetting": "GetAccountSettingRequest",
"PutAccountSetting": "PutAccountSettingRequest",
"RegisterPullTimeUpdateExclusion": "RegisterPullTimeUpdateExclusionRequest",
"DeregisterPullTimeUpdateExclusion": "DeregisterPullTimeUpdateExclusionRequest",
"ListPullTimeUpdateExclusions": "ListPullTimeUpdateExclusionsRequest",
"PutRegistryPolicy": "PutRegistryPolicyRequest",
"GetRegistryPolicy": "GetRegistryPolicyRequest",
"DeleteRegistryPolicy": "DeleteRegistryPolicyRequest",
@@ -73,6 +76,15 @@
"prefix": "Prefix"
}
},
"DeregisterPullTimeUpdateExclusionRequest": {
"type": "structure",
"required": [
"principalArn"
],
"members": {
"principalArn": "PrincipalArn"
}
},
"DescribeRegistryRequest": {
"type": "structure",
"members": {}
@@ -169,6 +181,13 @@
"min": 0,
"max": 30720
},
"ListPullTimeUpdateExclusionsRequest": {
"type": "structure",
"members": {
"maxResults": "MaxResults",
"nextToken": "NextToken"
}
},
"MaxResults": {
"type": "integer",
"min": 1,
@@ -187,6 +206,11 @@
"type": "list",
"member": "Prefix"
},
"PrincipalArn": {
"type": "string",
"max": 200,
"pattern": "^arn:aws(-[a-z]+)*:iam::[0-9]{12}:(role|user)/[\\w+=,.@-]+(/[\\w+=,.@-]+)*$"
},
"PutAccountSettingRequest": {
"type": "structure",
"required": [
@@ -241,6 +265,15 @@
"max": 25,
"pattern": "[0-9a-z-]{2,25}"
},
"RegisterPullTimeUpdateExclusionRequest": {
"type": "structure",
"required": [
"principalArn"
],
"members": {
"principalArn": "PrincipalArn"
}
},
"RegistryId": {
"type": "string",
"pattern": "[0-9]{12}"
@@ -0,0 +1,128 @@
package io.github.hectorvent.floci.services.ecr;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecr.EcrClient;
import software.amazon.awssdk.services.ecr.model.ExclusionAlreadyExistsException;
import software.amazon.awssdk.services.ecr.model.ExclusionNotFoundException;
import software.amazon.awssdk.services.ecr.model.InvalidParameterException;
import software.amazon.awssdk.services.ecr.model.LimitExceededException;
import software.amazon.awssdk.services.ecr.model.ListPullTimeUpdateExclusionsResponse;
import software.amazon.awssdk.services.ecr.model.RegisterPullTimeUpdateExclusionResponse;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
class EcrPullTimeExclusionsIntegrationTest {
private static final AtomicLong ACCOUNTS = new AtomicLong(741683100000L);
private static final String REGION = "eu-west-2";
private static final String ROLE = "arn:aws:iam::123456789012:role/scanners/Reader";
private String account;
private EcrClient client;
@BeforeAll
static void configureAwsJson() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void openClient() {
account = String.valueOf(ACCOUNTS.incrementAndGet());
client = AwsTestClients.create(EcrClient.builder(), account, Region.of(REGION));
}
@AfterEach
void closeClient() {
client.close();
}
@Test
void lifecycleUsesModeledErrorsAndSdkTimestamp() {
Instant before = Instant.now().minusSeconds(1);
RegisterPullTimeUpdateExclusionResponse created = client.registerPullTimeUpdateExclusion(r -> r.principalArn(ROLE));
assertEquals(ROLE, created.principalArn());
assertNotNull(created.createdAt());
assertFalse(created.createdAt().isBefore(before));
assertFalse(created.createdAt().isAfter(Instant.now().plusSeconds(1)));
assertThrows(ExclusionAlreadyExistsException.class, () -> client.registerPullTimeUpdateExclusion(r -> r.principalArn(ROLE)));
assertEquals(List.of(ROLE), client.listPullTimeUpdateExclusions(r -> {}).pullTimeUpdateExclusions());
assertEquals(ROLE, client.deregisterPullTimeUpdateExclusion(r -> r.principalArn(ROLE)).principalArn());
assertThrows(ExclusionNotFoundException.class, () -> client.deregisterPullTimeUpdateExclusion(r -> r.principalArn(ROLE)));
assertTrue(client.listPullTimeUpdateExclusions(r -> {}).pullTimeUpdateExclusions().isEmpty());
}
@Test
void pagesResumeAfterCursorDeletionAndAreScoped() {
List<String> arns = List.of(ROLE, "arn:aws:iam::123456789012:user/team/Scanner", "arn:aws:iam::123456789012:role/A");
arns.forEach(arn -> client.registerPullTimeUpdateExclusion(r -> r.principalArn(arn)));
List<String> sorted = arns.stream().sorted().toList();
ListPullTimeUpdateExclusionsResponse first = client.listPullTimeUpdateExclusions(r -> r.maxResults(1));
assertEquals(sorted.subList(0, 1), first.pullTimeUpdateExclusions());
assertNotNull(first.nextToken());
client.deregisterPullTimeUpdateExclusion(r -> r.principalArn(sorted.getFirst()));
ListPullTimeUpdateExclusionsResponse last = client.listPullTimeUpdateExclusions(r -> r.maxResults(2).nextToken(first.nextToken()));
assertEquals(sorted.subList(1, 3), last.pullTimeUpdateExclusions());
assertNull(last.nextToken());
try (EcrClient other = AwsTestClients.create(EcrClient.builder(), "741683199999", Region.of(REGION));
EcrClient region = AwsTestClients.create(EcrClient.builder(), account, Region.US_EAST_1)) {
assertTrue(other.listPullTimeUpdateExclusions(r -> {}).pullTimeUpdateExclusions().isEmpty());
assertTrue(region.listPullTimeUpdateExclusions(r -> {}).pullTimeUpdateExclusions().isEmpty());
assertThrows(InvalidParameterException.class, () -> other.listPullTimeUpdateExclusions(r -> r.nextToken(first.nextToken())));
assertThrows(InvalidParameterException.class, () -> region.listPullTimeUpdateExclusions(r -> r.nextToken(first.nextToken())));
}
}
@Test
void registryAllowsOneHundredExclusionsAndFreedSlotsCanBeReused() {
List<String> arns = new ArrayList<>();
for (int i = 0; i < 100; i++) {
String arn = "arn:aws:iam::123456789012:role/Scanner" + i;
client.registerPullTimeUpdateExclusion(r -> r.principalArn(arn));
arns.add(arn);
}
assertEquals(100, client.listPullTimeUpdateExclusions(r -> {}).pullTimeUpdateExclusions().size());
ListPullTimeUpdateExclusionsResponse all = client.listPullTimeUpdateExclusions(r -> r.maxResults(1000));
assertEquals(arns.stream().sorted().toList(), all.pullTimeUpdateExclusions());
assertNull(all.nextToken());
assertThrows(ExclusionAlreadyExistsException.class, () -> client.registerPullTimeUpdateExclusion(r -> r.principalArn(arns.getFirst())));
assertThrows(LimitExceededException.class, () -> client.registerPullTimeUpdateExclusion(r -> r.principalArn(ROLE)));
client.deregisterPullTimeUpdateExclusion(r -> r.principalArn(arns.getFirst()));
assertEquals(ROLE, client.registerPullTimeUpdateExclusion(r -> r.principalArn(ROLE)).principalArn());
}
@ParameterizedTest
@NullSource
@ValueSource(strings = {"", "arn:aws:iam::12:role/X", "arn:aws:iam::123456789012:group/Readers",
"arn:aws:sts::123456789012:assumed-role/X/Y", "arn:aws:iam:us-east-1:123456789012:role/X",
"arn:aws:iam::123456789012:role/trailing/"})
void invalidPrincipalsAreRejected(String arn) {
assertThrows(InvalidParameterException.class, () -> client.registerPullTimeUpdateExclusion(r -> r.principalArn(arn)));
assertThrows(InvalidParameterException.class, () -> client.deregisterPullTimeUpdateExclusion(r -> r.principalArn(arn)));
}
@ParameterizedTest
@ValueSource(strings = {"{\"maxResults\":0}", "{\"maxResults\":-1}", "{\"maxResults\":1001}",
"{\"maxResults\":2147483648}", "{\"maxResults\":1.5}", "{\"maxResults\":\"1\"}",
"{\"nextToken\":3}", "{\"nextToken\":{}}", "{\"nextToken\":\"%%%\"}"})
void malformedListInputsReturnClientErrors(String body) {
given().contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", "AmazonEC2ContainerRegistry_V20150921.ListPullTimeUpdateExclusions")
.body(body).post("/").then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
}
}
@@ -0,0 +1,80 @@
package io.github.hectorvent.floci.services.ecr;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
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.services.ecr.model.RegistrySettings;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
class EcrPullTimeExclusionsPersistenceTest {
private static final String REGION = "eu-west-2";
private static final String ACCOUNT = "741683100099";
private static final String KEY = REGION + "::" + ACCOUNT;
private static final String ROLE = "arn:aws:iam::123456789012:role/Scanner";
@Test
void oldRegistryRecordsAndSerializedExclusionsKeepOtherSettings() throws Exception {
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
InMemoryStorage<String, RegistrySettings> store = new InMemoryStorage<>();
store.put(KEY, mapper.readValue("{\"scanType\":\"ENHANCED\",\"policyText\":\"{}\"}", RegistrySettings.class));
EcrService service = service(store);
assertTrue(service.listPullTimeUpdateExclusions(null, null, REGION).items().isEmpty());
Instant created = service.registerPullTimeUpdateExclusion(ROLE, REGION).createdAt();
String saved = mapper.writeValueAsString(store.get(KEY).orElseThrow());
InMemoryStorage<String, RegistrySettings> restored = new InMemoryStorage<>();
restored.put(KEY, mapper.readValue(saved, RegistrySettings.class));
EcrService reloaded = service(restored);
assertEquals(List.of(ROLE), reloaded.listPullTimeUpdateExclusions(null, null, REGION).items());
assertEquals(created, restored.get(KEY).orElseThrow().getPullTimeUpdateExclusions().getFirst().createdAt());
assertEquals("ENHANCED", reloaded.registryScanningConfiguration(REGION).getScanType());
assertEquals("{}", reloaded.getRegistryPolicy(REGION));
reloaded.putRegistryScanningConfiguration("BASIC", List.of(), REGION);
assertEquals(List.of(ROLE), reloaded.listPullTimeUpdateExclusions(null, null, REGION).items());
reloaded.deregisterPullTimeUpdateExclusion(ROLE, REGION);
assertEquals("{}", reloaded.getRegistryPolicy(REGION));
}
@Test
void concurrentRegistrationsOfOnePrincipalHaveOneWinner() throws Exception {
EcrService service = service(new InMemoryStorage<>());
CountDownLatch start = new CountDownLatch(1);
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<String> first = executor.submit(() -> registerAfter(start, service));
Future<String> second = executor.submit(() -> registerAfter(start, service));
start.countDown();
assertEquals(List.of("ExclusionAlreadyExistsException", "registered"),
List.of(first.get(), second.get()).stream().sorted().toList());
}
assertEquals(List.of(ROLE), service.listPullTimeUpdateExclusions(null, null, REGION).items());
}
private String registerAfter(CountDownLatch start, EcrService service) throws InterruptedException {
start.await();
try {
service.registerPullTimeUpdateExclusion(ROLE, REGION);
return "registered";
} catch (AwsException duplicate) {
return duplicate.getErrorCode();
}
}
private EcrService service(InMemoryStorage<String, RegistrySettings> settings) {
return new EcrService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
settings, new InMemoryStorage<>(), mock(EcrRegistryManager.class), mock(EmulatorConfig.class),
new RegionResolver(REGION, ACCOUNT));
}
}
+1
View File
@@ -23,6 +23,7 @@ OUTPUT = REPO_ROOT / "src/main/resources/aws/ecr-request-shapes.json"
MODEL = Path("ecr/2015-09-21")
OPERATIONS = (
"GetAccountSetting", "PutAccountSetting",
"RegisterPullTimeUpdateExclusion", "DeregisterPullTimeUpdateExclusion", "ListPullTimeUpdateExclusions",
"PutRegistryPolicy", "GetRegistryPolicy", "DeleteRegistryPolicy",
"PutReplicationConfiguration", "DescribeRegistry",
"PutRegistryScanningConfiguration", "GetRegistryScanningConfiguration",