From daef71ca76794f579a587393a93cdd8a96f44a6d Mon Sep 17 00:00:00 2001 From: Nazimuddin Tajuddin Basha Date: Tue, 13 Oct 2026 12:17:16 -0500 Subject: [PATCH] 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. --- docs/services/cloudformation.md | 1 + docs/services/guardduty.md | 40 +- docs/services/index.md | 2 +- .../core/common/ServiceEnabledFilter.java | 4 +- .../floci/core/common/SignedServiceRoute.java | 101 +++++ .../provisioners/CfnRollback.java | 9 + ...tyMalwareProtectionPlanCfnProvisioner.java | 313 ++++++++++++++ .../floci/services/dlm/DlmRouteFilter.java | 29 +- .../guardduty/GuardDutyController.java | 82 +++- .../guardduty/GuardDutyRouteFilter.java | 35 ++ .../services/guardduty/GuardDutyService.java | 342 +++++++++++++++- .../model/MalwareProtectionPlan.java | 110 +++++ .../ResourceExplorer2Controller.java | 10 +- .../ResourceExplorer2PathRewriteFilter.java | 34 +- .../create-only-properties.json | 1 + .../SignedServiceRouteIntegrationTest.java | 66 +++ .../core/common/SignedServiceRouteTest.java | 36 ++ .../cloudformation/CfnProvisionerFixture.java | 11 + ...lwareProtectionPlanCfnIntegrationTest.java | 348 ++++++++++++++++ ...lwareProtectionPlanCfnProvisionerTest.java | 129 ++++++ ...yMalwareProtectionPlanIntegrationTest.java | 228 +++++++++++ ...dDutyMalwareProtectionPlanServiceTest.java | 382 ++++++++++++++++++ .../supported-resource-types.tsv | 1 + tools/docs/cfn_resource_types.yaml | 3 + 24 files changed, 2247 insertions(+), 70 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/core/common/SignedServiceRoute.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyRouteFilter.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/guardduty/model/MalwareProtectionPlan.java create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/SignedServiceRouteIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/SignedServiceRouteTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/GuardDutyMalwareProtectionPlanCfnIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisionerTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 0e0178e9f6..93144da26c 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -181,6 +181,7 @@ cross-resource references. | EventBridge Scheduler | `ScheduleGroup` | | Transfer Family | `Server` (management plane only; Ref returns the server ARN; Arn, ServerId and State attributes supported; AS2 managed egress IPs are not modeled; Domain replacement and IdentityProviderType changes are not supported), `User` (management plane only; Ref returns the user ARN; Arn attribute supported; Policy and PosixProfile are not supported; a ServerId or UserName change replaces the user) | | Backup | `BackupVault` | +| GuardDuty | `MalwareProtectionPlan` (management plane only: no scan runs, so the plan stays ACTIVE; Ref returns the plan id; a BucketName change is rejected) | | Pipes | `Pipe` | | Kinesis | `Stream` | | Kinesis Data Firehose | `DeliveryStream` | diff --git a/docs/services/guardduty.md b/docs/services/guardduty.md index da26edc8a2..640155a3e7 100644 --- a/docs/services/guardduty.md +++ b/docs/services/guardduty.md @@ -4,9 +4,10 @@ **Endpoint:** `http://localhost:4566` -Floci implements the GuardDuty detector management lifecycle and organization-configuration -readback for local SDK, CLI, and Terraform workflows. Detectors are isolated by account and -region and use the configured Floci storage mode. +Floci implements the GuardDuty detector management lifecycle, organization-configuration +readback, and Malware Protection plans for local SDK, CLI, Terraform and CloudFormation +workflows. Detectors and plans are isolated by account and region and use the configured Floci +storage mode. ## Supported Operations @@ -24,15 +25,42 @@ region and use the configured Floci storage mode. | `ListOrganizationAdminAccounts` | `GET /admin` | List the delegated administrator account | | `CreateMembers` | `POST /detector/{detectorId}/member` | Create GuardDuty member accounts for a detector | | `ListMembers` | `GET /detector/{detectorId}/member` | List detector members with pagination and association filtering | -| `TagResource` | `POST /tags/{resourceArn}` | Add tags to a detector | -| `UntagResource` | `DELETE /tags/{resourceArn}` | Remove tags from a detector | -| `ListTagsForResource` | `GET /tags/{resourceArn}` | List detector tags | +| `CreateMalwareProtectionPlan` | `POST /malware-protection-plan` | Create a Malware Protection plan for an S3 bucket | +| `GetMalwareProtectionPlan` | `GET /malware-protection-plan/{malwareProtectionPlanId}` | Return a plan's role, protected bucket, actions, status, and tags | +| `UpdateMalwareProtectionPlan` | `PATCH /malware-protection-plan/{malwareProtectionPlanId}` | Update a plan's role, object prefixes, and tagging action | +| `DeleteMalwareProtectionPlan` | `DELETE /malware-protection-plan/{malwareProtectionPlanId}` | Delete a plan | +| `ListMalwareProtectionPlans` | `GET /malware-protection-plan` | List plan ids with pagination | +| `TagResource` | `POST /tags/{resourceArn}` | Add tags to a detector or Malware Protection plan | +| `UntagResource` | `DELETE /tags/{resourceArn}` | Remove tags from a detector or Malware Protection plan | +| `ListTagsForResource` | `GET /tags/{resourceArn}` | List detector or Malware Protection plan tags | Feature lists and each feature's `additionalConfiguration` list are returned in the order they were submitted, so Terraform's ordered list blocks re-plan cleanly. A missing detector is reported as `BadRequestException` with the exact message the Terraform AWS provider matches for not-found detection, mirroring AWS. +## Malware Protection plans + +Plans are management plane only. Floci stores the plan and answers the five operations above, and +`AWS::GuardDuty::MalwareProtectionPlan` is provisioned from CloudFormation (`Ref` and +`Fn::GetAtt MalwareProtectionPlanId` are the plan id; `Arn`, `CreatedAt`, `Status` and +`StatusReasons` are also set). No object is scanned, no `GuardDutyMalwareScanStatus` tag is written, +and no scan-result event is published, so a plan stays `ACTIVE` with no status reasons. + +A bucket has at most one plan per account and region: a second `CreateMalwareProtectionPlan` for +the same bucket fails with `ConflictException`, unless it repeats the earlier request's +`clientToken`, which returns the existing plan. The bucket cannot be changed on an existing plan; +`UpdateMalwareProtectionPlan` changes the role, object prefixes (at most 5), and the tagging action. + +The role must be an IAM role ARN. An update is applied all-or-nothing: if any supplied field is invalid, none of them are stored. +`ListMalwareProtectionPlans` returns up to 100 ids per page, and its `nextToken` survives plans being created or deleted between pages. In a CloudFormation stack, dropping `ObjectPrefixes` or `Actions` from the template clears them on the plan, and a failed stack update restores the plan's previous role, prefixes, tagging action and tags. + +Plan tag keys follow GuardDuty's `TagKey` pattern (no `aws:` prefix, no spaces), and the tag +routes accept a plan's ARN only when it matches the stored plan's exactly, account and partition +included. The plan routes are served only to requests signed for `guardduty`, by the `Authorization` +header or the `X-Amz-Credential` query parameter, so a path-style S3 request for a bucket named +`malware-protection-plan` still reaches S3. + ## Configuration | Variable | Default | Description | diff --git a/docs/services/index.md b/docs/services/index.md index 0ffc778d68..39735a6ed6 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -87,7 +87,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 16 | | [ECR](ecr.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*` (control plane) and `/v2/...` (data plane proxied to `registry:2`) | JSON 1.1 + OCI Distribution | 17 | | [Resource Groups Tagging API](resource-groups-tagging.md) | `POST /` + `X-Amz-Target: ResourceGroupsTaggingAPI_20170126.*` | JSON 1.1 | 5 | -| [Resource Explorer](resource-explorer.md) | `POST /{OperationName}`, rewritten to `/re2/*` for the four paths S3 Vectors also claims | REST JSON | 32 | +| [Resource Explorer](resource-explorer.md) | `POST /{OperationName}`, rewritten to `/_re2/*` for the four paths S3 Vectors also claims | REST JSON | 32 | | [SES](ses.md) | `POST /` with `Action=` param | Query | 16 | | [SES v2](ses.md#v2) | `/v2/email/*` | REST JSON | 10 | | [OpenSearch](opensearch.md) | `/2021-01-01/opensearch/...` | REST JSON | 24 | diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java index 7fb9ff42c2..0676859277 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java @@ -60,9 +60,7 @@ public class ServiceEnabledFilter implements ContainerRequestFilter { return new ResolvedRequest(descriptor.externalKey(), descriptor.defaultProtocol()); } - return SigV4CredentialScope.serviceName(ctx.getHeaderString("Authorization")) - .or(() -> SigV4CredentialScope.serviceNameFromCredential( - ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential"))) + return SignedServiceRoute.signingService(ctx) .flatMap(catalog::byCredentialScope) .map(descriptor -> new ResolvedRequest( descriptor.externalKey(), protocolFor(claim, descriptor))) diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SignedServiceRoute.java b/src/main/java/io/github/hectorvent/floci/core/common/SignedServiceRoute.java new file mode 100644 index 0000000000..c953253bf5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/SignedServiceRoute.java @@ -0,0 +1,101 @@ +package io.github.hectorvent.floci.core.common; + +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.util.Optional; +import java.util.function.Predicate; + +/** + * Routes a REST service's paths that another controller also claims, by the service the request + * is signed for. A pre-matching filter calls {@link #apply} before JAX-RS route matching. + * + *

The service's controller registers the contested routes under an internal prefix. A request + * for one of the public paths that is signed for the service is rewritten onto that prefix; any + * other request keeps its path and reaches whichever controller claims it, usually S3's + * path-style {@code /{bucket}} routes. The signing service comes from the {@code Authorization} + * header's credential scope, or from the {@code X-Amz-Credential} query parameter on a + * query-signed request. + * + *

The internal prefix is itself a path S3 could claim, as bucket {@code _name}. A request sent + * straight to it that is not signed for the service is refused the way S3 refuses that bucket + * name, since an S3 bucket name may not begin with an underscore, rather than reaching the + * service. + */ +public final class SignedServiceRoute { + + private final ResolvedServiceCatalog catalog; + private final String externalKey; + private final String internalPrefix; + private final Predicate publicPaths; + + /** + * @param externalKey the service's external key, as {@link ServiceDescriptor#externalKey()} + * @param internalPrefix one path segment beginning with an underscore, such as {@code /_dlm} + * @param publicPaths which normalized request paths are the service's contested routes + */ + public SignedServiceRoute(ResolvedServiceCatalog catalog, String externalKey, String internalPrefix, + Predicate publicPaths) { + if (!internalPrefix.startsWith("/_") || internalPrefix.indexOf('/', 1) >= 0) { + throw new IllegalArgumentException("Internal prefix must be one segment starting with '/_': " + + internalPrefix); + } + this.catalog = catalog; + this.externalKey = externalKey; + this.internalPrefix = internalPrefix; + this.publicPaths = publicPaths; + } + + /** Matches {@code root} itself and every path beneath it. */ + public static Predicate under(String root) { + return path -> path.equals(root) || path.startsWith(root + "/"); + } + + /** + * The service a request is signed for, lower-cased, from the {@code Authorization} header or, + * failing that, the {@code X-Amz-Credential} query parameter. + */ + public static Optional signingService(ContainerRequestContext ctx) { + return SigV4CredentialScope.serviceName(ctx.getHeaderString("Authorization")) + .or(() -> SigV4CredentialScope.serviceNameFromCredential( + ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential"))); + } + + public void apply(ContainerRequestContext ctx) { + String path = ctx.getUriInfo().getPath(); + String normalizedPath = path.startsWith("/") ? path : "/" + path; + + if (under(internalPrefix).test(normalizedPath)) { + if (!signedForService(ctx)) { + ctx.abortWith(invalidBucketName()); + } + return; + } + if (!publicPaths.test(normalizedPath) || !signedForService(ctx)) { + return; + } + ctx.setRequestUri(ctx.getUriInfo().getRequestUriBuilder() + .replacePath(internalPrefix + normalizedPath) + .build()); + } + + private boolean signedForService(ContainerRequestContext ctx) { + return signingService(ctx) + .flatMap(catalog::byCredentialScope) + .map(ServiceDescriptor::externalKey) + .filter(externalKey::equals) + .isPresent(); + } + + private Response invalidBucketName() { + String bucket = internalPrefix.substring(1); + return Response.status(400) + .type(MediaType.APPLICATION_XML) + .entity("" + + "InvalidBucketName" + + "The specified bucket is not valid." + + "" + bucket + "") + .build(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java index 8c0d85c87c..61c1cf9021 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java @@ -129,6 +129,15 @@ public final class CfnRollback { */ public static final String API_KEY_UPDATE_SNAPSHOT_ATTR = "__FlociApiKeyUpdateSnapshot"; + /** + * Holds the role, object prefixes, tagging action and tags a GuardDuty Malware Protection plan + * carried before an in-place update changed them, or the plan an update created because the one + * the stack held was gone, so a failed stack update can put the plan back or delete the created + * one. Written by {@code GuardDutyMalwareProtectionPlanCfnProvisioner} before its first mutating + * call or right after that creation, and spent by its {@code rollbackUpdate}. + */ + public static final String GUARDDUTY_PLAN_UPDATE_SNAPSHOT_ATTR = "__FlociGuardDutyPlanUpdateSnapshot"; + /** * Holds the name and tags an API Gateway V2 VPC link carried before an in-place update changed * them, so a failed stack update can put them back. Written by {@code ApiGatewayV2CfnProvisioner} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java new file mode 100644 index 0000000000..5493bb3cae --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java @@ -0,0 +1,313 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +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 jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * CloudFormation provisioning for {@code AWS::GuardDuty::MalwareProtectionPlan}, backed by + * {@link GuardDutyService}. Management plane only: the plan is stored and reported, and no scan is + * performed. {@code Ref} and {@code Fn::GetAtt MalwareProtectionPlanId} are the plan id; + * {@code Arn}, {@code CreatedAt}, {@code Status} and {@code StatusReasons} are also set. + * + *

Role, object prefixes, the tagging action and tags update in place, and a property the + * template drops is cleared rather than left as it was. The bucket cannot change on an existing + * plan (the update API does not take it), so a different {@code BucketName} is refused rather than + * silently ignored. A failed stack update puts the plan back from a snapshot taken before the first + * mutating call. + */ +@ApplicationScoped +public class GuardDutyMalwareProtectionPlanCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(GuardDutyMalwareProtectionPlanCfnProvisioner.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static final String TYPE = "AWS::GuardDuty::MalwareProtectionPlan"; + private static final String NOT_FOUND = "ResourceNotFoundException"; + /** The attributes {@link #record} writes, which a rollback of a replacing create must put back. */ + private static final List RECORDED_ATTRIBUTES = + List.of("MalwareProtectionPlanId", "Arn", "CreatedAt", "Status", "StatusReasons"); + + private final GuardDutyService guardDutyService; + + @Inject + public GuardDutyMalwareProtectionPlanCfnProvisioner(GuardDutyService guardDutyService) { + this.guardDutyService = guardDutyService; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(CfnRollback.GUARDDUTY_PLAN_UPDATE_SNAPSHOT_ATTR); + boolean update = ctx.isUpdate() && ctx.priorPhysicalId() != null; + ObjectNode request = request(props, ctx, update); + Map tags = ctx.resolveTags(props, "Tags"); + + if (update) { + MalwareProtectionPlan existing = findPlan(ctx.priorPhysicalId(), ctx.region()); + if (existing != null) { + update(r, existing, request, tags, ctx); + return; + } + } + if (!tags.isEmpty()) { + ObjectNode tagNode = request.putObject("tags"); + tags.forEach(tagNode::put); + } + // Taken before record overwrites them, so a rollback can name the prior plan in full. + Map priorAttributes = update ? recordedAttributes(r) : Map.of(); + record(r, guardDutyService.createMalwareProtectionPlan(ctx.region(), ctx.accountId(), request)); + if (update) { + recordCreatedByUpdate(r, ctx, priorAttributes); + } + } + + private void update(StackResource r, MalwareProtectionPlan existing, ObjectNode request, + Map tags, ProvisionContext ctx) { + String bucket = request.path("protectedResource").path("s3Bucket").path("bucketName").asText(); + if (!Objects.equals(existing.getBucketName(), bucket)) { + throw new AwsException("ValidationError", + "Updating ProtectedResource/S3Bucket/BucketName requires resource replacement, " + + "which is not supported.", 400); + } + // The bucket and the idempotency token are not part of UpdateMalwareProtectionPlan. + request.remove("clientToken"); + if (request.path("protectedResource").path("s3Bucket") instanceof ObjectNode bucketNode) { + bucketNode.remove("bucketName"); + } + + snapshotBeforeUpdate(r, existing, ctx.region()); + try { + guardDutyService.updateMalwareProtectionPlan(ctx.region(), existing.getId(), request); + reconcileTags(existing, tags); + } catch (RuntimeException failure) { + // The stack skips rollbackUpdate for a resource whose own update failed, so undo it here. + try { + rollbackUpdate(r); + } catch (RuntimeException restoreFailure) { + r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, + "Could not roll back the update of Malware Protection plan " + existing.getId() + ": " + + restoreFailure.getMessage()); + if (restoreFailure != failure) { + failure.addSuppressed(restoreFailure); + } + } + throw failure; + } + record(r, guardDutyService.getMalwareProtectionPlan(ctx.region(), existing.getId())); + } + + /** + * Builds the Create/Update request body from the template's PascalCase properties. An update + * states every updatable property: one the template no longer has is sent empty, because the + * update API reads an absent field as "leave alone" and the plan would keep its old prefixes + * and tagging action while the stack reported UPDATE_COMPLETE. + */ + private static ObjectNode request(JsonNode props, ProvisionContext ctx, boolean update) { + ObjectNode request = JsonNodeFactory.instance.objectNode(); + String role = ctx.resolveOptional(props, "Role"); + if (role != null) { + request.put("role", role); + } + JsonNode resource = props != null && props.hasNonNull("ProtectedResource") + ? ctx.engine().resolveNode(props.get("ProtectedResource")) : null; + JsonNode s3Bucket = resource == null ? null : resource.path("S3Bucket"); + if (s3Bucket != null && s3Bucket.isObject()) { + ObjectNode bucket = request.putObject("protectedResource").putObject("s3Bucket"); + String bucketName = ctx.engine().resolve(s3Bucket.path("BucketName")); + if (bucketName != null && !bucketName.isBlank()) { + bucket.put("bucketName", bucketName); + } + JsonNode prefixes = s3Bucket.path("ObjectPrefixes"); + if (prefixes.isArray()) { + ArrayNode array = bucket.putArray("objectPrefixes"); + prefixes.forEach(prefix -> array.add(ctx.engine().resolve(prefix))); + } else if (update) { + bucket.putArray("objectPrefixes"); + } + } + JsonNode actions = props != null && props.hasNonNull("Actions") + ? ctx.engine().resolveNode(props.get("Actions")) : null; + JsonNode status = actions == null ? null : actions.path("Tagging").path("Status"); + if (status != null && !status.isMissingNode() && !status.isNull()) { + request.putObject("actions").putObject("tagging").put("status", ctx.engine().resolve(status)); + } else if (update) { + // An empty actions object clears the tagging action. + request.putObject("actions"); + } + return request; + } + + private void reconcileTags(MalwareProtectionPlan plan, Map desired) { + Map current = plan.getTags() == null ? Map.of() : plan.getTags(); + List stale = ProvisionContext.staleTagKeys(current, desired); + if (!stale.isEmpty()) { + guardDutyService.untagResource(plan.getArn(), stale); + } + boolean changed = desired.entrySet().stream() + .anyMatch(e -> !Objects.equals(current.get(e.getKey()), e.getValue())); + if (changed) { + guardDutyService.tagResource(plan.getArn(), desired); + } + } + + private MalwareProtectionPlan findPlan(String id, String region) { + try { + return guardDutyService.getMalwareProtectionPlan(region, id); + } catch (AwsException e) { + if (!NOT_FOUND.equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("Malware Protection plan {0} from the previous provision is gone, creating it again", id); + return null; + } + } + + private static void record(StackResource r, MalwareProtectionPlan plan) { + r.setPhysicalId(plan.getId()); + r.getAttributes().put("MalwareProtectionPlanId", plan.getId()); + r.getAttributes().put("Arn", plan.getArn()); + r.getAttributes().put("CreatedAt", plan.getCreatedAt()); + r.getAttributes().put("Status", plan.getStatus()); + // Floci never degrades a plan, so there are no status reasons to report. + r.getAttributes().put("StatusReasons", "[]"); + } + + private static Map recordedAttributes(StackResource r) { + Map attributes = new LinkedHashMap<>(); + for (String name : RECORDED_ATTRIBUTES) { + String value = r.getAttributes().get(name); + if (value != null) { + attributes.put(name, value); + } + } + return attributes; + } + + /** + * Records that this update created the plan because the one at the prior physical id was gone, + * so {@link #rollbackUpdate} can delete it and name the prior id again, with the attributes the + * resource reported for it rather than the ones written for the deleted replacement. + */ + private static void recordCreatedByUpdate(StackResource r, ProvisionContext ctx, + Map priorAttributes) { + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("region", ctx.region()); + snapshot.put("createdId", r.getPhysicalId()); + snapshot.put("priorId", ctx.priorPhysicalId()); + ObjectNode attributes = snapshot.putObject("priorAttributes"); + priorAttributes.forEach(attributes::put); + r.getAttributes().put(CfnRollback.GUARDDUTY_PLAN_UPDATE_SNAPSHOT_ATTR, snapshot.toString()); + } + + /** Captures what the update can change, as text on the resource, before the first mutating call. */ + private static void snapshotBeforeUpdate(StackResource r, MalwareProtectionPlan plan, String region) { + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("region", region); + snapshot.put("id", plan.getId()); + snapshot.put("role", plan.getRole()); + if (plan.getObjectPrefixes() != null) { + ArrayNode prefixes = snapshot.putArray("objectPrefixes"); + plan.getObjectPrefixes().forEach(prefixes::add); + } + if (plan.getTaggingStatus() != null) { + snapshot.put("taggingStatus", plan.getTaggingStatus()); + } + ObjectNode tags = snapshot.putObject("tags"); + if (plan.getTags() != null) { + plan.getTags().forEach(tags::put); + } + r.getAttributes().put(CfnRollback.GUARDDUTY_PLAN_UPDATE_SNAPSHOT_ATTR, snapshot.toString()); + } + + /** + * Undoes the update from the snapshot on the resource, and is also called by {@code update} when + * one of its own mutating calls fails. When the update created the plan because the one at the + * prior physical id was gone, the created plan is deleted and the resource names the prior id + * again. Otherwise the role, object prefixes, tagging action and tags are put back exactly as + * they were. With no snapshot on the resource the update changed nothing, since every mutating + * call is preceded by the snapshot or followed by the creation record. A plan deleted since the + * update fails the rollback with ResourceNotFoundException, and the stack reports it as failed. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + // The snapshot is spent only once the restore succeeded: a restore that throws leaves it in + // place for the next attempt instead of reporting a rollback that never happened. + String raw = resource.getAttributes().get(CfnRollback.GUARDDUTY_PLAN_UPDATE_SNAPSHOT_ATTR); + if (raw == null) { + return true; + } + JsonNode snapshot; + try { + snapshot = MAPPER.readTree(raw); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not read the Malware Protection plan update snapshot for " + + resource.getLogicalId(), e); + } + String region = snapshot.path("region").asText(); + if (snapshot.hasNonNull("createdId")) { + // Deleted before the resource names the prior id again, so a failed delete leaves the + // resource naming the created plan and deleting the stack still removes it. + delete(TYPE, snapshot.get("createdId").asText(), region); + String priorId = snapshot.path("priorId").asText(); + resource.setPhysicalId(priorId); + JsonNode priorAttributes = snapshot.path("priorAttributes"); + for (String name : RECORDED_ATTRIBUTES) { + JsonNode value = priorAttributes.get(name); + if (value != null && value.isTextual()) { + resource.getAttributes().put(name, value.asText()); + } else { + resource.getAttributes().remove(name); + } + } + resource.getAttributes().putIfAbsent("MalwareProtectionPlanId", priorId); + resource.getAttributes().remove(CfnRollback.GUARDDUTY_PLAN_UPDATE_SNAPSHOT_ATTR); + return true; + } + List prefixes = null; + if (snapshot.has("objectPrefixes")) { + prefixes = new ArrayList<>(); + for (JsonNode prefix : snapshot.get("objectPrefixes")) { + prefixes.add(prefix.asText()); + } + } + Map tags = new LinkedHashMap<>(); + snapshot.path("tags").fields().forEachRemaining(tag -> tags.put(tag.getKey(), tag.getValue().asText())); + guardDutyService.restoreMalwareProtectionPlan(region, snapshot.path("id").asText(), + snapshot.path("role").asText(), prefixes, + snapshot.hasNonNull("taggingStatus") ? snapshot.get("taggingStatus").asText() : null, tags); + resource.getAttributes().remove(CfnRollback.GUARDDUTY_PLAN_UPDATE_SNAPSHOT_ATTR); + return true; + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (physicalId == null || physicalId.isBlank()) { + return; + } + CfnDeletes.safeDelete("malware protection plan", physicalId, + () -> guardDutyService.deleteMalwareProtectionPlan(region, physicalId), NOT_FOUND); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/dlm/DlmRouteFilter.java b/src/main/java/io/github/hectorvent/floci/services/dlm/DlmRouteFilter.java index 0a876d9507..fae3043b46 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dlm/DlmRouteFilter.java +++ b/src/main/java/io/github/hectorvent/floci/services/dlm/DlmRouteFilter.java @@ -1,8 +1,7 @@ package io.github.hectorvent.floci.services.dlm; import io.github.hectorvent.floci.core.common.ResolvedServiceCatalog; -import io.github.hectorvent.floci.core.common.ServiceDescriptor; -import io.github.hectorvent.floci.core.common.SigV4CredentialScope; +import io.github.hectorvent.floci.core.common.SignedServiceRoute; import jakarta.inject.Inject; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerRequestFilter; @@ -19,36 +18,16 @@ import jakarta.ws.rs.ext.Provider; public class DlmRouteFilter implements ContainerRequestFilter { static final String INTERNAL_PREFIX = "/_dlm"; - private static final String DLM = "dlm"; - private static final String POLICIES_PATH = "/policies"; - private final ResolvedServiceCatalog catalog; + private final SignedServiceRoute route; @Inject public DlmRouteFilter(ResolvedServiceCatalog catalog) { - this.catalog = catalog; + this.route = new SignedServiceRoute(catalog, "dlm", INTERNAL_PREFIX, SignedServiceRoute.under("/policies")); } @Override public void filter(ContainerRequestContext ctx) { - String path = ctx.getUriInfo().getPath(); - String normalizedPath = path.startsWith("/") ? path : "/" + path; - if (!normalizedPath.equals(POLICIES_PATH) - && !normalizedPath.startsWith(POLICIES_PATH + "/")) { - return; - } - - boolean targetsDlm = SigV4CredentialScope.serviceName(ctx.getHeaderString("Authorization")) - .flatMap(catalog::byCredentialScope) - .map(ServiceDescriptor::externalKey) - .filter(DLM::equals) - .isPresent(); - if (!targetsDlm) { - return; - } - - ctx.setRequestUri(ctx.getUriInfo().getRequestUriBuilder() - .replacePath(INTERNAL_PREFIX + normalizedPath) - .build()); + route.apply(ctx); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java index bb34409bbc..20835810f4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java @@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.guardduty.model.Detector; import io.github.hectorvent.floci.services.guardduty.model.DetectorFeature; +import io.github.hectorvent.floci.services.guardduty.model.MalwareProtectionPlan; import io.github.hectorvent.floci.services.guardduty.model.MemberAccount; import io.github.hectorvent.floci.services.guardduty.model.OrganizationConfiguration; import io.github.hectorvent.floci.services.guardduty.model.OrganizationFeature; @@ -15,6 +16,7 @@ import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; +import jakarta.ws.rs.PATCH; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; @@ -25,12 +27,17 @@ import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; +import java.time.Instant; + /** - * GuardDuty (Smithy restJson1) — detector lifecycle and organization configuration. + * GuardDuty (Smithy restJson1): detector lifecycle, organization configuration and Malware + * Protection plans. * *

The literal {@code /detector} and {@code /admin} paths take JAX-RS precedence over S3's * {@code /{bucket}} and {@code /{bucket}/{key}} template routes, so these routes win with no - * extra routing wiring. Tag operations ({@code /tags/{arn}}) are served by + * extra routing wiring. {@code /malware-protection-plan} would win the same way, so + * {@link GuardDutyRouteFilter} moves only GuardDuty-signed requests for it to an internal prefix, + * and a path-style S3 request for a bucket of that name still reaches S3. Tag operations ({@code /tags/{arn}}) are served by * {@code SharedTagsController} via {@link GuardDutyTagHandler}. * *

GuardDuty reports every client error as {@code BadRequestException} (HTTP 400); the @@ -215,4 +222,75 @@ public class GuardDutyController { service.disableOrganizationAdminAccount(regionResolver.resolveRegion(headers), parse(body)); return Response.ok(objectMapper.createObjectNode()).build(); } + + @POST + @Path(GuardDutyRouteFilter.INTERNAL_PREFIX + GuardDutyRouteFilter.PLAN_PATH) + public Response createMalwareProtectionPlan(@Context HttpHeaders headers, String body) { + MalwareProtectionPlan plan = service.createMalwareProtectionPlan( + regionResolver.resolveRegion(headers), regionResolver.getAccountId(), parse(body)); + ObjectNode response = objectMapper.createObjectNode(); + response.put("malwareProtectionPlanId", plan.getId()); + return Response.ok(response).build(); + } + + @GET + @Path(GuardDutyRouteFilter.INTERNAL_PREFIX + GuardDutyRouteFilter.PLAN_PATH) + public Response listMalwareProtectionPlans( + @Context HttpHeaders headers, @QueryParam("nextToken") String nextToken) { + GuardDutyService.Page page = + service.listMalwareProtectionPlans(regionResolver.resolveRegion(headers), nextToken); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode plans = response.putArray("malwareProtectionPlans"); + for (MalwareProtectionPlan plan : page.items()) { + plans.addObject().put("malwareProtectionPlanId", plan.getId()); + } + if (page.nextToken() != null) { + response.put("nextToken", page.nextToken()); + } + return Response.ok(response).build(); + } + + @GET + @Path(GuardDutyRouteFilter.INTERNAL_PREFIX + GuardDutyRouteFilter.PLAN_PATH + "/{malwareProtectionPlanId}") + public Response getMalwareProtectionPlan( + @Context HttpHeaders headers, @PathParam("malwareProtectionPlanId") String planId) { + MalwareProtectionPlan plan = service.getMalwareProtectionPlan(regionResolver.resolveRegion(headers), planId); + ObjectNode response = objectMapper.createObjectNode(); + if (plan.getTaggingStatus() != null) { + response.putObject("actions").putObject("tagging").put("status", plan.getTaggingStatus()); + } + response.put("arn", plan.getArn()); + // The model types createdAt as a timestamp, which restJson1 carries as epoch seconds. + response.put("createdAt", Instant.parse(plan.getCreatedAt()).toEpochMilli() / 1000.0); + ObjectNode bucket = response.putObject("protectedResource").putObject("s3Bucket"); + bucket.put("bucketName", plan.getBucketName()); + if (plan.getObjectPrefixes() != null) { + ArrayNode prefixes = bucket.putArray("objectPrefixes"); + plan.getObjectPrefixes().forEach(prefixes::add); + } + response.put("role", plan.getRole()); + response.put("status", plan.getStatus()); + response.putArray("statusReasons"); + if (plan.getTags() != null && !plan.getTags().isEmpty()) { + ObjectNode tags = response.putObject("tags"); + plan.getTags().forEach(tags::put); + } + return Response.ok(response).build(); + } + + @PATCH + @Path(GuardDutyRouteFilter.INTERNAL_PREFIX + GuardDutyRouteFilter.PLAN_PATH + "/{malwareProtectionPlanId}") + public Response updateMalwareProtectionPlan( + @Context HttpHeaders headers, @PathParam("malwareProtectionPlanId") String planId, String body) { + service.updateMalwareProtectionPlan(regionResolver.resolveRegion(headers), planId, parse(body)); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + @DELETE + @Path(GuardDutyRouteFilter.INTERNAL_PREFIX + GuardDutyRouteFilter.PLAN_PATH + "/{malwareProtectionPlanId}") + public Response deleteMalwareProtectionPlan( + @Context HttpHeaders headers, @PathParam("malwareProtectionPlanId") String planId) { + service.deleteMalwareProtectionPlan(regionResolver.resolveRegion(headers), planId); + return Response.ok(objectMapper.createObjectNode()).build(); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyRouteFilter.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyRouteFilter.java new file mode 100644 index 0000000000..975f746080 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyRouteFilter.java @@ -0,0 +1,35 @@ +package io.github.hectorvent.floci.services.guardduty; + +import io.github.hectorvent.floci.core.common.ResolvedServiceCatalog; +import io.github.hectorvent.floci.core.common.SignedServiceRoute; +import jakarta.inject.Inject; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ContainerRequestFilter; +import jakarta.ws.rs.container.PreMatching; +import jakarta.ws.rs.ext.Provider; + +/** + * Rewrites GuardDuty Malware Protection plan requests to an internal prefix before JAX-RS route + * matching. Registered directly, {@code /malware-protection-plan} would outrank S3's + * {@code /{bucket}} routes, so a path-style request for a bucket of that name would reach GuardDuty. + * Only a request signed for GuardDuty is rewritten; anything else falls through to S3. + */ +@Provider +@PreMatching +public class GuardDutyRouteFilter implements ContainerRequestFilter { + + static final String INTERNAL_PREFIX = "/_guardduty"; + static final String PLAN_PATH = "/malware-protection-plan"; + + private final SignedServiceRoute route; + + @Inject + public GuardDutyRouteFilter(ResolvedServiceCatalog catalog) { + this.route = new SignedServiceRoute(catalog, "guardduty", INTERNAL_PREFIX, SignedServiceRoute.under(PLAN_PATH)); + } + + @Override + public void filter(ContainerRequestContext ctx) { + route.apply(ctx); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java index 1a66494ddc..6443863730 100644 --- a/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java @@ -8,12 +8,14 @@ import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.Base64Url; import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.guardduty.model.AdminAccount; import io.github.hectorvent.floci.services.guardduty.model.Detector; import io.github.hectorvent.floci.services.guardduty.model.DetectorAdditionalConfiguration; import io.github.hectorvent.floci.services.guardduty.model.DetectorFeature; +import io.github.hectorvent.floci.services.guardduty.model.MalwareProtectionPlan; import io.github.hectorvent.floci.services.guardduty.model.MemberAccount; import io.github.hectorvent.floci.services.guardduty.model.OrganizationAdditionalConfiguration; import io.github.hectorvent.floci.services.guardduty.model.OrganizationConfiguration; @@ -64,6 +66,21 @@ public class GuardDutyService { private static final Set FINDING_PUBLISHING_FREQUENCIES = Set.of("FIFTEEN_MINUTES", "ONE_HOUR", "SIX_HOURS"); private static final Set FEATURE_STATUSES = Set.of("ENABLED", "DISABLED"); + private static final int MAX_PLAN_OBJECT_PREFIXES = 5; + private static final int MAX_PLAN_OBJECT_PREFIX_LENGTH = 1024; + private static final int MAX_PLAN_TAGS = 200; + /** + * GuardDuty's documented TagKey pattern, {@code ^(?!aws:)[a-zA-Z+-=._:/]+$}, kept verbatim: the + * {@code +-=} range spans the digits and {@code , - . / : ; <}, so a space, {@code @} or + * {@code #} is rejected while a digit is not. + */ + private static final Pattern PLAN_TAG_KEY_PATTERN = Pattern.compile("^(?!aws:)[a-zA-Z+-=._:/]+$"); + /** The documented default page size of ListMalwareProtectionPlans. */ + private static final int PLAN_PAGE_SIZE = 100; + private static final String PLAN_TOKEN_PREFIX = "guardduty:v1:plan:"; + private static final String PLAN_ARN_RESOURCE_PREFIX = "malware-protection-plan/"; + static final String PLAN_NOT_FOUND_MESSAGE = + "The request is rejected because the input malwareProtectionPlanId is not owned by the current account."; private static final Set ORG_AUTO_ENABLE_VALUES = Set.of("NEW", "NONE", "ALL"); private static final Set DETECTOR_FEATURE_NAMES = Set.of( "S3_DATA_EVENTS", "EKS_AUDIT_LOGS", "EBS_MALWARE_PROTECTION", "RDS_LOGIN_EVENTS", @@ -78,6 +95,7 @@ public class GuardDutyService { private final StorageBackend detectorStore; private final StorageBackend adminAccountStore; private final StorageBackend memberStore; + private final StorageBackend malwareProtectionPlanStore; @Inject public GuardDutyService(StorageFactory storageFactory) { @@ -95,16 +113,31 @@ public class GuardDutyService { "guardduty", "guardduty-members.json", new TypeReference>() { + }), + storageFactory.create( + "guardduty", + "guardduty-malware-protection-plans.json", + new TypeReference>() { })); } + // Keeps the three-store arity existing fixtures construct this service with. + GuardDutyService( + StorageBackend detectorStore, + StorageBackend adminAccountStore, + StorageBackend memberStore) { + this(detectorStore, adminAccountStore, memberStore, new InMemoryStorage<>()); + } + GuardDutyService( StorageBackend detectorStore, StorageBackend adminAccountStore, - StorageBackend memberStore) { + StorageBackend memberStore, + StorageBackend malwareProtectionPlanStore) { this.detectorStore = detectorStore; this.adminAccountStore = adminAccountStore; this.memberStore = memberStore; + this.malwareProtectionPlanStore = malwareProtectionPlanStore; } public synchronized Detector createDetector(String region, String accountId, JsonNode request) { @@ -327,12 +360,307 @@ public class GuardDutyService { } return true; } + // ── Malware Protection plans ───────────────────────────────────────────────── + + public synchronized MalwareProtectionPlan createMalwareProtectionPlan( + String region, String accountId, JsonNode request) { + JsonNode resource = request.get("protectedResource"); + requireObject(resource, "protectedResource"); + JsonNode bucket = resource.get("s3Bucket"); + requireObject(bucket, "protectedResource.s3Bucket"); + String bucketName = requireText(bucket, "bucketName"); + if (bucketName.length() < 3 || bucketName.length() > 63) { + throw badRequest("bucketName must be between 3 and 63 characters."); + } + String role = readRole(request); + List prefixes = readObjectPrefixes(bucket); + String taggingStatus = readTaggingStatus(request); + Map tags = readPlanTags(request); + String clientToken = request.hasNonNull("clientToken") ? requireText(request, "clientToken") : null; + if (clientToken != null && clientToken.length() > 64) { + throw badRequest("clientToken must be at most 64 characters."); + } + + String prefix = region + "::"; + List existing = malwareProtectionPlanStore.scan(key -> key.startsWith(prefix)); + if (clientToken != null) { + for (MalwareProtectionPlan plan : existing) { + if (clientToken.equals(plan.getClientToken())) { + return plan; + } + } + } + for (MalwareProtectionPlan plan : existing) { + if (bucketName.equals(plan.getBucketName())) { + throw new AwsException("ConflictException", + "A Malware Protection plan already exists for the bucket " + bucketName + ".", 409); + } + } + + MalwareProtectionPlan plan = new MalwareProtectionPlan(); + plan.setId(UUID.randomUUID().toString().replace("-", "")); + plan.setArn(AwsArnUtils.Arn.of("guardduty", region, accountId, PLAN_ARN_RESOURCE_PREFIX + plan.getId()) + .toString()); + plan.setRole(role); + plan.setBucketName(bucketName); + plan.setObjectPrefixes(prefixes); + plan.setTaggingStatus(taggingStatus); + plan.setStatus("ACTIVE"); + plan.setCreatedAt(isoTimestamp()); + plan.setClientToken(clientToken); + plan.setTags(tags); + malwareProtectionPlanStore.put(storageKey(region, plan.getId()), plan); + return plan; + } + + public MalwareProtectionPlan getMalwareProtectionPlan(String region, String planId) { + return malwareProtectionPlanStore.get(storageKey(region, planId)) + .orElseThrow(GuardDutyService::planNotFound); + } + + /** Only role, object prefixes and the tagging action can change; the bucket is fixed at creation. */ + public synchronized void updateMalwareProtectionPlan(String region, String planId, JsonNode request) { + String key = storageKey(region, planId); + MalwareProtectionPlan plan = malwareProtectionPlanStore.get(key).orElseThrow(GuardDutyService::planNotFound); + + // Every supplied field is validated before any of them is applied: the store hands back the + // live object, so a change made before a later field is rejected would outlive the 400. + boolean roleSupplied = request.has("role"); + String role = roleSupplied ? readRole(request) : null; + JsonNode resource = request.get("protectedResource"); + boolean prefixesSupplied = false; + List prefixes = null; + if (resource != null && resource.has("s3Bucket")) { + JsonNode bucket = resource.get("s3Bucket"); + requireObject(bucket, "protectedResource.s3Bucket"); + prefixesSupplied = bucket.has("objectPrefixes"); + prefixes = prefixesSupplied ? readObjectPrefixes(bucket) : null; + } + boolean actionsSupplied = request.has("actions"); + String taggingStatus = actionsSupplied ? readTaggingStatus(request) : null; + + if (roleSupplied) { + plan.setRole(role); + } + if (prefixesSupplied) { + plan.setObjectPrefixes(prefixes); + } + if (actionsSupplied) { + plan.setTaggingStatus(taggingStatus); + } + malwareProtectionPlanStore.put(key, plan); + } + + /** + * Puts a plan's mutable settings back exactly as given, nulls included. Not an AWS operation: + * it is how a failed CloudFormation stack update undoes an in-place change, which the partial + * update above cannot express because it treats an absent field as "leave alone". + */ + public synchronized void restoreMalwareProtectionPlan(String region, String planId, String role, + List objectPrefixes, String taggingStatus, Map tags) { + String key = storageKey(region, planId); + MalwareProtectionPlan plan = malwareProtectionPlanStore.get(key).orElseThrow(GuardDutyService::planNotFound); + plan.setRole(role); + plan.setObjectPrefixes(objectPrefixes); + plan.setTaggingStatus(taggingStatus); + plan.setTags(tags); + malwareProtectionPlanStore.put(key, plan); + } + + public synchronized void deleteMalwareProtectionPlan(String region, String planId) { + String key = storageKey(region, planId); + if (malwareProtectionPlanStore.get(key).isEmpty()) { + throw planNotFound(); + } + malwareProtectionPlanStore.delete(key); + } + + /** + * Pages by plan id rather than position: the token names the last id returned and the next page + * starts at the first id after it, so a plan created or deleted between pages (the token's own + * plan included) neither fails the request nor skips or repeats a plan. + */ + public Page listMalwareProtectionPlans(String region, String nextToken) { + String prefix = region + "::"; + String after = decodePlanToken(nextToken); + List remaining = malwareProtectionPlanStore.scan(key -> key.startsWith(prefix)).stream() + .sorted(Comparator.comparing(MalwareProtectionPlan::getId)) + .filter(plan -> after == null || plan.getId().compareTo(after) > 0) + .toList(); + if (remaining.size() <= PLAN_PAGE_SIZE) { + return new Page<>(remaining, null); + } + List page = remaining.subList(0, PLAN_PAGE_SIZE); + return new Page<>(page, encodePlanToken(page.get(page.size() - 1).getId())); + } + + private static String encodePlanToken(String lastId) { + return Base64.getUrlEncoder().withoutPadding() + .encodeToString((PLAN_TOKEN_PREFIX + lastId).getBytes(StandardCharsets.UTF_8)); + } + + private static String decodePlanToken(String token) { + if (token == null) { + return null; + } + try { + String decoded = new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8); + if (decoded.startsWith(PLAN_TOKEN_PREFIX) && decoded.length() > PLAN_TOKEN_PREFIX.length()) { + return decoded.substring(PLAN_TOKEN_PREFIX.length()); + } + } catch (IllegalArgumentException e) { + // falls through to the rejection below + } + throw badRequest("nextToken is invalid."); + } + + /** The role must be an IAM role ARN; any other well-formed ARN is rejected. */ + private static String readRole(JsonNode request) { + String role = requireText(request, "role"); + boolean iamRole; + try { + AwsArnUtils.Arn arn = AwsArnUtils.parse(role); + iamRole = "iam".equals(arn.service()) && arn.resource().startsWith("role/") + && arn.resource().length() > "role/".length(); + } catch (IllegalArgumentException e) { + iamRole = false; + } + if (!iamRole) { + throw badRequest("role must be the ARN of an IAM role."); + } + return role; + } + + private static List readObjectPrefixes(JsonNode bucket) { + if (!bucket.has("objectPrefixes")) { + return null; + } + JsonNode node = bucket.get("objectPrefixes"); + if (!node.isArray() || node.size() > MAX_PLAN_OBJECT_PREFIXES) { + throw badRequest("objectPrefixes must be an array of at most " + MAX_PLAN_OBJECT_PREFIXES + " strings."); + } + List prefixes = new ArrayList<>(node.size()); + for (JsonNode item : node) { + if (!item.isTextual() || item.textValue().length() > MAX_PLAN_OBJECT_PREFIX_LENGTH) { + throw badRequest("objectPrefixes must contain strings of at most " + + MAX_PLAN_OBJECT_PREFIX_LENGTH + " characters."); + } + prefixes.add(item.textValue()); + } + // An empty list means "the whole bucket", the same as none, so it is stored as none and a + // plan created without prefixes and one updated to have none read back identically. + return prefixes.isEmpty() ? null : prefixes; + } + + private static String readTaggingStatus(JsonNode request) { + JsonNode actions = request.get("actions"); + if (actions == null || actions.isNull()) { + return null; + } + requireObject(actions, "actions"); + JsonNode tagging = actions.get("tagging"); + if (tagging == null || tagging.isNull()) { + return null; + } + requireObject(tagging, "actions.tagging"); + String status = requireText(tagging, "status"); + if (!FEATURE_STATUSES.contains(status)) { + throw badRequest("actions.tagging.status must be ENABLED or DISABLED."); + } + return status; + } + + private static Map readPlanTags(JsonNode request) { + if (!request.has("tags")) { + return null; + } + JsonNode tagsNode = request.get("tags"); + if (!tagsNode.isObject() || tagsNode.size() > MAX_PLAN_TAGS) { + throw badRequest("tags must be an object with at most " + MAX_PLAN_TAGS + " entries."); + } + Map tags = new LinkedHashMap<>(); + tagsNode.fields().forEachRemaining(entry -> { + JsonNode valueNode = entry.getValue(); + if (!valueNode.isTextual()) { + throw badRequest("tags contains a non-string value."); + } + requireValidPlanTag(entry.getKey(), valueNode.textValue()); + tags.put(entry.getKey(), valueNode.textValue()); + }); + return tags; + } + + /** The tag rules of a Malware Protection plan, shared by creation and the tag routes. */ + private static void requireValidPlanTag(String key, String value) { + if (key.length() > 128 || !PLAN_TAG_KEY_PATTERN.matcher(key).matches()) { + throw badRequest("tags contains an invalid key: " + key); + } + if (value.length() > 256) { + throw badRequest("tags contains a value longer than 256 characters."); + } + } + + private static boolean isMalwareProtectionPlanArn(String arn) { + try { + return AwsArnUtils.parse(arn).resource().startsWith(PLAN_ARN_RESOURCE_PREFIX); + } catch (IllegalArgumentException e) { + return false; + } + } + + /** + * Resolves the plan a tag route names. The store is keyed by region and id alone, so the whole + * supplied ARN must equal the stored plan's: a matching id under another partition, service or + * account does not identify this plan. + */ + private MalwareProtectionPlan planFromArn(String arn, DetectorRef ref) { + MalwareProtectionPlan plan = malwareProtectionPlanStore.get(ref.key()) + .orElseThrow(GuardDutyService::planNotFound); + if (!arn.equals(plan.getArn())) { + throw planNotFound(); + } + return plan; + } + + private static DetectorRef parsePlanArn(String arn) { + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String id = parsed.resource().substring(PLAN_ARN_RESOURCE_PREFIX.length()); + if (id.isEmpty()) { + throw badRequest("The request is rejected because an invalid resource ARN is specified: " + arn); + } + return new DetectorRef(parsed.region(), id); + } + + private static AwsException planNotFound() { + return new AwsException("ResourceNotFoundException", PLAN_NOT_FOUND_MESSAGE, 404); + } + public Map listTags(String arn) { + if (isMalwareProtectionPlanArn(arn)) { + MalwareProtectionPlan plan = planFromArn(arn, parsePlanArn(arn)); + return plan.getTags() == null ? Map.of() : plan.getTags(); + } Detector detector = detectorFromArn(arn); return detector.getTags() == null ? Map.of() : detector.getTags(); } public synchronized void tagResource(String arn, Map tags) { + if (isMalwareProtectionPlanArn(arn)) { + DetectorRef ref = parsePlanArn(arn); + MalwareProtectionPlan plan = planFromArn(arn, ref); + tags.forEach(GuardDutyService::requireValidPlanTag); + Map merged = new LinkedHashMap<>(); + if (plan.getTags() != null) { + merged.putAll(plan.getTags()); + } + merged.putAll(tags); + if (merged.size() > MAX_PLAN_TAGS) { + throw badRequest("A Malware Protection plan can have at most " + MAX_PLAN_TAGS + " tags."); + } + plan.setTags(merged); + malwareProtectionPlanStore.put(ref.key(), plan); + return; + } DetectorRef ref = parseDetectorArn(arn); Detector detector = detectorStore.get(ref.key()).orElseThrow(GuardDutyService::detectorNotFound); Map merged = new LinkedHashMap<>(); @@ -345,6 +673,18 @@ public class GuardDutyService { } public synchronized void untagResource(String arn, List tagKeys) { + if (isMalwareProtectionPlanArn(arn)) { + DetectorRef ref = parsePlanArn(arn); + MalwareProtectionPlan plan = planFromArn(arn, ref); + if (plan.getTags() == null) { + return; + } + Map remaining = new LinkedHashMap<>(plan.getTags()); + tagKeys.forEach(remaining::remove); + plan.setTags(remaining); + malwareProtectionPlanStore.put(ref.key(), plan); + return; + } DetectorRef ref = parseDetectorArn(arn); Detector detector = detectorStore.get(ref.key()).orElseThrow(GuardDutyService::detectorNotFound); if (detector.getTags() == null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/guardduty/model/MalwareProtectionPlan.java b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/MalwareProtectionPlan.java new file mode 100644 index 0000000000..f7c8e1dcb3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/guardduty/model/MalwareProtectionPlan.java @@ -0,0 +1,110 @@ +package io.github.hectorvent.floci.services.guardduty.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; +import java.util.Map; + +/** + * A GuardDuty Malware Protection plan for an S3 bucket. Management plane only: the plan is + * stored and reported, and no scan is performed, so it stays {@code ACTIVE} for its whole life. + */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class MalwareProtectionPlan { + private String id; + private String arn; + private String role; + private String bucketName; + private List objectPrefixes; + /** {@code ENABLED} or {@code DISABLED}; null when the plan was created with no actions. */ + private String taggingStatus; + private String status; + private String createdAt; + private String clientToken; + private Map tags; + + public MalwareProtectionPlan() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getArn() { + return arn; + } + + public void setArn(String arn) { + this.arn = arn; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getBucketName() { + return bucketName; + } + + public void setBucketName(String bucketName) { + this.bucketName = bucketName; + } + + public List getObjectPrefixes() { + return objectPrefixes; + } + + public void setObjectPrefixes(List objectPrefixes) { + this.objectPrefixes = objectPrefixes == null ? null : List.copyOf(objectPrefixes); + } + + public String getTaggingStatus() { + return taggingStatus; + } + + public void setTaggingStatus(String taggingStatus) { + this.taggingStatus = taggingStatus; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(String createdAt) { + this.createdAt = createdAt; + } + + public String getClientToken() { + return clientToken; + } + + public void setClientToken(String clientToken) { + this.clientToken = clientToken; + } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags == null ? null : Map.copyOf(tags); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Controller.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Controller.java index b3123d54b8..6f1edcd324 100644 --- a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Controller.java +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Controller.java @@ -48,7 +48,7 @@ public class ResourceExplorer2Controller { } @POST - @Path("/re2/ListResources") + @Path(ResourceExplorer2PathRewriteFilter.INTERNAL_PREFIX + "/ListResources") public Response listResources(@Context HttpHeaders headers, String body) throws IOException { JsonNode req = parseBody(body); String region = regionResolver.resolveRegion(headers); @@ -89,7 +89,7 @@ public class ResourceExplorer2Controller { } @POST - @Path("/re2/CreateIndex") + @Path(ResourceExplorer2PathRewriteFilter.INTERNAL_PREFIX + "/CreateIndex") public Response createIndex(@Context HttpHeaders headers, String body) throws IOException { JsonNode req = parseBody(body); String region = regionResolver.resolveRegion(headers); @@ -105,7 +105,7 @@ public class ResourceExplorer2Controller { } @POST - @Path("/re2/GetIndex") + @Path(ResourceExplorer2PathRewriteFilter.INTERNAL_PREFIX + "/GetIndex") public Response getIndex(@Context HttpHeaders headers) { String region = regionResolver.resolveRegion(headers); Index index = service.getIndex(region); @@ -122,7 +122,7 @@ public class ResourceExplorer2Controller { } @POST - @Path("/re2/DeleteIndex") + @Path(ResourceExplorer2PathRewriteFilter.INTERNAL_PREFIX + "/DeleteIndex") public Response deleteIndex(String body) throws IOException { JsonNode req = parseBody(body); String indexArn = optString(req, "Arn"); @@ -138,7 +138,7 @@ public class ResourceExplorer2Controller { } @POST - @Path("/re2/ListIndexes") + @Path(ResourceExplorer2PathRewriteFilter.INTERNAL_PREFIX + "/ListIndexes") public Response listIndexes(String body) throws IOException { JsonNode req = parseBody(body); String type = optString(req, "Type"); diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PathRewriteFilter.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PathRewriteFilter.java index 804988cb51..5adee91465 100644 --- a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PathRewriteFilter.java +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PathRewriteFilter.java @@ -1,8 +1,7 @@ package io.github.hectorvent.floci.services.resourceexplorer2; import io.github.hectorvent.floci.core.common.ResolvedServiceCatalog; -import io.github.hectorvent.floci.core.common.ServiceDescriptor; -import io.github.hectorvent.floci.core.common.SigV4CredentialScope; +import io.github.hectorvent.floci.core.common.SignedServiceRoute; import jakarta.inject.Inject; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerRequestFilter; @@ -20,7 +19,7 @@ import java.util.Set; * named operations apart. Floci resolves this the same way {@code AwsQueryController} resolves * query-protocol services: by the SigV4 credential scope, looked up in the * {@link ResolvedServiceCatalog}. When the scope resolves to the Resource Explorer 2 service, - * the conflicting path is rewritten to the {@code /re2/} prefix so it reaches + * the conflicting path is rewritten to the {@value #INTERNAL_PREFIX} prefix so it reaches * {@link ResourceExplorer2Controller}; otherwise it falls through to the S3 Vectors controller. * *

All other Resource Explorer 2 paths (e.g. {@code /ListResources}, {@code /Search}) are @@ -30,7 +29,7 @@ import java.util.Set; @PreMatching public class ResourceExplorer2PathRewriteFilter implements ContainerRequestFilter { - private static final String RESOURCE_EXPLORER_2 = "resource-explorer-2"; + static final String INTERNAL_PREFIX = "/_re2"; // Mirror of the index operation paths declared by S3VectorsController. A colliding path missing // from this set falls through to S3 Vectors even for Resource Explorer 2 callers. @@ -42,35 +41,16 @@ public class ResourceExplorer2PathRewriteFilter implements ContainerRequestFilte "/ListResources" ); - private final ResolvedServiceCatalog catalog; + private final SignedServiceRoute route; @Inject public ResourceExplorer2PathRewriteFilter(ResolvedServiceCatalog catalog) { - this.catalog = catalog; + this.route = new SignedServiceRoute(catalog, "resource-explorer-2", INTERNAL_PREFIX, + AMBIGUOUS_PATHS::contains); } @Override public void filter(ContainerRequestContext ctx) { - String path = ctx.getUriInfo().getPath(); - String normalizedPath = path.startsWith("/") ? path : "/" + path; - - if (!AMBIGUOUS_PATHS.contains(normalizedPath)) { - return; - } - - boolean targetsResourceExplorer2 = - SigV4CredentialScope.serviceName(ctx.getHeaderString("Authorization")) - .flatMap(catalog::byCredentialScope) - .map(ServiceDescriptor::externalKey) - .filter(RESOURCE_EXPLORER_2::equals) - .isPresent(); - - if (!targetsResourceExplorer2) { - return; - } - - ctx.setRequestUri(ctx.getUriInfo().getRequestUriBuilder() - .replacePath("/re2" + normalizedPath) - .build()); + route.apply(ctx); } } diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index e537dc8718..ab4552a746 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -457,6 +457,7 @@ "AWS::Events::Rule": [ "Name" ], + "AWS::GuardDuty::MalwareProtectionPlan": [], "AWS::IAM::AccessKey": [ "UserName", "Serial" diff --git a/src/test/java/io/github/hectorvent/floci/core/common/SignedServiceRouteIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/SignedServiceRouteIntegrationTest.java new file mode 100644 index 0000000000..b0f02fd3cd --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/SignedServiceRouteIntegrationTest.java @@ -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("InvalidBucketName")); + given().when().get(path) + .then().statusCode(400) + .body(containsString("InvalidBucketName")); + } + + @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()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/SignedServiceRouteTest.java b/src/test/java/io/github/hectorvent/floci/core/common/SignedServiceRouteTest.java new file mode 100644 index 0000000000..7d5ab37930 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/SignedServiceRouteTest.java @@ -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 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)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 59cdf76365..d4bc04ce26 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -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; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/GuardDutyMalwareProtectionPlanCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/GuardDutyMalwareProtectionPlanCfnIntegrationTest.java new file mode 100644 index 0000000000..5dd08c041b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/GuardDutyMalwareProtectionPlanCfnIntegrationTest.java @@ -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("CREATE_COMPLETE")) + .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("" + expectedStatus + "")) + .extract().asString(); + } + + private static void cloudFormation(String action, Map 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 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("" + expectedStatus + "")) + .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(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisionerTest.java new file mode 100644 index 0000000000..a226faad55 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisionerTest.java @@ -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; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanIntegrationTest.java new file mode 100644 index 0000000000..667bf08fc7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanIntegrationTest.java @@ -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"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java new file mode 100644 index 0000000000..9997aab865 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java @@ -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.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 first = service.listMalwareProtectionPlans(REGION, null); + assertEquals(100, first.items().size()); + assertTrue(first.nextToken() != null); + + GuardDutyService.Page 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 first = service.listMalwareProtectionPlans(REGION, null); + List 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 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 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 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); + } + } +} diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 6ec22b887c..e476c6de93 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -108,6 +108,7 @@ AWS::Events::Archive EventsArchiveCfnProvisioner AWS::Events::EventBus EventsCfnProvisioner AWS::Events::EventBusPolicy EventsCfnProvisioner AWS::Events::Rule EventsCfnProvisioner +AWS::GuardDuty::MalwareProtectionPlan GuardDutyMalwareProtectionPlanCfnProvisioner AWS::IAM::AccessKey IamAccessKeyCfnProvisioner AWS::IAM::InstanceProfile IamInstanceProfileCfnProvisioner AWS::IAM::ManagedPolicy IamManagedPolicyCfnProvisioner diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 0f32406c87..21fcf85b91 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -46,6 +46,7 @@ order: - AWS::Scheduler - AWS::Transfer - AWS::Backup + - AWS::GuardDuty - AWS::Pipes - AWS::Kinesis - AWS::KinesisFirehose @@ -139,6 +140,7 @@ service_labels: AWS::EKS: EKS AWS::ElasticLoadBalancingV2: Elastic Load Balancing v2 AWS::Events: EventBridge + AWS::GuardDuty: GuardDuty AWS::IAM: IAM AWS::IoT: IoT Core AWS::KMS: KMS @@ -195,6 +197,7 @@ notes: AWS::Cognito::UserPool: '`ProviderURL` is the local issuer of the tokens Floci mints, `/`' AWS::Events::Archive: '`KmsKeyIdentifier` is ignored' AWS::CloudFront::Function: '`KeyValueStoreAssociations` is ignored' + AWS::GuardDuty::MalwareProtectionPlan: 'management plane only: no scan runs, so the plan stays ACTIVE; Ref returns the plan id; a BucketName change is rejected' AWS::BedrockAgentCore::Runtime: 'Ref returns the AgentRuntimeId; CapacityProviderConfiguration, FilesystemConfigurations, LifecycleConfiguration, PlatformVersion and RequestHeaderConfiguration are accepted and not stored' AWS::BedrockAgentCore::RuntimeEndpoint: 'Ref returns the endpoint ARN; Tags are accepted and not stored' AWS::BedrockAgentCore::Memory: 'Ref returns the memory ARN; MemoryStrategies, IndexedKeys, NamespaceKeys and StreamDeliveryResources are accepted and not stored'