mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(securityhub): add organization configuration operations (#3161)
* feat(securityhub): add organization configuration operations * fix(securityhub): complete organization configuration contracts * fix(securityhub): harden organization contracts * test(securityhub): log tolerated organization state * test(securityhub): clean organization fixture state * test(securityhub): isolate organization cleanup failures * fix(securityhub): return modeled invalid access error
This commit is contained in:
1 parent
fd3c4d9ab6
commit
9d4e71f8a2
21 files changed
+1765
-14
No files matched your search
@@ -730,6 +730,7 @@ public interface EmulatorConfig {
|
||||
IdentityStoreServiceConfig identitystore();
|
||||
BudgetsServiceConfig budgets();
|
||||
Inspector2ServiceConfig inspector2();
|
||||
SecurityHubServiceConfig securityhub();
|
||||
DetectiveServiceConfig detective();
|
||||
ServiceQuotasServiceConfig servicequotas();
|
||||
RamServiceConfig ram();
|
||||
@@ -790,6 +791,11 @@ public interface EmulatorConfig {
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface SecurityHubServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface DetectiveServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@@ -36,6 +36,7 @@ import io.github.hectorvent.floci.services.macie2.MacieController;
|
||||
import io.github.hectorvent.floci.services.account.AccountController;
|
||||
import io.github.hectorvent.floci.services.accessanalyzer.AccessAnalyzerController;
|
||||
import io.github.hectorvent.floci.services.inspector2.Inspector2Controller;
|
||||
import io.github.hectorvent.floci.services.securityhub.SecurityHubController;
|
||||
import io.github.hectorvent.floci.services.detective.DetectiveController;
|
||||
import io.github.hectorvent.floci.services.aps.ApsController;
|
||||
import io.github.hectorvent.floci.services.controlcatalog.ControlCatalogController;
|
||||
@@ -440,6 +441,9 @@ public class ResolvedServiceCatalog {
|
||||
descriptor("inspector2", "inspector2", config.services().inspector2().enabled(), true,
|
||||
"inspector2", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("inspector2"), Set.of(), Set.of(Inspector2Controller.class)),
|
||||
descriptor("securityhub", "securityhub", config.services().securityhub().enabled(), true,
|
||||
"securityhub", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("securityhub"), Set.of(), Set.of(SecurityHubController.class)),
|
||||
descriptor("autoscaling", "autoscaling", config.services().autoscaling().enabled(), true,
|
||||
"autoscaling", config.storage().mode(), 5000L, AwsNamespaces.AUTOSCALING, ServiceProtocol.QUERY,
|
||||
protocols(ServiceProtocol.QUERY),
|
||||
|
||||
+324
@@ -0,0 +1,324 @@
|
||||
package io.github.hectorvent.floci.services.securityhub;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.securityhub.model.SecurityHubAssociation;
|
||||
import io.github.hectorvent.floci.services.securityhub.model.SecurityHubState;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.PATCH;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
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.time.Instant;
|
||||
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class SecurityHubController {
|
||||
private final SecurityHubService securityHubService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public SecurityHubController(SecurityHubService securityHubService,
|
||||
RegionResolver regionResolver, ObjectMapper objectMapper) {
|
||||
this.securityHubService = securityHubService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/organization/admin")
|
||||
public Response listOrganizationAdminAccounts(@Context HttpHeaders headers,
|
||||
@QueryParam("Feature") String feature,
|
||||
@QueryParam("MaxResults") String maxResultsValue,
|
||||
@QueryParam("NextToken") String nextToken) {
|
||||
Integer maxResults = Pagination.parseMaxResults(maxResultsValue, "InvalidInputException");
|
||||
if (maxResults != null && maxResults > 10) {
|
||||
throw new AwsException("InvalidInputException", "MaxResults must be between 1 and 10.", 400);
|
||||
}
|
||||
if (nextToken != null && !nextToken.isBlank()) {
|
||||
throw new AwsException("InvalidInputException", "NextToken is invalid.", 400);
|
||||
}
|
||||
SecurityHubState state = securityHubService.organizationAdminState(region(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var accounts = response.putArray("AdminAccounts");
|
||||
String requestedFeature = securityHubService.normalizeFeature(feature);
|
||||
if (state.getAdminAccountId() != null && requestedFeature.equals(state.getAdminFeature())) {
|
||||
accounts.addObject()
|
||||
.put("AccountId", state.getAdminAccountId())
|
||||
.put("Status", "ENABLED");
|
||||
}
|
||||
response.put("Feature", requestedFeature);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/organization/admin/enable")
|
||||
public Response enableOrganizationAdminAccount(@Context HttpHeaders headers, String body) {
|
||||
JsonNode request = readTree(body);
|
||||
SecurityHubState state = securityHubService.enableOrganizationAdminAccount(
|
||||
region(headers), request.path("AdminAccountId").asText(null), request.path("Feature").asText(null));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("AdminAccountId", state.getAdminAccountId());
|
||||
response.put("Feature", state.getAdminFeature());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/accounts")
|
||||
public Response describeHub(@Context HttpHeaders headers) {
|
||||
String region = region(headers);
|
||||
securityHubService.requireEnabled(region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("HubArn", securityHubService.hubArn(region));
|
||||
SecurityHubState state = securityHubService.state(region);
|
||||
response.put("AutoEnableControls", state.isAutoEnableControls());
|
||||
response.put("ControlFindingGenerator", state.getControlFindingGenerator());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/accounts")
|
||||
public Response enableSecurityHub(@Context HttpHeaders headers, String body) {
|
||||
securityHubService.enableSecurityHub(region(headers), readTree(body));
|
||||
return empty();
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/accounts")
|
||||
public Response updateSecurityHubConfiguration(@Context HttpHeaders headers, String body) {
|
||||
securityHubService.updateSecurityHubConfiguration(region(headers), readTree(body));
|
||||
return empty();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/findingAggregator/list")
|
||||
public Response listFindingAggregators(@Context HttpHeaders headers,
|
||||
@QueryParam("MaxResults") String maxResultsValue,
|
||||
@QueryParam("NextToken") String nextToken) {
|
||||
Integer maxResults = Pagination.parseMaxResults(maxResultsValue, "InvalidInputException");
|
||||
if (maxResults != null && maxResults > 100) {
|
||||
throw new AwsException("InvalidInputException", "MaxResults must be between 1 and 100.", 400);
|
||||
}
|
||||
if (nextToken != null && !nextToken.isBlank()) {
|
||||
throw new AwsException("InvalidInputException", "NextToken is invalid.", 400);
|
||||
}
|
||||
SecurityHubState state = securityHubService.state(region(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var items = response.putArray("FindingAggregators");
|
||||
if (state.getAggregatorArn() != null) {
|
||||
items.addObject().put("FindingAggregatorArn", state.getAggregatorArn());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/findingAggregator/create")
|
||||
public Response createFindingAggregator(@Context HttpHeaders headers, String body) {
|
||||
String region = region(headers);
|
||||
return aggregator(securityHubService.createFindingAggregator(region, readTree(body)), region);
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/findingAggregator/get/{findingAggregatorArn: .+}")
|
||||
public Response getFindingAggregator(@Context HttpHeaders headers,
|
||||
@PathParam("findingAggregatorArn") String findingAggregatorArn) {
|
||||
String region = region(headers);
|
||||
return aggregator(securityHubService.getFindingAggregator(region, findingAggregatorArn), region);
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/findingAggregator/update")
|
||||
public Response updateFindingAggregator(@Context HttpHeaders headers, String body) {
|
||||
String region = region(headers);
|
||||
SecurityHubState state = securityHubService.updateFindingAggregator(region, readTree(body));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("FindingAggregatorArn", state.getAggregatorArn());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/organization/configuration")
|
||||
public Response describeOrganizationConfiguration(@Context HttpHeaders headers) {
|
||||
SecurityHubState state = securityHubService.organizationConfiguration(region(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("AutoEnable", state.isAutoEnable());
|
||||
response.put("AutoEnableStandards", state.getAutoEnableStandards());
|
||||
response.put("MemberAccountLimitReached", false);
|
||||
ObjectNode configuration = response.putObject("OrganizationConfiguration");
|
||||
configuration.put("ConfigurationType", state.getOrganizationConfigurationType());
|
||||
configuration.put("Status", state.getOrganizationConfigurationStatus());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/organization/configuration")
|
||||
public Response updateOrganizationConfiguration(@Context HttpHeaders headers, String body) {
|
||||
securityHubService.updateOrganizationConfiguration(region(headers), readTree(body));
|
||||
return empty();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/configurationPolicy/list")
|
||||
public Response listConfigurationPolicies(@Context HttpHeaders headers,
|
||||
@QueryParam("MaxResults") String maxResultsValue,
|
||||
@QueryParam("NextToken") String nextToken) {
|
||||
String region = region(headers);
|
||||
Integer maxResults = Pagination.parseMaxResults(maxResultsValue, "InvalidInputException");
|
||||
PaginatedResult<java.util.Map.Entry<String, JsonNode>> page =
|
||||
securityHubService.policyPage(region, maxResults, nextToken);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var items = response.putArray("ConfigurationPolicySummaries");
|
||||
page.items().forEach(entry -> items.add(policySummary(region, entry.getKey(), entry.getValue())));
|
||||
if (page.nextToken() != null) {
|
||||
response.put("NextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/configurationPolicy/create")
|
||||
public Response createConfigurationPolicy(@Context HttpHeaders headers, String body) {
|
||||
String region = region(headers);
|
||||
JsonNode request = readTree(body);
|
||||
String id = securityHubService.createConfigurationPolicy(region, request);
|
||||
return Response.ok(policyDocument(region, id, request)).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/configurationPolicy/get/{id: .+}")
|
||||
public Response getConfigurationPolicy(@Context HttpHeaders headers, @PathParam("id") String id) {
|
||||
String region = region(headers);
|
||||
return Response.ok(policyDocument(region, id, securityHubService.getConfigurationPolicy(region, id))).build();
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/configurationPolicy/{id: .+}")
|
||||
public Response updateConfigurationPolicy(@Context HttpHeaders headers, @PathParam("id") String id, String body) {
|
||||
String region = region(headers);
|
||||
return Response.ok(policyDocument(region, id,
|
||||
securityHubService.updateConfigurationPolicy(region, id, readTree(body)))).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/configurationPolicyAssociation/get")
|
||||
public Response getConfigurationPolicyAssociation(@Context HttpHeaders headers, String body) {
|
||||
String region = region(headers);
|
||||
JsonNode request = readTree(body);
|
||||
return Response.ok(association(securityHubService.association(region, request))).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/configurationPolicyAssociation/associate")
|
||||
public Response startConfigurationPolicyAssociation(@Context HttpHeaders headers, String body) {
|
||||
String region = region(headers);
|
||||
JsonNode request = readTree(body);
|
||||
return Response.ok(association(securityHubService.associate(region, request))).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/configurationPolicyAssociation/disassociate")
|
||||
public Response startConfigurationPolicyDisassociation(@Context HttpHeaders headers, String body) {
|
||||
securityHubService.disassociate(region(headers), readTree(body));
|
||||
return empty();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/configurationPolicyAssociation/list")
|
||||
public Response listConfigurationPolicyAssociations(@Context HttpHeaders headers, String body) {
|
||||
String region = region(headers);
|
||||
PaginatedResult<SecurityHubAssociation> page = securityHubService.associationPage(region, readTree(body));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var items = response.putArray("ConfigurationPolicyAssociationSummaries");
|
||||
page.items().forEach(entry -> items.add(association(entry)));
|
||||
if (page.nextToken() != null) {
|
||||
response.put("NextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response aggregator(SecurityHubState state, String region) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("FindingAggregatorArn", state.getAggregatorArn());
|
||||
response.put("FindingAggregationRegion", region);
|
||||
response.put("RegionLinkingMode", state.getRegionLinkingMode());
|
||||
if (state.getRegions() != null) {
|
||||
response.set("Regions", state.getRegions());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private ObjectNode policySummary(String region, String id, JsonNode policy) {
|
||||
int slash = id == null ? -1 : id.lastIndexOf('/');
|
||||
String policyId = slash >= 0 ? id.substring(slash + 1) : id;
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("Arn", securityHubService.policyArn(region, policyId));
|
||||
response.put("Id", policyId);
|
||||
response.put("Name", policy.path("Name").asText());
|
||||
if (policy.hasNonNull("Description")) {
|
||||
response.put("Description", policy.path("Description").asText());
|
||||
}
|
||||
JsonNode securityHub = policy.path("ConfigurationPolicy").path("SecurityHub");
|
||||
if (securityHub.path("ServiceEnabled").isBoolean()) {
|
||||
response.put("ServiceEnabled", securityHub.path("ServiceEnabled").asBoolean());
|
||||
}
|
||||
response.put("UpdatedAt", policy.path("UpdatedAt").asText(Instant.now().toString()));
|
||||
return response;
|
||||
}
|
||||
|
||||
private ObjectNode policyDocument(String region, String id, JsonNode policy) {
|
||||
ObjectNode response = policySummary(region, id, policy);
|
||||
if (policy.has("ConfigurationPolicy")) {
|
||||
response.set("ConfigurationPolicy", policy.get("ConfigurationPolicy"));
|
||||
}
|
||||
response.put("CreatedAt", policy.path("CreatedAt").asText(Instant.now().toString()));
|
||||
return response;
|
||||
}
|
||||
|
||||
private ObjectNode association(SecurityHubAssociation association) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("AssociationStatus", association.getStatus());
|
||||
if (association.getStatusMessage() != null) {
|
||||
response.put("AssociationStatusMessage", association.getStatusMessage());
|
||||
}
|
||||
response.put("AssociationType", "APPLIED");
|
||||
response.put("ConfigurationPolicyId", association.getPolicyId());
|
||||
response.put("TargetId", association.getTargetId());
|
||||
response.put("TargetType", association.getTargetType());
|
||||
response.put("UpdatedAt", association.getUpdatedAt());
|
||||
return response;
|
||||
}
|
||||
|
||||
private String region(HttpHeaders headers) {
|
||||
return regionResolver.resolveRegion(headers);
|
||||
}
|
||||
|
||||
private Response empty() {
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
private JsonNode readTree(String body) {
|
||||
try {
|
||||
return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
|
||||
} catch (Exception e) {
|
||||
throw new WebApplicationException(JsonErrorResponseUtils.createSerializationErrorResponse());
|
||||
}
|
||||
}
|
||||
}
|
||||
+782
@@ -0,0 +1,782 @@
|
||||
package io.github.hectorvent.floci.services.securityhub;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
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.organizations.OrganizationsService;
|
||||
import io.github.hectorvent.floci.services.securityhub.model.SecurityHubAssociation;
|
||||
import io.github.hectorvent.floci.services.securityhub.model.SecurityHubState;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@ApplicationScoped
|
||||
public class SecurityHubService implements Resettable {
|
||||
private static final String SELF_MANAGED = "SELF_MANAGED_SECURITY_HUB";
|
||||
private static final List<String> LINKING_MODES = List.of(
|
||||
"ALL_REGIONS", "ALL_REGIONS_EXCEPT_SPECIFIED", "SPECIFIED_REGIONS", "NO_REGIONS");
|
||||
|
||||
private final AccountAwareStorageBackend<SecurityHubState> states;
|
||||
private final RegionResolver regionResolver;
|
||||
private final OrganizationsService organizationsService;
|
||||
|
||||
@Inject
|
||||
public SecurityHubService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
OrganizationsService organizationsService) {
|
||||
this(storageFactory.create("securityhub", "securityhub-state.json",
|
||||
new TypeReference<Map<String, SecurityHubState>>() {}), regionResolver, organizationsService);
|
||||
}
|
||||
|
||||
SecurityHubService(AccountAwareStorageBackend<SecurityHubState> states, RegionResolver regionResolver,
|
||||
OrganizationsService organizationsService) {
|
||||
this.states = states;
|
||||
this.regionResolver = regionResolver;
|
||||
this.organizationsService = organizationsService;
|
||||
}
|
||||
|
||||
public SecurityHubState state(String region) {
|
||||
return states.get(region).orElseGet(SecurityHubState::new);
|
||||
}
|
||||
|
||||
public SecurityHubState organizationAdminState(String region) {
|
||||
String callerAccountId = regionResolver.getAccountId();
|
||||
String managementAccountId = organizationsService.findManagementAccountForResource(callerAccountId)
|
||||
.orElseThrow(() -> invalidAccess("Only the organization management account can perform this operation."));
|
||||
if (!callerAccountId.equals(managementAccountId)) {
|
||||
throw invalidAccess("Only the organization management account can perform this operation.");
|
||||
}
|
||||
return state(region);
|
||||
}
|
||||
|
||||
public synchronized SecurityHubState enableOrganizationAdminAccount(String region, String adminAccountId,
|
||||
String feature) {
|
||||
requireAccountId(adminAccountId, "AdminAccountId");
|
||||
String requestedFeature = normalizeFeature(feature);
|
||||
requireOrganizationManagementAccount(adminAccountId);
|
||||
SecurityHubState management = state(region);
|
||||
if (management.getAdminAccountId() != null && !management.getAdminAccountId().equals(adminAccountId)) {
|
||||
throw conflict("A different Security Hub administrator account is already configured.");
|
||||
}
|
||||
management.setAdminAccountId(adminAccountId);
|
||||
management.setAdminFeature(requestedFeature);
|
||||
save(region, management);
|
||||
|
||||
SecurityHubState delegated = states.getForAccount(adminAccountId, region).orElseGet(SecurityHubState::new);
|
||||
delegated.setAdminAccountId(adminAccountId);
|
||||
delegated.setAdminFeature(requestedFeature);
|
||||
if ("SecurityHub".equals(requestedFeature)) {
|
||||
delegated.setEnabled(true);
|
||||
}
|
||||
states.putForAccount(adminAccountId, region, delegated);
|
||||
return management;
|
||||
}
|
||||
|
||||
public synchronized void enableSecurityHub(String region, JsonNode request) {
|
||||
SecurityHubState state = state(region);
|
||||
if (state.isEnabled()) {
|
||||
throw conflict("Security Hub is already enabled for this account.");
|
||||
}
|
||||
String controlFindingGenerator = text(request, "ControlFindingGenerator");
|
||||
if (controlFindingGenerator != null
|
||||
&& !"SECURITY_CONTROL".equals(controlFindingGenerator)
|
||||
&& !"STANDARD_CONTROL".equals(controlFindingGenerator)) {
|
||||
throw invalid("ControlFindingGenerator must be SECURITY_CONTROL or STANDARD_CONTROL.");
|
||||
}
|
||||
validateTags(request == null ? null : request.get("Tags"));
|
||||
state.setEnabled(true);
|
||||
if (controlFindingGenerator != null) {
|
||||
state.setControlFindingGenerator(controlFindingGenerator);
|
||||
}
|
||||
state.setHubTags(readTags(request == null ? null : request.get("Tags")));
|
||||
save(region, state);
|
||||
}
|
||||
|
||||
public synchronized void updateSecurityHubConfiguration(String region, JsonNode request) {
|
||||
requireEnabled(region);
|
||||
SecurityHubState state = state(region);
|
||||
JsonNode autoEnableControls = request == null ? null : request.get("AutoEnableControls");
|
||||
if (autoEnableControls != null && !autoEnableControls.isBoolean()) {
|
||||
throw invalid("AutoEnableControls must be a boolean.");
|
||||
}
|
||||
String controlFindingGenerator = text(request, "ControlFindingGenerator");
|
||||
if (controlFindingGenerator != null
|
||||
&& !"SECURITY_CONTROL".equals(controlFindingGenerator)
|
||||
&& !"STANDARD_CONTROL".equals(controlFindingGenerator)) {
|
||||
throw invalid("ControlFindingGenerator must be SECURITY_CONTROL or STANDARD_CONTROL.");
|
||||
}
|
||||
if (autoEnableControls != null) {
|
||||
state.setAutoEnableControls(autoEnableControls.booleanValue());
|
||||
}
|
||||
if (controlFindingGenerator != null) {
|
||||
state.setControlFindingGenerator(controlFindingGenerator);
|
||||
}
|
||||
save(region, state);
|
||||
}
|
||||
|
||||
public void requireEnabled(String region) {
|
||||
if (!state(region).isEnabled()) {
|
||||
throw notFound("Security Hub is not enabled for this account.");
|
||||
}
|
||||
}
|
||||
|
||||
public String normalizeFeature(String feature) {
|
||||
String requestedFeature = feature == null || feature.isBlank() ? "SecurityHub" : feature;
|
||||
if (!"SecurityHub".equals(requestedFeature) && !"SecurityHubV2".equals(requestedFeature)) {
|
||||
throw invalid("Feature must be SecurityHub or SecurityHubV2.");
|
||||
}
|
||||
return requestedFeature;
|
||||
}
|
||||
|
||||
public synchronized SecurityHubState createFindingAggregator(String region, JsonNode request) {
|
||||
requireEnabled(region);
|
||||
SecurityHubState state = state(region);
|
||||
if (state.getAggregatorArn() != null) {
|
||||
throw new AwsException("LimitExceededException",
|
||||
"Only one finding aggregator can exist for an account.", 429);
|
||||
}
|
||||
String mode = requireLinkingMode(request);
|
||||
JsonNode regions = validateAggregatorRegions(mode, request.get("Regions"));
|
||||
state.setAggregatorArn("arn:aws:securityhub:" + region + ":" + regionResolver.getAccountId()
|
||||
+ ":finding-aggregator/" + UUID.randomUUID());
|
||||
state.setRegionLinkingMode(mode);
|
||||
state.setRegions(regions);
|
||||
save(region, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
public SecurityHubState getFindingAggregator(String region, String findingAggregatorArn) {
|
||||
SecurityHubState state = state(region);
|
||||
if (state.getAggregatorArn() == null || findingAggregatorArn == null
|
||||
|| !state.getAggregatorArn().equals(findingAggregatorArn)) {
|
||||
throw notFound("The finding aggregator was not found.");
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
public synchronized SecurityHubState updateFindingAggregator(String region, JsonNode request) {
|
||||
requireEnabled(region);
|
||||
SecurityHubState state = state(region);
|
||||
String arn = requireText(request, "FindingAggregatorArn", "InvalidInputException");
|
||||
if (state.getAggregatorArn() == null || !state.getAggregatorArn().equals(arn)) {
|
||||
throw notFound("The finding aggregator was not found.");
|
||||
}
|
||||
String mode = requireLinkingMode(request);
|
||||
JsonNode regions = validateAggregatorRegions(mode, request.get("Regions"));
|
||||
state.setRegionLinkingMode(mode);
|
||||
state.setRegions(regions);
|
||||
save(region, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
public synchronized void updateOrganizationConfiguration(String region, JsonNode request) {
|
||||
SecurityHubState state = requireAdministrator(region);
|
||||
JsonNode autoEnable = request.get("AutoEnable");
|
||||
if (autoEnable == null || !autoEnable.isBoolean()) {
|
||||
throw invalid("AutoEnable is required.");
|
||||
}
|
||||
String autoStandards = text(request, "AutoEnableStandards");
|
||||
if (autoStandards != null && !"DEFAULT".equals(autoStandards) && !"NONE".equals(autoStandards)) {
|
||||
throw invalid("AutoEnableStandards must be DEFAULT or NONE.");
|
||||
}
|
||||
JsonNode organizationConfiguration = request.get("OrganizationConfiguration");
|
||||
String type = organizationConfiguration != null && organizationConfiguration.isObject()
|
||||
? text(organizationConfiguration, "ConfigurationType") : null;
|
||||
if (type != null && !"CENTRAL".equals(type) && !"LOCAL".equals(type)) {
|
||||
throw invalid("ConfigurationType must be CENTRAL or LOCAL.");
|
||||
}
|
||||
String desiredType = type == null ? state.getOrganizationConfigurationType() : type;
|
||||
if (desiredType == null) {
|
||||
desiredType = "LOCAL";
|
||||
}
|
||||
state.setOrganizationConfigurationType(desiredType);
|
||||
if ("CENTRAL".equals(desiredType)) {
|
||||
state.setAutoEnable(false);
|
||||
state.setAutoEnableStandards("NONE");
|
||||
state.setOrganizationConfigurationStatus("PENDING");
|
||||
state.setOrganizationConfigurationPendingPollsRemaining(1);
|
||||
} else {
|
||||
state.setAutoEnable(autoEnable.booleanValue());
|
||||
if (autoStandards != null) {
|
||||
state.setAutoEnableStandards(autoStandards);
|
||||
}
|
||||
state.setOrganizationConfigurationStatus("ENABLED");
|
||||
state.setOrganizationConfigurationPendingPollsRemaining(0);
|
||||
}
|
||||
save(region, state);
|
||||
}
|
||||
|
||||
public synchronized SecurityHubState organizationConfiguration(String region) {
|
||||
SecurityHubState state = requireAdministrator(region);
|
||||
if ("PENDING".equals(state.getOrganizationConfigurationStatus())
|
||||
&& state.getOrganizationConfigurationPendingPollsRemaining() > 0) {
|
||||
SecurityHubState response = copyConfigurationState(state);
|
||||
state.setOrganizationConfigurationPendingPollsRemaining(
|
||||
state.getOrganizationConfigurationPendingPollsRemaining() - 1);
|
||||
save(region, state);
|
||||
return response;
|
||||
}
|
||||
if ("PENDING".equals(state.getOrganizationConfigurationStatus())) {
|
||||
state.setOrganizationConfigurationStatus("ENABLED");
|
||||
save(region, state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
public synchronized String createConfigurationPolicy(String region, JsonNode request) {
|
||||
SecurityHubState state = requireAdministrator(region);
|
||||
String name = requireText(request, "Name", "InvalidInputException");
|
||||
validatePolicyName(name);
|
||||
boolean duplicate = state.getPolicies().values().stream()
|
||||
.anyMatch(policy -> name.equals(text(policy, "Name")));
|
||||
if (duplicate) {
|
||||
throw conflict("A configuration policy with the same name already exists.");
|
||||
}
|
||||
validateConfigurationPolicy(request.get("ConfigurationPolicy"));
|
||||
validateTags(request.get("Tags"));
|
||||
String id = UUID.randomUUID().toString();
|
||||
ObjectNode stored = (ObjectNode) request.deepCopy();
|
||||
String now = java.time.Instant.now().toString();
|
||||
stored.put("CreatedAt", now);
|
||||
stored.put("UpdatedAt", now);
|
||||
state.getPolicies().put(id, stored);
|
||||
save(region, state);
|
||||
return id;
|
||||
}
|
||||
|
||||
public JsonNode getConfigurationPolicy(String region, String identifier) {
|
||||
String id = normalizePolicyId(identifier);
|
||||
JsonNode policy = requireAdministrator(region).getPolicies().get(id);
|
||||
if (policy == null) {
|
||||
throw notFound("The configuration policy was not found.");
|
||||
}
|
||||
return policy;
|
||||
}
|
||||
|
||||
public synchronized JsonNode updateConfigurationPolicy(String region, String identifier, JsonNode request) {
|
||||
String id = normalizePolicyId(identifier);
|
||||
SecurityHubState state = requireAdministrator(region);
|
||||
JsonNode current = state.getPolicies().get(id);
|
||||
if (current == null) {
|
||||
throw notFound("The configuration policy was not found.");
|
||||
}
|
||||
String newName = text(request, "Name");
|
||||
if (newName != null) {
|
||||
validatePolicyName(newName);
|
||||
boolean duplicate = state.getPolicies().entrySet().stream()
|
||||
.anyMatch(entry -> !entry.getKey().equals(id)
|
||||
&& newName.equals(text(entry.getValue(), "Name")));
|
||||
if (duplicate) {
|
||||
throw conflict("A configuration policy with the same name already exists.");
|
||||
}
|
||||
}
|
||||
ObjectNode merged = (ObjectNode) current.deepCopy();
|
||||
if (newName != null) {
|
||||
merged.put("Name", newName);
|
||||
}
|
||||
if (request.has("Description")) {
|
||||
merged.set("Description", request.get("Description"));
|
||||
}
|
||||
if (request.has("ConfigurationPolicy")) {
|
||||
validateConfigurationPolicy(request.get("ConfigurationPolicy"));
|
||||
merged.set("ConfigurationPolicy", request.get("ConfigurationPolicy").deepCopy());
|
||||
}
|
||||
merged.put("UpdatedAt", java.time.Instant.now().toString());
|
||||
state.getPolicies().put(id, merged);
|
||||
save(region, state);
|
||||
return merged;
|
||||
}
|
||||
|
||||
public synchronized SecurityHubAssociation associate(String region, JsonNode request) {
|
||||
SecurityHubState state = requireAdministrator(region);
|
||||
TargetRef target = organizationTarget(request);
|
||||
String policyIdentifier = requireText(request, "ConfigurationPolicyIdentifier", "InvalidInputException");
|
||||
String policyId = normalizePolicyId(policyIdentifier);
|
||||
if (!SELF_MANAGED.equals(policyId) && !state.getPolicies().containsKey(policyId)) {
|
||||
throw notFound("The configuration policy was not found.");
|
||||
}
|
||||
SecurityHubAssociation existing = state.getAssociations().get(target.id());
|
||||
if (existing != null && !existing.isDisassociating()
|
||||
&& policyId.equals(existing.getPolicyId())) {
|
||||
throw conflict("The target is already associated with the specified configuration policy.");
|
||||
}
|
||||
SecurityHubAssociation association = new SecurityHubAssociation(
|
||||
target.id(), target.type(), policyId, "PENDING", 1);
|
||||
state.getAssociations().put(target.id(), association);
|
||||
save(region, state);
|
||||
return association.copy();
|
||||
}
|
||||
|
||||
public synchronized SecurityHubAssociation association(String region, JsonNode request) {
|
||||
SecurityHubState state = requireAdministrator(region);
|
||||
TargetRef target = organizationTarget(request);
|
||||
SecurityHubAssociation association = state.getAssociations().get(target.id());
|
||||
if (association == null) {
|
||||
throw notFound("The configuration policy association was not found.");
|
||||
}
|
||||
if ("PENDING".equals(association.getStatus()) && association.getPendingPollsRemaining() > 0) {
|
||||
SecurityHubAssociation response = association.copy();
|
||||
association.setPendingPollsRemaining(association.getPendingPollsRemaining() - 1);
|
||||
save(region, state);
|
||||
return response;
|
||||
}
|
||||
if ("PENDING".equals(association.getStatus())) {
|
||||
if (association.isDisassociating()) {
|
||||
state.getAssociations().remove(target.id());
|
||||
save(region, state);
|
||||
throw notFound("The configuration policy association was not found.");
|
||||
}
|
||||
association.setStatus("SUCCESS");
|
||||
association.setUpdatedAt(java.time.Instant.now().toString());
|
||||
applyPolicyToAccountTarget(region, state, association);
|
||||
save(region, state);
|
||||
}
|
||||
return association.copy();
|
||||
}
|
||||
|
||||
public synchronized void disassociate(String region, JsonNode request) {
|
||||
SecurityHubState state = requireAdministrator(region);
|
||||
TargetRef target = organizationTarget(request);
|
||||
String policyIdentifier = requireText(request, "ConfigurationPolicyIdentifier", "InvalidInputException");
|
||||
String requestedPolicyId = normalizePolicyId(policyIdentifier);
|
||||
SecurityHubAssociation association = state.getAssociations().get(target.id());
|
||||
if (association == null || !requestedPolicyId.equals(association.getPolicyId())) {
|
||||
throw notFound("The configuration policy association was not found.");
|
||||
}
|
||||
if (association.isDisassociating()) {
|
||||
throw conflict("The configuration policy association is already being removed.");
|
||||
}
|
||||
association.setStatus("PENDING");
|
||||
association.setUpdatedAt(java.time.Instant.now().toString());
|
||||
association.setPendingPollsRemaining(1);
|
||||
association.setDisassociating(true);
|
||||
save(region, state);
|
||||
}
|
||||
|
||||
private void applyPolicyToAccountTarget(String region, SecurityHubState administrator,
|
||||
SecurityHubAssociation association) {
|
||||
if (!"ACCOUNT".equals(association.getTargetType()) || SELF_MANAGED.equals(association.getPolicyId())) {
|
||||
return;
|
||||
}
|
||||
JsonNode policy = administrator.getPolicies().get(association.getPolicyId());
|
||||
JsonNode securityHub = policy == null ? null : policy.path("ConfigurationPolicy").path("SecurityHub");
|
||||
if (securityHub == null || !securityHub.isObject() || !securityHub.path("ServiceEnabled").isBoolean()) {
|
||||
return;
|
||||
}
|
||||
SecurityHubState target = states.getForAccount(association.getTargetId(), region)
|
||||
.orElseGet(SecurityHubState::new);
|
||||
target.setEnabled(securityHub.path("ServiceEnabled").asBoolean());
|
||||
states.putForAccount(association.getTargetId(), region, target);
|
||||
}
|
||||
|
||||
public List<SecurityHubAssociation> associations(String region) {
|
||||
return requireAdministrator(region).getAssociations().values().stream()
|
||||
.map(SecurityHubAssociation::copy)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public PaginatedResult<SecurityHubAssociation> associationPage(String region, JsonNode request) {
|
||||
JsonNode filters = request == null ? null : request.get("Filters");
|
||||
if (filters != null && !filters.isObject()) {
|
||||
throw invalid("Filters must be an object.");
|
||||
}
|
||||
String policyId = filters == null ? null : text(filters, "ConfigurationPolicyId");
|
||||
String associationType = filters == null ? null : text(filters, "AssociationType");
|
||||
String associationStatus = filters == null ? null : text(filters, "AssociationStatus");
|
||||
if (associationType != null && !"APPLIED".equals(associationType) && !"INHERITED".equals(associationType)) {
|
||||
throw invalid("AssociationType must be APPLIED or INHERITED.");
|
||||
}
|
||||
if (associationStatus != null && !List.of("PENDING", "SUCCESS", "FAILED").contains(associationStatus)) {
|
||||
throw invalid("AssociationStatus must be PENDING, SUCCESS, or FAILED.");
|
||||
}
|
||||
Integer maxResults = integer(request, "MaxResults");
|
||||
String nextToken = text(request, "NextToken");
|
||||
List<SecurityHubAssociation> filtered = associations(region).stream()
|
||||
.filter(item -> policyId == null || normalizePolicyId(policyId).equals(item.getPolicyId()))
|
||||
.filter(item -> associationType == null || "APPLIED".equals(associationType))
|
||||
.filter(item -> associationStatus == null || associationStatus.equals(item.getStatus()))
|
||||
.toList();
|
||||
return Pagination.paginate(filtered,
|
||||
item -> item.getTargetType() + "\u0000" + item.getTargetId(),
|
||||
maxResults, nextToken, 100, 100, "InvalidInputException");
|
||||
}
|
||||
|
||||
public List<Map.Entry<String, JsonNode>> policies(String region) {
|
||||
return List.copyOf(requireAdministrator(region).getPolicies().entrySet());
|
||||
}
|
||||
|
||||
public PaginatedResult<Map.Entry<String, JsonNode>> policyPage(String region, Integer maxResults,
|
||||
String nextToken) {
|
||||
return Pagination.paginate(policies(region), Map.Entry::getKey,
|
||||
maxResults, nextToken, 100, 100, "InvalidInputException");
|
||||
}
|
||||
|
||||
public Map<String, String> tagsForResource(String region, String arn) {
|
||||
SecurityHubState state = state(region);
|
||||
validateResourceArn(region, arn);
|
||||
if (arn.equals(hubArn(region))) {
|
||||
if (!state.isEnabled()) {
|
||||
throw notFound("The specified Security Hub resource was not found.");
|
||||
}
|
||||
return Map.copyOf(state.getHubTags());
|
||||
}
|
||||
JsonNode resource = taggedPolicy(state, region, arn);
|
||||
JsonNode tags = resource.get("Tags");
|
||||
if (tags == null || !tags.isObject()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
tags.fields().forEachRemaining(entry -> {
|
||||
if (entry.getValue().isTextual()) {
|
||||
result.put(entry.getKey(), entry.getValue().textValue());
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
public synchronized void tagResource(String region, String arn, Map<String, String> tags) {
|
||||
SecurityHubState state = state(region);
|
||||
validateResourceArn(region, arn);
|
||||
if (arn.equals(hubArn(region))) {
|
||||
if (!state.isEnabled()) {
|
||||
throw notFound("The specified Security Hub resource was not found.");
|
||||
}
|
||||
Map<String, String> merged = new LinkedHashMap<>(state.getHubTags());
|
||||
merged.putAll(tags);
|
||||
validateTags(merged);
|
||||
state.setHubTags(merged);
|
||||
save(region, state);
|
||||
return;
|
||||
}
|
||||
ObjectNode resource = policyResource(state, region, arn);
|
||||
ObjectNode current = resource.withObject("Tags");
|
||||
tags.forEach(current::put);
|
||||
validateTags(current);
|
||||
save(region, state);
|
||||
}
|
||||
|
||||
public synchronized void untagResource(String region, String arn, List<String> tagKeys) {
|
||||
SecurityHubState state = state(region);
|
||||
validateResourceArn(region, arn);
|
||||
if (arn.equals(hubArn(region))) {
|
||||
if (!state.isEnabled()) {
|
||||
throw notFound("The specified Security Hub resource was not found.");
|
||||
}
|
||||
Map<String, String> updated = new LinkedHashMap<>(state.getHubTags());
|
||||
tagKeys.forEach(updated::remove);
|
||||
state.setHubTags(updated);
|
||||
save(region, state);
|
||||
return;
|
||||
}
|
||||
ObjectNode resource = policyResource(state, region, arn);
|
||||
ObjectNode tags = resource.withObject("Tags");
|
||||
tagKeys.forEach(tags::remove);
|
||||
save(region, state);
|
||||
}
|
||||
|
||||
private JsonNode taggedPolicy(SecurityHubState state, String region, String arn) {
|
||||
validateResourceArn(region, arn);
|
||||
if (arn.equals(state.getAggregatorArn())) {
|
||||
throw notFound("The specified Security Hub resource was not found.");
|
||||
}
|
||||
String id = normalizePolicyId(arn);
|
||||
JsonNode policy = state.getPolicies().get(id);
|
||||
if (policy == null) {
|
||||
throw notFound("The specified Security Hub resource was not found.");
|
||||
}
|
||||
return policy;
|
||||
}
|
||||
|
||||
private void validateResourceArn(String region, String arn) {
|
||||
if (arn == null || !arn.startsWith("arn:aws:securityhub:" + region + ":" + regionResolver.getAccountId() + ":")) {
|
||||
throw notFound("The specified Security Hub resource was not found.");
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode policyResource(SecurityHubState state, String region, String arn) {
|
||||
JsonNode resource = taggedPolicy(state, region, arn);
|
||||
if (!(resource instanceof ObjectNode object)) {
|
||||
throw notFound("The specified Security Hub resource does not support mutable tags in this emulator.");
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
public String hubArn(String region) {
|
||||
return "arn:aws:securityhub:" + region + ":" + regionResolver.getAccountId() + ":hub/default";
|
||||
}
|
||||
|
||||
public String policyArn(String region, String id) {
|
||||
return "arn:aws:securityhub:" + region + ":" + regionResolver.getAccountId()
|
||||
+ ":configuration-policy/" + id;
|
||||
}
|
||||
|
||||
private static SecurityHubState copyConfigurationState(SecurityHubState source) {
|
||||
SecurityHubState copy = new SecurityHubState();
|
||||
copy.setAdminAccountId(source.getAdminAccountId());
|
||||
copy.setAdminFeature(source.getAdminFeature());
|
||||
copy.setEnabled(source.isEnabled());
|
||||
copy.setAutoEnable(source.isAutoEnable());
|
||||
copy.setAutoEnableStandards(source.getAutoEnableStandards());
|
||||
copy.setOrganizationConfigurationType(source.getOrganizationConfigurationType());
|
||||
copy.setOrganizationConfigurationStatus(source.getOrganizationConfigurationStatus());
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static JsonNode validateAggregatorRegions(String mode, JsonNode regions) {
|
||||
if (regions != null && !regions.isArray()) {
|
||||
throw invalid("Regions must be an array.");
|
||||
}
|
||||
if ("SPECIFIED_REGIONS".equals(mode) && (regions == null || regions.isEmpty())) {
|
||||
throw invalid("Regions is required when RegionLinkingMode is SPECIFIED_REGIONS.");
|
||||
}
|
||||
if (("NO_REGIONS".equals(mode) || "ALL_REGIONS".equals(mode))
|
||||
&& regions != null && !regions.isEmpty()) {
|
||||
throw invalid("Regions must be empty for the selected RegionLinkingMode.");
|
||||
}
|
||||
if (regions != null) {
|
||||
for (JsonNode candidate : regions) {
|
||||
if (!candidate.isTextual() || candidate.textValue().isBlank()) {
|
||||
throw invalid("Regions must contain non-blank Region identifiers.");
|
||||
}
|
||||
}
|
||||
}
|
||||
return regions == null ? null : regions.deepCopy();
|
||||
}
|
||||
|
||||
private static String requireLinkingMode(JsonNode request) {
|
||||
String mode = requireText(request, "RegionLinkingMode", "InvalidInputException");
|
||||
if (!LINKING_MODES.contains(mode)) {
|
||||
throw invalid("RegionLinkingMode is invalid.");
|
||||
}
|
||||
return mode;
|
||||
}
|
||||
|
||||
private static void validateTags(JsonNode tags) {
|
||||
if (tags == null || tags.isNull()) {
|
||||
return;
|
||||
}
|
||||
if (!tags.isObject() || tags.size() > 50) {
|
||||
throw invalid("Tags must be an object with at most 50 entries.");
|
||||
}
|
||||
tags.fields().forEachRemaining(entry -> validateTag(entry.getKey(), entry.getValue()));
|
||||
}
|
||||
|
||||
private static void validateTags(Map<String, String> tags) {
|
||||
if (tags.size() > 50) {
|
||||
throw invalid("Tags must contain at most 50 entries.");
|
||||
}
|
||||
tags.forEach((key, value) -> validateTag(
|
||||
key, value == null ? null : new com.fasterxml.jackson.databind.node.TextNode(value)));
|
||||
}
|
||||
|
||||
private static void validateTag(String key, JsonNode value) {
|
||||
if (key == null || key.isBlank() || key.length() > 128 || key.startsWith("aws:")
|
||||
|| !key.matches("[a-zA-Z+\\-=._:/]+")
|
||||
|| value == null || !value.isTextual() || value.textValue().length() > 256) {
|
||||
throw invalid("Tags contain an invalid key or value.");
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, String> readTags(JsonNode tags) {
|
||||
if (tags == null || tags.isNull()) {
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
validateTags(tags);
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
tags.fields().forEachRemaining(entry -> result.put(entry.getKey(), entry.getValue().textValue()));
|
||||
return result;
|
||||
}
|
||||
|
||||
private SecurityHubState requireAdministrator(String region) {
|
||||
requireEnabled(region);
|
||||
SecurityHubState state = state(region);
|
||||
if (state.getAdminAccountId() == null || !regionResolver.getAccountId().equals(state.getAdminAccountId())) {
|
||||
throw new AwsException("InvalidAccessException",
|
||||
"Only the delegated Security Hub administrator account can manage central configuration.", 401);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
private void save(String region, SecurityHubState state) {
|
||||
states.put(region, state);
|
||||
}
|
||||
|
||||
private static String normalizePolicyId(String identifier) {
|
||||
if (identifier == null || identifier.isBlank()) {
|
||||
throw invalid("Identifier is required.");
|
||||
}
|
||||
if (SELF_MANAGED.equals(identifier)) {
|
||||
return SELF_MANAGED;
|
||||
}
|
||||
int slash = identifier.lastIndexOf('/');
|
||||
return slash >= 0 ? identifier.substring(slash + 1) : identifier;
|
||||
}
|
||||
|
||||
private String requireCallerManagementAccount() {
|
||||
String callerAccountId = regionResolver.getAccountId();
|
||||
String managementAccountId = organizationsService.findManagementAccountForResource(callerAccountId)
|
||||
.orElseThrow(() -> new AwsException("AccessDeniedException",
|
||||
"Only the organization management account can perform this operation.", 403));
|
||||
if (!callerAccountId.equals(managementAccountId)) {
|
||||
throw new AwsException("AccessDeniedException",
|
||||
"Only the organization management account can perform this operation.", 403);
|
||||
}
|
||||
return managementAccountId;
|
||||
}
|
||||
|
||||
private void requireOrganizationManagementAccount(String targetAccountId) {
|
||||
String managementAccountId = requireCallerManagementAccount();
|
||||
String targetManagementAccountId = organizationsService.findManagementAccountForResource(targetAccountId)
|
||||
.orElseThrow(() -> invalid("AdminAccountId must belong to the caller's AWS organization."));
|
||||
if (!managementAccountId.equals(targetManagementAccountId)) {
|
||||
throw invalid("AdminAccountId must belong to the caller's AWS organization.");
|
||||
}
|
||||
}
|
||||
|
||||
private TargetRef organizationTarget(JsonNode input) {
|
||||
TargetRef target = target(input);
|
||||
String callerAccountId = regionResolver.getAccountId();
|
||||
String managementAccountId = organizationsService.findManagementAccountForResource(callerAccountId)
|
||||
.orElseThrow(() -> new AwsException("InvalidAccessException",
|
||||
"The delegated administrator must belong to an AWS organization.", 401));
|
||||
String targetManagementAccountId = organizationsService.findManagementAccountForResource(target.id())
|
||||
.orElseThrow(() -> notFound("The specified organization target was not found."));
|
||||
if (!managementAccountId.equals(targetManagementAccountId)) {
|
||||
throw notFound("The specified organization target was not found.");
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
private static void validatePolicyName(String name) {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw invalid("Name must contain a non-whitespace character.");
|
||||
}
|
||||
if (name.length() > 128) {
|
||||
throw invalid("Name exceeds the maximum length.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateConfigurationPolicy(JsonNode configurationPolicy) {
|
||||
if (configurationPolicy == null || !configurationPolicy.isObject()
|
||||
|| configurationPolicy.size() != 1 || !configurationPolicy.has("SecurityHub")) {
|
||||
throw invalid("ConfigurationPolicy must contain exactly one SecurityHub policy.");
|
||||
}
|
||||
JsonNode securityHub = configurationPolicy.get("SecurityHub");
|
||||
if (securityHub == null || !securityHub.isObject()) {
|
||||
throw invalid("ConfigurationPolicy.SecurityHub must be an object.");
|
||||
}
|
||||
JsonNode serviceEnabled = securityHub.get("ServiceEnabled");
|
||||
if (serviceEnabled != null && !serviceEnabled.isBoolean()) {
|
||||
throw invalid("ConfigurationPolicy.SecurityHub.ServiceEnabled must be a boolean.");
|
||||
}
|
||||
JsonNode standards = securityHub.get("EnabledStandardIdentifiers");
|
||||
if (standards != null) {
|
||||
if (!standards.isArray()) {
|
||||
throw invalid("EnabledStandardIdentifiers must be an array.");
|
||||
}
|
||||
for (JsonNode standard : standards) {
|
||||
if (!standard.isTextual() || standard.textValue().isBlank()) {
|
||||
throw invalid("EnabledStandardIdentifiers must contain non-blank strings.");
|
||||
}
|
||||
}
|
||||
}
|
||||
JsonNode controls = securityHub.get("SecurityControlsConfiguration");
|
||||
if (controls != null && !controls.isObject()) {
|
||||
throw invalid("SecurityControlsConfiguration must be an object.");
|
||||
}
|
||||
}
|
||||
|
||||
private static TargetRef target(JsonNode input) {
|
||||
JsonNode target = input == null ? null : input.get("Target");
|
||||
if (target == null || !target.isObject()) {
|
||||
throw invalid("Target is required.");
|
||||
}
|
||||
TargetRef found = null;
|
||||
for (Map.Entry<String, String> candidate : Map.of(
|
||||
"AccountId", "ACCOUNT", "OrganizationalUnitId", "ORGANIZATIONAL_UNIT", "RootId", "ROOT").entrySet()) {
|
||||
String value = text(target, candidate.getKey());
|
||||
if (value != null) {
|
||||
if (found != null) {
|
||||
throw invalid("Target must contain exactly one identifier.");
|
||||
}
|
||||
found = new TargetRef(value, candidate.getValue());
|
||||
}
|
||||
}
|
||||
if (found == null) {
|
||||
throw invalid("Target identifier is required.");
|
||||
}
|
||||
if ("ACCOUNT".equals(found.type()) && !found.id().matches("\\d{12}")) {
|
||||
throw invalid("AccountId must be a 12 digit account ID.");
|
||||
}
|
||||
if ("ORGANIZATIONAL_UNIT".equals(found.type()) && !found.id().matches("ou-[a-z0-9]{4,32}-[a-z0-9]{8,32}")) {
|
||||
throw invalid("OrganizationalUnitId is invalid.");
|
||||
}
|
||||
if ("ROOT".equals(found.type()) && !found.id().matches("r-[a-z0-9]{4,32}")) {
|
||||
throw invalid("RootId is invalid.");
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
private static void requireAccountId(String value, String field) {
|
||||
if (value == null || !value.matches("\\d{12}")) {
|
||||
throw invalid(field + " must be a 12 digit account ID.");
|
||||
}
|
||||
}
|
||||
|
||||
private static String requireText(JsonNode input, String field, String errorCode) {
|
||||
String value = text(input, field);
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new AwsException(errorCode, field + " is required.", 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String text(JsonNode input, String field) {
|
||||
JsonNode node = input == null ? null : input.get(field);
|
||||
return node != null && node.isTextual() ? node.textValue() : null;
|
||||
}
|
||||
|
||||
private static Integer integer(JsonNode input, String field) {
|
||||
JsonNode node = input == null ? null : input.get(field);
|
||||
if (node == null || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isIntegralNumber() || !node.canConvertToInt()) {
|
||||
throw invalid(field + " must be an integer.");
|
||||
}
|
||||
return node.intValue();
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidInputException", message, 400);
|
||||
}
|
||||
|
||||
private static AwsException invalidAccess(String message) {
|
||||
return new AwsException("InvalidAccessException", message, 401);
|
||||
}
|
||||
|
||||
private static AwsException conflict(String message) {
|
||||
return new AwsException("ResourceConflictException", message, 409);
|
||||
}
|
||||
|
||||
private static AwsException notFound(String message) {
|
||||
return new AwsException("ResourceNotFoundException", message, 404);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
states.clear();
|
||||
}
|
||||
|
||||
private record TargetRef(String id, String type) {}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package io.github.hectorvent.floci.services.securityhub;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.TagHandler;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** AWS Security Hub CSPM tagging on the shared REST /tags/{ResourceArn} path. */
|
||||
@ApplicationScoped
|
||||
public class SecurityHubTagHandler implements TagHandler {
|
||||
private final SecurityHubService service;
|
||||
|
||||
@Inject
|
||||
public SecurityHubTagHandler(SecurityHubService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String serviceKey() {
|
||||
return "securityhub";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tagsBodyKey() {
|
||||
return "Tags";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean strictTagValidation() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int tagResourceSuccessStatus() {
|
||||
return 200;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int untagResourceSuccessStatus() {
|
||||
return 200;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> listTags(String region, String arn) {
|
||||
return service.tagsForResource(region, arn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tagResource(String region, String arn, Map<String, String> tags) {
|
||||
service.tagResource(region, arn, tags);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void untagResource(String region, String arn, List<String> tagKeys) {
|
||||
service.untagResource(region, arn, tagKeys);
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package io.github.hectorvent.floci.services.securityhub.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class SecurityHubAssociation {
|
||||
private String targetId;
|
||||
private String targetType;
|
||||
private String policyId;
|
||||
private String status;
|
||||
private String statusMessage;
|
||||
private String updatedAt;
|
||||
private int pendingPollsRemaining;
|
||||
private boolean disassociating;
|
||||
|
||||
public SecurityHubAssociation() {
|
||||
}
|
||||
|
||||
public SecurityHubAssociation(String targetId, String targetType, String policyId,
|
||||
String status, int pendingPollsRemaining) {
|
||||
this.targetId = targetId;
|
||||
this.targetType = targetType;
|
||||
this.policyId = policyId;
|
||||
this.status = status;
|
||||
this.updatedAt = java.time.Instant.now().toString();
|
||||
this.pendingPollsRemaining = pendingPollsRemaining;
|
||||
}
|
||||
|
||||
public String getTargetId() { return targetId; }
|
||||
public void setTargetId(String targetId) { this.targetId = targetId; }
|
||||
public String getTargetType() { return targetType; }
|
||||
public void setTargetType(String targetType) { this.targetType = targetType; }
|
||||
public String getPolicyId() { return policyId; }
|
||||
public void setPolicyId(String policyId) { this.policyId = policyId; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public String getStatusMessage() { return statusMessage; }
|
||||
public void setStatusMessage(String statusMessage) { this.statusMessage = statusMessage; }
|
||||
public String getUpdatedAt() { return updatedAt; }
|
||||
public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; }
|
||||
public int getPendingPollsRemaining() { return pendingPollsRemaining; }
|
||||
public void setPendingPollsRemaining(int pendingPollsRemaining) { this.pendingPollsRemaining = pendingPollsRemaining; }
|
||||
public boolean isDisassociating() { return disassociating; }
|
||||
public void setDisassociating(boolean disassociating) { this.disassociating = disassociating; }
|
||||
|
||||
public SecurityHubAssociation copy() {
|
||||
SecurityHubAssociation copy = new SecurityHubAssociation(targetId, targetType, policyId, status,
|
||||
pendingPollsRemaining);
|
||||
copy.setStatusMessage(statusMessage);
|
||||
copy.setUpdatedAt(updatedAt);
|
||||
copy.setDisassociating(disassociating);
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package io.github.hectorvent.floci.services.securityhub.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class SecurityHubState {
|
||||
private String adminAccountId;
|
||||
private String adminFeature = "SecurityHub";
|
||||
private boolean enabled;
|
||||
private boolean autoEnable;
|
||||
private String autoEnableStandards = "DEFAULT";
|
||||
private boolean autoEnableControls = true;
|
||||
private String controlFindingGenerator = "SECURITY_CONTROL";
|
||||
private Map<String, String> hubTags = new LinkedHashMap<>();
|
||||
private String aggregatorArn;
|
||||
private String regionLinkingMode;
|
||||
private JsonNode regions;
|
||||
private String organizationConfigurationType = "LOCAL";
|
||||
private String organizationConfigurationStatus = "ENABLED";
|
||||
private int organizationConfigurationPendingPollsRemaining;
|
||||
private Map<String, JsonNode> policies = new LinkedHashMap<>();
|
||||
private Map<String, SecurityHubAssociation> associations = new LinkedHashMap<>();
|
||||
|
||||
public String getAdminAccountId() { return adminAccountId; }
|
||||
public void setAdminAccountId(String adminAccountId) { this.adminAccountId = adminAccountId; }
|
||||
public String getAdminFeature() { return adminFeature; }
|
||||
public void setAdminFeature(String adminFeature) { this.adminFeature = adminFeature; }
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public void setEnabled(boolean enabled) { this.enabled = enabled; }
|
||||
public boolean isAutoEnable() { return autoEnable; }
|
||||
public void setAutoEnable(boolean autoEnable) { this.autoEnable = autoEnable; }
|
||||
public String getAutoEnableStandards() { return autoEnableStandards; }
|
||||
public void setAutoEnableStandards(String autoEnableStandards) { this.autoEnableStandards = autoEnableStandards; }
|
||||
public boolean isAutoEnableControls() { return autoEnableControls; }
|
||||
public void setAutoEnableControls(boolean autoEnableControls) { this.autoEnableControls = autoEnableControls; }
|
||||
public String getControlFindingGenerator() { return controlFindingGenerator; }
|
||||
public void setControlFindingGenerator(String controlFindingGenerator) { this.controlFindingGenerator = controlFindingGenerator; }
|
||||
public Map<String, String> getHubTags() { return hubTags; }
|
||||
public void setHubTags(Map<String, String> hubTags) { this.hubTags = hubTags; }
|
||||
public String getAggregatorArn() { return aggregatorArn; }
|
||||
public void setAggregatorArn(String aggregatorArn) { this.aggregatorArn = aggregatorArn; }
|
||||
public String getRegionLinkingMode() { return regionLinkingMode; }
|
||||
public void setRegionLinkingMode(String regionLinkingMode) { this.regionLinkingMode = regionLinkingMode; }
|
||||
public JsonNode getRegions() { return regions; }
|
||||
public void setRegions(JsonNode regions) { this.regions = regions; }
|
||||
public String getOrganizationConfigurationType() { return organizationConfigurationType; }
|
||||
public void setOrganizationConfigurationType(String value) { organizationConfigurationType = value; }
|
||||
public String getOrganizationConfigurationStatus() { return organizationConfigurationStatus; }
|
||||
public void setOrganizationConfigurationStatus(String value) { organizationConfigurationStatus = value; }
|
||||
public int getOrganizationConfigurationPendingPollsRemaining() { return organizationConfigurationPendingPollsRemaining; }
|
||||
public void setOrganizationConfigurationPendingPollsRemaining(int value) { organizationConfigurationPendingPollsRemaining = value; }
|
||||
public Map<String, JsonNode> getPolicies() { return policies; }
|
||||
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; }
|
||||
}
|
||||
Reference in new issue
Block a user