Light, fluffy, and always free - The AWS Local Emulator alternative
fix(auth): explain signature date and service mismatches (#5591)
David Phillipsd5c6a36ac981
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsPresignedIdentityTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsPresignedIdentityTest.javaindex a63d127fe3..87e879ea42 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsPresignedIdentityTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsPresignedIdentityTest.java@@ -9,6 +9,7 @@ import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;import software.amazon.awssdk.auth.signer.Aws4Signer;import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams;+import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;import software.amazon.awssdk.http.SdkHttpFullRequest;import software.amazon.awssdk.http.SdkHttpMethod;import software.amazon.awssdk.services.iam.IamClient;@@ -26,8 +27,12 @@ import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;+import java.time.Clock;import java.time.Duration;import java.time.Instant;+import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;+import java.time.temporal.ChronoUnit;import static org.assertj.core.api.Assertions.assertThat;@@ -95,12 +100,7 @@ class StsPresignedIdentityTest {private static Document presignedIdentity(AwsCredentials credentials, HttpClient.Version version) throws Exception {byte[] body = "Action=GetCallerIdentity&Version=2011-06-15".getBytes(StandardCharsets.UTF_8);- SdkHttpFullRequest signed = Aws4Signer.create().presign(SdkHttpFullRequest.builder()- .uri(TestFixtures.endpoint()).method(SdkHttpMethod.POST)- .putHeader("Content-Type", "application/x-www-form-urlencoded")- .contentStreamProvider(() -> new ByteArrayInputStream(body)).build(),- Aws4PresignerParams.builder().awsCredentials(credentials).signingRegion(TestFixtures.region())- .signingName("sts").expirationTime(Instant.now().plusSeconds(60)).build());+ SdkHttpFullRequest signed = presign(credentials, body, "sts", Instant.now());HttpResponse<byte[]> response = send(signed, signed.getUri(), body, version);assertThat(response.statusCode()).as(new String(response.body(), StandardCharsets.UTF_8)).isEqualTo(200);boolean signaturesEnabled = Boolean.parseBoolean(System.getenv("FLOCI_AUTH_VALIDATE_SIGNATURES"));@@ -108,6 +108,27 @@ class StsPresignedIdentityTest {URI forged = URI.create(signed.getUri().toString().replaceAll("X-Amz-Signature=[^&]*","X-Amz-Signature=" + "0".repeat(64)));assertSignatureRefused(send(signed, forged, body, version));+ Instant signedAt = Instant.now().minusSeconds(120).truncatedTo(ChronoUnit.SECONDS);+ SdkHttpFullRequest expired = presign(credentials, body, "sts", signedAt);+ Instant before = Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.SECONDS);+ HttpResponse<byte[]> expiryResponse = send(expired, expired.getUri(), body, version);+ Instant after = Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.SECONDS);+ assertSignatureRefused(expiryResponse);+ DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);+ String prefix = "Signature expired: " + format.format(signedAt) + " is now earlier than ";+ String expiryMessage = parse(expiryResponse.body()).getElementsByTagNameNS("*", "Message")+ .item(0).getTextContent();+ assertThat(expiryMessage).startsWith(prefix);+ Instant cutoff = Instant.from(format.parse(expiryMessage.substring(prefix.length())));+ assertThat(cutoff).isBetween(before, after);+ assertClockRefusal(credentials, body, version, true, 1200);+ assertClockRefusal(credentials, body, version, false, 1200);+ assertClockRefusal(credentials, body, version, false, -1200);+ SdkHttpFullRequest wrongService = presign(credentials, body, "iam", Instant.now());+ HttpResponse<byte[]> scopeResponse = send(wrongService, wrongService.getUri(), body, version);+ assertSignatureRefused(scopeResponse);+ assertThat(parse(scopeResponse.body()).getElementsByTagNameNS("*", "Message").item(0).getTextContent())+ .isEqualTo("Credential should be scoped to correct service: 'sts'");assertSignatureRefused(send(signed, signed.getUri(),(new String(body, StandardCharsets.UTF_8) + "&Extra=changed").getBytes(StandardCharsets.UTF_8), version));}@@ -120,6 +141,44 @@ class StsPresignedIdentityTest {assertThat(new String(invalid.body(), StandardCharsets.UTF_8)).contains("InvalidClientTokenId");}}+ return parse(response.body());+ }++ private static void assertClockRefusal(AwsCredentials credentials, byte[] body, HttpClient.Version version,+ boolean query, long offset) throws Exception {+ Instant signedAt = Instant.now().plusSeconds(offset).truncatedTo(ChronoUnit.SECONDS);+ SdkHttpFullRequest signed = query ? presign(credentials, body, "sts", signedAt)+ : Aws4Signer.create().sign(SdkHttpFullRequest.builder()+ .uri(TestFixtures.endpoint()).method(SdkHttpMethod.POST)+ .putHeader("Content-Type", "application/x-www-form-urlencoded")+ .contentStreamProvider(() -> new ByteArrayInputStream(body)).build(),+ Aws4SignerParams.builder().awsCredentials(credentials).signingRegion(TestFixtures.region())+ .signingName("sts").signingClockOverride(Clock.fixed(signedAt, ZoneOffset.UTC)).build());+ long cutoffOffset = offset > 0 ? 900 : -900;+ Instant before = Instant.now().plusSeconds(cutoffOffset).truncatedTo(ChronoUnit.SECONDS);+ HttpResponse<byte[]> response = send(signed, signed.getUri(), body, version);+ Instant after = Instant.now().plusSeconds(cutoffOffset).truncatedTo(ChronoUnit.SECONDS);+ assertSignatureRefused(response);+ DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);+ String prefix = offset > 0+ ? "Signature not yet current: " + format.format(signedAt) + " is still later than "+ : "Signature expired: " + format.format(signedAt) + " is now earlier than ";+ String message = parse(response.body()).getElementsByTagNameNS("*", "Message").item(0).getTextContent();+ assertThat(message).startsWith(prefix);+ assertThat(Instant.from(format.parse(message.substring(prefix.length())))).isBetween(before, after);+ }++ private static SdkHttpFullRequest presign(AwsCredentials credentials, byte[] body, String service, Instant signedAt) {+ return Aws4Signer.create().presign(SdkHttpFullRequest.builder()+ .uri(TestFixtures.endpoint()).method(SdkHttpMethod.POST)+ .putHeader("Content-Type", "application/x-www-form-urlencoded")+ .contentStreamProvider(() -> new ByteArrayInputStream(body)).build(),+ Aws4PresignerParams.builder().awsCredentials(credentials).signingRegion(TestFixtures.region())+ .signingName(service).signingClockOverride(Clock.fixed(signedAt, ZoneOffset.UTC))+ .expirationTime(signedAt.plusSeconds(60)).build());+ }++ private static Document parse(byte[] body) throws Exception {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();factory.setNamespaceAware(true);factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);@@ -128,7 +187,7 @@ class StsPresignedIdentityTest {factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);factory.setXIncludeAware(false);factory.setExpandEntityReferences(false);- return factory.newDocumentBuilder().parse(new ByteArrayInputStream(response.body()));+ return factory.newDocumentBuilder().parse(new ByteArrayInputStream(body));}private static void assertSignatureRefused(HttpResponse<byte[]> response) {diff --git a/docs/configuration/multi-account.md b/docs/configuration/multi-account.mdindex bbda222d3c..8ec7c76319 100644--- a/docs/configuration/multi-account.md+++ b/docs/configuration/multi-account.md@@ -174,6 +174,17 @@ By default Floci does not verify SigV4 signatures. Only the access key ID matter- **S3** verifies every placement (`Authorization` header, presigned URL and presigned POST); see [S3 Signature Verification](../services/s3.md#signature-verification).- **Every other service** verifies the `Authorization` header or a SigV4 presigned query string. A nonblank Authorization header takes precedence. The canonical request is rebuilt from the request as it arrived, with the path encoded the way AWS signers encode it outside S3 and the body's own SHA-256 as the payload hash. A refusal comes back in the protocol the request used, with the Query and REST-XML name first (Route 53, CloudFront and S3 Control answer in XML) and the JSON, CBOR and REST-JSON name second: `SignatureDoesNotMatch` or `InvalidSignatureException` for a signature that does not verify or is more than 15 minutes from server time, `InvalidClientTokenId` or `UnrecognizedClientException` for an access key Floci does not know, and `IncompleteSignature` or `IncompleteSignatureException` for an `Authorization` header missing a part. Presigned requests use their `X-Amz-Expires` lifetime (1–604800 seconds) and may be at most 15 minutes in the future; credential scope date or service mismatches are refused. A signed `x-amz-content-sha256` payload marker is honored; otherwise the actual body is hashed. SigV4a is not verified here. API Gateway `execute-api` requests and AppSync GraphQL keep their own verifiers; API Gateway documents its [IAM authorization](../services/api-gateway.md#iam-authorization).+An expired presigned query reports `Signature expired: <signed-date> is now earlier than <cutoff>`.+The cutoff is the server time minus `X-Amz-Expires`, so the message describes the URL's lifetime.+An expired header signature uses the same wording with a cutoff 15 minutes before server time.+Query and header signatures more than 15 minutes ahead report+`Signature not yet current: <signed-date> is still later than <cutoff>`, with a cutoff 15 minutes+after server time.+When the receiving service has one registered signing scope, a mismatch reports+`Credential should be scoped to correct service: '<service>'`. Services with multiple accepted+scopes retain the generic mismatch message because their aliases do not identify a canonical+signing name.+To verify signatures:```bashdiff --git a/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.javaindex d21cad9d42..a1b5513d0f 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.java@@ -88,7 +88,7 @@ import java.util.function.UnaryOperator;* are AWS's: {@code IncompleteSignature} for a header that cannot be checked,* {@code InvalidClientTokenId} / {@code UnrecognizedClientException} for an access key Floci does* not know, and {@code SignatureDoesNotMatch} / {@code InvalidSignatureException} for a signature- * that does not verify or falls outside the fifteen-minute clock-skew window.+ * that does not verify, exceeds its query expiry or falls outside the header clock-skew window.** <p>Nothing here runs with the flag off: the filter returns before reading a single header.*/@@ -200,7 +200,7 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {}}String token = ctx.getHeaderString("X-Amz-Security-Token");- boolean scopeMatches = true;+ ServiceDescriptor queryService = null;if (presigned) {try {if (token == null) {@@ -209,7 +209,7 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {token = query.getFirst("X-Amz-Security-Token");}}- scopeMatches = queryScopeMatchesResource(ctx, resource, scope.service());+ queryService = queryService(ctx, resource);} catch (IllegalArgumentException error) {incompleteSignature(ctx, resource, "Cannot read presigned request form parameters.");return;@@ -225,12 +225,19 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {String amzDate = AMZ_DATE.format(requestTime);Instant now = Instant.now();- if (presigned ? requestTime.isAfter(now.plus(MAX_CLOCK_SKEW))- || !now.isBefore(requestTime.plusSeconds(expires))- : Duration.between(requestTime, now).abs().compareTo(MAX_CLOCK_SKEW) > 0) {- signatureDoesNotMatch(ctx, resource, "Signature expired: " + amzDate + " is outside the "- + MAX_CLOCK_SKEW.toMinutes() + " minute window around the server time "- + AMZ_DATE.format(now) + ".");+ if (presigned && !now.isBefore(requestTime.plusSeconds(expires))) {+ signatureDoesNotMatch(ctx, resource, "Signature expired: " + amzDate + " is now earlier than "+ + AMZ_DATE.format(now.minusSeconds(expires)));+ return;+ }+ if (requestTime.isAfter(now.plus(MAX_CLOCK_SKEW))) {+ signatureDoesNotMatch(ctx, resource, "Signature not yet current: " + amzDate + " is still later than "+ + AMZ_DATE.format(now.plus(MAX_CLOCK_SKEW)));+ return;+ }+ if (!presigned && requestTime.isBefore(now.minus(MAX_CLOCK_SKEW))) {+ signatureDoesNotMatch(ctx, resource, "Signature expired: " + amzDate + " is now earlier than "+ + AMZ_DATE.format(now.minus(MAX_CLOCK_SKEW)));return;}if (!amzDate.startsWith(scope.date())) {@@ -240,8 +247,13 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {return;}- if (!scopeMatches) {- signatureDoesNotMatch(ctx, resource, "Credential should be scoped to the service receiving the request.");+ if (queryService != null && !queryService.credentialScopes().contains(scope.service())) {+ // Multiple accepted scopes can include endpoint aliases, not canonical signing names.+ String expectedService = queryService.credentialScopes().size() == 1+ ? queryService.credentialScopes().iterator().next() : null;+ signatureDoesNotMatch(ctx, resource, expectedService == null+ ? "Credential should be scoped to the service receiving the request."+ : "Credential should be scoped to correct service: '" + expectedService + "'");return;}@@ -287,7 +299,7 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {amzDate, scope, secretKey, signature);}- private boolean queryScopeMatchesResource(ContainerRequestContext ctx, Class<?> resource, String service) {+ private ServiceDescriptor queryService(ContainerRequestContext ctx, Class<?> resource) {ServiceDescriptor descriptor;if (resource == AwsQueryController.class) {String action = AwsQueryServiceResolver.action(RequestBodyReader.formField(ctx, "Action"),@@ -301,7 +313,7 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {} else {descriptor = resource == null ? null : catalog.byResourceClass(resource).orElse(null);}- return descriptor == null || descriptor.credentialScopes().contains(service);+ return descriptor;}private static Instant parseAmzDate(String value) {diff --git a/src/test/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureIntegrationTest.javaindex 0dd44df8ea..def4d81c89 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureIntegrationTest.java@@ -8,11 +8,15 @@ import io.quarkus.test.junit.QuarkusTest;import io.quarkus.test.junit.TestProfile;import io.restassured.RestAssured;import io.restassured.path.xml.XmlPath;+import io.restassured.response.Response;+import io.restassured.specification.RequestSpecification;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.MethodOrderer;import org.junit.jupiter.api.Order;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestMethodOrder;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;import java.net.URI;import java.net.http.HttpClient;@@ -21,6 +25,9 @@ import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.time.Instant;+import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;+import java.time.temporal.ChronoUnit;import java.util.Map;import static io.restassured.RestAssured.given;@@ -256,21 +263,46 @@ class SigV4HeaderSignatureIntegrationTest {.body("__type", equalTo("InvalidSignatureException"));}- @Test+ @ParameterizedTest+ @CsvSource({"sts, -1200", "sts, 1200", "sts, -840", "sts, 840",+ "sqs, -1200", "sqs, 1200", "sqs, -840", "sqs, 840",+ "lambda, -1200", "lambda, 1200", "lambda, -840", "lambda, 840"})@Order(10)- void signatureOutsideTheClockSkewWindowIsRefused() {- given()- .filter(AwsRequestSigner.signedAs("test", "test", "sqs")- .signedAt(Instant.now().minus(Duration.ofMinutes(20))))- .contentType(JSON_1_0)- .header("X-Amz-Target", "AmazonSQS.ListQueues")- .body("{}")- .when()- .post("/")- .then()- .statusCode(403)- .body("__type", equalTo("InvalidSignatureException"))- .body("message", containsString("Signature expired"));+ void signatureClockSkewReportsTheDirectionAndCutoff(String service, long offset) {+ Instant signedAt = Instant.now().plusSeconds(offset).truncatedTo(ChronoUnit.SECONDS);+ boolean query = "sts".equals(service);+ boolean rest = "lambda".equals(service);+ RequestSpecification request = given()+ .filter(AwsRequestSigner.signedAs("test", "test", service).signedAt(signedAt));+ if (query) {+ request.contentType(FORM).body("Action=GetCallerIdentity&Version=2011-06-15");+ } else if (!rest) {+ request.contentType(JSON_1_0).header("X-Amz-Target", "AmazonSQS.ListQueues").body("{}");+ }+ long cutoffOffset = offset > 0 ? 900 : -900;+ Instant before = Instant.now().plusSeconds(cutoffOffset).truncatedTo(ChronoUnit.SECONDS);+ Response response = request.request(rest ? "GET" : "POST", rest ? "/2015-03-31/functions" : "/");+ Instant after = Instant.now().plusSeconds(cutoffOffset).truncatedTo(ChronoUnit.SECONDS);+ if (Math.abs(offset) < 900) {+ response.then().statusCode(200);+ return;+ }+ response.then().statusCode(403);+ String message;+ if (query) {+ response.then().body("ErrorResponse.Error.Code", equalTo("SignatureDoesNotMatch"));+ message = response.xmlPath().getString("ErrorResponse.Error.Message");+ } else {+ response.then().header("X-Amzn-Errortype", equalTo("InvalidSignatureException"));+ message = response.jsonPath().getString("message");+ }+ DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);+ String prefix = offset > 0+ ? "Signature not yet current: " + format.format(signedAt) + " is still later than "+ : "Signature expired: " + format.format(signedAt) + " is now earlier than ";+ assertTrue(message.startsWith(prefix), message);+ Instant cutoff = Instant.from(format.parse(message.substring(prefix.length())));+ assertTrue(!cutoff.isBefore(before) && !cutoff.isAfter(after), message);}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsPresignedSignatureIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsPresignedSignatureIntegrationTest.javaindex 8cccecb1a9..bdfe8832d6 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/StsPresignedSignatureIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsPresignedSignatureIntegrationTest.java@@ -20,6 +20,7 @@ import java.nio.charset.StandardCharsets;import java.time.Instant;import java.time.ZoneOffset;import java.time.format.DateTimeFormatter;+import java.time.temporal.ChronoUnit;import java.util.Map;import java.util.Set;import java.util.TreeMap;@@ -28,7 +29,9 @@ import java.util.stream.Collectors;import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;@QuarkusTest@TestProfile(StsPresignedSignatureIntegrationTest.SignaturesAndEnforcement.class)@@ -288,6 +291,74 @@ class StsPresignedSignatureIntegrationTest {}}+ @ParameterizedTest+ @CsvSource({"sts, expired", "sts, scope", "iam, expired", "iam, scope",+ "sqs, expired", "sqs, scope", "lambda, expired", "lambda, scope",+ "sts, future", "iam, future", "sqs, future", "lambda, future"})+ void queryRefusalExplainsExpiryOrExpectedService(String service, String failure) throws Exception {+ boolean rest = "lambda".equals(service);+ boolean queryProtocol = "sts".equals(service) || "iam".equals(service);+ String method = rest ? "GET" : "POST";+ String path = rest ? "/2015-03-31/functions" : "/";+ String body = "sts".equals(service) ? "Action=GetCallerIdentity&Version=2011-06-15"+ : "iam".equals(service) ? "Action=ListUsers&Version=2010-05-08" : rest ? "" : "{}";+ boolean expired = "expired".equals(failure);+ boolean future = "future".equals(failure);+ long cutoffOffset = future ? 900 : -60;+ Instant signedAt = Instant.now().plusSeconds(future ? 1200 : expired ? -120 : 0)+ .truncatedTo(ChronoUnit.SECONDS);+ URI uri = presignRequest("test", "test", method, path, expired || future ? service : "kms", body,+ new TreeMap<>(), null, signedAt);+ RequestSpecification request = given().urlEncodingEnabled(false);+ if (queryProtocol) {+ request.contentType("application/x-www-form-urlencoded");+ } else if (!rest) {+ request.contentType("application/x-amz-json-1.0").header("X-Amz-Target", "AmazonSQS.ListQueues");+ }+ if (queryProtocol) {+ request.body(body);+ } else if (!rest) {+ request.body(body.getBytes(StandardCharsets.UTF_8));+ }+ Instant before = Instant.now().plusSeconds(cutoffOffset).truncatedTo(ChronoUnit.SECONDS);+ Response response = request.request(method, uri);+ Instant after = Instant.now().plusSeconds(cutoffOffset).truncatedTo(ChronoUnit.SECONDS);+ response.then().statusCode(403);+ String message;+ if (queryProtocol) {+ response.then().body("ErrorResponse.Error.Code", equalTo("SignatureDoesNotMatch"));+ message = response.xmlPath().getString("ErrorResponse.Error.Message");+ } else {+ response.then().header("X-Amzn-Errortype", equalTo("InvalidSignatureException"));+ message = response.jsonPath().getString("message");+ }+ if (expired || future) {+ DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);+ String prefix = future+ ? "Signature not yet current: " + format.format(signedAt) + " is still later than "+ : "Signature expired: " + format.format(signedAt) + " is now earlier than ";+ assertTrue(message.startsWith(prefix), message);+ Instant cutoff = Instant.from(format.parse(message.substring(prefix.length())));+ assertTrue(!cutoff.isBefore(before) && !cutoff.isAfter(after), message);+ } else {+ assertEquals("Credential should be scoped to correct service: '"+ + service + "'", message);+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"airflow", "mwaa", "kms"})+ void multipleAcceptedScopesDoNotInventCanonicalSigningName(String service) throws Exception {+ URI uri = presignRequest("test", "test", "GET", "/environments", service, "", new TreeMap<>(), null);+ Response response = given().urlEncodingEnabled(false).get(uri);+ if ("kms".equals(service)) {+ response.then().statusCode(403).header("X-Amzn-Errortype", equalTo("InvalidSignatureException"))+ .body("message", equalTo("Credential should be scoped to the service receiving the request."));+ } else {+ response.then().statusCode(200);+ }+ }+@ParameterizedTest@ValueSource(strings = {"bad%ZZ=x&Action=ListUsers", "Action=ListUsers&X-Amz-Security-Token=%"})void malformedFormCannotEscapeAsServerError(String body) throws Exception {@@ -307,8 +378,14 @@ class StsPresignedSignatureIntegrationTest {private static URI presignRequest(String key, String secret, String method, String path, String service,String body, TreeMap<String, String> query, Boolean signedMarker) throws Exception {+ return presignRequest(key, secret, method, path, service, body, query, signedMarker, Instant.now());+ }++ private static URI presignRequest(String key, String secret, String method, String path, String service,+ String body, TreeMap<String, String> query, Boolean signedMarker,+ Instant signedAt) throws Exception {URI endpoint = URI.create("http://localhost:" + RestAssured.port + path);- String date = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC).format(Instant.now());+ String date = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC).format(signedAt);String scope = date.substring(0, 8) + "/us-east-1/" + service + "/aws4_request";query.putAll(Map.of("X-Amz-Algorithm", "AWS4-HMAC-SHA256", "X-Amz-Credential", key + "/" + scope,"X-Amz-Date", date, "X-Amz-Expires", "60", "X-Amz-SignedHeaders", Boolean.TRUE.equals(signedMarker)