Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(auth): verify query signatures and retain STS caller identity (#5584)

David Phillipsa017c94eccff
diff --git a/compatibility-tests/sdk-test-java/README.md b/compatibility-tests/sdk-test-java/README.md
index 5789c06497..69c057cf38 100644
--- a/compatibility-tests/sdk-test-java/README.md
+++ b/compatibility-tests/sdk-test-java/README.md
@@ -62,6 +62,20 @@ Partition Compatibility workflow does exactly that, and tolerates only the failu
`.github/ci/compat-partition-allowlist-cn-north-1.txt`. Tests that build their own client with an
explicit region keep that region.
+## STS presigned identity checks
+
+`StsPresignedIdentityTest` checks user and role identity over HTTP/1.1 and HTTP/2.
+Valid identity requests run in both modes. Forged signatures and changed bodies are
+sent only when signature checking is enabled. To check signature refusal, start Floci
+with `FLOCI_AUTH_VALIDATE_SIGNATURES=true` and pass the same setting to this test:
+
+```bash
+FLOCI_AUTH_VALIDATE_SIGNATURES=true mvn test -Dtest=StsPresignedIdentityTest
+```
+
+The test setting must match the server setting; it does not configure the server.
+The enabled mode also checks missing and incorrect temporary-session tokens.
+
## Metric filter publishing checks
`CloudWatchLogsMetricFilterTest` and `CloudFormationLogsMetricFilterTest` run
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.java
new file mode 100644
index 0000000000..a63d127fe3
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StsPresignedIdentityTest.java
@@ -0,0 +1,153 @@
+package com.floci.test;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.w3c.dom.Document;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
+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.http.SdkHttpFullRequest;
+import software.amazon.awssdk.http.SdkHttpMethod;
+import software.amazon.awssdk.services.iam.IamClient;
+import software.amazon.awssdk.services.iam.model.AccessKey;
+import software.amazon.awssdk.services.iam.model.User;
+import software.amazon.awssdk.services.sts.StsClient;
+import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
+import software.amazon.awssdk.services.sts.model.GetCallerIdentityResponse;
+
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilderFactory;
+import java.io.ByteArrayInputStream;
+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 static org.assertj.core.api.Assertions.assertThat;
+
+class StsPresignedIdentityTest {
+ @ParameterizedTest
+ @CsvSource({"false, HTTP_1_1", "true, HTTP_1_1", "false, HTTP_2", "true, HTTP_2"})
+ void sdkPresignedRequestKeepsUserOrRoleIdentity(boolean role, HttpClient.Version version) throws Exception {
+ String name = TestFixtures.uniqueName("sts-presigned");
+ try (IamClient iam = TestFixtures.iamClient(); StsClient root = TestFixtures.stsClient()) {
+ String expectedArn;
+ String expectedId;
+ AwsCredentials credentials;
+ String accessKey = null;
+ if (role) {
+ String roleArn = iam.createRole(r -> r.roleName(name).assumeRolePolicyDocument(
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":\"*\",\"Action\":\"sts:AssumeRole\"}]}"))
+ .role().arn();
+ try {
+ AssumeRoleResponse session = root.assumeRole(r -> r.roleArn(roleArn).roleSessionName("identity"));
+ expectedArn = session.assumedRoleUser().arn();
+ expectedId = session.assumedRoleUser().assumedRoleId();
+ credentials = AwsSessionCredentials.create(session.credentials().accessKeyId(),
+ session.credentials().secretAccessKey(), session.credentials().sessionToken());
+ } catch (RuntimeException error) {
+ iam.deleteRole(r -> r.roleName(name));
+ throw error;
+ }
+ } else {
+ User user = iam.createUser(r -> r.userName(name)).user();
+ expectedArn = user.arn();
+ expectedId = user.userId();
+ try {
+ AccessKey key = iam.createAccessKey(r -> r.userName(name)).accessKey();
+ accessKey = key.accessKeyId();
+ credentials = AwsBasicCredentials.create(accessKey, key.secretAccessKey());
+ } catch (RuntimeException error) {
+ iam.deleteUser(r -> r.userName(name));
+ throw error;
+ }
+ }
+ try (StsClient caller = StsClient.builder().endpointOverride(TestFixtures.endpoint())
+ .region(TestFixtures.region()).credentialsProvider(StaticCredentialsProvider.create(credentials)).build()) {
+ GetCallerIdentityResponse header = caller.getCallerIdentity();
+ assertThat(header.arn()).isEqualTo(expectedArn);
+ assertThat(header.userId()).isEqualTo(expectedId);
+ Document query = presignedIdentity(credentials, version);
+ assertThat(query.getElementsByTagNameNS("*", "Arn").item(0).getTextContent()).isEqualTo(expectedArn);
+ assertThat(query.getElementsByTagNameNS("*", "UserId").item(0).getTextContent()).isEqualTo(expectedId);
+ assertThat(query.getElementsByTagNameNS("*", "Account").item(0).getTextContent()).isEqualTo(header.account());
+ } finally {
+ if (role) {
+ iam.deleteRole(r -> r.roleName(name));
+ } else {
+ String key = accessKey;
+ try {
+ iam.deleteAccessKey(r -> r.userName(name).accessKeyId(key));
+ } finally {
+ iam.deleteUser(r -> r.userName(name));
+ }
+ }
+ }
+ }
+ }
+
+ 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());
+ 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"));
+ if (signaturesEnabled) {
+ URI forged = URI.create(signed.getUri().toString().replaceAll("X-Amz-Signature=[^&]*",
+ "X-Amz-Signature=" + "0".repeat(64)));
+ assertSignatureRefused(send(signed, forged, body, version));
+ assertSignatureRefused(send(signed, signed.getUri(),
+ (new String(body, StandardCharsets.UTF_8) + "&Extra=changed").getBytes(StandardCharsets.UTF_8), version));
+ }
+ if (signaturesEnabled && credentials instanceof AwsSessionCredentials) {
+ for (String replacement : new String[]{"", "X-Amz-Security-Token=wrong"}) {
+ URI wrongToken = URI.create(signed.getUri().toString()
+ .replaceAll("X-Amz-Security-Token=[^&]*", replacement));
+ HttpResponse<byte[]> invalid = send(signed, wrongToken, body, version);
+ assertThat(invalid.statusCode()).isEqualTo(403);
+ assertThat(new String(invalid.body(), StandardCharsets.UTF_8)).contains("InvalidClientTokenId");
+ }
+ }
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ 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()));
+ }
+
+ private static void assertSignatureRefused(HttpResponse<byte[]> response) {
+ assertThat(response.statusCode()).as(new String(response.body(), StandardCharsets.UTF_8)).isEqualTo(403);
+ assertThat(new String(response.body(), StandardCharsets.UTF_8)).contains("SignatureDoesNotMatch");
+ }
+
+ private static HttpResponse<byte[]> send(SdkHttpFullRequest signed, URI uri, byte[] body,
+ HttpClient.Version version) throws Exception {
+ HttpRequest.Builder request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10))
+ .POST(HttpRequest.BodyPublishers.ofByteArray(body));
+ signed.headers().forEach((name, values) -> {
+ if (!name.equalsIgnoreCase("Host") && !name.equalsIgnoreCase("Content-Length")) {
+ values.forEach(value -> request.header(name, value));
+ }
+ });
+ HttpResponse<byte[]> response = HttpClient.newBuilder().version(version).build()
+ .send(request.build(), HttpResponse.BodyHandlers.ofByteArray());
+ assertThat(response.version()).isEqualTo(version);
+ return response;
+ }
+}
diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md
index 5cdc9cc858..925048f8d9 100644
--- a/docs/configuration/environment-variables.md
+++ b/docs/configuration/environment-variables.md
@@ -23,7 +23,7 @@ Floci is configured exclusively through environment variables. Every option belo
| Variable | Default | Description |
|---|---|---|
-| `FLOCI_AUTH_VALIDATE_SIGNATURES` | `false` | When `true`, verifies the SigV4 signature of every signed request without evaluating policies: every S3 placement (`Authorization` header, presigned URL and presigned POST), and the `Authorization` header for every other service (see [Signature Validation](multi-account.md#signature-validation)) |
+| `FLOCI_AUTH_VALIDATE_SIGNATURES` | `false` | When `true`, verifies the SigV4 signature of every signed request without evaluating policies: every S3 placement (`Authorization` header, presigned URL and presigned POST), and header or presigned query signatures for every other service (see [Signature Validation](multi-account.md#signature-validation)) |
| `FLOCI_AUTH_PRESIGN_SECRET` | `local-emulator-secret` | Secret used to sign and verify pre-signed URLs |
## Network Exposure
diff --git a/docs/configuration/multi-account.md b/docs/configuration/multi-account.md
index b298097d9b..bbda222d3c 100644
--- a/docs/configuration/multi-account.md
+++ b/docs/configuration/multi-account.md
@@ -172,7 +172,7 @@ By default Floci does not verify SigV4 signatures. Only the access key ID matter
`FLOCI_AUTH_VALIDATE_SIGNATURES` verifies the SigV4 signature of every signed request, for every service, without evaluating any policy, and leaves unsigned requests alone:
- **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. 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 query-string signatures and SigV4a are not verified outside S3, and API Gateway `execute-api` requests keep their own [IAM authorization](../services/api-gateway.md#iam-authorization).
+- **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).
To verify signatures:
diff --git a/docs/services/sts.md b/docs/services/sts.md
index 4e0a35ecaa..fa64e80b34 100644
--- a/docs/services/sts.md
+++ b/docs/services/sts.md
@@ -113,5 +113,13 @@ For temporary credentials returned by an assumed-role action, its `Arn` and `Use
the `AssumedRoleUser.Arn` and `AssumedRoleUser.AssumedRoleId` returned when the session was created.
For `GetSessionToken` credentials they are those of the IAM user that minted them, and for `GetFederationToken`
credentials the `FederatedUser.Arn` and `FederatedUser.FederatedUserId` (`<account>:<name>`).
+The response resolves both header and query-string credentials, including the query session token,
+so a presigned request reports the same caller identity. A nonblank Authorization header retains
+precedence over query credentials.
When `FLOCI_SERVICES_IAM_SEED_DEPLOYER_PRINCIPAL=true`, requests signed with the seeded `floci` access key return `arn:aws:iam::000000000000:user/floci-deployer`. Other unknown local credentials continue to return the account root ARN for backward compatibility.
+
+When `FLOCI_AUTH_VALIDATE_SIGNATURES=true`, the shared signature verifier checks presigned query
+credentials for STS operations, including `GetCallerIdentity`, `GetSessionToken`, `GetFederationToken`
+and `AssumeRole`. It checks the request signature, credential scope, expiry and session token before
+execution. Nonblank Authorization headers retain priority. See [signature checks](../configuration/multi-account.md#signature-validation).
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/SigV4HeaderSignatureFilter.java
index 3de7b649c9..d21cad9d42 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
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.apigateway.ApiGatewayExecuteControlle
import io.github.hectorvent.floci.services.apigateway.ApiGatewayUserRequestController;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncExecutionController;
import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.RequestBodyReader;
import io.github.hectorvent.floci.services.s3.S3ControlController;
import io.github.hectorvent.floci.services.s3.S3Controller;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
@@ -24,6 +25,7 @@ import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
@@ -45,7 +47,7 @@ import java.util.Set;
import java.util.function.UnaryOperator;
/**
- * Verifies the SigV4 signature in the {@code Authorization} header of every request outside S3
+ * Verifies header and query SigV4 signatures on every request outside S3
* when {@code floci.auth.validate-signatures} is enabled, so a request signed with the wrong
* secret is refused by SQS, KMS, IAM, Scheduler and the rest as it already is by S3.
*
@@ -75,8 +77,10 @@ import java.util.function.UnaryOperator;
* Everything else is verified here, S3 Control included, whatever service its scope names.
*
* <p>As with S3, signature verification is authentication only, and an unsigned request is let
- * through: whether a caller may act is IAM enforcement's decision. Presigned query-string
- * signatures and SigV4a ({@code AWS4-ECDSA-P256-SHA256}) are not verified here.
+ * through: whether a caller may act is IAM enforcement's decision. A nonblank Authorization
+ * header takes precedence over query credentials. Query signatures expire at X-Amz-Expires;
+ * both placements share credential lookup, canonicalization and protocol error mapping.
+ * SigV4a ({@code AWS4-ECDSA-P256-SHA256}) is not verified here.
*
* <p>Errors follow the protocol the request used: a Query or REST-XML request (Route 53,
* CloudFront, S3 Control) receives an {@code <ErrorResponse>}, a CBOR request a CBOR body, and
@@ -96,6 +100,7 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
private static final Logger LOG = Logger.getLogger(SigV4HeaderSignatureFilter.class);
private static final Duration MAX_CLOCK_SKEW = Duration.ofMinutes(15);
+ private static final long MAX_EXPIRY_SECONDS = 604800;
private static final DateTimeFormatter AMZ_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
@@ -145,9 +150,22 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
if (resource != null && VERIFIED_ELSEWHERE.contains(resource)) {
return;
}
- SigV4AuthorizationHeader signed = SigV4AuthorizationHeader.parse(ctx.getHeaderString("Authorization"));
- if (signed == null) {
- return;
+ String authorization = ctx.getHeaderString("Authorization");
+ MultivaluedMap<String, String> query = ctx.getUriInfo().getQueryParameters();
+ boolean presigned = isBlank(authorization) && query.containsKey("X-Amz-Credential");
+ SigV4AuthorizationHeader signed;
+ if (presigned) {
+ if (!"AWS4-HMAC-SHA256".equals(query.getFirst("X-Amz-Algorithm"))) {
+ incompleteSignature(ctx, resource, "Presigned request requires X-Amz-Algorithm=AWS4-HMAC-SHA256.");
+ return;
+ }
+ signed = new SigV4AuthorizationHeader(query.getFirst("X-Amz-Credential"),
+ query.getFirst("X-Amz-SignedHeaders"), query.getFirst("X-Amz-Signature"));
+ } else {
+ signed = SigV4AuthorizationHeader.parse(authorization);
+ if (signed == null) {
+ return;
+ }
}
CredentialScope scope = CredentialScope.parse(signed.credential());
@@ -162,14 +180,42 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
"'Host' or ':authority' must be a 'SignedHeader' in the AWS Authorization.");
return;
}
- Instant requestTime = requestTime(ctx);
+ Instant requestTime = presigned ? parseAmzDate(query.getFirst("X-Amz-Date")) : requestTime(ctx);
if (requestTime == null) {
incompleteSignature(ctx, resource, "Authorization header requires existence of either a "
+ "'X-Amz-Date' or a 'Date' header.");
return;
}
- Optional<String> secretKey = resolveSecretKey(scope.accessKeyId(), ctx.getHeaderString("X-Amz-Security-Token"));
+ long expires = 0;
+ if (presigned) {
+ try {
+ expires = Long.parseLong(query.getFirst("X-Amz-Expires"));
+ if (expires < 1 || expires > MAX_EXPIRY_SECONDS) {
+ throw new IllegalArgumentException("Invalid expiry");
+ }
+ } catch (RuntimeException error) {
+ incompleteSignature(ctx, resource, "Presigned request requires X-Amz-Expires between 1 and 604800.");
+ return;
+ }
+ }
+ String token = ctx.getHeaderString("X-Amz-Security-Token");
+ boolean scopeMatches = true;
+ if (presigned) {
+ try {
+ if (token == null) {
+ token = RequestBodyReader.formField(ctx, "X-Amz-Security-Token");
+ if (token == null) {
+ token = query.getFirst("X-Amz-Security-Token");
+ }
+ }
+ scopeMatches = queryScopeMatchesResource(ctx, resource, scope.service());
+ } catch (IllegalArgumentException error) {
+ incompleteSignature(ctx, resource, "Cannot read presigned request form parameters.");
+ return;
+ }
+ }
+ Optional<String> secretKey = resolveSecretKey(scope.accessKeyId(), token);
if (secretKey.isEmpty()) {
LOG.debugv("Refusing {0} request signed with unknown access key {1}",
scope.service(), SigV4RequestValidator.sanitizeForLog(scope.accessKeyId()));
@@ -179,7 +225,9 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
String amzDate = AMZ_DATE.format(requestTime);
Instant now = Instant.now();
- if (Duration.between(requestTime, now).abs().compareTo(MAX_CLOCK_SKEW) > 0) {
+ 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) + ".");
@@ -192,6 +240,11 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
return;
}
+ if (!scopeMatches) {
+ signatureDoesNotMatch(ctx, resource, "Credential should be scoped to the service receiving the request.");
+ return;
+ }
+
byte[] body = signedBody(ctx);
UnaryOperator<String> headers = name -> "content-length".equals(name)
&& ctx.getProperty(SqsQueueUrlRouterFilter.APPENDED_BODY_BYTES_PROPERTY) != null
@@ -200,7 +253,7 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
boolean matches;
try {
matches = signatureMatches(ctx.getMethod(), rawPath(ctx), rawQuery(ctx), signed.signedHeaders(),
- headers, body, secretKey.get(), amzDate, scope, signed.signature());
+ headers, body, secretKey.get(), amzDate, scope, signed.signature(), presigned);
} catch (Exception e) {
LOG.debugv(e, "SigV4 verification failed to complete for accessKey={0}",
SigV4RequestValidator.sanitizeForLog(scope.accessKeyId()));
@@ -217,14 +270,48 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
static boolean signatureMatches(String method, String rawPath, String rawQuery, String signedHeaders,
UnaryOperator<String> headers, byte[] body, String secretKey,
String amzDate, CredentialScope scope, String signature) throws Exception {
+ return signatureMatches(method, rawPath, rawQuery, signedHeaders, headers, body,
+ secretKey, amzDate, scope, signature, false);
+ }
+
+ // Non-S3 body-bearing SDK presigners hash the body; only a signed payload marker opts out.
+ private static boolean signatureMatches(String method, String rawPath, String rawQuery, String signedHeaders,
+ UnaryOperator<String> headers, byte[] body, String secretKey,
+ String amzDate, CredentialScope scope, String signature,
+ boolean presigned) throws Exception {
return SigV4Canonicalization.signatureMatches(method, rawPath,
- SigV4Canonicalization.canonicalQueryString(rawQuery, false),
+ SigV4Canonicalization.canonicalQueryString(rawQuery, presigned),
SigV4Canonicalization.canonicalHeaders(signedHeaders, headers),
signedHeaders,
SigV4Canonicalization.payloadHash(headers.apply("x-amz-content-sha256"), signedHeaders, body, false),
amzDate, scope, secretKey, signature);
}
+ private boolean queryScopeMatchesResource(ContainerRequestContext ctx, Class<?> resource, String service) {
+ ServiceDescriptor descriptor;
+ if (resource == AwsQueryController.class) {
+ String action = AwsQueryServiceResolver.action(RequestBodyReader.formField(ctx, "Action"),
+ RequestBodyReader.formField(ctx, "Operation"));
+ String target = action == null ? null
+ : AwsQueryController.inferServiceFromAction(action, RequestBodyReader.formField(ctx, "Version"));
+ descriptor = target == null ? null : catalog.byExternalKey(target).orElse(null);
+ } else if (ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
+ && claim.service() != null) {
+ descriptor = claim.service();
+ } else {
+ descriptor = resource == null ? null : catalog.byResourceClass(resource).orElse(null);
+ }
+ return descriptor == null || descriptor.credentialScopes().contains(service);
+ }
+
+ private static Instant parseAmzDate(String value) {
+ try {
+ return value == null ? null : Instant.from(AMZ_DATE.parse(value));
+ } catch (DateTimeParseException error) {
+ return null;
+ }
+ }
+
/**
* The path as the client sent it, before any filter rewrote it or JAX-RS normalized it. Falls
* back to the request URI when no Vert.x request is current.
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4Canonicalization.java b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4Canonicalization.java
index fd9ac218d4..c37565f31d 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4Canonicalization.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/auth/SigV4Canonicalization.java
@@ -136,8 +136,9 @@ public final class SigV4Canonicalization {
*
* <p>The sentinels ({@code UNSIGNED-PAYLOAD}, the {@code STREAMING-*} forms) mean the caller
* chose not to sign the body, and are honoured only when {@code x-amz-content-sha256} is itself
- * in {@code SignedHeaders}: that is, when the choice is covered by the signature. A presigned
- * request is unsigned-payload by convention; every AWS presigner emits it that way.
+ * in {@code SignedHeaders}: that is, when the choice is covered by the signature. Callers whose
+ * presigning protocol uses an unsigned payload select it explicitly; body-bearing STS
+ * requests from the Java SDK instead carry the actual body hash.
*/
public static String payloadHash(String declaredContentSha256, String signedHeaders, byte[] body,
boolean presigned) throws Exception {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/RequestBodyReader.java b/src/main/java/io/github/hectorvent/floci/services/iam/RequestBodyReader.java
index 3ff7268b87..08e67d9916 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/RequestBodyReader.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/RequestBodyReader.java
@@ -13,7 +13,7 @@ import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
-final class RequestBodyReader {
+public final class RequestBodyReader {
private static final Logger LOG = Logger.getLogger(RequestBodyReader.class);
private static final String BUFFERED_BODY_PROPERTY =
@@ -44,7 +44,7 @@ final class RequestBodyReader {
return body;
}
- static String formField(ContainerRequestContext ctx, String key) {
+ public static String formField(ContainerRequestContext ctx, String key) {
MediaType mt = ctx.getMediaType();
if (mt == null
|| !"application".equalsIgnoreCase(mt.getType())
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
index e27988ad32..90f4232b9a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
@@ -228,12 +228,14 @@ public class StsQueryHandler {
private Response handleGetCallerIdentity(MultivaluedMap<String, String> params) {
String accountId = regionResolver.getAccountId();
- String authorization = headers == null ? null : headers.getHeaderString("Authorization");
- String accessKeyId = authorization == null ? null : accountResolver.extractAccessKeyId(authorization);
+ String accessKeyId = callerAccessKeyId();
String sessionToken = headers == null ? null : headers.getHeaderString("X-Amz-Security-Token");
if (sessionToken == null && params != null) {
sessionToken = getParam(params, "X-Amz-Security-Token");
}
+ if (sessionToken == null && uriInfo != null) {
+ sessionToken = uriInfo.getQueryParameters().getFirst("X-Amz-Security-Token");
+ }
String arn = iamService.resolveCallerArn(accessKeyId)
.orElse(regionResolver.buildGlobalArn("iam", accountId, "root"));
String userId = iamService.resolveCallerUserId(accessKeyId, sessionToken).orElse(accountId);
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsPresignedIdentityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsPresignedIdentityIntegrationTest.java
new file mode 100644
index 0000000000..49d9bc377d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsPresignedIdentityIntegrationTest.java
@@ -0,0 +1,111 @@
+package io.github.hectorvent.floci.services.iam;
+
+import io.github.hectorvent.floci.testing.EnforcementFixtures;
+import io.github.hectorvent.floci.testing.IamEnforcementProfile;
+import io.github.hectorvent.floci.testing.PartitionCleanup;
+import io.quarkus.test.common.http.TestHTTPResource;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import io.restassured.path.xml.XmlPath;
+import io.restassured.specification.RequestSpecification;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.net.URI;
+import java.util.UUID;
+import java.util.stream.Stream;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertAll;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+@QuarkusTest
+@TestProfile(IamEnforcementProfile.class)
+class StsPresignedIdentityIntegrationTest {
+ @Inject IamService iam;
+ @TestHTTPResource("/") URI baseUri;
+ @RegisterExtension final PartitionCleanup cleanup = new PartitionCleanup();
+
+ static Stream<Arguments> identities() {
+ return Stream.of("000000000000:us-east-1:aws", "123456789012:cn-north-1:aws-cn")
+ .flatMap(scope -> Stream.of("root", "user", "role")
+ .flatMap(kind -> Stream.of("header", "query", "mixed", "form-only", "form-mixed").map(mode -> Arguments.of(scope, kind, mode))));
+ }
+
+ @ParameterizedTest
+ @MethodSource("identities")
+ void callerIdentityRetainsCredentialIdentity(String scope, String kind, String mode) {
+ String[] parts = scope.split(":");
+ String account = parts[0];
+ String region = parts[1];
+ String partition = parts[2];
+ String name = "presigned-" + UUID.randomUUID().toString().substring(0, 8);
+ String rootAuth = auth(account, region, "iam");
+ String key = account;
+ String token = null;
+ String arn = "arn:" + partition + ":iam::" + account + ":root";
+ String userId = account;
+ if (kind.equals("user")) {
+ key = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), rootAuth, name).accessKeyId();
+ XmlPath user = given().header("Authorization", rootAuth).formParam("Action", "GetUser")
+ .formParam("UserName", name).post("/").then().statusCode(200).extract().xmlPath();
+ arn = user.getString("GetUserResponse.GetUserResult.User.Arn");
+ userId = user.getString("GetUserResponse.GetUserResult.User.UserId");
+ } else if (kind.equals("role")) {
+ cleanup.register(() -> EnforcementFixtures.removeRole(baseUri.getPort(), rootAuth, name));
+ String roleArn = given().header("Authorization", rootAuth).formParam("Action", "CreateRole")
+ .formParam("RoleName", name).formParam("AssumeRolePolicyDocument",
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":\"" + arn + "\"},\"Action\":\"sts:AssumeRole\"}]}")
+ .post("/").then().statusCode(200).extract().path("CreateRoleResponse.CreateRoleResult.Role.Arn");
+ XmlPath session = given().header("Authorization", auth(account, region, "sts"))
+ .formParam("Action", "AssumeRole").formParam("Version", "2011-06-15")
+ .formParam("RoleArn", roleArn).formParam("RoleSessionName", "identity-session")
+ .post("/").then().statusCode(200).extract().xmlPath();
+ key = session.getString("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");
+ token = session.getString("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken");
+ arn = session.getString("AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn");
+ userId = session.getString("AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.AssumedRoleId");
+ String sessionKey = key;
+ cleanup.register(() -> iam.unregisterSession(account, sessionKey));
+ }
+ RequestSpecification request = given().formParam("Action", "GetCallerIdentity")
+ .formParam("Version", "2011-06-15");
+ if (mode.equals("query")) {
+ request.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
+ .queryParam("X-Amz-Credential", key + "/20261013/" + region + "/sts/aws4_request")
+ .queryParam("X-Amz-SignedHeaders", "host").queryParam("X-Amz-Signature", "abc");
+ if (token != null) {
+ request.queryParam("X-Amz-Security-Token", token);
+ }
+ } else {
+ request.header("Authorization", auth(key, region, "sts"));
+ if (token != null) {
+ if (mode.startsWith("form-")) {
+ request.formParam("X-Amz-Security-Token", token);
+ } else {
+ request.header("X-Amz-Security-Token", token);
+ }
+ }
+ }
+ if ((mode.equals("mixed") || mode.equals("form-mixed"))) {
+ // A different query credential and token cannot relabel the header's caller.
+ request.queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
+ .queryParam("X-Amz-Credential", "999999999999/20261013/us-east-1/sts/aws4_request")
+ .queryParam("X-Amz-Security-Token", "wrong-query-token");
+ }
+ XmlPath identity = request.post("/").then().statusCode(200).extract().xmlPath();
+ String expectedArn = arn;
+ String expectedUserId = userId;
+ assertAll(() -> assertEquals(account, identity.getString("GetCallerIdentityResponse.GetCallerIdentityResult.Account")),
+ () -> assertEquals(expectedArn, identity.getString("GetCallerIdentityResponse.GetCallerIdentityResult.Arn")),
+ () -> assertEquals(expectedUserId, identity.getString("GetCallerIdentityResponse.GetCallerIdentityResult.UserId")));
+ }
+
+ private static String auth(String key, String region, String service) {
+ return EnforcementFixtures.auth(key, service).replace("us-east-1", region);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsPresignedSignatureIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsPresignedSignatureIntegrationTest.java
new file mode 100644
index 0000000000..8cccecb1a9
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsPresignedSignatureIntegrationTest.java
@@ -0,0 +1,340 @@
+package io.github.hectorvent.floci.services.iam;
+
+import io.github.hectorvent.floci.core.common.Digests;
+import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
+import io.github.hectorvent.floci.testutil.AwsRequestSigner;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.QuarkusTestProfile;
+import io.quarkus.test.junit.TestProfile;
+import io.restassured.RestAssured;
+import io.restassured.response.Response;
+import io.restassured.specification.RequestSpecification;
+import jakarta.inject.Inject;
+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.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+@QuarkusTest
+@TestProfile(StsPresignedSignatureIntegrationTest.SignaturesAndEnforcement.class)
+class StsPresignedSignatureIntegrationTest {
+ @Inject IamService iam;
+
+ public static class SignaturesAndEnforcement implements QuarkusTestProfile {
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ return Map.of("floci.auth.validate-signatures", "true",
+ "floci.services.iam.enforcement-enabled", "true");
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"valid", "forged", "missing", "expired", "scope", "body", "future", "date", "expiry", "algorithm", "host", "blank",
+ "alias", "url-shadow", "duplicate", "signature-first", "encoded", "unknown", "inactive"})
+ void queryIdentityRequiresAuthenticRequest(String mode) throws Exception {
+ String name = "presigned-auth-" + UUID.randomUUID();
+ Response user = root("CreateUser", "UserName=" + name);
+ user.then().statusCode(200);
+ String arn = user.xmlPath().getString("CreateUserResponse.CreateUserResult.User.Arn");
+ String id = user.xmlPath().getString("CreateUserResponse.CreateUserResult.User.UserId");
+ String key = null;
+ try {
+ Response created = root("CreateAccessKey", "UserName=" + name);
+ created.then().statusCode(200);
+ key = created.xmlPath().getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
+ String secret = created.xmlPath().getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey");
+ String body = ("alias".equals(mode) ? "Operation" : "Action") + "=GetCallerIdentity&Version=2011-06-15";
+ URI endpoint = URI.create("http://localhost:" + RestAssured.port + "/");
+ given().headers(AwsRequestSigner.signedAs(key, secret, "sts")
+ .headersFor("POST", endpoint, Map.of(), body.getBytes(StandardCharsets.UTF_8)))
+ .contentType("application/x-www-form-urlencoded").body(body).post("/")
+ .then().statusCode(200).body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(arn));
+ Instant time = "expired".equals(mode) ? Instant.now().minusSeconds(120)
+ : "future".equals(mode) ? Instant.now().plusSeconds(1800) : Instant.now();
+ String date = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC).format(time);
+ String service = "scope".equals(mode) ? "iam" : "sts";
+ String scope = ("date".equals(mode) ? "20000101" : date.substring(0, 8)) + "/us-east-1/" + service + "/aws4_request";
+ TreeMap<String, String> query = new TreeMap<>(Map.of("X-Amz-Algorithm", "AWS4-HMAC-SHA256",
+ "X-Amz-Credential", ("unknown".equals(mode) ? "AKIAUNKNOWN" : key) + "/" + scope, "X-Amz-Date", date, "X-Amz-Expires", "60",
+ "X-Amz-SignedHeaders", "host"));
+ if ("expiry".equals(mode)) {
+ query.put("X-Amz-Expires", "604801");
+ } else if ("algorithm".equals(mode)) {
+ query.put("X-Amz-Algorithm", "unsupported");
+ } else if ("host".equals(mode)) {
+ query.put("X-Amz-SignedHeaders", "content-type");
+ } else if ("url-shadow".equals(mode)) {
+ query.put("Action", "GetSessionToken");
+ } else if ("inactive".equals(mode)) {
+ root("UpdateAccessKey", "UserName=" + name + "&AccessKeyId=" + key + "&Status=Inactive")
+ .then().statusCode(200);
+ }
+ String encoded = query.entrySet().stream().map(e -> encode(e.getKey()) + "=" + encode(e.getValue()))
+ .collect(Collectors.joining("&"));
+ if ("duplicate".equals(mode)) {
+ encoded = encoded.replace("X-Amz-Date=", "X-Amz-Credential=zzzz&X-Amz-Date=");
+ }
+ String canonical = "POST\n/\n" + encoded + "\nhost:" + endpoint.getAuthority() + "\n\nhost\n"
+ + Digests.sha256Hex(body.getBytes(StandardCharsets.UTF_8));
+ String toSign = "AWS4-HMAC-SHA256\n" + date + "\n" + scope + "\n" + Digests.sha256Hex(canonical);
+ String signature = SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(
+ SigV4RequestValidator.deriveSigningKey(secret, date.substring(0, 8), "us-east-1", service), toSign));
+ if (!"missing".equals(mode)) {
+ encoded += "&X-Amz-Signature=" + ("forged".equals(mode) || "blank".equals(mode) || "alias".equals(mode)
+ || "url-shadow".equals(mode) || "signature-first".equals(mode) ? "0".repeat(64) : signature);
+ }
+ if ("signature-first".equals(mode)) {
+ encoded += "&X-Amz-Signature=" + signature;
+ } else if ("duplicate".equals(mode)) {
+ encoded += "&X-Amz-Signature=unused";
+ } else if ("encoded".equals(mode)) {
+ encoded = encoded.replace("X-Amz-Credential", "X-Amz-%43redential");
+ }
+ RequestSpecification request = given().urlEncodingEnabled(false);
+ if ("blank".equals(mode)) {
+ request.header("Authorization", " ");
+ }
+ Response response = request.contentType("application/x-www-form-urlencoded")
+ .body("body".equals(mode) ? body + "&Extra=changed" : body).post(endpoint + "?" + encoded);
+ if ("valid".equals(mode) || "duplicate".equals(mode) || "encoded".equals(mode)) {
+ response.then().statusCode(200).body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(arn))
+ .body("GetCallerIdentityResponse.GetCallerIdentityResult.UserId", equalTo(id));
+ } else {
+ boolean malformed = Set.of("missing", "expiry", "algorithm", "host").contains(mode);
+ String code = Set.of("unknown", "inactive").contains(mode) ? "InvalidClientTokenId"
+ : malformed ? "IncompleteSignature" : "SignatureDoesNotMatch";
+ response.then().statusCode(malformed ? 400 : 403).body("ErrorResponse.Error.Code", equalTo(code));
+ }
+ } finally {
+ try {
+ if (key != null) {
+ root("DeleteAccessKey", "UserName=" + name + "&AccessKeyId=" + key).then().statusCode(200);
+ }
+ } finally {
+ root("DeleteUser", "UserName=" + name).then().statusCode(200);
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"query", "missing", "wrong", "header-first", "form-first", "bad-header", "bad-form"})
+ void temporaryTokenSelectionMatchesIdentity(String mode) throws Exception {
+ Response issued = root("GetSessionToken", "DurationSeconds=900");
+ issued.then().statusCode(200);
+ String prefix = "GetSessionTokenResponse.GetSessionTokenResult.Credentials.";
+ String key = issued.xmlPath().getString(prefix + "AccessKeyId");
+ String secret = issued.xmlPath().getString(prefix + "SecretAccessKey");
+ String token = issued.xmlPath().getString(prefix + "SessionToken");
+ try {
+ String body = "Action=GetCallerIdentity&Version=2011-06-15";
+ Map<String, String> headers = new TreeMap<>();
+ TreeMap<String, String> query = new TreeMap<>();
+ if (!"missing".equals(mode)) {
+ query.put("X-Amz-Security-Token", Set.of("wrong", "header-first", "form-first").contains(mode)
+ ? "wrong" : token);
+ }
+ if ("header-first".equals(mode)) {
+ headers.put("X-Amz-Security-Token", token);
+ body += "&X-Amz-Security-Token=wrong";
+ } else if ("bad-header".equals(mode)) {
+ headers.put("X-Amz-Security-Token", "wrong");
+ } else if ("form-first".equals(mode) || "bad-form".equals(mode)) {
+ body += "&X-Amz-Security-Token=" + encode("form-first".equals(mode) ? token : "wrong");
+ }
+ URI uri = presign(key, secret, body, query);
+ Response response = given().headers(headers).urlEncodingEnabled(false)
+ .contentType("application/x-www-form-urlencoded").body(body).post(uri);
+ if (Set.of("query", "header-first", "form-first").contains(mode)) {
+ response.then().statusCode(200).body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn",
+ equalTo("arn:aws:iam::000000000000:root"));
+ } else {
+ response.then().statusCode(403).body("ErrorResponse.Error.Code", equalTo("InvalidClientTokenId"));
+ }
+ } finally {
+ iam.unregisterSession("000000000000", key);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void nonblankHeaderRemainsTheAuthenticationOwner(boolean forgedHeader) throws Exception {
+ String body = "Action=GetCallerIdentity";
+ URI valid = presign("test", "test", body, new TreeMap<>());
+ URI uri = forgedHeader ? valid : URI.create(valid.toString()
+ .replaceAll("X-Amz-Signature=[^&]*", "X-Amz-Signature=forged"));
+ Map<String, String> headers = AwsRequestSigner.signedAs("test", forgedHeader ? "wrong" : "test", "sts")
+ .headersFor("POST", uri, Map.of(), body.getBytes(StandardCharsets.UTF_8));
+ Response response = given().headers(headers).urlEncodingEnabled(false)
+ .contentType("application/x-www-form-urlencoded").body(body).post(uri);
+ response.then().statusCode(forgedHeader ? 403 : 200);
+ if (forgedHeader) {
+ response.then().body("ErrorResponse.Error.Code", equalTo("SignatureDoesNotMatch"));
+ } else {
+ response.then().body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn",
+ equalTo("arn:aws:iam::000000000000:root"));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"GetSessionToken", "GetFederationToken", "AssumeRole"})
+ void urlIdentityDoesNotChangeOtherBodyOperations(String action) {
+ // Query credentials must be authenticated for the operation that actually executes.
+ Response result = given().queryParam("Action", "GetCallerIdentity").queryParam("X-Amz-Credential", "test/20261013/us-east-1/sts/aws4_request")
+ .contentType("application/x-www-form-urlencoded").body("Action=" + action + "&Name=outside")
+ .post("/");
+ String key = result.xmlPath().getString(action + "Response." + action + "Result.Credentials.AccessKeyId");
+ try {
+ result.then().statusCode(400).body("ErrorResponse.Error.Code", equalTo("IncompleteSignature"));
+ } finally {
+ if (key != null) {
+ iam.unregisterSession("000000000000", key);
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void signedPayloadMarkerIsHonored(boolean signedMarker) throws Exception {
+ String body = "Action=GetCallerIdentity";
+ Map<String, String> headers = Map.of("x-amz-content-sha256", "UNSIGNED-PAYLOAD");
+ URI uri = presign("test", "test", body, new TreeMap<>(), signedMarker);
+ Response response = given().headers(headers).urlEncodingEnabled(false)
+ .contentType("application/x-www-form-urlencoded").body(body).post(uri);
+ response.then().statusCode(signedMarker ? 200 : 403);
+ if (!signedMarker) {
+ response.then().body("ErrorResponse.Error.Code", equalTo("SignatureDoesNotMatch"));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"GetSessionToken", "GetFederationToken", "AssumeRole"})
+ void querySignaturesProtectCredentialIssuance(String action) throws Exception {
+ String roleName = "presigned-issuance-" + UUID.randomUUID();
+ String body = "Action=" + action + "&Name=presigned&DurationSeconds=900";
+ if ("AssumeRole".equals(action)) {
+ Response role = root("CreateRole", "RoleName=" + roleName + "&AssumeRolePolicyDocument="
+ + encode("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":\"*\",\"Action\":\"sts:AssumeRole\"}]}"));
+ role.then().statusCode(200);
+ body += "&RoleArn=" + encode(role.xmlPath().getString("CreateRoleResponse.CreateRoleResult.Role.Arn"))
+ + "&RoleSessionName=presigned";
+ }
+ String issuedKey = null;
+ try {
+ URI valid = presign("test", "test", body, new TreeMap<>());
+ URI forged = URI.create(valid.toString().replaceAll("X-Amz-Signature=[^&]*", "X-Amz-Signature=forged"));
+ given().urlEncodingEnabled(false).contentType("application/x-www-form-urlencoded").body(body).post(forged)
+ .then().statusCode(403).body("ErrorResponse.Error.Code", equalTo("SignatureDoesNotMatch"));
+ Response issued = given().urlEncodingEnabled(false).contentType("application/x-www-form-urlencoded")
+ .body(body).post(valid);
+ issuedKey = issued.xmlPath().getString(action + "Response." + action + "Result.Credentials.AccessKeyId");
+ issued.then().statusCode(200);
+ assertNotNull(issuedKey);
+ } finally {
+ if (issuedKey != null) {
+ iam.unregisterSession("000000000000", issuedKey);
+ }
+ if ("AssumeRole".equals(action)) {
+ root("DeleteRole", "RoleName=" + roleName).then().statusCode(200);
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"json, false", "json, true", "rest, false", "rest, true", "query, false", "query, true"})
+ void sharedVerifierCoversOtherProtocols(String protocol, boolean forged) throws Exception {
+ String method = "rest".equals(protocol) ? "GET" : "POST";
+ String path = "rest".equals(protocol) ? "/schedule-groups" : "/";
+ String service = "rest".equals(protocol) ? "scheduler" : "query".equals(protocol) ? "iam" : "sqs";
+ String body = "rest".equals(protocol) ? "" : "query".equals(protocol) ? "Action=ListUsers&Version=2010-05-08" : "{}";
+ URI uri = presignRequest("test", forged ? "wrong" : "test", method, path, service, body,
+ new TreeMap<>(), null);
+ RequestSpecification request = given().urlEncodingEnabled(false);
+ if ("json".equals(protocol)) {
+ request.contentType("application/x-amz-json-1.0").header("X-Amz-Target", "AmazonSQS.ListQueues");
+ } else if ("query".equals(protocol)) {
+ request.contentType("application/x-www-form-urlencoded");
+ }
+ if (!"GET".equals(method)) {
+ if ("query".equals(protocol)) {
+ request.body(body);
+ } else {
+ request.body(body.getBytes(StandardCharsets.UTF_8));
+ }
+ }
+ Response response = request.request(method, uri);
+ response.then().statusCode(forged ? 403 : 200);
+ if (forged) {
+ if ("query".equals(protocol)) {
+ response.then().body("ErrorResponse.Error.Code", equalTo("SignatureDoesNotMatch"));
+ } else {
+ response.then().header("X-Amzn-Errortype", equalTo("InvalidSignatureException"));
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"bad%ZZ=x&Action=ListUsers", "Action=ListUsers&X-Amz-Security-Token=%"})
+ void malformedFormCannotEscapeAsServerError(String body) throws Exception {
+ URI uri = presignRequest("test", "test", "POST", "/", "iam", body, new TreeMap<>(), null);
+ given().urlEncodingEnabled(false).contentType("application/x-www-form-urlencoded").body(body).post(uri)
+ .then().statusCode(400);
+ }
+
+ private static URI presign(String key, String secret, String body, TreeMap<String, String> query) throws Exception {
+ return presign(key, secret, body, query, null);
+ }
+
+ private static URI presign(String key, String secret, String body, TreeMap<String, String> query,
+ Boolean signedMarker) throws Exception {
+ return presignRequest(key, secret, "POST", "/", "sts", body, query, signedMarker);
+ }
+
+ private static URI presignRequest(String key, String secret, String method, String path, String service,
+ String body, TreeMap<String, String> query, Boolean signedMarker) 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 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)
+ ? "host;x-amz-content-sha256" : "host"));
+ String encoded = query.entrySet().stream().map(e -> encode(e.getKey()) + "=" + encode(e.getValue()))
+ .collect(Collectors.joining("&"));
+ String signedHeaders = query.get("X-Amz-SignedHeaders");
+ String canonical = method + "\n" + path + "\n" + encoded + "\nhost:" + endpoint.getAuthority() + "\n"
+ + (Boolean.TRUE.equals(signedMarker) ? "x-amz-content-sha256:UNSIGNED-PAYLOAD\n" : "")
+ + "\n" + signedHeaders + "\n"
+ + (signedMarker != null ? "UNSIGNED-PAYLOAD" : Digests.sha256Hex(body.getBytes(StandardCharsets.UTF_8)));
+ String toSign = "AWS4-HMAC-SHA256\n" + date + "\n" + scope + "\n" + Digests.sha256Hex(canonical);
+ String signature = SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(
+ SigV4RequestValidator.deriveSigningKey(secret, date.substring(0, 8), "us-east-1", service), toSign));
+ return URI.create(endpoint + "?" + encoded + "&X-Amz-Signature=" + signature);
+ }
+
+ private static String encode(String value) {
+ return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
+ }
+
+ private static Response root(String action, String parameters) throws Exception {
+ String body = "Action=" + action + "&" + parameters;
+ URI uri = URI.create("http://localhost:" + RestAssured.port + "/");
+ return given().headers(AwsRequestSigner.signedAs("test", "test", "GetSessionToken".equals(action) ? "sts" : "iam")
+ .headersFor("POST", uri, Map.of(), body.getBytes(StandardCharsets.UTF_8)))
+ .contentType("application/x-www-form-urlencoded").body(body).post("/");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/StsSessionTokenCallerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/StsSessionTokenCallerIntegrationTest.java
index 8c2ba07318..97dcea5344 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/StsSessionTokenCallerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/StsSessionTokenCallerIntegrationTest.java
@@ -109,7 +109,7 @@ class StsSessionTokenCallerIntegrationTest {
void blankAuthorizationDoesNotHideTemporaryQueryCredentials(String authorization) throws Exception {
Credentials user = createUser();
Credentials issued = credentials(request(user, "sts", "GetSessionToken", Map.of()), "GetSessionToken");
- Response result = querySessionRequest(authorization, issued).post("/");
+ Response result = querySessionRequest(authorization, issued);
remember(result, "GetSessionToken");
result.then().statusCode(403).body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
}
@@ -120,22 +120,24 @@ class StsSessionTokenCallerIntegrationTest {
Credentials user = createUser();
String expected = request(user, "sts", "GetCallerIdentity", Map.of()).then().statusCode(200)
.extract().path("GetCallerIdentityResponse.GetCallerIdentityResult.Arn");
- Credentials issued = credentials(querySessionRequest(authorization, user).post("/"), "GetSessionToken");
+ Credentials issued = credentials(querySessionRequest(authorization, user), "GetSessionToken");
request(issued, "sts", "GetCallerIdentity", Map.of()).then().statusCode(200)
.body("GetCallerIdentityResponse.GetCallerIdentityResult.Arn", equalTo(expected));
}
- private RequestSpecification querySessionRequest(String authorization, Credentials caller) {
- RequestSpecification request = given().queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
- .queryParam("X-Amz-Credential", caller.key() + "/20261013/us-east-1/sts/aws4_request")
- .contentType("application/x-www-form-urlencoded").body("Action=GetSessionToken");
- if (caller.token() != null) {
- request.queryParam("X-Amz-Security-Token", caller.token());
- }
+ private Response querySessionRequest(String authorization, Credentials caller) throws Exception {
+ String body = "Action=GetSessionToken";
+ URI endpoint = URI.create("http://localhost:" + RestAssured.port + "/");
+ Map<String, String> query = caller.token() == null ? Map.of()
+ : Map.of("X-Amz-Security-Token", caller.token());
+ URI signed = AwsRequestSigner.signedAs(caller.key(), caller.secret(), "sts")
+ .presignedUri("POST", endpoint, query, body.getBytes(StandardCharsets.UTF_8));
+ RequestSpecification request = given().urlEncodingEnabled(false)
+ .contentType("application/x-www-form-urlencoded").body(body);
if (!"absent".equals(authorization)) {
request.header("Authorization", authorization);
}
- return request;
+ return request.post(signed);
}
private Credentials createUser() throws Exception {
diff --git a/src/test/java/io/github/hectorvent/floci/testutil/AwsRequestSigner.java b/src/test/java/io/github/hectorvent/floci/testutil/AwsRequestSigner.java
index 931e71a968..47d71811e1 100644
--- a/src/test/java/io/github/hectorvent/floci/testutil/AwsRequestSigner.java
+++ b/src/test/java/io/github/hectorvent/floci/testutil/AwsRequestSigner.java
@@ -142,6 +142,24 @@ public final class AwsRequestSigner implements Filter {
return result;
}
+ /** 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";
+ 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"));
+ String encoded = query.entrySet().stream()
+ .map(e -> S3RequestSigner.uriEncode(e.getKey()) + "=" + S3RequestSigner.uriEncode(e.getValue()))
+ .collect(Collectors.joining("&"));
+ String canonical = method + "\n" + doubleEncodedPath(uri.getRawPath()) + "\n" + encoded
+ + "\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));
+ return URI.create(uri + "?" + encoded + "&X-Amz-Signature=" + signature);
+ }
+
private static String doubleEncodedPath(String rawPath) {
String path = rawPath == null || rawPath.isEmpty() ? "/" : rawPath;
String[] segments = path.split("/", -1);