mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(guardduty): add Malware Protection plans and AWS::GuardDuty::MalwareProtectionPlan (#5373)
* feat(guardduty): add Malware Protection plans and AWS::GuardDuty::MalwareProtectionPlan Adds CreateMalwareProtectionPlan, GetMalwareProtectionPlan, UpdateMalwareProtectionPlan, DeleteMalwareProtectionPlan and ListMalwareProtectionPlans, and routes plan ARNs through the shared tag operations. Adds a CloudFormation provisioner for AWS::GuardDuty::MalwareProtectionPlan. Ref and Fn::GetAtt MalwareProtectionPlanId return the plan id, and Arn, CreatedAt, Status and StatusReasons are set. Role, object prefixes, the tagging action and tags update in place; a different BucketName is rejected because the update API cannot change the bucket. Management plane only: no scan runs, so a plan stays ACTIVE. Closes #4657 * fix(guardduty): address review findings on Malware Protection plans - Apply a plan update all-or-nothing: validate every supplied field before storing any, so a rejected request no longer changes the role. - Page ListMalwareProtectionPlans by the last returned id instead of an offset, so deleting a plan between pages neither fails nor skips, and use the documented default page size of 100. - Restore a plan on a failed CloudFormation stack update from a snapshot taken before the first change, and delete a plan an update created in place of one deleted out of band. - Clear ObjectPrefixes and Actions on a stack update that drops them. - Apply the creation tag rules to the shared tag routes. - Require the role to be an IAM role ARN. - Use explicit types instead of var. * style(guardduty): import ArrayList instead of fully qualified name * test(cloudformation): wire GuardDuty into CfnProvisionerFixture CfnProvisionerFixtureTest requires every provisioner to be reachable through a public Builder setter. Add a guardDuty(...) setter that registers GuardDutyMalwareProtectionPlanCfnProvisioner. * fix(guardduty): address second review round on Malware Protection plans - Rolling back a stack update that recreated a plan deleted out of band now restores the prior plan's Arn, CreatedAt, Status and StatusReasons, not only its id, so Fn::GetAtt no longer names the deleted replacement. The out-of-band test now changes the plan's properties: unchanged resources are skipped on update, so it never reached the create before. - Plan tag keys are checked against GuardDuty's documented TagKey pattern (^(?!aws:)[a-zA-Z+-=._:/]+$) on creation and on TagResource. - The tag routes require the supplied ARN to equal the stored plan's ARN, so a matching plan id under another account, service or partition is ResourceNotFoundException. - The /malware-protection-plan routes move behind a @PreMatching filter that rewrites only guardduty-signed requests to /_guardduty, as DlmRouteFilter does, so path-style S3 requests for a bucket of that name reach S3. * style(guardduty): import Instant and List, drop em-dash, document the plan route Review on #5373: GuardDutyController used an inline java.time.Instant and its Javadoc carried an em-dash, which AGENTS.md rules out. The Javadoc's routing paragraph now names /malware-protection-plan next to /detector and /admin and says GuardDutyRouteFilter keeps a same-named S3 bucket reachable. The CloudFormation and plan integration tests import List and nullValue instead of spelling them out. * refactor(core): share signed-service route rewriting across DLM, GuardDuty and Resource Explorer 2 DlmRouteFilter, GuardDutyRouteFilter and ResourceExplorer2PathRewriteFilter each repeated the same path test, credential-scope check and rewrite. They now delegate to SignedServiceRoute in core.common. The helper also reads the signing service from the X-Amz-Credential query parameter when there is no Authorization header, as ServiceEnabledFilter does (which now uses the same lookup), so a query-signed plan request reaches GuardDuty instead of S3. A request sent straight to an internal prefix that is not signed for the service is refused as S3 refuses that bucket name, rather than reaching the service's routes. Resource Explorer 2's prefix moves from /re2 to /_re2, since re2 is a valid bucket name.
This commit is contained in:
1 parent
63b48342d6
commit
daef71ca76
24 files changed
+2247
-70
No files matched your search
+66
@@ -0,0 +1,66 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
|
||||
/**
|
||||
* The services whose REST routes another controller also claims (DLM, GuardDuty Malware
|
||||
* Protection plans and Resource Explorer 2) are reached through {@link SignedServiceRoute}: by the
|
||||
* signing service, from the header or the query string, and never by calling the internal prefix
|
||||
* the routes are registered under.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class SignedServiceRouteIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000301";
|
||||
private static final String S3_AUTH = "AWS4-HMAC-SHA256 Credential=" + ACCOUNT
|
||||
+ "/20260215/us-east-1/s3/aws4_request";
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"/_guardduty/malware-protection-plan", "/_dlm/policies", "/_re2/CreateIndex"})
|
||||
void aRequestStraightToAnInternalPrefixIsRefusedAsAnInvalidBucket(String path) {
|
||||
given().header("Authorization", S3_AUTH)
|
||||
.when().get(path)
|
||||
.then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidBucketName</Code>"));
|
||||
given().when().get(path)
|
||||
.then().statusCode(400)
|
||||
.body(containsString("<Code>InvalidBucketName</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBucketNamedAfterTheOldResourceExplorerPrefixIsAnOrdinaryBucket() {
|
||||
given().header("Authorization", S3_AUTH)
|
||||
.when().put("/re2")
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", S3_AUTH)
|
||||
.body("not an index")
|
||||
.when().put("/re2/CreateIndex")
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", S3_AUTH)
|
||||
.when().get("/re2/CreateIndex")
|
||||
.then().statusCode(200)
|
||||
.body(equalTo("not an index"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aQuerySignedRequestIsRoutedByItsCredential() {
|
||||
given().queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
|
||||
.queryParam("X-Amz-Credential", ACCOUNT + "/20260215/us-east-1/dlm/aws4_request")
|
||||
.when().get("/policies")
|
||||
.then().statusCode(200)
|
||||
.body("Policies", notNullValue());
|
||||
given().queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
|
||||
.queryParam("X-Amz-Credential", ACCOUNT + "/20260215/us-east-1/guardduty/aws4_request")
|
||||
.when().get("/malware-protection-plan")
|
||||
.then().statusCode(200)
|
||||
.body("malwareProtectionPlans", notNullValue());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
class SignedServiceRouteTest {
|
||||
|
||||
private final ResolvedServiceCatalog catalog = mock(ResolvedServiceCatalog.class);
|
||||
|
||||
@Test
|
||||
void underMatchesTheRootAndPathsBeneathItOnly() {
|
||||
Predicate<String> plans = SignedServiceRoute.under("/malware-protection-plan");
|
||||
|
||||
assertTrue(plans.test("/malware-protection-plan"));
|
||||
assertTrue(plans.test("/malware-protection-plan/abc"));
|
||||
assertFalse(plans.test("/malware-protection-planner"));
|
||||
assertFalse(plans.test("/other/malware-protection-plan"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theInternalPrefixMustBeOneSegmentNoS3BucketCanBeNamed() {
|
||||
assertDoesNotThrow(() -> new SignedServiceRoute(catalog, "dlm", "/_dlm", path -> false));
|
||||
// A bucket may be named re2, so a prefix without the underscore could shadow one.
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new SignedServiceRoute(catalog, "resource-explorer-2", "/re2", path -> false));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new SignedServiceRoute(catalog, "dlm", "/_dlm/policies", path -> false));
|
||||
}
|
||||
}
|
||||
+11
@@ -69,6 +69,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ElbV2CfnP
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsArchiveCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.FirehoseCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.GuardDutyMalwareProtectionPlanCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamAccessKeyCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamInstanceProfileCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamManagedPolicyCfnProvisioner;
|
||||
@@ -129,6 +130,7 @@ import io.github.hectorvent.floci.services.elasticache.ElastiCacheService;
|
||||
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import io.github.hectorvent.floci.services.firehose.FirehoseService;
|
||||
import io.github.hectorvent.floci.services.guardduty.GuardDutyService;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iot.IotAuthorizerService;
|
||||
import io.github.hectorvent.floci.services.iot.IotDomainConfigurationService;
|
||||
@@ -242,6 +244,7 @@ final class CfnProvisionerFixture {
|
||||
private RedshiftService redshiftService;
|
||||
private RedshiftServerlessService redshiftServerlessService;
|
||||
private CloudMapService cloudMapService;
|
||||
private GuardDutyService guardDutyService;
|
||||
private BedrockAgentCoreControlService bedrockAgentCoreControlService;
|
||||
private BedrockAgentCoreMemoryService bedrockAgentCoreMemoryService;
|
||||
private CloudFormationResourceRegistry resourceRegistry;
|
||||
@@ -479,6 +482,9 @@ final class CfnProvisionerFixture {
|
||||
if (cloudMapService != null) {
|
||||
discovered.add(new CloudMapCfnProvisioner(cloudMapService));
|
||||
}
|
||||
if (guardDutyService != null) {
|
||||
discovered.add(new GuardDutyMalwareProtectionPlanCfnProvisioner(guardDutyService));
|
||||
}
|
||||
if (bedrockAgentCoreControlService != null && bedrockAgentCoreMemoryService != null) {
|
||||
discovered.add(new BedrockAgentCoreCfnProvisioner(bedrockAgentCoreControlService,
|
||||
bedrockAgentCoreMemoryService));
|
||||
@@ -776,6 +782,11 @@ final class CfnProvisionerFixture {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder guardDuty(GuardDutyService v) {
|
||||
this.guardDutyService = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder bedrockAgentCoreControl(BedrockAgentCoreControlService v) {
|
||||
this.bedrockAgentCoreControlService = v;
|
||||
return this;
|
||||
|
||||
+348
@@ -0,0 +1,348 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Provisions an {@code AWS::GuardDuty::MalwareProtectionPlan} through a CloudFormation stack, the
|
||||
* shape from the feature request: a bucket, the plan's role, and the plan. Asserts that {@code Ref}
|
||||
* and {@code Fn::GetAtt MalwareProtectionPlanId} are the plan id, that {@code Arn} and {@code Status}
|
||||
* match what {@code GetMalwareProtectionPlan} serves, that an update changes the plan in place, and
|
||||
* that deleting the stack removes it.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class GuardDutyMalwareProtectionPlanCfnIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
|
||||
private static final String GUARDDUTY_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/guardduty/aws4_request";
|
||||
private static final String STACK = "guardduty-malware-plan-cfn-it";
|
||||
|
||||
private static final String TEMPLATE = """
|
||||
{
|
||||
"Parameters": {
|
||||
"TagValue": {"Type": "String"},
|
||||
"TaggingStatus": {"Type": "String"},
|
||||
"Prefix": {"Type": "String"}
|
||||
},
|
||||
"Resources": {
|
||||
"Bucket": {"Type": "AWS::S3::Bucket"},
|
||||
"Role": {
|
||||
"Type": "AWS::IAM::Role",
|
||||
"Properties": {
|
||||
"AssumeRolePolicyDocument": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"Service": "malware-protection-plan.guardduty.amazonaws.com"},
|
||||
"Action": "sts:AssumeRole"
|
||||
}]
|
||||
}
|
||||
}
|
||||
},
|
||||
"Plan": {
|
||||
"Type": "AWS::GuardDuty::MalwareProtectionPlan",
|
||||
"Properties": {
|
||||
"Role": {"Fn::GetAtt": ["Role", "Arn"]},
|
||||
"ProtectedResource": {
|
||||
"S3Bucket": {
|
||||
"BucketName": {"Ref": "Bucket"},
|
||||
"ObjectPrefixes": [{"Ref": "Prefix"}]
|
||||
}
|
||||
},
|
||||
"Actions": {"Tagging": {"Status": {"Ref": "TaggingStatus"}}},
|
||||
"Tags": [{"Key": "stack", "Value": {"Ref": "TagValue"}}, {"Key": "team", "Value": "core"}]
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"PlanRef": {"Value": {"Ref": "Plan"}},
|
||||
"PlanId": {"Value": {"Fn::GetAtt": ["Plan", "MalwareProtectionPlanId"]}},
|
||||
"PlanArn": {"Value": {"Fn::GetAtt": ["Plan", "Arn"]}},
|
||||
"PlanStatus": {"Value": {"Fn::GetAtt": ["Plan", "Status"]}},
|
||||
"BucketName": {"Value": {"Ref": "Bucket"}},
|
||||
"RoleArn": {"Value": {"Fn::GetAtt": ["Role", "Arn"]}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUpdateAndDeleteAMalwareProtectionPlan() {
|
||||
cloudFormation("CreateStack", Map.of("TagValue", "v1", "TaggingStatus", "ENABLED", "Prefix", "in/"));
|
||||
String created = describeStacks("CREATE_COMPLETE");
|
||||
String planId = outputValue(created, "PlanId");
|
||||
|
||||
// Ref and Fn::GetAtt MalwareProtectionPlanId are the id; Arn and Status are what the service reports.
|
||||
assertEquals(planId, outputValue(created, "PlanRef"));
|
||||
assertEquals("ACTIVE", outputValue(created, "PlanStatus"));
|
||||
getPlan(planId)
|
||||
.statusCode(200)
|
||||
.body("arn", equalTo(outputValue(created, "PlanArn")))
|
||||
.body("role", equalTo(outputValue(created, "RoleArn")))
|
||||
.body("protectedResource.s3Bucket.bucketName", equalTo(outputValue(created, "BucketName")))
|
||||
.body("protectedResource.s3Bucket.objectPrefixes", hasItem("in/"))
|
||||
.body("actions.tagging.status", equalTo("ENABLED"))
|
||||
.body("tags.stack", equalTo("v1"))
|
||||
.body("tags.team", equalTo("core"));
|
||||
|
||||
cloudFormation("UpdateStack", Map.of("TagValue", "v2", "TaggingStatus", "DISABLED", "Prefix", "out/"));
|
||||
String updated = describeStacks("UPDATE_COMPLETE");
|
||||
|
||||
// Prefixes, the tagging action and tags change on the same plan; nothing is replaced.
|
||||
assertEquals(planId, outputValue(updated, "PlanId"));
|
||||
assertEquals(outputValue(created, "PlanArn"), outputValue(updated, "PlanArn"));
|
||||
getPlan(planId)
|
||||
.statusCode(200)
|
||||
.body("protectedResource.s3Bucket.objectPrefixes", hasItem("out/"))
|
||||
.body("actions.tagging.status", equalTo("DISABLED"))
|
||||
.body("tags.stack", equalTo("v2"))
|
||||
.body("tags.team", equalTo("core"));
|
||||
|
||||
cloudFormation("DeleteStack", Map.of());
|
||||
CfnStackWaits.awaitStackDeleted(STACK);
|
||||
|
||||
getPlan(planId).statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTemplateWithoutOptionalPropertiesStillProvisionsAPlan() {
|
||||
String stack = STACK + "-minimal";
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Plan": {
|
||||
"Type": "AWS::GuardDuty::MalwareProtectionPlan",
|
||||
"Properties": {
|
||||
"Role": "arn:aws:iam::000000000000:role/minimal-malware-role",
|
||||
"ProtectedResource": {"S3Bucket": {"BucketName": "gd-cfn-minimal-bucket"}}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {"PlanId": {"Value": {"Ref": "Plan"}}}
|
||||
}
|
||||
""";
|
||||
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateStack").formParam("StackName", stack).formParam("TemplateBody", template)
|
||||
.when().post("/").then().statusCode(200);
|
||||
String xml = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks").formParam("StackName", stack)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
|
||||
.extract().asString();
|
||||
|
||||
getPlan(outputValue(xml, "PlanId"))
|
||||
.statusCode(200)
|
||||
.body("actions", nullValue())
|
||||
.body("protectedResource.s3Bucket.bucketName", equalTo("gd-cfn-minimal-bucket"));
|
||||
|
||||
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DeleteStack").formParam("StackName", stack)
|
||||
.when().post("/").then().statusCode(200);
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
getPlan(outputValue(xml, "PlanId")).statusCode(404);
|
||||
}
|
||||
|
||||
/** The minimal plan template, with the optional properties and any extra resources spliced in. */
|
||||
private static final String VARIABLE_TEMPLATE = """
|
||||
{
|
||||
"Resources": {
|
||||
"Plan": {
|
||||
"Type": "AWS::GuardDuty::MalwareProtectionPlan",
|
||||
"Properties": {
|
||||
"Role": "arn:aws:iam::000000000000:role/variable-malware-role",
|
||||
"ProtectedResource": {"S3Bucket": {%s}}%s
|
||||
}
|
||||
}%s
|
||||
},
|
||||
"Outputs": {
|
||||
"PlanId": {"Value": {"Ref": "Plan"}},
|
||||
"PlanArn": {"Value": {"Fn::GetAtt": ["Plan", "Arn"]}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
/** A resource that fails after the plan, so the update rolls back. */
|
||||
private static final String FAILING_RESOURCE = """
|
||||
,
|
||||
"BadSecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"DependsOn": "Plan",
|
||||
"Properties": {
|
||||
"Name": "guardduty-malware-plan-cfn-rollback-it",
|
||||
"SecretString": "explicit",
|
||||
"GenerateSecretString": {"PasswordLength": 32}
|
||||
}
|
||||
}""";
|
||||
|
||||
@Test
|
||||
void anUpdateThatDropsObjectPrefixesAndActionsClearsThem() {
|
||||
String stack = STACK + "-clear";
|
||||
String bucket = "\"BucketName\": \"gd-cfn-clear-bucket\"";
|
||||
deploy(stack, "CreateStack", VARIABLE_TEMPLATE.formatted(
|
||||
bucket + ", \"ObjectPrefixes\": [\"in/\"]",
|
||||
", \"Actions\": {\"Tagging\": {\"Status\": \"ENABLED\"}}", ""));
|
||||
String planId = outputValue(describe(stack, "CREATE_COMPLETE"), "PlanId");
|
||||
getPlan(planId).statusCode(200)
|
||||
.body("protectedResource.s3Bucket.objectPrefixes", hasItem("in/"))
|
||||
.body("actions.tagging.status", equalTo("ENABLED"));
|
||||
|
||||
// Dropping the properties must widen the plan back to the whole bucket, not leave the old filter.
|
||||
deploy(stack, "UpdateStack", VARIABLE_TEMPLATE.formatted(bucket, "", ""));
|
||||
assertEquals(planId, outputValue(describe(stack, "UPDATE_COMPLETE"), "PlanId"));
|
||||
getPlan(planId).statusCode(200)
|
||||
.body("protectedResource.s3Bucket.objectPrefixes", nullValue())
|
||||
.body("actions", nullValue());
|
||||
|
||||
deploy(stack, "DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedUpdatePutsThePlanBackAsItWas() {
|
||||
String stack = STACK + "-rollback";
|
||||
String bucket = "\"BucketName\": \"gd-cfn-rollback-bucket\"";
|
||||
String original = bucket + ", \"ObjectPrefixes\": [\"in/\"]";
|
||||
String originalExtras = ", \"Actions\": {\"Tagging\": {\"Status\": \"ENABLED\"}},"
|
||||
+ " \"Tags\": [{\"Key\": \"stack\", \"Value\": \"v1\"}]";
|
||||
deploy(stack, "CreateStack", VARIABLE_TEMPLATE.formatted(original, originalExtras, ""));
|
||||
String planId = outputValue(describe(stack, "CREATE_COMPLETE"), "PlanId");
|
||||
|
||||
// The plan is changed in place before the secret fails the update.
|
||||
String changedExtras = ", \"Actions\": {\"Tagging\": {\"Status\": \"DISABLED\"}},"
|
||||
+ " \"Tags\": [{\"Key\": \"stack\", \"Value\": \"v2\"}]";
|
||||
deploy(stack, "UpdateStack", VARIABLE_TEMPLATE.formatted(
|
||||
bucket + ", \"ObjectPrefixes\": [\"out/\"]", changedExtras, FAILING_RESOURCE));
|
||||
assertEquals(planId, outputValue(describe(stack, "UPDATE_ROLLBACK_COMPLETE"), "PlanId"));
|
||||
|
||||
getPlan(planId).statusCode(200)
|
||||
.body("protectedResource.s3Bucket.objectPrefixes", equalTo(List.of("in/")))
|
||||
.body("actions.tagging.status", equalTo("ENABLED"))
|
||||
.body("tags", equalTo(Map.of("stack", "v1")));
|
||||
|
||||
deploy(stack, "DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
getPlan(planId).statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedUpdateDeletesThePlanItCreatedInPlaceOfOneDeletedOutOfBand() {
|
||||
String stack = STACK + "-recreate";
|
||||
String bucket = "\"BucketName\": \"gd-cfn-recreate-bucket\"";
|
||||
deploy(stack, "CreateStack", VARIABLE_TEMPLATE.formatted(bucket, "", ""));
|
||||
String created = describe(stack, "CREATE_COMPLETE");
|
||||
String planId = outputValue(created, "PlanId");
|
||||
String planArn = outputValue(created, "PlanArn");
|
||||
given().header("Authorization", GUARDDUTY_AUTH)
|
||||
.when().delete("/malware-protection-plan/" + planId).then().statusCode(200);
|
||||
|
||||
// The update creates a plan in place of the deleted one before the secret fails it. The
|
||||
// plan's own properties change too: an unchanged resource is skipped, and the create would
|
||||
// never run.
|
||||
deploy(stack, "UpdateStack", VARIABLE_TEMPLATE.formatted(
|
||||
bucket + ", \"ObjectPrefixes\": [\"changed/\"]", "", FAILING_RESOURCE));
|
||||
describe(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
// A plan the failed update left behind would still hold the bucket and make this a conflict.
|
||||
given().contentType("application/json").header("Authorization", GUARDDUTY_AUTH)
|
||||
.body("{\"role\":\"arn:aws:iam::000000000000:role/other\","
|
||||
+ "\"protectedResource\":{\"s3Bucket\":{\"bucketName\":\"gd-cfn-recreate-bucket\"}}}")
|
||||
.when().post("/malware-protection-plan").then().statusCode(200);
|
||||
|
||||
// A later update that leaves the plan alone re-reads its attributes: Fn::GetAtt must name
|
||||
// the prior plan again, not the replacement the rollback deleted.
|
||||
deploy(stack, "UpdateStack", VARIABLE_TEMPLATE.formatted(bucket, "", UNRELATED_RESOURCE));
|
||||
String updated = describe(stack, "UPDATE_COMPLETE");
|
||||
assertEquals(planId, outputValue(updated, "PlanId"));
|
||||
assertEquals(planArn, outputValue(updated, "PlanArn"));
|
||||
}
|
||||
|
||||
/** A resource that has nothing to do with the plan, so an update leaves the plan as it is. */
|
||||
private static final String UNRELATED_RESOURCE = """
|
||||
,
|
||||
"Marker": {
|
||||
"Type": "AWS::SSM::Parameter",
|
||||
"Properties": {"Name": "/guardduty-malware-plan-cfn-it/marker", "Type": "String", "Value": "x"}
|
||||
}""";
|
||||
|
||||
private static void deploy(String stack, String action, String template) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", stack);
|
||||
if (template != null) {
|
||||
request.formParam("TemplateBody", template);
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String describe(String stack, String expectedStatus) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stack)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private static void cloudFormation(String action, Map<String, String> parameters) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", STACK);
|
||||
if (!"DeleteStack".equals(action)) {
|
||||
request.formParam("TemplateBody", TEMPLATE);
|
||||
}
|
||||
int index = 1;
|
||||
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
|
||||
request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
|
||||
request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
|
||||
index++;
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String describeStacks(String expectedStatus) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", STACK)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private static String outputValue(String xml, String key) {
|
||||
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
|
||||
}
|
||||
|
||||
private static ValidatableResponse getPlan(String planId) {
|
||||
return given().header("Authorization", GUARDDUTY_AUTH)
|
||||
.when().get("/malware-protection-plan/" + planId).then();
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.guardduty.GuardDutyService;
|
||||
import io.github.hectorvent.floci.services.guardduty.model.MalwareProtectionPlan;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@code AWS::GuardDuty::MalwareProtectionPlan} in isolation: when an update creates a plan because
|
||||
* the one at the prior physical id was deleted out of band, rolling the update back deletes the
|
||||
* created plan and puts back every attribute {@code Fn::GetAtt} reads for the prior plan, not only
|
||||
* its id.
|
||||
*/
|
||||
class GuardDutyMalwareProtectionPlanCfnProvisionerTest {
|
||||
|
||||
private static final String TYPE = "AWS::GuardDuty::MalwareProtectionPlan";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String PRIOR_ID = "prior0000000000000000000000000ab";
|
||||
private static final String PRIOR_ARN = "arn:aws:guardduty:us-east-1:000000000000:malware-protection-plan/"
|
||||
+ PRIOR_ID;
|
||||
private static final String CREATED_ID = "created00000000000000000000000cd";
|
||||
private static final String CREATED_ARN = "arn:aws:guardduty:us-east-1:000000000000:malware-protection-plan/"
|
||||
+ CREATED_ID;
|
||||
|
||||
private final GuardDutyService guardDuty = mock(GuardDutyService.class);
|
||||
private final GuardDutyMalwareProtectionPlanCfnProvisioner provisioner =
|
||||
new GuardDutyMalwareProtectionPlanCfnProvisioner(guardDuty);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void rollingBackAReplacingCreatePutsThePriorPlanAttributesBack() throws Exception {
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId(PRIOR_ID);
|
||||
r.getAttributes().putAll(Map.of(
|
||||
"MalwareProtectionPlanId", PRIOR_ID,
|
||||
"Arn", PRIOR_ARN,
|
||||
"CreatedAt", "2026-01-01T00:00:00Z",
|
||||
"Status", "ACTIVE",
|
||||
"StatusReasons", "[]"));
|
||||
when(guardDuty.getMalwareProtectionPlan(REGION, PRIOR_ID))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "gone", 404));
|
||||
when(guardDuty.createMalwareProtectionPlan(eq(REGION), eq("000000000000"), any()))
|
||||
.thenReturn(plan(CREATED_ID, CREATED_ARN, "2026-02-02T00:00:00Z"));
|
||||
|
||||
provisioner.provision(r, mapper.readTree("""
|
||||
{"Role": "arn:aws:iam::000000000000:role/scan",
|
||||
"ProtectedResource": {"S3Bucket": {"BucketName": "bucket-a"}}}"""), ctx(PRIOR_ID));
|
||||
assertEquals(CREATED_ID, r.getPhysicalId());
|
||||
assertEquals(CREATED_ARN, r.getAttributes().get("Arn"));
|
||||
|
||||
provisioner.rollbackUpdate(r);
|
||||
|
||||
verify(guardDuty).deleteMalwareProtectionPlan(REGION, CREATED_ID);
|
||||
assertEquals(PRIOR_ID, r.getPhysicalId());
|
||||
assertEquals(PRIOR_ID, r.getAttributes().get("MalwareProtectionPlanId"));
|
||||
assertEquals(PRIOR_ARN, r.getAttributes().get("Arn"));
|
||||
assertEquals("2026-01-01T00:00:00Z", r.getAttributes().get("CreatedAt"));
|
||||
assertEquals("ACTIVE", r.getAttributes().get("Status"));
|
||||
assertEquals("[]", r.getAttributes().get("StatusReasons"));
|
||||
assertFalse(r.getAttributes().containsKey(CfnRollback.GUARDDUTY_PLAN_UPDATE_SNAPSHOT_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAttributeThePriorPlanNeverHadIsDroppedRatherThanLeftFromTheReplacement() throws Exception {
|
||||
// A resource recorded before CreatedAt was reported has no prior value for it.
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId(PRIOR_ID);
|
||||
r.getAttributes().putAll(Map.of("MalwareProtectionPlanId", PRIOR_ID, "Arn", PRIOR_ARN));
|
||||
when(guardDuty.getMalwareProtectionPlan(REGION, PRIOR_ID))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "gone", 404));
|
||||
when(guardDuty.createMalwareProtectionPlan(eq(REGION), eq("000000000000"), any()))
|
||||
.thenReturn(plan(CREATED_ID, CREATED_ARN, "2026-02-02T00:00:00Z"));
|
||||
|
||||
provisioner.provision(r, mapper.readTree("""
|
||||
{"Role": "arn:aws:iam::000000000000:role/scan",
|
||||
"ProtectedResource": {"S3Bucket": {"BucketName": "bucket-b"}}}"""), ctx(PRIOR_ID));
|
||||
provisioner.rollbackUpdate(r);
|
||||
|
||||
assertEquals(PRIOR_ARN, r.getAttributes().get("Arn"));
|
||||
assertFalse(r.getAttributes().containsKey("CreatedAt"));
|
||||
assertFalse(r.getAttributes().containsKey("Status"));
|
||||
}
|
||||
|
||||
private static MalwareProtectionPlan plan(String id, String arn, String createdAt) {
|
||||
MalwareProtectionPlan plan = new MalwareProtectionPlan();
|
||||
plan.setId(id);
|
||||
plan.setArn(arn);
|
||||
plan.setCreatedAt(createdAt);
|
||||
plan.setStatus("ACTIVE");
|
||||
plan.setBucketName("bucket");
|
||||
return plan;
|
||||
}
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null || node.isMissingNode() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null ? null : node.deepCopy();
|
||||
});
|
||||
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
|
||||
}
|
||||
|
||||
private static StackResource resource() {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Plan");
|
||||
r.setResourceType(TYPE);
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
package io.github.hectorvent.floci.services.guardduty;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Verifies the GuardDuty restJson1 Malware Protection plan lifecycle over HTTP. */
|
||||
@QuarkusTest
|
||||
class GuardDutyMalwareProtectionPlanIntegrationTest {
|
||||
|
||||
private static final String ROLE = "arn:aws:iam::000000000201:role/malware-scan";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void planCreateGetUpdateListDeleteLifecycle() {
|
||||
String auth = auth("000000000201", "eu-north-1");
|
||||
|
||||
String planId = createPlan(auth, """
|
||||
{"role":"%s","actions":{"tagging":{"status":"ENABLED"}},
|
||||
"protectedResource":{"s3Bucket":{"bucketName":"gd-plan-lifecycle","objectPrefixes":["in/"]}},
|
||||
"tags":{"env":"it"}}
|
||||
""".formatted(ROLE));
|
||||
|
||||
Response plan = given().header("Authorization", auth)
|
||||
.when().get("/malware-protection-plan/" + planId)
|
||||
.then().statusCode(200)
|
||||
.body("arn", equalTo("arn:aws:guardduty:eu-north-1:000000000201:malware-protection-plan/" + planId))
|
||||
.body("role", equalTo(ROLE))
|
||||
.body("status", equalTo("ACTIVE"))
|
||||
.body("statusReasons.size()", equalTo(0))
|
||||
.body("actions.tagging.status", equalTo("ENABLED"))
|
||||
.body("protectedResource.s3Bucket.bucketName", equalTo("gd-plan-lifecycle"))
|
||||
.body("protectedResource.s3Bucket.objectPrefixes", hasItem("in/"))
|
||||
.body("tags.env", equalTo("it"))
|
||||
.extract().response();
|
||||
// restJson1 carries a timestamp as epoch seconds, so SDKs deserialize it as a number.
|
||||
assertTrue(plan.path("createdAt") instanceof Number, "createdAt must be a JSON number");
|
||||
|
||||
given().header("Authorization", auth)
|
||||
.when().get("/malware-protection-plan")
|
||||
.then().statusCode(200)
|
||||
.body("malwareProtectionPlans.malwareProtectionPlanId", hasItem(planId));
|
||||
|
||||
given().contentType("application/json").header("Authorization", auth)
|
||||
.body("""
|
||||
{"actions":{"tagging":{"status":"DISABLED"}},
|
||||
"protectedResource":{"s3Bucket":{"objectPrefixes":["out/"]}}}
|
||||
""")
|
||||
.when().patch("/malware-protection-plan/" + planId)
|
||||
.then().statusCode(200);
|
||||
|
||||
given().header("Authorization", auth)
|
||||
.when().get("/malware-protection-plan/" + planId)
|
||||
.then().statusCode(200)
|
||||
.body("actions.tagging.status", equalTo("DISABLED"))
|
||||
.body("protectedResource.s3Bucket.objectPrefixes", hasItem("out/"))
|
||||
.body("protectedResource.s3Bucket.objectPrefixes", not(hasItem("in/")))
|
||||
.body("role", equalTo(ROLE));
|
||||
|
||||
given().header("Authorization", auth)
|
||||
.when().delete("/malware-protection-plan/" + planId)
|
||||
.then().statusCode(200);
|
||||
|
||||
given().header("Authorization", auth)
|
||||
.when().get("/malware-protection-plan/" + planId)
|
||||
.then().statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecondPlanForTheSameBucketIsAConflict() {
|
||||
String auth = auth("000000000202", "eu-north-1");
|
||||
String body = """
|
||||
{"role":"%s","protectedResource":{"s3Bucket":{"bucketName":"gd-plan-conflict"}}}
|
||||
""".formatted(ROLE);
|
||||
createPlan(auth, body);
|
||||
|
||||
given().contentType("application/json").header("Authorization", auth).body(body)
|
||||
.when().post("/malware-protection-plan")
|
||||
.then().statusCode(409)
|
||||
.body("__type", equalTo("ConflictException"))
|
||||
.body("message", containsString("gd-plan-conflict"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void plansAreIsolatedByAccountAndRegion() {
|
||||
String owner = auth("000000000203", "eu-north-1");
|
||||
String planId = createPlan(owner, """
|
||||
{"role":"%s","protectedResource":{"s3Bucket":{"bucketName":"gd-plan-isolated"}}}
|
||||
""".formatted(ROLE));
|
||||
|
||||
given().header("Authorization", auth("000000000204", "eu-north-1"))
|
||||
.when().get("/malware-protection-plan/" + planId)
|
||||
.then().statusCode(404);
|
||||
given().header("Authorization", auth("000000000203", "eu-west-3"))
|
||||
.when().get("/malware-protection-plan/" + planId)
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsOnAPlanUseTheSharedTagRoutes() {
|
||||
String auth = auth("000000000205", "eu-north-1");
|
||||
String planId = createPlan(auth, """
|
||||
{"role":"%s","protectedResource":{"s3Bucket":{"bucketName":"gd-plan-tags"}},"tags":{"a":"1"}}
|
||||
""".formatted(ROLE));
|
||||
String arn = "arn:aws:guardduty:eu-north-1:000000000205:malware-protection-plan/" + planId;
|
||||
|
||||
given().contentType("application/json").header("Authorization", auth)
|
||||
.body("{\"tags\":{\"b\":\"2\"}}")
|
||||
.when().post("/tags/" + arn)
|
||||
.then().statusCode(204);
|
||||
given().header("Authorization", auth)
|
||||
.when().delete("/tags/" + arn + "?tagKeys=a")
|
||||
.then().statusCode(204);
|
||||
|
||||
given().header("Authorization", auth)
|
||||
.when().get("/tags/" + arn)
|
||||
.then().statusCode(200)
|
||||
.body("tags.b", equalTo("2"))
|
||||
.body("tags.a", nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestMissingTheRoleIsABadRequest() {
|
||||
given().contentType("application/json").header("Authorization", auth("000000000206", "eu-north-1"))
|
||||
.body("{\"protectedResource\":{\"s3Bucket\":{\"bucketName\":\"gd-plan-bad\"}}}")
|
||||
.when().post("/malware-protection-plan")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theIdIsReturnedWithoutAnArnPrefix() {
|
||||
String planId = createPlan(auth("000000000207", "eu-north-1"), """
|
||||
{"role":"%s","protectedResource":{"s3Bucket":{"bucketName":"gd-plan-id"}}}
|
||||
""".formatted(ROLE));
|
||||
|
||||
assertEquals(32, planId.length());
|
||||
assertTrue(!planId.startsWith("arn:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anS3BucketNamedLikeThePlanRouteStillReachesS3() {
|
||||
String s3Auth = "AWS4-HMAC-SHA256 Credential=000000000208/20260215/us-east-1/s3/aws4_request";
|
||||
|
||||
given().header("Authorization", s3Auth)
|
||||
.when().put("/malware-protection-plan")
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", s3Auth)
|
||||
.body("scanned")
|
||||
.when().put("/malware-protection-plan/object.txt")
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", s3Auth)
|
||||
.when().get("/malware-protection-plan/object.txt")
|
||||
.then().statusCode(200)
|
||||
.body(equalTo("scanned"));
|
||||
|
||||
// Query-signed for S3, it is still the bucket.
|
||||
presigned("000000000208/20260215/us-east-1/s3/aws4_request")
|
||||
.when().get("/malware-protection-plan/object.txt")
|
||||
.then().statusCode(200)
|
||||
.body(equalTo("scanned"));
|
||||
|
||||
// The same path signed for GuardDuty is still the plan API.
|
||||
given().header("Authorization", auth("000000000208", "us-east-1"))
|
||||
.when().get("/malware-protection-plan")
|
||||
.then().statusCode(200)
|
||||
.body("malwareProtectionPlans", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aQuerySignedPlanRequestReachesGuardDuty() {
|
||||
String planId = createPlan(auth("000000000209", "us-east-1"), """
|
||||
{"role": "%s", "protectedResource": {"s3Bucket": {"bucketName": "query-signed-bucket"}}}
|
||||
""".formatted(ROLE));
|
||||
|
||||
presigned("000000000209/20260215/us-east-1/guardduty/aws4_request")
|
||||
.when().get("/malware-protection-plan/" + planId)
|
||||
.then().statusCode(200)
|
||||
.body("protectedResource.s3Bucket.bucketName", equalTo("query-signed-bucket"));
|
||||
}
|
||||
|
||||
/** A query-signed request; S3 checks the presigned parameters are present and unexpired. */
|
||||
private static RequestSpecification presigned(String credential) {
|
||||
return given().queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
|
||||
.queryParam("X-Amz-Credential", credential)
|
||||
.queryParam("X-Amz-Date", DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'")
|
||||
.withZone(ZoneOffset.UTC).format(Instant.now()))
|
||||
.queryParam("X-Amz-Expires", "300")
|
||||
.queryParam("X-Amz-SignedHeaders", "host")
|
||||
.queryParam("X-Amz-Signature", "0".repeat(64));
|
||||
}
|
||||
|
||||
private static String auth(String accountId, String region) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260215/" + region + "/guardduty/aws4_request";
|
||||
}
|
||||
|
||||
private static String createPlan(String authorization, String body) {
|
||||
return given().contentType("application/json").header("Authorization", authorization).body(body)
|
||||
.when().post("/malware-protection-plan")
|
||||
.then().statusCode(200)
|
||||
.body("malwareProtectionPlanId", notNullValue())
|
||||
.body("malwareProtectionPlanId", not(startsWith("arn:")))
|
||||
.extract().path("malwareProtectionPlanId");
|
||||
}
|
||||
}
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
package io.github.hectorvent.floci.services.guardduty;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.guardduty.model.Detector;
|
||||
import io.github.hectorvent.floci.services.guardduty.model.MalwareProtectionPlan;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class GuardDutyMalwareProtectionPlanServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/malware-scan";
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private final GuardDutyService service =
|
||||
new GuardDutyService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
|
||||
@Test
|
||||
void createStoresThePlanAndReportsAnArnInTheGuardDutyNamespace() {
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-one"));
|
||||
|
||||
assertEquals(32, plan.getId().length());
|
||||
assertEquals("arn:aws:guardduty:us-east-1:000000000000:malware-protection-plan/" + plan.getId(),
|
||||
plan.getArn());
|
||||
assertEquals("ACTIVE", plan.getStatus());
|
||||
assertEquals("bucket-one", plan.getBucketName());
|
||||
assertEquals(ROLE, plan.getRole());
|
||||
assertNull(plan.getTaggingStatus(), "no actions were requested");
|
||||
assertEquals(plan.getId(), service.getMalwareProtectionPlan(REGION, plan.getId()).getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createKeepsPrefixesTaggingActionAndTags() {
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, json("""
|
||||
{"role":"%s","actions":{"tagging":{"status":"ENABLED"}},
|
||||
"protectedResource":{"s3Bucket":{"bucketName":"bucket-two","objectPrefixes":["a/","b/"]}},
|
||||
"tags":{"env":"test"}}
|
||||
""".formatted(ROLE)));
|
||||
|
||||
assertEquals("ENABLED", plan.getTaggingStatus());
|
||||
assertEquals(List.of("a/", "b/"), plan.getObjectPrefixes());
|
||||
assertEquals(Map.of("env", "test"), plan.getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecondPlanForTheSameBucketConflicts() {
|
||||
service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-dup"));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-dup")));
|
||||
|
||||
assertEquals("ConflictException", error.getErrorCode());
|
||||
assertEquals(409, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSameBucketInAnotherRegionIsNotAConflict() {
|
||||
service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-regional"));
|
||||
|
||||
MalwareProtectionPlan other =
|
||||
service.createMalwareProtectionPlan("eu-west-1", ACCOUNT, create("bucket-regional"));
|
||||
|
||||
assertTrue(other.getArn().contains(":eu-west-1:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatingAClientTokenReturnsTheExistingPlanInsteadOfConflicting() {
|
||||
JsonNode request = json("""
|
||||
{"role":"%s","clientToken":"token-1",
|
||||
"protectedResource":{"s3Bucket":{"bucketName":"bucket-token"}}}
|
||||
""".formatted(ROLE));
|
||||
|
||||
MalwareProtectionPlan first = service.createMalwareProtectionPlan(REGION, ACCOUNT, request);
|
||||
MalwareProtectionPlan again = service.createMalwareProtectionPlan(REGION, ACCOUNT, request);
|
||||
|
||||
assertEquals(first.getId(), again.getId());
|
||||
assertEquals(1, service.listMalwareProtectionPlans(REGION, null).items().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateChangesRolePrefixesAndTaggingButNeverTheBucket() {
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-up"));
|
||||
|
||||
service.updateMalwareProtectionPlan(REGION, plan.getId(), json("""
|
||||
{"role":"arn:aws:iam::000000000000:role/other",
|
||||
"actions":{"tagging":{"status":"DISABLED"}},
|
||||
"protectedResource":{"s3Bucket":{"objectPrefixes":["only/"]}}}
|
||||
"""));
|
||||
|
||||
MalwareProtectionPlan updated = service.getMalwareProtectionPlan(REGION, plan.getId());
|
||||
assertEquals("arn:aws:iam::000000000000:role/other", updated.getRole());
|
||||
assertEquals("DISABLED", updated.getTaggingStatus());
|
||||
assertEquals(List.of("only/"), updated.getObjectPrefixes());
|
||||
assertEquals("bucket-up", updated.getBucketName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateWithNoFieldsLeavesThePlanAlone() {
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-noop"));
|
||||
|
||||
service.updateMalwareProtectionPlan(REGION, plan.getId(), json("{}"));
|
||||
|
||||
assertEquals(ROLE, service.getMalwareProtectionPlan(REGION, plan.getId()).getRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRemovesThePlanAndFreesTheBucket() {
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-del"));
|
||||
|
||||
service.deleteMalwareProtectionPlan(REGION, plan.getId());
|
||||
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.getMalwareProtectionPlan(REGION, plan.getId())).getErrorCode());
|
||||
service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-del"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownPlanIsResourceNotFoundOnGetUpdateAndDelete() {
|
||||
for (Runnable call : List.<Runnable>of(
|
||||
() -> service.getMalwareProtectionPlan(REGION, "missing"),
|
||||
() -> service.updateMalwareProtectionPlan(REGION, "missing", json("{}")),
|
||||
() -> service.deleteMalwareProtectionPlan(REGION, "missing"))) {
|
||||
AwsException error = assertThrows(AwsException.class, call::run);
|
||||
assertEquals("ResourceNotFoundException", error.getErrorCode());
|
||||
assertEquals(404, error.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPagesThroughPlansInIdOrderAtTheDocumentedDefaultPageSize() {
|
||||
for (int i = 0; i < 102; i++) {
|
||||
service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-page-" + i));
|
||||
}
|
||||
|
||||
GuardDutyService.Page<MalwareProtectionPlan> first = service.listMalwareProtectionPlans(REGION, null);
|
||||
assertEquals(100, first.items().size());
|
||||
assertTrue(first.nextToken() != null);
|
||||
|
||||
GuardDutyService.Page<MalwareProtectionPlan> second =
|
||||
service.listMalwareProtectionPlans(REGION, first.nextToken());
|
||||
assertEquals(2, second.items().size());
|
||||
assertNull(second.nextToken());
|
||||
assertTrue(first.items().get(99).getId().compareTo(second.items().get(0).getId()) < 0,
|
||||
"the second page continues after the last id of the first");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingThePlanTheTokenNamesDoesNotBreakOrSkipTheNextPage() {
|
||||
for (int i = 0; i < 103; i++) {
|
||||
service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-del-page-" + i));
|
||||
}
|
||||
GuardDutyService.Page<MalwareProtectionPlan> first = service.listMalwareProtectionPlans(REGION, null);
|
||||
List<MalwareProtectionPlan> all = new ArrayList<>(first.items());
|
||||
|
||||
// The last plan of page one is deleted before page two is requested.
|
||||
service.deleteMalwareProtectionPlan(REGION, first.items().get(99).getId());
|
||||
GuardDutyService.Page<MalwareProtectionPlan> second =
|
||||
service.listMalwareProtectionPlans(REGION, first.nextToken());
|
||||
all.addAll(second.items());
|
||||
|
||||
assertEquals(3, second.items().size(), "every plan after the deleted one is still listed once");
|
||||
assertNull(second.nextToken());
|
||||
// Page one already held the deleted plan, so the two pages together still cover all 103 once.
|
||||
assertEquals(103, all.stream().map(MalwareProtectionPlan::getId).distinct().count());
|
||||
assertTrue(second.items().stream().noneMatch(plan -> first.items().contains(plan)),
|
||||
"no plan repeats across the pages");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMalformedListTokenIsABadRequest() {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.listMalwareProtectionPlans(REGION, "not-a-token"));
|
||||
|
||||
assertEquals("BadRequestException", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRejectedUpdateChangesNothing() {
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, json("""
|
||||
{"role":"%s","actions":{"tagging":{"status":"ENABLED"}},
|
||||
"protectedResource":{"s3Bucket":{"bucketName":"bucket-atomic","objectPrefixes":["keep/"]}}}
|
||||
""".formatted(ROLE)));
|
||||
|
||||
// A valid role and prefixes ride along with an invalid tagging status.
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.updateMalwareProtectionPlan(
|
||||
REGION, plan.getId(), json("""
|
||||
{"role":"arn:aws:iam::000000000000:role/changed",
|
||||
"protectedResource":{"s3Bucket":{"objectPrefixes":["changed/"]}},
|
||||
"actions":{"tagging":{"status":"MAYBE"}}}
|
||||
""")));
|
||||
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
MalwareProtectionPlan unchanged = service.getMalwareProtectionPlan(REGION, plan.getId());
|
||||
assertEquals(ROLE, unchanged.getRole());
|
||||
assertEquals(List.of("keep/"), unchanged.getObjectPrefixes());
|
||||
assertEquals("ENABLED", unchanged.getTaggingStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatingWithEmptyPrefixesAndActionsClearsBothAndPartialUpdatesKeepThem() {
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, json("""
|
||||
{"role":"%s","actions":{"tagging":{"status":"ENABLED"}},
|
||||
"protectedResource":{"s3Bucket":{"bucketName":"bucket-clear","objectPrefixes":["a/"]}}}
|
||||
""".formatted(ROLE)));
|
||||
|
||||
service.updateMalwareProtectionPlan(REGION, plan.getId(), json("{\"role\":\"" + ROLE + "\"}"));
|
||||
assertEquals(List.of("a/"), service.getMalwareProtectionPlan(REGION, plan.getId()).getObjectPrefixes());
|
||||
assertEquals("ENABLED", service.getMalwareProtectionPlan(REGION, plan.getId()).getTaggingStatus());
|
||||
|
||||
service.updateMalwareProtectionPlan(REGION, plan.getId(), json(
|
||||
"{\"actions\":{},\"protectedResource\":{\"s3Bucket\":{\"objectPrefixes\":[]}}}"));
|
||||
MalwareProtectionPlan cleared = service.getMalwareProtectionPlan(REGION, plan.getId());
|
||||
assertNull(cleared.getObjectPrefixes());
|
||||
assertNull(cleared.getTaggingStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreReinstatesExactStateIncludingNulls() {
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-restore"));
|
||||
service.updateMalwareProtectionPlan(REGION, plan.getId(), json("""
|
||||
{"actions":{"tagging":{"status":"ENABLED"}},
|
||||
"protectedResource":{"s3Bucket":{"objectPrefixes":["x/"]}}}
|
||||
"""));
|
||||
|
||||
service.restoreMalwareProtectionPlan(REGION, plan.getId(), ROLE, null, null, Map.of("k", "v"));
|
||||
|
||||
MalwareProtectionPlan restored = service.getMalwareProtectionPlan(REGION, plan.getId());
|
||||
assertNull(restored.getObjectPrefixes());
|
||||
assertNull(restored.getTaggingStatus());
|
||||
assertEquals(Map.of("k", "v"), restored.getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRoleMustBeAnIamRoleArn() {
|
||||
for (String notARole : List.of(
|
||||
"arn:aws:s3:::some-bucket",
|
||||
"arn:aws:iam::000000000000:user/someone",
|
||||
"arn:aws:iam::000000000000:role/",
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:role/fake")) {
|
||||
assertBad("{\"role\":\"%s\",\"protectedResource\":{\"s3Bucket\":{\"bucketName\":\"bucket-role\"}}}"
|
||||
.formatted(notARole));
|
||||
}
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-role"));
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.updateMalwareProtectionPlan(
|
||||
REGION, plan.getId(), json("{\"role\":\"arn:aws:s3:::some-bucket\"}")));
|
||||
assertEquals("BadRequestException", error.getErrorCode());
|
||||
assertEquals(ROLE, service.getMalwareProtectionPlan(REGION, plan.getId()).getRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTagRoutesApplyTheSameRulesAsCreation() {
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-tag-rules"));
|
||||
|
||||
for (Map<String, String> bad : List.of(
|
||||
Map.of("aws:reserved", "x"),
|
||||
Map.of("k".repeat(129), "x"),
|
||||
Map.of("", "x"),
|
||||
Map.of("has space", "x"),
|
||||
Map.of("at@sign", "x"),
|
||||
Map.of("hash#", "x"),
|
||||
Map.of("fine", "v".repeat(257)))) {
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.tagResource(plan.getArn(), bad));
|
||||
assertEquals("BadRequestException", error.getErrorCode());
|
||||
}
|
||||
assertTrue(service.listTags(plan.getArn()).isEmpty(), "a rejected tag request stores nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsOnAPlanArnAreServedByTheSharedTagOperations() {
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-tag"));
|
||||
|
||||
service.tagResource(plan.getArn(), Map.of("a", "1", "b", "2"));
|
||||
service.untagResource(plan.getArn(), List.of("a"));
|
||||
|
||||
assertEquals(Map.of("b", "2"), service.listTags(plan.getArn()));
|
||||
assertEquals(Map.of("b", "2"), service.getMalwareProtectionPlan(REGION, plan.getId()).getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyInsideTheDocumentedPatternIsAccepted() {
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-tag-ok"));
|
||||
|
||||
Map<String, String> tags = Map.of("team:owner/cost-center_2.x+y=z", "v");
|
||||
service.tagResource(plan.getArn(), tags);
|
||||
|
||||
assertEquals(tags, service.listTags(plan.getArn()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTagRouteArnMustNameThePlanInFull() {
|
||||
MalwareProtectionPlan plan = service.createMalwareProtectionPlan(REGION, ACCOUNT, create("bucket-tag-arn"));
|
||||
service.tagResource(plan.getArn(), Map.of("keep", "1"));
|
||||
|
||||
for (String arn : List.of(
|
||||
plan.getArn().replace(":" + ACCOUNT + ":", ":111111111111:"),
|
||||
plan.getArn().replace(":guardduty:", ":macie2:"),
|
||||
plan.getArn().replace("arn:aws:", "arn:aws-cn:"))) {
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.listTags(arn)).getErrorCode(), arn);
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.tagResource(arn, Map.of("other", "2"))).getErrorCode(), arn);
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.untagResource(arn, List.of("keep"))).getErrorCode(), arn);
|
||||
}
|
||||
assertEquals(Map.of("keep", "1"), service.listTags(plan.getArn()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsOnAMissingPlanAreResourceNotFound() {
|
||||
String arn = "arn:aws:guardduty:us-east-1:000000000000:malware-protection-plan/missing";
|
||||
|
||||
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> service.listTags(arn)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void detectorTagsStillWorkAlongsidePlans() throws Exception {
|
||||
Detector detector = service.createDetector(REGION, ACCOUNT, json("{\"enable\":true,\"tags\":{\"k\":\"v\"}}"));
|
||||
String arn = "arn:aws:guardduty:us-east-1:000000000000:detector/" + detector.getId();
|
||||
|
||||
assertEquals(Map.of("k", "v"), service.listTags(arn));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidRequestsAreBadRequests() {
|
||||
assertBad("{\"role\":\"%s\"}".formatted(ROLE));
|
||||
assertBad("{\"protectedResource\":{\"s3Bucket\":{\"bucketName\":\"bucket-x\"}}}");
|
||||
assertBad("{\"role\":\"not-an-arn\",\"protectedResource\":{\"s3Bucket\":{\"bucketName\":\"bucket-x\"}}}");
|
||||
assertBad("{\"role\":\"%s\",\"protectedResource\":{\"s3Bucket\":{\"bucketName\":\"ab\"}}}".formatted(ROLE));
|
||||
assertBad("""
|
||||
{"role":"%s","protectedResource":{"s3Bucket":{"bucketName":"bucket-x",
|
||||
"objectPrefixes":["1","2","3","4","5","6"]}}}
|
||||
""".formatted(ROLE));
|
||||
assertBad("""
|
||||
{"role":"%s","actions":{"tagging":{"status":"MAYBE"}},
|
||||
"protectedResource":{"s3Bucket":{"bucketName":"bucket-x"}}}
|
||||
""".formatted(ROLE));
|
||||
assertBad("""
|
||||
{"role":"%s","tags":{"aws:reserved":"x"},
|
||||
"protectedResource":{"s3Bucket":{"bucketName":"bucket-x"}}}
|
||||
""".formatted(ROLE));
|
||||
assertBad("""
|
||||
{"role":"%s","tags":{"has space":"x"},
|
||||
"protectedResource":{"s3Bucket":{"bucketName":"bucket-x"}}}
|
||||
""".formatted(ROLE));
|
||||
assertFalse(service.listMalwareProtectionPlans(REGION, null).items().iterator().hasNext(),
|
||||
"a rejected request must not leave a plan behind");
|
||||
}
|
||||
|
||||
private void assertBad(String body) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.createMalwareProtectionPlan(REGION, ACCOUNT, json(body)));
|
||||
assertEquals("BadRequestException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
private JsonNode create(String bucket) {
|
||||
return json("{\"role\":\"%s\",\"protectedResource\":{\"s3Bucket\":{\"bucketName\":\"%s\"}}}"
|
||||
.formatted(ROLE, bucket));
|
||||
}
|
||||
|
||||
private JsonNode json(String text) {
|
||||
try {
|
||||
return objectMapper.readTree(text);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user