diff --git a/docs/services/iam.md b/docs/services/iam.md index da14291939..c3678bf129 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -68,6 +68,7 @@ or at the AWS Sign-In host of a region in the deployment's partition; any other | DeleteRole | Deletes an IAM role from the local IAM store. | | ListRoles | Lists IAM roles in the local account, with `Marker` and `MaxItems` paging. | | UpdateRole | Updates mutable IAM role fields. | +| UpdateRoleDescription | Modifies only a role's description and returns the modified role. | | CreateServiceLinkedRole | Creates a role under /aws-service-role/ for a service principal. | | DeleteServiceLinkedRole | Deletes a service-linked role and returns a deletion task id. | | GetServiceLinkedRoleDeletionStatus | Returns the status of a service-linked role deletion. | @@ -78,6 +79,10 @@ or at the AWS Sign-In host of a region in the deployment's partition; any other `CreateRole` and every action that takes a `RoleName` (`GetRole`, `DeleteRole`, `UpdateRole`, `TagRole`, `AttachRolePolicy`, `PutRolePolicy` and the rest) check it as AWS does: 1-64 characters of `[\w+=,.@-]`, otherwise `ValidationError`. A colon is never valid, so no role can take the name of the EC2 instance identity role, `aws:ec2-instance`. +`UpdateRoleDescription` is the description half of `UpdateRole`, which is what AWS's own reference tells callers to use instead. Both of its members are required, so a request without `Description` answers `ValidationError` rather than leaving the role as it is, an empty `Description` is a value that clears the description, and the modified role comes back in the response, which `UpdateRole` does not answer at all. + +A role `Description` is held to the shape AWS publishes for it on every action that takes one, `CreateRole`, `UpdateRole`, `UpdateRoleDescription` and `CreateServiceLinkedRole`: at most 1000 characters of `[\u0009\u000A\u000D\u0020-\u007E\u00A1-\u00FF]`, which admits tab, newline and carriage return and no other control character, otherwise `ValidationError`. The check runs before the role is looked up or created, so a refused description never reaches a stored role, and the `Role` these actions and `GetRole` answer always stays parsable XML. + ### Policies | Action | Description | @@ -1955,11 +1960,14 @@ the emulator cannot reason about: `CreateServiceLinkedRole` puts a role under `/aws-service-role//` and marks it as service-linked. As on AWS, a role carrying that mark is protected: `AttachRolePolicy`, `DetachRolePolicy`, `PutRolePolicy`, `DeleteRolePolicy`, `PutRolePermissionsBoundary`, -`DeleteRolePermissionsBoundary`, `UpdateRole`, `UpdateAssumeRolePolicy`, `AddRoleToInstanceProfile`, +`DeleteRolePermissionsBoundary`, `UpdateAssumeRolePolicy`, `AddRoleToInstanceProfile`, `RemoveRoleFromInstanceProfile` and `DeleteRole` all answer `UnmodifiableEntity` and name the -linked service to go through instead. `TagRole` and `UntagRole` are allowed, as on AWS. Within the -IAM API `DeleteServiceLinkedRole` is the only way to remove such a role — the emulator's own -`/_floci/state/reset` still clears it along with everything else. +linked service to go through instead. The description is the one field AWS leaves editable, "from +the IAM console, API, or CLI", so `UpdateRoleDescription` goes through on a service-linked role and +so does an `UpdateRole` carrying only a `Description`; `UpdateRole` answers `UnmodifiableEntity` +once it carries `MaxSessionDuration`, and then writes neither field. `TagRole` and `UntagRole` are +allowed, as on AWS. Within the IAM API `DeleteServiceLinkedRole` is the only way to remove such a +role — the emulator's own `/_floci/state/reset` still clears it along with everything else. Four deviations to be aware of: diff --git a/docs/services/index.md b/docs/services/index.md index 869276a62f..86bcf83ffd 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -23,7 +23,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Lambda Web Functions](lambda-web-functions.md) | `/2025-03-07/web-functions/...` | REST JSON | 20 | | [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 80 | | [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane | -| [IAM](iam.md) | `POST /` with `Action=` param | Query | 175 | +| [IAM](iam.md) | `POST /` with `Action=` param | Query | 176 | | [STS](sts.md) | `POST /` with `Action=` param | Query | 8 | | [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 | | [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 | 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 75614650e0..fcb3646fd3 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 @@ -207,6 +207,7 @@ public class IamQueryHandler { case "DeleteRole" -> handleDeleteRole(params); case "ListRoles" -> handleListRoles(params); case "UpdateRole" -> handleUpdateRole(params); + case "UpdateRoleDescription" -> handleUpdateRoleDescription(params); case "CreateServiceLinkedRole" -> handleCreateServiceLinkedRole(params); case "DeleteServiceLinkedRole" -> handleDeleteServiceLinkedRole(params); case "GetServiceLinkedRoleDeletionStatus" -> handleGetServiceLinkedRoleDeletionStatus(params); @@ -1423,6 +1424,24 @@ public class IamQueryHandler { return Response.ok(AwsQueryResponse.envelopeNoResult("UpdateRole", AwsNamespaces.IAM)).build(); } + /** + * The description half of UpdateRole, which AWS's own reference opens by telling callers to use + * instead. Both members are required here, where UpdateRole's are optional, and the modified + * role comes back, which UpdateRole does not answer at all. + */ + private Response handleUpdateRoleDescription(MultivaluedMap params) { + // Read rather than requireParam: roleDescriptionType declares no minimum length, so an + // empty Description is a value that clears the description, not an absent member. + String description = params.getFirst("Description"); + if (description == null) { + throw SmithyValidationErrors.validationError( + "Value null at 'description' failed to satisfy constraint: Member must not be null"); + } + IamRole role = iamService.updateRoleDescription(getParam(params, "RoleName"), description); + String result = new XmlBuilder().start("Role").raw(roleXml(role, true)).end("Role").build(); + return Response.ok(AwsQueryResponse.envelope("UpdateRoleDescription", AwsNamespaces.IAM, result)).build(); + } + private Response handleUpdateAssumeRolePolicy(MultivaluedMap params) { iamService.updateAssumeRolePolicy(requireParam(params, "RoleName"), requireParam(params, "PolicyDocument")); 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 03a0e60885..b4d1bdc60a 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,6 +193,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private static final Pattern SERVICE_PRINCIPAL_PATTERN = Pattern.compile("[\\w+=,.@-]{1,128}"); /** CustomSuffix as AWS constrains it: 1-64 characters of {@code [\w+=,.@-]}. */ private static final Pattern CUSTOM_SUFFIX_PATTERN = Pattern.compile("[\\w+=,.@-]{1,64}"); + private static final int ROLE_DESCRIPTION_MAX_LENGTH = 1000; + /** + * roleDescriptionType's character set, which AWS writes as + * {@code [\u0009\u000A\u000D\u0020-\u007E\u00A1-\u00FF]*}: tab, newline, carriage + * return, printable ASCII and the Latin-1 supplement, and no other control character. + * Written here the way {@code java.util.regex} reads it. + */ + private static final Pattern ROLE_DESCRIPTION_PATTERN = Pattern.compile("[\\t\\n\\r\\x20-\\x7E\\xA1-\\xFF]*"); + /** AWS's own spelling of that set, for the message, where the regex form would not be AWS's. */ + private static final String ROLE_DESCRIPTION_PATTERN_TEXT = + "[\\u0009\\u000A\\u000D\\u0020-\\u007E\\u00A1-\\u00FF]*"; private static final int ROLE_NAME_MAX_LENGTH = 64; /** roleNameType's character set. Excluding {@code :} is what reserves names such as {@code aws:ec2-instance} for AWS. */ private static final Pattern ROLE_NAME_PATTERN = Pattern.compile("[\\w+=,.@-]+"); @@ -1159,6 +1170,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { String description, int maxSessionDuration, Map tags, String permissionsBoundaryArn) { validateRoleName(roleName); + validateRoleDescription(description); if (permissionsBoundaryArn != null) { requirePolicy(permissionsBoundaryArn); // validate before anything is created } @@ -1209,6 +1221,36 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return roles.get(roleName); } + /** + * roleDescriptionType: at most 1000 characters of the set AWS publishes, which admits tab, + * newline and carriage return and no other control character. Enforced wherever a role + * description is taken, so {@code CreateRole}, {@code UpdateRole}, + * {@code UpdateRoleDescription} and {@code CreateServiceLinkedRole} answer the same way, and + * so a character XML cannot carry never reaches a stored role: {@code XmlBuilder} escapes the + * five entities and passes everything else through, which would make the {@code Role} this + * action and {@code GetRole} answer unparsable. + * + *

The rendering names neither the offending value nor the set, the way + * {@link #requireStatusFromEnum} does, which is the one IAM constraint rendering a recording + * covers. It also keeps the refused description out of the error body, where a control + * character would break the answer it is being refused for. + */ + private static void validateRoleDescription(String description) { + if (description == null) { + return; + } + String constraint; + if (description.length() > ROLE_DESCRIPTION_MAX_LENGTH) { + constraint = "Member must have length less than or equal to " + ROLE_DESCRIPTION_MAX_LENGTH; + } else if (!ROLE_DESCRIPTION_PATTERN.matcher(description).matches()) { + constraint = "Member must satisfy regular expression pattern: " + ROLE_DESCRIPTION_PATTERN_TEXT; + } else { + return; + } + throw SmithyValidationErrors.validationError( + "Value at 'description' failed to satisfy constraint: " + constraint); + } + /** roleNameType: 1-64 characters of {@code [\w+=,.@-]}, reported the way AWS reports a model constraint. */ private static void validateRoleName(String roleName) { String constraint; @@ -1258,8 +1300,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider { /** * AWS publishes UnmodifiableEntity on twelve role actions, and its message names the linked - * service the caller has to go through instead. This guards the eleven of them the emulator - * implements; UpdateRoleDescription is the twelfth and has no handler here. TagRole and + * service the caller has to go through instead. This guards the ten of them that refuse a + * service-linked role whatever the request asks for. UpdateRole and UpdateRoleDescription are + * the other two, and the user guide carves a description out of both, so {@link #updateRole} + * reaches for this only where a request asks for more than a description. TagRole and * UntagRole are deliberately not guarded — AWS does not publish the error on either, and * TagRole's reference says the role "can be a regular role or a service-linked role". * Within the IAM API, {@link #deleteServiceLinkedRole} is the only way to remove such a role. @@ -1313,6 +1357,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { throw new AwsException("InvalidInput", "CustomSuffix must be 1-64 characters matching [\\w+=,.@-].", 400); } + validateRoleDescription(description); // Most services refuse a suffix outright. The table carries what AWS was recorded // doing, and UNKNOWN keeps taking one rather than refusing on an inference: the name // as the caller sent it, since every recording used the canonical form and the two @@ -1407,13 +1452,40 @@ public class IamService implements SessionAccountLookup, ResourceProvider { .toList(); } - public void updateRole(String roleName, String description, int maxSessionDuration) { + /** + * Updates a role's description, its maximum session duration, or both. A service-linked role + * takes the description and refuses the duration: "You can edit the description of any role + * from the IAM console, API, or CLI", and the user guide's procedure for editing one is this + * action, as {@code aws iam update-role --role-name ROLE-NAME --description DESCRIPTION}. So + * the protection stands on MaxSessionDuration, the only other member this action takes, and a + * request carrying both is refused whole, before the description is written. + */ + public IamRole updateRole(String roleName, String description, int maxSessionDuration) { validateRoleName(roleName); + validateRoleDescription(description); IamRole role = getRole(roleName); - requireNotServiceLinked(role, roleName); - if (description != null) role.setDescription(description); - if (maxSessionDuration > 0) role.setMaxSessionDuration(maxSessionDuration); + if (maxSessionDuration > 0) { + requireNotServiceLinked(role, roleName); + } + if (description != null) { + role.setDescription(description); + } + if (maxSessionDuration > 0) { + role.setMaxSessionDuration(maxSessionDuration); + } roles.put(roleName, role); + return role; + } + + /** + * Modifies only a role's description. AWS documents UpdateRoleDescription as performing "the + * same function as the Description parameter in the UpdateRole operation", so it is that path + * with nothing else touched, and it answers the modified role. A service-linked role takes it: + * the user guide publishes a policy granting {@code iam:UpdateRoleDescription} on + * {@code arn:aws:iam::*:role/aws-service-role/*} for editing the description of one. + */ + public IamRole updateRoleDescription(String roleName, String description) { + return updateRole(roleName, description, 0); } public void updateAssumeRolePolicy(String roleName, String policyDocument) { diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamRoleDescriptionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamRoleDescriptionIntegrationTest.java new file mode 100644 index 0000000000..b94c1a4ded --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamRoleDescriptionIntegrationTest.java @@ -0,0 +1,207 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; + +/** + * {@code UpdateRoleDescription} over the wire. + * + *

The reference opens with "Use UpdateRole instead" and says the operation "performs the same + * function as the Description parameter in the UpdateRole operation", so it is that path and + * nothing else about the role moves. Its two members are both required, where UpdateRole's are + * optional, and it answers the modified role, which UpdateRole does not answer at all. The errors + * it models are {@code NoSuchEntity}, {@code UnmodifiableEntity} and {@code ServiceFailure}, and + * the last of those is not a description's to answer: AWS documents the description of any role as + * editable, a service-linked one included, which {@link IamServiceLinkedRoleIntegrationTest} + * covers alongside the protection that does hold there. + */ +@QuarkusTest +class IamRoleDescriptionIntegrationTest { + + private static final String ACCOUNT = "000000000931"; + private static final String REGION = "us-east-1"; + private static final String TRUST_POLICY = + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Service\":\"lambda.amazonaws.com\"}," + + "\"Action\":\"sts:AssumeRole\"}]}"; + private static final String RESULT = "UpdateRoleDescriptionResponse.UpdateRoleDescriptionResult"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void theNewDescriptionIsAppliedAndTheRoleComesBack() { + String roleName = role("applied", "the description it was created with"); + + update(Map.of("RoleName", roleName, "Description", "the description it answers with")) + .statusCode(200) + .body(RESULT + ".Role.RoleName", equalTo(roleName)) + .body(RESULT + ".Role.Description", equalTo("the description it answers with")) + .body(RESULT + ".Role.Arn", containsString(":role/" + roleName)); + + admin("GetRole", Map.of("RoleName", roleName)).statusCode(200) + .body("GetRoleResponse.GetRoleResult.Role.Description", + equalTo("the description it answers with")); + } + + @Test + void anEmptyDescriptionIsAValueAndClearsIt() { + // roleDescriptionType declares a maximum and no minimum, so an empty string satisfies the + // shape: the description it replaces is the one the role was created with. + String roleName = role("cleared", "about to be cleared"); + + update(Map.of("RoleName", roleName, "Description", "")).statusCode(200) + .body(RESULT + ".Role.Description", equalTo("")); + + admin("GetRole", Map.of("RoleName", roleName)).statusCode(200) + .body("GetRoleResponse.GetRoleResult.Role.Description", equalTo("")); + } + + @Test + void onlyTheDescriptionMoves() { + String roleName = role("only", "before"); + admin("UpdateRole", Map.of("RoleName", roleName, "MaxSessionDuration", "7200")) + .statusCode(200); + + update(Map.of("RoleName", roleName, "Description", "after")).statusCode(200) + .body(RESULT + ".Role.MaxSessionDuration", equalTo("7200")); + + admin("GetRole", Map.of("RoleName", roleName)).statusCode(200) + .body("GetRoleResponse.GetRoleResult.Role.MaxSessionDuration", equalTo("7200")) + .body("GetRoleResponse.GetRoleResult.Role.AssumeRolePolicyDocument", + containsString("lambda.amazonaws.com")); + } + + @Test + void theMaximumIsTakenAndOneCharacterMoreIsNot() { + String roleName = role("length", "before"); + String atMaximum = "d".repeat(1000); + + update(Map.of("RoleName", roleName, "Description", atMaximum)).statusCode(200) + .body(RESULT + ".Role.Description", equalTo(atMaximum)); + + update(Map.of("RoleName", roleName, "Description", "d".repeat(1001))).statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", + equalTo("1 validation error detected: Value at 'description' failed to " + + "satisfy constraint: Member must have length less than or equal " + + "to 1000")); + + admin("GetRole", Map.of("RoleName", roleName)).statusCode(200) + .body("GetRoleResponse.GetRoleResult.Role.Description", equalTo(atMaximum)); + } + + @Test + void aCharacterOutsideTheSetIsRefusedSoTheAnswerStaysParsable() { + // The set admits tab, newline and carriage return and no other control character, which is + // what keeps the Role this action answers readable: XmlBuilder escapes the five entities + // and passes everything else through, so a stored control character would make this + // response, and GetRole's, unparsable. + String roleName = role("control", "before"); + + update(Map.of("RoleName", roleName, "Description", "a" + (char) 1 + "b")).statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", + containsString("Member must satisfy regular expression pattern")); + + update(Map.of("RoleName", roleName, "Description", "two\nlines\tand a tab")).statusCode(200); + + admin("GetRole", Map.of("RoleName", roleName)).statusCode(200) + .body("GetRoleResponse.GetRoleResult.Role.Description", + containsString("lines")); + } + + @Test + void theOtherOperationsThatTakeADescriptionAnswerTheSameWay() { + // One validator, four call sites: the shape is shared, so a description CreateRole or + // UpdateRole would have stored is refused there too, and the create stores nothing. + admin("CreateRole", Map.of("RoleName", "role-description-sibling", + "AssumeRolePolicyDocument", TRUST_POLICY, "Description", "d".repeat(1001))) + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", containsString("at 'description'")); + admin("GetRole", Map.of("RoleName", "role-description-sibling")).statusCode(404); + + String roleName = role("sibling", "before"); + admin("UpdateRole", Map.of("RoleName", roleName, "Description", "a" + (char) 1 + "b")) + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + admin("GetRole", Map.of("RoleName", roleName)).statusCode(200) + .body("GetRoleResponse.GetRoleResult.Role.Description", equalTo("before")); + } + + @Test + void anAbsentDescriptionIsAValidationError() { + String roleName = role("absent-description", "kept"); + + update(Map.of("RoleName", roleName)).statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", + equalTo("1 validation error detected: Value null at 'description' failed " + + "to satisfy constraint: Member must not be null")); + + admin("GetRole", Map.of("RoleName", roleName)).statusCode(200) + .body("GetRoleResponse.GetRoleResult.Role.Description", equalTo("kept")); + } + + @Test + void anAbsentRoleNameIsAValidationError() { + update(Map.of("Description", "nobody to apply it to")).statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", containsString("at 'roleName'")); + } + + @Test + void theRoleNameIsReadBeforeTheRoleIsLookedUp() { + // A colon is outside roleNameType, and the shape is what AWS answers for: the lookup would + // otherwise decide, which is NoSuchEntity 404 for a role that cannot exist under that name. + update(Map.of("RoleName", "role:with:colons", "Description", "whatever")).statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", containsString("at 'roleName'")); + } + + @Test + void anUnknownRoleIsNoSuchEntity() { + update(Map.of("RoleName", "role-description-absent", "Description", "nothing to apply it to")) + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + private String role(String label, String description) { + String roleName = "role-description-" + label; + admin("CreateRole", Map.of("RoleName", roleName, "AssumeRolePolicyDocument", TRUST_POLICY, + "Description", description)).statusCode(200); + cleanup.register(() -> admin("DeleteRole", Map.of("RoleName", roleName)).statusCode(200)); + return roleName; + } + + private static ValidatableResponse update(Map params) { + return iam("UpdateRoleDescription", params); + } + + private static ValidatableResponse admin(String action, Map params) { + return iam(action, params); + } + + private static ValidatableResponse iam(String action, Map params) { + RequestSpecification spec = given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + + "/20261018/" + REGION + "/iam/aws4_request, SignedHeaders=host, " + + "Signature=abc") + .contentType("application/x-www-form-urlencoded") + .formParam("Action", action) + .formParam("Version", "2010-05-08"); + params.forEach(spec::formParam); + return spec.when().post("/").then(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java index 0076f861f5..f6eb53a6af 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java @@ -564,7 +564,9 @@ class IamServiceLinkedRoleIntegrationTest { String roleName = "AWSServiceRoleForProtectprobe"; String readOnly = "arn:aws:iam::aws:policy/ReadOnlyAccess"; - refusedAsUnmodifiable("UpdateRole", "RoleName", roleName, "Description", "hijacked"); + // UpdateRole is protected for its duration, not for its description, which AWS documents + // as editable on any role: aDescriptionEditIsTakenAndTheDurationIsStillRefused has that. + refusedAsUnmodifiable("UpdateRole", "RoleName", roleName, "MaxSessionDuration", "7200"); refusedAsUnmodifiable("UpdateAssumeRolePolicy", "RoleName", roleName, "PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[]}"); refusedAsUnmodifiable("DetachRolePolicy", "RoleName", roleName, "PolicyArn", readOnly); @@ -761,6 +763,88 @@ class IamServiceLinkedRoleIntegrationTest { + "account, please try a different suffix.")); } + @Test + @Order(32) + void aDescriptionOutsideItsShapeIsRefusedBeforeTheRoleIsCreated() { + // roleDescriptionType is the same shape CreateRole and UpdateRole take, so this answers + // ValidationError rather than this action's own InvalidInput, and stores nothing. + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", "descprobe.amazonaws.com") + .formParam("Description", "d".repeat(1001)) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", containsString("at 'description'")); + + given() + .formParam("Action", "GetRole") + .formParam("RoleName", "AWSServiceRoleForDescprobe") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(404); + } + + /** + * The description is the one thing AWS documents as editable on a service-linked role: "You + * can edit the description of any role from the IAM console, API, or CLI", and the user guide + * reaches it with {@code update-role --description} or {@code UpdateRoleDescription}, for + * which it publishes a policy over {@code arn:aws:iam::*:role/aws-service-role/*}. The guard + * stands on the duration instead, and a request for both is refused whole. + */ + @Test + @Order(33) + void aDescriptionEditIsTakenAndTheDurationIsStillRefused() { + createServiceLinkedRole("descriptionprobe.amazonaws.com"); + String roleName = "AWSServiceRoleForDescriptionprobe"; + + given() + .formParam("Action", "UpdateRoleDescription") + .formParam("RoleName", roleName) + .formParam("Description", "edited through UpdateRoleDescription") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("UpdateRoleDescriptionResponse.UpdateRoleDescriptionResult.Role.Description", + equalTo("edited through UpdateRoleDescription")) + .body("UpdateRoleDescriptionResponse.UpdateRoleDescriptionResult.Role.Path", + equalTo(SERVICE_LINKED_ROLE_PATH + "descriptionprobe.amazonaws.com/")); + + // The action the user guide's own procedure names, with nothing else in the request. + given() + .formParam("Action", "UpdateRole") + .formParam("RoleName", roleName) + .formParam("Description", "edited through UpdateRole") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + + refusedAsUnmodifiable("UpdateRole", "RoleName", roleName, + "Description", "hijacked", "MaxSessionDuration", "7200"); + + // The refused request carried a description too, and left the stored one alone. + given() + .formParam("Action", "GetRole") + .formParam("RoleName", roleName) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("GetRoleResponse.GetRoleResult.Role.Description", + equalTo("edited through UpdateRole")) + .body("GetRoleResponse.GetRoleResult.Role.MaxSessionDuration", equalTo("3600")); + } + /** * A table name plus a suffix can breach the 64-character RoleName limit even though the name * alone fits. Two entries are close enough for that to matter, and neither has a recording diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java index e7968cd8e9..79a9b5775d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java @@ -92,6 +92,76 @@ class IamServiceTest { ); } + @Test + void updateRoleDescriptionAnswersTheRoleAndMovesNothingElse() { + // "This operation performs the same function as the Description parameter in the UpdateRole + // operation", and UpdateRole answers no shape at all, so the role comes back from here. + iamService.createRole("R", "/", "{}", "before", 7200, null); + + IamRole updated = iamService.updateRoleDescription("R", "after"); + + assertEquals("after", updated.getDescription()); + assertEquals(7200, updated.getMaxSessionDuration()); + assertEquals("{}", updated.getAssumeRolePolicyDocument()); + assertEquals("after", iamService.getRole("R").getDescription()); + } + + @Test + void aRoleDescriptionIsHeldToItsShapeWhereverItIsTaken() { + iamService.createRole("R", "/", "{}", "fine", 3600, null); + + AwsException tooLong = assertThrows(AwsException.class, + () -> iamService.updateRoleDescription("R", "d".repeat(1001))); + assertEquals("ValidationError", tooLong.getErrorCode()); + assertEquals("1 validation error detected: Value at 'description' failed to satisfy " + + "constraint: Member must have length less than or equal to 1000", + tooLong.getMessage()); + + AwsException outsideTheSet = assertThrows(AwsException.class, + () -> iamService.updateRoleDescription("R", "a" + (char) 1 + "b")); + assertEquals("ValidationError", outsideTheSet.getErrorCode()); + + // Neither refusal wrote, and the create path answers the same way without storing a role. + assertEquals("fine", iamService.getRole("R").getDescription()); + assertEquals("ValidationError", assertThrows(AwsException.class, + () -> iamService.createRole("R2", "/", "{}", "d".repeat(1001), 3600, null)) + .getErrorCode()); + assertThrows(AwsException.class, () -> iamService.getRole("R2")); + + // Tab, newline and carriage return are inside the set AWS publishes. + iamService.updateRoleDescription("R", "one\ntwo\tthree\r"); + assertEquals("one\ntwo\tthree\r", iamService.getRole("R").getDescription()); + } + + @Test + void updateRoleDescriptionReadsTheRoleNameBeforeTheLookup() { + AwsException error = assertThrows(AwsException.class, + () -> iamService.updateRoleDescription("role:with:colons", "whatever")); + + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + } + + @Test + void aServiceLinkedRoleTakesADescriptionEditAndRefusesADuration() { + // "You can edit the description of any role from the IAM console, API, or CLI", by either + // action, so the protection AWS publishes on both stands on the duration instead. + String roleName = iamService.createServiceLinkedRole("es.amazonaws.com", null, "created with") + .getRoleName(); + + assertEquals("edited", iamService.updateRoleDescription(roleName, "edited").getDescription()); + assertEquals("edited again", iamService.updateRole(roleName, "edited again", 0).getDescription()); + + AwsException refused = assertThrows(AwsException.class, + () -> iamService.updateRole(roleName, "hijacked", 7200)); + assertEquals("UnmodifiableEntity", refused.getErrorCode()); + assertEquals(400, refused.getHttpStatus()); + + // Refused whole: the description that came with the duration was not written either. + assertEquals("edited again", iamService.getRole(roleName).getDescription()); + assertEquals(3600, iamService.getRole(roleName).getMaxSessionDuration()); + } + @Test void roleInlinePolicyQuotaIgnoresWhitespaceAndPreservesRejectedReplacement() { iamService.createRole("R", "/", "{}", null, 0, null);