Skip to content

feat(guardduty): add Malware Protection plans and AWS::GuardDuty::MalwareProtectionPlan - #5373

Merged
pgermosen merged 8 commits into
floci-io:mainfrom
upwardsolutions-inc:feat/guardduty-malware-protection-plan
Oct 13, 2026
Merged

pgermosen merged 8 commits into
floci-io:mainfrom
upwardsolutions-inc:feat/guardduty-malware-protection-plan

Conversation

@upwardsolutions-inc

Copy link
Copy Markdown
Contributor

Summary

GuardDuty had detectors, members and organization configuration but no Malware Protection plan operations, and AWS::GuardDuty::MalwareProtectionPlan was not provisioned. With FLOCI_SERVICES_CLOUDFORMATION_ALLOW_STUB_UNSUPPORTED_RESOURCE_TYPES=false a stack using it rolled back; by default it reported CREATE_COMPLETE and created nothing.

  • Adds CreateMalwareProtectionPlan, GetMalwareProtectionPlan, UpdateMalwareProtectionPlan (PATCH), DeleteMalwareProtectionPlan and ListMalwareProtectionPlans.
  • Plan ARNs (arn:aws:guardduty:<region>:<account>:malware-protection-plan/<id>) work with the shared TagResource, UntagResource and ListTagsForResource routes.
  • Adds a CloudFormation provisioner. Ref and Fn::GetAtt MalwareProtectionPlanId return the plan id; Arn, CreatedAt, Status and StatusReasons are set. Role, object prefixes, the tagging action and tags update in place.
  • Management plane only, as the issue suggests: no scan runs, no GuardDutyMalwareScanStatus tag is written and no scan-result event is published, so a plan stays ACTIVE with no status reasons. Scan emulation can follow separately.

Behaviours worth a look in review:

  • A second plan for the same bucket in an account and region returns ConflictException (409), unless it repeats the earlier request's clientToken, which returns the existing plan. The conflict rule is inferred from AWS allowing one plan per bucket; it is not spelled out in the API reference.
  • The bucket cannot change on an existing plan (UpdateMalwareProtectionPlan does not take it). A BucketName change in a stack update is rejected with a ValidationError instead of being silently ignored.
  • createdAt is returned as epoch seconds, as the API reference types it as a timestamp.
  • The three-store GuardDutyService constructor is kept as an overload so existing fixtures are unchanged.

Closes #4657

Type of change

  • New feature (feat:)

AWS Compatibility

Request and response shapes, the ACTIVE | WARNING | ERROR status values, the 5-prefix limit and tag rules follow those pages. Not checked against a real AWS account.

Checklist

  • PR title follows Conventional Commits
  • Tests added: 14 service unit tests, 6 HTTP lifecycle tests, 2 CloudFormation stack tests
  • Docs updated: docs/services/guardduty.md; the CloudFormation table is regenerated (regen_cfn_resource_types.py --strict passes)
  • Ran the new tests and the existing GuardDuty, CloudFormation inventory, create-only, schema-coverage and routing tests (78 tests, 0 failures). The full suite was not run locally.

@qodo-code-review

qodo-code-review Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Add GuardDuty Malware Protection plans and CloudFormation provisioning

✨ Enhancement 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Add persistent GuardDuty Malware Protection plan operations, pagination, and shared ARN-based
 tagging.
• Provision plans through CloudFormation, including in-place updates and failed-update rollback.
• Document management-plane-only behavior and test API, stack, and S3 routing workflows.
Diagram

graph TD
  Requests["HTTP requests"] --> Filter["Route filter"] --> API["GuardDuty API"] --> Service["Plan service"] --> Store["Plan storage"]
  Filter --> S3["S3 routes"]
  CloudFormation --> Provisioner["Plan provisioner"] --> Service
Loading
High-Level Assessment

Using the existing GuardDuty service and CloudFormation provisioner pattern is the best fit for management-plane support. A stub would leave stacks without a plan, while adding scan emulation now would substantially expand the scope.

Files changed (16) +2010 / -8

Enhancement (6) +907 / -2
CfnRollback.javaDefine GuardDuty plan update snapshot attribute +9/-0

Define GuardDuty plan update snapshot attribute

• Adds the resource attribute key used to retain plan state for failed CloudFormation update rollback.

src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java

GuardDutyMalwareProtectionPlanCfnProvisioner.javaProvision and roll back GuardDuty plans +313/-0

Provision and roll back GuardDuty plans

• Adds CloudFormation create, update, delete, attributes, and tag reconciliation for plans. Rejects bucket changes, clears removed optional settings, and restores or removes plans after failed updates.

src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java

GuardDutyController.javaExpose Malware Protection plan HTTP operations +80/-2

Expose Malware Protection plan HTTP operations

• Adds create, get, patch, delete, and list endpoints with plan response shapes and epoch-seconds creation timestamps.

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java

GuardDutyRouteFilter.javaSeparate GuardDuty plan paths from S3 bucket paths +55/-0

Separate GuardDuty plan paths from S3 bucket paths

• Rewrites GuardDuty-signed plan requests to internal routes so a path-style S3 bucket with the same name remains accessible.

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyRouteFilter.java

GuardDutyService.javaImplement persistent plan lifecycle and tagging +340/-0

Implement persistent plan lifecycle and tagging

• Adds plan storage, validation, idempotent creation, bucket conflicts, atomic updates, restoration, and ID-based pagination. Extends shared tag operations to exact plan ARNs.

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java

MalwareProtectionPlan.javaDefine the stored Malware Protection plan +110/-0

Define the stored Malware Protection plan

• Adds the plan model for identity, protected bucket, role, optional settings, status, creation time, idempotency token, and tags.

src/main/java/io/github/hectorvent/floci/services/guardduty/model/MalwareProtectionPlan.java

Tests (6) +1065 / -0
CfnProvisionerFixture.javaWire plan provisioner into CloudFormation fixtures +11/-0

Wire plan provisioner into CloudFormation fixtures

• Lets provisioner tests supply a GuardDuty service and discover its Malware Protection plan provisioner.

src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java

GuardDutyMalwareProtectionPlanCfnIntegrationTest.javaExercise plan stack lifecycle and rollback +348/-0

Exercise plan stack lifecycle and rollback

• Tests stack creation, references, updates, optional-property removal, deletion, and rollback after later resource failures. Covers cleanup of a plan recreated after out-of-band deletion.

src/test/java/io/github/hectorvent/floci/services/cloudformation/GuardDutyMalwareProtectionPlanCfnIntegrationTest.java

GuardDutyMalwareProtectionPlanCfnProvisionerTest.javaVerify prior attributes survive replacement rollback +129/-0

Verify prior attributes survive replacement rollback

• Checks that rollback deletes a plan created during an update and restores the previous physical ID and recorded attributes.

src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisionerTest.java

GuardDutyMalwareProtectionPlanIntegrationTest.javaTest plan APIs over HTTP +194/-0

Test plan APIs over HTTP

• Covers lifecycle responses, account and region isolation, conflicts, shared tagging, validation, and S3 routing coexistence.

src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanIntegrationTest.java

GuardDutyMalwareProtectionPlanServiceTest.javaTest plan service rules and pagination +382/-0

Test plan service rules and pagination

• Exercises persistence behavior, validation, idempotency, atomic and partial updates, restoration, tag ARN matching, and pagination across deletion.

src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java

supported-resource-types.tsvRegister the supported plan resource in test data +1/-0

Register the supported plan resource in test data

• Maps AWS::GuardDuty::MalwareProtectionPlan to its provisioner in the supported-resource fixture.

src/test/resources/cloudformation/supported-resource-types.tsv

Documentation (3) +37 / -6
cloudformation.mdList GuardDuty plan resource support +1/-0

List GuardDuty plan resource support

• Adds MalwareProtectionPlan to the supported CloudFormation resources and states its management-plane and bucket-update limitations.

docs/services/cloudformation.md

guardduty.mdDocument Malware Protection plan behavior +33/-6

Document Malware Protection plan behavior

• Describes the five plan operations, tagging, validation, pagination, CloudFormation attributes, and absence of scan execution.

docs/services/guardduty.md

cfn_resource_types.yamlConfigure generated GuardDuty resource documentation +3/-0

Configure generated GuardDuty resource documentation

• Adds GuardDuty ordering, its display label, and the plan's support limitations to documentation source data.

tools/docs/cfn_resource_types.yaml

Other (1) +1 / -0
create-only-properties.jsonRegister plan create-only property metadata +1/-0

Register plan create-only property metadata

• Adds the GuardDuty resource type with an empty create-only property list.

src/main/resources/cloudformation/create-only-properties.json

@qodo-code-review

qodo-code-review Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Deleting a plan can break the next page ✓ Resolved
Description
listMalwareProtectionPlans resumes from an encoded numeric offset rather than the sort key of the
last returned plan. If page one contains 50 of 51 plans and one of those plans is deleted, the
unchanged offset is rejected against the now-50-item list with a 400 error; with more plans, it can
instead skip an item.
Code

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[R453-455]

+        int offset = decodeOffset(nextToken, plans.size());
+        int end = Math.min(offset + DEFAULT_MAX_RESULTS, plans.size());
+        return new Page<>(plans.subList(offset, end), end < plans.size() ? encodeOffset(end) : null);
Relevance

●●● Strong

Pagination precedents explicitly accept continuation tokens surviving deletion of the prior
page-boundary item.

PR-#3927
PR-#4332

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The checklist requires pagination to survive deletion of a page-boundary item. The new list method
uses an offset, while decodeOffset rejects an offset greater than or equal to the current result
size.

Rule 3865590: Pagination nextToken handling must tolerate mutations between pages
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[448-455]
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[864-882]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Offset-based plan pagination fails or skips entries when plans are deleted between pages.

## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[448-455]
- src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java[140-154]

## Recommended Fix
Encode the last returned plan's ID in the token and resume at the first greater ID, even when the token's plan no longer exists. Test deleting the last item on page one before requesting page two.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Stack rollback leaves plan changes in place ✓ Resolved
Description
provision updates the plan and its tags without retaining prior state or implementing
rollbackUpdate. If a later resource fails during the same stack update, CloudFormation reports
that rollback is not implemented for the plan and cannot restore its previous configuration.
Code

src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[R67-68]

+                guardDutyService.updateMalwareProtectionPlan(ctx.region(), existing.getId(), request);
+                reconcileTags(existing, tags);
Relevance

●●● Strong

Recent CloudFormation precedents accept rollback fixes for in-place mutations lacking prior-state
restoration.

PR-#5009
PR-#4599

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new provisioner mutates the plan but inherits an interface rollback method that returns false.
The stack rollback path treats that result as an UPDATE_FAILED resource with a
rollback-not-implemented reason.

src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[54-70]
src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.java[38-53]
src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java[2070-2105]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A successful in-place plan update cannot be undone when its stack update rolls back.
## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[54-70]
- src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceProvisioner.java[38-53]
## Recommended Fix
Capture the prior role, prefixes, tagging action, and tags before mutation. Implement rollbackUpdate to restore them, and test a stack update where a later resource fails.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Rejected updates still change plan roles ✓ Resolved
Description
updateMalwareProtectionPlan calls plan.setRole on the stored plan before validating object
prefixes and actions.tagging.status. If either later field is invalid, validation throws and the
final put is skipped, but the in-memory store still holds the changed role because it returned the
stored object directly.
Code

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[424]

+            plan.setRole(role);
Relevance

●●● Strong

Recent findings accept preventing partial persisted mutations when later validation fails.

PR-#5149
PR-#4731

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The service retrieves a plan, sets its role, and then runs prefix and tagging validators that can
throw. InMemoryStorage returns the stored object itself, so an exception before the final put does
not undo the role mutation; the invalid update therefore leaves state changed.

Rule 3865583: When validating request fields, reject invalid input at the boundary and add regression tests
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[419-437]
src/main/java/io/github/hectorvent/floci/core/storage/InMemoryStorage.java[25-29]
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[415-437]
src/main/java/io/github/hectorvent/floci/core/storage/InMemoryStorage.java[14-26]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
An invalid malware protection plan update can change the stored plan before returning a validation error.

## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[415-437]
- src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java[91-115]

## Recommended Fix
Validate all supplied role, prefix, and tagging fields into local values before mutating the stored plan, then apply changes only after validation succeeds. Add a regression test with a valid role change and invalid tagging status that asserts a 400 error and verifies the role, prefixes, and other plan fields remain unchanged.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

4. S3 objects under one bucket reach GuardDuty ✓ Resolved
Description
The new /_guardduty/malware-protection-plan controller routes are publicly matchable, while
GuardDutyRouteFilter checks the signing service only for paths beginning
/malware-protection-plan. For a path-style S3 request to bucket _guardduty with an object key
beginning malware-protection-plan, the literal GuardDuty route wins over the S3 object route, so
reads and deletes reach the plan API instead.
Code

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java[254]

+    @Path(GuardDutyRouteFilter.INTERNAL_PREFIX + GuardDutyRouteFilter.PLAN_PATH + "/{malwareProtectionPlanId}")
Relevance

●●● Strong

Internal GuardDuty routes can capture valid S3 bucket _guardduty requests; routing-collision fixes
are accepted precedent.

PR-#4966

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The filter returns before checking credentials for paths under /_guardduty, but the new controller
registers literal routes there. S3 permits _guardduty as a bucket name and registers a GET object
route for /{bucket}/{key:.+}, which loses to the literal plan path.

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyRouteFilter.java[35-53]
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java[253-254]
src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java[6051-6069]
src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java[936-938]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Direct requests to the internal GuardDuty route can match before path-style S3 object routes, even when signed for S3.
## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyRouteFilter.java[35-53]
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java[253-290]
## Recommended Fix
Prevent non-GuardDuty requests to the internal prefix from matching the plan routes, including requests for objects in an `_guardduty` S3 bucket. Add a path-style S3 regression test for the colliding object key.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Query-signed plan requests miss GuardDuty ✓ Resolved
Description
GuardDutyRouteFilter reads the signing service exclusively from the Authorization header and
leaves the public plan path unchanged when that header is absent. A request signed using an
X-Amz-Credential query parameter therefore cannot reach the plan routes, which exist only beneath
the internal prefix, and instead falls through to S3 routing.
Code

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyRouteFilter.java[R42-49]

+        boolean targetsGuardDuty = SigV4CredentialScope.serviceName(ctx.getHeaderString("Authorization"))
+                .flatMap(catalog::byCredentialScope)
+                .map(ServiceDescriptor::externalKey)
+                .filter(GUARDDUTY::equals)
+                .isPresent();
+        if (!targetsGuardDuty) {
+            return;
+        }
Relevance

●●● Strong

Presigned SigV4 requests use query credentials; the filter must recognize them to route GuardDuty
correctly.

PR-#5059

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new filter checks only the header and returns without rewriting otherwise. Existing S3 routing
code recognizes SigV4 credentials carried by X-Amz-Credential, while every new plan controller
route requires the internal prefix.

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyRouteFilter.java[42-53]
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java[226-254]
src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java[117-127]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Query-signed GuardDuty plan requests have no Authorization header, so the route filter does not direct them to the plan controller.
## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyRouteFilter.java[42-49]
## Recommended Fix
When header credentials are absent, resolve the signing service from `X-Amz-Credential` before deciding whether to rewrite the path. Test that a query-signed plan request reaches GuardDuty while a query-signed S3 request retains its S3 route.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Rolled-back stacks retain a deleted plan's ARN ✓ Resolved
Description
rollbackUpdate restores the prior physical ID after deleting a replacement plan but leaves the
replacement's Arn and CreatedAt attributes on the resource. When an update recreates a plan
deleted out of band and a later resource fails, the rolled-back stack can expose the deleted plan's
ARN through Fn::GetAtt while Ref names the prior plan ID.
Code

src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[R253-256]

+            delete(TYPE, snapshot.get("createdId").asText(), region);
+            String priorId = snapshot.path("priorId").asText();
+            resource.setPhysicalId(priorId);
+            resource.getAttributes().put("MalwareProtectionPlanId", priorId);
Relevance

●●● Strong

Rollback precedents restore replacement state and stale CloudFormation attributes are explicitly
fixed.

PR-#4731
PR-#4451

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Provisioning writes the replacement's attributes, but this rollback branch resets only its ID. The
stack rollback walker changes status rather than restoring prior attributes, and intrinsic
resolution reads the remaining attribute map.

src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[183-203]
src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[249-258]
src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java[2097-2107]
src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java[655-665]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Replacement rollback restores the prior plan ID but retains attributes written for the deleted replacement.

## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[197-203]
- src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[250-257]

## Recommended Fix
Capture the prior exposed attributes when recording a plan created during update, then restore them alongside the prior physical ID during rollback. Add a stack-update test that checks `Fn::GetAtt` after rollback.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View medium (7)
7. Wrong-account plan ARNs can change tags ✓ Resolved
Description
parsePlanArn retains only the ARN's region and plan ID, while isMalwareProtectionPlanArn checks
only its resource prefix. If a caller supplies a plan ARN with their local plan's ID but another
account, service, or partition, the tag routes still resolve and modify that local plan instead of
rejecting the mismatched ARN.
Code

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[R608-614]

+    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);
Relevance

●●● Strong

Accepted ARN precedents require account, region, partition, and resource identity validation before
tag operations.

PR-#4563
PR-#4587
PR-#5133

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
ARN parsing drops the account, service, and partition, and the tag handlers look up the plan by the
resulting region-and-ID key. Account-aware storage restricts lookup to the caller's account, but
does not verify that the supplied ARN names that account's plan.

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[596-615]
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[621-645]
src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java[69-86]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The plan tag routes accept ARNs whose account, service, or partition does not identify the stored plan.

## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[596-615]
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[621-645]

## Recommended Fix
Validate the complete supplied ARN against the resolved plan's ARN before listing or changing tags. Test a matching plan ID with an altered account or service.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


8. Plan tags accept invalid key characters ✓ Resolved
Description
requireValidPlanTag checks key length and the reserved prefix but never checks the permitted key
characters. Both plan creation and the shared tag route therefore accept keys such as bad key,
which the GuardDuty create API's documented tag-key pattern excludes.
Code

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[R587-590]

+    private static void requireValidPlanTag(String key, String value) {
+        if (key.isEmpty() || key.length() > 128 || key.startsWith("aws:")) {
+            throw badRequest("tags contains an invalid key: " + key);
+        }
Relevance

●●● Strong

Validator omission is a deterministic API correctness bug; documented tag-key character constraints
are not enforced.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The shared validator has no character check, and both creation and tagging call it. The GuardDuty
API reference specifies a tag-key pattern that excludes spaces.

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[574-594]
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[630-645]
🌐 The tags parameter specifies the key pattern \(?!aws:\)\[a-zA-Z+-=._:/\]+.

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Plan tag validation accepts characters excluded by the GuardDuty tag-key pattern.

## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[586-594]

## Recommended Fix
Apply the documented key pattern in the shared plan-tag validator and test invalid keys through both creation and tagging.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


9. Two new Java locals use inferred typing ✓ Resolved
Description
request in the new provisioner and detector in the new service test are declared with var
instead of explicit types. A later reader must infer both types from their initializers, including
in the test covered by the same Java typing convention.
Code

src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[98]

+                var array = bucket.putArray("objectPrefixes");
Relevance

●●● Strong

The repository consistently accepts replacing added Java var declarations with explicit types,
including tests.

PR-#3460
PR-#3488

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The checklist prohibits var in added Java code, including tests; both cited declarations are added
by this PR.

Rule 3865579: Do not use var in Java code; use explicit types (applies to tests too)
src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[96-99]
src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java[175-180]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Two added Java locals use `var`, including one in a test.

## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[98-98]
- src/test/java/io/github/hectorvent/floci/services/guardduty/GuardDutyMalwareProtectionPlanServiceTest.java[177-177]

## Recommended Fix
Replace `var` with `ArrayNode` and `Detector`, adding imports as needed.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


10. Removed prefixes and tagging stay on the plan ✓ Resolved
Description
GuardDutyMalwareProtectionPlanCfnProvisioner.request() omits objectPrefixes and actions when
an updated template removes them, while updateMalwareProtectionPlan leaves stored values unchanged
when those fields are absent. If a stack drops ObjectPrefixes or Actions, it reports
UPDATE_COMPLETE while the plan retains its old prefix filter or tagging action; removing
ObjectPrefixes should instead widen scanning to the whole bucket.
Code

src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[R96-107]

+            JsonNode prefixes = s3Bucket.path("ObjectPrefixes");
+            if (prefixes.isArray()) {
+                var array = bucket.putArray("objectPrefixes");
+                prefixes.forEach(prefix -> array.add(ctx.engine().resolve(prefix)));
+            }
+        }
+        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));
+        }
Relevance

●●● Strong

Recent precedents accept clearing omitted optional update fields instead of silently retaining stale
configuration.

PR-#5008
PR-#5218

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The provisioner adds objectPrefixes only when the template value is an array and adds actions
only when Tagging.Status is present, then passes that request to updateMalwareProtectionPlan.
The service updates prefixes only when objectPrefixes is present and tagging only when actions
is present, so removing either property from the template cannot clear its stored value. By
contrast, the provisioner uses staleTagKeys to drive tags to the template’s desired state,
consistent with the ProvisionContext documentation for CloudFormation updates.

src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[63-69]
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[426-436]
src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java[191-202]
src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[87-108]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
On a CloudFormation update, removing `ObjectPrefixes` or `Actions` from the template leaves the previously configured prefixes or tagging action on the plan because the provisioner omits those fields and the service treats absent fields as no-ops.

## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[63-69]
- src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/GuardDutyMalwareProtectionPlanCfnProvisioner.java[96-107]
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[426-436]

## Recommended Fix
On CloudFormation updates, compare the resolved desired properties with the prior plan and explicitly clear options removed from the template before calling `updateMalwareProtectionPlan`. Supply an empty `protectedResource.s3Bucket.objectPrefixes` array when prefixes are removed, and set the tagging status to `DISABLED` (the AWS default) when actions are removed, or add a way to reset tagging status to null. Preserve partial-update behavior for direct API requests. Add an integration test that runs `UpdateStack` after removing `ObjectPrefixes` and `Actions` and asserts that both are cleared on the plan.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


11. Plan listings split earlier than expected ✓ Resolved
Description
listMalwareProtectionPlans uses the shared 50-item page limit. When an account has more than 50
plans, callers receive a continuation token after 50 results rather than the documented default page
of 100.
Code

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[R453-455]

+        int offset = decodeOffset(nextToken, plans.size());
+        int end = Math.min(offset + DEFAULT_MAX_RESULTS, plans.size());
+        return new Page<>(plans.subList(offset, end), end < plans.size() ? encodeOffset(end) : null);
Relevance

●●● Strong

The repository accepts aligning service page defaults with documented API behavior rather than
shared generic limits.

PR-#3488

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The implementation uses DEFAULT_MAX_RESULTS, defined as 50, and its test asserts a 50-item first
page. The AWS operation reference specifies a default page size of 100 plans.

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[60-64]
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[448-456]
🌐 The NextToken parameter documentation states that the default page size is 100 plans.

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Plan listings paginate at 50 entries instead of the documented default of 100.
## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[448-456]
## Recommended Fix
Give malware plan listings their own 100-item default page size and adjust the pagination test to cover more than 100 plans.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


12. Plan tags bypass creation checks ✓ Resolved
Description
tagResource merges plan tags without applying the key and value checks used by readPlanTags.
Through the shared tag route, a caller can store reserved aws: keys or overlong keys and values
that plan creation rejects.
Code

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[R561-565]

+            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);
Relevance

●●● Strong

Tagging precedents accept validating update-route tag keys and values consistently with creation
validation.

PR-#4587
PR-#3628

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Creation validates tag keys and values, whereas the new plan-tag branch checks only the merged tag
count. The GuardDuty tag handler forwards shared-route tags directly to that branch.

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[495-515]
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[552-567]
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyTagHandler.java[29-41]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The shared tagging route accepts plan tags that the create route rejects.
## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[495-515]
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[552-567]
## Recommended Fix
Extract the plan tag key and value validation into a shared helper and apply it before merging tags in tagResource. Add tag-route tests for reserved keys and oversized keys and values.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


13. Plans accept roles from other services ✓ Resolved
Description
createMalwareProtectionPlan and updateMalwareProtectionPlan check role with
AwsArnUtils.isArn, which checks ARN syntax rather than IAM role identity. A request containing an
ARN for another service passes validation and is stored as the plan's role.
Code

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[R365-367]

+        String role = requireText(request, "role");
+        if (!AwsArnUtils.isArn(role)) {
+            throw badRequest("role must be the ARN of an IAM role.");
Relevance

●● Moderate

ARN identity validation is generally accepted, but no close precedent specifically requires IAM-role
service validation.

PR-#4563
PR-#5133

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Both paths call the general ARN check before storing the supplied role. The ARN utility explicitly
does not validate whether the resource belongs to the indicated service, while the GuardDuty update
contract calls for an IAM role ARN.

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[361-367]
src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[419-424]
src/main/java/io/github/hectorvent/floci/core/common/AwsArnUtils.java[125-133]
🌐 The role request field is specified as the ARN of an IAM role.

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Malware plans accept a syntactically valid ARN even when it does not identify an IAM role.
## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[365-367]
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyService.java[419-424]
## Recommended Fix
Parse and validate the ARN service and resource as an IAM role in both create and update paths. Test rejection of valid ARNs for other resource types.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

14. S3 bucket named after the plan route is shadowed ✓ Resolved
Description
The new literal JAX-RS routes /malware-protection-plan and
/malware-protection-plan/{malwareProtectionPlanId} (GET, POST, PATCH, DELETE) outrank S3's
/{bucket} and /{bucket}/{key} templates, and nothing checks the SigV4 credential scope before
the route is matched. An S3 client using path-style addressing against a bucket named
malware-protection-plan gets GuardDuty JSON or a GuardDuty ResourceNotFoundException instead of
ListObjects, GetObject, DeleteObject or a multi-object delete.
Code

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java[R232-235]

+    @GET
+    @Path("/malware-protection-plan")
+    public Response listMalwareProtectionPlans(
+            @Context HttpHeaders headers, @QueryParam("nextToken") String nextToken) {
Relevance

●●● Strong

Accepted routing precedents enforce credential scope and prevent requests from selecting the wrong
service path.

PR-#5059
PR-#4563

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The controller comment says literal paths win over S3's template routes with no extra wiring, which
is true for any request that hits these paths. That covers S3 requests for a bucket with this valid
name. Elsewhere the repo resolves shared paths with a @PreMatching filter that dispatches on the
SigV4 credential scope (DlmRouteFilter), and these new routes have no such guard.

src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java[30-45]
src/main/java/io/github/hectorvent/floci/services/dlm/DlmRouteFilter.java[17-53]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new `/malware-protection-plan` routes take JAX-RS precedence over S3's `/{bucket}` routes. As a result, path-style S3 requests for a bucket named `malware-protection-plan` are handled by GuardDuty.

## Fix Focus Areas
- src/main/java/io/github/hectorvent/floci/services/guardduty/GuardDutyController.java[222-291]
- src/main/java/io/github/hectorvent/floci/services/dlm/DlmRouteFilter.java[17-53]

## Recommended Fix
Add a @PreMatching filter modeled on DlmRouteFilter. When the path is `/malware-protection-plan` or starts with `/malware-protection-plan/`, and the Authorization header's SigV4 scope resolves to guardduty, rewrite the path to an internal prefix such as `/_guardduty/malware-protection-plan...`. Then register the controller methods under that internal prefix. If you would rather keep the current behaviour, document the collision instead.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
✅ Compliance rules (platform): 8 rules
✅ Cross-repo context — repo relationships
Review mode: Auto: 🧠 Deep: Bug-dense, cross-cutting service and CloudFormation logic warrants redundant review.

Grey Divider

Tip of the day
💡 Did you know, you can turn these tips off under Display > Comment parts

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@hectorvent hectorvent added cloudformation AWS CloudFormation enhancement New feature or request guardduty Amazon GuardDuty labels Oct 10, 2026
…wareProtectionPlan

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 floci-io#4657
- 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.
@upwardsolutions-inc
upwardsolutions-inc force-pushed the feat/guardduty-malware-protection-plan branch from ff2b49f to 6fac825 Compare October 12, 2026 17:18
@upwardsolutions-inc
upwardsolutions-inc force-pushed the feat/guardduty-malware-protection-plan branch from 6fac825 to ab4e499 Compare October 12, 2026 17:21

@pgermosen pgermosen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@upwardsolutions-inc thanks, this is a careful one. CI is red on CfnProvisionerFixtureTest though: the new provisioner can't be reached through CfnProvisionerFixture, so the builder needs a GuardDutyService field and setter (step 7 of AGENTS.md's CloudFormation checklist). The ECS waiter failure in the same shard looks unrelated.

Two small ones in GuardDutyController: the inline java.time.Instant.parse should be an import, and the Javadoc line you rewrote still has an em-dash, which AGENTS.md rules out.

@pgermosen pgermosen added the waiting-author Review posted; waiting on the PR author to respond label Oct 12, 2026
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit ab4e499

CfnProvisionerFixtureTest requires every provisioner to be reachable through a public Builder setter. Add a guardDuty(...) setter that registers GuardDutyMalwareProtectionPlanCfnProvisioner.
@pgermosen

Copy link
Copy Markdown
Member

@upwardsolutions-inc thanks, the fixture wiring sorts out CI. The two from last time are still open: GuardDutyController keeps the inline java.time.Instant.parse and the em-dash in its Javadoc, and the CloudFormation integration test adds a java.util.List.of. That Javadoc's S3 paragraph should also name /malware-protection-plan next to /detector and /admin.

Two more. requireValidPlanTag skips the documented key pattern (?!aws:)[a-zA-Z+-=._:/]+, so a key like bad key gets through. And when an update recreated a missing plan, rollbackUpdate restores the prior id but keeps the deleted replacement's Arn and CreatedAt, so the prior values need capturing before record overwrites them.

- 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.
…are-protection-plan

# Conflicts:
#	src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
#	tools/docs/cfn_resource_types.yaml
… plan route

Review on floci-io#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.
@upwardsolutions-inc

Copy link
Copy Markdown
Contributor Author

@pgermosen thanks for the second pass. All of these should be sorted now:

  • requireValidPlanTag now checks the documented key pattern, so bad key gets rejected on both create and TagResource (8f12fb1).
  • The rollback after a recreated plan now captures the prior attributes before record runs and puts back Arn, CreatedAt, Status and StatusReasons along with the id. I also noticed the existing out-of-band test never actually reached that path, since an unchanged resource gets skipped on update. It changes the plan's prefixes now and checks Fn::GetAtt Arn after the rollback (8f12fb1).
  • Instant and List are imported, the em-dash is gone, and the controller Javadoc mentions /malware-protection-plan next to /detector and /admin (3e2e95c).

While I was in there I also made the tag routes require the full plan ARN to match, and moved the plan routes behind a small pre-matching filter like DlmRouteFilter, so a path-style S3 bucket called malware-protection-plan still goes to S3.

@upwardsolutions-inc

Copy link
Copy Markdown
Contributor Author

@pgermosen could you (or another maintainer) re-run the failed jobs on the latest CI run when you get a chance? https://github.com/floci-io/floci/actions/runs/38336484705

Both failures look like flakes unrelated to this change:

  • Shard 1: CognitoIntegrationTest.adminCreateUserEmailsAnInvitationWithAWorkingTemporaryPassword got a 400. The same test failed on main's own CI run a bit earlier (https://github.com/floci-io/floci/actions/runs/38334158331), and the full Cognito class passes for me locally.
  • Shard 2: ElbV2PreserveHostHeaderIntegrationTest.preservesHostHeaderWhenLoadBalancerAttributeIsEnabled timed out waiting on the data plane.

I don't have permission to re-run jobs on this repo. Thanks!

@pgermosen

Copy link
Copy Markdown
Member

@upwardsolutions-inc thanks, the tag-key pattern, the full rollback attributes and the full-ARN match on the tag routes all look right, and the filter is a better answer to the S3 collision than documenting it.

One thing: GuardDutyRouteFilter is a line-for-line copy of DlmRouteFilter, and ResourceExplorer2PathRewriteFilter repeats the same signed-for-service check, so this is the third copy. Could the path test, the credential-scope check and the rewrite move into one helper in core.common that all three use?

Both CI failures are unrelated: the Cognito invitation test fails on main too (its hand-built JSON breaks when the temporary password contains " or \), and the ELBv2 one timed out closing its test backend. The next push re-runs them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cloudformation AWS CloudFormation enhancement New feature or request guardduty Amazon GuardDuty released

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEAT] GuardDuty: Malware Protection for S3 plans and AWS::GuardDuty::MalwareProtectionPlan

3 participants