mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(core): verify SigV4 header signatures for every service under validate-signatures (#5268)
* fix(core): verify SigV4 header signatures for every service under validate-signatures FLOCI_AUTH_VALIDATE_SIGNATURES verified signatures for S3 only, so SQS, KMS, IAM, Scheduler and every other service accepted a request signed with the wrong secret. SigV4HeaderSignatureFilter verifies the Authorization header of every request outside S3 and execute-api when the flag is on, rebuilding the canonical request from the request as it arrived and answering in the protocol the request used. Unsigned requests are left alone, and the default configuration is unchanged. The filter runs after matching so it can hash the body. The SQS queue-URL router now records the bytes it appends to a Query body, and the CBOR content type is read from the header that preserves it, so neither rewrite breaks a valid signature. With the flag on, an unknown or synthetic access key is now refused by every service, as S3 already refused it. Closes #5195 * fix(core): skip signature checks by matched resource, strip the spoofable content-type header The filter skipped any request whose credential scope named s3 or execute-api, so a caller could sign an SQS or KMS call under either and pass with the wrong secret, and S3 Control was never checked. It now steps aside only for the resources another verifier owns: S3Controller and the API Gateway execute controllers. AwsCborContentTypeFilter removes any client-sent X-Floci-Original-Content-Type, so a signed Content-Type cannot be swapped behind a forged copy. REST-XML services (Route 53, CloudFront, S3 Control) get XML errors. Header and scope parsing reuse SigV4AuthorizationHeader and CredentialScope, and the canonical request moves into SigV4Canonicalization, shared with ExecuteApiSigV4Authorizer. * fix(core): leave AppSync GraphQL signatures to AppSync's own check AppSync's GraphQL endpoint verifies IAM signatures itself and answers a failure with the UnauthorizedException envelope AppSync clients parse. With validate-signatures on, the header filter reached it first and answered with a JSON InvalidSignatureException. AppSyncExecutionController joins the resources the filter steps aside for.
This commit is contained in:
1 parent
91c15be74a
commit
9f224d9de6
16 files changed
+1393
-178
No files matched your search
+121
@@ -0,0 +1,121 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.auth.CredentialScope;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4Canonicalization;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Checks the canonical request against signatures an independent signer produced, so the verifier
|
||||
* is not only ever compared with a signer written alongside it. Every expected signature below was
|
||||
* computed by botocore 1.43.108 ({@code SigV4Auth.add_auth}) for the same method, URL, headers and
|
||||
* body, with the clock pinned to 2026-01-01T00:00:00Z and the AWS documentation's example key pair.
|
||||
*/
|
||||
class SigV4HeaderSignatureFilterTest {
|
||||
|
||||
private static final String SECRET = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
|
||||
private static final String AMZ_DATE = "20260101T000000Z";
|
||||
private static final String SCOPE_DATE = "20260101";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String HOST = "localhost:4566";
|
||||
|
||||
@Test
|
||||
void queryRequestVerifies() throws Exception {
|
||||
assertTrue(matches("POST", "/", null,
|
||||
"content-type;host;x-amz-date",
|
||||
Map.of("content-type", "application/x-www-form-urlencoded; charset=utf-8"),
|
||||
"Action=GetCallerIdentity&Version=2011-06-15", SECRET, "sts",
|
||||
"5df4b2dd1edf5b1846612118237772601820753b9d87d8214afbad7e2d70d522"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonRequestVerifies() throws Exception {
|
||||
assertTrue(matches("POST", "/", null,
|
||||
"content-type;host;x-amz-date;x-amz-target",
|
||||
Map.of("content-type", "application/x-amz-json-1.0", "x-amz-target", "AmazonSQS.ListQueues"),
|
||||
"{}", SECRET, "sqs",
|
||||
"969501491602b1e686863668c36b1049fb733134484fe49487e1f6a8e0b2dc27"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restPathWithEscapesIsDoubleEncoded() throws Exception {
|
||||
assertTrue(matches("GET",
|
||||
"/2015-03-31/functions/arn%3Aaws%3Alambda%3Aus-east-1%3A000000000000%3Afunction%3Amy-fn/configuration",
|
||||
"Qualifier=v1", "host;x-amz-date", Map.of(), "", SECRET, "lambda",
|
||||
"52dde5d043128b9bef236aeea1158ab5ee3712d75e436b01fff35b3ed0dbc962"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restQueryIsCanonicalized() throws Exception {
|
||||
assertTrue(matches("GET", "/schedule-groups", "NamePrefix=a%20b%2Bc&MaxResults=5",
|
||||
"host;x-amz-date", Map.of(), "", SECRET, "scheduler",
|
||||
"6882cb650943c3c5770a1b6fe60091fa72f5a628948df4c7aae4fa4da5772da8"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sessionTokenHeaderIsPartOfTheSignature() throws Exception {
|
||||
assertTrue(matches("POST", "/", null,
|
||||
"content-type;host;x-amz-date;x-amz-security-token;x-amz-target",
|
||||
Map.of("content-type", "application/x-amz-json-1.1",
|
||||
"x-amz-target", "TrentService.ListKeys",
|
||||
"x-amz-security-token", "session-token-value"),
|
||||
"{\"Limit\":10}", SECRET, "kms",
|
||||
"5feaffc90be139e5f4288e442918fb838d1ef12f334d84ab292491f27535e800"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrongSecretDoesNotVerify() throws Exception {
|
||||
assertFalse(matches("POST", "/", null,
|
||||
"content-type;host;x-amz-date;x-amz-target",
|
||||
Map.of("content-type", "application/x-amz-json-1.0", "x-amz-target", "AmazonSQS.ListQueues"),
|
||||
"{}", "not-the-secret", "sqs",
|
||||
"969501491602b1e686863668c36b1049fb733134484fe49487e1f6a8e0b2dc27"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacedBodyDoesNotVerify() throws Exception {
|
||||
assertFalse(matches("POST", "/", null,
|
||||
"content-type;host;x-amz-date",
|
||||
Map.of("content-type", "application/x-www-form-urlencoded; charset=utf-8"),
|
||||
"Action=DeleteUser&UserName=admin", SECRET, "sts",
|
||||
"5df4b2dd1edf5b1846612118237772601820753b9d87d8214afbad7e2d70d522"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void signatureForAnotherServiceDoesNotVerify() throws Exception {
|
||||
assertFalse(matches("POST", "/", null,
|
||||
"content-type;host;x-amz-date;x-amz-target",
|
||||
Map.of("content-type", "application/x-amz-json-1.0", "x-amz-target", "AmazonSQS.ListQueues"),
|
||||
"{}", SECRET, "kms",
|
||||
"969501491602b1e686863668c36b1049fb733134484fe49487e1f6a8e0b2dc27"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void canonicalUriKeepsThePlainPathWhenNothingIsEscaped() {
|
||||
assertEquals(List.of("/"), SigV4Canonicalization.canonicalUriCandidates(""));
|
||||
assertEquals(List.of("/schedule-groups/default"),
|
||||
SigV4Canonicalization.canonicalUriCandidates("/schedule-groups/default"));
|
||||
assertEquals(List.of("/functions/a%3Ab", "/functions/a%253Ab"),
|
||||
SigV4Canonicalization.canonicalUriCandidates("/functions/a%3Ab"));
|
||||
}
|
||||
|
||||
private static boolean matches(String method, String rawPath, String rawQuery, String signedHeaders,
|
||||
Map<String, String> headers, String body, String secret, String service,
|
||||
String signature) throws Exception {
|
||||
return SigV4HeaderSignatureFilter.signatureMatches(method, rawPath, rawQuery, signedHeaders,
|
||||
name -> switch (name) {
|
||||
case "host" -> HOST;
|
||||
case "x-amz-date" -> AMZ_DATE;
|
||||
default -> headers.get(name);
|
||||
},
|
||||
body.getBytes(StandardCharsets.UTF_8), secret, AMZ_DATE,
|
||||
new CredentialScope("AKIDEXAMPLE", SCOPE_DATE, REGION, service), signature);
|
||||
}
|
||||
}
|
||||
+452
@@ -0,0 +1,452 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.github.hectorvent.floci.testing.ValidateSignaturesProfile;
|
||||
import io.github.hectorvent.floci.testutil.AppSyncRequestSigner;
|
||||
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
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 java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* {@code floci.auth.validate-signatures} authenticates every header-signed request, not only S3's:
|
||||
* a request signed with the wrong secret is refused in the error vocabulary of the protocol it
|
||||
* used, a request signed with the right one is served, and an unsigned request is left alone.
|
||||
* Shares {@link ValidateSignaturesProfile} with the S3 signature tests.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(ValidateSignaturesProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class SigV4HeaderSignatureIntegrationTest {
|
||||
|
||||
private static final String QUEUE = "validate-signatures-queue";
|
||||
private static final String JSON_1_0 = "application/x-amz-json-1.0";
|
||||
private static final String JSON_1_1 = "application/x-amz-json-1.1";
|
||||
private static final String FORM = "application/x-www-form-urlencoded";
|
||||
private static final String CBOR_1_1 = "application/x-amz-cbor-1.1";
|
||||
|
||||
private static String userAccessKeyId;
|
||||
private static String userSecretKey;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void jsonRequestWithTheRightSecretIsServed() {
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "test", "sqs"))
|
||||
.contentType(JSON_1_0)
|
||||
.header("X-Amz-Target", "AmazonSQS.CreateQueue")
|
||||
.body("{\"QueueName\":\"" + QUEUE + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("QueueUrl", containsString(QUEUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void jsonRequestWithTheWrongSecretIsRefused() {
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "not-the-secret", "sqs"))
|
||||
.contentType(JSON_1_0)
|
||||
.header("X-Amz-Target", "AmazonSQS.ListQueues")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body("__type", equalTo("InvalidSignatureException"));
|
||||
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "not-the-secret", "kms"))
|
||||
.contentType(JSON_1_1)
|
||||
.header("X-Amz-Target", "TrentService.ListKeys")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body("__type", equalTo("InvalidSignatureException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void queryRequestWithTheWrongSecretIsRefusedInXml() {
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "test", "iam"))
|
||||
.contentType(FORM)
|
||||
.body("Action=ListUsers&Version=2010-05-08")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "not-the-secret", "iam"))
|
||||
.contentType(FORM)
|
||||
.body("Action=ListUsers&Version=2010-05-08")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body("ErrorResponse.Error.Code", equalTo("SignatureDoesNotMatch"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void restJsonRequestWithTheWrongSecretIsRefusedThroughTheErrorTypeHeader() {
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "test", "scheduler"))
|
||||
.when()
|
||||
.get("/schedule-groups")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "not-the-secret", "scheduler"))
|
||||
.when()
|
||||
.get("/schedule-groups")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.header("X-Amzn-Errortype", equalTo("InvalidSignatureException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void pathWithEscapesVerifiesDoubleEncoded() {
|
||||
// A signature over the double-encoded ARN gets past authentication to Lambda's own 404.
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "test", "lambda"))
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get("/2015-03-31/functions/arn%3Aaws%3Alambda%3Aus-east-1%3A000000000000%3Afunction%3Amissing")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void queueUrlPathIsVerifiedBeforeItIsRewritten() {
|
||||
// An SDK v1 Query call posts to the queue URL; the router rewrites the path to / and
|
||||
// appends QueueUrl to the body, neither of which the client signed.
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "test", "sqs"))
|
||||
.contentType(FORM)
|
||||
.body("Action=GetQueueAttributes&AttributeName.1=All&Version=2012-11-05")
|
||||
.when()
|
||||
.post("/000000000000/" + QUEUE)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void cborContentTypeIsVerifiedAsTheClientSentIt() {
|
||||
// AwsCborContentTypeFilter rewrites application/x-amz-cbor-1.1 before matching; the client
|
||||
// signed the original. An empty CBOR map is the single byte 0xA0.
|
||||
byte[] emptyMap = {(byte) 0xA0};
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "test", "kinesis").signingContentType())
|
||||
.contentType(CBOR_1_1)
|
||||
.header("X-Amz-Target", "Kinesis_20131202.ListStreams")
|
||||
.body(emptyMap)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "not-the-secret", "kinesis").signingContentType())
|
||||
.contentType(CBOR_1_1)
|
||||
.header("X-Amz-Target", "Kinesis_20131202.ListStreams")
|
||||
.body(emptyMap)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.contentType(containsString("cbor"))
|
||||
.header("x-amzn-query-error", startsWith("InvalidSignatureException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void unknownAccessKeyIsRefused() {
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("AKIAUNKNOWNACCESSKEY", "some-secret", "sqs"))
|
||||
.contentType(JSON_1_0)
|
||||
.header("X-Amz-Target", "AmazonSQS.ListQueues")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body("__type", equalTo("UnrecognizedClientException"));
|
||||
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("AKIAUNKNOWNACCESSKEY", "some-secret", "sts"))
|
||||
.contentType(FORM)
|
||||
.body("Action=GetCallerIdentity&Version=2011-06-15")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidClientTokenId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void iamCreatedKeyVerifiesWithItsOwnSecretOnly() {
|
||||
AwsRequestSigner iam = AwsRequestSigner.signedAs("test", "test", "iam");
|
||||
given().filter(iam).contentType(FORM)
|
||||
.body("Action=CreateUser&UserName=validate-signatures-sqs-user&Version=2010-05-08")
|
||||
.when().post("/").then().statusCode(200);
|
||||
XmlPath key = given().filter(iam).contentType(FORM)
|
||||
.body("Action=CreateAccessKey&UserName=validate-signatures-sqs-user&Version=2010-05-08")
|
||||
.when().post("/").then().statusCode(200).extract().xmlPath();
|
||||
userAccessKeyId = key.getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
|
||||
userSecretKey = key.getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey");
|
||||
|
||||
AwsRequestSigner user = AwsRequestSigner.signedAs(userAccessKeyId, userSecretKey, "sqs");
|
||||
given()
|
||||
.filter(user)
|
||||
.contentType(JSON_1_0)
|
||||
.header("X-Amz-Target", "AmazonSQS.ListQueues")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.filter(user.withSecret("not-the-secret"))
|
||||
.contentType(JSON_1_0)
|
||||
.header("X-Amz-Target", "AmazonSQS.ListQueues")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body("__type", equalTo("InvalidSignatureException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@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"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void malformedAuthorizationHeaderIsIncomplete() {
|
||||
given()
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/sqs/aws4_request")
|
||||
.contentType(JSON_1_0)
|
||||
.header("X-Amz-Target", "AmazonSQS.ListQueues")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("IncompleteSignatureException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(12)
|
||||
void credentialScopeNamingAnotherVerifiersServiceIsStillVerified() {
|
||||
// Which verifier owns a request is decided by the resource it matched, not by the service
|
||||
// the caller wrote into its own credential scope.
|
||||
for (String scopeService : new String[]{"s3", "s3express", "execute-api"}) {
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "not-the-secret", scopeService))
|
||||
.contentType(JSON_1_0)
|
||||
.header("X-Amz-Target", "AmazonSQS.ListQueues")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body("__type", equalTo("InvalidSignatureException"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(13)
|
||||
void s3ControlIsVerifiedAndAnswersInXml() {
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "test", "s3"))
|
||||
.header("x-amz-account-id", "000000000000")
|
||||
.when()
|
||||
.get("/v20180820/accesspoint")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "not-the-secret", "s3"))
|
||||
.header("x-amz-account-id", "000000000000")
|
||||
.when()
|
||||
.get("/v20180820/accesspoint")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.contentType(containsString("xml"))
|
||||
.body("ErrorResponse.Error.Code", equalTo("SignatureDoesNotMatch"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(14)
|
||||
void restXmlServiceAnswersInXml() {
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "test", "route53"))
|
||||
.when()
|
||||
.get("/2013-04-01/hostedzone")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "not-the-secret", "route53"))
|
||||
.when()
|
||||
.get("/2013-04-01/hostedzone")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.contentType(containsString("xml"))
|
||||
.body("ErrorResponse.Error.Code", equalTo("SignatureDoesNotMatch"));
|
||||
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("AKIAUNKNOWNACCESSKEY", "some-secret", "route53"))
|
||||
.when()
|
||||
.get("/2013-04-01/hostedzone")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidClientTokenId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(15)
|
||||
void clientSuppliedOriginalContentTypeCannotStandInForTheSignedOne() throws Exception {
|
||||
// Signed over one Content-Type, sent with another plus Floci's internal header claiming the
|
||||
// signed value. A raw client keeps both headers exactly as written. The internal header is
|
||||
// stripped on the way in, so the swap is a mismatch rather than a verified request.
|
||||
URI uri = URI.create("http://localhost:" + RestAssured.port + "/");
|
||||
byte[] body = "{}".getBytes(StandardCharsets.UTF_8);
|
||||
Map<String, String> auth = AwsRequestSigner.signedAs("test", "test", "sqs").headersFor("POST", uri,
|
||||
Map.of("content-type", JSON_1_0, "x-amz-target", "AmazonSQS.ListQueues"), body);
|
||||
|
||||
assertEquals(200, sendSqsListQueues(uri, auth, JSON_1_0, null, body).statusCode());
|
||||
|
||||
HttpResponse<String> swapped = sendSqsListQueues(uri, auth, JSON_1_0 + "; charset=utf-8", JSON_1_0, body);
|
||||
assertEquals(403, swapped.statusCode());
|
||||
assertTrue(swapped.body().contains("InvalidSignatureException"), swapped.body());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(16)
|
||||
void executeApiRoutesAreLeftToTheirOwnAuthorizer() {
|
||||
// A wrong secret on an execute-api path is ExecuteApiSigV4Authorizer's call, per method:
|
||||
// here the API does not exist, so the answer is the controller's 404, not this filter's 403.
|
||||
for (String path : new String[]{"/execute-api/nope/stage/x", "/_aws/execute-api/nope/stage/x",
|
||||
"/restapis/nope/stage/_user_request_/x"}) {
|
||||
given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "not-the-secret", "execute-api"))
|
||||
.when()
|
||||
.get(path)
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(17)
|
||||
void appSyncGraphqlIsLeftToItsOwnIamCheck() throws Exception {
|
||||
// The management plane is verified here like any other service; the GraphQL endpoint is
|
||||
// AppSync's own, and a wrong secret there gets AppSync's UnauthorizedException envelope.
|
||||
String apiId = given()
|
||||
.filter(AwsRequestSigner.signedAs("test", "test", "appsync"))
|
||||
.contentType("application/json")
|
||||
.body("{\"name\": \"validate-signatures-graphql\", \"authenticationType\": \"AWS_IAM\"}")
|
||||
.when()
|
||||
.post("/v1/apis")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("graphqlApi.apiId");
|
||||
|
||||
String query = "{\"query\": \"{ __typename }\"}";
|
||||
Map<String, String> forged = AppSyncRequestSigner.signedHeaders(apiId, "localhost:" + RestAssured.port,
|
||||
query, "test", "not-the-secret", "us-east-1", Instant.now());
|
||||
given()
|
||||
.headers(forged)
|
||||
.contentType("application/json")
|
||||
.body(query)
|
||||
.when()
|
||||
.post("/v1/apis/" + apiId + "/graphql")
|
||||
.then()
|
||||
.statusCode(401)
|
||||
.header("x-amzn-errortype", containsString("UnauthorizedException"))
|
||||
.body("errors[0].errorType", equalTo("UnauthorizedException"));
|
||||
}
|
||||
|
||||
private static HttpResponse<String> sendSqsListQueues(URI uri, Map<String, String> auth, String contentType,
|
||||
String claimedOriginal, byte[] body) throws Exception {
|
||||
HttpRequest.Builder request = HttpRequest.newBuilder(uri)
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.POST(HttpRequest.BodyPublishers.ofByteArray(body))
|
||||
.header("Content-Type", contentType)
|
||||
.header("X-Amz-Target", "AmazonSQS.ListQueues");
|
||||
auth.forEach(request::header);
|
||||
if (claimedOriginal != null) {
|
||||
request.header(AwsCborContentTypeFilter.ORIGINAL_CONTENT_TYPE_HEADER, claimedOriginal);
|
||||
}
|
||||
try (HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build()) {
|
||||
return client.send(request.build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(18)
|
||||
void unsignedRequestIsLeftToIamEnforcement() {
|
||||
given()
|
||||
.contentType(JSON_1_0)
|
||||
.header("X-Amz-Target", "AmazonSQS.ListQueues")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
}
|
||||
+2
-10
@@ -1,9 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.testing.ValidateSignaturesProfile;
|
||||
import io.github.hectorvent.floci.testutil.S3RequestSigner;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.RestAssured;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -15,24 +15,16 @@ import org.junit.jupiter.api.TestMethodOrder;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(PreSignedUrlIntegrationTest.PresignValidationProfile.class)
|
||||
@TestProfile(ValidateSignaturesProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class PreSignedUrlIntegrationTest {
|
||||
|
||||
public static final class PresignValidationProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.auth.validate-signatures", "true");
|
||||
}
|
||||
}
|
||||
|
||||
private static final String BUCKET = "presign-test-bucket";
|
||||
|
||||
private static final S3RequestSigner LOCAL_SIGNER = S3RequestSigner.signedAs("test", "test");
|
||||
|
||||
+13
-11
@@ -1,6 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
|
||||
import io.github.hectorvent.floci.testing.ValidateSignaturesProfile;
|
||||
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
|
||||
import io.github.hectorvent.floci.testutil.S3RequestSigner;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -27,11 +29,11 @@ import static org.hamcrest.Matchers.equalTo;
|
||||
* {@code floci.auth.validate-signatures} authenticates every signed S3 request, whichever
|
||||
* placement carries the signature, without authorizing it: a forged or unknown credential is
|
||||
* refused, while bucket policies are not evaluated and unsigned requests pass, as they do with
|
||||
* {@code enforce-auth} off. Shares {@link PreSignedUrlIntegrationTest}'s profile, which covers the
|
||||
* presigned query-string placement.
|
||||
* {@code enforce-auth} off. Shares {@link ValidateSignaturesProfile} with
|
||||
* {@link PreSignedUrlIntegrationTest}, which covers the presigned query-string placement.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(PreSignedUrlIntegrationTest.PresignValidationProfile.class)
|
||||
@TestProfile(ValidateSignaturesProfile.class)
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class S3ValidateSignaturesIntegrationTest {
|
||||
|
||||
@@ -295,21 +297,21 @@ class S3ValidateSignaturesIntegrationTest {
|
||||
}
|
||||
|
||||
private static void createIamUser(String userName) {
|
||||
String authorization = "AWS4-HMAC-SHA256 Credential=test/" + CREDENTIAL_DATE
|
||||
+ "/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=unused";
|
||||
// validate-signatures verifies IAM's signatures too, so these calls carry real ones.
|
||||
AwsRequestSigner iam = AwsRequestSigner.signedAs("test", "test", "iam");
|
||||
given()
|
||||
.formParam("Action", "CreateUser")
|
||||
.formParam("UserName", userName)
|
||||
.header("Authorization", authorization)
|
||||
.filter(iam)
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.body("Action=CreateUser&UserName=" + userName + "&Version=2010-05-08")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
XmlPath key = given()
|
||||
.formParam("Action", "CreateAccessKey")
|
||||
.formParam("UserName", userName)
|
||||
.header("Authorization", authorization)
|
||||
.filter(iam)
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.body("Action=CreateAccessKey&UserName=" + userName + "&Version=2010-05-08")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Turns {@code floci.auth.validate-signatures} on, and nothing else. Quarkus builds the application
|
||||
* once per distinct profile class, so the classes that need only this override share this one
|
||||
* rather than each declaring an identical nested profile.
|
||||
*/
|
||||
public class ValidateSignaturesProfile implements QuarkusTestProfile {
|
||||
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.auth.validate-signatures", "true");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package io.github.hectorvent.floci.testutil;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
|
||||
import io.restassured.filter.Filter;
|
||||
import io.restassured.filter.FilterContext;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.FilterableRequestSpecification;
|
||||
import io.restassured.specification.FilterableResponseSpecification;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* A RestAssured filter that header-signs a request for a service other than S3 the way an AWS SDK
|
||||
* does: each segment of the wire path URI-encoded a second time, no {@code x-amz-content-sha256}
|
||||
* header, and the body's SHA-256 as the payload hash. Signs {@code host}, {@code x-amz-date} and,
|
||||
* when present, {@code x-amz-security-token} and {@code x-amz-target}. {@code Content-Type} is
|
||||
* signed only on request ({@link #signingContentType()}), because RestAssured appends a charset to
|
||||
* text types after the filter runs.
|
||||
*
|
||||
* <p>Attach with {@code given().filter(AwsRequestSigner.signedAs("test", "test", "sqs"))}. The
|
||||
* {@code with*} methods return a copy that deliberately deviates for the rejection cases.
|
||||
*/
|
||||
public final class AwsRequestSigner implements Filter {
|
||||
|
||||
private static final String ALGORITHM = "AWS4-HMAC-SHA256";
|
||||
private static final DateTimeFormatter AMZ_DATE =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
|
||||
private final String accessKeyId;
|
||||
private final String secretKey;
|
||||
private final String sessionToken;
|
||||
private final String service;
|
||||
private final Instant signedAt;
|
||||
private final boolean signContentType;
|
||||
|
||||
private AwsRequestSigner(String accessKeyId, String secretKey, String sessionToken, String service,
|
||||
Instant signedAt, boolean signContentType) {
|
||||
this.accessKeyId = accessKeyId;
|
||||
this.secretKey = secretKey;
|
||||
this.sessionToken = sessionToken;
|
||||
this.service = service;
|
||||
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);
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response filter(FilterableRequestSpecification request,
|
||||
FilterableResponseSpecification response, FilterContext ctx) {
|
||||
try {
|
||||
sign(request);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("could not sign the request", e);
|
||||
}
|
||||
return ctx.next(request, response);
|
||||
}
|
||||
|
||||
private void sign(FilterableRequestSpecification request) throws Exception {
|
||||
Map<String, String> signed = new LinkedHashMap<>();
|
||||
if (signContentType) {
|
||||
signed.put("content-type", request.getContentType());
|
||||
}
|
||||
String target = request.getHeaders().getValue("X-Amz-Target");
|
||||
if (target != null) {
|
||||
signed.put("x-amz-target", target);
|
||||
}
|
||||
headersFor(request.getMethod(), URI.create(request.getURI()), signed, bodyBytes(request.getBody()))
|
||||
.forEach(request::header);
|
||||
}
|
||||
|
||||
/**
|
||||
* The headers a signed request must carry ({@code X-Amz-Date}, {@code Authorization} and, with a
|
||||
* session token, {@code X-Amz-Security-Token}), for tests that send with a client other than
|
||||
* RestAssured. {@code host}, {@code x-amz-date} and the token are always signed; {@code extra}
|
||||
* names any further headers to sign, by lowercase name, with the values the request will carry.
|
||||
*/
|
||||
public Map<String, String> headersFor(String method, URI uri, Map<String, String> extra, byte[] body)
|
||||
throws Exception {
|
||||
String amzDate = AMZ_DATE.format(signedAt != null ? signedAt : Instant.now());
|
||||
String scopeDate = amzDate.substring(0, 8);
|
||||
String host = uri.getPort() > 0 && uri.getPort() != 80 && uri.getPort() != 443
|
||||
? uri.getHost() + ":" + uri.getPort()
|
||||
: uri.getHost();
|
||||
|
||||
TreeMap<String, String> headers = new TreeMap<>(extra);
|
||||
headers.put("host", host);
|
||||
headers.put("x-amz-date", amzDate);
|
||||
if (sessionToken != null) {
|
||||
headers.put("x-amz-security-token", sessionToken);
|
||||
}
|
||||
String signedHeaders = String.join(";", headers.keySet());
|
||||
String canonicalHeaders = headers.entrySet().stream()
|
||||
.map(h -> h.getKey() + ":" + h.getValue() + "\n")
|
||||
.collect(Collectors.joining());
|
||||
|
||||
String canonicalRequest = method + "\n"
|
||||
+ doubleEncodedPath(uri.getRawPath()) + "\n"
|
||||
+ S3RequestSigner.canonicalQueryString(uri.getRawQuery()) + "\n"
|
||||
+ canonicalHeaders + "\n"
|
||||
+ signedHeaders + "\n"
|
||||
+ SigV4RequestValidator.sha256Hex(body);
|
||||
String credentialScope = scopeDate + "/us-east-1/" + service + "/aws4_request";
|
||||
String stringToSign = ALGORITHM + "\n" + amzDate + "\n" + credentialScope + "\n"
|
||||
+ SigV4RequestValidator.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] signingKey = SigV4RequestValidator.deriveSigningKey(secretKey, scopeDate, "us-east-1", service);
|
||||
String signature = SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(signingKey, stringToSign));
|
||||
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
result.put("X-Amz-Date", amzDate);
|
||||
if (sessionToken != null) {
|
||||
result.put("X-Amz-Security-Token", sessionToken);
|
||||
}
|
||||
result.put("Authorization", ALGORITHM + " Credential=" + accessKeyId + "/" + credentialScope
|
||||
+ ", SignedHeaders=" + signedHeaders + ", Signature=" + signature);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String doubleEncodedPath(String rawPath) {
|
||||
String path = rawPath == null || rawPath.isEmpty() ? "/" : rawPath;
|
||||
String[] segments = path.split("/", -1);
|
||||
StringBuilder encoded = new StringBuilder();
|
||||
for (int i = 0; i < segments.length; i++) {
|
||||
if (i > 0) {
|
||||
encoded.append('/');
|
||||
}
|
||||
encoded.append(S3RequestSigner.uriEncode(segments[i]));
|
||||
}
|
||||
return encoded.toString();
|
||||
}
|
||||
|
||||
private static byte[] bodyBytes(Object body) {
|
||||
if (body == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
if (body instanceof byte[] bytes) {
|
||||
return bytes;
|
||||
}
|
||||
if (body instanceof String text) {
|
||||
return text.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
throw new IllegalArgumentException("unsupported body type " + body.getClass().getName());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user