mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(macie2): add member administration (#3488)
* feat(macie2): add member administration * fix(macie2): align member account fidelity * fix(macie2): align member pagination limit
This commit is contained in:
1 parent
8451571adb
commit
801edd863d
7 files changed
+445
-12
No files matched your search
+15
@@ -3,6 +3,7 @@ package com.floci.test;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.macie2.Macie2Client;
|
||||
import software.amazon.awssdk.services.macie2.model.CreateMemberResponse;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeFalse;
|
||||
@@ -11,6 +12,7 @@ import static org.junit.jupiter.api.Assumptions.assumeFalse;
|
||||
class MacieOrganizationAdministrationTest {
|
||||
private static final String MANAGEMENT_ACCOUNT = "222222222222";
|
||||
private static final String ADMIN_ACCOUNT = "111111111111";
|
||||
private static final String MEMBER_ACCOUNT = "333333333333";
|
||||
|
||||
@Test
|
||||
@DisplayName("uses AWS SDK models for delegated administration and organization configuration")
|
||||
@@ -33,6 +35,19 @@ class MacieOrganizationAdministrationTest {
|
||||
administrator.updateOrganizationConfiguration(request -> request.autoEnable(true));
|
||||
|
||||
assertThat(administrator.describeOrganizationConfiguration(request -> {}).autoEnable()).isTrue();
|
||||
|
||||
CreateMemberResponse member = administrator.createMember(request -> request
|
||||
.account(account -> account.accountId(MEMBER_ACCOUNT).email("member@example.com"))
|
||||
.tags(java.util.Map.of("team", "security")));
|
||||
assertThat(member.arn())
|
||||
.isEqualTo("arn:aws:macie2:us-east-1:" + ADMIN_ACCOUNT + ":member/" + MEMBER_ACCOUNT);
|
||||
assertThat(administrator.listMembers(request -> request.onlyAssociated("true")).members())
|
||||
.anySatisfy(account -> {
|
||||
assertThat(account.accountId()).isEqualTo(MEMBER_ACCOUNT);
|
||||
assertThat(account.administratorAccountId()).isEqualTo(ADMIN_ACCOUNT);
|
||||
assertThat(account.masterAccountId()).isEqualTo(ADMIN_ACCOUNT);
|
||||
assertThat(account.relationshipStatusAsString()).isEqualTo("Enabled");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ 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. |
|
||||
|
||||
@@ -2,8 +2,12 @@ package io.github.hectorvent.floci.services.macie2;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.macie2.model.MacieMember;
|
||||
import io.github.hectorvent.floci.services.macie2.model.MacieState;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
@@ -12,12 +16,16 @@ 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;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -35,8 +43,8 @@ public class MacieController {
|
||||
|
||||
public Response listAdminInternal(String region) {
|
||||
MacieState state = macieService.state(region);
|
||||
var response = objectMapper.createObjectNode();
|
||||
var accounts = response.putArray("adminAccounts");
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode accounts = response.putArray("adminAccounts");
|
||||
if (state.getAdminAccountId() != null) {
|
||||
accounts.addObject().put("accountId", state.getAdminAccountId()).put("status", "ENABLED");
|
||||
}
|
||||
@@ -45,16 +53,18 @@ public class MacieController {
|
||||
|
||||
@POST @Path("/admin")
|
||||
public Response enableOrganizationAdminAccount(@Context HttpHeaders headers, String body) {
|
||||
macieService.enableOrganizationAdminAccount(region(headers), readTree(body).path("adminAccountId").asText(null));
|
||||
macieService.enableOrganizationAdminAccount(
|
||||
region(headers), readTree(body).path("adminAccountId").asText(null));
|
||||
return empty();
|
||||
}
|
||||
|
||||
@GET @Path("/macie")
|
||||
public Response getMacieSession(@Context HttpHeaders headers) {
|
||||
macieService.requireSession(region(headers));
|
||||
var response = objectMapper.createObjectNode();
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("status", "ENABLED");
|
||||
response.put("serviceRole", "arn:aws:iam::" + regionResolver.getAccountId() + ":role/aws-service-role/macie.amazonaws.com/AWSServiceRoleForAmazonMacie");
|
||||
response.put("serviceRole", "arn:aws:iam::" + regionResolver.getAccountId()
|
||||
+ ":role/aws-service-role/macie.amazonaws.com/AWSServiceRoleForAmazonMacie");
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@@ -64,11 +74,55 @@ public class MacieController {
|
||||
return empty();
|
||||
}
|
||||
|
||||
@POST @Path("/members")
|
||||
public Response createMember(@Context HttpHeaders headers, String body) {
|
||||
JsonNode request = readTree(body);
|
||||
JsonNode account = request.get("account");
|
||||
if (account == null || !account.isObject()) {
|
||||
throw new AwsException(
|
||||
"ValidationException", "account is required.", 400);
|
||||
}
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
JsonNode tagsNode = request.get("tags");
|
||||
if (tagsNode != null && !tagsNode.isNull()) {
|
||||
if (!tagsNode.isObject()) {
|
||||
throw new AwsException(
|
||||
"ValidationException", "tags must be an object.", 400);
|
||||
}
|
||||
tagsNode.fields().forEachRemaining(entry -> tags.put(
|
||||
entry.getKey(), entry.getValue().isTextual() ? entry.getValue().asText() : null));
|
||||
}
|
||||
MacieMember member = macieService.createMember(
|
||||
region(headers),
|
||||
regionResolver.getAccountId(),
|
||||
account.path("accountId").asText(null),
|
||||
account.path("email").asText(null),
|
||||
tags);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("arn", member.arn());
|
||||
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) {
|
||||
MacieService.Page<MacieMember> page = macieService.listMembers(
|
||||
region(headers), regionResolver.getAccountId(), maxResults, nextToken, onlyAssociated);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("members", objectMapper.valueToTree(page.items()));
|
||||
if (page.nextToken() != null) {
|
||||
response.put("nextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@PATCH @Path("/admin/configuration")
|
||||
public Response updateOrganizationConfiguration(@Context HttpHeaders headers, String body) {
|
||||
JsonNode request = readTree(body);
|
||||
if (!request.has("autoEnable") || !request.get("autoEnable").isBoolean()) {
|
||||
throw new io.github.hectorvent.floci.core.common.AwsException("ValidationException", "autoEnable is required.", 400);
|
||||
throw new AwsException("ValidationException", "autoEnable is required.", 400);
|
||||
}
|
||||
macieService.updateOrganizationConfiguration(
|
||||
region(headers), regionResolver.getAccountId(), request.path("autoEnable").asBoolean());
|
||||
@@ -78,12 +132,18 @@ public class MacieController {
|
||||
@GET @Path("/admin/configuration")
|
||||
public Response describeOrganizationConfiguration(@Context HttpHeaders headers) {
|
||||
MacieState state = macieService.requireAdministratorSession(region(headers), regionResolver.getAccountId());
|
||||
var response = objectMapper.createObjectNode();
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("autoEnable", state.isAutoEnable());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private String region(HttpHeaders headers) { return regionResolver.resolveRegion(headers); }
|
||||
private Response empty() { return Response.ok(objectMapper.createObjectNode()).build(); }
|
||||
private JsonNode readTree(String body) { try { return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body); } catch (Exception e) { throw new WebApplicationException(JsonErrorResponseUtils.createSerializationErrorResponse()); } }
|
||||
private JsonNode readTree(String body) {
|
||||
try {
|
||||
return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
|
||||
} catch (Exception e) {
|
||||
throw new WebApplicationException(JsonErrorResponseUtils.createSerializationErrorResponse());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,24 +5,36 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.macie2.model.MacieMember;
|
||||
import io.github.hectorvent.floci.services.macie2.model.MacieState;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ApplicationScoped
|
||||
public class MacieService implements Resettable {
|
||||
private final AccountAwareStorageBackend<MacieState> states;
|
||||
private final AccountAwareStorageBackend<MacieMember> members;
|
||||
|
||||
@Inject
|
||||
public MacieService(StorageFactory storageFactory) {
|
||||
this(storageFactory.create("macie2", "macie2-state.json",
|
||||
new TypeReference<Map<String, MacieState>>() {}));
|
||||
new TypeReference<Map<String, MacieState>>() {}),
|
||||
storageFactory.create("macie2", "macie2-members.json",
|
||||
new TypeReference<Map<String, MacieMember>>() {}));
|
||||
}
|
||||
|
||||
MacieService(AccountAwareStorageBackend<MacieState> states) {
|
||||
MacieService(AccountAwareStorageBackend<MacieState> states,
|
||||
AccountAwareStorageBackend<MacieMember> members) {
|
||||
this.states = states;
|
||||
this.members = members;
|
||||
}
|
||||
|
||||
public MacieState state(String region) {
|
||||
@@ -82,17 +94,170 @@ public class MacieService implements Resettable {
|
||||
states.putForAccount(callerAccountId, region, state);
|
||||
}
|
||||
|
||||
public synchronized MacieMember createMember(
|
||||
String region, String callerAccountId, String memberAccountId, String email, Map<String, String> tags) {
|
||||
MacieState callerState = requireSessionForAccount(region, callerAccountId);
|
||||
requireAccountId(memberAccountId, "accountId");
|
||||
if (callerAccountId.equals(memberAccountId)) {
|
||||
throw validation("accountId must identify a different AWS account.");
|
||||
}
|
||||
requireEmail(email);
|
||||
Map<String, String> safeTags = validateTags(tags);
|
||||
|
||||
String key = memberKey(region, memberAccountId);
|
||||
if (members.getForAccount(callerAccountId, key).isPresent()) {
|
||||
throw conflict("The account is already associated with this Macie administrator account.");
|
||||
}
|
||||
boolean associatedWithDifferentAdministrator = members.scanAllAccounts().stream()
|
||||
.anyMatch(member -> memberAccountId.equals(member.accountId())
|
||||
&& !callerAccountId.equals(member.administratorAccountId()));
|
||||
if (associatedWithDifferentAdministrator) {
|
||||
throw conflict("The account is already associated with a different Macie administrator account.");
|
||||
}
|
||||
|
||||
boolean organizationAdministrator = callerAccountId.equals(callerState.getAdminAccountId());
|
||||
String now = Instant.now().toString();
|
||||
String arn = "arn:aws:macie2:" + region + ":" + callerAccountId + ":member/" + memberAccountId;
|
||||
MacieMember member = new MacieMember(
|
||||
memberAccountId,
|
||||
callerAccountId,
|
||||
callerAccountId,
|
||||
arn,
|
||||
organizationAdministrator ? null : email,
|
||||
null,
|
||||
organizationAdministrator ? "Enabled" : "Created",
|
||||
safeTags,
|
||||
now);
|
||||
members.putForAccount(callerAccountId, key, member);
|
||||
return member;
|
||||
}
|
||||
|
||||
public Page<MacieMember> listMembers(
|
||||
String region, String callerAccountId, String maxResultsValue, String nextToken, String onlyAssociated) {
|
||||
requireSessionForAccount(region, callerAccountId);
|
||||
int maxResults = parseMaxResults(maxResultsValue);
|
||||
Boolean associatedOnly = parseOnlyAssociated(onlyAssociated);
|
||||
List<MacieMember> items = new ArrayList<>(members.scanForAccount(
|
||||
callerAccountId, key -> key.startsWith(region + "::")));
|
||||
if (associatedOnly == null || associatedOnly) {
|
||||
items.removeIf(member -> !isCurrentMember(member.relationshipStatus()));
|
||||
}
|
||||
items.sort(Comparator.comparing(MacieMember::accountId));
|
||||
int offset = decodeOffset(nextToken, items.size());
|
||||
int end = Math.min(items.size(), offset + maxResults);
|
||||
return new Page<>(List.copyOf(items.subList(offset, end)),
|
||||
end < items.size() ? encodeOffset(end) : null);
|
||||
}
|
||||
|
||||
private MacieState requireSessionForAccount(String region, String accountId) {
|
||||
MacieState state = states.getForAccount(accountId, region).orElseGet(MacieState::new);
|
||||
if (!state.isEnabled()) {
|
||||
throw notFound("Macie is not enabled for this account.");
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
private static boolean isCurrentMember(String relationshipStatus) {
|
||||
return "Enabled".equals(relationshipStatus) || "Paused".equals(relationshipStatus);
|
||||
}
|
||||
|
||||
private static Boolean parseOnlyAssociated(String value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if ("true".equalsIgnoreCase(value)) {
|
||||
return true;
|
||||
}
|
||||
if ("false".equalsIgnoreCase(value)) {
|
||||
return false;
|
||||
}
|
||||
throw validation("onlyAssociated must be true or false.");
|
||||
}
|
||||
|
||||
private static int parseMaxResults(String value) {
|
||||
if (value == null) {
|
||||
return 25;
|
||||
}
|
||||
try {
|
||||
int parsed = Integer.parseInt(value);
|
||||
if (parsed < 1 || parsed > 25) {
|
||||
throw validation("maxResults must be between 1 and 25.");
|
||||
}
|
||||
return parsed;
|
||||
} catch (NumberFormatException e) {
|
||||
throw validation("maxResults must be between 1 and 25.");
|
||||
}
|
||||
}
|
||||
|
||||
private static int decodeOffset(String token, int size) {
|
||||
if (token == null) {
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
int offset = Integer.parseInt(new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8));
|
||||
if (offset < 0 || offset > size) {
|
||||
throw validation("nextToken is invalid.");
|
||||
}
|
||||
return offset;
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw validation("nextToken is invalid.");
|
||||
}
|
||||
}
|
||||
|
||||
private static String encodeOffset(int offset) {
|
||||
return Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(Integer.toString(offset).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String memberKey(String region, String accountId) {
|
||||
return region + "::" + accountId;
|
||||
}
|
||||
|
||||
private static void requireEmail(String email) {
|
||||
if (email == null || email.isBlank() || email.length() > 320 || email.indexOf('@') <= 0
|
||||
|| email.endsWith("@")) {
|
||||
throw validation("email must be a valid email address.");
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, String> validateTags(Map<String, String> tags) {
|
||||
if (tags == null) {
|
||||
return Map.of();
|
||||
}
|
||||
if (tags.size() > 50) {
|
||||
throw validation("A member can have at most 50 tags.");
|
||||
}
|
||||
for (Map.Entry<String, String> tag : tags.entrySet()) {
|
||||
if (tag.getKey() == null || tag.getKey().length() > 128
|
||||
|| tag.getValue() == null || tag.getValue().length() > 256) {
|
||||
throw validation("Tag keys can be at most 128 characters and values at most 256 characters.");
|
||||
}
|
||||
}
|
||||
return Map.copyOf(tags);
|
||||
}
|
||||
|
||||
public record Page<T>(List<T> items, String nextToken) {}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
states.clear();
|
||||
members.clear();
|
||||
}
|
||||
|
||||
private static void requireAccountId(String accountId) {
|
||||
requireAccountId(accountId, "adminAccountId");
|
||||
}
|
||||
|
||||
private static void requireAccountId(String accountId, String fieldName) {
|
||||
if (accountId == null || !accountId.matches("\\d{12}")) {
|
||||
throw new AwsException("ValidationException", "adminAccountId must be a 12 digit account ID.", 400);
|
||||
throw validation(fieldName + " must be a 12 digit account ID.");
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException validation(String message) {
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
}
|
||||
|
||||
private static AwsException conflict(String message) {
|
||||
return new AwsException("ConflictException", message, 409);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package io.github.hectorvent.floci.services.macie2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record MacieMember(
|
||||
String accountId,
|
||||
String administratorAccountId,
|
||||
String masterAccountId,
|
||||
String arn,
|
||||
String email,
|
||||
String invitedAt,
|
||||
String relationshipStatus,
|
||||
Map<String, String> tags,
|
||||
String updatedAt) {
|
||||
}
|
||||
+38
@@ -8,6 +8,7 @@ import org.junit.jupiter.api.Test;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
@QuarkusTest
|
||||
class MacieOrganizationIntegrationTest {
|
||||
@@ -51,6 +52,43 @@ class MacieOrganizationIntegrationTest {
|
||||
.get("/admin/configuration").then().statusCode(200).body("autoEnable", equalTo(true));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void delegatedAdministratorCreatesAndListsOrganizationMember() {
|
||||
given().contentType("application/json").header("Authorization", auth(MANAGEMENT_ACCOUNT, "macie2"))
|
||||
.body("{\"adminAccountId\":\"" + ADMIN_ACCOUNT + "\"}")
|
||||
.post("/admin").then().statusCode(200);
|
||||
|
||||
given().contentType("application/json").header("Authorization", auth(ADMIN_ACCOUNT, "macie2"))
|
||||
.body("{\"account\":{\"accountId\":\"444444444444\","
|
||||
+ "\"email\":\"member@example.com\"},\"tags\":{\"team\":\"security\"}}")
|
||||
.post("/members").then().statusCode(200)
|
||||
.body("arn", equalTo(
|
||||
"arn:aws:macie2:us-east-1:" + ADMIN_ACCOUNT + ":member/444444444444"));
|
||||
|
||||
given().header("Authorization", auth(ADMIN_ACCOUNT, "macie2"))
|
||||
.get("/members").then().statusCode(200)
|
||||
.body("members", hasSize(1))
|
||||
.body("members[0].accountId", equalTo("444444444444"))
|
||||
.body("members[0].administratorAccountId", equalTo(ADMIN_ACCOUNT))
|
||||
.body("members[0].masterAccountId", equalTo(ADMIN_ACCOUNT))
|
||||
.body("members[0].email", nullValue())
|
||||
.body("members[0].relationshipStatus", equalTo("Enabled"))
|
||||
.body("members[0].tags.team", equalTo("security"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listMembersRejectsInvalidOnlyAssociatedValue() {
|
||||
given().contentType("application/json").header("Authorization", auth(MANAGEMENT_ACCOUNT, "macie2"))
|
||||
.body("{\"adminAccountId\":\"" + ADMIN_ACCOUNT + "\"}")
|
||||
.post("/admin").then().statusCode(200);
|
||||
|
||||
given().header("Authorization", auth(ADMIN_ACCOUNT, "macie2"))
|
||||
.queryParam("onlyAssociated", "maybe")
|
||||
.get("/members").then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sharedAdminRouteKeepsGuardDutyBehavior() {
|
||||
given().header("Authorization", auth(GUARDDUTY_ACCOUNT, "guardduty"))
|
||||
|
||||
@@ -2,12 +2,18 @@ package io.github.hectorvent.floci.services.macie2;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.services.macie2.model.MacieMember;
|
||||
import io.github.hectorvent.floci.services.macie2.model.MacieState;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -20,7 +26,9 @@ class MacieServiceTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new MacieService(AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT));
|
||||
service = new MacieService(
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -60,6 +68,131 @@ class MacieServiceTest {
|
||||
assertEquals("ConflictException", error.getErrorCode());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void delegatedAdministratorCreatesEnabledMember() {
|
||||
service.enableOrganizationAdminAccount(REGION, ADMIN_ACCOUNT);
|
||||
|
||||
MacieMember member = service.createMember(
|
||||
REGION, ADMIN_ACCOUNT, "333333333333", "member@example.com", Map.of("team", "security"));
|
||||
|
||||
assertEquals("Enabled", member.relationshipStatus());
|
||||
assertEquals("arn:aws:macie2:us-east-1:111111111111:member/333333333333", member.arn());
|
||||
assertEquals("security", member.tags().get("team"));
|
||||
List<MacieMember> members = service.listMembers(REGION, ADMIN_ACCOUNT, null, null, null).items();
|
||||
assertEquals(1, members.size());
|
||||
assertEquals("333333333333", members.getFirst().accountId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void standaloneAdministratorCreatesAssociationExcludedFromDefaultMemberList() {
|
||||
service.enableMacie(REGION);
|
||||
|
||||
service.createMember(
|
||||
REGION, MANAGEMENT_ACCOUNT, "333333333333", "member@example.com", Map.of());
|
||||
|
||||
assertTrue(service.listMembers(REGION, MANAGEMENT_ACCOUNT, null, null, null).items().isEmpty());
|
||||
List<MacieMember> all = service.listMembers(
|
||||
REGION, MANAGEMENT_ACCOUNT, null, null, "false").items();
|
||||
assertEquals(1, all.size());
|
||||
assertEquals("Created", all.getFirst().relationshipStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateMemberAssociationIsConflict() {
|
||||
service.enableOrganizationAdminAccount(REGION, ADMIN_ACCOUNT);
|
||||
service.createMember(REGION, ADMIN_ACCOUNT, "333333333333", "member@example.com", Map.of());
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.createMember(
|
||||
REGION, ADMIN_ACCOUNT, "333333333333", "member@example.com", Map.of()));
|
||||
|
||||
assertEquals("ConflictException", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void memberCannotBeAssociatedWithDifferentAdministrator() {
|
||||
AccountAwareStorageBackend<MacieState> states = AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT);
|
||||
AccountAwareStorageBackend<MacieMember> members = AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT);
|
||||
MacieService localService = new MacieService(states, members);
|
||||
|
||||
localService.enableMacie(REGION);
|
||||
localService.createMember(
|
||||
REGION, MANAGEMENT_ACCOUNT, "333333333333", "member@example.com", Map.of());
|
||||
|
||||
MacieState secondAdmin = new MacieState();
|
||||
secondAdmin.setEnabled(true);
|
||||
secondAdmin.setAdminAccountId(ADMIN_ACCOUNT);
|
||||
states.putForAccount(ADMIN_ACCOUNT, REGION, secondAdmin);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> localService.createMember(
|
||||
REGION, ADMIN_ACCOUNT, "333333333333", "member@example.com", Map.of()));
|
||||
|
||||
assertEquals("ConflictException", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listMembersPaginatesAndValidatesNextToken() {
|
||||
service.enableOrganizationAdminAccount(REGION, ADMIN_ACCOUNT);
|
||||
service.createMember(REGION, ADMIN_ACCOUNT, "333333333331", "one@example.com", Map.of());
|
||||
service.createMember(REGION, ADMIN_ACCOUNT, "333333333332", "two@example.com", Map.of());
|
||||
service.createMember(REGION, ADMIN_ACCOUNT, "333333333333", "three@example.com", Map.of());
|
||||
|
||||
MacieService.Page<MacieMember> first = service.listMembers(
|
||||
REGION, ADMIN_ACCOUNT, "2", null, null);
|
||||
assertEquals(List.of("333333333331", "333333333332"),
|
||||
first.items().stream().map(MacieMember::accountId).toList());
|
||||
assertTrue(first.nextToken() != null && !first.nextToken().isBlank());
|
||||
|
||||
MacieService.Page<MacieMember> second = service.listMembers(
|
||||
REGION, ADMIN_ACCOUNT, "2", first.nextToken(), null);
|
||||
assertEquals(List.of("333333333333"), second.items().stream().map(MacieMember::accountId).toList());
|
||||
assertNull(second.nextToken());
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.listMembers(REGION, ADMIN_ACCOUNT, "2", "not-base64", null));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listMembersDefaultsAndCapsMaxResultsAtTwentyFive() {
|
||||
service.enableOrganizationAdminAccount(REGION, ADMIN_ACCOUNT);
|
||||
for (int i = 0; i < 26; i++) {
|
||||
String accountId = String.format("333333333%03d", i);
|
||||
service.createMember(REGION, ADMIN_ACCOUNT, accountId, "member" + i + "@example.com", Map.of());
|
||||
}
|
||||
|
||||
MacieService.Page<MacieMember> defaultPage = service.listMembers(
|
||||
REGION, ADMIN_ACCOUNT, null, null, null);
|
||||
assertEquals(25, defaultPage.items().size());
|
||||
assertTrue(defaultPage.nextToken() != null && !defaultPage.nextToken().isBlank());
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.listMembers(REGION, ADMIN_ACCOUNT, "26", null, null));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createMemberValidatesAccountEmailAndTagQuota() {
|
||||
service.enableOrganizationAdminAccount(REGION, ADMIN_ACCOUNT);
|
||||
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.createMember(REGION, ADMIN_ACCOUNT, "bad", "member@example.com", Map.of()))
|
||||
.getErrorCode());
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.createMember(REGION, ADMIN_ACCOUNT, "333333333333", "not-an-email", Map.of()))
|
||||
.getErrorCode());
|
||||
Map<String, String> tooManyTags = new LinkedHashMap<>();
|
||||
for (int i = 0; i < 51; i++) {
|
||||
tooManyTags.put("k" + i, "v");
|
||||
}
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.createMember(
|
||||
REGION, ADMIN_ACCOUNT, "333333333333", "member@example.com", tooManyTags))
|
||||
.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearRemovesMacieState() {
|
||||
service.enableOrganizationAdminAccount(REGION, ADMIN_ACCOUNT);
|
||||
|
||||
Reference in new issue
Block a user