mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(organizations): close accounts and refuse their requests (#9331)
This commit is contained in:
1 parent
ee51e7b993
commit
85a63055be
21 files changed
+749
-29
No files matched your search
@@ -2,6 +2,7 @@ package io.floci.aws.core.common;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.services.s3.S3Controller;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ResourceInfo;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
@@ -16,6 +17,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
@@ -24,6 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -40,6 +43,7 @@ class AccountContextFilterTest {
|
||||
private RegionResolver regionResolver;
|
||||
private RequestContext requestContext;
|
||||
private Map<String, String> sessionAccounts;
|
||||
private Set<String> closedAccounts;
|
||||
private boolean allowUnknownRegions;
|
||||
private boolean strictPartitions;
|
||||
private boolean enforceIam;
|
||||
@@ -52,14 +56,16 @@ class AccountContextFilterTest {
|
||||
regionResolver = spy(new RegionResolver(DEFAULT_REGION, DEFAULT_ACCOUNT));
|
||||
requestContext = new RequestContext();
|
||||
sessionAccounts = new HashMap<>();
|
||||
closedAccounts = new HashSet<>();
|
||||
allowUnknownRegions = false;
|
||||
strictPartitions = false;
|
||||
enforceIam = false;
|
||||
catalog = mock(ResolvedServiceCatalog.class);
|
||||
when(catalog.byResourceClass(S3Controller.class)).thenReturn(Optional.of(legacyDescriptor()));
|
||||
when(catalog.canonicalCredentialScope(anyString())).thenAnswer(call -> call.getArgument(0));
|
||||
SessionAccountLookup sessionLookup = akid -> Optional.ofNullable(sessionAccounts.get(akid));
|
||||
filter = new AccountContextFilter(accountResolver, regionResolver, requestContext, sessionLookup,
|
||||
this::config, () -> catalog);
|
||||
closedAccountLookup(closedAccounts::contains), this::config, () -> catalog);
|
||||
}
|
||||
|
||||
private ServiceDescriptor legacyDescriptor() {
|
||||
@@ -228,7 +234,7 @@ class AccountContextFilterTest {
|
||||
void anUnsignedRequestGetsTheDeploymentPartition() {
|
||||
RegionResolver china = new RegionResolver("cn-north-1", DEFAULT_ACCOUNT);
|
||||
AccountContextFilter chinaFilter = new AccountContextFilter(accountResolver, china, requestContext,
|
||||
akid -> Optional.empty(), this::config, () -> catalog);
|
||||
akid -> Optional.empty(), closedAccountLookup(accountId -> false), this::config, () -> catalog);
|
||||
chinaFilter.filter(mockContext(null, null));
|
||||
assertEquals("cn-north-1", requestContext.getRegion());
|
||||
assertEquals("aws-cn", requestContext.getPartition());
|
||||
@@ -408,6 +414,118 @@ class AccountContextFilterTest {
|
||||
assertEquals("us-west-2", requestContext.getRegion());
|
||||
}
|
||||
|
||||
/** The account's own 12-digit key, an IAM user's key and a session in the account all resolve to it. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"333344445555", "AKIAEXAMPLEACCESSKEY", "ASIAEXAMPLESESSIONKEY"})
|
||||
void aClosedAccountsCredentialIsRefused(String accessKeyId) {
|
||||
sessionAccounts.put("AKIAEXAMPLEACCESSKEY", "333344445555");
|
||||
sessionAccounts.put("ASIAEXAMPLESESSIONKEY", "333344445555");
|
||||
closedAccounts.add("333344445555");
|
||||
ContainerRequestContext ctx = mockContext(
|
||||
"AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260617/us-east-1/dynamodb/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc",
|
||||
null
|
||||
);
|
||||
|
||||
filter.filter(ctx);
|
||||
|
||||
assertRefusedAsUnrecognized(ctx);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClosedAccountsPresignedRequestIsRefused() {
|
||||
closedAccounts.add("333344445555");
|
||||
ContainerRequestContext ctx = mockContext(null, "333344445555/20260617/us-east-1/sqs/aws4_request");
|
||||
|
||||
filter.filter(ctx);
|
||||
|
||||
assertRefusedAsUnrecognized(ctx);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClosedAccountsS3RequestGetsS3sError() {
|
||||
closedAccounts.add("333344445555");
|
||||
ContainerRequestContext ctx = mockContext(
|
||||
"AWS4-HMAC-SHA256 Credential=333344445555/20260617/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc",
|
||||
null
|
||||
);
|
||||
|
||||
filter.filter(ctx);
|
||||
|
||||
assertRefusedAsS3InvalidAccessKey(ctx);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClosedAccountsLegacyS3SignatureGetsS3sError() {
|
||||
filter.resourceInfo = mock(ResourceInfo.class);
|
||||
doReturn(S3Controller.class).when(filter.resourceInfo).getResourceClass();
|
||||
closedAccounts.add("333344445555");
|
||||
ContainerRequestContext ctx = mockContext("AWS 333344445555:signature", null);
|
||||
|
||||
filter.filter(ctx);
|
||||
|
||||
assertRefusedAsS3InvalidAccessKey(ctx);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noAccountIsClosedWithoutOrganizations() {
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<ClosedAccountLookup> absent = mock(Instance.class);
|
||||
AccountContextFilter withoutOrganizations = new AccountContextFilter(accountResolver, regionResolver,
|
||||
requestContext, akid -> Optional.empty(), absent, this::config, () -> catalog);
|
||||
ContainerRequestContext ctx = mockContext(
|
||||
"AWS4-HMAC-SHA256 Credential=333344445555/20260617/us-east-1/dynamodb/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc",
|
||||
null
|
||||
);
|
||||
|
||||
withoutOrganizations.filter(ctx);
|
||||
|
||||
assertEquals("333344445555", requestContext.getAccountId());
|
||||
verify(ctx, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherAccountIsServedWhileOneIsClosed() {
|
||||
closedAccounts.add("333344445555");
|
||||
ContainerRequestContext ctx = mockContext(
|
||||
"AWS4-HMAC-SHA256 Credential=444455556666/20260617/us-east-1/dynamodb/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc",
|
||||
null
|
||||
);
|
||||
|
||||
filter.filter(ctx);
|
||||
|
||||
assertEquals("444455556666", requestContext.getAccountId());
|
||||
verify(ctx, never()).abortWith(any());
|
||||
}
|
||||
|
||||
private static Instance<ClosedAccountLookup> closedAccountLookup(ClosedAccountLookup lookup) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<ClosedAccountLookup> instance = mock(Instance.class);
|
||||
when(instance.isResolvable()).thenReturn(true);
|
||||
when(instance.get()).thenReturn(lookup);
|
||||
return instance;
|
||||
}
|
||||
|
||||
private static void assertRefusedAsUnrecognized(ContainerRequestContext ctx) {
|
||||
ArgumentCaptor<Response> aborted = ArgumentCaptor.forClass(Response.class);
|
||||
verify(ctx).abortWith(aborted.capture());
|
||||
assertEquals(403, aborted.getValue().getStatus());
|
||||
AwsErrorResponse error = (AwsErrorResponse) aborted.getValue().getEntity();
|
||||
assertEquals("UnrecognizedClientException", error.type());
|
||||
assertEquals("The security token included in the request is invalid.", error.message());
|
||||
}
|
||||
|
||||
private static void assertRefusedAsS3InvalidAccessKey(ContainerRequestContext ctx) {
|
||||
ArgumentCaptor<Response> aborted = ArgumentCaptor.forClass(Response.class);
|
||||
verify(ctx).abortWith(aborted.capture());
|
||||
assertEquals(403, aborted.getValue().getStatus());
|
||||
assertTrue(aborted.getValue().getEntity().toString().contains("<Code>InvalidAccessKeyId</Code>"),
|
||||
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);
|
||||
|
||||
+3
-2
@@ -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 {
|
||||
|
||||
@@ -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"));
|
||||
|
||||
+19
@@ -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();
|
||||
|
||||
+96
@@ -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.
|
||||
*
|
||||
* <p>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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+214
@@ -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.
|
||||
*
|
||||
* <p>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 <B extends AwsClientBuilder<B, C> & AwsSyncClientBuilder<B, C>, C extends SdkClient> void assertRefused(
|
||||
AwsCredentials credentials, B builder, Function<C, ?> call, int status, String errorCode) {
|
||||
try (C client = AwsTestClients.create(builder, credentials, Region.US_EAST_1, endpoint)) {
|
||||
AwsServiceException refused = assertThrows(AwsServiceException.class, () -> call.apply(client));
|
||||
assertEquals(status, refused.statusCode());
|
||||
assertEquals(errorCode, refused.awsErrorDetails().errorCode());
|
||||
}
|
||||
}
|
||||
|
||||
private ValidatableResponse presignedPost(String bucket, String accountId) {
|
||||
return given().multiPart("key", accountId)
|
||||
.multiPart("x-amz-credential", accountId + "/20261124/us-east-1/s3/aws4_request")
|
||||
.multiPart("file", accountId, "body".getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when().post("/" + bucket).then();
|
||||
}
|
||||
|
||||
private void closeAccount(String accountId) {
|
||||
organizations.request(MANAGEMENT_ACCOUNT, "CloseAccount", "{\"AccountId\":\"" + accountId + "\"}")
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private String callerAccount(AwsCredentials credentials) {
|
||||
try (StsClient sts = AwsTestClients.create(StsClient.builder(), credentials, Region.US_EAST_1, endpoint)) {
|
||||
return sts.getCallerIdentity().account();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,79 @@ class OrganizationsServiceTest {
|
||||
service.listTagsForResource(MANAGEMENT_ACCOUNT, status.getAccountId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeAccountLeavesTheAccountClosedInItsOrganization() {
|
||||
service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
|
||||
String member = service.createAccount(MANAGEMENT_ACCOUNT, "member@example.com", "Member", null, false)
|
||||
.getAccountId();
|
||||
|
||||
service.closeAccount(MANAGEMENT_ACCOUNT, member);
|
||||
|
||||
OrganizationAccount closed = service.describeAccount(MANAGEMENT_ACCOUNT, member);
|
||||
assertEquals("SUSPENDED", closed.getStatus());
|
||||
assertEquals("CLOSED", OrganizationsService.accountState(closed));
|
||||
assertTrue(service.isClosed(member));
|
||||
assertFalse(service.isClosed(MANAGEMENT_ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeAccountRefusesAnAccountAlreadyClosed() {
|
||||
service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
|
||||
String member = service.createAccount(MANAGEMENT_ACCOUNT, "member@example.com", "Member", null, false)
|
||||
.getAccountId();
|
||||
service.closeAccount(MANAGEMENT_ACCOUNT, member);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.closeAccount(MANAGEMENT_ACCOUNT, member));
|
||||
|
||||
assertEquals("AccountAlreadyClosedException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveAccountKeepsItsStatusAsItsState() {
|
||||
service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
|
||||
|
||||
OrganizationAccount management = service.describeAccount(MANAGEMENT_ACCOUNT, MANAGEMENT_ACCOUNT);
|
||||
|
||||
assertEquals("ACTIVE", OrganizationsService.accountState(management));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAccountOutsideEveryOrganizationIsNotClosed() {
|
||||
assertFalse(service.isClosed(OUTSIDER_ACCOUNT));
|
||||
assertFalse(service.isClosed(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClosedAccountCannotBecomeADelegatedAdministrator() {
|
||||
service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
|
||||
String member = service.createAccount(MANAGEMENT_ACCOUNT, "member@example.com", "Member", null, false)
|
||||
.getAccountId();
|
||||
service.closeAccount(MANAGEMENT_ACCOUNT, member);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.registerDelegatedAdministrator(MANAGEMENT_ACCOUNT, member, "config.amazonaws.com"));
|
||||
|
||||
assertEquals("ConstraintViolationException", error.getErrorCode());
|
||||
assertEquals("You cannot register a suspended account as a delegated administrator.", error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClosedAccountStaysInItsOrganization() {
|
||||
service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
|
||||
String member = service.createAccount(MANAGEMENT_ACCOUNT, "member@example.com", "Member", null, false)
|
||||
.getAccountId();
|
||||
service.closeAccount(MANAGEMENT_ACCOUNT, member);
|
||||
|
||||
AwsException removed = assertThrows(AwsException.class,
|
||||
() -> service.removeAccountFromOrganization(MANAGEMENT_ACCOUNT, member));
|
||||
AwsException left = assertThrows(AwsException.class, () -> service.leaveOrganization(member));
|
||||
|
||||
assertEquals("ConstraintViolationException", removed.getErrorCode());
|
||||
assertEquals("ConstraintViolationException", left.getErrorCode());
|
||||
assertTrue(service.isClosed(member));
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameAccountRenamesAMemberAccountAndTheManagementAccount() {
|
||||
service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
|
||||
|
||||
@@ -116,7 +116,7 @@ class S3GlobalLegacyListingTest {
|
||||
AccountResolver accounts = mock(AccountResolver.class);
|
||||
when(accounts.extractS3AccessKeyId(anyString())).thenAnswer(invocation -> request.getAccountId());
|
||||
controller = new S3Controller(s3, null, region, null, vertx, null, trail, accounts,
|
||||
request, null, null, config, new S3VirtualHostFilter(), Clock.systemUTC());
|
||||
request, null, null, null, config, new S3VirtualHostFilter(), Clock.systemUTC());
|
||||
headers = mock(HttpHeaders.class);
|
||||
uri = mock(UriInfo.class);
|
||||
when(uri.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
|
||||
@@ -63,6 +63,7 @@ class S3PolicyStatusControllerTest {
|
||||
mock(RequestContext.class),
|
||||
mock(IamService.class),
|
||||
mock(IamEnforcementFilter.class),
|
||||
null,
|
||||
mock(EmulatorConfig.class),
|
||||
new S3VirtualHostFilter(),
|
||||
Clock.systemUTC());
|
||||
|
||||
Reference in new issue
Block a user