feat(securityhub): import and query ASFF findings (#7692)

fix(securityhub): validate provider fields and preserve default product metadata

fix(securityhub): preserve custom names and reconcile provider updates

fix(securityhub): prefer provider fields on first import

docs(securityhub): update findings operation count

fix(securityhub): validate initial verification state
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-07 09:18:47 -04:00
1 parent 87eaaab92d
commit 6e75e4096e
13 files changed
+1896 -7

No files matched your search

+5
View File
@@ -281,6 +281,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s
$(PYTHON) tools/aws/regen_ecr_shapes.py
$(PYTHON) tools/aws/regen_payment_cryptography_shapes.py
$(PYTHON) tools/aws/regen_payment_cryptography_data_shapes.py
$(PYTHON) tools/aws/regen_securityhub_shapes.py
$(PYTHON) tools/aws/regen_iam_shapes.py
$(PYTHON) tools/aws/regen_sts_shapes.py
$(PYTHON) tools/aws/regen_apigateway_types.py
@@ -382,6 +383,10 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres
echo " Run 'make aws-data-sync' and commit the result."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_securityhub_shapes.py --check || { \
echo "error: Security Hub request shapes are out of date; run 'make aws-data-sync'."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_apigateway_types.py --check || { \
echo "error: API Gateway integration types are out of date; run 'make aws-data-sync'."; \
exit 1; \
@@ -0,0 +1,190 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.securityhub.SecurityHubClient;
import software.amazon.awssdk.services.securityhub.model.AwsSecurityFinding;
import software.amazon.awssdk.services.securityhub.model.BatchImportFindingsResponse;
import software.amazon.awssdk.services.securityhub.model.GetFindingsResponse;
import software.amazon.awssdk.services.securityhub.model.StringFilter;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
@DisplayName("Security Hub findings via AWS SDK")
class SecurityHubFindingsCompatibilityTest {
private static final String READ_ACCOUNT = "123456789128";
private static final String IMPORT_ACCOUNT = "123456789129";
@Test
void getFindingsReturnsEmptyListForEnabledHub() {
assumeFalse(TestFixtures.isRealAws(), "Uses emulator-only accounts");
try (SecurityHubClient client = TestFixtures.securityHubClient(READ_ACCOUNT)) {
client.enableSecurityHub(request -> request.enableDefaultStandards(false));
assertThat(client.getFindings(request -> request.maxResults(5)).findings()).isEmpty();
}
}
@Test
void batchImportFindingsCanBeReadBack() {
assumeFalse(TestFixtures.isRealAws(), "Uses emulator-only accounts");
String findingId = TestFixtures.uniqueName("securityhub-finding");
String productArn = TestFixtures.arn("securityhub", IMPORT_ACCOUNT,
"product/" + IMPORT_ACCOUNT + "/default");
String resourceArn = TestFixtures.globalArn("iam", IMPORT_ACCOUNT, "role/securityhub-test");
String timestamp = Instant.now().toString();
AwsSecurityFinding finding = AwsSecurityFinding.builder()
.schemaVersion("2018-10-08")
.id(findingId)
.productArn(productArn)
.generatorId("securityhub-findings-compatibility")
.awsAccountId(IMPORT_ACCOUNT)
.types("Software and Configuration Checks/Industry and Regulatory Standards")
.createdAt(timestamp)
.updatedAt(timestamp)
.severity(severity -> severity.label("MEDIUM"))
.title("Test\ncontrol finding")
.description("Imported by\nthe Security Hub compatibility test")
.resources(resource -> resource.type("AwsIamRole").id(resourceArn)
.partition(TestFixtures.partition()).region(TestFixtures.region().id()))
.compliance(compliance -> compliance.status("FAILED").securityControlId("IAM.1"))
.recordState("ACTIVE")
.build();
try (SecurityHubClient client = TestFixtures.securityHubClient(IMPORT_ACCOUNT)) {
client.enableSecurityHub(request -> request.enableDefaultStandards(false));
BatchImportFindingsResponse imported = client.batchImportFindings(request -> request.findings(finding));
assertThat(imported.successCount()).isEqualTo(1);
assertThat(imported.failedCount()).isZero();
assertThat(imported.failedFindings()).isEmpty();
assertThat(client.getFindings(request -> {}).findings())
.filteredOn(candidate -> findingId.equals(candidate.id()))
.singleElement()
.satisfies(candidate -> {
assertThat(candidate.productArn()).isEqualTo(productArn);
assertThat(candidate.awsAccountId()).isEqualTo(IMPORT_ACCOUNT);
assertThat(candidate.title()).isEqualTo(finding.title());
assertThat(candidate.description()).isEqualTo(finding.description());
assertThat(candidate.compliance().statusAsString()).isEqualTo("FAILED");
assertThat(candidate.severity().labelAsString()).isEqualTo("MEDIUM");
assertThat(candidate.findingProviderFields().severity().labelAsString()).isEqualTo("MEDIUM");
assertThat(candidate.findingProviderFields().types()).containsExactlyElementsOf(finding.types());
assertThat(candidate.recordStateAsString()).isEqualTo("ACTIVE");
assertThat(candidate.resources()).singleElement()
.satisfies(resource -> assertThat(resource.id()).isEqualTo(resourceArn));
});
}
}
@Test
void mixedImportDefaultsFiltersAndContinuationTokens() {
assumeFalse(TestFixtures.isRealAws(), "Uses emulator-only accounts");
String account = "123456789130";
String idPrefix = TestFixtures.uniqueName("securityhub-page");
String productArn = TestFixtures.arn("securityhub", account, "product/" + account + "/default");
String timestamp = Instant.now().toString();
AwsSecurityFinding first = AwsSecurityFinding.builder()
.schemaVersion("2018-10-08")
.id(idPrefix + "-one")
.productArn(productArn)
.generatorId("securityhub-findings-compatibility")
.awsAccountId(account)
.createdAt(timestamp)
.updatedAt(timestamp)
.title("First finding")
.description("Sparse finding imported by the SDK")
.resources(resource -> resource.type("AwsIamRole").id("role/first"))
.compliance(compliance -> compliance.securityControlId("IAM.1"))
.build();
AwsSecurityFinding second = first.toBuilder().id(idPrefix + "-two")
.title("Second finding")
.compliance(compliance -> compliance.securityControlId("IAM.2"))
.build();
AwsSecurityFinding third = first.toBuilder().id(idPrefix + "-three")
.title("Third finding")
.compliance(compliance -> compliance.securityControlId("EC2.1"))
.build();
AwsSecurityFinding invalid = first.toBuilder().id(idPrefix + "-invalid").title("").build();
try (SecurityHubClient client = TestFixtures.securityHubClient(account)) {
client.enableSecurityHub(request -> request.enableDefaultStandards(false));
BatchImportFindingsResponse imported = client.batchImportFindings(
request -> request.findings(first, invalid, second, third));
assertThat(imported.successCount()).isEqualTo(3);
assertThat(imported.failedCount()).isEqualTo(1);
assertThat(imported.failedFindings()).singleElement().satisfies(failure -> {
assertThat(failure.id()).isEqualTo(idPrefix + "-invalid");
assertThat(failure.errorCode()).isEqualTo("InvalidInput");
});
Set<String> ids = new HashSet<>();
String nextToken = null;
for (int pageNumber = 0; pageNumber < 3; pageNumber++) {
String token = nextToken;
GetFindingsResponse page = client.getFindings(request -> {
request.maxResults(1).filters(filters -> filters.productArn(
stringFilter(productArn, "EQUALS")));
if (token != null) {
request.nextToken(token);
}
});
assertThat(page.findings()).singleElement().satisfies(candidate -> {
ids.add(candidate.id());
assertThat(candidate.productName()).isEqualTo("Default");
assertThat(candidate.companyName()).isEqualTo("Personal");
assertThat(candidate.recordStateAsString()).isEqualTo("ACTIVE");
assertThat(candidate.workflow().statusAsString()).isEqualTo("NEW");
assertThat(candidate.createdAt()).isEqualTo(timestamp);
assertThat(candidate.resources()).hasSize(1);
});
nextToken = page.nextToken();
if (pageNumber < 2) {
assertThat(nextToken).isNotBlank();
}
}
assertThat(nextToken).isNull();
assertThat(ids).containsExactlyInAnyOrder(first.id(), second.id(), third.id());
assertThat(client.getFindings(request -> request.filters(filters -> filters
.complianceSecurityControlId(stringFilter("IAM.1", "EQUALS"),
stringFilter("IAM.2", "EQUALS")))).findings())
.extracting(AwsSecurityFinding::id)
.containsExactlyInAnyOrder(first.id(), second.id());
assertThat(client.getFindings(request -> request.filters(filters -> filters
.complianceSecurityControlId(stringFilter("IAM.1", "EQUALS"),
stringFilter("EC2", "PREFIX")))).findings())
.extracting(AwsSecurityFinding::id)
.containsExactlyInAnyOrder(first.id(), third.id());
assertThat(client.getFindings(request -> request.filters(filters -> filters
.complianceSecurityControlId(stringFilter("IAM.1", "NOT_EQUALS"),
stringFilter("IAM.2", "NOT_EQUALS")))).findings())
.extracting(AwsSecurityFinding::id)
.containsExactly(third.id());
assertThat(client.getFindings(request -> request.filters(filters -> filters
.complianceSecurityControlId(stringFilter("IAM", "PREFIX"),
stringFilter("IAM.1", "NOT_EQUALS")))).findings())
.extracting(AwsSecurityFinding::id)
.containsExactly(second.id());
assertThatThrownBy(() -> client.getFindings(request -> request.filters(filters -> filters
.complianceSecurityControlId(stringFilter("IAM.1", "EQUALS"),
stringFilter("IAM.2", "NOT_EQUALS")))))
.hasMessageContaining("cannot combine EQUALS with NOT_EQUALS");
}
}
private static StringFilter stringFilter(String value, String comparison) {
return StringFilter.builder().value(value).comparison(comparison).build();
}
}
+1 -1
View File
@@ -59,7 +59,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Amazon Macie](macie2.md) | `/admin`, `/macie`, `/admin/configuration` | REST JSON | 8 |
| [Amazon Inspector](inspector2.md) | `/delegatedadminaccounts/*`, `/status/batch/get`, `/enable`, `/disable`, `/organizationconfiguration/*` | REST JSON | 8 |
| [Amazon Verified Permissions](verifiedpermissions.md) | `POST /` + `X-Amz-Target: VerifiedPermissions.*` | JSON 1.0 | 34 |
| [Security Hub](securityhub.md) | `/organization/*`, `/accounts`, `/findingAggregator/*`, `/configurationPolicy*`, `/standards*`, `/tags/*` | REST JSON | 26 |
| [Security Hub](securityhub.md) | `/organization/*`, `/accounts`, `/findingAggregator/*`, `/configurationPolicy*`, `/standards*`, `/tags/*`, `/findings*` | REST JSON | 28 |
| [Amazon Detective](detective.md) | `/orgs/*`, `/graphs/list`, `/graph/*` | REST JSON | 8 |
| [Amazon Connect](connect.md) | `/instance`, `/instance/{instanceId}/*`, `/tags/*` | REST JSON | 15 |
| [Amazon AppIntegrations](appintegrations.md) | `/eventIntegrations/*`, `/dataIntegrations/*`, `/tags/*` | REST JSON | 14 |
+4
View File
@@ -20,6 +20,8 @@ Floci implements the AWS Security Hub CSPM organization and central-configuratio
| `BatchEnableStandards` | Subscribes standards (`READY` at once); an unknown standards ARN is `InvalidInputException`, a disabled hub `InvalidAccessException`. `EnableSecurityHub` subscribes AFSBP and CIS 1.2.0 unless `EnableDefaultStandards` is false |
| `BatchDisableStandards` | Removes subscriptions, answered as `DELETING`; an unknown one is `ResourceNotFoundException`, and then none of the batch is removed |
| `GetEnabledStandards` | Lists subscriptions, all or the named ones. Controls and findings are not evaluated |
| `BatchImportFindings` | Imports up to 100 ASFF findings for the caller's default product, with per-finding failures |
| `GetFindings` | Reads imported findings with eight string-filter fields and cursor pagination |
| `ListFindingAggregators` | - |
| `CreateFindingAggregator` | - |
| `GetFindingAggregator` | - |
@@ -47,6 +49,8 @@ The supported surface includes Security Hub CSPM enablement and configuration, d
Finding aggregators support `ALL_REGIONS`, `ALL_REGIONS_EXCEPT_SPECIFIED`, `SPECIFIED_REGIONS`, and `NO_REGIONS`. `GetFindingAggregator` accepts the complete finding-aggregator ARN carried in the greedy AWS REST path.
`BatchImportFindings` stores findings in the requested Region and reports invalid items individually. `GetFindings` reads findings from that Region and supports the `EQUALS`, `NOT_EQUALS`, and `PREFIX` comparisons for its documented string filters. `SortCriteria`, other filter comparisons, cross-Region aggregation of findings, and `BatchUpdateFindings` are not implemented.
Central organization configuration models asynchronous convergence. Changing to `CENTRAL` first reports organization status `PENDING`; a subsequent poll converges to `ENABLED`. Central configuration forces `AutoEnable` to `false` and `AutoEnableStandards` to `NONE`, as AWS does in the home and linked Regions. Configuration-policy association behaves similarly with `PENDING` followed by `SUCCESS`. Disassociation is represented as a pending transition before the association disappears.
Configuration-policy and hub tags are persisted and returned through the shared Security Hub tagging routes. Tag keys and values use the AWS Security Hub constraints, including the reserved `aws:` prefix restriction.
@@ -71,6 +71,22 @@ public final class RequestConstraintCheck {
checkValue(model.path("operations").path(operation).asText(), request, operation);
}
/** Checks one modeled value without treating it as a whole request. */
public void checkShape(String shapeName, JsonNode value) {
checkValue(shapeName, value, shapeName);
}
/** Checks a modeled request list's count without validating its members as one batch error. */
public void checkListSize(String operation, String member, int size) {
String input = model.path("operations").path(operation).asText();
String list = model.path("shapes").path(input).path("members").path(member).asText();
JsonNode shape = model.path("shapes").path(list);
if (!"list".equals(shape.path("type").asText())) {
throw new IllegalArgumentException(operation + "." + member + " is not a modeled list");
}
checkBounds(shape, operation + "." + member, "list", size);
}
private void checkValue(String name, JsonNode value, String path) {
JsonNode shape = model.path("shapes").path(name);
String type = shape.path("type").asText();
@@ -90,11 +106,7 @@ public final class RequestConstraintCheck {
case "integer", "long" -> value.longValue();
default -> value.size();
};
Long min = shape.has("min") ? shape.get("min").asLong() : null;
Long max = shape.has("max") ? shape.get("max").asLong() : null;
if (min != null && size < min || max != null && size > max) {
throw messages.bounds(path, type, min, max, size);
}
checkBounds(shape, path, type, size);
if (patterns.containsKey(name) && !patterns.get(name).matcher(value.asText()).matches()) {
throw messages.pattern(path, VendoredPatterns.quoted(shape));
}
@@ -138,4 +150,12 @@ public final class RequestConstraintCheck {
}
}
}
private void checkBounds(JsonNode shape, String path, String type, long size) {
Long min = shape.has("min") ? shape.get("min").asLong() : null;
Long max = shape.has("max") ? shape.get("max").asLong() : null;
if (min != null && size < min || max != null && size > max) {
throw messages.bounds(path, type, min, max, size);
}
}
}
@@ -34,13 +34,15 @@ import java.util.Map;
@Consumes(MediaType.APPLICATION_JSON)
public class SecurityHubController {
private final SecurityHubService securityHubService;
private final SecurityHubFindingsService findingsService;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public SecurityHubController(SecurityHubService securityHubService,
public SecurityHubController(SecurityHubService securityHubService, SecurityHubFindingsService findingsService,
RegionResolver regionResolver, ObjectMapper objectMapper) {
this.securityHubService = securityHubService;
this.findingsService = findingsService;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@@ -145,6 +147,35 @@ public class SecurityHubController {
return subscriptions(securityHubService.enabledStandards(region(headers), readTree(body)), "READY");
}
@POST
@Path("/findings/import")
public Response batchImportFindings(@Context HttpHeaders headers, String body) {
SecurityHubFindingsService.ImportResult imported = findingsService.batchImportFindings(
region(headers), readTree(body));
ObjectNode response = objectMapper.createObjectNode();
response.put("SuccessCount", imported.successCount());
response.put("FailedCount", imported.failedFindings().size());
ArrayNode failed = response.putArray("FailedFindings");
for (SecurityHubFindingsService.ImportFailure failure : imported.failedFindings()) {
failed.addObject().put("Id", failure.id()).put("ErrorCode", failure.errorCode())
.put("ErrorMessage", failure.errorMessage());
}
return Response.ok(response).build();
}
@POST
@Path("/findings")
public Response getFindings(@Context HttpHeaders headers, String body) {
PaginatedResult<ObjectNode> page = findingsService.getFindings(region(headers), readTree(body));
ObjectNode response = objectMapper.createObjectNode();
ArrayNode items = response.putArray("Findings");
page.items().forEach(items::add);
if (page.nextToken() != null) {
response.put("NextToken", page.nextToken());
}
return Response.ok(response).build();
}
private Response subscriptions(Map<String, String> subscriptions, String status) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode items = response.putArray("StandardsSubscriptions");
@@ -0,0 +1,455 @@
package io.floci.aws.services.securityhub;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.Base64Url;
import io.floci.aws.core.common.Digests;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
@ApplicationScoped
public class SecurityHubFindingsService implements Resettable {
private static final int MAX_FINDING_BYTES = 240 * 1024;
private static final Set<String> FILTER_FIELDS = Set.of("ComplianceAssociatedStandardsId", "RecordState",
"WorkflowStatus", "ComplianceStatus", "ComplianceSecurityControlId", "ProductArn",
"AwsAccountId", "Region");
private static final List<String> INVESTIGATION_FIELDS = List.of(
"Note", "UserDefinedFields", "VerificationState", "Workflow");
private static final List<String> PROVIDER_FIELDS = List.of(
"Confidence", "Criticality", "RelatedFindings", "Severity", "Types");
private final AccountAwareStorageBackend<Map<String, ObjectNode>> findings;
private final SecurityHubService securityHubService;
private final RegionResolver regionResolver;
@Inject
public SecurityHubFindingsService(StorageFactory storageFactory, SecurityHubService securityHubService,
RegionResolver regionResolver) {
this(storageFactory.createPartitioned("securityhub", "securityhub-findings.json",
new TypeReference<Map<String, Map<String, ObjectNode>>>() {}, ObjectNode.class, 32),
securityHubService, regionResolver);
}
SecurityHubFindingsService(AccountAwareStorageBackend<Map<String, ObjectNode>> findings,
SecurityHubService securityHubService, RegionResolver regionResolver) {
this.findings = findings;
this.securityHubService = securityHubService;
this.regionResolver = regionResolver;
}
public synchronized ImportResult batchImportFindings(String region, JsonNode request) {
JsonNode requestedFindings = request == null ? null : request.get("Findings");
if (requestedFindings == null || !requestedFindings.isArray()) {
throw invalid("Findings must contain between 1 and 100 findings.");
}
SecurityHubRequestShapes.checkFindingsSize(requestedFindings.size());
String accountId = regionResolver.getAccountId();
Map<String, ObjectNode> stored = new LinkedHashMap<>(
findings.getForAccount(accountId, region).orElseGet(LinkedHashMap::new));
List<ImportFailure> failures = new ArrayList<>();
Set<String> seen = new HashSet<>();
int successCount = 0;
boolean enabled = securityHubService.state(region).isEnabled();
for (JsonNode candidate : requestedFindings) {
String id = text(candidate, "Id");
ImportError error = enabled ? validateFinding(candidate, region, accountId)
: new ImportError("InvalidAccess", "Security Hub is not enabled for this account.");
if (error != null) {
failures.add(new ImportFailure(id == null ? "" : id,
error.code(), error.message()));
continue;
}
String key = findingKey(candidate.path("ProductArn").textValue(), id);
if (!seen.contains(key)) {
ObjectNode previous = stored.get(key);
JsonNode verificationState = candidate.get("VerificationState");
if (previous == null && verificationState != null) {
try {
SecurityHubRequestShapes.checkInitialVerificationState(verificationState);
} catch (AwsException e) {
failures.add(new ImportFailure(id, "InvalidInput",
"VerificationState must be a valid verification state."));
continue;
}
}
ObjectNode imported = ((ObjectNode) candidate).deepCopy();
Instant updatedAt = Instant.parse(imported.path("UpdatedAt").textValue());
if (previous != null && !updatedAt.isAfter(Instant.parse(previous.path("UpdatedAt").textValue()))) {
seen.add(key);
successCount++;
continue;
}
addManagedFields(imported, previous, region);
stored.put(key, imported);
seen.add(key);
if (findings.writesEntries()) {
findings.putEntryForAccount(accountId, region, key, imported);
}
}
successCount++;
}
if (successCount > 0 && !findings.writesEntries()) {
findings.putForAccount(accountId, region, stored);
}
return new ImportResult(successCount, failures);
}
public synchronized PaginatedResult<ObjectNode> getFindings(String region, JsonNode request) {
requireEnabled(region);
if (request == null || !request.isObject()) {
throw invalid("GetFindings request must be a JSON object.");
}
if (request.has("SortCriteria")) {
throw invalid("SortCriteria is not supported.");
}
SecurityHubRequestShapes.checkGetFindings(request);
Map<String, List<StringPredicate>> filters = parseFilters(request.get("Filters"));
Integer maxResults = Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException");
String nextToken = Pagination.parseNextToken(request, "NextToken", "InvalidInputException");
if (nextToken != null && nextToken.isEmpty()) {
throw invalid("NextToken is invalid.");
}
String accountId = regionResolver.getAccountId();
List<ObjectNode> matches = new ArrayList<>();
findings.getForAccount(accountId, region).ifPresent(stored -> stored.values().stream()
.filter(finding -> matches(finding, filters)).map(ObjectNode::deepCopy).forEach(matches::add));
String namespace = "securityhub-findings:" + scopeDigest(accountId, region, filters);
return Pagination.paginate(matches,
finding -> findingKey(finding.path("ProductArn").asText(), finding.path("Id").asText()),
maxResults == null ? 100 : maxResults, nextToken, namespace,
token -> invalid("NextToken is invalid."));
}
private ImportError validateFinding(JsonNode finding, String region, String accountId) {
if (finding == null || !finding.isObject()) {
return invalidFinding("Finding must be a JSON object.");
}
if (finding.toString().getBytes(StandardCharsets.UTF_8).length > MAX_FINDING_BYTES) {
return invalidFinding("Finding exceeds the 240 KB size limit.");
}
try {
SecurityHubRequestShapes.checkFinding(finding);
} catch (AwsException e) {
return invalidFinding(e.getMessage());
}
if (!"2018-10-08".equals(text(finding, "SchemaVersion"))) {
return invalidFinding("SchemaVersion must be 2018-10-08.");
}
for (Map.Entry<String, Integer> field : Map.of("Id", 512, "ProductArn", 2048,
"GeneratorId", 512, "Title", 256, "Description", 1024).entrySet()) {
String value = text(finding, field.getKey());
if (value.length() > field.getValue()) {
return invalidFinding(field.getKey() + " must not exceed " + field.getValue() + " characters.");
}
}
for (String field : List.of("ProductName", "CompanyName")) {
if (finding.has(field)) {
String value = text(finding, field);
if (value == null || value.length() > 128) {
return invalidFinding(field + " must contain between 1 and 128 characters.");
}
}
}
String findingAccount = text(finding, "AwsAccountId");
if (findingAccount == null || !findingAccount.matches("\\d{12}")) {
return invalidFinding("AwsAccountId must be a 12 digit account ID.");
}
if (!accountId.equals(findingAccount)) {
return new ImportError("InvalidAccess", "AwsAccountId must match the caller account for the default product.");
}
String defaultProductArn = regionResolver.buildArn("securityhub", region,
"product/" + accountId + "/default");
if (!defaultProductArn.equals(text(finding, "ProductArn"))) {
return new ImportError("InvalidAccess", "ProductArn must be the caller's default product ARN in this Region.");
}
for (String field : List.of("CreatedAt", "UpdatedAt")) {
String timestamp = text(finding, field);
if (timestamp == null || timestamp.isBlank()) {
return invalidFinding(field + " is required.");
}
try {
Instant.parse(timestamp);
} catch (DateTimeParseException e) {
return invalidFinding(field + " must be an ISO 8601 timestamp.");
}
}
JsonNode resources = finding.get("Resources");
if (resources == null || !resources.isArray() || resources.isEmpty() || resources.size() > 32) {
return invalidFinding("Resources must contain between 1 and 32 resources.");
}
JsonNode compliance = finding.get("Compliance");
if (compliance != null) {
if (!compliance.isObject()) {
return invalidFinding("Compliance must be a JSON object.");
}
if (compliance.has("Status") && text(compliance, "Status") == null) {
return invalidFinding("Compliance.Status must be a valid compliance status.");
}
}
if (finding.has("RecordState") && text(finding, "RecordState") == null) {
return invalidFinding("RecordState must be a valid record state.");
}
JsonNode providerFields = finding.path("FindingProviderFields");
if (!providerFields.isMissingNode() && !providerFields.isObject()) {
return invalidFinding("FindingProviderFields must be a JSON object.");
}
for (JsonNode severity : new JsonNode[] {finding.get("Severity"), providerFields.get("Severity")}) {
if (severity != null) {
if (!severity.isObject()) {
return invalidFinding("Severity must be a JSON object.");
}
if (!severity.has("Label") && !severity.has("Normalized")) {
return invalidFinding("Severity requires Label or Normalized.");
}
if (severity.has("Label")) {
String label = text(severity, "Label");
if (label == null) {
return invalidFinding("Severity.Label must be a valid severity label.");
}
}
if (severity.has("Normalized") && (!severity.path("Normalized").isIntegralNumber()
|| !severity.path("Normalized").canConvertToInt()
|| severity.path("Normalized").intValue() < 0
|| severity.path("Normalized").intValue() > 100)) {
return invalidFinding("Severity.Normalized must be between 0 and 100.");
}
}
}
for (JsonNode types : new JsonNode[] {finding.get("Types"), providerFields.get("Types")}) {
if (types != null) {
if (!types.isArray() || types.isEmpty() || types.size() > 50) {
return invalidFinding("Types must contain between 1 and 50 finding types.");
}
}
}
return null;
}
private void addManagedFields(ObjectNode imported, ObjectNode previous, String region) {
JsonNode providerFields = imported.path("FindingProviderFields");
ObjectNode provider = providerFields.isObject() ? (ObjectNode) providerFields : null;
for (String field : PROVIDER_FIELDS) {
if (provider != null && provider.has(field) && (previous == null || !imported.has(field))) {
imported.set(field, provider.get(field).deepCopy());
} else if (imported.has(field)) {
if (provider == null) {
provider = imported.putObject("FindingProviderFields");
}
if (!provider.has(field)) {
provider.set(field, imported.get(field).deepCopy());
}
}
}
if (imported.path("Severity").isObject()) {
normalizeSeverity((ObjectNode) imported.get("Severity"));
}
if (provider != null && provider.path("Severity").isObject()) {
normalizeSeverity((ObjectNode) provider.get("Severity"));
}
if (previous != null) {
for (String field : INVESTIGATION_FIELDS) {
JsonNode old = previous.get(field);
if (old == null) {
imported.remove(field);
} else {
imported.set(field, old.deepCopy());
}
}
}
if (!imported.has("ProductName")) {
imported.put("ProductName", previous == null ? "Default" : previous.path("ProductName").asText("Default"));
}
if (!imported.has("CompanyName")) {
imported.put("CompanyName", previous == null ? "Personal" : previous.path("CompanyName").asText("Personal"));
}
imported.put("Region", region);
if (!imported.hasNonNull("RecordState")) {
imported.put("RecordState", "ACTIVE");
}
if (previous == null) {
imported.putObject("Workflow").put("Status", "NEW");
}
}
private static void normalizeSeverity(ObjectNode severity) {
if (!severity.has("Normalized")) {
int normalized = switch (severity.path("Label").asText()) {
case "INFORMATIONAL" -> 0;
case "LOW" -> 1;
case "MEDIUM" -> 40;
case "HIGH" -> 70;
case "CRITICAL" -> 90;
default -> -1;
};
if (normalized >= 0) {
severity.put("Normalized", normalized);
}
} else if (!severity.has("Label")) {
int normalized = severity.path("Normalized").asInt();
String label = normalized == 0 ? "INFORMATIONAL" : normalized < 40 ? "LOW"
: normalized < 70 ? "MEDIUM" : normalized < 90 ? "HIGH" : "CRITICAL";
severity.put("Label", label);
}
}
private static Map<String, List<StringPredicate>> parseFilters(JsonNode input) {
Map<String, List<StringPredicate>> filters = new TreeMap<>();
if (input == null || input.isNull()) {
return filters;
}
if (!input.isObject() || input.size() > 10) {
throw invalid("Filters must contain at most 10 finding attributes.");
}
input.fields().forEachRemaining(entry -> {
String field = entry.getKey();
JsonNode values = entry.getValue();
if (!FILTER_FIELDS.contains(field)) {
throw invalid("Filter " + field + " is not supported.");
}
if (!values.isArray() || values.isEmpty() || values.size() > 20) {
throw invalid(field + " must contain between 1 and 20 filter values.");
}
List<StringPredicate> predicates = new ArrayList<>();
boolean equals = false;
boolean negative = false;
for (JsonNode value : values) {
String text = text(value, "Value");
String comparison = value.has("Comparison") ? text(value, "Comparison") : "EQUALS";
if (text == null || text.isEmpty() || !List.of("EQUALS", "PREFIX", "NOT_EQUALS")
.contains(comparison)) {
throw invalid(field + " requires a nonempty Value and EQUALS, PREFIX, or NOT_EQUALS.");
}
equals |= "EQUALS".equals(comparison);
negative |= "NOT_EQUALS".equals(comparison);
predicates.add(new StringPredicate(text, comparison));
}
if (equals && negative) {
throw invalid(field + " cannot combine EQUALS with NOT_EQUALS.");
}
filters.put(field, predicates);
});
return filters;
}
private static boolean matches(ObjectNode finding, Map<String, List<StringPredicate>> filters) {
for (Map.Entry<String, List<StringPredicate>> filter : filters.entrySet()) {
List<String> values = valuesFor(finding, filter.getKey());
if (values.isEmpty()) {
return false;
}
boolean hasPositive = false;
boolean positiveMatched = false;
for (StringPredicate predicate : filter.getValue()) {
if ("NOT_EQUALS".equals(predicate.comparison())) {
if (values.contains(predicate.value())) {
return false;
}
} else {
hasPositive = true;
positiveMatched |= values.stream().anyMatch(value -> "EQUALS".equals(predicate.comparison())
? value.equals(predicate.value()) : value.startsWith(predicate.value()));
}
}
if (hasPositive && !positiveMatched) {
return false;
}
}
return true;
}
private static List<String> valuesFor(ObjectNode finding, String field) {
if ("ComplianceAssociatedStandardsId".equals(field)) {
List<String> values = new ArrayList<>();
JsonNode associated = finding.path("Compliance").path("AssociatedStandards");
if (associated.isArray()) {
for (JsonNode standard : associated) {
addText(values, standard.path("StandardsId"));
}
}
return values;
}
JsonNode value = switch (field) {
case "WorkflowStatus" -> finding.path("Workflow").path("Status");
case "ComplianceStatus" -> finding.path("Compliance").path("Status");
case "ComplianceSecurityControlId" -> finding.path("Compliance").path("SecurityControlId");
default -> finding.path(field);
};
List<String> values = new ArrayList<>();
addText(values, value);
return values;
}
private static void addText(List<String> values, JsonNode node) {
if (node.isTextual()) {
values.add(node.textValue());
}
}
private static String scopeDigest(String accountId, String region,
Map<String, List<StringPredicate>> filters) {
StringBuilder scope = new StringBuilder(accountId).append(':').append(region);
filters.forEach((field, predicates) -> {
scope.append(':').append(field.length()).append(':').append(field);
for (StringPredicate predicate : predicates) {
scope.append(':').append(predicate.comparison()).append(':')
.append(predicate.value().length()).append(':').append(predicate.value());
}
});
return Base64Url.encode(Digests.sha256(scope.toString().getBytes(StandardCharsets.UTF_8)));
}
private static String findingKey(String productArn, String id) {
return Base64Url.encode(productArn + "\u0000" + id);
}
private void requireEnabled(String region) {
if (!securityHubService.state(region).isEnabled()) {
throw new AwsException("InvalidAccessException", "Security Hub is not enabled for this account.", 401);
}
}
private static String text(JsonNode node, String field) {
JsonNode value = node == null ? null : node.get(field);
return value != null && value.isTextual() ? value.textValue() : null;
}
private static AwsException invalid(String message) {
return new AwsException("InvalidInputException", message, 400);
}
private static ImportError invalidFinding(String message) {
return new ImportError("InvalidInput", message);
}
@Override
public void clear() {
findings.clear();
}
public record ImportFailure(String id, String errorCode, String errorMessage) {}
public record ImportResult(int successCount, List<ImportFailure> failedFindings) {}
private record ImportError(String code, String message) {}
private record StringPredicate(String value, String comparison) {}
}
@@ -0,0 +1,79 @@
package io.floci.aws.services.securityhub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestConstraintCheck;
import io.floci.aws.core.common.VendoredResources;
import java.util.List;
/** Checks the modeled part of Security Hub findings requests. */
final class SecurityHubRequestShapes {
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.of(
VendoredResources.read("aws/securityhub-request-shapes.json", "Security Hub request shapes", input -> {
JsonNode model = new ObjectMapper().readTree(input);
ObjectNode nonEmptyString = (ObjectNode) model.path("shapes").path("NonEmptyString");
// Java's dot excludes line breaks, but Security Hub accepts multiline non-blank text.
nonEmptyString.put("pattern", "(?s:" + nonEmptyString.path("pattern").asText() + ")");
return model;
}),
new RequestConstraintCheck.Messages() {
@Override
public AwsException type(String path, String type) {
return invalid(path + " must be a " + type + ".");
}
@Override
public AwsException bounds(String path, String type, Long min, Long max, long size) {
if ("BatchImportFindings.Findings".equals(path)) {
return invalid("Findings must contain between " + min + " and " + max + " findings.");
}
return invalid(path + " must be between " + min + " and " + max + ".");
}
@Override
public AwsException pattern(String path, String pattern) {
return invalid(path + " does not match the modeled pattern.");
}
@Override
public AwsException enumValue(String path, List<String> values) {
return invalid(path + " must be one of " + values + ".");
}
@Override
public AwsException required(String path) {
return invalid(path + " is required.");
}
});
private SecurityHubRequestShapes() {
}
static void checkFindingsSize(int size) {
CHECK.checkListSize("BatchImportFindings", "Findings", size);
}
static void checkFinding(JsonNode finding) {
JsonNode modeled = finding.deepCopy();
if (modeled instanceof ObjectNode object) {
object.remove("VerificationState");
}
CHECK.checkShape("AwsSecurityFinding", modeled);
}
static void checkInitialVerificationState(JsonNode value) {
CHECK.checkShape("VerificationState", value);
}
static void checkGetFindings(JsonNode request) {
CHECK.check("GetFindings", request);
}
private static AwsException invalid(String message) {
return new AwsException("InvalidInputException", message, 400);
}
}
@@ -0,0 +1,223 @@
{
"_source": {
"generator": "tools/aws/regen_securityhub_shapes.py",
"botocore": "botocore 1.43.118 (installed package)"
},
"operations": {
"BatchImportFindings": "BatchImportFindingsRequest",
"GetFindings": "GetFindingsRequest"
},
"shapes": {
"AwsSecurityFinding": {
"type": "structure",
"required": [
"SchemaVersion",
"Id",
"ProductArn",
"GeneratorId",
"AwsAccountId",
"CreatedAt",
"UpdatedAt",
"Title",
"Description",
"Resources"
],
"members": {
"SchemaVersion": "NonEmptyString",
"Id": "NonEmptyString",
"ProductArn": "NonEmptyString",
"ProductName": "NonEmptyString",
"CompanyName": "NonEmptyString",
"GeneratorId": "NonEmptyString",
"AwsAccountId": "NonEmptyString",
"Types": "TypeList",
"CreatedAt": "NonEmptyString",
"UpdatedAt": "NonEmptyString",
"Title": "NonEmptyString",
"Description": "NonEmptyString",
"Resources": "ResourceList",
"VerificationState": "VerificationState",
"RecordState": "RecordState",
"Compliance": "Compliance",
"Severity": "Severity",
"FindingProviderFields": "FindingProviderFields",
"ProductFields": "FieldMap",
"RelatedFindings": "RelatedFindingList"
}
},
"AwsSecurityFindingFilters": {
"type": "structure",
"members": {
"ComplianceAssociatedStandardsId": "StringFilterList",
"RecordState": "StringFilterList",
"WorkflowStatus": "StringFilterList",
"ComplianceStatus": "StringFilterList",
"ComplianceSecurityControlId": "StringFilterList",
"ProductArn": "StringFilterList",
"AwsAccountId": "StringFilterList",
"Region": "StringFilterList"
}
},
"BatchImportFindingsRequest": {
"type": "structure",
"required": [
"Findings"
],
"members": {
"Findings": "BatchImportFindingsRequestFindingList"
}
},
"BatchImportFindingsRequestFindingList": {
"type": "list",
"min": 1,
"max": 100,
"member": "AwsSecurityFinding"
},
"Compliance": {
"type": "structure",
"members": {
"Status": "ComplianceStatus"
}
},
"ComplianceStatus": {
"type": "string",
"enum": [
"PASSED",
"WARNING",
"FAILED",
"NOT_AVAILABLE"
]
},
"FieldMap": {
"type": "map",
"key": "NonEmptyString",
"value": "NonEmptyString"
},
"FindingProviderFields": {
"type": "structure",
"members": {
"Confidence": "RatioScale",
"Criticality": "RatioScale",
"Severity": "FindingProviderSeverity",
"RelatedFindings": "RelatedFindingList",
"Types": "TypeList"
}
},
"FindingProviderSeverity": {
"type": "structure",
"members": {
"Label": "SeverityLabel"
}
},
"GetFindingsRequest": {
"type": "structure",
"members": {
"Filters": "AwsSecurityFindingFilters",
"MaxResults": "MaxResults"
}
},
"MaxResults": {
"type": "integer",
"min": 1,
"max": 100
},
"NonEmptyString": {
"type": "string",
"pattern": ".*\\S.*"
},
"RatioScale": {
"type": "integer",
"min": 0,
"max": 100
},
"RecordState": {
"type": "string",
"enum": [
"ACTIVE",
"ARCHIVED"
]
},
"RelatedFinding": {
"type": "structure",
"required": [
"ProductArn",
"Id"
],
"members": {
"ProductArn": "NonEmptyString",
"Id": "NonEmptyString"
}
},
"RelatedFindingList": {
"type": "list",
"member": "RelatedFinding"
},
"Resource": {
"type": "structure",
"required": [
"Type",
"Id"
],
"members": {
"Type": "NonEmptyString",
"Id": "NonEmptyString"
}
},
"ResourceList": {
"type": "list",
"member": "Resource"
},
"Severity": {
"type": "structure",
"members": {
"Label": "SeverityLabel"
}
},
"SeverityLabel": {
"type": "string",
"enum": [
"INFORMATIONAL",
"LOW",
"MEDIUM",
"HIGH",
"CRITICAL"
]
},
"StringFilter": {
"type": "structure",
"members": {
"Value": "NonEmptyString",
"Comparison": "StringFilterComparison"
}
},
"StringFilterComparison": {
"type": "string",
"enum": [
"EQUALS",
"PREFIX",
"NOT_EQUALS",
"PREFIX_NOT_EQUALS",
"CONTAINS",
"NOT_CONTAINS",
"CONTAINS_WORD"
]
},
"StringFilterList": {
"type": "list",
"member": "StringFilter"
},
"TypeList": {
"type": "list",
"member": "NonEmptyString"
},
"VerificationState": {
"type": "string",
"enum": [
"UNKNOWN",
"TRUE_POSITIVE",
"FALSE_POSITIVE",
"BENIGN_POSITIVE"
]
}
}
}
@@ -105,6 +105,16 @@ class RequestConstraintCheckTest {
assertDoesNotThrow(() -> CHECK.check("Put", json("{\"name\":\"abc\",\"count\":null}")));
}
@Test
void individualShapeAndListSizeKeepTheModeledConstraints() {
assertEquals("enum Kind [A, B]", assertThrows(AwsException.class,
() -> CHECK.checkShape("Kind", json("\"C\""))).getMessage());
assertDoesNotThrow(() -> CHECK.checkShape("Kind", json("\"A\"")));
assertEquals("bounds Put.items list null..2 3", assertThrows(AwsException.class,
() -> CHECK.checkListSize("Put", "items", 3)).getMessage());
assertDoesNotThrow(() -> CHECK.checkListSize("Put", "items", 2));
}
@Test
void aStringIsMeasuredInCodePoints() {
// One emoji is two UTF-16 units but one code point, so it is under the minimum of 2.
@@ -0,0 +1,786 @@
package io.floci.aws.services.securityhub;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.ServiceConfigAccess;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.securityhub.model.SecurityHubState;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class SecurityHubFindingsServiceTest {
private static final String ACCOUNT = "222222222222";
private static final String OTHER_ACCOUNT = "333333333333";
private static final String REGION = "us-east-1";
private static final String OTHER_REGION = "us-west-2";
private static final String CREATED_AT = "2026-11-06T10:00:00Z";
@TempDir
Path tempDir;
private final ObjectMapper objectMapper = new ObjectMapper();
private AccountAwareStorageBackend<Map<String, ObjectNode>> storage;
private SecurityHubFindingsService service;
private SecurityHubService hub;
@BeforeEach
void setUp() {
storage = AccountAwareStorageBackend.inMemory(ACCOUNT);
hub = mock(SecurityHubService.class);
SecurityHubState state = new SecurityHubState();
state.setEnabled(true);
when(hub.state(anyString())).thenReturn(state);
service = new SecurityHubFindingsService(storage, hub, new RegionResolver(REGION, ACCOUNT));
}
@Test
void importRoundTripsAsffAndAddsManagedDefaults() {
ObjectNode finding = finding("one", ACCOUNT, REGION);
finding.putObject("ProductFields").put("source", "test");
finding.put("Confidence", 80);
finding.put("Criticality", 70);
finding.putArray("RelatedFindings").addObject().put("Id", "related")
.put("ProductArn", productArn(ACCOUNT, REGION));
finding.putObject("Severity").put("Label", "MEDIUM");
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION, batch(finding));
assertEquals(1, result.successCount());
assertTrue(result.failedFindings().isEmpty());
ObjectNode read = onlyFinding(service, REGION);
assertEquals("FAILED", read.path("Compliance").path("Status").asText());
assertEquals("IAM.1", read.path("Compliance").path("SecurityControlId").asText());
assertEquals("MEDIUM", read.path("Severity").path("Label").asText());
assertEquals("MEDIUM", read.path("FindingProviderFields").path("Severity").path("Label").asText());
assertEquals(40, read.path("Severity").path("Normalized").asInt());
assertEquals(40, read.path("FindingProviderFields").path("Severity").path("Normalized").asInt());
assertEquals(read.path("Types"), read.path("FindingProviderFields").path("Types"));
assertEquals(80, read.path("FindingProviderFields").path("Confidence").asInt());
assertEquals(70, read.path("FindingProviderFields").path("Criticality").asInt());
assertEquals(read.path("RelatedFindings"), read.path("FindingProviderFields").path("RelatedFindings"));
assertEquals("test", read.path("ProductFields").path("source").asText());
assertEquals("Default", read.path("ProductName").asText());
assertEquals("Personal", read.path("CompanyName").asText());
assertEquals(REGION, read.path("Region").asText());
assertEquals("NEW", read.path("Workflow").path("Status").asText());
assertEquals("ACTIVE", read.path("RecordState").asText());
assertEquals("AwsIamRole", read.path("Resources").path(0).path("Type").asText());
}
@Test
void importedFindingSurvivesPersistentStoreRestart() {
StorageFactory firstFactory = persistentFactory();
SecurityHubFindingsService first = new SecurityHubFindingsService(firstFactory, hub,
new RegionResolver(REGION, ACCOUNT));
assertEquals(1, first.batchImportFindings(REGION, batch(finding("persisted", ACCOUNT, REGION)))
.successCount());
firstFactory.shutdownAll();
StorageFactory secondFactory = persistentFactory();
SecurityHubFindingsService reopened = new SecurityHubFindingsService(secondFactory, hub,
new RegionResolver(REGION, ACCOUNT));
assertEquals("persisted", onlyFinding(reopened, REGION).path("Id").asText());
secondFactory.shutdownAll();
}
@Test
void batchImportReportsItemFailuresWithoutStoringThem() {
ObjectNode wrongProduct = finding("wrong-product", ACCOUNT, REGION);
wrongProduct.put("ProductArn", productArn(OTHER_ACCOUNT, REGION));
ObjectNode wrongAccount = finding("wrong-account", ACCOUNT, REGION);
wrongAccount.put("AwsAccountId", OTHER_ACCOUNT);
ObjectNode missingTitle = finding("missing-title", ACCOUNT, REGION);
missingTitle.remove("Title");
ObjectNode oversized = finding("oversized", ACCOUNT, REGION);
oversized.putObject("ProductFields").put("payload", "x".repeat(240 * 1024));
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(finding("valid", ACCOUNT, REGION), wrongProduct, wrongAccount, missingTitle, oversized));
assertEquals(1, result.successCount());
assertEquals(4, result.failedFindings().size());
assertEquals(List.of("InvalidAccess", "InvalidAccess", "InvalidInput", "InvalidInput"),
result.failedFindings().stream().map(SecurityHubFindingsService.ImportFailure::errorCode).toList());
assertEquals("valid", onlyFinding(service, REGION).path("Id").asText());
}
@Test
void batchImportRejectsInvalidOptionalComplianceAndRecordStatePerItem() {
ObjectNode noCompliance = finding("no-compliance", ACCOUNT, REGION);
noCompliance.remove("Compliance");
ObjectNode malformedCompliance = finding("malformed-compliance", ACCOUNT, REGION);
malformedCompliance.put("Compliance", "bad");
ObjectNode invalidStatus = finding("invalid-status", ACCOUNT, REGION);
((ObjectNode) invalidStatus.path("Compliance")).put("Status", "BOGUS");
ObjectNode invalidRecordState = finding("invalid-record-state", ACCOUNT, REGION);
invalidRecordState.put("RecordState", "BOGUS");
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(finding("valid", ACCOUNT, REGION), noCompliance, malformedCompliance,
invalidStatus, invalidRecordState));
assertEquals(2, result.successCount());
assertEquals(List.of("malformed-compliance", "invalid-status", "invalid-record-state"),
result.failedFindings().stream().map(SecurityHubFindingsService.ImportFailure::id).toList());
assertTrue(result.failedFindings().stream().allMatch(failure -> "InvalidInput".equals(failure.errorCode())));
assertEquals(Set.of("valid", "no-compliance"), Set.copyOf(service.getFindings(REGION,
objectMapper.createObjectNode()).items().stream().map(item -> item.path("Id").asText()).toList()));
}
@Test
void findingProviderFieldsMustBeAnObjectWhenPresent() {
ObjectNode malformed = finding("malformed-provider", ACCOUNT, REGION);
malformed.put("FindingProviderFields", "bad");
ObjectNode nullProvider = finding("null-provider", ACCOUNT, REGION);
nullProvider.putNull("FindingProviderFields");
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(malformed, nullProvider));
assertEquals(0, result.successCount());
assertEquals(List.of("malformed-provider", "null-provider"),
result.failedFindings().stream().map(SecurityHubFindingsService.ImportFailure::id).toList());
assertTrue(result.failedFindings().stream().allMatch(failure -> "InvalidInput".equals(failure.errorCode())));
assertTrue(service.getFindings(REGION, objectMapper.createObjectNode()).items().isEmpty());
}
@Test
void customDefaultProductCanProvideAndUpdateNames() {
ObjectNode first = finding("default-product-name", ACCOUNT, REGION);
first.put("ProductName", "Caller product");
first.put("CompanyName", "Caller company");
assertEquals(1, service.batchImportFindings(REGION, batch(first)).successCount());
assertEquals("Caller product", onlyFinding(service, REGION).path("ProductName").asText());
assertEquals("Caller company", onlyFinding(service, REGION).path("CompanyName").asText());
ObjectNode updated = first.deepCopy();
updated.put("UpdatedAt", "2026-11-06T11:00:00Z");
updated.put("ProductName", "Renamed product");
updated.put("CompanyName", "Renamed company");
assertEquals(1, service.batchImportFindings(REGION, batch(updated)).successCount());
assertEquals("Renamed product", onlyFinding(service, REGION).path("ProductName").asText());
assertEquals("Renamed company", onlyFinding(service, REGION).path("CompanyName").asText());
ObjectNode withoutNames = first.deepCopy();
withoutNames.put("UpdatedAt", "2026-11-06T12:00:00Z");
withoutNames.remove("ProductName");
withoutNames.remove("CompanyName");
assertEquals(1, service.batchImportFindings(REGION, batch(withoutNames)).successCount());
assertEquals("Renamed product", onlyFinding(service, REGION).path("ProductName").asText());
assertEquals("Renamed company", onlyFinding(service, REGION).path("CompanyName").asText());
}
@Test
void productAndCompanyNamesMustBeNonemptyAndAtMost128Characters() {
ObjectNode emptyProduct = finding("empty-product-name", ACCOUNT, REGION);
emptyProduct.put("ProductName", "");
ObjectNode longProduct = finding("long-product-name", ACCOUNT, REGION);
longProduct.put("ProductName", "x".repeat(129));
ObjectNode emptyCompany = finding("empty-company-name", ACCOUNT, REGION);
emptyCompany.put("CompanyName", " ");
ObjectNode longCompany = finding("long-company-name", ACCOUNT, REGION);
longCompany.put("CompanyName", "x".repeat(129));
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(emptyProduct, longProduct, emptyCompany, longCompany));
assertEquals(0, result.successCount());
assertEquals(List.of("empty-product-name", "long-product-name", "empty-company-name", "long-company-name"),
result.failedFindings().stream().map(SecurityHubFindingsService.ImportFailure::id).toList());
assertTrue(result.failedFindings().stream().allMatch(failure -> "InvalidInput".equals(failure.errorCode())));
assertTrue(service.getFindings(REGION, objectMapper.createObjectNode()).items().isEmpty());
}
@Test
void batchShapeAndRequiredResourceFieldsAreValidated() {
for (ObjectNode request : List.of(objectMapper.createObjectNode(), batch(),
batchWithCount(101))) {
AwsException error = assertThrows(AwsException.class,
() -> service.batchImportFindings(REGION, request));
assertEquals("InvalidInputException", error.getErrorCode());
}
ObjectNode missingResourceId = finding("bad-resource", ACCOUNT, REGION);
((ObjectNode) missingResourceId.path("Resources").path(0)).remove("Id");
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(missingResourceId));
assertEquals(0, result.successCount());
assertEquals("InvalidInput", result.failedFindings().getFirst().errorCode());
assertTrue(service.getFindings(REGION, objectMapper.createObjectNode()).items().isEmpty());
}
@Test
void vendoredShapeChecksRequiredFindingAndResourceMembers() {
ObjectNode valid = finding("valid", ACCOUNT, REGION);
for (String field : List.of("SchemaVersion", "Id", "ProductArn", "GeneratorId",
"AwsAccountId", "CreatedAt", "UpdatedAt", "Title", "Description", "Resources")) {
ObjectNode missing = valid.deepCopy();
missing.remove(field);
AwsException error = assertThrows(AwsException.class,
() -> SecurityHubRequestShapes.checkFinding(missing), field);
assertTrue(error.getMessage().contains("." + field + " is required."), field);
}
ObjectNode blankTitle = valid.deepCopy();
blankTitle.put("Title", " \t");
assertTrue(assertThrows(AwsException.class,
() -> SecurityHubRequestShapes.checkFinding(blankTitle)).getMessage().contains(".Title"));
for (String field : List.of("Type", "Id")) {
ObjectNode missing = valid.deepCopy();
((ObjectNode) missing.path("Resources").get(0)).remove(field);
AwsException error = assertThrows(AwsException.class,
() -> SecurityHubRequestShapes.checkFinding(missing), field);
assertTrue(error.getMessage().contains(".Resources[]." + field + " is required."), field);
}
ObjectNode blankResourceId = valid.deepCopy();
((ObjectNode) blankResourceId.path("Resources").get(0)).put("Id", " ");
assertTrue(assertThrows(AwsException.class,
() -> SecurityHubRequestShapes.checkFinding(blankResourceId))
.getMessage().contains(".Resources[].Id"));
}
@Test
void batchImportAcceptsMultilineTitleAndDescriptionButRejectsWhitespaceOnlyText() {
ObjectNode multilineTitle = finding("multiline-title", ACCOUNT, REGION);
multilineTitle.put("Title", "First line\nSecond line");
ObjectNode multilineDescription = finding("multiline-description", ACCOUNT, REGION);
multilineDescription.put("Description", "First line\nSecond line");
ObjectNode oneCharacterTitle = finding("one-character-title", ACCOUNT, REGION);
oneCharacterTitle.put("Title", "\nX\n");
ObjectNode oneCharacterDescription = finding("one-character-description", ACCOUNT, REGION);
oneCharacterDescription.put("Description", "\nY\n");
ObjectNode blankDescription = finding("blank-description", ACCOUNT, REGION);
blankDescription.put("Description", " \n\t ");
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(multilineTitle, multilineDescription, oneCharacterTitle, oneCharacterDescription,
blankDescription));
assertEquals(4, result.successCount());
assertEquals(List.of("blank-description"),
result.failedFindings().stream().map(SecurityHubFindingsService.ImportFailure::id).toList());
assertEquals("InvalidInput", result.failedFindings().getFirst().errorCode());
assertEquals(Set.of("multiline-title", "multiline-description", "one-character-title",
"one-character-description"), Set.copyOf(service.getFindings(REGION,
objectMapper.createObjectNode()).items().stream().map(item -> item.path("Id").asText()).toList()));
}
@Test
void reimportPreservesInvestigationFieldsAndSameBatchDuplicateUsesFirst() {
ObjectNode original = finding("one", ACCOUNT, REGION);
original.put("Title", "first");
original.putObject("Workflow").put("Status", "NOTIFIED");
original.putObject("Note").put("Text", "investigating").put("UpdatedBy", "analyst")
.put("UpdatedAt", CREATED_AT);
original.putObject("UserDefinedFields").put("reviewedBy", "analyst");
original.put("VerificationState", "UNKNOWN");
service.batchImportFindings(REGION, batch(original));
assertEquals("NEW", onlyFinding(service, REGION).path("Workflow").path("Status").asText());
assertEquals("investigating", onlyFinding(service, REGION).path("Note").path("Text").asText());
assertEquals("analyst", onlyFinding(service, REGION).path("UserDefinedFields").path("reviewedBy").asText());
assertEquals("UNKNOWN", onlyFinding(service, REGION).path("VerificationState").asText());
storage.getForAccount(ACCOUNT, REGION).orElseThrow().values().iterator().next()
.putObject("Workflow").put("Status", "NOTIFIED");
ObjectNode updated = finding("one", ACCOUNT, REGION);
updated.put("Title", "updated");
updated.put("UpdatedAt", "2026-11-06T11:00:00Z");
updated.putObject("Workflow").put("Status", "RESOLVED");
updated.putObject("Note").put("Text", "provider overwrite");
updated.putObject("UserDefinedFields").put("reviewedBy", "provider overwrite");
updated.put("VerificationState", "BOGUS");
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION, batch(updated));
assertEquals(1, result.successCount());
ObjectNode read = onlyFinding(service, REGION);
assertEquals("updated", read.path("Title").asText());
assertEquals("NOTIFIED", read.path("Workflow").path("Status").asText());
assertEquals("investigating", read.path("Note").path("Text").asText());
assertEquals("analyst", read.path("UserDefinedFields").path("reviewedBy").asText());
assertEquals("UNKNOWN", read.path("VerificationState").asText());
ObjectNode duplicate = finding("one", ACCOUNT, REGION);
duplicate.put("Title", "ignored second item");
ObjectNode firstInBatch = finding("one", ACCOUNT, REGION);
firstInBatch.put("Title", "first in batch");
firstInBatch.put("UpdatedAt", "2026-11-06T12:00:00Z");
duplicate.put("UpdatedAt", "2026-11-06T13:00:00Z");
SecurityHubFindingsService.ImportResult duplicates = service.batchImportFindings(REGION,
batch(firstInBatch, duplicate));
assertEquals(2, duplicates.successCount());
assertEquals("first in batch", onlyFinding(service, REGION).path("Title").asText());
}
@Test
void firstImportRejectsInvalidVerificationState() {
ObjectNode invalid = finding("invalid-verification", ACCOUNT, REGION);
invalid.put("VerificationState", "BOGUS");
ObjectNode nullValue = finding("null-verification", ACCOUNT, REGION);
nullValue.putNull("VerificationState");
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION, batch(invalid, nullValue));
assertEquals(0, result.successCount());
assertEquals(2, result.failedFindings().size());
assertTrue(result.failedFindings().stream().allMatch(failure -> "InvalidInput".equals(failure.errorCode())));
assertTrue(service.getFindings(REGION, objectMapper.createObjectNode()).items().isEmpty());
}
@Test
void providerFieldsPopulateTopLevelValuesAndCustomNamesCanChange() {
ObjectNode first = finding("one", ACCOUNT, REGION);
first.remove("Severity");
first.remove("Types");
first.put("Region", OTHER_REGION);
first.put("ProductName", "My Product");
first.put("CompanyName", "My Company");
ObjectNode providerFields = first.putObject("FindingProviderFields");
providerFields.putObject("Severity").put("Label", "HIGH");
providerFields.putArray("Types").add("Software and Configuration Checks/Vulnerabilities/CVE");
assertEquals(1, service.batchImportFindings(REGION, batch(first)).successCount());
ObjectNode read = onlyFinding(service, REGION);
assertEquals("HIGH", read.path("Severity").path("Label").asText());
assertEquals("Software and Configuration Checks/Vulnerabilities/CVE", read.path("Types").path(0).asText());
assertEquals(REGION, read.path("Region").asText());
ObjectNode updated = first.deepCopy();
updated.put("UpdatedAt", "2026-11-06T11:00:00Z");
updated.put("ProductName", "Renamed Product");
updated.put("CompanyName", "Renamed Company");
assertEquals(1, service.batchImportFindings(REGION, batch(updated)).successCount());
read = onlyFinding(service, REGION);
assertEquals("Renamed Product", read.path("ProductName").asText());
assertEquals("Renamed Company", read.path("CompanyName").asText());
assertEquals(REGION, read.path("Region").asText());
}
@Test
void reimportTopLevelProviderFieldsUpdatesBothRepresentations() {
ObjectNode first = finding("top-level-update", ACCOUNT, REGION);
assertEquals(1, service.batchImportFindings(REGION, batch(first)).successCount());
ObjectNode updated = first.deepCopy();
updated.put("UpdatedAt", "2026-11-06T11:00:00Z");
updated.putObject("Severity").put("Label", "HIGH");
updated.putArray("Types").add("Software and Configuration Checks/Vulnerabilities/CVE");
assertEquals(1, service.batchImportFindings(REGION, batch(updated)).successCount());
ObjectNode read = onlyFinding(service, REGION);
assertEquals("HIGH", read.path("Severity").path("Label").asText());
assertEquals("HIGH", read.path("FindingProviderFields").path("Severity").path("Label").asText());
assertEquals(read.path("Types"), read.path("FindingProviderFields").path("Types"));
}
@Test
void firstImportUsesProviderValuesWhenBothRepresentationsAreSupplied() {
ObjectNode first = finding("dual-first-import", ACCOUNT, REGION);
first.putObject("Severity").put("Label", "LOW");
first.putArray("Types").add("top-level/type");
ObjectNode provider = first.putObject("FindingProviderFields");
provider.putObject("Severity").put("Label", "HIGH");
provider.putArray("Types").add("provider/type");
assertEquals(1, service.batchImportFindings(REGION, batch(first)).successCount());
ObjectNode read = onlyFinding(service, REGION);
assertEquals("HIGH", read.path("Severity").path("Label").asText());
assertEquals("HIGH", read.path("FindingProviderFields").path("Severity").path("Label").asText());
assertEquals("provider/type", read.path("Types").path(0).asText());
assertEquals("provider/type", read.path("FindingProviderFields").path("Types").path(0).asText());
}
@Test
void reimportKeepsDistinctTopLevelAndProviderValuesWhenBothAreSupplied() {
ObjectNode first = finding("dual-update", ACCOUNT, REGION);
assertEquals(1, service.batchImportFindings(REGION, batch(first)).successCount());
ObjectNode updated = first.deepCopy();
updated.put("UpdatedAt", "2026-11-06T11:00:00Z");
updated.putObject("Severity").put("Label", "LOW");
updated.putObject("FindingProviderFields").putObject("Severity").put("Label", "CRITICAL");
assertEquals(1, service.batchImportFindings(REGION, batch(updated)).successCount());
ObjectNode read = onlyFinding(service, REGION);
assertEquals("LOW", read.path("Severity").path("Label").asText());
assertEquals("CRITICAL", read.path("FindingProviderFields").path("Severity").path("Label").asText());
}
@Test
void distinctTopLevelAndProviderFieldsAreBothValidated() {
ObjectNode invalidTopLevelSeverity = finding("invalid-top-level-severity", ACCOUNT, REGION);
((ObjectNode) invalidTopLevelSeverity.path("Severity")).put("Label", "BOGUS");
invalidTopLevelSeverity.putObject("FindingProviderFields").putObject("Severity").put("Label", "LOW");
ObjectNode invalidTopLevelTypes = finding("invalid-top-level-types", ACCOUNT, REGION);
invalidTopLevelTypes.putArray("Types").add(" ");
invalidTopLevelTypes.putObject("FindingProviderFields").putArray("Types").add("valid/type");
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(invalidTopLevelSeverity, invalidTopLevelTypes));
assertEquals(0, result.successCount());
assertEquals(List.of("invalid-top-level-severity", "invalid-top-level-types"),
result.failedFindings().stream().map(SecurityHubFindingsService.ImportFailure::id).toList());
assertTrue(service.getFindings(REGION, objectMapper.createObjectNode()).items().isEmpty());
}
@Test
void staleAndEqualTimestampUpdatesAreIgnored() {
ObjectNode first = finding("one", ACCOUNT, REGION);
first.put("Title", "original");
service.batchImportFindings(REGION, batch(first));
ObjectNode equal = first.deepCopy();
equal.put("Title", "equal timestamp");
ObjectNode older = first.deepCopy();
older.put("Title", "older timestamp");
older.put("UpdatedAt", "2026-11-06T09:00:00Z");
assertEquals(1, service.batchImportFindings(REGION, batch(equal)).successCount());
assertEquals(1, service.batchImportFindings(REGION, batch(older)).successCount());
assertEquals("original", onlyFinding(service, REGION).path("Title").asText());
}
@Test
void firstImportAcceptsFindingUpdatedAfterItWasCreated() {
ObjectNode updatedBeforeImport = finding("updated-before-import", ACCOUNT, REGION);
updatedBeforeImport.put("UpdatedAt", "2026-11-06T11:00:00Z");
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(updatedBeforeImport));
assertEquals(1, result.successCount());
assertTrue(result.failedFindings().isEmpty());
assertEquals("2026-11-06T11:00:00Z", onlyFinding(service, REGION).path("UpdatedAt").asText());
}
@Test
void malformedPresentSeverityAndTypesAreRejected() {
ObjectNode malformedSeverity = finding("malformed-severity", ACCOUNT, REGION);
malformedSeverity.put("Severity", "bad");
ObjectNode invalidSeverityLabel = finding("invalid-severity-label", ACCOUNT, REGION);
((ObjectNode) invalidSeverityLabel.path("Severity")).put("Label", "BOGUS");
ObjectNode emptySeverity = finding("empty-severity", ACCOUNT, REGION);
emptySeverity.putObject("Severity");
ObjectNode outOfRangeSeverity = finding("out-of-range-severity", ACCOUNT, REGION);
outOfRangeSeverity.putObject("Severity").put("Normalized", 101);
ObjectNode overflowSeverity = finding("overflow-severity", ACCOUNT, REGION);
overflowSeverity.putObject("Severity").put("Normalized", 4_294_967_336L);
ObjectNode malformedTypes = finding("malformed-types", ACCOUNT, REGION);
malformedTypes.put("Types", "bad");
ObjectNode invalidType = finding("invalid-type", ACCOUNT, REGION);
invalidType.putArray("Types").add(" ");
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(malformedSeverity, invalidSeverityLabel, emptySeverity, outOfRangeSeverity,
overflowSeverity, malformedTypes, invalidType));
assertEquals(0, result.successCount());
assertEquals(7, result.failedFindings().size());
assertTrue(result.failedFindings().stream().allMatch(error -> "InvalidInput".equals(error.errorCode())));
assertTrue(service.getFindings(REGION, objectMapper.createObjectNode()).items().isEmpty());
}
@Test
void providerConfidenceAndCriticalityUseModeledBoundsPerFinding() {
ObjectNode highConfidence = finding("high-confidence", ACCOUNT, REGION);
highConfidence.putObject("FindingProviderFields").put("Confidence", 101);
ObjectNode negativeCriticality = finding("negative-criticality", ACCOUNT, REGION);
negativeCriticality.putObject("FindingProviderFields").put("Criticality", -1);
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(finding("valid", ACCOUNT, REGION), highConfidence, negativeCriticality));
assertEquals(1, result.successCount());
assertEquals(2, result.failedFindings().size());
assertTrue(result.failedFindings().stream().allMatch(error -> "InvalidInput".equals(error.errorCode())));
assertEquals("valid", onlyFinding(service, REGION).path("Id").asText());
}
@Test
void malformedProductAndRelatedFieldsFailOnlyTheirFinding() {
ObjectNode badProduct = finding("bad-product-fields", ACCOUNT, REGION);
badProduct.put("ProductFields", "bad");
ObjectNode badRelated = finding("bad-related-findings", ACCOUNT, REGION);
badRelated.put("RelatedFindings", "bad");
ObjectNode badProviderRelated = finding("bad-provider-related", ACCOUNT, REGION);
badProviderRelated.putObject("FindingProviderFields").put("RelatedFindings", "bad");
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(finding("valid", ACCOUNT, REGION), badProduct, badRelated, badProviderRelated));
assertEquals(1, result.successCount());
assertEquals(List.of("bad-product-fields", "bad-related-findings", "bad-provider-related"),
result.failedFindings().stream().map(SecurityHubFindingsService.ImportFailure::id).toList());
assertTrue(result.failedFindings().stream().allMatch(error -> "InvalidInput".equals(error.errorCode())));
assertEquals("valid", onlyFinding(service, REGION).path("Id").asText());
}
@Test
void optionalSeverityAndTypesCanBeOmittedWithoutLosingOtherFindingFields() {
ObjectNode sparse = finding("sparse", ACCOUNT, REGION);
sparse.remove("Severity");
sparse.remove("Types");
ObjectNode normalizedOnly = finding("normalized-only", ACCOUNT, REGION);
((ObjectNode) normalizedOnly.path("Severity")).remove("Label");
((ObjectNode) normalizedOnly.path("Severity")).put("Normalized", 50);
normalizedOnly.remove("Types");
ObjectNode providerOnly = finding("provider-only", ACCOUNT, REGION);
providerOnly.remove("Severity");
providerOnly.remove("Types");
providerOnly.putObject("FindingProviderFields").putObject("Severity").put("Normalized", 60);
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(sparse, normalizedOnly, providerOnly));
assertEquals(3, result.successCount());
assertTrue(result.failedFindings().isEmpty());
List<ObjectNode> imported = service.getFindings(REGION, objectMapper.createObjectNode()).items();
assertEquals(3, imported.size());
assertTrue(imported.stream().filter(item -> "sparse".equals(item.path("Id").asText()))
.allMatch(item -> !item.has("Severity") && !item.has("Types")));
assertEquals(60, imported.stream().filter(item -> "provider-only".equals(item.path("Id").asText()))
.findFirst().orElseThrow().path("Severity").path("Normalized").asInt());
assertEquals("MEDIUM", imported.stream().filter(item -> "normalized-only".equals(item.path("Id").asText()))
.findFirst().orElseThrow().path("Severity").path("Label").asText());
}
@Test
void disabledHubReturnsPerFindingInvalidAccess() {
when(hub.state(anyString())).thenReturn(new SecurityHubState());
SecurityHubFindingsService.ImportResult result = service.batchImportFindings(REGION,
batch(finding("one", ACCOUNT, REGION), finding("two", ACCOUNT, REGION)));
assertEquals(0, result.successCount());
assertEquals(2, result.failedFindings().size());
assertTrue(result.failedFindings().stream().allMatch(error -> "InvalidAccess".equals(error.errorCode())));
assertEquals("InvalidAccessException", assertThrows(AwsException.class,
() -> service.getFindings(REGION, objectMapper.createObjectNode())).getErrorCode());
}
@Test
void supportedFiltersReadNestedValuesAndCombineFieldsWithAnd() {
ObjectNode first = finding("first", ACCOUNT, REGION);
ObjectNode second = finding("second", ACCOUNT, REGION);
second.put("RecordState", "ARCHIVED");
((ObjectNode) second.path("Compliance")).put("Status", "PASSED");
((ObjectNode) second.path("Compliance")).put("SecurityControlId", "EC2.1");
((ObjectNode) second.path("Compliance").path("AssociatedStandards").path(0))
.put("StandardsId", "standards/other/v/1.0.0");
service.batchImportFindings(REGION, batch(first, second));
Map<String, String> singleMatch = Map.of(
"ComplianceAssociatedStandardsId", "standards/cis-aws-foundations-benchmark/v/5.0.0",
"RecordState", "ACTIVE", "ComplianceStatus", "FAILED",
"ComplianceSecurityControlId", "IAM.1");
for (Map.Entry<String, String> filter : singleMatch.entrySet()) {
assertEquals("first", findWithFilter(filter.getKey(), filter.getValue()).getFirst().path("Id").asText(),
filter.getKey());
}
Map<String, String> bothMatch = Map.of("ProductArn", productArn(ACCOUNT, REGION),
"AwsAccountId", ACCOUNT, "Region", REGION, "WorkflowStatus", "NEW");
for (Map.Entry<String, String> filter : bothMatch.entrySet()) {
assertEquals(2, findWithFilter(filter.getKey(), filter.getValue()).size(), filter.getKey());
}
ObjectNode filters = objectMapper.createObjectNode();
filters.set("ComplianceStatus", predicates("FAILED", "EQUALS"));
filters.set("RecordState", predicates("ARCHIVED", "EQUALS"));
assertTrue(service.getFindings(REGION, query(filters, null, null)).items().isEmpty());
}
@Test
void positivePredicatesAreOrAndNegativePredicatesAreAnd() {
ObjectNode first = finding("first", ACCOUNT, REGION);
ObjectNode second = finding("second", ACCOUNT, REGION);
second.put("RecordState", "ARCHIVED");
service.batchImportFindings(REGION, batch(first, second));
ObjectNode filters = objectMapper.createObjectNode();
ArrayNode states = filters.putArray("RecordState");
states.add(predicate("ACTIVE", "EQUALS"));
states.add(predicate("ARCHIVED", "EQUALS"));
assertEquals(2, service.getFindings(REGION, query(filters, null, null)).items().size());
states.removeAll();
states.add(predicate("ACTIVE", "NOT_EQUALS"));
states.add(predicate("ARCHIVED", "NOT_EQUALS"));
assertTrue(service.getFindings(REGION, query(filters, null, null)).items().isEmpty());
states.removeAll();
states.add(predicate("A", "PREFIX"));
states.add(predicate("ARCHIVED", "NOT_EQUALS"));
assertEquals("first", service.getFindings(REGION, query(filters, null, null))
.items().getFirst().path("Id").asText());
states.removeAll();
states.add(predicate("ACTIVE", "EQUALS"));
states.add(predicate("ARCHIVED", "NOT_EQUALS"));
assertEquals("InvalidInputException", assertThrows(AwsException.class,
() -> service.getFindings(REGION, query(filters, null, null))).getErrorCode());
}
@Test
void paginationTokenIsScopedToAccountRegionAndFilters() {
service.batchImportFindings(REGION, batch(finding("one", ACCOUNT, REGION),
finding("two", ACCOUNT, REGION), finding("three", ACCOUNT, REGION)));
ObjectNode request = query(null, 1, null);
PaginatedResult<ObjectNode> first = service.getFindings(REGION, request);
assertEquals(1, first.items().size());
assertNotNull(first.nextToken());
Set<String> ids = new HashSet<>();
ids.add(first.items().getFirst().path("Id").asText());
String token = first.nextToken();
while (token != null) {
PaginatedResult<ObjectNode> page = service.getFindings(REGION, query(null, 1, token));
ids.add(page.items().getFirst().path("Id").asText());
token = page.nextToken();
}
assertEquals(Set.of("one", "two", "three"), ids);
assertEquals("InvalidInputException", assertThrows(AwsException.class,
() -> service.getFindings(OTHER_REGION, query(null, 1, first.nextToken()))).getErrorCode());
ObjectNode differentFilter = objectMapper.createObjectNode();
differentFilter.set("RecordState", predicates("ACTIVE", "EQUALS"));
assertEquals("InvalidInputException", assertThrows(AwsException.class,
() -> service.getFindings(REGION, query(differentFilter, 1, first.nextToken()))).getErrorCode());
SecurityHubFindingsService other = new SecurityHubFindingsService(storage, hub,
new RegionResolver(REGION, OTHER_ACCOUNT));
assertTrue(other.getFindings(REGION, objectMapper.createObjectNode()).items().isEmpty());
assertEquals("InvalidInputException", assertThrows(AwsException.class,
() -> other.getFindings(REGION, query(null, 1, first.nextToken()))).getErrorCode());
}
@Test
void invalidGetOptionsAndDisabledHubAreRejected() {
for (int size : List.of(0, 101)) {
assertEquals("InvalidInputException", assertThrows(AwsException.class,
() -> service.getFindings(REGION, query(null, size, null))).getErrorCode());
}
ObjectNode sort = objectMapper.createObjectNode();
sort.putArray("SortCriteria");
assertEquals("InvalidInputException", assertThrows(AwsException.class,
() -> service.getFindings(REGION, sort)).getErrorCode());
ObjectNode unsupported = objectMapper.createObjectNode();
unsupported.set("Title", predicates("title", "EQUALS"));
assertEquals("InvalidInputException", assertThrows(AwsException.class,
() -> service.getFindings(REGION, query(unsupported, null, null))).getErrorCode());
SecurityHubState disabled = new SecurityHubState();
when(hub.state(anyString())).thenReturn(disabled);
assertEquals("InvalidAccessException", assertThrows(AwsException.class,
() -> service.getFindings(REGION, objectMapper.createObjectNode())).getErrorCode());
}
private List<ObjectNode> findWithFilter(String field, String value) {
ObjectNode filters = objectMapper.createObjectNode();
filters.set(field, predicates(value, "EQUALS"));
return service.getFindings(REGION, query(filters, null, null)).items();
}
private ObjectNode finding(String id, String account, String region) {
ObjectNode finding = objectMapper.createObjectNode();
finding.put("SchemaVersion", "2018-10-08");
finding.put("Id", id);
finding.put("ProductArn", productArn(account, region));
finding.put("GeneratorId", "securityhub-test");
finding.put("AwsAccountId", account);
finding.put("CreatedAt", CREATED_AT);
finding.put("UpdatedAt", CREATED_AT);
finding.put("Title", "Control finding " + id);
finding.put("Description", "Finding imported by unit test");
finding.putArray("Types").add("Software and Configuration Checks/Industry and Regulatory Standards");
finding.putObject("Severity").put("Label", "MEDIUM");
finding.putArray("Resources").addObject().put("Type", "AwsIamRole")
.put("Id", "role/securityhub-test");
ObjectNode compliance = finding.putObject("Compliance");
compliance.put("Status", "FAILED");
compliance.put("SecurityControlId", "IAM.1");
compliance.putArray("AssociatedStandards").addObject()
.put("StandardsId", "standards/cis-aws-foundations-benchmark/v/5.0.0");
return finding;
}
private static String productArn(String account, String region) {
return "arn:aws:securityhub:" + region + ":" + account + ":product/" + account + "/default";
}
private StorageFactory persistentFactory() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
when(config.storage().persistentPath()).thenReturn(tempDir.toString());
ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class);
when(serviceConfigAccess.storageMode(anyString())).thenReturn("persistent");
return new StorageFactory(config, serviceConfigAccess);
}
private ObjectNode batch(ObjectNode... items) {
ObjectNode request = objectMapper.createObjectNode();
ArrayNode findings = request.putArray("Findings");
for (ObjectNode item : items) {
findings.add(item);
}
return request;
}
private ObjectNode batchWithCount(int count) {
ObjectNode request = objectMapper.createObjectNode();
ArrayNode findings = request.putArray("Findings");
for (int index = 0; index < count; index++) {
findings.add(finding("finding-" + index, ACCOUNT, REGION));
}
return request;
}
private ObjectNode query(ObjectNode filters, Integer maxResults, String nextToken) {
ObjectNode request = objectMapper.createObjectNode();
if (filters != null) {
request.set("Filters", filters);
}
if (maxResults != null) {
request.put("MaxResults", maxResults);
}
if (nextToken != null) {
request.put("NextToken", nextToken);
}
return request;
}
private ArrayNode predicates(String value, String comparison) {
ArrayNode predicates = objectMapper.createArrayNode();
predicates.add(predicate(value, comparison));
return predicates;
}
private ObjectNode predicate(String value, String comparison) {
return objectMapper.createObjectNode().put("Value", value).put("Comparison", comparison);
}
private static ObjectNode onlyFinding(SecurityHubFindingsService service, String region) {
List<ObjectNode> found = service.getFindings(region, new ObjectMapper().createObjectNode()).items();
assertEquals(1, found.size());
return found.getFirst();
}
}
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""Vendor the Security Hub request constraints used by findings import and retrieval."""
from __future__ import annotations
from pathlib import Path
import request_shapes
MODEL = Path("securityhub/2018-10-26")
OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/securityhub-request-shapes.json"
OPERATIONS = ("BatchImportFindings", "GetFindings")
# Keep the model fields this service validates. Other ASFF fields have separate checks or are
# preserved without interpretation; walking the entire model would reject unrelated content.
MEMBERS = {
"AwsSecurityFinding": ("SchemaVersion", "Id", "ProductArn", "ProductName", "CompanyName",
"GeneratorId", "AwsAccountId", "Types", "CreatedAt", "UpdatedAt",
"Title", "Description", "Resources", "VerificationState", "RecordState",
"Compliance", "Severity", "FindingProviderFields", "ProductFields",
"RelatedFindings"),
"Resource": ("Type", "Id"),
"Compliance": ("Status",),
"Severity": ("Label",),
"FindingProviderFields": ("Confidence", "Criticality", "Severity", "RelatedFindings", "Types"),
"FindingProviderSeverity": ("Label",),
"GetFindingsRequest": ("Filters", "MaxResults"),
"AwsSecurityFindingFilters": ("ComplianceAssociatedStandardsId", "RecordState",
"WorkflowStatus", "ComplianceStatus", "ComplianceSecurityControlId",
"ProductArn", "AwsAccountId", "Region"),
"StringFilter": ("Value", "Comparison"),
}
def prepare(model: dict) -> dict:
for name, included in MEMBERS.items():
shape = model["shapes"][name]
members = shape["members"]
shape["members"] = {field: members[field] for field in included}
return model
def main(argv: list[str] | None = None) -> int:
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
description=__doc__, operations=OPERATIONS, prepare=prepare)
if __name__ == "__main__":
raise SystemExit(main())
+38
View File
@@ -27,6 +27,7 @@ import regen_iam_shapes
import regen_payment_cryptography_shapes
import regen_logs_delivery_shapes
import regen_resource_groups_shapes
import regen_securityhub_shapes
import regen_sesv2_shapes
import regen_sts_shapes
import request_shapes as r
@@ -336,6 +337,8 @@ def test_build_constraints_output_is_stable():
(regen_iam_shapes, "iam/2010-05-08", "iam-request-shapes.json",
{"prepare": regen_iam_shapes.prepare}),
(regen_sts_shapes, "sts/2011-06-15", "sts-request-shapes.json", {}),
(regen_securityhub_shapes, "securityhub/2018-10-26", "securityhub-request-shapes.json",
{"prepare": regen_securityhub_shapes.prepare}),
])
def test_each_constraints_script_runs_the_shared_main_with_its_operations(script, model, output, extra,
monkeypatch):
@@ -362,6 +365,7 @@ def vendored(script) -> tuple[str, ...]:
regen_apigateway_documentation_shapes, regen_ecr_shapes, regen_iam_shapes, regen_logs_delivery_shapes,
regen_payment_cryptography_shapes,
regen_resource_groups_shapes, regen_sts_shapes,
regen_securityhub_shapes,
])
def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_shapes(script):
doc = json.loads(script.OUTPUT.read_text(encoding="utf-8"))
@@ -376,6 +380,40 @@ def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_
assert child in doc["shapes"], f"{name} names {child}"
def test_securityhub_shapes_keep_modelled_findings_and_filter_constraints():
doc = json.loads(regen_securityhub_shapes.OUTPUT.read_text(encoding="utf-8"))
shapes = doc["shapes"]
assert shapes["BatchImportFindingsRequestFindingList"]["min"] == 1
assert shapes["BatchImportFindingsRequestFindingList"]["max"] == 100
assert shapes["MaxResults"]["min"] == 1
assert shapes["MaxResults"]["max"] == 100
assert shapes["RatioScale"]["min"] == 0
assert shapes["RatioScale"]["max"] == 100
assert shapes["VerificationState"]["enum"] == ["UNKNOWN", "TRUE_POSITIVE", "FALSE_POSITIVE",
"BENIGN_POSITIVE"]
assert shapes["RecordState"]["enum"] == ["ACTIVE", "ARCHIVED"]
assert "CONTAINS" in shapes["StringFilterComparison"]["enum"]
assert shapes["AwsSecurityFinding"]["members"]["ProductFields"] == "FieldMap"
assert shapes["FindingProviderFields"]["members"]["RelatedFindings"] == "RelatedFindingList"
assert shapes["RelatedFinding"]["required"] == ["ProductArn", "Id"]
assert "Double" not in shapes
def test_securityhub_shapes_keep_required_findings_and_resource_strings():
doc = json.loads(regen_securityhub_shapes.OUTPUT.read_text(encoding="utf-8"))
shapes = doc["shapes"]
required = shapes["AwsSecurityFinding"]["required"]
assert required == ["SchemaVersion", "Id", "ProductArn", "GeneratorId", "AwsAccountId",
"CreatedAt", "UpdatedAt", "Title", "Description", "Resources"]
for field in required:
assert field in shapes["AwsSecurityFinding"]["members"]
assert shapes["Resource"]["required"] == ["Type", "Id"]
assert shapes["Resource"]["members"] == {"Type": "NonEmptyString", "Id": "NonEmptyString"}
assert shapes["ResourceList"]["member"] == "Resource"
assert shapes["NonEmptyString"]["pattern"] == r".*\S.*"
def test_apigateway_documentation_shapes_keep_path_query_and_body_constraints():
doc = json.loads(regen_apigateway_documentation_shapes.OUTPUT.read_text(encoding="utf-8"))
shapes = doc["shapes"]