From cf07da1eebfa0a190ca78a2f8531a12c6d630fa0 Mon Sep 17 00:00:00 2001 From: Jimmy Liu Jia <91264074+JimmyLiuJia@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:12:59 +0800 Subject: [PATCH] fix(ec2): enforce security group rule quotas (#9929) --- docs/services/ec2.md | 29 ++- docs/services/servicequotas.md | 5 +- .../io/floci/aws/config/EmulatorConfig.java | 7 + .../config/ServiceQuotasStartupValidator.java | 8 + .../Ec2SecurityGroupCfnProvisioner.java | 11 +- .../io/floci/aws/services/ec2/Ec2Service.java | 216 ++++++++++++----- .../services/ec2/model/ManagedPrefixList.java | 5 + .../aws/services/ec2/model/PrefixList.java | 5 + .../servicequotas/ServiceQuotasService.java | 13 +- src/main/resources/application.yml | 2 + .../ServiceQuotasStartupValidatorTest.java | 10 + ...ityGroupUpdateRollbackIntegrationTest.java | 46 ++++ ...SecurityGroupRuleQuotaIntegrationTest.java | 226 ++++++++++++++++++ .../aws/services/ec2/Ec2ServiceTest.java | 57 ++++- .../ServiceQuotasServiceTest.java | 22 +- src/test/resources/application.yml | 2 + 16 files changed, 592 insertions(+), 72 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/ec2/Ec2SecurityGroupRuleQuotaIntegrationTest.java diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 3f6b531555..6cc433d399 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -734,13 +734,17 @@ file inside the Floci container, for example: "eu-west-1": [{ "prefixListId": "pl-0123456789abcdef0", "prefixListName": "example-managed-service", + "weight": 6, "cidrs": ["192.0.2.0/24"] }] } ``` The file is read once when EC2 starts. Each entry needs a unique ID and name -within its region and at least one IPv4 CIDR. CIDRs are normalized to network +within its region and at least one IPv4 CIDR. An optional positive `weight` sets +its published rule quota weight; catalogs without it use 1 for compatibility. +The weight is not the CIDR count and is not returned by `DescribeManagedPrefixLists`. +CIDRs are normalized to network blocks; repeated or equivalent blocks within one list are rejected. Entries cannot replace the built-in lists. Invalid or unreadable files prevent startup when EC2 is enabled; disabled EC2 does not read the catalog. Configured lists @@ -772,6 +776,29 @@ resulting rule carries `prefixListId` in place of `cidrIpv4`, and `DescribeSecur the reference under the permission as `prefixListIds`. Authorizing against a list that does not exist returns `InvalidPrefixListID.NotFound`, so a typo cannot leave a rule pointing at nothing. +### Security group rule quota + +`AuthorizeSecurityGroupIngress` and `AuthorizeSecurityGroupEgress` enforce the VPC +`L-0EA8095F` quota, default 60. Inbound and outbound rules, and IPv4 and IPv6 +sources, have separate counts. A CIDR uses one slot; a security group reference +uses one slot in each address family. A customer-managed prefix list uses its +`MaxEntries`, and an AWS-managed list uses its published weight: S3 and DynamoDB +use 1, and CloudFront origin-facing uses 55. A prefix list reference consumes its +weight in both address family pools. Floci checks the entire request +before storing any of its rules and returns `RulesPerSecurityGroupLimitExceeded` +if either address family would exceed its limit. The default outbound allow-all +rule uses one IPv4 slot. + +Increasing a customer-managed list's `MaxEntries` also checks every security group +that references it. The resize leaves the list unchanged if a group would exceed +its rule quota. Remove security group references before deleting a customer-managed +list; otherwise deletion fails with `DependencyViolation`. + +Set `FLOCI_SERVICES_SERVICEQUOTAS_RULES_PER_SECURITY_GROUP` to a positive integer +to change the applied limit for both directions. Set +`FLOCI_SERVICES_EC2_ENFORCE_SECURITY_GROUP_RULE_QUOTA=false` to disable admission +checks for local setups that intentionally exceed that limit. + ### Transit Gateways | Action | Description | diff --git a/docs/services/servicequotas.md b/docs/services/servicequotas.md index 6251b7e606..e4b137e256 100644 --- a/docs/services/servicequotas.md +++ b/docs/services/servicequotas.md @@ -12,8 +12,8 @@ Unmodeled values are deliberately generous so local pipelines that gate on quota as AWS Landing Zone Accelerator, never stall on a limit the emulator does not enforce. The Organizations `Maximum number of accounts` quota uses AWS quota code `L-E619E033` and a local value of 50. VPC's `L-FE5A380F` ("NAT gateways per Availability Zone", 5) and `L-2AEEBF1A` ("Rules per -network ACL", 20) carry their AWS default values, so tooling that compares a desired value against -the default before requesting an increase takes the same path it would against AWS. +network ACL", 20) carry their AWS default values. VPC's `L-0EA8095F` ("Inbound or outbound +rules per security group") has an AWS default of 60 and a configurable applied value. EC2's `L-1216C47A` ("Running On-Demand Standard (A, C, D, H, I, M, R, T, Z) instances") reports a configurable applied value through `GetServiceQuota` and `ListServiceQuotas`. Set `FLOCI_SERVICES_SERVICEQUOTAS_STANDARD_ON_DEMAND_VCPUS` to @@ -76,6 +76,7 @@ Limitations. | --- | --- | --- | | `FLOCI_SERVICES_SERVICEQUOTAS_ENABLED` | `true` | Enables the service | | `FLOCI_SERVICES_SERVICEQUOTAS_STANDARD_ON_DEMAND_VCPUS` | `5` | Applied EC2 Standard On-Demand vCPU quota reported per local account and region; used by opt-in EC2 admission | +| `FLOCI_SERVICES_SERVICEQUOTAS_RULES_PER_SECURITY_GROUP` | `60` | Applied VPC rule quota for each security group, used by EC2 ingress and egress admission; must be positive | ## Example diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 7ce7b9aa83..16c4bf67aa 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1356,6 +1356,9 @@ public interface EmulatorConfig { @WithDefault("5") int standardOnDemandVcpus(); + + @WithDefault("60") + int rulesPerSecurityGroup(); } interface VerifiedPermissionsServiceConfig { @@ -4084,6 +4087,10 @@ public interface EmulatorConfig { @WithDefault("false") boolean enforceVcpuQuotas(); + /** Enforce the VPC rules-per-security-group quota on EC2 ingress and egress authorization. */ + @WithDefault("true") + boolean enforceSecurityGroupRuleQuota(); + /** * When true, DescribeInstances and IMDS report each instance's CFN- and * subnet-allocated private IP (AWS-faithful) instead of the Docker diff --git a/src/main/java/io/floci/aws/config/ServiceQuotasStartupValidator.java b/src/main/java/io/floci/aws/config/ServiceQuotasStartupValidator.java index f99c041ef5..4b60d68723 100644 --- a/src/main/java/io/floci/aws/config/ServiceQuotasStartupValidator.java +++ b/src/main/java/io/floci/aws/config/ServiceQuotasStartupValidator.java @@ -17,6 +17,7 @@ public class ServiceQuotasStartupValidator { void onStart(@Observes StartupEvent ignored) { validateStandardOnDemandVcpus(config.services().servicequotas().standardOnDemandVcpus()); + validateRulesPerSecurityGroup(config.services().servicequotas().rulesPerSecurityGroup()); } public static void validateStandardOnDemandVcpus(int value) { @@ -25,4 +26,11 @@ public class ServiceQuotasStartupValidator { "floci.services.servicequotas.standard-on-demand-vcpus must be nonnegative"); } } + + public static void validateRulesPerSecurityGroup(int value) { + if (value < 1) { + throw new IllegalArgumentException( + "floci.services.servicequotas.rules-per-security-group must be positive"); + } + } } diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java index 7ffad2f229..1f3645c798 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java @@ -131,18 +131,19 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner { if (reused && ctx.isUpdate()) { snapshotInPlace(r, region, groupId, ingress, egress, ownedTags, desiredTags); } - for (IpPermission perm : ingress.authorize()) { - ec2Service.authorizeSecurityGroupIngress(region, groupId, List.of(perm)); - } + // Release obsolete owned rules first, so an in-place replacement also works at the quota. for (IpPermission perm : ingress.revoke()) { ec2Service.revokeSecurityGroupIngress(region, groupId, List.of(perm)); } - for (IpPermission perm : egress.authorize()) { - ec2Service.authorizeSecurityGroupEgress(region, groupId, List.of(perm)); + for (IpPermission perm : ingress.authorize()) { + ec2Service.authorizeSecurityGroupIngress(region, groupId, List.of(perm)); } for (IpPermission perm : egress.revoke()) { ec2Service.revokeSecurityGroupEgress(region, groupId, List.of(perm)); } + for (IpPermission perm : egress.authorize()) { + ec2Service.authorizeSecurityGroupEgress(region, groupId, List.of(perm)); + } Ec2Tags.reconcileOwned(ec2Service, region, groupId, ownedTags, desiredTags); }); putRuleKeys(r, INGRESS_RULES_ATTR, ingress.declaredKeys()); diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index 0ea5ac2759..3711bf2226 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -2403,7 +2403,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab List lists = new ArrayList<>(defaultAwsManagedPrefixLists(region)); for (PrefixList configured : configuredManagedPrefixLists.getOrDefault(region, List.of())) { lists.add(awsManagedPrefixList(region, configured.getPrefixListId(), - configured.getPrefixListName(), configured.getCidrs())); + configured.getPrefixListName(), configured.getCidrs(), + configured.getWeight() == null ? 1 : configured.getWeight())); } return lists; } @@ -2446,6 +2447,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab || !list.getPrefixListId().matches("pl-(?:[0-9a-f]{8}|[0-9a-f]{17})") || list.getPrefixListName() == null || list.getPrefixListName().isBlank() || list.getCidrs() == null || list.getCidrs().isEmpty() + || (list.getWeight() != null && list.getWeight() < 1) || !ids.add(list.getPrefixListId()) || !names.add(list.getPrefixListName())) { throw new IllegalArgumentException("Invalid or duplicate prefix list in " + region.getKey()); } @@ -2480,12 +2482,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab private List defaultAwsManagedPrefixLists(String region) { List lists = new ArrayList<>(List.of( awsManagedPrefixList(region, "pl-63a5400a", "com.amazonaws." + region + ".s3", - List.of("52.216.0.0/15", "54.231.0.0/16")), + List.of("52.216.0.0/15", "54.231.0.0/16"), 1), awsManagedPrefixList(region, "pl-02cd2c6b", "com.amazonaws." + region + ".dynamodb", - List.of("3.218.182.0/24", "52.94.0.0/22")))); + List.of("3.218.182.0/24", "52.94.0.0/22"), 1))); if (AwsRegions.DEFAULT_PARTITION.equals(partitionForRegion(region))) { lists.add(awsManagedPrefixList(region, CLOUDFRONT_ORIGIN_FACING_PREFIX_LIST_ID, - CLOUDFRONT_ORIGIN_FACING_PREFIX_LIST_NAME, CLOUDFRONT_ORIGIN_FACING_CIDRS)); + CLOUDFRONT_ORIGIN_FACING_PREFIX_LIST_NAME, CLOUDFRONT_ORIGIN_FACING_CIDRS, 55)); } return lists; } @@ -2495,7 +2497,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return regionResolver != null ? regionResolver.partitionForRegion(region) : AwsRegions.partitionFor(region); } - private ManagedPrefixList awsManagedPrefixList(String region, String id, String name, List cidrs) { + private ManagedPrefixList awsManagedPrefixList(String region, String id, String name, List cidrs, + int quotaWeight) { ManagedPrefixList list = new ManagedPrefixList(); list.setPrefixListId(id); list.setPrefixListName(name); @@ -2509,6 +2512,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab list.setVersion(1); list.setRegion(region); list.setAwsManaged(true); + list.setQuotaWeight(quotaWeight); list.getEntriesByVersion().put("1", cidrs.stream() .map(cidr -> new PrefixListEntry(cidr, null)) .collect(Collectors.toList())); @@ -2605,67 +2609,81 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab public ManagedPrefixList modifyManagedPrefixList(String region, String prefixListId, Long currentVersion, String prefixListName, Integer maxEntries, List addEntries, List 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 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); + synchronized (attachmentTopologyLock(region)) { + 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); } - } - 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()) { - requireUnreservedPrefixListName(prefixListName); - list.setPrefixListName(prefixListName); - } + List 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); + } + } - 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); + 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 (effectiveMax > list.getMaxEntries()) { + requireManagedPrefixListResizeWithinSecurityGroupQuota(region, prefixListId, + effectiveMax - list.getMaxEntries()); + } + if (maxEntries != null) { + list.setMaxEntries(maxEntries); + } + if (prefixListName != null && !prefixListName.isBlank()) { + requireUnreservedPrefixListName(prefixListName); + 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); + reconcileFirewallPolicies(region); + return list; } - list.setState("modify-complete"); - managedPrefixLists.put(key(region, prefixListId), list); - reconcileFirewallPolicies(region); - 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)); - removeTags(region, prefixListId); - reconcileFirewallPolicies(region); - // AWS reports delete-complete on the returned object even though it is now gone. - list.setState("delete-complete"); - return list; + synchronized (attachmentTopologyLock(region)) { + synchronized (lockFor(key(region, prefixListId))) { + ManagedPrefixList list = getRequiredManagedPrefixList(region, prefixListId); + requireCustomerManaged(list, "deleted"); + if (securityGroups.scan(k -> k.startsWith(region + "::")).stream() + .anyMatch(group -> countPrefixListReferences(group.getIpPermissions(), prefixListId) > 0 + || countPrefixListReferences(group.getIpPermissionsEgress(), prefixListId) > 0)) { + throw new AwsException("DependencyViolation", + "The prefix list " + prefixListId + " is referenced by a security group.", 400); + } + managedPrefixLists.delete(key(region, prefixListId)); + removeTags(region, prefixListId); + reconcileFirewallPolicies(region); + // AWS reports delete-complete on the returned object even though it is now gone. + list.setState("delete-complete"); + return list; + } } } @@ -9414,6 +9432,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (dryRun) { throw dryRunOperation(); } + requireSecurityGroupRuleQuota(region, sg.getIpPermissions(), permissions); List next = new ArrayList<>(sg.getIpPermissions()); for (IpPermission perm : permissions) { resolveGroupReferences(region, sg.getVpcId(), perm); @@ -9447,6 +9466,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (dryRun) { throw dryRunOperation(); } + requireSecurityGroupRuleQuota(region, sg.getIpPermissionsEgress(), permissions); List next = new ArrayList<>(sg.getIpPermissionsEgress()); for (IpPermission perm : permissions) { resolveGroupReferences(region, sg.getVpcId(), perm); @@ -9461,6 +9481,86 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return rules; } + /** A larger customer list consumes more of every referencing group's ingress and egress quota. */ + private void requireManagedPrefixListResizeWithinSecurityGroupQuota(String region, String prefixListId, + int increase) { + if (!config.services().ec2().enforceSecurityGroupRuleQuota()) { + return; + } + int limit = config.services().servicequotas().rulesPerSecurityGroup(); + for (SecurityGroup group : securityGroups.scan(k -> k.startsWith(region + "::"))) { + requireManagedPrefixListResizeWithinQuota(region, group.getIpPermissions(), prefixListId, increase, limit); + requireManagedPrefixListResizeWithinQuota(region, group.getIpPermissionsEgress(), prefixListId, + increase, limit); + } + } + + private void requireManagedPrefixListResizeWithinQuota(String region, List permissions, + String prefixListId, int increase, int limit) { + long references = countPrefixListReferences(permissions, prefixListId); + if (references == 0) { + return; + } + long[] usage = new long[2]; + for (IpPermission permission : nullToEmpty(permissions)) { + addSecurityGroupRuleUsage(region, permission, usage); + } + long addedUsage = references * increase; + if (usage[0] + addedUsage > limit || usage[1] + addedUsage > limit) { + throw new AwsException("RulesPerSecurityGroupLimitExceeded", + "The maximum number of rules per security group has been reached.", 400); + } + } + + private static long countPrefixListReferences(List permissions, String prefixListId) { + return nullToEmpty(permissions).stream() + .flatMap(permission -> nullToEmpty(permission.getPrefixListIds()).stream()) + .filter(reference -> reference != null && prefixListId.equals(reference.getPrefixListId())) + .count(); + } + + /** Check the complete authorization before createRules writes any flattened rules. */ + private void requireSecurityGroupRuleQuota(String region, List existing, + List requested) { + if (!config.services().ec2().enforceSecurityGroupRuleQuota()) { + return; + } + long[] usage = new long[2]; + for (IpPermission permission : nullToEmpty(existing)) { + addSecurityGroupRuleUsage(region, permission, usage); + } + for (IpPermission permission : requested) { + addSecurityGroupRuleUsage(region, permission, usage); + } + int limit = config.services().servicequotas().rulesPerSecurityGroup(); + if (usage[0] > limit || usage[1] > limit) { + throw new AwsException("RulesPerSecurityGroupLimitExceeded", + "The maximum number of rules per security group has been reached.", 400); + } + } + + /** IPv4 and IPv6 are separate quota pools; group references use one slot in both. */ + private void addSecurityGroupRuleUsage(String region, IpPermission permission, long[] usage) { + long ipv4 = nullToEmpty(permission.getIpRanges()).size(); + long ipv6 = nullToEmpty(permission.getIpv6Ranges()).size(); + int groupReferences = nullToEmpty(permission.getUserIdGroupPairs()).size(); + ipv4 += groupReferences; + ipv6 += groupReferences; + for (PrefixListId reference : nullToEmpty(permission.getPrefixListIds())) { + ManagedPrefixList list = getRequiredManagedPrefixList(region, reference.getPrefixListId()); + int weight = list.isAwsManaged() ? list.getQuotaWeight() : list.getMaxEntries(); + ipv4 += weight; + ipv6 += weight; + } + if (ipv4 == 0 && ipv6 == 0) { + // Floci accepts a source-free permission and describes one rule for it. + ipv4++; + ipv6++; + } + usage[0] += ipv4; + usage[1] += ipv6; + } + /** * Flattens one permission into the {@link SecurityGroupRule} entries DescribeSecurityGroupRules * serves. AWS gives every rule exactly one source, so a permission carrying several sources fans diff --git a/src/main/java/io/floci/aws/services/ec2/model/ManagedPrefixList.java b/src/main/java/io/floci/aws/services/ec2/model/ManagedPrefixList.java index 2e69050f4b..9a6b2787b6 100644 --- a/src/main/java/io/floci/aws/services/ec2/model/ManagedPrefixList.java +++ b/src/main/java/io/floci/aws/services/ec2/model/ManagedPrefixList.java @@ -31,6 +31,7 @@ public class ManagedPrefixList { private String ownerId; private String region; private boolean awsManaged; + private Integer quotaWeight; private Map> entriesByVersion = new LinkedHashMap<>(); private List tags = new ArrayList<>(); @@ -70,6 +71,10 @@ public class ManagedPrefixList { public boolean isAwsManaged() { return awsManaged; } public void setAwsManaged(boolean awsManaged) { this.awsManaged = awsManaged; } + /** Internal quota weight for an AWS-managed list; not an EC2 response member. */ + public Integer getQuotaWeight() { return quotaWeight; } + public void setQuotaWeight(Integer quotaWeight) { this.quotaWeight = quotaWeight; } + // 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> getEntriesByVersion() { return entriesByVersion; } diff --git a/src/main/java/io/floci/aws/services/ec2/model/PrefixList.java b/src/main/java/io/floci/aws/services/ec2/model/PrefixList.java index 1c2fb7016d..a980d38100 100644 --- a/src/main/java/io/floci/aws/services/ec2/model/PrefixList.java +++ b/src/main/java/io/floci/aws/services/ec2/model/PrefixList.java @@ -13,6 +13,7 @@ public class PrefixList { private String prefixListId; private String prefixListName; private List cidrs = new ArrayList<>(); + private Integer weight; public PrefixList() {} @@ -30,4 +31,8 @@ public class PrefixList { public List getCidrs() { return cidrs; } public void setCidrs(List cidrs) { this.cidrs = cidrs; } + + /** Published AWS rule quota weight, which is independent of the number of CIDRs. */ + public Integer getWeight() { return weight; } + public void setWeight(Integer weight) { this.weight = weight; } } diff --git a/src/main/java/io/floci/aws/services/servicequotas/ServiceQuotasService.java b/src/main/java/io/floci/aws/services/servicequotas/ServiceQuotasService.java index 29b503f258..8e79224d46 100644 --- a/src/main/java/io/floci/aws/services/servicequotas/ServiceQuotasService.java +++ b/src/main/java/io/floci/aws/services/servicequotas/ServiceQuotasService.java @@ -34,8 +34,8 @@ import java.util.zip.CRC32; * executions"), plus a deterministic generic set for any other service code. * Unmodeled values are deliberately generous so local pipelines that gate on * quota headroom never stall on a limit the emulator does not enforce. - * Applied EC2 Standard On-Demand vCPU values use local configuration; AWS defaults - * retain the catalog value. + * Applied EC2 Standard On-Demand vCPU and VPC security group rule values use local + * configuration; AWS defaults retain their catalog values. * * @see Service Quotas API */ @@ -77,7 +77,8 @@ public class ServiceQuotasService { // compares its desired value against these before requesting an increase. "vpc", List.of( new QuotaDefinition("L-FE5A380F", "NAT gateways per Availability Zone", 5.0, false), - new QuotaDefinition("L-2AEEBF1A", "Rules per network ACL", 20.0, false))); + new QuotaDefinition("L-2AEEBF1A", "Rules per network ACL", 20.0, false), + new QuotaDefinition("L-0EA8095F", "Inbound or outbound rules per security group", 60.0, false))); private static final List GENERIC_QUOTA_NAMES = List.of( "Resources per Region", @@ -86,6 +87,7 @@ public class ServiceQuotasService { private final ObjectMapper objectMapper; private final int standardOnDemandVcpus; + private final int rulesPerSecurityGroup; private final StorageBackend requestedQuotaStore; private final Object openRequestLock = new Object(); @@ -93,7 +95,9 @@ public class ServiceQuotasService { public ServiceQuotasService(StorageFactory storageFactory, ObjectMapper objectMapper, EmulatorConfig config) { this.objectMapper = objectMapper; this.standardOnDemandVcpus = config.services().servicequotas().standardOnDemandVcpus(); + this.rulesPerSecurityGroup = config.services().servicequotas().rulesPerSecurityGroup(); ServiceQuotasStartupValidator.validateStandardOnDemandVcpus(standardOnDemandVcpus); + ServiceQuotasStartupValidator.validateRulesPerSecurityGroup(rulesPerSecurityGroup); this.requestedQuotaStore = storageFactory.create("servicequotas", "servicequotas-requested-changes.json", new TypeReference>() {}); @@ -215,6 +219,9 @@ public class ServiceQuotasService { node.put("QuotaName", quota.quotaName()); double value = applied && "ec2".equals(serviceCode) && "L-1216C47A".equals(quota.quotaCode()) ? standardOnDemandVcpus : quota.value(); + if (applied && "vpc".equals(serviceCode) && "L-0EA8095F".equals(quota.quotaCode())) { + value = rulesPerSecurityGroup; + } node.put("Value", value); node.put("Unit", "None"); node.put("Adjustable", true); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 7f1fbe944e..152998d8c8 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -879,6 +879,7 @@ floci: ec2: # Opt-in Standard On-Demand vCPU admission. FLOCI_SERVICES_EC2_ENFORCE_VCPU_QUOTAS enforce-vcpu-quotas: false + enforce-security-group-rule-quota: true # Optional complete catalog override for locally built guest images. image-catalog-path: ${FLOCI_SERVICES_EC2_IMAGE_CATALOG_PATH:} managed-prefix-list-catalog-path: ${FLOCI_SERVICES_EC2_MANAGED_PREFIX_LIST_CATALOG_PATH:} @@ -1300,6 +1301,7 @@ floci: servicequotas: enabled: true standard-on-demand-vcpus: 5 + rules-per-security-group: 60 verifiedpermissions: enabled: true # cedar-url: http://floci-cedar:8180 # set to skip sidecar container management diff --git a/src/test/java/io/floci/aws/config/ServiceQuotasStartupValidatorTest.java b/src/test/java/io/floci/aws/config/ServiceQuotasStartupValidatorTest.java index 99a16be430..d421b2c03d 100644 --- a/src/test/java/io/floci/aws/config/ServiceQuotasStartupValidatorTest.java +++ b/src/test/java/io/floci/aws/config/ServiceQuotasStartupValidatorTest.java @@ -33,9 +33,19 @@ class ServiceQuotasStartupValidatorTest { assertDoesNotThrow(() -> validator.onStart(new StartupEvent())); } + @ParameterizedTest + @ValueSource(ints = {0, -1, Integer.MIN_VALUE}) + void nonpositiveSecurityGroupRuleQuotaIsRejected(int value) { + IllegalArgumentException error = assertThrows(IllegalArgumentException.class, + () -> ServiceQuotasStartupValidator.validateRulesPerSecurityGroup(value)); + assertEquals("floci.services.servicequotas.rules-per-security-group must be positive", + error.getMessage()); + } + private static ServiceQuotasStartupValidator validator(int value) { EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); when(config.services().servicequotas().standardOnDemandVcpus()).thenReturn(value); + when(config.services().servicequotas().rulesPerSecurityGroup()).thenReturn(60); return new ServiceQuotasStartupValidator(config); } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationSecurityGroupUpdateRollbackIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationSecurityGroupUpdateRollbackIntegrationTest.java index f3f9790279..8d40ec7bee 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationSecurityGroupUpdateRollbackIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationSecurityGroupUpdateRollbackIntegrationTest.java @@ -17,8 +17,11 @@ import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * A stack update that changes an {@code AWS::EC2::SecurityGroup} in place and then fails on a later @@ -89,6 +92,42 @@ class CloudFormationSecurityGroupUpdateRollbackIntegrationTest { assertEquals(Map.of("external", "preserve"), tags(groupId)); } + @Test + void aFullGroupCanReplaceAnInlineRuleAndRollBackAtTheQuota() { + cfn.createStack(request -> request.stackName(stackName) + .templateBody(template(quotaIngress("10.65.0.0/24"), ""))); + stackCreated = true; + String groupId = CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE") + .outputs().getFirst().outputValue(); + assertEquals(60, ingressCidrs(groupId).size()); + + cfn.updateStack(request -> request.stackName(stackName) + .templateBody(template(quotaIngress("10.66.0.0/24"), ""))); + CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE"); + assertEquals(60, ingressCidrs(groupId).size()); + assertTrue(ingressCidrs(groupId).contains("10.66.0.0/24")); + + cfn.updateStack(request -> request.stackName(stackName) + .templateBody(template(quotaIngress("10.67.0.0/24"), failingResource()))); + CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_ROLLBACK_COMPLETE"); + Set afterRollback = ingressCidrs(groupId); + assertEquals(60, afterRollback.size()); + assertTrue(afterRollback.contains("10.66.0.0/24")); + assertFalse(afterRollback.contains("10.67.0.0/24")); + } + + private static String quotaIngress(String lastCidr) { + String firstRules = IntStream.range(0, 59) + .mapToObj(i -> "10.64." + i + ".0/24") + .map(CloudFormationSecurityGroupUpdateRollbackIntegrationTest::ingressRule) + .collect(Collectors.joining(",")); + return "\"SecurityGroupIngress\": [" + firstRules + "," + ingressRule(lastCidr) + "]"; + } + + private static String ingressRule(String cidr) { + return "{\"IpProtocol\":\"tcp\",\"FromPort\":443,\"ToPort\":443,\"CidrIp\":\"" + cidr + "\"}"; + } + private String template(String groupProperties, String moreResources) { return """ { @@ -124,6 +163,13 @@ class CloudFormationSecurityGroupUpdateRollbackIntegrationTest { return group.ipPermissions().stream().map(permission -> permission.fromPort()).collect(Collectors.toSet()); } + private Set ingressCidrs(String groupId) { + SecurityGroup group = ec2.describeSecurityGroups(request -> request.groupIds(groupId)).securityGroups() + .getFirst(); + return group.ipPermissions().stream().flatMap(permission -> permission.ipRanges().stream()) + .map(range -> range.cidrIp()).collect(Collectors.toSet()); + } + private Map tags(String groupId) { Map tags = new TreeMap<>(); ec2.describeTags(request -> request.filters(filter -> filter.name("resource-id").values(groupId))) diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2SecurityGroupRuleQuotaIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2SecurityGroupRuleQuotaIntegrationTest.java new file mode 100644 index 0000000000..a40d184309 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2SecurityGroupRuleQuotaIntegrationTest.java @@ -0,0 +1,226 @@ +package io.floci.aws.services.ec2; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.AddPrefixListEntry; +import software.amazon.awssdk.services.ec2.model.IpPermission; +import software.amazon.awssdk.services.ec2.model.IpRange; +import software.amazon.awssdk.services.ec2.model.Ipv6Range; +import software.amazon.awssdk.services.ec2.model.PrefixListId; + +import java.util.List; +import java.util.UUID; +import java.util.stream.IntStream; + +import static io.floci.aws.testing.AwsSdkErrors.assertAwsError; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +class Ec2SecurityGroupRuleQuotaIntegrationTest { + + @Test + void sixtyFirstIpv4IngressRuleFailsWithoutChangingTheGroup() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.85.0.0/16")).vpc().vpcId(); + String groupId = createGroup(ec2, vpcId); + try { + authorizeCidrs(ec2, groupId, false, 0, 60); + + assertAwsError("RulesPerSecurityGroupLimitExceeded", 400, + () -> authorizeCidrs(ec2, groupId, false, 60, 1)); + assertEquals(60, countRules(ec2, groupId, false)); + } finally { + ec2.deleteSecurityGroup(r -> r.groupId(groupId)); + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + + @Test + void aBatchThatCrossesTheQuotaDoesNotStoreAnyRule() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.86.0.0/16")).vpc().vpcId(); + String groupId = createGroup(ec2, vpcId); + try { + authorizeCidrs(ec2, groupId, false, 0, 59); + assertAwsError("RulesPerSecurityGroupLimitExceeded", 400, + () -> authorizeCidrs(ec2, groupId, false, 60, 2)); + assertEquals(59, countRules(ec2, groupId, false)); + } finally { + ec2.deleteSecurityGroup(r -> r.groupId(groupId)); + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + + @Test + void outboundQuotaIncludesTheDefaultRule() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.87.0.0/16")).vpc().vpcId(); + String groupId = createGroup(ec2, vpcId); + try { + assertEquals(1, countRules(ec2, groupId, true)); + authorizeCidrs(ec2, groupId, true, 0, 59); + assertAwsError("RulesPerSecurityGroupLimitExceeded", 400, + () -> authorizeCidrs(ec2, groupId, true, 60, 1)); + assertEquals(60, countRules(ec2, groupId, true)); + } finally { + ec2.deleteSecurityGroup(r -> r.groupId(groupId)); + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + + @Test + void awsManagedPrefixListsUsePublishedWeights() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.88.0.0/16")).vpc().vpcId(); + String cloudFrontGroup = createGroup(ec2, vpcId); + String s3Group = createGroup(ec2, vpcId); + try { + authorizeCidrs(ec2, cloudFrontGroup, false, 0, 5); + authorizePrefixList(ec2, cloudFrontGroup, "pl-3b927c52"); + assertAwsError("RulesPerSecurityGroupLimitExceeded", 400, + () -> authorizeCidrs(ec2, cloudFrontGroup, false, 6, 1)); + assertEquals(6, countRules(ec2, cloudFrontGroup, false)); + + authorizeCidrs(ec2, s3Group, false, 0, 59); + authorizePrefixList(ec2, s3Group, "pl-63a5400a"); + assertAwsError("RulesPerSecurityGroupLimitExceeded", 400, + () -> authorizeCidrs(ec2, s3Group, false, 60, 1)); + assertEquals(60, countRules(ec2, s3Group, false)); + } finally { + ec2.deleteSecurityGroup(r -> r.groupId(cloudFrontGroup)); + ec2.deleteSecurityGroup(r -> r.groupId(s3Group)); + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + + @Test + void customerManagedPrefixListUsesMaxEntriesRatherThanCurrentEntryCount() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.89.0.0/16")).vpc().vpcId(); + String groupId = createGroup(ec2, vpcId); + String listId = createTwentyEntryPrefixList(ec2); + try { + authorizeCidrs(ec2, groupId, false, 0, 40); + authorizePrefixList(ec2, groupId, listId); + assertAwsError("RulesPerSecurityGroupLimitExceeded", 400, + () -> authorizeCidrs(ec2, groupId, false, 41, 1)); + assertEquals(41, countRules(ec2, groupId, false)); + } finally { + ec2.deleteSecurityGroup(r -> r.groupId(groupId)); + ec2.deleteManagedPrefixList(r -> r.prefixListId(listId)); + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + + @Test + void resizingAReferencedListCannotExceedTheGroupRuleQuota() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.92.0.0/16")).vpc().vpcId(); + String groupId = createGroup(ec2, vpcId); + String listId = createTwentyEntryPrefixList(ec2); + try { + authorizeCidrs(ec2, groupId, false, 0, 40); + authorizePrefixList(ec2, groupId, listId); + assertAwsError("RulesPerSecurityGroupLimitExceeded", 400, + () -> ec2.modifyManagedPrefixList(r -> r.prefixListId(listId).maxEntries(21))); + assertEquals(20, ec2.describeManagedPrefixLists(r -> r.prefixListIds(listId)) + .prefixLists().getFirst().maxEntries()); + assertEquals(41, countRules(ec2, groupId, false)); + } finally { + ec2.deleteSecurityGroup(r -> r.groupId(groupId)); + ec2.deleteManagedPrefixList(r -> r.prefixListId(listId)); + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + + @Test + void prefixListWeightCountsAgainstBothAddressFamilies() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.91.0.0/16")).vpc().vpcId(); + String groupId = createGroup(ec2, vpcId); + try { + fillIpv6IngressQuota(ec2, groupId); + assertAwsError("RulesPerSecurityGroupLimitExceeded", 400, + () -> authorizePrefixList(ec2, groupId, "pl-63a5400a")); + assertEquals(60, countRules(ec2, groupId, false)); + } finally { + ec2.deleteSecurityGroup(r -> r.groupId(groupId)); + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + + @Test + void ipv4AndIpv6RulesHaveSeparateQuotaPools() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String vpcId = ec2.createVpc(r -> r.cidrBlock("10.90.0.0/16")).vpc().vpcId(); + String groupId = createGroup(ec2, vpcId); + try { + authorizeCidrs(ec2, groupId, false, 0, 60); + fillIpv6IngressQuota(ec2, groupId); + assertEquals(120, countRules(ec2, groupId, false)); + assertAwsError("RulesPerSecurityGroupLimitExceeded", 400, + () -> ec2.authorizeSecurityGroupIngress(r -> r.groupId(groupId).ipPermissions( + IpPermission.builder().ipProtocol("tcp").fromPort(443).toPort(443) + .ipv6Ranges(Ipv6Range.builder().cidrIpv6("2001:db8:3c::/48") + .build()).build()))); + } finally { + ec2.deleteSecurityGroup(r -> r.groupId(groupId)); + ec2.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + + private static String createGroup(Ec2Client ec2, String vpcId) { + return ec2.createSecurityGroup(r -> r.groupName("quota-" + UUID.randomUUID()) + .description("rule quota regression").vpcId(vpcId)).groupId(); + } + + private static String createTwentyEntryPrefixList(Ec2Client ec2) { + return ec2.createManagedPrefixList(r -> r.prefixListName("quota-" + UUID.randomUUID()) + .addressFamily("IPv4").maxEntries(20) + .entries(AddPrefixListEntry.builder().cidr("192.0.2.0/24").build())) + .prefixList().prefixListId(); + } + + private static void authorizeCidrs(Ec2Client ec2, String groupId, boolean egress, int start, int count) { + List ranges = IntStream.range(start, start + count) + .mapToObj(i -> IpRange.builder().cidrIp("10.1." + i + ".0/24").build()).toList(); + IpPermission permission = IpPermission.builder().ipProtocol("tcp").fromPort(443).toPort(443) + .ipRanges(ranges).build(); + if (egress) { + ec2.authorizeSecurityGroupEgress(r -> r.groupId(groupId).ipPermissions(permission)); + } else { + ec2.authorizeSecurityGroupIngress(r -> r.groupId(groupId).ipPermissions(permission)); + } + } + + private static void fillIpv6IngressQuota(Ec2Client ec2, String groupId) { + List ipv6 = IntStream.range(0, 60) + .mapToObj(i -> Ipv6Range.builder() + .cidrIpv6("2001:db8:" + Integer.toHexString(i) + "::/48").build()).toList(); + ec2.authorizeSecurityGroupIngress(r -> r.groupId(groupId).ipPermissions( + IpPermission.builder().ipProtocol("tcp").fromPort(443).toPort(443) + .ipv6Ranges(ipv6).build())); + } + + private static void authorizePrefixList(Ec2Client ec2, String groupId, String prefixListId) { + ec2.authorizeSecurityGroupIngress(r -> r.groupId(groupId).ipPermissions( + IpPermission.builder().ipProtocol("tcp").fromPort(443).toPort(443) + .prefixListIds(PrefixListId.builder().prefixListId(prefixListId).build()).build())); + } + + private static long countRules(Ec2Client ec2, String groupId, boolean egress) { + return ec2.describeSecurityGroupRules(r -> r.filters(f -> f.name("group-id").values(groupId))) + .securityGroupRules().stream().filter(rule -> rule.isEgress() == egress).count(); + } +} diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java index 4857323546..4f722e3e36 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java @@ -7794,16 +7794,22 @@ class Ec2ServiceTest { Path catalog = temp.resolve("prefix-lists.json"); Files.writeString(catalog, """ {"eu-west-1": [{"prefixListId": "pl-0123456789abcdef0", - "prefixListName": "example-managed-service", "cidrs": ["192.0.2.19/24"]}]} + "prefixListName": "example-managed-service", "weight": 6, + "cidrs": ["192.0.2.19/24"]}]} """); EmulatorConfig config = mockConfig(true); when(config.services().ec2().enabled()).thenReturn(true); + when(config.services().ec2().enforceSecurityGroupRuleQuota()).thenReturn(true); + EmulatorConfig.ServiceQuotasServiceConfig quotas = mock(EmulatorConfig.ServiceQuotasServiceConfig.class); + when(config.services().servicequotas()).thenReturn(quotas); + when(config.services().servicequotas().rulesPerSecurityGroup()).thenReturn(6); when(config.services().ec2().managedPrefixListCatalogPath()).thenReturn(Optional.of(catalog.toString())); Ec2Service service = mockModeService(config); String id = "pl-0123456789abcdef0"; ManagedPrefixList managed = service.describeManagedPrefixLists("eu-west-1", List.of(id), Map.of()).getFirst(); assertTrue(managed.isAwsManaged()); + assertEquals(6, managed.getQuotaWeight()); assertEquals("AWS", managed.getOwnerId()); assertEquals("IPv4", managed.getAddressFamily()); assertEquals("arn:aws:ec2:eu-west-1:aws:prefix-list/" + id, managed.getPrefixListArn()); @@ -7824,6 +7830,55 @@ class Ec2ServiceTest { permission.getPrefixListIds().add(new PrefixListId(id, null)); assertEquals(id, service.authorizeSecurityGroupIngress("eu-west-1", groupId, List.of(permission)) .getFirst().getPrefixListId()); + IpPermission extra = tcpPermission(443); + extra.getIpRanges().add(new IpRange("198.51.100.0/24", null)); + assertEquals("RulesPerSecurityGroupLimitExceeded", assertThrows(AwsException.class, + () -> service.authorizeSecurityGroupIngress("eu-west-1", groupId, List.of(extra))).getErrorCode()); + } + + @Test + void enforcedQuotaAcceptsLegacyAwsManagedPrefixListWithoutWeight(@TempDir Path temp) throws IOException { + Path catalog = temp.resolve("prefix-lists.json"); + Files.writeString(catalog, """ + {"eu-west-1": [{"prefixListId": "pl-0123456789abcdef0", + "prefixListName": "example-managed-service", "cidrs": ["192.0.2.0/24"]}]} + """); + EmulatorConfig config = mockConfig(true); + when(config.services().ec2().enabled()).thenReturn(true); + when(config.services().ec2().enforceSecurityGroupRuleQuota()).thenReturn(true); + when(config.services().ec2().managedPrefixListCatalogPath()).thenReturn(Optional.of(catalog.toString())); + Ec2Service service = mockModeService(config); + assertEquals(1, service.describeManagedPrefixLists("eu-west-1", + List.of("pl-0123456789abcdef0"), Map.of()).getFirst().getQuotaWeight()); + } + + @Test + void aReferencedCustomerManagedPrefixListCannotBeDeleted() { + EmulatorConfig config = mockConfig(true); + when(config.services().ec2().enforceSecurityGroupRuleQuota()).thenReturn(true); + EmulatorConfig.ServiceQuotasServiceConfig quotas = mock(EmulatorConfig.ServiceQuotasServiceConfig.class); + when(config.services().servicequotas()).thenReturn(quotas); + when(quotas.rulesPerSecurityGroup()).thenReturn(60); + Ec2Service service = mockModeService(config); + ManagedPrefixList list = service.createManagedPrefixList("us-east-1", "in-use", "IPv4", 20, + List.of(), List.of()); + String groupId = service.createSecurityGroup("us-east-1", "consumer", "consumer", null).getGroupId(); + IpPermission permission = tcpPermission(443); + permission.getPrefixListIds().add(new PrefixListId(list.getPrefixListId(), null)); + service.authorizeSecurityGroupIngress("us-east-1", groupId, List.of(permission)); + + AwsException error = assertThrows(AwsException.class, + () -> service.deleteManagedPrefixList("us-east-1", list.getPrefixListId())); + assertEquals("DependencyViolation", error.getErrorCode()); + assertEquals(20, service.describeManagedPrefixLists("us-east-1", + List.of(list.getPrefixListId()), Map.of()).getFirst().getMaxEntries()); + + IpPermission extra = tcpPermission(443); + extra.getIpRanges().add(new IpRange("192.0.2.0/24", null)); + assertEquals(1, service.authorizeSecurityGroupIngress("us-east-1", groupId, List.of(extra)).size()); + service.revokeSecurityGroupIngress("us-east-1", groupId, List.of(permission)); + assertEquals("delete-complete", service.deleteManagedPrefixList("us-east-1", + list.getPrefixListId()).getState()); } @ParameterizedTest diff --git a/src/test/java/io/floci/aws/services/servicequotas/ServiceQuotasServiceTest.java b/src/test/java/io/floci/aws/services/servicequotas/ServiceQuotasServiceTest.java index 6bd2b5264a..458721d2f6 100644 --- a/src/test/java/io/floci/aws/services/servicequotas/ServiceQuotasServiceTest.java +++ b/src/test/java/io/floci/aws/services/servicequotas/ServiceQuotasServiceTest.java @@ -35,6 +35,7 @@ class ServiceQuotasServiceTest { private static EmulatorConfig defaultConfig() { EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); when(config.services().servicequotas().standardOnDemandVcpus()).thenReturn(5); + when(config.services().servicequotas().rulesPerSecurityGroup()).thenReturn(60); return config; } @@ -126,8 +127,10 @@ class ServiceQuotasServiceTest { void vpcResolvesRealQuotaCodesWithNamesThroughGetAndList() { Map want = Map.of( "L-FE5A380F", "NAT gateways per Availability Zone", - "L-2AEEBF1A", "Rules per network ACL"); - Map defaults = Map.of("L-FE5A380F", 5.0, "L-2AEEBF1A", 20.0); + "L-2AEEBF1A", "Rules per network ACL", + "L-0EA8095F", "Inbound or outbound rules per security group"); + Map defaults = Map.of("L-FE5A380F", 5.0, "L-2AEEBF1A", 20.0, + "L-0EA8095F", 60.0); for (Map.Entry e : want.entrySet()) { JsonNode quota = service.getServiceQuota("vpc", e.getKey(), "us-east-1", "000000000000").path("Quota"); assertEquals(e.getKey(), quota.path("QuotaCode").asString()); @@ -142,6 +145,21 @@ class ServiceQuotasServiceTest { assertEquals(want.size() + 3, listed.size(), "synthetic quotas still appended: " + listed); } + @Test + void configuredSecurityGroupRuleQuotaChangesAppliedValueButNotAwsDefault() { + EmulatorConfig config = defaultConfig(); + when(config.services().servicequotas().rulesPerSecurityGroup()).thenReturn(80); + ServiceQuotasService configured = new ServiceQuotasService( + new InMemoryStorageFactory(ACCOUNT_ID), JacksonConfig.jsonMapper(), config); + String code = "L-0EA8095F"; + assertEquals(80.0, configured.getServiceQuota("vpc", code, "us-east-1", ACCOUNT_ID) + .path("Quota").path("Value").asDouble()); + assertEquals(80.0, configured.listServiceQuotas("vpc", code, null, null, null, "us-east-1", ACCOUNT_ID) + .path("Quotas").get(0).path("Value").asDouble()); + assertEquals(60.0, configured.getAwsDefaultServiceQuota("vpc", code, "us-east-1", ACCOUNT_ID) + .path("Quota").path("Value").asDouble()); + } + @Test void vpcUnknownQuotaCodeStillThrowsNoSuchResource() { AwsException e = assertThrows(AwsException.class, diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 03d838ba97..65075f22a9 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -358,6 +358,7 @@ floci: ec2: # Opt-in Standard On-Demand vCPU admission. FLOCI_SERVICES_EC2_ENFORCE_VCPU_QUOTAS enforce-vcpu-quotas: false + enforce-security-group-rule-quota: true # Optional complete catalog override for locally built guest images. image-catalog-path: ${FLOCI_SERVICES_EC2_IMAGE_CATALOG_PATH:} managed-prefix-list-catalog-path: ${FLOCI_SERVICES_EC2_MANAGED_PREFIX_LIST_CATALOG_PATH:} @@ -625,6 +626,7 @@ floci: servicequotas: enabled: true standard-on-demand-vcpus: 5 + rules-per-security-group: 60 verifiedpermissions: enabled: true ram: