From a453b4b252eeec2a93c7cdcbebc0c0e188801aec Mon Sep 17 00:00:00 2001 From: Sewci0 Date: Fri, 1 May 2026 06:48:09 +0800 Subject: [PATCH] fix: protocol-aware Access Denied response in IamEnforcementFilter (#657) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The deny path returned a JSON AccessDeniedException body for every request, including Query-protocol services (IAM, STS, EC2, SQS, SNS, RDS, ELBv2, CloudFormation, CloudWatch, ...) and S3, both of which speak XML. AWS SDKs hard-fail when an XML parser sees a leading "{", so the deny payload was unreadable for those clients — the AWS CLI prints "invalid XML received" and SDK error types are lost. Pick the response shape from request signals: - credentialScope == "s3" -> S3 XML - form-encoded body -> AWS Query XML - everything else -> historical JSON shape (DynamoDB, Lambda, Kinesis, KMS, REST-JSON services) Status code stays 403 across all protocols; the message string is unchanged, so downstream parsers that key off "not authorized to perform: " keep working. Closes #656 --- .../core/common/IamEnforcementFilter.java | 66 +++++++++- .../core/common/IamEnforcementFilterTest.java | 121 ++++++++++++++++++ 2 files changed, 181 insertions(+), 6 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index 1c8e7aedf0..5ccc31c6c1 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -16,6 +16,7 @@ import jakarta.ws.rs.ext.Provider; import org.jboss.logging.Logger; import java.util.List; +import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -105,7 +106,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { Decision decision = evaluator.evaluate(policies, action, resource); if (decision == Decision.DENY) { LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource); - ctx.abortWith(accessDeniedResponse(action)); + ctx.abortWith(accessDeniedResponse(action, credentialScope, ctx.getMediaType())); } } @@ -119,12 +120,65 @@ public class IamEnforcementFilter implements ContainerRequestFilter { return m.find() ? m.group(1) : null; } - private Response accessDeniedResponse(String action) { + /** + * Builds a 403 Access Denied response in the wire format the calling SDK + * expects. AWS SDKs hard-fail when they receive the wrong shape: an XML + * parser blows up on a leading {@code {}, and a JSON parser blows up on + * {@code <}. Pick the shape from request signals: + * + *
    + *
  • S3 → S3-flavored XML {@code ...}
  • + *
  • {@code application/x-www-form-urlencoded} body → AWS Query + * {@code ...} (IAM/STS/EC2/SQS/SNS/...)
  • + *
  • everything else (JSON 1.x, REST-JSON) → keep the historical JSON shape
  • + *
+ */ + // Package-private for unit testing. + static Response accessDeniedResponse(String action, String credentialScope, MediaType requestMediaType) { String message = "User is not authorized to perform: " + action; - String body = "{\"__type\":\"AccessDeniedException\",\"message\":\"" + message + "\"}"; - return Response.status(403) - .type(MediaType.APPLICATION_JSON) - .entity(body) + if ("s3".equals(credentialScope)) { + return s3XmlAccessDenied(message); + } + if (isFormEncoded(requestMediaType)) { + return queryXmlAccessDenied(message); + } + return jsonAccessDenied(message); + } + + private static boolean isFormEncoded(MediaType mt) { + return mt != null + && "application".equalsIgnoreCase(mt.getType()) + && "x-www-form-urlencoded".equalsIgnoreCase(mt.getSubtype()); + } + + private static Response queryXmlAccessDenied(String message) { + String xml = new XmlBuilder() + .start("ErrorResponse") + .start("Error") + .elem("Type", "Sender") + .elem("Code", "AccessDenied") + .elem("Message", message) + .end("Error") + .elem("RequestId", UUID.randomUUID().toString()) + .end("ErrorResponse") .build(); + return Response.status(403).type(MediaType.APPLICATION_XML).entity(xml).build(); + } + + private static Response s3XmlAccessDenied(String message) { + String xml = new XmlBuilder() + .raw("") + .start("Error") + .elem("Code", "AccessDenied") + .elem("Message", message) + .elem("RequestId", UUID.randomUUID().toString()) + .end("Error") + .build(); + return Response.status(403).type(MediaType.APPLICATION_XML).entity(xml).build(); + } + + private static Response jsonAccessDenied(String message) { + String body = "{\"__type\":\"AccessDeniedException\",\"message\":\"" + message + "\"}"; + return Response.status(403).type(MediaType.APPLICATION_JSON).entity(body).build(); } } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java new file mode 100644 index 0000000000..e052cd5b97 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java @@ -0,0 +1,121 @@ +package io.github.hectorvent.floci.core.common; + +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit tests for {@link IamEnforcementFilter#accessDeniedResponse}, focused on + * the protocol-aware response shape. AWS SDKs hard-fail on wrong-shape error + * payloads — an XML parser blows up on a leading {@code "{"} and a JSON parser + * blows up on a leading {@code "<"} — so each protocol has to get the right + * envelope. + */ +class IamEnforcementFilterTest { + + @Test + void queryProtocolGetsXmlErrorResponse() { + // IAM/STS/EC2/SQS/SNS/RDS/ELBv2/CFN/... — Query protocol, form-encoded body, XML response. + Response r = IamEnforcementFilter.accessDeniedResponse( + "iam:ListUsers", "iam", MediaType.APPLICATION_FORM_URLENCODED_TYPE); + + assertEquals(403, r.getStatus()); + assertEquals(MediaType.APPLICATION_XML_TYPE, r.getMediaType()); + String body = entityString(r); + assertTrue(body.contains(""), body); + assertTrue(body.contains("AccessDenied"), body); + assertTrue(body.contains("Sender"), body); + assertTrue(body.contains("User is not authorized to perform: iam:ListUsers"), body); + assertTrue(body.contains(""), body); + } + + @Test + void s3GetsS3FlavoredXmlError() { + // S3 — credential-scope is "s3"; S3 errors are ... at the root, no wrapper. + Response r = IamEnforcementFilter.accessDeniedResponse( + "s3:GetObject", "s3", null); + + assertEquals(403, r.getStatus()); + assertEquals(MediaType.APPLICATION_XML_TYPE, r.getMediaType()); + String body = entityString(r); + assertTrue(body.startsWith(""), body); + assertTrue(body.contains("AccessDenied"), body); + assertTrue(body.contains("User is not authorized to perform: s3:GetObject"), body); + // S3 errors do not have the Query Sender envelope. + assertTrue(!body.contains(""), body); + } + + @Test + void jsonProtocolGetsJsonErrorResponse() { + // DynamoDB / Cognito / Kinesis / ... — JSON 1.0/1.1, JSON error response. + Response r = IamEnforcementFilter.accessDeniedResponse( + "dynamodb:PutItem", "dynamodb", MediaType.valueOf("application/x-amz-json-1.0")); + + assertEquals(403, r.getStatus()); + assertEquals(MediaType.APPLICATION_JSON_TYPE, r.getMediaType()); + String body = entityString(r); + assertTrue(body.contains("\"__type\":\"AccessDeniedException\""), body); + assertTrue(body.contains("User is not authorized to perform: dynamodb:PutItem"), body); + } + + @Test + void restJsonProtocolGetsJsonErrorResponse() { + // Lambda / API Gateway — REST-JSON. + Response r = IamEnforcementFilter.accessDeniedResponse( + "lambda:InvokeFunction", "lambda", MediaType.APPLICATION_JSON_TYPE); + + assertEquals(403, r.getStatus()); + assertEquals(MediaType.APPLICATION_JSON_TYPE, r.getMediaType()); + String body = entityString(r); + assertTrue(body.contains("\"__type\":\"AccessDeniedException\""), body); + } + + @Test + void formEncodedTakesPrecedenceOverNonS3Service() { + // Even if the credentialScope isn't recognized, a form-encoded body + // means we're talking to a Query-protocol service — XML response. + Response r = IamEnforcementFilter.accessDeniedResponse( + "rds:CreateDBInstance", "rds", MediaType.APPLICATION_FORM_URLENCODED_TYPE); + + assertEquals(MediaType.APPLICATION_XML_TYPE, r.getMediaType()); + assertTrue(entityString(r).contains("")); + } + + @Test + void s3WithFormEncodedBodyStillGetsS3XmlShape() { + // S3 presigned POST uploads use multipart/form-data, not x-www-form-urlencoded, + // but if a form-encoded body ever does land here, the s3 scope must still win. + Response r = IamEnforcementFilter.accessDeniedResponse( + "s3:PutObject", "s3", MediaType.APPLICATION_FORM_URLENCODED_TYPE); + + String body = entityString(r); + assertTrue(body.contains("")); + assertTrue(!body.contains("")); + } + + @Test + void unknownContentTypeFallsBackToJson() { + // No Content-Type at all — most likely a GET against a REST-JSON service. + Response r = IamEnforcementFilter.accessDeniedResponse( + "kms:Decrypt", "kms", null); + + assertEquals(MediaType.APPLICATION_JSON_TYPE, r.getMediaType()); + assertTrue(entityString(r).contains("\"__type\":\"AccessDeniedException\"")); + } + + private static String entityString(Response r) { + Object entity = r.getEntity(); + assertNotNull(entity, "response body should not be null"); + if (entity instanceof byte[] b) { + return new String(b, StandardCharsets.UTF_8); + } + return entity.toString(); + } +}