diff --git a/Makefile b/Makefile index 1e9ee89157..0e3b73c056 100644 --- a/Makefile +++ b/Makefile @@ -31,6 +31,8 @@ # by tools/aws/regen_athena_shapes.py. # 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. # 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. @@ -291,6 +293,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s $(PYTHON) tools/aws/regen_lambda_microvm_shapes.py $(PYTHON) tools/aws/regen_athena_shapes.py $(PYTHON) tools/aws/regen_cur_shapes.py + $(PYTHON) tools/aws/regen_account_shapes.py $(PYTHON) tools/aws/regen_payment_cryptography_shapes.py $(PYTHON) tools/aws/regen_payment_cryptography_data_shapes.py $(PYTHON) tools/aws/regen_cloudfront_keyvaluestore_shapes.py @@ -399,6 +402,10 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres echo "error: CUR request shapes are out of date; run 'make aws-data-sync'."; \ exit 1; \ } + @$(PYTHON) tools/aws/regen_account_shapes.py --check || { \ + echo "error: Account Management request shapes are out of date; run 'make aws-data-sync'."; \ + exit 1; \ + } @$(PYTHON) tools/aws/regen_payment_cryptography_shapes.py --check || { \ echo ""; \ echo "error: src/main/resources/aws/payment-cryptography-request-shapes.json is out of date."; \ diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccountContactInformationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccountContactInformationTest.java new file mode 100644 index 0000000000..8c8433b294 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccountContactInformationTest.java @@ -0,0 +1,64 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.account.AccountClient; +import software.amazon.awssdk.services.account.model.ContactInformation; +import software.amazon.awssdk.services.account.model.GetContactInformationResponse; +import software.amazon.awssdk.services.account.model.PhoneNumberVerificationStatus; +import software.amazon.awssdk.services.account.model.ValidationException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +@DisplayName("AWS Account Management contact information") +class AccountContactInformationTest { + + @Test + void putAndGetContactInformationUseAwsSdk() { + assumeFalse(TestFixtures.isRealAws(), "Writes emulator account contact state"); + + try (AccountClient account = TestFixtures.accountClient()) { + account.putContactInformation(request -> request + .contactInformation(contact().companyName("Example Corp").build())); + + GetContactInformationResponse response = account.getContactInformation(request -> { }); + ContactInformation information = response.contactInformation(); + assertThat(information).isNotNull(); + assertThat(information.fullName()).isEqualTo("Jane Doe"); + assertThat(information.addressLine1()).isEqualTo("1 Main St"); + assertThat(information.addressLine2()).isNull(); + assertThat(information.city()).isEqualTo("Seattle"); + assertThat(information.stateOrRegion()).isEqualTo("WA"); + assertThat(information.postalCode()).isEqualTo("98101"); + assertThat(information.countryCode()).isEqualTo("US"); + assertThat(information.phoneNumber()).isEqualTo("+12065550100"); + assertThat(information.companyName()).isEqualTo("Example Corp"); + assertThat(response.verificationStatus()).isEqualTo(PhoneNumberVerificationStatus.NOT_SUPPORTED); + } + } + + @Test + void putContactInformationSurfacesValidationExceptionThroughAwsSdk() { + assumeFalse(TestFixtures.isRealAws(), "Asserts the emulator's validation message"); + + try (AccountClient account = TestFixtures.accountClient()) { + assertThatThrownBy(() -> account.putContactInformation(request -> request + .contactInformation(contact().phoneNumber("12065550100").build()))) + .isInstanceOf(ValidationException.class) + .hasMessageContaining("PhoneNumber"); + } + } + + private static ContactInformation.Builder contact() { + return ContactInformation.builder() + .fullName("Jane Doe") + .addressLine1("1 Main St") + .city("Seattle") + .stateOrRegion("WA") + .postalCode("98101") + .countryCode("US") + .phoneNumber("+12065550100"); + } +} diff --git a/docs/services/account.md b/docs/services/account.md index 612a133f90..c91bfa18df 100644 --- a/docs/services/account.md +++ b/docs/services/account.md @@ -4,7 +4,7 @@ **Endpoint:** `http://localhost:4566` -Floci supports alternate-contact management over the AWS REST JSON protocol. +Floci supports alternate contacts and primary contact information over the AWS REST JSON protocol. ## Supported Actions @@ -14,14 +14,20 @@ Floci supports alternate-contact management over the AWS REST JSON protocol. | `PutAlternateContact` | - | | `GetAlternateContact` | - | | `DeleteAlternateContact` | - | +| `PutContactInformation` | Creates or replaces the primary contact information of an account (`POST /putContactInformation`) | +| `GetContactInformation` | Returns the primary contact information of an account and its phone verification status (`POST /getContactInformation`) | -Alternate contacts are isolated by caller account and stored through `StorageFactory`. +Alternate contacts and primary contact information are isolated by caller account and stored through `StorageFactory`. ## 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`. +`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. + +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. + AWS models provider-side `InternalServerException` and `TooManyRequestsException`; Floci does not synthesize those failures without an actual triggering condition. See the [AWS Account Management API Reference](https://docs.aws.amazon.com/accounts/latest/reference/API_Operations.html). diff --git a/docs/services/index.md b/docs/services/index.md index 75ef89faf1..ad2be9b111 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -51,7 +51,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CloudWatch RUM](rum.md) | `/appmonitor`, `/appmonitor/{name}`, `/appmonitors` | REST JSON | 5 | | [X-Ray](xray.md) | `/TraceSegments`, `/Traces`, `/TraceSummaries`, `/ServiceGraph`, `/TraceGraph`, `/GetSamplingRules`, `/CreateSamplingRule`, `/SamplingTargets`, `/TelemetryRecords` | REST JSON | 11 | | [GuardDuty](guardduty.md) | `/detector`, `/detector/{detectorId}`, `/detector/{detectorId}/admin`, `/admin/*`, `/tags/*` | REST JSON | 28 | -| [AWS Account Management](account.md) | `/putAlternateContact`, `/getAlternateContact`, `/deleteAlternateContact` | REST JSON | 3 | +| [AWS Account Management](account.md) | `/putAlternateContact`, `/getAlternateContact`, `/deleteAlternateContact`, `/putContactInformation`, `/getContactInformation` | REST JSON | 5 | | [IAM Access Analyzer](access-analyzer.md) | `/analyzer`, `/analyzer/{name}`, `/policy/validation` | REST JSON | 5 | | [IAM Identity Center (SSO Admin)](ssoadmin.md) | `POST /` + `X-Amz-Target: SWBExternalService.*` | JSON 1.1 | 79 | | [IAM Identity Center OIDC](ssooidc.md) | `/client/register`, `/device_authorization`, `/token`, `/token?aws_iam=t`, `/authorize`, `/device` | REST JSON | 4 | diff --git a/src/main/java/io/floci/aws/services/account/AccountController.java b/src/main/java/io/floci/aws/services/account/AccountController.java index 6fdd259d38..383a1ab364 100644 --- a/src/main/java/io/floci/aws/services/account/AccountController.java +++ b/src/main/java/io/floci/aws/services/account/AccountController.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.JsonErrorResponseUtils; import io.floci.aws.core.common.RequestContext; import io.floci.aws.services.account.model.AlternateContact; +import io.floci.aws.services.account.model.ContactInformation; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.POST; @@ -20,6 +21,9 @@ import jakarta.ws.rs.core.Response; @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class AccountController { + // Floci has no phone verification flow, so every account reports this status. + private static final String VERIFICATION_STATUS_NOT_SUPPORTED = "NOT_SUPPORTED"; + private final AccountService accountService; private final ObjectMapper objectMapper; private final RequestContext requestContext; @@ -54,13 +58,36 @@ public class AccountController { return Response.ok().build(); } + @POST + @Path("/putContactInformation") + public Response putContactInformation(String body) { + accountService.putContactInformation(requestContext.getAccountId(), readTree(body)); + return Response.ok().build(); + } + + @POST + @Path("/getContactInformation") + public Response getContactInformation(String body) { + ContactInformation information = accountService.getContactInformation( + requestContext.getAccountId(), readTree(body)); + ObjectNode response = objectMapper.createObjectNode(); + response.set("ContactInformation", objectMapper.valueToTree(information)); + response.put("VerificationStatus", VERIFICATION_STATUS_NOT_SUPPORTED); + return Response.ok(response).build(); + } + private JsonNode readTree(String body) { + JsonNode request; try { - return objectMapper.reader() + request = objectMapper.reader() .with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .readTree(body == null || body.isBlank() ? "{}" : body); } catch (Exception e) { throw new WebApplicationException(JsonErrorResponseUtils.createSerializationErrorResponse()); } + if (!request.isObject()) { + throw new WebApplicationException(JsonErrorResponseUtils.createSerializationErrorResponse()); + } + return request; } } diff --git a/src/main/java/io/floci/aws/services/account/AccountRequestShapes.java b/src/main/java/io/floci/aws/services/account/AccountRequestShapes.java new file mode 100644 index 0000000000..a5ea7fabd5 --- /dev/null +++ b/src/main/java/io/floci/aws/services/account/AccountRequestShapes.java @@ -0,0 +1,56 @@ +package io.floci.aws.services.account; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RequestConstraintCheck; + +import java.util.List; + +/** + * Checks the primary contact 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. + */ +final class AccountRequestShapes { + + private static final RequestConstraintCheck.Messages VALIDATION = + RequestConstraintCheck.standardMessages("ValidationException"); + + private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load( + "aws/account-request-shapes.json", "Account Management request shapes", + new RequestConstraintCheck.Messages() { + @Override + public AwsException type(String path, String type) { + String member = path.substring(path.indexOf('.') + 1); + return new AwsException("SerializationException", member + " must be a " + type + ".", 400); + } + + @Override + public AwsException bounds(String path, String type, Long min, Long max, Number size) { + return VALIDATION.bounds(path, type, min, max, size); + } + + @Override + public AwsException pattern(String path, String pattern) { + return VALIDATION.pattern(path, pattern); + } + + @Override + public AwsException enumValue(String path, List values) { + return VALIDATION.enumValue(path, values); + } + + @Override + public AwsException required(String path) { + return VALIDATION.required(path); + } + }); + + private AccountRequestShapes() { + } + + static void check(String operation, JsonNode request) { + CHECK.check(operation, request); + } +} 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 826cf021c3..59e278e02c 100644 --- a/src/main/java/io/floci/aws/services/account/AccountService.java +++ b/src/main/java/io/floci/aws/services/account/AccountService.java @@ -10,6 +10,7 @@ import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.account.model.AlternateContact; +import io.floci.aws.services.account.model.ContactInformation; import io.floci.aws.services.organizations.OrganizationsService; import io.floci.aws.services.organizations.model.Organization; import io.floci.aws.services.organizations.model.OrganizationAccount; @@ -17,6 +18,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -29,14 +31,20 @@ public class AccountService implements Resettable, StoredResourceArns { 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"; private final AccountAwareStorageBackend contacts; + private final AccountAwareStorageBackend contactInformation; private final OrganizationsService organizationsService; @Inject public AccountService(StorageFactory storageFactory, OrganizationsService organizationsService) { this.contacts = storageFactory.create("account", "account-alternate-contacts.json", new TypeReference>() {}); + this.contactInformation = storageFactory.create("account", "account-contact-information.json", + new TypeReference>() {}); this.organizationsService = organizationsService; } @@ -68,6 +76,39 @@ public class AccountService implements Resettable, StoredResourceArns { contacts.deleteForAccount(targetAccountId, type); } + public void putContactInformation(String callerAccountId, JsonNode request) { + AccountRequestShapes.check("PutContactInformation", request); + String targetAccountId = resolveTargetAccount(callerAccountId, request); + JsonNode contact = request.get("ContactInformation"); + ContactInformation information = new ContactInformation(); + information.setFullName(text(contact, "FullName")); + information.setAddressLine1(text(contact, "AddressLine1")); + information.setAddressLine2(text(contact, "AddressLine2")); + information.setAddressLine3(text(contact, "AddressLine3")); + information.setCity(text(contact, "City")); + information.setStateOrRegion(text(contact, "StateOrRegion")); + information.setDistrictOrCounty(text(contact, "DistrictOrCounty")); + information.setPostalCode(text(contact, "PostalCode")); + information.setCountryCode(text(contact, "CountryCode")); + information.setPhoneNumber(text(contact, "PhoneNumber")); + information.setCompanyName(text(contact, "CompanyName")); + information.setWebsiteUrl(text(contact, "WebsiteUrl")); + // Only the API reference states this rule, so the vendored model cannot check it. + if (information.getStateOrRegion() == null && COUNTRIES_REQUIRING_STATE_OR_REGION + .contains(information.getCountryCode().toUpperCase(Locale.ROOT))) { + throw validation("StateOrRegion is required when CountryCode is " + + information.getCountryCode() + "."); + } + contactInformation.putForAccount(targetAccountId, PRIMARY_CONTACT_KEY, information); + } + + public ContactInformation getContactInformation(String callerAccountId, JsonNode request) { + AccountRequestShapes.check("GetContactInformation", request); + String targetAccountId = resolveTargetAccount(callerAccountId, request); + return contactInformation.getForAccount(targetAccountId, PRIMARY_CONTACT_KEY) + .orElseThrow(AccountService::contactInformationNotFound); + } + private String resolveTargetAccount(String callerAccountId, JsonNode request) { JsonNode accountIdNode = request == null ? null : request.get("AccountId"); if (accountIdNode == null || accountIdNode.isNull()) { @@ -118,6 +159,7 @@ public class AccountService implements Resettable, StoredResourceArns { @Override public void clear() { contacts.clear(); + contactInformation.clear(); } /** The namespace of the resource types this service finds, as the request-resources table names it. */ @@ -187,4 +229,9 @@ public class AccountService implements Resettable, StoredResourceArns { return new AwsException("ResourceNotFoundException", "The alternate contact does not exist for the specified account and contact type.", 404); } + + private static AwsException contactInformationNotFound() { + return new AwsException("ResourceNotFoundException", + "The contact information does not exist for the specified account.", 404); + } } diff --git a/src/main/java/io/floci/aws/services/account/model/ContactInformation.java b/src/main/java/io/floci/aws/services/account/model/ContactInformation.java new file mode 100644 index 0000000000..2ded9e45d3 --- /dev/null +++ b/src/main/java/io/floci/aws/services/account/model/ContactInformation.java @@ -0,0 +1,132 @@ +package io.floci.aws.services.account.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ContactInformation { + @JsonProperty("AddressLine1") + private String addressLine1; + @JsonProperty("AddressLine2") + private String addressLine2; + @JsonProperty("AddressLine3") + private String addressLine3; + @JsonProperty("City") + private String city; + @JsonProperty("CompanyName") + private String companyName; + @JsonProperty("CountryCode") + private String countryCode; + @JsonProperty("DistrictOrCounty") + private String districtOrCounty; + @JsonProperty("FullName") + private String fullName; + @JsonProperty("PhoneNumber") + private String phoneNumber; + @JsonProperty("PostalCode") + private String postalCode; + @JsonProperty("StateOrRegion") + private String stateOrRegion; + @JsonProperty("WebsiteUrl") + private String websiteUrl; + + public String getAddressLine1() { + return addressLine1; + } + + public void setAddressLine1(String addressLine1) { + this.addressLine1 = addressLine1; + } + + public String getAddressLine2() { + return addressLine2; + } + + public void setAddressLine2(String addressLine2) { + this.addressLine2 = addressLine2; + } + + public String getAddressLine3() { + return addressLine3; + } + + public void setAddressLine3(String addressLine3) { + this.addressLine3 = addressLine3; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getCompanyName() { + return companyName; + } + + public void setCompanyName(String companyName) { + this.companyName = companyName; + } + + public String getCountryCode() { + return countryCode; + } + + public void setCountryCode(String countryCode) { + this.countryCode = countryCode; + } + + public String getDistrictOrCounty() { + return districtOrCounty; + } + + public void setDistrictOrCounty(String districtOrCounty) { + this.districtOrCounty = districtOrCounty; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getPhoneNumber() { + return phoneNumber; + } + + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } + + public String getPostalCode() { + return postalCode; + } + + public void setPostalCode(String postalCode) { + this.postalCode = postalCode; + } + + public String getStateOrRegion() { + return stateOrRegion; + } + + public void setStateOrRegion(String stateOrRegion) { + this.stateOrRegion = stateOrRegion; + } + + public String getWebsiteUrl() { + return websiteUrl; + } + + public void setWebsiteUrl(String websiteUrl) { + this.websiteUrl = websiteUrl; + } +} diff --git a/src/main/resources/aws/account-request-shapes.json b/src/main/resources/aws/account-request-shapes.json new file mode 100644 index 0000000000..edd6cfa3c2 --- /dev/null +++ b/src/main/resources/aws/account-request-shapes.json @@ -0,0 +1,108 @@ +{ + "_source": { + "generator": "tools/aws/regen_account_shapes.py", + "botocore": "botocore 1.43.118 (installed package)" + }, + "operations": { + "GetContactInformation": "GetContactInformationRequest", + "PutContactInformation": "PutContactInformationRequest" + }, + "shapes": { + "AccountId": { + "type": "string", + "pattern": "\\d{12}" + }, + "AddressLine": { + "type": "string", + "min": 1, + "max": 60 + }, + "City": { + "type": "string", + "min": 1, + "max": 50 + }, + "CompanyName": { + "type": "string", + "min": 1, + "max": 50 + }, + "ContactInformation": { + "type": "structure", + "required": [ + "FullName", + "AddressLine1", + "City", + "PostalCode", + "CountryCode", + "PhoneNumber" + ], + "members": { + "FullName": "FullName", + "AddressLine1": "AddressLine", + "AddressLine2": "AddressLine", + "AddressLine3": "AddressLine", + "City": "City", + "StateOrRegion": "StateOrRegion", + "DistrictOrCounty": "DistrictOrCounty", + "PostalCode": "PostalCode", + "CountryCode": "CountryCode", + "PhoneNumber": "ContactInformationPhoneNumber", + "CompanyName": "CompanyName", + "WebsiteUrl": "WebsiteUrl" + } + }, + "ContactInformationPhoneNumber": { + "type": "string", + "min": 1, + "max": 20, + "pattern": "[+][\\s0-9()-]+" + }, + "CountryCode": { + "type": "string", + "min": 2, + "max": 2 + }, + "DistrictOrCounty": { + "type": "string", + "min": 1, + "max": 50 + }, + "FullName": { + "type": "string", + "min": 1, + "max": 50 + }, + "GetContactInformationRequest": { + "type": "structure", + "members": { + "AccountId": "AccountId" + } + }, + "PostalCode": { + "type": "string", + "min": 1, + "max": 20 + }, + "PutContactInformationRequest": { + "type": "structure", + "required": [ + "ContactInformation" + ], + "members": { + "ContactInformation": "ContactInformation", + "AccountId": "AccountId" + } + }, + "StateOrRegion": { + "type": "string", + "min": 1, + "max": 50 + }, + "WebsiteUrl": { + "type": "string", + "min": 1, + "max": 256 + } + } +} diff --git a/src/test/java/io/floci/aws/services/account/AccountContactInformationIntegrationTest.java b/src/test/java/io/floci/aws/services/account/AccountContactInformationIntegrationTest.java new file mode 100644 index 0000000000..28ff599776 --- /dev/null +++ b/src/test/java/io/floci/aws/services/account/AccountContactInformationIntegrationTest.java @@ -0,0 +1,173 @@ +package io.floci.aws.services.account; + +import com.fasterxml.jackson.databind.ObjectMapper; +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 java.util.concurrent.atomic.AtomicInteger; + +import static io.floci.aws.services.account.ContactInformationRequests.contactInformationRequest; +import static io.floci.aws.services.account.ContactInformationRequests.contactOf; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; + +@QuarkusTest +class AccountContactInformationIntegrationTest { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final AtomicInteger ACCOUNTS = new AtomicInteger(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void putThenGetReturnsTheContactAndItsVerificationStatus() { + String account = newAccount(); + ObjectNode request = contactInformationRequest(); + contactOf(request).put("CompanyName", "Example Corp"); + + put(account, request).statusCode(200).body(equalTo("")); + + get(account, "{}").statusCode(200) + .body("ContactInformation.FullName", equalTo("Jane Doe")) + .body("ContactInformation.AddressLine1", equalTo("1 Main St")) + .body("ContactInformation.City", equalTo("Seattle")) + .body("ContactInformation.StateOrRegion", equalTo("WA")) + .body("ContactInformation.PostalCode", equalTo("98101")) + .body("ContactInformation.CountryCode", equalTo("US")) + .body("ContactInformation.PhoneNumber", equalTo("+12065550100")) + .body("ContactInformation.CompanyName", equalTo("Example Corp")) + .body("ContactInformation", not(hasKey("AddressLine2"))) + .body("ContactInformation", not(hasKey("WebsiteUrl"))) + .body("VerificationStatus", equalTo("NOT_SUPPORTED")); + } + + @Test + void putReplacesTheStoredContact() { + String account = newAccount(); + ObjectNode first = contactInformationRequest(); + contactOf(first).put("CompanyName", "Example Corp"); + put(account, first).statusCode(200); + + ObjectNode second = contactInformationRequest(); + contactOf(second).put("FullName", "John Roe"); + put(account, second).statusCode(200); + + get(account, "{}").statusCode(200) + .body("ContactInformation.FullName", equalTo("John Roe")) + .body("ContactInformation", not(hasKey("CompanyName"))); + } + + @Test + void getBeforePutReturnsResourceNotFound() { + get(newAccount(), "{}").statusCode(404).body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + void contactsAreIsolatedByCallerAccount() { + String owner = newAccount(); + put(owner, contactInformationRequest()).statusCode(200); + + get(owner, "{}").statusCode(200); + get(newAccount(), "{}").statusCode(404).body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + void putWithoutContactInformationReturnsValidationException() { + put(newAccount(), MAPPER.createObjectNode()) + .statusCode(400).body("__type", equalTo("ValidationException")); + } + + @Test + void putWithNonStructureContactInformationReturnsSerializationException() { + ObjectNode request = MAPPER.createObjectNode(); + request.put("ContactInformation", "Jane Doe"); + + put(newAccount(), request).statusCode(400).body("__type", equalTo("SerializationException")); + } + + @Test + void nonObjectRequestBodyReturnsSerializationException() { + String account = newAccount(); + put(account, contactInformationRequest()).statusCode(200); + + get(account, "[]").statusCode(400).body("__type", equalTo("SerializationException")); + post(account, "/putContactInformation", "[]") + .statusCode(400).body("__type", equalTo("SerializationException")); + } + + @Test + void rejectedPutKeepsThePreviousContact() { + String account = newAccount(); + put(account, contactInformationRequest()).statusCode(200); + ObjectNode invalid = contactInformationRequest(); + contactOf(invalid).put("FullName", "John Roe"); + contactOf(invalid).put("PhoneNumber", "12065550100"); + + put(account, invalid).statusCode(400).body("__type", equalTo("ValidationException")); + + get(account, "{}").statusCode(200).body("ContactInformation.FullName", equalTo("Jane Doe")); + } + + @Test + void putRequiresStateOrRegionForTheUnitedStates() { + ObjectNode request = contactInformationRequest(); + contactOf(request).remove("StateOrRegion"); + + put(newAccount(), request).statusCode(400).body("__type", equalTo("ValidationException")); + } + + @Test + void nonStringAccountIdReturnsSerializationException() { + String account = newAccount(); + ObjectNode request = contactInformationRequest(); + request.put("AccountId", 123456789012L); + + put(account, request).statusCode(400).body("__type", equalTo("SerializationException")); + get(account, "{\"AccountId\":123456789012}") + .statusCode(400).body("__type", equalTo("SerializationException")); + } + + @Test + void anotherAccountIsRefusedOutsideAnOrganization() { + String account = newAccount(); + ObjectNode request = contactInformationRequest(); + request.put("AccountId", "111122223333"); + + put(account, request).statusCode(403).body("__type", equalTo("AccessDeniedException")); + get(account, "{\"AccountId\":\"111122223333\"}") + .statusCode(403).body("__type", equalTo("AccessDeniedException")); + } + + /** + * Contact information cannot be deleted, so every test acts on an account of its own. A 12-digit access key + * ID is the account ID a request acts as. + */ + private static String newAccount() { + return String.format("7310008259%02d", ACCOUNTS.incrementAndGet()); + } + + private static ValidatableResponse put(String account, ObjectNode request) { + return post(account, "/putContactInformation", request.toString()); + } + + private static ValidatableResponse get(String account, String body) { + return post(account, "/getContactInformation", body); + } + + private static ValidatableResponse post(String account, String path, String body) { + return given().contentType("application/json").header("Authorization", authorization(account)) + .body(body).post(path).then(); + } + + private static String authorization(String account) { + return "AWS4-HMAC-SHA256 Credential=" + account + "/20261114/us-east-1/account/aws4_request"; + } +} 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 17e662f260..75069d14da 100644 --- a/src/test/java/io/floci/aws/services/account/AccountServiceTest.java +++ b/src/test/java/io/floci/aws/services/account/AccountServiceTest.java @@ -4,19 +4,29 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.ServicePrincipals; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.account.model.AlternateContact; +import io.floci.aws.services.account.model.ContactInformation; import io.floci.aws.services.organizations.OrganizationsService; import io.floci.aws.services.organizations.model.Organization; +import io.floci.aws.services.organizations.model.OrganizationAccount; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; +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; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -37,6 +47,9 @@ class AccountServiceTest { AccountAwareStorageBackend store = AccountAwareStorageBackend.inMemory(ACCOUNT_ID); when(storageFactory.create(eq("account"), eq("account-alternate-contacts.json"), any(TypeReference.class))) .thenReturn((AccountAwareStorageBackend) store); + AccountAwareStorageBackend primaryStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID); + when(storageFactory.create(eq("account"), eq("account-contact-information.json"), any(TypeReference.class))) + .thenReturn((AccountAwareStorageBackend) primaryStore); organizations = mock(OrganizationsService.class); service = new AccountService(storageFactory, organizations); } @@ -106,6 +119,244 @@ class AccountServiceTest { assertEquals(Optional.empty(), service.find("accountInOrganization", List.of("111122223333"), "us-east-1")); } + @Test + void contactInformationPutAndGetRoundTrip() { + ObjectNode request = contactInformationRequest(); + ObjectNode contact = contactOf(request); + contact.put("AddressLine2", "Suite 500"); + contact.put("CompanyName", "Example Corp"); + contact.put("WebsiteUrl", "https://example.com"); + + service.putContactInformation(ACCOUNT_ID, request); + ContactInformation stored = service.getContactInformation(ACCOUNT_ID, mapper.createObjectNode()); + + assertEquals("Jane Doe", stored.getFullName()); + assertEquals("1 Main St", stored.getAddressLine1()); + assertEquals("Suite 500", stored.getAddressLine2()); + assertNull(stored.getAddressLine3()); + assertEquals("Seattle", stored.getCity()); + assertEquals("WA", stored.getStateOrRegion()); + assertNull(stored.getDistrictOrCounty()); + assertEquals("98101", stored.getPostalCode()); + assertEquals("US", stored.getCountryCode()); + assertEquals("+12065550100", stored.getPhoneNumber()); + assertEquals("Example Corp", stored.getCompanyName()); + assertEquals("https://example.com", stored.getWebsiteUrl()); + } + + @Test + void putContactInformationReplacesThePreviousContact() { + ObjectNode first = contactInformationRequest(); + contactOf(first).put("CompanyName", "Example Corp"); + service.putContactInformation(ACCOUNT_ID, first); + + ObjectNode second = contactInformationRequest(); + contactOf(second).put("FullName", "John Roe"); + service.putContactInformation(ACCOUNT_ID, second); + + ContactInformation stored = service.getContactInformation(ACCOUNT_ID, mapper.createObjectNode()); + assertEquals("John Roe", stored.getFullName()); + assertNull(stored.getCompanyName()); + } + + @Test + void getContactInformationBeforePutThrowsResourceNotFound() { + AwsException error = assertThrows(AwsException.class, + () -> service.getContactInformation(ACCOUNT_ID, mapper.createObjectNode())); + assertEquals("ResourceNotFoundException", error.getErrorCode()); + assertEquals(404, error.getHttpStatus()); + } + + @Test + void putContactInformationWithoutContactInformationThrowsValidation() { + AwsException error = assertThrows(AwsException.class, + () -> service.putContactInformation(ACCOUNT_ID, mapper.createObjectNode())); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void putContactInformationWithNonStructureContactInformationThrowsSerialization() { + ObjectNode request = mapper.createObjectNode(); + request.put("ContactInformation", "Jane Doe"); + AwsException error = assertThrows(AwsException.class, + () -> service.putContactInformation(ACCOUNT_ID, request)); + assertEquals("SerializationException", error.getErrorCode()); + } + + @Test + void putContactInformationWithANonStringMemberThrowsSerialization() { + ObjectNode request = contactInformationRequest(); + contactOf(request).put("PostalCode", 98101); + AwsException error = assertThrows(AwsException.class, + () -> service.putContactInformation(ACCOUNT_ID, request)); + assertEquals("SerializationException", error.getErrorCode()); + } + + @ParameterizedTest + @ValueSource(strings = {"FullName", "AddressLine1", "City", "PostalCode", "CountryCode", "PhoneNumber"}) + void putContactInformationRejectsAMissingRequiredMember(String member) { + ObjectNode request = contactInformationRequest(); + contactOf(request).remove(member); + AwsException error = assertThrows(AwsException.class, + () -> service.putContactInformation(ACCOUNT_ID, request)); + assertEquals("ValidationException", error.getErrorCode()); + assertTrue(error.getMessage().contains(member), error.getMessage()); + } + + @ParameterizedTest + @CsvSource({"FullName,50", "AddressLine1,60", "AddressLine2,60", "AddressLine3,60", "City,50", + "StateOrRegion,50", "DistrictOrCounty,50", "PostalCode,20", "CompanyName,50", "WebsiteUrl,256"}) + void putContactInformationEnforcesTheMaximumLengthOfEachMember(String member, int maximum) { + ObjectNode request = contactInformationRequest(); + contactOf(request).put(member, "1".repeat(maximum)); + service.putContactInformation(ACCOUNT_ID, request); + + assertContactInformationRejected(member, "1".repeat(maximum + 1)); + } + + @Test + void putContactInformationRejectsAnEmptyOptionalMember() { + assertContactInformationRejected("AddressLine2", ""); + } + + @ParameterizedTest + @ValueSource(strings = {"U", "USA"}) + void putContactInformationRequiresATwoCharacterCountryCode(String countryCode) { + assertContactInformationRejected("CountryCode", countryCode); + } + + @Test + void putContactInformationAcceptsSpacesParenthesesAndHyphensInThePhoneNumber() { + ObjectNode request = contactInformationRequest(); + contactOf(request).put("PhoneNumber", "+1 (206) 555-0100"); + + service.putContactInformation(ACCOUNT_ID, request); + + assertEquals("+1 (206) 555-0100", + service.getContactInformation(ACCOUNT_ID, mapper.createObjectNode()).getPhoneNumber()); + } + + @ParameterizedTest + @ValueSource(strings = {"12065550100", "+", "1+2065550100", "+1 206 555 ext 7"}) + void putContactInformationRejectsAPhoneNumberOutsideThePattern(String phoneNumber) { + assertContactInformationRejected("PhoneNumber", phoneNumber); + } + + @Test + void putContactInformationLimitsThePhoneNumberToTwentyCharacters() { + ObjectNode request = contactInformationRequest(); + contactOf(request).put("PhoneNumber", "+" + "1".repeat(19)); + service.putContactInformation(ACCOUNT_ID, request); + + assertContactInformationRejected("PhoneNumber", "+" + "1".repeat(20)); + } + + @ParameterizedTest + @ValueSource(strings = {"US", "CA", "GB", "DE", "JP", "IN", "BR"}) + void putContactInformationRequiresStateOrRegionForTheDocumentedCountries(String countryCode) { + ObjectNode request = contactInformationRequest(); + ObjectNode contact = contactOf(request); + contact.put("CountryCode", countryCode); + contact.remove("StateOrRegion"); + AwsException error = assertThrows(AwsException.class, + () -> service.putContactInformation(ACCOUNT_ID, request)); + assertEquals("ValidationException", error.getErrorCode()); + assertTrue(error.getMessage().contains("StateOrRegion"), error.getMessage()); + } + + @Test + void putContactInformationRequiresStateOrRegionForALowercaseCountryCode() { + ObjectNode request = contactInformationRequest(); + ObjectNode contact = contactOf(request); + contact.put("CountryCode", "us"); + contact.remove("StateOrRegion"); + AwsException error = assertThrows(AwsException.class, + () -> service.putContactInformation(ACCOUNT_ID, request)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void putContactInformationAllowsNoStateOrRegionElsewhere() { + ObjectNode request = contactInformationRequest(); + ObjectNode contact = contactOf(request); + contact.put("CountryCode", "FR"); + contact.remove("StateOrRegion"); + + service.putContactInformation(ACCOUNT_ID, request); + + assertNull(service.getContactInformation(ACCOUNT_ID, mapper.createObjectNode()).getStateOrRegion()); + } + + @Test + void contactInformationForAnotherAccountNeedsAnOrganization() { + when(organizations.describeOrganization(ACCOUNT_ID)) + .thenThrow(new AwsException("AWSOrganizationsNotInUseException", "no organization", 400)); + ObjectNode request = contactInformationRequest(); + request.put("AccountId", "111122223333"); + + AwsException putError = assertThrows(AwsException.class, + () -> service.putContactInformation(ACCOUNT_ID, request)); + assertEquals("AccessDeniedException", putError.getErrorCode()); + AwsException getError = assertThrows(AwsException.class, + () -> service.getContactInformation(ACCOUNT_ID, request)); + assertEquals("AccessDeniedException", getError.getErrorCode()); + } + + @Test + void contactInformationRejectsAMalformedAccountId() { + ObjectNode request = contactInformationRequest(); + request.put("AccountId", "1234"); + + AwsException putError = assertThrows(AwsException.class, + () -> service.putContactInformation(ACCOUNT_ID, request)); + assertEquals("ValidationException", putError.getErrorCode()); + AwsException getError = assertThrows(AwsException.class, + () -> service.getContactInformation(ACCOUNT_ID, request)); + assertEquals("ValidationException", getError.getErrorCode()); + } + + @Test + void managementAccountPutsContactInformationForAMemberAccount() { + String member = "111122223333"; + Organization organization = new Organization(); + organization.setFeatureSet("ALL"); + organization.setMasterAccountId(ACCOUNT_ID); + organization.setEnabledServicePrincipals(Map.of(ServicePrincipals.of("account"), Instant.EPOCH)); + when(organizations.describeOrganization(ACCOUNT_ID)).thenReturn(organization); + when(organizations.describeAccount(ACCOUNT_ID, ACCOUNT_ID)).thenReturn(new OrganizationAccount()); + ObjectNode request = contactInformationRequest(); + request.put("AccountId", member); + + service.putContactInformation(ACCOUNT_ID, request); + + ObjectNode memberRequest = mapper.createObjectNode(); + memberRequest.put("AccountId", member); + assertEquals("Jane Doe", service.getContactInformation(ACCOUNT_ID, memberRequest).getFullName()); + assertEquals("Jane Doe", service.getContactInformation(member, mapper.createObjectNode()).getFullName()); + AwsException error = assertThrows(AwsException.class, + () -> service.getContactInformation(ACCOUNT_ID, mapper.createObjectNode())); + assertEquals("ResourceNotFoundException", error.getErrorCode()); + } + + @Test + void clearRemovesContactInformation() { + service.putContactInformation(ACCOUNT_ID, contactInformationRequest()); + service.clear(); + AwsException error = assertThrows(AwsException.class, + () -> service.getContactInformation(ACCOUNT_ID, mapper.createObjectNode())); + assertEquals("ResourceNotFoundException", error.getErrorCode()); + } + + private void assertContactInformationRejected(String member, String value) { + ObjectNode request = contactInformationRequest(); + contactOf(request).put(member, value); + AwsException error = assertThrows(AwsException.class, + () -> service.putContactInformation(ACCOUNT_ID, request), + member + "=" + value); + assertEquals("ValidationException", error.getErrorCode()); + assertTrue(error.getMessage().contains(member), error.getMessage()); + } + private ObjectNode contactRequest() { ObjectNode request = mapper.createObjectNode(); request.put("AlternateContactType", "SECURITY"); diff --git a/src/test/java/io/floci/aws/services/account/ContactInformationRequests.java b/src/test/java/io/floci/aws/services/account/ContactInformationRequests.java new file mode 100644 index 0000000000..068afb949c --- /dev/null +++ b/src/test/java/io/floci/aws/services/account/ContactInformationRequests.java @@ -0,0 +1,31 @@ +package io.floci.aws.services.account; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +/** The valid {@code PutContactInformation} request the primary contact tests start from. */ +final class ContactInformationRequests { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private ContactInformationRequests() { + } + + static ObjectNode contactInformationRequest() { + ObjectNode contact = MAPPER.createObjectNode(); + contact.put("FullName", "Jane Doe"); + contact.put("AddressLine1", "1 Main St"); + contact.put("City", "Seattle"); + contact.put("StateOrRegion", "WA"); + contact.put("PostalCode", "98101"); + contact.put("CountryCode", "US"); + contact.put("PhoneNumber", "+12065550100"); + ObjectNode request = MAPPER.createObjectNode(); + request.set("ContactInformation", contact); + return request; + } + + static ObjectNode contactOf(ObjectNode request) { + return (ObjectNode) request.get("ContactInformation"); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java index 9e3b31ea65..f1ecf9b710 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java @@ -845,6 +845,8 @@ class IamRestRouteEnforcementIntegrationTest { checkedAs(user, "account", "POST", "/getAlternateContact", "{\"AlternateContactType\":\"BILLING\"}", "account:GetAlternateContact"); + checkedAs(user, "account", "POST", "/getContactInformation", "{}", "account:GetContactInformation"); + checkedAs(user, "account", "POST", "/putContactInformation", "{}", "account:PutContactInformation"); checkedAs(user, "controlcatalog", "POST", "/list-controls", "{}", "controlcatalog:ListControls"); checkedAs(user, "fis", "GET", "/experimentTemplates", null, "fis:ListExperimentTemplates"); checkedAs(user, "oam", "POST", "/ListSinks", "{}", "oam:ListSinks"); diff --git a/tools/aws/regen_account_shapes.py b/tools/aws/regen_account_shapes.py new file mode 100644 index 0000000000..923add1074 --- /dev/null +++ b/tools/aws/regen_account_shapes.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""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. + +Run from anywhere in the repo: + python3 tools/aws/regen_account_shapes.py + python3 tools/aws/regen_account_shapes.py --check +""" +from __future__ import annotations + +import sys +from pathlib import Path + +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 = ( + "GetContactInformation", + "PutContactInformation", +) + + +def main(argv: list[str] | None = None) -> int: + return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, + description=__doc__, operations=OPERATIONS) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.py index 2420c967bd..61ed6d383a 100644 --- a/tools/aws/test_request_shapes.py +++ b/tools/aws/test_request_shapes.py @@ -18,6 +18,7 @@ from pathlib import Path import pytest +import regen_account_shapes import regen_apigateway_documentation_shapes import regen_apigateway_shapes import regen_athena_shapes @@ -390,6 +391,7 @@ def test_build_constraints_output_is_stable(): (regen_iam_shapes, "iam/2010-05-08", "iam-request-shapes.json", {"prepare": regen_iam_shapes.prepare}), (regen_sts_shapes, "sts/2011-06-15", "sts-request-shapes.json", {}), + (regen_account_shapes, "account/2021-02-01", "account-request-shapes.json", {}), (regen_securityhub_shapes, "securityhub/2018-10-26", "securityhub-request-shapes.json", {"prepare": regen_securityhub_shapes.prepare}), ]) @@ -449,6 +451,7 @@ def vendored(script) -> tuple[str, ...]: regen_athena_shapes, regen_cur_shapes, regen_lambda_microvm_shapes, + regen_account_shapes, ]) def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_shapes(script): doc = json.loads(script.OUTPUT.read_text(encoding="utf-8"))