mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(iam): derive EC2 instance authorization from AWS metadata (#8150)
Authorize generated instance targets with their own stored tags before mutation. Return malformed Query errors as XML HTTP 404, reuse enforcement group cleanup, and update generated-target regression coverage. Regenerate IAM metadata on current main. Closes #8159
This commit is contained in:
1 parent
f64ca5ef16
commit
2dc93aa087
18 files changed
+566
-107
No files matched your search
@@ -2,6 +2,16 @@
|
||||
|
||||
**Protocol:** EC2 Query (XML) — `POST http://localhost:4566/` with `Action=` parameter
|
||||
|
||||
## 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.
|
||||
Policies can scope access to an exact instance ARN or use stored tags through `ec2:ResourceTag/<key>` and `aws:ResourceTag/<key>`.
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -14,6 +14,11 @@ public final class Ec2ErrorResponses {
|
||||
}
|
||||
|
||||
static boolean isEc2QueryRequest(ContainerRequestContext ctx) {
|
||||
return isEc2QueryRequest(ctx, true);
|
||||
}
|
||||
|
||||
/** Error decoding cannot inspect the form again while rendering that same failure. */
|
||||
static boolean isEc2QueryRequest(ContainerRequestContext ctx, boolean inspectForm) {
|
||||
if (!(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim)
|
||||
|| claim.protocol() != WireProtocol.AWS_QUERY) {
|
||||
return false;
|
||||
@@ -21,15 +26,13 @@ public final class Ec2ErrorResponses {
|
||||
if (claim.service() != null) {
|
||||
return "ec2".equals(claim.service().externalKey());
|
||||
}
|
||||
try {
|
||||
String action = AwsQueryServiceResolver.action(RequestBodyReader.formField(ctx, "Action"),
|
||||
RequestBodyReader.formField(ctx, "Operation"));
|
||||
return action != null && "ec2".equals(AwsQueryController.inferServiceFromAction(action,
|
||||
RequestBodyReader.formField(ctx, "Version")));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// A malformed form cannot identify a service; retain the generic protocol error.
|
||||
if (!inspectForm) {
|
||||
return false;
|
||||
}
|
||||
String action = AwsQueryServiceResolver.action(RequestBodyReader.formField(ctx, "Action"),
|
||||
RequestBodyReader.formField(ctx, "Operation"));
|
||||
return action != null && "ec2".equals(AwsQueryController.inferServiceFromAction(action,
|
||||
RequestBodyReader.formField(ctx, "Version")));
|
||||
}
|
||||
|
||||
public static Response authFailure() {
|
||||
|
||||
@@ -39,7 +39,6 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
@@ -736,14 +735,19 @@ public class IamConditionContextResolver {
|
||||
// ── EC2 ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
private Map<String, List<String>> ec2ConditionContext(String action, ContainerRequestContext ctx) {
|
||||
return switch (action) {
|
||||
case "ec2:RunInstances" -> ec2RunInstancesConditionContext(ctx);
|
||||
case "ec2:CreateTags" -> ec2CreateTagsConditionContext(ctx);
|
||||
case "ec2:DeleteTags" -> ec2ResourceTagConditionContext(ctx, "ResourceId.1");
|
||||
case "ec2:TerminateInstances", "ec2:DescribeInstances" ->
|
||||
ec2ResourceTagConditionContext(ctx, "InstanceId.1");
|
||||
default -> null;
|
||||
};
|
||||
if ("ec2:RunInstances".equals(action)) {
|
||||
return ec2RunInstancesConditionContext(ctx);
|
||||
}
|
||||
RequestResourceMembers.Targets targets = RequestResourceMembers.table().targets().get(action);
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
Map<String, String> form = formParameters(ctx);
|
||||
if ("ec2:CreateTags".equals(action)) {
|
||||
addRequestTags(conditions, form, "Tag.");
|
||||
}
|
||||
if (targets != null) {
|
||||
addResourceTags(conditions, form.get(targets.query() + ".1"), targets);
|
||||
}
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -759,27 +763,6 @@ public class IamConditionContextResolver {
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
/**
|
||||
* CreateTags both requests tags and targets existing resources, so both keys apply: the
|
||||
* {@code Tag.N} pairs being requested, and each {@code ResourceId.N}'s tags as they are
|
||||
* before this call. This context carries the first target; the rest come from
|
||||
* {@link #resolveRemainingTargets}.
|
||||
*/
|
||||
private Map<String, List<String>> ec2CreateTagsConditionContext(ContainerRequestContext ctx) {
|
||||
Map<String, String> form = formParameters(ctx);
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
addRequestTags(conditions, form, "Tag.");
|
||||
addResourceTags(conditions, form.get("ResourceId.1"));
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
private Map<String, List<String>> ec2ResourceTagConditionContext(ContainerRequestContext ctx,
|
||||
String idParameter) {
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
addResourceTags(conditions, formParameters(ctx).get(idParameter));
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
/**
|
||||
* One condition context per target after the first, for the EC2 actions that accept several
|
||||
* resource ids in one request. An untagged target yields an empty context rather than none,
|
||||
@@ -806,14 +789,11 @@ public class IamConditionContextResolver {
|
||||
if (!"ec2".equals(credentialScope)) {
|
||||
return List.of();
|
||||
}
|
||||
String idParameter = switch (action) {
|
||||
case "ec2:CreateTags", "ec2:DeleteTags" -> "ResourceId.";
|
||||
case "ec2:TerminateInstances", "ec2:DescribeInstances" -> "InstanceId.";
|
||||
default -> null;
|
||||
};
|
||||
if (idParameter == null) {
|
||||
RequestResourceMembers.Targets generatedTargets = RequestResourceMembers.table().targets().get(action);
|
||||
if (generatedTargets == null) {
|
||||
return List.of();
|
||||
}
|
||||
String idParameter = generatedTargets.query() + ".";
|
||||
Map<String, String> form = formParameters(ctx);
|
||||
List<Map<String, List<String>>> targets = new ArrayList<>();
|
||||
if (!form.containsKey(idParameter + 1)) {
|
||||
@@ -825,7 +805,7 @@ public class IamConditionContextResolver {
|
||||
if ("ec2:CreateTags".equals(action)) {
|
||||
addRequestTags(conditions, form, "Tag.");
|
||||
}
|
||||
addResourceTags(conditions, form.get(idParameter + i));
|
||||
addResourceTags(conditions, form.get(idParameter + i), generatedTargets);
|
||||
targets.add(conditions);
|
||||
}
|
||||
return targets;
|
||||
@@ -845,14 +825,24 @@ public class IamConditionContextResolver {
|
||||
}
|
||||
}
|
||||
|
||||
private void addResourceTags(Map<String, List<String>> conditions, String resourceId) {
|
||||
private void addResourceTags(Map<String, List<String>> conditions, String resourceId,
|
||||
RequestResourceMembers.Targets targets) {
|
||||
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);
|
||||
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;
|
||||
}
|
||||
}
|
||||
for (Tag tag : ec2Service.get().resourceTags(region, resourceId)) {
|
||||
conditions.put(RESOURCE_TAG_PREFIX + tag.getKey(),
|
||||
List.of(tag.getValue() == null ? "" : tag.getValue()));
|
||||
for (String prefix : prefixes) {
|
||||
conditions.put(prefix + tag.getKey(), List.of(tag.getValue() == null ? "" : tag.getValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -898,7 +888,8 @@ public class IamConditionContextResolver {
|
||||
int eq = pair.indexOf('=');
|
||||
String key = eq < 0 ? pair : pair.substring(0, eq);
|
||||
String value = eq < 0 ? "" : pair.substring(eq + 1);
|
||||
parameters.putIfAbsent(URLDecoder.decode(key, charset), URLDecoder.decode(value, charset));
|
||||
parameters.putIfAbsent(QueryFormDecoder.decode(key, charset, ctx),
|
||||
QueryFormDecoder.decode(value, charset, ctx));
|
||||
}
|
||||
ctx.setProperty(BUFFERED_FORM_BODY, parameters);
|
||||
return parameters;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/** Percent decoding shared by Query action extraction and IAM resource/context resolution. */
|
||||
public final class QueryFormDecoder {
|
||||
|
||||
private QueryFormDecoder() {
|
||||
}
|
||||
|
||||
public static String decode(String value, Charset charset, ContainerRequestContext ctx) {
|
||||
try {
|
||||
return URLDecoder.decode(value, charset);
|
||||
} catch (IllegalArgumentException invalidEncoding) {
|
||||
String message = "The form body contains an invalid percent escape.";
|
||||
boolean ec2 = Ec2ErrorResponses.isEc2QueryRequest(ctx, false);
|
||||
Response response = ec2 ? Ec2ErrorResponses.of("MalformedQueryString", message, 404)
|
||||
: AwsQueryResponse.error("MalformedQueryString", message, null, 404);
|
||||
throw new WebApplicationException(invalidEncoding, response);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -204,6 +204,7 @@ final class RequestResourceMembers {
|
||||
Map<String, List<Created>> creates, Map<String, List<Resource>> makes,
|
||||
Map<String, Targets> targets,
|
||||
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) {
|
||||
}
|
||||
|
||||
@@ -257,6 +258,32 @@ final class RequestResourceMembers {
|
||||
+ namespace.getValue() + " a minted id, no types whose format ends in its one variable");
|
||||
}
|
||||
});
|
||||
Map<String, Map<String, List<String>>> resourceTagKeys = new LinkedHashMap<>();
|
||||
if (!document.path("resourceTagKeys").isMissingNode() && !document.path("resourceTagKeys").isObject()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has malformed resource tag keys");
|
||||
}
|
||||
document.path("resourceTagKeys").properties().forEach(namespace -> {
|
||||
if (!namespace.getValue().isObject()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has malformed resource tag keys");
|
||||
}
|
||||
Map<String, List<String>> types = new LinkedHashMap<>();
|
||||
namespace.getValue().properties().forEach(type -> {
|
||||
List<String> keys = new ArrayList<>();
|
||||
if (!formats.getOrDefault(namespace.getKey(), Map.of()).containsKey(type.getKey())
|
||||
|| !type.getValue().isArray()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has malformed resource tag keys");
|
||||
}
|
||||
type.getValue().forEach(key -> {
|
||||
String prefix = key.asText("");
|
||||
if (!prefix.matches("[a-z0-9-]+:ResourceTag/") || keys.contains(prefix)) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has malformed resource tag keys");
|
||||
}
|
||||
keys.add(prefix);
|
||||
});
|
||||
types.put(type.getKey(), List.copyOf(keys));
|
||||
});
|
||||
resourceTagKeys.put(namespace.getKey(), Map.copyOf(types));
|
||||
});
|
||||
Map<String, List<Resource>> entries = new LinkedHashMap<>();
|
||||
Map<String, List<String>> actsOn = new LinkedHashMap<>();
|
||||
Map<String, List<Created>> creates = new LinkedHashMap<>();
|
||||
@@ -336,7 +363,7 @@ 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), namespaces,
|
||||
Map.copyOf(targets), 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")));
|
||||
|
||||
@@ -214,18 +214,13 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
|
||||
String token = ctx.getHeaderString("X-Amz-Security-Token");
|
||||
ServiceDescriptor queryService = null;
|
||||
if (presigned) {
|
||||
try {
|
||||
if (token == null) {
|
||||
token = RequestBodyReader.formField(ctx, "X-Amz-Security-Token");
|
||||
if (token == null) {
|
||||
token = RequestBodyReader.formField(ctx, "X-Amz-Security-Token");
|
||||
if (token == null) {
|
||||
token = query.getFirst("X-Amz-Security-Token");
|
||||
}
|
||||
token = query.getFirst("X-Amz-Security-Token");
|
||||
}
|
||||
queryService = queryService(ctx, resource);
|
||||
} catch (IllegalArgumentException error) {
|
||||
incompleteSignature(ctx, resource, "Cannot read presigned request form parameters.");
|
||||
return;
|
||||
}
|
||||
queryService = queryService(ctx, resource);
|
||||
}
|
||||
Optional<String> secretKey = resolveSecretKey(scope.accessKeyId(), token);
|
||||
if (secretKey.isEmpty()) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.services.iam;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import io.floci.aws.core.common.QueryFormDecoder;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -10,7 +11,6 @@ import org.jboss.logging.Logger;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@@ -69,10 +69,10 @@ public final class RequestBodyReader {
|
||||
for (String pair : form.split("&")) {
|
||||
int eq = pair.indexOf('=');
|
||||
String pairKey = eq < 0 ? pair : pair.substring(0, eq);
|
||||
if (!key.equals(URLDecoder.decode(pairKey, charset))) {
|
||||
if (!key.equals(QueryFormDecoder.decode(pairKey, charset, ctx))) {
|
||||
continue;
|
||||
}
|
||||
return eq < 0 ? "" : URLDecoder.decode(pair.substring(eq + 1), charset);
|
||||
return eq < 0 ? "" : QueryFormDecoder.decode(pair.substring(eq + 1), charset, ctx);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -2253,16 +2253,11 @@ public class ResourceArnBuilder {
|
||||
* A Query-protocol parameter, read from the same place the handler reads it. For a form POST
|
||||
* that is the body alone: {@code AwsQueryController} dispatches on the form parameters and never
|
||||
* sees the URL query, so authorizing a URL value would check one resource and act on another.
|
||||
* A value with an invalid percent escape is read as absent, so the resource stays the default
|
||||
* and the request goes on to be answered as it is without enforcement.
|
||||
* An invalid percent escape is rejected by the shared form decoder before authorization.
|
||||
*/
|
||||
private String firstFormParam(ContainerRequestContext ctx, String name) {
|
||||
if (RequestBodyReader.isForm(ctx)) {
|
||||
try {
|
||||
return RequestBodyReader.formField(ctx, name);
|
||||
} catch (IllegalArgumentException malformed) {
|
||||
return null;
|
||||
}
|
||||
return RequestBodyReader.formField(ctx, name);
|
||||
}
|
||||
return ctx.getUriInfo().getQueryParameters().getFirst(name);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"notCovered": {"airflow": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appsync": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "aps": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup:<id>:autoScalingGroupName/<name>`, while Floci mints `autoScalingGroup:<name>`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "batch": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rule does not fill a name from, so nearly every operation needs a correction", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/<name>_<id>, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "detective": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dlm": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dms": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ec2-instance-connect": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ecs": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticache": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticbeanstalk": "not read yet: an environment's ARN carries its application's name, `environment/<application>/<name>`, while most of its requests name it by EnvironmentName or EnvironmentId alone, so reaLine truncated
|
||||
"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": {"instance": ["aws:ResourceTag/", "ec2:ResourceTag/"]}},
|
||||
"unqualified": {"states": ["statemachine"]},
|
||||
"mintedIds": {"events": ["api-destination", "connection"]},
|
||||
"operations": {
|
||||
@@ -929,7 +930,7 @@
|
||||
"ec2:AssignPrivateIpAddresses": {"action": "ec2:AssignPrivateIpAddresses", "types": ["network-interface"], "resources": []},
|
||||
"ec2:AssignPrivateNatGatewayAddress": {"action": "ec2:AssignPrivateNatGatewayAddress", "types": ["natgateway"], "resources": []},
|
||||
"ec2:AssociateAddress": {"action": "ec2:AssociateAddress", "types": ["elastic-ip", "instance", "network-interface"], "resources": []},
|
||||
"ec2:AssociateApplicationStatusCheck": {"action": "ec2:AssociateApplicationStatusCheck", "types": ["application-status-check", "instance"], "resources": []},
|
||||
"ec2:AssociateApplicationStatusCheck": {"action": "ec2:AssociateApplicationStatusCheck", "types": ["application-status-check", "instance"], "resources": [], "targets": {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}},
|
||||
"ec2:AssociateCapacityReservationBillingOwner": {"action": "ec2:AssociateCapacityReservationBillingOwner", "types": ["capacity-reservation"], "resources": []},
|
||||
"ec2:AssociateClientVpnTargetNetwork": {"action": "ec2:AssociateClientVpnTargetNetwork", "types": ["client-vpn-endpoint", "subnet"], "resources": []},
|
||||
"ec2:AssociateDhcpOptions": {"action": "ec2:AssociateDhcpOptions", "types": ["dhcp-options", "vpc"], "resources": []},
|
||||
@@ -1397,7 +1398,7 @@
|
||||
"ec2:DetachVpnGateway": {"action": "ec2:DetachVpnGateway", "types": ["vpc", "vpn-gateway"], "resources": []},
|
||||
"ec2:DisableAddressTransfer": {"action": "ec2:DisableAddressTransfer", "types": ["elastic-ip"], "resources": []},
|
||||
"ec2:DisableAllowedImagesSettings": {"action": "ec2:DisableAllowedImagesSettings", "types": [], "resources": []},
|
||||
"ec2:DisableApplicationStatusCheckSuppression": {"action": "ec2:DisableApplicationStatusCheckSuppression", "types": ["instance"], "resources": []},
|
||||
"ec2:DisableApplicationStatusCheckSuppression": {"action": "ec2:DisableApplicationStatusCheckSuppression", "types": ["instance"], "resources": [], "targets": {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}},
|
||||
"ec2:DisableAwsNetworkPerformanceMetricSubscription": {"action": "ec2:DisableAwsNetworkPerformanceMetricSubscription", "types": [], "resources": []},
|
||||
"ec2:DisableCapacityManager": {"action": "ec2:DisableCapacityManager", "types": [], "resources": []},
|
||||
"ec2:DisableEbsEncryptionByDefault": {"action": "ec2:DisableEbsEncryptionByDefault", "types": [], "resources": []},
|
||||
@@ -1407,7 +1408,7 @@
|
||||
"ec2:DisableImageBlockPublicAccess": {"action": "ec2:DisableImageBlockPublicAccess", "types": [], "resources": []},
|
||||
"ec2:DisableImageDeprecation": {"action": "ec2:DisableImageDeprecation", "types": ["image"], "resources": []},
|
||||
"ec2:DisableImageDeregistrationProtection": {"action": "ec2:DisableImageDeregistrationProtection", "types": ["image"], "resources": []},
|
||||
"ec2:DisableInstanceSqlHaStandbyDetections": {"action": "ec2:DisableInstanceSqlHaStandbyDetections", "types": ["instance"], "resources": []},
|
||||
"ec2:DisableInstanceSqlHaStandbyDetections": {"action": "ec2:DisableInstanceSqlHaStandbyDetections", "types": ["instance"], "resources": [], "targets": {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}},
|
||||
"ec2:DisableIpamOrganizationAdminAccount": {"action": "ec2:DisableIpamOrganizationAdminAccount", "types": [], "resources": []},
|
||||
"ec2:DisableIpamPolicy": {"action": "ec2:DisableIpamPolicy", "types": ["ipam-policy"], "resources": []},
|
||||
"ec2:DisableRouteServerPropagation": {"action": "ec2:DisableRouteServerPropagation", "types": ["route-server", "route-table"], "resources": []},
|
||||
@@ -1418,7 +1419,7 @@
|
||||
"ec2:DisableVpcClassicLink": {"action": "ec2:DisableVpcClassicLink", "types": ["vpc"], "resources": []},
|
||||
"ec2:DisableVpcClassicLinkDnsSupport": {"action": "ec2:DisableVpcClassicLinkDnsSupport", "types": ["vpc"], "resources": []},
|
||||
"ec2:DisassociateAddress": {"action": "ec2:DisassociateAddress", "types": ["elastic-ip", "network-interface"], "resources": []},
|
||||
"ec2:DisassociateApplicationStatusCheck": {"action": "ec2:DisassociateApplicationStatusCheck", "types": ["application-status-check", "instance"], "resources": []},
|
||||
"ec2:DisassociateApplicationStatusCheck": {"action": "ec2:DisassociateApplicationStatusCheck", "types": ["application-status-check", "instance"], "resources": [], "targets": {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}},
|
||||
"ec2:DisassociateCapacityReservationBillingOwner": {"action": "ec2:DisassociateCapacityReservationBillingOwner", "types": ["capacity-reservation"], "resources": []},
|
||||
"ec2:DisassociateClientVpnTargetNetwork": {"action": "ec2:DisassociateClientVpnTargetNetwork", "types": ["client-vpn-endpoint"], "resources": []},
|
||||
"ec2:DisassociateEnclaveCertificateIamRole": {"action": "ec2:DisassociateEnclaveCertificateIamRole", "types": ["certificate", "role"], "resources": []},
|
||||
@@ -1438,7 +1439,7 @@
|
||||
"ec2:DisassociateVpcCidrBlock": {"action": "ec2:DisassociateVpcCidrBlock", "types": ["vpc"], "resources": []},
|
||||
"ec2:EnableAddressTransfer": {"action": "ec2:EnableAddressTransfer", "types": ["elastic-ip"], "resources": []},
|
||||
"ec2:EnableAllowedImagesSettings": {"action": "ec2:EnableAllowedImagesSettings", "types": [], "resources": []},
|
||||
"ec2:EnableApplicationStatusCheckSuppression": {"action": "ec2:EnableApplicationStatusCheckSuppression", "types": ["instance"], "resources": []},
|
||||
"ec2:EnableApplicationStatusCheckSuppression": {"action": "ec2:EnableApplicationStatusCheckSuppression", "types": ["instance"], "resources": [], "targets": {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}},
|
||||
"ec2:EnableAwsNetworkPerformanceMetricSubscription": {"action": "ec2:EnableAwsNetworkPerformanceMetricSubscription", "types": [], "resources": []},
|
||||
"ec2:EnableCapacityManager": {"action": "ec2:EnableCapacityManager", "types": [], "resources": []},
|
||||
"ec2:EnableEbsEncryptionByDefault": {"action": "ec2:EnableEbsEncryptionByDefault", "types": [], "resources": []},
|
||||
@@ -1448,7 +1449,7 @@
|
||||
"ec2:EnableImageBlockPublicAccess": {"action": "ec2:EnableImageBlockPublicAccess", "types": [], "resources": []},
|
||||
"ec2:EnableImageDeprecation": {"action": "ec2:EnableImageDeprecation", "types": ["image"], "resources": []},
|
||||
"ec2:EnableImageDeregistrationProtection": {"action": "ec2:EnableImageDeregistrationProtection", "types": ["image"], "resources": []},
|
||||
"ec2:EnableInstanceSqlHaStandbyDetections": {"action": "ec2:EnableInstanceSqlHaStandbyDetections", "types": ["instance"], "resources": []},
|
||||
"ec2:EnableInstanceSqlHaStandbyDetections": {"action": "ec2:EnableInstanceSqlHaStandbyDetections", "types": ["instance"], "resources": [], "targets": {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}},
|
||||
"ec2:EnableIpamInternetRegistryAssociation": {"action": "ec2:EnableIpamInternetRegistryAssociation", "types": ["ipam-internet-registry-association"], "resources": []},
|
||||
"ec2:EnableIpamOrganizationAdminAccount": {"action": "ec2:EnableIpamOrganizationAdminAccount", "types": [], "resources": []},
|
||||
"ec2:EnableIpamPolicy": {"action": "ec2:EnableIpamPolicy", "types": ["ipam-policy"], "resources": []},
|
||||
@@ -1644,7 +1645,7 @@
|
||||
"ec2:ModifyVpnConnectionOptions": {"action": "ec2:ModifyVpnConnectionOptions", "types": ["vpn-connection"], "resources": []},
|
||||
"ec2:ModifyVpnTunnelCertificate": {"action": "ec2:ModifyVpnTunnelCertificate", "types": ["vpn-connection"], "resources": []},
|
||||
"ec2:ModifyVpnTunnelOptions": {"action": "ec2:ModifyVpnTunnelOptions", "types": ["vpn-connection"], "resources": []},
|
||||
"ec2:MonitorInstances": {"action": "ec2:MonitorInstances", "types": ["instance"], "resources": []},
|
||||
"ec2:MonitorInstances": {"action": "ec2:MonitorInstances", "types": ["instance"], "resources": [], "targets": {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}},
|
||||
"ec2:MoveAddressToVpc": {"action": "ec2:MoveAddressToVpc", "types": [], "resources": []},
|
||||
"ec2:MoveByoipCidrToIpam": {"action": "ec2:MoveByoipCidrToIpam", "types": ["ipam-pool"], "resources": []},
|
||||
"ec2:MoveCapacityReservationInstances": {"action": "ec2:MoveCapacityReservationInstances", "types": ["capacity-reservation"], "resources": []},
|
||||
@@ -1657,7 +1658,7 @@
|
||||
"ec2:PurchaseHostReservation": {"action": "ec2:PurchaseHostReservation", "types": ["dedicated-host"], "resources": []},
|
||||
"ec2:PurchaseReservedInstancesOffering": {"action": "ec2:PurchaseReservedInstancesOffering", "types": [], "resources": []},
|
||||
"ec2:PurchaseScheduledInstances": {"action": "ec2:PurchaseScheduledInstances", "types": [], "resources": []},
|
||||
"ec2:RebootInstances": {"action": "ec2:RebootInstances", "types": ["instance"], "resources": []},
|
||||
"ec2:RebootInstances": {"action": "ec2:RebootInstances", "types": ["instance"], "resources": [], "targets": {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}},
|
||||
"ec2:RegisterImage": {"action": "ec2:RegisterImage", "types": ["image", "snapshot"], "resources": []},
|
||||
"ec2:RegisterInstanceEventNotificationAttributes": {"action": "ec2:RegisterInstanceEventNotificationAttributes", "types": [], "resources": []},
|
||||
"ec2:RegisterTransitGatewayMulticastGroupMembers": {"action": "ec2:RegisterTransitGatewayMulticastGroupMembers", "types": ["network-interface", "transit-gateway-multicast-domain"], "resources": []},
|
||||
@@ -1707,18 +1708,18 @@
|
||||
"ec2:SearchTransitGatewayRoutes": {"action": "ec2:SearchTransitGatewayRoutes", "types": ["transit-gateway-route-table"], "resources": []},
|
||||
"ec2:SendDiagnosticInterrupt": {"action": "ec2:SendDiagnosticInterrupt", "types": ["instance"], "resources": []},
|
||||
"ec2:StartDeclarativePoliciesReport": {"action": "ec2:StartDeclarativePoliciesReport", "types": [], "resources": []},
|
||||
"ec2:StartInstances": {"action": "ec2:StartInstances", "types": ["group", "instance", "license-configuration"], "resources": []},
|
||||
"ec2:StartInstances": {"action": "ec2:StartInstances", "types": ["group", "instance", "license-configuration"], "resources": [], "targets": {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}},
|
||||
"ec2:StartNetworkInsightsAccessScopeAnalysis": {"action": "ec2:StartNetworkInsightsAccessScopeAnalysis", "types": ["network-insights-access-scope", "network-insights-access-scope-analysis"], "resources": []},
|
||||
"ec2:StartNetworkInsightsAnalysis": {"action": "ec2:StartNetworkInsightsAnalysis", "types": ["network-insights-analysis", "network-insights-path"], "resources": []},
|
||||
"ec2:StartVpcEndpointServicePrivateDnsVerification": {"action": "ec2:StartVpcEndpointServicePrivateDnsVerification", "types": ["vpc-endpoint-service"], "resources": []},
|
||||
"ec2:StopInstances": {"action": "ec2:StopInstances", "types": ["instance"], "resources": []},
|
||||
"ec2:StopInstances": {"action": "ec2:StopInstances", "types": ["instance"], "resources": [], "targets": {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}},
|
||||
"ec2:TerminateClientVpnConnections": {"action": "ec2:TerminateClientVpnConnections", "types": ["client-vpn-endpoint"], "resources": []},
|
||||
"ec2:TerminateInstances": {"action": "ec2:TerminateInstances", "types": ["instance"], "resources": []},
|
||||
"ec2:TerminateInstances": {"action": "ec2:TerminateInstances", "types": ["instance"], "resources": [], "targets": {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}},
|
||||
"ec2:UnassignIpv6Addresses": {"action": "ec2:UnassignIpv6Addresses", "types": ["network-interface"], "resources": []},
|
||||
"ec2:UnassignPrivateIpAddresses": {"action": "ec2:UnassignPrivateIpAddresses", "types": ["network-interface"], "resources": []},
|
||||
"ec2:UnassignPrivateNatGatewayAddress": {"action": "ec2:UnassignPrivateNatGatewayAddress", "types": ["natgateway"], "resources": []},
|
||||
"ec2:UnlockSnapshot": {"action": "ec2:UnlockSnapshot", "types": ["snapshot"], "resources": []},
|
||||
"ec2:UnmonitorInstances": {"action": "ec2:UnmonitorInstances", "types": ["instance"], "resources": []},
|
||||
"ec2:UnmonitorInstances": {"action": "ec2:UnmonitorInstances", "types": ["instance"], "resources": [], "targets": {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}},
|
||||
"ec2:UpdateCapacityManagerMonitoredTagKeys": {"action": "ec2:UpdateCapacityManagerMonitoredTagKeys", "types": [], "resources": []},
|
||||
"ec2:UpdateCapacityManagerOrganizationsAccess": {"action": "ec2:UpdateCapacityManagerOrganizationsAccess", "types": [], "resources": []},
|
||||
"ec2:UpdateInterruptibleCapacityReservationAllocation": {"action": "ec2:UpdateInterruptibleCapacityReservationAllocation", "types": ["capacity-reservation"], "resources": []},
|
||||
|
||||
@@ -21,6 +21,7 @@ import io.floci.aws.services.lambdaweb.LambdaWebService;
|
||||
import io.floci.aws.services.lambdaweb.model.WebFunctionEndpoint;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
@@ -50,11 +51,13 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
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.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -1042,7 +1045,7 @@ class IamConditionContextResolverTest {
|
||||
void instanceActionsResolveResourceTagsFromTheFirstNamedInstance() {
|
||||
when(ec2Service.resourceTags("us-east-1", "i-0123456789")).thenReturn(List.of(new Tag("Team", "payments")));
|
||||
|
||||
for (String action : List.of("ec2:TerminateInstances", "ec2:DescribeInstances")) {
|
||||
for (String action : List.of("ec2:StartInstances", "ec2:StopInstances", "ec2:TerminateInstances", "ec2:RebootInstances")) {
|
||||
Map<String, List<String>> conditions = resolver.resolve("ec2", action,
|
||||
formRequest("Action=X&InstanceId.1=i-0123456789&InstanceId.2=i-9999999999"));
|
||||
assertEquals(List.of("payments"), conditions.get("aws:ResourceTag/Team"), action);
|
||||
@@ -1053,6 +1056,14 @@ class IamConditionContextResolverTest {
|
||||
.get("aws:ResourceTag/Team"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeInstancesHasNoResourceTagContextsEvenWhenInstancesAreNamed() {
|
||||
ContainerRequestContext request = formRequest("Action=DescribeInstances&InstanceId.1=i-first&InstanceId.2=i-second");
|
||||
assertNull(resolver.resolve("ec2", "ec2:DescribeInstances", request));
|
||||
assertEquals(List.of(), resolver.resolveRemainingTargets("ec2", "ec2:DescribeInstances", request));
|
||||
verify(ec2Service, never()).resourceTags(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourceTagsAreReadInTheRequestRegion() {
|
||||
requestContext.setRegion("eu-west-1");
|
||||
@@ -1063,6 +1074,37 @@ class IamConditionContextResolverTest {
|
||||
formRequest("Action=TerminateInstances&InstanceId.1=i-0123456789")).get("aws:ResourceTag/Team"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"ec2:StartInstances", "ec2:StopInstances", "ec2:RebootInstances", "ec2:TerminateInstances"})
|
||||
void instanceLifecycleContextsPreserveOrderEmptyTagsAndTheRequestRegion(String action) {
|
||||
requestContext.setRegion("eu-west-1");
|
||||
when(ec2Service.resourceTags("eu-west-1", "i-first")).thenReturn(List.of(new Tag("Env", "development")));
|
||||
when(ec2Service.resourceTags("eu-west-1", "i-second")).thenReturn(List.of(new Tag("Env", "production")));
|
||||
ContainerRequestContext request = formRequest("InstanceId.1=i-first&InstanceId.1=i-decoy"
|
||||
+ "&InstanceId.2=i-second&InstanceId.3=i-untagged&InstanceId.4=i-first&InstanceId.6=i-gap"
|
||||
+ "&ResourceId.1=i-decoy");
|
||||
Map<String, List<String>> first = Map.of("aws:ResourceTag/Env", List.of("development"),
|
||||
"ec2:ResourceTag/Env", List.of("development"));
|
||||
assertEquals(first, resolver.resolve("ec2", action, request));
|
||||
assertEquals(List.of(Map.of("aws:ResourceTag/Env", List.of("production"),
|
||||
"ec2:ResourceTag/Env", List.of("production")), Map.of(), first),
|
||||
resolver.resolveRemainingTargets("ec2", action, request));
|
||||
assertNull(resolver.resolve("ec2", action, formRequest("ResourceId.1=i-first&InstanceId.2=i-second")));
|
||||
assertEquals(List.of(), resolver.resolveRemainingTargets("ec2", action,
|
||||
formRequest("ResourceId.1=i-first&InstanceId.2=i-second")));
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.add("Action", action.substring(4));
|
||||
query.add("InstanceId.1", "i-first");
|
||||
query.add("InstanceId.1", "i-decoy");
|
||||
query.add("InstanceId.2", "i-second");
|
||||
query.add("InstanceId.4", "i-gap");
|
||||
ContainerRequestContext get = queryRequest("ec2", query);
|
||||
assertEquals(first, resolver.resolve("ec2", action, get));
|
||||
assertEquals(List.of(Map.of("aws:ResourceTag/Env", List.of("production"),
|
||||
"ec2:ResourceTag/Env", List.of("production"))),
|
||||
resolver.resolveRemainingTargets("ec2", action, get));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2ContextIsAbsentWhenNoResourceIsNamedOrTheActionIsNotCovered() {
|
||||
assertNull(resolver.resolve("ec2", "ec2:DescribeInstances", formRequest("Action=DescribeInstances")));
|
||||
@@ -1082,6 +1124,20 @@ class IamConditionContextResolverTest {
|
||||
verify(containerRequest).setProperty(eq("floci.bufferedFormBody"), any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Value=%ZZ", "Value=%", "Value=%A", "%ZZ=value"})
|
||||
void malformedFormsNeverReturnOrCachePartialParameters(String malformed) {
|
||||
ContainerRequestContext request = formRequest("Action=StartInstances&InstanceId.1=i-first&" + malformed);
|
||||
for (int attempt = 0; attempt < 2; attempt++) {
|
||||
WebApplicationException error = assertThrows(WebApplicationException.class,
|
||||
() -> IamConditionContextResolver.formParameters(request));
|
||||
assertEquals(404, error.getResponse().getStatus());
|
||||
assertEquals("application/xml", error.getResponse().getMediaType().toString());
|
||||
assertTrue(error.getResponse().getEntity().toString().contains("<Code>MalformedQueryString</Code>"));
|
||||
}
|
||||
verify(request, never()).setProperty(eq("floci.bufferedFormBody"), any());
|
||||
}
|
||||
|
||||
// ── The resolved context drives the real evaluator ─────────────────────────
|
||||
|
||||
private final IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class QueryFormDecoderTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"ec2,404", "sts,404", "'',404"})
|
||||
void malformedEncodingUsesTheClaimWithoutReadingTheFormAgain(String service, int status) {
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
ServiceDescriptor descriptor = service.isEmpty() ? null : new ServiceDescriptor(service, service,
|
||||
true, true, null, null, 0L, null, ServiceProtocol.QUERY, Set.of(ServiceProtocol.QUERY),
|
||||
Set.of(), Set.of(service), Set.of(), Set.of(), Set.of());
|
||||
when(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY))
|
||||
.thenReturn(new ProtocolClaim(WireProtocol.AWS_QUERY, descriptor, null, null));
|
||||
WebApplicationException error = assertThrows(WebApplicationException.class,
|
||||
() -> QueryFormDecoder.decode("%ZZ", StandardCharsets.UTF_8, ctx));
|
||||
assertEquals(status, error.getResponse().getStatus());
|
||||
assertEquals("application/xml", error.getResponse().getMediaType().toString());
|
||||
verify(ctx, never()).getEntityStream();
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,27 @@ class RequestResourceMembersTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedResourceTagKeysValidateTheirPrefixesAndResourceTypes() throws Exception {
|
||||
assertEquals(List.of("aws:ResourceTag/", "ec2:ResourceTag/"),
|
||||
RequestResourceMembers.table().resourceTagKeys().get("ec2").get("instance"));
|
||||
ObjectNode document = (ObjectNode) MAPPER.readTree("""
|
||||
{"namespaces":{"example":["example"]},"arnFormats":{"example":{
|
||||
"thing":"arn:${Partition}:example:${Region}:${Account}:thing/${ThingId}"}},
|
||||
"resourceTagKeys":{"example":{"thing":["vendor:ResourceTag/"]}},
|
||||
"operations":{"example:Read":{"resources":[]}}}
|
||||
""");
|
||||
assertEquals(List.of("vendor:ResourceTag/"),
|
||||
parse(document.toString()).resourceTagKeys().get("example").get("thing"));
|
||||
for (String invalid : List.of("{\"missing\":[\"vendor:ResourceTag/\"]}",
|
||||
"{\"thing\":\"vendor:ResourceTag/\"}", "{\"thing\":[\"vendor:ResourceTag\"]}",
|
||||
"{\"thing\":[\"vendor:ResourceTag/\",\"vendor:ResourceTag/\"]}")) {
|
||||
ObjectNode changed = document.deepCopy();
|
||||
((ObjectNode) changed.path("resourceTagKeys")).set("example", MAPPER.readTree(invalid));
|
||||
assertThrows(IllegalStateException.class, () -> parse(changed.toString()), invalid);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTableReadsItsNamespacesAndGivesEachTypeItNamesAnArnFormat() {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
|
||||
@@ -128,7 +128,10 @@ class RequestResourcesTest {
|
||||
assertEquals(List.of(), of(operation, json("{\"Resources\":\"i-one\"}")));
|
||||
}
|
||||
assertFalse(RequestResources.hasIndividualTargets("ec2:DescribeInstances"));
|
||||
assertEquals(List.of(), RequestResources.ofBody("ec2:TerminateInstances",
|
||||
assertEquals(List.of(instance), RequestResources.ofBody("ec2:TerminateInstances",
|
||||
new ObjectMapper().readTree("{\"InstanceIds\":[\"i-one\"]}"), "aws", "us-east-1",
|
||||
"000000000000", null));
|
||||
assertEquals(List.of(), RequestResources.ofBody("ec2:DescribeInstances",
|
||||
new ObjectMapper().readTree("{\"InstanceIds\":[\"i-one\"]}"), "aws", "us-east-1",
|
||||
"000000000000", null));
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.ext.web.RoutingContext;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
@@ -49,6 +50,7 @@ import java.util.Optional;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
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.Mockito.clearInvocations;
|
||||
@@ -683,6 +685,32 @@ class ResourceArnBuilderTest {
|
||||
builder.buildResources("ec2", "ec2:CreateTags", ctx, "us-east-1", ACCOUNT, "aws"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"StartInstances,aws-cn,cn-north-1", "StopInstances,aws-us-gov,us-gov-west-1",
|
||||
"RebootInstances,aws-cn,cn-north-1", "TerminateInstances,aws-us-gov,us-gov-west-1"})
|
||||
void instanceLifecycleTargetsUseOnlyTheHandlersInstanceIds(String operation, String partition, String region) {
|
||||
queryParams.add("InstanceId.1", "i-query-decoy");
|
||||
setFormBody("Action=" + operation + "&InstanceId.1=i-first&InstanceId.1=i-duplicate"
|
||||
+ "&InstanceId.2=i-second&InstanceId.3=i-first&InstanceId.5=i-gap&ResourceId.1=i-decoy");
|
||||
String prefix = "arn:" + partition + ":ec2:" + region + ":111122223333:instance/";
|
||||
assertEquals(List.of(prefix + "i-first", prefix + "i-second", prefix + "i-first"),
|
||||
builder.buildResources("ec2", "ec2:" + operation, ctx, region, "111122223333", partition));
|
||||
setFormBody("Action=" + operation + "&InstanceId.2=i-gap&ResourceId.1=i-decoy");
|
||||
assertEquals(List.of("*"),
|
||||
builder.buildResources("ec2", "ec2:" + operation, ctx, region, "111122223333", partition));
|
||||
when(ctx.getMethod()).thenReturn("GET");
|
||||
contextProperties.put(AwsProtocolClaimFilter.CLAIM_PROPERTY,
|
||||
new ProtocolClaim(WireProtocol.AWS_QUERY, null, operation, null));
|
||||
queryParams.clear();
|
||||
queryParams.add("Action", operation);
|
||||
queryParams.add("InstanceId.1", "i-first");
|
||||
queryParams.add("InstanceId.1", "i-decoy");
|
||||
queryParams.add("InstanceId.2", "i-second");
|
||||
queryParams.add("InstanceId.4", "i-gap");
|
||||
assertEquals(List.of(prefix + "i-first", prefix + "i-second"),
|
||||
builder.buildResources("ec2", "ec2:" + operation, ctx, region, "111122223333", partition));
|
||||
}
|
||||
|
||||
@Test
|
||||
void largeTagBatchReusesTheDecodedFormAndLeavesTheBodyForTheHandler() throws IOException {
|
||||
StringBuilder form = new StringBuilder("Action=CreateTags");
|
||||
@@ -986,10 +1014,10 @@ class ResourceArnBuilderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void stsMalformedRoleArnIsAuthorizedAsNoRole() {
|
||||
// Read as absent, so the request reaches the form reader, which refuses it as it does today.
|
||||
void stsMalformedRoleEncodingIsRejectedBeforeWildcardAuthorization() {
|
||||
setFormBody("Action=AssumeRole&Version=2011-06-15&RoleArn=arn%3Aaws%ZZ&RoleSessionName=robin");
|
||||
assertEquals("*", sts("sts:AssumeRole"));
|
||||
WebApplicationException error = assertThrows(WebApplicationException.class, () -> sts("sts:AssumeRole"));
|
||||
assertEquals(404, error.getResponse().getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+191
@@ -5,6 +5,7 @@ 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.floci.aws.testutil.AwsRequestSigner;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -12,6 +13,7 @@ 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 org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.awscore.exception.AwsServiceException;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
@@ -25,6 +27,10 @@ import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.isEmptyOrNullString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -232,6 +238,191 @@ class ResourceResolutionEnforcementIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"ec2:ResourceTag", "aws:ResourceTag", "exact-arn"})
|
||||
void instanceLifecyclePermissionsAllowOnlyTheDevelopmentInstance(String scope) {
|
||||
try (Ec2Client admin = ec2Admin()) {
|
||||
String development = instance(admin);
|
||||
String production = instance(admin);
|
||||
String untagged = instance(admin);
|
||||
admin.createTags(r -> r.resources(development).tags(tag("Env", "development")));
|
||||
admin.createTags(r -> r.resources(production).tags(tag("Env", "production")));
|
||||
String resource = "exact-arn".equals(scope) ? instanceArn(development) : "*";
|
||||
String condition = "exact-arn".equals(scope) ? "" :
|
||||
",\"Condition\":{\"StringEquals\":{\"" + scope + "/Env\":\"development\"}}";
|
||||
UserCredentials keys = lifecycleGroupUser(policy(lifecycleAllow(resource, condition)));
|
||||
try (Ec2Client caller = ec2Caller(keys)) {
|
||||
caller.stopInstances(r -> r.instanceIds(development));
|
||||
assertState(admin, development, "stopped");
|
||||
caller.startInstances(r -> r.instanceIds(development));
|
||||
assertState(admin, development, "running");
|
||||
for (String blocked : List.of(production, untagged)) {
|
||||
for (List<String> targets : List.of(List.of(blocked), List.of(development, blocked),
|
||||
List.of(blocked, development))) {
|
||||
denied(() -> caller.stopInstances(r -> r.instanceIds(targets)));
|
||||
assertState(admin, development, "running");
|
||||
assertState(admin, blocked, "running");
|
||||
admin.stopInstances(r -> r.instanceIds(development, blocked));
|
||||
denied(() -> caller.startInstances(r -> r.instanceIds(targets)));
|
||||
assertState(admin, development, "stopped");
|
||||
assertState(admin, blocked, "stopped");
|
||||
admin.startInstances(r -> r.instanceIds(development, blocked));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceLifecycleBatchesPairEachArnWithItsOwnTags() {
|
||||
try (Ec2Client admin = ec2Admin()) {
|
||||
String first = instance(admin);
|
||||
String second = instance(admin);
|
||||
admin.createTags(r -> r.resources(first).tags(tag("Env", "first")));
|
||||
admin.createTags(r -> r.resources(second).tags(tag("Env", "second")));
|
||||
String statements = lifecycleAllow(instanceArn(first),
|
||||
",\"Condition\":{\"StringEquals\":{\"ec2:ResourceTag/Env\":\"first\"}}") + ","
|
||||
+ lifecycleAllow(instanceArn(second),
|
||||
",\"Condition\":{\"StringEquals\":{\"ec2:ResourceTag/Env\":\"second\"}}");
|
||||
try (Ec2Client caller = ec2Caller(lifecycleGroupUser(policy(statements)))) {
|
||||
caller.stopInstances(r -> r.instanceIds(first, second, first));
|
||||
assertState(admin, first, "stopped");
|
||||
assertState(admin, second, "stopped");
|
||||
caller.startInstances(r -> r.instanceIds(second, first, second));
|
||||
assertState(admin, first, "running");
|
||||
assertState(admin, second, "running");
|
||||
admin.createTags(r -> r.resources(second).tags(tag("Env", "first")));
|
||||
denied(() -> caller.stopInstances(r -> r.instanceIds(first, second)));
|
||||
assertState(admin, first, "running");
|
||||
assertState(admin, second, "running");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupExplicitDenyBlocksInstanceLifecycleBeforeAnyMutation() {
|
||||
try (Ec2Client admin = ec2Admin()) {
|
||||
String first = instance(admin);
|
||||
String second = instance(admin);
|
||||
String statements = lifecycleAllow("*", "") + "," + """
|
||||
{"Effect":"Deny","Action":["ec2:StartInstances","ec2:StopInstances"],"Resource":"%s"}
|
||||
""".formatted(instanceArn(second));
|
||||
try (Ec2Client caller = ec2Caller(lifecycleGroupUser(policy(statements)))) {
|
||||
denied(() -> caller.stopInstances(r -> r.instanceIds(first, second)));
|
||||
assertState(admin, first, "running");
|
||||
assertState(admin, second, "running");
|
||||
admin.stopInstances(r -> r.instanceIds(first, second));
|
||||
denied(() -> caller.startInstances(r -> r.instanceIds(second, first)));
|
||||
assertState(admin, first, "stopped");
|
||||
assertState(admin, second, "stopped");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"RebootInstances", "TerminateInstances"})
|
||||
void generatedLifecycleActionsHonorInstanceTagsAndExplicitDeny(String operation) {
|
||||
try (Ec2Client admin = ec2Admin()) {
|
||||
String development = instance(admin);
|
||||
String production = instance(admin);
|
||||
admin.createTags(r -> r.resources(development).tags(tag("Env", "development")));
|
||||
admin.createTags(r -> r.resources(production).tags(tag("Env", "development")));
|
||||
String statements = """
|
||||
{"Effect":"Allow","Action":"ec2:%s","Resource":"*",
|
||||
"Condition":{"StringEquals":{"ec2:ResourceTag/Env":"development"}}},
|
||||
{"Effect":"Deny","Action":"ec2:%s","Resource":"%s"}
|
||||
""".formatted(operation, operation, instanceArn(production));
|
||||
try (Ec2Client caller = ec2Caller(lifecycleGroupUser(policy(statements)))) {
|
||||
for (List<String> targets : List.of(List.of(development, production),
|
||||
List.of(production, development))) {
|
||||
denied(() -> invokeLifecycle(caller, operation, targets));
|
||||
assertState(admin, development, "running");
|
||||
assertState(admin, production, "running");
|
||||
}
|
||||
admin.deleteTags(r -> r.resources(development).tags(tag("Env", null)));
|
||||
denied(() -> invokeLifecycle(caller, operation, List.of(development)));
|
||||
assertState(admin, development, "running");
|
||||
admin.createTags(r -> r.resources(development).tags(tag("Env", "development")));
|
||||
invokeLifecycle(caller, operation, List.of(development));
|
||||
assertState(admin, development, "TerminateInstances".equals(operation) ? "terminated" : "running");
|
||||
assertState(admin, production, "running");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void invokeLifecycle(Ec2Client client, String operation, List<String> ids) {
|
||||
if ("TerminateInstances".equals(operation)) {
|
||||
client.terminateInstances(r -> r.instanceIds(ids));
|
||||
} else {
|
||||
client.rebootInstances(r -> r.instanceIds(ids));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"StartInstances", "StopInstances"})
|
||||
void malformedLifecycleFormsReturnClientErrorsBeforeAnyMutation(String operation) {
|
||||
try (Ec2Client admin = ec2Admin()) {
|
||||
String id = instance(admin);
|
||||
boolean starting = "StartInstances".equals(operation);
|
||||
if (starting) {
|
||||
admin.stopInstances(r -> r.instanceIds(id));
|
||||
}
|
||||
String originalState = starting ? "stopped" : "running";
|
||||
UserCredentials keys = lifecycleGroupUser(policy(lifecycleAllow("*", "")));
|
||||
AwsRequestSigner signer = AwsRequestSigner.signedAs(keys.accessKeyId(), keys.secretAccessKey(), "ec2");
|
||||
String prefix = "Action=" + operation + "&Version=2016-11-15&";
|
||||
for (String malformed : List.of("InstanceId.1=%ZZ", "InstanceId.1=%", "InstanceId.1=%A",
|
||||
"InstanceId.1=" + id + "&InstanceId.2=%ZZ", "InstanceId.1=" + id + "&%ZZ=value")) {
|
||||
given().filter(signer).contentType("application/x-www-form-urlencoded")
|
||||
.body(prefix + malformed)
|
||||
.post("/").then().statusCode(404).contentType("application/xml")
|
||||
.body("Response.Errors.Error.Code", equalTo("MalformedQueryString"))
|
||||
.body("Response.RequestID", not(isEmptyOrNullString()));
|
||||
assertState(admin, id, originalState);
|
||||
}
|
||||
given().filter(signer).contentType("application/x-www-form-urlencoded")
|
||||
.body(prefix + "InstanceId.1=" + id + "&Extra=%25ZZ")
|
||||
.post("/").then().statusCode(200);
|
||||
assertState(admin, id, starting ? "running" : "stopped");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedAssumeRoleEncodingReturnsAQueryClientError() {
|
||||
UserCredentials keys = user("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"sts:AssumeRole","Resource":"*"}]}
|
||||
""");
|
||||
given().filter(AwsRequestSigner.signedAs(keys.accessKeyId(), keys.secretAccessKey(), "sts"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.body("Action=AssumeRole&Version=2011-06-15&RoleArn=arn%3Aaws%ZZ&RoleSessionName=repro")
|
||||
.post("/").then().statusCode(404).contentType("application/xml")
|
||||
.body("ErrorResponse.Error.Code", equalTo("MalformedQueryString"));
|
||||
}
|
||||
|
||||
private UserCredentials lifecycleGroupUser(String policy) {
|
||||
String name = "lifecycle-" + suffix();
|
||||
UserCredentials keys = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT, "iam"), name);
|
||||
try (IamClient admin = AwsTestClients.create(IamClient.builder(), ACCOUNT, Region.US_EAST_1)) {
|
||||
admin.createGroup(r -> r.groupName(name));
|
||||
cleanup.register(() -> EnforcementFixtures.removeGroup(baseUri.getPort(), auth(ACCOUNT, "iam"), name));
|
||||
admin.putGroupPolicy(r -> r.groupName(name).policyName("lifecycle").policyDocument(policy));
|
||||
admin.addUserToGroup(r -> r.groupName(name).userName(name));
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
private static String lifecycleAllow(String resource, String condition) {
|
||||
return """
|
||||
{"Effect":"Allow","Action":["ec2:StartInstances","ec2:StopInstances"],"Resource":"%s"%s}
|
||||
""".formatted(resource, condition);
|
||||
}
|
||||
|
||||
private static void assertState(Ec2Client admin, String id, String expected) {
|
||||
assertEquals(expected, admin.describeInstances(r -> r.instanceIds(id)).reservations().getFirst()
|
||||
.instances().getFirst().state().nameAsString());
|
||||
}
|
||||
|
||||
private UserCredentials user(String policy) {
|
||||
String name = "resource-reader-" + suffix();
|
||||
UserCredentials keys = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT, "iam"), name);
|
||||
|
||||
@@ -364,7 +364,8 @@ class StsPresignedSignatureIntegrationTest {
|
||||
void malformedFormCannotEscapeAsServerError(String body) throws Exception {
|
||||
URI uri = presignRequest("test", "test", "POST", "/", "iam", body, new TreeMap<>(), null);
|
||||
given().urlEncodingEnabled(false).contentType("application/x-www-form-urlencoded").body(body).post(uri)
|
||||
.then().statusCode(400);
|
||||
.then().statusCode(404).contentType("application/xml")
|
||||
.body("ErrorResponse.Error.Code", equalTo("MalformedQueryString"));
|
||||
}
|
||||
|
||||
private static URI presign(String key, String secret, String body, TreeMap<String, String> query) throws Exception {
|
||||
|
||||
@@ -92,9 +92,10 @@ 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` stages heterogeneous id-list namespaces separately: botocore supplies the list member
|
||||
and its serialized EC2 Query name (including queryName and capitalization), and documented id
|
||||
prefixes distinguish the supported resource types. Each generated `targets` entry preserves the
|
||||
`ID_TARGETS` stages id-list namespaces separately: a resource ARN's variable names its list member,
|
||||
with the configured heterogeneous resource list as a fallback. Botocore supplies its serialized
|
||||
EC2 Query name (including queryName and capitalization), and documented id prefixes distinguish
|
||||
the supported resource types. `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 `*`.
|
||||
`CORRECTIONS` gives an operation's resources where the rule gets them wrong, each with its reason; a
|
||||
@@ -651,8 +652,8 @@ KNOWN_VARIABLES = {"Partition", "Region", "Account"}
|
||||
# A staged read of heterogeneous resource-id lists. The model supplies the member and its wire name;
|
||||
# the Service Reference supplies the action's types and their ARN formats. EC2 documents instance ids
|
||||
# with the i- prefix (EC2 User Guide, resource-ids). Only instances are covered here: other ids retain
|
||||
# a wildcard entry, and other EC2 requests retain their existing wildcard authorization until their
|
||||
# ARN resolution and condition contexts have coverage. No operation names select this read.
|
||||
# a wildcard entry. Lists named by their resource ARN variable and heterogeneous Resources lists
|
||||
# share this reader and its generated condition contexts; requests without those lists stay unchanged.
|
||||
ID_TARGETS = {"ec2": {"member": "Resources", "prefixes": {"instance": "i-"}}}
|
||||
# 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}:")
|
||||
@@ -716,6 +717,20 @@ def checked_actions(documents: list[dict]) -> dict[str, dict]:
|
||||
return found
|
||||
|
||||
|
||||
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."""
|
||||
result = {}
|
||||
for document in documents:
|
||||
namespace = document["Name"]
|
||||
supported = ID_TARGETS.get(namespace, {}).get("prefixes", {})
|
||||
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}
|
||||
if types:
|
||||
result[namespace] = dict(sorted(types.items()))
|
||||
return dict(sorted(result.items()))
|
||||
|
||||
|
||||
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)."""
|
||||
@@ -1411,7 +1426,7 @@ def names_type(member: str, kind_stem: str) -> bool:
|
||||
# The vendored document
|
||||
# --------------------------------------------------------------------------- #
|
||||
def id_targets(operation: str, types: list[str], formats: dict[str, str], models: dict[str, dict]) -> dict | None:
|
||||
"""A heterogeneous id list, in model and EC2 Query spelling, with each supported type's discriminator."""
|
||||
"""An id list, in model and EC2 Query spelling, with each supported type's discriminator."""
|
||||
configured = ID_TARGETS.get(namespace_of(operation))
|
||||
if configured is None:
|
||||
return None
|
||||
@@ -1420,7 +1435,16 @@ def id_targets(operation: str, types: list[str], formats: dict[str, str], models
|
||||
spec = model["operations"].get(operation.split(":", 1)[1], {})
|
||||
if "input" not in spec or "ec2" not in _protocols(model):
|
||||
continue
|
||||
member = model["shapes"][spec["input"]["shape"]].get("members", {}).get(configured["member"])
|
||||
members = model["shapes"][spec["input"]["shape"]].get("members", {})
|
||||
variables = {variable for kind in configured["prefixes"] if kind in types and kind in formats
|
||||
for variable in set(VARIABLE_RE.findall(formats[kind])) - KNOWN_VARIABLES}
|
||||
candidates = [name for name, member in members.items()
|
||||
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}")
|
||||
member_name = candidates[0] if candidates else configured["member"]
|
||||
member = members.get(member_name)
|
||||
if member is None or _strings(model, model["shapes"][member["shape"]]) != "[]":
|
||||
continue
|
||||
prefixes = {kind: prefix for kind, prefix in configured["prefixes"].items()
|
||||
@@ -1431,9 +1455,9 @@ def id_targets(operation: str, types: list[str], formats: dict[str, str], models
|
||||
variables = set(VARIABLE_RE.findall(formats[kind])) - KNOWN_VARIABLES
|
||||
if len(variables) != 1:
|
||||
raise ValueError(f"{operation}: id target {kind} must have exactly one ARN variable")
|
||||
location = member.get("locationName", configured["member"])
|
||||
location = member.get("locationName", member_name)
|
||||
query = member.get("queryName", location[:1].upper() + location[1:])
|
||||
target = {"member": configured["member"] + "[]", "query": query, "prefixes": prefixes}
|
||||
target = {"member": member_name + "[]", "query": query, "prefixes": prefixes}
|
||||
if found is not None and found != target:
|
||||
raise ValueError(f"{operation}: clients disagree on the id target's serialization")
|
||||
found = target
|
||||
@@ -1617,6 +1641,7 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) ->
|
||||
if namespace not in NAMESPACES and namespace not in HAND_BUILT
|
||||
and namespace not in NOT_COVERED),
|
||||
"arnFormats": formats,
|
||||
"resourceTagKeys": resource_tag_keys(documents),
|
||||
"unqualified": unqualified,
|
||||
"mintedIds": minted,
|
||||
"operations": operations,
|
||||
@@ -1679,7 +1704,7 @@ def _check_overrides(covered: dict[str, dict]) -> None:
|
||||
def render(document: dict) -> str:
|
||||
"""The document with one operation to a line."""
|
||||
lines = ["{"]
|
||||
for key in ("_source", "namespaces", "clientsNotRead", "handBuilt", "notCovered", "otherNamespaces", "arnFormats",
|
||||
for key in ("_source", "namespaces", "clientsNotRead", "handBuilt", "notCovered", "otherNamespaces", "arnFormats", "resourceTagKeys",
|
||||
"unqualified", "mintedIds"):
|
||||
lines.append(f' "{key}": {json.dumps(document[key])},')
|
||||
lines.append(' "operations": {')
|
||||
@@ -1724,6 +1749,13 @@ def validate(document: dict) -> list[str]:
|
||||
return ["arnFormats is not an ARN format for each resource type of namespaces the file reads"]
|
||||
if list(operations) != sorted(operations):
|
||||
problems.append("operations is not sorted")
|
||||
tag_keys = document.get("resourceTagKeys", {})
|
||||
if not isinstance(tag_keys, dict) or any(
|
||||
not isinstance(kinds, dict) or any(kind not in formats.get(namespace, {})
|
||||
or not isinstance(keys, list) or not all(isinstance(key, str) for key in keys) or keys != sorted(set(keys))
|
||||
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")
|
||||
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, {})
|
||||
@@ -1986,6 +2018,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
print(f"error: could not read the Service Reference ({e})", file=sys.stderr)
|
||||
return 2
|
||||
untrue, added = verify_against(document, upstream, formats)
|
||||
if document.get("resourceTagKeys", {}) != resource_tag_keys(documents):
|
||||
untrue.append("resourceTagKeys differ from AWS Service Reference")
|
||||
for claim in untrue:
|
||||
print(f"error: {claim}", file=sys.stderr)
|
||||
if untrue:
|
||||
|
||||
@@ -1130,21 +1130,62 @@ def test_id_targets_follow_the_model_and_resource_types_not_operation_names():
|
||||
assert "targets" not in r.entry_for("ec2:AnnotateResources", upstream, formats, {"ec2": ec2})
|
||||
|
||||
|
||||
def test_generated_ec2_targets_match_botocores_actual_serialization():
|
||||
@pytest.mark.parametrize("operation,target", [(operation, entry["targets"])
|
||||
for operation, entry in json.loads(r.OUTPUT.read_text())["operations"].items() if "targets" in entry])
|
||||
def test_generated_targets_match_botocores_actual_serialization(operation, target):
|
||||
import botocore.session
|
||||
from botocore.serialize import create_serializer
|
||||
from botocore.utils import ArgumentGenerator
|
||||
|
||||
document = json.loads(r.OUTPUT.read_text())
|
||||
model = botocore.session.get_session().get_service_model("ec2")
|
||||
serializer = create_serializer("ec2")
|
||||
for name in ("CreateTags", "DeleteTags"):
|
||||
target = document["operations"]["ec2:" + name]["targets"]
|
||||
request = serializer.serialize_to_request(
|
||||
{"Resources": ["i-first", "vpc-second", "i-first"], "Tags": [{"Key": "Owner", "Value": "team+a"}]},
|
||||
model.operation_model(name))
|
||||
assert target["member"] == "Resources[]"
|
||||
assert [request["body"][target["query"] + "." + str(i)] for i in range(1, 4)] == ["i-first", "vpc-second", "i-first"]
|
||||
assert target["prefixes"] == {"instance": "i-"}
|
||||
namespace, name = operation.split(":", 1)
|
||||
first = next(iter(target["prefixes"].values())) + "first"
|
||||
ids = [first, "unmodelled-second", first]
|
||||
checked = 0
|
||||
for client in document["namespaces"][namespace]:
|
||||
model = botocore.session.get_session().get_service_model(client)
|
||||
if name not in model.operation_names:
|
||||
continue
|
||||
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)
|
||||
assert [request["body"][target["query"] + "." + str(i)] for i in range(1, 4)] == ids
|
||||
checked += 1
|
||||
assert checked > 0
|
||||
|
||||
|
||||
def test_instance_target_member_is_derived_from_the_arn_variable_not_the_action_name():
|
||||
names = ("StartInstances", "StopInstances", "RebootInstances", "TerminateInstances", "InventedAction")
|
||||
ec2 = model({name: {"InstanceIds": "Strings", "Resources": "Strings"} for name in names}, "ec2")
|
||||
formats = {"instance": "arn:${Partition}:ec2:${Region}:${Account}:instance/${InstanceId}"}
|
||||
for name in names:
|
||||
member = ec2["shapes"][name + "In"]["members"]["InstanceIds"]
|
||||
member["locationName"] = "instanceId"
|
||||
upstream = {"action": "ec2:" + name, "types": ["instance"]}
|
||||
entry = r.entry_for("ec2:" + name, upstream, formats, {"ec2": ec2})
|
||||
assert entry["targets"] == {"member": "InstanceIds[]", "query": "InstanceId", "prefixes": {"instance": "i-"}}
|
||||
member["queryName"] = "ExactWireName"
|
||||
assert r.entry_for("ec2:" + name, upstream, formats, {"ec2": ec2})["targets"]["query"] == "ExactWireName"
|
||||
# Unrelated lists cannot become instance targets, even with a familiar action name.
|
||||
del ec2["shapes"]["StartInstancesIn"]["members"]["InstanceIds"]
|
||||
del ec2["shapes"]["StartInstancesIn"]["members"]["Resources"]
|
||||
ec2["shapes"]["StartInstancesIn"]["members"]["DecoyInstanceIds"] = {"shape": "Strings"}
|
||||
assert "targets" not in r.entry_for("ec2:StartInstances",
|
||||
{"action": "ec2:StartInstances", "types": ["instance"]}, formats, {"ec2": ec2})
|
||||
renamed = model({"InventedAction": {"MachineIds": "Strings"}}, "ec2")
|
||||
renamed_formats = {"instance": "arn:${Partition}:ec2:${Region}:${Account}:instance/${MachineId}"}
|
||||
assert r.entry_for("ec2:InventedAction", {"action": "ec2:InventedAction", "types": ["instance"]},
|
||||
renamed_formats, {"ec2": renamed})["targets"]["member"] == "MachineIds[]"
|
||||
|
||||
|
||||
def test_resource_tag_prefixes_come_only_from_supported_reference_resources():
|
||||
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/"]}}
|
||||
assert r.resource_tag_keys([]) == {}
|
||||
|
||||
|
||||
def test_id_targets_reject_unknown_types_ambiguous_prefixes_and_malformed_members():
|
||||
|
||||
Reference in new issue
Block a user