From 85a63055beff134eb4b890585df73d6f5d7b76aa Mon Sep 17 00:00:00 2001 From: Yang Hao <1994728136@qq.com> Date: Tue, 24 Nov 2026 18:46:07 +0800 Subject: [PATCH] feat(organizations): close accounts and refuse their requests (#9331) --- .../java/com/floci/test/TestFixtures.java | 8 + .../test/OrganizationsCloseAccountTest.java | 69 ++++++ docs/services/account.md | 2 +- docs/services/organizations.md | 16 +- .../aws/core/common/AccountContextFilter.java | 41 +++- .../aws/core/common/ClosedAccountLookup.java | 11 + .../aws/core/common/IamEnforcementFilter.java | 2 +- .../aws/services/account/AccountService.java | 9 +- .../OrganizationsCfnProvisioner.java | 6 +- .../OrganizationsJsonHandler.java | 2 +- .../organizations/OrganizationsService.java | 49 +++- .../floci/aws/services/s3/S3Controller.java | 21 ++ .../core/common/AccountContextFilterTest.java | 124 +++++++++- ...ntOrganizationsContextIntegrationTest.java | 5 +- .../services/account/AccountServiceTest.java | 8 + .../OrganizationsCfnProvisionerTest.java | 19 ++ ...zationsCloseAccountIamIntegrationTest.java | 96 ++++++++ ...anizationsCloseAccountIntegrationTest.java | 214 ++++++++++++++++++ .../OrganizationsServiceTest.java | 73 ++++++ .../s3/S3GlobalLegacyListingTest.java | 2 +- .../s3/S3PolicyStatusControllerTest.java | 1 + 21 files changed, 749 insertions(+), 29 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OrganizationsCloseAccountTest.java create mode 100644 src/main/java/io/floci/aws/core/common/ClosedAccountLookup.java create mode 100644 src/test/java/io/floci/aws/services/organizations/OrganizationsCloseAccountIamIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/organizations/OrganizationsCloseAccountIntegrationTest.java 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 72271d422c..627443b675 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 @@ -996,6 +996,14 @@ public final class TestFixtures { .build(); } + public static StsClient stsClient(String accountId) { + return StsClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accountId, "test"))) + .build(); + } + public static KafkaClient kafkaClient() { return KafkaClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OrganizationsCloseAccountTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OrganizationsCloseAccountTest.java new file mode 100644 index 0000000000..5450f6f3bc --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OrganizationsCloseAccountTest.java @@ -0,0 +1,69 @@ +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.organizations.OrganizationsClient; +import software.amazon.awssdk.services.organizations.model.Account; +import software.amazon.awssdk.services.organizations.model.AccountAlreadyClosedException; +import software.amazon.awssdk.services.organizations.model.AccountState; +import software.amazon.awssdk.services.organizations.model.AccountStatus; +import software.amazon.awssdk.services.organizations.model.ConstraintViolationException; +import software.amazon.awssdk.services.organizations.model.OrganizationFeatureSet; +import software.amazon.awssdk.services.sts.StsClient; +import software.amazon.awssdk.services.sts.model.StsException; + +import java.util.concurrent.ThreadLocalRandom; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +/** + * As on AWS, a closed account stays in its organization until its post-closure period ends, so neither can be + * removed afterwards. Each run therefore uses a management account of its own, which lets it run again against the + * same Floci. + */ +@DisplayName("Organizations CloseAccount") +class OrganizationsCloseAccountTest { + + @Test + @DisplayName("closes a member account and refuses its credentials") + @ResourceLock("organizations") + void closeAccountUseAwsSdk() { + assumeFalse(TestFixtures.isRealAws(), "Closes an account, which AWS cannot reopen through the API"); + + String managementAccount = "7310009" + ThreadLocalRandom.current().nextInt(10_000, 100_000); + try (OrganizationsClient organizations = TestFixtures.organizationsClient(managementAccount); + AccountClient account = TestFixtures.accountClient(managementAccount)) { + organizations.createOrganization(request -> request.featureSet(OrganizationFeatureSet.ALL)); + organizations.enableAWSServiceAccess(request -> request.servicePrincipal("account.amazonaws.com")); + String member = organizations.createAccount(request -> request + .email("close-account@example.com").accountName("close-account")) + .createAccountStatus().accountId(); + + try (StsClient memberSts = TestFixtures.stsClient(member)) { + assertThat(memberSts.getCallerIdentity().account()).isEqualTo(member); + + organizations.closeAccount(request -> request.accountId(member)); + + Account closed = organizations.describeAccount(request -> request.accountId(member)).account(); + assertThat(closed.state()).isEqualTo(AccountState.CLOSED); + assertThat(closed.status()).isEqualTo(AccountStatus.SUSPENDED); + assertThat(account.getAccountInformation(request -> request.accountId(member)) + .accountStateAsString()).isEqualTo("CLOSED"); + assertThatThrownBy(() -> organizations.closeAccount(request -> request.accountId(member))) + .isInstanceOf(AccountAlreadyClosedException.class); + assertThatThrownBy(() -> organizations.removeAccountFromOrganization(request -> request + .accountId(member))) + .isInstanceOf(ConstraintViolationException.class); + assertThatThrownBy(memberSts::getCallerIdentity) + .isInstanceOfSatisfying(StsException.class, refused -> { + assertThat(refused.statusCode()).isEqualTo(403); + assertThat(refused.awsErrorDetails().errorCode()).isEqualTo("InvalidClientTokenId"); + }); + } + } + } +} diff --git a/docs/services/account.md b/docs/services/account.md index 71ac4c31b0..8cef04b701 100644 --- a/docs/services/account.md +++ b/docs/services/account.md @@ -22,7 +22,7 @@ Floci supports alternate contacts, primary contact information and account infor 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`. +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` closed reports `CLOSED`. 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. diff --git a/docs/services/organizations.md b/docs/services/organizations.md index cba80f66a4..2f7f90ba25 100644 --- a/docs/services/organizations.md +++ b/docs/services/organizations.md @@ -68,6 +68,20 @@ call `LeaveOrganization`. An account in no organization gets A `RoleName` off the published pattern answers `InvalidInputException` with the reference's `Reason` member (`INVALID_PATTERN`, or `INVALID_ROLE_NAME` for the reserved `AWSServiceRoleFor` prefix), so SDK callers can read the cause. +- `CloseAccount` closes a member account at once, skipping the few minutes AWS holds it in + `PENDING_CLOSURE`. As on AWS during the 90-day post-closure period, the account stays in the + organization: `DescribeAccount`, `ListAccounts` and `ListAccountsForParent` report its `State` as + `CLOSED` and its legacy `Status` as `SUSPENDED`, and Account Management's `GetAccountInformation` + reports `CLOSED`. Closing it again fails with `AccountAlreadyClosedException`; registering it as a + delegated administrator, `RemoveAccountFromOrganization` and `LeaveOrganization` fail with + `ConstraintViolationException`. The post-closure period does not end in Floci, so the account + stays closed and keeps its resources. +- A request whose `Authorization` header, SigV4 presigned URL or S3 presigned POST form carries a + credential of a closed account (its 12-digit access key id, an IAM user's key, or a session in the + account) is refused, whether or not IAM enforcement is on. AWS documents that these calls fail but + not the error, so Floci answers as it does for a credential it does not recognize: + `InvalidClientTokenId` or `UnrecognizedClientException`, `InvalidAccessKeyId` on S3 and + `AuthFailure` on EC2. - `DescribeEffectivePolicy` merges every policy of the requested type down the root → OU → target chain, with the closest ancestor winning on conflicting keys. As on AWS, the access-control types (`SERVICE_CONTROL_POLICY`, `RESOURCE_CONTROL_POLICY`) are rejected. @@ -110,7 +124,7 @@ call `LeaveOrganization`. An account in no organization gets | `MoveAccount` | Moves an account from one root or OU to another. | | `RemoveAccountFromOrganization` | Removes a member account from the organization. | | `LeaveOrganization` | Removes the calling member account from its organization. | -| `CloseAccount` | Closes a member account, moving it to PENDING_CLOSURE. | +| `CloseAccount` | Closes a member account: its `State` becomes `CLOSED` and its credentials stop working. | | `CreatePolicy` | Creates a policy of the specified type in the organization. | | `UpdatePolicy` | Updates the name, description or content of a customer-managed policy. | | `DeletePolicy` | Deletes a policy that is not attached to any target. | diff --git a/src/main/java/io/floci/aws/core/common/AccountContextFilter.java b/src/main/java/io/floci/aws/core/common/AccountContextFilter.java index afcb47850f..fd775195a8 100644 --- a/src/main/java/io/floci/aws/core/common/AccountContextFilter.java +++ b/src/main/java/io/floci/aws/core/common/AccountContextFilter.java @@ -5,6 +5,7 @@ import io.floci.aws.core.common.auth.SigV4aSignature; import io.floci.aws.services.s3.PreSignedUrlFilter; import jakarta.annotation.Priority; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import jakarta.ws.rs.Priorities; import jakarta.ws.rs.container.ContainerRequestContext; @@ -29,6 +30,8 @@ import java.util.Set; * the account; otherwise IAM and temporary credentials (e.g. assumed-role {@code ASIA...} * keys) are looked up via {@link SessionAccountLookup}; if * neither matches, the configured default account applies. + * + *
A request whose credentials resolve to a closed account (see {@link ClosedAccountLookup}) is refused.
*/
@Provider
@ApplicationScoped
@@ -60,6 +63,8 @@ public class AccountContextFilter implements ContainerRequestFilter {
private final RegionResolver regionResolver;
private final RequestContext requestContext;
private final SessionAccountLookup sessionAccountLookup;
+ // Read lazily, as IamService reads the organization ports: absent when Organizations is not deployed.
+ private final Instance Runs as its own management account and enables no service control policies, so the SCP enforcement this
+ * profile turns on never reaches it. As on AWS, a closed account stays in its organization, so the test ends with
+ * {@code /_floci/state/reset}. Test classes run one at a time, so the reset clears only what this class and the
+ * ones before it created.
+ */
+@QuarkusTest
+@TestProfile(IamEnforcementProfile.class)
+class OrganizationsCloseAccountIamIntegrationTest {
+
+ private static final String MANAGEMENT_ACCOUNT = "878787878787";
+ private static final String SECRET = "test";
+
+ @TestHTTPResource("/")
+ URI endpoint;
+
+ private final OrganizationsFixture organizations = new OrganizationsFixture();
+ private String member;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @BeforeEach
+ void createOrganizationWithAMember() {
+ organizations.request(MANAGEMENT_ACCOUNT, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")
+ .post("/").then().statusCode(200);
+ member = organizations.createAccount(MANAGEMENT_ACCOUNT, "member@example.com", "Member");
+ }
+
+ @AfterEach
+ void resetState() {
+ given().post("/_floci/state/reset").then().statusCode(200);
+ }
+
+ @Test
+ void closingTheAccountRefusesItsRootKeyAndItsSessions() {
+ Session session = EnforcementFixtures.assumeRole(endpoint.getPort(), MANAGEMENT_ACCOUNT,
+ "arn:aws:iam::" + member + ":role/OrganizationAccountAccessRole");
+ AwsCredentials rootKey = AwsBasicCredentials.create(member, SECRET);
+ AwsCredentials sessionKey = AwsSessionCredentials.create(session.accessKeyId(), SECRET, session.sessionToken());
+ assertEquals(member, callerAccount(rootKey));
+ assertEquals(member, callerAccount(sessionKey));
+
+ organizations.request(MANAGEMENT_ACCOUNT, "CloseAccount", "{\"AccountId\":\"" + member + "\"}")
+ .post("/").then().statusCode(200);
+
+ assertRefused(rootKey);
+ assertRefused(sessionKey);
+ assertEquals(MANAGEMENT_ACCOUNT, callerAccount(AwsBasicCredentials.create(MANAGEMENT_ACCOUNT, SECRET)));
+ }
+
+ private void assertRefused(AwsCredentials credentials) {
+ StsException refused = assertThrows(StsException.class, () -> callerAccount(credentials));
+ assertEquals(403, refused.statusCode());
+ assertEquals("InvalidClientTokenId", refused.awsErrorDetails().errorCode());
+ }
+
+ private String callerAccount(AwsCredentials credentials) {
+ try (StsClient sts = AwsTestClients.create(StsClient.builder(), credentials, Region.US_EAST_1, endpoint)) {
+ return sts.getCallerIdentity().account();
+ }
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/organizations/OrganizationsCloseAccountIntegrationTest.java b/src/test/java/io/floci/aws/services/organizations/OrganizationsCloseAccountIntegrationTest.java
new file mode 100644
index 0000000000..ea27badd07
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/organizations/OrganizationsCloseAccountIntegrationTest.java
@@ -0,0 +1,214 @@
+package io.floci.aws.services.organizations;
+
+import io.floci.aws.testing.AwsTestClients;
+import io.floci.aws.testing.EnforcementFixtures;
+import io.floci.aws.testing.EnforcementFixtures.Session;
+import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
+import io.floci.aws.testing.OrganizationsFixture;
+import io.floci.aws.testing.PartitionCleanup;
+import io.floci.aws.testing.RestAssuredJsonUtils;
+import io.quarkus.test.common.http.TestHTTPResource;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.ValidatableResponse;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
+import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
+import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder;
+import software.amazon.awssdk.awscore.client.builder.AwsSyncClientBuilder;
+import software.amazon.awssdk.awscore.exception.AwsServiceException;
+import software.amazon.awssdk.core.SdkClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
+import software.amazon.awssdk.services.s3.S3Client;
+import software.amazon.awssdk.services.sts.StsClient;
+
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.UUID;
+import java.util.function.Function;
+
+import static io.floci.aws.testing.EnforcementFixtures.auth;
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * {@code CloseAccount} end to end with IAM enforcement off, Floci's default: the account reads as closed in its
+ * organization, and every credential that resolves to it is refused across the wire protocols.
+ *
+ * Runs as its own management account, so it never contends for one with the other Organizations suites. As on
+ * AWS, a closed account stays in its organization and nothing in it can be deleted, so each test ends with
+ * {@code /_floci/state/reset}. Test classes run one at a time, so the reset clears only what this class and the
+ * ones before it created.
+ */
+@QuarkusTest
+class OrganizationsCloseAccountIntegrationTest {
+
+ private static final String MANAGEMENT_ACCOUNT = "858585858585";
+ private static final String SECRET = "test";
+
+ @TestHTTPResource("/")
+ URI endpoint;
+
+ @RegisterExtension
+ final PartitionCleanup cleanup = new PartitionCleanup();
+
+ private final OrganizationsFixture organizations = new OrganizationsFixture();
+ private String closed;
+ private String open;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @BeforeEach
+ void createOrganizationWithTwoMembers() {
+ organizations.request(MANAGEMENT_ACCOUNT, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")
+ .post("/").then().statusCode(200);
+ closed = organizations.createAccount(MANAGEMENT_ACCOUNT, "closed@example.com", "Closed");
+ open = organizations.createAccount(MANAGEMENT_ACCOUNT, "open@example.com", "Open");
+ }
+
+ /** Runs before the cleanup extension, which then finds no user left to delete. */
+ @AfterEach
+ void resetState() {
+ given().post("/_floci/state/reset").then().statusCode(200);
+ }
+
+ @Test
+ void aClosedAccountReadsClosedWhereverTheOrganizationListsIt() {
+ closeAccount(closed);
+
+ organizations.request(MANAGEMENT_ACCOUNT, "DescribeAccount", "{\"AccountId\":\"" + closed + "\"}")
+ .post("/").then().statusCode(200)
+ .body("Account.State", equalTo("CLOSED"))
+ .body("Account.Status", equalTo("SUSPENDED"));
+ String root = organizations.request(MANAGEMENT_ACCOUNT, "ListRoots", "{}")
+ .post("/").then().statusCode(200).extract().jsonPath().getString("Roots[0].Id");
+ assertListedAsClosed(organizations.request(MANAGEMENT_ACCOUNT, "ListAccounts", "{}"));
+ assertListedAsClosed(organizations.request(MANAGEMENT_ACCOUNT, "ListAccountsForParent",
+ "{\"ParentId\":\"" + root + "\"}"));
+ }
+
+ @Test
+ void closingAClosedAccountAgainIsRefused() {
+ closeAccount(closed);
+
+ organizations.request(MANAGEMENT_ACCOUNT, "CloseAccount", "{\"AccountId\":\"" + closed + "\"}")
+ .post("/").then().statusCode(400)
+ .body("__type", equalTo("AccountAlreadyClosedException"))
+ .body("message", equalTo("You attempted to close an account that is already closed."));
+ }
+
+ @Test
+ void theClosedAccountsOwnKeyIsRefusedInEveryProtocol() {
+ AwsCredentials key = AwsBasicCredentials.create(closed, SECRET);
+ assertEquals(closed, callerAccount(key));
+ closeAccount(closed);
+
+ assertRefused(key, StsClient.builder(), StsClient::getCallerIdentity, 403, "InvalidClientTokenId");
+ assertRefused(key, DynamoDbClient.builder(), DynamoDbClient::listTables, 403, "UnrecognizedClientException");
+ assertRefused(key, S3Client.builder(), S3Client::listBuckets, 403, "InvalidAccessKeyId");
+ // URLConnection cannot read the body of EC2's 401, so the SDK would see no error code: read it directly.
+ given().header("Authorization", auth(closed, "ec2"))
+ .formParam("Action", "DescribeVpcs").formParam("Version", "2016-11-15")
+ .post("/").then().statusCode(401)
+ .body("Response.Errors.Error.Code", equalTo("AuthFailure"));
+ }
+
+ /** A presigned POST carries its credential in the form body, not in a header or the query string. */
+ @Test
+ void theClosedAccountsPresignedPostIsRefused() {
+ String bucket = "closed-account-post-" + UUID.randomUUID();
+ // Unsigned, like the POST below, so both reach the default account.
+ given().put("/" + bucket).then().statusCode(200);
+ closeAccount(closed);
+
+ presignedPost(bucket, open).statusCode(204);
+ presignedPost(bucket, closed).statusCode(403).body("Error.Code", equalTo("InvalidAccessKeyId"));
+ }
+
+ @Test
+ void theClosedAccountCannotBeRemovedFromTheOrganization() {
+ closeAccount(closed);
+
+ organizations.request(MANAGEMENT_ACCOUNT, "RemoveAccountFromOrganization", "{\"AccountId\":\"" + closed + "\"}")
+ .post("/").then().statusCode(400)
+ .body("__type", equalTo("ConstraintViolationException"));
+ assertRefused(AwsBasicCredentials.create(closed, SECRET), StsClient.builder(), StsClient::getCallerIdentity,
+ 403, "InvalidClientTokenId");
+ }
+
+ @Test
+ void anIamUsersKeyInTheClosedAccountIsRefused() {
+ UserCredentials user = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), auth(closed, "iam"),
+ "closing-user");
+ AwsCredentials key = AwsBasicCredentials.create(user.accessKeyId(), user.secretAccessKey());
+ assertEquals(closed, callerAccount(key));
+ closeAccount(closed);
+
+ assertRefused(key, StsClient.builder(), StsClient::getCallerIdentity, 403, "InvalidClientTokenId");
+ }
+
+ @Test
+ void aSessionInTheClosedAccountIsRefused() {
+ Session session = EnforcementFixtures.assumeRole(endpoint.getPort(), MANAGEMENT_ACCOUNT,
+ "arn:aws:iam::" + closed + ":role/OrganizationAccountAccessRole");
+ AwsCredentials key = AwsSessionCredentials.create(session.accessKeyId(), SECRET, session.sessionToken());
+ assertEquals(closed, callerAccount(key));
+ closeAccount(closed);
+
+ assertRefused(key, StsClient.builder(), StsClient::getCallerIdentity, 403, "InvalidClientTokenId");
+ }
+
+ @Test
+ void theOtherAccountsKeepWorking() {
+ closeAccount(closed);
+
+ assertEquals(open, callerAccount(AwsBasicCredentials.create(open, SECRET)));
+ assertEquals(MANAGEMENT_ACCOUNT, callerAccount(AwsBasicCredentials.create(MANAGEMENT_ACCOUNT, SECRET)));
+ }
+
+ private void assertListedAsClosed(RequestSpecification listing) {
+ listing.post("/").then().statusCode(200)
+ .body("Accounts.findAll { it.Id == '" + closed + "' }.State", contains("CLOSED"))
+ .body("Accounts.findAll { it.Id == '" + closed + "' }.Status", contains("SUSPENDED"))
+ .body("Accounts.findAll { it.Id == '" + open + "' }.State", contains("ACTIVE"));
+ }
+
+ private & AwsSyncClientBuilder, C extends SdkClient> void assertRefused(
+ AwsCredentials credentials, B builder, FunctionInvalidAccessKeyId"),
+ aborted.getValue().getEntity().toString());
+ }
+
@Test
void resolvesIamAccessKeyFromPresignedCredential() {
sessionAccounts.put("AKIAPRESIGNEDACCESSKEY", "444455556666");
@@ -618,7 +736,7 @@ class AccountContextFilterTest {
strictPartitions = true;
RegionResolver gov = new RegionResolver("us-gov-west-1", DEFAULT_ACCOUNT);
AccountContextFilter govFilter = new AccountContextFilter(accountResolver, gov, requestContext,
- key -> Optional.empty(), this::config, () -> catalog);
+ key -> Optional.empty(), closedAccountLookup(accountId -> false), this::config, () -> catalog);
String credential = "AKID/20261015/custom:222222222222/cloudfront/aws4_request";
ContainerRequestContext ctx = mockContext(query ? null : "AWS4-HMAC-SHA256 Credential=" + credential,
query ? credential : null);
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 839bb418b5..54034118e6 100644
--- a/src/test/java/io/floci/aws/services/account/AccountOrganizationsContextIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/account/AccountOrganizationsContextIntegrationTest.java
@@ -160,11 +160,12 @@ class AccountOrganizationsContextIntegrationTest {
}
@Test
- void accountPendingClosureIsStillActive() {
+ void closedAccountReportsClosed() {
String closing = createAccount("account-to-close");
organizations("CloseAccount", "{\"AccountId\":\"" + closing + "\"}");
- account(closing, "/getAccountInformation", "{}").statusCode(200).body("AccountState", equalTo("ACTIVE"));
+ account(MANAGEMENT, "/getAccountInformation", "{\"AccountId\":\"" + closing + "\"}")
+ .statusCode(200).body("AccountState", equalTo("CLOSED"));
}
private static JsonNode describeAccount(String accountId) throws Exception {
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 f0bf64cb35..c3ef570c2a 100644
--- a/src/test/java/io/floci/aws/services/account/AccountServiceTest.java
+++ b/src/test/java/io/floci/aws/services/account/AccountServiceTest.java
@@ -531,6 +531,14 @@ class AccountServiceTest {
assertEquals("ACTIVE", service.getAccountInformation(ACCOUNT_ID, mapper.createObjectNode()).accountState());
}
+ @Test
+ void closedAccountReportsClosedRatherThanItsSuspendedStatus() {
+ when(organizations.findAccount(ACCOUNT_ID))
+ .thenReturn(Optional.of(organizationAccount("CREATED", "SUSPENDED", Instant.EPOCH)));
+
+ assertEquals("CLOSED", service.getAccountInformation(ACCOUNT_ID, mapper.createObjectNode()).accountState());
+ }
+
@Test
void putAccountNameRenamesTheOrganizationRecordAndKeepsTheNameForTheAccount() {
service.putAccountName(ACCOUNT_ID, accountNameRequest("Team Account"));
diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/OrganizationsCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/OrganizationsCfnProvisionerTest.java
index c9cac75afa..973214b4a7 100644
--- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/OrganizationsCfnProvisionerTest.java
+++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/OrganizationsCfnProvisionerTest.java
@@ -252,6 +252,25 @@ class OrganizationsCfnProvisionerTest {
assertEquals(ACCOUNT_PATH, r.getAttributes().get("Paths"));
}
+ @Test
+ void aClosedAccountsStateGetAttIsClosed() {
+ CreateAccountStatus status = new CreateAccountStatus();
+ status.setState("SUCCEEDED");
+ status.setAccountId("123456789012");
+ when(organizations.createAccount(eq(ACCOUNT), eq("dev@example.com"), eq("Dev"), any(), eq(false)))
+ .thenReturn(status);
+ OrganizationAccount closed = account(ROOT_ID);
+ closed.setStatus("SUSPENDED");
+ when(organizations.describeAccount(ACCOUNT, "123456789012")).thenReturn(closed);
+
+ StackResource r = resource("AWS::Organizations::Account", "Dev");
+ provisioner.provision(r, mapper.createObjectNode().put("AccountName", "Dev").put("Email", "dev@example.com"),
+ ctx());
+
+ assertEquals("SUSPENDED", r.getAttributes().get("Status"));
+ assertEquals("CLOSED", r.getAttributes().get("State"));
+ }
+
@Test
void accountPathsNameTheParentTheAccountWasMovedInto() {
CreateAccountStatus status = new CreateAccountStatus();
diff --git a/src/test/java/io/floci/aws/services/organizations/OrganizationsCloseAccountIamIntegrationTest.java b/src/test/java/io/floci/aws/services/organizations/OrganizationsCloseAccountIamIntegrationTest.java
new file mode 100644
index 0000000000..d4b5781f98
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/organizations/OrganizationsCloseAccountIamIntegrationTest.java
@@ -0,0 +1,96 @@
+package io.floci.aws.services.organizations;
+
+import io.floci.aws.testing.AwsTestClients;
+import io.floci.aws.testing.EnforcementFixtures;
+import io.floci.aws.testing.EnforcementFixtures.Session;
+import io.floci.aws.testing.IamEnforcementProfile;
+import io.floci.aws.testing.OrganizationsFixture;
+import io.floci.aws.testing.RestAssuredJsonUtils;
+import io.quarkus.test.common.http.TestHTTPResource;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
+import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.sts.StsClient;
+import software.amazon.awssdk.services.sts.model.StsException;
+
+import java.net.URI;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * A closed account's credentials under IAM enforcement: the account root key and a session the management account
+ * opened in it both work until the account is closed, and are refused before any policy is read once it is.
+ *
+ *