mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(iam): check a create's tags on its own and its tagging action (#6452)
Under IAM enforcement a request that tags the resource it creates was checked only for the operation's own action. AWS also checks the service's tagging action, as the SNS API reference says: "To be able to tag a topic on creation, you must have the sns:CreateTopic and sns:TagResource permissions." A caller allowed to create but not to tag could set at creation the tags that a tag-based policy trusts. The operation's own action did not see the tags either: aws:RequestTag and aws:TagKeys were set only for Logs, S3 and EC2 RunInstances, so a policy allowing sqs:CreateQueue only with aws:RequestTag/team never matched, and one denying it when aws:RequestTag/team is null refused a tagged create. AWS's Service Reference lists the tagging action among each operation's authorized actions and marks the actions that only tag, but does not say which request member carries the tags; botocore's models do. A new generator, tools/aws/regen_iam_tag_on_create.py, joins the two into src/main/resources/aws/iam-tag-on-create.json: 581 operations over 69 namespaces, those Floci authorizes by operation. An operation is in it when the reference lists, beside its own, an action that only tags and adds tags; its tags are read from a top-level member named Tags, TagList, TagSpecifications or the like that holds a tag list or map. 569 are read from the table (579 members), CloudWatch Logs CreateLogGroup is checked by hand as before, and 11 carry no tags this file can read, each with its reason. A correction gives SQS's Query name, Tag.N, and one drops an EC2 IPAM pool's allocation rule, which tags nothing. When a request carries tags, IamEnforcementFilter checks the tagging action for each resource's tags apart, with them as aws:RequestTag/<key> and aws:TagKeys, and, where the action takes it, the operation as its namespace's CreateAction key (ec2:CreateAction is RunInstances for an instance launched with tags). A tag specification's tags are checked on the resource of the type it names, from the ARN the reference gives the type with its name left open (arn:aws:ec2:<Region>:<account>:instance/*), which the table carries for EC2 and RDS; other tags on the resources the operation is checked on. Lambda's CreateFunction is now checked on the function its body names, which the reference gives it, rather than on *, so a grant scoped to the function covers both its action and its tags. The operation's own action is checked with the same two keys, once for each resource's tags, where the reference lists them for it or for a resource it acts on (542 of the 569), keeping any a service's own condition keys set. The table is keyed by operation, so the filter now carries the operation it resolved beside the action, which differs for an operation AWS authorizes under another name (Budgets' CreateBudget is budgets:ModifyBudget). The tags are read as the Floci handler that applies them reads them, so the check sees the tags the resource gets. A form's are read under the SDK's spelling, from 1 to the first number with no key, and under the further spellings the RDS, DocumentDB, Neptune, ElastiCache and Redshift handlers read, numbered as each numbers them; EC2's from every tag specification under either TagSpecification spelling, to the first naming no resource type. A body's member is read under its own name, and CloudWatch's PutMetricAlarm and PutCompositeAlarm also under tags, and a CodeDeploy tag as Key and Value or key and value, each as text whatever it holds, as its handler reads. The tagging action is also checked for tags under any other spelling a handler might read (a name, key or value in any case, any list spelling and number, an object's structures), so none a handler applies goes unchecked. The operation's own action is checked with every reading, its handler's, any other spelling's, and none where its handler reads none, and refused if any is denied, so a deny on a tag holds and a required tag counts only where the handler applies it. make iam-tag-on-create-check, part of aws-data-check, re-derives every member from the pinned botocore; make iam-tag-on-create-verify, part of iam-data-verify, checks every operation against AWS, and the IAM data drift workflow also runs on a change to the table or its generator. Not checked: sts:TagSession in a role's trust policy, service-specific request tag keys such as rds:req-tag, EC2 RequestSpotFleet's nested tags, and the REST services whose routes no rule maps yet.
This commit is contained in:
1 parent
36e244f104
commit
64f4f9e489
18 files changed
+3632
-26
No files matched your search
@@ -501,12 +501,16 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
conditionContext = conditionContext == null ? new HashMap<>() : new HashMap<>(conditionContext);
|
||||
callerArns.get().putPrincipalKeys(conditionContext);
|
||||
}
|
||||
List<Map<String, List<String>>> targetContexts = new ArrayList<>();
|
||||
targetContexts.add(conditionContext);
|
||||
// A create that carries tags is checked with them where its own action takes them, as the tagging
|
||||
// action it also needs is (see TagOnCreate); keys the service's own resolver gives are kept.
|
||||
Optional<TagOnCreate.Tagging> tagOnCreate = TagOnCreate.of(resolvedAuthorization.operation(), ctx);
|
||||
List<Map<String, List<String>>> requestTags = tagOnCreate.filter(TagOnCreate.Tagging::requestTags)
|
||||
.map(TagOnCreate::requestTagContexts).orElse(List.of());
|
||||
List<Map<String, List<String>>> targetContexts = withRequestTags(conditionContext, requestTags);
|
||||
for (Map<String, List<String>> target : remainingTargets) {
|
||||
Map<String, List<String>> targetContext = new HashMap<>(target);
|
||||
callerArns.ifPresent(arns -> arns.putPrincipalKeys(targetContext));
|
||||
targetContexts.add(targetContext);
|
||||
targetContexts.addAll(withRequestTags(targetContext, requestTags));
|
||||
}
|
||||
|
||||
RequestPrincipal principal = RequestPrincipal.caller(callerArns.orElse(null));
|
||||
@@ -534,6 +538,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
region, accountId, akid)) {
|
||||
return;
|
||||
}
|
||||
if (tagOnCreate.isPresent() && abortIfTagOnCreateDenied(ctx, caller, principal, callerArns.orElse(null),
|
||||
action, resolvedAuthorization.operation(), tagOnCreate.get(), credentialScope, resources, region,
|
||||
accountId, akid)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Tagged group creation requires either tagging permission, using the same resolved
|
||||
// caller (including session, boundary and SCP ceilings) as the primary operation.
|
||||
@@ -733,7 +742,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
.map(descriptor -> iamServiceScope(descriptor, claimedScope))
|
||||
.orElseGet(() -> catalog.canonicalCredentialScope(service));
|
||||
return new ResolvedAuthorization(servingScope,
|
||||
IamAuthorizedActions.actionFor(servingScope, queryAction));
|
||||
IamAuthorizedActions.actionFor(servingScope, queryAction), servingScope + ":" + queryAction);
|
||||
}
|
||||
|
||||
// Read from the route rather than the claim: a path the claim filter takes for RPC v2 can
|
||||
@@ -745,7 +754,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
}
|
||||
String servingScope = iamServiceScope(rpcV2Route.service(), claimedScope);
|
||||
return new ResolvedAuthorization(servingScope,
|
||||
actionRegistry.resolveOperation(servingScope, rpcV2Route.operation(), ctx));
|
||||
actionRegistry.resolveOperation(servingScope, rpcV2Route.operation(), ctx),
|
||||
servingScope + ":" + rpcV2Route.operation());
|
||||
}
|
||||
|
||||
ResolvedAuthorization routeAuthorization = restRouteAuthorization(ctx);
|
||||
@@ -756,9 +766,13 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
// A REST request is authorized by its route alone, never by an X-Amz-Target it carries.
|
||||
boolean rest = claimValue instanceof ProtocolClaim claim && claim.protocol() == WireProtocol.REST;
|
||||
String servingScope = servingCredentialScope(claimedScope, ctx);
|
||||
return new ResolvedAuthorization(servingScope, rest
|
||||
? actionRegistry.resolveRoute(servingScope, ctx)
|
||||
: actionRegistry.resolve(servingScope, ctx));
|
||||
if (rest) {
|
||||
return new ResolvedAuthorization(servingScope, actionRegistry.resolveRoute(servingScope, ctx));
|
||||
}
|
||||
String targetOperation = IamActionRegistry.targetOperation(ctx);
|
||||
String action = actionRegistry.resolve(servingScope, ctx);
|
||||
return targetOperation == null ? new ResolvedAuthorization(servingScope, action)
|
||||
: new ResolvedAuthorization(servingScope, action, servingScope + ":" + targetOperation);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -896,7 +910,15 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private record ResolvedAuthorization(String credentialScope, String action) {
|
||||
/**
|
||||
* The scope and action a request is authorized as, and the operation it calls as
|
||||
* {@code <namespace>:<Operation>}, which differs from the action for one AWS authorizes under another name.
|
||||
* A REST route maps straight to its action, which names the operation.
|
||||
*/
|
||||
private record ResolvedAuthorization(String credentialScope, String action, String operation) {
|
||||
ResolvedAuthorization(String credentialScope, String action) {
|
||||
this(credentialScope, action, action);
|
||||
}
|
||||
}
|
||||
|
||||
/** Floci's account-root principal, which is both the caller and the request's aws:PrincipalArn. */
|
||||
@@ -933,6 +955,52 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The context once for each set of tags the request carries, with that set's keys where the context has
|
||||
* none of its own, so each resource's tags are checked apart; the context alone when it carries none.
|
||||
*/
|
||||
private static List<Map<String, List<String>>> withRequestTags(Map<String, List<String>> context,
|
||||
List<Map<String, List<String>>> requestTags) {
|
||||
List<Map<String, List<String>>> contexts = new ArrayList<>();
|
||||
if (requestTags.isEmpty()) {
|
||||
contexts.add(context);
|
||||
}
|
||||
for (Map<String, List<String>> tags : requestTags) {
|
||||
Map<String, List<String>> withTags = context == null ? new HashMap<>() : new HashMap<>(context);
|
||||
tags.forEach(withTags::putIfAbsent);
|
||||
contexts.add(withTags);
|
||||
}
|
||||
return contexts;
|
||||
}
|
||||
|
||||
/**
|
||||
* A request that tags what it creates also needs the service's tagging action (see {@link TagOnCreate}),
|
||||
* checked as the caller for each set of tags, under any spelling a handler might read: on the resource a
|
||||
* tag specification names, else on the
|
||||
* resources the operation is checked on, with the set's tags as {@code aws:RequestTag/<key>} and
|
||||
* {@code aws:TagKeys}, the operation as the namespace's {@code CreateAction} key where the tagging action
|
||||
* takes one, and the keys that say who is calling. Returns true when the request was aborted.
|
||||
*/
|
||||
private boolean abortIfTagOnCreateDenied(ContainerRequestContext ctx, CallerContext caller,
|
||||
RequestPrincipal principal, CallerArns callerArns, String action,
|
||||
String operation, TagOnCreate.Tagging tagging,
|
||||
String credentialScope, List<String> resources,
|
||||
String region, String accountId, String akid) {
|
||||
for (TagOnCreate.TagSet set : tagging.checked()) {
|
||||
Map<String, List<String>> context = TagOnCreate.conditionContext(tagging, set, operation);
|
||||
if (callerArns != null) {
|
||||
callerArns.putPrincipalKeys(context);
|
||||
}
|
||||
List<String> tagged = TagOnCreate.resources(operation, set, requestPartition(), region, accountId,
|
||||
resources);
|
||||
if (abortIfDenied(ctx, caller, principal, tagging.action(), action, credentialScope, tagged,
|
||||
List.of(context), region, accountId, akid)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** What {@link PassedRoles} looks up, in the request's account and Region. */
|
||||
private PassedRoles.Lookups lookupsFor(String accountId, String region) {
|
||||
return new PassedRoles.Lookups() {
|
||||
|
||||
@@ -112,20 +112,29 @@ final class PassedRoleMembers {
|
||||
|
||||
private static Member member(String operation, JsonNode role) {
|
||||
String path = role.path("member").asText("");
|
||||
List<Step> steps = steps(path);
|
||||
if (steps == null) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads " + operation + " at " + path
|
||||
+ ", which is no member path");
|
||||
}
|
||||
String passedTo = role.hasNonNull("passedTo") ? role.get("passedTo").asText() : null;
|
||||
return new Member(path, steps, queryKeys(steps), passedTo, role.path("byName").asBoolean(false));
|
||||
}
|
||||
|
||||
/** The steps of a vendored member path; null when {@code path} is none. */
|
||||
static List<Step> steps(String path) {
|
||||
List<Step> steps = new ArrayList<>();
|
||||
for (String step : path.split("\\.", -1)) {
|
||||
Matcher matcher = STEP.matcher(step);
|
||||
if (!matcher.matches()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads " + operation + " at " + path
|
||||
+ ", which is no member path");
|
||||
return null;
|
||||
}
|
||||
Into into = matcher.group(2) != null ? Into.LIST : matcher.group(3) == null ? Into.NONE
|
||||
: matcher.group(3).isEmpty() ? Into.MAP : Into.KEY;
|
||||
String key = into == Into.LIST ? matcher.group(2) : into == Into.KEY ? matcher.group(3) : null;
|
||||
steps.add(new Step(matcher.group(1), into, key));
|
||||
}
|
||||
String passedTo = role.hasNonNull("passedTo") ? role.get("passedTo").asText() : null;
|
||||
return new Member(path, List.copyOf(steps), queryKeys(steps), passedTo, role.path("byName").asBoolean(false));
|
||||
return List.copyOf(steps);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -888,7 +888,7 @@ final class PassedRoles {
|
||||
* A gzip-encoded body is decompressed first, as {@code AwsJsonCborController} decompresses it before
|
||||
* running the request.
|
||||
*/
|
||||
private static JsonNode jsonBody(ContainerRequestContext ctx) {
|
||||
static JsonNode jsonBody(ContainerRequestContext ctx) {
|
||||
if (ctx.getProperty(IamConditionContextResolver.BUFFERED_JSON_BODY) instanceof JsonNode cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The tagging action a request that tags what it creates also needs, and the tags it attaches.
|
||||
*
|
||||
* <p>AWS checks the service's tagging action as well as the operation's own when the request carries
|
||||
* tags: the SNS API reference has "To be able to tag a topic on creation, you must have the
|
||||
* {@code sns:CreateTopic} and {@code sns:TagResource} permissions." Which action each operation needs and
|
||||
* where its request carries the tags come from {@link TagOnCreateMembers}, generated from AWS's Service
|
||||
* Reference and botocore. The operation's own action is checked with the tags too, where the Service
|
||||
* Reference lists {@code aws:RequestTag} or {@code aws:TagKeys} for it. The operations in {@link #BY_HAND}
|
||||
* need one of several tagging actions, and {@code IamEnforcementFilter} checks them itself.
|
||||
*
|
||||
* <p>The tags are read as the Floci handler that applies them reads them, so the check sees the tags the
|
||||
* resource gets: a form's tag list from 1 to the first number with no key, under the spellings the
|
||||
* handler reads, and a body's member under its own name. Each resource's tags are a set of their own,
|
||||
* checked apart: a member's, or a tag specification's for each type of resource it names.
|
||||
*/
|
||||
final class TagOnCreate {
|
||||
|
||||
/** Operations the enforcement filter checks itself: CloudWatch Logs takes either of two tagging actions. */
|
||||
static final Set<String> BY_HAND = Set.of("logs:CreateLogGroup");
|
||||
|
||||
/** CloudWatch's handler reads an alarm's tags from {@code tags} when the body has no {@code Tags}. */
|
||||
private static final Set<String> LOWER_CASE_TAGS = Set.of("cloudwatch:PutMetricAlarm", "cloudwatch:PutCompositeAlarm");
|
||||
|
||||
/**
|
||||
* CodeDeploy's handler reads a tag as {@code Key} and {@code Value}, or as {@code key} and {@code value} when it
|
||||
* has no {@code Key}.
|
||||
*/
|
||||
private static final Set<String> EITHER_CASE_TAGS = Set.of("codedeploy");
|
||||
|
||||
/**
|
||||
* The tags one resource gets, and the type of that resource where a tag specification names it, else null.
|
||||
*/
|
||||
record TagSet(String resourceType, Map<String, String> tags) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The tagging action a request needs, each set of tags it attaches as its handler reads them, the further
|
||||
* sets it carries under spellings another handler might read, whether the action takes the CreateAction key,
|
||||
* and whether the operation's own action takes the tags as well.
|
||||
*/
|
||||
record Tagging(String action, List<TagSet> sets, List<TagSet> otherSpellings, boolean createAction,
|
||||
boolean requestTags) {
|
||||
|
||||
/** Every set the tagging action is checked for, so no tag a handler might apply goes unchecked. */
|
||||
List<TagSet> checked() {
|
||||
List<TagSet> checked = new ArrayList<>(sets);
|
||||
checked.addAll(otherSpellings);
|
||||
return checked;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How a Floci Query handler numbers a tag list: from 1 to the first number with no key, every number there
|
||||
* is, or from 1 to the first number at which none of the prefixes has a key or a value.
|
||||
*/
|
||||
private enum Numbering { TO_FIRST_GAP, EVERY, EITHER_AT_EACH }
|
||||
|
||||
/** The prefixes a handler numbers a tag list under, in the order it reads them, and its tags' key and value. */
|
||||
private record Reading(List<String> prefixes, Numbering numbering, String key, String value) {
|
||||
}
|
||||
|
||||
private TagOnCreate() {
|
||||
}
|
||||
|
||||
/**
|
||||
* What a request for {@code operation}, as {@code <namespace>:<Operation>}, needs to tag what it creates:
|
||||
* empty when the table does not read the operation or the request carries no tags. A tag's key given
|
||||
* twice keeps its last value, as the services keep it.
|
||||
*/
|
||||
static Optional<Tagging> of(String operation, ContainerRequestContext ctx) {
|
||||
TagOnCreateMembers.Entry entry = TagOnCreateMembers.of(operation);
|
||||
if (entry == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
|
||||
JsonNode body = form.isEmpty() ? PassedRoles.jsonBody(ctx) : null;
|
||||
Set<TagSet> sets = new LinkedHashSet<>();
|
||||
Set<TagSet> otherSpellings = new LinkedHashSet<>();
|
||||
for (TagOnCreateMembers.Member member : entry.members()) {
|
||||
if (!form.isEmpty()) {
|
||||
if (member.inForm()) {
|
||||
sets.addAll(fromForm(form, operation, member));
|
||||
}
|
||||
otherSpellings.addAll(anySpellingInForm(form, member));
|
||||
} else if (body != null && body.isObject()) {
|
||||
Map<String, Map<String, String>> byType = new LinkedHashMap<>();
|
||||
collect(topLevel(body, operation, member.steps().getFirst().name()), member,
|
||||
EITHER_CASE_TAGS.contains(operation.substring(0, operation.indexOf(':'))), 0, null, byType);
|
||||
byType.forEach((type, tags) -> add(sets, type, tags));
|
||||
otherSpellings.addAll(anySpellingInBody(body, member));
|
||||
}
|
||||
}
|
||||
// A set already in one the handler reads, of the same resource type, adds nothing to check.
|
||||
otherSpellings.removeIf(other -> sets.stream().anyMatch(set -> Objects.equals(set.resourceType(),
|
||||
other.resourceType()) && set.tags().entrySet().containsAll(other.tags().entrySet())));
|
||||
return sets.isEmpty() && otherSpellings.isEmpty() ? Optional.empty()
|
||||
: Optional.of(new Tagging(entry.tagging(), List.copyOf(sets), List.copyOf(otherSpellings),
|
||||
entry.createAction(), entry.requestTags()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags a form carries at the member under any spelling a handler might read: its names in any case and
|
||||
* a trailing {@code s} dropped, any one word between a list's name and its numbers, every number, and the
|
||||
* tag's key and value in any case. One set for each spelling, and for a tag specification each resource type.
|
||||
*/
|
||||
private static List<TagSet> anySpellingInForm(Map<String, String> form, TagOnCreateMembers.Member member) {
|
||||
List<PassedRoleMembers.Step> steps = member.querySteps();
|
||||
if (!member.inForm()) {
|
||||
return List.of();
|
||||
}
|
||||
String key = member.key() == null ? "key" : member.key();
|
||||
String value = member.value() == null ? "value" : member.value();
|
||||
String list = "(?:\\.[A-Za-z]+)?\\.\\d+";
|
||||
Pattern name = Pattern.compile(steps.size() == 1
|
||||
? "(?<tag>(?<spelling>" + anyCase(steps.getFirst().name()) + "(?:\\.[A-Za-z]+)?)\\.\\d+)\\.(?<field>(?i:"
|
||||
+ Pattern.quote(key) + "|" + Pattern.quote(value) + "))"
|
||||
: "(?<tag>(?<specification>" + anyCase(steps.getFirst().name()) + list + ")\\.(?<spelling>"
|
||||
+ anyCase(steps.get(1).name()) + "(?:\\.[A-Za-z]+)?)\\.\\d+)\\.(?<field>(?i:"
|
||||
+ Pattern.quote(key) + "|" + Pattern.quote(value) + "))");
|
||||
Map<String, Map<String, String>> sets = new LinkedHashMap<>();
|
||||
Map<String, String[]> tags = new LinkedHashMap<>();
|
||||
Map<String, String> setOfTag = new HashMap<>();
|
||||
form.forEach((parameter, given) -> {
|
||||
Matcher matcher = name.matcher(parameter);
|
||||
if (!matcher.matches()) {
|
||||
return;
|
||||
}
|
||||
String set = matcher.group("spelling").toLowerCase(Locale.ROOT);
|
||||
if (steps.size() == 2) {
|
||||
String specification = matcher.group("specification");
|
||||
String type = member.resourceType() == null ? null : form.entrySet().stream()
|
||||
.filter(e -> e.getKey().equalsIgnoreCase(specification + "." + member.resourceType()))
|
||||
.map(Map.Entry::getValue).findFirst().orElse(null);
|
||||
set = specification.replaceAll("\\.\\d+$", "").toLowerCase(Locale.ROOT) + "|" + set + "|" + type;
|
||||
}
|
||||
String tag = matcher.group("tag").toLowerCase(Locale.ROOT);
|
||||
setOfTag.put(tag, set);
|
||||
tags.computeIfAbsent(tag, ignored -> new String[2])[matcher.group("field").equalsIgnoreCase(key) ? 0 : 1] = given;
|
||||
});
|
||||
tags.forEach((tag, pair) -> {
|
||||
if (pair[0] != null) {
|
||||
sets.computeIfAbsent(setOfTag.get(tag), ignored -> new LinkedHashMap<>())
|
||||
.put(pair[0], pair[1] == null ? "" : pair[1]);
|
||||
}
|
||||
});
|
||||
List<TagSet> found = new ArrayList<>();
|
||||
sets.forEach((set, read) -> {
|
||||
String type = steps.size() == 2 ? set.substring(set.lastIndexOf('|') + 1) : null;
|
||||
found.add(new TagSet("null".equals(type) ? null : type, Collections.unmodifiableMap(read)));
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The name in any case, and without a trailing {@code s} too, as {@code Tag.N} stands for {@code Tags}. */
|
||||
private static String anyCase(String name) {
|
||||
String stem = name.endsWith("s") ? name.substring(0, name.length() - 1) : name;
|
||||
return "(?i:" + Pattern.quote(name) + (stem.equals(name) ? "" : "|" + Pattern.quote(stem)) + ")";
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags a body carries at the member under any spelling a handler might read: its names, and a tag's
|
||||
* key and value, in any case, and a list or a map whichever the member is. One set for each top-level
|
||||
* spelling, and for a tag specification each resource type.
|
||||
*/
|
||||
private static List<TagSet> anySpellingInBody(JsonNode body, TagOnCreateMembers.Member member) {
|
||||
List<TagSet> found = new ArrayList<>();
|
||||
body.properties().forEach(top -> {
|
||||
if (!top.getKey().equalsIgnoreCase(member.steps().getFirst().name())) {
|
||||
return;
|
||||
}
|
||||
Map<String, Map<String, String>> byType = new LinkedHashMap<>();
|
||||
anySpelling(top.getValue(), member, 0, null, byType);
|
||||
byType.forEach((type, tags) -> {
|
||||
if (!tags.isEmpty()) {
|
||||
found.add(new TagSet(type, Collections.unmodifiableMap(tags)));
|
||||
}
|
||||
});
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
private static void anySpelling(JsonNode value, TagOnCreateMembers.Member member, int index, String type,
|
||||
Map<String, Map<String, String>> byType) {
|
||||
List<PassedRoleMembers.Step> steps = member.steps();
|
||||
if (value == null) {
|
||||
return;
|
||||
}
|
||||
if (index == steps.size() - 1) {
|
||||
Map<String, String> tags = byType.computeIfAbsent(type, ignored -> new LinkedHashMap<>());
|
||||
// Every element is a tag, its key as text whatever it holds and a missing one empty, as a handler that
|
||||
// reads it with asText takes it; an object's values that are structures are elements too, as a handler
|
||||
// iterating it reads them, and its members are a map's tags.
|
||||
for (JsonNode tag : value) {
|
||||
if (value.isObject() && !tag.isObject()) {
|
||||
continue;
|
||||
}
|
||||
JsonNode key = field(tag, member.key() == null ? "key" : member.key());
|
||||
tags.put(key == null || key.isNull() ? "" : key.asText(),
|
||||
text(field(tag, member.value() == null ? "value" : member.value())));
|
||||
}
|
||||
if (value.isObject()) {
|
||||
value.properties().forEach(tag -> tags.put(tag.getKey(), tag.getValue().isNull() ? ""
|
||||
: tag.getValue().asText()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
String next = steps.get(index + 1).name();
|
||||
if (value.isArray()) {
|
||||
for (JsonNode element : value) {
|
||||
JsonNode kind = member.resourceType() == null ? null : field(element, member.resourceType());
|
||||
anySpelling(field(element, next), member, index + 1,
|
||||
kind != null && kind.isTextual() ? kind.asText() : type, byType);
|
||||
}
|
||||
} else if (value.isObject()) {
|
||||
anySpelling(field(step(value, steps.get(index)), next), member, index + 1, type, byType);
|
||||
}
|
||||
}
|
||||
|
||||
/** A structure under a step that names a map's key, or the structure itself. */
|
||||
private static JsonNode step(JsonNode value, PassedRoleMembers.Step step) {
|
||||
return step.into() == PassedRoleMembers.Into.KEY ? field(value, step.key()) : value;
|
||||
}
|
||||
|
||||
/** A tag's value as text, empty when it has none. */
|
||||
private static String text(JsonNode value) {
|
||||
return value == null || value.isNull() ? "" : value.asText();
|
||||
}
|
||||
|
||||
/** The object's member {@code name} in any case; null for no such member, or no object. */
|
||||
private static JsonNode field(JsonNode node, String name) {
|
||||
if (node == null || !node.isObject()) {
|
||||
return null;
|
||||
}
|
||||
JsonNode exact = node.get(name);
|
||||
return exact != null ? exact : node.propertyStream().filter(member -> member.getKey().equalsIgnoreCase(name))
|
||||
.map(Map.Entry::getValue).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
private static void add(Set<TagSet> sets, String type, Map<String, String> tags) {
|
||||
if (!tags.isEmpty()) {
|
||||
sets.add(new TagSet(type, Collections.unmodifiableMap(tags)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The sets of tags a form carries at the member, as each handler that may serve the operation reads it: a
|
||||
* tag list's tags, or each tag specification's, from 1 to the first without a resource type, by its type.
|
||||
*/
|
||||
private static List<TagSet> fromForm(Map<String, String> form, String operation, TagOnCreateMembers.Member member) {
|
||||
boolean ec2 = operation.startsWith("ec2:");
|
||||
List<PassedRoleMembers.Step> steps = member.querySteps();
|
||||
Set<TagSet> sets = new LinkedHashSet<>();
|
||||
for (Reading reading : readings(operation, member, ec2)) {
|
||||
if (steps.size() == 1) {
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
read(form, reading, tags);
|
||||
add(sets, null, tags);
|
||||
continue;
|
||||
}
|
||||
Map<String, Map<String, String>> byType = new LinkedHashMap<>();
|
||||
for (String specifications : reading.prefixes()) {
|
||||
for (int i = 1; ; i++) {
|
||||
String specification = specifications + "." + i;
|
||||
String type = member.resourceType() == null ? null
|
||||
: form.get(specification + "." + member.resourceType());
|
||||
if (member.resourceType() != null ? type == null : noneUnder(form, specification)) {
|
||||
break;
|
||||
}
|
||||
read(form, gap(member, specification + "." + sdkPrefix(steps.get(1), ec2)),
|
||||
byType.computeIfAbsent(type, ignored -> new LinkedHashMap<>()));
|
||||
}
|
||||
}
|
||||
byType.forEach((type, tags) -> add(sets, type, tags));
|
||||
}
|
||||
return List.copyOf(sets);
|
||||
}
|
||||
|
||||
/**
|
||||
* How the Floci Query handler that serves the operation reads the member's tags. Most read the SDK's own
|
||||
* spelling, from 1 to the first number with no key; these read more, each as its handler does. Several
|
||||
* handlers serve the {@code rds} namespace and read its spellings in different orders, so each order is
|
||||
* read, and each set it gives is checked.
|
||||
*/
|
||||
private static List<Reading> readings(String operation, TagOnCreateMembers.Member member, boolean ec2) {
|
||||
PassedRoleMembers.Step first = member.querySteps().getFirst();
|
||||
return switch (operation.substring(0, operation.indexOf(':') + 1) + first.name()) {
|
||||
// Ec2QueryHandler.parseTagsForResource
|
||||
case "ec2:TagSpecification", "ec2:TagSpecifications" ->
|
||||
List.of(gap(member, "TagSpecification", "TagSpecifications"));
|
||||
// SqsQueryHandler
|
||||
case "sqs:Tag" -> List.of(new Reading(List.of("Tag"), Numbering.TO_FIRST_GAP, "Key", "Value"));
|
||||
// RdsQueryHandler and DocDbQueryHandler, then NeptuneQueryHandler
|
||||
case "rds:Tags" -> List.of(gap(member, "Tags.member", "Tags.Tag", "Tag"),
|
||||
gap(member, "Tags.Tag", "Tags.member", "Tag"));
|
||||
// ElastiCacheServerlessQueryHandler, else ElastiCacheQueryHandler
|
||||
case "elasticache:Tags" -> "elasticache:CreateServerlessCache".equals(operation)
|
||||
? List.of(new Reading(List.of("Tags.Tag", "Tags.member"), Numbering.EITHER_AT_EACH,
|
||||
member.key(), member.value()))
|
||||
: List.of(gap(member, "Tags.Tag", "Tags.member", "Tag"));
|
||||
// RedshiftQueryHandler
|
||||
case "redshift:Tags" -> List.of(gap(member, "Tags.member", "Tags.Tag"));
|
||||
case "redshift:TagList" -> List.of(new Reading(List.of("TagList.Tag"), Numbering.EVERY,
|
||||
member.key(), member.value()));
|
||||
default -> List.of(gap(member, sdkPrefix(first, ec2)));
|
||||
};
|
||||
}
|
||||
|
||||
private static Reading gap(TagOnCreateMembers.Member member, String... prefixes) {
|
||||
return new Reading(List.of(prefixes), Numbering.TO_FIRST_GAP,
|
||||
member.key() == null ? "key" : member.key(), member.value() == null ? "value" : member.value());
|
||||
}
|
||||
|
||||
/**
|
||||
* The prefix an SDK numbers a list or a map under: EC2 numbers a list under its name, the Query protocol
|
||||
* under the name its shape gives elements, or {@code member}, and a map's entries under {@code entry}.
|
||||
*/
|
||||
private static String sdkPrefix(PassedRoleMembers.Step step, boolean ec2) {
|
||||
if (step.into() == PassedRoleMembers.Into.MAP) {
|
||||
return step.name() + ".entry";
|
||||
}
|
||||
return ec2 ? step.name() : step.name() + "." + (step.key().isEmpty() ? "member" : step.key());
|
||||
}
|
||||
|
||||
private static boolean noneUnder(Map<String, String> form, String prefix) {
|
||||
return form.keySet().stream().noneMatch(name -> name.startsWith(prefix + "."));
|
||||
}
|
||||
|
||||
/** The tags the form numbers under the reading's prefixes, a tag with no value taking an empty one. */
|
||||
private static void read(Map<String, String> form, Reading reading, Map<String, String> tags) {
|
||||
switch (reading.numbering()) {
|
||||
case TO_FIRST_GAP -> {
|
||||
for (String prefix : reading.prefixes()) {
|
||||
for (int i = 1; ; i++) {
|
||||
String key = form.get(prefix + "." + i + "." + reading.key());
|
||||
if (key == null) {
|
||||
break;
|
||||
}
|
||||
tags.put(key, form.getOrDefault(prefix + "." + i + "." + reading.value(), ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
case EVERY -> {
|
||||
for (String prefix : reading.prefixes()) {
|
||||
Pattern name = Pattern.compile(Pattern.quote(prefix) + "\\.\\d+\\." + Pattern.quote(reading.key()));
|
||||
form.forEach((parameter, key) -> {
|
||||
if (name.matcher(parameter).matches() && key != null && !key.isBlank()) {
|
||||
String stem = parameter.substring(0, parameter.length() - reading.key().length());
|
||||
tags.put(key, form.getOrDefault(stem + reading.value(), ""));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
case EITHER_AT_EACH -> {
|
||||
for (int i = 1; ; i++) {
|
||||
String key = null;
|
||||
String value = null;
|
||||
for (String prefix : reading.prefixes()) {
|
||||
key = form.get(prefix + "." + i + "." + reading.key());
|
||||
value = form.get(prefix + "." + i + "." + reading.value());
|
||||
if (key != null || value != null) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (key == null || key.isBlank()) {
|
||||
break;
|
||||
}
|
||||
tags.put(key, value == null ? "" : value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags a body carries at the member, by the resource type of the tag specification they are in, null
|
||||
* outside one.
|
||||
*/
|
||||
private static void collect(JsonNode value, TagOnCreateMembers.Member member, boolean eitherCase, int index,
|
||||
String type, Map<String, Map<String, String>> byType) {
|
||||
List<PassedRoleMembers.Step> steps = member.steps();
|
||||
PassedRoleMembers.Step step = steps.get(index);
|
||||
if (index == steps.size() - 1) {
|
||||
Map<String, String> tags = byType.computeIfAbsent(type, ignored -> new LinkedHashMap<>());
|
||||
// CodeDeployJsonHandler iterates the member whatever it holds, which for an object is its values.
|
||||
if (step.into() == PassedRoleMembers.Into.LIST && value != null
|
||||
&& (value.isArray() || eitherCase && value.isObject())) {
|
||||
for (JsonNode tag : value) {
|
||||
if (eitherCase) {
|
||||
// As CodeDeployJsonHandler reads it: as text whatever it holds, a missing key an empty one.
|
||||
boolean lower = !tag.has(member.key());
|
||||
tags.put(tag.path(lower ? member.key().toLowerCase(Locale.ROOT) : member.key()).asText(),
|
||||
tag.path(lower ? member.value().toLowerCase(Locale.ROOT) : member.value()).asText());
|
||||
continue;
|
||||
}
|
||||
JsonNode key = tag.get(member.key());
|
||||
if (key != null && key.isValueNode() && !key.isNull()) {
|
||||
tags.put(key.asText(), text(tag.get(member.value())));
|
||||
}
|
||||
}
|
||||
} else if (step.into() == PassedRoleMembers.Into.MAP && value != null && value.isObject()) {
|
||||
value.properties().forEach(tag -> tags.put(tag.getKey(), tag.getValue().isNull() ? ""
|
||||
: tag.getValue().asText()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (value == null || !value.isContainerNode()) {
|
||||
return;
|
||||
}
|
||||
String next = steps.get(index + 1).name();
|
||||
switch (step.into()) {
|
||||
case NONE -> collect(value.get(next), member, eitherCase, index + 1, type, byType);
|
||||
case KEY -> collect(value.path(step.key()).get(next), member, eitherCase, index + 1, type, byType);
|
||||
case LIST, MAP -> {
|
||||
if (step.into() == PassedRoleMembers.Into.LIST ? value.isArray() : value.isObject()) {
|
||||
for (JsonNode element : value) {
|
||||
JsonNode kind = member.resourceType() == null ? null : element.get(member.resourceType());
|
||||
collect(element.get(next), member, eitherCase, index + 1,
|
||||
kind != null && kind.isTextual() ? kind.asText() : type, byType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The body's member {@code name}, or CloudWatch's {@code tags} where its handler reads an alarm's tags from it. */
|
||||
private static JsonNode topLevel(JsonNode body, String operation, String name) {
|
||||
if (!body.has(name) && "Tags".equals(name) && LOWER_CASE_TAGS.contains(operation)) {
|
||||
return body.get("tags");
|
||||
}
|
||||
return body.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* The condition keys a set of tags is checked with on the tagging action: each tag as
|
||||
* {@code aws:RequestTag/<key>}, their keys as {@code aws:TagKeys}, and, when the tagging action takes it,
|
||||
* the operation as its namespace's {@code CreateAction} key.
|
||||
*/
|
||||
static Map<String, List<String>> conditionContext(Tagging tagging, TagSet set, String operation) {
|
||||
Map<String, List<String>> context = requestTagContext(set);
|
||||
if (tagging.createAction()) {
|
||||
String namespace = tagging.action().substring(0, tagging.action().indexOf(':'));
|
||||
context.put(namespace + ":CreateAction", List.of(operation.substring(operation.indexOf(':') + 1)));
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
* The request's tags as condition keys, once for each reading of them: each tag as {@code aws:RequestTag/<key>}
|
||||
* and their keys as {@code aws:TagKeys}. The operation's own action is checked with each when it takes them, as
|
||||
* {@link Tagging#requestTags()} says, and refused if any is denied: the sets its handler reads, the sets under
|
||||
* any other spelling, and no tags where its handler reads none. So a deny on a tag holds whichever reading a
|
||||
* handler applies, and a create that requires a tag gets it only where the handler applies it.
|
||||
*/
|
||||
static List<Map<String, List<String>>> requestTagContexts(Tagging tagging) {
|
||||
List<Map<String, List<String>>> contexts = new ArrayList<>();
|
||||
if (tagging.sets().isEmpty() && !tagging.otherSpellings().isEmpty()) {
|
||||
// The handler applies none of the tags it reads, so a create that requires a tag does not get it.
|
||||
contexts.add(new HashMap<>());
|
||||
}
|
||||
for (TagSet set : tagging.checked()) {
|
||||
contexts.add(requestTagContext(set));
|
||||
}
|
||||
return contexts;
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> requestTagContext(TagSet set) {
|
||||
Map<String, List<String>> context = new HashMap<>();
|
||||
set.tags().forEach((key, value) -> context.put("aws:RequestTag/" + key, List.of(value)));
|
||||
context.put("aws:TagKeys", List.copyOf(set.tags().keySet()));
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
* The resources a set of tags goes to: for a tag specification's, the ARN the table gives its type, in the
|
||||
* request's partition, Region and account, as AWS checks the tagging action on the resource being tagged;
|
||||
* otherwise {@code resources}, the ones the operation itself is checked on.
|
||||
*/
|
||||
static List<String> resources(String operation, TagSet set, String partition, String region, String accountId,
|
||||
List<String> resources) {
|
||||
if (set.resourceType() == null) {
|
||||
return resources;
|
||||
}
|
||||
String arn = TagOnCreateMembers.table().resourceArns()
|
||||
.getOrDefault(operation.substring(0, operation.indexOf(':')), Map.of()).get(set.resourceType());
|
||||
return arn == null ? resources : List.of(arn.replace("${Partition}", partition)
|
||||
.replace("${Region}", region).replace("${Account}", accountId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Which tagging action each operation that tags what it creates needs, and where its request carries the
|
||||
* tags, read once from the vendored {@code aws/iam-tag-on-create.json}.
|
||||
*
|
||||
* <p>The file is generated by {@code tools/aws/regen_iam_tag_on_create.py} from AWS's Service Reference,
|
||||
* which lists the tagging action among an operation's authorized actions, and from botocore's model of the
|
||||
* request, which gives the members that carry the tags. Every operation of the namespaces it reads is in it
|
||||
* once: with the members to read, as one Floci checks by hand, or as one whose request carries no tags it
|
||||
* can read. {@code make iam-tag-on-create-check} re-derives every member from botocore and
|
||||
* {@code make iam-tag-on-create-verify} checks every operation against AWS.
|
||||
*
|
||||
* <p>A missing or malformed resource is a build defect, so loading fails with
|
||||
* {@link IllegalStateException} rather than leaving every operation it reads unchecked.
|
||||
*/
|
||||
final class TagOnCreateMembers {
|
||||
|
||||
static final String RESOURCE_NAME = "aws/iam-tag-on-create.json";
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* A member of a request that carries tags: a list of tag structures, whose key and value members are
|
||||
* named {@code key} and {@code value}, or a map, for which both are null. {@code steps} lead to it in a
|
||||
* JSON or CBOR body, the last one into the list or the map, and {@code querySteps} in the Query protocol's
|
||||
* form parameters. A list of tag specifications names the member of each specification that gives the type
|
||||
* of the resource its tags go to as {@code resourceType}, null for any other member.
|
||||
*/
|
||||
record Member(String path, List<PassedRoleMembers.Step> steps, List<PassedRoleMembers.Step> querySteps,
|
||||
String key, String value, String resourceType) {
|
||||
|
||||
/** Whether a form can carry the member: a top-level tag list or map, or a list of tag specifications. */
|
||||
boolean inForm() {
|
||||
return querySteps.size() == 1
|
||||
|| querySteps.size() == 2 && querySteps.getFirst().into() == PassedRoleMembers.Into.LIST;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What an operation needs: one tagging action, whether it takes the CreateAction key, whether the
|
||||
* operation's own action takes the request's tags as well, and its members.
|
||||
*/
|
||||
record Entry(String tagging, boolean createAction, boolean requestTags, List<Member> members) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The file: the entries read from it, the operations checked by hand or not read, and, for each namespace
|
||||
* whose tag specifications name a resource type, the ARN of each type, still holding {@code ${Partition}},
|
||||
* {@code ${Region}} and {@code ${Account}}.
|
||||
*/
|
||||
record Table(Map<String, Entry> entries, Set<String> byHand, Set<String> notRead,
|
||||
Set<String> namespaces, Set<String> notCovered, Set<String> otherNamespaces,
|
||||
Map<String, Map<String, String>> resourceArns) {
|
||||
}
|
||||
|
||||
private static final class Holder {
|
||||
static final Table TABLE = VendoredResources.read(RESOURCE_NAME, "IAM tag-on-create table",
|
||||
TagOnCreateMembers::parse);
|
||||
}
|
||||
|
||||
private TagOnCreateMembers() {
|
||||
}
|
||||
|
||||
/** What a request for {@code operation}, as {@code <namespace>:<Operation>}, needs; null when this table does not read it. */
|
||||
static Entry of(String operation) {
|
||||
return Holder.TABLE.entries().get(operation);
|
||||
}
|
||||
|
||||
static Table table() {
|
||||
return Holder.TABLE;
|
||||
}
|
||||
|
||||
static Table parse(InputStream in) throws IOException {
|
||||
JsonNode document = MAPPER.readTree(in);
|
||||
JsonNode operations = document.path("operations");
|
||||
if (!operations.isObject() || operations.isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " carries no operations");
|
||||
}
|
||||
Map<String, Entry> entries = new LinkedHashMap<>();
|
||||
Set<String> byHand = new LinkedHashSet<>();
|
||||
Set<String> notRead = new LinkedHashSet<>();
|
||||
operations.properties().forEach(operation -> {
|
||||
JsonNode entry = operation.getValue();
|
||||
if (entry.has("byHand")) {
|
||||
byHand.add(operation.getKey());
|
||||
} else if (entry.has("notRead")) {
|
||||
notRead.add(operation.getKey());
|
||||
} else if (entry.path("tags").isArray() && !entry.path("tags").isEmpty()
|
||||
&& entry.path("tagging").isArray() && entry.path("tagging").size() == 1) {
|
||||
List<Member> members = new ArrayList<>();
|
||||
for (JsonNode member : entry.path("tags")) {
|
||||
members.add(member(operation.getKey(), member));
|
||||
}
|
||||
entries.put(operation.getKey(), new Entry(entry.path("tagging").get(0).asText(),
|
||||
entry.path("createAction").asBoolean(false), entry.path("requestTags").asBoolean(false),
|
||||
List.copyOf(members)));
|
||||
} else {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " says nothing usable for " + operation.getKey());
|
||||
}
|
||||
});
|
||||
Map<String, Map<String, String>> resourceArns = new LinkedHashMap<>();
|
||||
document.path("resourceArns").properties().forEach(namespace -> {
|
||||
Map<String, String> types = new LinkedHashMap<>();
|
||||
namespace.getValue().properties().forEach(type -> {
|
||||
if (!type.getValue().asText("").startsWith("arn:${Partition}:")) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " gives " + namespace.getKey() + "'s "
|
||||
+ type.getKey() + " no ARN");
|
||||
}
|
||||
types.put(type.getKey(), type.getValue().asText());
|
||||
});
|
||||
resourceArns.put(namespace.getKey(), Map.copyOf(types));
|
||||
});
|
||||
entries.forEach((operation, entry) -> {
|
||||
if (entry.members().stream().anyMatch(member -> member.resourceType() != null)
|
||||
&& !resourceArns.containsKey(operation.substring(0, operation.indexOf(':')))) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " names the resource types " + operation
|
||||
+ " tags, but gives no ARN for them");
|
||||
}
|
||||
});
|
||||
return new Table(Map.copyOf(entries), Set.copyOf(byHand), Set.copyOf(notRead),
|
||||
Set.copyOf(document.path("namespaces").propertyStream().map(Map.Entry::getKey).toList()),
|
||||
Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
|
||||
Set.copyOf(document.path("otherNamespaces").valueStream().map(JsonNode::asText).toList()),
|
||||
Map.copyOf(resourceArns));
|
||||
}
|
||||
|
||||
private static Member member(String operation, JsonNode member) {
|
||||
String path = member.path("member").asText("");
|
||||
List<PassedRoleMembers.Step> steps = PassedRoleMembers.steps(path);
|
||||
String key = member.hasNonNull("key") ? member.get("key").asText() : null;
|
||||
String value = member.hasNonNull("value") ? member.get("value").asText() : null;
|
||||
PassedRoleMembers.Into last = steps == null ? null : steps.getLast().into();
|
||||
if (last != PassedRoleMembers.Into.LIST && last != PassedRoleMembers.Into.MAP
|
||||
|| (last == PassedRoleMembers.Into.LIST) != (key != null && value != null)) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads " + operation + " at " + path
|
||||
+ ", which is no path to a tag list or map");
|
||||
}
|
||||
List<PassedRoleMembers.Step> querySteps = member.hasNonNull("query")
|
||||
? PassedRoleMembers.steps(member.get("query").asText()) : steps;
|
||||
if (querySteps == null || querySteps.getLast().into() != last) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads " + operation + "'s tags at " + path
|
||||
+ " from a form by no path to a tag list or map");
|
||||
}
|
||||
String resourceType = member.hasNonNull("resourceType") ? member.get("resourceType").asText() : null;
|
||||
if (resourceType != null && (steps.size() < 2 || steps.getFirst().into() != PassedRoleMembers.Into.LIST)) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads " + operation + "'s tags at " + path
|
||||
+ " by resource type, though they are no list of tag specifications");
|
||||
}
|
||||
return new Member(path, steps, querySteps, key, value, resourceType);
|
||||
}
|
||||
}
|
||||
@@ -542,15 +542,20 @@ public class IamActionRegistry {
|
||||
}
|
||||
|
||||
// JSON 1.1: X-Amz-Target → the action AWS checks for the operation it names
|
||||
String target = ctx.getHeaderString("X-Amz-Target");
|
||||
if (target != null && target.contains(".")) {
|
||||
String operationName = target.substring(target.lastIndexOf('.') + 1);
|
||||
String operationName = targetOperation(ctx);
|
||||
if (operationName != null) {
|
||||
return resolveOperation(credentialScope, operationName, ctx);
|
||||
}
|
||||
|
||||
return resolveRoute(credentialScope, ctx);
|
||||
}
|
||||
|
||||
/** The operation a JSON request's {@code X-Amz-Target} names, the part after its last dot; null without one. */
|
||||
public static String targetOperation(ContainerRequestContext ctx) {
|
||||
String target = ctx.getHeaderString("X-Amz-Target");
|
||||
return target != null && target.contains(".") ? target.substring(target.lastIndexOf('.') + 1) : null;
|
||||
}
|
||||
|
||||
/** The action for a dispatched operation, including statement-dependent JSON and CBOR calls. */
|
||||
public String resolveOperation(String credentialScope, String operationName, ContainerRequestContext ctx) {
|
||||
if ("dynamodb".equals(credentialScope) && "ExecuteStatement".equals(operationName)) {
|
||||
|
||||
@@ -773,7 +773,9 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
// path: /2015-03-31/functions/name or similar
|
||||
String name = extractSegmentAfter(path, "functions");
|
||||
if (name == null) return "*";
|
||||
if (name == null) {
|
||||
return createdFunctionArn(path, ctx, region, accountId);
|
||||
}
|
||||
boolean qualifiedTarget = path.endsWith("/functions/" + name + "/invocations")
|
||||
|| path.endsWith("/functions/" + name + "/response-streaming-invocations")
|
||||
|| path.endsWith("/functions/" + name + "/provisioned-concurrency");
|
||||
@@ -801,6 +803,30 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The function {@code CreateFunction} makes, which its body names, in the caller's account and Region, as
|
||||
* every route but an invoke acts there: the Service Reference gives it the {@code function} resource, so
|
||||
* its own action, and the tagging action its tags need, are checked on that function. {@code *} for any
|
||||
* other route that names no function.
|
||||
*/
|
||||
private String createdFunctionArn(String path, ContainerRequestContext ctx, String region, String accountId) {
|
||||
if (!"POST".equalsIgnoreCase(ctx.getMethod()) || !"/2015-03-31/functions".equals(path)) {
|
||||
return "*";
|
||||
}
|
||||
JsonNode body = readJsonBody(ctx);
|
||||
JsonNode name = body == null ? null : body.get("FunctionName");
|
||||
if (name == null || !name.isTextual() || name.asText().isEmpty()) {
|
||||
return "*";
|
||||
}
|
||||
try {
|
||||
return AwsArnUtils.Arn.of("lambda", region, accountId,
|
||||
"function:" + LambdaArnUtils.resolve(name.asText()).name()).toString();
|
||||
} catch (AwsException e) {
|
||||
// A name Lambda refuses, which its handler answers with a 400 before creating anything.
|
||||
return AwsArnUtils.Arn.of("lambda", region, accountId, "function:" + name.asText()).toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource of a Lambda event source mapping, code signing config or layer route, as the Service
|
||||
* Reference gives it. A mapping is looked up by its UUID, a config by the id that ends its ARN and a
|
||||
|
||||
Reference in new issue
Block a user