Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ec2): support managed prefix lists (#2105)
Michal Schreiberac4b865a34bd
diff --git a/compatibility-tests/sdk-test-awscli/test/ec2.bats b/compatibility-tests/sdk-test-awscli/test/ec2.batsnew file mode 100644index 0000000000..c535edae80--- /dev/null+++ b/compatibility-tests/sdk-test-awscli/test/ec2.bats@@ -0,0 +1,136 @@+#!/usr/bin/env bats+# EC2 tests++setup() {+ load 'test_helper/common-setup'+ PREFIX_LIST_NAME="bats-prefix-list-$(unique_name)"+ PREFIX_LIST_ID=""+}++teardown() {+ if [ -n "$PREFIX_LIST_ID" ]; then+ aws_cmd ec2 delete-managed-prefix-list --prefix-list-id "$PREFIX_LIST_ID" >/dev/null 2>&1 || true+ fi+}++# Creates a prefix list holding 10.0.0.0/8 and sets PREFIX_LIST_ID.+create_prefix_list() {+ local out+ out=$(aws_cmd ec2 create-managed-prefix-list \+ --prefix-list-name "$PREFIX_LIST_NAME" \+ --address-family IPv4 \+ --max-entries 5 \+ --entries 'Cidr=10.0.0.0/8,Description=corporate')+ PREFIX_LIST_ID=$(json_get "$out" '.PrefixList.PrefixListId')+}++@test "EC2: create managed prefix list" {+ run aws_cmd ec2 create-managed-prefix-list \+ --prefix-list-name "$PREFIX_LIST_NAME" \+ --address-family IPv4 \+ --max-entries 5 \+ --entries 'Cidr=10.0.0.0/8,Description=corporate'+ assert_success+ PREFIX_LIST_ID=$(json_get "$output" '.PrefixList.PrefixListId')+ [ -n "$PREFIX_LIST_ID" ]++ state=$(json_get "$output" '.PrefixList.State')+ [ "$state" = "create-complete" ]+ version=$(json_get "$output" '.PrefixList.Version')+ [ "$version" = "1" ]+}++@test "EC2: describe managed prefix list by id" {+ create_prefix_list++ run aws_cmd ec2 describe-managed-prefix-lists --prefix-list-ids "$PREFIX_LIST_ID"+ assert_success+ name=$(json_get "$output" '.PrefixLists[0].PrefixListName')+ [ "$name" = "$PREFIX_LIST_NAME" ]+}++@test "EC2: describe managed prefix lists exposes the AWS-managed S3 list" {+ run aws_cmd ec2 describe-managed-prefix-lists \+ --filters "Name=prefix-list-name,Values=com.amazonaws.${AWS_DEFAULT_REGION}.s3"+ assert_success+ id=$(json_get "$output" '.PrefixLists[0].PrefixListId')+ [ "$id" = "pl-63a5400a" ]+ owner=$(json_get "$output" '.PrefixLists[0].OwnerId')+ [ "$owner" = "AWS" ]+}++@test "EC2: get managed prefix list entries" {+ create_prefix_list++ run aws_cmd ec2 get-managed-prefix-list-entries --prefix-list-id "$PREFIX_LIST_ID"+ assert_success+ cidr=$(json_get "$output" '.Entries[0].Cidr')+ [ "$cidr" = "10.0.0.0/8" ]+ desc=$(json_get "$output" '.Entries[0].Description')+ [ "$desc" = "corporate" ]+}++@test "EC2: modify managed prefix list bumps version and keeps history" {+ create_prefix_list++ run aws_cmd ec2 modify-managed-prefix-list \+ --prefix-list-id "$PREFIX_LIST_ID" \+ --add-entries 'Cidr=192.168.0.0/16,Description=lab'+ assert_success+ version=$(json_get "$output" '.PrefixList.Version')+ [ "$version" = "2" ]++ run aws_cmd ec2 get-managed-prefix-list-entries --prefix-list-id "$PREFIX_LIST_ID"+ assert_success+ count=$(json_get "$output" '.Entries | length')+ [ "$count" = "2" ]++ run aws_cmd ec2 get-managed-prefix-list-entries --prefix-list-id "$PREFIX_LIST_ID" --target-version 1+ assert_success+ count=$(json_get "$output" '.Entries | length')+ [ "$count" = "1" ]+}++@test "EC2: modify with a stale current version is rejected" {+ create_prefix_list+ aws_cmd ec2 modify-managed-prefix-list --prefix-list-id "$PREFIX_LIST_ID" \+ --add-entries 'Cidr=192.168.0.0/16' >/dev/null++ run aws_cmd ec2 modify-managed-prefix-list \+ --prefix-list-id "$PREFIX_LIST_ID" \+ --current-version 1 \+ --add-entries 'Cidr=172.16.0.0/12'+ assert_failure+ assert_output --partial "PrefixListVersionMismatch"+}++@test "EC2: AWS-managed prefix list cannot be modified" {+ run aws_cmd ec2 modify-managed-prefix-list \+ --prefix-list-id pl-63a5400a \+ --add-entries 'Cidr=10.1.0.0/16'+ assert_failure+ assert_output --partial "UnsupportedOperation"+}++@test "EC2: delete managed prefix list" {+ create_prefix_list+ local created_id="$PREFIX_LIST_ID"++ run aws_cmd ec2 delete-managed-prefix-list --prefix-list-id "$created_id"+ assert_success+ state=$(json_get "$output" '.PrefixList.State')+ [ "$state" = "delete-complete" ]+ PREFIX_LIST_ID=""++ run aws_cmd ec2 describe-managed-prefix-lists --prefix-list-ids "$created_id"+ assert_failure+ assert_output --partial "InvalidPrefixListID.NotFound"+}++@test "EC2: legacy describe-prefix-lists still serves the gateway lists" {+ run aws_cmd ec2 describe-prefix-lists \+ --filters "Name=prefix-list-name,Values=com.amazonaws.${AWS_DEFAULT_REGION}.s3"+ assert_success+ id=$(json_get "$output" '.PrefixLists[0].PrefixListId')+ [ "$id" = "pl-63a5400a" ]+}diff --git a/docs/services/ec2.md b/docs/services/ec2.mdindex c1f3c37025..17ae6efa7e 100644--- a/docs/services/ec2.md+++ b/docs/services/ec2.md@@ -274,6 +274,27 @@ Floci seeds the following resources on first use in each region so Terraform, th| Action | Description ||--------|-------------|| DescribePrefixLists | Returns prefix lists known to the local EC2 service. |+| CreateManagedPrefixList | Creates a customer-managed prefix list with its initial entries. |+| DescribeManagedPrefixLists | Lists customer-managed and AWS-managed prefix lists. |+| GetManagedPrefixListEntries | Returns the entries of a prefix list, optionally at an earlier version. |+| ModifyManagedPrefixList | Adds or removes entries, renames the list, or raises its entry limit. |+| DeleteManagedPrefixList | Deletes a customer-managed prefix list. |++Two AWS-managed prefix lists exist in every region without being created —+`com.amazonaws.<region>.s3` (`pl-63a5400a`) and `com.amazonaws.<region>.dynamodb`+(`pl-02cd2c6b`) — matching the gateway endpoint services on AWS. They are owned by `AWS`,+read-only, and served by both `DescribePrefixLists` and `DescribeManagedPrefixLists`;+modifying or deleting one returns `UnsupportedOperation`.++Entries are versioned. A prefix list starts at version 1, and each `ModifyManagedPrefixList`+that adds or removes entries stores a new version and bumps the counter, so+`GetManagedPrefixListEntries` can serve an earlier `TargetVersion`. Renaming the list or+changing `MaxEntries` does not create a version. Passing `CurrentVersion` makes the+modification conditional: a stale value returns `PrefixListVersionMismatch`. Removals are applied before+additions, so one call can replace an entry's description by removing and re-adding the CIDR.++Creation is synchronous: a new list is returned as `create-complete` rather than passing+through `create-in-progress`, since nothing about it is slow locally.### NAT Gatewaysdiff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.javaindex 4dfec9a48a..ca9f7bd6df 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java@@ -79,6 +79,11 @@ public class Ec2QueryHandler {case "DescribeFlowLogs" -> handleDescribeFlowLogs(params, region);case "DeleteFlowLogs" -> handleDeleteFlowLogs(params, region);case "DescribePrefixLists" -> handleDescribePrefixLists(params, region);+ case "CreateManagedPrefixList" -> handleCreateManagedPrefixList(params, region);+ case "DescribeManagedPrefixLists" -> handleDescribeManagedPrefixLists(params, region);+ case "GetManagedPrefixListEntries" -> handleGetManagedPrefixListEntries(params, region);+ case "ModifyManagedPrefixList" -> handleModifyManagedPrefixList(params, region);+ case "DeleteManagedPrefixList" -> handleDeleteManagedPrefixList(params, region);case "CreateDefaultVpc" -> handleCreateDefaultVpc(params, region);case "AssociateVpcCidrBlock" -> handleAssociateVpcCidrBlock(params, region);case "DisassociateVpcCidrBlock" -> handleDisassociateVpcCidrBlock(params, region);@@ -982,6 +987,142 @@ public class Ec2QueryHandler {return xmlResponse(xml.build());}+ private Response handleCreateManagedPrefixList(MultivaluedMap<String, String> p, String region) {+ ManagedPrefixList list = service.createManagedPrefixList(+ region,+ p.getFirst("PrefixListName"),+ p.getFirst("AddressFamily"),+ intOrNull(p, "MaxEntries"),+ parsePrefixListEntries(p, "Entry"),+ parseTagsForResource(p, "prefix-list"));+ XmlBuilder xml = new XmlBuilder()+ .start("CreateManagedPrefixListResponse", AwsNamespaces.EC2)+ .elem("requestId", UUID.randomUUID().toString())+ .start("prefixList").raw(managedPrefixListXml(list)).end("prefixList")+ .end("CreateManagedPrefixListResponse");+ return xmlResponse(xml.build());+ }++ private Response handleDescribeManagedPrefixLists(MultivaluedMap<String, String> p, String region) {+ List<String> ids = getList(p, "PrefixListId");+ Map<String, List<String>> filters = getFilters(p);+ List<ManagedPrefixList> lists = service.describeManagedPrefixLists(region, ids, filters);+ XmlBuilder xml = new XmlBuilder()+ .start("DescribeManagedPrefixListsResponse", AwsNamespaces.EC2)+ .elem("requestId", UUID.randomUUID().toString())+ .start("prefixListSet");+ for (ManagedPrefixList list : lists) {+ xml.start("item").raw(managedPrefixListXml(list)).end("item");+ }+ xml.end("prefixListSet").end("DescribeManagedPrefixListsResponse");+ return xmlResponse(xml.build());+ }++ private Response handleGetManagedPrefixListEntries(MultivaluedMap<String, String> p, String region) {+ List<PrefixListEntry> entries = service.getManagedPrefixListEntries(+ region, p.getFirst("PrefixListId"), longOrNull(p, "TargetVersion"));+ XmlBuilder xml = new XmlBuilder()+ .start("GetManagedPrefixListEntriesResponse", AwsNamespaces.EC2)+ .elem("requestId", UUID.randomUUID().toString())+ .start("entrySet");+ for (PrefixListEntry entry : entries) {+ xml.start("item").elem("cidr", entry.getCidr());+ if (entry.getDescription() != null) {+ xml.elem("description", entry.getDescription());+ }+ xml.end("item");+ }+ xml.end("entrySet").end("GetManagedPrefixListEntriesResponse");+ return xmlResponse(xml.build());+ }++ private Response handleModifyManagedPrefixList(MultivaluedMap<String, String> p, String region) {+ List<PrefixListEntry> removeEntries = parsePrefixListEntries(p, "RemoveEntry");+ ManagedPrefixList list = service.modifyManagedPrefixList(+ region,+ p.getFirst("PrefixListId"),+ longOrNull(p, "CurrentVersion"),+ p.getFirst("PrefixListName"),+ intOrNull(p, "MaxEntries"),+ parsePrefixListEntries(p, "AddEntry"),+ removeEntries.stream().map(PrefixListEntry::getCidr).toList());+ XmlBuilder xml = new XmlBuilder()+ .start("ModifyManagedPrefixListResponse", AwsNamespaces.EC2)+ .elem("requestId", UUID.randomUUID().toString())+ .start("prefixList").raw(managedPrefixListXml(list)).end("prefixList")+ .end("ModifyManagedPrefixListResponse");+ return xmlResponse(xml.build());+ }++ private Response handleDeleteManagedPrefixList(MultivaluedMap<String, String> p, String region) {+ ManagedPrefixList list = service.deleteManagedPrefixList(region, p.getFirst("PrefixListId"));+ XmlBuilder xml = new XmlBuilder()+ .start("DeleteManagedPrefixListResponse", AwsNamespaces.EC2)+ .elem("requestId", UUID.randomUUID().toString())+ .start("prefixList").raw(managedPrefixListXml(list)).end("prefixList")+ .end("DeleteManagedPrefixListResponse");+ return xmlResponse(xml.build());+ }++ private String managedPrefixListXml(ManagedPrefixList list) {+ XmlBuilder xml = new XmlBuilder()+ .elem("prefixListId", list.getPrefixListId())+ .elem("addressFamily", list.getAddressFamily())+ .elem("state", list.getState());+ if (list.getStateMessage() != null) {+ xml.elem("stateMessage", list.getStateMessage());+ }+ xml.elem("prefixListArn", list.getPrefixListArn())+ .elem("prefixListName", list.getPrefixListName())+ .elem("maxEntries", list.getMaxEntries() == null ? 0 : list.getMaxEntries())+ .elem("version", list.getVersion())+ .elem("ownerId", list.getOwnerId());+ xml.raw(tagSetXml(list.getTags()));+ return xml.build();+ }++ // Entry lists arrive as Entry.N.Cidr / AddEntry.N.Cidr / RemoveEntry.N.Cidr. RemoveEntry+ // carries only a Cidr on the wire, which parses here as an entry with a null description.+ private List<PrefixListEntry> parsePrefixListEntries(MultivaluedMap<String, String> p, String prefix) {+ List<PrefixListEntry> entries = new ArrayList<>();+ for (int i = 1; ; i++) {+ String cidr = p.getFirst(prefix + "." + i + ".Cidr");+ if (cidr == null) break;+ entries.add(new PrefixListEntry(cidr, p.getFirst(prefix + "." + i + ".Description")));+ }+ return entries;+ }++ // Malformed numerics must surface as a client error, not escape the handler as an+ // unchecked NumberFormatException and turn into a 500. Only an absent parameter is null: a+ // present but blank value is malformed input, and treating it as absent would quietly drop+ // the conditional-version check on ModifyManagedPrefixList.+ private Integer intOrNull(MultivaluedMap<String, String> p, String name) {+ String value = p.getFirst(name);+ if (value == null) {+ return null;+ }+ try {+ return Integer.valueOf(value);+ } catch (NumberFormatException e) {+ throw new AwsException("InvalidParameterValue",+ "Invalid value '" + value + "' for " + name + ".", 400);+ }+ }++ private Long longOrNull(MultivaluedMap<String, String> p, String name) {+ String value = p.getFirst(name);+ if (value == null) {+ return null;+ }+ try {+ return Long.valueOf(value);+ } catch (NumberFormatException e) {+ throw new AwsException("InvalidParameterValue",+ "Invalid value '" + value + "' for " + name + ".", 400);+ }+ }+private Response handleDeleteVpcEndpoints(MultivaluedMap<String, String> p, String region) {List<String> endpointIds = getList(p, "VpcEndpointId");service.deleteVpcEndpoints(region, endpointIds);diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.javaindex 71fec0f924..22c7481898 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java@@ -51,11 +51,13 @@ import io.github.hectorvent.floci.services.ec2.model.IpRange;import io.github.hectorvent.floci.services.ec2.model.KeyPair;import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;+import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;import io.github.hectorvent.floci.services.ec2.model.NatGateway;import io.github.hectorvent.floci.services.ec2.model.NetworkAcl;import io.github.hectorvent.floci.services.ec2.model.NetworkAclAssociation;import io.github.hectorvent.floci.services.ec2.model.NetworkAclEntry;import io.github.hectorvent.floci.services.ec2.model.PrefixList;+import io.github.hectorvent.floci.services.ec2.model.PrefixListEntry;import io.github.hectorvent.floci.services.ec2.model.Placement;import io.github.hectorvent.floci.services.ec2.model.Reservation;import io.github.hectorvent.floci.services.ec2.model.Route;@@ -112,6 +114,7 @@ public class Ec2Service implements ContainerTeardown {private final StorageBackend<String, NatGateway> natGateways;private final StorageBackend<String, SpotInstanceRequest> spotInstanceRequests;private final StorageBackend<String, NetworkAcl> networkAcls;+ private final StorageBackend<String, ManagedPrefixList> managedPrefixLists;// resourceId → List<Tag>private final StorageBackend<String, List<Tag>> tags;private final Set<String> seededRegions = ConcurrentHashMap.newKeySet();@@ -141,6 +144,7 @@ public class Ec2Service implements ContainerTeardown {storageFactory.create("ec2", "ec2-nat-gateways.json", new TypeReference<Map<String, NatGateway>>() {}),storageFactory.create("ec2", "ec2-spot-instance-requests.json", new TypeReference<Map<String, SpotInstanceRequest>>() {}),storageFactory.create("ec2", "ec2-network-acls.json", new TypeReference<Map<String, NetworkAcl>>() {}),+ storageFactory.create("ec2", "ec2-managed-prefix-lists.json", new TypeReference<Map<String, ManagedPrefixList>>() {}),storageFactory.create("ec2", "ec2-tags.json", new TypeReference<Map<String, List<Tag>>>() {}));}@@ -166,6 +170,7 @@ public class Ec2Service implements ContainerTeardown {StorageBackend<String, NatGateway> natGateways,StorageBackend<String, SpotInstanceRequest> spotInstanceRequests,StorageBackend<String, NetworkAcl> networkAcls,+ StorageBackend<String, ManagedPrefixList> managedPrefixLists,StorageBackend<String, List<Tag>> tags) {this.accountId = config.defaultAccountId();this.config = config;@@ -191,6 +196,7 @@ public class Ec2Service implements ContainerTeardown {this.natGateways = natGateways;this.spotInstanceRequests = spotInstanceRequests;this.networkAcls = networkAcls;+ this.managedPrefixLists = managedPrefixLists;this.tags = tags;}@@ -534,22 +540,229 @@ public class Ec2Service implements ContainerTeardown {// AWS-managed prefix lists for the gateway-endpoint services (S3, DynamoDB). These are// not user-created, so they're returned as static managed data per region. Querying any// other service name (e.g. an interface endpoint) correctly yields no match.+ //+ // The legacy DescribePrefixLists surface projects the same objects that+ // DescribeManagedPrefixLists serves, so the two APIs cannot report different CIDRs for the+ // same list.public List<PrefixList> describePrefixLists(String region, List<String> ids, Map<String, List<String>> filters) {- List<PrefixList> managed = new ArrayList<>();- managed.add(new PrefixList("pl-63a5400a", "com.amazonaws." + region + ".s3",- new ArrayList<>(List.of("52.216.0.0/15", "54.231.0.0/16"))));- managed.add(new PrefixList("pl-02cd2c6b", "com.amazonaws." + region + ".dynamodb",- new ArrayList<>(List.of("3.218.182.0/24", "52.94.0.0/22"))));-List<String> names = filters.getOrDefault("prefix-list-name", List.of());List<String> filterIds = filters.getOrDefault("prefix-list-id", List.of());- return managed.stream()+ return awsManagedPrefixLists(region).stream().filter(pl -> ids.isEmpty() || ids.contains(pl.getPrefixListId())).filter(pl -> filterIds.isEmpty() || filterIds.contains(pl.getPrefixListId())).filter(pl -> names.isEmpty() || names.contains(pl.getPrefixListName()))+ .map(pl -> new PrefixList(pl.getPrefixListId(), pl.getPrefixListName(),+ pl.currentEntries().stream()+ .map(PrefixListEntry::getCidr)+ .collect(Collectors.toCollection(ArrayList::new)))).collect(Collectors.toList());}+ // =========================================================================+ // Managed prefix lists+ // =========================================================================++ private List<ManagedPrefixList> awsManagedPrefixLists(String region) {+ return List.of(+ awsManagedPrefixList(region, "pl-63a5400a", "com.amazonaws." + region + ".s3",+ List.of("52.216.0.0/15", "54.231.0.0/16")),+ awsManagedPrefixList(region, "pl-02cd2c6b", "com.amazonaws." + region + ".dynamodb",+ List.of("3.218.182.0/24", "52.94.0.0/22")));+ }++ private ManagedPrefixList awsManagedPrefixList(String region, String id, String name, List<String> cidrs) {+ ManagedPrefixList list = new ManagedPrefixList();+ list.setPrefixListId(id);+ list.setPrefixListName(name);+ // AWS-managed lists are owned by AWS itself, not by the calling account.+ list.setOwnerId("AWS");+ list.setPrefixListArn(AwsArnUtils.Arn.of("ec2", region, "aws", "prefix-list/" + id).toString());+ list.setAddressFamily("IPv4");+ list.setState("create-complete");+ list.setMaxEntries(cidrs.size());+ list.setVersion(1);+ list.setRegion(region);+ list.setAwsManaged(true);+ list.getEntriesByVersion().put("1", cidrs.stream()+ .map(cidr -> new PrefixListEntry(cidr, null))+ .collect(Collectors.toList()));+ return list;+ }++ public ManagedPrefixList createManagedPrefixList(String region, String prefixListName, String addressFamily,+ Integer maxEntries, List<PrefixListEntry> entries,+ List<Tag> prefixListTags) {+ if (prefixListName == null || prefixListName.isBlank()) {+ throw new AwsException("MissingParameter", "The request must contain the parameter PrefixListName.", 400);+ }+ if (!"IPv4".equals(addressFamily) && !"IPv6".equals(addressFamily)) {+ throw new AwsException("InvalidParameterValue",+ "Invalid value '" + addressFamily + "' for addressFamily. Valid values are IPv4 and IPv6.", 400);+ }+ if (maxEntries == null || maxEntries < 1) {+ throw new AwsException("InvalidParameterValue",+ "Invalid value for maxEntries. It must be greater than 0.", 400);+ }+ List<PrefixListEntry> initial = entries == null ? List.of() : entries;+ if (initial.size() > maxEntries) {+ throw new AwsException("InvalidParameterValue",+ "The number of entries exceeds the maximum of " + maxEntries + ".", 400);+ }+ initial.forEach(entry -> validatePrefixListEntry(entry, addressFamily));++ ManagedPrefixList list = new ManagedPrefixList();+ String prefixListId = "pl-" + randomHex(17);+ list.setPrefixListId(prefixListId);+ list.setPrefixListName(prefixListName);+ list.setPrefixListArn(AwsArnUtils.Arn.of("ec2", region, accountId, "prefix-list/" + prefixListId).toString());+ list.setAddressFamily(addressFamily);+ list.setMaxEntries(maxEntries);+ list.setOwnerId(accountId);+ list.setRegion(region);+ // AWS creates asynchronously (create-in-progress then create-complete). Nothing here is+ // slow, so the list is complete by the time the caller sees it.+ list.setState("create-complete");+ list.setVersion(1);+ list.getEntriesByVersion().put("1", new ArrayList<>(initial));+ if (prefixListTags != null && !prefixListTags.isEmpty()) {+ list.setTags(new ArrayList<>(prefixListTags));+ tags.put(prefixListId, new ArrayList<>(prefixListTags));+ }+ managedPrefixLists.put(key(region, prefixListId), list);+ return list;+ }++ public List<ManagedPrefixList> describeManagedPrefixLists(String region, List<String> prefixListIds,+ Map<String, List<String>> filters) {+ List<ManagedPrefixList> all = new ArrayList<>(awsManagedPrefixLists(region));+ managedPrefixLists.scan(k -> true).stream()+ .filter(list -> region.equals(list.getRegion()))+ .forEach(all::add);++ if (!prefixListIds.isEmpty()) {+ for (String prefixListId : prefixListIds) {+ if (all.stream().noneMatch(list -> list.getPrefixListId().equals(prefixListId))) {+ throw new AwsException("InvalidPrefixListID.NotFound",+ "The prefix list ID '" + prefixListId + "' does not exist.", 400);+ }+ }+ }+ return all.stream()+ .filter(list -> prefixListIds.isEmpty() || prefixListIds.contains(list.getPrefixListId()))+ .filter(list -> matchesFilters(list, filters, region))+ .collect(Collectors.toList());+ }++ public List<PrefixListEntry> getManagedPrefixListEntries(String region, String prefixListId, Long targetVersion) {+ ManagedPrefixList list = getRequiredManagedPrefixList(region, prefixListId);+ long version = targetVersion != null ? targetVersion : list.getVersion();+ List<PrefixListEntry> entries = list.getEntriesByVersion().get(String.valueOf(version));+ if (entries == null) {+ throw new AwsException("InvalidParameterValue",+ "Version " + version + " does not exist for prefix list " + prefixListId + ".", 400);+ }+ return entries;+ }++ /**+ * Applies removals before additions, matching AWS, so a single call can replace an entry's+ * description by removing and re-adding the same CIDR. Only an entry change produces a new+ * version — renaming the list leaves the version untouched.+ */+ public ManagedPrefixList modifyManagedPrefixList(String region, String prefixListId, Long currentVersion,+ String prefixListName, Integer maxEntries,+ List<PrefixListEntry> addEntries, List<String> removeCidrs) {+ synchronized (lockFor(key(region, prefixListId))) {+ ManagedPrefixList list = getRequiredManagedPrefixList(region, prefixListId);+ requireCustomerManaged(list, "modified");+ if (currentVersion != null && currentVersion != list.getVersion()) {+ throw new AwsException("PrefixListVersionMismatch",+ "The prefix list has the incorrect version number.", 400);+ }++ List<PrefixListEntry> updated = new ArrayList<>(list.currentEntries());+ if (removeCidrs != null && !removeCidrs.isEmpty()) {+ updated.removeIf(entry -> removeCidrs.contains(entry.getCidr()));+ }+ if (addEntries != null) {+ for (PrefixListEntry entry : addEntries) {+ validatePrefixListEntry(entry, list.getAddressFamily());+ updated.removeIf(existing -> existing.getCidr().equals(entry.getCidr()));+ updated.add(entry);+ }+ }++ int effectiveMax = maxEntries != null ? maxEntries : list.getMaxEntries();+ if (effectiveMax < 1) {+ throw new AwsException("InvalidParameterValue",+ "Invalid value for maxEntries. It must be greater than 0.", 400);+ }+ if (updated.size() > effectiveMax) {+ throw new AwsException("InvalidParameterValue",+ "The number of entries exceeds the maximum of " + effectiveMax + ".", 400);+ }+ if (maxEntries != null) {+ list.setMaxEntries(maxEntries);+ }+ if (prefixListName != null && !prefixListName.isBlank()) {+ list.setPrefixListName(prefixListName);+ }++ boolean entriesChanged = (addEntries != null && !addEntries.isEmpty())+ || (removeCidrs != null && !removeCidrs.isEmpty());+ if (entriesChanged) {+ long nextVersion = list.getVersion() + 1;+ list.getEntriesByVersion().put(String.valueOf(nextVersion), updated);+ list.setVersion(nextVersion);+ }+ list.setState("modify-complete");+ managedPrefixLists.put(key(region, prefixListId), list);+ return list;+ }+ }++ public ManagedPrefixList deleteManagedPrefixList(String region, String prefixListId) {+ synchronized (lockFor(key(region, prefixListId))) {+ ManagedPrefixList list = getRequiredManagedPrefixList(region, prefixListId);+ requireCustomerManaged(list, "deleted");+ managedPrefixLists.delete(key(region, prefixListId));+ tags.delete(prefixListId);+ // AWS reports delete-complete on the returned object even though it is now gone.+ list.setState("delete-complete");+ return list;+ }+ }++ private ManagedPrefixList getRequiredManagedPrefixList(String region, String prefixListId) {+ if (prefixListId == null || prefixListId.isBlank()) {+ throw new AwsException("MissingParameter",+ "The request must contain the parameter PrefixListId.", 400);+ }+ return describeManagedPrefixLists(region, List.of(prefixListId), Map.of()).stream()+ .findFirst()+ .orElseThrow(() -> new AwsException("InvalidPrefixListID.NotFound",+ "The prefix list ID '" + prefixListId + "' does not exist.", 400));+ }++ private void requireCustomerManaged(ManagedPrefixList list, String verb) {+ if (list.isAwsManaged()) {+ throw new AwsException("UnsupportedOperation",+ "The prefix list " + list.getPrefixListId()+ + " is an AWS-managed prefix list and cannot be " + verb + ".", 400);+ }+ }++ private void validatePrefixListEntry(PrefixListEntry entry, String addressFamily) {+ if (entry.getCidr() == null || entry.getCidr().isBlank()) {+ throw new AwsException("MissingParameter", "Every prefix list entry must specify a Cidr.", 400);+ }+ boolean ipv6 = entry.getCidr().contains(":");+ if (ipv6 != "IPv6".equals(addressFamily)) {+ throw new AwsException("InvalidParameterValue",+ "The CIDR '" + entry.getCidr() + "' does not match the address family " + addressFamily + ".", 400);+ }+ }+private String key(String region, String id) {return region + "::" + id;}@@ -2218,7 +2431,12 @@ public class Ec2Service implements ContainerTeardown {NetworkAcl networkAcl = networkAcls.get(storeKey).orElse(null);if (networkAcl != null) { networkAcl.setTags(new ArrayList<>(tagList)); networkAcls.put(storeKey, networkAcl); return; }Address address = addresses.get(storeKey).orElse(null);- if (address != null) { address.setTags(new ArrayList<>(tagList)); addresses.put(storeKey, address); }+ if (address != null) { address.setTags(new ArrayList<>(tagList)); addresses.put(storeKey, address); return; }+ ManagedPrefixList prefixList = managedPrefixLists.get(storeKey).orElse(null);+ if (prefixList != null) {+ prefixList.setTags(new ArrayList<>(tagList));+ managedPrefixLists.put(storeKey, prefixList);+ }}public List<Map<String, String>> describeTags(String region, Map<String, List<String>> filters) {@@ -2268,6 +2486,7 @@ public class Ec2Service implements ContainerTeardown {if (resourceId.startsWith("lt-")) return "launch-template";if (resourceId.startsWith("vpce-")) return "vpc-endpoint";if (resourceId.startsWith("nat-")) return "natgateway";+ if (resourceId.startsWith("pl-")) return "prefix-list";return "unknown";}@@ -2769,6 +2988,14 @@ public class Ec2Service implements ContainerTeardown {default -> true;};}+ if (resource instanceof ManagedPrefixList prefixList) {+ return switch (filterName) {+ case "prefix-list-id" -> matchesValue(values, prefixList.getPrefixListId());+ case "prefix-list-name" -> matchesValue(values, prefixList.getPrefixListName());+ case "owner-id" -> matchesValue(values, prefixList.getOwnerId());+ default -> true;+ };+ }if (resource instanceof SecurityGroup sg) {return switch (filterName) {case "group-id" -> matchesValue(values, sg.getGroupId());@@ -2894,6 +3121,7 @@ public class Ec2Service implements ContainerTeardown {if (resource instanceof Address addr) return addr.getTags();if (resource instanceof Volume vol) return vol.getTags();if (resource instanceof NetworkInterface ni) return ni.getTagSet();+ if (resource instanceof ManagedPrefixList prefixList) return prefixList.getTags();if (resource instanceof LaunchTemplate lt) return lt.getTags();if (resource instanceof VpcEndpoint endpoint) return endpoint.getTags();if (resource instanceof NatGateway natGateway) return natGateway.getTags();diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/ManagedPrefixList.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/ManagedPrefixList.javanew file mode 100644index 0000000000..64e797fc3e--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/ManagedPrefixList.java@@ -0,0 +1,87 @@+package io.github.hectorvent.floci.services.ec2.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++/**+ * A customer-managed or AWS-managed prefix list.+ *+ * <p>Entries are versioned: every successful modification stores a new version and bumps+ * {@link #version}, so {@code GetManagedPrefixListEntries} can serve a historical+ * {@code TargetVersion} the way AWS does. {@link #entriesByVersion} is the full history;+ * the current entries are the highest version.+ */+@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class ManagedPrefixList {++ private String prefixListId;+ private String prefixListName;+ private String prefixListArn;+ private String addressFamily;+ private String state = "create-complete";+ private String stateMessage;+ private Integer maxEntries;+ private long version = 1;+ private String ownerId;+ private String region;+ private boolean awsManaged;+ private Map<String, List<PrefixListEntry>> entriesByVersion = new LinkedHashMap<>();+ private List<Tag> tags = new ArrayList<>();++ public ManagedPrefixList() {}++ public String getPrefixListId() { return prefixListId; }+ public void setPrefixListId(String prefixListId) { this.prefixListId = prefixListId; }++ public String getPrefixListName() { return prefixListName; }+ public void setPrefixListName(String prefixListName) { this.prefixListName = prefixListName; }++ public String getPrefixListArn() { return prefixListArn; }+ public void setPrefixListArn(String prefixListArn) { this.prefixListArn = prefixListArn; }++ public String getAddressFamily() { return addressFamily; }+ public void setAddressFamily(String addressFamily) { this.addressFamily = addressFamily; }++ public String getState() { return state; }+ public void setState(String state) { this.state = state; }++ public String getStateMessage() { return stateMessage; }+ public void setStateMessage(String stateMessage) { this.stateMessage = stateMessage; }++ public Integer getMaxEntries() { return maxEntries; }+ public void setMaxEntries(Integer maxEntries) { this.maxEntries = maxEntries; }++ public long getVersion() { return version; }+ public void setVersion(long version) { this.version = version; }++ public String getOwnerId() { return ownerId; }+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }++ public String getRegion() { return region; }+ public void setRegion(String region) { this.region = region; }++ /** AWS-managed lists (the gateway-endpoint service lists) are read-only. */+ public boolean isAwsManaged() { return awsManaged; }+ public void setAwsManaged(boolean awsManaged) { this.awsManaged = awsManaged; }++ // Keyed by version as a string: Jackson writes non-String map keys as strings anyway, so+ // using String here keeps the persisted JSON stable across a serialize/deserialize round trip.+ public Map<String, List<PrefixListEntry>> getEntriesByVersion() { return entriesByVersion; }+ public void setEntriesByVersion(Map<String, List<PrefixListEntry>> entriesByVersion) {+ this.entriesByVersion = entriesByVersion;+ }++ public List<Tag> getTags() { return tags; }+ public void setTags(List<Tag> tags) { this.tags = tags; }++ /** Entries for the current version, or an empty list if the version holds none. */+ public List<PrefixListEntry> currentEntries() {+ return entriesByVersion.getOrDefault(String.valueOf(version), List.of());+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/PrefixListEntry.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/PrefixListEntry.javanew file mode 100644index 0000000000..d476575983--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/PrefixListEntry.java@@ -0,0 +1,25 @@+package io.github.hectorvent.floci.services.ec2.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class PrefixListEntry {++ private String cidr;+ private String description;++ public PrefixListEntry() {}++ public PrefixListEntry(String cidr, String description) {+ this.cidr = cidr;+ this.description = description;+ }++ public String getCidr() { return cidr; }+ public void setCidr(String cidr) { this.cidr = cidr; }++ public String getDescription() { return description; }+ public void setDescription(String description) { this.description = description; }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ManagedPrefixListIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ManagedPrefixListIntegrationTest.javanew file mode 100644index 0000000000..3e24269553--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ManagedPrefixListIntegrationTest.java@@ -0,0 +1,292 @@+package io.github.hectorvent.floci.services.ec2;++import io.quarkus.test.junit.QuarkusTest;+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.*;++/**+ * Integration tests for managed prefix lists over the EC2 Query protocol: create, describe with+ * filters, entry versioning through modify, and delete.+ *+ * <p>Ordered because the cases build on one prefix list, mirroring how a client drives the+ * resource through its lifecycle.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class Ec2ManagedPrefixListIntegrationTest {++ private static final String AUTH_HEADER =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";++ private static final String LIST_NAME = "integration-prefix-list";++ private static String prefixListId;++ @Test+ @Order(1)+ void createManagedPrefixList() {+ prefixListId = given()+ .formParam("Action", "CreateManagedPrefixList")+ .formParam("PrefixListName", LIST_NAME)+ .formParam("AddressFamily", "IPv4")+ .formParam("MaxEntries", "5")+ .formParam("Entry.1.Cidr", "10.0.0.0/8")+ .formParam("Entry.1.Description", "corporate")+ .formParam("TagSpecification.1.ResourceType", "prefix-list")+ .formParam("TagSpecification.1.Tag.1.Key", "env")+ .formParam("TagSpecification.1.Tag.1.Value", "test")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("CreateManagedPrefixListResponse.prefixList.prefixListName", equalTo(LIST_NAME))+ .body("CreateManagedPrefixListResponse.prefixList.addressFamily", equalTo("IPv4"))+ .body("CreateManagedPrefixListResponse.prefixList.state", equalTo("create-complete"))+ .body("CreateManagedPrefixListResponse.prefixList.version", equalTo("1"))+ .body("CreateManagedPrefixListResponse.prefixList.maxEntries", equalTo("5"))+ .body("CreateManagedPrefixListResponse.prefixList.prefixListArn",+ containsString(":prefix-list/pl-"))+ .body("CreateManagedPrefixListResponse.prefixList.tagSet.item.key", equalTo("env"))+ .extract().path("CreateManagedPrefixListResponse.prefixList.prefixListId");++ org.junit.jupiter.api.Assertions.assertTrue(prefixListId.startsWith("pl-"));+ }++ @Test+ @Order(2)+ void describeByIdReturnsTheCreatedList() {+ given()+ .formParam("Action", "DescribeManagedPrefixLists")+ .formParam("PrefixListId.1", prefixListId)+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DescribeManagedPrefixListsResponse.prefixListSet.item.prefixListName", equalTo(LIST_NAME));+ }++ @Test+ @Order(3)+ void describeIncludesAwsManagedGatewayLists() {+ given()+ .formParam("Action", "DescribeManagedPrefixLists")+ .formParam("Filter.1.Name", "prefix-list-name")+ .formParam("Filter.1.Value.1", "com.amazonaws.us-east-1.s3")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DescribeManagedPrefixListsResponse.prefixListSet.item.prefixListId", equalTo("pl-63a5400a"))+ .body("DescribeManagedPrefixListsResponse.prefixListSet.item.ownerId", equalTo("AWS"));+ }++ @Test+ @Order(4)+ void getEntriesReturnsTheInitialEntry() {+ given()+ .formParam("Action", "GetManagedPrefixListEntries")+ .formParam("PrefixListId", prefixListId)+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("GetManagedPrefixListEntriesResponse.entrySet.item.cidr", equalTo("10.0.0.0/8"))+ .body("GetManagedPrefixListEntriesResponse.entrySet.item.description", equalTo("corporate"));+ }++ @Test+ @Order(5)+ void modifyAddsAnEntryAndBumpsVersion() {+ given()+ .formParam("Action", "ModifyManagedPrefixList")+ .formParam("PrefixListId", prefixListId)+ .formParam("AddEntry.1.Cidr", "192.168.0.0/16")+ .formParam("AddEntry.1.Description", "lab")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("ModifyManagedPrefixListResponse.prefixList.version", equalTo("2"))+ .body("ModifyManagedPrefixListResponse.prefixList.state", equalTo("modify-complete"));++ given()+ .formParam("Action", "GetManagedPrefixListEntries")+ .formParam("PrefixListId", prefixListId)+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("GetManagedPrefixListEntriesResponse.entrySet.item.cidr",+ hasItems("10.0.0.0/8", "192.168.0.0/16"));+ }++ @Test+ @Order(6)+ void earlierVersionRemainsRetrievable() {+ given()+ .formParam("Action", "GetManagedPrefixListEntries")+ .formParam("PrefixListId", prefixListId)+ .formParam("TargetVersion", "1")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("GetManagedPrefixListEntriesResponse.entrySet.item.cidr", equalTo("10.0.0.0/8"));+ }++ @Test+ @Order(7)+ void modifyWithStaleCurrentVersionIsRejected() {+ given()+ .formParam("Action", "ModifyManagedPrefixList")+ .formParam("PrefixListId", prefixListId)+ .formParam("CurrentVersion", "1")+ .formParam("AddEntry.1.Cidr", "172.16.0.0/12")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("Response.Errors.Error.Code", equalTo("PrefixListVersionMismatch"));+ }++ @Test+ @Order(8)+ void modifyingAnAwsManagedListIsRejected() {+ given()+ .formParam("Action", "ModifyManagedPrefixList")+ .formParam("PrefixListId", "pl-63a5400a")+ .formParam("AddEntry.1.Cidr", "10.1.0.0/16")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("Response.Errors.Error.Code", equalTo("UnsupportedOperation"));+ }++ @Test+ @Order(9)+ void describeUnknownIdIsRejected() {+ given()+ .formParam("Action", "DescribeManagedPrefixLists")+ .formParam("PrefixListId.1", "pl-doesnotexist")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("Response.Errors.Error.Code", equalTo("InvalidPrefixListID.NotFound"));+ }++ @Test+ @Order(10)+ void legacyDescribePrefixListsStillServesGatewayLists() {+ given()+ .formParam("Action", "DescribePrefixLists")+ .formParam("Filter.1.Name", "prefix-list-name")+ .formParam("Filter.1.Value.1", "com.amazonaws.us-east-1.s3")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DescribePrefixListsResponse.prefixListSet.item.prefixListId", equalTo("pl-63a5400a"))+ .body("DescribePrefixListsResponse.prefixListSet.item.cidrSet.item",+ hasItems("52.216.0.0/15", "54.231.0.0/16"));+ }++ @Test+ @Order(11)+ void malformedNumericParametersReturnAClientError() {+ given()+ .formParam("Action", "GetManagedPrefixListEntries")+ .formParam("PrefixListId", prefixListId)+ .formParam("TargetVersion", "not-a-number")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));++ given()+ .formParam("Action", "CreateManagedPrefixList")+ .formParam("PrefixListName", "malformed-max-entries")+ .formParam("AddressFamily", "IPv4")+ .formParam("MaxEntries", "plenty")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));+ }++ /**+ * A blank value is present-but-malformed, not absent. Treating it as absent would drop the+ * conditional-version check and let a modification through that CurrentVersion asked to gate.+ */+ @Test+ @Order(11)+ void blankNumericParametersReturnAClientError() {+ given()+ .formParam("Action", "ModifyManagedPrefixList")+ .formParam("PrefixListId", prefixListId)+ .formParam("CurrentVersion", " ")+ .formParam("AddEntry.1.Cidr", "172.16.0.0/12")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));++ given()+ .formParam("Action", "GetManagedPrefixListEntries")+ .formParam("PrefixListId", prefixListId)+ .formParam("TargetVersion", "")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));+ }++ @Test+ @Order(12)+ void deleteManagedPrefixList() {+ given()+ .formParam("Action", "DeleteManagedPrefixList")+ .formParam("PrefixListId", prefixListId)+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DeleteManagedPrefixListResponse.prefixList.state", equalTo("delete-complete"));++ given()+ .formParam("Action", "DescribeManagedPrefixLists")+ .formParam("PrefixListId.1", prefixListId)+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("Response.Errors.Error.Code", equalTo("InvalidPrefixListID.NotFound"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.javaindex 3009e50c75..7a1a671087 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java@@ -7,6 +7,8 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.services.ec2.model.Address;import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;+import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;+import io.github.hectorvent.floci.services.ec2.model.PrefixListEntry;import io.github.hectorvent.floci.services.ec2.model.Instance;import io.github.hectorvent.floci.services.ec2.model.InternetGateway;import io.github.hectorvent.floci.services.ec2.model.Image;@@ -89,6 +91,32 @@ class Ec2ServicePersistenceTest {assertEquals(12, snapshots.getFirst().getVolumeSize());}+ @Test+ void managedPrefixListAndItsVersionHistorySurviveRestart(@TempDir Path dir) {+ Ec2Service first = newService(dir);+ ManagedPrefixList created = first.createManagedPrefixList(REGION, "persisted-list", "IPv4", 5,+ List.of(new PrefixListEntry("10.0.0.0/8", "corporate")), List.of());+ first.modifyManagedPrefixList(REGION, created.getPrefixListId(), null, null, null,+ List.of(new PrefixListEntry("192.168.0.0/16", "lab")), List.of());++ Ec2Service restarted = newService(dir);++ List<ManagedPrefixList> lists =+ restarted.describeManagedPrefixLists(REGION, List.of(created.getPrefixListId()), Map.of());+ assertEquals(1, lists.size(), "managed prefix list must survive restart");+ assertEquals("persisted-list", lists.getFirst().getPrefixListName());+ assertEquals(2, lists.getFirst().getVersion());++ // Entry history is a nested map on the model, so a restart is the first place a broken+ // serialization round trip would show up.+ assertEquals(2,+ restarted.getManagedPrefixListEntries(REGION, created.getPrefixListId(), null).size());+ List<PrefixListEntry> firstVersion =+ restarted.getManagedPrefixListEntries(REGION, created.getPrefixListId(), 1L);+ assertEquals(1, firstVersion.size(), "earlier version must survive restart");+ assertEquals("corporate", firstVersion.getFirst().getDescription());+ }+private BlockDeviceMapping blockDeviceMapping(String snapshotId, int volumeSize) {EbsBlockDevice ebs = new EbsBlockDevice();ebs.setSnapshotId(snapshotId);@@ -123,6 +151,7 @@ class Ec2ServicePersistenceTest {load(dir, "ec2-nat-gateways.json", new TypeReference<Map<String, NatGateway>>() {}),load(dir, "ec2-spot-instance-requests.json", new TypeReference<Map<String, SpotInstanceRequest>>() {}),load(dir, "ec2-network-acls.json", new TypeReference<Map<String, NetworkAcl>>() {}),+ load(dir, "ec2-managed-prefix-lists.json", new TypeReference<Map<String, ManagedPrefixList>>() {}),load(dir, "ec2-tags.json", new TypeReference<Map<String, List<Tag>>>() {}));}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.javaindex dd708df4cc..a1871a7df2 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java@@ -12,6 +12,8 @@ import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;import io.github.hectorvent.floci.services.ec2.model.Instance;import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;+import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;+import io.github.hectorvent.floci.services.ec2.model.PrefixListEntry;import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;import io.github.hectorvent.floci.services.ec2.model.Reservation;import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;@@ -561,6 +563,265 @@ class Ec2ServiceTest {assertEquals("available", detached.getState());}+ // =========================================================================+ // Managed prefix lists+ // =========================================================================++ private static Ec2Service prefixListService() {+ return new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),+ new InMemoryStorageFactory());+ }++ @Test+ void createManagedPrefixListStoresEntriesAtVersionOne() {+ Ec2Service service = prefixListService();++ ManagedPrefixList list = service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5,+ List.of(new PrefixListEntry("10.0.0.0/8", "corporate")), List.of());++ assertTrue(list.getPrefixListId().startsWith("pl-"));+ assertEquals("create-complete", list.getState());+ assertEquals(1, list.getVersion());+ assertEquals("000000000000", list.getOwnerId());+ assertEquals("arn:aws:ec2:us-east-1:000000000000:prefix-list/" + list.getPrefixListId(),+ list.getPrefixListArn());+ assertEquals(1, list.currentEntries().size());+ assertEquals("corporate", list.currentEntries().getFirst().getDescription());+ }++ @Test+ void createManagedPrefixListRejectsMoreEntriesThanMaxEntries() {+ Ec2Service service = prefixListService();++ AwsException error = assertThrows(AwsException.class, () -> service.createManagedPrefixList(+ "us-east-1", "corp", "IPv4", 1,+ List.of(new PrefixListEntry("10.0.0.0/8", null), new PrefixListEntry("10.1.0.0/16", null)),+ List.of()));+ assertEquals("InvalidParameterValue", error.getErrorCode());+ }++ @Test+ void createManagedPrefixListRejectsCidrOfTheWrongAddressFamily() {+ Ec2Service service = prefixListService();++ AwsException error = assertThrows(AwsException.class, () -> service.createManagedPrefixList(+ "us-east-1", "corp", "IPv4", 5,+ List.of(new PrefixListEntry("2001:db8::/32", null)), List.of()));+ assertEquals("InvalidParameterValue", error.getErrorCode());+ }++ @Test+ void describeManagedPrefixListsIncludesAwsManagedAndIsRegionScoped() {+ Ec2Service service = prefixListService();+ service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5, List.of(), List.of());++ List<ManagedPrefixList> east = service.describeManagedPrefixLists("us-east-1", List.of(), Map.of());+ assertEquals(3, east.size());+ assertTrue(east.stream().anyMatch(l -> "com.amazonaws.us-east-1.s3".equals(l.getPrefixListName())));+ assertTrue(east.stream().anyMatch(l -> "corp".equals(l.getPrefixListName())));++ // The customer list belongs to us-east-1; only the AWS-managed pair shows up elsewhere.+ List<ManagedPrefixList> west = service.describeManagedPrefixLists("us-west-2", List.of(), Map.of());+ assertEquals(2, west.size());+ assertTrue(west.stream().allMatch(ManagedPrefixList::isAwsManaged));+ assertTrue(west.stream().anyMatch(l -> "com.amazonaws.us-west-2.s3".equals(l.getPrefixListName())));+ }++ @Test+ void createManagedPrefixListAcceptsIpv6Entries() {+ Ec2Service service = prefixListService();++ ManagedPrefixList list = service.createManagedPrefixList("us-east-1", "corp-v6", "IPv6", 5,+ List.of(new PrefixListEntry("2001:db8::/32", "lab")), List.of());++ assertEquals("IPv6", list.getAddressFamily());+ assertEquals("2001:db8::/32", list.currentEntries().getFirst().getCidr());++ service.modifyManagedPrefixList("us-east-1", list.getPrefixListId(), null, null, null,+ List.of(new PrefixListEntry("2001:db8:1::/48", null)), List.of());+ assertEquals(2, service.getManagedPrefixListEntries("us-east-1", list.getPrefixListId(), null).size());++ AwsException error = assertThrows(AwsException.class, () -> service.modifyManagedPrefixList(+ "us-east-1", list.getPrefixListId(), null, null, null,+ List.of(new PrefixListEntry("10.0.0.0/8", null)), List.of()));+ assertEquals("InvalidParameterValue", error.getErrorCode());+ }++ @Test+ void managedPrefixListLookupsRejectAMissingId() {+ Ec2Service service = prefixListService();++ for (String missing : new String[] {null, " "}) {+ assertEquals("MissingParameter", assertThrows(AwsException.class, () ->+ service.getManagedPrefixListEntries("us-east-1", missing, null)).getErrorCode());+ assertEquals("MissingParameter", assertThrows(AwsException.class, () ->+ service.deleteManagedPrefixList("us-east-1", missing)).getErrorCode());+ assertEquals("MissingParameter", assertThrows(AwsException.class, () ->+ service.modifyManagedPrefixList("us-east-1", missing, null, null, null,+ List.of(), List.of())).getErrorCode());+ }+ }++ @Test+ void describeManagedPrefixListsFiltersByName() {+ Ec2Service service = prefixListService();+ service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5, List.of(), List.of());++ List<ManagedPrefixList> found = service.describeManagedPrefixLists("us-east-1", List.of(),+ Map.of("prefix-list-name", List.of("corp")));++ assertEquals(1, found.size());+ assertEquals("corp", found.getFirst().getPrefixListName());+ }++ @Test+ void describeManagedPrefixListsRejectsUnknownId() {+ Ec2Service service = prefixListService();++ AwsException error = assertThrows(AwsException.class, () ->+ service.describeManagedPrefixLists("us-east-1", List.of("pl-missing"), Map.of()));+ assertEquals("InvalidPrefixListID.NotFound", error.getErrorCode());+ }++ @Test+ void modifyBumpsVersionAndKeepsEarlierVersionsRetrievable() {+ Ec2Service service = prefixListService();+ ManagedPrefixList created = service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5,+ List.of(new PrefixListEntry("10.0.0.0/8", null)), List.of());++ ManagedPrefixList modified = service.modifyManagedPrefixList("us-east-1", created.getPrefixListId(),+ null, null, null, List.of(new PrefixListEntry("192.168.0.0/16", "lab")), List.of());++ assertEquals(2, modified.getVersion());+ assertEquals("modify-complete", modified.getState());+ assertEquals(2, service.getManagedPrefixListEntries("us-east-1", created.getPrefixListId(), null).size());+ assertEquals(1, service.getManagedPrefixListEntries("us-east-1", created.getPrefixListId(), 1L).size());+ }++ @Test+ void modifyAppliesRemovalsBeforeAdditionsSoADescriptionCanBeReplaced() {+ Ec2Service service = prefixListService();+ ManagedPrefixList created = service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5,+ List.of(new PrefixListEntry("10.0.0.0/8", "old")), List.of());++ service.modifyManagedPrefixList("us-east-1", created.getPrefixListId(), null, null, null,+ List.of(new PrefixListEntry("10.0.0.0/8", "new")), List.of("10.0.0.0/8"));++ List<PrefixListEntry> entries =+ service.getManagedPrefixListEntries("us-east-1", created.getPrefixListId(), null);+ assertEquals(1, entries.size());+ assertEquals("new", entries.getFirst().getDescription());+ }++ @Test+ void renamingDoesNotCreateANewVersion() {+ Ec2Service service = prefixListService();+ ManagedPrefixList created = service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5,+ List.of(new PrefixListEntry("10.0.0.0/8", null)), List.of());++ ManagedPrefixList renamed = service.modifyManagedPrefixList("us-east-1", created.getPrefixListId(),+ null, "corp-renamed", null, List.of(), List.of());++ assertEquals("corp-renamed", renamed.getPrefixListName());+ assertEquals(1, renamed.getVersion());+ }++ @Test+ void modifyWithStaleCurrentVersionIsRejected() {+ Ec2Service service = prefixListService();+ ManagedPrefixList created = service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5,+ List.of(new PrefixListEntry("10.0.0.0/8", null)), List.of());+ service.modifyManagedPrefixList("us-east-1", created.getPrefixListId(), null, null, null,+ List.of(new PrefixListEntry("192.168.0.0/16", null)), List.of());++ AwsException error = assertThrows(AwsException.class, () ->+ service.modifyManagedPrefixList("us-east-1", created.getPrefixListId(), 1L, null, null,+ List.of(new PrefixListEntry("172.16.0.0/12", null)), List.of()));+ assertEquals("PrefixListVersionMismatch", error.getErrorCode());+ }++ @Test+ void awsManagedListsCannotBeModifiedOrDeleted() {+ Ec2Service service = prefixListService();++ AwsException modifyError = assertThrows(AwsException.class, () ->+ service.modifyManagedPrefixList("us-east-1", "pl-63a5400a", null, "hijacked", null,+ List.of(), List.of()));+ assertEquals("UnsupportedOperation", modifyError.getErrorCode());++ AwsException deleteError = assertThrows(AwsException.class, () ->+ service.deleteManagedPrefixList("us-east-1", "pl-63a5400a"));+ assertEquals("UnsupportedOperation", deleteError.getErrorCode());+ }++ @Test+ void deleteRemovesTheListFromDescribe() {+ Ec2Service service = prefixListService();+ ManagedPrefixList created = service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5,+ List.of(), List.of());++ ManagedPrefixList deleted = service.deleteManagedPrefixList("us-east-1", created.getPrefixListId());++ assertEquals("delete-complete", deleted.getState());+ assertThrows(AwsException.class, () ->+ service.describeManagedPrefixLists("us-east-1", List.of(created.getPrefixListId()), Map.of()));+ }++ @Test+ void legacyDescribePrefixListsProjectsTheSameAwsManagedData() {+ Ec2Service service = prefixListService();++ var legacy = service.describePrefixLists("us-east-1", List.of(),+ Map.of("prefix-list-name", List.of("com.amazonaws.us-east-1.s3")));++ assertEquals(1, legacy.size());+ assertEquals("pl-63a5400a", legacy.getFirst().getPrefixListId());+ assertEquals(List.of("52.216.0.0/15", "54.231.0.0/16"), legacy.getFirst().getCidrs());+ }++ @Test+ void modifyRejectsANonPositiveMaxEntries() {+ Ec2Service service = prefixListService();+ ManagedPrefixList created = service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5,+ List.of(), List.of());++ // The list is empty, so a size check alone would let a zero capacity through.+ AwsException error = assertThrows(AwsException.class, () ->+ service.modifyManagedPrefixList("us-east-1", created.getPrefixListId(), null, null, 0,+ List.of(), List.of()));+ assertEquals("InvalidParameterValue", error.getErrorCode());+ assertEquals(5, service.describeManagedPrefixLists("us-east-1",+ List.of(created.getPrefixListId()), Map.of()).getFirst().getMaxEntries());+ }++ @Test+ void createTagsOnAPrefixListIsVisibleToDescribeAndTagFilters() {+ Ec2Service service = prefixListService();+ ManagedPrefixList created = service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5,+ List.of(), List.of());++ service.createTags("us-east-1", List.of(created.getPrefixListId()), List.of(new Tag("env", "prod")));++ ManagedPrefixList described = service.describeManagedPrefixLists("us-east-1",+ List.of(created.getPrefixListId()), Map.of()).getFirst();+ assertEquals(1, described.getTags().size());+ assertEquals("prod", described.getTags().getFirst().getValue());++ assertEquals(1, service.describeManagedPrefixLists("us-east-1", List.of(),+ Map.of("tag:env", List.of("prod"))).size());++ assertEquals("prefix-list", service.describeTags("us-east-1",+ Map.of("resource-id", List.of(created.getPrefixListId()))).getFirst().get("resourceType"));+ assertEquals(1, service.describeTags("us-east-1",+ Map.of("resource-type", List.of("prefix-list"))).size());++ service.deleteTags("us-east-1", List.of(created.getPrefixListId()), List.of(new Tag("env", null)));+ assertTrue(service.describeManagedPrefixLists("us-east-1", List.of(created.getPrefixListId()), Map.of())+ .getFirst().getTags().isEmpty());+ }+private static EmulatorConfig mockConfig(boolean ec2Mock) {EmulatorConfig config = mock(EmulatorConfig.class);EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);