Light, fluffy, and always free - The AWS Local Emulator alternative
feat(dlm): manage lifecycle policies (#4335)
XuJian4a51c0e814db
diff --git a/README.md b/README.mdindex 0c1d5804e2..821da6dd87 100644--- a/README.md+++ b/README.md@@ -302,7 +302,7 @@ Floci supports local emulation for application services, data services, eventing| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, DataSync, IoT Core, Amazon Connect, Amazon AppIntegrations || Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, Amazon Inspector, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin, OIDC, Access Portal, SCIM), Identity Store, Amazon Macie, Amazon Detective, Security Hub, Amazon Verified Permissions, Control Catalog, Control Tower, Service Catalog, AWS Marketplace || Cost and billing | AWS Budgets, Pricing, Cost Explorer, Cost and Usage Reports, BCM Pricing Calculator, BCM Data Exports |-| Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |+| Resilience, backup, and config | AWS FIS, AWS Backup, Amazon Data Lifecycle Manager, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |For operation-level compatibility, see the [Services Overview](https://floci.io/floci/services/).@@ -376,6 +376,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/| Application Auto Scaling | In-process | Scalable targets, target-tracking and step scaling policies, CloudWatch alarm creation, tagging (policies are stored but inert) || Elastic Beanstalk | In-process | Applications, application versions, environments, configuration templates, platform and solution stack metadata || AWS Backup | In-process | Vaults, backup plans, selections, simulated job lifecycle, recovery points |+| Amazon Data Lifecycle Manager | In-process | Lifecycle policy and tag management; schedules are stored but do not create snapshots or AMIs || AWS FIS | In-process | All 26 management APIs for templates, experiments, target accounts, action and target discovery, safety lever, tagging, and pagination; experiment execution is a safe control-plane simulation and does not inject faults into other services || AWS Config | In-process | Config rules, evaluation-driven compliance (PutEvaluations, compliance details and summaries), configuration recorders, delivery channels, retention configuration, conformance packs, tagging || Organizations | In-process | Organizations, roots, nested OUs, member accounts, all policy types with `FullAWSAccess` and effective-policy inheritance, trusted service access, delegated administrators, resource policy, and the full invitation/handshake flow; created accounts are usable Floci accounts and member accounts can read the organization they belong to |diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xmlindex 41eb203033..6379645ffb 100644--- a/compatibility-tests/sdk-test-java/pom.xml+++ b/compatibility-tests/sdk-test-java/pom.xml@@ -599,6 +599,11 @@<groupId>software.amazon.awssdk</groupId><artifactId>appintegrations</artifactId></dependency>+ <!-- Amazon Data Lifecycle Manager client -->+ <dependency>+ <groupId>software.amazon.awssdk</groupId>+ <artifactId>dlm</artifactId>+ </dependency><!-- DataSync client --><dependency><groupId>software.amazon.awssdk</groupId>diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.javaindex 2117f6a32d..abb6276214 100644--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java@@ -114,6 +114,7 @@ import software.amazon.awssdk.services.scheduler.SchedulerClient;import software.amazon.awssdk.services.appconfig.AppConfigClient;import software.amazon.awssdk.services.appconfigdata.AppConfigDataClient;import software.amazon.awssdk.services.appintegrations.AppIntegrationsClient;+import software.amazon.awssdk.services.dlm.DlmClient;import software.amazon.awssdk.services.datasync.DataSyncClient;import software.amazon.awssdk.services.autoscaling.AutoScalingClient;import software.amazon.awssdk.services.backup.BackupClient;@@ -1220,6 +1221,14 @@ public final class TestFixtures {.build();}+ public static DlmClient dlmClient() {+ return DlmClient.builder()+ .endpointOverride(ENDPOINT)+ .region(REGION)+ .credentialsProvider(CREDENTIALS)+ .build();+ }+public static PipesClient pipesClient() {return PipesClient.builder().endpointOverride(ENDPOINT)diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DlmTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DlmTest.javanew file mode 100644index 0000000000..f110540b66--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DlmTest.java@@ -0,0 +1,121 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.dlm.DlmClient;+import software.amazon.awssdk.services.dlm.model.CreateRule;+import software.amazon.awssdk.services.dlm.model.GettablePolicyStateValues;+import software.amazon.awssdk.services.dlm.model.IntervalUnitValues;+import software.amazon.awssdk.services.dlm.model.LifecyclePolicy;+import software.amazon.awssdk.services.dlm.model.PolicyDetails;+import software.amazon.awssdk.services.dlm.model.PolicyTypeValues;+import software.amazon.awssdk.services.dlm.model.ResourceNotFoundException;+import software.amazon.awssdk.services.dlm.model.ResourceTypeValues;+import software.amazon.awssdk.services.dlm.model.RetainRule;+import software.amazon.awssdk.services.dlm.model.Schedule;+import software.amazon.awssdk.services.dlm.model.SettablePolicyStateValues;+import software.amazon.awssdk.services.dlm.model.Tag;++import java.time.Instant;+import java.util.Map;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++@DisplayName("Amazon Data Lifecycle Manager")+class DlmTest {++ private static DlmClient dlm;+ private static String policyId;+ private static String policyArn;++ @BeforeAll+ static void setup() {+ dlm = TestFixtures.dlmClient();+ }++ @AfterAll+ static void cleanup() {+ if (dlm == null) {+ return;+ }+ if (policyId != null) {+ try {+ dlm.deleteLifecyclePolicy(r -> r.policyId(policyId));+ } catch (RuntimeException e) {+ System.out.println("DLM cleanup skipped the lifecycle policy: " + e);+ }+ }+ dlm.close();+ }++ @Test+ void policyLifecycleRoundTripsNestedDetailsTimestampsFiltersAndTags() {+ PolicyDetails details = PolicyDetails.builder()+ .policyType(PolicyTypeValues.EBS_SNAPSHOT_MANAGEMENT)+ .resourceTypes(ResourceTypeValues.VOLUME)+ .targetTags(Tag.builder().key("backup").value("true").build())+ .schedules(Schedule.builder()+ .name("daily")+ .createRule(CreateRule.builder()+ .interval(24)+ .intervalUnit(IntervalUnitValues.HOURS)+ .build())+ .retainRule(RetainRule.builder().count(7).build())+ .tagsToAdd(Tag.builder().key("managed").value("dlm").build())+ .build())+ .build();++ policyId = dlm.createLifecyclePolicy(r -> r+ .executionRoleArn("arn:aws:iam::000000000000:role/dlm")+ .description("daily")+ .state(SettablePolicyStateValues.ENABLED)+ .policyDetails(details)+ .tags(Map.of("env", "test")))+ .policyId();++ LifecyclePolicy created = dlm.getLifecyclePolicy(r -> r.policyId(policyId)).policy();+ policyArn = created.policyArn();++ assertThat(created.description()).isEqualTo("daily");+ assertThat(created.dateCreated()).isBetween(Instant.now().minusSeconds(30), Instant.now().plusSeconds(1));+ assertThat(created.policyDetails().resourceTypes()).containsExactly(ResourceTypeValues.VOLUME);+ assertThat(created.policyDetails().schedules().get(0).createRule().interval()).isEqualTo(24);+ assertThat(created.tags()).containsEntry("env", "test");++ assertThat(dlm.getLifecyclePolicies(r -> r+ .state(GettablePolicyStateValues.ENABLED)+ .resourceTypes(ResourceTypeValues.VOLUME)+ .targetTags("backup=true")+ .tagsToAdd("managed=dlm"))+ .policies())+ .extracting(summary -> summary.policyId())+ .contains(policyId);++ dlm.updateLifecyclePolicy(r -> r+ .policyId(policyId)+ .description("weekly")+ .state(SettablePolicyStateValues.DISABLED));+ LifecyclePolicy updated = dlm.getLifecyclePolicy(r -> r.policyId(policyId)).policy();+ assertThat(updated.description()).isEqualTo("weekly");+ assertThat(updated.state()).isEqualTo(GettablePolicyStateValues.DISABLED);+ assertThat(updated.policyDetails().schedules().get(0).createRule().interval()).isEqualTo(24);++ dlm.tagResource(r -> r.resourceArn(policyArn).tags(Map.of("owner", "platform")));+ assertThat(dlm.listTagsForResource(r -> r.resourceArn(policyArn)).tags())+ .containsEntry("env", "test")+ .containsEntry("owner", "platform");++ dlm.untagResource(r -> r.resourceArn(policyArn).tagKeys("env"));+ assertThat(dlm.listTagsForResource(r -> r.resourceArn(policyArn)).tags())+ .doesNotContainKey("env")+ .containsEntry("owner", "platform");++ dlm.deleteLifecyclePolicy(r -> r.policyId(policyId));+ assertThatThrownBy(() -> dlm.getLifecyclePolicy(r -> r.policyId(policyId)))+ .isInstanceOf(ResourceNotFoundException.class);+ policyId = null;+ }+}diff --git a/docs/services/dlm.md b/docs/services/dlm.mdnew file mode 100644index 0000000000..19c793e2c2--- /dev/null+++ b/docs/services/dlm.md@@ -0,0 +1,63 @@+# Amazon Data Lifecycle Manager++**Protocol:** REST JSON+**Endpoint:** `http://localhost:4566/policies` (SigV4 service `dlm`)++Floci emulates the DLM management plane for EBS snapshot and AMI lifecycle policy+configuration. Policies, nested policy details, and resource tags are persisted and+isolated by account and region.++## Supported Actions++<!-- floci:actions:start -->+| Action | Description |+| --- | --- |+| `CreateLifecyclePolicy` | Creates an EBS snapshot or AMI lifecycle policy configuration. |+| `GetLifecyclePolicy` | Returns one lifecycle policy and its nested details. |+| `GetLifecyclePolicies` | Lists lifecycle policies with the supported DLM filters. |+| `UpdateLifecyclePolicy` | Updates the supplied members of a lifecycle policy. |+| `DeleteLifecyclePolicy` | Deletes a lifecycle policy configuration. |+| `ListTagsForResource` | Lists the tags attached to a lifecycle policy. |+| `TagResource` | Adds or replaces tags on a lifecycle policy. |+| `UntagResource` | Removes selected tags from a lifecycle policy. |+<!-- floci:actions:end -->++`GetLifecyclePolicies` supports policy id, state, resource type, target-tag,+schedule-tag, and default-policy filters. `UpdateLifecyclePolicy` changes only the+members supplied by the caller and preserves the rest of the policy.++Policy timestamps use ISO 8601, as required by the DLM SDK model. Tags supplied on+create are returned by `GetLifecyclePolicy` and can also be managed with the resource+tagging actions.++## Not emulated++Floci stores DLM policy configuration but does not execute schedules. It does not+create EBS snapshots or AMIs, copy them across Regions, or enforce retention and+exclusion rules. The nested `PolicyDetails` document is retained so SDK and+infrastructure-as-code configuration can round-trip without claiming that backup+jobs have run.++## Configuration++| Variable | Default | Description |+|---|---|---|+| `FLOCI_SERVICES_DLM_ENABLED` | `true` | Enable or disable the service |++## Examples++```bash+export AWS_ENDPOINT_URL=http://localhost:4566++policy_id=$(aws dlm create-lifecycle-policy \+ --execution-role-arn arn:aws:iam::000000000000:role/dlm \+ --description daily \+ --state ENABLED \+ --policy-details '{"PolicyType":"EBS_SNAPSHOT_MANAGEMENT","ResourceTypes":["VOLUME"],"TargetTags":[{"Key":"backup","Value":"true"}],"Schedules":[{"Name":"daily","CreateRule":{"Interval":24,"IntervalUnit":"HOURS"},"RetainRule":{"Count":7}}]}' \+ --query PolicyId \+ --output text)++aws dlm get-lifecycle-policy --policy-id "$policy_id"+aws dlm get-lifecycle-policies --state ENABLED --resource-types VOLUME+aws dlm delete-lifecycle-policy --policy-id "$policy_id"+```diff --git a/docs/services/index.md b/docs/services/index.mdindex ae2480e533..c088351a4d 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -59,6 +59,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [Amazon Detective](detective.md) | `/orgs/*`, `/graphs/list`, `/graph/*` | REST JSON | 8 || [Amazon Connect](connect.md) | `/instance`, `/instance/{instanceId}/*`, `/tags/*` | REST JSON | 15 || [Amazon AppIntegrations](appintegrations.md) | `/eventIntegrations/*`, `/dataIntegrations/*`, `/tags/*` | REST JSON | 14 |+| [Amazon Data Lifecycle Manager](dlm.md) | `/policies`, `/policies/{policyId}`, `/tags/{resourceArn}` | REST JSON | 8 || [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 8 || [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 7 || [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 14 |diff --git a/mkdocs.yml b/mkdocs.ymlindex 47972c1565..69fdeb67a3 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -165,6 +165,7 @@ nav:- GuardDuty: services/guardduty.md- Connect: services/connect.md- AppIntegrations: services/appintegrations.md+ - Amazon Data Lifecycle Manager: services/dlm.md- ACM: services/acm.md- ECS: services/ecs.md- ECR: services/ecr.mddiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 88b38c1149..7f4771682c 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -793,6 +793,7 @@ public interface EmulatorConfig {ControlTowerServiceConfig controltower();ConnectServiceConfig connect();AppIntegrationsServiceConfig appintegrations();+ DlmServiceConfig dlm();CognitoIdentityServiceConfig cognitoidentity();GlobalAcceleratorServiceConfig globalaccelerator();DataSyncServiceConfig datasync();@@ -836,6 +837,11 @@ public interface EmulatorConfig {boolean enabled();}+ interface DlmServiceConfig {+ @WithDefault("true")+ boolean enabled();+ }+interface CognitoIdentityServiceConfig {@WithDefault("true")boolean enabled();diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex 41d06f1a2c..a51f50f03c 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -58,6 +58,7 @@ import io.github.hectorvent.floci.services.securityhub.SecurityHubController;import io.github.hectorvent.floci.services.ssooidc.SsoOidcController;import io.github.hectorvent.floci.services.ssoportal.SsoPortalController;import io.github.hectorvent.floci.services.detective.DetectiveController;+import io.github.hectorvent.floci.services.dlm.DlmController;import io.github.hectorvent.floci.services.aps.ApsController;import io.github.hectorvent.floci.services.controlcatalog.ControlCatalogController;import io.github.hectorvent.floci.services.controltower.ControlTowerControlController;@@ -674,6 +675,10 @@ public class ResolvedServiceCatalog {protocols(ServiceProtocol.REST_JSON),Set.of(), Set.of("app-integrations"), Set.of(),Set.of(io.github.hectorvent.floci.services.appintegrations.AppIntegrationsController.class)),+ descriptor("dlm", "dlm", config.services().dlm().enabled(), true,+ "dlm", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,+ protocols(ServiceProtocol.REST_JSON),+ Set.of(), Set.of("dlm"), Set.of(), Set.of(DlmController.class)),descriptor("cognito-identity", "cognitoidentity",config.services().cognitoidentity().enabled(), true,"cognitoidentity", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,diff --git a/src/main/java/io/github/hectorvent/floci/core/common/TagDispatcher.java b/src/main/java/io/github/hectorvent/floci/core/common/TagDispatcher.javaindex 6065628e9a..3e704dc0f0 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/TagDispatcher.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/TagDispatcher.java@@ -89,7 +89,9 @@ public class TagDispatcher {} catch (AwsException e) {throw e;} catch (Exception e) {- String code = handler.strictTagValidation() ? "ValidationException" : "BadRequestException";+ String code = handler.strictTagValidation()+ ? handler.tagValidationErrorCode()+ : "BadRequestException";throw new AwsException(code, e.getMessage(), 400);}}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/TagHandler.java b/src/main/java/io/github/hectorvent/floci/core/common/TagHandler.javaindex 69f559e71d..c1687495bd 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/TagHandler.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/TagHandler.java@@ -76,6 +76,11 @@ public interface TagHandler {return false;}+ /** AWS error code used when strict tag payload validation fails. */+ default String tagValidationErrorCode() {+ return "ValidationException";+ }+/*** Whether an {@code UntagResource} request may omit the tag-key query parameter.* Defaults to {@code false} so strict handlers retain their existing validation.diff --git a/src/main/java/io/github/hectorvent/floci/services/dlm/DlmController.java b/src/main/java/io/github/hectorvent/floci/services/dlm/DlmController.javanew file mode 100644index 0000000000..0d02307cbd--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/dlm/DlmController.java@@ -0,0 +1,144 @@+package io.github.hectorvent.floci.services.dlm;++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.ObjectNode;+import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.services.dlm.model.LifecyclePolicy;+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;+import jakarta.ws.rs.Produces;+import jakarta.ws.rs.QueryParam;+import jakarta.ws.rs.WebApplicationException;+import jakarta.ws.rs.core.Context;+import jakarta.ws.rs.core.HttpHeaders;+import jakarta.ws.rs.core.MediaType;+import jakarta.ws.rs.core.Response;++import java.util.List;+import java.util.Map;++@Path(DlmRouteFilter.INTERNAL_PREFIX)+@Produces(MediaType.APPLICATION_JSON)+@Consumes(MediaType.APPLICATION_JSON)+public class DlmController {++ private final DlmService dlmService;+ private final RegionResolver regionResolver;+ private final ObjectMapper objectMapper;++ @Inject+ public DlmController(DlmService dlmService, RegionResolver regionResolver, ObjectMapper objectMapper) {+ this.dlmService = dlmService;+ this.regionResolver = regionResolver;+ this.objectMapper = objectMapper;+ }++ @POST+ @Path("/policies")+ public Response createLifecyclePolicy(@Context HttpHeaders headers, String body) {+ String region = regionResolver.resolveRegion(headers);+ LifecyclePolicy policy = dlmService.createLifecyclePolicy(readTree(body), region);+ ObjectNode response = objectMapper.createObjectNode();+ response.put("PolicyId", policy.getPolicyId());+ return Response.ok(response).build();+ }++ @GET+ @Path("/policies/{policyId}")+ public Response getLifecyclePolicy(@PathParam("policyId") String policyId,+ @Context HttpHeaders headers) {+ String region = regionResolver.resolveRegion(headers);+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Policy", policyNode(dlmService.getLifecyclePolicy(policyId, region)));+ return Response.ok(response).build();+ }++ @GET+ @Path("/policies")+ public Response getLifecyclePolicies(@Context HttpHeaders headers,+ @QueryParam("policyIds") List<String> policyIds,+ @QueryParam("state") String state,+ @QueryParam("resourceTypes") List<String> resourceTypes,+ @QueryParam("targetTags") List<String> targetTags,+ @QueryParam("tagsToAdd") List<String> tagsToAdd,+ @QueryParam("defaultPolicyType") String defaultPolicyType) {+ String region = regionResolver.resolveRegion(headers);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode policies = response.putArray("Policies");+ for (LifecyclePolicy policy : dlmService.getLifecyclePolicies(region, policyIds, state,+ resourceTypes, targetTags, tagsToAdd, defaultPolicyType)) {+ policies.add(policySummaryNode(policy));+ }+ return Response.ok(response).build();+ }++ @PATCH+ @Path("/policies/{policyId}")+ public Response updateLifecyclePolicy(@PathParam("policyId") String policyId,+ @Context HttpHeaders headers, String body) {+ String region = regionResolver.resolveRegion(headers);+ dlmService.updateLifecyclePolicy(policyId, readTree(body), region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ @DELETE+ @Path("/policies/{policyId}")+ public Response deleteLifecyclePolicy(@PathParam("policyId") String policyId,+ @Context HttpHeaders headers) {+ String region = regionResolver.resolveRegion(headers);+ dlmService.deleteLifecyclePolicy(policyId, region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private ObjectNode policyNode(LifecyclePolicy policy) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("PolicyId", policy.getPolicyId());+ node.put("Description", policy.getDescription());+ node.put("State", policy.getState());+ node.put("ExecutionRoleArn", policy.getExecutionRoleArn());+ node.put("DateCreated", policy.getDateCreated());+ node.put("DateModified", policy.getDateModified());+ if (policy.getPolicyDetails() != null) {+ node.set("PolicyDetails", policy.getPolicyDetails());+ }+ node.set("Tags", objectMapper.valueToTree(+ policy.getTags() != null ? policy.getTags() : Map.of()));+ node.put("PolicyArn", policy.getPolicyArn());+ node.put("DefaultPolicy", policy.getDefaultPolicyType() != null);+ return node;+ }++ private ObjectNode policySummaryNode(LifecyclePolicy policy) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("PolicyId", policy.getPolicyId());+ node.put("Description", policy.getDescription());+ node.put("State", policy.getState());+ node.set("Tags", objectMapper.valueToTree(+ policy.getTags() != null ? policy.getTags() : Map.of()));+ JsonNode details = policy.getPolicyDetails();+ String policyType = details == null ? null : details.path("PolicyType").textValue();+ if (policyType == null) {+ policyType = "EBS_SNAPSHOT_MANAGEMENT";+ }+ node.put("PolicyType", policyType);+ node.put("DefaultPolicy", policy.getDefaultPolicyType() != null);+ return node;+ }++ private JsonNode readTree(String body) {+ try {+ return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);+ } catch (Exception e) {+ throw new WebApplicationException(JsonErrorResponseUtils.createSerializationErrorResponse());+ }+ }+}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.javanew file mode 100644index 0000000000..0a876d9507--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/dlm/DlmRouteFilter.java@@ -0,0 +1,54 @@+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 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 DLM policy requests to an internal prefix before JAX-RS route matching.+ * DLM and IoT expose the same {@code /policies} paths, so their public routes+ * cannot both be registered directly.+ */+@Provider+@PreMatching+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;++ @Inject+ public DlmRouteFilter(ResolvedServiceCatalog catalog) {+ this.catalog = catalog;+ }++ @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());+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/dlm/DlmService.java b/src/main/java/io/github/hectorvent/floci/services/dlm/DlmService.javanew file mode 100644index 0000000000..ad6f23a0ff--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/dlm/DlmService.java@@ -0,0 +1,590 @@+package io.github.hectorvent.floci.services.dlm;++import com.fasterxml.jackson.core.type.TypeReference;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.node.JsonNodeFactory;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.Resettable;+import io.github.hectorvent.floci.core.common.TagHandler;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.dlm.model.LifecyclePolicy;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.Instant;+import java.util.LinkedHashMap;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.UUID;+import java.util.regex.Pattern;++@ApplicationScoped+public class DlmService implements Resettable, TagHandler {++ private static final Logger LOG = Logger.getLogger(DlmService.class);+ private static final String SERVICE = "dlm";+ private static final Pattern DESCRIPTION = Pattern.compile("[0-9A-Za-z _-]{1,500}");+ private static final Pattern EXECUTION_ROLE_ARN = Pattern.compile(+ "arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::[0-9]+:role/.+");+ private static final Pattern TAG_KEY = Pattern.compile("(?!aws:)[a-zA-Z+\\-=._:/]{1,128}");+ private static final Set<String> STATES = Set.of("ENABLED", "DISABLED");+ private static final Set<String> DEFAULT_POLICY_TYPES = Set.of("VOLUME", "INSTANCE");+ private static final Set<String> DEFAULT_POLICY_FILTERS = Set.of("VOLUME", "INSTANCE", "ALL");+ private static final Set<String> RESOURCE_TYPES = Set.of("VOLUME", "INSTANCE");+ private static final Set<String> POLICY_TYPES = Set.of(+ "EBS_SNAPSHOT_MANAGEMENT", "IMAGE_MANAGEMENT", "EVENT_BASED_POLICY");++ private final AccountAwareStorageBackend<LifecyclePolicy> policies;++ @Inject+ public DlmService(StorageFactory storageFactory) {+ this(storageFactory.create("dlm", "dlm-lifecycle-policies.json",+ new TypeReference<Map<String, LifecyclePolicy>>() {}));+ }++ DlmService(AccountAwareStorageBackend<LifecyclePolicy> policies) {+ this.policies = policies;+ }++ public LifecyclePolicy createLifecyclePolicy(JsonNode request, String region) {+ requireObject(request, "Request payload");+ String executionRoleArn = requiredText(request, "ExecutionRoleArn");+ validateExecutionRoleArn(executionRoleArn);+ String description = requiredText(request, "Description");+ validateDescription(description);+ String state = requiredText(request, "State");+ validateState(state);++ LifecyclePolicy policy = new LifecyclePolicy();+ String policyId = "policy-" + UUID.randomUUID().toString().replace("-", "");+ String now = Instant.now().toString();+ policy.setPolicyId(policyId);+ policy.setExecutionRoleArn(executionRoleArn);+ policy.setDescription(description);+ policy.setState(state);+ policy.setDateCreated(now);+ policy.setDateModified(now);+ policy.setPolicyArn(AwsArnUtils.Arn.of(+ SERVICE, region, policies.accountId(), "policy/" + policyId).toString());+ policy.setPolicyDetails(readPolicyDetails(request.get("PolicyDetails")));+ policy.setTags(readTags(request.get("Tags"), false));+ policy.setDefaultPolicyType(optionalEnum(request, "DefaultPolicy", DEFAULT_POLICY_TYPES));+ policy.setCreateInterval(optionalPositiveInteger(request, "CreateInterval"));+ policy.setRetainInterval(optionalPositiveInteger(request, "RetainInterval"));+ policy.setCopyTags(optionalBoolean(request, "CopyTags"));+ policy.setExtendDeletion(optionalBoolean(request, "ExtendDeletion"));+ policy.setCrossRegionCopyTargets(optionalArray(request, "CrossRegionCopyTargets", 3));+ policy.setExclusions(optionalObject(request, "Exclusions"));+ normalizeDefaultPolicyDetails(policy);++ policies.put(storageKey(region, policyId), policy);+ LOG.infov("Created DLM lifecycle policy: {0}", policyId);+ return policy;+ }++ public LifecyclePolicy getLifecyclePolicy(String policyId, String region) {+ validatePolicyId(policyId);+ return policies.get(storageKey(region, policyId))+ .orElseThrow(() -> notFound(policyId));+ }++ public List<LifecyclePolicy> getLifecyclePolicies(String region,+ List<String> policyIds,+ String state,+ List<String> resourceTypes,+ List<String> targetTags,+ List<String> tagsToAdd,+ String defaultPolicyType) {+ Set<String> ids = normalizedQueryValues(policyIds);+ Set<String> requestedResourceTypes = normalizedQueryValues(resourceTypes);+ Set<String> requestedTargetTags = normalizedQueryValues(targetTags);+ Set<String> requestedTagsToAdd = normalizedQueryValues(tagsToAdd);+ if (state != null) {+ validateGettableState(state);+ }+ requestedResourceTypes.forEach(value -> validateEnum("resourceTypes", value, RESOURCE_TYPES));+ if (requestedResourceTypes.size() > 1) {+ throw invalidRequest("resourceTypes must contain exactly one value.");+ }+ if (defaultPolicyType != null) {+ validateEnum("defaultPolicyType", defaultPolicyType, DEFAULT_POLICY_FILTERS);+ }+ ids.forEach(DlmService::validatePolicyId);++ return policies.scan(key -> key.startsWith(region + "::")).stream()+ .filter(policy -> ids.isEmpty() || ids.contains(policy.getPolicyId()))+ .filter(policy -> state == null || state.equals(policy.getState()))+ .filter(policy -> requestedResourceTypes.isEmpty()+ || !disjoint(requestedResourceTypes, policyResourceTypes(policy)))+ .filter(policy -> requestedTargetTags.isEmpty()+ || policyTargetTags(policy).containsAll(requestedTargetTags))+ .filter(policy -> requestedTagsToAdd.isEmpty()+ || policyTagsToAdd(policy).containsAll(requestedTagsToAdd))+ .filter(policy -> matchesDefaultPolicyType(policy, defaultPolicyType))+ .sorted((left, right) -> left.getPolicyId().compareTo(right.getPolicyId()))+ .toList();+ }++ public LifecyclePolicy updateLifecyclePolicy(String policyId, JsonNode request, String region) {+ requireObject(request, "Request payload");+ LifecyclePolicy current = getLifecyclePolicy(policyId, region);+ LifecyclePolicy policy = new LifecyclePolicy(current);+ boolean changed = false;++ if (request.has("ExecutionRoleArn")) {+ String value = requiredText(request, "ExecutionRoleArn");+ validateExecutionRoleArn(value);+ policy.setExecutionRoleArn(value);+ changed = true;+ }+ if (request.has("Description")) {+ String value = requiredText(request, "Description");+ validateDescription(value);+ policy.setDescription(value);+ changed = true;+ }+ if (request.has("State")) {+ String value = requiredText(request, "State");+ validateState(value);+ policy.setState(value);+ changed = true;+ }+ if (request.has("PolicyDetails")) {+ JsonNode details = readPolicyDetails(request.get("PolicyDetails"));+ validateImmutablePolicyDetails(current.getPolicyDetails(), details);+ policy.setPolicyDetails(details);+ changed = true;+ }+ if (request.has("CreateInterval")) {+ policy.setCreateInterval(optionalPositiveInteger(request, "CreateInterval"));+ changed = true;+ }+ if (request.has("RetainInterval")) {+ policy.setRetainInterval(optionalPositiveInteger(request, "RetainInterval"));+ changed = true;+ }+ if (request.has("CopyTags")) {+ policy.setCopyTags(optionalBoolean(request, "CopyTags"));+ changed = true;+ }+ if (request.has("ExtendDeletion")) {+ policy.setExtendDeletion(optionalBoolean(request, "ExtendDeletion"));+ changed = true;+ }+ if (request.has("CrossRegionCopyTargets")) {+ policy.setCrossRegionCopyTargets(optionalArray(request, "CrossRegionCopyTargets", 3));+ changed = true;+ }+ if (request.has("Exclusions")) {+ policy.setExclusions(optionalObject(request, "Exclusions"));+ changed = true;+ }+ if (changed) {+ normalizeDefaultPolicyDetails(policy);+ policy.setDateModified(Instant.now().toString());+ policies.put(storageKey(region, policyId), policy);+ }+ return changed ? policy : current;+ }++ public void deleteLifecyclePolicy(String policyId, String region) {+ getLifecyclePolicy(policyId, region);+ policies.delete(storageKey(region, policyId));+ LOG.infov("Deleted DLM lifecycle policy: {0}", policyId);+ }++ @Override+ public String serviceKey() {+ return SERVICE;+ }++ @Override+ public String tagsBodyKey() {+ return "Tags";+ }++ @Override+ public boolean strictTagValidation() {+ return true;+ }++ @Override+ public String tagValidationErrorCode() {+ return "InvalidRequestException";+ }++ @Override+ public int tagResourceSuccessStatus() {+ return 200;+ }++ @Override+ public int untagResourceSuccessStatus() {+ return 200;+ }++ @Override+ public Map<String, String> listTags(String region, String arn) {+ return Map.copyOf(policyForArn(region, arn).getTags());+ }++ @Override+ public void tagResource(String region, String arn, Map<String, String> tags) {+ validateTags(tags, true);+ LifecyclePolicy policy = policyForArn(region, arn);+ Map<String, String> updated = new LinkedHashMap<>(policy.getTags());+ updated.putAll(tags);+ policy.setTags(updated);+ policies.put(storageKey(region, policy.getPolicyId()), policy);+ }++ @Override+ public void untagResource(String region, String arn, List<String> tagKeys) {+ if (tagKeys == null || tagKeys.isEmpty()) {+ throw invalidRequest("TagKeys must contain at least one key.");+ }+ tagKeys.forEach(DlmService::validateTagKey);+ LifecyclePolicy policy = policyForArn(region, arn);+ Map<String, String> updated = new LinkedHashMap<>(policy.getTags());+ tagKeys.forEach(updated::remove);+ policy.setTags(updated);+ policies.put(storageKey(region, policy.getPolicyId()), policy);+ }++ @Override+ public void clear() {+ policies.clear();+ }++ private LifecyclePolicy policyForArn(String region, String arn) {+ return policies.scan(key -> key.startsWith(region + "::")).stream()+ .filter(policy -> policy.getPolicyArn().equals(arn))+ .findFirst()+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "Lifecycle policy " + arn + " was not found.", 404));+ }++ private static JsonNode readPolicyDetails(JsonNode node) {+ if (node == null || node.isNull()) {+ return null;+ }+ requireObject(node, "PolicyDetails");+ String policyType = optionalText(node, "PolicyType");+ if (policyType != null) {+ validateEnum("PolicyDetails.PolicyType", policyType, POLICY_TYPES);+ }+ JsonNode resourceTypes = node.get("ResourceTypes");+ if (resourceTypes != null && !resourceTypes.isNull()) {+ if (!resourceTypes.isArray() || resourceTypes.size() != 1+ || !resourceTypes.get(0).isTextual()) {+ throw invalidRequest("PolicyDetails.ResourceTypes must contain exactly one string value.");+ }+ validateEnum("PolicyDetails.ResourceTypes", resourceTypes.get(0).textValue(), RESOURCE_TYPES);+ }+ return node.deepCopy();+ }++ private static void validateImmutablePolicyDetails(JsonNode existing, JsonNode updated) {+ if (existing == null || updated == null) {+ return;+ }+ for (String field : List.of("PolicyType", "ResourceTypes", "ResourceType")) {+ JsonNode before = existing.get(field);+ JsonNode after = updated.get(field);+ if (before != null && after != null && !before.equals(after)) {+ throw invalidRequest("PolicyDetails." + field + " cannot be changed.");+ }+ }+ }++ private static void normalizeDefaultPolicyDetails(LifecyclePolicy policy) {+ if (policy.getDefaultPolicyType() == null) {+ return;+ }+ ObjectNode details = policy.getPolicyDetails() == null+ ? JsonNodeFactory.instance.objectNode()+ : (ObjectNode) policy.getPolicyDetails().deepCopy();+ details.putIfAbsent("PolicyLanguage", JsonNodeFactory.instance.textNode("SIMPLIFIED"));+ details.putIfAbsent("ResourceType", JsonNodeFactory.instance.textNode(policy.getDefaultPolicyType()));+ putIfPresent(details, "CreateInterval", policy.getCreateInterval());+ putIfPresent(details, "RetainInterval", policy.getRetainInterval());+ putIfPresent(details, "CopyTags", policy.getCopyTags());+ putIfPresent(details, "ExtendDeletion", policy.getExtendDeletion());+ setIfPresent(details, "CrossRegionCopyTargets", policy.getCrossRegionCopyTargets());+ setIfPresent(details, "Exclusions", policy.getExclusions());+ policy.setPolicyDetails(details);+ }++ private static void putIfPresent(ObjectNode node, String field, Object value) {+ if (value instanceof Integer integer) {+ node.put(field, integer);+ } else if (value instanceof Boolean bool) {+ node.put(field, bool);+ }+ }++ private static void setIfPresent(ObjectNode node, String field, JsonNode value) {+ if (value != null) {+ node.set(field, value.deepCopy());+ }+ }++ private static Map<String, String> readTags(JsonNode node, boolean required) {+ if (node == null || node.isNull()) {+ if (required) {+ throw invalidRequest("Tags is required.");+ }+ return new LinkedHashMap<>();+ }+ if (!node.isObject()) {+ throw invalidRequest("Tags must be a map of string keys to string values.");+ }+ Map<String, String> tags = new LinkedHashMap<>();+ node.fields().forEachRemaining(entry -> {+ if (!entry.getValue().isTextual()) {+ throw invalidRequest("Tag values must be strings.");+ }+ tags.put(entry.getKey(), entry.getValue().textValue());+ });+ validateTags(tags, required);+ return tags;+ }++ private static void validateTags(Map<String, String> tags, boolean requireOne) {+ if (tags == null || (requireOne && tags.isEmpty())) {+ throw invalidRequest("Tags must contain at least one entry.");+ }+ if (tags.size() > 200) {+ throw invalidRequest("Tags must contain no more than 200 entries.");+ }+ tags.forEach((key, value) -> {+ validateTagKey(key);+ if (value == null || value.length() > 256) {+ throw invalidRequest("Tag values must contain no more than 256 characters.");+ }+ });+ }++ private static void validateTagKey(String key) {+ if (key == null || !TAG_KEY.matcher(key).matches()) {+ throw invalidRequest("Tag keys must be 1-128 valid characters and must not start with aws:.");+ }+ }++ private static JsonNode optionalObject(JsonNode request, String field) {+ JsonNode node = request.get(field);+ if (node == null || node.isNull()) {+ return null;+ }+ requireObject(node, field);+ return node.deepCopy();+ }++ private static JsonNode optionalArray(JsonNode request, String field, int maxSize) {+ JsonNode node = request.get(field);+ if (node == null || node.isNull()) {+ return null;+ }+ if (!node.isArray() || node.size() > maxSize) {+ throw invalidRequest(field + " must be an array with no more than " + maxSize + " entries.");+ }+ return node.deepCopy();+ }++ private static Integer optionalPositiveInteger(JsonNode request, String field) {+ JsonNode node = request.get(field);+ if (node == null || node.isNull()) {+ return null;+ }+ if (!node.isIntegralNumber() || !node.canConvertToInt() || node.intValue() < 1) {+ throw invalidRequest(field + " must be a positive integer.");+ }+ return node.intValue();+ }++ private static Boolean optionalBoolean(JsonNode request, String field) {+ JsonNode node = request.get(field);+ if (node == null || node.isNull()) {+ return null;+ }+ if (!node.isBoolean()) {+ throw invalidRequest(field + " must be a boolean.");+ }+ return node.booleanValue();+ }++ private static String optionalEnum(JsonNode request, String field, Set<String> values) {+ String value = optionalText(request, field);+ if (value != null) {+ validateEnum(field, value, values);+ }+ return value;+ }++ private static String requiredText(JsonNode request, String field) {+ String value = optionalText(request, field);+ if (value == null) {+ throw invalidRequest(field + " is required.");+ }+ return value;+ }++ private static String optionalText(JsonNode request, String field) {+ JsonNode node = request == null ? null : request.get(field);+ if (node == null || node.isNull()) {+ return null;+ }+ if (!node.isTextual()) {+ throw invalidRequest(field + " must be a string.");+ }+ return node.textValue();+ }++ private static void validateDescription(String description) {+ if (!DESCRIPTION.matcher(description).matches()) {+ throw invalidRequest("Description must be 1-500 letters, digits, spaces, underscores, or hyphens.");+ }+ }++ private static void validateExecutionRoleArn(String executionRoleArn) {+ if (executionRoleArn.length() > 2048 || !EXECUTION_ROLE_ARN.matcher(executionRoleArn).matches()) {+ throw invalidRequest("ExecutionRoleArn must be a valid IAM role ARN.");+ }+ }++ private static void validateState(String state) {+ validateEnum("State", state, STATES);+ }++ private static void validateGettableState(String state) {+ if (!Set.of("ENABLED", "DISABLED", "ERROR").contains(state)) {+ throw invalidRequest("state contains an invalid value.");+ }+ }++ private static void validateEnum(String field, String value, Set<String> allowed) {+ if (!allowed.contains(value)) {+ throw invalidRequest(field + " contains an invalid value: " + value + ".");+ }+ }++ private static void validatePolicyId(String policyId) {+ if (policyId == null || policyId.length() > 64 || !policyId.matches("policy-[a-f0-9]+")) {+ throw invalidRequest("PolicyId must match policy-[a-f0-9]+.");+ }+ }++ private static void requireObject(JsonNode node, String field) {+ if (node == null || !node.isObject()) {+ throw invalidRequest(field + " must be a JSON object.");+ }+ }++ private static boolean matchesDefaultPolicyType(LifecyclePolicy policy, String filter) {+ if (filter == null) {+ return true;+ }+ if ("ALL".equals(filter)) {+ return policy.getDefaultPolicyType() != null;+ }+ return filter.equals(policy.getDefaultPolicyType());+ }++ private static Set<String> policyResourceTypes(LifecyclePolicy policy) {+ JsonNode details = policy.getPolicyDetails();+ Set<String> values = new LinkedHashSet<>();+ if (details != null) {+ JsonNode list = details.get("ResourceTypes");+ if (list != null && list.isArray()) {+ list.forEach(node -> {+ if (node.isTextual()) {+ values.add(node.textValue());+ }+ });+ }+ JsonNode single = details.get("ResourceType");+ if (single != null && single.isTextual()) {+ values.add(single.textValue());+ }+ }+ if (policy.getDefaultPolicyType() != null) {+ values.add(policy.getDefaultPolicyType());+ }+ return values;+ }++ private static Set<String> policyTargetTags(LifecyclePolicy policy) {+ return tagPairs(policy.getPolicyDetails(), "TargetTags");+ }++ private static Set<String> policyTagsToAdd(LifecyclePolicy policy) {+ Set<String> values = new LinkedHashSet<>();+ JsonNode details = policy.getPolicyDetails();+ JsonNode schedules = details == null ? null : details.get("Schedules");+ if (schedules != null && schedules.isArray()) {+ schedules.forEach(schedule -> values.addAll(tagPairs(schedule, "TagsToAdd")));+ }+ return values;+ }++ private static Set<String> tagPairs(JsonNode parent, String field) {+ Set<String> values = new LinkedHashSet<>();+ JsonNode tags = parent == null ? null : parent.get(field);+ if (tags != null && tags.isArray()) {+ for (JsonNode tag : tags) {+ JsonNode key = tag.get("Key");+ JsonNode value = tag.get("Value");+ if (key != null && key.isTextual() && value != null && value.isTextual()) {+ values.add(key.textValue() + "=" + value.textValue());+ }+ }+ }+ return values;+ }++ private static Set<String> normalizedQueryValues(List<String> values) {+ Set<String> normalized = new LinkedHashSet<>();+ if (values == null) {+ return normalized;+ }+ for (String value : values) {+ if (value == null) {+ continue;+ }+ for (String part : value.split(",")) {+ if (!part.isBlank()) {+ normalized.add(part);+ }+ }+ }+ return normalized;+ }++ private static boolean disjoint(Set<String> left, Set<String> right) {+ for (String value : left) {+ if (right.contains(value)) {+ return false;+ }+ }+ return true;+ }++ private static String storageKey(String region, String policyId) {+ return region + "::" + policyId;+ }++ private static AwsException notFound(String policyId) {+ return new AwsException("ResourceNotFoundException",+ "Lifecycle policy " + policyId + " was not found.", 404);+ }++ private static AwsException invalidRequest(String message) {+ return new AwsException("InvalidRequestException", message, 400);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/dlm/model/LifecyclePolicy.java b/src/main/java/io/github/hectorvent/floci/services/dlm/model/LifecyclePolicy.javanew file mode 100644index 0000000000..d18683472a--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/dlm/model/LifecyclePolicy.java@@ -0,0 +1,178 @@+package io.github.hectorvent.floci.services.dlm.model;++import com.fasterxml.jackson.databind.JsonNode;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.LinkedHashMap;+import java.util.Map;++@RegisterForReflection+public class LifecyclePolicy {+ private String policyId;+ private String description;+ private String state;+ private String executionRoleArn;+ private String dateCreated;+ private String dateModified;+ private JsonNode policyDetails;+ private Map<String, String> tags = new LinkedHashMap<>();+ private String policyArn;+ private String defaultPolicyType;+ private Integer createInterval;+ private Integer retainInterval;+ private Boolean copyTags;+ private Boolean extendDeletion;+ private JsonNode crossRegionCopyTargets;+ private JsonNode exclusions;++ public LifecyclePolicy() {+ }++ public LifecyclePolicy(LifecyclePolicy source) {+ this.policyId = source.policyId;+ this.description = source.description;+ this.state = source.state;+ this.executionRoleArn = source.executionRoleArn;+ this.dateCreated = source.dateCreated;+ this.dateModified = source.dateModified;+ this.policyDetails = source.policyDetails == null ? null : source.policyDetails.deepCopy();+ this.tags = source.tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(source.tags);+ this.policyArn = source.policyArn;+ this.defaultPolicyType = source.defaultPolicyType;+ this.createInterval = source.createInterval;+ this.retainInterval = source.retainInterval;+ this.copyTags = source.copyTags;+ this.extendDeletion = source.extendDeletion;+ this.crossRegionCopyTargets = source.crossRegionCopyTargets == null+ ? null : source.crossRegionCopyTargets.deepCopy();+ this.exclusions = source.exclusions == null ? null : source.exclusions.deepCopy();+ }++ public String getPolicyId() {+ return policyId;+ }++ public void setPolicyId(String policyId) {+ this.policyId = policyId;+ }++ public String getDescription() {+ return description;+ }++ public void setDescription(String description) {+ this.description = description;+ }++ public String getState() {+ return state;+ }++ public void setState(String state) {+ this.state = state;+ }++ public String getExecutionRoleArn() {+ return executionRoleArn;+ }++ public void setExecutionRoleArn(String executionRoleArn) {+ this.executionRoleArn = executionRoleArn;+ }++ public String getDateCreated() {+ return dateCreated;+ }++ public void setDateCreated(String dateCreated) {+ this.dateCreated = dateCreated;+ }++ public String getDateModified() {+ return dateModified;+ }++ public void setDateModified(String dateModified) {+ this.dateModified = dateModified;+ }++ public JsonNode getPolicyDetails() {+ return policyDetails;+ }++ public void setPolicyDetails(JsonNode policyDetails) {+ this.policyDetails = policyDetails;+ }++ public Map<String, String> getTags() {+ return tags;+ }++ public void setTags(Map<String, String> tags) {+ this.tags = tags;+ }++ public String getPolicyArn() {+ return policyArn;+ }++ public void setPolicyArn(String policyArn) {+ this.policyArn = policyArn;+ }++ public String getDefaultPolicyType() {+ return defaultPolicyType;+ }++ public void setDefaultPolicyType(String defaultPolicyType) {+ this.defaultPolicyType = defaultPolicyType;+ }++ public Integer getCreateInterval() {+ return createInterval;+ }++ public void setCreateInterval(Integer createInterval) {+ this.createInterval = createInterval;+ }++ public Integer getRetainInterval() {+ return retainInterval;+ }++ public void setRetainInterval(Integer retainInterval) {+ this.retainInterval = retainInterval;+ }++ public Boolean getCopyTags() {+ return copyTags;+ }++ public void setCopyTags(Boolean copyTags) {+ this.copyTags = copyTags;+ }++ public Boolean getExtendDeletion() {+ return extendDeletion;+ }++ public void setExtendDeletion(Boolean extendDeletion) {+ this.extendDeletion = extendDeletion;+ }++ public JsonNode getCrossRegionCopyTargets() {+ return crossRegionCopyTargets;+ }++ public void setCrossRegionCopyTargets(JsonNode crossRegionCopyTargets) {+ this.crossRegionCopyTargets = crossRegionCopyTargets;+ }++ public JsonNode getExclusions() {+ return exclusions;+ }++ public void setExclusions(JsonNode exclusions) {+ this.exclusions = exclusions;+ }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex c0d12fe71f..358836537d 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -827,6 +827,8 @@ floci:enabled: trueappintegrations:enabled: true+ dlm:+ enabled: truecognitoidentity:enabled: trueglobalaccelerator:diff --git a/src/test/java/io/github/hectorvent/floci/services/dlm/DlmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dlm/DlmIntegrationTest.javanew file mode 100644index 0000000000..4a2ad294e7--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/dlm/DlmIntegrationTest.java@@ -0,0 +1,152 @@+package io.github.hectorvent.floci.services.dlm;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.Response;+import io.restassured.specification.RequestSpecification;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasItem;+import static org.hamcrest.Matchers.hasSize;+import static org.hamcrest.Matchers.matchesPattern;+import static org.hamcrest.Matchers.nullValue;++@QuarkusTest+class DlmIntegrationTest {++ private static final String ACCOUNT_ID = "723679240095";++ @Test+ void lifecycleRoundTripsThroughRestJsonIncludingTagsAndFilters() {+ Response created = dlm(ACCOUNT_ID, "us-east-1")+ .body("""+ {"ExecutionRoleArn":"arn:aws:iam::723679240095:role/dlm",+ "Description":"daily","State":"ENABLED","Tags":{"env":"test"},+ "PolicyDetails":{"PolicyType":"EBS_SNAPSHOT_MANAGEMENT",+ "ResourceTypes":["VOLUME"],+ "TargetTags":[{"Key":"backup","Value":"true"}],+ "Schedules":[{"Name":"daily","CreateRule":{"Interval":24,"IntervalUnit":"HOURS"},+ "RetainRule":{"Count":7},"TagsToAdd":[{"Key":"managed","Value":"dlm"}]}]}}+ """)+ .when()+ .post("/policies")+ .then()+ .statusCode(200)+ .body("PolicyId", matchesPattern("policy-[a-f0-9]+"))+ .extract().response();+ String policyId = created.path("PolicyId");+ String policyArn = "arn:aws:dlm:us-east-1:" + ACCOUNT_ID + ":policy/" + policyId;++ try {+ dlm(ACCOUNT_ID, "us-east-1")+ .when()+ .get("/policies/" + policyId)+ .then()+ .statusCode(200)+ .body("Policy.Description", equalTo("daily"))+ .body("Policy.PolicyArn", equalTo(policyArn))+ .body("Policy.DateCreated", matchesPattern(".*Z"))+ .body("Policy.PolicyDetails.Schedules[0].CreateRule.Interval", equalTo(24))+ .body("Policy.Tags.env", equalTo("test"));++ dlm(ACCOUNT_ID, "us-east-1")+ .queryParam("state", "ENABLED")+ .queryParam("resourceTypes", "VOLUME")+ .queryParam("targetTags", "backup=true")+ .queryParam("tagsToAdd", "managed=dlm")+ .when()+ .get("/policies")+ .then()+ .statusCode(200)+ .body("Policies", hasSize(1))+ .body("Policies.PolicyId", hasItem(policyId));++ dlm(ACCOUNT_ID, "us-east-1")+ .body("{\"Description\":\"weekly\",\"State\":\"DISABLED\"}")+ .when()+ .patch("/policies/" + policyId)+ .then()+ .statusCode(200);++ dlm(ACCOUNT_ID, "us-east-1")+ .when()+ .get("/policies/" + policyId)+ .then()+ .statusCode(200)+ .body("Policy.Description", equalTo("weekly"))+ .body("Policy.State", equalTo("DISABLED"))+ .body("Policy.ExecutionRoleArn", equalTo("arn:aws:iam::723679240095:role/dlm"))+ .body("Policy.Tags.env", equalTo("test"));++ dlm(ACCOUNT_ID, "us-east-1")+ .body("{\"Tags\":{\"owner\":\"platform\"}}")+ .when()+ .post("/tags/" + policyArn)+ .then()+ .statusCode(200);++ dlm(ACCOUNT_ID, "us-east-1")+ .when()+ .get("/tags/" + policyArn)+ .then()+ .statusCode(200)+ .body("Tags.env", equalTo("test"))+ .body("Tags.owner", equalTo("platform"));++ dlm(ACCOUNT_ID, "us-east-1")+ .queryParam("tagKeys", "env")+ .when()+ .delete("/tags/" + policyArn)+ .then()+ .statusCode(200);++ dlm(ACCOUNT_ID, "us-east-1")+ .when()+ .get("/tags/" + policyArn)+ .then()+ .statusCode(200)+ .body("Tags.env", nullValue())+ .body("Tags.owner", equalTo("platform"));++ dlm("999999999999", "us-east-1")+ .when()+ .get("/policies/" + policyId)+ .then()+ .statusCode(404)+ .body("__type", equalTo("ResourceNotFoundException"));++ dlm(ACCOUNT_ID, "eu-west-1")+ .when()+ .get("/policies/" + policyId)+ .then()+ .statusCode(404)+ .body("__type", equalTo("ResourceNotFoundException"));+ } finally {+ dlm(ACCOUNT_ID, "us-east-1")+ .when()+ .delete("/policies/" + policyId)+ .then()+ .statusCode(200);+ }+ }++ @Test+ void createValidatesRequiredMembersBeforeWriting() {+ dlm(ACCOUNT_ID, "us-east-1")+ .body("{\"Description\":\"daily\",\"State\":\"ENABLED\"}")+ .when()+ .post("/policies")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidRequestException"));+ }++ private static RequestSpecification dlm(String accountId, String region) {+ String authorization = "AWS4-HMAC-SHA256 Credential=" + accountId+ + "/20260101/" + region + "/dlm/aws4_request";+ return given()+ .contentType("application/json")+ .header("Authorization", authorization);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/dlm/DlmServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/dlm/DlmServiceTest.javanew file mode 100644index 0000000000..00144d6f5c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/dlm/DlmServiceTest.java@@ -0,0 +1,195 @@+package io.github.hectorvent.floci.services.dlm;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.services.dlm.model.LifecyclePolicy;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++class DlmServiceTest {++ private static final String REGION = "us-east-1";+ private static final String ROLE = "arn:aws:iam::000000000000:role/dlm";++ private final ObjectMapper objectMapper = new ObjectMapper();+ private AccountAwareStorageBackend<LifecyclePolicy> policies;+ private DlmService service;++ @BeforeEach+ void setUp() {+ policies = AccountAwareStorageBackend.inMemory("000000000000");+ service = new DlmService(policies);+ }++ @Test+ void lifecyclePreservesNestedPolicyDetailsAndOmittedUpdateMembers() throws Exception {+ LifecyclePolicy created = service.createLifecyclePolicy(customPolicy("daily", "ENABLED"), REGION);++ assertTrue(created.getPolicyId().matches("policy-[a-f0-9]+"));+ assertEquals("VOLUME", created.getPolicyDetails().path("ResourceTypes").get(0).asText());+ assertEquals(24, created.getPolicyDetails().path("Schedules").get(0)+ .path("CreateRule").path("Interval").asInt());+ assertEquals("arn:aws:dlm:us-east-1:000000000000:policy/" + created.getPolicyId(),+ created.getPolicyArn());+ assertNotNull(created.getDateCreated());++ JsonNode update = objectMapper.readTree("""+ {"Description":"weekly","State":"DISABLED","PolicyDetails":{+ "PolicyType":"EBS_SNAPSHOT_MANAGEMENT",+ "ResourceTypes":["VOLUME"],+ "TargetTags":[{"Key":"backup","Value":"true"}],+ "Schedules":[{"Name":"weekly","CreateRule":{"Interval":168,"IntervalUnit":"HOURS"},+ "RetainRule":{"Count":4},"TagsToAdd":[{"Key":"managed","Value":"dlm"}]}]+ }}+ """);+ service.updateLifecyclePolicy(created.getPolicyId(), update, REGION);++ LifecyclePolicy updated = service.getLifecyclePolicy(created.getPolicyId(), REGION);+ assertEquals("weekly", updated.getDescription());+ assertEquals("DISABLED", updated.getState());+ assertEquals(ROLE, updated.getExecutionRoleArn());+ assertEquals(168, updated.getPolicyDetails().path("Schedules").get(0)+ .path("CreateRule").path("Interval").asInt());+ assertEquals("test", updated.getTags().get("env"));++ service.deleteLifecyclePolicy(created.getPolicyId(), REGION);+ AwsException missing = assertThrows(AwsException.class,+ () -> service.getLifecyclePolicy(created.getPolicyId(), REGION));+ assertEquals("ResourceNotFoundException", missing.getErrorCode());+ }++ @Test+ void listSupportsAllDocumentedFilters() throws Exception {+ LifecyclePolicy daily = service.createLifecyclePolicy(customPolicy("daily", "ENABLED"), REGION);+ service.createLifecyclePolicy(objectMapper.readTree("""+ {"ExecutionRoleArn":"%s","Description":"images","State":"DISABLED",+ "PolicyDetails":{"PolicyType":"IMAGE_MANAGEMENT","ResourceTypes":["INSTANCE"],+ "TargetTags":[{"Key":"image","Value":"true"}],+ "Schedules":[{"TagsToAdd":[{"Key":"managed","Value":"ami"}]}]}}+ """.formatted(ROLE)), REGION);+ service.createLifecyclePolicy(objectMapper.readTree("""+ {"ExecutionRoleArn":"%s","Description":"defaults","State":"ENABLED",+ "DefaultPolicy":"VOLUME","CreateInterval":1,"RetainInterval":7}+ """.formatted(ROLE)), REGION);++ assertEquals(List.of(daily.getPolicyId()), service.getLifecyclePolicies(REGION,+ List.of(daily.getPolicyId()), null, List.of(), List.of(), List.of(), null).stream()+ .map(LifecyclePolicy::getPolicyId).toList());+ assertEquals(2, service.getLifecyclePolicies(REGION, List.of(), "ENABLED",+ List.of(), List.of(), List.of(), null).size());+ assertEquals(1, service.getLifecyclePolicies(REGION, List.of(), null,+ List.of("INSTANCE"), List.of(), List.of(), null).size());+ assertEquals(1, service.getLifecyclePolicies(REGION, List.of(), null,+ List.of(), List.of("backup=true"), List.of(), null).size());+ assertEquals(1, service.getLifecyclePolicies(REGION, List.of(), null,+ List.of(), List.of(), List.of("managed=dlm"), null).size());+ assertEquals(1, service.getLifecyclePolicies(REGION, List.of(), null,+ List.of(), List.of(), List.of(), "VOLUME").size());+ assertEquals(1, service.getLifecyclePolicies(REGION, List.of(), null,+ List.of(), List.of(), List.of(), "ALL").size());+ }++ @Test+ void tagsRoundTripThroughTheSharedRestHandlerContract() throws Exception {+ LifecyclePolicy policy = service.createLifecyclePolicy(customPolicy("daily", "ENABLED"), REGION);++ assertEquals("Tags", service.tagsBodyKey());+ assertEquals("InvalidRequestException", service.tagValidationErrorCode());+ assertEquals(200, service.tagResourceSuccessStatus());+ service.tagResource(REGION, policy.getPolicyArn(), Map.of("owner", "platform"));+ assertEquals(Map.of("env", "test", "owner", "platform"),+ service.listTags(REGION, policy.getPolicyArn()));++ service.untagResource(REGION, policy.getPolicyArn(), List.of("env"));+ assertEquals(Map.of("owner", "platform"), service.listTags(REGION, policy.getPolicyArn()));+ }++ @Test+ void invalidRequestsDoNotMutateStoredState() throws Exception {+ LifecyclePolicy policy = service.createLifecyclePolicy(customPolicy("daily", "ENABLED"), REGION);++ AwsException badDescription = assertThrows(AwsException.class, () ->+ service.updateLifecyclePolicy(policy.getPolicyId(),+ objectMapper.readTree("{\"Description\":\"not.allowed\"}"), REGION));+ assertEquals("InvalidRequestException", badDescription.getErrorCode());+ assertEquals("daily", service.getLifecyclePolicy(policy.getPolicyId(), REGION).getDescription());++ AwsException changedType = assertThrows(AwsException.class, () ->+ service.updateLifecyclePolicy(policy.getPolicyId(), objectMapper.readTree("""+ {"PolicyDetails":{"PolicyType":"IMAGE_MANAGEMENT","ResourceTypes":["VOLUME"]}}+ """), REGION));+ assertEquals("InvalidRequestException", changedType.getErrorCode());++ AwsException partiallyInvalid = assertThrows(AwsException.class, () ->+ service.updateLifecyclePolicy(policy.getPolicyId(), objectMapper.readTree("""+ {"Description":"changed","State":"ERROR"}+ """), REGION));+ assertEquals("InvalidRequestException", partiallyInvalid.getErrorCode());+ assertEquals("daily", service.getLifecyclePolicy(policy.getPolicyId(), REGION).getDescription());++ AwsException badState = assertThrows(AwsException.class, () ->+ service.createLifecyclePolicy(objectMapper.readTree("""+ {"ExecutionRoleArn":"%s","Description":"bad","State":"ERROR"}+ """.formatted(ROLE)), REGION));+ assertEquals("InvalidRequestException", badState.getErrorCode());+ }++ @Test+ void createAllowsEmptyTagsAndSupportedArnPartitions() throws Exception {+ JsonNode request = objectMapper.readTree("""+ {"ExecutionRoleArn":"arn:aws-eusc:iam::000000000000:role/dlm",+ "Description":"daily","State":"ENABLED","Tags":{}}+ """);++ LifecyclePolicy policy = service.createLifecyclePolicy(request, REGION);++ assertTrue(policy.getTags().isEmpty());+ assertEquals("arn:aws-eusc:iam::000000000000:role/dlm", policy.getExecutionRoleArn());+ }++ @Test+ void listRejectsMultipleResourceTypes() throws Exception {+ service.createLifecyclePolicy(customPolicy("daily", "ENABLED"), REGION);++ AwsException invalid = assertThrows(AwsException.class, () -> service.getLifecyclePolicies(REGION,+ List.of(), null, List.of("VOLUME", "INSTANCE"), List.of(), List.of(), null));++ assertEquals("InvalidRequestException", invalid.getErrorCode());+ }++ @Test+ void regionScopingAndResetAreAppliedByTheStorageKey() throws Exception {+ LifecyclePolicy policy = service.createLifecyclePolicy(customPolicy("daily", "ENABLED"), REGION);++ assertTrue(service.getLifecyclePolicies("eu-west-1", List.of(), null,+ List.of(), List.of(), List.of(), null).isEmpty());+ assertThrows(AwsException.class,+ () -> service.getLifecyclePolicy(policy.getPolicyId(), "eu-west-1"));++ service.clear();+ assertTrue(policies.keys().isEmpty());+ assertFalse(service.getLifecyclePolicies(REGION, List.of(), null,+ List.of(), List.of(), List.of(), null).stream().findAny().isPresent());+ }++ private JsonNode customPolicy(String description, String state) throws Exception {+ return objectMapper.readTree("""+ {"ExecutionRoleArn":"%s","Description":"%s","State":"%s","Tags":{"env":"test"},+ "PolicyDetails":{"PolicyType":"EBS_SNAPSHOT_MANAGEMENT","ResourceTypes":["VOLUME"],+ "TargetTags":[{"Key":"backup","Value":"true"}],+ "Schedules":[{"Name":"daily","CreateRule":{"Interval":24,"IntervalUnit":"HOURS"},+ "RetainRule":{"Count":7},"TagsToAdd":[{"Key":"managed","Value":"dlm"}]}]}}+ """.formatted(ROLE, description, state));+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 7148773cc8..aab3a1871b 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -489,6 +489,8 @@ floci:enabled: trueappintegrations:enabled: true+ dlm:+ enabled: truecognitoidentity:enabled: trueglobalaccelerator:diff --git a/tools/docs/services.yaml b/tools/docs/services.yamlindex 70e6136d58..0a8d58b061 100644--- a/tools/docs/services.yaml+++ b/tools/docs/services.yaml@@ -158,6 +158,19 @@ services:- TagResourceByBody- TagResourcePut- UntagResourceByQuery+ - service: dlm+ doc: docs/services/dlm.md+ sources:+ - { path: src/main/java/io/github/hectorvent/floci/services/dlm/DlmController.java, mode: rest }+ - { path: src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java, mode: rest }+ rename_actions:+ ListTags: ListTagsForResource+ TagResourcePost: TagResource+ exclude_actions:+ - ListTagsByQuery+ - TagResourceByBody+ - TagResourcePut+ - UntagResourceByQuery- service: connectdoc: docs/services/connect.mdsources: