fix(ec2): resolve interface identity for tag authorization (#8352)

* fix(ec2): resolve interface identity for tag authorization
* fix(ec2): read resource condition keys through the generated table
* fix(ec2): look up a tag batch's interfaces in one pass
This commit is contained in:
luiseterc authored and GitHub committed 2026-11-14 18:42:23 -04:00
1 parent 4de81e8370
commit 16745c3804
13 files changed
+542 -25

No files matched your search

+9
View File
@@ -2,6 +2,15 @@
**Protocol:** EC2 Query (XML) — `POST http://localhost:4566/` with `Action=` parameter
A request acting on a network interface carries its `ec2:Vpc` and `ec2:Subnet` (as ARNs),
`ec2:AvailabilityZone` and `ec2:NetworkInterfaceID`, read from the interface Floci holds:
stored, held by an instance as its primary interface, or owned by a VPC endpoint, NAT
gateway or Instance Connect endpoint. Which keys a resource type takes, and the member of
its botocore shape each comes from, are generated from the Service Reference and botocore
(`resourceKeys` in `iam-request-resources.json`). In a `CreateTags` or `DeleteTags` batch
every interface is checked against its own keys and tags before any tag changes; another
interface's VPC or tags cannot authorize it. Authorization reads do not create default resources.
## Instance IAM authorization
With IAM enforcement enabled, modeled instance-list operations, including `StartInstances`, `StopInstances`, `TerminateInstances`, and `RebootInstances`, authorize each requested instance ARN before changing any instance state.
+7
View File
@@ -3009,6 +3009,13 @@ floci populates:
`logs:CreateLogStream`, `logs:DeleteLogStream`, `logs:TagResource`, `logs:UntagResource`,
`logs:ListTagsForResource`, `logs:DeleteLogGroup`, `logs:PutRetentionPolicy` and
`logs:DeleteRetentionPolicy` use the owning log group's tags.
- EC2 resource keys such as a network interface's `ec2:Vpc`, `ec2:Subnet`, `ec2:AvailabilityZone` and
`ec2:NetworkInterfaceID`: for every action on a resource EC2 holds, the members of the resource the
key names, an ARN for a key the Service Reference types as one. `resourceKeys` in
`iam-request-resources.json` gives each type's keys and members, generated from the Service Reference
and botocore by `tools/aws/regen_iam_request_resources.py`; network interfaces are read so far, and a
key of a type EC2 does not yet answer for stays absent. A batch is evaluated once per resource, each
with its own keys.
- `s3:ExistingObjectTag/<key>`: the tags already on the target object version, for
`s3:GetObject`, `s3:GetObjectTagging`, `s3:GetObjectAcl`, `s3:PutObjectAcl`,
`s3:DeleteObjectTagging`, `s3:PutObjectTagging` and the annotation actions, and for their
@@ -1,6 +1,7 @@
package io.floci.aws.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsCrossAccountService;
@@ -70,10 +71,14 @@ import java.util.function.Function;
public class IamConditionContextResolver {
private static final Logger LOG = Logger.getLogger(IamConditionContextResolver.class);
/** Reads a resource EC2 holds as its fields, java.time ones included. */
private static final ObjectMapper RESOURCE_MAPPER = new ObjectMapper().findAndRegisterModules();
/** Set by {@code ResourceArnBuilder.readJsonBody}, which runs earlier in the same filter pass. */
static final String BUFFERED_JSON_BODY = "floci.bufferedJsonBody";
private static final String BUFFERED_FORM_BODY = "floci.bufferedFormBody";
/** Prefixes the action whose numbered EC2 targets {@link #heldTargets} looked up for the request. */
private static final String HELD_TARGETS = "floci.heldTargets.";
private static final String REQUEST_TAG_PREFIX = "aws:RequestTag/";
private static final String RESOURCE_TAG_PREFIX = "aws:ResourceTag/";
/**
@@ -105,6 +110,7 @@ public class IamConditionContextResolver {
private final Instance<LambdaWebService> lambdaWebService;
private final Instance<RequestConditionSpelling> requestConditionSpellings;
private final RequestContext requestContext;
private final RegionResolver regionResolver;
private final EmulatorConfig config;
private final CurrentVertxRequest currentVertxRequest;
private final Clock clock;
@@ -124,11 +130,12 @@ public class IamConditionContextResolver {
Instance<LambdaWebService> lambdaWebService,
Instance<RequestConditionSpelling> requestConditionSpellings,
RequestContext requestContext,
RegionResolver regionResolver,
EmulatorConfig config,
CurrentVertxRequest currentVertxRequest,
ResolvedServiceCatalog serviceCatalog) {
this(dynamoDbFacade, ec2Service, s3Service, logsService, crossAccountService, iamService,
lambdaWebService, requestConditionSpellings, requestContext,
lambdaWebService, requestConditionSpellings, requestContext, regionResolver,
config, currentVertxRequest, serviceCatalog, Clock.systemUTC());
}
@@ -141,6 +148,7 @@ public class IamConditionContextResolver {
Instance<LambdaWebService> lambdaWebService,
Instance<RequestConditionSpelling> requestConditionSpellings,
RequestContext requestContext,
RegionResolver regionResolver,
EmulatorConfig config,
CurrentVertxRequest currentVertxRequest,
ResolvedServiceCatalog serviceCatalog, Clock clock) {
@@ -153,6 +161,7 @@ public class IamConditionContextResolver {
this.lambdaWebService = lambdaWebService;
this.requestConditionSpellings = requestConditionSpellings;
this.requestContext = requestContext;
this.regionResolver = regionResolver;
this.config = config;
this.currentVertxRequest = currentVertxRequest;
this.clock = clock;
@@ -838,6 +847,8 @@ public class IamConditionContextResolver {
}
if (targets != null) {
addResourceTags(conditions, form.get(targets.query() + ".1"), targets);
addResourceKeys(conditions, form.get(targets.query() + ".1"), targets,
heldTargets(action, ctx, form, targets));
}
return conditions.isEmpty() ? null : conditions;
}
@@ -892,17 +903,50 @@ public class IamConditionContextResolver {
// The handlers read numbered members from 1 up to the first gap, and so does this.
return targets;
}
Map<String, Object> held = heldTargets(action, ctx, form, generatedTargets);
for (int i = 2; form.containsKey(idParameter + i); i++) {
Map<String, List<String>> conditions = new LinkedHashMap<>();
if ("ec2:CreateTags".equals(action)) {
addRequestTags(conditions, form, "Tag.");
}
addResourceTags(conditions, form.get(idParameter + i), generatedTargets);
addResourceKeys(conditions, form.get(idParameter + i), generatedTargets, held);
targets.add(conditions);
}
return targets;
}
/**
* What EC2 holds under each numbered target of an {@code action} request whose type has generated resource keys,
* keyed by id. The targets are looked up together, once per request and action, so the first target's context
* and the remaining targets' contexts share a single pass over EC2's stores however many the request names.
*/
private Map<String, Object> heldTargets(String action, ContainerRequestContext ctx, Map<String, String> form,
RequestResourceMembers.Targets targets) {
String property = HELD_TARGETS + action;
if (ctx.getProperty(property) instanceof HeldTargets cached) {
return cached.byId();
}
Map<String, Object> held = new LinkedHashMap<>();
if (ec2Service.isResolvable()) {
Map<String, Set<String>> idsByType = new LinkedHashMap<>();
for (int i = 1; form.containsKey(targets.query() + "." + i); i++) {
String id = form.get(targets.query() + "." + i);
String type = targetType(id, targets);
if (type != null && !ec2ResourceKeys(type).isEmpty()) {
idsByType.computeIfAbsent(type, ignored -> new LinkedHashSet<>()).add(id);
}
}
idsByType.forEach((type, ids) -> held.putAll(ec2Service.get().heldResources(requestRegion(), type, ids)));
}
ctx.setProperty(property, new HeldTargets(held));
return held;
}
/** The resources {@link #heldTargets} found for a request, kept on it under the action they were read for. */
private record HeldTargets(Map<String, Object> byId) {
}
private static void addRequestTags(Map<String, List<String>> conditions, Map<String, String> form,
String prefix) {
for (int i = 1; form.containsKey(prefix + i + ".Key"); i++) {
@@ -917,10 +961,13 @@ 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) {
/**
* The stored tags and the generated resource keys of one generated EC2 ARN (see {@link #putResourceKeys}), never
* borrowed from another target in the same request.
*/
public Map<String, List<String>> withEc2ResourceContext(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;
@@ -935,12 +982,17 @@ public class IamConditionContextResolver {
}
List<String> prefixes = RequestResourceMembers.table().resourceTagKeys()
.getOrDefault("ec2", Map.of()).getOrDefault(parts[0], List.of());
if (prefixes.isEmpty()) {
Map<String, RequestResourceMembers.ResourceKey> keys = ec2ResourceKeys(parts[0]);
if (prefixes.isEmpty() && keys.isEmpty()) {
return context;
}
Map<String, List<String>> result = context == null ? new LinkedHashMap<>() : new LinkedHashMap<>(context);
result.keySet().removeIf(key -> prefixes.stream().anyMatch(key::startsWith));
result.keySet().removeIf(key -> prefixes.stream().anyMatch(key::startsWith) || keys.containsKey(key));
putStoredTags(result, region, parts[1], prefixes);
if (!keys.isEmpty()) {
putResourceKeys(result, region, parts[0],
ec2Service.get().heldResources(region, parts[0], List.of(parts[1])).get(parts[1]));
}
return result;
}
@@ -949,16 +1001,80 @@ public class IamConditionContextResolver {
if (resourceId == null || resourceId.isBlank() || !ec2Service.isResolvable()) {
return;
}
String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion();
List<String> prefixes = List.of(RESOURCE_TAG_PREFIX);
String type = targetType(resourceId, targets);
List<String> prefixes = type == null ? List.of(RESOURCE_TAG_PREFIX)
: RequestResourceMembers.table().resourceTagKeys().getOrDefault("ec2", Map.of())
.getOrDefault(type, List.of());
putStoredTags(conditions, requestRegion(), resourceId, prefixes);
}
/**
* The generated resource keys of the type whose id prefix {@code resourceId} carries, from what {@code held} says
* EC2 holds under it (see {@link #putResourceKeys}).
*/
private void addResourceKeys(Map<String, List<String>> conditions, String resourceId,
RequestResourceMembers.Targets targets, Map<String, Object> held) {
String type = targetType(resourceId, targets);
if (type != null) {
putResourceKeys(conditions, requestRegion(), type, held.get(resourceId));
}
}
/** The generated EC2 resource type whose id prefix {@code resourceId} carries, or null when none does. */
private static String targetType(String resourceId, RequestResourceMembers.Targets targets) {
if (resourceId == null || resourceId.isBlank()) {
return null;
}
for (Map.Entry<String, String> type : targets.prefixes().entrySet()) {
if (resourceId.startsWith(type.getValue())) {
prefixes = RequestResourceMembers.table().resourceTagKeys()
.getOrDefault("ec2", Map.of()).getOrDefault(type.getKey(), List.of());
break;
return type.getKey();
}
}
putStoredTags(conditions, region, resourceId, prefixes);
return null;
}
/** The condition keys the request-resources table reads from a member of EC2's resource {@code type}. */
private static Map<String, RequestResourceMembers.ResourceKey> ec2ResourceKeys(String type) {
return RequestResourceMembers.table().resourceKeys().getOrDefault("ec2", Map.of())
.getOrDefault(type, Map.of());
}
private String requestRegion() {
return requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion();
}
/**
* Each condition key the request-resources table gives EC2's resource {@code type} as a member of its botocore
* shape, valued from that member of {@code held}, the resource EC2 holds under the target's id, as the ARN of the
* key's type where the Service Reference types the key as one. A member with no value, or no resource held,
* leaves the key absent.
*/
private void putResourceKeys(Map<String, List<String>> conditions, String region, String type, Object held) {
Map<String, RequestResourceMembers.ResourceKey> keys = ec2ResourceKeys(type);
if (keys.isEmpty() || held == null) {
return;
}
JsonNode resource = RESOURCE_MAPPER.valueToTree(held);
String account = requestContext.getAccountId();
String partition = regionResolver.partitionForRegion(region);
keys.forEach((key, spec) -> {
String value = memberValue(resource, spec.member());
if (value != null && !value.isBlank()) {
conditions.put(key, List.of(spec.arn() == null ? value
: RequestResources.idArn("ec2", spec.arn(), value, partition, region, account)));
}
});
}
/** The scalar the resource holds in the botocore member {@code member}, its field of that name, case aside. */
private static String memberValue(JsonNode resource, String member) {
for (Map.Entry<String, JsonNode> field : resource.properties()) {
if (field.getKey().equalsIgnoreCase(member) && field.getValue().isValueNode()
&& !field.getValue().isNull()) {
return field.getValue().asText();
}
}
return null;
}
private void putStoredTags(Map<String, List<String>> conditions, String region, String resourceId,
@@ -1340,7 +1340,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
Map<String, List<String>> taggedContext = targetContext;
if ("ec2".equals(credentialScope) && !RequestResources.hasIndividualTargets(operationAction)
&& AwsArnUtils.isArn(resource)) {
taggedContext = conditionContextResolver.withEc2ResourceTags(
taggedContext = conditionContextResolver.withEc2ResourceContext(
credentialScope, operationAction, resource, region, accountId, targetContext);
}
Map<String, List<String>> effectiveContext = IamConditionContextResolver.withGlobalContext(
@@ -265,6 +265,14 @@ final class RequestResourceMembers {
record Targets(Member member, String query, Map<String, String> prefixes) {
}
/**
* A condition key of a resource type that a member of the type's botocore shape names ({@code ec2:Vpc}, a
* network interface's {@code VpcId}): its value is that member of the resource its service holds, as the ARN of
* the namespace's type {@code arn} where the Service Reference types the key as an ARN, as given otherwise.
*/
record ResourceKey(String member, String arn) {
}
/**
* A request an operation's service makes to another service as the caller: {@code action}, on that service's
* resource of {@code type} which the record of the operation's resource of type {@code of} holds in
@@ -290,6 +298,7 @@ final class RequestResourceMembers {
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,
Map<String, Map<String, Map<String, ResourceKey>>> resourceKeys,
Set<String> namespaces, Set<String> handBuilt, Set<String> notCovered, Set<String> otherNamespaces,
Map<String, List<Forwarded>> forwarded) {
}
@@ -372,6 +381,7 @@ final class RequestResourceMembers {
});
resourceTagKeys.put(namespace.getKey(), Map.copyOf(types));
});
Map<String, Map<String, Map<String, ResourceKey>>> resourceKeys = resourceKeys(document, formats);
Map<String, List<Resource>> entries = new LinkedHashMap<>();
Map<String, List<String>> actsOn = new LinkedHashMap<>();
Map<String, List<Created>> creates = new LinkedHashMap<>();
@@ -477,12 +487,44 @@ final class RequestResourceMembers {
});
return new Table(Map.copyOf(entries), Map.copyOf(actsOn), Map.copyOf(creates), Map.copyOf(makes),
Map.copyOf(targets), Map.copyOf(ec2Query), Map.copyOf(located), Map.copyOf(formats),
Map.copyOf(resourceTagKeys), namespaces,
Map.copyOf(resourceTagKeys), resourceKeys, namespaces,
names(document.path("handBuilt")),
Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
names(document.path("otherNamespaces")), Map.copyOf(forwarded));
}
/** Each resource type's member-named condition keys, by namespace, refusing a type or ARN type with no format. */
private static Map<String, Map<String, Map<String, ResourceKey>>> resourceKeys(
JsonNode document, Map<String, Map<String, ArnFormat>> formats) {
JsonNode section = document.path("resourceKeys");
if (!section.isMissingNode() && !section.isObject()) {
throw new IllegalStateException(RESOURCE_NAME + " has malformed resource keys");
}
Map<String, Map<String, Map<String, ResourceKey>>> result = new LinkedHashMap<>();
section.properties().forEach(namespace -> {
Map<String, ArnFormat> known = formats.getOrDefault(namespace.getKey(), Map.of());
Map<String, Map<String, ResourceKey>> types = new LinkedHashMap<>();
namespace.getValue().properties().forEach(type -> {
if (!known.containsKey(type.getKey()) || !type.getValue().isObject()) {
throw new IllegalStateException(RESOURCE_NAME + " has malformed resource keys");
}
Map<String, ResourceKey> keys = new LinkedHashMap<>();
type.getValue().properties().forEach(key -> {
String member = key.getValue().path("member").asText("");
JsonNode arn = key.getValue().path("arn");
if (!key.getKey().startsWith(namespace.getKey() + ":") || member.isEmpty()
|| !arn.isMissingNode() && !known.containsKey(arn.asText(""))) {
throw new IllegalStateException(RESOURCE_NAME + " has malformed resource keys");
}
keys.put(key.getKey(), new ResourceKey(member, arn.isMissingNode() ? null : arn.asText()));
});
types.put(type.getKey(), Map.copyOf(keys));
});
result.put(namespace.getKey(), Map.copyOf(types));
});
return Map.copyOf(result);
}
/**
* A request the operation's service makes to another as the caller, joined with what the file records of its
* action: the type it acts on and the {@code ViaService} key of its namespace, if any.
@@ -225,11 +225,7 @@ public final class RequestResources {
String arn = "*";
for (Map.Entry<String, String> prefix : targets.prefixes().entrySet()) {
if (id.startsWith(prefix.getValue())) {
String format = formats.get(prefix.getKey()).format();
Map<String, String> filling = new HashMap<>();
VARIABLE.matcher(format).results().map(match -> match.group(1))
.forEach(variable -> filling.put(variable, id));
arn = render(format, filling, partition, region, accountId);
arn = idArn(formats.get(prefix.getKey()).format(), id, partition, region, accountId);
break;
}
}
@@ -850,6 +846,21 @@ public final class RequestResources {
}
/** The format with each variable replaced once: the partition, Region and account, a value, or else {@code *}. */
/**
* The ARN of the namespace's resource of {@code type} named by {@code id}, the one variable of its format past
* partition, Region and account, as a request naming the resource by its id gives it.
*/
static String idArn(String namespace, String type, String id, String partition, String region, String accountId) {
return idArn(RequestResourceMembers.table().formats().get(namespace).get(type).format(), id, partition, region,
accountId);
}
private static String idArn(String format, String id, String partition, String region, String accountId) {
Map<String, String> filling = new HashMap<>();
VARIABLE.matcher(format).results().map(match -> match.group(1)).forEach(variable -> filling.put(variable, id));
return render(format, filling, partition, region, accountId);
}
private static String render(String format, Map<String, String> filling, String partition, String region,
String accountId) {
Matcher variable = VARIABLE.matcher(format);
@@ -15636,6 +15636,37 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
List<String> networkInterfaceIds,
List<Map.Entry<String, List<String>>> filters,
int maxResults, String nextToken) {
return describeNetworkInterfaces(accountId, region, networkInterfaceIds, filters, maxResults, nextToken, true);
}
/**
* The resources of {@code type} EC2 holds for the caller under {@code ids}, keyed by id, as its Describe operation
* answers them, which the IAM condition keys the request-resources table reads from a resource's members are
* valued from: a network interface of any kind, stored, held by an instance or owned by an endpoint or a NAT
* gateway. All of them come from one pass over the stores, so a request naming many costs no more lookups than one
* naming a single resource. Empty for a type it does not answer for. An id it holds nothing under is absent, and
* the request fails on it. Reads only: it creates no default resources.
*/
public Map<String, Object> heldResources(String region, String type, Collection<String> ids) {
if (!"network-interface".equals(type) || ids.isEmpty()) {
return Map.of();
}
// The id filter rather than the id list: a filter leaves out what it does not match, where an id the store
// lacks would fail the whole lookup with InvalidNetworkInterfaceID.NotFound.
Map<String, Object> held = new HashMap<>();
describeNetworkInterfaces(callerAccountId(), region, List.of(),
List.of(Map.entry("network-interface-id", List.copyOf(ids))), 0, null, false)
.networkInterfaces().stream()
.filter(ni -> ids.contains(ni.getNetworkInterfaceId()))
.forEach(ni -> held.put(ni.getNetworkInterfaceId(), ni));
return held;
}
private NetworkInterfaceListResult describeNetworkInterfaces(String accountId, String region,
List<String> networkInterfaceIds,
List<Map.Entry<String, List<String>>> filters,
int maxResults, String nextToken,
boolean createDefaults) {
// Validate pagination parameters
if (maxResults > 0 && !networkInterfaceIds.isEmpty()) {
throw new AwsException("InvalidParameterCombination",
@@ -15656,7 +15687,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
ensureDefaultResources(region);
if (createDefaults) {
ensureDefaultResources(region);
}
String safeAccount = accountId != null ? accountId : callerAccountId();
List<NetworkInterface> result = new ArrayList<>();
Set<String> foundIds = new HashSet<>();
@@ -6,6 +6,7 @@
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-gateway", "backup-search", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "end-user-messaging", "entityresolution", "evs", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "outposts", "panorama", "partnercentral", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "ssmmessages", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web"],
"arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "account": {"account": "arn:${Partition}:account::${Account}:account", "accountInOrganization": "arn:${Partition}:account::${ManagementAccountId}:account/o-${OrganizationId}/${MemberAccountId}"}, "acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "system-table": "arn:${Partition}:athena:${Region}:${Account}:system-table/${TableName}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudfront": {"anycast-ip-list": "arn:${Partition}:cloudfront::${Account}:anycast-ip-list/${Id}", "cache-policy": "arn:${Partition}:cloudfront::${Account}:cache-policy/${Id}", "connection-function": "arn:${Partition}:cloudfront::${Account}:connection-function/${Id}", "connection-group": "arn:${Partition}:cloudfront::${Account}:connection-group/${Id}", "continuous-deployment-policy": "arn:${Partition}:cloudfront::${Account}:continuous-deployment-policy/${Id}", "distribution": "arn:${Partition}:cloudfront::${Account}:distribution/${DistributionId}", "distribution-tenant": "arn:${Partition}:cloudfront::${Account}:distribution-tenant/${Id}", "field-level-encryption-config": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-config/${Id}", "field-level-encryption-profile": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-profile/${Id}", "function": "arn:${Partition}:cloudfront::${Account}:function/${Name}", "key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${Name}", "origin-access-control": "arn:${Partition}:cloudfront::${Account}:origin-access-control/${Id}", "origin-access-identity": "arn:${Partition}:cloudfront::${Account}:origin-access-identity/${Id}", "origin-request-policy": "arn:${Partition}:cloudfront::${Account}:origin-request-policy/${Id}", "realtime-log-config": "arn:${Partition}:cloudfront::${Account}:realtime-log-config/${Name}", "response-headers-policy": "arn:${Partition}:cloudfront::${Account}:response-headers-policy/${Id}", "streaming-distribution": "arn:${Partition}:cloudfront::${Account}:streaming-distribution/${DistributionId}", "trust-store": "arn:${Partition}:cloudfront::${Account}:trust-store/${Id}", "vpcorigin": "arn:${Partition}:cloudfront::${Account}:vpcorigin/${Id}"}, "cloudfront-keyvaluestore": {"key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${ResourceId}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Line truncated
"resourceTagKeys": {"ec2": {"application-status-check": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-block": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-manager-data-export": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-cancellation-quote": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-fleet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-modification-quote": ["aws:ResourceTag/", "ec2:ResourceTag/"], "carrier-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "client-vpn-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "coip-pool": ["aws:ResourceTag/", "ec2:ResourceTag/"], "customer-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "declarative-policies-report": ["aws:ResourceTag/", "ec2:ResourceTag/"], "dedicated-host": ["aws:ResourceTag/", "ec2:ResourceTag/"], "dhcp-options": ["aws:ResourceTag/", "ec2:ResourceTag/"], "egress-only-internet-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "elastic-gpu": ["aws:ResourceTag/", "ec2:ResourceTag/"], "elastic-ip": ["aws:ResourceTag/", "ec2:ResourceTag/"], "export-image-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "export-instance-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "fleet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "fpga-image": ["aws:ResourceTag/", "ec2:ResourceTag/"], "host-reservation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "image": ["aws:ResourceTag/", "ec2:ResourceTag/"], "image-usage-report": ["aws:ResourceTag/", "ec2:ResourceTag/"], "import-image-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "import-snapshot-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance-connect-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance-event-window": ["aws:ResourceTag/", "ec2:ResourceTag/"], "internet-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-external-resource-verification-token": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-internet-registry-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-policy": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-pool": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-pool-allocation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-prefix-list-resolver": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-prefix-list-resolver-target": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-resource-discovery": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-resource-discovery-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-scope": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipv4pool-ec2": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipv6pool-ec2": ["aws:ResourceTag/", "ec2:ResourceTag/"], "key-pair": ["aws:ResourceTag/", "ec2:ResourceTag/"], "launch-template": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-route-table": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-route-table-virtual-interface-group-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-route-table-vpc-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-virtual-interface": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-virtual-interface-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "mac-modification-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "natgateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-acl": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-access-scope": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-access-scope-analysis": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-analysis": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-path": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-interface": ["aws:ResourceTag/", "ec2:ResourceTag/"], "outpost-lag": ["aws:ResourceTag/", "ec2:ResourceTag/"], "placement-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "prefix-list": ["aws:ResourceTag/", "ec2:ResourceTag/"], "replace-root-volume-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "reserved-instances": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-server": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-server-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-server-peer": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-table": ["aws:ResourceTag/", "ec2:ResourceTag/"], "secondary-interface": ["aws:ResourceTag/", "ec2:ResourceTag/"], "secondary-network": ["aws:ResourceTag/", "ec2:ResourceTag/"], "secondary-subnet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "security-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "security-group-rule": ["aws:ResourceTag/", "ec2:ResourceTag/"], "snapshot": ["aws:ResourceTag/", "ec2:ResourceTag/"], "spot-fleet-request": ["aws:ResourceTag/", "ec2:ResourceTag/"], "spot-instances-request": ["aws:ResourceTag/", "Line truncated
"resourceKeys": {"ec2": {"capacity-reservation": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}, "ec2:CapacityReservationFleet": {"member": "CapacityReservationFleetId", "arn": "capacity-reservation-fleet"}, "ec2:EbsOptimized": {"member": "EbsOptimized"}, "ec2:EndDateType": {"member": "EndDateType"}, "ec2:EphemeralStorage": {"member": "EphemeralStorage"}, "ec2:InstanceMatchCriteria": {"member": "InstanceMatchCriteria"}, "ec2:InstanceType": {"member": "InstanceType"}, "ec2:Tenancy": {"member": "Tenancy"}}, "carrier-gateway": {"ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "dhcp-options": {"ec2:DhcpOptionsID": {"member": "DhcpOptionsId"}}, "fpga-image": {"ec2:Owner": {"member": "OwnerId"}, "ec2:Public": {"member": "Public"}}, "image": {"ec2:ImageID": {"member": "ImageId"}, "ec2:ImageType": {"member": "ImageType"}, "ec2:Owner": {"member": "OwnerId"}, "ec2:Public": {"member": "Public"}, "ec2:RootDeviceType": {"member": "RootDeviceType"}}, "instance": {"ec2:EbsOptimized": {"member": "EbsOptimized"}, "ec2:InstanceID": {"member": "InstanceId"}, "ec2:InstanceType": {"member": "InstanceType"}, "ec2:RootDeviceType": {"member": "RootDeviceType"}}, "internet-gateway": {"ec2:InternetGatewayID": {"member": "InternetGatewayId"}}, "launch-template": {"ec2:LaunchTemplate": {"member": "LaunchTemplateId", "arn": "launch-template"}}, "network-acl": {"ec2:NetworkAclID": {"member": "NetworkAclId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "network-interface": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:NetworkInterfaceID": {"member": "NetworkInterfaceId"}, "ec2:Subnet": {"member": "SubnetId", "arn": "subnet"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "reserved-instances": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:InstanceType": {"member": "InstanceType"}}, "route-table": {"ec2:RouteTableID": {"member": "RouteTableId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "secondary-interface": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}}, "security-group": {"ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "snapshot": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:Encrypted": {"member": "Encrypted"}, "ec2:Owner": {"member": "OwnerId"}, "ec2:SnapshotID": {"member": "SnapshotId"}, "ec2:VolumeSize": {"member": "VolumeSize"}}, "subnet": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}, "ec2:SubnetID": {"member": "SubnetId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "transit-gateway": {"ec2:transitGatewayId": {"member": "TransitGatewayId"}}, "transit-gateway-attachment": {"ec2:transitGatewayAttachmentId": {"member": "TransitGatewayAttachmentId"}}, "transit-gateway-connect-peer": {"ec2:transitGatewayConnectPeerId": {"member": "TransitGatewayConnectPeerId"}}, "transit-gateway-metering-policy": {"ec2:transitGatewayMeteringPolicyId": {"member": "TransitGatewayMeteringPolicyId"}}, "transit-gateway-multicast-domain": {"ec2:transitGatewayMulticastDomainId": {"member": "TransitGatewayMulticastDomainId"}}, "transit-gateway-policy-table": {"ec2:transitGatewayPolicyTableId": {"member": "TransitGatewayPolicyTableId"}}, "transit-gateway-route-table": {"ec2:transitGatewayRouteTableId": {"member": "TransitGatewayRouteTableId"}}, "transit-gateway-route-table-announcement": {"ec2:transitGatewayRouteTableAnnouncementId": {"member": "TransitGatewayRouteTableAnnouncementId"}}, "volume": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}, "ec2:Encrypted": {"member": "Encrypted"}, "ec2:KmsKeyId": {"member": "KmsKeyId"}, "ec2:VolumeID": {"member": "VolumeId"}, "ec2:VolumeInitializationRate": {"member": "VolumeInitializationRate"}, "ec2:VolumeType": {"member": "VolumeType"}}, "vpc": {"ec2:VpcID": {"member": "VpcId"}}, "vpc-peering-connection": {"ec2:VpcPeeringConnectionID": {"member": "VpcPeeringConnectionId"}}}},
"unqualified": {"lambda": ["function"], "ssm": ["parameter"], "states": ["statemachine"]},
"mintedIds": {"events": ["api-destination", "connection"]},
"integerVariables": {"lambda": {"layerVersion": ["LayerVersion"]}},
@@ -0,0 +1,160 @@
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.Ec2Exception;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class Ec2InterfaceTagContextIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@ParameterizedTest
@CsvSource({"us-east-1,aws", "us-gov-west-1,aws-us-gov", "cn-north-1,aws-cn"})
void interfaceTaggingUsesEachTargetsVpc(String region, String partition) {
String user = "eni-context-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", region, "iam"), user);
String arn = "arn:" + partition + ":ec2:" + region + ":000000000000:";
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.of(region), endpoint);
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.of(region), endpoint)) {
String vpc = admin.createVpc(r -> r.cidrBlock("10.205.0.0/16")).vpc().vpcId();
String foreignVpc = admin.createVpc(r -> r.cidrBlock("10.206.0.0/16")).vpc().vpcId();
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.205.1.0/24")).subnet().subnetId();
String foreignSubnet = admin.createSubnet(r -> r.vpcId(foreignVpc).cidrBlock("10.206.1.0/24"))
.subnet().subnetId();
String eni = admin.createNetworkInterface(r -> r.subnetId(subnet).tagSpecifications(t -> t
.resourceType("network-interface").tags(tag -> tag.key("Owner").value("lab"))))
.networkInterface().networkInterfaceId();
String foreign = admin.createNetworkInterface(r -> r.subnetId(foreignSubnet).tagSpecifications(t -> t
.resourceType("network-interface").tags(tag -> tag.key("Owner").value("lab"))))
.networkInterface().networkInterfaceId();
String policy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["ec2:CreateTags","ec2:DeleteTags"],"Resource":"%snetwork-interface/*",
"Condition":{"ArnEquals":{"ec2:Vpc":"%svpc/%s"},
"StringEquals":{"aws:ResourceTag/Owner":"lab"}}}]}
""".formatted(arn, arn, vpc);
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", region, "iam"),
user, "tag-vpc", policy);
try {
client.createTags(r -> r.resources(eni).tags(t -> t.key("Runtime").value("cni")));
assertEquals("cni", runtimeTag(admin, eni));
assertEquals("UnauthorizedOperation", assertThrows(Ec2Exception.class, () -> client.createTags(r -> r
.resources(eni, foreign).tags(t -> t.key("Runtime").value("changed"))))
.awsErrorDetails().errorCode());
assertEquals("cni", runtimeTag(admin, eni));
assertEquals("UnauthorizedOperation", assertThrows(Ec2Exception.class, () -> client.deleteTags(r -> r
.resources(eni, foreign).tags(t -> t.key("Runtime")))).awsErrorDetails().errorCode());
assertEquals("cni", runtimeTag(admin, eni));
client.deleteTags(r -> r.resources(eni).tags(t -> t.key("Runtime")));
assertEquals("", runtimeTag(admin, eni));
String narrow = policy.replace("\"ec2:Vpc\":\"" + arn + "vpc/" + vpc + "\"",
"\"ec2:Vpc\":\"" + arn + "vpc/" + vpc + "\",\"ec2:Subnet\":\"" + arn
+ "subnet/" + subnet + "\"");
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", region, "iam"),
user, "tag-vpc", narrow.replace("subnet/" + subnet, "subnet/" + foreignSubnet));
assertEquals("UnauthorizedOperation", assertThrows(Ec2Exception.class, () -> client.createTags(r -> r
.resources(eni).tags(t -> t.key("Runtime").value("cni")))).awsErrorDetails().errorCode());
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", region, "iam"),
user, "tag-vpc", narrow);
String instanceId = admin.runInstances(r -> r.imageId("ami-0abcdef1234567891").instanceType("t3.micro")
.subnetId(subnet).minCount(1).maxCount(1).tagSpecifications(t -> t.resourceType("network-interface")
.tags(tag -> tag.key("Owner").value("lab")))).instances().getFirst().instanceId();
try {
String primary = admin.describeInstances(r -> r.instanceIds(instanceId)).reservations().getFirst()
.instances().getFirst().networkInterfaces().getFirst().networkInterfaceId();
client.createTags(r -> r.resources(primary).tags(t -> t.key("Runtime").value("cni")));
assertEquals("cni", runtimeTag(admin, primary));
client.deleteTags(r -> r.resources(primary).tags(t -> t.key("Runtime")));
} finally {
admin.terminateInstances(r -> r.instanceIds(instanceId));
}
admin.createTags(r -> r.resources(eni).tags(t -> t.key("Owner").value("other")));
assertEquals("UnauthorizedOperation", assertThrows(Ec2Exception.class, () -> client.createTags(r -> r
.resources(eni).tags(t -> t.key("Runtime").value("cni")))).awsErrorDetails().errorCode());
} finally {
admin.deleteNetworkInterface(r -> r.networkInterfaceId(eni));
admin.deleteNetworkInterface(r -> r.networkInterfaceId(foreign));
admin.deleteSubnet(r -> r.subnetId(subnet));
admin.deleteSubnet(r -> r.subnetId(foreignSubnet));
admin.deleteVpc(r -> r.vpcId(vpc));
admin.deleteVpc(r -> r.vpcId(foreignVpc));
}
}
}
/**
* The interface's keys come from the request-resources table for every action on it, not only tagging: a delete
* is refused outside the granted VPC. A NAT gateway's interface, which Floci builds rather than stores, carries
* its VPC too.
*/
@Test
void everyInterfaceActionAndManagedInterfaceCarryTheirVpc() {
String region = "us-east-1";
String user = "eni-actions-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", region, "iam"), user);
String arn = "arn:aws:ec2:" + region + ":000000000000:";
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "000000000000", Region.of(region), endpoint);
Ec2Client client = AwsTestClients.create(Ec2Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.of(region), endpoint)) {
String vpc = admin.createVpc(r -> r.cidrBlock("10.207.0.0/16")).vpc().vpcId();
String foreignVpc = admin.createVpc(r -> r.cidrBlock("10.208.0.0/16")).vpc().vpcId();
String subnet = admin.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.207.1.0/24")).subnet().subnetId();
String foreignSubnet = admin.createSubnet(r -> r.vpcId(foreignVpc).cidrBlock("10.208.1.0/24"))
.subnet().subnetId();
String eni = admin.createNetworkInterface(r -> r.subnetId(subnet)).networkInterface().networkInterfaceId();
String foreign = admin.createNetworkInterface(r -> r.subnetId(foreignSubnet))
.networkInterface().networkInterfaceId();
String natGateway = admin.createNatGateway(r -> r.subnetId(subnet).connectivityType("private"))
.natGateway().natGatewayId();
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", region, "iam"), user, "vpc", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["ec2:DeleteNetworkInterface","ec2:CreateTags"],"Resource":"%snetwork-interface/*",
"Condition":{"ArnEquals":{"ec2:Vpc":"%svpc/%s"}}}]}
""".formatted(arn, arn, vpc));
try {
String managed = admin.describeNatGateways(r -> r.natGatewayIds(natGateway)).natGateways().getFirst()
.natGatewayAddresses().getFirst().networkInterfaceId();
client.createTags(r -> r.resources(managed).tags(t -> t.key("Runtime").value("nat")));
assertEquals("nat", runtimeTag(admin, managed));
assertEquals("UnauthorizedOperation", assertThrows(Ec2Exception.class,
() -> client.deleteNetworkInterface(r -> r.networkInterfaceId(foreign)))
.awsErrorDetails().errorCode());
client.deleteNetworkInterface(r -> r.networkInterfaceId(eni));
} finally {
admin.deleteNatGateway(r -> r.natGatewayId(natGateway));
admin.deleteNetworkInterface(r -> r.networkInterfaceId(foreign));
}
}
}
private String runtimeTag(Ec2Client client, String id) {
return client.describeNetworkInterfaces(r -> r.networkInterfaceIds(id)).networkInterfaces().getFirst()
.tagSet().stream().filter(t -> "Runtime".equals(t.key())).map(t -> t.value()).findFirst().orElse("");
}
}
@@ -11,6 +11,7 @@ import io.floci.aws.services.dynamodb.backend.NativeDynamoDbBackend;
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
import io.floci.aws.services.dynamodb.model.TableDefinition;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.NetworkInterface;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.iam.IamPolicyEvaluator;
import io.floci.aws.services.iam.IamPolicyEvaluator.Decision;
@@ -39,6 +40,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -53,11 +55,14 @@ import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -148,7 +153,7 @@ class IamConditionContextResolverTest {
dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance,
crossAccountServiceInstance, iamServiceInstance,
lambdaWebServiceInstance, spellings(new ShapeNamingSpelling()),
requestContext, config,
requestContext, new RegionResolver("us-east-1", "123456789012"), config,
null, serviceCatalog);
}
@@ -624,6 +629,41 @@ class IamConditionContextResolverTest {
resolver.resolve("iam", "iam:AttachRolePolicy", queryRequest("iam", query)));
}
@Test
void aTagBatchLooksUpItsInterfacesOnceAndGivesEachTargetItsOwnKeys() {
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
query.add("Action", "DeleteTags");
query.add("ResourceId.1", "eni-1");
query.add("ResourceId.2", "eni-2");
query.add("ResourceId.3", "eni-3");
ContainerRequestContext request = queryRequest("ec2", query);
Map<String, Object> properties = new HashMap<>();
properties.put(AwsProtocolClaimFilter.CLAIM_PROPERTY,
request.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY));
when(request.getProperty(anyString())).thenAnswer(call -> properties.get(call.<String>getArgument(0)));
doAnswer(call -> properties.put(call.getArgument(0), call.getArgument(1)))
.when(request).setProperty(anyString(), any());
when(ec2Service.heldResources(eq("us-east-1"), eq("network-interface"), anyCollection())).thenReturn(Map.of(
"eni-1", networkInterface("eni-1", "vpc-a"), "eni-2", networkInterface("eni-2", "vpc-b"),
"eni-3", networkInterface("eni-3", "vpc-a")));
Map<String, List<String>> first = resolver.resolve("ec2", "ec2:DeleteTags", request);
List<Map<String, List<String>>> rest = resolver.resolveRemainingTargets("ec2", "ec2:DeleteTags", request);
assertEquals(List.of("arn:aws:ec2:us-east-1:123456789012:vpc/vpc-a"), first.get("ec2:Vpc"));
assertEquals(List.of("arn:aws:ec2:us-east-1:123456789012:vpc/vpc-b"), rest.get(0).get("ec2:Vpc"));
assertEquals(List.of("eni-3"), rest.get(1).get("ec2:NetworkInterfaceID"));
verify(ec2Service, times(1)).heldResources(anyString(), anyString(), anyCollection());
verify(ec2Service).heldResources("us-east-1", "network-interface", Set.of("eni-1", "eni-2", "eni-3"));
}
private static NetworkInterface networkInterface(String id, String vpcId) {
NetworkInterface networkInterface = new NetworkInterface();
networkInterface.setNetworkInterfaceId(id);
networkInterface.setVpcId(vpcId);
return networkInterface;
}
private static ContainerRequestContext queryRequest(String service, MultivaluedMap<String, String> query) {
ContainerRequestContext request = mock(ContainerRequestContext.class);
UriInfo uri = mock(UriInfo.class);
@@ -806,7 +846,7 @@ class IamConditionContextResolverTest {
private IamConditionContextResolver resolverAt(Instant now) {
return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class),
spellings(), requestContext, config, null,
spellings(), requestContext, new RegionResolver("us-east-1", "123456789012"), config, null,
serviceCatalog, Clock.fixed(now, ZoneOffset.UTC));
}
@@ -155,6 +155,7 @@ class DynamoDbFacadeTest {
mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class), mock(Instance.class),
requestContext,
new RegionResolver(OTHER_REGION, "000000000000"),
mock(EmulatorConfig.class),
null, mock(io.floci.aws.core.common.ResolvedServiceCatalog.class));
ContainerRequestContext request = mock(ContainerRequestContext.class);
+75 -2
View File
@@ -103,7 +103,10 @@ example, i-0123456789abcdef0)") or its examples (`"GroupId": "sg-903004f8"`), di
`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.
namespaces its Service Reference resource-tag condition keys, as their service keeps tags by resource id, and
`resourceKeys` the type's other condition keys that name a member of its botocore shape (`ec2:Vpc` a network
interface's `VpcId`), which its service answers from the resource it holds, as an ARN where the reference types the
key as one.
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
@@ -543,6 +546,60 @@ def resource_tag_keys(documents: list[dict]) -> dict[str, dict[str, list[str]]]:
return dict(sorted(result.items()))
SCALAR_SHAPES = ("string", "boolean", "integer", "long")
def resource_keys(documents: list[dict], data: Path, namespaces: dict[str, list[str]]) -> dict[str, dict[str, dict]]:
"""The condition keys the Service Reference gives each resource type of the id-target namespaces that name a
member of the type's botocore shape (`network-interface` is `NetworkInterface`): a key named as a member, or as
the member without its `Id` (`ec2:Vpc` its `VpcId`, `ec2:NetworkInterfaceID` its `NetworkInterfaceId`), holding a
scalar. Each is `{"member": <member>}`, with `"arn": <type>` where the reference types the key as an ARN and the
namespace has a type named as the key (`ec2:Vpc` takes a `vpc` ARN); an ARN key with no such type is left out, as
are keys with a variable and keys no member names. The type's service holds the member's value for the resource
a request names, which is the key's value."""
result = {}
for document in documents:
namespace = document["Name"]
if namespace not in ID_TARGETS or namespace not in namespaces:
continue
key_types = {key["Name"]: key.get("Types", []) for key in document.get("ConditionKeys", [])}
shapes = {}
for model in load_models(data, set(namespaces[namespace])).values():
shapes.update(model["shapes"])
types = {resource["Name"] for resource in document.get("Resources", []) if resource.get("ARNFormats")}
by_shape_name = {_shape_name(kind).lower(): kind for kind in types}
found = {}
for resource in document.get("Resources", []):
shape = shapes.get(_shape_name(resource["Name"]))
if not shape or shape.get("type") != "structure":
continue
members = {name.lower(): (name, spec["shape"]) for name, spec in shape.get("members", {}).items()}
keys = {}
for key in resource.get("ConditionKeys", []):
if not key.startswith(namespace + ":") or "${" in key:
continue
named = key.split(":", 1)[1].lower()
member = members.get(named) or members.get(named + "id")
if member is None or shapes.get(member[1], {}).get("type") not in SCALAR_SHAPES:
continue
spec = {"member": member[0]}
if "ARN" in key_types.get(key, []):
if named not in by_shape_name:
continue
spec["arn"] = by_shape_name[named]
keys[key] = spec
if keys:
found[resource["Name"]] = dict(sorted(keys.items()))
if found:
result[namespace] = dict(sorted(found.items()))
return dict(sorted(result.items()))
def _shape_name(kind: str) -> str:
"""The botocore shape a resource type of the reference names: `network-interface` is `NetworkInterface`."""
return "".join(part[:1].upper() + part[1:] for part in kind.split("-"))
def arn_formats(documents: list[dict], namespaces: set[str]) -> dict[str, dict[str, str]]:
"""Each resource type of the namespaces given, as its first ARN format, its account `${Account}` where the
reference names it `${AccountId}` (DataSync's, IAM Identity Center's applications)."""
@@ -2660,6 +2717,7 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) ->
and namespace not in NOT_COVERED),
"arnFormats": formats,
"resourceTagKeys": resource_tag_keys(documents),
"resourceKeys": resource_keys(documents, data, namespaces),
"unqualified": unqualified,
"mintedIds": minted,
"integerVariables": integer_variables(operations, namespaces, data),
@@ -2790,7 +2848,7 @@ def render(document: dict) -> str:
"""The document with one operation to a line."""
lines = ["{"]
for key in ("_source", "namespaces", "handBuilt", "notCovered", "otherNamespaces", "arnFormats", "resourceTagKeys",
"unqualified", "mintedIds", "integerVariables", "forwardedActions"):
"resourceKeys", "unqualified", "mintedIds", "integerVariables", "forwardedActions"):
lines.append(f' "{key}": {json.dumps(document[key])},')
lines.append(' "operations": {')
operations = list(document["operations"].items())
@@ -2854,6 +2912,18 @@ def validate(document: dict) -> list[str]:
or any(not isinstance(key, str) or not re.fullmatch(r"[a-z0-9-]+:ResourceTag/", key) for key in keys)
for kind, keys in kinds.items()) for namespace, kinds in tag_keys.items()):
problems.append("resourceTagKeys is not stored-tag prefixes for supported resource types")
resource_keys_document = document.get("resourceKeys", {})
if not isinstance(resource_keys_document, dict) or any(
not isinstance(kinds, dict) or any(
kind not in formats.get(namespace, {}) or not isinstance(keys, dict) or not keys
or list(keys) != sorted(keys) or any(
not re.fullmatch(rf"{re.escape(namespace)}:[A-Za-z0-9]+", key) or not isinstance(spec, dict)
or set(spec) - {"member", "arn"} or not isinstance(spec.get("member"), str)
or ("arn" in spec and spec["arn"] not in formats.get(namespace, {}))
for key, spec in keys.items())
for kind, keys in kinds.items())
for namespace, kinds in resource_keys_document.items()):
problems.append("resourceKeys is not member-named condition keys of supported resource types")
unqualified = document.get("unqualified")
if not isinstance(unqualified, dict) or not all(
isinstance(kinds, list) and kinds and all(isinstance(kind, str) and kind in formats.get(namespace, {})
@@ -3186,6 +3256,9 @@ def main(argv: list[str] | None = None) -> int:
untrue, added = verify_against(document, upstream, formats)
if document.get("resourceTagKeys", {}) != resource_tag_keys(documents):
untrue.append("resourceTagKeys differ from AWS Service Reference")
if document.get("resourceKeys", {}) != resource_keys(documents, resolve_botocore_data(args.botocore_data)[0],
document["namespaces"]):
untrue.append("resourceKeys differ from AWS Service Reference and botocore")
untrue += verify_forwarded(document, documents)
for claim in untrue:
print(f"error: {claim}", file=sys.stderr)
@@ -1429,6 +1429,30 @@ def test_resource_tag_prefixes_cover_every_type_of_an_id_target_namespace_from_t
assert r.resource_tag_keys([]) == {}
def test_resource_keys_are_the_reference_keys_a_member_of_the_types_shape_names(monkeypatch):
model = {"shapes": {
"NetworkInterface": {"type": "structure", "members": {
"VpcId": {"shape": "String"}, "SubnetId": {"shape": "String"},
"NetworkInterfaceId": {"shape": "String"}, "Groups": {"shape": "GroupList"}}},
"String": {"type": "string"}, "GroupList": {"type": "list", "member": {"shape": "String"}}}}
monkeypatch.setattr(r, "load_models", lambda data, clients: {"ec2": model})
document = {"Name": "ec2", "ConditionKeys": [
{"Name": "ec2:Vpc", "Types": ["ARN"]}, {"Name": "ec2:Subnet", "Types": ["ARN"]},
{"Name": "ec2:NetworkInterfaceID", "Types": ["String"]}, {"Name": "ec2:Region", "Types": ["String"]},
{"Name": "ec2:Groups", "Types": ["String"]}],
"Resources": [
{"Name": "network-interface", "ARNFormats": ["arn:${Partition}:ec2:${Region}:${Account}:network-interface/x"],
"ConditionKeys": ["aws:ResourceTag/${TagKey}", "ec2:Vpc", "ec2:Subnet", "ec2:NetworkInterfaceID",
"ec2:Region", "ec2:Groups", "ec2:Attribute/${AttributeName}"]},
{"Name": "vpc", "ARNFormats": ["arn:${Partition}:ec2:${Region}:${Account}:vpc/${VpcId}"],
"ConditionKeys": []}]}
# A key named as the member or as it without its Id; a list member, a key no member names, an ARN key with no
# type named as it and a key with a variable are left out.
assert r.resource_keys([document], Path("."), {"ec2": ["ec2"]}) == {"ec2": {"network-interface": {
"ec2:NetworkInterfaceID": {"member": "NetworkInterfaceId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}}}
assert r.resource_keys([document], Path("."), {}) == {}
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"}