mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(iam): resolve EC2 network resources and ownership tags (#8288)
EC2 network operations with resource-scoped policies were checked against `*`, and stored ownership conditions were missing. Every EC2 request is now read by the generated request-resource rules, its EC2 Query list names from botocore, so a resource-scoped policy applies to each EC2 operation whose request names a resource. A list a type's ARN variable names is the request's targets only when the request names nothing else, and the sg-, acl-, rtb- and eni- id prefixes come from botocore's examples. Each target is evaluated with its own stored tags, under every EC2 type's Service Reference resource-tag keys, and tags on creation are authorized separately. A forged SDK spelling cannot replace an EC2 wire value. ENI creation tags are kept in the regional tag index and stay in sync with CreateTags and DeleteTags. Closes #8286 Closes #8287 Closes #8291 Closes #8295 Closes #8300 Closes #8306
This commit is contained in:
1 parent
4649d6c683
commit
a138f88094
20 files changed
+2163
-587
No files matched your search
@@ -6,12 +6,23 @@
|
||||
|
||||
With IAM enforcement enabled, modeled instance-list operations, including `StartInstances`, `StopInstances`, `TerminateInstances`, and `RebootInstances`, authorize each requested instance ARN before changing any instance state.
|
||||
Policies can scope access to an exact instance ARN or use stored tags through `ec2:ResourceTag/<key>` and `aws:ResourceTag/<key>`.
|
||||
Creation-time `CreateNetworkInterface` tags also populate the regional IAM tag index.
|
||||
Later `CreateTags` and `DeleteTags` keep the ENI response and authorization tags in sync,
|
||||
and deleting the interface removes its indexed tags.
|
||||
A batch containing an unauthorized instance is denied in full, including when another instance in that batch is allowed.
|
||||
These checks also apply in EC2 mock mode.
|
||||
Target members and resource-tag condition keys come from generated AWS model and Service Reference data.
|
||||
Malformed percent escapes in a form body are rejected with a client error before authorization uses any partially decoded parameters.
|
||||
See the [AWS EC2 authorization reference](https://docs.aws.amazon.com/service-authorization/latest/reference/list_ec2.html) for supported resource types and condition keys.
|
||||
|
||||
## Elastic IP IAM authorization
|
||||
|
||||
With IAM enforcement enabled, `AssociateAddress` authorizes the requested allocation and
|
||||
instance or network interface against their individual ARNs and stored ownership tags.
|
||||
Every supplied target needs a grant, and an explicit deny on any target rejects the request
|
||||
before association. `ReleaseAddress` also resolves the allocation named by `AllocationId`,
|
||||
so policies can scope release to that allocation or its stored tags.
|
||||
|
||||
## Instance Execution Model
|
||||
|
||||
`RunInstances` launches a **real Docker container** for each instance. By default, the container is kept alive with `tail -f /dev/null` so any base image works regardless of its default CMD. Catalog entries that opt into the `systemd` guest runtime start `/sbin/init` instead, with the Docker mounts needed for a systemd-based cloud-image guest. Those guests also get the Docker host's `/lib/modules/<KernelVersion>` (the running kernel's directory only, so the guest's own package manager keeps a writable `/lib/modules`) read-only, so `modprobe` finds modules the shared kernel already has (for example `br_netfilter`, which Kubernetes node setup loads). The mount is read-only, but it is not a boundary for a privileged guest: one can remount that directory read-write and load any module built for the shared kernel (see the warning below). On Docker Desktop or OrbStack, that directory is the Linux VM's, which may not hold modules matching the kernel that VM is running. If `/lib/modules/<KernelVersion>` does not exist on the Docker daemon's host, Docker creates an empty root-owned directory there and `modprobe` still fails. The bind is read-only, so a guest that installs the `linux-modules` package for the host's exact kernel version cannot write into it.
|
||||
|
||||
+47
-11
@@ -2730,19 +2730,55 @@ also applies to other role operations such as `DeleteRole` and `ListRolePolicies
|
||||
`Path` cannot change this ARN. Once the role exists, its stored path and partition apply;
|
||||
creation still uses the path the request asks for.
|
||||
|
||||
`ec2:CreateVpc` is evaluated against `vpc/*` in the caller's partition, Region and account,
|
||||
so a VPC-scoped grant can authorize creation with `aws:RequestTag` conditions. When supplied,
|
||||
IPv4 and IPv6 IPAM pools and an IPv6 address pool are checked as additional resources. Tags
|
||||
at creation additionally require `ec2:CreateTags` on the new VPC, with `ec2:CreateAction`
|
||||
set to `CreateVpc`. Explicit denies on these resources still apply. The resource mapping
|
||||
is generated from the Service Reference and botocore, as it is for every EC2 operation:
|
||||
a request is checked on the resources its members name, each EC2 Query list read under the
|
||||
wire name botocore serializes it with, and an operation whose request names none stays on `*`.
|
||||
|
||||
`ec2:CreateSubnet`, `ec2:CreateRouteTable`, `ec2:CreateSecurityGroup`, and
|
||||
`ec2:CreateVpcEndpoint` authorize
|
||||
both the new resource ARN and the existing parent VPC. `ec2:CreateInternetGateway`
|
||||
authorizes the new gateway ARN. Tag-on-create checks apply to the new resource only;
|
||||
the parent VPC uses its own stored ownership tags.
|
||||
|
||||
`ec2:CreateNetworkInterface` checks the new interface, its subnet and every supplied
|
||||
security group separately. The generated EC2 Query names preserve SDK list serialization
|
||||
(for example, `Groups` is sent as `SecurityGroupId.N`). `ec2:AllocateAddress` checks
|
||||
the new elastic IP and any supplied address pool; its created resource type is derived
|
||||
from botocore's operation description and returned allocation ID. `ec2:CreateNatGateway`
|
||||
checks the new gateway and each supplied subnet, elastic IP and VPC separately, including
|
||||
stored ownership tags on its existing parents.
|
||||
|
||||
The network mutation operations include subnet attribute updates, route
|
||||
creation/replacement/deletion and association, gateway attachment/detachment,
|
||||
security-group ingress/egress changes, and VPC, subnet, route table, gateway, and
|
||||
security-group deletion. Each generated ARN is checked with that resource's own
|
||||
stored tags; allowing an owned VPC does not authorize an unowned gateway or subnet.
|
||||
|
||||
`ec2:ModifyVpcAttribute` resolves the supplied `VpcId` to its ARN and checks the target's
|
||||
current stored tags under `aws:ResourceTag/` and `ec2:ResourceTag/`. Tags are read for each
|
||||
resolved ARN independently; request tags do not replace ownership tags on an existing VPC.
|
||||
The prefixes come from the generated `resourceTagKeys` table in `iam-request-resources.json`,
|
||||
derived from the Service Reference; new keys belong in the generator rather than Java branches.
|
||||
|
||||
EC2 tagging targets come from `regen_iam_request_resources.py`, with EC2 among its namespaces.
|
||||
The Service Reference supplies the resource types and ARN formats, botocore supplies the
|
||||
`Resources` list and its EC2 Query spelling (`ResourceId.N`), and a documented generator
|
||||
mapping identifies instance IDs. The generated entries select `CreateTags` and `DeleteTags`
|
||||
from their input shapes and resource types, without an operation-name branch in Java.
|
||||
Each instance ARN is evaluated with that target's existing tags; every target must be authorized
|
||||
before the handler changes any tags. Other EC2 resource types retain wildcard authorization
|
||||
against every target context, including when mixed with instances. Only instance ARNs narrow
|
||||
the context to their own stored tags. Resource resolution reuses the decoded form parameters
|
||||
rather than reparsing the body for each target. The readers preserve the handler's parameter
|
||||
ordering, first duplicate value and stop at the first missing list index. This staged EC2 read
|
||||
covers only instances in heterogeneous target lists; other EC2 operations retain their existing
|
||||
wildcard resource resolution.
|
||||
`Resources` list and its EC2 Query spelling (`ResourceId.N`), and the id prefix botocore gives
|
||||
each type, in its documentation or its request and response examples (`"GroupId": "sg-903004f8"`),
|
||||
identifies instance, security-group, network-acl, route-table and network-interface IDs.
|
||||
The generated entries select `CreateTags` and `DeleteTags` from their input shapes and resource
|
||||
types, without an operation-name branch in Java. Each ARN is evaluated with that target's own
|
||||
stored tags; every target must be authorized before the handler changes any tags. Other EC2
|
||||
resource types retain wildcard authorization against every target context, including mixed
|
||||
batches. Resource resolution reuses the decoded form parameters rather than reparsing the body
|
||||
for each target. The readers preserve the handler's parameter ordering, first duplicate value
|
||||
and stop at the first missing list index. A list a type's ARN variable names, such as
|
||||
`InstanceIds`, is the request's targets only when the request names nothing else the action acts
|
||||
on: a launch's `SecurityGroupIds` are read beside its image and subnet, each on its own ARN.
|
||||
|
||||
Which type each action takes is vendored, not written out in Java:
|
||||
`src/main/resources/aws/iam-action-resources.json` is generated by
|
||||
|
||||
@@ -889,6 +889,33 @@ public class IamConditionContextResolver {
|
||||
}
|
||||
}
|
||||
|
||||
/** Stored tags for one generated EC2 ARN, never borrowed from another target in the same request. */
|
||||
public Map<String, List<String>> withEc2ResourceTags(String scope, String action, String resource,
|
||||
String region, String accountId,
|
||||
Map<String, List<String>> context) {
|
||||
if (!"ec2".equals(scope) || RequestResources.hasIndividualTargets(action)
|
||||
|| !AwsArnUtils.isArn(resource) || !ec2Service.isResolvable()) {
|
||||
return context;
|
||||
}
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(resource);
|
||||
if (!"ec2".equals(arn.service()) || !region.equals(arn.region()) || !accountId.equals(arn.accountId())) {
|
||||
return context;
|
||||
}
|
||||
String[] parts = arn.resource().split("/", 2);
|
||||
if (parts.length != 2 || parts[1].contains("*") || parts[1].contains("?")) {
|
||||
return context;
|
||||
}
|
||||
List<String> prefixes = RequestResourceMembers.table().resourceTagKeys()
|
||||
.getOrDefault("ec2", Map.of()).getOrDefault(parts[0], List.of());
|
||||
if (prefixes.isEmpty()) {
|
||||
return context;
|
||||
}
|
||||
Map<String, List<String>> result = context == null ? new LinkedHashMap<>() : new LinkedHashMap<>(context);
|
||||
result.keySet().removeIf(key -> prefixes.stream().anyMatch(key::startsWith));
|
||||
putStoredTags(result, region, parts[1], prefixes);
|
||||
return result;
|
||||
}
|
||||
|
||||
private void addResourceTags(Map<String, List<String>> conditions, String resourceId,
|
||||
RequestResourceMembers.Targets targets) {
|
||||
if (resourceId == null || resourceId.isBlank() || !ec2Service.isResolvable()) {
|
||||
@@ -903,6 +930,11 @@ public class IamConditionContextResolver {
|
||||
break;
|
||||
}
|
||||
}
|
||||
putStoredTags(conditions, region, resourceId, prefixes);
|
||||
}
|
||||
|
||||
private void putStoredTags(Map<String, List<String>> conditions, String region, String resourceId,
|
||||
List<String> prefixes) {
|
||||
for (Tag tag : ec2Service.get().resourceTags(region, resourceId)) {
|
||||
for (String prefix : prefixes) {
|
||||
conditions.put(prefix + tag.getKey(), List.of(tag.getValue() == null ? "" : tag.getValue()));
|
||||
|
||||
@@ -1332,8 +1332,14 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
}
|
||||
}
|
||||
for (Map<String, List<String>> targetContext : resourceContexts) {
|
||||
Map<String, List<String>> taggedContext = targetContext;
|
||||
if ("ec2".equals(credentialScope) && !RequestResources.hasIndividualTargets(operationAction)
|
||||
&& AwsArnUtils.isArn(resource)) {
|
||||
taggedContext = conditionContextResolver.withEc2ResourceTags(
|
||||
credentialScope, operationAction, resource, region, accountId, targetContext);
|
||||
}
|
||||
Map<String, List<String>> effectiveContext = IamConditionContextResolver.withGlobalContext(
|
||||
targetContext, resource, region, accountId, resourceOwnerAccountId, action);
|
||||
taggedContext, resource, region, accountId, resourceOwnerAccountId, action);
|
||||
ResourcePolicyDecision resourcePolicyDecision = evaluator.evaluateResourcePolicyFor(
|
||||
effectiveResourcePolicies, principal, action, resource, effectiveContext);
|
||||
Decision decision = evaluator.evaluateResolvedResourcePolicy(
|
||||
|
||||
@@ -224,6 +224,7 @@ final class RequestResourceMembers {
|
||||
record Table(Map<String, List<Resource>> operations, Map<String, List<String>> types,
|
||||
Map<String, List<Created>> creates, Map<String, List<Resource>> makes,
|
||||
Map<String, Targets> targets,
|
||||
Map<String, Map<Member, String>> ec2Query,
|
||||
Map<String, Map<String, String>> located, Map<String, Map<String, ArnFormat>> formats,
|
||||
Map<String, Map<String, List<String>>> resourceTagKeys,
|
||||
Set<String> namespaces, Set<String> handBuilt, Set<String> notCovered, Set<String> otherNamespaces,
|
||||
@@ -311,6 +312,7 @@ final class RequestResourceMembers {
|
||||
Map<String, List<Created>> creates = new LinkedHashMap<>();
|
||||
Map<String, List<Resource>> makes = new LinkedHashMap<>();
|
||||
Map<String, Targets> targets = new LinkedHashMap<>();
|
||||
Map<String, Map<Member, String>> ec2Query = new LinkedHashMap<>();
|
||||
Map<String, Map<String, String>> located = new LinkedHashMap<>();
|
||||
Map<String, List<Forwarded>> forwarded = new LinkedHashMap<>();
|
||||
JsonNode forwardedActions = document.path("forwardedActions");
|
||||
@@ -373,6 +375,20 @@ final class RequestResourceMembers {
|
||||
if (!under.isEmpty()) {
|
||||
creates.put(operation.getKey(), List.copyOf(under));
|
||||
}
|
||||
Map<Member, String> queryMembers = new LinkedHashMap<>();
|
||||
operation.getValue().path("ec2Query").properties().forEach(member -> {
|
||||
String path = member.getKey();
|
||||
String wire = member.getValue().asText("");
|
||||
if (!namespace.equals("ec2") || !path.matches("[A-Za-z][A-Za-z0-9_]*(\\[\\])?")
|
||||
|| !LOCATED_MEMBER.matcher(wire).matches()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has invalid EC2 Query member: " + path);
|
||||
}
|
||||
boolean list = path.endsWith("[]");
|
||||
queryMembers.put(new Member(list ? path.substring(0, path.length() - 2) : path, list), wire);
|
||||
});
|
||||
if (!queryMembers.isEmpty()) {
|
||||
ec2Query.put(operation.getKey(), Map.copyOf(queryMembers));
|
||||
}
|
||||
Map<String, String> where = new LinkedHashMap<>();
|
||||
operation.getValue().path("located").properties().forEach(member -> {
|
||||
if (!LOCATED_MEMBER.matcher(member.getKey()).matches()
|
||||
@@ -395,7 +411,8 @@ final class RequestResourceMembers {
|
||||
}
|
||||
});
|
||||
return new Table(Map.copyOf(entries), Map.copyOf(actsOn), Map.copyOf(creates), Map.copyOf(makes),
|
||||
Map.copyOf(targets), Map.copyOf(located), Map.copyOf(formats), Map.copyOf(resourceTagKeys), namespaces,
|
||||
Map.copyOf(targets), Map.copyOf(ec2Query), Map.copyOf(located), Map.copyOf(formats),
|
||||
Map.copyOf(resourceTagKeys), namespaces,
|
||||
names(document.path("handBuilt")),
|
||||
Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
|
||||
names(document.path("otherNamespaces")), Map.copyOf(forwarded));
|
||||
|
||||
@@ -115,7 +115,7 @@ public final class RequestResources {
|
||||
}
|
||||
Map<String, String> sent = IamConditionContextResolver.formParameters(ctx);
|
||||
JsonNode body = sent.isEmpty() ? located(table, operation, PassedRoles.jsonBody(ctx), ctx, labels) : null;
|
||||
Map<String, String> form = located(table, operation, sent, ctx, labels);
|
||||
Map<String, String> form = ec2Query(table, operation, located(table, operation, sent, ctx, labels));
|
||||
return resources.isEmpty() ? List.of()
|
||||
: named(operation, resources, formats(table, operation), form, body, partition, region, accountId, stored);
|
||||
}
|
||||
@@ -309,7 +309,8 @@ public final class RequestResources {
|
||||
String region, String accountId, Map<String, String> labels) {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
return created(table, operation, tagging, resources -> served(resources, ctx),
|
||||
() -> located(table, operation, IamConditionContextResolver.formParameters(ctx), ctx, labels),
|
||||
() -> ec2Query(table, operation,
|
||||
located(table, operation, IamConditionContextResolver.formParameters(ctx), ctx, labels)),
|
||||
() -> IamConditionContextResolver.formParameters(ctx).isEmpty()
|
||||
? located(table, operation, PassedRoles.jsonBody(ctx), ctx, labels) : null,
|
||||
partition, region, accountId);
|
||||
@@ -857,6 +858,28 @@ public final class RequestResources {
|
||||
}
|
||||
}
|
||||
|
||||
/** Normalize only generated EC2 wire members; JSON task inputs keep their SDK names. */
|
||||
private static Map<String, String> ec2Query(RequestResourceMembers.Table table, String operation,
|
||||
Map<String, String> sent) {
|
||||
Map<RequestResourceMembers.Member, String> members = table.ec2Query().get(operation);
|
||||
if (sent.isEmpty() || members == null) {
|
||||
return sent;
|
||||
}
|
||||
Map<String, String> form = new HashMap<>(sent);
|
||||
members.forEach((member, wire) -> {
|
||||
// Ignore forged SDK/Query spellings the EC2 handler itself does not read.
|
||||
form.keySet().removeIf(key -> key.equals(member.name()) || key.startsWith(member.name() + "."));
|
||||
if (member.list()) {
|
||||
for (int index = 1; sent.containsKey(wire + "." + index); index++) {
|
||||
form.put(member.name() + ".member." + index, sent.get(wire + "." + index));
|
||||
}
|
||||
} else if (sent.containsKey(wire)) {
|
||||
form.put(member.name(), sent.get(wire));
|
||||
}
|
||||
});
|
||||
return form;
|
||||
}
|
||||
|
||||
/**
|
||||
* The non-empty strings a request gives a member, read as its handler reads them: a form's parameter, or its
|
||||
* list numbered under {@code member} from 1 to the first missing, or a body's value, as text whether a string,
|
||||
|
||||
@@ -11012,6 +11012,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
RouteTable rt = routeTables.get(storeKey).orElse(null);
|
||||
if (rt != null) { rt.setTags(new ArrayList<>(tagList)); routeTables.put(storeKey, rt); return; }
|
||||
NetworkInterface networkInterface = networkInterfaces.get(storeKey).orElse(null);
|
||||
if (networkInterface != null) {
|
||||
networkInterface.getTagSet().clear();
|
||||
networkInterface.getTagSet().addAll(tagList);
|
||||
networkInterfaces.put(storeKey, networkInterface);
|
||||
return;
|
||||
}
|
||||
KeyPair kp = keyPairs.get(storeKey).orElse(null);
|
||||
if (kp != null) { kp.setTags(new ArrayList<>(tagList)); keyPairs.put(storeKey, kp); return; }
|
||||
LaunchTemplate lt = launchTemplates.get(storeKey).orElse(null);
|
||||
@@ -15945,6 +15952,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
ni.setPrivateIpAddresses(ipList);
|
||||
|
||||
networkInterfaces.put(key(region, eniId), ni);
|
||||
putTags(region, eniId, new ArrayList<>(ni.getTagSet()));
|
||||
return ni;
|
||||
}
|
||||
}
|
||||
@@ -15966,6 +15974,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
releaseInterfaceAddresses(region, networkInterfaceId, true);
|
||||
networkInterfaces.delete(key(region, networkInterfaceId));
|
||||
removeTags(region, networkInterfaceId);
|
||||
releasePrivateIps(region, ni.getSubnetId(), List.of(ni.getPrivateIpAddress()));
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,150 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.Address;
|
||||
import software.amazon.awssdk.services.ec2.model.AssociateAddressRequest;
|
||||
import software.amazon.awssdk.services.ec2.model.TagSpecification;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class Ec2AddressIamIntegrationTest {
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"instance", "network-interface"})
|
||||
void associationRequiresEveryRequestedTargetWithItsOwnStoredTags(String kind) {
|
||||
String user = "address-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
|
||||
auth("000000000000", "iam"), user);
|
||||
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
|
||||
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
String vpc = admin.createVpc(r -> r.cidrBlock("10.211.0.0/16")).vpc().vpcId();
|
||||
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.211.1.0/24")).subnet().subnetId();
|
||||
String target;
|
||||
if ("instance".equals(kind)) {
|
||||
target = admin.runInstances(r -> r.imageId("ami-amazonlinux2023").instanceType("t3.micro")
|
||||
.minCount(1).maxCount(1).subnetId(subnet).tagSpecifications(tags(kind, "foreign")))
|
||||
.instances().getFirst().instanceId();
|
||||
} else {
|
||||
target = admin.createNetworkInterface(r -> r.subnetId(subnet).tagSpecifications(tags(kind, "foreign")))
|
||||
.networkInterface().networkInterfaceId();
|
||||
}
|
||||
String allocation = admin.allocateAddress(r -> r.domain("vpc")
|
||||
.tagSpecifications(tags("elastic-ip", "address"))).allocationId();
|
||||
String addressGrant = grant("AssociateAddress", "elastic-ip/" + allocation, "address");
|
||||
String targetGrant = grant("AssociateAddress", kind + "/" + target, "target");
|
||||
AssociateAddressRequest.Builder builder = AssociateAddressRequest.builder().allocationId(allocation);
|
||||
if ("instance".equals(kind)) {
|
||||
builder.instanceId(target);
|
||||
} else {
|
||||
builder.networkInterfaceId(target);
|
||||
}
|
||||
AssociateAddressRequest request = builder.build();
|
||||
try {
|
||||
policy(user, addressGrant + "," + targetGrant);
|
||||
assertAwsError("UnauthorizedOperation", 403, () -> client.associateAddress(request));
|
||||
assertNull(admin.describeAddresses(r -> r.allocationIds(allocation)).addresses().getFirst().associationId());
|
||||
admin.createTags(r -> r.resources(target).tags(t -> t.key("Owner").value("target")));
|
||||
policy(user, addressGrant);
|
||||
assertAwsError("UnauthorizedOperation", 403, () -> client.associateAddress(request));
|
||||
policy(user, targetGrant);
|
||||
assertAwsError("UnauthorizedOperation", 403, () -> client.associateAddress(request));
|
||||
policy(user, addressGrant + "," + targetGrant + "," + targetGrant.replace("Allow", "Deny"));
|
||||
assertAwsError("UnauthorizedOperation", 403, () -> client.associateAddress(request));
|
||||
policy(user, addressGrant + "," + targetGrant + "," + addressGrant.replace("Allow", "Deny"));
|
||||
assertAwsError("UnauthorizedOperation", 403, () -> client.associateAddress(request));
|
||||
policy(user, addressGrant + "," + targetGrant);
|
||||
String association = client.associateAddress(request).associationId();
|
||||
Address result = admin.describeAddresses(r -> r.allocationIds(allocation)).addresses().getFirst();
|
||||
assertEquals(association, result.associationId());
|
||||
assertEquals(target, "instance".equals(kind) ? result.instanceId() : result.networkInterfaceId());
|
||||
} finally {
|
||||
Address address = admin.describeAddresses(r -> r.allocationIds(allocation)).addresses().getFirst();
|
||||
if (address.associationId() != null) {
|
||||
admin.disassociateAddress(r -> r.associationId(address.associationId()));
|
||||
}
|
||||
admin.releaseAddress(r -> r.allocationId(allocation));
|
||||
if ("instance".equals(kind)) {
|
||||
admin.terminateInstances(r -> r.instanceIds(target));
|
||||
}
|
||||
admin.describeNetworkInterfaces().networkInterfaces().stream().filter(n -> vpc.equals(n.vpcId()))
|
||||
.forEach(n -> admin.deleteNetworkInterface(r -> r.networkInterfaceId(n.networkInterfaceId())));
|
||||
admin.deleteSubnet(r -> r.subnetId(subnet));
|
||||
admin.deleteVpc(r -> r.vpcId(vpc));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void releaseRequiresTheNamedAllocationsStoredOwnershipAndHonorsExplicitDeny() {
|
||||
String user = "release-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
|
||||
auth("000000000000", "iam"), user);
|
||||
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
|
||||
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
String allocation = admin.allocateAddress(r -> r.domain("vpc")
|
||||
.tagSpecifications(tags("elastic-ip", "foreign"))).allocationId();
|
||||
String grant = grant("ReleaseAddress", "elastic-ip/" + allocation, "address");
|
||||
try {
|
||||
policy(user, grant);
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> client.releaseAddress(r -> r.allocationId(allocation)));
|
||||
admin.createTags(r -> r.resources(allocation).tags(t -> t.key("Owner").value("address")));
|
||||
policy(user, grant + "," + grant.replace("Allow", "Deny"));
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> client.releaseAddress(r -> r.allocationId(allocation)));
|
||||
policy(user, grant.replace(allocation, "eipalloc-other"));
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> client.releaseAddress(r -> r.allocationId(allocation)));
|
||||
policy(user, grant);
|
||||
client.releaseAddress(r -> r.allocationId(allocation));
|
||||
} finally {
|
||||
if (admin.describeAddresses().addresses().stream().anyMatch(a -> allocation.equals(a.allocationId()))) {
|
||||
admin.releaseAddress(r -> r.allocationId(allocation));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void policy(String user, String statements) {
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), user,
|
||||
"address", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
|
||||
}
|
||||
|
||||
private static String grant(String action, String resource, String owner) {
|
||||
return """
|
||||
{"Effect":"Allow","Action":"ec2:%s","Resource":"arn:aws:ec2:us-east-1:000000000000:%s",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/Owner":"%s"}}}
|
||||
""".formatted(action, resource, owner);
|
||||
}
|
||||
|
||||
private static TagSpecification tags(String type, String owner) {
|
||||
return TagSpecification.builder().resourceType(type).tags(t -> t.key("Owner").value(owner)).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.CreateVpcRequest;
|
||||
import software.amazon.awssdk.services.ec2.model.ResourceType;
|
||||
import software.amazon.awssdk.services.ec2.model.Tag;
|
||||
import software.amazon.awssdk.services.ec2.model.TagSpecification;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class Ec2CreateVpcIamIntegrationTest {
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"us-east-1", "us-gov-west-1", "cn-north-1"})
|
||||
void scopedCreateRequiresRequestTagsAndTagPermissionAndHonorsExplicitDeny(String region) {
|
||||
String name = "vpc-create-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
|
||||
auth("000000000000", "iam"), name);
|
||||
String resource = AwsArnUtils.Arn.of("ec2", region, "000000000000", "vpc/*").toString();
|
||||
String create = """
|
||||
{"Effect":"Allow","Action":"ec2:CreateVpc","Resource":"%s",
|
||||
"Condition":{"StringEquals":{"aws:RequestTag/ManagedBy":"integration-test"}}}
|
||||
""".formatted(resource);
|
||||
String tag = """
|
||||
{"Effect":"Allow","Action":"ec2:CreateTags","Resource":"%s",
|
||||
"Condition":{"StringEquals":{"ec2:CreateAction":"CreateVpc"}}}
|
||||
""".formatted(resource);
|
||||
try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), Region.of(region), endpoint);
|
||||
Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.of(region), endpoint)) {
|
||||
CreateVpcRequest request = tagged("integration-test");
|
||||
policy(name, create);
|
||||
denied(client, request);
|
||||
policy(name, create + "," + tag);
|
||||
denied(client, CreateVpcRequest.builder().cidrBlock("10.200.0.0/16").build());
|
||||
denied(client, tagged("other"));
|
||||
String vpcId = client.createVpc(request).vpc().vpcId();
|
||||
try {
|
||||
assertTrue(vpcId.startsWith("vpc-"));
|
||||
assertTrue(admin.describeVpcs(r -> r.vpcIds(vpcId)).vpcs().getFirst().tags().stream()
|
||||
.anyMatch(t -> t.key().equals("ManagedBy") && t.value().equals("integration-test")));
|
||||
} finally {
|
||||
admin.deleteVpc(r -> r.vpcId(vpcId));
|
||||
}
|
||||
policy(name, create + "," + tag + "," + """
|
||||
{"Effect":"Deny","Action":"ec2:CreateVpc","Resource":"%s"}
|
||||
""".formatted(resource));
|
||||
denied(client, request);
|
||||
policy(name, create.replace(":000000000000:", ":111122223333:") + "," + tag);
|
||||
denied(client, request);
|
||||
policy(name, create + "," + tag + "," + """
|
||||
{"Effect":"Deny","Action":"ec2:CreateTags","Resource":"%s"}
|
||||
""".formatted(resource));
|
||||
denied(client, request);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"ipv4-ipam", "ipv6-ipam", "ipv6-pool"})
|
||||
void optionalPoolsNeedTheirOwnGrantAndTagsAreCheckedOnlyOnTheVpc(String pool) {
|
||||
String name = "vpc-pool-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
|
||||
auth("000000000000", "iam"), name);
|
||||
String resource = pool.equals("ipv6-pool")
|
||||
? "arn:aws:ec2:us-east-1:000000000000:ipv6pool-ec2/ipv6pool-one"
|
||||
: "arn:aws:ec2::000000000000:ipam-pool/ipam-pool-one";
|
||||
CreateVpcRequest.Builder request = tagged("integration-test").toBuilder();
|
||||
switch (pool) {
|
||||
case "ipv4-ipam" -> request.ipv4IpamPoolId("ipam-pool-one");
|
||||
case "ipv6-ipam" -> request.ipv6IpamPoolId("ipam-pool-one");
|
||||
default -> request.ipv6Pool("ipv6pool-one");
|
||||
}
|
||||
String vpc = """
|
||||
{"Effect":"Allow","Action":["ec2:CreateVpc","ec2:CreateTags"],
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:vpc/*"}
|
||||
""";
|
||||
String grant = """
|
||||
{"Effect":"Allow","Action":"ec2:CreateVpc","Resource":"%s"}
|
||||
""".formatted(resource);
|
||||
try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), Region.US_EAST_1, endpoint);
|
||||
Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint)) {
|
||||
policy(name, vpc);
|
||||
denied(client, request.build());
|
||||
policy(name, vpc + "," + grant);
|
||||
String vpcId = client.createVpc(request.build()).vpc().vpcId();
|
||||
admin.deleteVpc(r -> r.vpcId(vpcId));
|
||||
policy(name, vpc + "," + grant + "," + grant.replace("Allow", "Deny"));
|
||||
denied(client, request.build());
|
||||
}
|
||||
}
|
||||
|
||||
private CreateVpcRequest tagged(String owner) {
|
||||
return CreateVpcRequest.builder().cidrBlock("10.200.0.0/16")
|
||||
.tagSpecifications(TagSpecification.builder().resourceType(ResourceType.VPC)
|
||||
.tags(Tag.builder().key("ManagedBy").value(owner).build()).build()).build();
|
||||
}
|
||||
|
||||
private void denied(Ec2Client client, CreateVpcRequest request) {
|
||||
assertAwsError("UnauthorizedOperation", 403, () -> client.createVpc(request));
|
||||
}
|
||||
|
||||
private void policy(String name, String statements) {
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), name,
|
||||
"create", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.Tag;
|
||||
import software.amazon.awssdk.services.ec2.model.TagSpecification;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class Ec2NatGatewayIamIntegrationTest {
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void natCreationRequiresBothOwnedParentsAndSeparatelyAuthorizedTags() {
|
||||
String name = "nat-iam-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
|
||||
auth("000000000000", "iam"), name);
|
||||
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
|
||||
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
String vpc = admin.createVpc(r -> r.cidrBlock("10.205.0.0/16")).vpc().vpcId();
|
||||
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.205.1.0/24")
|
||||
.tagSpecifications(tags("subnet", "owner"))).subnet().subnetId();
|
||||
String allocation = admin.allocateAddress(r -> r.domain("vpc")
|
||||
.tagSpecifications(tags("elastic-ip", "foreign"))).allocationId();
|
||||
String created = """
|
||||
{"Effect":"Allow","Action":"ec2:CreateNatGateway",
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:natgateway/*",
|
||||
"Condition":{"StringEquals":{"aws:RequestTag/Owner":"owner"}}}
|
||||
""";
|
||||
String parents = """
|
||||
{"Effect":"Allow","Action":"ec2:CreateNatGateway",
|
||||
"Resource":["arn:aws:ec2:us-east-1:000000000000:subnet/%s",
|
||||
"arn:aws:ec2:us-east-1:000000000000:elastic-ip/%s"],
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/Owner":"owner"}}}
|
||||
""".formatted(subnet, allocation);
|
||||
String tag = """
|
||||
{"Effect":"Allow","Action":"ec2:CreateTags",
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:natgateway/*",
|
||||
"Condition":{"StringEquals":{"ec2:CreateAction":"CreateNatGateway"}}}
|
||||
""";
|
||||
try {
|
||||
policy(name, created + "," + parents + "," + tag);
|
||||
assertAwsError("UnauthorizedOperation", 403, () -> create(client, subnet, allocation));
|
||||
admin.createTags(r -> r.resources(allocation).tags(Tag.builder().key("Owner").value("owner").build()));
|
||||
policy(name, created + "," + tag);
|
||||
assertAwsError("UnauthorizedOperation", 403, () -> create(client, subnet, allocation));
|
||||
policy(name, created + "," + parents);
|
||||
assertAwsError("UnauthorizedOperation", 403, () -> create(client, subnet, allocation));
|
||||
policy(name, created + "," + parents + "," + tag + "," + """
|
||||
{"Effect":"Deny","Action":"ec2:CreateNatGateway",
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:elastic-ip/%s"}
|
||||
""".formatted(allocation));
|
||||
assertAwsError("UnauthorizedOperation", 403, () -> create(client, subnet, allocation));
|
||||
policy(name, created + "," + parents + "," + tag);
|
||||
create(client, subnet, allocation);
|
||||
} finally {
|
||||
admin.describeNatGateways().natGateways().stream().filter(n -> vpc.equals(n.vpcId()))
|
||||
.forEach(n -> admin.deleteNatGateway(r -> r.natGatewayId(n.natGatewayId())));
|
||||
admin.releaseAddress(r -> r.allocationId(allocation));
|
||||
admin.deleteSubnet(r -> r.subnetId(subnet));
|
||||
admin.deleteVpc(r -> r.vpcId(vpc));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void policy(String name, String statements) {
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), name, "nat",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
|
||||
}
|
||||
|
||||
private static void create(Ec2Client client, String subnet, String allocation) {
|
||||
client.createNatGateway(r -> r.subnetId(subnet).allocationId(allocation)
|
||||
.tagSpecifications(tags("natgateway", "owner")));
|
||||
}
|
||||
|
||||
private static TagSpecification tags(String type, String owner) {
|
||||
return TagSpecification.builder().resourceType(type)
|
||||
.tags(Tag.builder().key("Owner").value(owner).build()).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.Tag;
|
||||
import software.amazon.awssdk.services.ec2.model.TagSpecification;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class Ec2NetworkCreateIamIntegrationTest {
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void gatewayEndpointChecksEverySuppliedRouteTable() {
|
||||
String user = "endpoint-routes-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
|
||||
auth("000000000000", "iam"), user);
|
||||
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
|
||||
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
String vpc = admin.createVpc(r -> r.cidrBlock("10.204.0.0/16")).vpc().vpcId();
|
||||
String first = admin.createRouteTable(r -> r.vpcId(vpc)).routeTable().routeTableId();
|
||||
String second = admin.createRouteTable(r -> r.vpcId(vpc)).routeTable().routeTableId();
|
||||
String allow = """
|
||||
{"Effect":"Allow","Action":"ec2:CreateVpcEndpoint",
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:*"}
|
||||
""";
|
||||
String deny = """
|
||||
{"Effect":"Deny","Action":"ec2:CreateVpcEndpoint",
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:route-table/%s"}
|
||||
""".formatted(second);
|
||||
try {
|
||||
policy(user, allow + "," + deny);
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> client.createVpcEndpoint(r -> r.vpcId(vpc).vpcEndpointType("Gateway")
|
||||
.serviceName("com.amazonaws.us-east-1.s3").routeTableIds(first, second)));
|
||||
policy(user, allow);
|
||||
String id = client.createVpcEndpoint(r -> r.vpcId(vpc).vpcEndpointType("Gateway")
|
||||
.serviceName("com.amazonaws.us-east-1.s3").routeTableIds(first, second))
|
||||
.vpcEndpoint().vpcEndpointId();
|
||||
admin.deleteVpcEndpoints(r -> r.vpcEndpointIds(id));
|
||||
} finally {
|
||||
admin.describeVpcEndpoints().vpcEndpoints().stream().filter(e -> vpc.equals(e.vpcId()))
|
||||
.forEach(e -> admin.deleteVpcEndpoints(r -> r.vpcEndpointIds(e.vpcEndpointId())));
|
||||
admin.deleteRouteTable(r -> r.routeTableId(second));
|
||||
admin.deleteRouteTable(r -> r.routeTableId(first));
|
||||
admin.deleteVpc(r -> r.vpcId(vpc));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"CreateSubnet,subnet", "CreateRouteTable,route-table", "CreateSecurityGroup,security-group",
|
||||
"CreateInternetGateway,internet-gateway", "CreateVpcEndpoint,vpc-endpoint", "AllocateAddress,elastic-ip"})
|
||||
void creationChecksNewResourceTagsAndParentOwnershipSeparately(String action, String type) {
|
||||
String name = "network-create-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
|
||||
auth("000000000000", "iam"), name);
|
||||
String resource = "arn:aws:ec2:us-east-1:000000000000:" + type + "/*";
|
||||
String create = """
|
||||
{"Effect":"Allow","Action":"ec2:%s","Resource":"%s",
|
||||
"Condition":{"StringEquals":{"aws:RequestTag/ManagedBy":"integration-test"}}}
|
||||
""".formatted(action, resource);
|
||||
String tags = """
|
||||
{"Effect":"Allow","Action":"ec2:CreateTags","Resource":"%s",
|
||||
"Condition":{"StringEquals":{"ec2:CreateAction":"%s"}}}
|
||||
""".formatted(resource, action);
|
||||
try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), Region.US_EAST_1, endpoint);
|
||||
Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint)) {
|
||||
String vpc = admin.createVpc(r -> r.cidrBlock("10.201.0.0/16").tagSpecifications(
|
||||
specification("vpc", "parent-owner"))).vpc().vpcId();
|
||||
String parentArn = "arn:aws:ec2:us-east-1:000000000000:vpc/" + vpc;
|
||||
String parent = """
|
||||
{"Effect":"Allow","Action":"ec2:%s","Resource":"%s",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/ManagedBy":"parent-owner"}}}
|
||||
""".formatted(action, parentArn);
|
||||
try {
|
||||
policy(name, create + "," + parent);
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> create(client, action, type, vpc, "integration-test"));
|
||||
policy(name, create + "," + tags + "," + parent);
|
||||
assertAwsError("UnauthorizedOperation", 403, () -> create(client, action, type, vpc, "wrong-owner"));
|
||||
String id = create(client, action, type, vpc, "integration-test");
|
||||
assertEquals("integration-test", admin.describeTags(r -> r.filters(f -> f.name("resource-id")
|
||||
.values(id))).tags().stream().filter(t -> t.key().equals("ManagedBy")).findFirst()
|
||||
.orElseThrow().value());
|
||||
delete(admin, action, id);
|
||||
policy(name, create + "," + tags + "," + parent + "," + create.replace("Allow", "Deny"));
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> create(client, action, type, vpc, "integration-test"));
|
||||
policy(name, create.replace(":000000000000:", ":111122223333:") + "," + tags + "," + parent);
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> create(client, action, type, vpc, "integration-test"));
|
||||
if (!action.equals("CreateInternetGateway") && !action.equals("AllocateAddress")) {
|
||||
policy(name, create + "," + tags);
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> create(client, action, type, vpc, "integration-test"));
|
||||
policy(name, create + "," + tags + "," + parent.replace("parent-owner", "integration-test"));
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> create(client, action, type, vpc, "integration-test"));
|
||||
policy(name, create + "," + tags + "," + parent + "," + parent.replace("Allow", "Deny"));
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> create(client, action, type, vpc, "integration-test"));
|
||||
} else {
|
||||
policy(name, create + "," + tags);
|
||||
delete(admin, action, create(client, action, type, vpc, "integration-test"));
|
||||
}
|
||||
} finally {
|
||||
admin.deleteVpc(r -> r.vpcId(vpc));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String create(Ec2Client client, String action, String type, String vpc, String owner) {
|
||||
TagSpecification tags = specification(type, owner);
|
||||
return switch (action) {
|
||||
case "CreateSubnet" -> client.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.201.1.0/24")
|
||||
.tagSpecifications(tags)).subnet().subnetId();
|
||||
case "CreateRouteTable" -> client.createRouteTable(r -> r.vpcId(vpc).tagSpecifications(tags))
|
||||
.routeTable().routeTableId();
|
||||
case "CreateSecurityGroup" -> client.createSecurityGroup(r -> r.vpcId(vpc)
|
||||
.groupName("network-" + UUID.randomUUID()).description("IAM integration test")
|
||||
.tagSpecifications(tags)).groupId();
|
||||
case "CreateVpcEndpoint" -> client.createVpcEndpoint(r -> r.vpcId(vpc).vpcEndpointType("Gateway")
|
||||
.serviceName("com.amazonaws.us-east-1.s3").tagSpecifications(tags)).vpcEndpoint().vpcEndpointId();
|
||||
case "CreateInternetGateway" -> client.createInternetGateway(r -> r.tagSpecifications(tags))
|
||||
.internetGateway().internetGatewayId();
|
||||
case "AllocateAddress" -> client.allocateAddress(r -> r.domain("vpc").tagSpecifications(tags)).allocationId();
|
||||
default -> throw new IllegalArgumentException(action);
|
||||
};
|
||||
}
|
||||
|
||||
private void delete(Ec2Client admin, String action, String id) {
|
||||
switch (action) {
|
||||
case "CreateSubnet" -> admin.deleteSubnet(r -> r.subnetId(id));
|
||||
case "CreateRouteTable" -> admin.deleteRouteTable(r -> r.routeTableId(id));
|
||||
case "CreateSecurityGroup" -> admin.deleteSecurityGroup(r -> r.groupId(id));
|
||||
case "CreateVpcEndpoint" -> admin.deleteVpcEndpoints(r -> r.vpcEndpointIds(id));
|
||||
case "CreateInternetGateway" -> admin.deleteInternetGateway(r -> r.internetGatewayId(id));
|
||||
case "AllocateAddress" -> admin.releaseAddress(r -> r.allocationId(id));
|
||||
default -> throw new IllegalArgumentException(action);
|
||||
}
|
||||
}
|
||||
|
||||
private TagSpecification specification(String type, String owner) {
|
||||
return TagSpecification.builder().resourceType(type)
|
||||
.tags(Tag.builder().key("ManagedBy").value(owner).build()).build();
|
||||
}
|
||||
|
||||
|
||||
private void policy(String name, String statements) {
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), name,
|
||||
"network", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.NetworkInterface;
|
||||
import software.amazon.awssdk.services.ec2.model.TagSpecification;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class Ec2NetworkInterfaceIamIntegrationTest {
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void creationChecksSubnetAndEverySecurityGroupWithTheirOwnTags() {
|
||||
String user = "eni-create-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
|
||||
auth("000000000000", "iam"), user);
|
||||
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
|
||||
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
String vpc = admin.createVpc(r -> r.cidrBlock("10.203.0.0/16")).vpc().vpcId();
|
||||
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.203.1.0/24")
|
||||
.tagSpecifications(tags("subnet", "subnet-owner"))).subnet().subnetId();
|
||||
String group = admin.createSecurityGroup(r -> r.vpcId(vpc).groupName("eni-test")
|
||||
.description("IAM fixture").tagSpecifications(tags("security-group", "group-owner"))).groupId();
|
||||
String second = admin.createSecurityGroup(r -> r.vpcId(vpc).groupName("eni-test-second")
|
||||
.description("IAM fixture").tagSpecifications(tags("security-group", "group-owner"))).groupId();
|
||||
String create = """
|
||||
{"Effect":"Allow","Action":"ec2:CreateNetworkInterface",
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:network-interface/*",
|
||||
"Condition":{"StringEquals":{"aws:RequestTag/ManagedBy":"integration-test"}}}
|
||||
""";
|
||||
String tag = """
|
||||
{"Effect":"Allow","Action":"ec2:CreateTags",
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:network-interface/*",
|
||||
"Condition":{"StringEquals":{"ec2:CreateAction":"CreateNetworkInterface"}}}
|
||||
""";
|
||||
String subnetGrant = grant("subnet/" + subnet, "subnet-owner");
|
||||
String firstGrant = grant("security-group/" + group, "group-owner");
|
||||
String secondGrant = grant("security-group/" + second, "group-owner");
|
||||
String all = create + "," + tag + "," + subnetGrant + "," + firstGrant + "," + secondGrant;
|
||||
Runnable request = () -> create(client, subnet, group, second, "integration-test");
|
||||
try {
|
||||
policy(user, create + "," + subnetGrant + "," + firstGrant + "," + secondGrant);
|
||||
assertAwsError("UnauthorizedOperation", 403, request::run);
|
||||
policy(user, create + "," + tag + "," + firstGrant + "," + secondGrant);
|
||||
assertAwsError("UnauthorizedOperation", 403, request::run);
|
||||
policy(user, create + "," + tag + "," + subnetGrant + "," + firstGrant);
|
||||
assertAwsError("UnauthorizedOperation", 403, request::run);
|
||||
policy(user, all.replace("subnet-owner", "group-owner"));
|
||||
assertAwsError("UnauthorizedOperation", 403, request::run);
|
||||
policy(user, all + "," + secondGrant.replace("Allow", "Deny"));
|
||||
assertAwsError("UnauthorizedOperation", 403, request::run);
|
||||
policy(user, all);
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> create(client, subnet, group, second, "wrong-owner"));
|
||||
String eni = create(client, subnet, group, second, "integration-test");
|
||||
assertEquals(2, admin.describeNetworkInterfaces(r -> r.networkInterfaceIds(eni))
|
||||
.networkInterfaces().getFirst().groups().size());
|
||||
admin.deleteNetworkInterface(r -> r.networkInterfaceId(eni));
|
||||
} finally {
|
||||
for (NetworkInterface eni : admin.describeNetworkInterfaces().networkInterfaces()) {
|
||||
if (subnet.equals(eni.subnetId())) {
|
||||
admin.deleteNetworkInterface(r -> r.networkInterfaceId(eni.networkInterfaceId()));
|
||||
}
|
||||
}
|
||||
admin.deleteSecurityGroup(r -> r.groupId(second));
|
||||
admin.deleteSecurityGroup(r -> r.groupId(group));
|
||||
admin.deleteSubnet(r -> r.subnetId(subnet));
|
||||
admin.deleteVpc(r -> r.vpcId(vpc));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void creationTagsAuthorizeLaterMutationsAndStayInSync() {
|
||||
String user = "eni-tags-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
|
||||
auth("000000000000", "iam"), user);
|
||||
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
|
||||
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
String vpc = admin.createVpc(r -> r.cidrBlock("10.204.0.0/16")).vpc().vpcId();
|
||||
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.204.1.0/24")).subnet().subnetId();
|
||||
String eni = admin.createNetworkInterface(r -> r.subnetId(subnet)
|
||||
.tagSpecifications(tags("network-interface", "team-a"))).networkInterface().networkInterfaceId();
|
||||
try {
|
||||
policy(user, """
|
||||
{"Effect":"Allow","Action":["ec2:CreateTags","ec2:DeleteTags"],
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:network-interface/%s",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/ManagedBy":"team-a",
|
||||
"ec2:ResourceTag/ManagedBy":"team-a"}}}
|
||||
""".formatted(eni));
|
||||
client.createTags(r -> r.resources(eni).tags(t -> t.key("Purpose").value("fixture")));
|
||||
assertEquals(2, admin.describeNetworkInterfaces(r -> r.networkInterfaceIds(eni))
|
||||
.networkInterfaces().getFirst().tagSet().size());
|
||||
client.createTags(r -> r.resources(eni).tags(t -> t.key("ManagedBy").value("team-b")));
|
||||
assertEquals("team-b", admin.describeNetworkInterfaces(r -> r.networkInterfaceIds(eni))
|
||||
.networkInterfaces().getFirst().tagSet().stream().filter(t -> t.key().equals("ManagedBy"))
|
||||
.findFirst().orElseThrow().value());
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> client.createTags(r -> r.resources(eni).tags(t -> t.key("Purpose").value("denied"))));
|
||||
admin.createTags(r -> r.resources(eni).tags(t -> t.key("ManagedBy").value("team-a")));
|
||||
client.deleteTags(r -> r.resources(eni).tags(t -> t.key("ManagedBy")));
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> client.createTags(r -> r.resources(eni).tags(t -> t.key("Purpose").value("denied"))));
|
||||
} finally {
|
||||
admin.deleteNetworkInterface(r -> r.networkInterfaceId(eni));
|
||||
assertEquals(0, admin.describeTags(r -> r.filters(f -> f.name("resource-id").values(eni))).tags().size());
|
||||
admin.deleteSubnet(r -> r.subnetId(subnet));
|
||||
admin.deleteVpc(r -> r.vpcId(vpc));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String create(Ec2Client client, String subnet, String group, String second, String owner) {
|
||||
return client.createNetworkInterface(r -> r.subnetId(subnet).groups(group, second)
|
||||
.tagSpecifications(tags("network-interface", owner))).networkInterface().networkInterfaceId();
|
||||
}
|
||||
|
||||
private TagSpecification tags(String type, String owner) {
|
||||
return TagSpecification.builder().resourceType(type).tags(t -> t.key("ManagedBy").value(owner)).build();
|
||||
}
|
||||
|
||||
private String grant(String resource, String owner) {
|
||||
return """
|
||||
{"Effect":"Allow","Action":"ec2:CreateNetworkInterface",
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:%s",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/ManagedBy":"%s"}}}
|
||||
""".formatted(resource, owner);
|
||||
}
|
||||
|
||||
private void policy(String user, String statements) {
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), user,
|
||||
"network", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
|
||||
import software.amazon.awssdk.services.ec2.model.IpPermission;
|
||||
import software.amazon.awssdk.services.ec2.model.RouteTableAssociation;
|
||||
import software.amazon.awssdk.services.ec2.model.TagSpecification;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class Ec2NetworkMutationIamIntegrationTest {
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"ModifySubnetAttribute", "AttachInternetGateway", "DetachInternetGateway",
|
||||
"CreateRoute", "ReplaceRoute", "DeleteRoute", "AssociateRouteTable",
|
||||
"AuthorizeSecurityGroupIngress", "AuthorizeSecurityGroupEgress", "RevokeSecurityGroupIngress",
|
||||
"RevokeSecurityGroupEgress", "DeleteVpc", "DeleteSubnet", "DeleteRouteTable",
|
||||
"DeleteInternetGateway", "DeleteSecurityGroup"})
|
||||
void scopedMutationsReadCurrentOwnershipAndHonorDenies(String action) {
|
||||
String user = "network-mutation-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
|
||||
auth("000000000000", "iam"), user);
|
||||
try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), Region.US_EAST_1, endpoint);
|
||||
Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint)) {
|
||||
String vpc = admin.createVpc(r -> r.cidrBlock("10.202.0.0/16").tagSpecifications(tags("vpc"))).vpc().vpcId();
|
||||
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.202.1.0/24")
|
||||
.tagSpecifications(tags("subnet"))).subnet().subnetId();
|
||||
String table = admin.createRouteTable(r -> r.vpcId(vpc).tagSpecifications(tags("route-table")))
|
||||
.routeTable().routeTableId();
|
||||
String gateway = admin.createInternetGateway(r -> r.tagSpecifications(tags("internet-gateway")))
|
||||
.internetGateway().internetGatewayId();
|
||||
String group = admin.createSecurityGroup(r -> r.vpcId(vpc).groupName("scoped-" + UUID.randomUUID())
|
||||
.description("IAM mutation fixture").tagSpecifications(tags("security-group"))).groupId();
|
||||
IpPermission permission = IpPermission.builder().ipProtocol("tcp").fromPort(443).toPort(443)
|
||||
.ipRanges(r -> r.cidrIp("192.0.2.0/24")).build();
|
||||
if (action.equals("DetachInternetGateway") || action.endsWith("Route")) {
|
||||
admin.attachInternetGateway(r -> r.internetGatewayId(gateway).vpcId(vpc));
|
||||
}
|
||||
if (action.equals("ReplaceRoute") || action.equals("DeleteRoute")) {
|
||||
admin.createRoute(r -> r.routeTableId(table).gatewayId(gateway).destinationCidrBlock("0.0.0.0/0"));
|
||||
}
|
||||
if (action.equals("RevokeSecurityGroupIngress")) {
|
||||
admin.authorizeSecurityGroupIngress(r -> r.groupId(group).ipPermissions(permission));
|
||||
}
|
||||
if (action.equals("RevokeSecurityGroupEgress")) {
|
||||
admin.authorizeSecurityGroupEgress(r -> r.groupId(group).ipPermissions(permission));
|
||||
}
|
||||
if (action.equals("DeleteVpc")) {
|
||||
admin.deleteSubnet(r -> r.subnetId(subnet));
|
||||
admin.deleteRouteTable(r -> r.routeTableId(table));
|
||||
admin.deleteSecurityGroup(r -> r.groupId(group));
|
||||
}
|
||||
Runnable mutate = () -> {
|
||||
switch (action) {
|
||||
case "ModifySubnetAttribute" -> client.modifySubnetAttribute(r -> r.subnetId(subnet)
|
||||
.mapPublicIpOnLaunch(v -> v.value(true)));
|
||||
case "AttachInternetGateway" -> client.attachInternetGateway(r -> r.internetGatewayId(gateway).vpcId(vpc));
|
||||
case "DetachInternetGateway" -> client.detachInternetGateway(r -> r.internetGatewayId(gateway).vpcId(vpc));
|
||||
case "CreateRoute" -> client.createRoute(r -> r.routeTableId(table).gatewayId(gateway)
|
||||
.destinationCidrBlock("0.0.0.0/0"));
|
||||
case "ReplaceRoute" -> client.replaceRoute(r -> r.routeTableId(table).gatewayId(gateway)
|
||||
.destinationCidrBlock("0.0.0.0/0"));
|
||||
case "DeleteRoute" -> client.deleteRoute(r -> r.routeTableId(table).destinationCidrBlock("0.0.0.0/0"));
|
||||
case "AssociateRouteTable" -> client.associateRouteTable(r -> r.routeTableId(table).subnetId(subnet));
|
||||
case "AuthorizeSecurityGroupIngress" -> client.authorizeSecurityGroupIngress(r -> r.groupId(group)
|
||||
.ipPermissions(permission));
|
||||
case "AuthorizeSecurityGroupEgress" -> client.authorizeSecurityGroupEgress(r -> r.groupId(group)
|
||||
.ipPermissions(permission));
|
||||
case "RevokeSecurityGroupIngress" -> client.revokeSecurityGroupIngress(r -> r.groupId(group)
|
||||
.ipPermissions(permission));
|
||||
case "RevokeSecurityGroupEgress" -> client.revokeSecurityGroupEgress(r -> r.groupId(group)
|
||||
.ipPermissions(permission));
|
||||
case "DeleteVpc" -> client.deleteVpc(r -> r.vpcId(vpc));
|
||||
case "DeleteSubnet" -> client.deleteSubnet(r -> r.subnetId(subnet));
|
||||
case "DeleteRouteTable" -> client.deleteRouteTable(r -> r.routeTableId(table));
|
||||
case "DeleteInternetGateway" -> client.deleteInternetGateway(r -> r.internetGatewayId(gateway));
|
||||
case "DeleteSecurityGroup" -> client.deleteSecurityGroup(r -> r.groupId(group));
|
||||
default -> throw new IllegalArgumentException(action);
|
||||
}
|
||||
};
|
||||
String grant = """
|
||||
{"Effect":"Allow","Action":"ec2:%s","Resource":"arn:aws:ec2:us-east-1:000000000000:*",
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/Owner":"integration-test"}}}
|
||||
""".formatted(action);
|
||||
// New rule IDs have no stored tags; authorization of the parent group remains required.
|
||||
String rules = """
|
||||
,{"Effect":"Allow","Action":"ec2:%s",
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:security-group-rule/*"}
|
||||
""".formatted(action);
|
||||
try {
|
||||
policy(user, grant.replace("integration-test", "wrong-owner") + rules);
|
||||
assertAwsError("UnauthorizedOperation", 403, mutate::run);
|
||||
policy(user, grant.replace(":000000000000:", ":111122223333:") + rules);
|
||||
assertAwsError("UnauthorizedOperation", 403, mutate::run);
|
||||
policy(user, grant + rules + "," + grant.replace("Allow", "Deny"));
|
||||
assertAwsError("UnauthorizedOperation", 403, mutate::run);
|
||||
policy(user, grant + rules);
|
||||
mutate.run();
|
||||
if (action.equals("ModifySubnetAttribute")) {
|
||||
assertTrue(admin.describeSubnets(r -> r.subnetIds(subnet)).subnets().getFirst().mapPublicIpOnLaunch());
|
||||
}
|
||||
} finally {
|
||||
if (!action.equals("DeleteVpc")) {
|
||||
if (!action.equals("DeleteRouteTable")) {
|
||||
for (RouteTableAssociation association : admin.describeRouteTables(r -> r.routeTableIds(table))
|
||||
.routeTables().getFirst().associations()) {
|
||||
if (!Boolean.TRUE.equals(association.main())) {
|
||||
admin.disassociateRouteTable(r -> r.associationId(association.routeTableAssociationId()));
|
||||
}
|
||||
}
|
||||
remove(() -> admin.deleteRouteTable(r -> r.routeTableId(table)));
|
||||
}
|
||||
remove(() -> admin.deleteSubnet(r -> r.subnetId(subnet)));
|
||||
remove(() -> admin.deleteSecurityGroup(r -> r.groupId(group)));
|
||||
}
|
||||
remove(() -> admin.detachInternetGateway(r -> r.internetGatewayId(gateway).vpcId(vpc)));
|
||||
remove(() -> admin.deleteInternetGateway(r -> r.internetGatewayId(gateway)));
|
||||
remove(() -> admin.deleteVpc(r -> r.vpcId(vpc)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private TagSpecification tags(String type) {
|
||||
return TagSpecification.builder().resourceType(type).tags(t -> t.key("Owner").value("integration-test")).build();
|
||||
}
|
||||
|
||||
|
||||
private void remove(Runnable cleanup) {
|
||||
try {
|
||||
cleanup.run();
|
||||
} catch (Ec2Exception expected) {
|
||||
// The action under test may already have removed or detached this fixture.
|
||||
if (!expected.awsErrorDetails().errorCode().endsWith(".NotFound")
|
||||
&& !expected.awsErrorDetails().errorCode().equals("Gateway.NotAttached")) {
|
||||
throw expected;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void policy(String user, String statements) {
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), user,
|
||||
"mutation", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.Tag;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class Ec2NetworkTagsIamIntegrationTest {
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void networkTagBatchesAuthorizeEachResourceAndItsOwnStoredTags() {
|
||||
String user = "network-tags-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
|
||||
auth("000000000000", "iam"), user);
|
||||
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
|
||||
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
String vpc = admin.createVpc(r -> r.cidrBlock("10.206.0.0/16")).vpc().vpcId();
|
||||
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.206.1.0/24")).subnet().subnetId();
|
||||
String group = admin.describeSecurityGroups(r -> r.filters(f -> f.name("vpc-id").values(vpc)))
|
||||
.securityGroups().getFirst().groupId();
|
||||
String acl = admin.describeNetworkAcls(r -> r.filters(f -> f.name("vpc-id").values(vpc)))
|
||||
.networkAcls().getFirst().networkAclId();
|
||||
String route = admin.describeRouteTables(r -> r.filters(f -> f.name("vpc-id").values(vpc)))
|
||||
.routeTables().getFirst().routeTableId();
|
||||
String eni = admin.createNetworkInterface(r -> r.subnetId(subnet).groups(group))
|
||||
.networkInterface().networkInterfaceId();
|
||||
List<String> ids = List.of(group, acl, route, eni);
|
||||
String resources = """
|
||||
["arn:aws:ec2:us-east-1:000000000000:security-group/*",
|
||||
"arn:aws:ec2:us-east-1:000000000000:network-acl/*",
|
||||
"arn:aws:ec2:us-east-1:000000000000:route-table/*",
|
||||
"arn:aws:ec2:us-east-1:000000000000:network-interface/*"]
|
||||
""";
|
||||
String grant = """
|
||||
{"Effect":"Allow","Action":"ec2:CreateTags","Resource":%s,
|
||||
"Condition":{"StringEquals":{"aws:RequestTag/Owner":"owner"},
|
||||
"ForAllValues:StringEquals":{"aws:TagKeys":["Owner"]},
|
||||
"StringEqualsIfExists":{"aws:ResourceTag/Owner":"${aws:RequestTag/Owner}"},
|
||||
"Null":{"aws:ResourceTag/ManagedBy":"true"}}},
|
||||
{"Effect":"Allow","Action":"ec2:DeleteTags","Resource":%s,
|
||||
"Condition":{"StringEquals":{"aws:ResourceTag/Owner":"owner"}}}
|
||||
""".formatted(resources, resources);
|
||||
try {
|
||||
policy(user, grant);
|
||||
client.createTags(r -> r.resources(ids).tags(owner("owner")));
|
||||
assertEquals(4, admin.describeTags(r -> r.filters(f -> f.name("resource-id").values(ids)))
|
||||
.tags().stream().filter(t -> "Owner".equals(t.key()) && "owner".equals(t.value())).count());
|
||||
admin.createTags(r -> r.resources(eni).tags(owner("foreign")));
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> client.createTags(r -> r.resources(ids).tags(owner("owner"))));
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> client.deleteTags(r -> r.resources(ids).tags(owner("owner"))));
|
||||
assertEquals(4, admin.describeTags(r -> r.filters(f -> f.name("resource-id").values(ids)))
|
||||
.tags().stream().filter(t -> "Owner".equals(t.key())).count());
|
||||
admin.createTags(r -> r.resources(eni).tags(owner("owner")));
|
||||
policy(user, grant + "," + """
|
||||
{"Effect":"Deny","Action":["ec2:CreateTags","ec2:DeleteTags"],
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:network-interface/%s"}
|
||||
""".formatted(eni));
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> client.createTags(r -> r.resources(ids).tags(owner("owner"))));
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> client.deleteTags(r -> r.resources(ids).tags(owner("owner"))));
|
||||
policy(user, grant);
|
||||
// A resource type not covered by the grants must not borrow a preceding target's ARN.
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> client.createTags(r -> r.resources(group, vpc).tags(owner("owner"))));
|
||||
client.deleteTags(r -> r.resources(ids).tags(owner("owner")));
|
||||
assertTrue(admin.describeTags(r -> r.filters(f -> f.name("resource-id").values(ids))).tags().stream()
|
||||
.noneMatch(t -> "Owner".equals(t.key())));
|
||||
} finally {
|
||||
admin.deleteNetworkInterface(r -> r.networkInterfaceId(eni));
|
||||
admin.deleteSubnet(r -> r.subnetId(subnet));
|
||||
admin.deleteVpc(r -> r.vpcId(vpc));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void policy(String user, String statements) {
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), user, "tags",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
|
||||
}
|
||||
|
||||
private static Tag owner(String value) {
|
||||
return Tag.builder().key("Owner").value(value).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.ResourceType;
|
||||
import software.amazon.awssdk.services.ec2.model.Tag;
|
||||
import software.amazon.awssdk.services.ec2.model.TagSpecification;
|
||||
import software.amazon.awssdk.services.ec2.model.VpcAttributeName;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class Ec2VpcResourceTagsIntegrationTest {
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"aws:ResourceTag/", "ec2:ResourceTag/"})
|
||||
void modifyVpcAttributeUsesTheTargetsCurrentTagsAndHonorsDeny(String prefix) {
|
||||
String user = "vpc-tag-" + UUID.randomUUID();
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
|
||||
auth("000000000000", "iam"), user);
|
||||
String allow = """
|
||||
{"Effect":"Allow","Action":"ec2:ModifyVpcAttribute",
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:vpc/*",
|
||||
"Condition":{"StringEquals":{"%sManagedBy":"integration-test"}}}
|
||||
""".formatted(prefix);
|
||||
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.US_EAST_1, endpoint);
|
||||
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
|
||||
String owned = create(admin, "integration-test");
|
||||
String other = create(admin, "other");
|
||||
String untagged = admin.createVpc(r -> r.cidrBlock("10.203.0.0/16")).vpc().vpcId();
|
||||
try {
|
||||
policy(user, allow);
|
||||
client.modifyVpcAttribute(r -> r.vpcId(owned).enableDnsHostnames(a -> a.value(true)));
|
||||
assertTrue(admin.describeVpcAttribute(r -> r.vpcId(owned)
|
||||
.attribute(VpcAttributeName.ENABLE_DNS_HOSTNAMES)).enableDnsHostnames().value());
|
||||
denied(client, other);
|
||||
denied(client, untagged);
|
||||
policy(user, allow + "," + """
|
||||
{"Effect":"Deny","Action":"ec2:ModifyVpcAttribute",
|
||||
"Resource":"arn:aws:ec2:us-east-1:000000000000:vpc/%s"}
|
||||
""".formatted(owned));
|
||||
denied(client, owned);
|
||||
policy(user, allow);
|
||||
admin.createTags(r -> r.resources(owned).tags(Tag.builder().key("ManagedBy").value("other").build()));
|
||||
denied(client, owned);
|
||||
} finally {
|
||||
for (String id : new String[]{owned, other, untagged}) {
|
||||
admin.deleteVpc(r -> r.vpcId(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String create(Ec2Client client, String owner) {
|
||||
return client.createVpc(r -> r.cidrBlock("10.202.0.0/16")
|
||||
.tagSpecifications(TagSpecification.builder().resourceType(ResourceType.VPC)
|
||||
.tags(Tag.builder().key("ManagedBy").value(owner).build()).build())).vpc().vpcId();
|
||||
}
|
||||
|
||||
private void denied(Ec2Client client, String vpcId) {
|
||||
assertAwsError("UnauthorizedOperation", 403,
|
||||
() -> client.modifyVpcAttribute(r -> r.vpcId(vpcId).enableDnsHostnames(a -> a.value(true))));
|
||||
}
|
||||
|
||||
private void policy(String user, String statements) {
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), user,
|
||||
"modify", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
|
||||
}
|
||||
}
|
||||
@@ -447,7 +447,10 @@ class RequestResourceMembersTest {
|
||||
}
|
||||
String sent = where == null ? value : "other";
|
||||
put(body, member, sent);
|
||||
form.append('&').append(parameter(member)).append('=').append(encoded(sent));
|
||||
String ec2Wire = table.ec2Query().getOrDefault(operation.getKey(), Map.of()).get(member);
|
||||
String parameter = ec2Wire == null ? parameter(member)
|
||||
: ec2Wire + (member.list() ? ".1" : "");
|
||||
form.append('&').append(parameter).append('=').append(encoded(sent));
|
||||
});
|
||||
List<String> named = operation.getValue().stream()
|
||||
.filter(other -> (other == resource || named(other) || sharesAMember(other, given)
|
||||
|
||||
@@ -31,6 +31,7 @@ class RequestResourcesTest {
|
||||
private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
|
||||
private static final String MACHINE = "arn:aws:states:us-east-1:000000000000:stateMachine:orders";
|
||||
private static final RegionResolver US_EAST_1 = new RegionResolver("us-east-1", "000000000000");
|
||||
|
||||
/** EventBridge as it answers the reader: the Region's default bus, {@code event-bus/default}. */
|
||||
private static final StoredResourceArns EVENTS = new StoredResourceArns() {
|
||||
@Override
|
||||
@@ -50,6 +51,34 @@ class RequestResourcesTest {
|
||||
}
|
||||
};
|
||||
|
||||
@Test
|
||||
void ec2ListsUseSdkWireNamesAndIgnoreForgedQuerySpellings() {
|
||||
String prefix = "arn:aws:ec2:us-east-1:000000000000:";
|
||||
List<String> expected = List.of(prefix + "network-interface/*", prefix + "security-group/sg-one",
|
||||
prefix + "security-group/sg-two", prefix + "subnet/subnet-one");
|
||||
assertEquals(expected, of("ec2:CreateNetworkInterface", form("Action=CreateNetworkInterface"
|
||||
+ "&SubnetId=subnet-one&SecurityGroupId.1=sg-one&SecurityGroupId.2=sg-two"
|
||||
+ "&Groups.member.1=sg-forged&Groups.2=sg-forged&Groups=sg-forged")));
|
||||
assertEquals(expected, of("ec2:CreateNetworkInterface", json("""
|
||||
{"SubnetId":"subnet-one","Groups":["sg-one","sg-two"]}
|
||||
""")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createVpcChecksItsNewArnAndOnlyThePoolsPresentInTheRequest() {
|
||||
String prefix = "arn:aws:ec2:us-east-1:000000000000:";
|
||||
assertEquals(List.of(prefix + "vpc/*"), of("ec2:CreateVpc", json("{\"CidrBlock\":\"10.0.0.0/16\"}")));
|
||||
assertEquals(List.of("arn:aws:ec2::000000000000:ipam-pool/ipam-pool-v4",
|
||||
prefix + "ipv6pool-ec2/ipv6pool-one", prefix + "vpc/*",
|
||||
"arn:aws:ec2::000000000000:ipam-pool/ipam-pool-v6"),
|
||||
of("ec2:CreateVpc", json("""
|
||||
{"Ipv4IpamPoolId":"ipam-pool-v4","Ipv6IpamPoolId":"ipam-pool-v6",
|
||||
"Ipv6Pool":"ipv6pool-one"}
|
||||
""")));
|
||||
assertEquals(List.of(prefix + "vpc/*", "arn:aws:ec2::000000000000:ipam-pool/ipam-pool-v6"),
|
||||
of("ec2:CreateVpc", json("{\"Ipv6IpamPoolId\":\"ipam-pool-v6\"}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inferredLandingZoneIdentifiersKeepRawContextAcrossOperations() {
|
||||
String arn = "arn:aws:controltower:::landingzone/missing";
|
||||
|
||||
@@ -94,13 +94,16 @@ follow the rule unchanged: a family of a hand-built namespace whose requests nam
|
||||
way the rule reads them. `HAND_BUILT` are the namespaces `ResourceArnBuilder` builds resources for itself, and
|
||||
`NOT_COVERED` the ones Floci serves that are not read yet, each with its reason;
|
||||
`RequestResourceNamespacesIntegrationTest` fails for a served namespace in none of the three.
|
||||
`ID_TARGETS` is Floci's coverage of id-list namespaces, the types of each it reads by id (EC2's instances): a
|
||||
resource ARN's variable names its list member, with the request's list of whatever resources it acts on
|
||||
(`Resources`) as a fallback. Botocore supplies its serialized EC2 Query name (including queryName and
|
||||
capitalization), and the id prefix botocore documents each type with ("the instance ID (for example,
|
||||
i-0123456789abcdef0)") distinguishes them. `resourceTagKeys` comes from those types' Service Reference condition keys. Each generated `targets` entry preserves the
|
||||
request's order and duplicates, including a wildcard for each unsupported id; only resolved ARNs
|
||||
use the corresponding target's condition context. Other requests in those namespaces stay on `*`.
|
||||
`ID_TARGETS` is Floci's coverage of id-list namespaces, the types of each it reads by id (EC2's instances and
|
||||
network resources): a resource ARN's variable names its list member, with the request's list of whatever resources
|
||||
it acts on (`Resources`) as a fallback. A list a type's variable names is the request's targets only when the
|
||||
request names nothing else the action acts on. Botocore supplies its serialized EC2 Query name (including queryName
|
||||
and capitalization), and the id prefix botocore gives each type, in its documentation ("the instance ID (for
|
||||
example, i-0123456789abcdef0)") or its examples (`"GroupId": "sg-903004f8"`), distinguishes them. Each generated
|
||||
`targets` entry preserves the request's order and duplicates, including a wildcard for each unsupported id; only
|
||||
resolved ARNs use the corresponding target's condition context. Every other request of those namespaces is read by
|
||||
the ordinary rules, its EC2 Query wire names (`ec2Query`) from botocore. `resourceTagKeys` gives every type of those
|
||||
namespaces its Service Reference resource-tag condition keys, as their service keeps tags by resource id.
|
||||
Beyond the members' names, botocore's shapes and documentation say what a member names, and the rule reads them:
|
||||
- a member whose documentation names the type, word for word ("The name of the pipeline to start"), fills its
|
||||
variable when it is the kind the variable is (a name, an id), and is found by the type's service otherwise
|
||||
@@ -217,7 +220,9 @@ from regen_iam_passed_roles import (
|
||||
load_models,
|
||||
namespace_of,
|
||||
)
|
||||
from regen_partitions import load_model as load_json_file
|
||||
from regen_partitions import resolve_botocore_data
|
||||
from regen_query_services import latest_model_dir
|
||||
from regen_rest_routes import MODELS as REST_MODELS
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
@@ -418,15 +423,17 @@ KNOWN_VARIABLES = {"Partition", "Region", "Account"}
|
||||
|
||||
# Floci's coverage of id-list namespaces: the types of each it reads by id, which ResourceArnBuilder and the condition
|
||||
# resolver resolve with their stored tags. It states no AWS fact: the model supplies each list member and its wire
|
||||
# name, the Service Reference the action's types and ARN formats, and botocore's documentation the id prefix of each
|
||||
# type (`id_prefixes`). Other ids keep a wildcard entry until their coverage grows; requests without those lists stay
|
||||
# unchanged.
|
||||
ID_TARGETS = {"ec2": ("instance",)}
|
||||
# name, the Service Reference the action's types and ARN formats, and botocore's documentation and examples the id
|
||||
# prefix of each type (`id_prefixes`). Other ids keep a wildcard entry until their coverage grows; every request
|
||||
# without those lists is read by the ordinary rules.
|
||||
ID_TARGETS = {"ec2": ("instance", "network-acl", "network-interface", "route-table", "security-group")}
|
||||
# An ARN format's account given as `${AccountId}`, the account `${Account}` gives in every other format.
|
||||
ACCOUNT_ID_SLOT_RE = re.compile(r"^(arn:[^:]*:[^:]*:[^:]*:)\$\{AccountId}:")
|
||||
VARIABLE_RE = re.compile(r"\$\{(\w+)}")
|
||||
# A type's id with the example botocore documents it by: "the instance ID (for example, i-0123456789abcdef0)".
|
||||
ID_EXAMPLE_RE = re.compile(r"\b([a-z][a-z ]*?) ID \(for example, ([a-z0-9]+-)[0-9a-f]{8,}\)")
|
||||
# An id one of botocore's request or response examples gives a member: "GroupId": "sg-903004f8".
|
||||
EXAMPLE_ID_RE = re.compile(r"^([a-z0-9]+-)[0-9a-f]{8,17}$")
|
||||
# A sentence of botocore's documentation stating the members that key a type: "<things> are uniquely identified by the
|
||||
# combination of <parts>".
|
||||
UNIQUE_KEY_RE = re.compile(r"(?P<things>[A-Za-z][A-Za-z ]*?) (?:are|is) uniquely identified by (?:the )?combination of "
|
||||
@@ -499,14 +506,17 @@ def checked_actions(documents: list[dict]) -> dict[str, dict]:
|
||||
|
||||
|
||||
def resource_tag_keys(documents: list[dict]) -> dict[str, dict[str, list[str]]]:
|
||||
"""Stored-tag key prefixes for the resource types the id-target reader supports."""
|
||||
"""Stored-tag key prefixes for every resource type of the id-target namespaces, as the Service Reference gives each
|
||||
type's resource-tag condition keys: their service keeps a resource's tags by its id, whatever its type."""
|
||||
result = {}
|
||||
for document in documents:
|
||||
namespace = document["Name"]
|
||||
supported = ID_TARGETS.get(namespace, ())
|
||||
if namespace not in ID_TARGETS:
|
||||
continue
|
||||
types = {resource["Name"]: sorted(key.removesuffix("${TagKey}")
|
||||
for key in resource.get("ConditionKeys", []) if key.endswith(":ResourceTag/${TagKey}"))
|
||||
for resource in document.get("Resources", []) if resource["Name"] in supported}
|
||||
for resource in document.get("Resources", [])}
|
||||
types = {kind: keys for kind, keys in types.items() if keys}
|
||||
if types:
|
||||
result[namespace] = dict(sorted(types.items()))
|
||||
return dict(sorted(result.items()))
|
||||
@@ -696,7 +706,9 @@ def documented_members(models: dict[str, dict], operation: str) -> dict[str, dic
|
||||
for field, nested in shape.get("members", {}).items()]
|
||||
for path, item, item_shape in entries:
|
||||
strings = _strings(model, item_shape)
|
||||
if strings is None:
|
||||
# A list inside a structure (`InstanceSpecification.ExcludeDataVolumeIds`) is no path the vendored
|
||||
# file or its reader takes, so it names nothing.
|
||||
if strings is None or "." in path and strings:
|
||||
continue
|
||||
element = model["shapes"][item_shape["member"]["shape"]] if item_shape["type"] == "list" else item_shape
|
||||
found.setdefault(path, {"path": path + strings, "nested": "." in path,
|
||||
@@ -1460,7 +1472,7 @@ def resources_for(operation: str, types: list[str], formats: dict[str, str], mem
|
||||
kept += kinds if len(kinds) == 1 else (full if len(full) == 1 else [])
|
||||
specs = [{"types": kinds, "arn": arns[member]} for member, kinds in sorted(by_arn.items())]
|
||||
return specs + [{"type": kind, "fill": dict(sorted(filled[kind].items()))} for kind in types if kind in kept] + \
|
||||
also_filled(types, members, filled, kept, used, aliased or set())
|
||||
also_filled(types, members, filled, kept, used, aliased or set(), shapes)
|
||||
|
||||
|
||||
RESOURCE_PART_RE = re.compile(r"^arn:\$\{Partition}:[^:]*:[^:]*:[^:]*:([A-Za-z][A-Za-z0-9-]*)(.*)$")
|
||||
@@ -1493,6 +1505,40 @@ def with_made(resources: list[dict], operation: str, formats: dict[str, str]) ->
|
||||
for resource, is_made in zip(resources, made, strict=True)]
|
||||
|
||||
|
||||
def with_documented_creation(resources: list[dict], operation: str, types: list[str],
|
||||
formats: dict[str, str], models: dict[str, dict]) -> list[dict]:
|
||||
"""A create whose name differs from its type can name it in the operation's opening sentence:
|
||||
AllocateAddress 'Allocates an Elastic IP address'. Require that direct object and the type's sole
|
||||
ARN id as a string in the response, absent from the request. Pool ids echoed in the response and
|
||||
types mentioned later in the documentation do not identify a newly created resource."""
|
||||
name = operation.split(":", 1)[1]
|
||||
verb = CREATING_RE.match(name)
|
||||
if not verb:
|
||||
return resources
|
||||
named = {kind for resource in resources for kind in _kinds(resource)}
|
||||
added = []
|
||||
for kind in types:
|
||||
variables = set(VARIABLE_RE.findall(formats.get(kind, ""))) - KNOWN_VARIABLES
|
||||
if kind in named or len(variables) != 1:
|
||||
continue
|
||||
variable = next(iter(variables))
|
||||
if kind_of(variable) != "id":
|
||||
continue
|
||||
phrase = r"[ -]+".join(re.escape(word) for word in re.split(r"[ -]+", kind.lower()))
|
||||
opening = rf"^{verb.group().lower()}s? (?:a |an |the )?{phrase}\b"
|
||||
for model in models.values():
|
||||
spec = model["operations"].get(name, {})
|
||||
if "input" not in spec or "output" not in spec or not re.match(opening, _lead(spec.get("documentation"))):
|
||||
continue
|
||||
inputs = model["shapes"][spec["input"]["shape"]].get("members", {})
|
||||
outputs = model["shapes"][spec["output"]["shape"]].get("members", {})
|
||||
if variable not in inputs and variable in outputs \
|
||||
and model["shapes"][outputs[variable]["shape"]]["type"] == "string":
|
||||
added.append({"type": kind, "fill": {}, "made": True})
|
||||
break
|
||||
return resources + added
|
||||
|
||||
|
||||
def child_id(child: str, parent: str) -> str | None:
|
||||
"""The variable a child type's ARN format adds to its parent's: the parent's with its leading resource type word
|
||||
replaced and one id appended (`listener/app/.../${ListenerId}` for `loadbalancer/app/...`); None for any other."""
|
||||
@@ -1596,7 +1642,8 @@ def _filling(variable: str, kind_stem: str, variables: int, names: dict[str, str
|
||||
|
||||
|
||||
def also_filled(types: list[str], members: dict[str, str], filled: dict[str, dict[str, str]],
|
||||
kept: list[str], used: dict[str, str], aliased: set[str]) -> list[dict]:
|
||||
kept: list[str], used: dict[str, str], aliased: set[str],
|
||||
shapes: dict[str, str] | None = None) -> list[dict]:
|
||||
"""The resources a request names besides the one it fills a type with, when it names several of that type and
|
||||
acts on each of them.
|
||||
|
||||
@@ -1613,7 +1660,15 @@ def also_filled(types: list[str], members: dict[str, str], filled: dict[str, dic
|
||||
for member in sorted(members):
|
||||
if used.get(kind) == member:
|
||||
continue
|
||||
if member not in aliased or not names_type(member, kind_stem):
|
||||
# Two qualified ids of the same modeled id shape name separate resources: IPv4 and IPv6 IPAM pools.
|
||||
selected = used.get(kind, "")
|
||||
sibling_id = (len(filled[kind]) == 1 and kind_of(variable) == "id"
|
||||
and kind_of(member) == "id" and kind_of(selected) == "id"
|
||||
and stem(member) != stem(variable) and stem(selected) != stem(variable)
|
||||
and stem(member).endswith(stem(variable)) and stem(selected).endswith(stem(variable))
|
||||
and (shapes or {}).get(member) == (shapes or {}).get(selected)
|
||||
and stem((shapes or {}).get(member, "")) == stem(variable))
|
||||
if not sibling_id and (member not in aliased or not names_type(member, kind_stem)):
|
||||
continue
|
||||
if not compatible(member, variable):
|
||||
continue
|
||||
@@ -1633,10 +1688,52 @@ def names_type(member: str, kind_stem: str) -> bool:
|
||||
# --------------------------------------------------------------------------- #
|
||||
# The vendored document
|
||||
# --------------------------------------------------------------------------- #
|
||||
def id_prefixes(models: dict[str, dict], kinds: tuple[str, ...]) -> dict[str, str]:
|
||||
"""The prefix botocore documents each type's ids with, "the instance ID (for example, i-0123456789abcdef0)", for the
|
||||
types given; a type it gives no example of has none."""
|
||||
def load_examples(data: Path, clients: set[str]) -> dict[str, dict]:
|
||||
"""Each client's botocore `examples-1.json`, the requests and responses its API reference shows, for the clients
|
||||
that have one."""
|
||||
examples = {}
|
||||
for client in sorted(clients):
|
||||
if not (data / client).is_dir():
|
||||
continue
|
||||
directory = latest_model_dir(data, client)
|
||||
for name in ("examples-1.json", "examples-1.json.gz"):
|
||||
if (directory / name).is_file():
|
||||
examples[client] = load_json_file(directory / name)
|
||||
break
|
||||
return examples
|
||||
|
||||
|
||||
def _example_ids(model: dict, shape_name: str, value: object, found: list[tuple[str, str]]) -> None:
|
||||
"""The ids an example's value gives, each with the string shape botocore declares for its member: the
|
||||
`SecurityGroupId` a `GroupId` holds, or each of a `GroupIds` list."""
|
||||
shape = model["shapes"].get(shape_name, {})
|
||||
if isinstance(value, dict) and shape.get("type") == "structure":
|
||||
members = shape.get("members", {})
|
||||
for name, item in value.items():
|
||||
if name in members:
|
||||
_example_ids(model, members[name]["shape"], item, found)
|
||||
elif isinstance(value, list) and shape.get("type") == "list":
|
||||
for item in value:
|
||||
_example_ids(model, shape["member"]["shape"], item, found)
|
||||
elif isinstance(value, str) and shape.get("type") == "string":
|
||||
match = EXAMPLE_ID_RE.match(value)
|
||||
if match:
|
||||
found.append((shape_name, match.group(1)))
|
||||
|
||||
|
||||
def id_prefixes(models: dict[str, dict], kinds: tuple[str, ...],
|
||||
examples: dict[str, dict] | None = None) -> dict[str, str]:
|
||||
"""The prefix botocore gives each type's ids, for the types given: in its documentation, "the instance ID (for
|
||||
example, i-0123456789abcdef0)", and in its examples, the ids of the members whose shape names the type
|
||||
(`"GroupId": "sg-903004f8"`, a `SecurityGroupId`). The prefix given most wins; a type with none has none."""
|
||||
counts: dict[str, dict[str, int]] = {}
|
||||
|
||||
def count(named: str, prefix: str) -> None:
|
||||
kind = next((kind for kind in kinds if stem(kind) == stem(named)), None)
|
||||
if kind:
|
||||
counts.setdefault(kind, {}).setdefault(prefix, 0)
|
||||
counts[kind][prefix] += 1
|
||||
|
||||
for model in models.values():
|
||||
for shape in model["shapes"].values():
|
||||
for member in shape.get("members", {}).values():
|
||||
@@ -1645,23 +1742,35 @@ def id_prefixes(models: dict[str, dict], kinds: tuple[str, ...]) -> dict[str, st
|
||||
continue
|
||||
text = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", documentation))
|
||||
for named, prefix in ID_EXAMPLE_RE.findall(text):
|
||||
kind = next((kind for kind in kinds if stem(kind) == stem(named.split()[-1])), None)
|
||||
if kind:
|
||||
counts.setdefault(kind, {}).setdefault(prefix, 0)
|
||||
counts[kind][prefix] += 1
|
||||
count(named.split()[-1], prefix)
|
||||
for client, document in sorted((examples or {}).items()):
|
||||
model = models.get(client)
|
||||
if model is None:
|
||||
continue
|
||||
for operation, shown in sorted(document.get("examples", {}).items()):
|
||||
spec = model["operations"].get(operation, {})
|
||||
for example in shown:
|
||||
found: list[tuple[str, str]] = []
|
||||
for part in ("input", "output"):
|
||||
if part in spec and isinstance(example.get(part), dict):
|
||||
_example_ids(model, spec[part]["shape"], example[part], found)
|
||||
for shape_name, prefix in found:
|
||||
count(shape_name, prefix)
|
||||
return {kind: max(found, key=found.get) for kind, found in sorted(counts.items())}
|
||||
|
||||
|
||||
def namespace_id_prefixes(namespace: str, models: dict[str, dict]) -> dict[str, str] | None:
|
||||
def namespace_id_prefixes(namespace: str, models: dict[str, dict],
|
||||
examples: dict[str, dict] | None = None) -> dict[str, str] | None:
|
||||
"""`id_prefixes` of the types `ID_TARGETS` reads by id in the namespace; None for a namespace it reads none of."""
|
||||
return id_prefixes(models, ID_TARGETS[namespace]) if namespace in ID_TARGETS else None
|
||||
return id_prefixes(models, ID_TARGETS[namespace], examples) if namespace in ID_TARGETS else None
|
||||
|
||||
|
||||
def id_targets(operation: str, types: list[str], formats: dict[str, str], models: dict[str, dict],
|
||||
known: dict[str, str] | None = None) -> dict | None:
|
||||
"""An id list, in model and EC2 Query spelling, with each type `ID_TARGETS` reads by id's discriminator, the prefix
|
||||
botocore documents its ids with (`id_prefixes`): the list a type's ARN variable names, or else the request's list
|
||||
of whatever resources it acts on (`Resources`, of the tagging calls)."""
|
||||
botocore gives its ids (`id_prefixes`): the list a type's ARN variable names, when the request names nothing else
|
||||
the action acts on, or else the request's list of whatever resources it acts on (`Resources`, of the tagging
|
||||
calls). None when the request has neither, and the ordinary rules read it."""
|
||||
configured = ID_TARGETS.get(namespace_of(operation))
|
||||
if configured is None:
|
||||
return None
|
||||
@@ -1678,7 +1787,9 @@ def id_targets(operation: str, types: list[str], formats: dict[str, str], models
|
||||
if _strings(model, model["shapes"][member["shape"]]) == "[]"
|
||||
and name.lower().removesuffix("s") in {variable.lower() for variable in variables}]
|
||||
if len(candidates) > 1:
|
||||
raise ValueError(f"{operation}: several id lists name the target: {candidates}")
|
||||
# Lists of several types (a VPC endpoint's `RouteTableIds` and `SecurityGroupIds`) name more than one
|
||||
# thing the action acts on, which the ordinary rules read.
|
||||
continue
|
||||
listed = [name for name, member in members.items() if stem(name) == "resource"
|
||||
and _strings(model, model["shapes"][member["shape"]]) == "[]"]
|
||||
member_name = candidates[0] if candidates else listed[0] if len(listed) == 1 else None
|
||||
@@ -1686,6 +1797,19 @@ def id_targets(operation: str, types: list[str], formats: dict[str, str], models
|
||||
if member is None or _strings(model, model["shapes"][member["shape"]]) != "[]":
|
||||
continue
|
||||
prefixes = {kind: prefix for kind, prefix in known.items() if kind in types and kind in formats}
|
||||
if candidates:
|
||||
# A list a type's ARN variable names holds that type's ids alone, and it is all the request acts on only
|
||||
# when the request names nothing else the action acts on: a launch's `SecurityGroupIds` sit beside its
|
||||
# image, subnet and key pair, so they are not its targets.
|
||||
listed_as = member_name.lower().removesuffix("s")
|
||||
prefixes = {kind: prefix for kind, prefix in prefixes.items()
|
||||
if listed_as in {variable.lower() for variable in VARIABLE_RE.findall(formats[kind])}}
|
||||
others = {kind for resource in by_client(operation, models,
|
||||
lambda read: read_resources(operation, types, formats, read),
|
||||
formats)
|
||||
for kind in _kinds(resource)} - set(prefixes)
|
||||
if others:
|
||||
continue
|
||||
if not prefixes:
|
||||
continue
|
||||
for kind in prefixes:
|
||||
@@ -1701,6 +1825,29 @@ def id_targets(operation: str, types: list[str], formats: dict[str, str], models
|
||||
return found
|
||||
|
||||
|
||||
def ec2_query_members(operation: str, models: dict[str, dict], named: set[str]) -> dict[str, str]:
|
||||
"""Wire names for the top-level EC2 members the rules read. EC2 lists use Name.N,
|
||||
unlike Query's Name.member.N; locationName/queryName can also rename a member."""
|
||||
result = {}
|
||||
for model in models.values():
|
||||
spec = model["operations"].get(operation.split(":", 1)[1], {})
|
||||
if "ec2" not in _protocols(model) or "input" not in spec:
|
||||
continue
|
||||
for name, member in model["shapes"][spec["input"]["shape"]].get("members", {}).items():
|
||||
shape = model["shapes"][member["shape"]]
|
||||
suffix = _strings(model, shape)
|
||||
if name not in named or suffix is None:
|
||||
continue
|
||||
location = member.get("locationName", name)
|
||||
wire = member.get("queryName", location[:1].upper() + location[1:])
|
||||
if suffix or wire != name:
|
||||
path = name + suffix
|
||||
if path in result and result[path] != wire:
|
||||
raise ValueError(f"{operation}: clients disagree on {name}'s EC2 Query name")
|
||||
result[path] = wire
|
||||
return result
|
||||
|
||||
|
||||
def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: dict[str, dict],
|
||||
known: dict[str, str] | None = None, forwarded: dict[str, dict] | None = None) -> dict:
|
||||
"""What the file says for one operation, `forwarded` being what the file records of each action `FORWARDED`
|
||||
@@ -1713,13 +1860,11 @@ def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: d
|
||||
arn_members = {member for member, values in patterns.items()
|
||||
if (kind_of(member) == "identifier" or stem(member) in ("", "resource"))
|
||||
and values and all(only_arn(value) for value in values)}
|
||||
if namespace_of(operation) in ID_TARGETS:
|
||||
entry = {"action": upstream["action"], "types": types, "resources": []}
|
||||
targets = id_targets(operation, types, formats, models, known)
|
||||
if targets is not None:
|
||||
entry["targets"] = targets
|
||||
return entry
|
||||
targets = id_targets(operation, types, formats, models, known) if namespace_of(operation) in ID_TARGETS else None
|
||||
if targets is not None:
|
||||
return {"action": upstream["action"], "types": types, "resources": [], "targets": targets}
|
||||
resources = by_client(operation, models, lambda read: read_resources(operation, types, formats, read), formats)
|
||||
resources = with_documented_creation(resources, operation, types, formats, models)
|
||||
resources = with_made(resources, operation, formats)
|
||||
if operation in MEASURED:
|
||||
resources = measured_resources(operation, types, formats, resources)
|
||||
@@ -1732,6 +1877,9 @@ def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: d
|
||||
if makes:
|
||||
entry["makes"] = makes
|
||||
named = _named(resources) | _named(creates) | _named(makes)
|
||||
query_members = ec2_query_members(operation, models, named)
|
||||
if query_members:
|
||||
entry["ec2Query"] = query_members
|
||||
located = {member: where for member, where in located_members(models, operation.split(":", 1)[1]).items()
|
||||
if member in named}
|
||||
if located:
|
||||
@@ -2255,7 +2403,8 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) ->
|
||||
check_forwarded(authorized_by(documents))
|
||||
forwarded = forwarded_actions(documents)
|
||||
operations = {}
|
||||
prefixes = {namespace: namespace_id_prefixes(namespace, load_models(data, set(namespaces[namespace])))
|
||||
prefixes = {namespace: namespace_id_prefixes(namespace, load_models(data, set(namespaces[namespace])),
|
||||
load_examples(data, set(namespaces[namespace])))
|
||||
for namespace in ID_TARGETS if namespace in namespaces}
|
||||
for operation, value in sorted(covered.items()):
|
||||
models = load_models(data, set(namespaces[namespace_of(operation)]))
|
||||
@@ -2473,7 +2622,7 @@ def validate(document: dict) -> list[str]:
|
||||
problems.append(f"{operation!r} is not an operation of a namespace the file reads")
|
||||
continue
|
||||
if not isinstance(entry, dict) or not {"action", "types", "resources"} <= set(entry) <= {
|
||||
"action", "types", "resources", "creates", "makes", "located", "targets", "forwarded"}:
|
||||
"action", "types", "resources", "creates", "makes", "located", "targets", "forwarded", "ec2Query"}:
|
||||
problems.append(f"{operation} is not an action, its types and its resources")
|
||||
continue
|
||||
if not isinstance(entry["action"], str) or not OPERATION_RE.match(entry["action"]) \
|
||||
@@ -2513,6 +2662,13 @@ def validate(document: dict) -> list[str]:
|
||||
values = [p for p in prefixes.values() if isinstance(p, str)]
|
||||
if any(a.startswith(b) for i, a in enumerate(values) for j, b in enumerate(values) if i != j):
|
||||
problems.append(f"{operation} has ambiguous id prefixes")
|
||||
query_members = entry.get("ec2Query")
|
||||
if query_members is not None and (namespace != "ec2" or not isinstance(query_members, dict)
|
||||
or not query_members or not all(isinstance(member, str)
|
||||
and re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*(\[\])?", member)
|
||||
and isinstance(wire, str) and re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", wire)
|
||||
for member, wire in query_members.items())):
|
||||
problems.append(f"{operation} has invalid EC2 Query member names")
|
||||
located = entry.get("located", {})
|
||||
if not isinstance(located, dict) or not located and "located" in entry or not all(
|
||||
isinstance(member, str) and PATH_RE.match(member) and isinstance(where, str) and LOCATED_RE.match(where)
|
||||
@@ -2644,7 +2800,8 @@ def derive(document: dict, data: Path) -> list[str]:
|
||||
if sorted(document["forwardedActions"]) != named:
|
||||
problems.append(f"the file records {sorted(document['forwardedActions'])} as forwarded actions, FORWARDED "
|
||||
f"names {named}")
|
||||
prefixes = {namespace: namespace_id_prefixes(namespace, load_models(data, set(document["namespaces"][namespace])))
|
||||
prefixes = {namespace: namespace_id_prefixes(namespace, load_models(data, set(document["namespaces"][namespace])),
|
||||
load_examples(data, set(document["namespaces"][namespace])))
|
||||
for namespace in ID_TARGETS if namespace in document["namespaces"]}
|
||||
for operation, entry in document["operations"].items():
|
||||
namespace = namespace_of(operation)
|
||||
|
||||
@@ -1262,6 +1262,24 @@ def with_instance_example(model_: dict) -> dict:
|
||||
return model_
|
||||
|
||||
|
||||
def test_create_vpc_reads_the_new_vpc_and_each_optional_pool():
|
||||
ec2 = model({"CreateVpc": {"CidrBlock": "String", "Ipv4IpamPoolId": "IpamPoolId",
|
||||
"Ipv6IpamPoolId": "IpamPoolId", "Ipv6Pool": "Ipv6PoolEc2Id"}}, "ec2")
|
||||
ec2["shapes"]["IpamPoolId"] = {"type": "string"}
|
||||
ec2["shapes"]["Ipv6PoolEc2Id"] = {"type": "string"}
|
||||
formats = {"vpc": "arn:${Partition}:ec2:${Region}:${Account}:vpc/${VpcId}",
|
||||
"ipam-pool": "arn:${Partition}:ec2::${Account}:ipam-pool/${IpamPoolId}",
|
||||
"ipv6pool-ec2": "arn:${Partition}:ec2:${Region}:${Account}:ipv6pool-ec2/${Ipv6PoolEc2Id}"}
|
||||
upstream = {"action": "ec2:CreateVpc", "types": ["ipam-pool", "ipv6pool-ec2", "vpc"]}
|
||||
entry = r.entry_for("ec2:CreateVpc", upstream, formats, {"ec2": ec2})
|
||||
assert entry["resources"] == [
|
||||
{"type": "ipam-pool", "fill": {"IpamPoolId": "Ipv4IpamPoolId"}},
|
||||
{"type": "ipv6pool-ec2", "fill": {"Ipv6PoolEc2Id": "Ipv6Pool"}},
|
||||
{"type": "vpc", "fill": {}, "made": True},
|
||||
{"type": "ipam-pool", "fill": {"IpamPoolId": "Ipv6IpamPoolId"}}]
|
||||
assert "targets" not in entry
|
||||
|
||||
|
||||
def test_id_targets_follow_the_model_and_resource_types_not_operation_names():
|
||||
ec2 = with_instance_example(model({"AnnotateResources": {"Resources": "Strings"}}, "ec2"))
|
||||
member = ec2["shapes"]["AnnotateResourcesIn"]["members"]["Resources"]
|
||||
@@ -1301,7 +1319,9 @@ def test_generated_targets_match_botocores_actual_serialization(operation, targe
|
||||
operation_model = model.operation_model(name)
|
||||
parameters = ArgumentGenerator().generate_skeleton(operation_model.input_shape)
|
||||
parameters[target["member"].removesuffix("[]")] = ids
|
||||
request = create_serializer(model.metadata["protocol"]).serialize_to_request(parameters, operation_model)
|
||||
# The skeleton's other members are placeholders (an empty tag key), so only the serialization is checked.
|
||||
request = create_serializer(model.metadata["protocol"], include_validation=False).serialize_to_request(
|
||||
parameters, operation_model)
|
||||
assert [request["body"][target["query"] + "." + str(i)] for i in range(1, 4)] == ids
|
||||
checked += 1
|
||||
assert checked > 0
|
||||
@@ -1331,15 +1351,34 @@ def test_instance_target_member_is_derived_from_the_arn_variable_not_the_action_
|
||||
renamed_formats, {"ec2": renamed})["targets"]["member"] == "MachineIds[]"
|
||||
|
||||
|
||||
def test_resource_tag_prefixes_come_only_from_supported_reference_resources():
|
||||
def test_resource_tag_prefixes_cover_every_type_of_an_id_target_namespace_from_the_reference():
|
||||
documents = [{"Name": "ec2", "Resources": [
|
||||
{"Name": "instance", "ConditionKeys": ["vendor:ResourceTag/${TagKey}", "aws:RequestTag/${TagKey}",
|
||||
"aws:ResourceTag/${TagKey}", "ec2:Region"]},
|
||||
{"Name": "volume", "ConditionKeys": ["volume:ResourceTag/${TagKey}"]}]}]
|
||||
assert r.resource_tag_keys(documents) == {"ec2": {"instance": ["aws:ResourceTag/", "vendor:ResourceTag/"]}}
|
||||
{"Name": "volume", "ConditionKeys": ["volume:ResourceTag/${TagKey}"]},
|
||||
{"Name": "untaggable", "ConditionKeys": ["ec2:Region"]}]},
|
||||
{"Name": "other", "Resources": [{"Name": "thing", "ConditionKeys": ["aws:ResourceTag/${TagKey}"]}]}]
|
||||
assert r.resource_tag_keys(documents) == {"ec2": {"instance": ["aws:ResourceTag/", "vendor:ResourceTag/"],
|
||||
"volume": ["volume:ResourceTag/"]}}
|
||||
assert r.resource_tag_keys([]) == {}
|
||||
|
||||
|
||||
def test_id_prefixes_read_botocores_examples_by_the_shape_of_each_member():
|
||||
ec2 = model({"DescribeGroups": {"GroupIds": "GroupIdList", "Label": "String"}}, "ec2")
|
||||
ec2["shapes"]["SecurityGroupId"] = {"type": "string"}
|
||||
ec2["shapes"]["GroupIdList"] = {"type": "list", "member": {"shape": "SecurityGroupId"}}
|
||||
ec2["operations"]["DescribeGroups"]["output"] = {"shape": "DescribeGroupsOut"}
|
||||
ec2["shapes"]["DescribeGroupsOut"] = {"type": "structure", "members": {"GroupId": {"shape": "SecurityGroupId"}}}
|
||||
examples = {"ec2": {"examples": {"DescribeGroups": [
|
||||
{"input": {"GroupIds": ["sg-903004f8", "sg-1a2b3c4d"], "Label": "lb-0123456789abcdef"},
|
||||
"output": {"GroupId": "sg-0a1b2c3d4e5f60718"}},
|
||||
{"input": {"GroupIds": ["xx-12345678"]}}]}}}
|
||||
assert r.id_prefixes({"ec2": ec2}, ("security-group",), examples) == {"security-group": "sg-"}
|
||||
# A String member's id-like value names no type, and without examples nothing is known.
|
||||
assert r.id_prefixes({"ec2": ec2}, ("lb",), examples) == {}
|
||||
assert r.id_prefixes({"ec2": ec2}, ("security-group",)) == {}
|
||||
|
||||
|
||||
def test_id_targets_reject_unknown_types_ambiguous_prefixes_and_malformed_members():
|
||||
import copy
|
||||
|
||||
@@ -1714,3 +1753,119 @@ def test_a_resource_id_variable_takes_a_member_named_so_and_a_bare_id_the_member
|
||||
# A bare `Id` is whatever the operation is about: the tenant's is its `DistributionTenantId`.
|
||||
assert r._filling("Id", "distributiontenant", 1, {"Id": "Id", "DistributionTenantId": "DistributionTenantId"},
|
||||
{"Id"}) == "DistributionTenantId"
|
||||
|
||||
|
||||
def test_vpc_operations_read_vpc_ids_and_stored_tag_keys():
|
||||
ec2 = model({"ModifyVpcAttribute": {"VpcId": "String"}}, "ec2")
|
||||
formats = {"vpc": "arn:${Partition}:ec2:${Region}:${Account}:vpc/${VpcId}"}
|
||||
assert r.entry_for("ec2:ModifyVpcAttribute", {"action": "ec2:ModifyVpcAttribute", "types": ["vpc"]},
|
||||
formats, {"ec2": ec2})["resources"] == [{"type": "vpc", "fill": {"VpcId": "VpcId"}}]
|
||||
assert r.resource_tag_keys([{"Name": "ec2", "Resources": [{"Name": "vpc", "ConditionKeys": [
|
||||
"aws:ResourceTag/${TagKey}", "ec2:ResourceTag/${TagKey}", "ec2:Region"]}]}]) == {
|
||||
"ec2": {"vpc": ["aws:ResourceTag/", "ec2:ResourceTag/"]}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation,kind,variable", [
|
||||
("CreateSubnet", "subnet", "SubnetId"),
|
||||
("CreateRouteTable", "route-table", "RouteTableId"),
|
||||
("CreateSecurityGroup", "security-group", "SecurityGroupId"),
|
||||
("CreateInternetGateway", "internet-gateway", "InternetGatewayId"),
|
||||
])
|
||||
def test_network_creates_authorize_new_resource_and_existing_vpc(operation, kind, variable):
|
||||
has_parent = operation != "CreateInternetGateway"
|
||||
members = {"VpcId": "String"} if has_parent else {}
|
||||
ec2 = model({operation: members}, "ec2")
|
||||
formats = {kind: f"arn:${{Partition}}:ec2:${{Region}}:${{Account}}:{kind}/${{{variable}}}",
|
||||
"vpc": "arn:${Partition}:ec2:${Region}:${Account}:vpc/${VpcId}"}
|
||||
types = [kind, "vpc"] if has_parent else [kind]
|
||||
entry = r.entry_for(f"ec2:{operation}", {"action": f"ec2:{operation}", "types": types},
|
||||
formats, {"ec2": ec2})
|
||||
expected = [{"type": kind, "fill": {}}]
|
||||
if has_parent:
|
||||
expected[0]["made"] = True
|
||||
expected.append({"type": "vpc", "fill": {"VpcId": "VpcId"}})
|
||||
assert entry["resources"] == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("documentation,output_id,input_id,expected", [
|
||||
("<p>Allocates an Elastic IP address to your account.</p>", True, False, True),
|
||||
("Allocates a pool for an Elastic IP address.", True, False, False),
|
||||
("Describes an Elastic IP address.", True, False, False),
|
||||
("Allocates an Elastic IP address.", False, False, False),
|
||||
("Allocates an Elastic IP address.", True, True, False),
|
||||
])
|
||||
def test_documented_creation_requires_direct_object_and_new_response_id(documentation, output_id, input_id, expected):
|
||||
ec2 = model({"AllocateAddress": {"AllocationId": "String"} if input_id else {}}, "ec2")
|
||||
ec2["operations"]["AllocateAddress"].update(documentation=documentation, output={"shape": "Out"})
|
||||
ec2["shapes"]["Out"] = {"type": "structure", "members": {
|
||||
"AllocationId" if output_id else "PublicIp": {"shape": "String"}}}
|
||||
formats = {"elastic-ip": "arn:${Partition}:ec2:${Region}:${Account}:elastic-ip/${AllocationId}"}
|
||||
assert r.with_documented_creation([], "ec2:AllocateAddress", ["elastic-ip"], formats, {"ec2": ec2}) == (
|
||||
[{"type": "elastic-ip", "fill": {}, "made": True}] if expected else [])
|
||||
|
||||
|
||||
def test_ec2_query_names_follow_model_serialization_and_only_read_resource_members():
|
||||
ec2 = model({"CreateNetworkInterface": {"Groups": "Strings", "SubnetId": "String", "Ignored": "Strings"}}, "ec2")
|
||||
group = ec2["shapes"]["CreateNetworkInterfaceIn"]["members"]["Groups"]
|
||||
group["locationName"] = "securityGroupId"
|
||||
assert r.ec2_query_members("ec2:CreateNetworkInterface", {"ec2": ec2}, {"Groups", "SubnetId"}) == {
|
||||
"Groups[]": "SecurityGroupId"}
|
||||
group["queryName"] = "ExactGroupWireName"
|
||||
assert r.ec2_query_members("ec2:CreateNetworkInterface", {"ec2": ec2}, {"Groups"}) == {
|
||||
"Groups[]": "ExactGroupWireName"}
|
||||
ec2["metadata"]["protocol"] = "query"
|
||||
assert r.ec2_query_members("ec2:CreateNetworkInterface", {"ec2": ec2}, {"Groups"}) == {}
|
||||
|
||||
|
||||
def test_a_typed_list_is_the_targets_only_when_the_request_names_nothing_else_the_action_acts_on():
|
||||
ec2 = model({"Launch": {"SecurityGroupIds": "Strings", "ImageId": "String"},
|
||||
"ApplyGroups": {"SecurityGroupIds": "Strings"},
|
||||
"AnnotateResources": {"Resources": "Strings"}}, "ec2")
|
||||
formats = {"security-group": "arn:${Partition}:ec2:${Region}:${Account}:security-group/${SecurityGroupId}",
|
||||
"image": "arn:${Partition}:ec2:${Region}::image/${ImageId}"}
|
||||
known = {"security-group": "sg-"}
|
||||
# A launch's groups sit beside its image: the ordinary rules read both, and the groups are not its targets.
|
||||
launch = r.entry_for("ec2:Launch", {"action": "ec2:Launch", "types": ["image", "security-group"]},
|
||||
formats, {"ec2": ec2}, known)
|
||||
assert "targets" not in launch
|
||||
assert {"type": "image", "fill": {"ImageId": "ImageId"}} in launch["resources"]
|
||||
applied = r.entry_for("ec2:ApplyGroups", {"action": "ec2:ApplyGroups", "types": ["security-group"]},
|
||||
formats, {"ec2": ec2}, known)
|
||||
assert applied["targets"] == {"member": "SecurityGroupIds[]", "query": "SecurityGroupIds",
|
||||
"prefixes": {"security-group": "sg-"}}
|
||||
tags = r.entry_for("ec2:AnnotateResources", {"action": "ec2:AnnotateResources", "types": ["security-group"]},
|
||||
formats, {"ec2": ec2}, known)
|
||||
assert tags["targets"]["prefixes"] == {"security-group": "sg-"}
|
||||
|
||||
|
||||
def test_a_list_inside_a_structure_is_no_member_the_rules_read():
|
||||
ec2 = model({"CreateSnapshots": {"InstanceSpecification": "Specification"}}, "ec2")
|
||||
ec2["shapes"]["Specification"] = {"type": "structure", "members": {
|
||||
"InstanceId": {"shape": "String"}, "ExcludeDataVolumeIds": {"shape": "Strings"}}}
|
||||
found = r.documented_members({"ec2": ec2}, "CreateSnapshots")
|
||||
assert "InstanceSpecification.InstanceId" in found
|
||||
assert "InstanceSpecification.ExcludeDataVolumeIds" not in found
|
||||
|
||||
|
||||
def test_lists_of_several_types_are_read_by_the_ordinary_rules():
|
||||
ec2 = model({"CreateEndpoint": {"RouteTableIds": "Strings", "SecurityGroupIds": "Strings"}}, "ec2")
|
||||
formats = {"route-table": "arn:${Partition}:ec2:${Region}:${Account}:route-table/${RouteTableId}",
|
||||
"security-group": "arn:${Partition}:ec2:${Region}:${Account}:security-group/${SecurityGroupId}"}
|
||||
entry = r.entry_for("ec2:CreateEndpoint", {"action": "ec2:CreateEndpoint", "types": ["route-table", "security-group"]},
|
||||
formats, {"ec2": ec2}, {"route-table": "rtb-", "security-group": "sg-"})
|
||||
assert "targets" not in entry
|
||||
assert {kind for resource in entry["resources"] for kind in r._kinds(resource)} == {"route-table", "security-group"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation,members,kinds", [
|
||||
("AssociateAddress", {"AllocationId": "String", "InstanceId": "String", "NetworkInterfaceId": "String"},
|
||||
["elastic-ip", "instance", "network-interface"]),
|
||||
("ReleaseAddress", {"AllocationId": "String"}, ["elastic-ip"]),
|
||||
])
|
||||
def test_eip_operations_read_scalar_targets_from_models(operation, members, kinds):
|
||||
variables = {"elastic-ip": "AllocationId", "instance": "InstanceId", "network-interface": "NetworkInterfaceId"}
|
||||
formats = {kind: f"arn:${{Partition}}:ec2:${{Region}}:${{Account}}:{kind}/${{{variables[kind]}}}" for kind in kinds}
|
||||
ec2 = model({operation: members}, "ec2")
|
||||
action = "ec2:" + operation
|
||||
entry = r.entry_for(action, {"action": action, "types": kinds}, formats, {"ec2": ec2})
|
||||
assert entry["resources"] == [{"type": kind, "fill": {variables[kind]: variables[kind]}} for kind in kinds]
|
||||
Reference in new issue
Block a user