Light, fluffy, and always free - The AWS Local Emulator alternative
feat(aps): implement AMP rule groups namespaces (#3330)
Matan Baruch6eca8540a8ae
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AmpTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AmpTest.javaindex 863e39d85c..1651cee1e1 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AmpTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AmpTest.java@@ -7,11 +7,16 @@ import org.junit.jupiter.api.MethodOrderer;import org.junit.jupiter.api.Order;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestMethodOrder;+import software.amazon.awssdk.core.SdkBytes;import software.amazon.awssdk.services.amp.AmpClient;+import software.amazon.awssdk.services.amp.model.CreateRuleGroupsNamespaceResponse;import software.amazon.awssdk.services.amp.model.CreateWorkspaceResponse;+import software.amazon.awssdk.services.amp.model.DescribeRuleGroupsNamespaceResponse;import software.amazon.awssdk.services.amp.model.DescribeWorkspaceResponse;+import software.amazon.awssdk.services.amp.model.ListRuleGroupsNamespacesResponse;import software.amazon.awssdk.services.amp.model.ListWorkspacesResponse;import software.amazon.awssdk.services.amp.model.ResourceNotFoundException;+import software.amazon.awssdk.services.amp.model.RuleGroupsNamespaceStatusCode;import software.amazon.awssdk.services.amp.model.WorkspaceStatusCode;import java.util.Map;@@ -114,6 +119,48 @@ class AmpTest {@Test@Order(6)+ void ruleGroupsNamespaceLifecycle() {+ SdkBytes rules = SdkBytes.fromUtf8String("groups:\n- name: alerts\n rules: []\n");++ CreateRuleGroupsNamespaceResponse created = amp.createRuleGroupsNamespace(r -> r+ .workspaceId(workspaceId)+ .name("alerts")+ .data(rules)+ .tags(Map.of("team", "devops")));++ assertThat(created.name()).isEqualTo("alerts");+ assertThat(created.arn()).contains(":rulegroupsnamespace/" + workspaceId + "/alerts");+ assertThat(created.status().statusCode()).isEqualTo(RuleGroupsNamespaceStatusCode.ACTIVE);+ assertThat(created.tags()).containsEntry("team", "devops");++ DescribeRuleGroupsNamespaceResponse described = amp.describeRuleGroupsNamespace(r -> r+ .workspaceId(workspaceId).name("alerts"));++ assertThat(described.ruleGroupsNamespace().arn()).isEqualTo(created.arn());+ assertThat(described.ruleGroupsNamespace().data()).isEqualTo(rules);+ assertThat(described.ruleGroupsNamespace().createdAt()).isNotNull();+ assertThat(described.ruleGroupsNamespace().modifiedAt()).isNotNull();++ ListRuleGroupsNamespacesResponse listed = amp.listRuleGroupsNamespaces(r -> r+ .workspaceId(workspaceId).name("ale"));+ assertThat(listed.ruleGroupsNamespaces())+ .anySatisfy(n -> assertThat(n.name()).isEqualTo("alerts"));++ SdkBytes updated = SdkBytes.fromUtf8String("groups:\n- name: updated\n rules: []\n");+ amp.putRuleGroupsNamespace(r -> r.workspaceId(workspaceId).name("alerts").data(updated));++ assertThat(amp.describeRuleGroupsNamespace(r -> r.workspaceId(workspaceId).name("alerts"))+ .ruleGroupsNamespace().data()).isEqualTo(updated);++ amp.deleteRuleGroupsNamespace(r -> r.workspaceId(workspaceId).name("alerts"));++ assertThatThrownBy(() -> amp.describeRuleGroupsNamespace(r -> r+ .workspaceId(workspaceId).name("alerts")))+ .isInstanceOf(ResourceNotFoundException.class);+ }++ @Test+ @Order(7)void deleteWorkspaceThenDescribeThrowsResourceNotFound() {amp.deleteWorkspace(r -> r.workspaceId(workspaceId));diff --git a/docs/services/index.md b/docs/services/index.mdindex 0108ad1d7d..61a9441783 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -105,7 +105,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [AWS RAM](ram.md) | `POST /{operationname}` (lowercase), `DELETE /deleteresourceshare` | REST JSON | 12 || [Control Catalog](controlcatalog.md) | `/get-control`, `/list-controls` | REST JSON | 2 || [Control Tower](controltower.md) | `/list-landingzones`, `/get-landingzone`, `/create-landingzone`, `/*-baseline*` | REST JSON | 15 |-| [Managed Prometheus (AMP)](managed-prometheus.md) | `/workspaces/*`, `/tags/*` | REST JSON | 8 |+| [Managed Prometheus (AMP)](managed-prometheus.md) | `/workspaces/*`, `/workspaces/*/rulegroupsnamespaces/*`, `/tags/*` | REST JSON | 13 || [AWS Backup](backup.md) | `/backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 20 || [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 || [CodeGuru Reviewer](codegurureviewer.md) | `/associations`, `/associations/{associationArn}`, `/tags/*` | REST JSON | 7 |diff --git a/docs/services/managed-prometheus.md b/docs/services/managed-prometheus.mdindex 2475e1ee36..db2697f8a1 100644--- a/docs/services/managed-prometheus.md+++ b/docs/services/managed-prometheus.md@@ -3,10 +3,10 @@**Protocol:** REST JSON**Endpoint:** `http://localhost:4566`-Floci implements the AMP **workspace** lifecycle — the surface Terraform's and Pulumi's-`aws_prometheus_workspace` resource uses — plus tagging through the shared-`/tags/{resourceArn}` dispatcher. Alert manager definitions, rule groups namespaces, scrapers-and logging configurations are not implemented.+Floci implements the AMP **workspace** and **rule groups namespace** lifecycles — the surface+Terraform's and Pulumi's `aws_prometheus_workspace` and `aws_prometheus_rule_group_namespace`+resources use — plus tagging through the shared `/tags/{resourceArn}` dispatcher. Alert manager+definitions, scrapers and logging configurations are not implemented.## Emulation notes@@ -22,6 +22,27 @@ and logging configurations are not implemented.`alias_prefix` data-source argument.- `clientToken` on `CreateWorkspace` is accepted and ignored: creates are not deduplicated.- `kmsKeyArn` is stored and echoed back but no encryption is performed.+- A rule groups namespace is **ACTIVE from birth** for the same reason, so the provider's+ create (`CREATING` → `ACTIVE`) and update (`UPDATING` → `ACTIVE`) waiters complete on their+ first poll.+- The `data` blob is stored and returned byte for byte. Floci does not parse or validate the+ Prometheus rules it contains, so an invalid rule file is accepted.+- Rule groups namespaces live inside their workspace: `DeleteWorkspace` deletes the namespaces+ it holds, and every namespace operation on an unknown workspace returns+ `ResourceNotFoundException` (404).+- Creating a namespace whose name already exists in the workspace returns `ConflictException`+ (409). `PutRuleGroupsNamespace` requires an existing namespace and returns+ `ResourceNotFoundException` (404) otherwise.+- The `name` parameter of `ListRuleGroupsNamespaces` is a **prefix** filter, like `alias` on+ `ListWorkspaces`.+- Namespace names are validated against AMP's documented constraints (1 to 128 characters+ matching `.*[0-9A-Za-z][-.0-9A-Z_a-z]*.*`). Floci additionally rejects `/`, because the+ namespace is addressed as a single path segment.+- `clientToken` on `CreateRuleGroupsNamespace` is accepted and ignored, the same as on+ `CreateWorkspace`: creates are not deduplicated.+- The shared tags dispatcher rejects an ARN whose service, region or account does not match the+ request with `ValidationException` (400), rather than resolving it against the request's own+ region.## Supported Operations@@ -31,7 +52,12 @@ and logging configurations are not implemented.| `DescribeWorkspace` | `GET /workspaces/{workspaceId}` | Returns the workspace description including `prometheusEndpoint` || `ListWorkspaces` | `GET /workspaces` | Lists workspaces; `alias` prefix filter, `maxResults`/`nextToken` pagination || `UpdateWorkspaceAlias` | `POST /workspaces/{workspaceId}/alias` | Updates the alias (`204`) |-| `DeleteWorkspace` | `DELETE /workspaces/{workspaceId}` | Deletes the workspace (`202`) |-| `ListTagsForResource` | `GET /tags/{resourceArn}` | Lists workspace tags (shared tags dispatcher) |-| `TagResource` | `POST /tags/{resourceArn}` | Adds or overwrites workspace tags (`200`) |-| `UntagResource` | `DELETE /tags/{resourceArn}?tagKeys=...` | Removes workspace tags (`200`) |+| `DeleteWorkspace` | `DELETE /workspaces/{workspaceId}` | Deletes the workspace and its rule groups namespaces (`202`) |+| `CreateRuleGroupsNamespace` | `POST /workspaces/{workspaceId}/rulegroupsnamespaces` | Creates a namespace (`202`); returns `name`, `arn`, `status`, `tags` |+| `DescribeRuleGroupsNamespace` | `GET /workspaces/{workspaceId}/rulegroupsnamespaces/{name}` | Returns the namespace description including `data` |+| `ListRuleGroupsNamespaces` | `GET /workspaces/{workspaceId}/rulegroupsnamespaces` | Lists namespaces; `name` prefix filter, `maxResults`/`nextToken` pagination |+| `PutRuleGroupsNamespace` | `PUT /workspaces/{workspaceId}/rulegroupsnamespaces/{name}` | Replaces the namespace `data` (`202`) |+| `DeleteRuleGroupsNamespace` | `DELETE /workspaces/{workspaceId}/rulegroupsnamespaces/{name}` | Deletes the namespace (`202`) |+| `ListTagsForResource` | `GET /tags/{resourceArn}` | Lists workspace or namespace tags (shared tags dispatcher) |+| `TagResource` | `POST /tags/{resourceArn}` | Adds or overwrites workspace or namespace tags (`200`) |+| `UntagResource` | `DELETE /tags/{resourceArn}?tagKeys=...` | Removes workspace or namespace tags (`200`) |diff --git a/src/main/java/io/github/hectorvent/floci/services/aps/ApsController.java b/src/main/java/io/github/hectorvent/floci/services/aps/ApsController.javaindex 90aff865fb..99465ef932 100644--- a/src/main/java/io/github/hectorvent/floci/services/aps/ApsController.java+++ b/src/main/java/io/github/hectorvent/floci/services/aps/ApsController.java@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.common.Pagination;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.services.aps.model.PrometheusWorkspace;+import io.github.hectorvent.floci.services.aps.model.RuleGroupsNamespace;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ObjectNode;import jakarta.inject.Inject;@@ -12,6 +13,7 @@ import jakarta.ws.rs.Consumes;import jakarta.ws.rs.DELETE;import jakarta.ws.rs.GET;import jakarta.ws.rs.POST;+import jakarta.ws.rs.PUT;import jakarta.ws.rs.Path;import jakarta.ws.rs.PathParam;import jakarta.ws.rs.Produces;@@ -26,8 +28,9 @@ import java.util.Map;/*** Amazon Managed Service for Prometheus (Smithy restJson1, SigV4 scope {@code aps}) — the- * workspace lifecycle only: create/describe/list/delete plus alias update. Tagging goes through- * the shared {@code /tags/{resourceArn}} dispatcher, which routes {@code arn:aws:aps:...} to+ * workspace lifecycle (create/describe/list/delete plus alias update) and rule groups namespaces+ * (create/describe/list/put/delete). Tagging goes through the shared+ * {@code /tags/{resourceArn}} dispatcher, which routes {@code arn:aws:aps:...} to* {@link ApsService}'s TagHandler implementation.** <p>The literal {@code /workspaces} path segment takes JAX-RS precedence over S3's@@ -122,6 +125,100 @@ public class ApsController {return Response.status(204).build();}+ @POST+ @Path("/workspaces/{workspaceId}/rulegroupsnamespaces")+ public Response createRuleGroupsNamespace(@Context HttpHeaders headers,+ @PathParam("workspaceId") String workspaceId,+ Map<String, Object> request) {+ Map<String, Object> body = request != null ? request : Map.of();+ RuleGroupsNamespace namespace = service.createRuleGroupsNamespace(+ regionResolver.resolveRegion(headers), workspaceId,+ asString(body.get("name"), "name"), asString(body.get("data"), "data"),+ asStringMap(body.get("tags"), "tags"));+ return Response.status(202).entity(toNamespaceMutationResponse(namespace)).build();+ }++ @GET+ @Path("/workspaces/{workspaceId}/rulegroupsnamespaces")+ public Response listRuleGroupsNamespaces(@Context HttpHeaders headers,+ @PathParam("workspaceId") String workspaceId,+ @QueryParam("name") String name,+ @QueryParam("maxResults") String maxResultsParam,+ @QueryParam("nextToken") String nextToken) {+ PaginatedResult<RuleGroupsNamespace> result = service.listRuleGroupsNamespaces(+ regionResolver.resolveRegion(headers), workspaceId, name,+ Pagination.parseMaxResults(maxResultsParam, "ValidationException"), nextToken);++ Map<String, Object> response = new HashMap<>();+ response.put("ruleGroupsNamespaces", result.items().stream().map(this::toNamespaceSummary).toList());+ if (result.nextToken() != null) {+ response.put("nextToken", result.nextToken());+ }+ return Response.ok(response).build();+ }++ @GET+ @Path("/workspaces/{workspaceId}/rulegroupsnamespaces/{name}")+ public Response describeRuleGroupsNamespace(@Context HttpHeaders headers,+ @PathParam("workspaceId") String workspaceId,+ @PathParam("name") String name) {+ RuleGroupsNamespace namespace = service.describeRuleGroupsNamespace(+ regionResolver.resolveRegion(headers), workspaceId, name);+ ObjectNode response = objectMapper.createObjectNode();+ ObjectNode description = toNamespaceSummary(namespace);+ description.put("data", namespace.getEncodedData());+ response.set("ruleGroupsNamespace", description);+ return Response.ok(response).build();+ }++ @PUT+ @Path("/workspaces/{workspaceId}/rulegroupsnamespaces/{name}")+ public Response putRuleGroupsNamespace(@Context HttpHeaders headers,+ @PathParam("workspaceId") String workspaceId,+ @PathParam("name") String name,+ Map<String, Object> request) {+ Map<String, Object> body = request != null ? request : Map.of();+ RuleGroupsNamespace namespace = service.putRuleGroupsNamespace(+ regionResolver.resolveRegion(headers), workspaceId, name,+ asString(body.get("data"), "data"));+ return Response.status(202).entity(toNamespaceMutationResponse(namespace)).build();+ }++ @DELETE+ @Path("/workspaces/{workspaceId}/rulegroupsnamespaces/{name}")+ public Response deleteRuleGroupsNamespace(@Context HttpHeaders headers,+ @PathParam("workspaceId") String workspaceId,+ @PathParam("name") String name) {+ service.deleteRuleGroupsNamespace(regionResolver.resolveRegion(headers), workspaceId, name);+ return Response.status(202).build();+ }++ private ObjectNode toNamespaceMutationResponse(RuleGroupsNamespace namespace) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("name", namespace.getName());+ node.put("arn", namespace.getArn());+ node.set("status", namespaceStatusNode(namespace));+ node.set("tags", objectMapper.valueToTree(namespace.getTags()));+ return node;+ }++ private ObjectNode toNamespaceSummary(RuleGroupsNamespace namespace) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("arn", namespace.getArn());+ node.put("name", namespace.getName());+ node.set("status", namespaceStatusNode(namespace));+ node.set("tags", objectMapper.valueToTree(namespace.getTags()));+ node.put("createdAt", namespace.getCreatedAt().toEpochMilli() / 1000.0);+ node.put("modifiedAt", namespace.getModifiedAt().toEpochMilli() / 1000.0);+ return node;+ }++ private ObjectNode namespaceStatusNode(RuleGroupsNamespace namespace) {+ ObjectNode status = objectMapper.createObjectNode();+ status.put("statusCode", namespace.getStatus());+ return status;+ }+private ObjectNode toWorkspaceDescription(PrometheusWorkspace workspace) {ObjectNode node = toWorkspaceSummary(workspace);node.put("prometheusEndpoint", workspace.getPrometheusEndpoint());diff --git a/src/main/java/io/github/hectorvent/floci/services/aps/ApsService.java b/src/main/java/io/github/hectorvent/floci/services/aps/ApsService.javaindex 21a29f01d3..1276f101a6 100644--- a/src/main/java/io/github/hectorvent/floci/services/aps/ApsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/aps/ApsService.java@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.TagHandler;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.aps.model.PrometheusWorkspace;+import io.github.hectorvent.floci.services.aps.model.RuleGroupsNamespace;import com.fasterxml.jackson.core.type.TypeReference;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;@@ -18,6 +19,7 @@ import java.time.Instant;import java.util.List;import java.util.Map;import java.util.UUID;+import java.util.regex.Pattern;@ApplicationScopedpublic class ApsService implements TagHandler {@@ -26,14 +28,19 @@ public class ApsService implements TagHandler {// AMP's ListWorkspacesRequest declares maxResults with a default of 100 and a maximum of 1000.private static final int DEFAULT_PAGE = 100;private static final int MAX_PAGE = 1000;+ private static final int MAX_NAMESPACE_NAME_LENGTH = 128;+ private static final Pattern NAMESPACE_NAME = Pattern.compile(".*[0-9A-Za-z][-.0-9A-Z_a-z]*.*");private final StorageBackend<String, PrometheusWorkspace> storage;+ private final StorageBackend<String, RuleGroupsNamespace> namespaceStorage;private final RegionResolver regionResolver;@Injectpublic ApsService(StorageFactory storageFactory, RegionResolver regionResolver) {this.storage = storageFactory.create("aps", "aps-workspaces.json",new TypeReference<Map<String, PrometheusWorkspace>>() {});+ this.namespaceStorage = storageFactory.create("aps", "aps-rule-groups-namespaces.json",+ new TypeReference<Map<String, RuleGroupsNamespace>>() {});this.regionResolver = regionResolver;}@@ -85,6 +92,10 @@ public class ApsService implements TagHandler {public void deleteWorkspace(String region, String workspaceId) {describeWorkspace(region, workspaceId);+ String namespacePrefix = namespaceKeyPrefix(region, workspaceId);+ for (RuleGroupsNamespace namespace : namespaceStorage.scan(k -> k.startsWith(namespacePrefix))) {+ namespaceStorage.delete(namespaceKey(region, workspaceId, namespace.getName()));+ }storage.delete(key(region, workspaceId));LOG.infov("Deleted AMP workspace: {0} in {1}", workspaceId, region);}@@ -95,6 +106,71 @@ public class ApsService implements TagHandler {storage.put(key(region, workspaceId), workspace);}+ public RuleGroupsNamespace createRuleGroupsNamespace(String region, String workspaceId, String name,+ String encodedData, Map<String, String> tags) {+ describeWorkspace(region, workspaceId);+ requireNamespaceName(name);+ requireNamespaceData(encodedData);+ if (namespaceStorage.get(namespaceKey(region, workspaceId, name)).isPresent()) {+ throw new AwsException("ConflictException",+ "Rule groups namespace already exists: " + name, 409);+ }++ RuleGroupsNamespace namespace = new RuleGroupsNamespace();+ namespace.setName(name);+ namespace.setWorkspaceId(workspaceId);+ namespace.setArn(regionResolver.buildArn("aps", region,+ "rulegroupsnamespace/" + workspaceId + "/" + name));+ namespace.setStatus("ACTIVE");+ namespace.setEncodedData(encodedData);+ Instant now = Instant.now();+ namespace.setCreatedAt(now);+ namespace.setModifiedAt(now);+ if (tags != null) {+ namespace.getTags().putAll(tags);+ }++ namespaceStorage.put(namespaceKey(region, workspaceId, name), namespace);+ LOG.infov("Created AMP rule groups namespace: {0} in workspace {1}", name, workspaceId);+ return namespace;+ }++ public RuleGroupsNamespace describeRuleGroupsNamespace(String region, String workspaceId, String name) {+ describeWorkspace(region, workspaceId);+ return namespaceStorage.get(namespaceKey(region, workspaceId, name))+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "Rule groups namespace not found: " + name, 404));+ }++ public PaginatedResult<RuleGroupsNamespace> listRuleGroupsNamespaces(String region, String workspaceId,+ String namePrefix, Integer maxResults,+ String nextToken) {+ describeWorkspace(region, workspaceId);+ String prefix = namespaceKeyPrefix(region, workspaceId);+ List<RuleGroupsNamespace> all = namespaceStorage.scan(k -> k.startsWith(prefix)).stream()+ .filter(n -> namePrefix == null || namePrefix.isEmpty()+ || (n.getName() != null && n.getName().startsWith(namePrefix)))+ .toList();+ return Pagination.paginate(all, RuleGroupsNamespace::getName, maxResults, nextToken,+ DEFAULT_PAGE, MAX_PAGE, "ValidationException");+ }++ public RuleGroupsNamespace putRuleGroupsNamespace(String region, String workspaceId, String name,+ String encodedData) {+ requireNamespaceData(encodedData);+ RuleGroupsNamespace namespace = describeRuleGroupsNamespace(region, workspaceId, name);+ namespace.setEncodedData(encodedData);+ namespace.setModifiedAt(Instant.now());+ namespaceStorage.put(namespaceKey(region, workspaceId, name), namespace);+ return namespace;+ }++ public void deleteRuleGroupsNamespace(String region, String workspaceId, String name) {+ describeRuleGroupsNamespace(region, workspaceId, name);+ namespaceStorage.delete(namespaceKey(region, workspaceId, name));+ LOG.infov("Deleted AMP rule groups namespace: {0} in workspace {1}", name, workspaceId);+ }+// ── TagHandler: the shared /tags/{resourceArn} dispatcher routes aps ARNs here ──@Override@@ -115,7 +191,7 @@ public class ApsService implements TagHandler {@Overridepublic Map<String, String> listTags(String region, String arn) {- return Map.copyOf(workspaceByArn(region, arn).getTags());+ return Map.copyOf(taggableByArn(region, arn).tags());}@Override@@ -128,32 +204,52 @@ public class ApsService implements TagHandler {"Tag keys must not begin with aws:. Offending key: " + tagKey, 400);}}- PrometheusWorkspace workspace = workspaceByArn(region, arn);- workspace.getTags().putAll(tags);- storage.put(key(region, workspace.getWorkspaceId()), workspace);+ Taggable taggable = taggableByArn(region, arn);+ taggable.tags().putAll(tags);+ taggable.persist().run();}@Overridepublic void untagResource(String region, String arn, List<String> tagKeys) {- PrometheusWorkspace workspace = workspaceByArn(region, arn);- tagKeys.forEach(workspace.getTags()::remove);- storage.put(key(region, workspace.getWorkspaceId()), workspace);+ Taggable taggable = taggableByArn(region, arn);+ tagKeys.forEach(taggable.tags()::remove);+ taggable.persist().run();+ }++ private record Taggable(Map<String, String> tags, Runnable persist) {}- private PrometheusWorkspace workspaceByArn(String region, String arn) {- // arn:aws:aps:<region>:<account>:workspace/<workspaceId>- String resource;+ private Taggable taggableByArn(String region, String arn) {+ AwsArnUtils.Arn parsed;try {- resource = AwsArnUtils.parse(arn).resource();+ parsed = AwsArnUtils.parse(arn);} catch (IllegalArgumentException e) {throw new AwsException("ValidationException", "Invalid resource ARN: " + arn, 400);}- String prefix = "workspace/";- if (!resource.startsWith(prefix) || resource.length() == prefix.length()) {+ if (!"aps".equals(parsed.service()) || !region.equals(parsed.region())+ || !regionResolver.getAccountId().equals(parsed.accountId())) {throw new AwsException("ValidationException",- "Tags are only supported on AMP workspaces: " + arn, 400);+ "The resource ARN does not belong to this AMP account and region: " + arn, 400);}- return describeWorkspace(region, resource.substring(prefix.length()));+ String resource = parsed.resource();+ String workspacePrefix = "workspace/";+ if (resource.startsWith(workspacePrefix) && resource.length() > workspacePrefix.length()) {+ PrometheusWorkspace workspace =+ describeWorkspace(region, resource.substring(workspacePrefix.length()));+ return new Taggable(workspace.getTags(),+ () -> storage.put(key(region, workspace.getWorkspaceId()), workspace));+ }+ String namespacePrefix = "rulegroupsnamespace/";+ if (resource.startsWith(namespacePrefix)) {+ String[] parts = resource.substring(namespacePrefix.length()).split("/", 2);+ if (parts.length == 2 && !parts[0].isEmpty() && !parts[1].isEmpty()) {+ RuleGroupsNamespace namespace = describeRuleGroupsNamespace(region, parts[0], parts[1]);+ return new Taggable(namespace.getTags(),+ () -> namespaceStorage.put(namespaceKey(region, parts[0], parts[1]), namespace));+ }+ }+ throw new AwsException("ValidationException",+ "Tags are only supported on AMP workspaces and rule groups namespaces: " + arn, 400);}// AMP is regional ("You can have one or more workspaces in each Region in your account"), so@@ -166,6 +262,30 @@ public class ApsService implements TagHandler {return region + "::";}+ private static String namespaceKey(String region, String workspaceId, String name) {+ return namespaceKeyPrefix(region, workspaceId) + name;+ }++ private static String namespaceKeyPrefix(String region, String workspaceId) {+ return keyPrefix(region) + workspaceId + "::";+ }++ private static void requireNamespaceName(String name) {+ if (name == null || name.isEmpty() || name.length() > MAX_NAMESPACE_NAME_LENGTH+ || !NAMESPACE_NAME.matcher(name).matches() || name.indexOf('/') >= 0) {+ throw new AwsException("ValidationException",+ "name must be 1 to " + MAX_NAMESPACE_NAME_LENGTH+ + " characters matching " + NAMESPACE_NAME.pattern()+ + " and must not contain '/'.", 400);+ }+ }++ private static void requireNamespaceData(String encodedData) {+ if (encodedData == null || encodedData.isEmpty()) {+ throw new AwsException("ValidationException", "data must not be empty.", 400);+ }+ }+// AMP strips leading/trailing blanks from every alias it accepts, including the list filter.private static String stripAlias(String alias) {return alias == null ? null : alias.strip();diff --git a/src/main/java/io/github/hectorvent/floci/services/aps/model/RuleGroupsNamespace.java b/src/main/java/io/github/hectorvent/floci/services/aps/model/RuleGroupsNamespace.javanew file mode 100644index 0000000000..d8885df304--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/aps/model/RuleGroupsNamespace.java@@ -0,0 +1,51 @@+package io.github.hectorvent.floci.services.aps.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.Map;+import java.util.concurrent.ConcurrentHashMap;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class RuleGroupsNamespace {++ private String name;+ private String workspaceId;+ private String arn;+ private String status;+ private String encodedData;+ private Instant createdAt;+ private Instant modifiedAt;+ private Map<String, String> tags = new ConcurrentHashMap<>();++ public RuleGroupsNamespace() {+ }++ public String getName() { return name; }+ public void setName(String name) { this.name = name; }++ public String getWorkspaceId() { return workspaceId; }+ public void setWorkspaceId(String workspaceId) { this.workspaceId = workspaceId; }++ public String getArn() { return arn; }+ public void setArn(String arn) { this.arn = arn; }++ public String getStatus() { return status; }+ public void setStatus(String status) { this.status = status; }++ public String getEncodedData() { return encodedData; }+ public void setEncodedData(String encodedData) { this.encodedData = encodedData; }++ public Instant getCreatedAt() { return createdAt; }+ public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }++ public Instant getModifiedAt() { return modifiedAt; }+ public void setModifiedAt(Instant modifiedAt) { this.modifiedAt = modifiedAt; }++ public Map<String, String> getTags() { return tags; }+ public void setTags(Map<String, String> tags) {+ this.tags = tags != null ? new ConcurrentHashMap<>(tags) : new ConcurrentHashMap<>();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/aps/ApsControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/aps/ApsControllerIntegrationTest.javaindex c7ee7c7f2b..232397d1a0 100644--- a/src/test/java/io/github/hectorvent/floci/services/aps/ApsControllerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/aps/ApsControllerIntegrationTest.java@@ -3,6 +3,9 @@ package io.github.hectorvent.floci.services.aps;import io.quarkus.test.junit.QuarkusTest;import org.junit.jupiter.api.Test;+import java.nio.charset.StandardCharsets;+import java.util.Base64;+import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.containsString;import static org.hamcrest.Matchers.emptyString;@@ -224,6 +227,156 @@ class ApsControllerIntegrationTest {.body("tags", not(org.hamcrest.Matchers.hasKey("team")));}+ private static final String RULES = Base64.getEncoder().encodeToString(+ "groups:\n- name: alerts\n rules: []\n".getBytes(StandardCharsets.UTF_8));++ @Test+ void ruleGroupsNamespaceLifecycleRoundTrip() {+ String workspaceId = createWorkspace("rules-lifecycle");++ String arn = given()+ .contentType("application/json")+ .body("""+ {"name": "alerts", "data": "%s", "tags": {"team": "devops"}, "clientToken": "token-123"}+ """.formatted(RULES))+ .when()+ .post("/workspaces/{workspaceId}/rulegroupsnamespaces", workspaceId)+ .then()+ .statusCode(202)+ .body("name", equalTo("alerts"))+ .body("arn", containsString(":rulegroupsnamespace/" + workspaceId + "/alerts"))+ .body("status.statusCode", equalTo("ACTIVE"))+ .body("tags.team", equalTo("devops"))+ .extract().path("arn");++ given()+ .when()+ .get("/workspaces/{workspaceId}/rulegroupsnamespaces/{name}", workspaceId, "alerts")+ .then()+ .statusCode(200)+ .body("ruleGroupsNamespace.name", equalTo("alerts"))+ .body("ruleGroupsNamespace.arn", equalTo(arn))+ .body("ruleGroupsNamespace.status.statusCode", equalTo("ACTIVE"))+ .body("ruleGroupsNamespace.data", equalTo(RULES))+ .body("ruleGroupsNamespace.createdAt", notNullValue())+ .body("ruleGroupsNamespace.modifiedAt", notNullValue());++ given()+ .when()+ .get("/workspaces/{workspaceId}/rulegroupsnamespaces", workspaceId)+ .then()+ .statusCode(200)+ .body("ruleGroupsNamespaces.name", hasItem("alerts"))+ .body("ruleGroupsNamespaces.find { it.name == 'alerts' }.data", equalTo(null));++ String updated = Base64.getEncoder().encodeToString(+ "groups:\n- name: updated\n rules: []\n".getBytes(StandardCharsets.UTF_8));+ given()+ .contentType("application/json")+ .body("{\"data\": \"%s\"}".formatted(updated))+ .when()+ .put("/workspaces/{workspaceId}/rulegroupsnamespaces/{name}", workspaceId, "alerts")+ .then()+ .statusCode(202)+ .body("status.statusCode", equalTo("ACTIVE"));++ given()+ .when()+ .get("/workspaces/{workspaceId}/rulegroupsnamespaces/{name}", workspaceId, "alerts")+ .then()+ .statusCode(200)+ .body("ruleGroupsNamespace.data", equalTo(updated));++ given()+ .when()+ .delete("/workspaces/{workspaceId}/rulegroupsnamespaces/{name}", workspaceId, "alerts")+ .then()+ .statusCode(202)+ .body(is(emptyString()));++ given()+ .when()+ .get("/workspaces/{workspaceId}/rulegroupsnamespaces/{name}", workspaceId, "alerts")+ .then()+ .statusCode(404)+ .header("X-Amzn-Errortype", equalTo("ResourceNotFoundException"));+ }++ @Test+ void createRuleGroupsNamespaceRejectsDuplicateNameWithConflict() {+ String workspaceId = createWorkspace("rules-duplicate");+ String body = """+ {"name": "alerts", "data": "%s"}+ """.formatted(RULES);++ given().contentType("application/json").body(body)+ .when().post("/workspaces/{workspaceId}/rulegroupsnamespaces", workspaceId)+ .then().statusCode(202);++ given().contentType("application/json").body(body)+ .when()+ .post("/workspaces/{workspaceId}/rulegroupsnamespaces", workspaceId)+ .then()+ .statusCode(409)+ .header("X-Amzn-Errortype", equalTo("ConflictException"));+ }++ @Test+ void ruleGroupsNamespaceRoutesRejectAnUnknownWorkspace() {+ given()+ .when()+ .get("/workspaces/{workspaceId}/rulegroupsnamespaces", "ws-missing")+ .then()+ .statusCode(404)+ .header("X-Amzn-Errortype", equalTo("ResourceNotFoundException"));+ }++ @Test+ void deletingAWorkspaceDeletesItsRuleGroupsNamespaces() {+ String workspaceId = createWorkspace("rules-cascade");+ given()+ .contentType("application/json")+ .body("{\"name\": \"alerts\", \"data\": \"%s\"}".formatted(RULES))+ .when().post("/workspaces/{workspaceId}/rulegroupsnamespaces", workspaceId)+ .then().statusCode(202);++ given().when().delete("/workspaces/{workspaceId}", workspaceId).then().statusCode(202);++ given()+ .when()+ .get("/workspaces/{workspaceId}/rulegroupsnamespaces/{name}", workspaceId, "alerts")+ .then()+ .statusCode(404)+ .header("X-Amzn-Errortype", equalTo("ResourceNotFoundException"));+ }++ @Test+ void ruleGroupsNamespaceTagsRoundTripThroughSharedTagsDispatcher() {+ String workspaceId = createWorkspace("rules-tags");+ String arn = given()+ .contentType("application/json")+ .body("{\"name\": \"alerts\", \"data\": \"%s\", \"tags\": {\"team\": \"devops\"}}".formatted(RULES))+ .when().post("/workspaces/{workspaceId}/rulegroupsnamespaces", workspaceId)+ .then().statusCode(202)+ .extract().path("arn");++ given()+ .contentType("application/json")+ .body("{\"tags\": {\"env\": \"test\"}}")+ .when()+ .post("/tags/{arn}", arn)+ .then()+ .statusCode(200);++ given()+ .when()+ .get("/tags/{arn}", arn)+ .then()+ .statusCode(200)+ .body("tags.team", equalTo("devops"))+ .body("tags.env", equalTo("test"));+ }+@Testvoid tagResourceRejectsReservedAwsKeyPrefix() {String workspaceId = createWorkspace("aws-prefix-test");diff --git a/src/test/java/io/github/hectorvent/floci/services/aps/ApsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/aps/ApsServiceTest.javaindex efb16e53f7..39662081bf 100644--- a/src/test/java/io/github/hectorvent/floci/services/aps/ApsServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/aps/ApsServiceTest.java@@ -4,12 +4,17 @@ import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.aps.model.PrometheusWorkspace;+import io.github.hectorvent.floci.services.aps.model.RuleGroupsNamespace;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.mockito.Mockito;+import java.nio.charset.StandardCharsets;+import java.util.Base64;+import java.util.HashMap;import java.util.List;import java.util.Map;@@ -20,14 +25,22 @@ class ApsServiceTest {private static final String US_EAST_1 = "us-east-1";private static final String EU_WEST_1 = "eu-west-1";+ private static final String RULES = Base64.getEncoder().encodeToString(+ "groups:\n- name: alerts\n rules: []\n".getBytes(StandardCharsets.UTF_8));private ApsService service;+ private final Map<String, StorageBackend<String, ?>> backendsByFile = new HashMap<>();@BeforeEachvoid setUp() {+ backendsByFile.clear();StorageFactory storageFactory = Mockito.mock(StorageFactory.class);when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))- .thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));+ .thenAnswer(invocation -> {+ StorageBackend<String, ?> backend = AccountAwareStorageBackend.inMemory("000000000000");+ backendsByFile.put(invocation.getArgument(1), backend);+ return backend;+ });service = new ApsService(storageFactory, new RegionResolver(US_EAST_1, "000000000000"));}@@ -174,7 +187,7 @@ class ApsServiceTest {// A tag call served by another region must not see (or mutate) this workspace.AwsException ex = assertThrows(AwsException.class,() -> service.tagResource(EU_WEST_1, workspace.getArn(), Map.of("team", "devops")));- assertEquals("ResourceNotFoundException", ex.getErrorCode());+ assertEquals("ValidationException", ex.getErrorCode());assertTrue(service.listTags(US_EAST_1, workspace.getArn()).isEmpty());}@@ -201,4 +214,181 @@ class ApsServiceTest {service.listTags(US_EAST_1, "arn:aws:aps:us-east-1:000000000000:workspace"));assertEquals("ValidationException", ex.getErrorCode());}++ private String workspaceWithNamespace(String namespaceName) {+ String workspaceId = service.createWorkspace(US_EAST_1, "rules", null, null).getWorkspaceId();+ service.createRuleGroupsNamespace(US_EAST_1, workspaceId, namespaceName, RULES, null);+ return workspaceId;+ }++ @Test+ void createRuleGroupsNamespaceIsActiveWithArnAndRoundTripsData() {+ String workspaceId = service.createWorkspace(US_EAST_1, "rules", null, null).getWorkspaceId();++ RuleGroupsNamespace namespace = service.createRuleGroupsNamespace(+ US_EAST_1, workspaceId, "alerts", RULES, Map.of("team", "devops"));++ assertEquals("alerts", namespace.getName());+ assertEquals("ACTIVE", namespace.getStatus());+ assertEquals("arn:aws:aps:us-east-1:000000000000:rulegroupsnamespace/" + workspaceId + "/alerts",+ namespace.getArn());+ assertEquals(RULES, namespace.getEncodedData());+ assertNotNull(namespace.getCreatedAt());+ assertNotNull(namespace.getModifiedAt());+ assertEquals("devops", namespace.getTags().get("team"));+ }++ @Test+ void createRuleGroupsNamespaceUnknownWorkspaceThrowsResourceNotFound() {+ AwsException ex = assertThrows(AwsException.class, () ->+ service.createRuleGroupsNamespace(US_EAST_1, "ws-missing", "alerts", RULES, null));+ assertEquals("ResourceNotFoundException", ex.getErrorCode());+ }++ @Test+ void createRuleGroupsNamespaceRejectsDuplicateNameWithConflict() {+ String workspaceId = workspaceWithNamespace("alerts");++ AwsException ex = assertThrows(AwsException.class, () ->+ service.createRuleGroupsNamespace(US_EAST_1, workspaceId, "alerts", RULES, null));+ assertEquals("ConflictException", ex.getErrorCode());+ assertEquals(409, ex.getHttpStatus());+ }++ @Test+ void createRuleGroupsNamespaceRejectsMissingData() {+ String workspaceId = service.createWorkspace(US_EAST_1, "rules", null, null).getWorkspaceId();++ AwsException ex = assertThrows(AwsException.class, () ->+ service.createRuleGroupsNamespace(US_EAST_1, workspaceId, "alerts", null, null));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals(400, ex.getHttpStatus());+ }++ @Test+ void putRuleGroupsNamespaceReplacesTheStoredData() {+ String workspaceId = workspaceWithNamespace("alerts");+ String updated = Base64.getEncoder().encodeToString(+ "groups:\n- name: updated\n rules: []\n".getBytes(StandardCharsets.UTF_8));++ service.putRuleGroupsNamespace(US_EAST_1, workspaceId, "alerts", updated);++ assertEquals(updated,+ service.describeRuleGroupsNamespace(US_EAST_1, workspaceId, "alerts").getEncodedData());+ }++ @Test+ void putRuleGroupsNamespaceUnknownNameThrowsResourceNotFound() {+ String workspaceId = workspaceWithNamespace("alerts");++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putRuleGroupsNamespace(US_EAST_1, workspaceId, "missing", RULES));+ assertEquals("ResourceNotFoundException", ex.getErrorCode());+ }++ @Test+ void listRuleGroupsNamespacesFiltersByNamePrefixAndPaginates() {+ String workspaceId = workspaceWithNamespace("prod-alerts");+ service.createRuleGroupsNamespace(US_EAST_1, workspaceId, "prod-records", RULES, null);+ service.createRuleGroupsNamespace(US_EAST_1, workspaceId, "staging-alerts", RULES, null);++ assertEquals(3, service.listRuleGroupsNamespaces(US_EAST_1, workspaceId, null, null, null)+ .items().size());+ assertEquals(2, service.listRuleGroupsNamespaces(US_EAST_1, workspaceId, "prod-", null, null)+ .items().size());++ PaginatedResult<RuleGroupsNamespace> firstPage =+ service.listRuleGroupsNamespaces(US_EAST_1, workspaceId, null, 2, null);+ assertEquals(2, firstPage.items().size());+ assertNotNull(firstPage.nextToken());+ assertEquals(1, service.listRuleGroupsNamespaces(US_EAST_1, workspaceId, null, 2,+ firstPage.nextToken()).items().size());+ }++ @Test+ void ruleGroupsNamespacesAreScopedToTheirWorkspace() {+ String workspaceId = workspaceWithNamespace("alerts");+ String otherWorkspaceId =+ service.createWorkspace(US_EAST_1, "other", null, null).getWorkspaceId();++ assertEquals(0, service.listRuleGroupsNamespaces(US_EAST_1, otherWorkspaceId, null, null, null)+ .items().size());+ AwsException ex = assertThrows(AwsException.class, () ->+ service.describeRuleGroupsNamespace(US_EAST_1, otherWorkspaceId, "alerts"));+ assertEquals("ResourceNotFoundException", ex.getErrorCode());+ assertEquals("alerts",+ service.describeRuleGroupsNamespace(US_EAST_1, workspaceId, "alerts").getName());+ }++ @Test+ void deleteRuleGroupsNamespaceThenDescribeThrowsResourceNotFound() {+ String workspaceId = workspaceWithNamespace("alerts");++ service.deleteRuleGroupsNamespace(US_EAST_1, workspaceId, "alerts");++ AwsException ex = assertThrows(AwsException.class, () ->+ service.describeRuleGroupsNamespace(US_EAST_1, workspaceId, "alerts"));+ assertEquals("ResourceNotFoundException", ex.getErrorCode());+ }++ @Test+ void deleteWorkspaceRemovesItsRuleGroupsNamespaces() {+ String workspaceId = workspaceWithNamespace("alerts");+ service.createRuleGroupsNamespace(US_EAST_1, workspaceId, "records", RULES, null);++ service.deleteWorkspace(US_EAST_1, workspaceId);++ assertTrue(backendsByFile.get("aps-rule-groups-namespaces.json").scan(k -> true).isEmpty());+ }++ @Test+ void createRuleGroupsNamespaceRejectsNamesThatBreakPathAddressing() {+ String workspaceId = service.createWorkspace(US_EAST_1, "rules", null, null).getWorkspaceId();++ for (String invalid : List.of("nested/name", "", "!!!", "x".repeat(129))) {+ AwsException ex = assertThrows(AwsException.class, () ->+ service.createRuleGroupsNamespace(US_EAST_1, workspaceId, invalid, RULES, null));+ assertEquals("ValidationException", ex.getErrorCode(), "name: " + invalid);+ assertEquals(400, ex.getHttpStatus());+ }+ }++ @Test+ void tagHandlerRejectsArnsFromAnotherAccountOrRegion() {+ String workspaceId = service.createWorkspace(US_EAST_1, "rules", null, null).getWorkspaceId();+ service.createRuleGroupsNamespace(US_EAST_1, workspaceId, "alerts", RULES, null);++ String foreignAccount = "arn:aws:aps:us-east-1:999999999999:rulegroupsnamespace/"+ + workspaceId + "/alerts";+ AwsException byAccount = assertThrows(AwsException.class,+ () -> service.listTags(US_EAST_1, foreignAccount));+ assertEquals("ValidationException", byAccount.getErrorCode());++ String foreignRegion = "arn:aws:aps:eu-west-1:000000000000:rulegroupsnamespace/"+ + workspaceId + "/alerts";+ AwsException byRegion = assertThrows(AwsException.class,+ () -> service.listTags(US_EAST_1, foreignRegion));+ assertEquals("ValidationException", byRegion.getErrorCode());++ String foreignService = "arn:aws:ecs:us-east-1:000000000000:rulegroupsnamespace/"+ + workspaceId + "/alerts";+ AwsException byService = assertThrows(AwsException.class,+ () -> service.listTags(US_EAST_1, foreignService));+ assertEquals("ValidationException", byService.getErrorCode());+ }++ @Test+ void tagHandlerRoundTripsRuleGroupsNamespaceTagsByArn() {+ String workspaceId = service.createWorkspace(US_EAST_1, "rules", null, null).getWorkspaceId();+ String arn = service.createRuleGroupsNamespace(+ US_EAST_1, workspaceId, "alerts", RULES, Map.of("env", "test")).getArn();++ assertEquals(Map.of("env", "test"), service.listTags(US_EAST_1, arn));++ service.tagResource(US_EAST_1, arn, Map.of("team", "devops"));+ assertEquals(Map.of("env", "test", "team", "devops"), service.listTags(US_EAST_1, arn));++ service.untagResource(US_EAST_1, arn, List.of("env"));+ assertEquals(Map.of("team", "devops"), service.listTags(US_EAST_1, arn));+ }}