Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Sam Fakhreddine9563b7ef08e9
diff --git a/docs/services/ec2.md b/docs/services/ec2.md
index cae0562675..d52ce425eb 100644
--- a/docs/services/ec2.md
+++ b/docs/services/ec2.md
@@ -207,6 +207,7 @@ Floci seeds the following resources on first use in each region so Terraform, th
| AuthorizeSecurityGroupEgress | Adds outbound permissions, with the same source types as the inbound call. |
| RevokeSecurityGroupIngress | Removes inbound permissions. Matches on protocol and port range only, so it removes every permission on that port regardless of source. |
| RevokeSecurityGroupEgress | Removes outbound permissions, matched the same way as the inbound call. |
+| GetSecurityGroupsForVpc | Lists the security groups belonging to one VPC, with the same filters as the describe call. |
| DescribeSecurityGroupRules | Lists stored security group rules. |
| ModifySecurityGroupRules | Updates supported fields on security group rules. |
| UpdateSecurityGroupRuleDescriptionsIngress | Updates descriptions on matching inbound security group rules. |
@@ -390,6 +391,7 @@ real AWS rejects; Floci does not model subnet IPv6 allocation.
| DeleteTransitGatewayRoute | Removes a static route. |
| ReplaceTransitGatewayRoute | Points an existing route at a different target, or writes it if absent. |
| SearchTransitGatewayRoutes | Returns a route table's routes, static and propagated, filtered. |
+| ExportTransitGatewayRoutes | Reports the S3 object a route-table export would be written to. |
A route table asked for by name is never a default one; only the table a gateway mints for itself
carries `defaultAssociationRouteTable` or `defaultPropagationRouteTable`. Deleting a route table is
@@ -421,6 +423,8 @@ route table's own listings drop the route table id that the mutating calls inclu
Route table ids follow the live API's own inconsistency: an id that does not exist is
`InvalidRouteTableID.NotFound`, while one of the wrong shape is `InvalidRouteTableId.Malformed`.
+`ExportTransitGatewayRoutes` validates the route table and requires `S3Bucket`, then returns the `s3://` object key the export would occupy. No object is written and nothing is uploaded — the value is a caller that needs the call to succeed and the key to look right, not a readable export.
+
### NAT Gateways
| Action | Description |
@@ -488,6 +492,58 @@ Launch templates store versioned launch data. New template versions can be creat
| DescribeVolumes | Lists or returns stored EBS volume records. |
| DeleteVolume | Deletes an EBS volume record. |
+### EBS Encryption Defaults
+
+| Action | Description |
+|--------|-------------|
+| EnableEbsEncryptionByDefault | Turns on default encryption for new volumes in the region. |
+| DisableEbsEncryptionByDefault | Turns default encryption back off. |
+| GetEbsEncryptionByDefault | Reports whether default encryption is on. |
+| ModifyEbsDefaultKmsKeyId | Sets the KMS key used when a volume names none. |
+| GetEbsDefaultKmsKeyId | Reports the current default KMS key. |
+| ResetEbsDefaultKmsKeyId | Restores the AWS-managed default key. |
+
+These are account-level settings scoped per region, not per volume, and nothing here encrypts anything — no volume's stored bytes change. LZA's SecurityStack drives them through its `Custom::EnableEbsEncryptionByDefault` Lambda, which calls enable plus `ModifyEbsDefaultKmsKeyId` on create and disable on delete, then reads the state back with the two `Get` calls.
+
+An account that has never set a key reports `alias/aws/ebs`, the AWS-managed EBS key every account starts with, rather than an empty value — the module runner fails hard on a missing `KmsKeyId`, so the fallback is what keeps it running. `ResetEbsDefaultKmsKeyId` returns to that same alias. `ModifyEbsDefaultKmsKeyId` requires `KmsKeyId` and rejects a blank one with `MissingParameter`; the key is stored as given and is not checked against KMS.
+
+### IPAM
+
+| Action | Description |
+|--------|-------------|
+| EnableIpamOrganizationAdminAccount | Delegates IPAM administration to a member account. |
+| DisableIpamOrganizationAdminAccount | Removes the IPAM delegated administrator. |
+| CreateIpam | Creates an IPAM with its default private and public scopes. |
+| DescribeIpams | Lists or returns stored IPAMs. |
+| ModifyIpam | Updates an IPAM's description, tier, metered account and operating regions. |
+| DeleteIpam | Deletes an IPAM and, leniently, the pools that belong to it. |
+| CreateIpamPool | Creates a pool under a scope, optionally sourced from a parent pool. |
+| DescribeIpamPools | Lists or returns stored pools. |
+| ModifyIpamPool | Updates a pool's description, auto-import flag and netmask-length bounds. |
+| DeleteIpamPool | Deletes a pool. |
+| ProvisionIpamPoolCidr | Provisions a CIDR onto a pool, validated against its source pool. |
+| GetIpamPoolCidrs | Returns a pool's provisioned CIDRs. |
+| AllocateIpamPoolCidr | Allocates a CIDR from a pool, by explicit CIDR or by netmask length. |
+| ReleaseIpamPoolAllocation | Releases an allocation, returning its space to the pool. |
+| GetIpamPoolAllocations | Returns a pool's live allocations. |
+| AssociateIpamByoasn | Associates a BYOASN with a CIDR. |
+| DisassociateIpamByoasn | Removes a BYOASN association. |
+| DescribeIpamByoasn | Lists BYOASN associations in the region. |
+
+This is what LZA needs end to end: the Organization stage delegates the IPAM admin through `Custom::EnableIpamOrganizationAdminAccount`, the Network stages build the IPAM and pool hierarchy through CloudFormation, and the `get-ipam-subnet-cidr` custom-resource Lambda allocates subnet CIDRs from pools at Deploy time.
+
+Allocation is real rather than recorded. `AllocateIpamPoolCidr` by netmask length hands out the first free block that fits, skipping both live allocations and any space already provisioned onward to child pools, and reports `InsufficientCidrBlocks` when nothing fits. An explicit `Cidr` must fall inside a provisioned CIDR and must not overlap an existing allocation. `ProvisionIpamPoolCidr` on a pool with a source pool requires the CIDR to sit inside one of the parent's provisioned CIDRs. Releasing an allocation returns its space, so the next allocation of the same size reuses it.
+
+`CreateIpam`, `CreateIpamPool`, `ProvisionIpamPoolCidr` and `AllocateIpamPoolCidr` honour `ClientToken` — the four IPAM operations that model it. A replay returns what the first call produced rather than creating a second resource: the same pool, the same provisioned CIDR, the same allocation id and CIDR, with pool consumption unchanged. This matters most on `AllocateIpamPoolCidr`, which LZA's `get-ipam-subnet-cidr` Lambda retries; without it each retry would burn another distinct CIDR out of the pool. Parameter differences on a replay are ignored rather than rejected as `IdempotentParameterMismatch`, and the token is not echoed in the response, matching the AWS output shapes. A token is scoped to the account that used it.
+
+Pool lookups deliberately fall back to an id-only scan across accounts, so a RAM-shared pool resolves from a workload account and region. That fallback covers reads and allocation only: `AllocateIpamPoolCidr` from an account that does not own the pool succeeds and writes the allocation back to the owner's partition rather than forking a copy into the caller's. Mutations of the pool itself — `ModifyIpamPool`, `DeleteIpamPool`, `ProvisionIpamPoolCidr` — are owner-only, as are `ModifyIpam` and `DeleteIpam`, and a non-owner gets `InvalidIpamPoolId.NotFound` or `InvalidIpamId.NotFound`, which is what AWS returns for a resource you cannot act on. `ReleaseIpamPoolAllocation` stays on the cross-account path, since no per-allocation caller is tracked to check ownership against.
+
+The delegated administrator is stored organization-wide rather than per account, so every member account reads the same value and delegating a second, different account conflicts with `InvalidParameterValue` no matter which account asks.
+
+Omitting a required identifier is a modeled `MissingParameter` rather than a not-found: this covers `IpamPoolId` on every pool operation, and `IpamScopeId` on `CreateIpamPool`. A `CreateIpamPool` naming a scope no IPAM owns is rejected with `InvalidIpamScopeId.NotFound` instead of storing a pool with a null `ipamId`.
+
+State is reported settled rather than transitional, as elsewhere in this service: IPAMs and pools come back `create-complete` immediately and `delete-complete` on deletion, with no intermediate states. `DeleteIpam` cascades to the IPAM's pools, which real AWS requires `--cascade` to do. BYOASN associations are stored and echoed but nothing validates the ASN or advertises it.
+
## Configuration
| Environment variable | Default | Description |
diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java
index 65e11461d6..4063bbc7ab 100644
--- a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java
+++ b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java
@@ -330,6 +330,54 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
.collect(Collectors.toUnmodifiableSet());
}
+ /** A value together with the account partition that owns it, as recovered by {@link #findAnyAccountEntry}. */
+ public record OwnedEntry<V>(String account, V value) {}
+
+ /**
+ * Resolves a logical key across every account's partition, modelling a globally-unique
+ * namespace — as S3 bucket names are in AWS, where a bucket lives in one account but is
+ * legitimately reachable cross-account. Tries the current caller's partition first (via
+ * {@link #get}, which also covers pre-multi-account un-prefixed data), then falls back to any
+ * other account that owns the key. Returns the first match, or empty if no account has it.
+ *
+ * <p>Unlike {@link #get}, a cross-account hit is <em>not</em> migrated into the caller's
+ * partition: the entry legitimately belongs to its owning account and must stay there.
+ */
+ public Optional<V> findAnyAccount(String key) {
+ return findAnyAccountEntry(key).map(OwnedEntry::value);
+ }
+
+ /**
+ * Like {@link #findAnyAccount}, but also reports the owning account so a cross-account
+ * <em>mutation</em> can write the value back to its owner's partition (via
+ * {@link #putForAccount}) instead of forking a phantom copy into the caller's partition.
+ * The caller's own hit is owned by the current account context; a scanned hit's owner is
+ * the account segment of its raw key (or {@code defaultAccountId} for pre-multi-account,
+ * un-prefixed data).
+ */
+ public Optional<OwnedEntry<V>> findAnyAccountEntry(String key) {
+ Optional<V> own = get(key);
+ if (own.isPresent()) {
+ return Optional.of(new OwnedEntry<>(prefix(), own.get()));
+ }
+ String suffix = "/" + key;
+ for (String rawKey : delegate.keys()) {
+ if (rawKey.equals(key)) {
+ Optional<V> value = delegate.get(rawKey);
+ if (value.isPresent()) {
+ return Optional.of(new OwnedEntry<>(defaultAccountId, value.get()));
+ }
+ } else if (rawKey.endsWith(suffix)) {
+ Optional<V> value = delegate.get(rawKey);
+ if (value.isPresent()) {
+ String account = rawKey.substring(0, rawKey.length() - suffix.length());
+ return Optional.of(new OwnedEntry<>(account, value.get()));
+ }
+ }
+ }
+ return Optional.empty();
+ }
+
// ---
private String prefix() {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2EbsEncryptionService.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2EbsEncryptionService.java
new file mode 100644
index 0000000000..af72c37032
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2EbsEncryptionService.java
@@ -0,0 +1,85 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.Map;
+
+/**
+ * Region-scoped EBS account-level encryption defaults: whether new volumes are
+ * encrypted by default and which KMS key is used when no key is specified.
+ *
+ * <p>LZA's SecurityStack {@code Custom::EnableEbsEncryptionByDefault} Lambda
+ * calls EnableEbsEncryptionByDefault + ModifyEbsDefaultKmsKeyId on create and
+ * DisableEbsEncryptionByDefault on delete; the module runner additionally reads
+ * the state back with the Get variants, which fail hard on a missing KmsKeyId,
+ * so the default key falls back to the AWS-managed {@code alias/aws/ebs}.</p>
+ */
+@ApplicationScoped
+public class Ec2EbsEncryptionService {
+
+ private static final Logger LOG = Logger.getLogger(Ec2EbsEncryptionService.class);
+
+ /** The AWS-managed EBS key every account starts with. */
+ static final String AWS_MANAGED_KEY_ALIAS = "alias/aws/ebs";
+
+ private static final String ENABLED_SUFFIX = "enabled";
+ private static final String KMS_KEY_SUFFIX = "kmsKeyId";
+
+ // key(region, setting) -> value
+ private final StorageBackend<String, String> settings;
+
+ @Inject
+ public Ec2EbsEncryptionService(StorageFactory storageFactory) {
+ this(storageFactory.create("ec2", "ec2-ebs-encryption.json", new TypeReference<Map<String, String>>() {}));
+ }
+
+ // Package-private for hermetic tests (pass an in-memory StorageBackend directly).
+ Ec2EbsEncryptionService(StorageBackend<String, String> settings) {
+ this.settings = settings;
+ }
+
+ public boolean getEbsEncryptionByDefault(String region) {
+ return settings.get(key(region, ENABLED_SUFFIX)).map(Boolean::parseBoolean).orElse(false);
+ }
+
+ public boolean enableEbsEncryptionByDefault(String region) {
+ settings.put(key(region, ENABLED_SUFFIX), "true");
+ LOG.infov("Enabled EBS encryption by default in {0}", region);
+ return true;
+ }
+
+ public boolean disableEbsEncryptionByDefault(String region) {
+ settings.put(key(region, ENABLED_SUFFIX), "false");
+ LOG.infov("Disabled EBS encryption by default in {0}", region);
+ return false;
+ }
+
+ public String getEbsDefaultKmsKeyId(String region) {
+ return settings.get(key(region, KMS_KEY_SUFFIX)).orElse(AWS_MANAGED_KEY_ALIAS);
+ }
+
+ public String modifyEbsDefaultKmsKeyId(String region, String kmsKeyId) {
+ if (kmsKeyId == null || kmsKeyId.isBlank()) {
+ throw new AwsException("MissingParameter", "The request must contain the parameter KmsKeyId", 400);
+ }
+ settings.put(key(region, KMS_KEY_SUFFIX), kmsKeyId);
+ LOG.infov("EBS default KMS key in {0} set to {1}", region, kmsKeyId);
+ return kmsKeyId;
+ }
+
+ public String resetEbsDefaultKmsKeyId(String region) {
+ settings.delete(key(region, KMS_KEY_SUFFIX));
+ LOG.infov("EBS default KMS key in {0} reset to {1}", region, AWS_MANAGED_KEY_ALIAS);
+ return AWS_MANAGED_KEY_ALIAS;
+ }
+
+ private static String key(String region, String setting) {
+ return region + "|" + setting;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2IpamService.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2IpamService.java
new file mode 100644
index 0000000000..067dfbaff5
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2IpamService.java
@@ -0,0 +1,895 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+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.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+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.IpamPoolCidr;
+import io.github.hectorvent.floci.services.ec2.model.IpamScope;
+import io.github.hectorvent.floci.services.ec2.model.AsnAssociation;
+import io.github.hectorvent.floci.services.ec2.model.Tag;
+
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.context.ContextNotActiveException;
+import jakarta.enterprise.inject.Instance;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.ThreadLocalRandom;
+
+/**
+ * Amazon VPC IP Address Manager (IPAM) emulation: organization admin
+ * delegation, IPAMs with default scopes, hierarchical pools with provisioned
+ * CIDRs, and CIDR allocations.
+ *
+ * <p>This is what LZA needs end to end: the Organization stage delegates the
+ * IPAM admin ({@code Custom::EnableIpamOrganizationAdminAccount}), the Network
+ * stages create the IPAM + pool hierarchy through CloudFormation, and the
+ * {@code get-ipam-subnet-cidr} custom-resource Lambda allocates subnet CIDRs
+ * from pools at Deploy time. Pool lookups deliberately fall back to an
+ * id-only scan so RAM-shared pools resolve from workload accounts/regions.</p>
+ */
+@ApplicationScoped
+public class Ec2IpamService {
+
+ private static final Logger LOG = Logger.getLogger(Ec2IpamService.class);
+
+ private static final String ADMIN_ACCOUNT_KEY = "ipam-organization-admin-account";
+
+ /**
+ * Partition the delegated-admin setting is stored under. The management account delegates it
+ * once and every member account must read the same value, so it cannot live in the ordinary
+ * account-prefixed namespace. The literal is not a valid 12-digit account id precisely so it
+ * can never collide with a real account's partition.
+ */
+ private static final String ORGANIZATION_PARTITION = "organization";
+
+ private final EmulatorConfig config;
+ // key(region, ipamId) -> Ipam
+ private final StorageBackend<String, Ipam> ipams;
+ // key(region, ipamPoolId) -> IpamPool
+ private final StorageBackend<String, IpamPool> pools;
+ // org-wide settings, e.g. the delegated admin account
+ private final StorageBackend<String, String> settings;
+ private final StorageBackend<String, AsnAssociation> asnAssociations;
+ private final Instance<RequestContext> requestContextInstance;
+
+ @Inject
+ public Ec2IpamService(EmulatorConfig config, StorageFactory storageFactory,
+ Instance<RequestContext> requestContextInstance) {
+ this(config,
+ storageFactory.create("ec2", "ec2-ipams.json", new TypeReference<Map<String, Ipam>>() {}),
+ storageFactory.create("ec2", "ec2-ipam-pools.json", new TypeReference<Map<String, IpamPool>>() {}),
+ storageFactory.create("ec2", "ec2-ipam-settings.json", new TypeReference<Map<String, String>>() {}),
+ storageFactory.create("ec2", "ec2-ipam-asn-associations.json", new TypeReference<Map<String, AsnAssociation>>() {}),
+ requestContextInstance);
+ }
+
+ // Package-private for hermetic tests (pass in-memory StorageBackends directly).
+ Ec2IpamService(EmulatorConfig config,
+ StorageBackend<String, Ipam> ipams,
+ StorageBackend<String, IpamPool> pools,
+ StorageBackend<String, String> settings,
+ StorageBackend<String, AsnAssociation> asnAssociations) {
+ this(config, ipams, pools, settings, asnAssociations, null);
+ }
+
+ Ec2IpamService(EmulatorConfig config,
+ StorageBackend<String, Ipam> ipams,
+ StorageBackend<String, IpamPool> pools,
+ StorageBackend<String, String> settings,
+ StorageBackend<String, AsnAssociation> asnAssociations,
+ Instance<RequestContext> requestContextInstance) {
+ this.config = config;
+ this.ipams = ipams;
+ this.pools = pools;
+ this.settings = settings;
+ this.asnAssociations = asnAssociations;
+ this.requestContextInstance = requestContextInstance;
+ }
+
+ /**
+ * The account making the current request, resolved the same way
+ * {@code AccountAwareStorageBackend} derives its key prefix, so an ownership comparison
+ * against a resolved entry's partition is meaningful both in and out of a request scope.
+ */
+ private String callerAccountId() {
+ if (requestContextInstance != null) {
+ try {
+ String accountId = requestContextInstance.get().getAccountId();
+ if (accountId != null) {
+ return accountId;
+ }
+ } catch (ContextNotActiveException e) {
+ // Tolerated: callers outside a request scope (startup, internal provisioning)
+ // legitimately fall through to the default account. Logged so an unexpected
+ // context loss inside a request doesn't produce silent wrong-owner decisions.
+ LOG.debugv("No active request context — resolving caller as default account {0}",
+ config.defaultAccountId());
+ }
+ }
+ return config.defaultAccountId();
+ }
+
+ /**
+ * Only the organization's management account may enable/disable the IPAM delegated
+ * administrator (real AWS: a non-management member calling either op is denied). 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 they call without an assumed role, which is how LZA's
+ * Organization-stage custom resource invokes these operations.
+ *
+ * <p>{@code UnauthorizedOperation} is EC2 Query's permission-denied code: both operations
+ * model a {@code DryRun} member documented as returning {@code DryRunOperation} when the
+ * caller has permission and {@code UnauthorizedOperation} when it does not.</p>
+ */
+ private void requireManagementAccount() {
+ String caller = callerAccountId();
+ if (!caller.equals(config.defaultAccountId())) {
+ throw new AwsException("UnauthorizedOperation",
+ "Account " + caller + " is not authorized to modify the IPAM organization "
+ + "delegated administrator; only the organization's management account may.", 403);
+ }
+ }
+
+ // ─── Organization admin delegation ──────────────────────────────────────
+
+ public boolean enableIpamOrganizationAdminAccount(String delegatedAdminAccountId) {
+ requireManagementAccount();
+ if (delegatedAdminAccountId == null || delegatedAdminAccountId.isBlank()) {
+ throw new AwsException("MissingParameter", "DelegatedAdminAccountId is required.", 400);
+ }
+ Optional<String> existing = organizationAdmin();
+ if (existing.isPresent() && !existing.get().equals(delegatedAdminAccountId)) {
+ throw new AwsException("InvalidParameterValue",
+ "Account " + existing.get() + " is already the IPAM delegated administrator.", 400);
+ }
+ putOrganizationAdmin(delegatedAdminAccountId);
+ LOG.infov("IPAM organization admin delegated to {0}", delegatedAdminAccountId);
+ return true;
+ }
+
+ public Optional<String> getIpamOrganizationAdminAccount() {
+ return organizationAdmin();
+ }
+
+ public boolean disableIpamOrganizationAdminAccount(String delegatedAdminAccountId) {
+ requireManagementAccount();
+ Optional<String> existing = organizationAdmin();
+ if (existing.isEmpty() || !existing.get().equals(delegatedAdminAccountId)) {
+ throw new AwsException("InvalidParameterValue",
+ "Account " + delegatedAdminAccountId + " is not the IPAM delegated administrator.", 400);
+ }
+ deleteOrganizationAdmin();
+ LOG.infov("IPAM organization admin delegation removed from {0}", delegatedAdminAccountId);
+ return true;
+ }
+
+ private Optional<String> organizationAdmin() {
+ if (settings instanceof AccountAwareStorageBackend<?> rawAccountAware) {
+ @SuppressWarnings("unchecked")
+ AccountAwareStorageBackend<String> accountAware =
+ (AccountAwareStorageBackend<String>) rawAccountAware;
+ return accountAware.getForAccount(ORGANIZATION_PARTITION, ADMIN_ACCOUNT_KEY);
+ }
+ return settings.get(ADMIN_ACCOUNT_KEY);
+ }
+
+ private void putOrganizationAdmin(String delegatedAdminAccountId) {
+ if (settings instanceof AccountAwareStorageBackend<?> rawAccountAware) {
+ @SuppressWarnings("unchecked")
+ AccountAwareStorageBackend<String> accountAware =
+ (AccountAwareStorageBackend<String>) rawAccountAware;
+ accountAware.putForAccount(ORGANIZATION_PARTITION, ADMIN_ACCOUNT_KEY, delegatedAdminAccountId);
+ return;
+ }
+ settings.put(ADMIN_ACCOUNT_KEY, delegatedAdminAccountId);
+ }
+
+ private void deleteOrganizationAdmin() {
+ if (settings instanceof AccountAwareStorageBackend<?> rawAccountAware) {
+ @SuppressWarnings("unchecked")
+ AccountAwareStorageBackend<String> accountAware =
+ (AccountAwareStorageBackend<String>) rawAccountAware;
+ accountAware.deleteForAccount(ORGANIZATION_PARTITION, ADMIN_ACCOUNT_KEY);
+ return;
+ }
+ settings.delete(ADMIN_ACCOUNT_KEY);
+ }
+
+ // ─── IPAMs + default scopes ─────────────────────────────────────────────
+
+ /** {@code IpamTier}. Stored on the IPAM and echoed back by DescribeIpams. */
+ private static final Set<String> TIERS = Set.of("free", "advanced");
+
+ /** {@code IpamMeteredAccount}. Stored on the IPAM and echoed back by DescribeIpams. */
+ private static final Set<String> METERED_ACCOUNTS = Set.of("ipam-owner", "resource-owner");
+
+ /** {@code AddressFamily}. Decides how a pool's CIDRs are parsed, so a wrong one is not cosmetic. */
+ private static final Set<String> ADDRESS_FAMILIES = Set.of("ipv4", "ipv6");
+
+ /**
+ * Rejects a value outside a modelled enum. An absent value is left to the caller's default:
+ * every one of these members is optional, and the defaults applied below are AWS's own.
+ */
+ private static void requireEnum(String value, Set<String> allowed, String parameter) {
+ if (value != null && !allowed.contains(value)) {
+ throw new AwsException("InvalidParameterValue",
+ "Value (" + value + ") for parameter " + parameter + " is invalid. "
+ + "Valid values are: " + String.join(", ", new TreeSet<>(allowed)) + ".", 400);
+ }
+ }
+
+ public Ipam createIpam(String region, String description, List<String> operatingRegions) {
+ return createIpam(region, description, operatingRegions, config.defaultAccountId());
+ }
+
+ /** Overload for callers (e.g. CloudFormation provisioning) that already have the real
+ * owning account resolved, instead of falling back to this service's ambient default. */
+ public Ipam createIpam(String region, String description, List<String> operatingRegions,
+ String ownerId) {
+ return createIpam(region, description, operatingRegions, ownerId,
+ false, "ipam-owner", "free", null, List.of());
+ }
+
+ public Ipam createIpam(String region, String description, List<String> operatingRegions,
+ String requestedOwnerId, Boolean enablePrivateGua, String meteredAccount,
+ String tier, String clientToken, List<Tag> tags) {
+ // A null owner means "whoever is calling": resolve it the same way account-aware
+ // storage picks its partition, so the recorded owner and the partition always agree.
+ String ownerId = requestedOwnerId != null ? requestedOwnerId : callerAccountId();
+ requireEnum(tier, TIERS, "Tier");
+ requireEnum(meteredAccount, METERED_ACCOUNTS, "MeteredAccount");
+ if (clientToken != null && !clientToken.isBlank()) {
+ for (Ipam existing : ipams.scan(k -> true)) {
+ if (region.equals(existing.getRegion())
+ && clientToken.equals(existing.getClientToken())) {
+ return existing;
+ }
+ }
+ }
+ Ipam ipam = new Ipam();
+ ipam.setIpamId("ipam-" + randomHex(17));
+ ipam.setIpamArn("arn:aws:ec2::" + ownerId + ":ipam/" + ipam.getIpamId());
+ ipam.setOwnerId(ownerId);
+ ipam.setRegion(region);
+ ipam.setDescription(description);
+ ipam.setState("create-complete");
+ ipam.setEnablePrivateGua(enablePrivateGua != null ? enablePrivateGua : false);
+ ipam.setMeteredAccount(meteredAccount != null ? meteredAccount : "ipam-owner");
+ ipam.setTier(tier != null ? tier : "free");
+ ipam.setClientToken(clientToken != null && !clientToken.isBlank() ? clientToken : null);
+ ipam.setTags(tags != null ? new ArrayList<>(tags) : new ArrayList<>());
+ ipam.setOperatingRegions(operatingRegions != null ? new ArrayList<>(operatingRegions) : new ArrayList<>());
+ ipam.getScopes().add(defaultScope(ipam, ownerId, "private"));
+ ipam.getScopes().add(defaultScope(ipam, ownerId, "public"));
+ ipam.setPrivateDefaultScopeId(ipam.getScopes().get(0).getIpamScopeId());
+ ipam.setPublicDefaultScopeId(ipam.getScopes().get(1).getIpamScopeId());
+ ipams.put(key(region, ipam.getIpamId()), ipam);
+ LOG.infov("Created IPAM {0} in {1}", ipam.getIpamId(), region);
+ return ipam;
+ }
+
+ private static IpamScope defaultScope(Ipam ipam, String ownerId, String scopeType) {
+ IpamScope scope = new IpamScope();
+ scope.setIpamScopeId("ipam-scope-" + randomHex(17));
+ scope.setIpamScopeArn("arn:aws:ec2::" + ownerId + ":ipam-scope/" + scope.getIpamScopeId());
+ scope.setIpamId(ipam.getIpamId());
+ scope.setScopeType(scopeType);
+ scope.setDefault(true);
+ scope.setState("create-complete");
+ return scope;
+ }
+
+ public List<Ipam> describeIpams(String region, List<String> ipamIds) {
+ List<Ipam> result = new ArrayList<>();
+ for (Ipam ipam : ipams.scan(k -> true)) {
+ if (region != null && ipam.getRegion() != null && !region.equals(ipam.getRegion())) {
+ continue;
+ }
+ if (ipamIds != null && !ipamIds.isEmpty() && !ipamIds.contains(ipam.getIpamId())) {
+ continue;
+ }
+ result.add(ipam);
+ }
+ return result;
+ }
+
+ public AsnAssociation associateIpamByoasn(String region, String asn, String cidr) {
+ if (asn == null || asn.isBlank()) {
+ throw new AwsException("MissingParameter", "Asn is required.", 400);
+ }
+ if (cidr == null || cidr.isBlank()) {
+ throw new AwsException("MissingParameter", "Cidr is required.", 400);
+ }
+ String key = key(region, asn + "|" + cidr);
+ String ipamId = null;
+ for (Ipam ipam : ipams.scan(k -> true)) {
+ if (region != null && ipam.getRegion() != null && region.equals(ipam.getRegion())) {
+ ipamId = ipam.getIpamId();
+ break;
+ }
+ }
+ AsnAssociation association = new AsnAssociation();
+ association.setAsn(asn);
+ association.setCidr(cidr);
+ association.setIpamId(ipamId);
+ association.setState("associated");
+ association.setStatusMessage("");
+ asnAssociations.put(key, association);
+ return association;
+ }
+
+ public boolean hasAsnAssociation(String region, String asn, String cidr) {
+ String key = key(region, asn + "|" + cidr);
+ return asnAssociations.get(key).isPresent();
+ }
+
+ public List<AsnAssociation> describeIpamByoasn(String region) {
+ List<AsnAssociation> result = new ArrayList<>();
+ String prefix = region + "|";
+ result.addAll(asnAssociations.scan(k -> k.startsWith(prefix)));
+ return result;
+ }
+
+ public AsnAssociation disassociateIpamByoasn(String region, String asn, String cidr) {
+ if (asn == null || asn.isBlank()) {
+ throw new AwsException("MissingParameter", "Asn is required.", 400);
+ }
+ if (cidr == null || cidr.isBlank()) {
+ throw new AwsException("MissingParameter", "Cidr is required.", 400);
+ }
+ String storageKey = key(region, asn + "|" + cidr);
+ AsnAssociation association = asnAssociations.get(storageKey)
+ .orElseThrow(() -> new AwsException("InvalidParameterValue", "BYOASN association was not found.", 400));
+ asnAssociations.delete(storageKey);
+ association.setState("disassociated");
+ return association;
+ }
+
+ public Ipam deleteIpam(String region, String ipamId) {
+ OwnedIpam ownedIpam = requireOwnedIpamForMutation(region, ipamId);
+ Ipam ipam = ownedIpam.ipam();
+ deleteIpamEntry(ownedIpam);
+ // Lenient cascade (AWS requires --cascade): drop the IPAM's pools too.
+ for (IpamPool pool : pools.scan(k -> true)) {
+ if (ipamId.equals(pool.getIpamId())) {
+ pools.delete(key(pool.getRegion(), pool.getIpamPoolId()));
+ }
+ }
+ ipam.setState("delete-complete");
+ return ipam;
+ }
+
+ public Ipam modifyIpam(String region, String ipamId, String description,
+ List<String> addOperatingRegions, List<String> removeOperatingRegions) {
+ return modifyIpam(region, ipamId, description, addOperatingRegions, removeOperatingRegions,
+ null, null, null);
+ }
+
+ public Ipam modifyIpam(String region, String ipamId, String description,
+ List<String> addOperatingRegions, List<String> removeOperatingRegions,
+ Boolean enablePrivateGua, String meteredAccount, String tier) {
+ requireEnum(tier, TIERS, "Tier");
+ requireEnum(meteredAccount, METERED_ACCOUNTS, "MeteredAccount");
+ OwnedIpam ownedIpam = requireOwnedIpamForMutation(region, ipamId);
+ Ipam ipam = ownedIpam.ipam();
+ if (description != null) {
+ ipam.setDescription(description);
+ }
+ if (enablePrivateGua != null) {
+ ipam.setEnablePrivateGua(enablePrivateGua);
+ }
+ if (meteredAccount != null) {
+ ipam.setMeteredAccount(meteredAccount);
+ }
+ if (tier != null) {
+ ipam.setTier(tier);
+ }
+ if (addOperatingRegions != null) {
+ for (String operatingRegion : addOperatingRegions) {
+ if (operatingRegion != null
+ && !operatingRegion.isBlank()
+ && !ipam.getOperatingRegions().contains(operatingRegion)) {
+ ipam.getOperatingRegions().add(operatingRegion);
+ }
+ }
+ }
+ if (removeOperatingRegions != null) {
+ ipam.getOperatingRegions().removeIf(removeOperatingRegions::contains);
+ }
+ saveIpam(ownedIpam);
+ return ipam;
+ }
+
+ // ─── Pools + provisioned CIDRs ──────────────────────────────────────────
+
+ public IpamPool createIpamPool(String region, String ipamScopeId, String locale,
+ String sourceIpamPoolId, String addressFamily, String description) {
+ return createIpamPool(region, ipamScopeId, locale, sourceIpamPoolId, addressFamily,
+ description, config.defaultAccountId());
+ }
+
+ /** Overload for callers (e.g. CloudFormation provisioning) that already have the real
+ * owning account resolved, instead of falling back to this service's ambient default. */
+ public IpamPool createIpamPool(String region, String ipamScopeId, String locale,
+ String sourceIpamPoolId, String addressFamily, String description,
+ String ownerId) {
+ return createIpamPool(region, ipamScopeId, locale, sourceIpamPoolId, addressFamily,
+ description, ownerId, null);
+ }
+
+ /**
+ * Creates a pool, honouring {@code ClientToken}: a replay returns the pool the first call
+ * created rather than minting a second one. Parameter differences on a replay are ignored,
+ * as {@link #createIpam} already does.
+ */
+ public IpamPool createIpamPool(String region, String ipamScopeId, String locale,
+ String sourceIpamPoolId, String addressFamily, String description,
+ String requestedOwnerId, String clientToken) {
+ // Same null-means-caller resolution as createIpam.
+ String ownerId = requestedOwnerId != null ? requestedOwnerId : callerAccountId();
+ if (ipamScopeId == null || ipamScopeId.isBlank()) {
+ throw new AwsException("MissingParameter", "IpamScopeId is required.", 400);
+ }
+ requireEnum(addressFamily, ADDRESS_FAMILIES, "AddressFamily");
+ if (sourceIpamPoolId != null && sourceIpamPoolId.isBlank()) {
+ throw new AwsException("MissingParameter", "SourceIpamPoolId is required.", 400);
+ }
+ if (clientToken != null && !clientToken.isBlank()) {
+ // Caller-partition scan: an idempotency token is scoped to the account that used it.
+ for (IpamPool existing : pools.scan(k -> true)) {
+ if (region.equals(existing.getRegion())
+ && clientToken.equals(existing.getClientToken())) {
+ return existing;
+ }
+ }
+ }
+ if (sourceIpamPoolId != null) {
+ requirePool(region, sourceIpamPoolId);
+ }
+ IpamPool pool = new IpamPool();
+ pool.setIpamPoolId("ipam-pool-" + randomHex(17));
+ pool.setIpamPoolArn("arn:aws:ec2::" + ownerId + ":ipam-pool/" + pool.getIpamPoolId());
+ pool.setIpamId(ipamIdOfScope(ipamScopeId));
+ pool.setIpamScopeId(ipamScopeId);
+ pool.setOwnerId(ownerId);
+ pool.setRegion(region);
+ pool.setLocale(locale);
+ pool.setSourceIpamPoolId(sourceIpamPoolId);
+ pool.setAddressFamily(addressFamily != null ? addressFamily : "ipv4");
+ pool.setDescription(description);
+ pool.setState("create-complete");
+ pool.setClientToken(clientToken != null && !clientToken.isBlank() ? clientToken : null);
+ pools.put(key(region, pool.getIpamPoolId()), pool);
+ LOG.infov("Created IPAM pool {0} (scope {1}, source {2})",
+ pool.getIpamPoolId(), ipamScopeId, sourceIpamPoolId);
+ return pool;
+ }
+
+ public IpamPool modifyIpamPool(String region, String ipamPoolId, String description,
+ Boolean autoImport, Integer allocationMinNetmaskLength,
+ Integer allocationMaxNetmaskLength, Integer allocationDefaultNetmaskLength,
+ boolean clearAllocationDefaultNetmaskLength) {
+ OwnedPool ownedPool = requireOwnedPoolForMutation(region, ipamPoolId);
+ IpamPool pool = ownedPool.pool();
+ if (description != null) {
+ pool.setDescription(description);
+ }
+ if (autoImport != null) {
+ pool.setAutoImport(autoImport);
+ }
+ if (allocationMinNetmaskLength != null) {
+ pool.setAllocationMinNetmaskLength(allocationMinNetmaskLength);
+ }
+ if (allocationMaxNetmaskLength != null) {
+ pool.setAllocationMaxNetmaskLength(allocationMaxNetmaskLength);
+ }
+ if (clearAllocationDefaultNetmaskLength) {
+ pool.setAllocationDefaultNetmaskLength(null);
+ } else if (allocationDefaultNetmaskLength != null) {
+ pool.setAllocationDefaultNetmaskLength(allocationDefaultNetmaskLength);
+ }
+ savePool(ownedPool);
+ return pool;
+ }
+
+ /** Resolves the IPAM owning a scope. {@code IpamScopeId} is a required member of
+ * CreateIpamPool, so an unknown scope is an error rather than a null {@code ipamId}. */
+ private String ipamIdOfScope(String ipamScopeId) {
+ for (Ipam ipam : ipams.scan(k -> true)) {
+ for (IpamScope scope : ipam.getScopes()) {
+ if (ipamScopeId.equals(scope.getIpamScopeId())) {
+ return ipam.getIpamId();
+ }
+ }
+ }
+ throw new AwsException("InvalidIpamScopeId.NotFound",
+ "IPAM scope " + ipamScopeId + " does not exist.", 400);
+ }
+
+ public List<IpamPool> describeIpamPools(String region, List<String> ipamPoolIds) {
+ if (ipamPoolIds != null && !ipamPoolIds.isEmpty()) {
+ List<IpamPool> result = new ArrayList<>();
+ for (String id : ipamPoolIds) {
+ result.add(requirePool(region, id));
+ }
+ return result;
+ }
+ List<IpamPool> result = new ArrayList<>();
+ for (IpamPool pool : pools.scan(k -> true)) {
+ if (region != null && pool.getRegion() != null && !region.equals(pool.getRegion())) {
+ continue;
+ }
+ result.add(pool);
+ }
+ return result;
+ }
+
+ public IpamPool deleteIpamPool(String region, String ipamPoolId) {
+ OwnedPool ownedPool = requireOwnedPoolForMutation(region, ipamPoolId);
+ IpamPool pool = ownedPool.pool();
+ deletePool(ownedPool);
+ pool.setState("delete-complete");
+ return pool;
+ }
+
+ public IpamPoolCidr provisionIpamPoolCidr(String region, String ipamPoolId, String cidr) {
+ return provisionIpamPoolCidr(region, ipamPoolId, cidr, null);
+ }
+
+ /**
+ * Provisions a CIDR onto a pool, honouring {@code ClientToken}: a replay returns the CIDR the
+ * first call provisioned instead of adding a duplicate entry.
+ */
+ public IpamPoolCidr provisionIpamPoolCidr(String region, String ipamPoolId, String cidr,
+ String clientToken) {
+ OwnedPool ownedPool = requireOwnedPoolForMutation(region, ipamPoolId);
+ IpamPool pool = ownedPool.pool();
+ if (clientToken != null && !clientToken.isBlank()) {
+ for (IpamPoolCidr existing : pool.getProvisionedCidrs()) {
+ if (clientToken.equals(existing.getClientToken())) {
+ return existing;
+ }
+ }
+ }
+ if (cidr == null || cidr.isBlank()) {
+ throw new AwsException("MissingParameter", "Cidr is required.", 400);
+ }
+ if (pool.getSourceIpamPoolId() != null) {
+ IpamPool source = requirePool(region, pool.getSourceIpamPoolId());
+ boolean inSource = source.getProvisionedCidrs().stream()
+ .anyMatch(provisioned -> Ipv4Cidrs.contains(provisioned.getCidr(), cidr));
+ if (!inSource) {
+ throw new AwsException("InvalidParameterValue",
+ "CIDR " + cidr + " is not within the provisioned CIDRs of source pool "
+ + pool.getSourceIpamPoolId() + ".", 400);
+ }
+ } else {
+ Ipv4Cidrs.contains(cidr, cidr); // validate syntax for top-level pools
+ }
+ IpamPoolCidr poolCidr = new IpamPoolCidr(cidr, "provisioned");
+ poolCidr.setClientToken(clientToken != null && !clientToken.isBlank() ? clientToken : null);
+ pool.getProvisionedCidrs().add(poolCidr);
+ savePool(ownedPool);
+ return poolCidr;
+ }
+
+ public List<IpamPoolCidr> getIpamPoolCidrs(String region, String ipamPoolId) {
+ return requirePool(region, ipamPoolId).getProvisionedCidrs();
+ }
+
+ // ─── Allocations ────────────────────────────────────────────────────────
+
+ public IpamPoolAllocation allocateIpamPoolCidr(String region, String ipamPoolId,
+ Integer netmaskLength, String cidr,
+ String description) {
+ return allocateIpamPoolCidr(region, ipamPoolId, netmaskLength, cidr, description, null);
+ }
+
+ /**
+ * Allocates a CIDR from a pool, honouring {@code ClientToken}. LZA's
+ * {@code get-ipam-subnet-cidr} custom resource retries this call, and without the replay
+ * check each retry would burn another distinct CIDR out of the pool.
+ */
+ public IpamPoolAllocation allocateIpamPoolCidr(String region, String ipamPoolId,
+ Integer netmaskLength, String cidr,
+ String description, String clientToken) {
+ OwnedPool ownedPool = requireOwnedPool(region, ipamPoolId);
+ IpamPool pool = ownedPool.pool();
+ if (clientToken != null && !clientToken.isBlank()) {
+ for (IpamPoolAllocation existing : pool.getAllocations()) {
+ if (clientToken.equals(existing.getClientToken())) {
+ return existing;
+ }
+ }
+ }
+ List<String> provisioned = pool.getProvisionedCidrs().stream()
+ .map(IpamPoolCidr::getCidr).toList();
+ List<String> occupied = occupiedSpace(pool);
+
+ String chosen;
+ if (cidr != null && !cidr.isBlank()) {
+ boolean inPool = provisioned.stream().anyMatch(p -> Ipv4Cidrs.contains(p, cidr));
+ if (!inPool) {
+ throw new AwsException("InvalidParameterValue",
+ "CIDR " + cidr + " is not within pool " + ipamPoolId + ".", 400);
+ }
+ boolean taken = occupied.stream().anyMatch(o -> Ipv4Cidrs.overlaps(o, cidr));
+ if (taken) {
+ throw new AwsException("InvalidParameterValue",
+ "CIDR " + cidr + " overlaps an existing allocation in pool " + ipamPoolId + ".", 400);
+ }
+ chosen = cidr;
+ } else if (netmaskLength != null) {
+ chosen = Ipv4Cidrs.firstFreeBlock(provisioned, occupied, netmaskLength);
+ if (chosen == null) {
+ throw new AwsException("InsufficientCidrBlocks",
+ "Pool " + ipamPoolId + " has no free /" + netmaskLength + " block.", 400);
+ }
+ } else {
+ throw new AwsException("MissingParameter",
+ "Either NetmaskLength or Cidr is required.", 400);
+ }
+
+ IpamPoolAllocation allocation = new IpamPoolAllocation();
+ allocation.setIpamPoolAllocationId("ipam-pool-alloc-" + randomHex(17));
+ allocation.setCidr(chosen);
+ allocation.setDescription(description);
+ allocation.setResourceType("custom");
+ allocation.setResourceOwner(config.defaultAccountId());
+ allocation.setClientToken(clientToken != null && !clientToken.isBlank() ? clientToken : null);
+ pool.getAllocations().add(allocation);
+ savePool(ownedPool);
+ LOG.infov("Allocated {0} from IPAM pool {1}", chosen, ipamPoolId);
+ return allocation;
+ }
+
+ public boolean releaseIpamPoolAllocation(String region, String ipamPoolId,
+ String ipamPoolAllocationId, String cidr) {
+ OwnedPool ownedPool = requireOwnedPool(region, ipamPoolId);
+ IpamPool pool = ownedPool.pool();
+ boolean removed = pool.getAllocations().removeIf(a ->
+ (ipamPoolAllocationId != null && ipamPoolAllocationId.equals(a.getIpamPoolAllocationId()))
+ || (ipamPoolAllocationId == null && cidr != null && cidr.equals(a.getCidr())));
+ if (!removed) {
+ String identifier = ipamPoolAllocationId != null
+ ? ipamPoolAllocationId
+ : "for CIDR " + cidr;
+ throw new AwsException("InvalidIpamPoolAllocationId.NotFound",
+ "Allocation " + identifier + " not found in pool " + ipamPoolId + ".", 400);
+ }
+ savePool(ownedPool);
+ return true;
+ }
+
+ public List<IpamPoolAllocation> getIpamPoolAllocations(String region, String ipamPoolId) {
+ return requirePool(region, ipamPoolId).getAllocations();
+ }
+
+ /**
+ * Space already unavailable in a pool: live allocations plus every CIDR
+ * provisioned onward to child pools.
+ */
+ private List<String> occupiedSpace(IpamPool pool) {
+ List<String> occupied = new ArrayList<>();
+ for (IpamPoolAllocation allocation : pool.getAllocations()) {
+ occupied.add(allocation.getCidr());
+ }
+ for (IpamPool other : allPools()) {
+ if (pool.getIpamPoolId().equals(other.getSourceIpamPoolId())) {
+ for (IpamPoolCidr provisioned : other.getProvisionedCidrs()) {
+ occupied.add(provisioned.getCidr());
+ }
+ }
+ }
+ return occupied;
+ }
+
+ // ─── Lookup helpers ─────────────────────────────────────────────────────
+
+ /**
+ * Resolves an IPAM the way pools resolve — across every account's partition — and then rejects
+ * a caller that does not own it. Modifying or deleting another account's IPAM is not an AWS
+ * operation, and AWS reports an IPAM you cannot see as absent.
+ */
+ private OwnedIpam requireOwnedIpamForMutation(String region, String ipamId) {
+ OwnedIpam ownedIpam = requireOwnedIpam(region, ipamId);
+ if (ownedIpam.accountId() != null && !ownedIpam.accountId().equals(callerAccountId())) {
+ throw ipamNotFound(ipamId);
+ }
+ return ownedIpam;
+ }
+
+ private OwnedIpam requireOwnedIpam(String region, String ipamId) {
+ if (ipams instanceof AccountAwareStorageBackend<?> rawAccountAware) {
+ @SuppressWarnings("unchecked")
+ AccountAwareStorageBackend<Ipam> accountAware =
+ (AccountAwareStorageBackend<Ipam>) rawAccountAware;
+ Optional<AccountAwareStorageBackend.OwnedEntry<Ipam>> exact =
+ accountAware.findAnyAccountEntry(key(region, ipamId));
+ if (exact.isPresent()) {
+ var entry = exact.get();
+ return new OwnedIpam(entry.account(), entry.value());
+ }
+ for (Ipam ipam : accountAware.scanAllAccounts()) {
+ if (ipam.getIpamId().equals(ipamId)) {
+ var entry = accountAware.findAnyAccountEntry(
+ key(ipam.getRegion(), ipam.getIpamId())).orElseThrow();
+ return new OwnedIpam(entry.account(), entry.value());
+ }
+ }
+ throw ipamNotFound(ipamId);
+ }
+
+ Optional<Ipam> direct = ipams.get(key(region, ipamId));
+ if (direct.isPresent()) {
+ return new OwnedIpam(null, direct.get());
+ }
+ for (Ipam ipam : ipams.scan(k -> true)) {
+ if (ipam.getIpamId().equals(ipamId)) {
+ return new OwnedIpam(null, ipam);
+ }
+ }
+ throw ipamNotFound(ipamId);
+ }
+
+ private void saveIpam(OwnedIpam ownedIpam) {
+ Ipam ipam = ownedIpam.ipam();
+ String ipamKey = key(ipam.getRegion(), ipam.getIpamId());
+ if (ownedIpam.accountId() != null
+ && ipams instanceof AccountAwareStorageBackend<?> rawAccountAware) {
+ @SuppressWarnings("unchecked")
+ AccountAwareStorageBackend<Ipam> accountAware =
+ (AccountAwareStorageBackend<Ipam>) rawAccountAware;
+ accountAware.putForAccount(ownedIpam.accountId(), ipamKey, ipam);
+ return;
+ }
+ ipams.put(ipamKey, ipam);
+ }
+
+ private void deleteIpamEntry(OwnedIpam ownedIpam) {
+ Ipam ipam = ownedIpam.ipam();
+ String ipamKey = key(ipam.getRegion(), ipam.getIpamId());
+ if (ownedIpam.accountId() != null
+ && ipams instanceof AccountAwareStorageBackend<?> rawAccountAware) {
+ @SuppressWarnings("unchecked")
+ AccountAwareStorageBackend<Ipam> accountAware =
+ (AccountAwareStorageBackend<Ipam>) rawAccountAware;
+ accountAware.deleteForAccount(ownedIpam.accountId(), ipamKey);
+ return;
+ }
+ ipams.delete(ipamKey);
+ }
+
+ private static AwsException ipamNotFound(String ipamId) {
+ return new AwsException("InvalidIpamId.NotFound", "IPAM " + ipamId + " does not exist.", 400);
+ }
+
+ private IpamPool requirePool(String region, String ipamPoolId) {
+ return requireOwnedPool(region, ipamPoolId).pool();
+ }
+
+ /**
+ * Resolves a pool for an operation on the pool itself. A RAM-shared pool permits cross-account
+ * <em>allocation</em>, but Modify/Delete/Provision are owner-only in AWS, which reports a pool
+ * you cannot act on as simply absent.
+ */
+ private OwnedPool requireOwnedPoolForMutation(String region, String ipamPoolId) {
+ OwnedPool ownedPool = requireOwnedPool(region, ipamPoolId);
+ if (ownedPool.accountId() != null && !ownedPool.accountId().equals(callerAccountId())) {
+ throw poolNotFound(ipamPoolId);
+ }
+ return ownedPool;
+ }
+
+ private OwnedPool requireOwnedPool(String region, String ipamPoolId) {
+ if (ipamPoolId == null || ipamPoolId.isBlank()) {
+ throw new AwsException("MissingParameter", "IpamPoolId is required.", 400);
+ }
+ if (pools instanceof AccountAwareStorageBackend<?> rawAccountAware) {
+ @SuppressWarnings("unchecked")
+ AccountAwareStorageBackend<IpamPool> accountAware =
+ (AccountAwareStorageBackend<IpamPool>) rawAccountAware;
+ Optional<AccountAwareStorageBackend.OwnedEntry<IpamPool>> exact =
+ accountAware.findAnyAccountEntry(key(region, ipamPoolId));
+ if (exact.isPresent()) {
+ var entry = exact.get();
+ return new OwnedPool(entry.account(), entry.value());
+ }
+ for (IpamPool pool : accountAware.scanAllAccounts()) {
+ if (pool.getIpamPoolId().equals(ipamPoolId)) {
+ var entry = accountAware.findAnyAccountEntry(
+ key(pool.getRegion(), pool.getIpamPoolId())).orElseThrow();
+ return new OwnedPool(entry.account(), entry.value());
+ }
+ }
+ throw poolNotFound(ipamPoolId);
+ }
+
+ Optional<IpamPool> direct = pools.get(key(region, ipamPoolId));
+ if (direct.isPresent()) {
+ return new OwnedPool(null, direct.get());
+ }
+ // RAM-shared pools are resolved from other accounts/regions by id.
+ for (IpamPool pool : pools.scan(k -> true)) {
+ if (pool.getIpamPoolId().equals(ipamPoolId)) {
+ return new OwnedPool(null, pool);
+ }
+ }
+ throw poolNotFound(ipamPoolId);
+ }
+
+ private List<IpamPool> allPools() {
+ if (pools instanceof AccountAwareStorageBackend<?> rawAccountAware) {
+ @SuppressWarnings("unchecked")
+ AccountAwareStorageBackend<IpamPool> accountAware =
+ (AccountAwareStorageBackend<IpamPool>) rawAccountAware;
+ return accountAware.scanAllAccounts();
+ }
+ return pools.scan(k -> true);
+ }
+
+ private void savePool(OwnedPool ownedPool) {
+ IpamPool pool = ownedPool.pool();
+ String poolKey = key(pool.getRegion(), pool.getIpamPoolId());
+ if (ownedPool.accountId() != null
+ && pools instanceof AccountAwareStorageBackend<?> rawAccountAware) {
+ @SuppressWarnings("unchecked")
+ AccountAwareStorageBackend<IpamPool> accountAware =
+ (AccountAwareStorageBackend<IpamPool>) rawAccountAware;
+ accountAware.putForAccount(ownedPool.accountId(), poolKey, pool);
+ return;
+ }
+ pools.put(poolKey, pool);
+ }
+
+ private void deletePool(OwnedPool ownedPool) {
+ IpamPool pool = ownedPool.pool();
+ String poolKey = key(pool.getRegion(), pool.getIpamPoolId());
+ if (ownedPool.accountId() != null
+ && pools instanceof AccountAwareStorageBackend<?> rawAccountAware) {
+ @SuppressWarnings("unchecked")
+ AccountAwareStorageBackend<IpamPool> accountAware =
+ (AccountAwareStorageBackend<IpamPool>) rawAccountAware;
+ accountAware.deleteForAccount(ownedPool.accountId(), poolKey);
+ return;
+ }
+ pools.delete(poolKey);
+ }
+
+ private static AwsException poolNotFound(String ipamPoolId) {
+ return new AwsException("InvalidIpamPoolId.NotFound",
+ "IPAM pool " + ipamPoolId + " does not exist.", 400);
+ }
+
+ private record OwnedPool(String accountId, IpamPool pool) {}
+
+ private record OwnedIpam(String accountId, Ipam ipam) {}
+
+ private static String key(String region, String id) {
+ return region + "|" + id;
+ }
+
+ private static String randomHex(int len) {
+ String chars = "0123456789abcdef";
+ StringBuilder sb = new StringBuilder(len);
+ ThreadLocalRandom r = ThreadLocalRandom.current();
+ for (int i = 0; i < len; i++) {
+ sb.append(chars.charAt(r.nextInt(chars.length())));
+ }
+ return sb.toString();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
index d2af0c9caf..2df94b0781 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
@@ -40,12 +40,17 @@ public class Ec2QueryHandler {
private final Ec2Service service;
private final EmulatorConfig config;
private final FlowLogService flowLogService;
+ private final Ec2EbsEncryptionService ebsEncryptionService;
+ private final Ec2IpamService ipamService;
@Inject
- public Ec2QueryHandler(Ec2Service service, EmulatorConfig config, FlowLogService flowLogService) {
+ public Ec2QueryHandler(Ec2Service service, EmulatorConfig config, FlowLogService flowLogService,
+ Ec2EbsEncryptionService ebsEncryptionService, Ec2IpamService ipamService) {
this.service = service;
this.config = config;
this.flowLogService = flowLogService;
+ this.ebsEncryptionService = ebsEncryptionService;
+ this.ipamService = ipamService;
}
public Response handle(String action, MultivaluedMap<String, String> params, String region) {
@@ -64,6 +69,13 @@ public class Ec2QueryHandler {
case "DescribeInstanceStatus" -> handleDescribeInstanceStatus(params, region);
case "DescribeInstanceAttribute" -> handleDescribeInstanceAttribute(params, region);
case "ModifyInstanceAttribute" -> handleModifyInstanceAttribute(params, region);
+ // EBS encryption defaults
+ case "GetEbsEncryptionByDefault" -> handleGetEbsEncryptionByDefault(region);
+ case "EnableEbsEncryptionByDefault" -> handleEnableEbsEncryptionByDefault(region);
+ case "DisableEbsEncryptionByDefault" -> handleDisableEbsEncryptionByDefault(region);
+ case "GetEbsDefaultKmsKeyId" -> handleGetEbsDefaultKmsKeyId(region);
+ case "ModifyEbsDefaultKmsKeyId" -> handleModifyEbsDefaultKmsKeyId(params, region);
+ case "ResetEbsDefaultKmsKeyId" -> handleResetEbsDefaultKmsKeyId(region);
// VPCs
case "CreateVpc" -> handleCreateVpc(params, region);
case "DescribeVpcs" -> handleDescribeVpcs(params, region);
@@ -121,6 +133,7 @@ public class Ec2QueryHandler {
case "DeleteTransitGatewayRoute" -> handleDeleteTransitGatewayRoute(params, region);
case "ReplaceTransitGatewayRoute" -> handleReplaceTransitGatewayRoute(params, region);
case "SearchTransitGatewayRoutes" -> handleSearchTransitGatewayRoutes(params, region);
+ case "ExportTransitGatewayRoutes" -> handleExportTransitGatewayRoutes(params, region);
case "CreateDefaultVpc" -> handleCreateDefaultVpc(params, region);
case "AssociateVpcCidrBlock" -> handleAssociateVpcCidrBlock(params, region);
case "DisassociateVpcCidrBlock" -> handleDisassociateVpcCidrBlock(params, region);
@@ -132,6 +145,7 @@ public class Ec2QueryHandler {
// Security Groups
case "CreateSecurityGroup" -> handleCreateSecurityGroup(params, region);
case "DescribeSecurityGroups" -> handleDescribeSecurityGroups(params, region);
+ case "GetSecurityGroupsForVpc" -> handleGetSecurityGroupsForVpc(params, region);
case "DeleteSecurityGroup" -> handleDeleteSecurityGroup(params, region);
case "AuthorizeSecurityGroupIngress" -> handleAuthorizeSecurityGroupIngress(params, region);
case "AuthorizeSecurityGroupEgress" -> handleAuthorizeSecurityGroupEgress(params, region);
@@ -222,6 +236,25 @@ public class Ec2QueryHandler {
case "RequestSpotInstances" -> handleRequestSpotInstances(params, region);
case "DescribeSpotInstanceRequests" -> handleDescribeSpotInstanceRequests(params, region);
case "CancelSpotInstanceRequests" -> handleCancelSpotInstanceRequests(params, region);
+ // IPAM
+ case "EnableIpamOrganizationAdminAccount" -> handleEnableIpamOrgAdmin(params);
+ case "DisableIpamOrganizationAdminAccount" -> handleDisableIpamOrgAdmin(params);
+ case "CreateIpam" -> handleCreateIpam(params, region);
+ case "DescribeIpams" -> handleDescribeIpams(params, region);
+ case "DeleteIpam" -> handleDeleteIpam(params, region);
+ case "ModifyIpam" -> handleModifyIpam(params, region);
+ case "CreateIpamPool" -> handleCreateIpamPool(params, region);
+ case "DescribeIpamPools" -> handleDescribeIpamPools(params, region);
+ case "DeleteIpamPool" -> handleDeleteIpamPool(params, region);
+ case "ModifyIpamPool" -> handleModifyIpamPool(params, region);
+ case "AssociateIpamByoasn" -> handleAssociateIpamByoasn(params, region);
+ case "DescribeIpamByoasn" -> handleDescribeIpamByoasn(params, region);
+ case "DisassociateIpamByoasn" -> handleDisassociateIpamByoasn(params, region);
+ case "ProvisionIpamPoolCidr" -> handleProvisionIpamPoolCidr(params, region);
+ case "GetIpamPoolCidrs" -> handleGetIpamPoolCidrs(params, region);
+ case "AllocateIpamPoolCidr" -> handleAllocateIpamPoolCidr(params, region);
+ case "ReleaseIpamPoolAllocation" -> handleReleaseIpamPoolAllocation(params, region);
+ case "GetIpamPoolAllocations" -> handleGetIpamPoolAllocations(params, region);
default -> ec2Error("UnsupportedOperation",
"Operation " + action + " is not supported.", 400);
};
@@ -501,6 +534,56 @@ public class Ec2QueryHandler {
}
}
+ // ─── EBS encryption defaults ─────────────────────────────────────────────
+
+ private Response handleGetEbsEncryptionByDefault(String region) {
+ return ebsEncryptionBooleanResponse("GetEbsEncryptionByDefaultResponse",
+ ebsEncryptionService.getEbsEncryptionByDefault(region));
+ }
+
+ private Response handleEnableEbsEncryptionByDefault(String region) {
+ return ebsEncryptionBooleanResponse("EnableEbsEncryptionByDefaultResponse",
+ ebsEncryptionService.enableEbsEncryptionByDefault(region));
+ }
+
+ private Response handleDisableEbsEncryptionByDefault(String region) {
+ return ebsEncryptionBooleanResponse("DisableEbsEncryptionByDefaultResponse",
+ ebsEncryptionService.disableEbsEncryptionByDefault(region));
+ }
+
+ private Response handleGetEbsDefaultKmsKeyId(String region) {
+ return ebsKmsKeyResponse("GetEbsDefaultKmsKeyIdResponse",
+ ebsEncryptionService.getEbsDefaultKmsKeyId(region));
+ }
+
+ private Response handleModifyEbsDefaultKmsKeyId(MultivaluedMap<String, String> p, String region) {
+ return ebsKmsKeyResponse("ModifyEbsDefaultKmsKeyIdResponse",
+ ebsEncryptionService.modifyEbsDefaultKmsKeyId(region, p.getFirst("KmsKeyId")));
+ }
+
+ private Response handleResetEbsDefaultKmsKeyId(String region) {
+ return ebsKmsKeyResponse("ResetEbsDefaultKmsKeyIdResponse",
+ ebsEncryptionService.resetEbsDefaultKmsKeyId(region));
+ }
+
+ private Response ebsEncryptionBooleanResponse(String rootElement, boolean enabled) {
+ XmlBuilder xml = new XmlBuilder()
+ .start(rootElement, AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("ebsEncryptionByDefault", String.valueOf(enabled))
+ .end(rootElement);
+ return xmlResponse(xml.build());
+ }
+
+ private Response ebsKmsKeyResponse(String rootElement, String kmsKeyId) {
+ XmlBuilder xml = new XmlBuilder()
+ .start(rootElement, AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("kmsKeyId", kmsKeyId)
+ .end(rootElement);
+ return xmlResponse(xml.build());
+ }
+
private Response xmlResponse(String xml) {
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
@@ -1093,6 +1176,361 @@ public class Ec2QueryHandler {
return xmlResponse(xml.build());
}
+ // ─── IPAM ─────────────────────────────────────────────────────────────────
+
+ private Response handleEnableIpamOrgAdmin(MultivaluedMap<String, String> p) {
+ ipamService.enableIpamOrganizationAdminAccount(p.getFirst("DelegatedAdminAccountId"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("EnableIpamOrganizationAdminAccountResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("success", "true")
+ .end("EnableIpamOrganizationAdminAccountResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDisableIpamOrgAdmin(MultivaluedMap<String, String> p) {
+ ipamService.disableIpamOrganizationAdminAccount(p.getFirst("DelegatedAdminAccountId"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("DisableIpamOrganizationAdminAccountResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("success", "true")
+ .end("DisableIpamOrganizationAdminAccountResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleCreateIpam(MultivaluedMap<String, String> p, String region) {
+ List<String> operatingRegions = new ArrayList<>();
+ for (int i = 1; p.getFirst("OperatingRegion." + i + ".RegionName") != null; i++) {
+ operatingRegions.add(p.getFirst("OperatingRegion." + i + ".RegionName"));
+ }
+ if (operatingRegions.isEmpty()) {
+ operatingRegions.add(region);
+ }
+ checkDryRun(p);
+ Ipam ipam = ipamService.createIpam(region, p.getFirst("Description"), operatingRegions,
+ null,
+ p.getFirst("EnablePrivateGua") == null ? false : Boolean.parseBoolean(p.getFirst("EnablePrivateGua")),
+ p.getFirst("MeteredAccount"), p.getFirst("Tier"), p.getFirst("ClientToken"),
+ parseTagsForResource(p, "ipam"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("CreateIpamResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString());
+ writeIpam(xml, "ipam", ipam);
+ xml.end("CreateIpamResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeIpams(MultivaluedMap<String, String> p, String region) {
+ checkDryRun(p);
+ List<String> ids = getList(p, "IpamId");
+ if (ids.isEmpty()) {
+ ids = getList(p, "IpamIds.member");
+ }
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeIpamsResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("ipamSet");
+ for (Ipam ipam : ipamService.describeIpams(region, ids)) {
+ writeIpam(xml, "item", ipam);
+ }
+ xml.end("ipamSet").end("DescribeIpamsResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDeleteIpam(MultivaluedMap<String, String> p, String region) {
+ checkDryRun(p);
+ Ipam ipam = ipamService.deleteIpam(region, p.getFirst("IpamId"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("DeleteIpamResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString());
+ writeIpam(xml, "ipam", ipam);
+ xml.end("DeleteIpamResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleAssociateIpamByoasn(MultivaluedMap<String, String> params, String region) {
+ checkDryRun(params);
+ AsnAssociation association = ipamService.associateIpamByoasn(region, params.getFirst("Asn"), params.getFirst("Cidr"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("AssociateIpamByoasnResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("asnAssociation")
+ .elem("asn", association.getAsn())
+ .elem("cidr", association.getCidr())
+ .elem("state", association.getState())
+ .elem("statusMessage", association.getStatusMessage())
+ .end("asnAssociation")
+ .end("AssociateIpamByoasnResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeIpamByoasn(MultivaluedMap<String, String> params, String region) {
+ checkDryRun(params);
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeIpamByoasnResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("byoasnSet");
+ for (AsnAssociation association : ipamService.describeIpamByoasn(region)) {
+ xml.start("item")
+ .elem("asn", association.getAsn())
+ .elem("ipamId", association.getIpamId())
+ .elem("state", association.getState())
+ .elem("statusMessage", association.getStatusMessage())
+ .end("item");
+ }
+ xml.end("byoasnSet").end("DescribeIpamByoasnResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDisassociateIpamByoasn(MultivaluedMap<String, String> params, String region) {
+ checkDryRun(params);
+ AsnAssociation association = ipamService.disassociateIpamByoasn(
+ region, params.getFirst("Asn"), params.getFirst("Cidr"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("DisassociateIpamByoasnResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("asnAssociation")
+ .elem("asn", association.getAsn())
+ .elem("cidr", association.getCidr())
+ .elem("state", association.getState())
+ .elem("statusMessage", association.getStatusMessage())
+ .end("asnAssociation")
+ .end("DisassociateIpamByoasnResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private void checkDryRun(MultivaluedMap<String, String> params) {
+ if (Boolean.parseBoolean(params.getFirst("DryRun"))) {
+ throw new AwsException("DryRunOperation", "Request would have succeeded, but DryRun flag is set.", 412);
+ }
+ }
+
+ private Response handleModifyIpam(MultivaluedMap<String, String> p, String region) {
+ checkDryRun(p);
+ List<String> addOperatingRegions = new ArrayList<>();
+ for (int i = 1; p.getFirst("AddOperatingRegion." + i + ".RegionName") != null; i++) {
+ addOperatingRegions.add(p.getFirst("AddOperatingRegion." + i + ".RegionName"));
+ }
+ List<String> removeOperatingRegions = new ArrayList<>();
+ for (int i = 1; p.getFirst("RemoveOperatingRegion." + i + ".RegionName") != null; i++) {
+ removeOperatingRegions.add(p.getFirst("RemoveOperatingRegion." + i + ".RegionName"));
+ }
+ Ipam ipam = ipamService.modifyIpam(
+ region,
+ p.getFirst("IpamId"),
+ p.getFirst("Description"),
+ addOperatingRegions,
+ removeOperatingRegions,
+ p.getFirst("EnablePrivateGua") == null ? null : Boolean.parseBoolean(p.getFirst("EnablePrivateGua")),
+ p.getFirst("MeteredAccount"),
+ p.getFirst("Tier"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("ModifyIpamResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString());
+ writeIpam(xml, "ipam", ipam);
+ xml.end("ModifyIpamResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleCreateIpamPool(MultivaluedMap<String, String> p, String region) {
+ checkDryRun(p);
+ IpamPool pool = ipamService.createIpamPool(region,
+ p.getFirst("IpamScopeId"),
+ p.getFirst("Locale"),
+ p.getFirst("SourceIpamPoolId"),
+ p.getFirst("AddressFamily"),
+ p.getFirst("Description"),
+ null,
+ p.getFirst("ClientToken"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("CreateIpamPoolResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString());
+ writeIpamPool(xml, "ipamPool", pool);
+ xml.end("CreateIpamPoolResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDescribeIpamPools(MultivaluedMap<String, String> p, String region) {
+ checkDryRun(p);
+ List<String> ids = getList(p, "IpamPoolId");
+ if (ids.isEmpty()) {
+ ids = getList(p, "IpamPoolIds.member");
+ }
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeIpamPoolsResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("ipamPoolSet");
+ for (IpamPool pool : ipamService.describeIpamPools(region, ids)) {
+ writeIpamPool(xml, "item", pool);
+ }
+ xml.end("ipamPoolSet").end("DescribeIpamPoolsResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleDeleteIpamPool(MultivaluedMap<String, String> p, String region) {
+ checkDryRun(p);
+ IpamPool pool = ipamService.deleteIpamPool(region, p.getFirst("IpamPoolId"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("DeleteIpamPoolResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString());
+ writeIpamPool(xml, "ipamPool", pool);
+ xml.end("DeleteIpamPoolResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleModifyIpamPool(MultivaluedMap<String, String> p, String region) {
+ checkDryRun(p);
+ IpamPool pool = ipamService.modifyIpamPool(
+ region,
+ p.getFirst("IpamPoolId"),
+ p.getFirst("Description"),
+ p.getFirst("AutoImport") == null ? null : Boolean.parseBoolean(p.getFirst("AutoImport")),
+ parseOptionalInt(p.getFirst("AllocationMinNetmaskLength"), "AllocationMinNetmaskLength"),
+ parseOptionalInt(p.getFirst("AllocationMaxNetmaskLength"), "AllocationMaxNetmaskLength"),
+ parseOptionalInt(p.getFirst("AllocationDefaultNetmaskLength"), "AllocationDefaultNetmaskLength"),
+ Boolean.parseBoolean(p.getFirst("ClearAllocationDefaultNetmaskLength")));
+ XmlBuilder xml = new XmlBuilder()
+ .start("ModifyIpamPoolResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString());
+ writeIpamPool(xml, "ipamPool", pool);
+ xml.end("ModifyIpamPoolResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleProvisionIpamPoolCidr(MultivaluedMap<String, String> p, String region) {
+ IpamPoolCidr cidr = ipamService.provisionIpamPoolCidr(region,
+ p.getFirst("IpamPoolId"), p.getFirst("Cidr"), p.getFirst("ClientToken"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("ProvisionIpamPoolCidrResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("ipamPoolCidr")
+ .elem("cidr", cidr.getCidr())
+ .elem("state", cidr.getState())
+ .end("ipamPoolCidr")
+ .end("ProvisionIpamPoolCidrResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleGetIpamPoolCidrs(MultivaluedMap<String, String> p, String region) {
+ XmlBuilder xml = new XmlBuilder()
+ .start("GetIpamPoolCidrsResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("ipamPoolCidrSet");
+ for (IpamPoolCidr cidr : ipamService.getIpamPoolCidrs(region, p.getFirst("IpamPoolId"))) {
+ xml.start("item")
+ .elem("cidr", cidr.getCidr())
+ .elem("state", cidr.getState())
+ .end("item");
+ }
+ xml.end("ipamPoolCidrSet").end("GetIpamPoolCidrsResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleAllocateIpamPoolCidr(MultivaluedMap<String, String> p, String region) {
+ IpamPoolAllocation allocation = ipamService.allocateIpamPoolCidr(region,
+ p.getFirst("IpamPoolId"),
+ parseOptionalInt(p.getFirst("NetmaskLength"), "NetmaskLength"),
+ p.getFirst("Cidr"),
+ p.getFirst("Description"),
+ p.getFirst("ClientToken"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("AllocateIpamPoolCidrResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString());
+ writeIpamPoolAllocation(xml, "ipamPoolAllocation", allocation);
+ xml.end("AllocateIpamPoolCidrResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleReleaseIpamPoolAllocation(MultivaluedMap<String, String> p, String region) {
+ ipamService.releaseIpamPoolAllocation(region,
+ p.getFirst("IpamPoolId"),
+ p.getFirst("IpamPoolAllocationId"),
+ p.getFirst("Cidr"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("ReleaseIpamPoolAllocationResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("success", "true")
+ .end("ReleaseIpamPoolAllocationResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private Response handleGetIpamPoolAllocations(MultivaluedMap<String, String> p, String region) {
+ XmlBuilder xml = new XmlBuilder()
+ .start("GetIpamPoolAllocationsResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("ipamPoolAllocationSet");
+ for (IpamPoolAllocation allocation
+ : ipamService.getIpamPoolAllocations(region, p.getFirst("IpamPoolId"))) {
+ writeIpamPoolAllocation(xml, "item", allocation);
+ }
+ xml.end("ipamPoolAllocationSet").end("GetIpamPoolAllocationsResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private void writeIpam(XmlBuilder xml, String wrapper, Ipam ipam) {
+ xml.start(wrapper)
+ .elem("ipamId", ipam.getIpamId())
+ .elem("ipamArn", ipam.getIpamArn())
+ .elem("ipamRegion", ipam.getRegion())
+ .elem("ownerId", ipam.getOwnerId())
+ .elem("publicDefaultScopeId", ipam.getPublicDefaultScopeId())
+ .elem("privateDefaultScopeId", ipam.getPrivateDefaultScopeId())
+ .elem("scopeCount", String.valueOf(ipam.getScopes().size()))
+ .elem("state", ipam.getState())
+ .elem("enablePrivateGua", String.valueOf(Boolean.TRUE.equals(ipam.getEnablePrivateGua())))
+ .elem("meteredAccount", ipam.getMeteredAccount())
+ .elem("tier", ipam.getTier());
+ if (ipam.getDescription() != null) {
+ xml.elem("description", ipam.getDescription());
+ }
+ xml.start("operatingRegionSet");
+ for (String operatingRegion : ipam.getOperatingRegions()) {
+ xml.start("item").elem("regionName", operatingRegion).end("item");
+ }
+ xml.end("operatingRegionSet")
+ .raw(tagSetXml(ipam.getTags()))
+ .end(wrapper);
+ }
+
+ private void writeIpamPool(XmlBuilder xml, String wrapper, IpamPool pool) {
+ xml.start(wrapper)
+ .elem("ipamPoolId", pool.getIpamPoolId())
+ .elem("ipamPoolArn", pool.getIpamPoolArn())
+ .elem("ipamScopeId", pool.getIpamScopeId())
+ .elem("ownerId", pool.getOwnerId())
+ .elem("locale", pool.getLocale())
+ .elem("addressFamily", pool.getAddressFamily())
+ .elem("state", pool.getState())
+ .elem("autoImport", String.valueOf(pool.isAutoImport()));
+ if (pool.getSourceIpamPoolId() != null) {
+ xml.elem("sourceIpamPoolId", pool.getSourceIpamPoolId());
+ }
+ if (pool.getDescription() != null) {
+ xml.elem("description", pool.getDescription());
+ }
+ if (pool.getAllocationMinNetmaskLength() != null) {
+ xml.elem("allocationMinNetmaskLength", String.valueOf(pool.getAllocationMinNetmaskLength()));
+ }
+ if (pool.getAllocationMaxNetmaskLength() != null) {
+ xml.elem("allocationMaxNetmaskLength", String.valueOf(pool.getAllocationMaxNetmaskLength()));
+ }
+ if (pool.getAllocationDefaultNetmaskLength() != null) {
+ xml.elem("allocationDefaultNetmaskLength", String.valueOf(pool.getAllocationDefaultNetmaskLength()));
+ }
+ xml.end(wrapper);
+ }
+
+ private void writeIpamPoolAllocation(XmlBuilder xml, String wrapper, IpamPoolAllocation allocation) {
+ xml.start(wrapper)
+ .elem("ipamPoolAllocationId", allocation.getIpamPoolAllocationId())
+ .elem("cidr", allocation.getCidr())
+ .elem("resourceType", allocation.getResourceType());
+ if (allocation.getDescription() != null) {
+ xml.elem("description", allocation.getDescription());
+ }
+ xml.end(wrapper);
+ }
+
private Response handleCreateVpcEndpoint(MultivaluedMap<String, String> p, String region) {
VpcEndpoint endpoint = service.createVpcEndpoint(
region,
@@ -1601,6 +2039,17 @@ public class Ec2QueryHandler {
return xmlResponse(xml.build());
}
+ private Response handleExportTransitGatewayRoutes(MultivaluedMap<String, String> p, String region) {
+ String s3Location = service.exportTransitGatewayRoutes(
+ region, p.getFirst("TransitGatewayRouteTableId"), p.getFirst("S3Bucket"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("ExportTransitGatewayRoutesResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("s3Location", s3Location)
+ .end("ExportTransitGatewayRoutesResponse");
+ return xmlResponse(xml.build());
+ }
+
private String routeTableXml(TransitGatewayRouteTable routeTable, boolean includeTags) {
XmlBuilder xml = new XmlBuilder()
.elem("transitGatewayRouteTableId", routeTable.getTransitGatewayRouteTableId())
@@ -1794,6 +2243,7 @@ public class Ec2QueryHandler {
return xmlResponse(xml.build());
}
+
private Response handleCreateDefaultVpc(MultivaluedMap<String, String> p, String region) {
Vpc vpc = service.createDefaultVpc(region);
XmlBuilder xml = new XmlBuilder()
@@ -1913,6 +2363,28 @@ public class Ec2QueryHandler {
return xmlResponse(xml.build());
}
+ private Response handleGetSecurityGroupsForVpc(MultivaluedMap<String, String> p, String region) {
+ String vpcId = p.getFirst("VpcId");
+ Map<String, List<String>> filters = getFilters(p);
+ List<SecurityGroup> sgs = service.getSecurityGroupsForVpc(region, vpcId, filters);
+ XmlBuilder xml = new XmlBuilder()
+ .start("GetSecurityGroupsForVpcResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .start("securityGroupForVpcSet");
+ for (SecurityGroup sg : sgs) {
+ xml.start("item")
+ .elem("groupId", sg.getGroupId())
+ .elem("groupName", sg.getGroupName())
+ .elem("description", sg.getDescription())
+ .elem("ownerId", sg.getOwnerId())
+ .elem("primaryVpcId", sg.getVpcId())
+ .raw(tagSetXml(sg.getTags()))
+ .end("item");
+ }
+ xml.end("securityGroupForVpcSet").end("GetSecurityGroupsForVpcResponse");
+ return xmlResponse(xml.build());
+ }
+
private Response handleDeleteSecurityGroup(MultivaluedMap<String, String> p, String region) {
String groupId = p.getFirst("GroupId");
if (groupId == null) groupId = p.getFirst("GroupName");
@@ -3426,6 +3898,9 @@ public class Ec2QueryHandler {
if (endpoint.getCreationTimestamp() != null) {
xml.elem("creationTimestamp", ISO_FMT.format(endpoint.getCreationTimestamp()));
}
+ if (endpoint.getPolicyDocument() != null) {
+ xml.elem("policyDocument", endpoint.getPolicyDocument());
+ }
xml.start("routeTableIdSet");
for (String routeTableId : endpoint.getRouteTableIds()) {
xml.elem("item", routeTableId);
@@ -3441,9 +3916,6 @@ public class Ec2QueryHandler {
xml.start("item").elem("groupId", securityGroupId).end("item");
}
xml.end("groupSet");
- if (endpoint.getPolicyDocument() != null) {
- xml.elem("policyDocument", endpoint.getPolicyDocument());
- }
xml.raw(tagSetXml(endpoint.getTags()));
return xml.build();
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
index d0b73ee7ec..d5f3607148 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
@@ -1892,6 +1892,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return applyRouteFilters(routes, filters);
}
+ /** No real S3 write — returns a location string (unique random suffix) matching the export naming AWS uses. */
+ public String exportTransitGatewayRoutes(String region, String routeTableId, String s3Bucket) {
+ getRequiredTransitGatewayRouteTable(region, routeTableId);
+ if (s3Bucket == null || s3Bucket.isBlank()) {
+ throw new AwsException("MissingParameter", "S3Bucket is required.", 400);
+ }
+ return "s3://" + s3Bucket + "/" + routeTableId + "-" + randomHex(8) + ".csv";
+ }
+
/**
* The route search filters, as the live API applies them. The three CIDR relationship filters
* differ in the value they take, which is not something the reference spells out:
@@ -2871,6 +2880,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
.collect(Collectors.toList());
}
+
public List<VpcEndpoint> deleteVpcEndpoints(String region, List<String> endpointIds) {
ensureDefaultResources(region);
List<VpcEndpoint> deleted = new ArrayList<>();
@@ -3075,6 +3085,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
.collect(Collectors.toList());
}
+ public List<SecurityGroup> getSecurityGroupsForVpc(String region, String vpcId,
+ Map<String, List<String>> filters) {
+ ensureDefaultResources(region);
+ getRequiredVpc(region, vpcId);
+ return securityGroups.scan(k -> true).stream()
+ .filter(sg -> sg.getRegion().equals(region))
+ .filter(sg -> vpcId.equals(sg.getVpcId()))
+ .filter(sg -> matchesFilters(sg, filters, region))
+ .collect(Collectors.toList());
+ }
+
public void deleteSecurityGroup(String region, String groupId) {
ensureDefaultResources(region);
if (securityGroups.get(key(region, groupId)).isEmpty()) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ipv4Cidrs.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ipv4Cidrs.java
new file mode 100644
index 0000000000..2a4c554774
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ipv4Cidrs.java
@@ -0,0 +1,113 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+
+import java.util.List;
+
+/**
+ * Minimal IPv4 CIDR math backing the IPAM emulation: containment, overlap and
+ * first-free-block scans over a pool's provisioned space.
+ */
+final class Ipv4Cidrs {
+
+ private Ipv4Cidrs() {}
+
+ /** True when {@code inner} lies entirely within {@code outer}. */
+ static boolean contains(String outer, String inner) {
+ long[] o = parse(outer);
+ long[] i = parse(inner);
+ return o[0] <= i[0] && i[1] <= o[1];
+ }
+
+ /** True when the two blocks share any address. */
+ static boolean overlaps(String a, String b) {
+ long[] x = parse(a);
+ long[] y = parse(b);
+ return x[0] <= y[1] && y[0] <= x[1];
+ }
+
+ /**
+ * The first /{@code netmask} block inside any of the {@code provisioned}
+ * CIDRs (in order) that overlaps none of the {@code occupied} CIDRs, or
+ * {@code null} when the space is exhausted or the request is larger than
+ * every provisioned block.
+ */
+ static String firstFreeBlock(List<String> provisioned, List<String> occupied, int netmask) {
+ if (netmask < 0 || netmask > 32) {
+ throw invalid("/" + netmask);
+ }
+ long size = 1L << (32 - netmask);
+ for (String pool : provisioned) {
+ long[] p = parse(pool);
+ long base = alignUp(p[0], size);
+ while (base + size - 1 <= p[1]) {
+ long blockedUntil = -1;
+ for (String occ : occupied) {
+ long[] o = parse(occ);
+ if (o[0] <= base + size - 1 && base <= o[1]) {
+ blockedUntil = Math.max(blockedUntil, o[1]);
+ }
+ }
+ if (blockedUntil < 0) {
+ return toIp(base) + "/" + netmask;
+ }
+ base = alignUp(blockedUntil + 1, size);
+ }
+ }
+ return null;
+ }
+
+ private static long alignUp(long address, long size) {
+ long rem = address % size;
+ return rem == 0 ? address : address + (size - rem);
+ }
+
+ /** Parse "a.b.c.d/len" into {firstAddress, lastAddress} (network-aligned). */
+ private static long[] parse(String cidr) {
+ if (cidr == null) {
+ throw invalid("null");
+ }
+ int slash = cidr.indexOf('/');
+ if (slash < 0) {
+ throw invalid(cidr);
+ }
+ int prefix;
+ try {
+ prefix = Integer.parseInt(cidr.substring(slash + 1));
+ } catch (NumberFormatException e) {
+ throw invalid(cidr);
+ }
+ if (prefix < 0 || prefix > 32) {
+ throw invalid(cidr);
+ }
+ String[] octets = cidr.substring(0, slash).split("\\.");
+ if (octets.length != 4) {
+ throw invalid(cidr);
+ }
+ long ip = 0;
+ for (String octet : octets) {
+ int value;
+ try {
+ value = Integer.parseInt(octet);
+ } catch (NumberFormatException e) {
+ throw invalid(cidr);
+ }
+ if (value < 0 || value > 255) {
+ throw invalid(cidr);
+ }
+ ip = (ip << 8) | value;
+ }
+ long size = 1L << (32 - prefix);
+ long base = (ip / size) * size;
+ return new long[] {base, base + size - 1};
+ }
+
+ private static String toIp(long address) {
+ return ((address >> 24) & 0xFF) + "." + ((address >> 16) & 0xFF) + "."
+ + ((address >> 8) & 0xFF) + "." + (address & 0xFF);
+ }
+
+ private static AwsException invalid(String cidr) {
+ return new AwsException("InvalidParameterValue", "Invalid IPv4 CIDR: " + cidr, 400);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/AsnAssociation.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/AsnAssociation.java
new file mode 100644
index 0000000000..b77ba0f7e6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/AsnAssociation.java
@@ -0,0 +1,35 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AsnAssociation {
+ private String asn;
+ private String cidr;
+ private String ipamId;
+ private String state;
+ private String statusMessage;
+
+ public AsnAssociation() {}
+
+ public AsnAssociation(String asn, String cidr, String ipamId, String state, String statusMessage) {
+ this.asn = asn;
+ this.cidr = cidr;
+ this.ipamId = ipamId;
+ this.state = state;
+ this.statusMessage = statusMessage;
+ }
+
+ public String getAsn() { return asn; }
+ public void setAsn(String asn) { this.asn = asn; }
+ public String getCidr() { return cidr; }
+ public void setCidr(String cidr) { this.cidr = cidr; }
+ public String getIpamId() { return ipamId; }
+ public void setIpamId(String ipamId) { this.ipamId = ipamId; }
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+ public String getStatusMessage() { return statusMessage; }
+ public void setStatusMessage(String statusMessage) { this.statusMessage = statusMessage; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Ipam.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Ipam.java
new file mode 100644
index 0000000000..7ab1e5f172
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Ipam.java
@@ -0,0 +1,75 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Ipam {
+
+ private String ipamId;
+ private String ipamArn;
+ private String ownerId;
+ private String region;
+ private String description;
+ private String publicDefaultScopeId;
+ private String privateDefaultScopeId;
+ private String state;
+ private Boolean enablePrivateGua;
+ private String meteredAccount;
+ private String tier;
+ private String clientToken;
+ private List<String> operatingRegions = new ArrayList<>();
+ private List<IpamScope> scopes = new ArrayList<>();
+ private List<Tag> tags = new ArrayList<>();
+
+ public Ipam() {}
+
+ public String getIpamId() { return ipamId; }
+ public void setIpamId(String ipamId) { this.ipamId = ipamId; }
+
+ public String getIpamArn() { return ipamArn; }
+ public void setIpamArn(String ipamArn) { this.ipamArn = ipamArn; }
+
+ public String getOwnerId() { return ownerId; }
+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+
+ public String getPublicDefaultScopeId() { return publicDefaultScopeId; }
+ public void setPublicDefaultScopeId(String publicDefaultScopeId) { this.publicDefaultScopeId = publicDefaultScopeId; }
+
+ public String getPrivateDefaultScopeId() { return privateDefaultScopeId; }
+ public void setPrivateDefaultScopeId(String privateDefaultScopeId) { this.privateDefaultScopeId = privateDefaultScopeId; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+
+ public Boolean getEnablePrivateGua() { return enablePrivateGua; }
+ public void setEnablePrivateGua(Boolean enablePrivateGua) { this.enablePrivateGua = enablePrivateGua; }
+
+ public String getMeteredAccount() { return meteredAccount; }
+ public void setMeteredAccount(String meteredAccount) { this.meteredAccount = meteredAccount; }
+
+ public String getTier() { return tier; }
+ public void setTier(String tier) { this.tier = tier; }
+
+ public String getClientToken() { return clientToken; }
+ public void setClientToken(String clientToken) { this.clientToken = clientToken; }
+
+ public List<String> getOperatingRegions() { return operatingRegions; }
+ public void setOperatingRegions(List<String> operatingRegions) { this.operatingRegions = operatingRegions; }
+
+ public List<IpamScope> getScopes() { return scopes; }
+ public void setScopes(List<IpamScope> scopes) { this.scopes = scopes; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpamPool.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpamPool.java
new file mode 100644
index 0000000000..949f9a7157
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpamPool.java
@@ -0,0 +1,98 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class IpamPool {
+
+ private String ipamPoolId;
+ private String ipamPoolArn;
+ private String ipamId;
+ private String ipamScopeId;
+ private String ownerId;
+ private String region;
+ private String locale;
+ private String sourceIpamPoolId;
+ private String addressFamily;
+ private String description;
+ private String state;
+ private boolean autoImport;
+ private Integer allocationMinNetmaskLength;
+ private Integer allocationMaxNetmaskLength;
+ private Integer allocationDefaultNetmaskLength;
+ private List<IpamPoolCidr> provisionedCidrs = new ArrayList<>();
+ private List<IpamPoolAllocation> allocations = new ArrayList<>();
+ private List<Tag> tags = new ArrayList<>();
+ /** Idempotency token of the CreateIpamPool call that created this pool. */
+ private String clientToken;
+
+ public IpamPool() {}
+
+ public String getIpamPoolId() { return ipamPoolId; }
+ public void setIpamPoolId(String ipamPoolId) { this.ipamPoolId = ipamPoolId; }
+
+ public String getIpamPoolArn() { return ipamPoolArn; }
+ public void setIpamPoolArn(String ipamPoolArn) { this.ipamPoolArn = ipamPoolArn; }
+
+ public String getIpamId() { return ipamId; }
+ public void setIpamId(String ipamId) { this.ipamId = ipamId; }
+
+ public String getIpamScopeId() { return ipamScopeId; }
+ public void setIpamScopeId(String ipamScopeId) { this.ipamScopeId = ipamScopeId; }
+
+ public String getOwnerId() { return ownerId; }
+ public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public String getLocale() { return locale; }
+ public void setLocale(String locale) { this.locale = locale; }
+
+ public String getSourceIpamPoolId() { return sourceIpamPoolId; }
+ public void setSourceIpamPoolId(String sourceIpamPoolId) { this.sourceIpamPoolId = sourceIpamPoolId; }
+
+ public String getAddressFamily() { return addressFamily; }
+ public void setAddressFamily(String addressFamily) { this.addressFamily = addressFamily; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+
+ public boolean isAutoImport() { return autoImport; }
+ public void setAutoImport(boolean autoImport) { this.autoImport = autoImport; }
+
+ public Integer getAllocationMinNetmaskLength() { return allocationMinNetmaskLength; }
+ public void setAllocationMinNetmaskLength(Integer allocationMinNetmaskLength) {
+ this.allocationMinNetmaskLength = allocationMinNetmaskLength;
+ }
+
+ public Integer getAllocationMaxNetmaskLength() { return allocationMaxNetmaskLength; }
+ public void setAllocationMaxNetmaskLength(Integer allocationMaxNetmaskLength) {
+ this.allocationMaxNetmaskLength = allocationMaxNetmaskLength;
+ }
+
+ public Integer getAllocationDefaultNetmaskLength() { return allocationDefaultNetmaskLength; }
+ public void setAllocationDefaultNetmaskLength(Integer allocationDefaultNetmaskLength) {
+ this.allocationDefaultNetmaskLength = allocationDefaultNetmaskLength;
+ }
+
+ public List<IpamPoolCidr> getProvisionedCidrs() { return provisionedCidrs; }
+ public void setProvisionedCidrs(List<IpamPoolCidr> provisionedCidrs) { this.provisionedCidrs = provisionedCidrs; }
+
+ public List<IpamPoolAllocation> getAllocations() { return allocations; }
+ public void setAllocations(List<IpamPoolAllocation> allocations) { this.allocations = allocations; }
+
+ public List<Tag> getTags() { return tags; }
+ public void setTags(List<Tag> tags) { this.tags = tags; }
+
+ public String getClientToken() { return clientToken; }
+ public void setClientToken(String clientToken) { this.clientToken = clientToken; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpamPoolAllocation.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpamPoolAllocation.java
new file mode 100644
index 0000000000..ae87781819
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpamPoolAllocation.java
@@ -0,0 +1,41 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class IpamPoolAllocation {
+
+ private String ipamPoolAllocationId;
+ private String cidr;
+ private String description;
+ private String resourceType;
+ private String resourceId;
+ private String resourceOwner;
+ /** Idempotency token of the AllocateIpamPoolCidr call that created this allocation. */
+ private String clientToken;
+
+ public IpamPoolAllocation() {}
+
+ public String getIpamPoolAllocationId() { return ipamPoolAllocationId; }
+ public void setIpamPoolAllocationId(String ipamPoolAllocationId) { this.ipamPoolAllocationId = ipamPoolAllocationId; }
+
+ public String getCidr() { return cidr; }
+ public void setCidr(String cidr) { this.cidr = cidr; }
+
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+
+ public String getResourceType() { return resourceType; }
+ public void setResourceType(String resourceType) { this.resourceType = resourceType; }
+
+ public String getResourceId() { return resourceId; }
+ public void setResourceId(String resourceId) { this.resourceId = resourceId; }
+
+ public String getResourceOwner() { return resourceOwner; }
+ public void setResourceOwner(String resourceOwner) { this.resourceOwner = resourceOwner; }
+
+ public String getClientToken() { return clientToken; }
+ public void setClientToken(String clientToken) { this.clientToken = clientToken; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpamPoolCidr.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpamPoolCidr.java
new file mode 100644
index 0000000000..c077bcd3eb
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpamPoolCidr.java
@@ -0,0 +1,30 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class IpamPoolCidr {
+
+ private String cidr;
+ private String state;
+ /** Idempotency token of the ProvisionIpamPoolCidr call that created this CIDR. */
+ private String clientToken;
+
+ public IpamPoolCidr() {}
+
+ public IpamPoolCidr(String cidr, String state) {
+ this.cidr = cidr;
+ this.state = state;
+ }
+
+ public String getCidr() { return cidr; }
+ public void setCidr(String cidr) { this.cidr = cidr; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+
+ public String getClientToken() { return clientToken; }
+ public void setClientToken(String clientToken) { this.clientToken = clientToken; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpamScope.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpamScope.java
new file mode 100644
index 0000000000..2cc7d7b69d
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpamScope.java
@@ -0,0 +1,36 @@
+package io.github.hectorvent.floci.services.ec2.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class IpamScope {
+
+ private String ipamScopeId;
+ private String ipamScopeArn;
+ private String ipamId;
+ private String scopeType;
+ private boolean isDefault;
+ private String state;
+
+ public IpamScope() {}
+
+ public String getIpamScopeId() { return ipamScopeId; }
+ public void setIpamScopeId(String ipamScopeId) { this.ipamScopeId = ipamScopeId; }
+
+ public String getIpamScopeArn() { return ipamScopeArn; }
+ public void setIpamScopeArn(String ipamScopeArn) { this.ipamScopeArn = ipamScopeArn; }
+
+ public String getIpamId() { return ipamId; }
+ public void setIpamId(String ipamId) { this.ipamId = ipamId; }
+
+ public String getScopeType() { return scopeType; }
+ public void setScopeType(String scopeType) { this.scopeType = scopeType; }
+
+ public boolean isDefault() { return isDefault; }
+ public void setDefault(boolean isDefault) { this.isDefault = isDefault; }
+
+ public String getState() { return state; }
+ public void setState(String state) { this.state = state; }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2EbsEncryptionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2EbsEncryptionIntegrationTest.java
new file mode 100644
index 0000000000..daab146a6a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2EbsEncryptionIntegrationTest.java
@@ -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"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2EbsEncryptionServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2EbsEncryptionServiceTest.java
new file mode 100644
index 0000000000..194573d068
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2EbsEncryptionServiceTest.java
@@ -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", " "));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ExportTransitGatewayRoutesConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ExportTransitGatewayRoutesConsumerTest.java
new file mode 100644
index 0000000000..b9a6b4e32c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ExportTransitGatewayRoutesConsumerTest.java
@@ -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"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
index 6e76716fc0..080f0462a0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
@@ -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);
+ }
+
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamClientTokenConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamClientTokenConsumerTest.java
new file mode 100644
index 0000000000..543d48e7b8
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamClientTokenConsumerTest.java
@@ -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"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamOwnerAccountConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamOwnerAccountConsumerTest.java
new file mode 100644
index 0000000000..b962a6675b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamOwnerAccountConsumerTest.java
@@ -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/"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamServiceTest.java
new file mode 100644
index 0000000000..9beb16dedb
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IpamServiceTest.java
@@ -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());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ModifyIpamPoolConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ModifyIpamPoolConsumerTest.java
new file mode 100644
index 0000000000..a7b76afa17
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ModifyIpamPoolConsumerTest.java
@@ -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"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java
index a649e22432..d65d04dcfa 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java
@@ -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);
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointSecurityGroupConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointSecurityGroupConsumerTest.java
new file mode 100644
index 0000000000..cc3ff76d42
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointSecurityGroupConsumerTest.java
@@ -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"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ipv4CidrsTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ipv4CidrsTest.java
new file mode 100644
index 0000000000..9816b804f0
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ipv4CidrsTest.java
@@ -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"));
+ }
+}