Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(iam): default UserName to the calling access key's owner (#1801)

Hector Venturaeb2fa9c25fe9
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
index 6030aa4fe2..9185cedb73 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
@@ -257,10 +257,30 @@ public class AwsQueryController {
String region = regionResolver.resolveRegion(httpHeaders);
+ try {
+ return dispatchToHandler(service, action, formParams, authorization, region);
+ } catch (AwsException e) {
+ // Handlers that don't render their own error XML would otherwise reach
+ // AwsExceptionMapper, which emits JSON — the same JSON-on-the-XML-wire defect.
+ // The declared code and status must survive; only the encoding changes.
+ return xmlErrorResponse(e.getErrorCode(), e.getMessage(), e.getHttpStatus(),
+ e.getHttpStatus() >= 500 ? "Receiver" : "Sender");
+ } catch (Exception e) {
+ // A handler bug (e.g. an NPE) must never leak Quarkus's JSON error page onto
+ // the Query/XML wire — SDK parsers fail before they can surface anything useful.
+ LOG.errorv(e, "Unhandled error dispatching Query action {0} for service {1}", action, service);
+ return xmlErrorResponse("InternalFailure",
+ "Unexpected error: " + e.getMessage(), 500, "Receiver");
+ }
+ }
+
+ private Response dispatchToHandler(String service, String action,
+ MultivaluedMap<String, String> formParams,
+ String authorization, String region) {
return switch (service) {
case "sqs" -> sqsQueryHandler.handle(action, formParams, region);
case "sns" -> snsQueryHandler.handle(action, formParams, region);
- case "iam" -> iamQueryHandler.handle(action, formParams);
+ case "iam" -> iamQueryHandler.handle(action, formParams, authorization);
case "sts" -> stsQueryHandler.handle(action, formParams);
case "elasticache" -> elastiCacheQueryHandler.handle(action, formParams);
case "rds" -> {
@@ -456,10 +476,14 @@ public class AwsQueryController {
}
private Response xmlErrorResponse(String code, String message, int status) {
+ return xmlErrorResponse(code, message, status, "Sender");
+ }
+
+ private Response xmlErrorResponse(String code, String message, int status, String type) {
String xml = new XmlBuilder()
.start("ErrorResponse")
.start("Error")
- .elem("Type", "Sender")
+ .elem("Type", type)
.elem("Code", code)
.elem("Message", message)
.end("Error")
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
index 7088d73e3e..b2d9d9ada2 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
@@ -35,21 +35,24 @@ public class IamQueryHandler {
private final IamService iamService;
private final IamPolicyEvaluator policyEvaluator;
+ private final AccountResolver accountResolver;
@Inject
- public IamQueryHandler(IamService iamService, IamPolicyEvaluator policyEvaluator) {
+ public IamQueryHandler(IamService iamService, IamPolicyEvaluator policyEvaluator,
+ AccountResolver accountResolver) {
this.iamService = iamService;
this.policyEvaluator = policyEvaluator;
+ this.accountResolver = accountResolver;
}
- public Response handle(String action, MultivaluedMap<String, String> params) {
+ public Response handle(String action, MultivaluedMap<String, String> params, String authorization) {
LOG.debugv("IAM action: {0}", action);
try {
return switch (action) {
// Users
case "CreateUser" -> handleCreateUser(params);
- case "GetUser" -> handleGetUser(params);
+ case "GetUser" -> handleGetUser(params, authorization);
case "DeleteUser" -> handleDeleteUser(params);
case "ListUsers" -> handleListUsers(params);
case "UpdateUser" -> handleUpdateUser(params);
@@ -133,8 +136,8 @@ public class IamQueryHandler {
// Access Keys
case "CreateAccessKey" -> handleCreateAccessKey(params);
- case "DeleteAccessKey" -> handleDeleteAccessKey(params);
- case "ListAccessKeys" -> handleListAccessKeys(params);
+ case "DeleteAccessKey" -> handleDeleteAccessKey(params, authorization);
+ case "ListAccessKeys" -> handleListAccessKeys(params, authorization);
case "UpdateAccessKey" -> handleUpdateAccessKey(params);
case "GetAccessKeyLastUsed" -> handleGetAccessKeyLastUsed(params);
@@ -179,9 +182,28 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("CreateUser", AwsNamespaces.IAM, result)).build();
}
- private Response handleGetUser(MultivaluedMap<String, String> params) {
+ // UserName is optional on GetUser/ListAccessKeys/DeleteAccessKey: real AWS determines
+ // it implicitly from the access key that signed the request. Mirrors moto: an access
+ // key that maps to no stored IAM user is the documented NoSuchEntity error.
+ private String resolveUserName(MultivaluedMap<String, String> params, String authorization) {
String userName = getParam(params, "UserName");
- IamUser user = iamService.getUser(userName != null ? userName : "root");
+ if (userName != null) {
+ return userName;
+ }
+ String accessKeyId = accountResolver.extractAccessKeyId(authorization);
+ if (accessKeyId == null) {
+ throw new AwsException("NoSuchEntity",
+ "No access key could be determined from the request.", 404);
+ }
+ return iamService.findUserNameByAccessKeyId(accessKeyId)
+ .orElseThrow(() -> new AwsException("NoSuchEntity",
+ "The Access Key with id " + accessKeyId + " cannot be found.", 404));
+ }
+
+ private Response handleGetUser(MultivaluedMap<String, String> params, String authorization) {
+ // UserName is optional per the IAM model: it defaults to the user owning the
+ // access key that signed the request.
+ IamUser user = iamService.getUser(resolveUserName(params, authorization));
String result = new XmlBuilder().start("User").raw(userXml(user)).end("User").build();
return Response.ok(AwsQueryResponse.envelope("GetUser", AwsNamespaces.IAM, result)).build();
}
@@ -672,13 +694,13 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("CreateAccessKey", AwsNamespaces.IAM, result)).build();
}
- private Response handleDeleteAccessKey(MultivaluedMap<String, String> params) {
- iamService.deleteAccessKey(getParam(params, "UserName"), getParam(params, "AccessKeyId"));
+ private Response handleDeleteAccessKey(MultivaluedMap<String, String> params, String authorization) {
+ iamService.deleteAccessKey(resolveUserName(params, authorization), getParam(params, "AccessKeyId"));
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteAccessKey", AwsNamespaces.IAM)).build();
}
- private Response handleListAccessKeys(MultivaluedMap<String, String> params) {
- List<AccessKey> keys = iamService.listAccessKeys(getParam(params, "UserName"));
+ private Response handleListAccessKeys(MultivaluedMap<String, String> params, String authorization) {
+ List<AccessKey> keys = iamService.listAccessKeys(resolveUserName(params, authorization));
var xml = new XmlBuilder().start("AccessKeyMetadata");
for (AccessKey k : keys) {
xml.start("member").raw(accessKeyXml(k, false)).end("member");
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
index f3d40e8b3d..345fae5347 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
@@ -193,11 +193,23 @@ public class IamService implements SessionAccountLookup {
}
public IamUser getUser(String userName) {
+ if (userName == null) {
+ throw new AwsException("NoSuchEntity",
+ "The user with name null cannot be found.", 404);
+ }
return users.get(userName)
.orElseThrow(() -> new AwsException("NoSuchEntity",
"The user with name " + userName + " cannot be found.", 404));
}
+ /** The IAM user that owns the given access key id, when it is a real stored key. */
+ public Optional<String> findUserNameByAccessKeyId(String accessKeyId) {
+ if (accessKeyId == null) {
+ return Optional.empty();
+ }
+ return accessKeys.get(accessKeyId).map(AccessKey::getUserName);
+ }
+
public void deleteUser(String userName) {
IamUser user = getUser(userName);
if (!user.getAttachedPolicyArns().isEmpty()) {
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AwsQueryInternalErrorIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AwsQueryInternalErrorIntegrationTest.java
new file mode 100644
index 0000000000..ba2113aec2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/AwsQueryInternalErrorIntegrationTest.java
@@ -0,0 +1,66 @@
+package io.github.hectorvent.floci.core.common;
+
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.quarkus.test.InjectMock;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+
+/**
+ * A handler bug on the Query protocol must render the XML InternalFailure contract, never
+ * Quarkus's default JSON error page — SDK XML parsers fail on JSON before surfacing anything
+ * (issue #1753 hit exactly this via an NPE in the IAM handler).
+ */
+@QuarkusTest
+class AwsQueryInternalErrorIntegrationTest {
+
+ @InjectMock
+ IamService iamService;
+
+ @Test
+ void unhandledHandlerExceptionRendersXmlInternalFailure() {
+ when(iamService.listUsers(any())).thenThrow(new RuntimeException("simulated handler bug"));
+
+ given()
+ .formParam("Action", "ListUsers")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(500)
+ .contentType(containsString("xml"))
+ .body("ErrorResponse.Error.Type", equalTo("Receiver"))
+ .body("ErrorResponse.Error.Code", equalTo("InternalFailure"))
+ .body("ErrorResponse.Error.Message", containsString("simulated handler bug"));
+ }
+
+ /**
+ * The catch-all must not swallow AwsException. CloudWatch Metrics is the Query handler that
+ * renders no error XML of its own, so its AwsException reaches the controller: it has to keep
+ * its declared code and 4xx status and be encoded as XML, not collapse to a 500 InternalFailure
+ * (nor reach AwsExceptionMapper, which would emit JSON onto the XML wire).
+ */
+ @Test
+ void awsExceptionFromAHandlerKeepsItsCodeAndStatusAsXml() {
+ given()
+ .formParam("Action", "SetAlarmState")
+ .formParam("AlarmName", "no-such-alarm")
+ .formParam("StateValue", "ALARM")
+ .formParam("StateReason", "reason")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/monitoring/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(404)
+ .contentType(containsString("xml"))
+ .body("ErrorResponse.Error.Type", equalTo("Sender"))
+ .body("ErrorResponse.Error.Code", equalTo("ResourceNotFound"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java
index a073f95bfb..3aab7d378e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamIntegrationTest.java
@@ -767,6 +767,106 @@ class IamIntegrationTest {
// Access Keys
// =========================================================================
+ private static void createUser(String userName) {
+ given()
+ .formParam("Action", "CreateUser")
+ .formParam("UserName", userName)
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private static String createAccessKeyFor(String userName) {
+ return given()
+ .formParam("Action", "CreateAccessKey")
+ .formParam("UserName", userName)
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
+ }
+
+ @Test
+ @Order(56)
+ void listAccessKeysWithoutUserNameResolvesCaller() {
+ // UserName is optional per the IAM model: it defaults to the owner of the access
+ // key that signed the request (issue #1753: this path used to leak a JSON 500).
+ createUser("caller-list-user");
+ String keyId = createAccessKeyFor("caller-list-user");
+
+ given()
+ .formParam("Action", "ListAccessKeys")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=" + keyId + "/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .contentType(containsString("xml"))
+ .body("ListAccessKeysResponse.ListAccessKeysResult.AccessKeyMetadata.member.UserName",
+ equalTo("caller-list-user"));
+ }
+
+ @Test
+ @Order(57)
+ void listAccessKeysWithoutUserNameUnknownKeyReturnsNoSuchEntityXml() {
+ // The conventional 'test' key owns no IAM user: moto parity is the documented
+ // NoSuchEntity XML error, never a JSON body on the Query wire.
+ given()
+ .formParam("Action", "ListAccessKeys")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(404)
+ .contentType(containsString("xml"))
+ .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"))
+ .body("ErrorResponse.Error.Message", containsString("test"));
+ }
+
+ @Test
+ @Order(58)
+ void getUserWithoutUserNameResolvesCaller() {
+ createUser("caller-get-user");
+ String keyId = createAccessKeyFor("caller-get-user");
+
+ given()
+ .formParam("Action", "GetUser")
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=" + keyId + "/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("GetUserResponse.GetUserResult.User.UserName", equalTo("caller-get-user"));
+ }
+
+ @Test
+ @Order(59)
+ void deleteAccessKeyWithoutUserNameResolvesOwner() {
+ createUser("caller-del-user");
+ String keyId = createAccessKeyFor("caller-del-user");
+
+ given()
+ .formParam("Action", "DeleteAccessKey")
+ .formParam("AccessKeyId", keyId)
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=" + keyId + "/20260227/us-east-1/iam/aws4_request")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("DeleteAccessKeyResponse"));
+ }
+
@Test
@Order(40)
void createAndListAccessKeys() {
@@ -937,4 +1037,21 @@ class IamIntegrationTest {
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("UnsupportedOperation"));
}
+
+ @Test
+ @Order(73)
+ void getUserWithoutUserNameOnAnUnsignedRequestDoesNotLeakNull() {
+ // No Authorization header means no access key to resolve the caller from. The action
+ // still routes to IAM by name, so the error must read as a sentence rather than
+ // interpolating a null key id onto the wire.
+ given()
+ .formParam("Action", "GetUser")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(404)
+ .contentType(containsString("xml"))
+ .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"))
+ .body("ErrorResponse.Error.Message", not(containsString("null")));
+ }
}