mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): derive EC2 instance authorization from AWS metadata (#8150)
Authorize generated instance targets with their own stored tags before mutation. Return malformed Query errors as XML HTTP 404, reuse enforcement group cleanup, and update generated-target regression coverage. Regenerate IAM metadata on current main. Closes #8159
This commit is contained in:
1 parent
f64ca5ef16
commit
2dc93aa087
18 files changed
+566
-107
No files matched your search
@@ -14,6 +14,11 @@ public final class Ec2ErrorResponses {
|
||||
}
|
||||
|
||||
static boolean isEc2QueryRequest(ContainerRequestContext ctx) {
|
||||
return isEc2QueryRequest(ctx, true);
|
||||
}
|
||||
|
||||
/** Error decoding cannot inspect the form again while rendering that same failure. */
|
||||
static boolean isEc2QueryRequest(ContainerRequestContext ctx, boolean inspectForm) {
|
||||
if (!(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim)
|
||||
|| claim.protocol() != WireProtocol.AWS_QUERY) {
|
||||
return false;
|
||||
@@ -21,15 +26,13 @@ public final class Ec2ErrorResponses {
|
||||
if (claim.service() != null) {
|
||||
return "ec2".equals(claim.service().externalKey());
|
||||
}
|
||||
try {
|
||||
String action = AwsQueryServiceResolver.action(RequestBodyReader.formField(ctx, "Action"),
|
||||
RequestBodyReader.formField(ctx, "Operation"));
|
||||
return action != null && "ec2".equals(AwsQueryController.inferServiceFromAction(action,
|
||||
RequestBodyReader.formField(ctx, "Version")));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// A malformed form cannot identify a service; retain the generic protocol error.
|
||||
if (!inspectForm) {
|
||||
return false;
|
||||
}
|
||||
String action = AwsQueryServiceResolver.action(RequestBodyReader.formField(ctx, "Action"),
|
||||
RequestBodyReader.formField(ctx, "Operation"));
|
||||
return action != null && "ec2".equals(AwsQueryController.inferServiceFromAction(action,
|
||||
RequestBodyReader.formField(ctx, "Version")));
|
||||
}
|
||||
|
||||
public static Response authFailure() {
|
||||
|
||||
@@ -39,7 +39,6 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
@@ -736,14 +735,19 @@ public class IamConditionContextResolver {
|
||||
// ── EC2 ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
private Map<String, List<String>> ec2ConditionContext(String action, ContainerRequestContext ctx) {
|
||||
return switch (action) {
|
||||
case "ec2:RunInstances" -> ec2RunInstancesConditionContext(ctx);
|
||||
case "ec2:CreateTags" -> ec2CreateTagsConditionContext(ctx);
|
||||
case "ec2:DeleteTags" -> ec2ResourceTagConditionContext(ctx, "ResourceId.1");
|
||||
case "ec2:TerminateInstances", "ec2:DescribeInstances" ->
|
||||
ec2ResourceTagConditionContext(ctx, "InstanceId.1");
|
||||
default -> null;
|
||||
};
|
||||
if ("ec2:RunInstances".equals(action)) {
|
||||
return ec2RunInstancesConditionContext(ctx);
|
||||
}
|
||||
RequestResourceMembers.Targets targets = RequestResourceMembers.table().targets().get(action);
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
Map<String, String> form = formParameters(ctx);
|
||||
if ("ec2:CreateTags".equals(action)) {
|
||||
addRequestTags(conditions, form, "Tag.");
|
||||
}
|
||||
if (targets != null) {
|
||||
addResourceTags(conditions, form.get(targets.query() + ".1"), targets);
|
||||
}
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -759,27 +763,6 @@ public class IamConditionContextResolver {
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
/**
|
||||
* CreateTags both requests tags and targets existing resources, so both keys apply: the
|
||||
* {@code Tag.N} pairs being requested, and each {@code ResourceId.N}'s tags as they are
|
||||
* before this call. This context carries the first target; the rest come from
|
||||
* {@link #resolveRemainingTargets}.
|
||||
*/
|
||||
private Map<String, List<String>> ec2CreateTagsConditionContext(ContainerRequestContext ctx) {
|
||||
Map<String, String> form = formParameters(ctx);
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
addRequestTags(conditions, form, "Tag.");
|
||||
addResourceTags(conditions, form.get("ResourceId.1"));
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
private Map<String, List<String>> ec2ResourceTagConditionContext(ContainerRequestContext ctx,
|
||||
String idParameter) {
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
addResourceTags(conditions, formParameters(ctx).get(idParameter));
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
/**
|
||||
* One condition context per target after the first, for the EC2 actions that accept several
|
||||
* resource ids in one request. An untagged target yields an empty context rather than none,
|
||||
@@ -806,14 +789,11 @@ public class IamConditionContextResolver {
|
||||
if (!"ec2".equals(credentialScope)) {
|
||||
return List.of();
|
||||
}
|
||||
String idParameter = switch (action) {
|
||||
case "ec2:CreateTags", "ec2:DeleteTags" -> "ResourceId.";
|
||||
case "ec2:TerminateInstances", "ec2:DescribeInstances" -> "InstanceId.";
|
||||
default -> null;
|
||||
};
|
||||
if (idParameter == null) {
|
||||
RequestResourceMembers.Targets generatedTargets = RequestResourceMembers.table().targets().get(action);
|
||||
if (generatedTargets == null) {
|
||||
return List.of();
|
||||
}
|
||||
String idParameter = generatedTargets.query() + ".";
|
||||
Map<String, String> form = formParameters(ctx);
|
||||
List<Map<String, List<String>>> targets = new ArrayList<>();
|
||||
if (!form.containsKey(idParameter + 1)) {
|
||||
@@ -825,7 +805,7 @@ public class IamConditionContextResolver {
|
||||
if ("ec2:CreateTags".equals(action)) {
|
||||
addRequestTags(conditions, form, "Tag.");
|
||||
}
|
||||
addResourceTags(conditions, form.get(idParameter + i));
|
||||
addResourceTags(conditions, form.get(idParameter + i), generatedTargets);
|
||||
targets.add(conditions);
|
||||
}
|
||||
return targets;
|
||||
@@ -845,14 +825,24 @@ public class IamConditionContextResolver {
|
||||
}
|
||||
}
|
||||
|
||||
private void addResourceTags(Map<String, List<String>> conditions, String resourceId) {
|
||||
private void addResourceTags(Map<String, List<String>> conditions, String resourceId,
|
||||
RequestResourceMembers.Targets targets) {
|
||||
if (resourceId == null || resourceId.isBlank() || !ec2Service.isResolvable()) {
|
||||
return;
|
||||
}
|
||||
String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion();
|
||||
List<String> prefixes = List.of(RESOURCE_TAG_PREFIX);
|
||||
for (Map.Entry<String, String> type : targets.prefixes().entrySet()) {
|
||||
if (resourceId.startsWith(type.getValue())) {
|
||||
prefixes = RequestResourceMembers.table().resourceTagKeys()
|
||||
.getOrDefault("ec2", Map.of()).getOrDefault(type.getKey(), List.of());
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (Tag tag : ec2Service.get().resourceTags(region, resourceId)) {
|
||||
conditions.put(RESOURCE_TAG_PREFIX + tag.getKey(),
|
||||
List.of(tag.getValue() == null ? "" : tag.getValue()));
|
||||
for (String prefix : prefixes) {
|
||||
conditions.put(prefix + tag.getKey(), List.of(tag.getValue() == null ? "" : tag.getValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -898,7 +888,8 @@ public class IamConditionContextResolver {
|
||||
int eq = pair.indexOf('=');
|
||||
String key = eq < 0 ? pair : pair.substring(0, eq);
|
||||
String value = eq < 0 ? "" : pair.substring(eq + 1);
|
||||
parameters.putIfAbsent(URLDecoder.decode(key, charset), URLDecoder.decode(value, charset));
|
||||
parameters.putIfAbsent(QueryFormDecoder.decode(key, charset, ctx),
|
||||
QueryFormDecoder.decode(value, charset, ctx));
|
||||
}
|
||||
ctx.setProperty(BUFFERED_FORM_BODY, parameters);
|
||||
return parameters;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/** Percent decoding shared by Query action extraction and IAM resource/context resolution. */
|
||||
public final class QueryFormDecoder {
|
||||
|
||||
private QueryFormDecoder() {
|
||||
}
|
||||
|
||||
public static String decode(String value, Charset charset, ContainerRequestContext ctx) {
|
||||
try {
|
||||
return URLDecoder.decode(value, charset);
|
||||
} catch (IllegalArgumentException invalidEncoding) {
|
||||
String message = "The form body contains an invalid percent escape.";
|
||||
boolean ec2 = Ec2ErrorResponses.isEc2QueryRequest(ctx, false);
|
||||
Response response = ec2 ? Ec2ErrorResponses.of("MalformedQueryString", message, 404)
|
||||
: AwsQueryResponse.error("MalformedQueryString", message, null, 404);
|
||||
throw new WebApplicationException(invalidEncoding, response);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -204,6 +204,7 @@ final class RequestResourceMembers {
|
||||
Map<String, List<Created>> creates, Map<String, List<Resource>> makes,
|
||||
Map<String, Targets> targets,
|
||||
Map<String, Map<String, String>> located, Map<String, Map<String, ArnFormat>> formats,
|
||||
Map<String, Map<String, List<String>>> resourceTagKeys,
|
||||
Set<String> namespaces, Set<String> handBuilt, Set<String> notCovered, Set<String> otherNamespaces) {
|
||||
}
|
||||
|
||||
@@ -257,6 +258,32 @@ final class RequestResourceMembers {
|
||||
+ namespace.getValue() + " a minted id, no types whose format ends in its one variable");
|
||||
}
|
||||
});
|
||||
Map<String, Map<String, List<String>>> resourceTagKeys = new LinkedHashMap<>();
|
||||
if (!document.path("resourceTagKeys").isMissingNode() && !document.path("resourceTagKeys").isObject()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has malformed resource tag keys");
|
||||
}
|
||||
document.path("resourceTagKeys").properties().forEach(namespace -> {
|
||||
if (!namespace.getValue().isObject()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has malformed resource tag keys");
|
||||
}
|
||||
Map<String, List<String>> types = new LinkedHashMap<>();
|
||||
namespace.getValue().properties().forEach(type -> {
|
||||
List<String> keys = new ArrayList<>();
|
||||
if (!formats.getOrDefault(namespace.getKey(), Map.of()).containsKey(type.getKey())
|
||||
|| !type.getValue().isArray()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has malformed resource tag keys");
|
||||
}
|
||||
type.getValue().forEach(key -> {
|
||||
String prefix = key.asText("");
|
||||
if (!prefix.matches("[a-z0-9-]+:ResourceTag/") || keys.contains(prefix)) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has malformed resource tag keys");
|
||||
}
|
||||
keys.add(prefix);
|
||||
});
|
||||
types.put(type.getKey(), List.copyOf(keys));
|
||||
});
|
||||
resourceTagKeys.put(namespace.getKey(), Map.copyOf(types));
|
||||
});
|
||||
Map<String, List<Resource>> entries = new LinkedHashMap<>();
|
||||
Map<String, List<String>> actsOn = new LinkedHashMap<>();
|
||||
Map<String, List<Created>> creates = new LinkedHashMap<>();
|
||||
@@ -336,7 +363,7 @@ final class RequestResourceMembers {
|
||||
}
|
||||
});
|
||||
return new Table(Map.copyOf(entries), Map.copyOf(actsOn), Map.copyOf(creates), Map.copyOf(makes),
|
||||
Map.copyOf(targets), Map.copyOf(located), Map.copyOf(formats), namespaces,
|
||||
Map.copyOf(targets), Map.copyOf(located), Map.copyOf(formats), Map.copyOf(resourceTagKeys), namespaces,
|
||||
names(document.path("handBuilt")),
|
||||
Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
|
||||
names(document.path("otherNamespaces")));
|
||||
|
||||
@@ -214,18 +214,13 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
|
||||
String token = ctx.getHeaderString("X-Amz-Security-Token");
|
||||
ServiceDescriptor queryService = null;
|
||||
if (presigned) {
|
||||
try {
|
||||
if (token == null) {
|
||||
token = RequestBodyReader.formField(ctx, "X-Amz-Security-Token");
|
||||
if (token == null) {
|
||||
token = RequestBodyReader.formField(ctx, "X-Amz-Security-Token");
|
||||
if (token == null) {
|
||||
token = query.getFirst("X-Amz-Security-Token");
|
||||
}
|
||||
token = query.getFirst("X-Amz-Security-Token");
|
||||
}
|
||||
queryService = queryService(ctx, resource);
|
||||
} catch (IllegalArgumentException error) {
|
||||
incompleteSignature(ctx, resource, "Cannot read presigned request form parameters.");
|
||||
return;
|
||||
}
|
||||
queryService = queryService(ctx, resource);
|
||||
}
|
||||
Optional<String> secretKey = resolveSecretKey(scope.accessKeyId(), token);
|
||||
if (secretKey.isEmpty()) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.services.iam;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import io.floci.aws.core.common.QueryFormDecoder;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -10,7 +11,6 @@ import org.jboss.logging.Logger;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@@ -69,10 +69,10 @@ public final class RequestBodyReader {
|
||||
for (String pair : form.split("&")) {
|
||||
int eq = pair.indexOf('=');
|
||||
String pairKey = eq < 0 ? pair : pair.substring(0, eq);
|
||||
if (!key.equals(URLDecoder.decode(pairKey, charset))) {
|
||||
if (!key.equals(QueryFormDecoder.decode(pairKey, charset, ctx))) {
|
||||
continue;
|
||||
}
|
||||
return eq < 0 ? "" : URLDecoder.decode(pair.substring(eq + 1), charset);
|
||||
return eq < 0 ? "" : QueryFormDecoder.decode(pair.substring(eq + 1), charset, ctx);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -2253,16 +2253,11 @@ public class ResourceArnBuilder {
|
||||
* A Query-protocol parameter, read from the same place the handler reads it. For a form POST
|
||||
* that is the body alone: {@code AwsQueryController} dispatches on the form parameters and never
|
||||
* sees the URL query, so authorizing a URL value would check one resource and act on another.
|
||||
* A value with an invalid percent escape is read as absent, so the resource stays the default
|
||||
* and the request goes on to be answered as it is without enforcement.
|
||||
* An invalid percent escape is rejected by the shared form decoder before authorization.
|
||||
*/
|
||||
private String firstFormParam(ContainerRequestContext ctx, String name) {
|
||||
if (RequestBodyReader.isForm(ctx)) {
|
||||
try {
|
||||
return RequestBodyReader.formField(ctx, name);
|
||||
} catch (IllegalArgumentException malformed) {
|
||||
return null;
|
||||
}
|
||||
return RequestBodyReader.formField(ctx, name);
|
||||
}
|
||||
return ctx.getUriInfo().getQueryParameters().getFirst(name);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user