mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(query): route signed GET requests through the Query dispatcher (#6007)
Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
1 parent
b955aa09ff
commit
a103b938d2
14 files changed
+451
-31
No files matched your search
@@ -58,6 +58,18 @@ python3.9 -m venv .venv-legacy
|
||||
FLOCI_ENDPOINT=http://localhost:4566 .venv-legacy/bin/python -m pytest legacy/
|
||||
```
|
||||
|
||||
## Legacy Query GET
|
||||
|
||||
`legacy/test_elb_query_get.py` checks that public Boto 2 Query GET reads and
|
||||
deletes Classic load balancers created through Boto 3 POST, including the
|
||||
missing-resource error. Boto 2.49.0 requires a separate Python 3.9 environment:
|
||||
|
||||
```bash
|
||||
python3.9 -m venv .venv-legacy
|
||||
.venv-legacy/bin/pip install boto==2.49.0 boto3 pytest cryptography
|
||||
FLOCI_ENDPOINT=http://localhost:4566 .venv-legacy/bin/python -m pytest legacy/test_elb_query_get.py
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Boto 2 Query GET and Boto 3 POST share Classic ELB state and errors."""
|
||||
|
||||
from urllib.parse import urlsplit
|
||||
import uuid
|
||||
|
||||
from boto.ec2.elb import ELBConnection
|
||||
from boto.exception import BotoServerError
|
||||
from boto.regioninfo import RegionInfo
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
import pytest
|
||||
|
||||
|
||||
def test_classic_elb_get_lifecycle(aws_config):
|
||||
endpoint = urlsplit(aws_config["endpoint_url"])
|
||||
legacy = ELBConnection(
|
||||
aws_access_key_id=aws_config["aws_access_key_id"],
|
||||
aws_secret_access_key=aws_config["aws_secret_access_key"],
|
||||
port=endpoint.port,
|
||||
is_secure=endpoint.scheme == "https",
|
||||
region=RegionInfo(name=aws_config["region_name"], endpoint=endpoint.hostname),
|
||||
)
|
||||
legacy.auth_region_name = aws_config["region_name"]
|
||||
legacy.auth_service_name = "elasticloadbalancing"
|
||||
current = boto3.client("elb", **aws_config)
|
||||
name = "query-get-" + uuid.uuid4().hex[:12]
|
||||
try:
|
||||
current.create_load_balancer(
|
||||
LoadBalancerName=name,
|
||||
AvailabilityZones=[aws_config["region_name"] + "a"],
|
||||
Listeners=[{"Protocol": "HTTP", "LoadBalancerPort": 80, "InstancePort": 8080}],
|
||||
)
|
||||
assert [item.name for item in legacy.get_all_load_balancers([name])] == [name]
|
||||
legacy.delete_load_balancer(name)
|
||||
with pytest.raises(BotoServerError) as old_error:
|
||||
legacy.get_all_load_balancers([name])
|
||||
assert old_error.value.status == 400
|
||||
assert old_error.value.error_code == "LoadBalancerNotFound"
|
||||
with pytest.raises(ClientError) as new_error:
|
||||
current.describe_load_balancers(LoadBalancerNames=[name])
|
||||
assert new_error.value.response["Error"]["Code"] == "LoadBalancerNotFound"
|
||||
finally:
|
||||
current.delete_load_balancer(LoadBalancerName=name)
|
||||
legacy.close()
|
||||
current.close()
|
||||
@@ -1,6 +1,7 @@
|
||||
# Elastic Load Balancing (Classic, v1)
|
||||
|
||||
**Protocol:** Query (XML) — `POST http://localhost:4566/` with `Action=` and `Version=2012-06-01`
|
||||
**Protocol:** Query (XML), form `POST` or SigV4-signed `GET` at `http://localhost:4566/`
|
||||
with `Action=` and `Version=2012-06-01`.
|
||||
|
||||
Classic Elastic Load Balancing is the 2012-06-01 API behind `aws elb` and Terraform's `aws_elb`
|
||||
resource. It is a **different API** from [ELB v2](elb.md) (ALB/NLB, 2015-12-01), even though both
|
||||
@@ -9,7 +10,7 @@ scope.
|
||||
|
||||
## How Floci tells the two apart
|
||||
|
||||
Every Query-protocol request carries the API version it is speaking as the `Version` form
|
||||
Every Query-protocol request carries the API version it is speaking as the `Version` request
|
||||
parameter, and that is what Floci routes on:
|
||||
|
||||
| `Version` | Answered by |
|
||||
|
||||
@@ -75,7 +75,7 @@ public class AwsProtocolClaimFilter implements ContainerRequestFilter {
|
||||
ctx.setProperty(CLAIM_PROPERTY, resolved);
|
||||
if (resolved.protocol() == WireProtocol.AWS_QUERY && "GET".equalsIgnoreCase(signals.method())) {
|
||||
ctx.setRequestUri(ctx.getUriInfo().getRequestUriBuilder()
|
||||
.replacePath(AwsQueryController.CLOUDWATCH_GET_PATH).build());
|
||||
.replacePath(AwsQueryController.QUERY_GET_PATH).build());
|
||||
}
|
||||
if (resolved.protocol() == WireProtocol.REST) {
|
||||
Optional<String> scope = SigV4CredentialScope.serviceName(signals.authorization());
|
||||
|
||||
@@ -55,7 +55,7 @@ import java.util.stream.Stream;
|
||||
@Path("/")
|
||||
public class AwsQueryController {
|
||||
|
||||
static final String CLOUDWATCH_GET_PATH = "/_cloudwatch-query";
|
||||
static final String QUERY_GET_PATH = "/_query";
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AwsQueryController.class);
|
||||
|
||||
@@ -379,22 +379,10 @@ public class AwsQueryController {
|
||||
"AdminAddUserToGroup", "AdminRemoveUserFromGroup", "AdminListGroupsForUser"
|
||||
);
|
||||
|
||||
/** Root GET requests that can use the CloudWatch Query handler without claiming S3 traffic. */
|
||||
public static boolean isCloudWatchQueryGet(String authorization, String target, String accept,
|
||||
MultivaluedMap<String, String> queryParams) {
|
||||
String auth = IamEnforcementFilter.requestAuthorization(authorization, queryParams);
|
||||
if (auth != null) {
|
||||
return SigV4CredentialScope.serviceName(auth).filter("monitoring"::equals).isPresent();
|
||||
}
|
||||
String action = AwsQueryServiceResolver.action(queryParams);
|
||||
return target == null && (accept == null || !accept.contains(MediaType.TEXT_HTML)) && action != null
|
||||
&& "monitoring".equals(inferServiceFromAction(action, queryParams.getFirst("Version")));
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path(CLOUDWATCH_GET_PATH)
|
||||
@Path(QUERY_GET_PATH)
|
||||
@Produces({MediaType.APPLICATION_XML, MediaType.TEXT_HTML})
|
||||
public Response dispatchCloudWatchQueryGet(@HeaderParam("Authorization") String authorization,
|
||||
public Response dispatchQueryGet(@HeaderParam("Authorization") String authorization,
|
||||
@Context UriInfo uriInfo,
|
||||
@Context ContainerRequestContext request) {
|
||||
// Only the pre-matching Query claim may select this internal route.
|
||||
@@ -404,6 +392,11 @@ public class AwsQueryController {
|
||||
}
|
||||
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
|
||||
String action = AwsQueryServiceResolver.action(queryParams);
|
||||
String auth = IamEnforcementFilter.requestAuthorization(authorization, queryParams);
|
||||
String service = serviceResolver.resolve(auth, action, queryParams.getFirst("Version"));
|
||||
if (!"monitoring".equals(service)) {
|
||||
return dispatch(auth, queryParams);
|
||||
}
|
||||
if (action == null) {
|
||||
return Response.status(404).type(MediaType.APPLICATION_XML)
|
||||
.entity("<UnknownOperationException/>").build();
|
||||
|
||||
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.dynamodb.DynamoDbTableNames;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import io.github.hectorvent.floci.services.iam.IamActionRegistry;
|
||||
import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;
|
||||
import io.github.hectorvent.floci.services.s3.S3ObjectActions;
|
||||
import io.github.hectorvent.floci.services.s3.S3ObjectKeys;
|
||||
@@ -663,6 +664,15 @@ public class IamConditionContextResolver {
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
static Map<String, String> formParameters(ContainerRequestContext ctx) {
|
||||
if ("GET".equalsIgnoreCase(ctx.getMethod()) && IamActionRegistry.isQueryRequest(ctx)) {
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
ctx.getUriInfo().getQueryParameters().forEach((key, values) -> {
|
||||
if (!values.isEmpty()) {
|
||||
parameters.put(key, values.getFirst());
|
||||
}
|
||||
});
|
||||
return parameters;
|
||||
}
|
||||
Object cached = ctx.getProperty(BUFFERED_FORM_BODY);
|
||||
if (cached instanceof Map<?, ?> map) {
|
||||
return (Map<String, String>) map;
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
@@ -18,7 +19,7 @@ import java.util.regex.Pattern;
|
||||
* Claiming uses non-payload signals only (method, path, headers, query parameters) so it is safe
|
||||
* to run in a pre-matching filter without touching the entity stream. As a
|
||||
* consequence the awsQuery claim covers POST {@code /} with the form
|
||||
* content type and the CloudWatch GET requests the dispatcher accepts.
|
||||
* content type and the signed Query GET requests the dispatcher accepts.
|
||||
* The spec's body-level {@code Action}/{@code Version} checks
|
||||
* stay downstream in {@code AwsQueryController}, which already rejects a
|
||||
* missing {@code Action} with the AWS {@code MissingAction} error. Nothing
|
||||
@@ -94,9 +95,12 @@ public class ProtocolClaimer {
|
||||
}
|
||||
|
||||
if ("GET".equalsIgnoreCase(signals.method()) && isRootPath(path)
|
||||
&& AwsQueryController.isCloudWatchQueryGet(signals.authorization(),
|
||||
signals.xAmzTarget(), signals.accept(), signals.queryParameters())) {
|
||||
ServiceDescriptor service = catalog.byCredentialScope("monitoring").orElse(null);
|
||||
&& isQueryGet(signals)) {
|
||||
String authorization = IamEnforcementFilter.requestAuthorization(
|
||||
signals.authorization(), signals.queryParameters());
|
||||
ServiceDescriptor service = SigV4CredentialScope.serviceName(authorization)
|
||||
.flatMap(catalog::byCredentialScope)
|
||||
.orElseGet(() -> catalog.byCredentialScope("monitoring").orElse(null));
|
||||
return Optional.of(new ProtocolClaim(WireProtocol.AWS_QUERY, service,
|
||||
AwsQueryServiceResolver.action(signals.queryParameters()), null));
|
||||
}
|
||||
@@ -146,6 +150,20 @@ public class ProtocolClaimer {
|
||||
return path != null && RPC_V2_PATH.matcher(path).matches();
|
||||
}
|
||||
|
||||
private boolean isQueryGet(ClaimSignals signals) {
|
||||
String authorization = IamEnforcementFilter.requestAuthorization(
|
||||
signals.authorization(), signals.queryParameters());
|
||||
if (authorization != null) {
|
||||
return SigV4CredentialScope.serviceName(authorization).flatMap(catalog::byCredentialScope)
|
||||
.filter(service -> service.supportsProtocol(ServiceProtocol.QUERY)).isPresent();
|
||||
}
|
||||
String action = AwsQueryServiceResolver.action(signals.queryParameters());
|
||||
return signals.xAmzTarget() == null
|
||||
&& (signals.accept() == null || !signals.accept().contains(MediaType.TEXT_HTML))
|
||||
&& action != null && "monitoring".equals(AwsQueryController.inferServiceFromAction(
|
||||
action, signals.queryParameters().getFirst("Version")));
|
||||
}
|
||||
|
||||
private static boolean isRootPath(String path) {
|
||||
return path == null || path.isEmpty() || "/".equals(path);
|
||||
}
|
||||
|
||||
@@ -45,6 +45,9 @@ public final class RequestBodyReader {
|
||||
}
|
||||
|
||||
public static String formField(ContainerRequestContext ctx, String key) {
|
||||
if ("GET".equalsIgnoreCase(ctx.getMethod()) && IamActionRegistry.isQueryRequest(ctx)) {
|
||||
return ctx.getUriInfo().getQueryParameters().getFirst(key);
|
||||
}
|
||||
MediaType mt = ctx.getMediaType();
|
||||
if (mt == null
|
||||
|| !"application".equalsIgnoreCase(mt.getType())
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class AwsQueryGetIamEnforcementIntegrationTest {
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"false,Action", "false,Operation", "true,Action", "true,Operation"})
|
||||
void getRequiresPermissionForTheQueryService(boolean presigned, String actionParameter) throws Exception {
|
||||
String user = "query-get-" + UUID.randomUUID();
|
||||
String admin = auth("000000000000", "iam");
|
||||
EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser(
|
||||
cleanup, baseUri.getPort(), admin, user);
|
||||
putPolicy(admin, user, "s3:ListAllMyBuckets");
|
||||
describe(credentials, presigned, actionParameter).statusCode(403)
|
||||
.contentType("application/xml")
|
||||
.body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
|
||||
putPolicy(admin, user, "elasticloadbalancing:DescribeLoadBalancers");
|
||||
describe(credentials, presigned, actionParameter).statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("LoadBalancerNotFound"));
|
||||
}
|
||||
|
||||
private static ValidatableResponse describe(EnforcementFixtures.UserCredentials credentials,
|
||||
boolean presigned, String actionParameter) throws Exception {
|
||||
AwsRequestSigner signer = AwsRequestSigner.signedAs(credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), "elasticloadbalancing");
|
||||
Map<String, String> query = Map.of(actionParameter, "DescribeLoadBalancers", "Version", "2012-06-01",
|
||||
"LoadBalancerNames.member.1", "missing-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
if (presigned) {
|
||||
return given().urlEncodingEnabled(false)
|
||||
.get(signer.presignedUri("GET", baseUri, query, new byte[0])).then();
|
||||
}
|
||||
return given().filter(signer).queryParams(query).get("/").then();
|
||||
}
|
||||
|
||||
private static void putPolicy(String admin, String user, String action) {
|
||||
given().header("Authorization", admin).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "PutUserPolicy").formParam("UserName", user)
|
||||
.formParam("PolicyName", "query-read")
|
||||
.formParam("PolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Allow","Action":"%s","Resource":"*"
|
||||
}]}
|
||||
""".formatted(action))
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@QuarkusTest
|
||||
class AwsQueryGetIntegrationTest {
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"elasticloadbalancing,DescribeLoadBalancers,2012-06-01",
|
||||
"elasticloadbalancing,DescribeLoadBalancers,2015-12-01",
|
||||
"autoscaling,DescribeTags,2011-01-01",
|
||||
"ec2,DescribeAvailabilityZones,2016-11-15",
|
||||
"iam,ListUsers,2010-05-08",
|
||||
"sts,GetCallerIdentity,2011-06-15",
|
||||
"sns,ListTopics,2010-03-31",
|
||||
"sqs,ListQueues,2012-11-05",
|
||||
"rds,DescribeDBInstances,2014-10-31",
|
||||
"ses,GetSendQuota,2010-12-01",
|
||||
"docdb,DescribeDBClusters,2014-10-31",
|
||||
"neptune,DescribeDBClusters,2014-10-31"
|
||||
})
|
||||
void queryGetUsesTheSigningServiceAndApiVersion(String service, String action, String version) {
|
||||
ValidatableResponse response = given().header("Authorization", auth("test", service))
|
||||
.queryParam("Action", action).queryParam("Version", version)
|
||||
.get("/").then().statusCode(200)
|
||||
.contentType("application/xml").body(containsString(action + "Response"));
|
||||
if ("elasticloadbalancing".equals(service) || "autoscaling".equals(service)) {
|
||||
response.body(containsString("/doc/" + version + "/"));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"elasticloadbalancing,DescribeLoadBalancers,2012-06-01",
|
||||
"ec2,DescribeAvailabilityZones,2016-11-15",
|
||||
"iam,ListUsers,2010-05-08"
|
||||
})
|
||||
void signingServiceKeepsQueryGetWhenTargetAndBrowserHeadersArePresent(
|
||||
String service, String action, String version) {
|
||||
given().header("Authorization", auth("test", service))
|
||||
.header("X-Amz-Target", "AmazonSSM.GetParameter").header("Accept", "text/html")
|
||||
.queryParam("Action", action).queryParam("Version", version)
|
||||
.get("/").then().statusCode(200).body(containsString(action + "Response"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Action", "Operation"})
|
||||
void getDescribesAndDeletesTheSameClassicLoadBalancerAsPost(String actionParameter) {
|
||||
String name = "query-get-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
Map<String, String> identity = Map.of(
|
||||
"Version", "2012-06-01", "LoadBalancerName", name);
|
||||
cleanup.register(() -> given().header("Authorization", auth("test", "elasticloadbalancing"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParams(identity).formParam("Action", "DeleteLoadBalancer").post("/"));
|
||||
given().header("Authorization", auth("test", "elasticloadbalancing"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParams(identity).formParam("Action", "CreateLoadBalancer")
|
||||
.formParam("Listeners.member.1.Protocol", "HTTP")
|
||||
.formParam("Listeners.member.1.LoadBalancerPort", "80")
|
||||
.formParam("Listeners.member.1.InstancePort", "8080")
|
||||
.post("/").then().statusCode(200);
|
||||
classicGet(actionParameter, name).get("/").then().statusCode(200)
|
||||
.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult"
|
||||
+ ".LoadBalancerDescriptions.member.LoadBalancerName", equalTo(name));
|
||||
given().header("Authorization", auth("test", "elasticloadbalancing"))
|
||||
.queryParams(identity).queryParam(actionParameter, "DeleteLoadBalancer")
|
||||
.get("/").then().statusCode(200);
|
||||
classicGet(actionParameter, name).get("/").then().statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("LoadBalancerNotFound"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void presignedGetKeepsTheVersionAndReturnsTheClassicError() throws Exception {
|
||||
presignedClassicGet(AwsRequestSigner.signedAs("test", "test", "elasticloadbalancing"),
|
||||
"missing-query-get-load-balancer").statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("LoadBalancerNotFound"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void presignedGetUsesTheCredentialAccountAndNonDefaultRegion() throws Exception {
|
||||
String name = "query-region-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
AwsRequestSigner signer = AwsRequestSigner.signedAs("777777777777", "test", "elasticloadbalancing")
|
||||
.inRegion("eu-west-1");
|
||||
cleanup.register(() -> given().port(baseUri.getPort()).filter(signer)
|
||||
.formParam("Action", "DeleteLoadBalancer").formParam("Version", "2012-06-01")
|
||||
.formParam("LoadBalancerName", name).post("/"));
|
||||
given().filter(signer).formParam("Action", "CreateLoadBalancer")
|
||||
.formParam("Version", "2012-06-01").formParam("LoadBalancerName", name)
|
||||
.formParam("Listeners.member.1.Protocol", "HTTP")
|
||||
.formParam("Listeners.member.1.LoadBalancerPort", "80")
|
||||
.formParam("Listeners.member.1.InstancePort", "8080")
|
||||
.post("/").then().statusCode(200);
|
||||
presignedClassicGet(signer, name).statusCode(200)
|
||||
.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult"
|
||||
+ ".LoadBalancerDescriptions.member.LoadBalancerName", equalTo(name));
|
||||
for (AwsRequestSigner foreign : new AwsRequestSigner[] {signer.inRegion("us-east-1"),
|
||||
AwsRequestSigner.signedAs("888888888888", "test", "elasticloadbalancing")
|
||||
.inRegion("eu-west-1")}) {
|
||||
presignedClassicGet(foreign, name).statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("LoadBalancerNotFound"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingActionReturnsAQueryError() {
|
||||
given().header("Authorization", auth("test", "elasticloadbalancing"))
|
||||
.queryParam("Version", "2012-06-01").get("/").then().statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("MissingAction"));
|
||||
}
|
||||
|
||||
private static RequestSpecification classicGet(String actionParameter, String name) {
|
||||
return given().header("Authorization", auth("test", "elasticloadbalancing"))
|
||||
.queryParam(actionParameter, "DescribeLoadBalancers")
|
||||
.queryParam("Version", "2012-06-01")
|
||||
.queryParam("LoadBalancerNames.member.1", name);
|
||||
}
|
||||
|
||||
private static ValidatableResponse presignedClassicGet(AwsRequestSigner signer, String name) throws Exception {
|
||||
Map<String, String> query = Map.of("Action", "DescribeLoadBalancers", "Version", "2012-06-01",
|
||||
"LoadBalancerNames.member.1", name);
|
||||
return given().urlEncodingEnabled(false)
|
||||
.get(signer.presignedUri("GET", baseUri, query, new byte[0])).then();
|
||||
}
|
||||
}
|
||||
+36
@@ -201,6 +201,42 @@ class IamConditionContextResolverTest {
|
||||
formRequest("PolicyArn=arn%3Aaws%3Aiam%3A%3A123456789012%3Apolicy%2FTeam%2FA%2BB%252F")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryGetConditionsUseTheFirstDecodedUrlValue() {
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.add("Action", "CreateTags");
|
||||
query.add("ResourceId.1", "i-target");
|
||||
query.add("Tag.1.Key", "Team");
|
||||
query.add("Tag.1.Value", "A+B%2F");
|
||||
query.add("Tag.1.Value", "ignored");
|
||||
when(ec2Service.resourceTags("i-target")).thenReturn(List.of(new Tag("Owner", "alice")));
|
||||
Map<String, List<String>> conditions = resolver.resolve(
|
||||
"ec2", "ec2:CreateTags", queryRequest("ec2", query));
|
||||
assertEquals(List.of("A+B%2F"), conditions.get("aws:RequestTag/Team"));
|
||||
assertEquals(List.of("Team"), conditions.get("aws:TagKeys"));
|
||||
assertEquals(List.of("alice"), conditions.get("aws:ResourceTag/Owner"));
|
||||
|
||||
query.clear();
|
||||
query.add("Action", "AttachRolePolicy");
|
||||
query.add("PolicyArn", "arn:aws:iam::123456789012:policy/Team/A+B%2F");
|
||||
assertEquals(Map.of("iam:PolicyARN", List.of("arn:aws:iam::123456789012:policy/Team/A+B%2F")),
|
||||
resolver.resolve("iam", "iam:AttachRolePolicy", queryRequest("iam", query)));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext queryRequest(String service, MultivaluedMap<String, String> query) {
|
||||
ContainerRequestContext request = mock(ContainerRequestContext.class);
|
||||
UriInfo uri = mock(UriInfo.class);
|
||||
when(request.getMethod()).thenReturn("GET");
|
||||
when(request.getHeaderString("Authorization")).thenReturn(
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261014/us-east-1/" + service + "/aws4_request");
|
||||
when(request.getUriInfo()).thenReturn(uri);
|
||||
when(uri.getPath()).thenReturn("/");
|
||||
when(uri.getQueryParameters()).thenReturn(query);
|
||||
when(request.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY))
|
||||
.thenReturn(new ProtocolClaim(WireProtocol.AWS_QUERY, null, query.getFirst("Action"), null));
|
||||
return request;
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesS3ListBucketQueryConditionContext() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
|
||||
+10
@@ -104,6 +104,16 @@ class ServiceEnablementIntegrationTest {
|
||||
.body(containsString("<Message>Service sqs is not enabled.</Message>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void signedQueryGetIsRejectedWhenItsServiceIsDisabled() {
|
||||
given().header("Authorization", authorization("sqs"))
|
||||
.queryParam("Action", "ListQueues").queryParam("Version", "2012-11-05")
|
||||
.get("/").then().statusCode(400)
|
||||
.contentType("application/xml")
|
||||
.body(containsString("<Code>ServiceNotAvailableException</Code>"))
|
||||
.body(containsString("<Message>Service sqs is not enabled.</Message>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dynamodbTargetedCborRequestsReturnCborErrors() throws Exception {
|
||||
JsonNode body = cborBody(
|
||||
|
||||
+43
@@ -481,4 +481,47 @@ class SigV4HeaderSignatureIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(19)
|
||||
void queryGetAuthenticatesTheIssuedKeyBeforeDispatch() {
|
||||
AwsRequestSigner signer = AwsRequestSigner.signedAs(
|
||||
userAccessKeyId, userSecretKey, "elasticloadbalancing");
|
||||
given().filter(signer)
|
||||
.queryParam("Action", "DescribeLoadBalancers")
|
||||
.queryParam("Version", "2012-06-01")
|
||||
.get("/").then().statusCode(200)
|
||||
.body(containsString("DescribeLoadBalancersResponse"));
|
||||
given().filter(signer.withSecret("not-the-issued-secret"))
|
||||
.queryParam("Action", "DescribeLoadBalancers")
|
||||
.queryParam("Version", "2012-06-01")
|
||||
.get("/").then().statusCode(403)
|
||||
.contentType(containsString("xml"))
|
||||
.body("ErrorResponse.Error.Code", equalTo("SignatureDoesNotMatch"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(20)
|
||||
void presignedQueryGetAuthenticatesTheIssuedKeyBeforeDispatch() throws Exception {
|
||||
URI endpoint = URI.create("http://localhost:" + RestAssured.port + "/");
|
||||
Map<String, String> query = Map.of(
|
||||
"Action", "DescribeLoadBalancers", "Version", "2012-06-01");
|
||||
AwsRequestSigner signer = AwsRequestSigner.signedAs(
|
||||
userAccessKeyId, userSecretKey, "elasticloadbalancing");
|
||||
try (HttpClient client = HttpClient.newHttpClient()) {
|
||||
URI signed = signer.presignedUri("GET", endpoint, query, new byte[0]);
|
||||
HttpResponse<String> accepted = client.send(HttpRequest.newBuilder(signed).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, accepted.statusCode(), accepted.body());
|
||||
assertTrue(accepted.body().contains("DescribeLoadBalancersResponse"), accepted.body());
|
||||
|
||||
URI forged = signer.withSecret("not-the-issued-secret")
|
||||
.presignedUri("GET", endpoint, query, new byte[0]);
|
||||
HttpResponse<String> refused = client.send(HttpRequest.newBuilder(forged).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(403, refused.statusCode(), refused.body());
|
||||
assertEquals("SignatureDoesNotMatch",
|
||||
new XmlPath(refused.body()).getString("ErrorResponse.Error.Code"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
-9
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iam;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -10,6 +11,8 @@ import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -55,19 +58,21 @@ class IamResourceScopedPolicyEnforcementIntegrationTest {
|
||||
.formatted(action, resource);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyNamingOneUserLeavesTheOthersAlone() {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"POST", "GET", "PRESIGNED"})
|
||||
void aDenyNamingOneUserLeavesTheOthersAlone(String protocol) throws Exception {
|
||||
String suffix = suffix();
|
||||
String denied = "deny-" + suffix;
|
||||
String allowed = "keep-" + suffix;
|
||||
createUser(denied);
|
||||
createUser(allowed);
|
||||
|
||||
String akid = userWith(denying("DeleteUser", arn("user/" + denied)));
|
||||
EnforcementFixtures.UserCredentials credentials = userWithCredentials(
|
||||
denying("DeleteUser", arn("user/" + denied)));
|
||||
|
||||
userIam(akid, "DeleteUser", Map.of("UserName", denied))
|
||||
iamCall(credentials, "DeleteUser", Map.of("UserName", denied), protocol)
|
||||
.statusCode(403).body(containsString("AccessDenied"));
|
||||
userIam(akid, "DeleteUser", Map.of("UserName", allowed)).statusCode(200);
|
||||
iamCall(credentials, "DeleteUser", Map.of("UserName", allowed), protocol).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -378,12 +383,16 @@ class IamResourceScopedPolicyEnforcementIntegrationTest {
|
||||
|
||||
/** An IAM user in {@link #ACCOUNT_ID} carrying {@code policy} inline. */
|
||||
private String userWith(String policy) {
|
||||
return userWithCredentials(policy).accessKeyId();
|
||||
}
|
||||
|
||||
private EnforcementFixtures.UserCredentials userWithCredentials(String policy) {
|
||||
String user = "scoped-" + suffix();
|
||||
String accessKeyId = EnforcementFixtures.createUser(cleanup, port(),
|
||||
adminAuth(), user).accessKeyId();
|
||||
EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser(cleanup, port(),
|
||||
adminAuth(), user);
|
||||
adminIam("PutUserPolicy", Map.of("UserName", user, "PolicyName", "p",
|
||||
"PolicyDocument", policy)).statusCode(200);
|
||||
return accessKeyId;
|
||||
return credentials;
|
||||
}
|
||||
|
||||
private static ValidatableResponse adminIam(String action, Map<String, String> params) {
|
||||
@@ -396,7 +405,7 @@ class IamResourceScopedPolicyEnforcementIntegrationTest {
|
||||
}
|
||||
|
||||
private static ValidatableResponse iamCall(String akid, String action,
|
||||
Map<String, String> params) {
|
||||
Map<String, String> params) {
|
||||
RequestSpecification spec = given()
|
||||
.header("Authorization", auth(akid))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
@@ -406,6 +415,23 @@ class IamResourceScopedPolicyEnforcementIntegrationTest {
|
||||
return spec.when().post("/").then();
|
||||
}
|
||||
|
||||
private ValidatableResponse iamCall(EnforcementFixtures.UserCredentials credentials, String action,
|
||||
Map<String, String> params, String protocol) throws Exception {
|
||||
if ("POST".equals(protocol)) {
|
||||
return iamCall(credentials.accessKeyId(), action, params);
|
||||
}
|
||||
AwsRequestSigner signer = AwsRequestSigner.signedAs(credentials.accessKeyId(),
|
||||
credentials.secretAccessKey(), "iam");
|
||||
Map<String, String> query = new LinkedHashMap<>(params);
|
||||
query.put("Operation", action);
|
||||
query.put("Version", "2010-05-08");
|
||||
if ("PRESIGNED".equals(protocol)) {
|
||||
return given().urlEncodingEnabled(false)
|
||||
.get(signer.presignedUri("GET", baseUri, query, new byte[0])).then();
|
||||
}
|
||||
return given().filter(signer).queryParams(query).get("/").then();
|
||||
}
|
||||
|
||||
private static String auth(String accessKeyId) {
|
||||
return EnforcementFixtures.auth(accessKeyId, "iam");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user