mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(securityhub): add member account operations and DisableOrganizationAdminAccount (#7791)
Add CreateMembers, ListMembers, GetMembers, DisassociateMembers, DeleteMembers and DisableOrganizationAdminAccount, the operations Landing Zone Accelerator and Terraform's aws_securityhub_member use to manage Security Hub members. Organization accounts added by the delegated administrator become Enabled members and have Security Hub and its default standards enabled for them; other accounts are Created. Organization members can be disassociated but not deleted. Disabling the delegated administrator marks its organization members Removed. Macie already served POST /members and GET /members, so Security Hub calls on those paths were answered by Macie. Both routes now dispatch on the SigV4 credential scope in SecurityAdminController, as GET /admin already does; unsigned requests still reach Macie. Closes #2197
This commit is contained in:
1 parent
d9a258ae44
commit
9f77c736e9
12 files changed
+937
-23
No files matched your search
+113
@@ -0,0 +1,113 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.parallel.ResourceLock;
|
||||
import software.amazon.awssdk.services.organizations.OrganizationsClient;
|
||||
import software.amazon.awssdk.services.organizations.model.AlreadyInOrganizationException;
|
||||
import software.amazon.awssdk.services.organizations.model.CreateAccountResponse;
|
||||
import software.amazon.awssdk.services.securityhub.SecurityHubClient;
|
||||
import software.amazon.awssdk.services.securityhub.model.AdminAccount;
|
||||
import software.amazon.awssdk.services.securityhub.model.CreateMembersResponse;
|
||||
import software.amazon.awssdk.services.securityhub.model.DeleteMembersResponse;
|
||||
import software.amazon.awssdk.services.securityhub.model.GetMembersResponse;
|
||||
import software.amazon.awssdk.services.securityhub.model.Member;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeFalse;
|
||||
|
||||
@DisplayName("Security Hub member accounts")
|
||||
@ResourceLock("organizations")
|
||||
class SecurityHubMembersTest {
|
||||
private static final Logger LOG = Logger.getLogger(SecurityHubMembersTest.class);
|
||||
private static final String MANAGEMENT_ACCOUNT = "test";
|
||||
|
||||
@Test
|
||||
void delegatedAdministratorManagesOrganizationMembersUsingAwsSdk() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Avoids changing Security Hub organization settings in real AWS");
|
||||
|
||||
try (OrganizationsClient organizations = TestFixtures.organizationsClient()) {
|
||||
boolean createdOrganization = ensureOrganization(organizations);
|
||||
String adminAccount = createMemberAccount(organizations, "securityhub-members-admin");
|
||||
String memberAccount = createMemberAccount(organizations, "securityhub-members-member");
|
||||
|
||||
try (SecurityHubClient management = TestFixtures.securityHubClient(MANAGEMENT_ACCOUNT);
|
||||
SecurityHubClient administrator = TestFixtures.securityHubClient(adminAccount);
|
||||
SecurityHubClient member = TestFixtures.securityHubClient(memberAccount)) {
|
||||
// Another test may have left its own administrator designated; an organization has only one.
|
||||
for (AdminAccount existing : management.listOrganizationAdminAccounts(request -> {}).adminAccounts()) {
|
||||
management.disableOrganizationAdminAccount(request -> request.adminAccountId(existing.accountId()));
|
||||
}
|
||||
management.enableOrganizationAdminAccount(request -> request.adminAccountId(adminAccount));
|
||||
|
||||
CreateMembersResponse created = administrator.createMembers(request -> request
|
||||
.accountDetails(details -> details.accountId(memberAccount)));
|
||||
assertThat(created.unprocessedAccounts()).isEmpty();
|
||||
assertThat(member.describeHub(request -> {}).hubArn()).contains(memberAccount);
|
||||
|
||||
assertThat(administrator.listMembers(request -> {}).members())
|
||||
.singleElement()
|
||||
.satisfies(listed -> {
|
||||
assertThat(listed.accountId()).isEqualTo(memberAccount);
|
||||
assertThat(listed.administratorId()).isEqualTo(adminAccount);
|
||||
assertThat(listed.memberStatus()).isEqualTo("Enabled");
|
||||
assertThat(listed.invitedAt()).isNotNull();
|
||||
assertThat(listed.updatedAt()).isNotNull();
|
||||
});
|
||||
|
||||
GetMembersResponse fetched = administrator.getMembers(request -> request.accountIds(memberAccount));
|
||||
assertThat(fetched.members()).extracting(Member::accountId).containsExactly(memberAccount);
|
||||
assertThat(fetched.unprocessedAccounts()).isEmpty();
|
||||
|
||||
administrator.disassociateMembers(request -> request.accountIds(memberAccount));
|
||||
DeleteMembersResponse deleted = administrator.deleteMembers(request -> request.accountIds(memberAccount));
|
||||
assertThat(deleted.unprocessedAccounts())
|
||||
.singleElement()
|
||||
.satisfies(result -> assertThat(result.accountId()).isEqualTo(memberAccount));
|
||||
assertThat(administrator.listMembers(request -> {}).members()).isEmpty();
|
||||
List<Member> all = administrator.listMembers(request -> request.onlyAssociated(false)).members();
|
||||
assertThat(all).extracting(Member::memberStatus).containsExactly("Removed");
|
||||
|
||||
management.disableOrganizationAdminAccount(request -> request.adminAccountId(adminAccount));
|
||||
assertThat(management.listOrganizationAdminAccounts(request -> {}).adminAccounts()).isEmpty();
|
||||
} finally {
|
||||
cleanup("remove member account", () ->
|
||||
organizations.removeAccountFromOrganization(request -> request.accountId(memberAccount)));
|
||||
cleanup("remove administrator account", () ->
|
||||
organizations.removeAccountFromOrganization(request -> request.accountId(adminAccount)));
|
||||
if (createdOrganization) {
|
||||
cleanup("delete test organization", organizations::deleteOrganization);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void cleanup(String action, Runnable cleanup) {
|
||||
try {
|
||||
cleanup.run();
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnf(e, "Security Hub members compatibility cleanup failed: %s", action);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean ensureOrganization(OrganizationsClient organizations) {
|
||||
try {
|
||||
organizations.createOrganization(request -> request.featureSet("ALL"));
|
||||
return true;
|
||||
} catch (AlreadyInOrganizationException e) {
|
||||
LOG.debugf(e, "Default compatibility account already belongs to an AWS organization");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static String createMemberAccount(OrganizationsClient organizations, String prefix) {
|
||||
String suffix = TestFixtures.uniqueName(prefix);
|
||||
CreateAccountResponse response = organizations.createAccount(request -> request
|
||||
.accountName(suffix)
|
||||
.email(suffix + "@example.com"));
|
||||
return response.createAccountStatus().accountId();
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [Amazon Macie](macie2.md) | `/admin`, `/macie`, `/admin/configuration` | REST JSON | 8 |
|
||||
| [Amazon Inspector](inspector2.md) | `/delegatedadminaccounts/*`, `/status/batch/get`, `/enable`, `/disable`, `/organizationconfiguration/*` | REST JSON | 8 |
|
||||
| [Amazon Verified Permissions](verifiedpermissions.md) | `POST /` + `X-Amz-Target: VerifiedPermissions.*` | JSON 1.0 | 34 |
|
||||
| [Security Hub](securityhub.md) | `/organization/*`, `/accounts`, `/findingAggregator/*`, `/configurationPolicy*`, `/standards*`, `/tags/*`, `/findings*` | REST JSON | 28 |
|
||||
| [Security Hub](securityhub.md) | `/organization/*`, `/accounts`, `/findingAggregator/*`, `/configurationPolicy*`, `/standards*`, `/members*`, `/tags/*`, `/findings*` | REST JSON | 34 |
|
||||
| [Amazon Detective](detective.md) | `/orgs/*`, `/graphs/list`, `/graph/*` | REST JSON | 8 |
|
||||
| [Amazon Connect](connect.md) | `/instance`, `/instance/{instanceId}/*`, `/tags/*` | REST JSON | 15 |
|
||||
| [Amazon AppIntegrations](appintegrations.md) | `/eventIntegrations/*`, `/dataIntegrations/*`, `/tags/*` | REST JSON | 14 |
|
||||
|
||||
@@ -10,11 +10,11 @@ Floci implements the REST JSON organization surfaces used to configure Macie loc
|
||||
| `EnableOrganizationAdminAccount` | Designates the delegated Macie administrator account. |
|
||||
| `GetMacieSession` | Returns the current account Macie session. |
|
||||
| `EnableMacie` | Enables Macie for the current account. |
|
||||
| `CreateMember` | - |
|
||||
| `ListMembers` | - |
|
||||
| `UpdateOrganizationConfiguration` | Updates organization auto-enable settings as the delegated administrator. |
|
||||
| `DescribeOrganizationConfiguration` | Reads organization auto-enable settings as the delegated administrator. |
|
||||
| `ListOrganizationAdminAccounts` | Lists the delegated Macie administrator for the organization. |
|
||||
| `CreateMember` | - |
|
||||
| `ListMembers` | - |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
Delegation is visible in both the management-account and delegated-account request scopes. Designating the delegated administrator enables Macie for that account in the Region, matching AWS Organizations integration behavior.
|
||||
|
||||
@@ -13,6 +13,10 @@ Floci implements the AWS Security Hub CSPM organization and central-configuratio
|
||||
| --- | --- |
|
||||
| `ListOrganizationAdminAccounts` | - |
|
||||
| `EnableOrganizationAdminAccount` | - |
|
||||
| `DisableOrganizationAdminAccount` | Removes the delegated administrator; only the management account may call it. The former administrator keeps Security Hub, and its organization members become `Removed` |
|
||||
| `GetMembers` | Returns the named members whatever their status; an account that is not a member is listed in `UnprocessedAccounts` |
|
||||
| `DisassociateMembers` | Sets the named members to `Removed`; an account that is not a member is `ResourceNotFoundException`, and then none of the batch changes |
|
||||
| `DeleteMembers` | Deletes invited members; an organization account or a non member is listed in `UnprocessedAccounts`, since AWS allows only disassociating organization accounts |
|
||||
| `DescribeHub` | - |
|
||||
| `EnableSecurityHub` | - |
|
||||
| `UpdateSecurityHubConfiguration` | - |
|
||||
@@ -36,6 +40,8 @@ Floci implements the AWS Security Hub CSPM organization and central-configuratio
|
||||
| `StartConfigurationPolicyAssociation` | - |
|
||||
| `StartConfigurationPolicyDisassociation` | - |
|
||||
| `ListConfigurationPolicyAssociations` | - |
|
||||
| `CreateMembers` | Adds up to 50 accounts. The delegated administrator's organization accounts become `Enabled` at once, with Security Hub and its default standards enabled for them; other accounts are `Created` |
|
||||
| `ListMembers` | Lists `Enabled` members, or every member with `OnlyAssociated=false`, in account order with up to 50 per page |
|
||||
| `ListTagsForResource` | - |
|
||||
| `TagResource` | - |
|
||||
| `UntagResource` | - |
|
||||
@@ -47,6 +53,10 @@ The supported surface includes Security Hub CSPM enablement and configuration, d
|
||||
|
||||
`EnableOrganizationAdminAccount` supports the AWS `SecurityHub` and `SecurityHubV2` feature values. Legacy `SecurityHub` delegation enables Security Hub CSPM for the delegated administrator in the current Region, matching AWS organization behavior.
|
||||
|
||||
Member accounts follow the AWS organization model. `CreateMembers` from the delegated `SecurityHub` administrator adds an account of the same organization as an `Enabled` member, without an invitation, and enables Security Hub CSPM with its default standards in that account unless it is already enabled. The organization management account is the exception: it must enable Security Hub CSPM itself, and until it does it is reported in `UnprocessedAccounts`. Any other account is added as `Created`; `InviteMembers` and the member side of invitations are not implemented. `CreateMembers` on a `Removed` member adds it again.
|
||||
|
||||
`POST /members` and `GET /members` are shared with Macie, which serves `CreateMember` and `ListMembers` at the same paths. Floci routes each request by the service in its SigV4 credential scope; an unsigned request reaches Macie, as before.
|
||||
|
||||
Finding aggregators support `ALL_REGIONS`, `ALL_REGIONS_EXCEPT_SPECIFIED`, `SPECIFIED_REGIONS`, and `NO_REGIONS`. `GetFindingAggregator` accepts the complete finding-aggregator ARN carried in the greedy AWS REST path.
|
||||
|
||||
`BatchImportFindings` stores findings in the requested Region and reports invalid items individually. `GetFindings` reads findings from that Region and supports the `EQUALS`, `NOT_EQUALS`, and `PREFIX` comparisons for its documented string filters. `SortCriteria`, other filter comparisons, cross-Region aggregation of findings, and `BatchUpdateFindings` are not implemented.
|
||||
|
||||
@@ -18,7 +18,6 @@ import jakarta.ws.rs.PATCH;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
@@ -77,8 +76,8 @@ public class MacieController {
|
||||
return empty();
|
||||
}
|
||||
|
||||
@POST @Path("/members")
|
||||
public Response createMember(@Context HttpHeaders headers, String body) {
|
||||
/** CreateMember. Security Hub serves POST /members too, so SecurityAdminController routes here by signing scope. */
|
||||
public Response createMember(String region, String body) {
|
||||
JsonNode request = readTree(body);
|
||||
JsonNode account = request.get("account");
|
||||
if (account == null || !account.isObject()) {
|
||||
@@ -96,7 +95,7 @@ public class MacieController {
|
||||
entry.getKey(), entry.getValue().isTextual() ? entry.getValue().asText() : null));
|
||||
}
|
||||
MacieMember member = macieService.createMember(
|
||||
region(headers),
|
||||
region,
|
||||
regionResolver.getAccountId(),
|
||||
account.path("accountId").asText(null),
|
||||
account.path("email").asText(null),
|
||||
@@ -106,13 +105,10 @@ public class MacieController {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@GET @Path("/members")
|
||||
public Response listMembers(@Context HttpHeaders headers,
|
||||
@QueryParam("maxResults") String maxResults,
|
||||
@QueryParam("nextToken") String nextToken,
|
||||
@QueryParam("onlyAssociated") String onlyAssociated) {
|
||||
/** ListMembers. Security Hub serves GET /members too, so SecurityAdminController routes here by signing scope. */
|
||||
public Response listMembers(String region, String maxResults, String nextToken, String onlyAssociated) {
|
||||
MacieService.Page<MacieMember> page = macieService.listMembers(
|
||||
region(headers), regionResolver.getAccountId(), maxResults, nextToken, onlyAssociated);
|
||||
region, regionResolver.getAccountId(), maxResults, nextToken, onlyAssociated);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("members", objectMapper.valueToTree(page.items()));
|
||||
if (page.nextToken() != null) {
|
||||
|
||||
@@ -9,14 +9,17 @@ import io.floci.aws.core.common.SigV4CredentialScope;
|
||||
import io.floci.aws.services.guardduty.GuardDutyService;
|
||||
import io.floci.aws.services.guardduty.model.AdminAccount;
|
||||
import io.floci.aws.services.macie2.MacieController;
|
||||
import io.floci.aws.services.securityhub.SecurityHubController;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
|
||||
@@ -25,14 +28,17 @@ import jakarta.ws.rs.core.UriInfo;
|
||||
public class SecurityAdminController {
|
||||
private final GuardDutyService guardDutyService;
|
||||
private final MacieController macieController;
|
||||
private final SecurityHubController securityHubController;
|
||||
private final ObjectMapper mapper;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public SecurityAdminController(GuardDutyService guardDutyService, MacieController macieController,
|
||||
SecurityHubController securityHubController,
|
||||
ObjectMapper mapper, RegionResolver regionResolver) {
|
||||
this.guardDutyService = guardDutyService;
|
||||
this.macieController = macieController;
|
||||
this.securityHubController = securityHubController;
|
||||
this.mapper = mapper;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
@@ -43,16 +49,9 @@ public class SecurityAdminController {
|
||||
@Context UriInfo uriInfo,
|
||||
@QueryParam("maxResults") String maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
String service = SigV4CredentialScope.serviceName(headers.getHeaderString("Authorization"))
|
||||
.or(() -> SigV4CredentialScope.serviceNameFromCredential(
|
||||
uriInfo.getQueryParameters().getFirst("X-Amz-Credential")))
|
||||
.orElse("");
|
||||
String service = signingService(headers, uriInfo);
|
||||
if ("macie2".equals(service)) {
|
||||
String region = headers.getHeaderString("Authorization") != null
|
||||
? regionResolver.resolveRegion(headers)
|
||||
: regionResolver.resolveRegionFromPresignedCredential(
|
||||
uriInfo.getQueryParameters().getFirst("X-Amz-Credential"));
|
||||
return macieController.listAdminInternal(region);
|
||||
return macieController.listAdminInternal(signingRegion(headers, uriInfo));
|
||||
}
|
||||
if ("guardduty".equals(service) || service.isBlank()) {
|
||||
GuardDutyService.Page<AdminAccount> page = guardDutyService.listOrganizationAdminAccounts(
|
||||
@@ -69,4 +68,51 @@ public class SecurityAdminController {
|
||||
}
|
||||
throw new AwsException("UnknownOperationException", "GET /admin is not supported for " + service + ".", 400);
|
||||
}
|
||||
|
||||
/** Macie CreateMember and Security Hub CreateMembers share POST /members; the signing scope picks one. */
|
||||
@POST
|
||||
@Path("/members")
|
||||
public Response createMembers(@Context HttpHeaders headers, @Context UriInfo uriInfo, String body) {
|
||||
String service = signingService(headers, uriInfo);
|
||||
if ("securityhub".equals(service)) {
|
||||
return securityHubController.createMembers(signingRegion(headers, uriInfo), body);
|
||||
}
|
||||
if ("macie2".equals(service) || service.isBlank()) {
|
||||
return macieController.createMember(signingRegion(headers, uriInfo), body);
|
||||
}
|
||||
throw new AwsException("UnknownOperationException", "POST /members is not supported for " + service + ".", 400);
|
||||
}
|
||||
|
||||
/** Macie and Security Hub ListMembers share GET /members, with differently cased query parameters. */
|
||||
@GET
|
||||
@Path("/members")
|
||||
public Response listMembers(@Context HttpHeaders headers, @Context UriInfo uriInfo) {
|
||||
String service = signingService(headers, uriInfo);
|
||||
MultivaluedMap<String, String> query = uriInfo.getQueryParameters();
|
||||
if ("securityhub".equals(service)) {
|
||||
return securityHubController.listMembers(signingRegion(headers, uriInfo), query.getFirst("OnlyAssociated"),
|
||||
query.getFirst("MaxResults"), query.getFirst("NextToken"));
|
||||
}
|
||||
if ("macie2".equals(service) || service.isBlank()) {
|
||||
return macieController.listMembers(signingRegion(headers, uriInfo), query.getFirst("maxResults"),
|
||||
query.getFirst("nextToken"), query.getFirst("onlyAssociated"));
|
||||
}
|
||||
throw new AwsException("UnknownOperationException", "GET /members is not supported for " + service + ".", 400);
|
||||
}
|
||||
|
||||
/** The service a request is signed for, from its Authorization header or, presigned, its X-Amz-Credential. */
|
||||
private static String signingService(HttpHeaders headers, UriInfo uriInfo) {
|
||||
return SigV4CredentialScope.serviceName(headers.getHeaderString("Authorization"))
|
||||
.or(() -> SigV4CredentialScope.serviceNameFromCredential(
|
||||
uriInfo.getQueryParameters().getFirst("X-Amz-Credential")))
|
||||
.orElse("");
|
||||
}
|
||||
|
||||
/** The region a request is signed for, read from the same place as {@link #signingService}. */
|
||||
private String signingRegion(HttpHeaders headers, UriInfo uriInfo) {
|
||||
return headers.getHeaderString("Authorization") != null
|
||||
? regionResolver.resolveRegion(headers)
|
||||
: regionResolver.resolveRegionFromPresignedCredential(
|
||||
uriInfo.getQueryParameters().getFirst("X-Amz-Credential"));
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.Pagination;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.services.securityhub.model.SecurityHubAssociation;
|
||||
import io.floci.aws.services.securityhub.model.SecurityHubMember;
|
||||
import io.floci.aws.services.securityhub.model.SecurityHubState;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
@@ -27,6 +28,7 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Path("/")
|
||||
@@ -85,6 +87,88 @@ public class SecurityHubController {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/organization/admin/disable")
|
||||
public Response disableOrganizationAdminAccount(@Context HttpHeaders headers, String body) {
|
||||
JsonNode request = readTree(body);
|
||||
securityHubService.disableOrganizationAdminAccount(
|
||||
region(headers), request.path("AdminAccountId").asText(null), request.path("Feature").asText(null));
|
||||
return empty();
|
||||
}
|
||||
|
||||
/** CreateMembers. Macie serves POST /members too, so SecurityAdminController routes here by signing scope. */
|
||||
public Response createMembers(String region, String body) {
|
||||
List<SecurityHubService.UnprocessedAccount> unprocessed =
|
||||
securityHubService.createMembers(region, readTree(body));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
unprocessedAccounts(response, unprocessed);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
/** ListMembers. Macie serves GET /members too, so SecurityAdminController routes here by signing scope. */
|
||||
public Response listMembers(String region, String onlyAssociated, String maxResults, String nextToken) {
|
||||
PaginatedResult<SecurityHubMember> page =
|
||||
securityHubService.memberPage(region, onlyAssociated, maxResults, nextToken);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode members = response.putArray("Members");
|
||||
page.items().forEach(member -> members.add(member(member)));
|
||||
if (page.nextToken() != null) {
|
||||
response.put("NextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/members/get")
|
||||
public Response getMembers(@Context HttpHeaders headers, String body) {
|
||||
SecurityHubService.MemberLookup lookup = securityHubService.getMembers(region(headers), readTree(body));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode members = response.putArray("Members");
|
||||
lookup.members().forEach(member -> members.add(member(member)));
|
||||
unprocessedAccounts(response, lookup.unprocessed());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/members/disassociate")
|
||||
public Response disassociateMembers(@Context HttpHeaders headers, String body) {
|
||||
securityHubService.disassociateMembers(region(headers), readTree(body));
|
||||
return empty();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/members/delete")
|
||||
public Response deleteMembers(@Context HttpHeaders headers, String body) {
|
||||
List<SecurityHubService.UnprocessedAccount> unprocessed =
|
||||
securityHubService.deleteMembers(region(headers), readTree(body));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
unprocessedAccounts(response, unprocessed);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private ObjectNode member(SecurityHubMember member) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("AccountId", member.getAccountId());
|
||||
if (member.getEmail() != null) {
|
||||
node.put("Email", member.getEmail());
|
||||
}
|
||||
node.put("MasterId", member.getAdministratorId());
|
||||
node.put("AdministratorId", member.getAdministratorId());
|
||||
node.put("MemberStatus", member.getMemberStatus());
|
||||
if (member.getInvitedAt() != null) {
|
||||
node.put("InvitedAt", member.getInvitedAt());
|
||||
}
|
||||
node.put("UpdatedAt", member.getUpdatedAt());
|
||||
return node;
|
||||
}
|
||||
|
||||
private static void unprocessedAccounts(ObjectNode response, List<SecurityHubService.UnprocessedAccount> accounts) {
|
||||
ArrayNode items = response.putArray("UnprocessedAccounts");
|
||||
for (SecurityHubService.UnprocessedAccount account : accounts) {
|
||||
items.addObject().put("AccountId", account.accountId()).put("ProcessingResult", account.processingResult());
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/accounts")
|
||||
public Response describeHub(@Context HttpHeaders headers) {
|
||||
|
||||
@@ -14,11 +14,14 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.organizations.OrganizationsService;
|
||||
import io.floci.aws.services.securityhub.model.SecurityHubAssociation;
|
||||
import io.floci.aws.services.securityhub.model.SecurityHubMember;
|
||||
import io.floci.aws.services.securityhub.model.SecurityHubState;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -27,6 +30,9 @@ import java.util.UUID;
|
||||
@ApplicationScoped
|
||||
public class SecurityHubService implements Resettable {
|
||||
private static final String SELF_MANAGED = "SELF_MANAGED_SECURITY_HUB";
|
||||
private static final String MEMBER_CREATED = "Created";
|
||||
private static final String MEMBER_ENABLED = "Enabled";
|
||||
private static final String MEMBER_REMOVED = "Removed";
|
||||
private static final List<String> LINKING_MODES = List.of(
|
||||
"ALL_REGIONS", "ALL_REGIONS_EXCEPT_SPECIFIED", "SPECIFIED_REGIONS", "NO_REGIONS");
|
||||
|
||||
@@ -85,6 +91,242 @@ public class SecurityHubService implements Resettable {
|
||||
return management;
|
||||
}
|
||||
|
||||
/**
|
||||
* DisableOrganizationAdminAccount: removes the delegation. The former administrator keeps Security Hub
|
||||
* enabled, but loses its organization role, so the organization members it managed become Removed.
|
||||
*/
|
||||
public synchronized void disableOrganizationAdminAccount(String region, String adminAccountId, String feature) {
|
||||
requireAccountId(adminAccountId, "AdminAccountId");
|
||||
String requestedFeature = normalizeFeature(feature);
|
||||
String managementAccountId = requireCallerManagementAccount();
|
||||
SecurityHubState management = state(region);
|
||||
if (!adminAccountId.equals(management.getAdminAccountId())
|
||||
|| !requestedFeature.equals(management.getAdminFeature())) {
|
||||
throw invalid("Account " + adminAccountId + " is not the " + requestedFeature
|
||||
+ " administrator account for the organization.");
|
||||
}
|
||||
// The management account can delegate to itself, and then both states are the same stored record.
|
||||
boolean selfDelegated = adminAccountId.equals(managementAccountId);
|
||||
SecurityHubState delegated = selfDelegated
|
||||
? management : states.getForAccount(adminAccountId, region).orElse(null);
|
||||
String now = Instant.now().toString();
|
||||
if (delegated != null) {
|
||||
delegated.setAdminAccountId(null);
|
||||
delegated.setAdminFeature("SecurityHub");
|
||||
for (SecurityHubMember member : delegated.getMembers().values()) {
|
||||
if (member.isOrganizationMember() && !MEMBER_REMOVED.equals(member.getMemberStatus())) {
|
||||
member.setMemberStatus(MEMBER_REMOVED);
|
||||
member.setUpdatedAt(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
management.setAdminAccountId(null);
|
||||
management.setAdminFeature("SecurityHub");
|
||||
save(region, management);
|
||||
if (delegated != null && !selfDelegated) {
|
||||
states.putForAccount(adminAccountId, region, delegated);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Members ───────────────────────────────────────────────────────────────
|
||||
|
||||
/** A CreateMembers or DeleteMembers entry Security Hub did not act on, with the reason. */
|
||||
public record UnprocessedAccount(String accountId, String processingResult) {}
|
||||
|
||||
private record AccountDetail(String accountId, String email) {}
|
||||
|
||||
/**
|
||||
* CreateMembers: an account in the caller's organization, added by the delegated administrator, becomes
|
||||
* an Enabled member at once and has Security Hub and its default standards enabled for it. Any other
|
||||
* account is Created and would need an invitation. Accounts Security Hub cannot add are reported back
|
||||
* rather than failing the batch; a malformed entry fails it before anything is changed.
|
||||
*/
|
||||
public synchronized List<UnprocessedAccount> createMembers(String region, JsonNode request) {
|
||||
SecurityHubState administrator = requireSubscribed(region);
|
||||
JsonNode details = request == null ? null : request.get("AccountDetails");
|
||||
if (details == null || !details.isArray() || details.isEmpty() || details.size() > 50) {
|
||||
throw invalid("AccountDetails must hold 1 to 50 accounts.");
|
||||
}
|
||||
// Every entry is checked before any is applied: applying one enables Security Hub in that account
|
||||
// and changes the live stored state, so a later malformed entry must not leave a half-applied batch.
|
||||
List<AccountDetail> accounts = new ArrayList<>(details.size());
|
||||
for (JsonNode detail : details) {
|
||||
String accountId = requireText(detail, "AccountId", "InvalidInputException");
|
||||
String email = text(detail, "Email");
|
||||
if (email != null && email.isBlank()) {
|
||||
throw invalid("Email must contain a non-whitespace character.");
|
||||
}
|
||||
accounts.add(new AccountDetail(accountId, email));
|
||||
}
|
||||
String administratorId = regionResolver.getAccountId();
|
||||
boolean delegatedAdministrator = administratorId.equals(administrator.getAdminAccountId())
|
||||
&& "SecurityHub".equals(administrator.getAdminFeature());
|
||||
String organization = delegatedAdministrator
|
||||
? organizationsService.findManagementAccountForResource(administratorId).orElse(null) : null;
|
||||
List<UnprocessedAccount> unprocessed = new ArrayList<>();
|
||||
String now = Instant.now().toString();
|
||||
for (AccountDetail account : accounts) {
|
||||
String accountId = account.accountId();
|
||||
String email = account.email();
|
||||
if (!accountId.matches("\\d{12}")) {
|
||||
unprocessed.add(new UnprocessedAccount(accountId, "Invalid account ID."));
|
||||
continue;
|
||||
}
|
||||
if (accountId.equals(administratorId)) {
|
||||
unprocessed.add(new UnprocessedAccount(accountId,
|
||||
"The administrator account cannot be added as a member account."));
|
||||
continue;
|
||||
}
|
||||
SecurityHubMember existing = administrator.getMembers().get(accountId);
|
||||
boolean organizationMember = organization != null && organization.equals(
|
||||
organizationsService.findManagementAccountForResource(accountId).orElse(null));
|
||||
// A member stays as it is, unless it was Removed, or was Created before it joined the organization.
|
||||
boolean joinedOrganization = existing != null && organizationMember
|
||||
&& MEMBER_CREATED.equals(existing.getMemberStatus());
|
||||
if (existing != null && !MEMBER_REMOVED.equals(existing.getMemberStatus()) && !joinedOrganization) {
|
||||
continue;
|
||||
}
|
||||
if (organizationMember && !enableForOrganizationMember(region, accountId, organization)) {
|
||||
unprocessed.add(new UnprocessedAccount(accountId, "Security Hub CSPM cannot be enabled "
|
||||
+ "automatically for the organization management account. Enable it in that account first."));
|
||||
continue;
|
||||
}
|
||||
administrator.getMembers().put(accountId, new SecurityHubMember(
|
||||
accountId,
|
||||
email != null ? email : existing == null ? null : existing.getEmail(),
|
||||
administratorId,
|
||||
organizationMember ? MEMBER_ENABLED : MEMBER_CREATED,
|
||||
organizationMember,
|
||||
organizationMember ? now : null,
|
||||
now));
|
||||
}
|
||||
save(region, administrator);
|
||||
return unprocessed;
|
||||
}
|
||||
|
||||
/** Enables Security Hub with its default standards for an organization account; false if Security Hub may not. */
|
||||
private boolean enableForOrganizationMember(String region, String accountId, String managementAccountId) {
|
||||
SecurityHubState member = states.getForAccount(accountId, region).orElseGet(SecurityHubState::new);
|
||||
if (member.isEnabled()) {
|
||||
return true;
|
||||
}
|
||||
if (accountId.equals(managementAccountId)) {
|
||||
return false;
|
||||
}
|
||||
member.setEnabled(true);
|
||||
for (Standard standard : STANDARDS) {
|
||||
if (standard.enabledByDefault()) {
|
||||
member.getStandardsSubscriptions().put(
|
||||
subscriptionArn(region, accountId, standard), standardsArn(region, standard));
|
||||
}
|
||||
}
|
||||
states.putForAccount(accountId, region, member);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** ListMembers: only Enabled members unless OnlyAssociated is false, in account ID order. */
|
||||
public synchronized PaginatedResult<SecurityHubMember> memberPage(String region, String onlyAssociatedValue,
|
||||
String maxResultsValue, String nextToken) {
|
||||
SecurityHubState administrator = requireSubscribed(region);
|
||||
boolean onlyAssociated = true;
|
||||
if (onlyAssociatedValue != null) {
|
||||
if (!"true".equalsIgnoreCase(onlyAssociatedValue) && !"false".equalsIgnoreCase(onlyAssociatedValue)) {
|
||||
throw invalid("OnlyAssociated must be true or false.");
|
||||
}
|
||||
onlyAssociated = Boolean.parseBoolean(onlyAssociatedValue);
|
||||
}
|
||||
Integer maxResults = Pagination.parseMaxResults(maxResultsValue, "InvalidInputException");
|
||||
if (maxResults != null && (maxResults < 1 || maxResults > 50)) {
|
||||
throw invalid("MaxResults must be between 1 and 50.");
|
||||
}
|
||||
boolean associatedOnly = onlyAssociated;
|
||||
List<SecurityHubMember> members = administrator.getMembers().values().stream()
|
||||
.filter(member -> !associatedOnly || MEMBER_ENABLED.equals(member.getMemberStatus()))
|
||||
.sorted(Comparator.comparing(SecurityHubMember::getAccountId))
|
||||
.map(SecurityHubMember::copy)
|
||||
.toList();
|
||||
return Pagination.paginate(members, SecurityHubMember::getAccountId, maxResults, nextToken,
|
||||
50, 50, "InvalidInputException", "NextToken");
|
||||
}
|
||||
|
||||
/** GetMembers: the named members whatever their status; an account that is not one is reported back. */
|
||||
public synchronized MemberLookup getMembers(String region, JsonNode request) {
|
||||
SecurityHubState administrator = requireSubscribed(region);
|
||||
List<SecurityHubMember> found = new ArrayList<>();
|
||||
List<UnprocessedAccount> unprocessed = new ArrayList<>();
|
||||
for (String accountId : accountIds(request)) {
|
||||
SecurityHubMember member = administrator.getMembers().get(accountId);
|
||||
if (member == null) {
|
||||
unprocessed.add(new UnprocessedAccount(accountId, "Account is not a member of this administrator."));
|
||||
} else {
|
||||
found.add(member.copy());
|
||||
}
|
||||
}
|
||||
return new MemberLookup(found, unprocessed);
|
||||
}
|
||||
|
||||
public record MemberLookup(List<SecurityHubMember> members, List<UnprocessedAccount> unprocessed) {}
|
||||
|
||||
/**
|
||||
* DisassociateMembers: the named members become Removed. Every account is checked before any changes,
|
||||
* so an account that is not a member fails the whole request with ResourceNotFoundException.
|
||||
*/
|
||||
public synchronized void disassociateMembers(String region, JsonNode request) {
|
||||
SecurityHubState administrator = requireSubscribed(region);
|
||||
List<String> accountIds = accountIds(request);
|
||||
for (String accountId : accountIds) {
|
||||
if (!administrator.getMembers().containsKey(accountId)) {
|
||||
throw notFound("Account " + accountId + " is not a member of this administrator.");
|
||||
}
|
||||
}
|
||||
String now = Instant.now().toString();
|
||||
for (String accountId : accountIds) {
|
||||
SecurityHubMember member = administrator.getMembers().get(accountId);
|
||||
if (!MEMBER_REMOVED.equals(member.getMemberStatus())) {
|
||||
member.setMemberStatus(MEMBER_REMOVED);
|
||||
member.setUpdatedAt(now);
|
||||
}
|
||||
}
|
||||
save(region, administrator);
|
||||
}
|
||||
|
||||
/**
|
||||
* DeleteMembers: removes invited members. An organization account cannot be deleted, only disassociated,
|
||||
* so it is reported back, as is an account that is not a member.
|
||||
*/
|
||||
public synchronized List<UnprocessedAccount> deleteMembers(String region, JsonNode request) {
|
||||
SecurityHubState administrator = requireSubscribed(region);
|
||||
List<UnprocessedAccount> unprocessed = new ArrayList<>();
|
||||
for (String accountId : accountIds(request)) {
|
||||
SecurityHubMember member = administrator.getMembers().get(accountId);
|
||||
if (member == null) {
|
||||
unprocessed.add(new UnprocessedAccount(accountId, "Account is not a member of this administrator."));
|
||||
} else if (member.isOrganizationMember()) {
|
||||
unprocessed.add(new UnprocessedAccount(accountId,
|
||||
"An account that belongs to the organization cannot be deleted; disassociate it instead."));
|
||||
} else {
|
||||
administrator.getMembers().remove(accountId);
|
||||
}
|
||||
}
|
||||
save(region, administrator);
|
||||
return unprocessed;
|
||||
}
|
||||
|
||||
private static List<String> accountIds(JsonNode request) {
|
||||
JsonNode ids = request == null ? null : request.get("AccountIds");
|
||||
if (ids == null || !ids.isArray()) {
|
||||
throw invalid("AccountIds is required.");
|
||||
}
|
||||
List<String> accountIds = new ArrayList<>(ids.size());
|
||||
for (JsonNode id : ids) {
|
||||
if (!id.isTextual()) {
|
||||
throw invalid("AccountIds must contain account ID strings.");
|
||||
}
|
||||
accountIds.add(id.textValue());
|
||||
}
|
||||
return accountIds;
|
||||
}
|
||||
|
||||
public synchronized void enableSecurityHub(String region, JsonNode request) {
|
||||
SecurityHubState state = state(region);
|
||||
if (state.isEnabled()) {
|
||||
@@ -147,7 +389,11 @@ public class SecurityHubService implements Resettable {
|
||||
}
|
||||
|
||||
public String subscriptionArn(String region, Standard standard) {
|
||||
return regionResolver.buildArn("securityhub", region,
|
||||
return subscriptionArn(region, regionResolver.getAccountId(), standard);
|
||||
}
|
||||
|
||||
private String subscriptionArn(String region, String accountId, Standard standard) {
|
||||
return regionResolver.buildArn("securityhub", region, accountId,
|
||||
"subscription/" + standard.path().substring(standard.path().indexOf('/') + 1));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package io.floci.aws.services.securityhub.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/** A member account of a Security Hub administrator, stored in the administrator's state. */
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class SecurityHubMember {
|
||||
private String accountId;
|
||||
private String email;
|
||||
private String administratorId;
|
||||
private String memberStatus;
|
||||
private boolean organizationMember;
|
||||
private String invitedAt;
|
||||
private String updatedAt;
|
||||
|
||||
public SecurityHubMember() {
|
||||
}
|
||||
|
||||
public SecurityHubMember(String accountId, String email, String administratorId, String memberStatus,
|
||||
boolean organizationMember, String invitedAt, String updatedAt) {
|
||||
this.accountId = accountId;
|
||||
this.email = email;
|
||||
this.administratorId = administratorId;
|
||||
this.memberStatus = memberStatus;
|
||||
this.organizationMember = organizationMember;
|
||||
this.invitedAt = invitedAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public String getAccountId() { return accountId; }
|
||||
public void setAccountId(String accountId) { this.accountId = accountId; }
|
||||
public String getEmail() { return email; }
|
||||
public void setEmail(String email) { this.email = email; }
|
||||
public String getAdministratorId() { return administratorId; }
|
||||
public void setAdministratorId(String administratorId) { this.administratorId = administratorId; }
|
||||
public String getMemberStatus() { return memberStatus; }
|
||||
public void setMemberStatus(String memberStatus) { this.memberStatus = memberStatus; }
|
||||
public boolean isOrganizationMember() { return organizationMember; }
|
||||
public void setOrganizationMember(boolean organizationMember) { this.organizationMember = organizationMember; }
|
||||
public String getInvitedAt() { return invitedAt; }
|
||||
public void setInvitedAt(String invitedAt) { this.invitedAt = invitedAt; }
|
||||
public String getUpdatedAt() { return updatedAt; }
|
||||
public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; }
|
||||
|
||||
public SecurityHubMember copy() {
|
||||
return new SecurityHubMember(accountId, email, administratorId, memberStatus, organizationMember,
|
||||
invitedAt, updatedAt);
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,8 @@ public class SecurityHubState {
|
||||
private Map<String, SecurityHubAssociation> associations = new LinkedHashMap<>();
|
||||
/** Enabled standards: subscription ARN to standards ARN. */
|
||||
private Map<String, String> standardsSubscriptions = new LinkedHashMap<>();
|
||||
/** This account's members when it is a Security Hub administrator, keyed by member account ID. */
|
||||
private Map<String, SecurityHubMember> members = new LinkedHashMap<>();
|
||||
|
||||
public String getAdminAccountId() { return adminAccountId; }
|
||||
public void setAdminAccountId(String adminAccountId) { this.adminAccountId = adminAccountId; }
|
||||
@@ -65,4 +67,8 @@ public class SecurityHubState {
|
||||
public void setPolicies(Map<String, JsonNode> policies) { this.policies = policies; }
|
||||
public Map<String, SecurityHubAssociation> getAssociations() { return associations; }
|
||||
public void setAssociations(Map<String, SecurityHubAssociation> associations) { this.associations = associations; }
|
||||
public Map<String, SecurityHubMember> getMembers() { return members; }
|
||||
public void setMembers(Map<String, SecurityHubMember> value) {
|
||||
members = value == null ? new LinkedHashMap<>() : value;
|
||||
}
|
||||
}
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
package io.floci.aws.services.securityhub;
|
||||
|
||||
import io.floci.aws.services.organizations.OrganizationsService;
|
||||
import io.floci.aws.services.organizations.model.Handshake;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.everyItem;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
@QuarkusTest
|
||||
class SecurityHubMembersIntegrationTest {
|
||||
|
||||
@Inject
|
||||
OrganizationsService organizationsService;
|
||||
|
||||
@Test
|
||||
void delegatedAdministratorManagesOrganizationMemberLifecycle() {
|
||||
String management = "947100000001";
|
||||
String administrator = "947100000002";
|
||||
String member = "947100000003";
|
||||
createOrganization(management, administrator, member);
|
||||
designateAdministrator(management, administrator);
|
||||
|
||||
given().header("Authorization", auth(member)).get("/accounts").then().statusCode(404);
|
||||
createMembers(administrator, "[{\"AccountId\":\"" + member + "\"}]")
|
||||
.then().statusCode(200).body("UnprocessedAccounts", hasSize(0));
|
||||
|
||||
// An organization account is enabled for the member, with Security Hub's default standards.
|
||||
given().header("Authorization", auth(member)).get("/accounts").then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", auth(member)).body("{}")
|
||||
.post("/standards/get").then().statusCode(200)
|
||||
.body("StandardsSubscriptions", hasSize(2))
|
||||
.body("StandardsSubscriptions.StandardsSubscriptionArn",
|
||||
everyItem(containsString(":" + member + ":subscription/")));
|
||||
|
||||
given().header("Authorization", auth(administrator)).get("/members").then().statusCode(200)
|
||||
.body("Members", hasSize(1))
|
||||
.body("Members[0].AccountId", equalTo(member))
|
||||
.body("Members[0].AdministratorId", equalTo(administrator))
|
||||
.body("Members[0].MasterId", equalTo(administrator))
|
||||
.body("Members[0].MemberStatus", equalTo("Enabled"))
|
||||
.body("Members[0].InvitedAt", notNullValue())
|
||||
.body("Members[0].UpdatedAt", notNullValue())
|
||||
.body("Members[0].Email", nullValue())
|
||||
.body("NextToken", nullValue());
|
||||
|
||||
given().contentType("application/json").header("Authorization", auth(administrator))
|
||||
.body("{\"AccountIds\":[\"" + member + "\",\"947100000099\"]}")
|
||||
.post("/members/get").then().statusCode(200)
|
||||
.body("Members", hasSize(1))
|
||||
.body("Members[0].AccountId", equalTo(member))
|
||||
.body("UnprocessedAccounts", hasSize(1))
|
||||
.body("UnprocessedAccounts[0].AccountId", equalTo("947100000099"))
|
||||
.body("UnprocessedAccounts[0].ProcessingResult", notNullValue());
|
||||
|
||||
// An organization account can only be disassociated, never deleted.
|
||||
deleteMembers(administrator, member).then().statusCode(200)
|
||||
.body("UnprocessedAccounts", hasSize(1))
|
||||
.body("UnprocessedAccounts[0].AccountId", equalTo(member));
|
||||
given().contentType("application/json").header("Authorization", auth(administrator))
|
||||
.body("{\"AccountIds\":[\"" + member + "\"]}")
|
||||
.post("/members/disassociate").then().statusCode(200);
|
||||
given().header("Authorization", auth(administrator)).get("/members").then().statusCode(200)
|
||||
.body("Members", hasSize(0));
|
||||
given().header("Authorization", auth(administrator)).queryParam("OnlyAssociated", "false")
|
||||
.get("/members").then().statusCode(200)
|
||||
.body("Members", hasSize(1))
|
||||
.body("Members[0].MemberStatus", equalTo("Removed"));
|
||||
|
||||
createMembers(administrator, "[{\"AccountId\":\"" + member + "\"}]")
|
||||
.then().statusCode(200).body("UnprocessedAccounts", hasSize(0));
|
||||
given().header("Authorization", auth(administrator)).get("/members").then().statusCode(200)
|
||||
.body("Members[0].MemberStatus", equalTo("Enabled"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void accountOutsideTheOrganizationIsCreatedAndCanBeDeleted() {
|
||||
String administrator = "947100000011";
|
||||
String invited = "957100000012";
|
||||
enableSecurityHub(administrator);
|
||||
|
||||
createMembers(administrator, "[{\"AccountId\":\"" + invited + "\",\"Email\":\"sec@example.com\"}]")
|
||||
.then().statusCode(200).body("UnprocessedAccounts", hasSize(0));
|
||||
given().header("Authorization", auth(invited)).get("/accounts").then().statusCode(404);
|
||||
given().header("Authorization", auth(administrator)).get("/members").then().statusCode(200)
|
||||
.body("Members", hasSize(0));
|
||||
given().header("Authorization", auth(administrator)).queryParam("OnlyAssociated", "FALSE")
|
||||
.get("/members").then().statusCode(200)
|
||||
.body("Members", hasSize(1))
|
||||
.body("Members[0].MemberStatus", equalTo("Created"))
|
||||
.body("Members[0].Email", equalTo("sec@example.com"))
|
||||
.body("Members[0].InvitedAt", nullValue());
|
||||
|
||||
deleteMembers(administrator, invited).then().statusCode(200).body("UnprocessedAccounts", hasSize(0));
|
||||
given().contentType("application/json").header("Authorization", auth(administrator))
|
||||
.body("{\"AccountIds\":[\"" + invited + "\"]}")
|
||||
.post("/members/get").then().statusCode(200)
|
||||
.body("Members", hasSize(0))
|
||||
.body("UnprocessedAccounts[0].AccountId", equalTo(invited));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createMembersReportsAccountsItCannotAdd() {
|
||||
String management = "947100000021";
|
||||
String administrator = "947100000022";
|
||||
createOrganization(management, administrator);
|
||||
designateAdministrator(management, administrator);
|
||||
|
||||
createMembers(administrator, "[{\"AccountId\":\"" + management + "\"},{\"AccountId\":\"" + administrator
|
||||
+ "\"},{\"AccountId\":\"12345\"}]")
|
||||
.then().statusCode(200)
|
||||
.body("UnprocessedAccounts", hasSize(3))
|
||||
.body("UnprocessedAccounts.AccountId", equalTo(List.of(management, administrator, "12345")));
|
||||
given().header("Authorization", auth(administrator)).queryParam("OnlyAssociated", "false")
|
||||
.get("/members").then().statusCode(200).body("Members", hasSize(0));
|
||||
|
||||
// Once the management account enables Security Hub itself, it can be added like any other member.
|
||||
enableSecurityHub(management);
|
||||
createMembers(administrator, "[{\"AccountId\":\"" + management + "\"}]")
|
||||
.then().statusCode(200).body("UnprocessedAccounts", hasSize(0));
|
||||
given().header("Authorization", auth(administrator)).get("/members").then().statusCode(200)
|
||||
.body("Members[0].AccountId", equalTo(management))
|
||||
.body("Members[0].MemberStatus", equalTo("Enabled"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void memberOperationsValidateInputAndState() {
|
||||
String administrator = "947100000031";
|
||||
createMembers(administrator, "[{\"AccountId\":\"957100000031\"}]")
|
||||
.then().statusCode(401).body("__type", equalTo("InvalidAccessException"));
|
||||
given().header("Authorization", auth(administrator)).get("/members")
|
||||
.then().statusCode(401).body("__type", equalTo("InvalidAccessException"));
|
||||
|
||||
enableSecurityHub(administrator);
|
||||
createMembers(administrator, "[]").then().statusCode(400).body("__type", equalTo("InvalidInputException"));
|
||||
String fiftyOne = IntStream.range(0, 51)
|
||||
.mapToObj(i -> "{\"AccountId\":\"" + (957100001000L + i) + "\"}")
|
||||
.collect(Collectors.joining(",", "[", "]"));
|
||||
createMembers(administrator, fiftyOne).then().statusCode(400).body("__type", equalTo("InvalidInputException"));
|
||||
createMembers(administrator, "[{\"Email\":\"a@example.com\"}]")
|
||||
.then().statusCode(400).body("__type", equalTo("InvalidInputException"));
|
||||
given().header("Authorization", auth(administrator)).queryParam("MaxResults", "51")
|
||||
.get("/members").then().statusCode(400).body("__type", equalTo("InvalidInputException"));
|
||||
given().header("Authorization", auth(administrator)).queryParam("OnlyAssociated", "maybe")
|
||||
.get("/members").then().statusCode(400).body("__type", equalTo("InvalidInputException"));
|
||||
given().contentType("application/json").header("Authorization", auth(administrator)).body("{}")
|
||||
.post("/members/get").then().statusCode(400).body("__type", equalTo("InvalidInputException"));
|
||||
|
||||
// A disassociation naming a non-member fails as a whole: the real member stays as it was.
|
||||
createMembers(administrator, "[{\"AccountId\":\"957100000032\"},{\"AccountId\":\"957100000033\"}]")
|
||||
.then().statusCode(200);
|
||||
given().contentType("application/json").header("Authorization", auth(administrator))
|
||||
.body("{\"AccountIds\":[\"957100000032\",\"957100000099\"]}")
|
||||
.post("/members/disassociate").then().statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
given().contentType("application/json").header("Authorization", auth(administrator))
|
||||
.body("{\"AccountIds\":[\"957100000032\"]}")
|
||||
.post("/members/get").then().statusCode(200)
|
||||
.body("Members[0].MemberStatus", equalTo("Created"));
|
||||
|
||||
String nextToken = given().header("Authorization", auth(administrator))
|
||||
.queryParam("OnlyAssociated", "false").queryParam("MaxResults", "1")
|
||||
.get("/members").then().statusCode(200)
|
||||
.body("Members", hasSize(1))
|
||||
.body("Members[0].AccountId", equalTo("957100000032"))
|
||||
.extract().path("NextToken");
|
||||
given().header("Authorization", auth(administrator))
|
||||
.queryParam("OnlyAssociated", "false").queryParam("MaxResults", "1").queryParam("NextToken", nextToken)
|
||||
.get("/members").then().statusCode(200)
|
||||
.body("Members[0].AccountId", equalTo("957100000033"))
|
||||
.body("NextToken", nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disablingTheAdministratorRemovesItsOrganizationRole() {
|
||||
String management = "947100000041";
|
||||
String administrator = "947100000042";
|
||||
String member = "947100000043";
|
||||
String successor = "947100000044";
|
||||
createOrganization(management, administrator, member, successor);
|
||||
designateAdministrator(management, administrator);
|
||||
createMembers(administrator, "[{\"AccountId\":\"" + member + "\"},{\"AccountId\":\"957100000041\"}]")
|
||||
.then().statusCode(200);
|
||||
|
||||
disableAdministrator(administrator, administrator).then().statusCode(403)
|
||||
.body("__type", equalTo("AccessDeniedException"));
|
||||
disableAdministrator(management, successor).then().statusCode(400)
|
||||
.body("__type", equalTo("InvalidInputException"));
|
||||
given().contentType("application/json").header("Authorization", auth(management))
|
||||
.body("{\"AdminAccountId\":\"" + administrator + "\",\"Feature\":\"SecurityHubV2\"}")
|
||||
.post("/organization/admin/disable").then().statusCode(400)
|
||||
.body("__type", equalTo("InvalidInputException"));
|
||||
|
||||
disableAdministrator(management, administrator).then().statusCode(200);
|
||||
given().header("Authorization", auth(management)).get("/organization/admin").then().statusCode(200)
|
||||
.body("AdminAccounts", hasSize(0));
|
||||
given().header("Authorization", auth(administrator)).get("/accounts").then().statusCode(200);
|
||||
given().header("Authorization", auth(administrator)).get("/organization/configuration")
|
||||
.then().statusCode(401).body("__type", equalTo("InvalidAccessException"));
|
||||
given().header("Authorization", auth(administrator)).queryParam("OnlyAssociated", "false")
|
||||
.get("/members").then().statusCode(200)
|
||||
.body("Members.find { it.AccountId == '" + member + "' }.MemberStatus", equalTo("Removed"))
|
||||
.body("Members.find { it.AccountId == '957100000041' }.MemberStatus", equalTo("Created"));
|
||||
disableAdministrator(management, administrator).then().statusCode(400)
|
||||
.body("__type", equalTo("InvalidInputException"));
|
||||
|
||||
designateAdministrator(management, successor);
|
||||
given().header("Authorization", auth(management)).get("/organization/admin").then().statusCode(200)
|
||||
.body("AdminAccounts[0].AccountId", equalTo(successor));
|
||||
}
|
||||
|
||||
@Test
|
||||
void managementAccountCanRemoveItselfAsAdministrator() {
|
||||
String management = "947100000051";
|
||||
String member = "947100000052";
|
||||
createOrganization(management, member);
|
||||
enableSecurityHub(management);
|
||||
designateAdministrator(management, management);
|
||||
createMembers(management, "[{\"AccountId\":\"" + member + "\"}]").then().statusCode(200);
|
||||
|
||||
disableAdministrator(management, management).then().statusCode(200);
|
||||
given().header("Authorization", auth(management)).get("/organization/admin").then().statusCode(200)
|
||||
.body("AdminAccounts", hasSize(0));
|
||||
given().header("Authorization", auth(management)).queryParam("OnlyAssociated", "false")
|
||||
.get("/members").then().statusCode(200)
|
||||
.body("Members[0].MemberStatus", equalTo("Removed"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sharedMembersRoutesFollowTheSigningService() {
|
||||
String administrator = "947100000061";
|
||||
enableSecurityHub(administrator);
|
||||
createMembers(administrator, "[{\"AccountId\":\"957100000061\"}]").then().statusCode(200);
|
||||
|
||||
given().contentType("application/json").header("Authorization", EnforcementFixtures.auth(administrator, "macie2"))
|
||||
.body("{}").post("/macie").then().statusCode(200);
|
||||
given().header("Authorization", EnforcementFixtures.auth(administrator, "macie2")).get("/members").then().statusCode(200)
|
||||
.body("members", hasSize(0));
|
||||
given().header("Authorization", auth(administrator)).queryParam("OnlyAssociated", "false")
|
||||
.get("/members").then().statusCode(200)
|
||||
.body("Members", hasSize(1));
|
||||
given().contentType("application/json").header("Authorization", EnforcementFixtures.auth(administrator, "guardduty"))
|
||||
.body("{}").post("/members").then().statusCode(400)
|
||||
.body("__type", equalTo("UnknownOperationException"));
|
||||
given().header("Authorization", EnforcementFixtures.auth(administrator, "guardduty")).get("/members").then().statusCode(400)
|
||||
.body("__type", equalTo("UnknownOperationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedBatchChangesNothing() {
|
||||
String management = "947100000071";
|
||||
String administrator = "947100000072";
|
||||
String member = "947100000073";
|
||||
createOrganization(management, administrator, member);
|
||||
designateAdministrator(management, administrator);
|
||||
|
||||
// The valid organization account comes first, so a half-applied batch would have enabled it.
|
||||
createMembers(administrator, "[{\"AccountId\":\"" + member + "\"},{\"AccountId\":\"957100000071\","
|
||||
+ "\"Email\":\" \"}]")
|
||||
.then().statusCode(400).body("__type", equalTo("InvalidInputException"));
|
||||
given().header("Authorization", auth(member)).get("/accounts").then().statusCode(404);
|
||||
given().header("Authorization", auth(administrator)).queryParam("OnlyAssociated", "false")
|
||||
.get("/members").then().statusCode(200).body("Members", hasSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createdMemberBecomesEnabledOnceItJoinsTheOrganization() {
|
||||
String management = "947100000081";
|
||||
String administrator = "947100000082";
|
||||
String latecomer = "957100000083";
|
||||
createOrganization(management, administrator);
|
||||
designateAdministrator(management, administrator);
|
||||
|
||||
createMembers(administrator, "[{\"AccountId\":\"" + latecomer + "\"}]").then().statusCode(200);
|
||||
given().header("Authorization", auth(administrator)).queryParam("OnlyAssociated", "false")
|
||||
.get("/members").then().statusCode(200).body("Members[0].MemberStatus", equalTo("Created"));
|
||||
|
||||
joinOrganization(management, latecomer);
|
||||
createMembers(administrator, "[{\"AccountId\":\"" + latecomer + "\"}]")
|
||||
.then().statusCode(200).body("UnprocessedAccounts", hasSize(0));
|
||||
given().header("Authorization", auth(administrator)).get("/members").then().statusCode(200)
|
||||
.body("Members", hasSize(1))
|
||||
.body("Members[0].MemberStatus", equalTo("Enabled"))
|
||||
.body("Members[0].InvitedAt", notNullValue());
|
||||
given().header("Authorization", auth(latecomer)).get("/accounts").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void presignedMemberRequestsUseTheCredentialScope() {
|
||||
String administrator = "947100000091";
|
||||
enableSecurityHub(administrator);
|
||||
|
||||
// presignedQuery is already URL-encoded, so RestAssured must send it as it is.
|
||||
given().urlEncodingEnabled(false).contentType("application/json")
|
||||
.body("{\"AccountDetails\":[{\"AccountId\":\"957100000091\"}]}")
|
||||
.post("/members?" + EnforcementFixtures.presignedQuery(administrator, "securityhub"))
|
||||
.then().statusCode(200).body("UnprocessedAccounts", hasSize(0));
|
||||
given().urlEncodingEnabled(false).get("/members?OnlyAssociated=false&" + EnforcementFixtures.presignedQuery(administrator, "securityhub"))
|
||||
.then().statusCode(200)
|
||||
.body("Members", hasSize(1))
|
||||
.body("Members[0].AccountId", equalTo("957100000091"));
|
||||
}
|
||||
|
||||
private Response createMembers(String administrator, String accountDetails) {
|
||||
return given().contentType("application/json").header("Authorization", auth(administrator))
|
||||
.body("{\"AccountDetails\":" + accountDetails + "}").post("/members");
|
||||
}
|
||||
|
||||
private Response deleteMembers(String administrator, String accountId) {
|
||||
return given().contentType("application/json").header("Authorization", auth(administrator))
|
||||
.body("{\"AccountIds\":[\"" + accountId + "\"]}").post("/members/delete");
|
||||
}
|
||||
|
||||
private Response disableAdministrator(String caller, String adminAccountId) {
|
||||
return given().contentType("application/json").header("Authorization", auth(caller))
|
||||
.body("{\"AdminAccountId\":\"" + adminAccountId + "\"}").post("/organization/admin/disable");
|
||||
}
|
||||
|
||||
private void enableSecurityHub(String accountId) {
|
||||
given().contentType("application/json").header("Authorization", auth(accountId))
|
||||
.body("{}").post("/accounts").then().statusCode(200);
|
||||
}
|
||||
|
||||
private void createOrganization(String managementAccountId, String... members) {
|
||||
organizationsService.createOrganization(managementAccountId, "ALL");
|
||||
for (String member : members) {
|
||||
joinOrganization(managementAccountId, member);
|
||||
}
|
||||
}
|
||||
|
||||
private void joinOrganization(String managementAccountId, String member) {
|
||||
Handshake handshake = organizationsService.inviteAccountToOrganization(
|
||||
managementAccountId, member, "ACCOUNT", null);
|
||||
organizationsService.acceptHandshake(member, handshake.getId());
|
||||
}
|
||||
|
||||
private void designateAdministrator(String managementAccountId, String administratorAccountId) {
|
||||
given().contentType("application/json").header("Authorization", auth(managementAccountId))
|
||||
.body("{\"AdminAccountId\":\"" + administratorAccountId + "\"}")
|
||||
.post("/organization/admin/enable").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String auth(String accountId) {
|
||||
return EnforcementFixtures.auth(accountId, "securityhub");
|
||||
}
|
||||
}
|
||||
@@ -328,6 +328,7 @@ services:
|
||||
- { path: services/securityadmin/SecurityAdminController.java, mode: rest }
|
||||
rename_actions:
|
||||
ListAdmin: ListOrganizationAdminAccounts
|
||||
CreateMembers: CreateMember
|
||||
- service: resource-groups
|
||||
doc: docs/services/resource-groups.md
|
||||
sources:
|
||||
@@ -410,12 +411,14 @@ services:
|
||||
doc: docs/services/securityhub.md
|
||||
sources:
|
||||
- { path: services/securityhub/SecurityHubController.java, mode: rest }
|
||||
- { path: services/securityadmin/SecurityAdminController.java, mode: rest }
|
||||
- { path: core/common/SharedTagsController.java, mode: rest }
|
||||
rename_actions:
|
||||
ListTags: ListTagsForResource
|
||||
TagResourcePost: TagResource
|
||||
exclude_actions:
|
||||
- ListTagsByQuery
|
||||
- ListAdmin
|
||||
- TagResourceByBody
|
||||
- TagResourcePut
|
||||
- UntagResourceByQuery
|
||||
|
||||
Reference in new issue
Block a user