mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudwatch): route Query GET requests through CloudWatch (#5589)
* fix(cloudwatch): route public Query GET requests correctly Reuse Query dispatch and IAM classification for supported CloudWatch GET requests while preserving S3 and presigned URL routing. * test(cloudwatch): verify Query header name casing Signed-off-by: Andre Kurait <akurait@amazon.com> * fix(cloudwatch): match signed Query GET errors and add SDK coverage Signed-off-by: Andre Kurait <akurait@amazon.com> * fix(test): isolate TLS fixtures and escape invitation passwords Signed-off-by: Andre Kurait <akurait@amazon.com> * chore: declare directly used dependency APIs Signed-off-by: Andre Kurait <akurait@amazon.com> * fix(cloudwatch): enforce Query GET authentication and IAM policies Signed-off-by: Andre Kurait <akurait@amazon.com> * chore: follow existing framework dependency declarations Signed-off-by: Andre Kurait <akurait@amazon.com> * fix(cloudwatch): simplify signed Query GET routing Reuse the existing presigned credential resolver and let the signing scope select CloudWatch before browser or target headers. Match the current and legacy API versions observed in AWS, and cover header/presigned IAM checks. Remove unrelated CI fixture changes from this PR; they remain on the ASG branch. Signed-off-by: Andre Kurait <akurait@amazon.com> * fix(cloudwatch): isolate Query GET routing and authentication Signed-off-by: Andre Kurait <akurait@amazon.com> --------- Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
1 parent
9df4ffbfa1
commit
984e8187c9
17 files changed
+778
-38
No files matched your search
@@ -0,0 +1,109 @@
|
||||
"""CloudWatch Query GET behavior also exercised against the live AWS endpoint."""
|
||||
|
||||
import datetime
|
||||
import http.client
|
||||
import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
import xml.etree.ElementTree as ET
|
||||
from contextlib import closing
|
||||
|
||||
import boto3
|
||||
from botocore.auth import SigV4Auth, SigV4QueryAuth
|
||||
from botocore.awsrequest import AWSRequest
|
||||
from botocore.credentials import Credentials
|
||||
|
||||
|
||||
def test_cloudwatch_query_get(aws_config):
|
||||
with closing(boto3.client("cloudwatch", **aws_config)) as client:
|
||||
endpoint = client.meta.endpoint_url.rstrip("/")
|
||||
region = client.meta.region_name
|
||||
credentials = Credentials(aws_config["aws_access_key_id"], aws_config["aws_secret_access_key"],
|
||||
aws_config.get("aws_session_token"))
|
||||
|
||||
def request(method, parameters, authorization_header="Authorization", *,
|
||||
presigned=False, headers=None, version="2010-08-01"):
|
||||
query = {} if version is None else {"Version": version}
|
||||
encoded = urllib.parse.urlencode({**query, **parameters})
|
||||
url = endpoint + ("/?" + encoded if method == "GET" else "/")
|
||||
body = None if method == "GET" else encoded
|
||||
signed = AWSRequest(method=method, url=url, data=body,
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded", **(headers or {})})
|
||||
signer = (SigV4QueryAuth(credentials, "monitoring", region, expires=60) if presigned
|
||||
else SigV4Auth(credentials, "monitoring", region))
|
||||
signer.add_auth(signed)
|
||||
headers = dict(signed.headers.items())
|
||||
if not presigned:
|
||||
headers[authorization_header] = headers.pop("Authorization")
|
||||
parsed = urllib.parse.urlsplit(signed.url)
|
||||
connection_type = http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection
|
||||
with closing(connection_type(parsed.hostname, parsed.port, timeout=30)) as connection:
|
||||
connection.request(method, parsed.path + ("?" + parsed.query if parsed.query else ""),
|
||||
body=body, headers=headers)
|
||||
response = connection.getresponse()
|
||||
return response.status, ET.fromstring(response.read())
|
||||
|
||||
namespace = "FlociCompatibility/QueryGet/" + uuid.uuid4().hex
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
status, _ = request("POST", {
|
||||
"Action": "PutMetricData", "Namespace": namespace,
|
||||
"MetricData.member.1.MetricName": "Requests", "MetricData.member.1.Value": "17",
|
||||
"MetricData.member.1.Timestamp": now.isoformat(),
|
||||
})
|
||||
assert status == 200
|
||||
parameters = {
|
||||
"Action": "GetMetricStatistics", "Namespace": namespace, "MetricName": "Requests",
|
||||
"StartTime": (now - datetime.timedelta(minutes=2)).isoformat(),
|
||||
"EndTime": (now + datetime.timedelta(minutes=2)).isoformat(),
|
||||
"Period": "60", "Statistics.member.1": "Sum",
|
||||
}
|
||||
# AWS may need time to expose a newly published custom metric.
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
status, result = request("GET", parameters)
|
||||
assert status == 200
|
||||
sums = [float(node.text) for node in result.iter() if node.tag.endswith("}Sum") or node.tag == "Sum"]
|
||||
if sums or time.monotonic() >= deadline:
|
||||
assert sums == [17.0]
|
||||
break
|
||||
time.sleep(1)
|
||||
for header in ["Authorization", "authorization", "AUTHORIZATION", "aUtHoRiZaTiOn"]:
|
||||
status, result = request("GET", parameters, header)
|
||||
assert status == 200
|
||||
assert result.tag.endswith("GetMetricStatisticsResponse")
|
||||
assert [float(node.text) for node in result.iter()
|
||||
if node.tag.endswith("}Sum") or node.tag == "Sum"] == [17.0]
|
||||
status, result = request("GET", parameters, presigned=True)
|
||||
assert status == 200
|
||||
assert [float(node.text) for node in result.iter()
|
||||
if node.tag.endswith("}Sum") or node.tag == "Sum"] == [17.0]
|
||||
for selection in [{"Operation": "ListMetrics"}, {"Action": "ListMetrics", "Operation": "PutDashboard"}]:
|
||||
status, result = request("GET", selection | {"Namespace": namespace})
|
||||
assert status == 200
|
||||
assert result.tag.endswith("ListMetricsResponse")
|
||||
status, result = request("GET", {"Action": "PutDashboard"})
|
||||
assert status == 400
|
||||
assert result.tag.endswith("ErrorResponse")
|
||||
for action in ["DefinitelyUnknownAction", ""]:
|
||||
status, result = request("GET", {"Action": action})
|
||||
assert status == 404
|
||||
assert [node.text for node in result.iter() if node.tag.endswith("}Code") or node.tag == "Code"] == [
|
||||
"InvalidAction"]
|
||||
status, result = request("GET", {})
|
||||
assert status == 404
|
||||
assert result.tag.endswith("UnknownOperationException")
|
||||
for presigned in [False, True]:
|
||||
for headers in [{}, {"Accept": "text/html"}, {"X-Amz-Target": "AmazonSSM.GetParameter"}]:
|
||||
status, result = request("GET", {"Action": "ListMetrics", "Namespace": namespace},
|
||||
presigned=presigned, headers=headers)
|
||||
assert status == 200
|
||||
assert result.tag.endswith("ListMetricsResponse")
|
||||
for action, version, expected in [
|
||||
("ListMetrics", None, 200), ("ListMetrics", "2009-05-15", 200),
|
||||
("ListMetrics", "", 404), ("ListMetrics", "2000-01-01", 404),
|
||||
("ListMetricStreams", None, 404), ("ListMetricStreams", "2009-05-15", 404),
|
||||
("ListMetricStreams", "2010-08-01", 200),
|
||||
]:
|
||||
status, result = request("GET", {"Action": action}, version=version)
|
||||
assert status == expected
|
||||
assert result.tag.endswith(action + "Response" if expected == 200 else "ErrorResponse")
|
||||
@@ -330,8 +330,24 @@ aws logs put-retention-policy \
|
||||
|
||||
## CloudWatch Metrics {#metrics}
|
||||
|
||||
**Protocol:** Query (XML) and JSON 1.1 (both supported)
|
||||
**Endpoint:** `POST http://localhost:4566/`
|
||||
**Protocol:** Query (XML) and JSON 1.0 (both supported)
|
||||
|
||||
CloudWatch Query operations accept form-encoded POST requests and root GET requests with
|
||||
URL query parameters. GET uses the existing handlers, signature validation and IAM policy checks. A `monitoring`
|
||||
credential in the Authorization header or presigned URL selects CloudWatch, including
|
||||
requests with browser Accept headers or unrelated target headers. Unsigned GET requests
|
||||
select it only for unambiguous supported actions; ordinary S3, SNS and browser requests
|
||||
retain their existing routing. Only a Query protocol claim can dispatch a CloudWatch GET;
|
||||
an unclaimed request cannot perform a CloudWatch operation. Header-signed and presigned
|
||||
requests use the account and region in their credential scope.
|
||||
`Action` takes precedence over `Operation`.
|
||||
|
||||
Use `Version=2010-08-01` for current GET operations. Omitting the version selects the
|
||||
legacy `2009-05-15` API, which supports only `ListMetrics` and `GetMetricStatistics`.
|
||||
An invalid version or action returns HTTP 404 `InvalidAction`; an absent action returns
|
||||
HTTP 404 `UnknownOperationException`. IAM policies use the `cloudwatch` action prefix.
|
||||
|
||||
**Endpoint:** `http://localhost:4566/`. Query: GET or POST; JSON: POST.
|
||||
|
||||
### Supported Actions
|
||||
|
||||
|
||||
@@ -73,6 +73,10 @@ public class AwsProtocolClaimFilter implements ContainerRequestFilter {
|
||||
|
||||
ProtocolClaim resolved = claim.get();
|
||||
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());
|
||||
}
|
||||
if (resolved.protocol() == WireProtocol.REST) {
|
||||
Optional<String> scope = SigV4CredentialScope.serviceName(signals.authorization());
|
||||
if (scope.isPresent() && catalog.byCredentialScope(scope.get()).isEmpty()) {
|
||||
|
||||
@@ -23,15 +23,17 @@ import io.github.hectorvent.floci.services.sns.SnsQueryHandler;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsQueryHandler;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
@@ -52,6 +54,8 @@ import java.util.stream.Stream;
|
||||
@Path("/")
|
||||
public class AwsQueryController {
|
||||
|
||||
static final String CLOUDWATCH_GET_PATH = "/_cloudwatch-query";
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AwsQueryController.class);
|
||||
|
||||
private static final Set<String> STS_ACTIONS = Set.of(
|
||||
@@ -298,7 +302,6 @@ public class AwsQueryController {
|
||||
@Produces(MediaType.APPLICATION_XML)
|
||||
public Response dispatch(
|
||||
@HeaderParam("Authorization") String authorization,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
MultivaluedMap<String, String> formParams) {
|
||||
|
||||
String action = AwsQueryServiceResolver.action(formParams);
|
||||
@@ -310,7 +313,7 @@ public class AwsQueryController {
|
||||
String service = serviceResolver.resolve(authorization, action, formParams.getFirst("Version"));
|
||||
LOG.debugv("Query protocol service={0} action={1}", service, action);
|
||||
|
||||
String region = regionResolver.resolveRegion(httpHeaders);
|
||||
String region = regionResolver.resolveRegionFromAuth(authorization);
|
||||
|
||||
try {
|
||||
return dispatchToHandler(service, action, formParams, authorization, region);
|
||||
@@ -535,6 +538,8 @@ public class AwsQueryController {
|
||||
"ListTagsForResource"
|
||||
);
|
||||
|
||||
private static final String CLOUDWATCH_API_VERSION = "2010-08-01";
|
||||
|
||||
private static final Set<String> CLOUDWATCH_ACTIONS = Set.of(
|
||||
"PutMetricData", "ListMetrics", "GetMetricStatistics", "GetMetricData",
|
||||
"PutMetricAlarm", "DescribeAlarms", "DeleteAlarms", "SetAlarmState",
|
||||
@@ -651,6 +656,49 @@ public class AwsQueryController {
|
||||
"GetClusterCredentials", "GetClusterCredentialsWithIAM"
|
||||
);
|
||||
|
||||
/** 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)
|
||||
@Produces({MediaType.APPLICATION_XML, MediaType.TEXT_HTML})
|
||||
public Response dispatchCloudWatchQueryGet(@HeaderParam("Authorization") String authorization,
|
||||
@Context UriInfo uriInfo,
|
||||
@Context ContainerRequestContext request) {
|
||||
// Only the pre-matching Query claim may select this internal route.
|
||||
if (!(request.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim)
|
||||
|| claim.protocol() != WireProtocol.AWS_QUERY) {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
|
||||
String action = AwsQueryServiceResolver.action(queryParams);
|
||||
if (action == null) {
|
||||
return Response.status(404).type(MediaType.APPLICATION_XML)
|
||||
.entity("<UnknownOperationException/>").build();
|
||||
}
|
||||
String version = queryParams.getFirst("Version");
|
||||
version = version == null ? "2009-05-15" : version;
|
||||
Set<String> actions = switch (version) {
|
||||
case "2009-05-15" -> Set.of("ListMetrics", "GetMetricStatistics");
|
||||
case CLOUDWATCH_API_VERSION -> CLOUDWATCH_ACTIONS;
|
||||
default -> Set.of();
|
||||
};
|
||||
if (!actions.contains(action)) {
|
||||
return xmlErrorResponse("InvalidAction", "Could not find operation " + action + " for version "
|
||||
+ version, 404);
|
||||
}
|
||||
return dispatch(IamEnforcementFilter.requestAuthorization(authorization, queryParams), queryParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tried last, so by name alone SQS takes only what no other service defines, as it takes a name
|
||||
* nobody defines. Its {@code Version} is what wins back the two names SNS also defines.
|
||||
@@ -691,7 +739,7 @@ public class AwsQueryController {
|
||||
new QueryService("sns", Set.of("2010-03-31"), SNS_ACTIONS),
|
||||
new QueryService("elasticache", Set.of("2015-02-02"), ELASTICACHE_ACTIONS),
|
||||
new QueryService("rds", Set.of("2014-10-31"), RDS_ACTIONS),
|
||||
new QueryService("monitoring", Set.of("2010-08-01"), CLOUDWATCH_ACTIONS),
|
||||
new QueryService("monitoring", Set.of(CLOUDWATCH_API_VERSION), CLOUDWATCH_ACTIONS),
|
||||
new QueryService("cloudformation", Set.of("2010-05-15"), CLOUDFORMATION_ACTIONS),
|
||||
new QueryService("email", Set.of("2010-12-01"), SES_ACTIONS),
|
||||
new QueryService("cognito-idp", Set.of(), COGNITO_ACTIONS),
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
|
||||
/**
|
||||
* The non-payload identification signals a request's wire protocol is claimed
|
||||
* from: HTTP method, path, and the claim-relevant headers. The entity stream
|
||||
* from: HTTP method, path, query parameters, and claim-relevant headers. The entity stream
|
||||
* is deliberately absent — claiming must never touch it.
|
||||
*
|
||||
* @param method the HTTP method
|
||||
@@ -14,9 +15,12 @@ import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
* @param smithyProtocol the raw Smithy-Protocol header, or null
|
||||
* @param xAmzTarget the raw X-Amz-Target header, or null
|
||||
* @param authorization the raw Authorization header, or null
|
||||
* @param accept the raw Accept header, or null
|
||||
* @param queryParameters the request query parameters
|
||||
*/
|
||||
public record ClaimSignals(String method, String path, String contentType,
|
||||
String smithyProtocol, String xAmzTarget, String authorization) {
|
||||
String smithyProtocol, String xAmzTarget, String authorization,
|
||||
String accept, MultivaluedMap<String, String> queryParameters) {
|
||||
|
||||
static ClaimSignals from(ContainerRequestContext ctx) {
|
||||
String contentType = ctx.getHeaderString(AwsCborContentTypeFilter.ORIGINAL_CONTENT_TYPE_HEADER);
|
||||
@@ -29,6 +33,8 @@ public record ClaimSignals(String method, String path, String contentType,
|
||||
contentType,
|
||||
ctx.getHeaderString(ProtocolClaimer.SMITHY_PROTOCOL_HEADER),
|
||||
ctx.getHeaderString("X-Amz-Target"),
|
||||
ctx.getHeaderString("Authorization"));
|
||||
ctx.getHeaderString("Authorization"),
|
||||
ctx.getHeaderString("Accept"),
|
||||
ctx.getUriInfo().getQueryParameters());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -552,7 +552,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
private ResolvedAuthorization resolveAuthorization(String auth, String claimedScope,
|
||||
ContainerRequestContext ctx) {
|
||||
Object claimValue = ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY);
|
||||
// Authorization must not depend on the pre-matching claim filter running first.
|
||||
// Form POSTs are also recognized without a claim; GET dispatch requires the Query claim.
|
||||
if (IamActionRegistry.isQueryRequest(ctx)) {
|
||||
String queryAction = actionRegistry.queryAction(ctx);
|
||||
if (queryAction == null || queryAction.isBlank()) {
|
||||
@@ -774,7 +774,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
// Sorting the rest keeps the choice stable, since credentialScopes is a Set.of whose
|
||||
// iteration order changes per JVM run.
|
||||
if (descriptor.credentialScopes().contains(descriptor.externalKey())) {
|
||||
return descriptor.externalKey();
|
||||
return catalog.canonicalCredentialScope(descriptor.externalKey());
|
||||
}
|
||||
return descriptor.credentialScopes().stream()
|
||||
.filter(scope -> scope.equals(catalog.canonicalCredentialScope(scope)))
|
||||
@@ -1454,7 +1454,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
if (isCbor(protocol)) {
|
||||
return cborError(ctx, code, message, status);
|
||||
}
|
||||
if (isFormEncoded(ctx.getMediaType())) {
|
||||
if (protocol == WireProtocol.AWS_QUERY || isFormEncoded(ctx.getMediaType())) {
|
||||
return queryXmlError(queryCode, message, status);
|
||||
}
|
||||
return jsonError(code, message, status);
|
||||
|
||||
@@ -15,10 +15,11 @@ import java.util.regex.Pattern;
|
||||
* first protocol whose "identification for claiming" signals match claims the
|
||||
* request.
|
||||
* <p>
|
||||
* Claiming uses non-payload signals only (method, path, headers) so it is safe
|
||||
* 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 is narrowed to POST {@code /} with the form
|
||||
* content type; the spec's body-level {@code Action}/{@code Version} checks
|
||||
* consequence the awsQuery claim covers POST {@code /} with the form
|
||||
* content type and the CloudWatch 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
|
||||
* below awsQuery in the precision order claims such requests, so the narrowed
|
||||
@@ -92,6 +93,14 @@ public class ProtocolClaimer {
|
||||
return Optional.of(rpcV2Claim(WireProtocol.RPCV2_CBOR, rpcV2Path));
|
||||
}
|
||||
|
||||
if ("GET".equalsIgnoreCase(signals.method()) && isRootPath(path)
|
||||
&& AwsQueryController.isCloudWatchQueryGet(signals.authorization(),
|
||||
signals.xAmzTarget(), signals.accept(), signals.queryParameters())) {
|
||||
ServiceDescriptor service = catalog.byCredentialScope("monitoring").orElse(null);
|
||||
return Optional.of(new ProtocolClaim(WireProtocol.AWS_QUERY, service,
|
||||
AwsQueryServiceResolver.action(signals.queryParameters()), null));
|
||||
}
|
||||
|
||||
if (post && isRootPath(path)) {
|
||||
String target = signals.xAmzTarget();
|
||||
if (target != null) {
|
||||
|
||||
@@ -104,6 +104,7 @@ public class ResolvedServiceCatalog {
|
||||
java.util.Map.of(
|
||||
"s3express", "s3",
|
||||
"iot-jobs-data", "iot",
|
||||
"monitoring", "cloudwatch",
|
||||
"awsssoportal", "sso");
|
||||
|
||||
private final ServiceCatalog catalog;
|
||||
|
||||
+3
-1
@@ -448,7 +448,9 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
|
||||
CborErrorResponses.mediaTypeFor(contentType)));
|
||||
return;
|
||||
}
|
||||
if (isFormEncoded(ctx.getMediaType())) {
|
||||
if (isFormEncoded(ctx.getMediaType())
|
||||
|| ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
|
||||
&& claim.protocol() == WireProtocol.AWS_QUERY) {
|
||||
ctx.abortWith(AwsQueryResponse.error(queryCode, message, null, status));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsProtocolClaimFilter;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
|
||||
import io.github.hectorvent.floci.core.common.ProtocolClaim;
|
||||
import io.github.hectorvent.floci.core.common.WireProtocol;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
@@ -318,32 +321,42 @@ public class IamActionRegistry {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Query-protocol action from the form body while preserving the entity stream for
|
||||
* the controller. The controller dispatches only the form body, using the same Action-first,
|
||||
* Operation-second rule. A URL Action must not override the operation that will execute.
|
||||
* Returns the Query action from GET query parameters or the POST form body, preserving the
|
||||
* entity stream. Both use the controller's Action-first, Operation-second rule; a POST URL
|
||||
* Action must not override the form operation that will execute.
|
||||
*/
|
||||
public String queryAction(ContainerRequestContext ctx) {
|
||||
if ("GET".equalsIgnoreCase(ctx.getMethod())) {
|
||||
return AwsQueryServiceResolver.action(ctx.getUriInfo().getQueryParameters());
|
||||
}
|
||||
return AwsQueryServiceResolver.action(
|
||||
RequestBodyReader.formField(ctx, "Action"),
|
||||
RequestBodyReader.formField(ctx, "Operation"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the API version a Query request declares, from the form body for the same reason as
|
||||
* {@link #queryAction}: it is the value the controller routes on.
|
||||
*/
|
||||
/** Returns the API version from the same Query input that the controller dispatches. */
|
||||
public String queryVersion(ContainerRequestContext ctx) {
|
||||
if ("GET".equalsIgnoreCase(ctx.getMethod())) {
|
||||
return ctx.getUriInfo().getQueryParameters().getFirst("Version");
|
||||
}
|
||||
return RequestBodyReader.formField(ctx, "Version");
|
||||
}
|
||||
|
||||
/** The same form POST at the root that the Query controller dispatches. */
|
||||
/** The root form POST or CloudWatch GET that the Query controller dispatches. */
|
||||
public static boolean isQueryRequest(ContainerRequestContext ctx) {
|
||||
if (!"POST".equalsIgnoreCase(ctx.getMethod()) || ctx.getUriInfo() == null) {
|
||||
if ("GET".equalsIgnoreCase(ctx.getMethod())) {
|
||||
return ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
|
||||
&& claim.protocol() == WireProtocol.AWS_QUERY;
|
||||
}
|
||||
if (ctx.getUriInfo() == null) {
|
||||
return false;
|
||||
}
|
||||
String path = ctx.getUriInfo().getPath();
|
||||
if (path != null && !path.isEmpty() && !"/".equals(path)) {
|
||||
return false;
|
||||
}
|
||||
MediaType mediaType = ctx.getMediaType();
|
||||
return (path == null || path.isEmpty() || "/".equals(path))
|
||||
return "POST".equalsIgnoreCase(ctx.getMethod())
|
||||
&& mediaType != null
|
||||
&& "application".equalsIgnoreCase(mediaType.getType())
|
||||
&& "x-www-form-urlencoded".equalsIgnoreCase(mediaType.getSubtype());
|
||||
|
||||
@@ -82,7 +82,7 @@ class CredentialScopeAliasTest {
|
||||
.filter(scope -> !scope.equals(catalog.canonicalCredentialScope(scope)))
|
||||
.collect(Collectors.toMap(scope -> scope, catalog::canonicalCredentialScope));
|
||||
|
||||
assertEquals(Map.of("s3express", "s3", "iot-jobs-data", "iot", "awsssoportal", "sso"), rewritten);
|
||||
assertEquals(Map.of("s3express", "s3", "iot-jobs-data", "iot", "awsssoportal", "sso", "monitoring", "cloudwatch"), rewritten);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+34
-1
@@ -2,7 +2,11 @@ package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -22,7 +26,8 @@ class ProtocolClaimerIntegrationTest {
|
||||
|
||||
private Optional<ProtocolClaim> claim(String method, String path, String contentType,
|
||||
String smithyProtocol, String xAmzTarget, String authorization) {
|
||||
return claimer.claim(new ClaimSignals(method, path, contentType, smithyProtocol, xAmzTarget, authorization));
|
||||
return claimer.claim(new ClaimSignals(method, path, contentType, smithyProtocol, xAmzTarget,
|
||||
authorization, null, new MultivaluedHashMap<>()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -140,6 +145,34 @@ class ProtocolClaimerIntegrationTest {
|
||||
assertNull(withoutAuth.service());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Action", "Operation"})
|
||||
void cloudWatchGetsUseTheQueryClaimWithOrWithoutASignature(String actionParameter) {
|
||||
MultivaluedHashMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.putSingle(actionParameter, "GetMetricStatistics");
|
||||
query.putSingle("Version", "2010-08-01");
|
||||
for (String authorization : new String[] {null, SQS_AUTH.replace("/sqs/", "/monitoring/")}) {
|
||||
ProtocolClaim claim = claimer.claim(new ClaimSignals("GET", "/", null, null, null,
|
||||
authorization, null, query)).orElseThrow();
|
||||
assertEquals(WireProtocol.AWS_QUERY, claim.protocol());
|
||||
assertEquals("monitoring", claim.service().externalKey());
|
||||
assertEquals("GetMetricStatistics", claim.operation());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"GET, /bucket",
|
||||
"POST, /"
|
||||
})
|
||||
void cloudWatchGetClaimRequiresARootGet(String method, String path) {
|
||||
MultivaluedHashMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.putSingle("Action", "GetMetricStatistics");
|
||||
ProtocolClaim claim = claimer.claim(new ClaimSignals(method, path, null, null, null,
|
||||
SQS_AUTH.replace("/sqs/", "/monitoring/"), null, query)).orElseThrow();
|
||||
assertEquals(WireProtocol.REST, claim.protocol());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonRpcTrafficFallsThroughAsRest() {
|
||||
Optional<ProtocolClaim> get = claim("GET", "/", null, null, null, null);
|
||||
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.config.EncoderConfig;
|
||||
import io.restassured.http.ContentType;
|
||||
import io.restassured.response.Response;
|
||||
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.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.config;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class CloudWatchQueryGetIamEnforcementIntegrationTest {
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Action", "Operation"})
|
||||
void unsignedWritesReturnQueryAuthenticationErrors(String actionParameter) {
|
||||
given()
|
||||
.queryParam(actionParameter, "PutMetricData")
|
||||
.queryParam("Version", "2010-08-01")
|
||||
.queryParam("Namespace", "query-auth-" + UUID.randomUUID())
|
||||
.queryParam("MetricData.member.1.MetricName", "Denied")
|
||||
.queryParam("MetricData.member.1.Value", "1")
|
||||
.when().get("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.contentType(containsString("xml"))
|
||||
.body("ErrorResponse.Error.Code", equalTo("MissingAuthenticationToken"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"rpc-v2-cbor", "unknown"})
|
||||
void anUnclaimedGetCannotDeleteAnAlarm(String smithyProtocol) {
|
||||
String alarm = "query-unclaimed-" + UUID.randomUUID();
|
||||
String root = auth("000000000000", "monitoring");
|
||||
given().header("Authorization", root).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "PutMetricAlarm").formParam("Version", "2010-08-01")
|
||||
.formParam("AlarmName", alarm).formParam("Namespace", "Example/QueryGet")
|
||||
.formParam("MetricName", "Requests").formParam("Statistic", "Sum").formParam("Period", "60")
|
||||
.formParam("EvaluationPeriods", "1").formParam("Threshold", "1")
|
||||
.formParam("ComparisonOperator", "GreaterThanThreshold")
|
||||
.post("/").then().statusCode(200);
|
||||
cleanup.register(() -> given().port(baseUri.getPort()).header("Authorization", root)
|
||||
.contentType("application/x-www-form-urlencoded").formParam("Action", "DeleteAlarms")
|
||||
.formParam("AlarmNames.member.1", alarm).post("/").then().statusCode(200));
|
||||
given().header("Smithy-Protocol", smithyProtocol).queryParam("Action", "DeleteAlarms")
|
||||
.queryParam("Version", "2010-08-01").queryParam("AlarmNames.member.1", alarm)
|
||||
.get("/").then().body(not(containsString("DeleteAlarmsResponse")));
|
||||
given().header("Authorization", root).queryParam("Action", "DescribeAlarms")
|
||||
.queryParam("Version", "2010-08-01").queryParam("AlarmNames.member.1", alarm)
|
||||
.get("/").then().statusCode(200).body(containsString(alarm));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"rpc-v2-cbor", "unknown"})
|
||||
void anUnclaimedGetCannotPublishMetrics(String smithyProtocol) {
|
||||
String namespace = "query-unclaimed-" + UUID.randomUUID();
|
||||
given().header("Smithy-Protocol", smithyProtocol).queryParam("Action", "PutMetricData")
|
||||
.queryParam("Version", "2010-08-01").queryParam("Namespace", namespace)
|
||||
.queryParam("MetricData.member.1.MetricName", "Denied").queryParam("MetricData.member.1.Value", "1")
|
||||
.get("/").then().body(not(containsString("PutMetricDataResponse")));
|
||||
given().header("Authorization", auth("000000000000", "monitoring"))
|
||||
.queryParam("Action", "ListMetrics").queryParam("Version", "2010-08-01")
|
||||
.queryParam("Namespace", namespace).get("/").then().statusCode(200)
|
||||
.body(not(containsString(namespace)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void internalRouteCannotBeCalledDirectly() {
|
||||
given().header("Authorization", auth("000000000000", "monitoring"))
|
||||
.queryParam("Action", "ListMetrics").get("/_cloudwatch-query")
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"Action,false", "Operation,false", "Action,true", "Operation,true"})
|
||||
void deniedSignedReadsReturnQueryAuthorizationErrors(String actionParameter, boolean presigned) {
|
||||
String user = "query-denied-" + UUID.randomUUID();
|
||||
String accessKey = EnforcementFixtures.createUser(
|
||||
cleanup, baseUri.getPort(), auth("000000000000", "iam"), user).accessKeyId();
|
||||
|
||||
signedRequest(accessKey, presigned)
|
||||
.queryParam(actionParameter, "ListMetrics")
|
||||
.queryParam("Version", "2010-08-01")
|
||||
.when().get("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.contentType(containsString("xml"))
|
||||
.body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"GET,Action", "GET,Operation", "PRESIGNED,Action", "PRESIGNED,Operation",
|
||||
"POST,Action", "JSON,Action"})
|
||||
void anAllowedSignedReadStillReachesCloudWatch(String protocol, String actionParameter) {
|
||||
String user = "query-allowed-" + UUID.randomUUID();
|
||||
String admin = auth("000000000000", "iam");
|
||||
String accessKey = EnforcementFixtures.createUser(
|
||||
cleanup, baseUri.getPort(), admin, user).accessKeyId();
|
||||
given()
|
||||
.header("Authorization", admin)
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "PutUserPolicy")
|
||||
.formParam("Version", "2010-05-08")
|
||||
.formParam("UserName", user)
|
||||
.formParam("PolicyName", "list-metrics")
|
||||
.formParam("PolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Allow","Action":"cloudwatch:ListMetrics","Resource":"*"
|
||||
}]}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
RequestSpecification request = signedRequest(accessKey, "PRESIGNED".equals(protocol));
|
||||
Response response = switch (protocol) {
|
||||
case "JSON" -> request.contentType("application/x-amz-json-1.0")
|
||||
.config(config().encoderConfig(EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs("application/x-amz-json-1.0", ContentType.JSON)))
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801.ListMetrics").body("{}").post("/");
|
||||
case "POST" -> request.contentType("application/x-www-form-urlencoded")
|
||||
.formParam(actionParameter, "ListMetrics").formParam("Version", "2010-08-01").post("/");
|
||||
default -> request.queryParam(actionParameter, "ListMetrics")
|
||||
.queryParam("Version", "2010-08-01").get("/");
|
||||
};
|
||||
response.then().statusCode(200);
|
||||
if ("JSON".equals(protocol)) {
|
||||
response.then().contentType(containsString("json"));
|
||||
} else {
|
||||
response.then().contentType(containsString("xml")).body(containsString("ListMetricsResponse"));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void userPolicyAndAlarmStorageUseTheCredentialAccount(boolean presigned) {
|
||||
String account = "111122223333";
|
||||
String admin = auth(account, "iam");
|
||||
String user = "query-account-" + UUID.randomUUID();
|
||||
String alarm = "query-account-" + UUID.randomUUID();
|
||||
String key = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), admin, user).accessKeyId();
|
||||
given().header("Authorization", admin).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "PutUserPolicy").formParam("UserName", user).formParam("PolicyName", "cloudwatch")
|
||||
.formParam("PolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Allow","Action":"cloudwatch:*","Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:PrincipalAccount":"111122223333"}}
|
||||
}]}
|
||||
""").post("/").then().statusCode(200);
|
||||
cleanup.register(() -> given().port(baseUri.getPort()).header("Authorization", auth(account, "monitoring"))
|
||||
.contentType("application/x-www-form-urlencoded").formParam("Action", "DeleteAlarms")
|
||||
.formParam("AlarmNames.member.1", alarm).post("/").then().statusCode(200));
|
||||
signedRequest(key, presigned).queryParam("Action", "PutMetricAlarm").queryParam("Version", "2010-08-01")
|
||||
.queryParam("AlarmName", alarm).queryParam("Namespace", "Example/QueryGet")
|
||||
.queryParam("MetricName", "Requests").queryParam("Statistic", "Sum").queryParam("Period", "60")
|
||||
.queryParam("EvaluationPeriods", "1").queryParam("Threshold", "1")
|
||||
.queryParam("ComparisonOperator", "GreaterThanThreshold")
|
||||
.get("/").then().statusCode(200);
|
||||
signedRequest(key, presigned).queryParam("Action", "DescribeAlarms").queryParam("Version", "2010-08-01")
|
||||
.queryParam("AlarmNames.member.1", alarm).get("/").then().statusCode(200)
|
||||
.body(containsString("arn:aws:cloudwatch:us-east-1:" + account + ":alarm:" + alarm));
|
||||
signedRequest("000000000000", presigned).queryParam("Action", "DescribeAlarms")
|
||||
.queryParam("Version", "2010-08-01").queryParam("AlarmNames.member.1", alarm)
|
||||
.get("/").then().statusCode(200).body(not(containsString(alarm)));
|
||||
}
|
||||
|
||||
private static RequestSpecification signedRequest(String accessKey, boolean presigned) {
|
||||
return presigned
|
||||
? given().queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
|
||||
.queryParam("X-Amz-Credential", accessKey + "/20261013/us-east-1/monitoring/aws4_request")
|
||||
: given().header("Authorization", auth(accessKey, "monitoring"));
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudWatchQueryGetIntegrationTest {
|
||||
|
||||
private static String authorization(String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=test/20261013/us-east-1/" + service + "/aws4_request";
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Authorization", "authorization", "AUTHORIZATION", "aUtHoRiZaTiOn"})
|
||||
void getReadsMetricWrittenThroughPublicPost(String headerName) {
|
||||
Instant now = Instant.now();
|
||||
String namespace = "Example/QueryGet/" + headerName;
|
||||
given().header(headerName, authorization("monitoring"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "PutMetricData").formParam("Version", "2010-08-01")
|
||||
.formParam("Namespace", namespace)
|
||||
.formParam("MetricData.member.1.MetricName", "Requests")
|
||||
.formParam("MetricData.member.1.Value", "17")
|
||||
.formParam("MetricData.member.1.Timestamp", now.toString())
|
||||
.post("/").then().statusCode(200);
|
||||
given().header(headerName, authorization("monitoring"))
|
||||
.queryParam("Action", "GetMetricStatistics").queryParam("Version", "2010-08-01")
|
||||
.queryParam("Namespace", namespace).queryParam("MetricName", "Requests")
|
||||
.queryParam("StartTime", now.minusSeconds(120).toString())
|
||||
.queryParam("EndTime", now.plusSeconds(120).toString()).queryParam("Period", "60")
|
||||
.queryParam("Statistics.member.1", "Sum")
|
||||
.get("/").then().statusCode(200)
|
||||
.body("GetMetricStatisticsResponse.GetMetricStatisticsResult.Datapoints.member.Sum", equalTo("17.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void operationFallbackUsesTheSamePublicHandler() {
|
||||
given().header("Authorization", authorization("monitoring"))
|
||||
.queryParam("Operation", "ListMetrics")
|
||||
.get("/").then().statusCode(200).body(containsString("ListMetricsResponse"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3ScopeAndUnrelatedQueryKeepBucketListing() {
|
||||
given().header("Authorization", authorization("s3"))
|
||||
.queryParam("Action", "GetMetricStatistics")
|
||||
.get("/").then().statusCode(200).body(containsString("ListAllMyBucketsResult"));
|
||||
given().queryParam("X-Amz-Credential", "test/20261013/us-east-1/s3/aws4_request")
|
||||
.queryParam("Action", "GetMetricStatistics")
|
||||
.get("/").then().statusCode(200).body(containsString("ListAllMyBucketsResult"));
|
||||
given().queryParam("Action", "UnknownAction")
|
||||
.get("/").then().statusCode(200).body(containsString("ListAllMyBucketsResult"));
|
||||
given().queryParam("Action", "TagResource")
|
||||
.get("/").then().statusCode(200).body(containsString("ListAllMyBucketsResult"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cloudWatchValidationStillReturnsQueryErrors() {
|
||||
given().header("Authorization", authorization("monitoring"))
|
||||
.queryParam("Action", "PutDashboard").queryParam("Version", "2010-08-01")
|
||||
.get("/").then().statusCode(400).body(containsString("ErrorResponse"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"false, , ", "false, text/html, ", "false, , AmazonSSM.GetParameter",
|
||||
"true, , ", "true, text/html, NotAService.Operation"})
|
||||
void signingScopeSelectsCloudWatchRegardlessOfBrowserOrTargetHeaders(
|
||||
boolean presigned, String accept, String target) {
|
||||
RequestSpecification request = given().queryParam("Action", "ListMetrics");
|
||||
if (presigned) {
|
||||
request.queryParam("X-Amz-Credential", "test/20261013/us-east-1/monitoring/aws4_request");
|
||||
} else {
|
||||
request.header("Authorization", authorization("monitoring"));
|
||||
}
|
||||
if (accept != null) {
|
||||
request.header("Accept", accept);
|
||||
}
|
||||
if (target != null) {
|
||||
request.header("X-Amz-Target", target);
|
||||
}
|
||||
request.get("/").then().statusCode(200).body(containsString("ListMetricsResponse"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(value = {
|
||||
"ListMetrics, OMITTED, 200", "ListMetrics, 2009-05-15, 200", "ListMetrics, 2010-08-01, 200",
|
||||
"ListMetrics, '', 404", "ListMetrics, 2000-01-01, 404",
|
||||
"ListMetricStreams, OMITTED, 404", "ListMetricStreams, 2009-05-15, 404",
|
||||
"ListMetricStreams, 2010-08-01, 200"
|
||||
}, nullValues = "OMITTED")
|
||||
void versionSelectsTheCurrentOrLegacyOperations(String action, String version, int status) {
|
||||
RequestSpecification request = given().header("Authorization", authorization("monitoring"))
|
||||
.queryParam("Action", action);
|
||||
if (version != null) {
|
||||
request.queryParam("Version", version);
|
||||
}
|
||||
if (status == 200) {
|
||||
request.get("/").then().statusCode(status).body(containsString(action + "Response"));
|
||||
} else {
|
||||
request.get("/").then().statusCode(status)
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidAction"));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"ListMetrics,UnknownAction,200", "UnknownAction,ListMetrics,404", "ListMetrics,ListMetrics,200"})
|
||||
void theFirstRepeatedActionWins(String first, String second, int status) {
|
||||
given().header("Authorization", authorization("monitoring"))
|
||||
.queryParam("Action", first, second)
|
||||
.get("/").then().statusCode(status)
|
||||
.body(containsString(status == 200 ? "ListMetricsResponse" : "InvalidAction"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"UnknownAction", ""})
|
||||
void signedUnknownCloudWatchActionsReturnAwsErrors(String action) {
|
||||
given().header("Authorization", authorization("monitoring"))
|
||||
.queryParam("Action", action).queryParam("Version", "2010-08-01")
|
||||
.get("/").then().statusCode(404)
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidAction"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void signedCloudWatchGetWithoutAnActionReturnsUnknownOperation() {
|
||||
given().header("Authorization", authorization("monitoring"))
|
||||
.queryParam("Version", "2010-08-01")
|
||||
.get("/").then().statusCode(404).body(containsString("<UnknownOperationException/>"));
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
|
||||
import io.github.hectorvent.floci.testutil.S3RequestSigner;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(CloudWatchQueryGetSignatureIntegrationTest.Authentication.class)
|
||||
class CloudWatchQueryGetSignatureIntegrationTest {
|
||||
|
||||
public static class Authentication implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.auth.validate-signatures", "true",
|
||||
"floci.services.s3.enforce-auth", "true",
|
||||
"floci.services.iam.enforcement-enabled", "true");
|
||||
}
|
||||
}
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void genuineSignaturesReachCloudWatchAndTamperingIsRefused(boolean presigned) throws Exception {
|
||||
AwsRequestSigner signer = AwsRequestSigner.signedAs("test", "test", "monitoring");
|
||||
Map<String, String> query = Map.of("Action", "ListMetrics", "Version", "2010-08-01");
|
||||
request(signer, query, presigned).then().statusCode(200).body(containsString("ListMetricsResponse"));
|
||||
request(signer.withSecret("wrong-secret"), query, presigned).then().statusCode(403)
|
||||
.contentType(containsString("xml"))
|
||||
.body("ErrorResponse.Error.Code", equalTo("SignatureDoesNotMatch"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void regionalWritesAndIamConditionsUseTheSigningRegion(boolean presigned) throws Exception {
|
||||
String user = "cw-query-" + UUID.randomUUID();
|
||||
String alarm = "cw-query-" + UUID.randomUUID();
|
||||
String key = null;
|
||||
AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "monitoring").inRegion("us-west-2");
|
||||
iam("CreateUser", Map.of("UserName", user)).then().statusCode(200);
|
||||
try {
|
||||
Response credentials = iam("CreateAccessKey", Map.of("UserName", user));
|
||||
credentials.then().statusCode(200);
|
||||
key = credentials.xmlPath().getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
|
||||
String secret = credentials.xmlPath().getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey");
|
||||
iam("PutUserPolicy", Map.of("UserName", user, "PolicyName", "regional-cloudwatch", "PolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Allow","Action":["cloudwatch:PutMetricAlarm","cloudwatch:DescribeAlarms"],
|
||||
"Resource":"*","Condition":{"StringEquals":{
|
||||
"aws:RequestedRegion":"us-west-2","aws:PrincipalAccount":"000000000000"}}
|
||||
}]}
|
||||
""")).then().statusCode(200);
|
||||
AwsRequestSigner signer = AwsRequestSigner.signedAs(key, secret, "monitoring").inRegion("us-west-2");
|
||||
request(signer, Map.of("Action", "PutMetricAlarm", "Version", "2010-08-01", "AlarmName", alarm,
|
||||
"Namespace", "Example/QueryGet", "MetricName", "Requests", "Statistic", "Sum", "Period", "60",
|
||||
"EvaluationPeriods", "1", "Threshold", "1", "ComparisonOperator", "GreaterThanThreshold"), presigned)
|
||||
.then().statusCode(200);
|
||||
Map<String, String> describe = Map.of("Action", "DescribeAlarms", "Version", "2010-08-01",
|
||||
"AlarmNames.member.1", alarm);
|
||||
request(signer, describe, presigned).then().statusCode(200)
|
||||
.body(containsString("arn:aws:cloudwatch:us-west-2:000000000000:alarm:" + alarm));
|
||||
request(signer.inRegion("us-east-1"), describe, presigned).then().statusCode(403)
|
||||
.body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
|
||||
request(root.inRegion("us-east-1"), describe, presigned).then().statusCode(200)
|
||||
.body(not(containsString(alarm)));
|
||||
request(signer, Map.of("Action", "DeleteAlarms", "Version", "2010-08-01",
|
||||
"AlarmNames.member.1", alarm), presigned).then().statusCode(403)
|
||||
.body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
|
||||
request(signer, describe, presigned).then().statusCode(200).body(containsString(alarm));
|
||||
} finally {
|
||||
request(root, Map.of("Action", "DeleteAlarms", "Version", "2010-08-01",
|
||||
"AlarmNames.member.1", alarm), false).then().statusCode(200);
|
||||
if (key != null) {
|
||||
iam("DeleteAccessKey", Map.of("UserName", user, "AccessKeyId", key)).then().statusCode(200);
|
||||
}
|
||||
iam("DeleteUserPolicy", Map.of("UserName", user, "PolicyName", "regional-cloudwatch"));
|
||||
iam("DeleteUser", Map.of("UserName", user)).then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void signedS3ControlRequestStaysWithS3() throws Exception {
|
||||
given().filter(S3RequestSigner.signedAs("test", "test")).queryParam("Action", "ListMetrics")
|
||||
.get("/").then().statusCode(200).body(containsString("ListAllMyBucketsResult"));
|
||||
}
|
||||
|
||||
private Response request(AwsRequestSigner signer, Map<String, String> query, boolean presigned) throws Exception {
|
||||
if (presigned) {
|
||||
return given().urlEncodingEnabled(false).get(signer.presignedUri("GET", endpoint, query, new byte[0]));
|
||||
}
|
||||
URI uri = URI.create(endpoint + "?" + encode(query));
|
||||
return given().urlEncodingEnabled(false).headers(signer.headersFor("GET", uri, Map.of(), new byte[0])).get(uri);
|
||||
}
|
||||
|
||||
private Response iam(String action, Map<String, String> parameters) throws Exception {
|
||||
String body = "Action=" + action + "&Version=2010-05-08&" + encode(parameters);
|
||||
return given().headers(AwsRequestSigner.signedAs("test", "test", "iam")
|
||||
.headersFor("POST", endpoint, Map.of(), body.getBytes(StandardCharsets.UTF_8)))
|
||||
.contentType("application/x-www-form-urlencoded").body(body).post(endpoint);
|
||||
}
|
||||
|
||||
private static String encode(Map<String, String> parameters) {
|
||||
return parameters.entrySet().stream().map(entry -> URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8)
|
||||
+ "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)).collect(Collectors.joining("&"));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsProtocolClaimFilter;
|
||||
import io.github.hectorvent.floci.core.common.ProtocolClaim;
|
||||
import io.github.hectorvent.floci.core.common.WireProtocol;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
@@ -8,6 +11,7 @@ import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvFileSource;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
@@ -31,6 +35,32 @@ class IamActionRegistryTest {
|
||||
|
||||
private final IamActionRegistry registry = new IamActionRegistry();
|
||||
|
||||
@Test
|
||||
void cloudWatchGetUsesQueryActionAndOperationPrecedence() {
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.add("Action", "GetMetricStatistics");
|
||||
query.add("Operation", "ListMetrics");
|
||||
query.add("Version", "2010-08-01");
|
||||
ContainerRequestContext ctx = mockCtx("GET", "/", query, null, "");
|
||||
when(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY))
|
||||
.thenReturn(new ProtocolClaim(WireProtocol.AWS_QUERY, null, "GetMetricStatistics", null));
|
||||
assertEquals("monitoring:GetMetricStatistics", registry.resolve("monitoring", ctx));
|
||||
assertEquals("GetMetricStatistics", registry.queryAction(ctx));
|
||||
assertEquals("2010-08-01", registry.queryVersion(ctx));
|
||||
query.remove("Action");
|
||||
assertEquals("monitoring:ListMetrics", registry.resolve("monitoring", ctx));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRequiresTheQueryClaimRatherThanQueryParametersAlone() {
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.add("Action", "ListMetrics");
|
||||
ContainerRequestContext ctx = mockCtx("GET", "/", query, null, "");
|
||||
assertEquals(false, IamActionRegistry.isQueryRequest(ctx));
|
||||
when(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY)).thenReturn(new ProtocolClaim(WireProtocol.REST, null, null, null));
|
||||
assertEquals(false, IamActionRegistry.isQueryRequest(ctx));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesActionFromFormEncodedBody() {
|
||||
// AWS SDKs send Query-protocol calls as POST with
|
||||
|
||||
@@ -39,36 +39,43 @@ public final class AwsRequestSigner implements Filter {
|
||||
private final String secretKey;
|
||||
private final String sessionToken;
|
||||
private final String service;
|
||||
private final String region;
|
||||
private final Instant signedAt;
|
||||
private final boolean signContentType;
|
||||
|
||||
private AwsRequestSigner(String accessKeyId, String secretKey, String sessionToken, String service,
|
||||
Instant signedAt, boolean signContentType) {
|
||||
Instant signedAt, boolean signContentType, String region) {
|
||||
this.accessKeyId = accessKeyId;
|
||||
this.secretKey = secretKey;
|
||||
this.sessionToken = sessionToken;
|
||||
this.service = service;
|
||||
this.region = region;
|
||||
this.signedAt = signedAt;
|
||||
this.signContentType = signContentType;
|
||||
}
|
||||
|
||||
public static AwsRequestSigner signedAs(String accessKeyId, String secretKey, String service) {
|
||||
return new AwsRequestSigner(accessKeyId, secretKey, null, service, null, false);
|
||||
return new AwsRequestSigner(accessKeyId, secretKey, null, service, null, false, "us-east-1");
|
||||
}
|
||||
|
||||
/** Signs as of a fixed instant instead of now; used to trip the clock-skew window. */
|
||||
public AwsRequestSigner signedAt(Instant instant) {
|
||||
return new AwsRequestSigner(accessKeyId, secretKey, sessionToken, service, instant, signContentType);
|
||||
return new AwsRequestSigner(accessKeyId, secretKey, sessionToken, service, instant, signContentType, region);
|
||||
}
|
||||
|
||||
/** Signs with the same key but a different secret, as a client with a stale secret would. */
|
||||
public AwsRequestSigner withSecret(String otherSecret) {
|
||||
return new AwsRequestSigner(accessKeyId, otherSecret, sessionToken, service, signedAt, signContentType);
|
||||
return new AwsRequestSigner(accessKeyId, otherSecret, sessionToken, service, signedAt, signContentType, region);
|
||||
}
|
||||
|
||||
/** Also signs {@code content-type}, as the Java SDK and botocore do; for binary bodies only. */
|
||||
public AwsRequestSigner signingContentType() {
|
||||
return new AwsRequestSigner(accessKeyId, secretKey, sessionToken, service, signedAt, true);
|
||||
return new AwsRequestSigner(accessKeyId, secretKey, sessionToken, service, signedAt, true, region);
|
||||
}
|
||||
|
||||
public AwsRequestSigner inRegion(String signingRegion) {
|
||||
return new AwsRequestSigner(accessKeyId, secretKey, sessionToken, service, signedAt, signContentType,
|
||||
signingRegion);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -126,10 +133,10 @@ public final class AwsRequestSigner implements Filter {
|
||||
+ canonicalHeaders + "\n"
|
||||
+ signedHeaders + "\n"
|
||||
+ Digests.sha256Hex(body);
|
||||
String credentialScope = scopeDate + "/us-east-1/" + service + "/aws4_request";
|
||||
String credentialScope = scopeDate + "/" + region + "/" + service + "/aws4_request";
|
||||
String stringToSign = ALGORITHM + "\n" + amzDate + "\n" + credentialScope + "\n"
|
||||
+ Digests.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] signingKey = SigV4RequestValidator.deriveSigningKey(secretKey, scopeDate, "us-east-1", service);
|
||||
byte[] signingKey = SigV4RequestValidator.deriveSigningKey(secretKey, scopeDate, region, service);
|
||||
String signature = SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(signingKey, stringToSign));
|
||||
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
@@ -145,7 +152,7 @@ public final class AwsRequestSigner implements Filter {
|
||||
/** Presigns a body-bearing request with caller-supplied query fields, including a session token. */
|
||||
public URI presignedUri(String method, URI uri, Map<String, String> extraQuery, byte[] body) throws Exception {
|
||||
String date = AMZ_DATE.format(signedAt != null ? signedAt : Instant.now());
|
||||
String scope = date.substring(0, 8) + "/us-east-1/" + service + "/aws4_request";
|
||||
String scope = date.substring(0, 8) + "/" + region + "/" + service + "/aws4_request";
|
||||
TreeMap<String, String> query = new TreeMap<>(extraQuery);
|
||||
query.putAll(Map.of("X-Amz-Algorithm", ALGORITHM, "X-Amz-Credential", accessKeyId + "/" + scope,
|
||||
"X-Amz-Date", date, "X-Amz-Expires", "60", "X-Amz-SignedHeaders", "host"));
|
||||
@@ -156,7 +163,7 @@ public final class AwsRequestSigner implements Filter {
|
||||
+ "\nhost:" + uri.getAuthority() + "\n\nhost\n" + Digests.sha256Hex(body);
|
||||
String toSign = ALGORITHM + "\n" + date + "\n" + scope + "\n" + Digests.sha256Hex(canonical);
|
||||
String signature = SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(
|
||||
SigV4RequestValidator.deriveSigningKey(secretKey, date.substring(0, 8), "us-east-1", service), toSign));
|
||||
SigV4RequestValidator.deriveSigningKey(secretKey, date.substring(0, 8), region, service), toSign));
|
||||
return URI.create(uri + "?" + encoded + "&X-Amz-Signature=" + signature);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user