fix(ec2): return modeled authentication error envelopes (#7613)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-05 15:36:40 -04:00
1 parent f2debe4ce0
commit d34c8443cd
11 files changed
+285 -31

No files matched your search

@@ -0,0 +1,32 @@
package io.github.hectorvent.floci.core.common;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.UUID;
/** EC2's error envelope differs from the other Query services. */
public final class Ec2ErrorResponses {
private Ec2ErrorResponses() {
}
public static Response authFailure() {
return of("AuthFailure", "AWS was not able to validate the provided access credentials", 401);
}
public static Response of(String code, String message, int status) {
String xml = new XmlBuilder()
.start("Response")
.start("Errors")
.start("Error")
.elem("Code", code)
.elem("Message", message)
.end("Error")
.end("Errors")
.elem("RequestID", UUID.randomUUID().toString())
.end("Response")
.build();
return Response.status(status).entity(xml).type(MediaType.APPLICATION_XML).build();
}
}
@@ -1920,6 +1920,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private static Response accessDeniedResponse(String action, String credentialScope, MediaType requestMediaType,
String resourceArn, WireProtocol protocol, boolean restXml) {
String message = accessDeniedMessage(action);
if ("ec2".equals(credentialScope)) {
return Ec2ErrorResponses.of("UnauthorizedOperation",
"You are not authorized to perform this operation. " + message, 403);
}
if ("s3".equals(credentialScope)) {
String resourcePath = formatS3ResourcePath(resourceArn);
return s3XmlAccessDenied(message, resourcePath);
@@ -2031,7 +2035,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
/**
* The response for an access key that exists nowhere, in each protocol's own vocabulary for
* the same failure. S3 answers with {@code InvalidAccessKeyId}, as
* {@code S3HeaderSignatureFilter} already does. Query services answer with
* {@code S3HeaderSignatureFilter} already does. EC2 answers {@code AuthFailure}
* in its own error envelope. Other Query services answer with
* {@code InvalidClientTokenId}: neither code is modelled by sts, iam or sqs, but botocore's
* own integration tests retry on {@code InvalidClientTokenId} from {@code sts:AssumeRole} and
* {@code iam:ListGroups} while credentials propagate. JSON services answer with
@@ -2039,6 +2044,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
* and what the API Gateway execute path already returns.
*/
static Response unrecognizedClientResponse(String credentialScope, ContainerRequestContext ctx) {
if ("ec2".equals(credentialScope)) {
return Ec2ErrorResponses.authFailure();
}
if ("s3".equals(credentialScope)) {
return s3XmlError("InvalidAccessKeyId", S3_INVALID_ACCESS_KEY_ID, 403);
}
@@ -88,7 +88,8 @@ import java.util.function.UnaryOperator;
* everything else JSON, which REST-JSON clients read through {@code X-Amzn-Errortype}. The codes
* are AWS's: {@code IncompleteSignature} for a header that cannot be checked,
* {@code InvalidClientTokenId} / {@code UnrecognizedClientException} for an access key Floci does
* not know, and {@code SignatureDoesNotMatch} / {@code InvalidSignatureException} for a signature
* not know (EC2 instead answers {@code AuthFailure} in its own envelope), and
* {@code SignatureDoesNotMatch} / {@code InvalidSignatureException} for a signature
* that does not verify, exceeds its query expiry or falls outside the header clock-skew window.
*
* <p>Nothing here runs with the flag off: the filter returns before reading a single header.
@@ -234,6 +235,10 @@ public class SigV4HeaderSignatureFilter implements ContainerRequestFilter {
if (secretKey.isEmpty()) {
LOG.debugv("Refusing {0} request signed with unknown access key {1}",
scope.service(), SigV4RequestValidator.sanitizeForLog(scope.accessKeyId()));
if (resource == AwsQueryController.class && "ec2".equals(scope.service())) {
ctx.abortWith(Ec2ErrorResponses.authFailure());
return;
}
abort(ctx, resource, 403, "InvalidClientTokenId", "UnrecognizedClientException", INVALID_TOKEN_MESSAGE);
return;
}
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsPartition;
import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.AwsRegionFacts;
import io.github.hectorvent.floci.core.common.Ec2ErrorResponses;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.SshPublicKeys;
@@ -378,34 +379,14 @@ public class Ec2QueryHandler {
case "AllocateIpamPoolCidr" -> handleAllocateIpamPoolCidr(params, region);
case "ReleaseIpamPoolAllocation" -> handleReleaseIpamPoolAllocation(params, region);
case "GetIpamPoolAllocations" -> handleGetIpamPoolAllocations(params, region);
default -> ec2Error("UnsupportedOperation",
default -> Ec2ErrorResponses.of("UnsupportedOperation",
"Operation " + action + " is not supported.", 400);
};
} catch (AwsException e) {
return ec2Error(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
return Ec2ErrorResponses.of(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
}
/**
* EC2 uses a different error envelope than other Query-protocol services.
* The AWS SDK v2 EC2 client parses {@code <Response><Errors><Error><Code>},
* not the standard {@code <ErrorResponse><Error><Code>} shape.
*/
private Response ec2Error(String code, String message, int status) {
String xml = new XmlBuilder()
.start("Response")
.start("Errors")
.start("Error")
.elem("Code", code)
.elem("Message", message)
.end("Error")
.end("Errors")
.elem("RequestID", UUID.randomUUID().toString())
.end("Response")
.build();
return Response.status(status).entity(xml).type(MediaType.APPLICATION_XML).build();
}
// ─── Parameter helpers ────────────────────────────────────────────────────
private String firstPresent(MultivaluedMap<String, String> p, String first, String second) {
@@ -1963,7 +1944,7 @@ public class Ec2QueryHandler {
// Apply filters
services = applyVpcEndpointServiceFilters(services, filters);
} catch (AwsException e) {
return ec2Error(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
return Ec2ErrorResponses.of(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
XmlBuilder xml = new XmlBuilder()
@@ -2158,7 +2139,7 @@ public class Ec2QueryHandler {
resourceIds = getList(p, "ResourceIds.member");
}
if (resourceIds.isEmpty()) {
return ec2Error("MissingParameter", "The request must contain at least one ResourceId.", 400);
return Ec2ErrorResponses.of("MissingParameter", "The request must contain at least one ResourceId.", 400);
}
XmlBuilder xml = new XmlBuilder()
@@ -0,0 +1,35 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
import java.net.URI;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
final class Ec2ErrorAssertions {
private Ec2ErrorAssertions() {
}
static void assertGetError(AwsRequestSigner signer, URI endpoint, boolean presigned,
int expectedStatus, String expectedCode, String expectedMessage) throws Exception {
Map<String, String> query = Map.of("Action", "DescribeVpcs", "Version", "2016-11-15");
if (presigned) {
given().urlEncodingEnabled(false)
.get(signer.presignedUri("GET", endpoint, query, new byte[0])).then()
.statusCode(expectedStatus).body("Response.Errors.Error.Code", equalTo(expectedCode))
.body("Response.Errors.Error.Message", startsWith(expectedMessage))
.body("Response.RequestID", not(emptyOrNullString()));
} else {
given().filter(signer).queryParams(query).get(endpoint).then()
.statusCode(expectedStatus).body("Response.Errors.Error.Code", equalTo(expectedCode))
.body("Response.Errors.Error.Message", startsWith(expectedMessage))
.body("Response.RequestID", not(emptyOrNullString()));
}
}
}
@@ -0,0 +1,96 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.EnforcementFixtures.UserCredentials;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.http.apache5.Apache5HttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import java.net.URI;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class Ec2IamErrorIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void sdkParsesDenialAndAllowsTheSameUserAfterPermissionIsGranted() {
String name = "ec2-denial-" + UUID.randomUUID();
UserCredentials credentials = user(name);
try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(),
credentials.accessKeyId(), credentials.secretAccessKey(), Region.US_EAST_1, endpoint)) {
Ec2Exception denied = assertThrows(Ec2Exception.class, client::describeVpcs);
assertEquals(403, denied.statusCode());
assertEquals("UnauthorizedOperation", denied.awsErrorDetails().errorCode());
assertTrue(denied.awsErrorDetails().errorMessage()
.startsWith("You are not authorized to perform this operation."));
assertNotNull(denied.requestId());
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), name,
"describe", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"ec2:DescribeVpcs","Resource":"*"}
]}
""");
assertNotNull(client.describeVpcs().vpcs());
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void signedAndPresignedGetDenialsUseEc2Envelope(boolean presigned) throws Exception {
UserCredentials credentials = user("ec2-get-denial-" + UUID.randomUUID());
AwsRequestSigner signer = AwsRequestSigner.signedAs(
credentials.accessKeyId(), credentials.secretAccessKey(), "ec2");
Ec2ErrorAssertions.assertGetError(signer, endpoint, presigned, 403, "UnauthorizedOperation",
"You are not authorized to perform this operation.");
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void unknownKeysOnSignedAndPresignedGetUseEc2AuthenticationError(boolean presigned) throws Exception {
AwsRequestSigner signer = AwsRequestSigner.signedAs("AKIAUNKNOWNACCESSKEY", "some-secret", "ec2");
Ec2ErrorAssertions.assertGetError(signer, endpoint, presigned, 401, "AuthFailure",
"AWS was not able to validate the provided access credentials");
}
private UserCredentials user(String name) {
return EnforcementFixtures.createUser(cleanup, endpoint.getPort(), auth("000000000000", "iam"), name);
}
@Test
void sdkParsesAnUnknownAccessKeyWithIamEnforcement() {
try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(),
"AKIAUNKNOWNACCESSKEY", "some-secret", Region.US_EAST_1, Apache5HttpClient.builder(), endpoint)) {
Ec2Exception denied = assertThrows(Ec2Exception.class, client::describeVpcs);
assertEquals(401, denied.statusCode());
assertEquals("AuthFailure", denied.awsErrorDetails().errorCode());
assertEquals("AWS was not able to validate the provided access credentials",
denied.awsErrorDetails().errorMessage());
assertNotNull(denied.requestId());
}
}
}
@@ -0,0 +1,60 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.ValidateSignaturesProfile;
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.http.apache5.Apache5HttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import java.net.URI;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
@TestProfile(ValidateSignaturesProfile.class)
class Ec2SignatureErrorIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@Test
void sdkParsesAnUnknownAccessKeyWithSignatureValidation() {
try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(),
"AKIAUNKNOWNACCESSKEY", "some-secret", Region.US_EAST_1, Apache5HttpClient.builder(), endpoint)) {
Ec2Exception denied = assertThrows(Ec2Exception.class, client::describeVpcs);
assertEquals(401, denied.statusCode());
assertEquals("AuthFailure", denied.awsErrorDetails().errorCode());
assertEquals("AWS was not able to validate the provided access credentials",
denied.awsErrorDetails().errorMessage());
assertNotNull(denied.requestId());
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void unknownKeysOnSignedAndPresignedGetUseEc2Envelope(boolean presigned) throws Exception {
AwsRequestSigner signer = AwsRequestSigner.signedAs("AKIAUNKNOWNACCESSKEY", "some-secret", "ec2");
Ec2ErrorAssertions.assertGetError(signer, endpoint, presigned, 401, "AuthFailure",
"AWS was not able to validate the provided access credentials");
}
@Test
void anEc2SigningScopeDoesNotChangeRestJsonErrors() {
given().filter(AwsRequestSigner.signedAs("AKIAUNKNOWNACCESSKEY", "some-secret", "ec2"))
.get("/2015-03-31/functions").then()
.statusCode(403).contentType("application/json")
.body("__type", equalTo("UnrecognizedClientException"));
}
}
@@ -2249,7 +2249,7 @@ class IamEnforcementFilterTest {
@Test
void queryProtocolGetsXmlErrorResponse() {
// IAM/STS/EC2/SQS/SNS/RDS/ELBv2/CFN/... — Query protocol, form-encoded body, XML response.
// Ordinary Query services retain ErrorResponse; EC2 uses its own envelope.
Response r = IamEnforcementFilter.accessDeniedResponse(
"iam:ListUsers", "iam", MediaType.APPLICATION_FORM_URLENCODED_TYPE);
@@ -2263,6 +2263,41 @@ class IamEnforcementFilterTest {
assertTrue(body.contains("<RequestId>"), body);
}
@ParameterizedTest
@CsvSource({"ec2,ec2:DescribeVpcs,UnauthorizedOperation", "iam,iam:ListUsers,AccessDenied",
"sts,sts:AssumeRole,AccessDenied", "sns,sns:ListTopics,AuthorizationError"})
void queryDenialsUseTheServiceErrorEnvelope(String scope, String action, String code) {
Response response = IamEnforcementFilter.accessDeniedResponse(
action, scope, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
String body = entityString(response);
assertEquals(403, response.getStatus());
assertEquals(MediaType.APPLICATION_XML_TYPE, response.getMediaType());
assertTrue(body.contains("<Code>" + code + "</Code>"), body);
if ("ec2".equals(scope)) {
assertTrue(body.contains("<Response><Errors><Error>"), body);
assertTrue(body.contains("<Message>You are not authorized to perform this operation."), body);
assertTrue(body.contains("<RequestID>"), body);
} else {
assertTrue(body.contains("<ErrorResponse><Error>"), body);
assertTrue(body.contains("<RequestId>"), body);
}
}
@ParameterizedTest
@CsvSource({"ec2,AuthFailure", "iam,InvalidClientTokenId", "sts,InvalidClientTokenId"})
void unknownQueryAccessKeysUseTheServiceErrorEnvelope(String scope, String code) {
ContainerRequestContext context = mock(ContainerRequestContext.class);
when(context.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
Response response = IamEnforcementFilter.unrecognizedClientResponse(scope, context);
String body = entityString(response);
assertEquals("ec2".equals(scope) ? 401 : 403, response.getStatus());
assertTrue(body.contains("ec2".equals(scope)
? "AWS was not able to validate the provided access credentials"
: "The security token included in the request is invalid"), body);
assertTrue(body.contains("<Code>" + code + "</Code>"), body);
assertTrue(body.contains("ec2".equals(scope) ? "<RequestID>" : "<RequestId>"), body);
}
@ParameterizedTest
@CsvSource({"REST_XML, application/xml", "REST_JSON, application/json"})
void restDenialUsesTheServiceCatalogProtocol(ServiceProtocol serviceProtocol, String expectedContentType) {
@@ -63,7 +63,7 @@ class Ec2CreateRouteDryRunIntegrationTest {
Ec2Exception error = assertThrows(Ec2Exception.class, () -> caller.createRoute(fixture.request()
.gatewayId(fixture.gatewayId).dryRun(true).build()));
assertEquals(403, error.statusCode());
assertTrue(error.awsErrorDetails().rawResponse().asUtf8String().contains("<Code>AccessDenied</Code>"));
assertEquals("UnauthorizedOperation", error.awsErrorDetails().errorCode());
}
assertEquals(before, fixture.routes());
}
@@ -106,7 +106,7 @@ class Ec2CreateRouteDryRunIntegrationTest {
.then().statusCode(200);
Ec2Exception denied = assertThrows(Ec2Exception.class, () -> caller.createRoute(request));
assertEquals(403, denied.statusCode());
assertTrue(denied.awsErrorDetails().rawResponse().asUtf8String().contains("<Code>AccessDenied</Code>"));
assertEquals("UnauthorizedOperation", denied.awsErrorDetails().errorCode());
assertEquals(before, fixture.routes());
}
}
@@ -48,7 +48,8 @@ class IamTagKeysEnforcementIntegrationTest {
.formParam("Action", "CreateTags").formParam("ResourceId.1", id)
.formParam("Tag.1.Key", "Team").formParam("Tag.1.Value", "payments")
.formParam("Tag.2.Key", "Admin").formParam("Tag.2.Value", "true")
.post("/").then().statusCode(403).body(containsString("AccessDenied"));
.post("/").then().statusCode(403)
.body("Response.Errors.Error.Code", equalTo("UnauthorizedOperation"));
}
@Test
@@ -49,7 +49,8 @@ public final class AwsTestClients {
return create(builder, account, "test", region, httpClientBuilder, endpoint);
}
private static <B extends AwsClientBuilder<B, C> & AwsSyncClientBuilder<B, C>, C> C create(
/** Explicit credentials and transport for status codes whose bodies URLConnection cannot read. */
public static <B extends AwsClientBuilder<B, C> & AwsSyncClientBuilder<B, C>, C> C create(
B builder, String accessKey, String secretKey, Region region,
SdkHttpClient.Builder<?> httpClientBuilder, URI endpoint) {
return builder.endpointOverride(endpoint)