fix(ecs): check ECS requests on the resources they name, from the generated request resources (#8341)

ECS was not read by the request-resources generator, so under IAM enforcement
every ECS request was checked on *: a grant scoped to a cluster, service or
task definition was refused, and a deny scoped to one never applied. ecs now
moves into NAMESPACES, and where the rules misread it the rule is fixed:

- a member whose documentation spells a type of two variables as its format
  does ("(family:revision)" for a task definition) is found by its service,
  each element of a list, rather than read as an ARN alone;
- a member documented as naming its service's default when left out ("If you
  do not specify a cluster, the default cluster is assumed") names it
  (defaults), rather than naming nothing;
- a member documented as a name or an ARN of another type, in either order or
  naming the type before them, reads that type's ARN (arnOf), as a pattern
  taking one does;
- a list element's id field beside an enum field holding the target's type,
  whose one value is the action's type, fills that type's last variable
  (PutAttributes' attributes[].targetId).

The reader fills a defaults member from the default the service gives, finds
each value of one list member, and names a resource given by its own full ARN
for a type of several variables too, also giving the variable that ARN's value
beside the request's other members, as a handler may read either. EcsService
answers the lookups, reading only: the revision a reference the table finds
resolves to, and the default cluster. It now mints a service's deployments
and revisions under the service, as AWS does.

The ECS task arms of Step Functions now take the action from
IamAuthorizedActions and the resources from RequestResources.ofBody, as the
EMR arm does, so a service, cluster or task definition ECS does not have is
checked on the ARN the request names, as the direct call is.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-14 16:01:34 -04:00
1 parent e286aef015
commit 6305250206
14 files changed
+1088 -184

No files matched your search

+16
View File
@@ -907,6 +907,22 @@ with `maxResults` (1 to 100) and `nextToken`.
| `SubmitAttachmentStateChanges` | Agent callback stub |
| `DiscoverPollEndpoint` | Returns the agent polling endpoint |
## IAM Enforcement
With IAM enforcement on, each ECS request is checked on the resources it names, from the generated request
resources: a cluster, service, task, container instance, task set or capacity provider by its name or its ARN; a
service, task or container instance in the request's `cluster`, given by name or ARN, or in the `default` cluster
when the request names none, as ECS does; an attribute on the container instance its `targetId` names; a service
deployment or revision by its ARN, which Floci mints under its service as AWS does
(`service-deployment/<cluster>/<service>/<id>`); and a task definition as the revision ECS resolves its reference to, a
family alone being its latest revision, so `web`, `web:3` and the revision's ARN are the same resource. A service or
task given by its ARN is checked on that ARN and, when the request's cluster is another, on the one of its name in
that cluster too, which `UpdateService` acts on. A task definition ECS does not have is checked on any revision,
`task-definition/*:*`. An operation whose action has no
resource type in the Service Authorization Reference (`ListClusters`, `ListServices`, `DescribeTaskDefinition`,
`DeregisterTaskDefinition`, the account settings) is checked on `*`. The roles a request passes are checked as
`iam:PassRole` and the tags it sets as `ecs:TagResource`.
## Configuration
Every `awsvpc` task receives an ENI in its subnet. With `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED=true`, a Docker-backed task's containers additionally share one protected network namespace built around that ENI, and packets are filtered against its security groups. A task without explicit security groups uses its subnet VPC's default group. Containers in the same task can communicate over localhost. Bridge and host task networking do not attach task-level `awsvpc` security groups. Mock mode reports control-plane state, including the ENI, and does not enforce packet filtering.
+10 -7
View File
@@ -716,9 +716,9 @@ and resource type comes from the Service Authorization Reference:
| Resource | Action | Resource evaluated | Refused with |
|---|---|---|---|
| `arn:aws:states:::ecs:runTask`, with `.sync` or `.waitForTaskToken` | `ecs:RunTask` | The task definition revision the task would run | `ECS.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:ecs:updateService` | `ecs:UpdateService` | The service it acts on | `Ecs.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:ecs:describeServices` | `ecs:DescribeServices` | Each service it answers for | `Ecs.AccessDeniedException` |
| `arn:aws:states:::ecs:runTask`, with `.sync` or `.waitForTaskToken` | `ecs:RunTask` | The task definition revision ECS resolves `TaskDefinition` to | `ECS.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:ecs:updateService` | `ecs:UpdateService` | The service the request names | `Ecs.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:ecs:describeServices` | `ecs:DescribeServices` | Each service the request names | `Ecs.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:ecs:listServices` | `ecs:ListServices` | `*` | `Ecs.AccessDeniedException` |
| `arn:aws:states:::elasticmapreduce:createCluster`, `.sync` | `elasticmapreduce:RunJobFlow` | `*` | `EMR.AccessDeniedException` |
| `arn:aws:states:::elasticmapreduce:setClusterTerminationProtection` | `elasticmapreduce:SetTerminationProtection` | `cluster/<ClusterId>` | `EMR.AccessDeniedException` |
@@ -736,9 +736,12 @@ A task definition is evaluated as the revision it resolves to, so a bare family,
the ARN give the same resource: `task-definition/<family>:<revision>`. A role allowed only an older
revision is refused a bare family whose latest revision is newer.
The ECS services are resolved as ECS resolves them. `updateService` acts on the service of that name in
the request's `Cluster`, or in `default` with none, whatever cluster a service ARN in the request
names, and that is the service evaluated.
The ECS APIs are checked as the same call made directly is, from the generated request resources: a
service is the one of that name in the request's `Cluster`, given by name or ARN, or in `default` with
none, which `updateService` acts on, and a service ARN is evaluated as given as well, so one of another
cluster than the request's needs the action on both. A task definition ECS does not have is evaluated on any
revision, `task-definition/*:*`, and a service or cluster it does not have on the ARN the request
names, so a role allowed nothing is refused before ECS answers.
A ByName API needs its `List` action as well as its `Modify` one, since it reads the cluster's fleets or
groups to find the id. Nothing documents this for a task: it is inferred from what the integration
@@ -757,7 +760,7 @@ for the `Tags` they send, on the application a create makes or the one a job run
tag as `aws:RequestTag/<key>` and the keys as `aws:TagKeys`, which the API's own action is checked with too.
A request naming nothing it can reach has only the role checks, and its service answers it: no
`TaskDefinition` or one ECS does not have, a service or cluster ECS does not have, no `ClusterId`, no
`TaskDefinition`, no `ClusterId`, no
`ApplicationId`, or a `cancelJobRun` without `JobRunId`. A form an integration does not serve keeps
its answer: `.waitForTaskToken` on EMR and EMR Serverless and `.sync` on an EMR API with no wait are
"Unsupported" whether or not enforcement is on, and so is any API Floci does not have.
@@ -58,7 +58,7 @@ final class RequestResourceMembers {
private static final Set<String> ARN_KEYS = Set.of("types", "arn", "made", "endpoint");
/** The keys of a resource whose format's variables members fill, or its service finds by them. */
private static final Set<String> FILL_KEYS = Set.of("type", "fill", "when", "unless", "arnOf", "account", "fixed",
"made", "find", "endpoint", "default", "whenDefault", "unlessDefault");
"made", "find", "endpoint", "default", "whenDefault", "unlessDefault", "defaults");
/** The keys of a resource named through a member naming another of its service's own: it is read no other way. */
private static final Set<String> THROUGH_KEYS = Set.of("types", "through", "when", "endpoint");
/** The keys of a resource its service acts on for a request naming none of it: it is read no other way. */
@@ -132,6 +132,27 @@ final class RequestResourceMembers {
String resource = format.split(":", 6)[5];
return AwsArnUtils.parse(arn).resource().substring(resource.indexOf("${"));
}
/**
* The value {@code variable} takes in an ARN of the format, by the text the format puts around each variable
* ({@code api} for {@code ServiceName} in {@code service/blue/api}); null when the ARN does not match.
*/
String variable(String arn, String variable) {
String resource = format.split(":", 6)[5];
Matcher each = VARIABLE.matcher(resource);
StringBuilder regex = new StringBuilder("^");
List<String> names = new ArrayList<>();
int at = 0;
while (each.find()) {
regex.append(Pattern.quote(resource.substring(at, each.start()))).append("(.+?)");
names.add(each.group(1));
at = each.end();
}
regex.append(Pattern.quote(resource.substring(at))).append('$');
Matcher matched = Pattern.compile(regex.toString()).matcher(AwsArnUtils.parse(arn).resource());
int index = names.indexOf(variable);
return matched.matches() && index >= 0 ? matched.group(index + 1) : null;
}
}
/**
@@ -162,12 +183,25 @@ final class RequestResourceMembers {
* {@code Search} with no {@code ViewArn}, on the Region's default view), read no other way. Of two types whose
* formats differ by one variable a member fills, the one without it applies {@code whenDefault} that member is
* absent or names its type's default resource, which the service gives, and the other {@code unlessDefault}: a
* rule on EventBridge's default bus has no bus in its ARN. Each maps the member to that type.
* rule on EventBridge's default bus has no bus in its ARN. Each maps the member to that type. A member filling a
* variable that is the one of another type's format names that type's default when the request leaves it out
* ({@code defaults}, the member mapped to the type), which the service gives: an ECS service of a request with no
* {@code cluster} is on the default cluster. One member of {@code find} may be a list, each of whose values the
* service finds (ECS's {@code taskDefinitions[]}).
*/
record Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
Map<String, String> fixed, boolean made, List<Member> find, String endpoint, Member through,
boolean byDefault, Map<String, String> whenDefault, Map<String, String> unlessDefault) {
boolean byDefault, Map<String, String> whenDefault, Map<String, String> unlessDefault,
Map<String, String> defaults) {
Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
Map<String, String> fixed, boolean made, List<Member> find, String endpoint, Member through,
boolean byDefault, Map<String, String> whenDefault, Map<String, String> unlessDefault) {
this(types, arn, fill, when, unless, arnOf, account, fixed, made, find, endpoint, through, byDefault,
whenDefault, unlessDefault, Map.of());
}
Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
@@ -517,9 +551,11 @@ final class RequestResourceMembers {
find.add(member(operation, member.asText("")));
}
if (resource.has("find") && (!resource.path("find").isArray() || find.isEmpty() || !fill.isEmpty()
|| find.stream().anyMatch(Member::list) || FOUND_ONLY.stream().anyMatch(resource::has))) {
|| (find.size() > 1 && find.stream().anyMatch(Member::list))
|| FOUND_ONLY.stream().anyMatch(resource::has))) {
throw new IllegalStateException(RESOURCE_NAME + " finds a " + type + " for " + operation + " by "
+ resource.path("find") + ", no members of one value each, or beside members reading it otherwise");
+ resource.path("find") + ", no members of one value each or one list, or beside members reading "
+ "it otherwise");
}
if (fill.values().stream().filter(member -> member.list() || member.map()).count() > 1) {
throw new IllegalStateException(RESOURCE_NAME + " fills " + type + " for " + operation
@@ -557,7 +593,36 @@ final class RequestResourceMembers {
+ " from " + account.name() + ", no member of one account or a type of none");
}
return new Resource(List.of(type), null, Map.copyOf(fill), when, unless, Map.copyOf(arnOf), account,
Map.copyOf(fixed), made, List.copyOf(find), endpoint, null, byDefault, whenDefault, unlessDefault);
Map.copyOf(fixed), made, List.copyOf(find), endpoint, null, byDefault, whenDefault, unlessDefault,
defaults(operation, type, resource.path("defaults"), fill, formats));
}
/**
* The {@code defaults} of a resource: each member filling a variable mapped to the type whose format is that
* variable alone, whose default the member names when a request leaves it out; empty when it has none.
*/
private static Map<String, String> defaults(String operation, String type, JsonNode defaults,
Map<String, Member> fill, Map<String, ArnFormat> formats) {
if (defaults.isMissingNode()) {
return Map.of();
}
Map<String, String> found = new LinkedHashMap<>();
defaults.properties().forEach(entry -> {
ArnFormat named = formats.get(entry.getValue().asText(""));
String variable = fill.entrySet().stream().filter(filled -> filled.getValue().path().equals(entry.getKey()))
.map(Map.Entry::getKey).findFirst().orElse(null);
if (named == null || variable == null || !ONE_VARIABLE.matcher(named.format().split(":", 6)[5]).matches()
|| !named.format().endsWith("${" + variable + "}")) {
throw new IllegalStateException(RESOURCE_NAME + " names the default of " + entry.getValue() + " by "
+ entry.getKey() + " for " + operation + "'s " + type
+ ", no member filling the one variable of that type's format");
}
found.put(entry.getKey(), entry.getValue().asText());
});
if (found.isEmpty()) {
throw new IllegalStateException(RESOURCE_NAME + " names no defaults for " + operation + "'s " + type);
}
return Map.copyOf(found);
}
/**
@@ -595,7 +595,9 @@ public final class RequestResources {
* The ARNs of a type the request names through the variables it fills: one for each value of a list member,
* none when it gives none of them. A value that is itself an ARN of the type names that resource, and the others
* in the same list their own, as a handler taking a name or an ARN for each reads them (CodeBuild's
* {@code BatchGetProjects}). They are in the account the resource's account member gives, which its handler
* {@code BatchGetProjects}); for a type of several variables it also gives the variable it fills its own value
* there, beside what the request's other members fill, as a handler may read the one or the other (an ECS
* service ARN of another cluster than the request's names that service and the one of its name in that cluster). They are in the account the resource's account member gives, which its handler
* acts in, and none when that member holds no account id; in the request's without one, or with a JSON null for
* it. An ARN given for a name puts the
* resource in that ARN's account and Region, the caller's and the request's where it leaves them empty, as its
@@ -608,7 +610,9 @@ public final class RequestResources {
* the type without a qualifier, is cut where the format ends, as an ARN given is. A variable no member fills
* takes the value the resource gives it {@code fixed}. A type
* whose service mints an id after its name is the caller's resource {@code stored} finds under that name, or
* else has that id open.
* else has that id open. A member the request leaves out that names its service's default of another type
* ({@code defaults}) fills its variable from the ARN of that default, which {@code stored} gives in the caller's
* account: an ECS service a request names with no cluster is on the default cluster.
*/
private static void fill(Set<String> arns, RequestResourceMembers.Resource resource,
Map<String, RequestResourceMembers.ArnFormat> formats, Map<String, String> form,
@@ -638,17 +642,26 @@ public final class RequestResources {
stored.findDefault(resource.types().getFirst(), region).ifPresent(arns::add);
}
}
// A member the request leaves out naming its service's default of another type then fills the variable
// from that resource's ARN: an ECS service of a request with no cluster is on the default cluster.
String defaulted = resource.defaults().get(variable.getValue().path());
Optional<String> fallback = values.isEmpty() && defaulted != null && formats.containsKey(defaulted)
&& stored != null && account.equals(accountId) ? stored.findDefault(defaulted, region)
: Optional.empty();
if (fallback.isPresent()) {
values = List.of(fallback.get());
}
RequestResourceMembers.ArnFormat named = fallback.isPresent() ? formats.get(defaulted)
: arnOf(resource, variable.getValue().path(), formats);
if (values.isEmpty()) {
continue;
}
given = true;
RequestResourceMembers.ArnFormat named = arnOf(resource, variable.getValue().path(), formats);
if (resource.fill().size() == 1 && fromRequest == null) {
List<String> asArns = values.stream()
.filter(value -> !isArnOf(named, value)
&& format.pattern().matcher(value).matches()).toList();
asArns.forEach(value -> addNamed(arns, format.checked(value), format.awsOwned(), partition, region,
accountId, stored));
List<String> asArns = fromRequest != null ? List.of() : values.stream()
.filter(value -> !isArnOf(named, value) && format.pattern().matcher(value).matches()).toList();
asArns.forEach(value -> addNamed(arns, format.checked(value), format.awsOwned(), partition, region,
accountId, stored));
if (resource.fill().size() == 1) {
values = values.stream().filter(value -> !asArns.contains(value)).toList();
if (values.isEmpty()) {
return;
@@ -657,8 +670,14 @@ public final class RequestResources {
List<Filling> next = new ArrayList<>();
for (Filling filling : fillings) {
for (String value : values) {
// The type's own ARN, for a type of several variables, names that resource and gives this variable
// its value too, beside what the request's other members fill: a handler may read the one or the
// other (an ECS service ARN of another cluster than the request's).
next.add(isArnOf(named, value)
? filling.with(variable.getKey(), named.variable(value), AwsArnUtils.parse(value))
: asArns.contains(value)
? filling.with(variable.getKey(), format.variable(value, variable.getKey()),
AwsArnUtils.parse(value))
: filling.with(variable.getKey(), value, null));
}
}
@@ -731,12 +750,24 @@ public final class RequestResources {
* ({@code find}), when the request gives each one value: the caller's resource {@code stored} finds under those
* values in the Region, or else its ARN with that id open, as for a create; in the account its account member gives
* when it has one, which {@code stored} finds the resource of as {@code findInAccount}; none when it leaves one out
* or gives it a JSON null, which its handler reads as none.
* or gives it a JSON null, which its handler reads as none. A find by one list member finds each of its values
* (ECS's {@code taskDefinitions[]}).
*/
private static void found(Set<String> arns, RequestResourceMembers.Resource resource,
Map<String, RequestResourceMembers.ArnFormat> formats, Map<String, String> form,
JsonNode body, String partition, String region, String accountId,
StoredResourceArns stored) {
if (resource.find().size() == 1 && resource.find().getFirst().list()) {
String account = accountOf(resource, form, body, accountId);
if (account == null) {
return;
}
for (String value : values(form, body, resource.find().getFirst())) {
foundOne(arns, resource.types().getFirst(), List.of(value), formats, partition, region, account,
accountId, stored);
}
return;
}
List<String> names = new ArrayList<>();
for (RequestResourceMembers.Member member : resource.find()) {
List<String> values = values(form, body, member);
@@ -752,7 +783,13 @@ public final class RequestResources {
if (account == null) {
return;
}
String type = resource.types().getFirst();
foundOne(arns, resource.types().getFirst(), names, formats, partition, region, account, accountId, stored);
}
/** The resource of the type {@code stored} finds by the values in the account, or else its ARN with its id open. */
private static void foundOne(Set<String> arns, String type, List<String> names,
Map<String, RequestResourceMembers.ArnFormat> formats, String partition,
String region, String account, String accountId, StoredResourceArns stored) {
Optional<String> found = stored == null ? Optional.empty()
: account.equals(accountId) ? stored.findByMembers(type, names, region)
: stored.findInAccount(type, names, account, region);
@@ -9,6 +9,7 @@ import io.floci.aws.core.common.ContainerTeardown;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.resource.ExplorerResource;
import io.floci.aws.core.resource.ResourceProvider;
import io.floci.aws.core.resource.SupportedResourceType;
@@ -121,7 +122,8 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApplicationScoped
public class EcsService implements ContainerTeardown, ResourceProvider, Resettable, PassedRoleLookup {
public class EcsService implements ContainerTeardown, ResourceProvider, Resettable, PassedRoleLookup,
StoredResourceArns {
private static final Logger LOG = Logger.getLogger(EcsService.class);
private static final String DEFAULT_CLUSTER = "default";
@@ -4819,6 +4821,14 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
return slash < 0 ? id : id.substring(slash + 1);
}
/**
* The task set id a service revision's ARN ends in, its last segment, whether it is under its service
* ({@code service-revision/<cluster>/<service>/<id>}) or was minted before it was ({@code service-revision/<id>}).
*/
private static String revisionTaskSetId(String revisionArn) {
return revisionArn.substring(revisionArn.lastIndexOf('/') + 1);
}
/**
* Records the deployment and the revision it targets. The revision is the snapshot of the
* service's configuration, so it is copied out of the service rather than read back from it
@@ -4828,16 +4838,23 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
* <p>The revision ARN ends in the deployment's task set id, the {@code <id>} of
* {@code ecs-svc/<id>}, as AWS's does. The Terraform AWS provider's
* {@code wait_for_steady_state} finds the deployment to poll by looking for that id in each
* deployment's {@code targetServiceRevisionArn}. The ARN built here is
* {@code service-revision/<id>}; AWS's is {@code service-revision/<cluster>/<service>/<id>}.
* deployment's {@code targetServiceRevisionArn}. Both ARNs are under the service's cluster and name, as AWS's
* are and as IAM checks them: {@code service-revision/<cluster>/<service>/<id>}.
*/
/**
* The ARN of a deployment or a revision of the service, {@code <type>/<cluster>/<service>/<id>}, as AWS mints them
* and as the Service Authorization Reference gives their formats.
*/
private String underService(EcsServiceModel svc, String type, String id, String region) {
String cluster = svc.getClusterArn().substring(svc.getClusterArn().lastIndexOf('/') + 1);
return regionResolver.buildArn("ecs", region, type + "/" + cluster + "/" + svc.getServiceName() + "/" + id);
}
private void recordServiceDeployment(EcsServiceModel svc, String taskDefinition, String region) {
svc.setFailedDeploymentId(null);
String deploymentId = UUID.randomUUID().toString().replace("-", "");
String deploymentArn = regionResolver.buildArn("ecs", region,
"service-deployment/" + deploymentId);
String revisionArn = regionResolver.buildArn("ecs", region,
"service-revision/" + taskSetId(svc));
String deploymentArn = underService(svc, "service-deployment", deploymentId, region);
String revisionArn = underService(svc, "service-revision", taskSetId(svc), region);
Instant now = Instant.now();
List<String> priorRevisions = serviceRevisions.values().stream()
@@ -5086,7 +5103,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
private void restoreServiceRevision(EcsServiceModel svc, ServiceRevision revision) {
String revisionArn = revision.getServiceRevisionArn();
String taskSetId = taskSetId(revisionArn);
String taskSetId = revisionTaskSetId(revisionArn);
svc.setTaskDefinition(revision.getTaskDefinition());
svc.setLaunchType(revision.getLaunchType());
svc.setCapacityProviderStrategy(revision.getCapacityProviderStrategy());
@@ -5141,7 +5158,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
if (targetRevisionArn == null) {
return false;
}
String failedTaskSetId = taskSetId(targetRevisionArn);
String failedTaskSetId = revisionTaskSetId(targetRevisionArn);
String failedDeploymentId = "ecs-svc/" + failedTaskSetId;
EcsCluster cluster = resolveClusterByArn(svc.getClusterArn());
if (cluster == null) {
@@ -6110,15 +6127,13 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
Instant createdAt = svc.getLastDeploymentAt() != null ? svc.getLastDeploymentAt() : svc.getCreatedAt();
String revisionArn = regionResolver.buildArn("ecs", region,
"service-revision/" + taskSetId(svc));
String revisionArn = underService(svc, "service-revision", taskSetId(svc), region);
ServiceRevision revision = newServiceRevision(svc, pinnedTaskDefinitionArn(svc, key, region),
revisionArn, createdAt, region);
serviceRevisions.putIfAbsent(revisionArn, revision);
ServiceDeployment recovered = newServiceDeployment(svc, revision.getTaskDefinition(),
regionResolver.buildArn("ecs", region,
"service-deployment/" + UUID.randomUUID().toString().replace("-", "")),
underService(svc, "service-deployment", UUID.randomUUID().toString().replace("-", ""), region),
revisionArn, createdAt);
recovered.setSourceServiceRevisionArns(List.of());
ServiceDeployment existing = serviceDeployments.putIfAbsent(
@@ -6257,6 +6272,34 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
return Optional.ofNullable(findTaskDefinition(ref, region)).map(TaskDefinition::getTaskDefinitionArn);
}
@Override
public String namespace() {
return "ecs";
}
/** ECS stores no resource under a name a request fills an ARN with: a family a create names is a new revision. */
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
/**
* The revision a task definition reference a request names resolves to, as {@code RunTask} resolves it (a family
* alone is its latest revision), for a request the table finds its task definition for ({@code find}). Reads only.
*/
@Override
public Optional<String> findByMembers(String type, List<String> names, String region) {
return "task-definition".equals(type) && names.size() == 1
? taskDefinitionArn(names.getFirst(), region) : Optional.empty();
}
/** The cluster ECS acts on for a request naming none, {@code default}, which every account has. */
@Override
public Optional<String> findDefault(String type, String region) {
return "cluster".equals(type)
? Optional.of(regionResolver.buildArn("ecs", region, "cluster/" + DEFAULT_CLUSTER)) : Optional.empty();
}
/** The roles a task started from the definition runs with, for the {@code iam:PassRole} check of RunTask and the rest. */
@Override
public List<String> taskDefinitionRoles(String reference, String region) {
@@ -6343,31 +6386,6 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
.findFirst().orElse(null);
}
/**
* The ARN of the service {@code updateService} would act on, found the way it finds it: by the last segment of
* the reference within the cluster the request names. Reads only, so it creates no default cluster.
*/
public Optional<String> updatedServiceArn(String clusterRef, String serviceRef, String region) {
return existingClusterName(clusterRef, region)
.map(cluster -> services.get(serviceKey(region, cluster, extractServiceName(serviceRef))))
.map(EcsServiceModel::getServiceArn);
}
/** The ARN of the service {@code describeServices} would answer for the reference. Reads only. */
public Optional<String> describedServiceArn(String clusterRef, String serviceRef, String region) {
return existingClusterName(clusterRef, region)
.map(cluster -> resolveService(cluster, serviceRef, region))
.map(EcsServiceModel::getServiceArn);
}
/** The name of the cluster {@code resolveClusterOrDefault} would answer with, without creating the default. */
private Optional<String> existingClusterName(String clusterRef, String region) {
if (clusterRef == null || clusterRef.isBlank() || DEFAULT_CLUSTER.equals(clusterRef)) {
return Optional.of(DEFAULT_CLUSTER);
}
return Optional.ofNullable(resolveCluster(clusterRef, region)).map(EcsCluster::getClusterName);
}
private EcsServiceModel resolveServiceOrThrow(String clusterName, String serviceId, String region) {
EcsServiceModel svc = resolveService(clusterName, serviceId, region);
if (svc == null) {
@@ -10,7 +10,6 @@ import io.floci.aws.core.common.RequestResources;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser;
import io.floci.aws.services.dynamodb.DynamoDbTableNames;
import io.floci.aws.services.ecs.EcsService;
import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.services.iam.IamAuthorizedActions;
import io.floci.aws.services.iam.ResourceArnBuilder;
@@ -90,19 +89,20 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
*
* @param redshiftData finds the workgroup or the session target a Data API request names; without it a
* workgroup is any workgroup and a session names nothing
* @param ecs finds the task definition revision or the service a request reaches, reading only; without
* it such a request names nothing
* @param ecs finds the task definition revision a reference resolves to and the default cluster, reading
* only; without it a family names any revision and a request naming no cluster any cluster
* @param callback whether the state's resource ended in {@code .waitForTaskToken}, which {@code integration}
* no longer shows: EMR and EMR Serverless have no such form, so theirs stays unsupported
*/
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine,
StoredResourceArns redshiftData, EcsService ecs, boolean callback) {
StoredResourceArns redshiftData, StoredResourceArns ecs, boolean callback) {
if (integration.isAnySuffix("ecs", "runTask")
&& (integration.suffix().isEmpty() || ".sync".equals(integration.suffix()))) {
return Optional.of(ecsRunTask(input, machine, ecs));
return Optional.of(accessDenied(ECS_OPTIMIZED_PREFIX, ecs("RunTask", input, machine, ecs)));
}
if (integration.isSdkService("ecs") && SdkManagementTaskInvoker.supports(integration)) {
return Optional.of(ecsSdk(integration.api(), input, machine, ecs));
return Optional.of(accessDenied(ECS_SDK_PREFIX,
ecs(AslExecutor.capitalizeFirst(integration.api()), input, machine, ecs)));
}
if (!callback && integration.isOptimizedService("elasticmapreduce") && EmrTaskInvoker.serves(integration)) {
return Optional.of(emr(integration.api(), input, machine));
@@ -327,45 +327,26 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
}
/**
* {@code ecs:RunTask} on the revision the task would run, as {@code EcsService.runTask} resolves the reference, so
* a family and the revision it stands for are the same resource. A definition ECS does not have names nothing, so
* ECS answers it.
* The ECS call an API makes, checked as the vendored request resources check the same call made directly, on what
* its request names, its members read in either casing as the integration recases them: {@code RunTask} on the
* revision ECS resolves its task definition to, a family alone being its latest, and a service on the cluster the
* request names, or the default one. {@code ListServices} acts on no resource type. A request that is no object is
* answered by the service.
*/
private static TaskPermissions ecsRunTask(JsonNode input, StateMachine machine, EcsService ecs) {
String taskDefinition = input.path("TaskDefinition").asText(null);
if (ecs == null || taskDefinition == null) {
return accessDenied(ECS_OPTIMIZED_PREFIX, List.of());
}
return accessDenied(ECS_OPTIMIZED_PREFIX, ecs.taskDefinitionArn(taskDefinition, regionOf(machine))
.map(arn -> List.of(new Permission("ecs:RunTask", arn))).orElse(List.of()));
}
/**
* The ECS action on the service each request reaches, read as the handler reads its members, either casing being
* recased for it, and resolved as the handler resolves them: a service ECS does not have names nothing, so ECS
* answers it. {@code ListServices} has no resource type in the service reference.
*/
private static TaskPermissions ecsSdk(String api, JsonNode input, StateMachine machine, EcsService ecs) {
String action = "ecs:" + AslExecutor.capitalizeFirst(api);
if ("listServices".equals(api)) {
return accessDenied(ECS_SDK_PREFIX, List.of(new Permission(action, ANY_RESOURCE)));
}
private static List<Permission> ecs(String operation, JsonNode input, StateMachine machine,
StoredResourceArns ecs) {
String namedAs = "ecs:" + operation;
String action = IamAuthorizedActions.actionFor("ecs", operation);
JsonNode request = AslExecutor.recaseKeys(MAPPER, input, false);
if (ecs == null || !request.isObject()) {
return accessDenied(ECS_SDK_PREFIX, List.of());
if (!request.isObject() || !RequestResources.reads(namedAs)) {
return List.of();
}
String cluster = request.has("cluster") ? request.path("cluster").asText() : null;
String region = regionOf(machine);
Set<String> services = new LinkedHashSet<>();
if ("updateService".equals(api)) {
ecs.updatedServiceArn(cluster, request.path("service").asText(), region).ifPresent(services::add);
} else if (request.path("services").isArray()) {
for (JsonNode service : request.path("services")) {
ecs.describedServiceArn(cluster, service.asText(), region).ifPresent(services::add);
}
if (RequestResources.actsOnNoResource(namedAs)) {
return List.of(new Permission(action, ANY_RESOURCE));
}
return accessDenied(ECS_SDK_PREFIX,
services.stream().map(service -> new Permission(action, service)).toList());
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
return RequestResources.ofBody(namedAs, request, owner.partition(), owner.region(), owner.accountId(), ecs)
.stream().map(resource -> new Permission(action, resource)).toList();
}
/**
@@ -428,10 +409,6 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
.map(check -> new Permission(check.action(), check.resource(), check.context())).toList());
}
private static String regionOf(StateMachine machine) {
return AwsArnUtils.parse(machine.getStateMachineArn()).region();
}
/** The value when it is the non-blank string an id has to be, as the integrations require of one. */
private static String text(JsonNode value) {
return value.isTextual() && !value.asText().isBlank() ? value.asText() : null;
@@ -1,10 +1,10 @@
{
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "--source-dir /tmp/claude-1000/-home-depende-eclipse-workspace-floci-priamo-w/255d427b-2dfb-49a4-9919-91df9eb6dd39/scratchpad/f8288-refdocs", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-14", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."},
"namespaces": {"access-analyzer": ["accessanalyzer"], "account": ["account"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudfront": ["cloudfront"], "cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "controlcatalog": ["controlcatalog"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dynamodb": ["dynamodb"], "ec2": ["ec2"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "emr-serverless": ["emr-serverless"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "fis": ["fis"], "globalaccelerator": ["globalaccelerator"], "guardduty": ["guardduty"], "inspector2": ["inspector2"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "logs": ["logs"], "macie2": ["macie2"], "oam": ["oam"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "quicksight": ["quicksight"], "ram": ["ram"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-explorer-2": ["resource-explorer-2"], "route53": ["route53"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "ssm": ["ssm"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"], "xray": ["xray"]},
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-14", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."},
"namespaces": {"access-analyzer": ["accessanalyzer"], "account": ["account"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudfront": ["cloudfront"], "cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "controlcatalog": ["controlcatalog"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dynamodb": ["dynamodb"], "ec2": ["ec2"], "ecr": ["ecr"], "ecs": ["ecs"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "emr-serverless": ["emr-serverless"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "fis": ["fis"], "globalaccelerator": ["globalaccelerator"], "guardduty": ["guardduty"], "inspector2": ["inspector2"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "logs": ["logs"], "macie2": ["macie2"], "oam": ["oam"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "quicksight": ["quicksight"], "ram": ["ram"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-explorer-2": ["resource-explorer-2"], "route53": ["route53"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "ssm": ["ssm"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"], "xray": ["xray"]},
"handBuilt": ["apigateway", "bedrock", "dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes", "resource-groups", "s3", "scheduler", "secretsmanager", "sns", "sqs", "sts"],
"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 rules do not fill a name from, so nearly every operation's resource would be left open", "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 aloLine truncated
"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 rules do not fill a name from, so nearly every operation's resource would be left open", "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", "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 reading it needs the stored environment those find", "elasticfilesystem": "REST: its requests namLine 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
"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
"unqualified": {"ssm": ["parameter"], "states": ["statemachine"]},
"mintedIds": {"events": ["api-destination", "connection"]},
@@ -1797,6 +1797,94 @@
"ecr:UpdateRepositoryCreationTemplate": {"action": "ecr:UpdateRepositoryCreationTemplate", "types": [], "resources": []},
"ecr:UploadLayerPart": {"action": "ecr:UploadLayerPart", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}, {"types": ["repository"], "through": "uploadId"}]},
"ecr:ValidatePullThroughCacheRule": {"action": "ecr:ValidatePullThroughCacheRule", "types": [], "resources": []},
"ecs:AssociateGatewayWithCluster": {"action": "ecs:AssociateGatewayWithCluster", "types": ["gateway"], "resources": [{"type": "gateway", "fill": {"GatewayId": "gateway"}}]},
"ecs:ContinueServiceDeployment": {"action": "ecs:ContinueServiceDeployment", "types": ["service", "service-deployment"], "resources": [{"types": ["service", "service-deployment"], "arn": "serviceDeploymentArn"}]},
"ecs:CreateCapacityProvider": {"action": "ecs:CreateCapacityProvider", "types": ["capacity-provider"], "resources": [{"types": ["capacity-provider"], "arn": "autoScalingGroupProvider.autoScalingGroupArn"}, {"types": ["capacity-provider"], "arn": "managedInstancesProvider.infrastructureRoleArn"}, {"type": "capacity-provider", "fill": {"CapacityProviderName": "name"}}]},
"ecs:CreateCluster": {"action": "ecs:CreateCluster", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "clusterName"}}]},
"ecs:CreateDaemon": {"action": "ecs:CreateDaemon", "types": ["daemon"], "resources": [{"types": ["daemon"], "arn": "capacityProviderArns[]"}, {"type": "daemon", "fill": {"DaemonName": "daemonName"}}]},
"ecs:CreateExpressGatewayService": {"action": "ecs:CreateExpressGatewayService", "types": ["service"], "resources": [{"types": ["service"], "arn": "executionRoleArn"}, {"types": ["service"], "arn": "infrastructureRoleArn"}, {"types": ["service"], "arn": "taskRoleArn"}, {"type": "service", "fill": {"ClusterName": "cluster", "ServiceName": "serviceName"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}, "unless": {"serviceName": [null]}}]},
"ecs:CreateGateway": {"action": "ecs:CreateGateway", "types": ["gateway"], "resources": [{"types": ["gateway"], "arn": "infrastructureRoleArn"}, {"type": "gateway", "fill": {"GatewayName": "name"}}]},
"ecs:CreateService": {"action": "ecs:CreateService", "types": ["service"], "resources": [{"types": ["service"], "arn": "loadBalancers[].targetGroupArn"}, {"types": ["service"], "arn": "serviceRegistries[].registryArn"}, {"types": ["service"], "arn": "vpcLatticeConfigurations[].roleArn"}, {"types": ["service"], "arn": "vpcLatticeConfigurations[].targetGroupArn"}, {"type": "service", "fill": {"ClusterName": "cluster", "ServiceName": "serviceName"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:CreateTaskSet": {"action": "ecs:CreateTaskSet", "types": ["task-set"], "resources": [{"types": ["task-set"], "arn": "loadBalancers[].targetGroupArn"}, {"types": ["task-set"], "arn": "serviceRegistries[].registryArn"}, {"type": "task-set", "fill": {"ClusterName": "cluster", "ServiceName": "service"}, "arnOf": {"cluster": "cluster"}}]},
"ecs:DeleteAccountSetting": {"action": "ecs:DeleteAccountSetting", "types": [], "resources": []},
"ecs:DeleteAttributes": {"action": "ecs:DeleteAttributes", "types": ["container-instance"], "resources": [{"type": "container-instance", "fill": {"ClusterName": "cluster", "ContainerInstanceId": "attributes[].targetId"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:DeleteCapacityProvider": {"action": "ecs:DeleteCapacityProvider", "types": ["capacity-provider"], "resources": [{"type": "capacity-provider", "fill": {"CapacityProviderName": "capacityProvider"}}]},
"ecs:DeleteCluster": {"action": "ecs:DeleteCluster", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "cluster"}}]},
"ecs:DeleteDaemon": {"action": "ecs:DeleteDaemon", "types": ["daemon"], "resources": [{"types": ["daemon"], "arn": "daemonArn"}]},
"ecs:DeleteDaemonTaskDefinition": {"action": "ecs:DeleteDaemonTaskDefinition", "types": ["daemon-task-definition"], "resources": [{"type": "daemon-task-definition", "fill": {}, "find": ["daemonTaskDefinition"]}]},
"ecs:DeleteExpressGatewayService": {"action": "ecs:DeleteExpressGatewayService", "types": ["service"], "resources": [{"types": ["service"], "arn": "serviceArn"}]},
"ecs:DeleteGateway": {"action": "ecs:DeleteGateway", "types": ["gateway"], "resources": [{"type": "gateway", "fill": {"GatewayId": "gateway"}}]},
"ecs:DeleteService": {"action": "ecs:DeleteService", "types": ["service"], "resources": [{"type": "service", "fill": {"ClusterName": "cluster", "ServiceName": "service"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:DeleteTaskDefinitions": {"action": "ecs:DeleteTaskDefinitions", "types": ["task-definition"], "resources": [{"type": "task-definition", "fill": {}, "find": ["taskDefinitions[]"]}]},
"ecs:DeleteTaskSet": {"action": "ecs:DeleteTaskSet", "types": ["task-set"], "resources": [{"type": "task-set", "fill": {"ClusterName": "cluster", "ServiceName": "service", "TaskSetId": "taskSet"}, "arnOf": {"cluster": "cluster"}}]},
"ecs:DeregisterContainerInstance": {"action": "ecs:DeregisterContainerInstance", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:DeregisterTaskDefinition": {"action": "ecs:DeregisterTaskDefinition", "types": [], "resources": []},
"ecs:DescribeCapacityProviders": {"action": "ecs:DescribeCapacityProviders", "types": ["capacity-provider"], "resources": [{"type": "capacity-provider", "fill": {"CapacityProviderName": "capacityProviders[]"}}]},
"ecs:DescribeClusters": {"action": "ecs:DescribeClusters", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "clusters[]"}, "defaults": {"clusters[]": "cluster"}}]},
"ecs:DescribeContainerInstances": {"action": "ecs:DescribeContainerInstances", "types": ["container-instance"], "resources": [{"type": "container-instance", "fill": {"ClusterName": "cluster", "ContainerInstanceId": "containerInstances[]"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:DescribeDaemon": {"action": "ecs:DescribeDaemon", "types": ["daemon"], "resources": [{"types": ["daemon"], "arn": "daemonArn"}]},
"ecs:DescribeDaemonDeployments": {"action": "ecs:DescribeDaemonDeployments", "types": ["daemon", "daemon-deployment"], "resources": [{"types": ["daemon", "daemon-deployment"], "arn": "daemonDeploymentArns[]"}]},
"ecs:DescribeDaemonRevisions": {"action": "ecs:DescribeDaemonRevisions", "types": ["daemon", "daemon-revision"], "resources": [{"types": ["daemon", "daemon-revision"], "arn": "daemonRevisionArns[]"}]},
"ecs:DescribeDaemonTaskDefinition": {"action": "ecs:DescribeDaemonTaskDefinition", "types": ["daemon-task-definition"], "resources": [{"type": "daemon-task-definition", "fill": {}, "find": ["daemonTaskDefinition"]}]},
"ecs:DescribeExpressGatewayService": {"action": "ecs:DescribeExpressGatewayService", "types": ["service"], "resources": [{"types": ["service"], "arn": "serviceArn"}]},
"ecs:DescribeGateway": {"action": "ecs:DescribeGateway", "types": ["gateway"], "resources": [{"type": "gateway", "fill": {"GatewayId": "gateway"}}]},
"ecs:DescribeGatewayResources": {"action": "ecs:DescribeGatewayResources", "types": ["gateway"], "resources": [{"type": "gateway", "fill": {"GatewayId": "gateway"}}]},
"ecs:DescribeGatewayRoute": {"action": "ecs:DescribeGatewayRoute", "types": ["gateway", "gateway-route"], "resources": [{"types": ["gateway", "gateway-route"], "arn": "gatewayRouteArn"}]},
"ecs:DescribeServiceDeployments": {"action": "ecs:DescribeServiceDeployments", "types": ["service", "service-deployment"], "resources": [{"types": ["service", "service-deployment"], "arn": "serviceDeploymentArns[]"}]},
"ecs:DescribeServiceRevisions": {"action": "ecs:DescribeServiceRevisions", "types": ["service", "service-revision"], "resources": [{"types": ["service", "service-revision"], "arn": "serviceRevisionArns[]"}]},
"ecs:DescribeServices": {"action": "ecs:DescribeServices", "types": ["service"], "resources": [{"type": "service", "fill": {"ClusterName": "cluster", "ServiceName": "services[]"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:DescribeTaskDefinition": {"action": "ecs:DescribeTaskDefinition", "types": [], "resources": []},
"ecs:DescribeTaskSets": {"action": "ecs:DescribeTaskSets", "types": ["task-set"], "resources": [{"type": "task-set", "fill": {"ClusterName": "cluster", "ServiceName": "service", "TaskSetId": "taskSets[]"}, "arnOf": {"cluster": "cluster"}}]},
"ecs:DescribeTasks": {"action": "ecs:DescribeTasks", "types": ["task"], "resources": [{"type": "task", "fill": {"ClusterName": "cluster", "TaskId": "tasks[]"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:DisassociateGatewayFromCluster": {"action": "ecs:DisassociateGatewayFromCluster", "types": ["gateway"], "resources": [{"type": "gateway", "fill": {"GatewayId": "gateway"}}]},
"ecs:DiscoverPollEndpoint": {"action": "ecs:DiscoverPollEndpoint", "types": [], "resources": []},
"ecs:ExecuteCommand": {"action": "ecs:ExecuteCommand", "types": ["cluster", "task"], "resources": [{"type": "cluster", "fill": {"ClusterName": "cluster"}, "defaults": {"cluster": "cluster"}}, {"type": "task", "fill": {"ClusterName": "cluster", "TaskId": "task"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:GetTaskProtection": {"action": "ecs:GetTaskProtection", "types": ["task"], "resources": [{"type": "task", "fill": {"ClusterName": "cluster", "TaskId": "tasks[]"}, "arnOf": {"cluster": "cluster"}}]},
"ecs:ListAccountSettings": {"action": "ecs:ListAccountSettings", "types": [], "resources": []},
"ecs:ListAttributes": {"action": "ecs:ListAttributes", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:ListClusters": {"action": "ecs:ListClusters", "types": [], "resources": []},
"ecs:ListContainerInstances": {"action": "ecs:ListContainerInstances", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:ListDaemonDeployments": {"action": "ecs:ListDaemonDeployments", "types": ["daemon"], "resources": [{"types": ["daemon"], "arn": "daemonArn"}]},
"ecs:ListDaemonTaskDefinitions": {"action": "ecs:ListDaemonTaskDefinitions", "types": [], "resources": []},
"ecs:ListDaemons": {"action": "ecs:ListDaemons", "types": [], "resources": []},
"ecs:ListGatewayClusterAssociations": {"action": "ecs:ListGatewayClusterAssociations", "types": ["cluster", "gateway"], "resources": [{"type": "cluster", "fill": {"ClusterName": "cluster"}}, {"type": "gateway", "fill": {"GatewayId": "gateway"}}]},
"ecs:ListGatewayRoutes": {"action": "ecs:ListGatewayRoutes", "types": ["cluster", "gateway", "gateway-route", "service"], "resources": [{"type": "cluster", "fill": {"ClusterName": "cluster"}}, {"type": "service", "fill": {"ClusterName": "cluster", "ServiceName": "service"}, "arnOf": {"cluster": "cluster"}, "unless": {"service": [null]}}]},
"ecs:ListGateways": {"action": "ecs:ListGateways", "types": ["gateway"], "resources": [{"type": "gateway", "fill": {"GatewayName": "names[]"}}]},
"ecs:ListServiceDeployments": {"action": "ecs:ListServiceDeployments", "types": ["service"], "resources": [{"type": "service", "fill": {"ClusterName": "cluster", "ServiceName": "service"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:ListServices": {"action": "ecs:ListServices", "types": [], "resources": []},
"ecs:ListServicesByNamespace": {"action": "ecs:ListServicesByNamespace", "types": [], "resources": []},
"ecs:ListTagsForResource": {"action": "ecs:ListTagsForResource", "types": ["capacity-provider", "cluster", "container-instance", "service", "task", "task-definition", "task-set"], "resources": [{"types": ["capacity-provider", "cluster", "container-instance", "service", "task", "task-definition", "task-set"], "arn": "resourceArn"}]},
"ecs:ListTaskDefinitionFamilies": {"action": "ecs:ListTaskDefinitionFamilies", "types": [], "resources": []},
"ecs:ListTaskDefinitions": {"action": "ecs:ListTaskDefinitions", "types": [], "resources": []},
"ecs:ListTasks": {"action": "ecs:ListTasks", "types": ["container-instance"], "resources": [{"type": "container-instance", "fill": {"ClusterName": "cluster", "ContainerInstanceId": "containerInstance"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}, "unless": {"containerInstance": [null]}}]},
"ecs:PutAccountSetting": {"action": "ecs:PutAccountSetting", "types": [], "resources": []},
"ecs:PutAccountSettingDefault": {"action": "ecs:PutAccountSettingDefault", "types": [], "resources": []},
"ecs:PutAttributes": {"action": "ecs:PutAttributes", "types": ["container-instance"], "resources": [{"type": "container-instance", "fill": {"ClusterName": "cluster", "ContainerInstanceId": "attributes[].targetId"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:PutClusterCapacityProviders": {"action": "ecs:PutClusterCapacityProviders", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "cluster"}}]},
"ecs:RegisterContainerInstance": {"action": "ecs:RegisterContainerInstance", "types": ["cluster"], "resources": [{"types": ["cluster"], "arn": "containerInstanceArn"}, {"type": "cluster", "fill": {"ClusterName": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:RegisterDaemonTaskDefinition": {"action": "ecs:RegisterDaemonTaskDefinition", "types": ["daemon-task-definition"], "resources": [{"types": ["daemon-task-definition"], "arn": "executionRoleArn"}, {"types": ["daemon-task-definition"], "arn": "taskRoleArn"}, {"type": "daemon-task-definition", "fill": {"DaemonTaskDefinitionFamilyName": "family"}}]},
"ecs:RegisterTaskDefinition": {"action": "ecs:RegisterTaskDefinition", "types": ["task-definition"], "resources": [{"types": ["task-definition"], "arn": "executionRoleArn"}, {"types": ["task-definition"], "arn": "taskRoleArn"}, {"type": "task-definition", "fill": {"TaskDefinitionFamilyName": "family"}}]},
"ecs:RunTask": {"action": "ecs:RunTask", "types": ["task-definition"], "resources": [{"types": ["task-definition"], "arn": "overrides.executionRoleArn"}, {"types": ["task-definition"], "arn": "overrides.taskRoleArn"}, {"type": "task-definition", "fill": {}, "find": ["taskDefinition"]}]},
"ecs:StartTask": {"action": "ecs:StartTask", "types": ["task-definition"], "resources": [{"types": ["task-definition"], "arn": "overrides.executionRoleArn"}, {"types": ["task-definition"], "arn": "overrides.taskRoleArn"}, {"type": "task-definition", "fill": {}, "find": ["taskDefinition"]}]},
"ecs:StopServiceDeployment": {"action": "ecs:StopServiceDeployment", "types": ["service", "service-deployment"], "resources": [{"types": ["service", "service-deployment"], "arn": "serviceDeploymentArn"}]},
"ecs:StopTask": {"action": "ecs:StopTask", "types": ["task"], "resources": [{"types": ["task"], "arn": "task"}, {"type": "task", "fill": {"ClusterName": "cluster", "TaskId": "task"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:SubmitAttachmentStateChanges": {"action": "ecs:SubmitAttachmentStateChanges", "types": ["cluster"], "resources": [{"types": ["cluster"], "arn": "attachments[].attachmentArn"}, {"type": "cluster", "fill": {"ClusterName": "cluster"}}]},
"ecs:SubmitContainerStateChange": {"action": "ecs:SubmitContainerStateChange", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "cluster"}}]},
"ecs:SubmitTaskStateChange": {"action": "ecs:SubmitTaskStateChange", "types": ["cluster"], "resources": [{"types": ["cluster"], "arn": "attachments[].attachmentArn"}, {"type": "cluster", "fill": {"ClusterName": "cluster"}}]},
"ecs:TagResource": {"action": "ecs:TagResource", "types": ["capacity-provider", "cluster", "container-instance", "daemon", "daemon-task-definition", "gateway", "service", "task", "task-definition", "task-set"], "resources": [{"types": ["capacity-provider", "cluster", "container-instance", "daemon", "daemon-task-definition", "gateway", "service", "task", "task-definition", "task-set"], "arn": "resourceArn"}]},
"ecs:UntagResource": {"action": "ecs:UntagResource", "types": ["capacity-provider", "cluster", "container-instance", "daemon", "daemon-task-definition", "gateway", "service", "task", "task-definition", "task-set"], "resources": [{"types": ["capacity-provider", "cluster", "container-instance", "daemon", "daemon-task-definition", "gateway", "service", "task", "task-definition", "task-set"], "arn": "resourceArn"}]},
"ecs:UpdateCapacityProvider": {"action": "ecs:UpdateCapacityProvider", "types": ["capacity-provider"], "resources": [{"types": ["capacity-provider"], "arn": "managedInstancesProvider.infrastructureRoleArn"}, {"type": "capacity-provider", "fill": {"CapacityProviderName": "name"}}]},
"ecs:UpdateCluster": {"action": "ecs:UpdateCluster", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "cluster"}}]},
"ecs:UpdateClusterSettings": {"action": "ecs:UpdateClusterSettings", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "cluster"}}]},
"ecs:UpdateContainerAgent": {"action": "ecs:UpdateContainerAgent", "types": ["container-instance"], "resources": [{"type": "container-instance", "fill": {"ClusterName": "cluster", "ContainerInstanceId": "containerInstance"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:UpdateContainerInstancesState": {"action": "ecs:UpdateContainerInstancesState", "types": ["container-instance"], "resources": [{"type": "container-instance", "fill": {"ClusterName": "cluster", "ContainerInstanceId": "containerInstances[]"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:UpdateDaemon": {"action": "ecs:UpdateDaemon", "types": ["daemon"], "resources": [{"types": ["daemon"], "arn": "capacityProviderArns[]"}, {"types": ["daemon"], "arn": "daemonArn"}]},
"ecs:UpdateExpressGatewayService": {"action": "ecs:UpdateExpressGatewayService", "types": ["service"], "resources": [{"types": ["service"], "arn": "executionRoleArn"}, {"types": ["service"], "arn": "serviceArn"}, {"types": ["service"], "arn": "taskRoleArn"}]},
"ecs:UpdateGateway": {"action": "ecs:UpdateGateway", "types": ["gateway"], "resources": [{"types": ["gateway"], "arn": "infrastructureRoleArn"}, {"type": "gateway", "fill": {"GatewayId": "gateway"}}]},
"ecs:UpdateService": {"action": "ecs:UpdateService", "types": ["service"], "resources": [{"types": ["service"], "arn": "loadBalancers[].targetGroupArn"}, {"types": ["service"], "arn": "serviceRegistries[].registryArn"}, {"types": ["service"], "arn": "vpcLatticeConfigurations[].roleArn"}, {"types": ["service"], "arn": "vpcLatticeConfigurations[].targetGroupArn"}, {"type": "service", "fill": {"ClusterName": "cluster", "ServiceName": "service"}, "arnOf": {"cluster": "cluster"}, "defaults": {"cluster": "cluster"}}]},
"ecs:UpdateServicePrimaryTaskSet": {"action": "ecs:UpdateServicePrimaryTaskSet", "types": ["service"], "resources": [{"type": "service", "fill": {"ClusterName": "cluster", "ServiceName": "service"}, "arnOf": {"cluster": "cluster"}}]},
"ecs:UpdateTaskProtection": {"action": "ecs:UpdateTaskProtection", "types": ["task"], "resources": [{"type": "task", "fill": {"ClusterName": "cluster", "TaskId": "tasks[]"}, "arnOf": {"cluster": "cluster"}}]},
"ecs:UpdateTaskSet": {"action": "ecs:UpdateTaskSet", "types": ["task-set"], "resources": [{"type": "task-set", "fill": {"ClusterName": "cluster", "ServiceName": "service", "TaskSetId": "taskSet"}, "arnOf": {"cluster": "cluster"}}]},
"elasticloadbalancing:AddListenerCertificates": {"action": "elasticloadbalancing:AddListenerCertificates", "types": ["listener/app", "listener/net"], "resources": [{"types": ["listener/app", "listener/net"], "arn": "Certificates[].CertificateArn"}, {"types": ["listener/app", "listener/net"], "arn": "ListenerArn"}]},
"elasticloadbalancing:AddTags": {"action": "elasticloadbalancing:AddTags", "types": ["listener-rule/app", "listener-rule/net", "listener/app", "listener/gwy", "listener/net", "loadbalancer", "loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/", "targetgroup", "truststore"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerNames[]"}}, {"types": ["listener-rule/app", "listener-rule/net", "listener/app", "listener/gwy", "listener/net", "loadbalancer", "loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/", "targetgroup", "truststore"], "arn": "ResourceArns[]"}]},
"elasticloadbalancing:AddTrustStoreRevocations": {"action": "elasticloadbalancing:AddTrustStoreRevocations", "types": ["truststore"], "resources": [{"types": ["truststore"], "arn": "TrustStoreArn"}]},
@@ -192,8 +192,9 @@ class RequestResourceMembersTest {
assertEquals(List.of(new Member("Namespace", false), new Member("Dimension", false)), parseUnchecked(document(
formats, "{\"type\":\"target\",\"fill\":{},\"find\":[\"Namespace\",\"Dimension\"]}"))
.operations().get("a:Op").getFirst().find());
// No members, a list, members beside one filling it, no list of them, or beside members reading it otherwise.
for (String bad : List.of("\"fill\":{},\"find\":[]", "\"fill\":{},\"find\":[\"Ids[]\"]",
// No members, a list beside another, members beside one filling it, no list of them, or beside members
// reading it otherwise.
for (String bad : List.of("\"fill\":{},\"find\":[]", "\"fill\":{},\"find\":[\"Ids[]\",\"Namespace\"]",
"\"fill\":{\"Id\":\"Id\"},\"find\":[\"Namespace\"]", "\"fill\":{},\"find\":\"Namespace\"",
"\"fill\":{},\"find\":{\"a\":\"Namespace\"}",
"\"fill\":{},\"find\":[\"Namespace\"],\"absent\":{\"Namespace\":\"ecs\"}")) {
@@ -394,6 +395,33 @@ class RequestResourceMembersTest {
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A{}.B{}.Name\"}}")));
}
/**
* A member filling the one variable of another type's format names that type's default for a request leaving it
* out ({@code defaults}: an ECS service on the default cluster), and a type its service finds may be found by each
* value of one list member; a default for a member filling no such variable, or none, and a list beside another
* member to find by, fail to load.
*/
@Test
void aDefaultAMemberNamesWhenLeftOutAndAFindByOneListAreReadAsWritten() {
String formats = "\"arnFormats\":{\"a\":{"
+ "\"cluster\":\"arn:${Partition}:a:${Region}:${Account}:cluster/${ClusterName}\","
+ "\"service\":\"arn:${Partition}:a:${Region}:${Account}:service/${ClusterName}/${ServiceName}\"}}";
String fill = "\"fill\":{\"ClusterName\":\"cluster\",\"ServiceName\":\"services[]\"}";
assertEquals(Map.of("cluster", "cluster"), parseUnchecked(document(formats, "{\"type\":\"service\"," + fill
+ ",\"defaults\":{\"cluster\":\"cluster\"}}")).operations().get("a:Op").getFirst().defaults());
assertEquals(Map.of(), parseUnchecked(document(formats, "{\"type\":\"service\"," + fill + "}"))
.operations().get("a:Op").getFirst().defaults());
for (String bad : List.of("{\"services[]\":\"cluster\"}", "{\"other\":\"cluster\"}", "{\"cluster\":\"service\"}",
"{\"cluster\":\"none\"}", "{}")) {
assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"type\":\"service\"," + fill
+ ",\"defaults\":" + bad + "}")), bad);
}
assertEquals(List.of(new Member("names", true)), parseUnchecked(document(formats,
"{\"type\":\"service\",\"fill\":{},\"find\":[\"names[]\"]}")).operations().get("a:Op").getFirst().find());
assertThrows(IllegalStateException.class, () -> parse(document(formats,
"{\"type\":\"service\",\"fill\":{},\"find\":[\"names[]\",\"cluster\"]}")));
}
/**
* Each resource alone, from a request naming it and nothing else, gives exactly its ARN, in the account its
* account member names when it has one, with those sharing its explicit member selector, those the operation
@@ -1218,6 +1218,72 @@ class RequestResourcesTest {
serverless, namespace -> kms));
}
/**
* An ECS request names its cluster by name or ARN, and the default cluster, which ECS gives, when it names none; a
* service or a task given by its own ARN is that resource, and by its name in the cluster the request names too
* when that is another, as a handler may read the one or the other; and a task definition is the revision ECS
* resolves a reference to, a family alone being its latest, each of a list's found on its own, or its revision
* open when ECS has none.
*/
@Test
void anEcsRequestNamesItsClusterOrTheDefaultAndTheRevisionEcsResolves() {
String prefix = "arn:aws:ecs:us-east-1:000000000000:";
StoredResourceArns ecs = new StoredResourceArns() {
@Override
public String namespace() {
return "ecs";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
if (!"task-definition".equals(type) || names.size() != 1) {
return Optional.empty();
}
return switch (names.getFirst()) {
case "web", "web:3", "arn:aws:ecs:us-east-1:000000000000:task-definition/web:3" ->
Optional.of(prefix + "task-definition/web:3");
default -> Optional.empty();
};
}
@Override
public Optional<String> findDefault(String type, String region) {
return "cluster".equals(type) ? Optional.of(prefix + "cluster/default") : Optional.empty();
}
};
assertEquals(List.of(prefix + "service/default/api"),
of("ecs:DescribeServices", json("{\"services\":[\"api\"]}"), ecs));
assertEquals(List.of(prefix + "service/blue/api"),
of("ecs:DescribeServices", json("{\"cluster\":\"blue\",\"services\":[\"api\"]}"), ecs));
assertEquals(List.of(prefix + "service/blue/api"), of("ecs:DescribeServices",
json("{\"cluster\":\"" + prefix + "cluster/blue\",\"services\":[\"api\"]}"), ecs));
assertEquals(List.of(prefix + "service/blue/api"), of("ecs:DescribeServices",
json("{\"cluster\":\"blue\",\"services\":[\"" + prefix + "service/blue/api\"]}"), ecs));
assertEquals(List.of(prefix + "service/green/api", prefix + "service/blue/api"), of("ecs:DescribeServices",
json("{\"cluster\":\"blue\",\"services\":[\"" + prefix + "service/green/api\"]}"), ecs));
assertEquals(List.of(prefix + "task/blue/t-2", prefix + "task/default/t-1", prefix + "task/default/t-2"),
of("ecs:DescribeTasks", json("{\"tasks\":[\"t-1\",\"" + prefix + "task/blue/t-2\"]}"), ecs));
assertEquals(List.of(prefix + "cluster/default"), of("ecs:DescribeClusters", json("{}"), ecs));
assertEquals(List.of(prefix + "cluster/blue"), of("ecs:DeleteCluster", json("{\"cluster\":\"blue\"}"), ecs));
// A cluster given by ARN however the documentation words it ("The ARN or short name of the cluster").
assertEquals(List.of(prefix + "cluster/blue", prefix + "task/blue/t-1"), of("ecs:ExecuteCommand",
json("{\"cluster\":\"" + prefix + "cluster/blue\",\"task\":\"t-1\",\"command\":\"ls\"}"), ecs));
// Each attribute is on the container instance its targetId names.
assertEquals(List.of(prefix + "container-instance/blue/i-1", prefix + "container-instance/blue/i-2"),
of("ecs:PutAttributes", json("{\"cluster\":\"blue\",\"attributes\":[{\"name\":\"a\",\"targetId\":\"i-1\"},"
+ "{\"name\":\"b\",\"targetType\":\"container-instance\",\"targetId\":\"i-2\"}]}"), ecs));
// Without ECS to give its default, a service of no cluster is in any.
assertEquals(List.of(prefix + "service/*/api"), of("ecs:DescribeServices", json("{\"services\":[\"api\"]}")));
for (String reference : List.of("web", "web:3", prefix + "task-definition/web:3")) {
assertEquals(List.of(prefix + "task-definition/web:3"),
of("ecs:RunTask", json("{\"taskDefinition\":\"" + reference + "\"}"), ecs), reference);
}
assertEquals(List.of(prefix + "task-definition/*:*"),
of("ecs:RunTask", json("{\"taskDefinition\":\"gone\"}"), ecs));
assertEquals(List.of(prefix + "task-definition/web:3", prefix + "task-definition/*:*"),
of("ecs:DeleteTaskDefinitions", json("{\"taskDefinitions\":[\"web:3\",\"gone:1\"]}"), ecs));
}
/**
* A Parameter Store parameter is {@code parameter/<name>} whether its name starts with a slash or not, without the
* whitespace around it, a name of two leading slashes keeping the second and one beginning {@code /parameter/}
@@ -0,0 +1,258 @@
package io.floci.aws.services.ecs;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
/**
* Under IAM enforcement an ECS request is checked on the resources it names, at the ARNs ECS mints for them: a
* cluster by its name or ARN, a service or a task in the request's cluster or the default one, a task definition as
* the revision its reference resolves to, and a capacity provider. A grant scoped to one reaches it and no other.
* ECS runs in mock mode, with no container behind a task.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class EcsIamIntegrationTest {
private static final String ACCOUNT = "000000000472";
private static final String REGION = "us-east-1";
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TARGET_PREFIX = "AmazonEC2ContainerServiceV20141113.";
@TestHTTPResource
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aClusterScopedGrantReachesThatClusterByNameOrArnAndNoOther() {
String mine = cluster();
String other = cluster();
String arn = arn("cluster/" + mine);
String user = user(allow(List.of(arn), "ecs:DescribeClusters", "ecs:ListContainerInstances"));
call(user, "DescribeClusters", Map.of("clusters", List.of(mine))).statusCode(200)
.body("clusters[0].clusterArn", equalTo(arn));
call(user, "DescribeClusters", Map.of("clusters", List.of(arn))).statusCode(200);
call(user, "ListContainerInstances", Map.of("cluster", mine)).statusCode(200);
denied(call(user, "DescribeClusters", Map.of("clusters", List.of(other))), "ecs:DescribeClusters");
denied(call(user, "ListContainerInstances", Map.of("cluster", other)), "ecs:ListContainerInstances");
}
/** A service is in the cluster the request names, by name or ARN, or in the default cluster when it names none. */
@Test
void aServiceIsCheckedInTheClusterTheRequestNamesOrTheDefaultOne() {
String family = family();
String cluster = cluster();
String name = "svc-" + UUID.randomUUID().toString().substring(0, 8);
String inCluster = service(cluster, name, family);
String inDefault = service(null, name, family);
String user = user(allow(List.of(inCluster), "ecs:DescribeServices", "ecs:UpdateService"));
call(user, "DescribeServices", Map.of("cluster", cluster, "services", List.of(name))).statusCode(200)
.body("services[0].serviceArn", equalTo(inCluster));
call(user, "DescribeServices", Map.of("cluster", arn("cluster/" + cluster), "services", List.of(inCluster)))
.statusCode(200);
call(user, "UpdateService", Map.of("cluster", cluster, "service", name, "desiredCount", 0)).statusCode(200);
// The same name in the default cluster is another service.
denied(call(user, "DescribeServices", Map.of("services", List.of(name))), "ecs:DescribeServices");
denied(call(user, "UpdateService", Map.of("service", name, "desiredCount", 0)), "ecs:UpdateService");
String inDefaultOnly = user(allow(List.of(inDefault), "ecs:DescribeServices"));
call(inDefaultOnly, "DescribeServices", Map.of("services", List.of(name))).statusCode(200)
.body("services[0].serviceArn", equalTo(inDefault));
call(inDefaultOnly, "DescribeServices", Map.of("cluster", "default", "services", List.of(name))).statusCode(200);
denied(call(inDefaultOnly, "DescribeServices", Map.of("cluster", cluster, "services", List.of(name))),
"ecs:DescribeServices");
}
/** A task definition is the revision its reference resolves to, a family alone being its latest. */
@Test
void aTaskDefinitionIsTheRevisionItsReferenceResolvesTo() {
String family = family();
register(family);
String cluster = cluster();
String user = user(allow(List.of(arn("task-definition/" + family + ":2")), "ecs:RunTask"));
for (String reference : List.of(family, family + ":2", arn("task-definition/" + family + ":2"))) {
stopAfter(cluster, call(user, "RunTask", Map.of("cluster", cluster, "taskDefinition", reference))
.statusCode(200).extract().path("tasks[0].taskArn"));
}
denied(call(user, "RunTask", Map.of("cluster", cluster, "taskDefinition", family + ":1")), "ecs:RunTask");
}
/**
* A new revision a registration makes is checked on its family with the revision open, never on the revision
* that happens to be the latest: a deny on an old revision does not refuse registering the next.
*/
@Test
void aRegistrationIsCheckedOnItsFamilyNotOnTheLatestRevision() {
String family = family();
String user = user("{\"Version\":\"2012-10-17\",\"Statement\":["
+ "{\"Effect\":\"Allow\",\"Action\":\"ecs:RegisterTaskDefinition\",\"Resource\":\"*\"},"
+ "{\"Effect\":\"Deny\",\"Action\":\"ecs:RegisterTaskDefinition\",\"Resource\":\""
+ arn("task-definition/" + family + ":1") + "\"}]}");
call(user, "RegisterTaskDefinition", Map.of("family", family, "containerDefinitions",
List.of(Map.of("name", "runner", "image", "floci-test/runner:latest", "memory", 128))))
.statusCode(200).body("taskDefinition.revision", equalTo(2));
}
/** A service's deployments are under its cluster and name, as AWS mints them, and checked on those ARNs. */
@Test
void aServiceDeploymentIsCheckedOnTheArnEcsMintsUnderItsService() {
String family = family();
String cluster = cluster();
String name = "svc-" + UUID.randomUUID().toString().substring(0, 8);
service(cluster, name, family);
String deployment = call(ACCOUNT, "ListServiceDeployments", Map.of("cluster", cluster, "service", name))
.statusCode(200).extract().path("serviceDeployments[0].serviceDeploymentArn");
assertThat(deployment, startsWith(arn("service-deployment/" + cluster + "/" + name + "/")));
String mine = user(allow(List.of(deployment), "ecs:DescribeServiceDeployments"));
call(mine, "DescribeServiceDeployments", Map.of("serviceDeploymentArns", List.of(deployment))).statusCode(200)
.body("serviceDeployments[0].serviceDeploymentArn", equalTo(deployment));
String another = user(allow(List.of(arn("service-deployment/" + cluster + "/other/*")),
"ecs:DescribeServiceDeployments"));
denied(call(another, "DescribeServiceDeployments", Map.of("serviceDeploymentArns", List.of(deployment))),
"ecs:DescribeServiceDeployments");
}
@Test
void aTaskIsCheckedOnTheArnEcsMintsForIt() {
String family = family();
String cluster = cluster();
String mine = run(cluster, family);
String other = run(cluster, family);
String user = user(allow(List.of(mine), "ecs:DescribeTasks", "ecs:StopTask"));
call(user, "DescribeTasks", Map.of("cluster", cluster, "tasks", List.of(mine.substring(mine.lastIndexOf('/') + 1))))
.statusCode(200).body("tasks[0].taskArn", equalTo(mine));
call(user, "DescribeTasks", Map.of("cluster", cluster, "tasks", List.of(mine))).statusCode(200);
denied(call(user, "DescribeTasks", Map.of("cluster", cluster, "tasks", List.of(other))), "ecs:DescribeTasks");
denied(call(user, "StopTask", Map.of("cluster", cluster, "task", other)), "ecs:StopTask");
}
@Test
void aCapacityProviderIsCheckedOnTheArnEcsMintsForIt() {
String mine = capacityProvider();
String other = capacityProvider();
String arn = arn("capacity-provider/" + mine);
String user = user(allow(List.of(arn), "ecs:DescribeCapacityProviders"));
call(user, "DescribeCapacityProviders", Map.of("capacityProviders", List.of(mine))).statusCode(200)
.body("capacityProviders[0].capacityProviderArn", equalTo(arn));
denied(call(user, "DescribeCapacityProviders", Map.of("capacityProviders", List.of(other))),
"ecs:DescribeCapacityProviders");
}
private String cluster() {
String name = "iam-" + UUID.randomUUID().toString().substring(0, 8);
call(ACCOUNT, "CreateCluster", Map.of("clusterName", name)).statusCode(200);
cleanup.register(() -> call(ACCOUNT, "DeleteCluster", Map.of("cluster", name)));
return name;
}
private String family() {
String family = "iam-" + UUID.randomUUID().toString().substring(0, 8);
register(family);
return family;
}
private void register(String family) {
call(ACCOUNT, "RegisterTaskDefinition", Map.of("family", family, "containerDefinitions",
List.of(Map.of("name", "runner", "image", "floci-test/runner:latest", "memory", 128))))
.statusCode(200);
}
/** A service of no tasks in the cluster, or in the default one for none; its ARN as ECS mints it. */
private String service(String cluster, String name, String family) {
Map<String, Object> request = cluster == null
? Map.of("serviceName", name, "taskDefinition", family, "desiredCount", 0)
: Map.of("cluster", cluster, "serviceName", name, "taskDefinition", family, "desiredCount", 0);
String arn = call(ACCOUNT, "CreateService", request).statusCode(200).extract().path("service.serviceArn");
cleanup.register(() -> call(ACCOUNT, "DeleteService", cluster == null
? Map.of("service", name, "force", true) : Map.of("cluster", cluster, "service", name, "force", true)));
return arn;
}
private String run(String cluster, String family) {
String task = call(ACCOUNT, "RunTask", Map.of("cluster", cluster, "taskDefinition", family)).statusCode(200)
.extract().path("tasks[0].taskArn");
stopAfter(cluster, task);
return task;
}
private void stopAfter(String cluster, String task) {
cleanup.register(() -> call(ACCOUNT, "StopTask", Map.of("cluster", cluster, "task", task)));
}
private String capacityProvider() {
String name = "iam-" + UUID.randomUUID().toString().substring(0, 8);
call(ACCOUNT, "CreateCapacityProvider", Map.of("name", name, "autoScalingGroupProvider", Map.of(
"autoScalingGroupArn", "arn:aws:autoscaling:" + REGION + ":" + ACCOUNT
+ ":autoScalingGroup:00000000-0000-0000-0000-000000000000:autoScalingGroupName/" + name)))
.statusCode(200);
cleanup.register(() -> call(ACCOUNT, "DeleteCapacityProvider", Map.of("capacityProvider", name)));
return name;
}
private static String arn(String resource) {
return "arn:aws:ecs:" + REGION + ":" + ACCOUNT + ":" + resource;
}
private static String allow(List<String> resources, String... actions) {
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\""
+ String.join("\",\"", actions) + "\"],\"Resource\":[\"" + String.join("\",\"", resources) + "\"]}]}";
}
private static void denied(ValidatableResponse response, String action) {
response.statusCode(400).body("__type", equalTo("AccessDeniedException"))
.body("message", containsString(action));
}
private String user(String policy) {
String name = "ecs-" + UUID.randomUUID().toString().substring(0, 8);
String authorization = auth(ACCOUNT, "iam");
String accessKeyId = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), authorization, name)
.accessKeyId();
EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, name, "p", policy);
return accessKeyId;
}
private ValidatableResponse call(String accessKeyId, String action, Map<String, ?> body) {
return given().port(endpoint.getPort())
.header("X-Amz-Target", TARGET_PREFIX + action)
.header("Authorization", auth(accessKeyId, "ecs"))
.contentType(CONTENT_TYPE)
.body(body)
.when().post("/")
.then();
}
}
@@ -344,11 +344,17 @@ class StepFunctionsJobTaskIamIntegrationTest {
assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString());
}
/**
* A definition ECS does not have is checked as the call made directly checks it, on any revision of its family:
* a role allowed nothing is refused, and one allowed {@code ecs:RunTask} gets ECS's own answer.
*/
@Test
void aTaskDefinitionEcsDoesNotHaveIsLeftToEcs() throws Exception {
void aTaskDefinitionEcsDoesNotHaveIsCheckedAsTheDirectCallIs() throws Exception {
Map<String, Object> task = task("ecs:runTask", Map.of("TaskDefinition", "no-such-family-" + UUID.randomUUID()));
assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), "ECS.ClientException");
assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), "ECS.AccessDeniedException");
assertFailed(terminal(start(machine(task, role(STATES_TRUST, allow("*", "ecs:RunTask"))), "{}")),
"ECS.ClientException");
}
/** {@code .sync} needs the starting call alone: the wait reads what the task launched with no Describe grant. */
@@ -451,7 +457,10 @@ class StepFunctionsJobTaskIamIntegrationTest {
target.notReached().check();
}
/** The service ARN's own cluster is not what {@code UpdateService} reads: the task acts on the request's. */
/**
* The service ARN's own cluster is not what {@code UpdateService} reads: the task acts on the service of that name
* in the request's cluster. The request names both, so the task needs the action on both, as the direct call does.
*/
@Test
void updateServiceIsEvaluatedOnTheServiceItActsOn() throws Exception {
String family = family();
@@ -468,7 +477,15 @@ class StepFunctionsJobTaskIamIntegrationTest {
assertTrue(refused.jsonPath().getString("cause").contains(inOther), refused.asString());
assertEquals(0, desiredCount(other, name));
Response allowed = terminal(start(machine(task, role(STATES_TRUST, allow(inOther, "ecs:UpdateService"))), "{}"));
Response onlyActedOn = terminal(start(machine(task, role(STATES_TRUST, allow(inOther, "ecs:UpdateService"))),
"{}"));
assertFailed(onlyActedOn, "Ecs.AccessDeniedException");
assertTrue(onlyActedOn.jsonPath().getString("cause").contains(inNamed), onlyActedOn.asString());
assertEquals(0, desiredCount(other, name));
Response allowed = terminal(start(machine(task, role(STATES_TRUST,
policy(List.of(Map.of("Effect", "Allow", "Action", List.of("ecs:UpdateService"),
"Resource", List.of(inNamed, inOther)))))), "{}"));
assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString());
assertEquals(1, desiredCount(other, name));
assertEquals(0, desiredCount(named, name));
@@ -493,14 +510,23 @@ class StepFunctionsJobTaskIamIntegrationTest {
assertEquals(2, MAPPER.readTree(allowed.jsonPath().getString("output")).path("Services").size());
}
/** What a service does not have reaches nothing: a role allowed nothing gets the service's own answer. */
/**
* A service or a cluster ECS does not have is checked as the call made directly checks it, on the ARN the request
* names: a role allowed nothing is refused, and one allowed the action gets ECS's own answer.
*/
@Test
void aServiceEcsDoesNotHaveIsLeftToEcs() throws Exception {
void aServiceEcsDoesNotHaveIsCheckedAsTheDirectCallIs() throws Exception {
String cluster = ecsCluster();
String role = role(STATES_TRUST, READ_ONLY);
String nothing = role(STATES_TRUST, READ_ONLY);
Map<String, Object> noService = task("aws-sdk:ecs:updateService",
Map.of("Cluster", cluster, "Service", "no-such-service"));
assertFailed(terminal(start(machine(noService, nothing), "{}")), "Ecs.AccessDeniedException");
assertFailed(terminal(start(machine(task("aws-sdk:ecs:describeServices",
Map.of("Cluster", cluster, "Services", List.of("no-such-service"))), nothing), "{}")),
"Ecs.AccessDeniedException");
assertFailed(terminal(start(machine(task("aws-sdk:ecs:updateService",
Map.of("Cluster", cluster, "Service", "no-such-service")), role), "{}")), "Ecs.ServiceNotFoundException");
String role = role(STATES_TRUST, allow("*", "ecs:UpdateService", "ecs:DescribeServices"));
assertFailed(terminal(start(machine(noService, role), "{}")), "Ecs.ServiceNotFoundException");
assertFailed(terminal(start(machine(task("aws-sdk:ecs:updateService",
Map.of("Cluster", "no-such-cluster", "Service", "any")), role), "{}")), "Ecs.ClusterNotFoundException");
Response described = terminal(start(machine(task("aws-sdk:ecs:describeServices",
@@ -3,7 +3,6 @@ package io.floci.aws.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.services.ecs.EcsService;
import io.floci.aws.services.stepfunctions.LambdaTaskAuthorizer.Permission;
import io.floci.aws.services.stepfunctions.model.StateMachine;
import org.junit.jupiter.api.Test;
@@ -29,6 +28,7 @@ class TaskPermissionsTest {
private static final String ENDPOINT = "arn:aws:sns:eu-west-1:111122223333:endpoint/GCM/app/id";
private static final String TASK_DEFINITION = "arn:aws:ecs:eu-west-1:111122223333:task-definition/orders:7";
private static final String SERVICE = "arn:aws:ecs:eu-west-1:111122223333:service/c/s";
private static final String ANY_REVISION = "arn:aws:ecs:eu-west-1:111122223333:task-definition/*:*";
private static final String EMR_CLUSTER = "arn:aws:elasticmapreduce:eu-west-1:111122223333:cluster/j-1";
private static final String APPLICATION = "arn:aws:emr-serverless:eu-west-1:111122223333:/applications/a";
@@ -400,79 +400,68 @@ class TaskPermissionsTest {
assertEquals(Optional.empty(), TaskPermissions.of(integration("aws-sdk:redshiftdata:executeStatement.sync"), json("{}"), machine("aws")));
}
/** Whatever names it, the check is on the revision {@code EcsService} finds, which is the one it would run. */
/** Whatever names it, the check is on the revision ECS resolves it to, which is the one it would run. */
@ParameterizedTest
@ValueSource(strings = {"ecs:runTask", "ecs:runTask.sync"})
void runTaskIsCheckedOnTheRevisionEcsFinds(String tail) throws Exception {
EcsService ecs = mock(EcsService.class);
when(ecs.taskDefinitionArn("orders", "eu-west-1")).thenReturn(Optional.of(TASK_DEFINITION));
assertEquals(TaskPermissions.accessDenied("ECS.", List.of(new Permission("ecs:RunTask", TASK_DEFINITION))),
ecsPermissions(tail, "{\"TaskDefinition\":\"orders\"}", ecs));
void runTaskIsCheckedOnTheRevisionEcsResolves(String tail) throws Exception {
for (String reference : List.of("orders", "orders:7", TASK_DEFINITION)) {
assertEquals(TaskPermissions.accessDenied("ECS.", List.of(new Permission("ecs:RunTask", TASK_DEFINITION))),
ecsPermissions(tail, "{\"TaskDefinition\":\"" + reference + "\"}", ecs()), reference);
}
}
/** A form the integration does not serve is left to its unsupported-mode answer, whatever the role. */
@Test
void aRunTaskFormEcsDoesNotServeStaysUnchecked() throws Exception {
assertEquals(Optional.empty(), TaskPermissions.of(integration("ecs:runTask.sync:2"),
json("{\"TaskDefinition\":\"orders\"}"), machine("aws"), null, mock(EcsService.class), false));
json("{\"TaskDefinition\":\"orders\"}"), machine("aws"), null, ecs(), false));
}
/** {@code executeTaskState} strips the suffix, so this is a {@code .waitForTaskToken} as the dispatch sees it. */
@Test
void runTaskWithATokenIsChecked() throws Exception {
EcsService ecs = mock(EcsService.class);
when(ecs.taskDefinitionArn("orders", "eu-west-1")).thenReturn(Optional.of(TASK_DEFINITION));
assertEquals(List.of(new Permission("ecs:RunTask", TASK_DEFINITION)),
TaskPermissions.of(integration("ecs:runTask"), json("{\"TaskDefinition\":\"orders\"}"), machine("aws"),
null, ecs, true).orElseThrow().permissions());
}
@ParameterizedTest
@ValueSource(strings = {"{}", "{\"TaskDefinition\":null}", "{\"TaskDefinition\":\"no-such\"}"})
void aTaskDefinitionEcsDoesNotFindNeedsNoPermission(String request) throws Exception {
assertEquals(TaskPermissions.accessDenied("ECS.", List.of()),
ecsPermissions("ecs:runTask", request, mock(EcsService.class)));
null, ecs(), true).orElseThrow().permissions());
}
/** A request naming no definition is answered by ECS; one naming a definition ECS does not have, any revision. */
@Test
void runTaskWithoutEcsNamesNothing() throws Exception {
assertEquals(TaskPermissions.accessDenied("ECS.", List.of()), TaskPermissions.of(integration("ecs:runTask"),
json("{\"TaskDefinition\":\"orders\"}"), machine("aws")).orElseThrow());
void aTaskDefinitionEcsDoesNotHaveIsCheckedWithAnyRevision() throws Exception {
for (String request : List.of("{}", "{\"TaskDefinition\":null}")) {
assertEquals(TaskPermissions.accessDenied("ECS.", List.of()), ecsPermissions("ecs:runTask", request, ecs()),
request);
}
assertEquals(List.of(new Permission("ecs:RunTask", ANY_REVISION)),
ecsPermissions("ecs:runTask", "{\"TaskDefinition\":\"no-such\"}", ecs()).permissions());
assertEquals(List.of(new Permission("ecs:RunTask", ANY_REVISION)), TaskPermissions.of(integration("ecs:runTask"),
json("{\"TaskDefinition\":\"orders\"}"), machine("aws")).orElseThrow().permissions());
}
/** The members are read in either casing, as the SDK form recases them for the handler. */
@ParameterizedTest
@ValueSource(strings = {"{\"Cluster\":\"c\",\"Service\":\"s\"}", "{\"cluster\":\"c\",\"service\":\"s\"}"})
void updateServiceIsCheckedOnTheServiceEcsFinds(String request) throws Exception {
EcsService ecs = mock(EcsService.class);
when(ecs.updatedServiceArn("c", "s", "eu-west-1")).thenReturn(Optional.of(SERVICE));
@ValueSource(strings = {"{\"Cluster\":\"c\",\"Service\":\"s\"}", "{\"cluster\":\"c\",\"service\":\"s\"}",
"{\"Cluster\":\"arn:aws:ecs:eu-west-1:111122223333:cluster/c\",\"Service\":\"s\"}"})
void updateServiceIsCheckedOnTheServiceItNames(String request) throws Exception {
assertEquals(TaskPermissions.accessDenied("Ecs.", List.of(new Permission("ecs:UpdateService", SERVICE))),
ecsPermissions("aws-sdk:ecs:updateService", request, ecs));
ecsPermissions("aws-sdk:ecs:updateService", request, ecs()));
}
@Test
void updateServiceWithNoClusterAsksForTheDefault() throws Exception {
EcsService ecs = mock(EcsService.class);
when(ecs.updatedServiceArn(null, "s", "eu-west-1")).thenReturn(Optional.of(SERVICE));
assertEquals(List.of(new Permission("ecs:UpdateService", SERVICE)),
ecsPermissions("aws-sdk:ecs:updateService", "{\"Service\":\"s\"}", ecs).permissions());
void updateServiceWithNoClusterIsOnTheDefaultCluster() throws Exception {
assertEquals(List.of(new Permission("ecs:UpdateService", "arn:aws:ecs:eu-west-1:111122223333:service/default/s")),
ecsPermissions("aws-sdk:ecs:updateService", "{\"Service\":\"s\"}", ecs()).permissions());
}
/** Each service named, a name in the request's cluster and an ARN as given, whether ECS has it or not. */
@Test
void describeServicesIsCheckedOnEachDistinctServiceEcsFinds() throws Exception {
EcsService ecs = mock(EcsService.class);
when(ecs.describedServiceArn("c", "a", "eu-west-1")).thenReturn(Optional.of(SERVICE));
when(ecs.describedServiceArn("c", SERVICE, "eu-west-1")).thenReturn(Optional.of(SERVICE));
when(ecs.describedServiceArn("c", "b", "eu-west-1")).thenReturn(Optional.of(SERVICE + "b"));
void describeServicesIsCheckedOnEachServiceItNames() throws Exception {
String inC = "arn:aws:ecs:eu-west-1:111122223333:service/c/";
assertEquals(List.of(new Permission("ecs:DescribeServices", SERVICE),
new Permission("ecs:DescribeServices", SERVICE + "b")),
new Permission("ecs:DescribeServices", inC + "a"),
new Permission("ecs:DescribeServices", inC + "missing")),
ecsPermissions("aws-sdk:ecs:describeServices",
"{\"Cluster\":\"c\",\"Services\":[\"a\",\"" + SERVICE + "\",\"missing\",\"b\"]}", ecs)
"{\"Cluster\":\"c\",\"Services\":[\"a\",\"" + SERVICE + "\",\"missing\",\"a\"]}", ecs())
.permissions());
}
@@ -618,10 +607,32 @@ class TaskPermissionsTest {
.orElseThrow().permissions());
}
private static TaskPermissions ecsPermissions(String tail, String request, EcsService ecs) throws Exception {
private static TaskPermissions ecsPermissions(String tail, String request, StoredResourceArns ecs) throws Exception {
return TaskPermissions.of(integration(tail), json(request), machine("aws"), null, ecs, false).orElseThrow();
}
/** What ECS answers IAM: the revision {@code orders} and {@code orders:7} resolve to, and its default cluster. */
private static StoredResourceArns ecs() {
return new StoredResourceArns() {
@Override
public String namespace() {
return "ecs";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return "task-definition".equals(type) && List.of(List.of("orders"), List.of("orders:7"),
List.of(TASK_DEFINITION)).contains(names) ? Optional.of(TASK_DEFINITION) : Optional.empty();
}
@Override
public Optional<String> findDefault(String type, String region) {
return "cluster".equals(type) ? Optional.of("arn:aws:ecs:" + region + ":111122223333:cluster/default")
: Optional.empty();
}
};
}
private static List<Permission> sdkPermissions(String api, String request) throws Exception {
return TaskPermissions.of(integration("aws-sdk:dynamodb:" + api), json(request), machine("aws")).orElseThrow().permissions();
}
+203 -16
View File
@@ -137,11 +137,25 @@ Beyond the members' names, botocore's shapes and documentation say what a member
(CodePipeline's `CreateCustomActionType` makes an action type whose `ActionOwner` is `Custom`);
- a type named only by an optional member documented as holding what the operation is about ("the cluster to which
the instance group belongs") is named, when the request leaves that member out, through each member naming what
the operation is about (`ModifyInstanceGroups`' `InstanceGroups[].InstanceGroupId`).
the operation is about (`ModifyInstanceGroups`' `InstanceGroups[].InstanceGroupId`);
- a type of two variables no member fills is named by the member whose documentation spells it as its format does
("The family and revision (family:revision) or full ARN of the task definition to run"), which its service finds
as its handler resolves it (`find`), each element of a list; such a member, "or full ARN" coming after something
else, holds no ARN alone;
- a member documented as a name or an ARN of another type than the one whose variable it fills ("The short name or
full Amazon Resource Name (ARN) of the cluster", "The Amazon Resource Name (ARN) or short name of the cluster",
"the cluster name or ARN": an ECS service's `cluster`) may give that type's ARN (`arnOf`), as a pattern taking
one does;
- a list element's id field beside a field of its stem holding the target's type, an enum whose one value is a
type the action acts on, fills that type's last variable no member fills (ECS's `PutAttributes`:
`attributes[].targetId`, beside `targetType`, on the container instance it names);
- a member whose documentation says its service uses its default for a request leaving it out ("If you do not
specify a cluster, the default cluster is assumed") names that default then (`defaults`), when it fills the one
variable of that type's format, rather than naming nothing.
What a request names, this file alone says. A service only looks up what it holds where an entry asks it to
(`StoredResourceArns`): the resource the members a `find` gives name, the ones a `through` member reaches, and the
resource its handler uses for a member left out (Athena's `primary` workgroup, EventBridge's `default` bus). No
service says what an operation acts on.
resource its handler uses for a member left out (Athena's `primary` workgroup, EventBridge's `default` bus, ECS's
`default` cluster). No service says what an operation acts on.
`MEASURED` holds what AWS checks where neither botocore nor the Service Reference says it, and nothing else. It
and `FORWARDED` are the only parts of the file stated by hand, and an entry is admitted only with evidence from AWS
@@ -233,7 +247,7 @@ OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-request-resources.json"
NAMESPACES = ("access-analyzer", "account", "acm", "application-autoscaling", "athena", "bcm-data-exports",
"bcm-pricing-calculator", "budgets", "ce", "cloudfront", "cloudfront-keyvaluestore", "cloudtrail",
"codebuild", "codepipeline", "cognito-identity", "cognito-idp", "controlcatalog", "controltower", "cur",
"datasync", "ec2", "ecr", "elasticloadbalancing", "elasticmapreduce", "emr-serverless", "es", "events",
"datasync", "ec2", "ecr", "ecs", "elasticloadbalancing", "elasticmapreduce", "emr-serverless", "es", "events",
"firehose", "fis", "globalaccelerator", "inspector2", "kinesisanalytics", "macie2", "oam",
"payment-cryptography", "quicksight", "ram", "redshift", "redshift-data", "redshift-serverless",
"rekognition", "resource-explorer-2", "route53", "servicediscovery", "servicequotas", "ssm", "sso",
@@ -374,7 +388,6 @@ NOT_COVERED: dict[str, str] = {
"dlm": _REST,
"dms": _LATER,
"ec2-instance-connect": _LATER,
"ecs": _LATER,
"elasticache": _LATER,
"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 "
@@ -667,6 +680,19 @@ def doc_kind(lead: str) -> str | None:
return None
def spelled(kind: str, arn: str) -> str | None:
"""How documentation spells a resource of two variables joined by a colon after its type's word, each variable
without the type's own words and its kind: `(family:revision)` for a task definition,
`task-definition/${TaskDefinitionFamilyName}:${TaskDefinitionRevisionNumber}`; None for any other format."""
match = re.fullmatch(r"[A-Za-z][A-Za-z0-9-]*/\$\{(\w+)}:\$\{(\w+)}", _resource(arn))
if not match:
return None
own = "".join(part.capitalize() for part in kind.split("-"))
words = [re.sub(r"(?:Name|Number|Id|Identifier)$", "", variable.removeprefix(own)).lower()
for variable in match.groups()]
return f"({words[0]}:{words[1]})" if all(words) else None
def doc_names(lead: str, kind: str, formats: dict[str, str]) -> bool:
"""Whether a member's documentation says it names a resource of the type, by the type's name or its format's
leading resource word, word for word and followed by a word that ends it: "The name of the stream processor you
@@ -752,7 +778,11 @@ def with_documented(operation: str, types: list[str], formats: dict[str, str], m
"""The resources, completed from what botocore's shapes and documentation say each member names.
- A member whose documentation's head noun is an ARN of a type the action acts on (or of whatever it acts on)
holds one: Redshift's `ResourceName`, 'The Amazon Resource Name (ARN) to which you want to add the tag'.
holds one: Redshift's `ResourceName`, 'The Amazon Resource Name (ARN) to which you want to add the tag'; not
one documented as a name, an id or a spelled form or that ARN ('The family and revision (family:revision) or
full ARN of the task definition').
- A type of two variables no member fills is found by its service (`find`) by the one member whose
documentation spells it as its format does, `(family:revision)` for a task definition, each element of a list.
- An ARN member whose pattern takes another service's ARNs (a role's, a bucket's, a key's, CUR's billing view),
or whose documentation gives it as the ARN of another type of the service (a `CreateExport`'s
`Export.ExportArn`, "for this export"), names none of the action's resources, unless named after one of them.
@@ -783,7 +813,7 @@ def with_documented(operation: str, types: list[str], formats: dict[str, str], m
continue
head, of = doc_head(fact["lead"])
if re.search(r"(?:arns?|amazon resource names? \(arns?\))$", head) \
and not re.search(r"\b(?:name|id|identifier)s? or\b", head) and (
and not re.search(r"(?:\b(?:name|id|identifier)s?|\)) or\b", head) and (
(of is None and stem(path).startswith("resource"))
or (of is not None and any(doc_names("the name of the " + part.strip(), kind, formats)
for part in re.split(r",| or ", of) for kind in kinds))):
@@ -866,6 +896,18 @@ def with_documented(operation: str, types: list[str], formats: dict[str, str], m
current["fill"] = dict(sorted(fill.items()))
else:
resources.append({"type": kind, "fill": dict(sorted(fill.items()))})
# A type of two variables no member fills is named by the one member whose documentation spells it as its format
# does, which its service finds as its handler resolves it, each element of a list: ECS's `taskDefinition`, "The
# family and revision (family:revision) or full ARN of the task definition to run".
for kind in kinds:
form = spelled(kind, formats[kind])
if form is None or any(resource.get("type") == kind and (resource.get("fill") or "find" in resource)
for resource in resources):
continue
spelling = [fact["path"] for path, fact in sorted(facts.items()) if not fact["nested"] and form in fact["lead"]]
if len(spelling) == 1:
resources = [resource for resource in resources if resource.get("type") != kind]
resources.append({"type": kind, "fill": {}, "find": spelling})
# A nested field filling a variable an optional top-level member of its name fills too is read when that member
# is absent.
optional = optional_members(models, name)
@@ -1254,6 +1296,16 @@ def account_members(models: dict[str, dict], operation: str) -> list[str]:
# A pattern that takes an ARN of a type before a name: `(arn:...:event-bus\/)?<name>`, the type's word captured.
NAME_OR_ARN_RE = re.compile(r"^\(arn:[^)]*:([A-Za-z][A-Za-z0-9-]*)\\?/\)\?")
# Documentation saying a member is a name or an ARN of a type: "The short name or full Amazon Resource Name (ARN) of
# the cluster", the type's phrase captured.
DOC_NAME_OR_ARN_RE = re.compile(r"^(?:the |a |an )?(?:short )?name or (?:the )?(?:full )?"
r"(?:arn|amazon resource name \(arn\)) ?(?:of |for )?(?:the |a |an )?(?P<phrase>.+)$")
# The same in the other order: "The Amazon Resource Name (ARN) or short name of the cluster".
DOC_ARN_OR_NAME_RE = re.compile(r"^(?:the |a |an )?(?:full )?(?:arn|amazon resource name \(arn\)) or (?:the )?(?:short )?"
r"name (?:of|for) (?:the |a |an )?(?P<phrase>.+)$")
# Or naming the type before them, anywhere in the documentation: "This can either be the cluster name or ARN".
DOC_TYPE_NAME_OR_ARN_RE = re.compile(r"\bthe (?P<phrase>[a-z][a-z -]*?) name or (?:the )?(?:full )?"
r"(?:arn|amazon resource name \(arn\))\b")
def name_or_arn_members(models: dict[str, dict], operation: str) -> dict[str, str]:
@@ -1281,6 +1333,42 @@ def name_or_arn_members(models: dict[str, dict], operation: str) -> dict[str, st
return found
def documented_name_or_arn_members(models: dict[str, dict], operation: str) -> dict[str, str]:
"""The top-level string members of the operation's request whose documentation says it is a name or an ARN of a
type ("The short name or full Amazon Resource Name (ARN) of the cluster"), by name, each with the resource type
word of that ARN."""
found: dict[str, str] = {}
for model in models.values():
spec = model["operations"].get(operation)
if spec is None or "input" not in spec or not READ_PROTOCOLS & _protocols(model):
continue
for name, member in model["shapes"][spec["input"]["shape"]].get("members", {}).items():
word = _documented_name_or_arn(member.get("documentation")) \
if member.get("location") in BODY_LOCATIONS and model["shapes"][member["shape"]]["type"] == "string" \
else None
if word:
found.setdefault(name, word)
return found
def _documented_name_or_arn(documentation: str | None) -> str | None:
"""The resource type word of the ARN a member's documentation says it holds instead of a name: `cluster` for "The
short name or full Amazon Resource Name (ARN) of the cluster that hosts the service", or with its `of` left out
("(ARN)the cluster"), the two the other way round ("The Amazon Resource Name (ARN) or short name of the
cluster"), or the type before them ("This can either be the cluster name or ARN"); None for any other."""
lead = _lead(documentation)
match = DOC_NAME_OR_ARN_RE.match(lead) or DOC_ARN_OR_NAME_RE.match(lead) \
or DOC_TYPE_NAME_OR_ARN_RE.search(_lead_text(documentation))
if not match:
return None
words = []
for word in match.group("phrase").split():
if word in DOC_STOP:
break
words.append(word)
return "-".join(words) or None
def _name_or_arn(shape: dict) -> str | None:
"""The resource type word of the ARN a string shape's pattern takes before a name; None for another shape."""
match = NAME_OR_ARN_RE.match(shape.get("pattern") or "") if shape["type"] == "string" else None
@@ -1294,14 +1382,18 @@ def named_by(word: str, formats: dict[str, str]) -> str | None:
return found[0] if len(found) == 1 else None
def with_arn_of(resources: list[dict], formats: dict[str, str], members: dict[str, str]) -> list[dict]:
def with_arn_of(resources: list[dict], formats: dict[str, str], members: dict[str, str],
documented: dict[str, str] | None = None) -> list[dict]:
"""The resources, each a type named by its variables reading a member that may give an ARN of a type instead of
its name, as that type's one variable."""
its name, as that type's one variable: one whose pattern takes it, or one whose documentation says so of another
type than the resource's (an ECS service's `cluster`), an ARN of its own type naming it already."""
found = []
for resource in resources:
read = {path.removesuffix("[]") for path in resource.get("fill", {}).values()} | set(resource.get("when", {})) \
| set(resource.get("unless", {}))
arn_of = {member: named_by(members[member], formats) for member in sorted(read) if member in members}
arn_of |= {member: kind for member in sorted(read) if member in (documented or {}) and member not in arn_of
for kind in [named_by(documented[member], formats)] if kind != resource.get("type")}
arn_of = {member: kind for member, kind in arn_of.items() if kind is not None}
found.append(dict(resource, arnOf={**resource.get("arnOf", {}), **arn_of})
if "fill" in resource and "default" not in resource and arn_of else resource)
@@ -2011,21 +2103,62 @@ def read_resources(operation: str, types: list[str], formats: dict[str, str], mo
requested_members(models)),
types, members, through_members(models, formats))
resources = with_documented(operation, types, formats, models, resources)
resources = with_typed_targets(resources, formats, typed_target_fields(models, name))
optional = optional_members(models, name)
resources = with_absent_arn(resources, formats, optional)
resources = with_absent_account(resources, formats, account_members(models, name), optional)
resources = with_map_fields(resources, types, formats, map_fields(models, name))
resources = with_account(resources, formats, account_members(models, name))
resources = with_structure_account(resources, formats, structure_account_members(models, name, types))
resources = with_arn_of(resources, formats, name_or_arn_members(models, name))
resources = with_arn_of(resources, formats, name_or_arn_members(models, name),
documented_name_or_arn_members(models, name))
resources = with_default_pairs(resources, formats, optional)
resources = with_enum_named(operation, resources, formats, models)
resources = with_subject_through(operation, resources, members, map_fields(models, name), optional, models)
resources = with_documented_defaults(resources, formats, defaulted_members(models, name))
resources = with_optional_qualifier(resources, optional)
# Two rules naming the same resource the same way name it once.
return [resource for index, resource in enumerate(resources) if resource not in resources[:index]]
def typed_target_fields(models: dict[str, dict], operation: str) -> dict[str, list[str]]:
"""The id fields of each element of a top-level list of structures in the operation's request beside a field of
the same stem holding the target's type, an enum (`attributes[].targetId` beside `targetType`), by their path, each
with that enum's values."""
found: dict[str, list[str]] = {}
for model in models.values():
spec = model["operations"].get(operation)
if spec is None or "input" not in spec or _reading(model) != "all":
continue
for name, member in model["shapes"][spec["input"]["shape"]].get("members", {}).items():
shape = model["shapes"][member["shape"]]
element = model["shapes"][shape["member"]["shape"]] if shape["type"] == "list" else {}
fields = element.get("members", {}) if element.get("type") == "structure" else {}
for field, nested in fields.items():
kind = fields.get(field[:-2] + "Type") if field.endswith("Id") else None
enum = model["shapes"][kind["shape"]].get("enum") if kind else None
if enum and model["shapes"][nested["shape"]]["type"] == "string":
found.setdefault(f"{name}[].{field}", list(enum))
return found
def with_typed_targets(resources: list[dict], formats: dict[str, str], typed: dict[str, list[str]]) -> list[dict]:
"""The resources, a type named by its variables taking the last one no member fills from each element's id field
whose target type enum has that type alone: ECS's `PutAttributes` attaches each attribute to the container
instance its `targetId` names, its `targetType` being `container-instance`."""
found = []
for resource in resources:
fill = resource.get("fill")
variables = [v for v in VARIABLE_RE.findall(formats.get(resource.get("type"), "")) if v not in KNOWN_VARIABLES]
paths = [path for path, kinds in typed.items() if kinds == [resource.get("type")]]
if fill is None or "find" in resource or not variables or variables[-1] in fill or len(paths) != 1 \
or any("[]" in path for path in fill.values()):
found.append(resource)
continue
found.append(dict(resource, fill=dict(sorted({**fill, variables[-1]: paths[0]}.items()))))
return found
def with_enum_named(operation: str, resources: list[dict], formats: dict[str, str],
models: dict[str, dict]) -> list[dict]:
"""The resources, a variable no member fills of a type named by its variables `fixed` to the one value of an enum
@@ -2227,15 +2360,59 @@ def named_by_variable(variable: str, formats: dict[str, str]) -> str | None:
return found[0] if len(found) == 1 else None
# Documentation saying what a service uses for a member a request leaves out: "If you do not specify a cluster, the
# default cluster is assumed", "If you don't specify a cluster, default is used".
DOC_DEFAULT_RE = re.compile(r"\bif you do(?: not|n't) specify an? ([a-z][a-z -]*?), (?:the )?default(?: [a-z -]+?)? is "
r"(?:assumed|used)\b")
def defaulted_members(models: dict[str, dict], operation: str) -> dict[str, str]:
"""The optional top-level members of the operation's request, strings or lists of them, whose documentation says
its service uses its default of a type for a request leaving them out, by their path, each with the word it
names that type by: ECS's `cluster`, "If you do not specify a cluster, the default cluster is assumed"."""
found: dict[str, str] = {}
for model in models.values():
spec = model["operations"].get(operation)
if spec is None or "input" not in spec or _reading(model) != "all":
continue
shape = model["shapes"][spec["input"]["shape"]]
for name, member in shape.get("members", {}).items():
strings = _strings(model, model["shapes"][member["shape"]])
said = DOC_DEFAULT_RE.search(_lead_text(member.get("documentation")))
if name not in shape.get("required", []) and strings is not None and said:
found.setdefault(name + strings, said.group(1).replace(" ", "-"))
return found
def with_documented_defaults(resources: list[dict], formats: dict[str, str], defaulted: dict[str, str]) -> list[dict]:
"""The resources, each variable of a type named by its variables filled from a member whose documentation says its
service uses its default for a request leaving it out marked so (`defaults`), when the variable is the one of a
type whose format is that variable alone named by the word the documentation uses: a service's
`service/${ClusterName}/${ServiceName}` is on the default cluster, `cluster/${ClusterName}`, for a request with
no `cluster`. The reader asks the type's service for that default."""
found = []
for resource in resources:
defaults = {}
for variable, path in resource.get("fill", {}).items():
kind = named_by_variable(variable, formats)
if path in defaulted and kind is not None and related(stem(defaulted[path]), stem(kind)):
defaults[path] = kind
found.append(dict(resource, defaults=dict(sorted(defaults.items()))) if defaults and "type" in resource
and not {"when", "unless", "find", "default"} & set(resource) else resource)
return found
def with_optional_qualifier(resources: list[dict], optional: set[str]) -> list[dict]:
"""The resources, one filling a variable from an optional member no other resource reads, beside another it
fills from a member that is, named only when the request gives that member: Redshift's `GetClusterCredentials`
checks the database it names only 'If the DbName parameter is specified'."""
checks the database it names only 'If the DbName parameter is specified'. A member naming its service's default
when left out (`defaults`) names one then."""
read = [path for resource in resources for path in resource.get("fill", {}).values()]
found = []
for resource in resources:
fill = resource.get("fill", {})
own = [path for path in fill.values() if path in optional and read.count(path) == 1]
own = [path for path in fill.values() if path in optional and read.count(path) == 1
and path not in resource.get("defaults", {})]
if len(fill) >= 2 and len(own) == 1 and len(own) < len(fill) \
and not {"when", "unless", "find", "whenDefault", "unlessDefault"} & set(resource):
resource = dict(resource, unless={own[0]: [None]})
@@ -2693,7 +2870,8 @@ def _resource_problems(operation: str, resource: object, types: set[str], format
"endpoint"}
or {"type", "fill"} <= set(resource) <= {"type", "fill", "when", "unless", "arnOf", "account",
"fixed", "made", "find", "endpoint",
"default", "whenDefault", "unlessDefault"}):
"default", "whenDefault", "unlessDefault",
"defaults"}):
return [f"{operation} names {resource!r}, which is neither an ARN member nor a type's variables"]
for key in ("whenDefault", "unlessDefault"):
pair = resource.get(key)
@@ -2725,9 +2903,10 @@ def _resource_problems(operation: str, resource: object, types: set[str], format
fill = resource["fill"]
find = resource.get("find", [])
if not isinstance(find, list) or ("find" in resource and (not find or fill or set(resource) & FOUND_ONLY)) \
or not all(isinstance(path, str) and PATH_RE.match(path) and not path.endswith("[]") for path in find):
return [f"{operation} finds {kinds[0]} by {find!r}, which are no members of one value each, or beside a fill "
f"or members reading it otherwise"]
or not all(isinstance(path, str) and PATH_RE.match(path) and (not path.endswith("[]") or len(find) == 1)
for path in find):
return [f"{operation} finds {kinds[0]} by {find!r}, which are no members of one value each or one list, or "
f"beside a fill or members reading it otherwise"]
variables = set(VARIABLE_RE.findall(formats[kinds[0]])) - KNOWN_VARIABLES
if not isinstance(fill, dict) or set(fill) - variables or not all(
isinstance(path, str) and FILL_PATH_RE.match(path) for path in fill.values()):
@@ -2747,6 +2926,14 @@ def _resource_problems(operation: str, resource: object, types: set[str], format
and len(set(VARIABLE_RE.findall(formats.get(kind, ""))) - KNOWN_VARIABLES) == 1
and formats[kind].endswith("}") for path, kind in arn_of.items()):
return [f"{operation} reads {arn_of!r} as ARNs of types, which are no members or types of one variable"]
defaults = resource.get("defaults", {})
if not isinstance(defaults, dict) or ("defaults" in resource and not defaults) or not all(
isinstance(kind, str) and kind in formats and variable in fill and fill[variable] == path
and ONE_VARIABLE_RE.match(_resource(formats[kind])) and _resource(formats[kind]).endswith("${" + variable + "}")
for path, kind in defaults.items()
for variable in [next((v for v, p in fill.items() if p == path), "")]):
return [f"{operation} names {defaults!r} as defaults of types, which are no members filling a variable that is "
f"such a type's alone"]
account = resource.get("account")
if account is not None and (not isinstance(account, str) or not PATH_RE.match(account) or account.endswith("[]")
or "${Account}" not in formats[kinds[0]]):
+126 -2
View File
@@ -737,10 +737,19 @@ def test_a_well_formed_document_validates():
fill={"GroupName": "Group.Name"}, fixed={"GroupId": "g-1"}, made=True)
document["operations"]["svc:A"]["resources"][0]["made"] = True
assert r.validate(document) == []
# A type whose ARN is all an id its service mints, found by the members naming it.
# A type whose ARN is all an id its service mints, found by the members naming it, or each value of one list.
document = good_document()
document["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Namespace", "Id"])
assert r.validate(document) == []
document["operations"]["svc:B"]["resources"][0].update(find=["Ids[]"])
assert r.validate(document) == []
# A member filling the one variable of another type's format names that type's default when left out.
document = good_document()
document["arnFormats"]["svc"]["service"] = "arn:${Partition}:svc:${Region}:${Account}:service/${ThingName}/${Name}"
document["operations"]["svc:A"]["types"] = ["service"]
document["operations"]["svc:A"]["resources"] = [{"type": "service", "fill": {"ThingName": "thing", "Name": "Names[]"},
"defaults": {"thing": "thing"}}]
assert r.validate(document) == []
# A resource named through a member naming another of its service's own, which it runs on, or through each
# value of a list's field when another member is absent.
document = good_document()
@@ -820,7 +829,11 @@ def with_a_create() -> dict:
(lambda d: d.pop("mintedIds"), "mintedIds"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(find=["Namespace"]), "beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=[]), "beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Ids[]"]), "beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Ids[]", "Namespace"]), "beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(defaults={"Names[]": "thing"}), "defaults of types"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(defaults={"Other": "thing"}), "defaults of types"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(defaults={}), "defaults of types"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(defaults=["thing"]), "defaults of types"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find="Namespace"), "beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Namespace"], fixed={"GroupId": "g"}),
"beside a fill"),
@@ -1684,6 +1697,117 @@ def test_a_resource_one_optional_member_qualifies_is_named_only_when_the_request
assert r.with_optional_qualifier(resources, {"ClusterIdentifier"}) == resources
CLUSTERS = {"cluster": "arn:${Partition}:svc:${Region}:${Account}:cluster/${ClusterName}",
"service": "arn:${Partition}:svc:${Region}:${Account}:service/${ClusterName}/${ServiceName}",
"task-definition": "arn:${Partition}:svc:${Region}:${Account}:task-definition/"
"${TaskDefinitionFamilyName}:${TaskDefinitionRevisionNumber}"}
def cluster_model(operation: str, docs: dict[str, str], required: tuple[str, ...] = ()) -> dict[str, dict]:
"""A JSON model whose operation takes `docs`' members, `Names` lists for those ending in `s`, others strings."""
shapes = {"String": {"type": "string"}, "Names": {"type": "list", "member": {"shape": "String"}},
"In": {"type": "structure", "required": list(required), "members": {
name: {"shape": "Names" if name.endswith("s") else "String", "documentation": doc}
for name, doc in docs.items()}}}
return {"svc": {"metadata": {"protocol": "json"}, "operations": {operation: {"input": {"shape": "In"}}},
"shapes": shapes}}
CLUSTER_DOC = ("<p>The short name or full Amazon Resource Name (ARN) of the cluster that hosts the service to describe. "
"If you do not specify a cluster, the default cluster is assumed.</p>")
def test_a_member_whose_service_uses_its_default_when_left_out_names_that_default():
# ECS: "If you do not specify a cluster, the default cluster is assumed", or "default is used".
assert r.defaulted_members(cluster_model("DescribeServices", {"cluster": CLUSTER_DOC}), "DescribeServices") == {
"cluster": "cluster"}
assert r.defaulted_members(cluster_model("ListThings", {"cluster": "<p>If you don't specify a cluster, default is "
"used.</p>"}), "ListThings") == {"cluster": "cluster"}
assert r.defaulted_members(cluster_model("DescribeClusters", {"clusters": "<p>A list of up to 100 cluster names. If "
"you do not specify a cluster, the default "
"cluster is assumed.</p>"}),
"DescribeClusters") == {"clusters[]": "cluster"}
# A required member is never left out, and one documenting no default names none.
assert r.defaulted_members(cluster_model("DeleteCluster", {"cluster": CLUSTER_DOC}, ("cluster",)),
"DeleteCluster") == {}
assert r.defaulted_members(cluster_model("DescribeThing", {"cluster": "<p>The name of the cluster.</p>"}),
"DescribeThing") == {}
service = {"type": "service", "fill": {"ClusterName": "cluster", "ServiceName": "services[]"}}
defaulted = dict(service, defaults={"cluster": "cluster"})
assert r.with_documented_defaults([service], CLUSTERS, {"cluster": "cluster"}) == [defaulted]
# Only the default of the type whose format is that variable alone, named by the documentation's word.
assert r.with_documented_defaults([service], CLUSTERS, {"cluster": "pool"}) == [service]
assert r.with_documented_defaults([service], CLUSTERS, {"serviceName": "service"}) == [service]
# Named then, not only when the request gives it.
assert r.with_optional_qualifier([defaulted], {"cluster"}) == [defaulted]
assert r.with_optional_qualifier([service], {"cluster"}) == [dict(service, unless={"cluster": [None]})]
def test_a_member_documented_as_a_name_or_an_arn_of_another_type_may_give_that_types_arn():
for doc in (CLUSTER_DOC, "<p>The short name or full ARN of the cluster that hosts the task.</p>",
# AWS's own typo, the "of" left out.
"<p>The short name or full Amazon Resource Name (ARN)the cluster that hosts the service to describe.</p>",
# The two the other way round, and the type before them past the first sentence.
"<p>The Amazon Resource Name (ARN) or short name of the cluster the task is running in.</p>",
"<p>The cluster that hosts the service. This can either be the cluster name or ARN.</p>"):
assert r.documented_name_or_arn_members(cluster_model("DescribeServices", {"cluster": doc}),
"DescribeServices") == {"cluster": "cluster"}
assert r.documented_name_or_arn_members(cluster_model("DescribeServices", {"cluster": "<p>The name of the cluster."
"</p>"}), "DescribeServices") == {}
service = {"type": "service", "fill": {"ClusterName": "cluster", "ServiceName": "service"}}
cluster = {"type": "cluster", "fill": {"ClusterName": "cluster"}}
assert r.with_arn_of([service, cluster], CLUSTERS, {}, {"cluster": "cluster"}) == [
dict(service, arnOf={"cluster": "cluster"}), cluster]
# A pattern taking the ARN says so of the resource's own type too.
assert r.with_arn_of([cluster], CLUSTERS, {"cluster": "cluster"}) == [dict(cluster, arnOf={"cluster": "cluster"})]
def test_each_elements_id_whose_target_type_is_one_type_fills_that_types_last_variable():
shapes = {"String": {"type": "string"}, "TargetType": {"type": "string", "enum": ["container-instance"]},
"Attribute": {"type": "structure", "members": {"name": {"shape": "String"},
"targetType": {"shape": "TargetType"},
"targetId": {"shape": "String"}}},
"Attributes": {"type": "list", "member": {"shape": "Attribute"}},
"In": {"type": "structure", "members": {"cluster": {"shape": "String"},
"attributes": {"shape": "Attributes"}}}}
models = {"svc": {"metadata": {"protocol": "json"}, "operations": {"PutAttributes": {"input": {"shape": "In"}}},
"shapes": shapes}}
typed = r.typed_target_fields(models, "PutAttributes")
assert typed == {"attributes[].targetId": ["container-instance"]}
formats = {"container-instance": "arn:${Partition}:svc:${Region}:${Account}:container-instance/${ClusterName}/"
"${ContainerInstanceId}"}
instance = {"type": "container-instance", "fill": {"ClusterName": "cluster"}}
assert r.with_typed_targets([instance], formats, typed) == [
{"type": "container-instance", "fill": {"ClusterName": "cluster",
"ContainerInstanceId": "attributes[].targetId"}}]
# Not a type the enum does not name alone, nor a variable a member fills already.
assert r.with_typed_targets([instance], formats, {"attributes[].targetId": ["container-instance", "task"]}) == [
instance]
filled = {"type": "container-instance", "fill": {"ClusterName": "cluster", "ContainerInstanceId": "instance"}}
assert r.with_typed_targets([filled], formats, typed) == [filled]
def test_a_type_of_two_variables_its_documentation_spells_is_found_by_its_service():
assert r.spelled("task-definition", CLUSTERS["task-definition"]) == "(family:revision)"
assert r.spelled("service", CLUSTERS["service"]) is None
assert r.spelled("cluster", CLUSTERS["cluster"]) is None
run = cluster_model("RunTask", {"taskDefinition": "<p>The <code>family</code> and <code>revision</code> (<code>"
"family:revision</code>) or full ARN of the task definition to "
"run.</p>"})
# Read neither as an ARN alone nor left unnamed: its service resolves a family to its latest revision.
assert r.with_documented("svc:RunTask", ["task-definition"], CLUSTERS, run, []) == [
{"type": "task-definition", "fill": {}, "find": ["taskDefinition"]}]
delete = cluster_model("DeleteTaskDefinitions", {"taskDefinitions": "<p>The family and revision (family:revision)"
" or full Amazon Resource Name (ARN) of the "
"task definition to delete.</p>"})
assert r.with_documented("svc:DeleteTaskDefinitions", ["task-definition"], CLUSTERS, delete, []) == [
{"type": "task-definition", "fill": {}, "find": ["taskDefinitions[]"]}]
# A member holding the ARN alone still names it as one.
by_arn = cluster_model("RunTask", {"definition": "<p>The full ARN of the task definition to run.</p>"})
assert r.with_documented("svc:RunTask", ["task-definition"], CLUSTERS, by_arn, []) == [
{"types": ["task-definition"], "arn": "definition"}]
def test_an_arn_patterns_type_words_and_a_clients_versioned_twin():
assert r.pattern_words("arn:aws:svc:[a-z0-9-]+:([0-9]{12}):(bus-v2|subscriber|source-v2\\/(a|b))\\/[A-Za-z]+") == {
"bus-v2", "subscriber", "source-v2"}