feat(ec2): IPAM with real CIDR allocation, EBS encryption defaults, and transit gateway route export (#2596)

* feat(ec2): add IPAM model, CIDR math and Ec2IpamService

Emulates VPC IPAM: organization admin delegation, IPAMs with default scopes, hierarchical pools with provisioned CIDRs, and netmask/specific-CIDR allocations that skip space held by allocations and child pools. This is the surface LZA needs for Custom::EnableIpamOrganizationAdminAccount (Organization stage) and the get-ipam-subnet-cidr Lambda (Deploy stage).

* feat(ec2): wire IPAM actions into the EC2 query handler

Adds 13 dispatch arms and XML writers: enable/disable org admin, IPAM and pool CRUD, provisioned CIDR reads, and pool CIDR allocate/release/list.

* test(ec2): construct Ec2QueryHandler with the IPAM service

* feat(storage): add OwnedEntry/findAnyAccount helpers

Extracted from 9dfda3cb (fix(s3): resolve buckets cross-account under
a global bucket namespace) — that commit's storage-layer helpers are a
genuine prerequisite for the Route 53 VPC associations work that follows,
but its full diff also carries an unrelated S3 replication feature chain.
This isolates just the additive AccountAwareStorageBackend.OwnedEntry /
findAnyAccount / findAnyAccountEntry helpers those commits need.

* feat(ec2): add owner-account overload for createIpamPool

Adds a createIpamPool overload taking an explicit ownerId, with the 6-arg
form delegating to it using the ambient default account. Purely additive
delegation; existing callers are unaffected.

Provenance: extracted verbatim from 91b93aab ("fix(ec2): stamp IPAM and IPAM
pool ownerId with the resolved account"), which is otherwise CloudFormation
provisioning work and remains on hold. Only the Ec2IpamService method is taken
here — none of that commit's Cfn provisioner files are included. The overload
itself touches no CloudFormation code; it is needed because account-scoped IPAM
tests construct pools for an explicit owning account.

* feat(ec2): add IPAM ASN associations and discovery operations

* fix: preserve shared IPAM pool ownership

* feat(ec2): add ModifyIpamPool

Net-new operation, part of the deferred 16-op EC2 IPAM/TransitGateway
P0 block. IpamPool gains autoImport, allocationMinNetmaskLength,
allocationMaxNetmaskLength, and allocationDefaultNetmaskLength fields
(the CIDR allocation defaults real ModifyIpamPool controls); resource
tag add/remove is out of scope for this pass.

Persists through the existing requireOwnedPool/savePool account-scoped
helpers, matching every other pool mutation in this service.

* feat(ec2): EBS account-level encryption defaults

Adds Get/Enable/DisableEbsEncryptionByDefault and
Get/Modify/ResetEbsDefaultKmsKeyId, region-scoped with the AWS-managed
alias/aws/ebs fallback. LZA's SecurityStack
Custom::EnableEbsEncryptionByDefault Lambda calls these and previously
failed with UnsupportedOperation.

* test(ec2): construct Ec2QueryHandler with the EBS encryption service

* feat(ec2): add GetSecurityGroupsForVpc and ModifyVpcEndpoint

Two of the deferred 16-op EC2 IPAM/TransitGateway P0 block; grouped
together since neither has ties to IPAM or TransitGateway and there
was no existing feature branch for standalone VPC-endpoint/
security-group work.

GetSecurityGroupsForVpc filters the existing security group store by
vpcId, using the simplified SecurityGroupForVpc response shape (no
ipPermissions) per the real API. ModifyVpcEndpoint adds a
policyDocument field to VpcEndpoint plus add/remove-list handling for
route tables, subnets, and security groups; IpAddressType/DnsOptions/
SubnetConfigurations are out of scope for this pass.

New branch cut from main (both ops depend only on core SecurityGroup/
VpcEndpoint infra that already lives there, not on any in-flight
feature branch's work).

* feat(ec2): add ExportTransitGatewayRoutes

No real S3 write happens: the operation validates the route table and
bucket, then returns a deterministic s3:// location string matching the
real operation's export naming convention.

* fix(ec2): honour ClientToken on the IPAM pool creates and allocations

* fix(ec2): keep IPAM and IPAM-pool mutations owner-only

* fix(ec2): return MissingParameter for absent IPAM pool and scope ids

* fix(ec2): store the IPAM delegated administrator organization-wide

* test(ec2): cover IPAM ClientToken idempotency at the wire level

* docs(ec2): document the IPAM operations

* docs(ec2): document the EBS encryption defaults and the other branch-added operations

* fix(ec2): drop the ModifyVpcEndpoint copy superseded by upstream #2526

Upstream landed its own ModifyVpcEndpoint (2e8cbc13d), so the branch
copy became a duplicate case label, a duplicate handler and service
method, and a doubled policyDocument element in vpcEndpointXml. The
branch wire tests now exercise the upstream implementation and pass
unchanged. GetSecurityGroupsForVpc from the same original commit is
not upstream and stays.

* fix(ec2): enforce the modelled IPAM enums on create and modify

Tier, MeteredAccount and AddressFamily are all modelled enums, and all
three were stored verbatim. CreateIpam and ModifyIpam wrote whatever
arrived into the IPAM and DescribeIpams echoed it back; CreateIpamPool did
the same with AddressFamily, which is worse than cosmetic — it is what
decides how the pool's CIDRs are parsed and allocated, so a pool created
with a third address family is a pool whose CIDR math never made sense.

Reject an unmodelled value with InvalidParameterValue, the code the rest
of this service already answers for a bad parameter. An absent value still
falls through to the AWS default, since every one of these members is
optional.

* fix(ec2): report the calling account as IPAM owner and harden IPAM input parsing

- CreateIpam/CreateIpamPool recorded config.defaultAccountId() as owner
  while account-aware storage partitioned by the caller, so a non-default
  account got resources whose ownerId and ARN named the wrong account.
  The handler now passes null and the service resolves null-means-caller
  with the same fallback chain storage uses.
- The ContextNotActiveException fallback in callerAccountId() now logs at
  debug so an unexpected context loss is diagnosable.
- Netmask-length parameters on ModifyIpamPool and AllocateIpamPoolCidr go
  through parseOptionalInt, returning InvalidParameterValue instead of an
  unmapped NumberFormatException on non-integer input.
- ReleaseIpamPoolAllocation's not-found message names the CIDR when no
  allocation id was supplied instead of rendering 'Allocation null'.
- Reworded the ExportTransitGatewayRoutes Javadoc: the S3 location has a
  unique random suffix, it is not deterministic.

* fix(ec2): require management account for IPAM org-admin delegation

EnableIpamOrganizationAdminAccount and DisableIpamOrganizationAdminAccount
never checked the calling account, so any member account could change or
remove the org-wide IPAM delegated administrator. Real AWS restricts both
operations to the organization's management account.

This emulator has no cross-service organization membership to resolve the
true management account from, so the configured default account stands in
for it — the same account launched Lambdas resolve to when calling without
an assumed role, matching how LZA's Organization-stage custom resource
invokes these operations.

* test(ec2): verify the IPAM org-admin gate against the real query path

Confirms EnableIpamOrganizationAdminAccount/DisableIpamOrganizationAdminAccount
succeed over the actual query-protocol endpoint using the same non-12-digit
credential style every other test in this suite uses, which
AccountContextFilter/AccountResolver resolve to the configured default
account -- the same resolution LZA's Organization-stage custom resource
relies on. Verifies 79bc8e251's management-account gate does not regress
that path.

* docs: drop the ec2 docs-drift tracking file, filed as floci-io/floci#2605

pgermosen's review on #2596 correctly flagged this file as a parallel,
invisible issue tracker that introduces a new top-level directory main
doesn't have, cites internal workflow details a maintainer can't act
on, and references a stale commit SHA unreachable from this branch's
history. The underlying finding (ten operations Ec2QueryHandler
dispatches with no docs row, predating this branch) is real and now
tracked as a GitHub issue instead.

* fix(ec2): use UnauthorizedOperation for the IPAM org-admin denial
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-26 23:24:56 -04:00
1 parent 0205e4ed7e
commit 9563b7ef08
24 files changed
+3693 -5

No files matched your search

@@ -0,0 +1,113 @@
package io.github.hectorvent.floci.services.ec2;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
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;
/**
* Integration tests for the EBS account-level encryption defaults via the EC2
* Query Protocol (form-encoded POST, XML response).
*
* <p>Mirrors the call sequence of LZA's {@code Custom::EnableEbsEncryptionByDefault}
* Lambda: enable + set the default KMS key on create, disable on delete.</p>
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class Ec2EbsEncryptionIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static final String KEY_ARN =
"arn:aws:kms:us-east-1:000000000000:key/12345678-1234-1234-1234-123456789012";
@Test
@Order(1)
void encryptionByDefaultStartsDisabled() {
given()
.formParam("Action", "GetEbsEncryptionByDefault")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body("GetEbsEncryptionByDefaultResponse.ebsEncryptionByDefault", equalTo("false"));
}
@Test
@Order(2)
void enableEncryptionByDefault() {
given()
.formParam("Action", "EnableEbsEncryptionByDefault")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("EnableEbsEncryptionByDefaultResponse.ebsEncryptionByDefault", equalTo("true"));
given()
.formParam("Action", "GetEbsEncryptionByDefault")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("GetEbsEncryptionByDefaultResponse.ebsEncryptionByDefault", equalTo("true"));
}
@Test
@Order(3)
void modifyDefaultKmsKeyId() {
given()
.formParam("Action", "ModifyEbsDefaultKmsKeyId")
.formParam("KmsKeyId", KEY_ARN)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ModifyEbsDefaultKmsKeyIdResponse.kmsKeyId", equalTo(KEY_ARN));
given()
.formParam("Action", "GetEbsDefaultKmsKeyId")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("GetEbsDefaultKmsKeyIdResponse.kmsKeyId", equalTo(KEY_ARN));
}
@Test
@Order(4)
void resetDefaultKmsKeyId() {
given()
.formParam("Action", "ResetEbsDefaultKmsKeyId")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ResetEbsDefaultKmsKeyIdResponse.kmsKeyId", equalTo("alias/aws/ebs"));
}
@Test
@Order(5)
void disableEncryptionByDefault() {
given()
.formParam("Action", "DisableEbsEncryptionByDefault")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DisableEbsEncryptionByDefaultResponse.ebsEncryptionByDefault", equalTo("false"));
}
}
@@ -0,0 +1,65 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class Ec2EbsEncryptionServiceTest {
private Ec2EbsEncryptionService service;
@BeforeEach
void setUp() {
service = new Ec2EbsEncryptionService(new InMemoryStorage<>());
}
@Test
void encryptionByDefaultIsDisabledInitially() {
assertFalse(service.getEbsEncryptionByDefault("us-east-1"));
}
@Test
void enableAndDisableEncryptionByDefault() {
assertTrue(service.enableEbsEncryptionByDefault("us-east-1"));
assertTrue(service.getEbsEncryptionByDefault("us-east-1"));
assertFalse(service.disableEbsEncryptionByDefault("us-east-1"));
assertFalse(service.getEbsEncryptionByDefault("us-east-1"));
}
@Test
void encryptionByDefaultIsRegionScoped() {
service.enableEbsEncryptionByDefault("us-east-1");
assertTrue(service.getEbsEncryptionByDefault("us-east-1"));
assertFalse(service.getEbsEncryptionByDefault("eu-west-1"));
}
@Test
void defaultKmsKeyIdIsAwsManagedAlias() {
assertEquals("alias/aws/ebs", service.getEbsDefaultKmsKeyId("us-east-1"));
}
@Test
void modifyAndResetDefaultKmsKeyId() {
String keyArn = "arn:aws:kms:us-east-1:111122223333:key/12345678-1234-1234-1234-123456789012";
assertEquals(keyArn, service.modifyEbsDefaultKmsKeyId("us-east-1", keyArn));
assertEquals(keyArn, service.getEbsDefaultKmsKeyId("us-east-1"));
// The custom key applies only to the region it was set in.
assertEquals("alias/aws/ebs", service.getEbsDefaultKmsKeyId("eu-west-1"));
assertEquals("alias/aws/ebs", service.resetEbsDefaultKmsKeyId("us-east-1"));
assertEquals("alias/aws/ebs", service.getEbsDefaultKmsKeyId("us-east-1"));
}
@Test
void modifyDefaultKmsKeyIdRequiresKey() {
assertThrows(AwsException.class, () -> service.modifyEbsDefaultKmsKeyId("us-east-1", null));
assertThrows(AwsException.class, () -> service.modifyEbsDefaultKmsKeyId("us-east-1", " "));
}
}
@@ -0,0 +1,79 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
/**
* Wire-level tests for {@code ExportTransitGatewayRoutes}: no real S3 write happens — the
* operation returns an {@code s3://} location string (with a unique random suffix) matching
* the real operation's naming convention.
*/
@QuarkusTest
class Ec2ExportTransitGatewayRoutesConsumerTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ec2/aws4_request";
private String createTransitGateway() {
return given()
.formParam("Action", "CreateTransitGateway")
.formParam("Description", "export-routes-test-tgw")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateTransitGatewayResponse.transitGateway.transitGatewayId", startsWith("tgw-"))
.extract().path("CreateTransitGatewayResponse.transitGateway.transitGatewayId");
}
private String createRouteTable(String tgwId) {
return given()
.formParam("Action", "CreateTransitGatewayRouteTable")
.formParam("TransitGatewayId", tgwId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract()
.path("CreateTransitGatewayRouteTableResponse.transitGatewayRouteTable.transitGatewayRouteTableId");
}
@Test
void exportTransitGatewayRoutes_returnsS3Location() {
String tgwId = createTransitGateway();
String routeTableId = createRouteTable(tgwId);
given()
.formParam("Action", "ExportTransitGatewayRoutes")
.formParam("TransitGatewayRouteTableId", routeTableId)
.formParam("S3Bucket", "my-export-bucket")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ExportTransitGatewayRoutesResponse.s3Location", startsWith("s3://my-export-bucket/"));
}
@Test
void exportTransitGatewayRoutes_missingBucket_returnsAwsErrorShape() {
String tgwId = createTransitGateway();
String routeTableId = createRouteTable(tgwId);
given()
.formParam("Action", "ExportTransitGatewayRoutes")
.formParam("TransitGatewayRouteTableId", routeTableId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("MissingParameter"));
}
}
@@ -7,6 +7,8 @@ import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
@@ -3965,4 +3967,173 @@ class Ec2IntegrationTest {
.body("DescribeSecurityGroupRulesResponse.securityGroupRuleSet.item.securityGroupRuleId",
equalTo(ruleId));
}
@Test
@Order(321)
void modifyIpamUpdatesDescriptionAndOperatingRegionsOverQuery() {
String ipamId = given()
.formParam("Action", "CreateIpam")
.formParam("Description", "initial-ipam")
.formParam("OperatingRegion.1.RegionName", "us-east-1")
.formParam("OperatingRegion.2.RegionName", "us-west-1")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateIpamResponse.ipam.ipamId");
given()
.formParam("Action", "ModifyIpam")
.formParam("IpamId", ipamId)
.formParam("Description", "updated-ipam")
.formParam("AddOperatingRegion.1.RegionName", "us-west-2")
.formParam("RemoveOperatingRegion.1.RegionName", "us-east-1")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ModifyIpamResponse.ipam.ipamId", equalTo(ipamId))
.body("ModifyIpamResponse.ipam.description", equalTo("updated-ipam"))
.body("ModifyIpamResponse.ipam.operatingRegionSet.item.regionName",
hasItems("us-west-1", "us-west-2"));
given()
.formParam("Action", "DescribeIpams")
.formParam("IpamId.1", ipamId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeIpamsResponse.ipamSet.item.description", equalTo("updated-ipam"))
.body("DescribeIpamsResponse.ipamSet.item.operatingRegionSet.item.regionName",
hasItems("us-west-1", "us-west-2"))
.body("DescribeIpamsResponse.ipamSet.item.operatingRegionSet.item.regionName",
not(hasItem("us-east-1")));
}
@Test
@Order(322)
void modifyIpamUnknownIdsReturnAwsErrorShape() {
given()
.formParam("Action", "ModifyIpam")
.formParam("IpamId", "ipam-doesnotexist")
.formParam("Description", "updated-ipam")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidIpamId.NotFound"));
}
@Test
@Order(323)
void associateIpamByoasnSuccess() {
given()
.formParam("Action", "AssociateIpamByoasn")
.formParam("Asn", "65000")
.formParam("Cidr", "10.0.0.0/16")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("AssociateIpamByoasnResponse.asnAssociation.asn", equalTo("65000"))
.body("AssociateIpamByoasnResponse.asnAssociation.cidr", equalTo("10.0.0.0/16"))
.body("AssociateIpamByoasnResponse.asnAssociation.state", equalTo("associated"))
.body("AssociateIpamByoasnResponse.asnAssociation.statusMessage", equalTo(""));
}
@Test
@Order(324)
void associateIpamByoasnDryRunThrows() {
given()
.formParam("Action", "AssociateIpamByoasn")
.formParam("Asn", "65000")
.formParam("Cidr", "10.0.0.0/16")
.formParam("DryRun", "true")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(412)
.body("Response.Errors.Error.Code", equalTo("DryRunOperation"));
}
@Test
@Order(325)
void createIpamFullFieldsRoundTrip() {
String id = given()
.formParam("Action", "CreateIpam")
.formParam("ClientToken", "create-ipam-full-325")
.formParam("Description", "full-ipam")
.formParam("EnablePrivateGua", "true")
.formParam("MeteredAccount", "resource-owner")
.formParam("Tier", "advanced")
.formParam("OperatingRegion.1.RegionName", "us-east-1")
.formParam("TagSpecification.1.ResourceType", "ipam")
.formParam("TagSpecification.1.Tag.1.Key", "Name")
.formParam("TagSpecification.1.Tag.1.Value", "full")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("CreateIpamResponse.ipam.enablePrivateGua", equalTo("true"))
.body("CreateIpamResponse.ipam.meteredAccount", equalTo("resource-owner"))
.body("CreateIpamResponse.ipam.tier", equalTo("advanced"))
.body("CreateIpamResponse.ipam.tagSet.item.key", equalTo("Name"))
.extract().path("CreateIpamResponse.ipam.ipamId");
given().formParam("Action", "DescribeIpams").formParam("IpamId.1", id)
.header("Authorization", AUTH_HEADER).when().post("/").then().statusCode(200)
.body("DescribeIpamsResponse.ipamSet.item.ipamId", equalTo(id))
.body("DescribeIpamsResponse.ipamSet.item.tagSet.item.value", equalTo("full"));
}
@Test
@Order(326)
void createIpamDryRunDoesNotMutate() {
given().formParam("Action", "CreateIpam").formParam("ClientToken", "dry-run-326")
.formParam("DryRun", "true").header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(412)
.body("Response.Errors.Error.Code", equalTo("DryRunOperation"));
given().formParam("Action", "DescribeIpams").formParam("Filter.1.Name", "state")
.formParam("Filter.1.Value.1", "create-complete")
.header("Authorization", AUTH_HEADER).when().post("/").then().statusCode(200);
}
@Test
@Order(327)
void describeAndDisassociateIpamByoasn() {
given().formParam("Action", "AssociateIpamByoasn").formParam("Asn", "65001")
.formParam("Cidr", "10.1.0.0/16").header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200);
given().formParam("Action", "DescribeIpamByoasn").header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("DescribeIpamByoasnResponse.byoasnSet.item.asn", hasItem("65001"));
given().formParam("Action", "DisassociateIpamByoasn").formParam("Asn", "65001")
.formParam("Cidr", "10.1.0.0/16").header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200)
.body("DisassociateIpamByoasnResponse.asnAssociation.state", equalTo("disassociated"));
}
@Test
@Order(328)
void enableIpamOrganizationAdminAccountSucceedsForTheDefaultAccountCredential() {
// LZA's Organization-stage custom resource calls this over the query protocol with the
// same style of credential every other test in this suite uses (a non-12-digit access
// key, which AccountContextFilter/AccountResolver resolve to the configured default
// account). The management-account gate added alongside this test must not deny that
// path — only a caller whose credential resolves to a DIFFERENT 12-digit account should
// be denied.
given().formParam("Action", "EnableIpamOrganizationAdminAccount")
.formParam("DelegatedAdminAccountId", "111111111111")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200);
given().formParam("Action", "DisableIpamOrganizationAdminAccount")
.formParam("DelegatedAdminAccountId", "111111111111")
.header("Authorization", AUTH_HEADER)
.when().post("/").then().statusCode(200);
}
}
@@ -0,0 +1,174 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Wire-level tests for {@code ClientToken} idempotency on the IPAM allocation path.
*
* <p>LZA's {@code get-ipam-subnet-cidr} custom-resource Lambda retries
* {@code AllocateIpamPoolCidr} with the same token; before this was honoured each retry burned
* another distinct CIDR out of the pool. Service-level tests cover the dedupe itself, so what
* this class falsifies is the handler wiring — that {@code ClientToken} is read off the form
* post at all.
*/
@QuarkusTest
class Ec2IpamClientTokenConsumerTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ec2/aws4_request";
private String provisionedPool(String cidr) {
String ipamId = given()
.formParam("Action", "CreateIpam")
.formParam("Description", "client-token-test-ipam")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateIpamResponse.ipam.ipamId");
String scopeId = given()
.formParam("Action", "DescribeIpams")
.formParam("IpamId.1", ipamId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("DescribeIpamsResponse.ipamSet.item.privateDefaultScopeId");
String poolId = given()
.formParam("Action", "CreateIpamPool")
.formParam("IpamScopeId", scopeId)
.formParam("AddressFamily", "ipv4")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateIpamPoolResponse.ipamPool.ipamPoolId");
given()
.formParam("Action", "ProvisionIpamPoolCidr")
.formParam("IpamPoolId", poolId)
.formParam("Cidr", cidr)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
return poolId;
}
private String allocate(String poolId, String clientToken) {
return given()
.formParam("Action", "AllocateIpamPoolCidr")
.formParam("IpamPoolId", poolId)
.formParam("NetmaskLength", "24")
.formParam("Description", "lza subnet")
.formParam("ClientToken", clientToken)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("AllocateIpamPoolCidrResponse.ipamPoolAllocation.ipamPoolAllocationId");
}
@Test
void retryingAllocateIpamPoolCidrWithTheSameClientTokenReusesTheAllocation() {
String poolId = provisionedPool("10.0.0.0/16");
String first = allocate(poolId, "lza-retry-token");
String retry = allocate(poolId, "lza-retry-token");
assertEquals(first, retry);
given()
.formParam("Action", "GetIpamPoolAllocations")
.formParam("IpamPoolId", poolId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("GetIpamPoolAllocationsResponse.ipamPoolAllocationSet.item.cidr",
equalTo("10.0.0.0/24"));
}
@Test
void distinctClientTokensStillAllocateDistinctCidrs() {
String poolId = provisionedPool("10.1.0.0/16");
allocate(poolId, "token-one");
allocate(poolId, "token-two");
assertEquals(List.of("10.1.0.0/24", "10.1.1.0/24"), allocatedCidrs(poolId));
}
private List<String> allocatedCidrs(String poolId) {
return given()
.formParam("Action", "GetIpamPoolAllocations")
.formParam("IpamPoolId", poolId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath()
.getList("GetIpamPoolAllocationsResponse.ipamPoolAllocationSet.item.cidr", String.class);
}
@Test
void retryingProvisionIpamPoolCidrWithTheSameClientTokenProvisionsOnce() {
String poolId = provisionedPool("10.2.0.0/16");
for (int attempt = 0; attempt < 2; attempt++) {
given()
.formParam("Action", "ProvisionIpamPoolCidr")
.formParam("IpamPoolId", poolId)
.formParam("Cidr", "10.3.0.0/16")
.formParam("ClientToken", "provision-retry-token")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ProvisionIpamPoolCidrResponse.ipamPoolCidr.cidr", equalTo("10.3.0.0/16"));
}
List<String> provisioned = given()
.formParam("Action", "GetIpamPoolCidrs")
.formParam("IpamPoolId", poolId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath()
.getList("GetIpamPoolCidrsResponse.ipamPoolCidrSet.item.cidr", String.class);
assertEquals(List.of("10.2.0.0/16", "10.3.0.0/16"), provisioned,
"a replayed ClientToken must not provision the CIDR a second time");
}
@Test
void allocateIpamPoolCidrWithoutAPoolIdIsAMissingParameter() {
given()
.formParam("Action", "AllocateIpamPoolCidr")
.formParam("NetmaskLength", "24")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("MissingParameter"));
}
}
@@ -0,0 +1,62 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
/**
* Wire-level test that IPAM resources created by a non-default account report that account —
* not the emulator's default — as their owner. Account-aware storage already partitions by the
* caller, so an owner id taken from {@code config.defaultAccountId()} would disagree with the
* partition the resource actually lives in.
*/
@QuarkusTest
class Ec2IpamOwnerAccountConsumerTest {
private static final String CALLER = "222222222222";
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=" + CALLER + "/20260101/us-east-1/ec2/aws4_request";
@Test
void createIpamAndPoolReportTheCallingAccountAsOwner() {
String ipamId = given()
.formParam("Action", "CreateIpam")
.formParam("Description", "owner-account-test-ipam")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateIpamResponse.ipam.ownerId", equalTo(CALLER))
.body("CreateIpamResponse.ipam.ipamArn",
startsWith("arn:aws:ec2::" + CALLER + ":ipam/"))
.extract().path("CreateIpamResponse.ipam.ipamId");
String scopeId = given()
.formParam("Action", "DescribeIpams")
.formParam("IpamId.1", ipamId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeIpamsResponse.ipamSet.item.ownerId", equalTo(CALLER))
.extract().path("DescribeIpamsResponse.ipamSet.item.privateDefaultScopeId");
given()
.formParam("Action", "CreateIpamPool")
.formParam("IpamScopeId", scopeId)
.formParam("AddressFamily", "ipv4")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateIpamPoolResponse.ipamPool.ownerId", equalTo(CALLER))
.body("CreateIpamPoolResponse.ipamPool.ipamPoolArn",
startsWith("arn:aws:ec2::" + CALLER + ":ipam-pool/"));
}
}
@@ -0,0 +1,626 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ec2.model.Ipam;
import io.github.hectorvent.floci.services.ec2.model.IpamPool;
import io.github.hectorvent.floci.services.ec2.model.IpamPoolAllocation;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class Ec2IpamServiceTest {
private static final String REGION = "us-east-1";
private Ec2IpamService service;
@BeforeEach
void setUp() {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn("000000000000");
service = new Ec2IpamService(config,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
}
// --- organization admin delegation (the Organization-stage blocker, LZA
// Custom::EnableIpamOrganizationAdminAccount) ---
@Test
void enableIpamOrganizationAdminAccountRecordsTheDelegatedAdmin() {
assertTrue(service.enableIpamOrganizationAdminAccount("111111111111"));
assertEquals("111111111111", service.getIpamOrganizationAdminAccount().orElseThrow());
// enabling the same account again is idempotent, mirroring AWS
assertTrue(service.enableIpamOrganizationAdminAccount("111111111111"));
}
@Test
void enablingADifferentAccountWhileOneIsDelegatedThrows() {
service.enableIpamOrganizationAdminAccount("111111111111");
assertThrows(AwsException.class,
() -> service.enableIpamOrganizationAdminAccount("222222222222"));
}
@Test
void disableClearsTheDelegatedAdminAndRejectsMismatches() {
service.enableIpamOrganizationAdminAccount("111111111111");
assertThrows(AwsException.class,
() -> service.disableIpamOrganizationAdminAccount("222222222222"));
assertTrue(service.disableIpamOrganizationAdminAccount("111111111111"));
assertTrue(service.getIpamOrganizationAdminAccount().isEmpty());
}
@Test
@SuppressWarnings("unchecked")
void theDelegatedAdminIsVisibleFromEveryAccountButOnlyManagementCanEnableOrConflict() {
AtomicReference<String> caller = new AtomicReference<>("222222222222");
RequestContext requestContext = mock(RequestContext.class);
when(requestContext.getAccountId()).thenAnswer(invocation -> caller.get());
Instance<RequestContext> contextInstance = mock(Instance.class);
when(contextInstance.get()).thenReturn(requestContext);
AccountAwareStorageBackend<String> settings = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), contextInstance, "000000000000");
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn("222222222222");
Ec2IpamService orgService = new Ec2IpamService(config, new InMemoryStorage<>(),
new InMemoryStorage<>(), settings, new InMemoryStorage<>(), contextInstance);
orgService.enableIpamOrganizationAdminAccount("333333333333");
caller.set("111111111111");
assertEquals("333333333333", orgService.getIpamOrganizationAdminAccount().orElseThrow(),
"the delegated admin is an organization-wide setting, readable from any account");
AwsException conflict = assertThrows(AwsException.class,
() -> orgService.enableIpamOrganizationAdminAccount("444444444444"),
"a non-management member account must not be able to change the org-wide delegation");
assertEquals("UnauthorizedOperation", conflict.getErrorCode());
caller.set("222222222222");
AwsException error = assertThrows(AwsException.class,
() -> orgService.enableIpamOrganizationAdminAccount("444444444444"));
assertEquals("InvalidParameterValue", error.getErrorCode());
}
@Test
@SuppressWarnings("unchecked")
void onlyManagementAccountCanDisableTheDelegatedAdmin() {
AtomicReference<String> caller = new AtomicReference<>("222222222222");
RequestContext requestContext = mock(RequestContext.class);
when(requestContext.getAccountId()).thenAnswer(invocation -> caller.get());
Instance<RequestContext> contextInstance = mock(Instance.class);
when(contextInstance.get()).thenReturn(requestContext);
AccountAwareStorageBackend<String> settings = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), contextInstance, "000000000000");
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn("222222222222");
Ec2IpamService orgService = new Ec2IpamService(config, new InMemoryStorage<>(),
new InMemoryStorage<>(), settings, new InMemoryStorage<>(), contextInstance);
orgService.enableIpamOrganizationAdminAccount("333333333333");
caller.set("111111111111");
AwsException error = assertThrows(AwsException.class,
() -> orgService.disableIpamOrganizationAdminAccount("333333333333"),
"a non-management member account must not be able to remove the org-wide delegation");
assertEquals("UnauthorizedOperation", error.getErrorCode());
assertEquals("333333333333", orgService.getIpamOrganizationAdminAccount().orElseThrow());
caller.set("222222222222");
assertTrue(orgService.disableIpamOrganizationAdminAccount("333333333333"));
}
// --- IPAM + scopes ---
@Test
void createIpamCreatesDefaultScopesAndIsDescribable() {
Ipam ipam = service.createIpam(REGION, "test ipam", List.of(REGION));
assertTrue(ipam.getIpamId().startsWith("ipam-"));
assertTrue(ipam.getPrivateDefaultScopeId().startsWith("ipam-scope-"));
assertTrue(ipam.getPublicDefaultScopeId().startsWith("ipam-scope-"));
assertNotNull(ipam.getIpamArn());
List<Ipam> described = service.describeIpams(REGION, List.of());
assertEquals(1, described.size());
assertEquals(ipam.getIpamId(), described.get(0).getIpamId());
}
@Test
void createIpamPreservesFullFieldsAndClientTokenIsIdempotent() {
Ipam first = service.createIpam(REGION, "full", List.of(REGION, "us-west-2"),
"000000000000", true, "resource-owner", "advanced", "token-1",
List.of(new Tag("Name", "full")));
Ipam second = service.createIpam(REGION, "different", List.of(REGION),
"000000000000", false, "ipam-owner", "free", "token-1", List.of());
assertEquals(first.getIpamId(), second.getIpamId());
assertEquals(true, first.getEnablePrivateGua());
assertEquals("resource-owner", first.getMeteredAccount());
assertEquals("advanced", first.getTier());
assertEquals("full", first.getTags().getFirst().getValue());
}
@Test
void deleteIpamRemovesItAndUnknownIdsThrow() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
service.deleteIpam(REGION, ipam.getIpamId());
assertTrue(service.describeIpams(REGION, List.of()).isEmpty());
assertThrows(AwsException.class, () -> service.deleteIpam(REGION, "ipam-doesnotexist"));
}
@Test
void associateIpamByoasnStoresAssociation() {
service.associateIpamByoasn("us-east-1", "65000", "10.0.0.0/16");
assertTrue(service.hasAsnAssociation("us-east-1", "65000", "10.0.0.0/16"));
}
@Test
void associateIpamByoasnValidatesNullAndBlankInputs() {
assertThrows(AwsException.class, () -> service.associateIpamByoasn("us-east-1", null, "10.0.0.0/16"));
assertThrows(AwsException.class, () -> service.associateIpamByoasn("us-east-1", "", "10.0.0.0/16"));
assertThrows(AwsException.class, () -> service.associateIpamByoasn("us-east-1", "65000", null));
assertThrows(AwsException.class, () -> service.associateIpamByoasn("us-east-1", "65000", ""));
}
@Test
void associateIpamByoasnPersistsAcrossServiceInstances() {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn("000000000000");
InMemoryStorage<String, io.github.hectorvent.floci.services.ec2.model.AsnAssociation> backend = new InMemoryStorage<>();
Ec2IpamService firstService = new Ec2IpamService(config,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), backend);
firstService.associateIpamByoasn("us-west-2", "65001", "192.168.0.0/16");
Ec2IpamService secondService = new Ec2IpamService(config,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), backend);
assertTrue(secondService.hasAsnAssociation("us-west-2", "65001", "192.168.0.0/16"));
}
@Test
void modifyIpamUpdatesDescriptionAndOperatingRegions() {
Ipam ipam = service.createIpam(REGION, "initial", List.of(REGION, "us-west-1"));
Ipam modified = service.modifyIpam(
REGION,
ipam.getIpamId(),
"updated",
List.of("us-west-2", "us-west-1"),
List.of(REGION));
assertEquals("updated", modified.getDescription());
assertEquals(List.of("us-west-1", "us-west-2"), modified.getOperatingRegions());
assertEquals(modified.getIpamId(),
service.describeIpams(REGION, List.of(ipam.getIpamId())).getFirst().getIpamId());
}
@Test
void modifyIpamUnknownIdsThrow() {
AwsException error = assertThrows(AwsException.class,
() -> service.modifyIpam(REGION, "ipam-doesnotexist", "updated", List.of(), List.of()));
assertEquals("InvalidIpamId.NotFound", error.getErrorCode());
}
// --- pools + provisioned CIDRs ---
@Test
void createPoolProvisionCidrAndReadItBack() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
IpamPool pool = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", "global pool");
assertTrue(pool.getIpamPoolId().startsWith("ipam-pool-"));
service.provisionIpamPoolCidr(REGION, pool.getIpamPoolId(), "10.0.0.0/8");
var cidrs = service.getIpamPoolCidrs(REGION, pool.getIpamPoolId());
assertEquals(1, cidrs.size());
assertEquals("10.0.0.0/8", cidrs.get(0).getCidr());
assertEquals("provisioned", cidrs.get(0).getState());
}
@Test
void provisioningOutsideTheSourcePoolThrows() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
IpamPool parent = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", "parent");
service.provisionIpamPoolCidr(REGION, parent.getIpamPoolId(), "10.0.0.0/8");
IpamPool child = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, parent.getIpamPoolId(), "ipv4", "child");
service.provisionIpamPoolCidr(REGION, child.getIpamPoolId(), "10.0.0.0/12");
assertThrows(AwsException.class,
() -> service.provisionIpamPoolCidr(REGION, child.getIpamPoolId(), "192.168.0.0/16"));
}
@Test
void describeIpamPoolsFiltersById() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
IpamPool pool = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", null);
assertEquals(1, service.describeIpamPools(REGION, List.of(pool.getIpamPoolId())).size());
assertThrows(AwsException.class,
() -> service.describeIpamPools(REGION, List.of("ipam-pool-doesnotexist")));
}
@Test
void omittingIpamPoolIdIsAMissingParameterNotANotFound() {
for (Executable call : List.<Executable>of(
() -> service.deleteIpamPool(REGION, null),
() -> service.modifyIpamPool(REGION, "", "d", null, null, null, null, false),
() -> service.provisionIpamPoolCidr(REGION, null, "10.0.0.0/8"),
() -> service.getIpamPoolCidrs(REGION, ""),
() -> service.allocateIpamPoolCidr(REGION, null, 24, null, null),
() -> service.releaseIpamPoolAllocation(REGION, "", "alloc", null),
() -> service.getIpamPoolAllocations(REGION, null))) {
AwsException error = assertThrows(AwsException.class, call);
assertEquals("MissingParameter", error.getErrorCode());
}
}
@Test
void createIpamPoolRejectsMissingAndUnknownScopes() {
AwsException missing = assertThrows(AwsException.class,
() -> service.createIpamPool(REGION, null, REGION, null, "ipv4", null));
assertEquals("MissingParameter", missing.getErrorCode());
AwsException unknown = assertThrows(AwsException.class,
() -> service.createIpamPool(REGION, "ipam-scope-doesnotexist", REGION, null, "ipv4", null));
assertEquals("InvalidIpamScopeId.NotFound", unknown.getErrorCode());
}
@Test
void createIpamPoolRejectsABlankSourcePoolIdAsTheSourceParameter() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
AwsException error = assertThrows(AwsException.class,
() -> service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, "", "ipv4", null));
assertEquals("MissingParameter", error.getErrorCode());
assertTrue(error.getMessage().contains("SourceIpamPoolId"),
"a blank SourceIpamPoolId must not be reported as a missing IpamPoolId");
}
// --- allocations (what LZA's get-ipam-subnet-cidr Lambda needs) ---
private IpamPool poolWith(String... provisionedCidrs) {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
IpamPool pool = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", null);
for (String cidr : provisionedCidrs) {
service.provisionIpamPoolCidr(REGION, pool.getIpamPoolId(), cidr);
}
return pool;
}
@Test
void allocateByNetmaskHandsOutSequentialFreeBlocks() {
IpamPool pool = poolWith("10.0.0.0/16");
IpamPoolAllocation first =
service.allocateIpamPoolCidr(REGION, pool.getIpamPoolId(), 24, null, null);
IpamPoolAllocation second =
service.allocateIpamPoolCidr(REGION, pool.getIpamPoolId(), 24, null, null);
assertEquals("10.0.0.0/24", first.getCidr());
assertEquals("10.0.1.0/24", second.getCidr());
assertTrue(first.getIpamPoolAllocationId().startsWith("ipam-pool-alloc-"));
}
@Test
void allocateSkipsSpaceProvisionedToChildPools() {
IpamPool parent = poolWith("10.0.0.0/16");
IpamPool child = service.createIpamPool(REGION,
service.describeIpamPools(REGION, List.of(parent.getIpamPoolId()))
.get(0).getIpamScopeId(),
REGION, parent.getIpamPoolId(), "ipv4", "child");
service.provisionIpamPoolCidr(REGION, child.getIpamPoolId(), "10.0.0.0/24");
IpamPoolAllocation alloc =
service.allocateIpamPoolCidr(REGION, parent.getIpamPoolId(), 24, null, null);
assertEquals("10.0.1.0/24", alloc.getCidr());
}
@Test
void allocateSpecificCidrAndRejectOverlap() {
IpamPool pool = poolWith("10.0.0.0/16");
IpamPoolAllocation alloc =
service.allocateIpamPoolCidr(REGION, pool.getIpamPoolId(), null, "10.0.5.0/24", null);
assertEquals("10.0.5.0/24", alloc.getCidr());
assertThrows(AwsException.class,
() -> service.allocateIpamPoolCidr(REGION, pool.getIpamPoolId(), null, "10.0.5.128/25", null));
}
@Test
void allocationExhaustionThrows() {
IpamPool pool = poolWith("10.0.0.0/24");
service.allocateIpamPoolCidr(REGION, pool.getIpamPoolId(), 24, null, null);
assertThrows(AwsException.class,
() -> service.allocateIpamPoolCidr(REGION, pool.getIpamPoolId(), 24, null, null));
}
@Test
void releaseFreesTheAllocationForReuse() {
IpamPool pool = poolWith("10.0.0.0/24");
IpamPoolAllocation alloc =
service.allocateIpamPoolCidr(REGION, pool.getIpamPoolId(), 24, null, null);
assertTrue(service.releaseIpamPoolAllocation(REGION, pool.getIpamPoolId(),
alloc.getIpamPoolAllocationId(), alloc.getCidr()));
IpamPoolAllocation again =
service.allocateIpamPoolCidr(REGION, pool.getIpamPoolId(), 24, null, null);
assertEquals("10.0.0.0/24", again.getCidr());
}
@Test
void getIpamPoolAllocationsListsLiveAllocations() {
IpamPool pool = poolWith("10.0.0.0/16");
service.allocateIpamPoolCidr(REGION, pool.getIpamPoolId(), 24, null, "subnet-a");
service.allocateIpamPoolCidr(REGION, pool.getIpamPoolId(), 24, null, "subnet-b");
assertEquals(2, service.getIpamPoolAllocations(REGION, pool.getIpamPoolId()).size());
}
// --- ClientToken idempotency (LZA's get-ipam-subnet-cidr custom resource retries
// AllocateIpamPoolCidr; a replay must not burn a second CIDR out of the pool) ---
@Test
void replayingAnAllocationClientTokenReturnsTheOriginalAllocation() {
IpamPool pool = poolWith("10.0.0.0/16");
IpamPoolAllocation first = service.allocateIpamPoolCidr(
REGION, pool.getIpamPoolId(), 24, null, "subnet-a", "alloc-token");
IpamPoolAllocation replay = service.allocateIpamPoolCidr(
REGION, pool.getIpamPoolId(), 24, null, "subnet-a", "alloc-token");
assertEquals(first.getIpamPoolAllocationId(), replay.getIpamPoolAllocationId());
assertEquals(first.getCidr(), replay.getCidr());
assertEquals(1, service.getIpamPoolAllocations(REGION, pool.getIpamPoolId()).size(),
"a replayed ClientToken must not consume a second CIDR");
}
@Test
void distinctAllocationClientTokensStillConsumeDistinctCidrs() {
IpamPool pool = poolWith("10.0.0.0/16");
IpamPoolAllocation first = service.allocateIpamPoolCidr(
REGION, pool.getIpamPoolId(), 24, null, null, "token-a");
IpamPoolAllocation second = service.allocateIpamPoolCidr(
REGION, pool.getIpamPoolId(), 24, null, null, "token-b");
assertEquals("10.0.0.0/24", first.getCidr());
assertEquals("10.0.1.0/24", second.getCidr());
}
@Test
void replayingAProvisionClientTokenReturnsTheOriginalCidr() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
IpamPool pool = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", null);
service.provisionIpamPoolCidr(REGION, pool.getIpamPoolId(), "10.0.0.0/8", "provision-token");
service.provisionIpamPoolCidr(REGION, pool.getIpamPoolId(), "10.0.0.0/8", "provision-token");
assertEquals(1, service.getIpamPoolCidrs(REGION, pool.getIpamPoolId()).size(),
"a replayed ClientToken must not provision the CIDR twice");
}
@Test
void replayingAPoolCreateClientTokenReturnsTheOriginalPool() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
IpamPool first = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", "first", "000000000000", "pool-token");
IpamPool replay = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", "second", "000000000000", "pool-token");
assertEquals(first.getIpamPoolId(), replay.getIpamPoolId());
assertEquals(1, service.describeIpamPools(REGION, List.of()).size());
}
@Test
void allocatingFromAnUnknownPoolThrows() {
assertThrows(AwsException.class,
() -> service.allocateIpamPoolCidr(REGION, "ipam-pool-doesnotexist", 24, null, null));
}
@Test
@SuppressWarnings("unchecked")
void allocationResolvesSharedPoolAndWritesBackToOwnerAccount() {
String ownerAccount = "111111111111";
String workloadAccount = "222222222222";
AtomicReference<String> caller = new AtomicReference<>(ownerAccount);
RequestContext requestContext = mock(RequestContext.class);
when(requestContext.getAccountId()).thenAnswer(invocation -> caller.get());
Instance<RequestContext> contextInstance = mock(Instance.class);
when(contextInstance.get()).thenReturn(requestContext);
AccountAwareStorageBackend<Ipam> ipams = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), contextInstance, "000000000000");
AccountAwareStorageBackend<IpamPool> pools = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), contextInstance, "000000000000");
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn(workloadAccount);
Ec2IpamService accountAwareService = new Ec2IpamService(
config, ipams, pools, new InMemoryStorage<>(), new InMemoryStorage<>(),
contextInstance);
Ipam ipam = accountAwareService.createIpam(REGION, null, List.of(REGION), ownerAccount);
IpamPool pool = accountAwareService.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", "shared pool", ownerAccount);
accountAwareService.provisionIpamPoolCidr(REGION, pool.getIpamPoolId(), "10.0.0.0/16");
caller.set(workloadAccount);
IpamPoolAllocation allocation = accountAwareService.allocateIpamPoolCidr(
REGION, pool.getIpamPoolId(), 24, null, "shared-services subnet");
assertEquals("10.0.0.0/24", allocation.getCidr());
String poolKey = REGION + "|" + pool.getIpamPoolId();
assertEquals(1, pools.getForAccount(ownerAccount, poolKey).orElseThrow()
.getAllocations().size());
assertTrue(pools.getForAccount(workloadAccount, poolKey).isEmpty(),
"cross-account allocation must not fork the pool into the caller account");
}
/**
* A RAM-shared pool lets a workload account allocate from it, but Modify/Delete/Provision of
* the pool itself stay owner-only in AWS. The fixture puts the pool in {@code ownerAccount}
* and leaves the caller set to {@code workloadAccount}.
*/
@SuppressWarnings("unchecked")
private record SharedPoolFixture(Ec2IpamService service, AccountAwareStorageBackend<IpamPool> pools,
AccountAwareStorageBackend<Ipam> ipams, AtomicReference<String> caller,
Ipam ipam, IpamPool pool) {}
@SuppressWarnings("unchecked")
private SharedPoolFixture sharedPoolOwnedByAnotherAccount() {
String ownerAccount = "111111111111";
String workloadAccount = "222222222222";
AtomicReference<String> caller = new AtomicReference<>(ownerAccount);
RequestContext requestContext = mock(RequestContext.class);
when(requestContext.getAccountId()).thenAnswer(invocation -> caller.get());
Instance<RequestContext> contextInstance = mock(Instance.class);
when(contextInstance.get()).thenReturn(requestContext);
AccountAwareStorageBackend<Ipam> ipams = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), contextInstance, "000000000000");
AccountAwareStorageBackend<IpamPool> pools = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), contextInstance, "000000000000");
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn(workloadAccount);
Ec2IpamService service = new Ec2IpamService(
config, ipams, pools, new InMemoryStorage<>(), new InMemoryStorage<>(),
contextInstance);
Ipam ipam = service.createIpam(REGION, null, List.of(REGION), ownerAccount);
IpamPool pool = service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(),
REGION, null, "ipv4", "shared pool", ownerAccount);
service.provisionIpamPoolCidr(REGION, pool.getIpamPoolId(), "10.0.0.0/16");
caller.set(workloadAccount);
return new SharedPoolFixture(service, pools, ipams, caller, ipam, pool);
}
@Test
void modifyingAnotherAccountsPoolIsRejected() {
SharedPoolFixture fixture = sharedPoolOwnedByAnotherAccount();
AwsException error = assertThrows(AwsException.class,
() -> fixture.service().modifyIpamPool(REGION, fixture.pool().getIpamPoolId(),
"hijacked", null, null, null, null, false));
assertEquals("InvalidIpamPoolId.NotFound", error.getErrorCode());
assertEquals("shared pool",
fixture.pools().getForAccount("111111111111", REGION + "|" + fixture.pool().getIpamPoolId())
.orElseThrow().getDescription());
}
@Test
void deletingAnotherAccountsPoolIsRejected() {
SharedPoolFixture fixture = sharedPoolOwnedByAnotherAccount();
AwsException error = assertThrows(AwsException.class,
() -> fixture.service().deleteIpamPool(REGION, fixture.pool().getIpamPoolId()));
assertEquals("InvalidIpamPoolId.NotFound", error.getErrorCode());
assertTrue(fixture.pools()
.getForAccount("111111111111", REGION + "|" + fixture.pool().getIpamPoolId()).isPresent());
}
@Test
void provisioningIntoAnotherAccountsPoolIsRejected() {
SharedPoolFixture fixture = sharedPoolOwnedByAnotherAccount();
AwsException error = assertThrows(AwsException.class,
() -> fixture.service().provisionIpamPoolCidr(
REGION, fixture.pool().getIpamPoolId(), "192.168.0.0/16"));
assertEquals("InvalidIpamPoolId.NotFound", error.getErrorCode());
assertEquals(1, fixture.pools()
.getForAccount("111111111111", REGION + "|" + fixture.pool().getIpamPoolId())
.orElseThrow().getProvisionedCidrs().size());
}
@Test
void allocatingFromAnotherAccountsSharedPoolIsStillAllowed() {
SharedPoolFixture fixture = sharedPoolOwnedByAnotherAccount();
IpamPoolAllocation allocation = fixture.service().allocateIpamPoolCidr(
REGION, fixture.pool().getIpamPoolId(), 24, null, "workload subnet");
assertEquals("10.0.0.0/24", allocation.getCidr());
}
@Test
void deletingAnotherAccountsIpamIsRejectedAndLeavesItIntact() {
SharedPoolFixture fixture = sharedPoolOwnedByAnotherAccount();
AwsException error = assertThrows(AwsException.class,
() -> fixture.service().deleteIpam(REGION, fixture.ipam().getIpamId()));
assertEquals("InvalidIpamId.NotFound", error.getErrorCode());
assertTrue(fixture.ipams()
.getForAccount("111111111111", REGION + "|" + fixture.ipam().getIpamId()).isPresent());
}
@Test
void modifyingAnotherAccountsIpamIsRejectedAndForksNoCopy() {
SharedPoolFixture fixture = sharedPoolOwnedByAnotherAccount();
AwsException error = assertThrows(AwsException.class,
() -> fixture.service().modifyIpam(REGION, fixture.ipam().getIpamId(),
"hijacked", List.of(), List.of()));
assertEquals("InvalidIpamId.NotFound", error.getErrorCode());
assertTrue(fixture.ipams()
.getForAccount("222222222222", REGION + "|" + fixture.ipam().getIpamId()).isEmpty(),
"a rejected cross-account modify must not fork the IPAM into the caller account");
}
// --- modelled enums (Tier, MeteredAccount, AddressFamily) ---
@Test
void createIpamRejectsAnUnmodelledTier() {
AwsException error = assertThrows(AwsException.class,
() -> service.createIpam(REGION, "bad tier", List.of(REGION), "000000000000",
false, "ipam-owner", "platinum", null, List.of()));
assertEquals("InvalidParameterValue", error.getErrorCode());
assertTrue(service.describeIpams(REGION, List.of()).isEmpty(),
"a rejected CreateIpam must not have stored an IPAM");
}
@Test
void createIpamRejectsAnUnmodelledMeteredAccount() {
AwsException error = assertThrows(AwsException.class,
() -> service.createIpam(REGION, "bad metered account", List.of(REGION), "000000000000",
false, "someone-else", "free", null, List.of()));
assertEquals("InvalidParameterValue", error.getErrorCode());
}
@Test
void createIpamAcceptsBothModelledTiers() {
assertEquals("free", service.createIpam(REGION, "free tier", List.of(REGION), "000000000000",
false, "ipam-owner", "free", null, List.of()).getTier());
assertEquals("advanced", service.createIpam(REGION, "advanced tier", List.of(REGION), "000000000000",
false, "resource-owner", "advanced", null, List.of()).getTier());
}
@Test
void modifyIpamRejectsAnUnmodelledTierAndLeavesTheStoredOneIntact() {
Ipam ipam = service.createIpam(REGION, "initial", List.of(REGION));
AwsException error = assertThrows(AwsException.class,
() -> service.modifyIpam(REGION, ipam.getIpamId(), null, List.of(), List.of(),
null, null, "platinum"));
assertEquals("InvalidParameterValue", error.getErrorCode());
assertEquals("free", service.describeIpams(REGION, List.of(ipam.getIpamId())).getFirst().getTier());
}
@Test
void createIpamPoolRejectsAnUnmodelledAddressFamily() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
AwsException error = assertThrows(AwsException.class,
() -> service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(), REGION,
null, "ipv5", "bad address family"));
assertEquals("InvalidParameterValue", error.getErrorCode());
assertTrue(service.describeIpamPools(REGION, List.of()).isEmpty(),
"a rejected CreateIpamPool must not have stored a pool");
}
@Test
void createIpamPoolAcceptsBothModelledAddressFamilies() {
Ipam ipam = service.createIpam(REGION, null, List.of(REGION));
assertEquals("ipv4", service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(), REGION,
null, "ipv4", "v4 pool").getAddressFamily());
assertEquals("ipv6", service.createIpamPool(REGION, ipam.getPrivateDefaultScopeId(), REGION,
null, "ipv6", "v6 pool").getAddressFamily());
}
}
@@ -0,0 +1,132 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
/**
* Wire-level tests for {@code ModifyIpamPool}.
*
* <p>New class, not appended to {@code Ec2IntegrationTest} (which uses ordered fixtures this
* operation doesn't need), so falsifiability isolates per operation (CS-001).
*/
@QuarkusTest
class Ec2ModifyIpamPoolConsumerTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ec2/aws4_request";
private String createIpamPool() {
String ipamId = given()
.formParam("Action", "CreateIpam")
.formParam("Description", "modify-pool-test-ipam")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateIpamResponse.ipam.ipamId");
String scopeId = given()
.formParam("Action", "DescribeIpams")
.formParam("IpamId.1", ipamId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("DescribeIpamsResponse.ipamSet.item.privateDefaultScopeId");
return given()
.formParam("Action", "CreateIpamPool")
.formParam("IpamScopeId", scopeId)
.formParam("AddressFamily", "ipv4")
.formParam("Description", "initial-pool")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateIpamPoolResponse.ipamPool.ipamPoolId");
}
@Test
void modifyIpamPool_updatesDescriptionAutoImportAndNetmaskBounds() {
String poolId = createIpamPool();
given()
.formParam("Action", "ModifyIpamPool")
.formParam("IpamPoolId", poolId)
.formParam("Description", "updated-pool")
.formParam("AutoImport", "true")
.formParam("AllocationMinNetmaskLength", "24")
.formParam("AllocationMaxNetmaskLength", "28")
.formParam("AllocationDefaultNetmaskLength", "26")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ModifyIpamPoolResponse.ipamPool.ipamPoolId", equalTo(poolId))
.body("ModifyIpamPoolResponse.ipamPool.description", equalTo("updated-pool"))
.body("ModifyIpamPoolResponse.ipamPool.autoImport", equalTo("true"))
.body("ModifyIpamPoolResponse.ipamPool.allocationMinNetmaskLength", equalTo("24"))
.body("ModifyIpamPoolResponse.ipamPool.allocationMaxNetmaskLength", equalTo("28"))
.body("ModifyIpamPoolResponse.ipamPool.allocationDefaultNetmaskLength", equalTo("26"));
given()
.formParam("Action", "DescribeIpamPools")
.formParam("IpamPoolId.1", poolId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeIpamPoolsResponse.ipamPoolSet.item.description", equalTo("updated-pool"));
}
@Test
void modifyIpamPool_clearAllocationDefaultNetmaskLength_removesIt() {
String poolId = createIpamPool();
given()
.formParam("Action", "ModifyIpamPool")
.formParam("IpamPoolId", poolId)
.formParam("AllocationDefaultNetmaskLength", "26")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ModifyIpamPoolResponse.ipamPool.allocationDefaultNetmaskLength", equalTo("26"));
given()
.formParam("Action", "ModifyIpamPool")
.formParam("IpamPoolId", poolId)
.formParam("ClearAllocationDefaultNetmaskLength", "true")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString("allocationDefaultNetmaskLength")));
}
@Test
void modifyIpamPool_unknownId_returnsAwsErrorShape() {
given()
.formParam("Action", "ModifyIpamPool")
.formParam("IpamPoolId", "ipam-pool-doesnotexist")
.formParam("Description", "irrelevant")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidIpamPoolId.NotFound"));
}
}
@@ -60,7 +60,8 @@ class Ec2RunInstancesPublicIpParamTest {
nullable(Boolean.class))).thenReturn(new Reservation());
Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class),
mock(FlowLogService.class));
mock(FlowLogService.class), mock(Ec2EbsEncryptionService.class),
mock(Ec2IpamService.class));
handler.handle("RunInstances", p, REGION);
ArgumentCaptor<Boolean> associatePublicIp = ArgumentCaptor.forClass(Boolean.class);
@@ -0,0 +1,203 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
/**
* Wire-level tests for {@code GetSecurityGroupsForVpc} and {@code ModifyVpcEndpoint}.
*
* <p>New class rather than appended to {@code Ec2IntegrationTest} (which uses ordered
* class-field fixtures these operations don't need), so falsifiability isolates per
* operation (CS-001).
*/
@QuarkusTest
class Ec2VpcEndpointSecurityGroupConsumerTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ec2/aws4_request";
private String createVpc() {
return given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", "10.77.0.0/16")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
}
@Test
void getSecurityGroupsForVpc_returnsOnlyGroupsInThatVpc() {
String vpcId = createVpc();
String otherVpcId = createVpc();
String groupId = given()
.formParam("Action", "CreateSecurityGroup")
.formParam("GroupName", "vpc-scoped-sg")
.formParam("GroupDescription", "scoped to one vpc")
.formParam("VpcId", vpcId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateSecurityGroupResponse.groupId");
given()
.formParam("Action", "CreateSecurityGroup")
.formParam("GroupName", "other-vpc-sg")
.formParam("GroupDescription", "in a different vpc")
.formParam("VpcId", otherVpcId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "GetSecurityGroupsForVpc")
.formParam("VpcId", vpcId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("GetSecurityGroupsForVpcResponse.securityGroupForVpcSet.item.groupId", hasItem(groupId))
.body("GetSecurityGroupsForVpcResponse.securityGroupForVpcSet.item.primaryVpcId",
everyItem(equalTo(vpcId)));
}
@Test
void getSecurityGroupsForVpc_unknownVpc_returnsAwsErrorShape() {
given()
.formParam("Action", "GetSecurityGroupsForVpc")
.formParam("VpcId", "vpc-doesnotexist")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", startsWith("InvalidVpcID"));
}
@Test
void modifyVpcEndpoint_updatesPolicyAndRouteTables() {
String vpcId = createVpc();
String routeTableId = given()
.formParam("Action", "CreateRouteTable")
.formParam("VpcId", vpcId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateRouteTableResponse.routeTable.routeTableId");
String endpointId = given()
.formParam("Action", "CreateVpcEndpoint")
.formParam("VpcId", vpcId)
.formParam("ServiceName", "com.amazonaws.us-east-1.s3")
.formParam("VpcEndpointType", "Gateway")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVpcEndpointResponse.vpcEndpoint.vpcEndpointId");
given()
.formParam("Action", "ModifyVpcEndpoint")
.formParam("VpcEndpointId", endpointId)
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\"}")
.formParam("AddRouteTableId.1", routeTableId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ModifyVpcEndpointResponse.return", equalTo("true"));
given()
.formParam("Action", "DescribeVpcEndpoints")
.formParam("VpcEndpointId.1", endpointId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeVpcEndpointsResponse.vpcEndpointSet.item.policyDocument",
equalTo("{\"Version\":\"2012-10-17\"}"))
.body("DescribeVpcEndpointsResponse.vpcEndpointSet.item.routeTableIdSet.item",
equalTo(routeTableId));
}
@Test
void modifyVpcEndpoint_resetPolicy_clearsPolicyDocument() {
String vpcId = createVpc();
String endpointId = given()
.formParam("Action", "CreateVpcEndpoint")
.formParam("VpcId", vpcId)
.formParam("ServiceName", "com.amazonaws.us-east-1.s3")
.formParam("VpcEndpointType", "Gateway")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVpcEndpointResponse.vpcEndpoint.vpcEndpointId");
given()
.formParam("Action", "ModifyVpcEndpoint")
.formParam("VpcEndpointId", endpointId)
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\"}")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "ModifyVpcEndpoint")
.formParam("VpcEndpointId", endpointId)
.formParam("ResetPolicy", "true")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "DescribeVpcEndpoints")
.formParam("VpcEndpointId.1", endpointId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString("policyDocument")));
}
@Test
void modifyVpcEndpoint_unknownId_returnsAwsErrorShape() {
given()
.formParam("Action", "ModifyVpcEndpoint")
.formParam("VpcEndpointId", "vpce-doesnotexist")
.formParam("PolicyDocument", "{}")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", startsWith("InvalidVpcEndpointId"));
}
}
@@ -0,0 +1,57 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class Ipv4CidrsTest {
@Test
void containsIsTrueOnlyForBlocksInsideTheOuterCidr() {
assertTrue(Ipv4Cidrs.contains("10.0.0.0/8", "10.4.0.0/14"));
assertTrue(Ipv4Cidrs.contains("10.0.0.0/8", "10.0.0.0/8"));
assertFalse(Ipv4Cidrs.contains("10.0.0.0/8", "192.168.0.0/16"));
assertFalse(Ipv4Cidrs.contains("10.4.0.0/14", "10.0.0.0/8"));
}
@Test
void overlapsDetectsAnySharedAddressSpace() {
assertTrue(Ipv4Cidrs.overlaps("10.0.0.0/24", "10.0.0.128/25"));
assertTrue(Ipv4Cidrs.overlaps("10.0.0.0/8", "10.255.0.0/16"));
assertFalse(Ipv4Cidrs.overlaps("10.0.0.0/24", "10.0.1.0/24"));
}
@Test
void firstFreeBlockSkipsOccupiedSpaceInOrder() {
assertEquals("10.0.1.0/24",
Ipv4Cidrs.firstFreeBlock(List.of("10.0.0.0/16"), List.of("10.0.0.0/24"), 24));
assertEquals("10.0.0.0/24",
Ipv4Cidrs.firstFreeBlock(List.of("10.0.0.0/16"), List.of(), 24));
// occupied space in the middle: allocation order fills around it
assertEquals("10.0.2.0/24",
Ipv4Cidrs.firstFreeBlock(List.of("10.0.0.0/16"),
List.of("10.0.0.0/24", "10.0.1.0/24", "10.0.3.0/24"), 24));
}
@Test
void firstFreeBlockReturnsNullWhenExhausted() {
assertEquals(null,
Ipv4Cidrs.firstFreeBlock(List.of("10.0.0.0/24"), List.of("10.0.0.0/24"), 24));
// requested block larger than the pool itself
assertEquals(null,
Ipv4Cidrs.firstFreeBlock(List.of("10.0.0.0/24"), List.of(), 16));
}
@Test
void invalidCidrsThrow() {
assertThrows(AwsException.class, () -> Ipv4Cidrs.contains("10.0.0.0", "10.0.0.0/8"));
assertThrows(AwsException.class, () -> Ipv4Cidrs.contains("10.0.0.0/33", "10.0.0.0/8"));
assertThrows(AwsException.class, () -> Ipv4Cidrs.contains("banana/8", "10.0.0.0/8"));
}
}