mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(ec2): IPAM with real CIDR allocation, EBS encryption defaults, and transit gateway route export (#2596)
* feat(ec2): add IPAM model, CIDR math and Ec2IpamService
Emulates VPC IPAM: organization admin delegation, IPAMs with default scopes, hierarchical pools with provisioned CIDRs, and netmask/specific-CIDR allocations that skip space held by allocations and child pools. This is the surface LZA needs for Custom::EnableIpamOrganizationAdminAccount (Organization stage) and the get-ipam-subnet-cidr Lambda (Deploy stage).
* feat(ec2): wire IPAM actions into the EC2 query handler
Adds 13 dispatch arms and XML writers: enable/disable org admin, IPAM and pool CRUD, provisioned CIDR reads, and pool CIDR allocate/release/list.
* test(ec2): construct Ec2QueryHandler with the IPAM service
* feat(storage): add OwnedEntry/findAnyAccount helpers
Extracted from 9dfda3cb (fix(s3): resolve buckets cross-account under
a global bucket namespace) — that commit's storage-layer helpers are a
genuine prerequisite for the Route 53 VPC associations work that follows,
but its full diff also carries an unrelated S3 replication feature chain.
This isolates just the additive AccountAwareStorageBackend.OwnedEntry /
findAnyAccount / findAnyAccountEntry helpers those commits need.
* feat(ec2): add owner-account overload for createIpamPool
Adds a createIpamPool overload taking an explicit ownerId, with the 6-arg
form delegating to it using the ambient default account. Purely additive
delegation; existing callers are unaffected.
Provenance: extracted verbatim from 91b93aab ("fix(ec2): stamp IPAM and IPAM
pool ownerId with the resolved account"), which is otherwise CloudFormation
provisioning work and remains on hold. Only the Ec2IpamService method is taken
here — none of that commit's Cfn provisioner files are included. The overload
itself touches no CloudFormation code; it is needed because account-scoped IPAM
tests construct pools for an explicit owning account.
* feat(ec2): add IPAM ASN associations and discovery operations
* fix: preserve shared IPAM pool ownership
* feat(ec2): add ModifyIpamPool
Net-new operation, part of the deferred 16-op EC2 IPAM/TransitGateway
P0 block. IpamPool gains autoImport, allocationMinNetmaskLength,
allocationMaxNetmaskLength, and allocationDefaultNetmaskLength fields
(the CIDR allocation defaults real ModifyIpamPool controls); resource
tag add/remove is out of scope for this pass.
Persists through the existing requireOwnedPool/savePool account-scoped
helpers, matching every other pool mutation in this service.
* feat(ec2): EBS account-level encryption defaults
Adds Get/Enable/DisableEbsEncryptionByDefault and
Get/Modify/ResetEbsDefaultKmsKeyId, region-scoped with the AWS-managed
alias/aws/ebs fallback. LZA's SecurityStack
Custom::EnableEbsEncryptionByDefault Lambda calls these and previously
failed with UnsupportedOperation.
* test(ec2): construct Ec2QueryHandler with the EBS encryption service
* feat(ec2): add GetSecurityGroupsForVpc and ModifyVpcEndpoint
Two of the deferred 16-op EC2 IPAM/TransitGateway P0 block; grouped
together since neither has ties to IPAM or TransitGateway and there
was no existing feature branch for standalone VPC-endpoint/
security-group work.
GetSecurityGroupsForVpc filters the existing security group store by
vpcId, using the simplified SecurityGroupForVpc response shape (no
ipPermissions) per the real API. ModifyVpcEndpoint adds a
policyDocument field to VpcEndpoint plus add/remove-list handling for
route tables, subnets, and security groups; IpAddressType/DnsOptions/
SubnetConfigurations are out of scope for this pass.
New branch cut from main (both ops depend only on core SecurityGroup/
VpcEndpoint infra that already lives there, not on any in-flight
feature branch's work).
* feat(ec2): add ExportTransitGatewayRoutes
No real S3 write happens: the operation validates the route table and
bucket, then returns a deterministic s3:// location string matching the
real operation's export naming convention.
* fix(ec2): honour ClientToken on the IPAM pool creates and allocations
* fix(ec2): keep IPAM and IPAM-pool mutations owner-only
* fix(ec2): return MissingParameter for absent IPAM pool and scope ids
* fix(ec2): store the IPAM delegated administrator organization-wide
* test(ec2): cover IPAM ClientToken idempotency at the wire level
* docs(ec2): document the IPAM operations
* docs(ec2): document the EBS encryption defaults and the other branch-added operations
* fix(ec2): drop the ModifyVpcEndpoint copy superseded by upstream #2526
Upstream landed its own ModifyVpcEndpoint (2e8cbc13d), so the branch
copy became a duplicate case label, a duplicate handler and service
method, and a doubled policyDocument element in vpcEndpointXml. The
branch wire tests now exercise the upstream implementation and pass
unchanged. GetSecurityGroupsForVpc from the same original commit is
not upstream and stays.
* fix(ec2): enforce the modelled IPAM enums on create and modify
Tier, MeteredAccount and AddressFamily are all modelled enums, and all
three were stored verbatim. CreateIpam and ModifyIpam wrote whatever
arrived into the IPAM and DescribeIpams echoed it back; CreateIpamPool did
the same with AddressFamily, which is worse than cosmetic — it is what
decides how the pool's CIDRs are parsed and allocated, so a pool created
with a third address family is a pool whose CIDR math never made sense.
Reject an unmodelled value with InvalidParameterValue, the code the rest
of this service already answers for a bad parameter. An absent value still
falls through to the AWS default, since every one of these members is
optional.
* fix(ec2): report the calling account as IPAM owner and harden IPAM input parsing
- CreateIpam/CreateIpamPool recorded config.defaultAccountId() as owner
while account-aware storage partitioned by the caller, so a non-default
account got resources whose ownerId and ARN named the wrong account.
The handler now passes null and the service resolves null-means-caller
with the same fallback chain storage uses.
- The ContextNotActiveException fallback in callerAccountId() now logs at
debug so an unexpected context loss is diagnosable.
- Netmask-length parameters on ModifyIpamPool and AllocateIpamPoolCidr go
through parseOptionalInt, returning InvalidParameterValue instead of an
unmapped NumberFormatException on non-integer input.
- ReleaseIpamPoolAllocation's not-found message names the CIDR when no
allocation id was supplied instead of rendering 'Allocation null'.
- Reworded the ExportTransitGatewayRoutes Javadoc: the S3 location has a
unique random suffix, it is not deterministic.
* fix(ec2): require management account for IPAM org-admin delegation
EnableIpamOrganizationAdminAccount and DisableIpamOrganizationAdminAccount
never checked the calling account, so any member account could change or
remove the org-wide IPAM delegated administrator. Real AWS restricts both
operations to the organization's management account.
This emulator has no cross-service organization membership to resolve the
true management account from, so the configured default account stands in
for it — the same account launched Lambdas resolve to when calling without
an assumed role, matching how LZA's Organization-stage custom resource
invokes these operations.
* test(ec2): verify the IPAM org-admin gate against the real query path
Confirms EnableIpamOrganizationAdminAccount/DisableIpamOrganizationAdminAccount
succeed over the actual query-protocol endpoint using the same non-12-digit
credential style every other test in this suite uses, which
AccountContextFilter/AccountResolver resolve to the configured default
account -- the same resolution LZA's Organization-stage custom resource
relies on. Verifies 79bc8e251's management-account gate does not regress
that path.
* docs: drop the ec2 docs-drift tracking file, filed as floci-io/floci#2605
pgermosen's review on #2596 correctly flagged this file as a parallel,
invisible issue tracker that introduces a new top-level directory main
doesn't have, cites internal workflow details a maintainer can't act
on, and references a stale commit SHA unreachable from this branch's
history. The underlying finding (ten operations Ec2QueryHandler
dispatches with no docs row, predating this branch) is real and now
tracked as a GitHub issue instead.
* fix(ec2): use UnauthorizedOperation for the IPAM org-admin denial
This commit is contained in:
1 parent
0205e4ed7e
commit
9563b7ef08
24 files changed
+3693
-5
No files matched your search
@@ -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() {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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()) {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
Reference in new issue
Block a user