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