mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -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
@@ -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) {
|
||||
}
|
||||
Reference in new issue
Block a user