From 3e4d867de319ad40704e93207ec22ea8766150f4 Mon Sep 17 00:00:00 2001 From: Yang Hao <1994728136@qq.com> Date: Sat, 14 Nov 2026 23:29:06 +0800 Subject: [PATCH] fix(account): check alternate contact requests against the model (#8312) --- Makefile | 2 +- docs/services/account.md | 6 +- .../account/AccountRequestShapes.java | 6 +- .../aws/services/account/AccountService.java | 58 ++------ .../resources/aws/account-request-shapes.json | 71 ++++++++++ ...ccountAlternateContactIntegrationTest.java | 43 +++--- ...ntOrganizationsContextIntegrationTest.java | 4 +- .../services/account/AccountServiceTest.java | 134 +++++++++++++++--- .../account/AlternateContactRequests.java | 23 +++ tools/aws/regen_account_shapes.py | 6 +- 10 files changed, 260 insertions(+), 93 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/account/AlternateContactRequests.java diff --git a/Makefile b/Makefile index 0e3b73c056..10b5c8843a 100644 --- a/Makefile +++ b/Makefile @@ -32,7 +32,7 @@ # src/main/resources/aws/cur-request-shapes.json, the Cost and Usage Reports request constraints # for every operation, is generated from botocore's CUR model by tools/aws/regen_cur_shapes.py. # src/main/resources/aws/account-request-shapes.json, the Account Management request constraints of the -# primary contact operations, is generated from botocore's Account model by tools/aws/regen_account_shapes.py. +# contact operations, is generated from botocore's Account model by tools/aws/regen_account_shapes.py. # src/main/resources/aws/payment-cryptography-request-shapes.json, the Payment Cryptography # request constraints, is generated from botocore's model by # tools/aws/regen_payment_cryptography_shapes.py. diff --git a/docs/services/account.md b/docs/services/account.md index 84b5653860..f379d0ab62 100644 --- a/docs/services/account.md +++ b/docs/services/account.md @@ -22,11 +22,9 @@ Alternate contacts and primary contact information are isolated by caller accoun ## AWS-compatible failures -`PutAlternateContact` validates the contact type, name, title, email address, phone number, and optional target account ID. `GetAlternateContact` returns `ResourceNotFoundException` when the requested contact has not been configured. Invalid request data uses `ValidationException` and unsupported cross-account access uses `AccessDeniedException`. +Requests of all five operations are checked by `RequestConstraintCheck` against the member types, required members, lengths, patterns and enum values generated from botocore's Account model, such as the `AlternateContactType` values (`BILLING`, `OPERATIONS`, `SECURITY`) and the `PhoneNumber` pattern of `PutContactInformation` (a `+` followed by digits, spaces, parentheses, or hyphens). `tools/aws/regen_account_shapes.py` vendors them; `make aws-data-sync` regenerates them and `make aws-data-check` checks for drift. A member of the wrong JSON type fails with `SerializationException` and any other violation with `ValidationException`. `PutContactInformation` also requires `StateOrRegion` for the countries the API reference documents as requiring it (`US`, `CA`, `GB`, `DE`, `JP`, `IN`, `BR`), a rule the model does not carry. `GetAlternateContact` and `DeleteAlternateContact` return `ResourceNotFoundException` when the requested contact has not been configured, and `GetContactInformation` when no contact information has been stored. -`PutContactInformation` and `GetContactInformation` requests are checked by `RequestConstraintCheck` against the member types, required members, lengths and patterns generated from botocore's Account model, such as the `PhoneNumber` pattern (a `+` followed by digits, spaces, parentheses, or hyphens). `tools/aws/regen_account_shapes.py` vendors them; `make aws-data-sync` regenerates them and `make aws-data-check` checks for drift. A member of the wrong JSON type fails with `SerializationException` and any other violation with `ValidationException`. `PutContactInformation` also requires `StateOrRegion` for the countries the API reference documents as requiring it (`US`, `CA`, `GB`, `DE`, `JP`, `IN`, `BR`), a rule the model does not carry. `GetContactInformation` returns `ResourceNotFoundException` when no contact information has been stored. Both operations apply the same target account ID rules as the alternate-contact operations. - -A request that names an `AccountId` runs in the organizations context: the caller must be the organization's management account or its delegated administrator for Account Management, the organization must have all features and trusted access for Account Management enabled, and the `AccountId` must name a member account of that organization. Naming the management account returns `AccessDeniedException`, including when the management account names itself; its own contacts are reached by leaving `AccountId` out. +A request that names an `AccountId` runs in the organizations context: the caller must be the organization's management account or its delegated administrator for Account Management, the organization must have all features and trusted access for Account Management enabled, and the `AccountId` must name a member account of that organization other than the management account. Any other request that names an `AccountId` returns `AccessDeniedException`, including the management account naming itself, whose own contacts are reached by leaving `AccountId` out. Three behaviors are Floci's own. An account has no primary contact until `PutContactInformation` stores one, because Floci has no sign-up contact to return. `CountryCode` is checked for its two-character length only, not against the ISO 3166-1 list. `GetContactInformation` always reports `VerificationStatus` as `NOT_SUPPORTED`, because Floci does not verify phone numbers. diff --git a/src/main/java/io/floci/aws/services/account/AccountRequestShapes.java b/src/main/java/io/floci/aws/services/account/AccountRequestShapes.java index a5ea7fabd5..4f9291ba18 100644 --- a/src/main/java/io/floci/aws/services/account/AccountRequestShapes.java +++ b/src/main/java/io/floci/aws/services/account/AccountRequestShapes.java @@ -7,10 +7,10 @@ import io.floci.aws.core.common.RequestConstraintCheck; import java.util.List; /** - * Checks the primary contact requests against the constraints generated by + * Checks the Account Management requests against the constraints generated by * {@code tools/aws/regen_account_shapes.py}. A member of the wrong JSON type answers - * {@code SerializationException}, as a non-string {@code AccountId} does on the alternate contact - * operations; every other violation is a {@code ValidationException} in the standard wording. + * {@code SerializationException}; every other violation is a {@code ValidationException} in the + * standard wording. */ final class AccountRequestShapes { diff --git a/src/main/java/io/floci/aws/services/account/AccountService.java b/src/main/java/io/floci/aws/services/account/AccountService.java index 60bdc85325..c7e04f74fa 100644 --- a/src/main/java/io/floci/aws/services/account/AccountService.java +++ b/src/main/java/io/floci/aws/services/account/AccountService.java @@ -22,15 +22,10 @@ import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.regex.Pattern; @ApplicationScoped public class AccountService implements Resettable, StoredResourceArns { private static final String ACCOUNT_MANAGEMENT_SERVICE_PRINCIPAL = ServicePrincipals.of("account"); - private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}"); - private static final Pattern EMAIL = Pattern.compile("\\s*[\\w+=.#|!&-]+@[\\w.-]+\\.[\\w]+\\s*"); - private static final Pattern PHONE = Pattern.compile("[\\s0-9()+-]+"); - private static final Set CONTACT_TYPES = Set.of("BILLING", "OPERATIONS", "SECURITY"); private static final Set COUNTRIES_REQUIRING_STATE_OR_REGION = Set.of("US", "CA", "GB", "DE", "JP", "IN", "BR"); private static final String PRIMARY_CONTACT_KEY = "primary"; @@ -49,27 +44,30 @@ public class AccountService implements Resettable, StoredResourceArns { } public void putAlternateContact(String callerAccountId, JsonNode request) { + AccountRequestShapes.check("PutAlternateContact", request); String targetAccountId = resolveTargetAccount(callerAccountId, request); - String type = requireContactType(request); + String type = text(request, "AlternateContactType"); AlternateContact contact = new AlternateContact( type, - requirePattern(request, "EmailAddress", 1, 254, EMAIL), - requireLength(request, "Name", 1, 64), - requirePattern(request, "PhoneNumber", 1, 25, PHONE), - requireLength(request, "Title", 1, 50)); + text(request, "EmailAddress"), + text(request, "Name"), + text(request, "PhoneNumber"), + text(request, "Title")); contacts.putForAccount(targetAccountId, type, contact); } public AlternateContact getAlternateContact(String callerAccountId, JsonNode request) { + AccountRequestShapes.check("GetAlternateContact", request); String targetAccountId = resolveTargetAccount(callerAccountId, request); - String type = requireContactType(request); + String type = text(request, "AlternateContactType"); return contacts.getForAccount(targetAccountId, type) .orElseThrow(AccountService::notFound); } public synchronized void deleteAlternateContact(String callerAccountId, JsonNode request) { + AccountRequestShapes.check("DeleteAlternateContact", request); String targetAccountId = resolveTargetAccount(callerAccountId, request); - String type = requireContactType(request); + String type = text(request, "AlternateContactType"); if (contacts.getForAccount(targetAccountId, type).isEmpty()) { throw notFound(); } @@ -110,18 +108,10 @@ public class AccountService implements Resettable, StoredResourceArns { } private String resolveTargetAccount(String callerAccountId, JsonNode request) { - JsonNode accountIdNode = request == null ? null : request.get("AccountId"); - if (accountIdNode == null || accountIdNode.isNull()) { + String requestedAccountId = text(request, "AccountId"); + if (requestedAccountId == null) { return callerAccountId; } - if (!accountIdNode.isTextual()) { - throw new AwsException("SerializationException", - "AccountId must be a string.", 400); - } - String requestedAccountId = accountIdNode.textValue(); - if (!ACCOUNT_ID.matcher(requestedAccountId).matches()) { - throw validation("AccountId must be a 12 digit account ID."); - } Organization organization; OrganizationAccount caller; @@ -193,30 +183,6 @@ public class AccountService implements Resettable, StoredResourceArns { .toString()); } - private static String requireContactType(JsonNode request) { - String value = requireLength(request, "AlternateContactType", 1, 32); - if (!CONTACT_TYPES.contains(value)) { - throw validation("AlternateContactType must be BILLING, OPERATIONS, or SECURITY."); - } - return value; - } - - private static String requirePattern(JsonNode request, String field, int min, int max, Pattern pattern) { - String value = requireLength(request, field, min, max); - if (!pattern.matcher(value).matches()) { - throw validation(field + " does not satisfy the required pattern."); - } - return value; - } - - private static String requireLength(JsonNode request, String field, int min, int max) { - String value = text(request, field); - if (value == null || value.length() < min || value.length() > max) { - throw validation(field + " must be between " + min + " and " + max + " characters."); - } - return value; - } - private static String text(JsonNode request, String field) { JsonNode value = request == null ? null : request.get(field); return value != null && value.isTextual() ? value.textValue() : null; diff --git a/src/main/resources/aws/account-request-shapes.json b/src/main/resources/aws/account-request-shapes.json index edd6cfa3c2..b2c68dbb94 100644 --- a/src/main/resources/aws/account-request-shapes.json +++ b/src/main/resources/aws/account-request-shapes.json @@ -4,7 +4,10 @@ "botocore": "botocore 1.43.118 (installed package)" }, "operations": { + "DeleteAlternateContact": "DeleteAlternateContactRequest", + "GetAlternateContact": "GetAlternateContactRequest", "GetContactInformation": "GetContactInformationRequest", + "PutAlternateContact": "PutAlternateContactRequest", "PutContactInformation": "PutContactInformationRequest" }, "shapes": { @@ -17,6 +20,14 @@ "min": 1, "max": 60 }, + "AlternateContactType": { + "type": "string", + "enum": [ + "BILLING", + "OPERATIONS", + "SECURITY" + ] + }, "City": { "type": "string", "min": 1, @@ -63,27 +74,82 @@ "min": 2, "max": 2 }, + "DeleteAlternateContactRequest": { + "type": "structure", + "required": [ + "AlternateContactType" + ], + "members": { + "AlternateContactType": "AlternateContactType", + "AccountId": "AccountId" + } + }, "DistrictOrCounty": { "type": "string", "min": 1, "max": 50 }, + "EmailAddress": { + "type": "string", + "min": 1, + "max": 254, + "pattern": "[\\s]*[\\w+=.#|!&-]+@[\\w.-]+\\.[\\w]+[\\s]*" + }, "FullName": { "type": "string", "min": 1, "max": 50 }, + "GetAlternateContactRequest": { + "type": "structure", + "required": [ + "AlternateContactType" + ], + "members": { + "AlternateContactType": "AlternateContactType", + "AccountId": "AccountId" + } + }, "GetContactInformationRequest": { "type": "structure", "members": { "AccountId": "AccountId" } }, + "Name": { + "type": "string", + "min": 1, + "max": 64 + }, + "PhoneNumber": { + "type": "string", + "min": 1, + "max": 25, + "pattern": "[\\s0-9()+-]+" + }, "PostalCode": { "type": "string", "min": 1, "max": 20 }, + "PutAlternateContactRequest": { + "type": "structure", + "required": [ + "Name", + "Title", + "EmailAddress", + "PhoneNumber", + "AlternateContactType" + ], + "members": { + "Name": "Name", + "Title": "Title", + "EmailAddress": "EmailAddress", + "PhoneNumber": "PhoneNumber", + "AlternateContactType": "AlternateContactType", + "AccountId": "AccountId" + } + }, "PutContactInformationRequest": { "type": "structure", "required": [ @@ -99,6 +165,11 @@ "min": 1, "max": 50 }, + "Title": { + "type": "string", + "min": 1, + "max": 50 + }, "WebsiteUrl": { "type": "string", "min": 1, diff --git a/src/test/java/io/floci/aws/services/account/AccountAlternateContactIntegrationTest.java b/src/test/java/io/floci/aws/services/account/AccountAlternateContactIntegrationTest.java index 8f82321311..75aa50fee9 100644 --- a/src/test/java/io/floci/aws/services/account/AccountAlternateContactIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/account/AccountAlternateContactIntegrationTest.java @@ -1,11 +1,13 @@ package io.floci.aws.services.account; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.ValidatableResponse; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import static io.floci.aws.services.account.AlternateContactRequests.alternateContactRequest; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; @@ -26,23 +28,31 @@ class AccountAlternateContactIntegrationTest { @Test void rejectsInvalidContactType() { - given().contentType("application/json").header("Authorization", AUTH) - .body("{\"AlternateContactType\":\"OTHER\"}") - .post("/getAlternateContact").then().statusCode(400).body("__type", equalTo("ValidationException")); + post("/getAlternateContact", "{\"AlternateContactType\":\"OTHER\"}") + .statusCode(400).body("__type", equalTo("ValidationException")) + .body("message", equalTo("Invalid parameter at 'AlternateContactType' failed to satisfy constraint: " + + "'Member must satisfy enum value set: [BILLING, OPERATIONS, SECURITY]'")); + } + + @Test + void rejectsNonStringMember() { + ObjectNode request = alternateContactRequest().put("PhoneNumber", 12025550123L); + post("/putAlternateContact", request.toString()) + .statusCode(400).body("__type", equalTo("SerializationException")) + .body("message", equalTo("PhoneNumber must be a string.")); } @Test void rejectsNonStringAccountIdInsteadOfFallingBackToCaller() { - given().contentType("application/json").header("Authorization", AUTH) - .body("{\"AccountId\":123456789012,\"AlternateContactType\":\"SECURITY\",\"Name\":\"Security\",\"Title\":\"Owner\",\"EmailAddress\":\"security@example.com\",\"PhoneNumber\":\"+12025550123\"}") - .post("/putAlternateContact").then().statusCode(400).body("__type", equalTo("SerializationException")); + ObjectNode request = alternateContactRequest().put("AccountId", 123456789012L); + post("/putAlternateContact", request.toString()) + .statusCode(400).body("__type", equalTo("SerializationException")); } @Test void trailingJsonReturnsSerializationException() { - given().contentType("application/json").header("Authorization", AUTH) - .body("{\"AlternateContactType\":\"SECURITY\"} {}") - .post("/getAlternateContact").then().statusCode(400).body("__type", equalTo("SerializationException")); + post("/getAlternateContact", "{\"AlternateContactType\":\"SECURITY\"} {}") + .statusCode(400).body("__type", equalTo("SerializationException")); } @Test @@ -58,20 +68,19 @@ class AccountAlternateContactIntegrationTest { } private static ValidatableResponse put(String email) { - return given().contentType("application/json").header("Authorization", AUTH) - .body("{\"AlternateContactType\":\"SECURITY\",\"Name\":\"Security\",\"Title\":\"Owner\",\"EmailAddress\":\"" + email + "\",\"PhoneNumber\":\"+12025550123\"}") - .post("/putAlternateContact").then(); + return post("/putAlternateContact", alternateContactRequest().put("EmailAddress", email).toString()); } private static ValidatableResponse get() { - return given().contentType("application/json").header("Authorization", AUTH) - .body("{\"AlternateContactType\":\"SECURITY\"}") - .post("/getAlternateContact").then(); + return post("/getAlternateContact", "{\"AlternateContactType\":\"SECURITY\"}"); } private static ValidatableResponse delete() { + return post("/deleteAlternateContact", "{\"AlternateContactType\":\"SECURITY\"}"); + } + + private static ValidatableResponse post(String path, String body) { return given().contentType("application/json").header("Authorization", AUTH) - .body("{\"AlternateContactType\":\"SECURITY\"}") - .post("/deleteAlternateContact").then(); + .body(body).post(path).then(); } } diff --git a/src/test/java/io/floci/aws/services/account/AccountOrganizationsContextIntegrationTest.java b/src/test/java/io/floci/aws/services/account/AccountOrganizationsContextIntegrationTest.java index 7ccb1c8607..2f10c38f04 100644 --- a/src/test/java/io/floci/aws/services/account/AccountOrganizationsContextIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/account/AccountOrganizationsContextIntegrationTest.java @@ -9,6 +9,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static io.floci.aws.services.account.AlternateContactRequests.alternateContactRequest; import static io.floci.aws.services.account.ContactInformationRequests.contactInformationRequest; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; @@ -74,8 +75,7 @@ class AccountOrganizationsContextIntegrationTest { } private static String alternateContact(String accountId) { - return "{\"AccountId\":\"" + accountId + "\",\"AlternateContactType\":\"SECURITY\",\"Name\":\"Security\"," - + "\"Title\":\"Owner\",\"EmailAddress\":\"security@example.com\",\"PhoneNumber\":\"+12025550123\"}"; + return alternateContactRequest().put("AccountId", accountId).toString(); } private static String createAccount(String name) { diff --git a/src/test/java/io/floci/aws/services/account/AccountServiceTest.java b/src/test/java/io/floci/aws/services/account/AccountServiceTest.java index 258295edf2..a4a3c862fc 100644 --- a/src/test/java/io/floci/aws/services/account/AccountServiceTest.java +++ b/src/test/java/io/floci/aws/services/account/AccountServiceTest.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; import java.time.Instant; @@ -24,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import static io.floci.aws.services.account.AlternateContactRequests.alternateContactRequest; import static io.floci.aws.services.account.ContactInformationRequests.contactInformationRequest; import static io.floci.aws.services.account.ContactInformationRequests.contactOf; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -58,7 +60,7 @@ class AccountServiceTest { @Test void ownAccountPutAndGetRoundTrip() { - ObjectNode request = contactRequest(); + ObjectNode request = alternateContactRequest(); service.putAlternateContact(ACCOUNT_ID, request); AlternateContact contact = service.getAlternateContact(ACCOUNT_ID, request); assertEquals("security@example.com", contact.getEmailAddress()); @@ -67,16 +69,17 @@ class AccountServiceTest { @Test void nonStringAccountIdReturnsSerializationException() { - ObjectNode request = contactRequest(); + ObjectNode request = alternateContactRequest(); request.put("AccountId", 123456789012L); AwsException error = assertThrows(AwsException.class, () -> service.putAlternateContact(ACCOUNT_ID, request)); assertEquals("SerializationException", error.getErrorCode()); + assertEquals("AccountId must be a string.", error.getMessage()); } @Test void clearRemovesContacts() { - ObjectNode request = contactRequest(); + ObjectNode request = alternateContactRequest(); service.putAlternateContact(ACCOUNT_ID, request); service.clear(); AwsException error = assertThrows(AwsException.class, @@ -86,7 +89,7 @@ class AccountServiceTest { @Test void deleteRemovesContactAndDeletingUnsetThrows() { - ObjectNode request = contactRequest(); + ObjectNode request = alternateContactRequest(); service.putAlternateContact(ACCOUNT_ID, request); service.deleteAlternateContact(ACCOUNT_ID, request); AwsException getError = assertThrows(AwsException.class, @@ -97,6 +100,105 @@ class AccountServiceTest { assertEquals("ResourceNotFoundException", deleteError.getErrorCode()); } + @ParameterizedTest + @ValueSource(strings = {"AlternateContactType", "Name", "Title", "EmailAddress", "PhoneNumber"}) + void putAlternateContactRejectsAMissingRequiredMember(String member) { + ObjectNode request = alternateContactRequest(); + request.remove(member); + assertAlternateContactRejected(() -> service.putAlternateContact(ACCOUNT_ID, request), member); + } + + @ParameterizedTest + @ValueSource(strings = {"BILLING", "OPERATIONS", "SECURITY"}) + void putAlternateContactAcceptsEachContactType(String type) { + ObjectNode request = alternateContactRequest(); + request.put("AlternateContactType", type); + service.putAlternateContact(ACCOUNT_ID, request); + + assertEquals(type, service.getAlternateContact(ACCOUNT_ID, request).getAlternateContactType()); + } + + @Test + void putAlternateContactAcceptsAPhoneNumberWithoutAPlus() { + ObjectNode request = alternateContactRequest(); + request.put("PhoneNumber", "12025550123"); + service.putAlternateContact(ACCOUNT_ID, request); + + assertEquals("12025550123", service.getAlternateContact(ACCOUNT_ID, request).getPhoneNumber()); + } + + @ParameterizedTest + @CsvSource({"Name,64", "Title,50", "PhoneNumber,25"}) + void putAlternateContactEnforcesTheMaximumLengthOfEachMember(String member, int maximum) { + ObjectNode request = alternateContactRequest(); + request.put(member, "1".repeat(maximum)); + service.putAlternateContact(ACCOUNT_ID, request); + + request.put(member, "1".repeat(maximum + 1)); + assertAlternateContactRejected(() -> service.putAlternateContact(ACCOUNT_ID, request), member); + } + + @Test + void putAlternateContactLimitsTheEmailAddressTo254Characters() { + ObjectNode request = alternateContactRequest(); + request.put("EmailAddress", "a".repeat(242) + "@example.com"); + service.putAlternateContact(ACCOUNT_ID, request); + + request.put("EmailAddress", "a".repeat(243) + "@example.com"); + assertAlternateContactRejected(() -> service.putAlternateContact(ACCOUNT_ID, request), "EmailAddress"); + } + + @ParameterizedTest + @CsvSource({"EmailAddress,security.example.com", "EmailAddress,security@example", "PhoneNumber,555-CALL", + "Name,''"}) + void putAlternateContactRejectsAMemberOutsideItsConstraints(String member, String value) { + ObjectNode request = alternateContactRequest(); + request.put(member, value); + assertAlternateContactRejected(() -> service.putAlternateContact(ACCOUNT_ID, request), member); + } + + @Test + void putAlternateContactWithANonStringMemberThrowsSerialization() { + ObjectNode request = alternateContactRequest(); + request.put("PhoneNumber", 15550100); + AwsException error = assertThrows(AwsException.class, + () -> service.putAlternateContact(ACCOUNT_ID, request)); + assertEquals("SerializationException", error.getErrorCode()); + assertEquals("PhoneNumber must be a string.", error.getMessage()); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = {"OTHER", "security"}) + void getAndDeleteAlternateContactRequireAKnownContactType(String type) { + ObjectNode request = mapper.createObjectNode().put("AlternateContactType", type); + + assertAlternateContactRejected(() -> service.getAlternateContact(ACCOUNT_ID, request), "AlternateContactType"); + assertAlternateContactRejected(() -> service.deleteAlternateContact(ACCOUNT_ID, request), + "AlternateContactType"); + } + + @Test + void alternateContactChecksTheRequestBeforeTheTargetAccount() { + when(organizations.describeOrganization(ACCOUNT_ID)) + .thenThrow(new AwsException("AWSOrganizationsNotInUseException", "no organization", 400)); + ObjectNode request = mapper.createObjectNode(); + request.put("AccountId", "111122223333"); + request.put("AlternateContactType", "OTHER"); + + assertAlternateContactRejected(() -> service.getAlternateContact(ACCOUNT_ID, request), "AlternateContactType"); + } + + @Test + void alternateContactRejectsAMalformedAccountId() { + ObjectNode request = alternateContactRequest(); + request.put("AccountId", "1234"); + + assertAlternateContactRejected(() -> service.putAlternateContact(ACCOUNT_ID, request), "AccountId"); + assertAlternateContactRejected(() -> service.getAlternateContact(ACCOUNT_ID, request), "AccountId"); + assertAlternateContactRejected(() -> service.deleteAlternateContact(ACCOUNT_ID, request), "AccountId"); + } + @Test void findsTheMemberAccountOfTheCallersOrganizationARequestNames() { Organization organization = new Organization(); @@ -338,7 +440,7 @@ class AccountServiceTest { @Test void delegatedAdministratorCannotNameTheManagementAccount() { callerIsInAnOrganizationManagedBy(MANAGEMENT_ACCOUNT_ID, delegatedAdministrator()); - ObjectNode alternateContact = contactRequest(); + ObjectNode alternateContact = alternateContactRequest(); alternateContact.put("AccountId", MANAGEMENT_ACCOUNT_ID); ObjectNode contactInformation = contactInformationRequest(); contactInformation.put("AccountId", MANAGEMENT_ACCOUNT_ID); @@ -353,7 +455,7 @@ class AccountServiceTest { @Test void managementAccountCannotNameItself() { callerIsInAnOrganizationManagedBy(ACCOUNT_ID, new OrganizationAccount()); - ObjectNode request = contactRequest(); + ObjectNode request = alternateContactRequest(); request.put("AccountId", ACCOUNT_ID); assertManagementAccountRefused(() -> service.putAlternateContact(ACCOUNT_ID, request)); @@ -362,13 +464,13 @@ class AccountServiceTest { @Test void delegatedAdministratorCanNameItsOwnAccount() { callerIsInAnOrganizationManagedBy(MANAGEMENT_ACCOUNT_ID, delegatedAdministrator()); - ObjectNode request = contactRequest(); + ObjectNode request = alternateContactRequest(); request.put("AccountId", ACCOUNT_ID); service.putAlternateContact(ACCOUNT_ID, request); assertEquals("security@example.com", - service.getAlternateContact(ACCOUNT_ID, contactRequest()).getEmailAddress()); + service.getAlternateContact(ACCOUNT_ID, alternateContactRequest()).getEmailAddress()); } @Test @@ -390,6 +492,12 @@ class AccountServiceTest { assertTrue(error.getMessage().contains(member), error.getMessage()); } + private static void assertAlternateContactRejected(Executable call, String member) { + AwsException error = assertThrows(AwsException.class, call, member); + assertEquals("ValidationException", error.getErrorCode()); + assertTrue(error.getMessage().startsWith("Invalid parameter at '" + member + "'"), error.getMessage()); + } + private void callerIsInAnOrganizationManagedBy(String managementAccountId, OrganizationAccount caller) { Organization organization = new Organization(); organization.setFeatureSet("ALL"); @@ -411,14 +519,4 @@ class AccountServiceTest { assertEquals(403, error.getHttpStatus()); assertTrue(error.getMessage().contains("management account of the organization"), error.getMessage()); } - - private ObjectNode contactRequest() { - ObjectNode request = mapper.createObjectNode(); - request.put("AlternateContactType", "SECURITY"); - request.put("EmailAddress", "security@example.com"); - request.put("Name", "Security Team"); - request.put("PhoneNumber", "+1 555 0100"); - request.put("Title", "Security"); - return request; - } } diff --git a/src/test/java/io/floci/aws/services/account/AlternateContactRequests.java b/src/test/java/io/floci/aws/services/account/AlternateContactRequests.java new file mode 100644 index 0000000000..8df0a1d93f --- /dev/null +++ b/src/test/java/io/floci/aws/services/account/AlternateContactRequests.java @@ -0,0 +1,23 @@ +package io.floci.aws.services.account; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +/** The valid {@code PutAlternateContact} request the alternate contact tests start from. */ +final class AlternateContactRequests { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private AlternateContactRequests() { + } + + static ObjectNode alternateContactRequest() { + ObjectNode request = MAPPER.createObjectNode(); + request.put("AlternateContactType", "SECURITY"); + request.put("Name", "Security Team"); + request.put("Title", "Security"); + request.put("EmailAddress", "security@example.com"); + request.put("PhoneNumber", "+1 555 0100"); + return request; + } +} diff --git a/tools/aws/regen_account_shapes.py b/tools/aws/regen_account_shapes.py index 923add1074..536b2a3741 100644 --- a/tools/aws/regen_account_shapes.py +++ b/tools/aws/regen_account_shapes.py @@ -2,7 +2,7 @@ """Vendor Account Management request constraints from botocore's Apache-2.0 service model. AccountRequestShapes checks the operations listed here through RequestConstraintCheck using the -model's types, required members, bounds and patterns. +model's types, required members, bounds, patterns and enums. Run from anywhere in the repo: python3 tools/aws/regen_account_shapes.py @@ -18,9 +18,11 @@ import request_shapes OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/account-request-shapes.json" MODEL = Path("account/2021-02-01") -# The alternate contact operations keep the hand-written checks of AccountService. OPERATIONS = ( + "DeleteAlternateContact", + "GetAlternateContact", "GetContactInformation", + "PutAlternateContact", "PutContactInformation", )