mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(iam): check requests on the resources they name (#6511)
Under IAM enforcement a request is checked against the resources it acts on. ResourceArnBuilder builds their ARNs by hand for 17 namespaces; every other request was checked on *, so a grant scoped to a resource was refused and a deny scoped to one never applied. AWS's Service Reference lists the resource types each action acts on and each type's ARN formats, but not which request member names a resource; botocore's models give the members. A new generator, tools/aws/regen_iam_request_resources.py, joins the two into src/main/resources/aws/iam-request-resources.json: for each operation, the action it is checked as, that action's resource types and the resources its request names, by a member holding a resource's ARN or by members filling the variables of a type's format, matched by name. A variable nothing fills is left open, as a service mints a new resource's id; a type nothing names is not checked, as an action lists the optional resources its requests may use; and types named only through the same members are alternatives, of which the one named in full is kept. Corrections give a v2 CreateLoadBalancer the load balancer of its Type, application when it gives none (a Type outside application, network and gateway is now refused, as AWS refuses it, rather than read as an application load balancer the table does not name), and read StartExecution's and StartSyncExecution's stateMachineArn up to a #, as Floci runs the machine before Step Functions Local's test case. A state machine's version or alias, stateMachine:<name>:<qualifier>, is checked on the state machine's ARN, as Step Functions authorizes it, so an execution started through one is the state machine's too. RequestResources reads them from a JSON or CBOR body or a Query form, for the namespaces the table reads, and ResourceArnBuilder uses them where it has no branch. They are read for the operation the request is dispatched as, which IamEnforcementFilter resolves and checks the action of (the Query action, the JSON target or the Smithy RPC v2 path's operation), never for an X-Amz-Target or Action the request names again, and as the handlers read them: a list only from a list, a number or a null as its text. A member whose botocore shape is an account id gives the account of the types named by variables: ECR's registryId selects the registry its handler acts in, and a JSON null is no registry, the caller's, as ECR reads it. ECR's BatchGetRepositoryScanningConfiguration, whose AWS request has no registryId, no longer reads one: it acts in the caller's registry, where IAM checks it. An ARN value counts when it matches the format of a type the action acts on; one naming another account or Region is checked as given and as each resource of that name a handler may act on instead, in its account or the caller's and its Region or the request's (ECR's tag handlers keep the ARN's account in the request's Region). A request naming none, or whose action acts on no resource type, stays on *, as AWS checks it. A create's tagging action is checked on the same resources, except where the create makes a resource under a parent its action acts on: CreateListener acts on a load balancer and CreateRule on a listener, and their tags are checked on the new listener or rule, built from the parent's ARN with the type word replaced and its own id open. The table gives these from the formats: a child type's is its parent's with one id appended. So the AWS Load Balancer Controller's policy, which allows AddTags at creation only on target groups and application and network load balancers, and on listeners and rules, now holds. The first namespaces read are Elastic Load Balancing, ECR, Step Functions and Cognito user pools (298 operations); the 99 others Floci serves are listed as not read yet, with their reason, and RequestResourceNamespacesIntegrationTest fails for a served namespace in none of the lists. make iam-request-resources-check, part of aws-data-check, re-derives every operation from the pinned botocore; make iam-request-resources-verify, part of iam-data-verify, checks the actions, types and formats against AWS, and the IAM data drift workflow also runs on a change to the table or its generator. Not in this change: the 99 other namespaces, Query lists other than Name.member.N, identifiers inside structures (SetRulePriorities, CreateStateMachineAlias' routing configuration) and EventBridge.
This commit is contained in:
1 parent
b66ee9ecf0
commit
932af22f4a
20 files changed
+3182
-48
No files matched your search
@@ -427,7 +427,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
}
|
||||
|
||||
List<String> resources = resolveResourceArns(credentialScope,
|
||||
targetResources(credentialScope, action, ctx, region, accountId));
|
||||
targetResources(credentialScope, action, resolvedAuthorization.operation(), ctx, region, accountId));
|
||||
|
||||
Optional<PresignedScope> presignedScope = iamService.presignedScope(akid);
|
||||
if (presignedScope.isPresent()) {
|
||||
@@ -976,7 +976,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
/**
|
||||
* 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
|
||||
* tag specification names, else on the resource a create makes under a parent its action acts on, 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.
|
||||
@@ -986,13 +986,16 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
String operation, TagOnCreate.Tagging tagging,
|
||||
String credentialScope, List<String> resources,
|
||||
String region, String accountId, String akid) {
|
||||
// A create of a resource under a parent its action acts on tags the new one (see RequestResources).
|
||||
List<String> created = RequestResources.created(operation, ctx, AwsRegions.partitionFor(region), region,
|
||||
accountId);
|
||||
List<String> made = created.isEmpty() ? resources : created;
|
||||
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);
|
||||
List<String> tagged = TagOnCreate.resources(operation, set, requestPartition(), region, accountId, made);
|
||||
if (abortIfDenied(ctx, caller, principal, tagging.action(), action, credentialScope, tagged,
|
||||
List.of(context), region, accountId, akid)) {
|
||||
return true;
|
||||
@@ -1583,10 +1586,12 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
/**
|
||||
* Logs and Secrets Manager targets depend on the serving operation and the request's partition, STS
|
||||
* targets on the serving operation;
|
||||
* Scheduler and Pipes targets on the request's partition, which those services mint their ARNs in.
|
||||
* Scheduler and Pipes targets on the request's partition, which those services mint their ARNs in; and the
|
||||
* targets of a namespace the table of request resources reads on {@code operation}, the one the request is
|
||||
* dispatched as (see {@link RequestResources}).
|
||||
*/
|
||||
private List<String> targetResources(String credentialScope, String action, ContainerRequestContext ctx,
|
||||
String region, String accountId) {
|
||||
private List<String> targetResources(String credentialScope, String action, String operation,
|
||||
ContainerRequestContext ctx, String region, String accountId) {
|
||||
if ("logs".equals(credentialScope)) {
|
||||
return arnBuilder.buildLogResources(action, ctx, region, accountId, requestPartition());
|
||||
}
|
||||
@@ -1599,7 +1604,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
if ("scheduler".equals(credentialScope) || "pipes".equals(credentialScope) || "dsql".equals(credentialScope)) {
|
||||
return arnBuilder.buildResources(credentialScope, ctx, region, accountId, requestPartition());
|
||||
}
|
||||
return arnBuilder.buildResources(credentialScope, ctx, region, accountId);
|
||||
return arnBuilder.buildResources(credentialScope, operation, ctx, region, accountId,
|
||||
AwsRegions.partitionFor(region));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
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.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The resources each operation's request names, for the namespaces whose ARNs {@code ResourceArnBuilder} does not
|
||||
* build itself, read once from the vendored {@code aws/iam-request-resources.json}.
|
||||
*
|
||||
* <p>The file is generated by {@code tools/aws/regen_iam_request_resources.py} from AWS's Service Reference, which
|
||||
* lists the resource types each action acts on and each type's ARN formats, and from botocore's model of the
|
||||
* request, which gives the members that name them. {@code make iam-request-resources-check} re-derives every
|
||||
* operation from botocore and {@code make iam-request-resources-verify} checks them 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 checked on {@code *}.
|
||||
*/
|
||||
final class RequestResourceMembers {
|
||||
|
||||
static final String RESOURCE_NAME = "aws/iam-request-resources.json";
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final Pattern VARIABLE = Pattern.compile("\\$\\{(\\w+)}");
|
||||
private static final Pattern MEMBER = Pattern.compile("[A-Za-z][A-Za-z0-9_]*(\\[])?");
|
||||
/** An ARN format's leading resource type word, and the rest of its resource. */
|
||||
private static final Pattern RESOURCE_PART = Pattern.compile(
|
||||
"^arn:\\$\\{Partition}:[^:]*:[^:]*:[^:]*:([A-Za-z][A-Za-z0-9-]*)(.*)$");
|
||||
/** The one id a child type's format appends to its parent's. */
|
||||
private static final Pattern APPENDED_ID = Pattern.compile("[/:]\\$\\{\\w+}");
|
||||
|
||||
/** A top-level request member that holds a string, or a list of them when {@code list}. */
|
||||
record Member(String name, boolean list) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A resource type's ARN format, with {@code ${Partition}}, {@code ${Region}}, {@code ${Account}} and the
|
||||
* variables a request fills, and the pattern an ARN of the type matches; {@code unqualified} when its service
|
||||
* checks an ARN of it given with a qualifier, one more {@code :<name>} past the format, without that qualifier
|
||||
* (Step Functions checks a version or an alias on its state machine's ARN).
|
||||
*/
|
||||
record ArnFormat(String format, Pattern pattern, boolean unqualified) {
|
||||
|
||||
/** The ARN as its service checks it: an unqualified type's without the qualifier it may carry. */
|
||||
String checked(String arn) {
|
||||
if (!unqualified) {
|
||||
return arn;
|
||||
}
|
||||
long colons = format.chars().filter(c -> c == ':').count();
|
||||
int at = -1;
|
||||
for (long found = 0; found <= colons; found++) {
|
||||
at = arn.indexOf(':', at + 1);
|
||||
if (at < 0) {
|
||||
return arn;
|
||||
}
|
||||
}
|
||||
return arn.substring(0, at);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A resource a request names: by a member holding its ARN, which names a resource of one of {@code types} when
|
||||
* it matches the type's format, or by members filling the variables of one type's format, the others open,
|
||||
* only {@code when} each member named has one of its values, an empty one for the member absent, in the
|
||||
* account an {@code account} member gives (ECR's {@code registryId}), or else the request's. An ARN member's
|
||||
* value is read up to the character {@code before}, when there is one, as its handler drops the rest.
|
||||
*/
|
||||
record Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
|
||||
Member account, String before) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A resource a create makes under a parent its action acts on, from a member holding the parent's ARN: the
|
||||
* parent's resource with its leading type word {@code parentWord} replaced by {@code childWord} and an open
|
||||
* id appended after {@code separator} ({@code listener/app/<lb>/<id>/*} under {@code loadbalancer/app/...}).
|
||||
*/
|
||||
record Created(String type, String parent, Member arn, String parentWord, String childWord, String separator) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The file: each operation's resources and the resources it creates under a parent, as
|
||||
* {@code <namespace>:<Operation>}, each namespace's ARN formats, and the namespaces it reads, those built by
|
||||
* hand, those not read yet, and the others with resource types.
|
||||
*/
|
||||
record Table(Map<String, List<Resource>> operations, Map<String, List<Created>> creates,
|
||||
Map<String, Map<String, ArnFormat>> formats, Set<String> namespaces, Set<String> handBuilt,
|
||||
Set<String> notCovered, Set<String> otherNamespaces) {
|
||||
}
|
||||
|
||||
private static final class Holder {
|
||||
static final Table TABLE = VendoredResources.read(RESOURCE_NAME, "IAM request resources table",
|
||||
RequestResourceMembers::parse);
|
||||
}
|
||||
|
||||
private RequestResourceMembers() {
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
Set<String> namespaces = Set.copyOf(document.path("namespaces").propertyStream().map(Map.Entry::getKey).toList());
|
||||
Map<String, Map<String, ArnFormat>> formats = new LinkedHashMap<>();
|
||||
document.path("arnFormats").properties().forEach(namespace -> {
|
||||
Set<String> unqualified = names(document.path("unqualified").path(namespace.getKey()));
|
||||
Map<String, ArnFormat> types = new LinkedHashMap<>();
|
||||
namespace.getValue().properties().forEach(type -> {
|
||||
String format = type.getValue().asText("");
|
||||
if (!format.startsWith("arn:${Partition}:")) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " gives " + namespace.getKey() + "'s "
|
||||
+ type.getKey() + " no ARN format");
|
||||
}
|
||||
types.put(type.getKey(), new ArnFormat(format, pattern(format), unqualified.contains(type.getKey())));
|
||||
});
|
||||
formats.put(namespace.getKey(), Map.copyOf(types));
|
||||
});
|
||||
document.path("unqualified").properties().forEach(namespace -> {
|
||||
Set<String> types = formats.getOrDefault(namespace.getKey(), Map.of()).keySet();
|
||||
if (!namespace.getValue().isArray() || !types.containsAll(names(namespace.getValue()))) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " checks " + namespace.getKey() + "'s "
|
||||
+ namespace.getValue() + " without a qualifier, no types with an ARN format");
|
||||
}
|
||||
});
|
||||
Map<String, List<Resource>> entries = new LinkedHashMap<>();
|
||||
Map<String, List<Created>> creates = new LinkedHashMap<>();
|
||||
operations.properties().forEach(operation -> {
|
||||
String namespace = operation.getKey().substring(0, Math.max(0, operation.getKey().indexOf(':')));
|
||||
if (!namespaces.contains(namespace)) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads " + operation.getKey()
|
||||
+ ", of no namespace it reads");
|
||||
}
|
||||
List<Resource> resources = new ArrayList<>();
|
||||
for (JsonNode resource : operation.getValue().path("resources")) {
|
||||
resources.add(resource(operation.getKey(), resource, formats.getOrDefault(namespace, Map.of())));
|
||||
}
|
||||
entries.put(operation.getKey(), List.copyOf(resources));
|
||||
List<Created> made = new ArrayList<>();
|
||||
for (JsonNode created : operation.getValue().path("creates")) {
|
||||
made.add(created(operation.getKey(), created, formats.getOrDefault(namespace, Map.of())));
|
||||
}
|
||||
if (!made.isEmpty()) {
|
||||
creates.put(operation.getKey(), List.copyOf(made));
|
||||
}
|
||||
});
|
||||
return new Table(Map.copyOf(entries), Map.copyOf(creates), Map.copyOf(formats), namespaces,
|
||||
names(document.path("handBuilt")),
|
||||
Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
|
||||
names(document.path("otherNamespaces")));
|
||||
}
|
||||
|
||||
private static Set<String> names(JsonNode list) {
|
||||
return Set.copyOf(list.valueStream().map(JsonNode::asText).toList());
|
||||
}
|
||||
|
||||
private static Resource resource(String operation, JsonNode resource, Map<String, ArnFormat> formats) {
|
||||
if (resource.has("arn")) {
|
||||
List<String> types = resource.path("types").valueStream().map(JsonNode::asText).toList();
|
||||
if (types.isEmpty() || !formats.keySet().containsAll(types)) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads an ARN for " + operation
|
||||
+ " of types with no format: " + types);
|
||||
}
|
||||
String before = resource.has("before") ? resource.path("before").asText("") : null;
|
||||
if (before != null && before.length() != 1) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads an ARN for " + operation
|
||||
+ " before " + before + ", no one character");
|
||||
}
|
||||
return new Resource(types, member(operation, resource.path("arn").asText("")), Map.of(), Map.of(), null,
|
||||
before);
|
||||
}
|
||||
String type = resource.path("type").asText("");
|
||||
ArnFormat format = formats.get(type);
|
||||
if (format == null || !resource.path("fill").isObject()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " names a " + type + " for " + operation
|
||||
+ ", a type with no format or no variables to fill");
|
||||
}
|
||||
Set<String> variables = Set.copyOf(VARIABLE.matcher(format.format()).results().map(m -> m.group(1)).toList());
|
||||
Map<String, Member> fill = new LinkedHashMap<>();
|
||||
resource.path("fill").properties().forEach(variable -> {
|
||||
if (!variables.contains(variable.getKey())) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " fills " + variable.getKey() + " for " + operation
|
||||
+ ", no variable of " + type + "'s format");
|
||||
}
|
||||
fill.put(variable.getKey(), member(operation, variable.getValue().asText("")));
|
||||
});
|
||||
if (fill.values().stream().filter(Member::list).count() > 1) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " fills " + type + " for " + operation
|
||||
+ " from more than one list");
|
||||
}
|
||||
Map<String, List<String>> when = new LinkedHashMap<>();
|
||||
resource.path("when").properties().forEach(member -> {
|
||||
if (member(operation, member.getKey()).list() || !member.getValue().isArray() || member.getValue().isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " names a " + type + " for " + operation
|
||||
+ " when " + member.getKey() + " has no values");
|
||||
}
|
||||
when.put(member.getKey(), member.getValue().valueStream().map(value -> value.isNull() ? "" : value.asText())
|
||||
.toList());
|
||||
});
|
||||
Member account = resource.has("account") ? member(operation, resource.path("account").asText("")) : null;
|
||||
if (account != null && (account.list() || !format.format().contains("${Account}"))) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " takes " + type + "'s account for " + operation
|
||||
+ " from " + account.name() + ", no member of one account or a type of none");
|
||||
}
|
||||
return new Resource(List.of(type), null, Map.copyOf(fill), Map.copyOf(when), account, null);
|
||||
}
|
||||
|
||||
private static Created created(String operation, JsonNode created, Map<String, ArnFormat> formats) {
|
||||
String type = created.path("type").asText("");
|
||||
String parent = created.path("parent").asText("");
|
||||
Matcher child = formats.containsKey(type) ? RESOURCE_PART.matcher(formats.get(type).format()) : null;
|
||||
Matcher under = formats.containsKey(parent) ? RESOURCE_PART.matcher(formats.get(parent).format()) : null;
|
||||
if (child == null || under == null || !child.matches() || !under.matches()
|
||||
|| child.group(1).equals(under.group(1)) || !child.group(2).startsWith(under.group(2))
|
||||
|| !APPENDED_ID.matcher(child.group(2).substring(under.group(2).length())).matches()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " creates a " + type + " for " + operation
|
||||
+ " under a " + parent + ", no parent of it");
|
||||
}
|
||||
String separator = child.group(2).substring(under.group(2).length(), under.group(2).length() + 1);
|
||||
return new Created(type, parent, member(operation, created.path("arn").asText("")), under.group(1),
|
||||
child.group(1), separator);
|
||||
}
|
||||
|
||||
private static Member member(String operation, String path) {
|
||||
if (!MEMBER.matcher(path).matches()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads " + operation + " at " + path + ", which is no member");
|
||||
}
|
||||
return path.endsWith("[]") ? new Member(path.substring(0, path.length() - 2), true) : new Member(path, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* What an ARN of the format matches: its literal parts, a partition, any Region and account, and anything for
|
||||
* each other variable but nothing.
|
||||
*/
|
||||
static Pattern pattern(String format) {
|
||||
StringBuilder regex = new StringBuilder("^");
|
||||
Matcher variable = VARIABLE.matcher(format);
|
||||
int at = 0;
|
||||
while (variable.find()) {
|
||||
regex.append(Pattern.quote(format.substring(at, variable.start())));
|
||||
regex.append(switch (variable.group(1)) {
|
||||
case "Partition" -> "[^:]+";
|
||||
case "Region", "Account" -> "[^:]*";
|
||||
default -> ".+";
|
||||
});
|
||||
at = variable.end();
|
||||
}
|
||||
return Pattern.compile(regex.append(Pattern.quote(format.substring(at))).append('$').toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
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.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The resources a request names, as ARNs, for the namespaces {@link RequestResourceMembers} reads: those whose
|
||||
* ARNs {@code ResourceArnBuilder} does not build itself, which are otherwise checked on {@code *}, so a grant
|
||||
* scoped to a resource is refused and a deny scoped to one never applies.
|
||||
*
|
||||
* <p>A request names a resource by a member holding its ARN, which counts when it matches the ARN format of a
|
||||
* resource type the action acts on, or by members filling the variables of a type's format, the others open as
|
||||
* {@code *} (a resource a request creates has the id its service mints). An ARN with a qualifier its service drops
|
||||
* to check it is checked without one (a state machine's version or alias, on the state machine). An ARN naming
|
||||
* another account or Region than the request's is checked as given and as each resource of that name a handler may
|
||||
* act on instead, in the ARN's account or the caller's and in the ARN's Region or the request's, and the request is
|
||||
* refused if any is denied, as handlers mix them (ECR's tag handlers keep the ARN's account in the request's
|
||||
* Region).
|
||||
*/
|
||||
public final class RequestResources {
|
||||
|
||||
private static final Pattern VARIABLE = Pattern.compile("\\$\\{(\\w+)}");
|
||||
private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
|
||||
|
||||
private RequestResources() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARNs of the resources a request names, in the request's partition, Region and account: empty when the
|
||||
* table does not read the operation or its request names none, so it is checked on {@code *}. The operation,
|
||||
* as {@code <namespace>:<Operation>}, is the one the request is dispatched as, never read from the request
|
||||
* again, whose {@code X-Amz-Target} or {@code Action} may name another.
|
||||
*/
|
||||
public static List<String> of(String operation, ContainerRequestContext ctx, String partition, String region,
|
||||
String accountId) {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
List<RequestResourceMembers.Resource> resources = operation == null ? null : table.operations().get(operation);
|
||||
if (resources == null || resources.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
|
||||
JsonNode body = form.isEmpty() ? PassedRoles.jsonBody(ctx) : null;
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats = formats(table, operation);
|
||||
Set<String> arns = new LinkedHashSet<>();
|
||||
for (RequestResourceMembers.Resource resource : resources) {
|
||||
if (!applies(resource, form, body)) {
|
||||
continue;
|
||||
}
|
||||
if (resource.arn() != null) {
|
||||
for (String value : values(form, body, resource.arn())) {
|
||||
String named = before(value, resource.before());
|
||||
resource.types().stream().map(formats::get).filter(format -> format.pattern().matcher(named).matches())
|
||||
.findFirst().ifPresent(format -> addNamed(arns, format.checked(named), partition, region,
|
||||
accountId));
|
||||
}
|
||||
} else {
|
||||
fill(arns, resource, formats.get(resource.types().getFirst()), form, body, partition, region, accountId);
|
||||
}
|
||||
}
|
||||
return List.copyOf(arns);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARNs of the resources a create makes under a parent its action acts on, from the parent's ARN in the
|
||||
* request, read as the operation's own resource reads that member, their ids open; empty when it makes none,
|
||||
* so its tags go where the operation is checked. The operation is the one the request is dispatched as, as for
|
||||
* {@link #of}.
|
||||
*/
|
||||
public static List<String> created(String operation, ContainerRequestContext ctx, String partition, String region,
|
||||
String accountId) {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
List<RequestResourceMembers.Created> creates = operation == null ? null : table.creates().get(operation);
|
||||
if (creates == null) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
|
||||
JsonNode body = form.isEmpty() ? PassedRoles.jsonBody(ctx) : null;
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats = formats(table, operation);
|
||||
Set<String> arns = new LinkedHashSet<>();
|
||||
for (RequestResourceMembers.Created created : creates) {
|
||||
String separator = table.operations().getOrDefault(operation, List.of()).stream()
|
||||
.filter(resource -> created.arn().equals(resource.arn()) && resource.before() != null)
|
||||
.map(RequestResourceMembers.Resource::before).findFirst().orElse(null);
|
||||
RequestResourceMembers.ArnFormat parentFormat = formats.get(created.parent());
|
||||
for (String value : values(form, body, created.arn())) {
|
||||
String named = before(value, separator);
|
||||
if (!parentFormat.pattern().matcher(named).matches()) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parent = AwsArnUtils.parse(parentFormat.checked(named));
|
||||
String under = parent.resource().substring(created.parentWord().length());
|
||||
addNamed(arns, new AwsArnUtils.Arn(parent.partition(), parent.service(), parent.region(),
|
||||
parent.accountId(), created.childWord() + under + created.separator() + "*").toString(),
|
||||
partition, region, accountId);
|
||||
}
|
||||
}
|
||||
return List.copyOf(arns);
|
||||
}
|
||||
|
||||
/** The value up to {@code separator}, which its handler drops the rest after; the whole value without one. */
|
||||
private static String before(String value, String separator) {
|
||||
int at = separator == null ? -1 : value.indexOf(separator);
|
||||
return at < 0 ? value : value.substring(0, at);
|
||||
}
|
||||
|
||||
/** Whether each member the resource is named {@code when} has one of its values, an empty one for absent. */
|
||||
private static boolean applies(RequestResourceMembers.Resource resource, Map<String, String> form, JsonNode body) {
|
||||
for (Map.Entry<String, List<String>> member : resource.when().entrySet()) {
|
||||
List<String> values = values(form, body, new RequestResourceMembers.Member(member.getKey(), false));
|
||||
if (!member.getValue().contains(values.isEmpty() ? "" : values.getFirst())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The ARN formats of the operation's namespace, the part of {@code <namespace>:<Operation>} before its colon. */
|
||||
private static Map<String, RequestResourceMembers.ArnFormat> formats(RequestResourceMembers.Table table,
|
||||
String operation) {
|
||||
return table.formats().getOrDefault(operation.substring(0, operation.indexOf(':')), Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* 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. 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.
|
||||
*/
|
||||
private static void fill(Set<String> arns, RequestResourceMembers.Resource resource,
|
||||
RequestResourceMembers.ArnFormat format, Map<String, String> form, JsonNode body,
|
||||
String partition, String region, String accountId) {
|
||||
String account = accountId;
|
||||
if (resource.account() != null) {
|
||||
List<String> given = isNull(body, resource.account()) ? List.of() : values(form, body, resource.account());
|
||||
if (!given.isEmpty() && !ACCOUNT_ID.matcher(given.getFirst()).matches()) {
|
||||
return;
|
||||
}
|
||||
account = given.isEmpty() ? accountId : given.getFirst();
|
||||
}
|
||||
List<Map<String, String>> fillings = new ArrayList<>(List.of(Map.of()));
|
||||
for (Map.Entry<String, RequestResourceMembers.Member> variable : resource.fill().entrySet()) {
|
||||
List<String> values = values(form, body, variable.getValue());
|
||||
if (values.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (resource.fill().size() == 1 && values.stream().allMatch(value -> format.pattern().matcher(value).matches())) {
|
||||
values.forEach(value -> addNamed(arns, format.checked(value), partition, region, accountId));
|
||||
return;
|
||||
}
|
||||
List<Map<String, String>> next = new ArrayList<>();
|
||||
for (Map<String, String> filling : fillings) {
|
||||
for (String value : values) {
|
||||
Map<String, String> more = new HashMap<>(filling);
|
||||
more.put(variable.getKey(), value);
|
||||
next.add(more);
|
||||
}
|
||||
}
|
||||
fillings = next;
|
||||
}
|
||||
if (!resource.fill().isEmpty() && fillings.getFirst().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (Map<String, String> filling : fillings) {
|
||||
arns.add(render(format.format(), filling, partition, region, account));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a body gives the member a JSON null, which a handler reading an account with {@code asText(null)} reads
|
||||
* as none (ECR's {@code registryId}, its caller's registry then).
|
||||
*/
|
||||
private static boolean isNull(JsonNode body, RequestResourceMembers.Member member) {
|
||||
return body != null && body.isObject() && body.path(member.name()).isNull();
|
||||
}
|
||||
|
||||
/** The format with each variable replaced once: the partition, Region and account, a value, or else {@code *}. */
|
||||
private static String render(String format, Map<String, String> filling, String partition, String region,
|
||||
String accountId) {
|
||||
Matcher variable = VARIABLE.matcher(format);
|
||||
StringBuilder arn = new StringBuilder();
|
||||
while (variable.find()) {
|
||||
String value = switch (variable.group(1)) {
|
||||
case "Partition" -> partition;
|
||||
case "Region" -> region;
|
||||
case "Account" -> accountId;
|
||||
default -> filling.getOrDefault(variable.group(1), "*");
|
||||
};
|
||||
variable.appendReplacement(arn, Matcher.quoteReplacement(value));
|
||||
}
|
||||
return variable.appendTail(arn).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* An ARN the request names: as given, and, when it names another partition, account or Region than the
|
||||
* request's, as each resource of that name in the request's partition, in the ARN's account or the caller's and
|
||||
* the ARN's Region or the request's, whichever its handler acts on. An ARN with no account or Region keeps none.
|
||||
*/
|
||||
private static void addNamed(Set<String> arns, String arn, String partition, String region, String accountId) {
|
||||
arns.add(arn);
|
||||
if (!AwsArnUtils.isArn(arn)) {
|
||||
return;
|
||||
}
|
||||
AwsArnUtils.Arn named = AwsArnUtils.parse(arn);
|
||||
List<String> accounts = named.accountId().isEmpty() ? List.of("") : List.of(named.accountId(), accountId);
|
||||
List<String> regions = named.region().isEmpty() ? List.of("") : List.of(named.region(), region);
|
||||
for (String account : accounts) {
|
||||
for (String inRegion : regions) {
|
||||
arns.add(new AwsArnUtils.Arn(partition, named.service(), inRegion, account, named.resource()).toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The non-empty strings a request gives a member, read as its handler reads them: a form's parameter, or its
|
||||
* list numbered under {@code member} from 1 to the first missing, or a body's value, as text whether a string,
|
||||
* a number, a boolean or a null, and a list member's only from a list, a single value giving none.
|
||||
*/
|
||||
private static List<String> values(Map<String, String> form, JsonNode body, RequestResourceMembers.Member member) {
|
||||
List<String> values = new ArrayList<>();
|
||||
if (!form.isEmpty()) {
|
||||
if (!member.list()) {
|
||||
add(values, form.get(member.name()));
|
||||
return values;
|
||||
}
|
||||
for (int i = 1; form.containsKey(member.name() + ".member." + i); i++) {
|
||||
add(values, form.get(member.name() + ".member." + i));
|
||||
}
|
||||
return values;
|
||||
}
|
||||
JsonNode value = body == null || !body.isObject() ? null : body.get(member.name());
|
||||
if (value == null) {
|
||||
return values;
|
||||
}
|
||||
if (!member.list()) {
|
||||
addValue(values, value);
|
||||
} else if (value.isArray()) {
|
||||
for (JsonNode element : value) {
|
||||
addValue(values, element);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* A body's value as text, as a handler's {@code asText()} reads it, a null as {@code null}, and nothing for a
|
||||
* structure, which a handler reads as blank.
|
||||
*/
|
||||
private static void addValue(List<String> values, JsonNode value) {
|
||||
if (value.isValueNode()) {
|
||||
add(values, value.asText());
|
||||
}
|
||||
}
|
||||
|
||||
private static void add(List<String> values, String value) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
values.add(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -232,10 +232,10 @@ public class EcrJsonHandler {
|
||||
// MANUAL), with empty appliedScanFilters. Note: real AWS reports unknown repos
|
||||
// in the `failures` array; here describeRepositories throws
|
||||
// RepositoryNotFoundException, failing the whole batch instead.
|
||||
// AWS's request has no registryId, so the repositories are the caller's.
|
||||
List<String> names = parseStringList(request.path("repositoryNames"));
|
||||
String registryId = request.path("registryId").asText(null);
|
||||
|
||||
List<Repository> repos = service.describeRepositories(names, registryId, region);
|
||||
List<Repository> repos = service.describeRepositories(names, null, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode configs = objectMapper.createArrayNode();
|
||||
|
||||
@@ -45,6 +45,8 @@ import java.util.stream.Collectors;
|
||||
public class ElbV2Service implements ResourceProvider, ServerCertificateReferenceProvider, VpcDependencyProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ElbV2Service.class);
|
||||
/** {@code LoadBalancerTypeEnum}, in the model's order. */
|
||||
private static final List<String> LOAD_BALANCER_TYPES = List.of("application", "network", "gateway");
|
||||
|
||||
@Inject
|
||||
ElbV2DataPlane dataPlane;
|
||||
@@ -226,12 +228,16 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
|
||||
/**
|
||||
* Resolving the subnets and publishing the balancer happen under EC2's subnet lock, so a
|
||||
* DeleteSubnet cannot pass its dependency check in between and leave the balancer on a subnet
|
||||
* that is gone.
|
||||
* that is gone. A {@code Type} outside the model's enum is refused, as AWS refuses it, rather
|
||||
* than read as an application load balancer, which is not the one IAM checks the request for.
|
||||
*/
|
||||
public LoadBalancer createLoadBalancer(String region, String name, String scheme,
|
||||
String type, String ipAddressType,
|
||||
List<String> subnets, List<String> securityGroups,
|
||||
Map<String, String> initialTags) {
|
||||
if (type != null && !LOAD_BALANCER_TYPES.contains(type)) {
|
||||
throw SmithyValidationErrors.validationError(SmithyValidationErrors.notInEnum(type, "type", LOAD_BALANCER_TYPES));
|
||||
}
|
||||
return ec2Service.supplyWithSubnetReferencesHeld(region, () -> createLoadBalancerWithSubnetsHeld(
|
||||
region, name, scheme, type, ipAddressType, subnets, securityGroups, initialTags));
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.RequestResources;
|
||||
import io.github.hectorvent.floci.core.common.ServicePrincipals;
|
||||
import io.github.hectorvent.floci.core.common.SigV4CredentialScope;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.LogGroupTagTarget;
|
||||
@@ -124,6 +125,16 @@ public class ResourceArnBuilder {
|
||||
*/
|
||||
public List<String> buildResources(String credentialScope, ContainerRequestContext ctx,
|
||||
String region, String accountId, String partition) {
|
||||
return buildResources(credentialScope, null, ctx, region, accountId, partition);
|
||||
}
|
||||
|
||||
/**
|
||||
* The resources a request is checked against, {@code operation} the one it is dispatched as, as
|
||||
* {@code <namespace>:<Operation>}: a namespace with no branch here is checked on the resources its request
|
||||
* names for that operation (see {@link RequestResources}), and on {@code *} without one.
|
||||
*/
|
||||
public List<String> buildResources(String credentialScope, String operation, ContainerRequestContext ctx,
|
||||
String region, String accountId, String partition) {
|
||||
if (credentialScope == null) {
|
||||
return List.of("*");
|
||||
}
|
||||
@@ -143,10 +154,22 @@ public class ResourceArnBuilder {
|
||||
case "pipes" -> List.of(buildPipesArn(path, ctx, region, accountId, partition));
|
||||
case "dsql" -> List.of(buildDsqlArn(path, ctx, region, accountId, partition));
|
||||
case "eks" -> List.of(buildEksArn(path, ctx, region, accountId));
|
||||
default -> List.of("*");
|
||||
default -> namedResources(credentialScope, operation, ctx, region, accountId, partition);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The resources a request of a namespace this builder has no branch for names, from the vendored table of
|
||||
* request resources (see {@link RequestResources}); {@code *} when it names none, or the operation is not one
|
||||
* of the namespace.
|
||||
*/
|
||||
private static List<String> namedResources(String credentialScope, String operation, ContainerRequestContext ctx,
|
||||
String region, String accountId, String partition) {
|
||||
List<String> named = operation == null || !operation.startsWith(credentialScope + ":") ? List.of()
|
||||
: RequestResources.of(operation, ctx, partition, region, accountId);
|
||||
return named.isEmpty() ? List.of("*") : named;
|
||||
}
|
||||
|
||||
private String buildResourceGroupArn(ContainerRequestContext ctx, String region, String accountId) {
|
||||
JsonNode body = readJsonBody(ctx);
|
||||
if (body == null) {
|
||||
|
||||
Reference in new issue
Block a user