From 93c1d39348b4dc959ec9384aba4761aadb8d0b3c Mon Sep 17 00:00:00 2001 From: Yang Hao <1994728136@qq.com> Date: Tue, 17 Nov 2026 18:58:24 +0800 Subject: [PATCH] feat(account): implement GetAccountInformation and PutAccountName (#8725) --- Makefile | 3 +- .../java/com/floci/test/TestFixtures.java | 6 +- .../floci/test/AccountInformationTest.java | 91 +++++++++ docs/services/account.md | 12 +- docs/services/index.md | 2 +- .../services/account/AccountController.java | 28 +++ .../aws/services/account/AccountService.java | 57 +++++- .../account/model/AccountInformation.java | 8 + .../organizations/OrganizationsService.java | 26 ++- .../services/ssoportal/SsoPortalService.java | 2 +- .../resources/aws/account-request-shapes.json | 24 +++ ...ountContactInformationIntegrationTest.java | 27 +-- .../AccountInformationIntegrationTest.java | 85 ++++++++ .../services/account/AccountNameRequests.java | 23 +++ ...ntOrganizationsContextIntegrationTest.java | 113 +++++++++- .../aws/services/account/AccountRequests.java | 19 ++ .../services/account/AccountServiceTest.java | 193 +++++++++++++++++- ...amRestRouteEnforcementIntegrationTest.java | 2 + .../OrganizationsServiceTest.java | 23 +++ .../ssoportal/SsoPortalServiceTest.java | 2 +- tools/aws/regen_account_shapes.py | 2 + 21 files changed, 698 insertions(+), 50 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccountInformationTest.java create mode 100644 src/main/java/io/floci/aws/services/account/model/AccountInformation.java create mode 100644 src/test/java/io/floci/aws/services/account/AccountInformationIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/account/AccountNameRequests.java create mode 100644 src/test/java/io/floci/aws/services/account/AccountRequests.java diff --git a/Makefile b/Makefile index 834739f1ed..4414b52574 100644 --- a/Makefile +++ b/Makefile @@ -37,7 +37,8 @@ # every operation, is generated from botocore's emr-containers model by # tools/aws/regen_emr_containers_shapes.py. # src/main/resources/aws/account-request-shapes.json, the Account Management request constraints of the -# contact operations, is generated from botocore's Account model by tools/aws/regen_account_shapes.py. +# contact and account information 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/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index 51a52affa0..4435b55a17 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -554,10 +554,14 @@ public final class TestFixtures { } public static AccountClient accountClient() { + return accountClient("test"); + } + + public static AccountClient accountClient(String accountId) { return AccountClient.builder() .endpointOverride(ENDPOINT) .region(REGION) - .credentialsProvider(CREDENTIALS) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accountId, "test"))) .build(); } diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccountInformationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccountInformationTest.java new file mode 100644 index 0000000000..3744a44a10 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AccountInformationTest.java @@ -0,0 +1,91 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; +import software.amazon.awssdk.services.account.AccountClient; +import software.amazon.awssdk.services.account.model.AccountState; +import software.amazon.awssdk.services.account.model.GetAccountInformationResponse; +import software.amazon.awssdk.services.account.model.ValidationException; +import software.amazon.awssdk.services.organizations.OrganizationsClient; +import software.amazon.awssdk.services.organizations.model.Account; +import software.amazon.awssdk.services.organizations.model.OrganizationFeatureSet; + +import java.time.temporal.ChronoUnit; + +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 account information") +class AccountInformationTest { + private static final String STANDALONE_ACCOUNT = "731000830101"; + private static final String MANAGEMENT_ACCOUNT = "731000830102"; + + @Test + @DisplayName("names an account in no organization") + void putAndGetAccountNameUseAwsSdk() { + assumeFalse(TestFixtures.isRealAws(), "Writes emulator account state"); + + try (AccountClient account = TestFixtures.accountClient(STANDALONE_ACCOUNT)) { + account.putAccountName(request -> request.accountName("Dev Sandbox")); + + GetAccountInformationResponse information = account.getAccountInformation(request -> { }); + assertThat(information.accountId()).isEqualTo(STANDALONE_ACCOUNT); + assertThat(information.accountName()).isEqualTo("Dev Sandbox"); + assertThat(information.accountState()).isEqualTo(AccountState.ACTIVE); + assertThat(information.accountCreatedDate()).isNull(); + + assertThatThrownBy(() -> account.putAccountName(request -> request.accountName(""))) + .isInstanceOf(ValidationException.class) + .hasMessageContaining("AccountName"); + } + } + + @Test + @DisplayName("renames a member account as Organizations describes it") + @ResourceLock("organizations") + void putAccountNameRenamesAMemberAccountUseAwsSdk() { + assumeFalse(TestFixtures.isRealAws(), "Creates an organization and a member account"); + + try (OrganizationsClient organizations = TestFixtures.organizationsClient(MANAGEMENT_ACCOUNT); + AccountClient account = TestFixtures.accountClient(MANAGEMENT_ACCOUNT)) { + organizations.createOrganization(request -> request.featureSet(OrganizationFeatureSet.ALL)); + String member = null; + try { + organizations.enableAWSServiceAccess(request -> request.servicePrincipal("account.amazonaws.com")); + String created = organizations.createAccount(request -> request + .email("account-information@example.com").accountName("account-information")) + .createAccountStatus().accountId(); + member = created; + + account.putAccountName(request -> request.accountId(created).accountName("Renamed Member")); + + Account described = organizations.describeAccount(request -> request.accountId(created)).account(); + assertThat(described.name()).isEqualTo("Renamed Member"); + GetAccountInformationResponse information = + account.getAccountInformation(request -> request.accountId(created)); + assertThat(information.accountId()).isEqualTo(created); + assertThat(information.accountName()).isEqualTo("Renamed Member"); + assertThat(information.accountState()).isEqualTo(AccountState.ACTIVE); + assertThat(information.accountCreatedDate()) + .isEqualTo(described.joinedTimestamp().truncatedTo(ChronoUnit.SECONDS)); + } finally { + removeOrganization(organizations, member); + } + } + } + + /** Best effort, so a failed assertion above stays the reported failure. */ + private static void removeOrganization(OrganizationsClient organizations, String member) { + try { + if (member != null) { + organizations.removeAccountFromOrganization(request -> request.accountId(member)); + } + organizations.deleteOrganization(); + } catch (RuntimeException e) { + System.err.println("[WARN] Organizations cleanup failed, leaving the organization in place: " + + e.getMessage()); + } + } +} diff --git a/docs/services/account.md b/docs/services/account.md index f379d0ab62..71ac4c31b0 100644 --- a/docs/services/account.md +++ b/docs/services/account.md @@ -4,7 +4,7 @@ **Endpoint:** `http://localhost:4566` -Floci supports alternate contacts and primary contact information over the AWS REST JSON protocol. +Floci supports alternate contacts, primary contact information and account information over the AWS REST JSON protocol. ## Supported Actions @@ -16,15 +16,21 @@ Floci supports alternate contacts and primary contact information over the AWS R | `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`) | +| `GetAccountInformation` | Returns the ID, name, creation date and state of an account (`POST /getAccountInformation`) | +| `PutAccountName` | Renames an account (`POST /putAccountName`) | Alternate contacts and primary contact information are isolated by caller account and stored through `StorageFactory`. +An account in an organization takes its name, creation date and state from its Organizations record. `PutAccountName` renames that record, so `DescribeAccount` and `ListAccounts` answer the new name at once. `AccountCreatedDate` is the `JoinedTimestamp` of an account that Organizations `CreateAccount` made; an invited account and the management account have none. An account that `CloseAccount` left `PENDING_CLOSURE`, a state Account Management does not have, reports `ACTIVE`. + +Account Management also keeps a name for each account through `StorageFactory`: the one `PutAccountName` last set, or else the name the account had in Organizations when it was created in or invited into an organization. An account that leaves its organization answers that name. The management account keeps one only if `PutAccountName` gave it one, so it has none after `DeleteOrganization` otherwise. An account in no organization is `ACTIVE`. It has no creation date, and no name until it is given one, because Floci has no sign-up to take them from. + ## AWS-compatible failures -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. +Requests of all seven 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`), the `PhoneNumber` pattern of `PutContactInformation` (a `+` followed by digits, spaces, parentheses, or hyphens), and the `AccountName` of `PutAccountName` (1 to 50 printable ASCII characters other than `<` and `>`). `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. -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. +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 and account information 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/docs/services/index.md b/docs/services/index.md index c9087df1f3..f93e09cba7 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`, `/putContactInformation`, `/getContactInformation` | REST JSON | 5 | +| [AWS Account Management](account.md) | `/putAlternateContact`, `/getAlternateContact`, `/deleteAlternateContact`, `/putContactInformation`, `/getContactInformation`, `/getAccountInformation`, `/putAccountName` | REST JSON | 7 | | [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 383a1ab364..46d9de33e4 100644 --- a/src/main/java/io/floci/aws/services/account/AccountController.java +++ b/src/main/java/io/floci/aws/services/account/AccountController.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; 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.AccountInformation; import io.floci.aws.services.account.model.AlternateContact; import io.floci.aws.services.account.model.ContactInformation; import jakarta.inject.Inject; @@ -17,6 +18,8 @@ import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; +import java.time.temporal.ChronoUnit; + @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -76,6 +79,31 @@ public class AccountController { return Response.ok(response).build(); } + @POST + @Path("/getAccountInformation") + public Response getAccountInformation(String body) { + AccountInformation information = accountService.getAccountInformation( + requestContext.getAccountId(), readTree(body)); + ObjectNode response = objectMapper.createObjectNode(); + response.put("AccountId", information.accountId()); + if (information.accountName() != null) { + response.put("AccountName", information.accountName()); + } + if (information.accountCreatedDate() != null) { + response.put("AccountCreatedDate", + information.accountCreatedDate().truncatedTo(ChronoUnit.SECONDS).toString()); + } + response.put("AccountState", information.accountState()); + return Response.ok(response).build(); + } + + @POST + @Path("/putAccountName") + public Response putAccountName(String body) { + accountService.putAccountName(requestContext.getAccountId(), readTree(body)); + return Response.ok().build(); + } + private JsonNode readTree(String body) { JsonNode request; try { 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 c7e04f74fa..a3cfe60c60 100644 --- a/src/main/java/io/floci/aws/services/account/AccountService.java +++ b/src/main/java/io/floci/aws/services/account/AccountService.java @@ -9,14 +9,17 @@ import io.floci.aws.core.common.ServicePrincipals; 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.AccountInformation; import io.floci.aws.services.account.model.AlternateContact; import io.floci.aws.services.account.model.ContactInformation; +import io.floci.aws.services.organizations.AccountPlacementListener; import io.floci.aws.services.organizations.OrganizationsService; import io.floci.aws.services.organizations.model.Organization; import io.floci.aws.services.organizations.model.OrganizationAccount; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import java.time.Instant; import java.util.List; import java.util.Locale; import java.util.Map; @@ -24,14 +27,19 @@ import java.util.Optional; import java.util.Set; @ApplicationScoped -public class AccountService implements Resettable, StoredResourceArns { +public class AccountService implements Resettable, StoredResourceArns, AccountPlacementListener { private static final String ACCOUNT_MANAGEMENT_SERVICE_PRINCIPAL = ServicePrincipals.of("account"); 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 static final String ACCOUNT_NAME_KEY = "name"; + private static final String ACCOUNT_STATE_ACTIVE = "ACTIVE"; + private static final String JOINED_METHOD_CREATED = "CREATED"; + private static final String ORGANIZATIONS_STATUS_PENDING_CLOSURE = "PENDING_CLOSURE"; private final AccountAwareStorageBackend contacts; private final AccountAwareStorageBackend contactInformation; + private final AccountAwareStorageBackend accountNames; private final OrganizationsService organizationsService; @Inject @@ -40,6 +48,8 @@ public class AccountService implements Resettable, StoredResourceArns { new TypeReference>() {}); this.contactInformation = storageFactory.create("account", "account-contact-information.json", new TypeReference>() {}); + this.accountNames = storageFactory.create("account", "account-names.json", + new TypeReference>() {}); this.organizationsService = organizationsService; } @@ -107,6 +117,50 @@ public class AccountService implements Resettable, StoredResourceArns { .orElseThrow(AccountService::contactInformationNotFound); } + public AccountInformation getAccountInformation(String callerAccountId, JsonNode request) { + AccountRequestShapes.check("GetAccountInformation", request); + String targetAccountId = resolveTargetAccount(callerAccountId, request); + return organizationsService.findAccount(targetAccountId) + .map(AccountService::informationOf) + .orElseGet(() -> new AccountInformation(targetAccountId, + accountNames.getForAccount(targetAccountId, ACCOUNT_NAME_KEY).orElse(null), + null, ACCOUNT_STATE_ACTIVE)); + } + + public void putAccountName(String callerAccountId, JsonNode request) { + AccountRequestShapes.check("PutAccountName", request); + String targetAccountId = resolveTargetAccount(callerAccountId, request); + String name = text(request, "AccountName"); + // Kept for the account as well, so the name outlives its organization. + accountNames.putForAccount(targetAccountId, ACCOUNT_NAME_KEY, name); + organizationsService.renameAccount(targetAccountId, name); + } + + /** + * Keeps the Organizations name of an account created in or invited into an organization, which + * {@code GetAccountInformation} answers once the account leaves it. A name the account already has stays. + */ + @Override + public void accountPlacementChanged(String managementAccountId, String accountId) { + if (accountNames.getForAccount(accountId, ACCOUNT_NAME_KEY).isPresent()) { + return; + } + organizationsService.findAccount(accountId) + .ifPresent(account -> accountNames.putForAccount(accountId, ACCOUNT_NAME_KEY, account.getName())); + } + + private static AccountInformation informationOf(OrganizationAccount account) { + // An invited account existed before it joined, so its JoinedTimestamp is not its creation date. + Instant created = JOINED_METHOD_CREATED.equals(account.getJoinedMethod()) + ? account.getJoinedTimestamp() + : null; + // Account Management has no PENDING_CLOSURE, and such an account is still usable. + String state = ORGANIZATIONS_STATUS_PENDING_CLOSURE.equals(account.getStatus()) + ? ACCOUNT_STATE_ACTIVE + : account.getStatus(); + return new AccountInformation(account.getId(), account.getName(), created, state); + } + private String resolveTargetAccount(String callerAccountId, JsonNode request) { String requestedAccountId = text(request, "AccountId"); if (requestedAccountId == null) { @@ -151,6 +205,7 @@ public class AccountService implements Resettable, StoredResourceArns { public void clear() { contacts.clear(); contactInformation.clear(); + accountNames.clear(); } /** The namespace of the resource types this service finds, as the request-resources table names it. */ diff --git a/src/main/java/io/floci/aws/services/account/model/AccountInformation.java b/src/main/java/io/floci/aws/services/account/model/AccountInformation.java new file mode 100644 index 0000000000..72a8ccfa41 --- /dev/null +++ b/src/main/java/io/floci/aws/services/account/model/AccountInformation.java @@ -0,0 +1,8 @@ +package io.floci.aws.services.account.model; + +import java.time.Instant; + +/** What {@code GetAccountInformation} answers for an account; a member Floci does not know is null. */ +public record AccountInformation(String accountId, String accountName, Instant accountCreatedDate, + String accountState) { +} diff --git a/src/main/java/io/floci/aws/services/organizations/OrganizationsService.java b/src/main/java/io/floci/aws/services/organizations/OrganizationsService.java index ce4898c2d1..267e00639f 100644 --- a/src/main/java/io/floci/aws/services/organizations/OrganizationsService.java +++ b/src/main/java/io/floci/aws/services/organizations/OrganizationsService.java @@ -694,7 +694,21 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization return requireAccount(requireOrganizationForCaller(callerAccountId), accountId); } - public Optional findAccountForPortal(String accountId) { + /** + * Renames an account in the organization that holds it, as Account Management's {@code PutAccountName} does, + * so {@code DescribeAccount} and {@code ListAccounts} answer the new name. Does nothing for an account in no + * organization. + */ + public void renameAccount(String accountId, String name) { + findOrganizationForAccount(accountId).ifPresent(organization -> accountIn(organization, accountId) + .ifPresent(account -> { + account.setName(name); + accounts.putForAccount(organization.getMasterAccountId(), accountId, account); + })); + } + + /** The record of an account in the organization that holds it, empty for an account in no organization. */ + public Optional findAccount(String accountId) { if (accountId == null || !ACCOUNT_ID_PATTERN.matcher(accountId).matches()) { return Optional.empty(); } @@ -1593,6 +1607,12 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization .toList(); } + private Optional accountIn(Organization organization, String accountId) { + return accountsIn(organization).stream() + .filter(account -> accountId.equals(account.getId())) + .findFirst(); + } + private List organizationalUnitsIn(Organization organization) { return organizationalUnits.scanAllAccounts().stream() .filter(ou -> organization.getId().equals(ou.getOrganizationId())) @@ -1623,9 +1643,7 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization if (accountId == null || !ACCOUNT_ID_PATTERN.matcher(accountId).matches()) { throw invalidInput("Account id must be 12 digits."); } - return accountsIn(organization).stream() - .filter(account -> accountId.equals(account.getId())) - .findFirst() + return accountIn(organization, accountId) .orElseThrow(() -> new AwsException("AccountNotFoundException", "We can't find an AWS account with the AccountId " + accountId + ".", 400)); } diff --git a/src/main/java/io/floci/aws/services/ssoportal/SsoPortalService.java b/src/main/java/io/floci/aws/services/ssoportal/SsoPortalService.java index b94113358e..c29531efc7 100644 --- a/src/main/java/io/floci/aws/services/ssoportal/SsoPortalService.java +++ b/src/main/java/io/floci/aws/services/ssoportal/SsoPortalService.java @@ -54,7 +54,7 @@ public class SsoPortalService { if (accounts.containsKey(assignment.accountId())) { return; } - PortalAccountInfo info = organizationsService.findAccountForPortal(assignment.accountId()) + PortalAccountInfo info = organizationsService.findAccount(assignment.accountId()) .map(account -> new PortalAccountInfo(account.getId(), account.getName(), account.getEmail())) .orElseGet(() -> new PortalAccountInfo(assignment.accountId(), null, null)); accounts.put(assignment.accountId(), info); diff --git a/src/main/resources/aws/account-request-shapes.json b/src/main/resources/aws/account-request-shapes.json index b2c68dbb94..4c8e5b8a86 100644 --- a/src/main/resources/aws/account-request-shapes.json +++ b/src/main/resources/aws/account-request-shapes.json @@ -5,8 +5,10 @@ }, "operations": { "DeleteAlternateContact": "DeleteAlternateContactRequest", + "GetAccountInformation": "GetAccountInformationRequest", "GetAlternateContact": "GetAlternateContactRequest", "GetContactInformation": "GetContactInformationRequest", + "PutAccountName": "PutAccountNameRequest", "PutAlternateContact": "PutAlternateContactRequest", "PutContactInformation": "PutContactInformationRequest" }, @@ -15,6 +17,12 @@ "type": "string", "pattern": "\\d{12}" }, + "AccountName": { + "type": "string", + "min": 1, + "max": 50, + "pattern": "[ -;=?-~]+" + }, "AddressLine": { "type": "string", "min": 1, @@ -100,6 +108,12 @@ "min": 1, "max": 50 }, + "GetAccountInformationRequest": { + "type": "structure", + "members": { + "AccountId": "AccountId" + } + }, "GetAlternateContactRequest": { "type": "structure", "required": [ @@ -132,6 +146,16 @@ "min": 1, "max": 20 }, + "PutAccountNameRequest": { + "type": "structure", + "required": [ + "AccountName" + ], + "members": { + "AccountName": "AccountName", + "AccountId": "AccountId" + } + }, "PutAlternateContactRequest": { "type": "structure", "required": [ diff --git a/src/test/java/io/floci/aws/services/account/AccountContactInformationIntegrationTest.java b/src/test/java/io/floci/aws/services/account/AccountContactInformationIntegrationTest.java index 28ff599776..f08e9da797 100644 --- a/src/test/java/io/floci/aws/services/account/AccountContactInformationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/account/AccountContactInformationIntegrationTest.java @@ -10,9 +10,9 @@ import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicInteger; +import static io.floci.aws.services.account.AccountRequests.account; 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; @@ -95,11 +95,11 @@ class AccountContactInformationIntegrationTest { @Test void nonObjectRequestBodyReturnsSerializationException() { - String account = newAccount(); - put(account, contactInformationRequest()).statusCode(200); + String caller = newAccount(); + put(caller, contactInformationRequest()).statusCode(200); - get(account, "[]").statusCode(400).body("__type", equalTo("SerializationException")); - post(account, "/putContactInformation", "[]") + get(caller, "[]").statusCode(400).body("__type", equalTo("SerializationException")); + account(caller, "/putContactInformation", "[]") .statusCode(400).body("__type", equalTo("SerializationException")); } @@ -154,20 +154,11 @@ class AccountContactInformationIntegrationTest { return String.format("7310008259%02d", ACCOUNTS.incrementAndGet()); } - private static ValidatableResponse put(String account, ObjectNode request) { - return post(account, "/putContactInformation", request.toString()); + private static ValidatableResponse put(String caller, ObjectNode request) { + return account(caller, "/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"; + private static ValidatableResponse get(String caller, String body) { + return account(caller, "/getContactInformation", body); } } diff --git a/src/test/java/io/floci/aws/services/account/AccountInformationIntegrationTest.java b/src/test/java/io/floci/aws/services/account/AccountInformationIntegrationTest.java new file mode 100644 index 0000000000..ca5c6f9003 --- /dev/null +++ b/src/test/java/io/floci/aws/services/account/AccountInformationIntegrationTest.java @@ -0,0 +1,85 @@ +package io.floci.aws.services.account; + +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.AccountNameRequests.accountNameRequest; +import static io.floci.aws.services.account.AccountRequests.account; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; + +/** Accounts in no organization; {@code AccountOrganizationsContextIntegrationTest} covers the others. */ +@QuarkusTest +class AccountInformationIntegrationTest { + private static final AtomicInteger ACCOUNTS = new AtomicInteger(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void accountIsActiveAndUnnamedUntilPutAccountName() { + String account = newAccount(); + + get(account, "{}").statusCode(200) + .body("AccountId", equalTo(account)) + .body("AccountState", equalTo("ACTIVE")) + .body("$", not(hasKey("AccountName"))) + .body("$", not(hasKey("AccountCreatedDate"))); + + put(account, accountNameRequest("Dev Sandbox").toString()).statusCode(200).body(equalTo("")); + + get(account, "{}").statusCode(200) + .body("AccountId", equalTo(account)) + .body("AccountName", equalTo("Dev Sandbox")) + .body("AccountState", equalTo("ACTIVE")); + get(newAccount(), "{}").statusCode(200).body("$", not(hasKey("AccountName"))); + } + + @Test + void putAccountNameRejectsANameOutsideTheModel() { + String account = newAccount(); + put(account, accountNameRequest("Dev Sandbox").toString()).statusCode(200); + + put(account, accountNameRequest("").toString()).statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", startsWith("Invalid parameter at 'AccountName'")); + put(account, "{}").statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", startsWith("Invalid parameter at 'AccountName'")); + put(account, "{\"AccountName\":42}").statusCode(400).body("__type", equalTo("SerializationException")); + + get(account, "{}").statusCode(200).body("AccountName", equalTo("Dev Sandbox")); + } + + @Test + void anotherAccountIsRefusedOutsideAnOrganization() { + String account = newAccount(); + + put(account, accountNameRequest("111122223333", "Member").toString()) + .statusCode(403).body("__type", equalTo("AccessDeniedException")); + get(account, "{\"AccountId\":\"111122223333\"}") + .statusCode(403).body("__type", equalTo("AccessDeniedException")); + } + + /** Names cannot be deleted, so every test acts on an account of its own. */ + private static String newAccount() { + return String.format("7310009000%02d", ACCOUNTS.incrementAndGet()); + } + + private static ValidatableResponse put(String caller, String body) { + return account(caller, "/putAccountName", body); + } + + private static ValidatableResponse get(String caller, String body) { + return account(caller, "/getAccountInformation", body); + } +} diff --git a/src/test/java/io/floci/aws/services/account/AccountNameRequests.java b/src/test/java/io/floci/aws/services/account/AccountNameRequests.java new file mode 100644 index 0000000000..d7241a2c15 --- /dev/null +++ b/src/test/java/io/floci/aws/services/account/AccountNameRequests.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 {@code PutAccountName} request the account information tests send. */ +final class AccountNameRequests { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private AccountNameRequests() { + } + + static ObjectNode accountNameRequest(String name) { + ObjectNode request = MAPPER.createObjectNode(); + request.put("AccountName", name); + return request; + } + + static ObjectNode accountNameRequest(String accountId, String name) { + return accountNameRequest(name).put("AccountId", accountId); + } +} 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 2f10c38f04..839bb418b5 100644 --- a/src/test/java/io/floci/aws/services/account/AccountOrganizationsContextIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/account/AccountOrganizationsContextIntegrationTest.java @@ -1,6 +1,7 @@ package io.floci.aws.services.account; -import io.floci.aws.testing.EnforcementFixtures; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.testing.OrganizationsRequests; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; @@ -9,17 +10,23 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.time.Instant; + +import static io.floci.aws.services.account.AccountNameRequests.accountNameRequest; +import static io.floci.aws.services.account.AccountRequests.account; 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; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; /** Requests that name an {@code AccountId}, sent by the accounts of one organization. */ @QuarkusTest class AccountOrganizationsContextIntegrationTest { /** The management account of an organization of this class's own, which no other test uses. */ private static final String MANAGEMENT = "731000826800"; + private static final ObjectMapper MAPPER = new ObjectMapper(); private static String delegatedAdministrator; private static String member; @@ -62,6 +69,9 @@ class AccountOrganizationsContextIntegrationTest { refused(account(delegatedAdministrator, "/putContactInformation", contactInformationRequest().put("AccountId", MANAGEMENT).toString())); refused(account(delegatedAdministrator, "/getContactInformation", "{\"AccountId\":\"" + MANAGEMENT + "\"}")); + refused(account(delegatedAdministrator, "/putAccountName", + accountNameRequest(MANAGEMENT, "Management").toString())); + refused(account(delegatedAdministrator, "/getAccountInformation", "{\"AccountId\":\"" + MANAGEMENT + "\"}")); } @Test @@ -69,6 +79,99 @@ class AccountOrganizationsContextIntegrationTest { refused(account(MANAGEMENT, "/putAlternateContact", alternateContact(MANAGEMENT))); } + @Test + void memberAccountIsDescribedByItsOrganizationRecord() throws Exception { + JsonNode described = describeAccount(member); + + account(delegatedAdministrator, "/getAccountInformation", "{\"AccountId\":\"" + member + "\"}") + .statusCode(200) + .body("AccountId", equalTo(member)) + .body("AccountName", equalTo("account-member")) + .body("AccountCreatedDate", + equalTo(Instant.ofEpochSecond(described.path("JoinedTimestamp").longValue()).toString())) + .body("AccountState", equalTo("ACTIVE")); + } + + @Test + void managementAccountHasNoCreationDate() throws Exception { + account(MANAGEMENT, "/getAccountInformation", "{}").statusCode(200) + .body("AccountId", equalTo(MANAGEMENT)) + .body("AccountName", equalTo(describeAccount(MANAGEMENT).path("Name").textValue())) + .body("AccountState", equalTo("ACTIVE")) + .body("$", not(hasKey("AccountCreatedDate"))); + } + + @Test + void renamingAMemberAccountShowsInDescribeAccount() { + String renamed = createAccount("account-to-rename"); + + account(MANAGEMENT, "/putAccountName", accountNameRequest(renamed, "Renamed Member").toString()) + .statusCode(200).body(equalTo("")); + + organizations("DescribeAccount", "{\"AccountId\":\"" + renamed + "\"}") + .body("Account.Name", equalTo("Renamed Member")); + organizations("ListAccounts", "{}") + .body("Accounts.find { it.Id == '" + renamed + "' }.Name", equalTo("Renamed Member")); + account(renamed, "/getAccountInformation", "{}").statusCode(200) + .body("AccountName", equalTo("Renamed Member")); + } + + @Test + void nameOutlivesTheOrganization() { + String leaving = createAccount("account-to-remove"); + account(delegatedAdministrator, "/putAccountName", accountNameRequest(leaving, "Former Member").toString()) + .statusCode(200); + + organizations("RemoveAccountFromOrganization", "{\"AccountId\":\"" + leaving + "\"}"); + + account(leaving, "/getAccountInformation", "{}").statusCode(200) + .body("AccountName", equalTo("Former Member")) + .body("AccountState", equalTo("ACTIVE")) + .body("$", not(hasKey("AccountCreatedDate"))); + } + + @Test + void removedAccountKeepsTheNameItWasCreatedWith() { + String removed = createAccount("account-removed-unnamed"); + + organizations("RemoveAccountFromOrganization", "{\"AccountId\":\"" + removed + "\"}"); + + account(removed, "/getAccountInformation", "{}").statusCode(200) + .body("AccountName", equalTo("account-removed-unnamed")); + } + + @Test + void accountThatLeavesKeepsItsName() { + String leaving = createAccount("account-that-leaves"); + + OrganizationsRequests.request(leaving, "LeaveOrganization", "{}").when().post("/").then().statusCode(200); + + account(leaving, "/getAccountInformation", "{}").statusCode(200) + .body("AccountName", equalTo("account-that-leaves")); + } + + @Test + void managementAccountRenamesItselfWithoutAnAccountId() { + account(MANAGEMENT, "/putAccountName", accountNameRequest("Management Account").toString()) + .statusCode(200); + + organizations("DescribeAccount", "{\"AccountId\":\"" + MANAGEMENT + "\"}") + .body("Account.Name", equalTo("Management Account")); + } + + @Test + void accountPendingClosureIsStillActive() { + String closing = createAccount("account-to-close"); + organizations("CloseAccount", "{\"AccountId\":\"" + closing + "\"}"); + + account(closing, "/getAccountInformation", "{}").statusCode(200).body("AccountState", equalTo("ACTIVE")); + } + + private static JsonNode describeAccount(String accountId) throws Exception { + String body = organizations("DescribeAccount", "{\"AccountId\":\"" + accountId + "\"}").extract().asString(); + return MAPPER.readTree(body).path("Account"); + } + private static void refused(ValidatableResponse response) { response.statusCode(403).body("__type", equalTo("AccessDeniedException")) .body("message", containsString("management account of the organization")); @@ -88,10 +191,4 @@ class AccountOrganizationsContextIntegrationTest { private static ValidatableResponse organizations(String action, String body) { return OrganizationsRequests.request(MANAGEMENT, action, body).when().post("/").then().statusCode(200); } - - private static ValidatableResponse account(String caller, String path, String body) { - return given().contentType("application/json") - .header("Authorization", EnforcementFixtures.auth(caller, "account")) - .body(body).post(path).then(); - } } diff --git a/src/test/java/io/floci/aws/services/account/AccountRequests.java b/src/test/java/io/floci/aws/services/account/AccountRequests.java new file mode 100644 index 0000000000..548a31edfd --- /dev/null +++ b/src/test/java/io/floci/aws/services/account/AccountRequests.java @@ -0,0 +1,19 @@ +package io.floci.aws.services.account; + +import io.floci.aws.testing.EnforcementFixtures; +import io.restassured.response.ValidatableResponse; + +import static io.restassured.RestAssured.given; + +/** An Account Management request sent by a given caller account, for the integration tests. */ +final class AccountRequests { + + private AccountRequests() { + } + + static ValidatableResponse account(String caller, String path, String body) { + return given().contentType("application/json") + .header("Authorization", EnforcementFixtures.auth(caller, "account")) + .body(body).post(path).then(); + } +} 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 a4a3c862fc..f0bf64cb35 100644 --- a/src/test/java/io/floci/aws/services/account/AccountServiceTest.java +++ b/src/test/java/io/floci/aws/services/account/AccountServiceTest.java @@ -7,6 +7,7 @@ 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.AccountInformation; import io.floci.aws.services.account.model.AlternateContact; import io.floci.aws.services.account.model.ContactInformation; import io.floci.aws.services.organizations.OrganizationsService; @@ -25,6 +26,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import static io.floci.aws.services.account.AccountNameRequests.accountNameRequest; 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; @@ -35,6 +37,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class AccountServiceTest { @@ -54,6 +57,9 @@ class AccountServiceTest { AccountAwareStorageBackend primaryStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID); when(storageFactory.create(eq("account"), eq("account-contact-information.json"), any(TypeReference.class))) .thenReturn((AccountAwareStorageBackend) primaryStore); + AccountAwareStorageBackend nameStore = AccountAwareStorageBackend.inMemory(ACCOUNT_ID); + when(storageFactory.create(eq("account"), eq("account-names.json"), any(TypeReference.class))) + .thenReturn((AccountAwareStorageBackend) nameStore); organizations = mock(OrganizationsService.class); service = new AccountService(storageFactory, organizations); } @@ -105,7 +111,7 @@ class AccountServiceTest { void putAlternateContactRejectsAMissingRequiredMember(String member) { ObjectNode request = alternateContactRequest(); request.remove(member); - assertAlternateContactRejected(() -> service.putAlternateContact(ACCOUNT_ID, request), member); + assertInvalidParameter(() -> service.putAlternateContact(ACCOUNT_ID, request), member); } @ParameterizedTest @@ -135,7 +141,7 @@ class AccountServiceTest { service.putAlternateContact(ACCOUNT_ID, request); request.put(member, "1".repeat(maximum + 1)); - assertAlternateContactRejected(() -> service.putAlternateContact(ACCOUNT_ID, request), member); + assertInvalidParameter(() -> service.putAlternateContact(ACCOUNT_ID, request), member); } @Test @@ -145,7 +151,7 @@ class AccountServiceTest { service.putAlternateContact(ACCOUNT_ID, request); request.put("EmailAddress", "a".repeat(243) + "@example.com"); - assertAlternateContactRejected(() -> service.putAlternateContact(ACCOUNT_ID, request), "EmailAddress"); + assertInvalidParameter(() -> service.putAlternateContact(ACCOUNT_ID, request), "EmailAddress"); } @ParameterizedTest @@ -154,7 +160,7 @@ class AccountServiceTest { void putAlternateContactRejectsAMemberOutsideItsConstraints(String member, String value) { ObjectNode request = alternateContactRequest(); request.put(member, value); - assertAlternateContactRejected(() -> service.putAlternateContact(ACCOUNT_ID, request), member); + assertInvalidParameter(() -> service.putAlternateContact(ACCOUNT_ID, request), member); } @Test @@ -173,8 +179,8 @@ class AccountServiceTest { void getAndDeleteAlternateContactRequireAKnownContactType(String type) { ObjectNode request = mapper.createObjectNode().put("AlternateContactType", type); - assertAlternateContactRejected(() -> service.getAlternateContact(ACCOUNT_ID, request), "AlternateContactType"); - assertAlternateContactRejected(() -> service.deleteAlternateContact(ACCOUNT_ID, request), + assertInvalidParameter(() -> service.getAlternateContact(ACCOUNT_ID, request), "AlternateContactType"); + assertInvalidParameter(() -> service.deleteAlternateContact(ACCOUNT_ID, request), "AlternateContactType"); } @@ -186,7 +192,7 @@ class AccountServiceTest { request.put("AccountId", "111122223333"); request.put("AlternateContactType", "OTHER"); - assertAlternateContactRejected(() -> service.getAlternateContact(ACCOUNT_ID, request), "AlternateContactType"); + assertInvalidParameter(() -> service.getAlternateContact(ACCOUNT_ID, request), "AlternateContactType"); } @Test @@ -194,9 +200,9 @@ class AccountServiceTest { 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"); + assertInvalidParameter(() -> service.putAlternateContact(ACCOUNT_ID, request), "AccountId"); + assertInvalidParameter(() -> service.getAlternateContact(ACCOUNT_ID, request), "AccountId"); + assertInvalidParameter(() -> service.deleteAlternateContact(ACCOUNT_ID, request), "AccountId"); } @Test @@ -450,6 +456,10 @@ class AccountServiceTest { assertManagementAccountRefused(() -> service.deleteAlternateContact(ACCOUNT_ID, alternateContact)); assertManagementAccountRefused(() -> service.putContactInformation(ACCOUNT_ID, contactInformation)); assertManagementAccountRefused(() -> service.getContactInformation(ACCOUNT_ID, contactInformation)); + assertManagementAccountRefused(() -> service.putAccountName(ACCOUNT_ID, + accountNameRequest(MANAGEMENT_ACCOUNT_ID, "Management"))); + assertManagementAccountRefused(() -> service.getAccountInformation(ACCOUNT_ID, + mapper.createObjectNode().put("AccountId", MANAGEMENT_ACCOUNT_ID))); } @Test @@ -482,6 +492,167 @@ class AccountServiceTest { assertEquals("ResourceNotFoundException", error.getErrorCode()); } + @Test + void accountOutsideAnOrganizationIsActiveAndUnnamedUntilPutAccountName() { + assertEquals(new AccountInformation(ACCOUNT_ID, null, null, "ACTIVE"), + service.getAccountInformation(ACCOUNT_ID, mapper.createObjectNode())); + + service.putAccountName(ACCOUNT_ID, accountNameRequest("Dev Sandbox")); + service.putAccountName(ACCOUNT_ID, accountNameRequest("Dev Sandbox 2")); + + assertEquals(new AccountInformation(ACCOUNT_ID, "Dev Sandbox 2", null, "ACTIVE"), + service.getAccountInformation(ACCOUNT_ID, mapper.createObjectNode())); + assertNull(service.getAccountInformation("111122223333", mapper.createObjectNode()).accountName()); + } + + @Test + void accountInAnOrganizationIsDescribedByItsOrganizationRecord() { + Instant joined = Instant.parse("2026-11-17T08:00:00Z"); + when(organizations.findAccount(ACCOUNT_ID)) + .thenReturn(Optional.of(organizationAccount("CREATED", "ACTIVE", joined))); + + assertEquals(new AccountInformation(ACCOUNT_ID, "Team Account", joined, "ACTIVE"), + service.getAccountInformation(ACCOUNT_ID, mapper.createObjectNode())); + } + + @Test + void invitedAccountHasNoCreationDate() { + when(organizations.findAccount(ACCOUNT_ID)) + .thenReturn(Optional.of(organizationAccount("INVITED", "ACTIVE", Instant.EPOCH))); + + assertNull(service.getAccountInformation(ACCOUNT_ID, mapper.createObjectNode()).accountCreatedDate()); + } + + @Test + void accountPendingClosureIsStillActive() { + when(organizations.findAccount(ACCOUNT_ID)) + .thenReturn(Optional.of(organizationAccount("CREATED", "PENDING_CLOSURE", Instant.EPOCH))); + + assertEquals("ACTIVE", service.getAccountInformation(ACCOUNT_ID, mapper.createObjectNode()).accountState()); + } + + @Test + void putAccountNameRenamesTheOrganizationRecordAndKeepsTheNameForTheAccount() { + service.putAccountName(ACCOUNT_ID, accountNameRequest("Team Account")); + + verify(organizations).renameAccount(ACCOUNT_ID, "Team Account"); + // Once no organization holds the account, the name kept for it answers. + assertEquals("Team Account", + service.getAccountInformation(ACCOUNT_ID, mapper.createObjectNode()).accountName()); + } + + @Test + void managementAccountRenamesAMemberAccount() { + String member = "111122223333"; + callerIsInAnOrganizationManagedBy(ACCOUNT_ID, new OrganizationAccount()); + + service.putAccountName(ACCOUNT_ID, accountNameRequest(member, "Member")); + + verify(organizations).renameAccount(member, "Member"); + } + + @Test + void accountInformationForAnotherAccountNeedsAnOrganization() { + when(organizations.describeOrganization(ACCOUNT_ID)) + .thenThrow(new AwsException("AWSOrganizationsNotInUseException", "no organization", 400)); + + AwsException putError = assertThrows(AwsException.class, + () -> service.putAccountName(ACCOUNT_ID, accountNameRequest("111122223333", "Member"))); + assertEquals("AccessDeniedException", putError.getErrorCode()); + AwsException getError = assertThrows(AwsException.class, () -> service.getAccountInformation(ACCOUNT_ID, + mapper.createObjectNode().put("AccountId", "111122223333"))); + assertEquals("AccessDeniedException", getError.getErrorCode()); + } + + @Test + void accountInformationRejectsAMalformedAccountId() { + assertInvalidParameter(() -> service.putAccountName(ACCOUNT_ID, accountNameRequest("1234", "Member")), + "AccountId"); + assertInvalidParameter(() -> service.getAccountInformation(ACCOUNT_ID, + mapper.createObjectNode().put("AccountId", "1234")), "AccountId"); + } + + @ParameterizedTest + @ValueSource(strings = {"A", "Dev Sandbox", "a!\"#$%&'()*+,-./0:;=?@[\\]^_`{|}~"}) + void putAccountNameAcceptsPrintableAsciiOtherThanAngleBrackets(String name) { + service.putAccountName(ACCOUNT_ID, accountNameRequest(name)); + + assertEquals(name, service.getAccountInformation(ACCOUNT_ID, mapper.createObjectNode()).accountName()); + } + + @ParameterizedTest + @ValueSource(strings = {"", "