diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index 2385b2623f..4351a52fc8 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -76,6 +76,10 @@ software.amazon.awssdk acm + + software.amazon.awssdk + amp + software.amazon.awssdk sqs 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.java index d041f0289d..ba77b9d7ec 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 @@ -60,6 +60,7 @@ import software.amazon.awssdk.services.apigatewayv2.ApiGatewayV2Client; import software.amazon.awssdk.services.elasticache.ElastiCacheClient; import software.amazon.awssdk.services.elasticbeanstalk.ElasticBeanstalkClient; import software.amazon.awssdk.services.acm.AcmClient; +import software.amazon.awssdk.services.amp.AmpClient; import software.amazon.awssdk.services.efs.EfsClient; import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ecr.EcrClient; @@ -514,6 +515,14 @@ public final class TestFixtures { .build(); } + public static AmpClient ampClient() { + return AmpClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .build(); + } + public static KinesisClient kinesisClient() { return KinesisClient.builder() .endpointOverride(ENDPOINT) 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.java new file mode 100644 index 0000000000..863e39d85c --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AmpTest.java @@ -0,0 +1,127 @@ +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.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import software.amazon.awssdk.services.amp.AmpClient; +import software.amazon.awssdk.services.amp.model.CreateWorkspaceResponse; +import software.amazon.awssdk.services.amp.model.DescribeWorkspaceResponse; +import software.amazon.awssdk.services.amp.model.ListWorkspacesResponse; +import software.amazon.awssdk.services.amp.model.ResourceNotFoundException; +import software.amazon.awssdk.services.amp.model.WorkspaceStatusCode; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("Managed Prometheus (AMP)") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class AmpTest { + + private static AmpClient amp; + private static String alias; + private static String workspaceId; + private static String workspaceArn; + + @BeforeAll + static void setup() { + amp = TestFixtures.ampClient(); + alias = "sdk-test-workspace-" + System.currentTimeMillis(); + } + + @AfterAll + static void cleanup() { + if (amp != null) { + if (workspaceId != null) { + try { + amp.deleteWorkspace(r -> r.workspaceId(workspaceId)); + } catch (Exception ignored) {} + } + amp.close(); + } + } + + @Test + @Order(1) + void createWorkspace() { + CreateWorkspaceResponse response = amp.createWorkspace(r -> r + .alias(alias) + .tags(Map.of("team", "devops"))); + + workspaceId = response.workspaceId(); + workspaceArn = response.arn(); + + assertThat(workspaceId).startsWith("ws-"); + assertThat(workspaceArn).contains(":aps:").contains(":workspace/" + workspaceId); + assertThat(response.status().statusCode()).isEqualTo(WorkspaceStatusCode.ACTIVE); + assertThat(response.tags()).containsEntry("team", "devops"); + } + + @Test + @Order(2) + void describeWorkspace() { + DescribeWorkspaceResponse response = amp.describeWorkspace(r -> r.workspaceId(workspaceId)); + + assertThat(response.workspace().workspaceId()).isEqualTo(workspaceId); + assertThat(response.workspace().alias()).isEqualTo(alias); + assertThat(response.workspace().arn()).isEqualTo(workspaceArn); + assertThat(response.workspace().status().statusCode()).isEqualTo(WorkspaceStatusCode.ACTIVE); + assertThat(response.workspace().prometheusEndpoint()).contains("/workspaces/" + workspaceId); + // Proves the wire timestamp is restJson1 epoch-seconds: an ISO string here fails SDK + // deserialization before any assertion runs. + assertThat(response.workspace().createdAt()).isNotNull(); + assertThat(response.workspace().tags()).containsEntry("team", "devops"); + } + + @Test + @Order(3) + void listWorkspacesByAliasPrefix() { + ListWorkspacesResponse response = amp.listWorkspaces(r -> r.alias("sdk-test-workspace-")); + + assertThat(response.workspaces()) + .anySatisfy(w -> assertThat(w.workspaceId()).isEqualTo(workspaceId)); + } + + @Test + @Order(4) + void updateWorkspaceAlias() { + amp.updateWorkspaceAlias(r -> r.workspaceId(workspaceId).alias(alias + "-renamed")); + + assertThat(amp.describeWorkspace(r -> r.workspaceId(workspaceId)).workspace().alias()) + .isEqualTo(alias + "-renamed"); + } + + @Test + @Order(5) + void tagResourceRoundTrip() { + amp.tagResource(r -> r.resourceArn(workspaceArn).tags(Map.of("env", "test"))); + + assertThat(amp.listTagsForResource(r -> r.resourceArn(workspaceArn)).tags()) + .containsEntry("team", "devops") + .containsEntry("env", "test"); + + amp.untagResource(r -> r.resourceArn(workspaceArn).tagKeys("env")); + + assertThat(amp.listTagsForResource(r -> r.resourceArn(workspaceArn)).tags()) + .containsEntry("team", "devops") + .doesNotContainKey("env"); + } + + @Test + @Order(6) + void deleteWorkspaceThenDescribeThrowsResourceNotFound() { + amp.deleteWorkspace(r -> r.workspaceId(workspaceId)); + + // The terraform/pulumi provider's delete waiter matches this typed exception + // (errs.IsA[*types.ResourceNotFoundException]) to treat the workspace as gone. + assertThatThrownBy(() -> amp.describeWorkspace(r -> r.workspaceId(workspaceId))) + .isInstanceOf(ResourceNotFoundException.class); + + workspaceId = null; + } +} diff --git a/docs/services/index.md b/docs/services/index.md index d5639ea608..9cd19dbe82 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -90,6 +90,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Service Quotas](servicequotas.md) | `POST /` + `X-Amz-Target: ServiceQuotasV20190624.*` | JSON 1.1 | 5 | | [AWS RAM](ram.md) | `POST /{operationname}` (lowercase), `DELETE /deleteresourceshare` | REST JSON | 12 | | [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 | | [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 | | [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*` | REST XML | 50 | diff --git a/docs/services/managed-prometheus.md b/docs/services/managed-prometheus.md new file mode 100644 index 0000000000..2475e1ee36 --- /dev/null +++ b/docs/services/managed-prometheus.md @@ -0,0 +1,37 @@ +# Amazon Managed Service for Prometheus (AMP) + +**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. + +## Emulation notes + +- A workspace is **ACTIVE from birth**. Real AMP answers the create `202` with status + `CREATING`; Floci provisions nothing, so `DescribeWorkspace` reports `ACTIVE` immediately and + the Terraform provider's create waiter (`CREATING` → `ACTIVE`) completes on its first poll. +- `DeleteWorkspace` removes the workspace immediately; a subsequent `DescribeWorkspace` returns + `ResourceNotFoundException` (404), which the provider's delete waiter treats as gone. +- `prometheusEndpoint` is reported in the real AWS shape + (`https://aps-workspaces..amazonaws.com/workspaces//`). It is not a live + ingestion/query endpoint. +- The `alias` parameter of `ListWorkspaces` is a **prefix** filter, matching the provider's + `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. + +## Supported Operations + +| Operation | Method and path | Description | +|---|---|---| +| `CreateWorkspace` | `POST /workspaces` | Creates a workspace (`202`); returns `workspaceId`, `arn`, `status`, `tags` | +| `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`) | diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 3b5f41e28f..ce2cd62255 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -289,10 +289,19 @@ public interface EmulatorConfig { ControlTowerStorageConfig controltower(); + ApsStorageConfig aps(); + LakeFormationStorageConfig lakeformation(); EfsStorageConfig efs(); } + interface ApsStorageConfig { + Optional mode(); + + @WithDefault("5000") + long flushIntervalMs(); + } + interface SsmStorageConfig { Optional mode(); @@ -679,6 +688,9 @@ public interface EmulatorConfig { ServiceQuotasServiceConfig servicequotas(); RamServiceConfig ram(); ControlTowerServiceConfig controltower(); + + ApsServiceConfig aps(); + LakeFormationServiceConfig lakeformation(); EfsServiceConfig efs(); } @@ -688,6 +700,11 @@ public interface EmulatorConfig { boolean enabled(); } + interface ApsServiceConfig { + @WithDefault("true") + boolean enabled(); + } + interface IotServiceConfig { @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.java index 2b29ff1b77..e3d9953f71 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 @@ -31,6 +31,7 @@ import io.github.hectorvent.floci.services.ses.SesController; import io.github.hectorvent.floci.services.appsync.AppSyncController; import io.github.hectorvent.floci.services.rdsdata.RdsDataController; import io.github.hectorvent.floci.services.guardduty.GuardDutyController; +import io.github.hectorvent.floci.services.aps.ApsController; import io.github.hectorvent.floci.services.controltower.ControlTowerController; import io.github.hectorvent.floci.services.rum.RumController; import io.github.hectorvent.floci.services.s3vectors.S3VectorsController; @@ -536,6 +537,11 @@ public class ResolvedServiceCatalog { config.storage().services().controltower().flushIntervalMs(), null, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON), Set.of(), Set.of("controltower"), Set.of(), Set.of(ControlTowerController.class)), + descriptor("aps", "aps", config.services().aps().enabled(), true, + "aps", storageMode(config.storage().services().aps().mode(), config.storage().mode()), + config.storage().services().aps().flushIntervalMs(), null, ServiceProtocol.REST_JSON, + protocols(ServiceProtocol.REST_JSON), + Set.of(), Set.of("aps"), Set.of(), Set.of(ApsController.class)), descriptor("lakeformation", "lakeformation", config.services().lakeformation().enabled(), true, "lakeformation", storageMode(config.storage().services().lakeformation().mode(), config.storage().mode()), 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.java new file mode 100644 index 0000000000..90aff865fb --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/aps/ApsController.java @@ -0,0 +1,179 @@ +package io.github.hectorvent.floci.services.aps; + +import io.github.hectorvent.floci.core.common.AwsException; +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 com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +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.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.util.HashMap; +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 + * {@link ApsService}'s TagHandler implementation. + * + *

The literal {@code /workspaces} path segment takes JAX-RS precedence over S3's + * {@code /{bucket}} template route, so these routes need no extra routing wiring (see + * {@link io.github.hectorvent.floci.services.controltower.ControlTowerController}). + */ +@Path("/") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class ApsController { + + private final ApsService service; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public ApsController(ApsService service, RegionResolver regionResolver, ObjectMapper objectMapper) { + this.service = service; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @POST + @Path("/workspaces") + public Response createWorkspace(@Context HttpHeaders headers, Map request) { + Map body = request != null ? request : Map.of(); + String alias = asString(body.get("alias"), "alias"); + String kmsKeyArn = asString(body.get("kmsKeyArn"), "kmsKeyArn"); + Map tags = asStringMap(body.get("tags"), "tags"); + // clientToken is accepted and ignored: creates are not deduplicated. + + PrometheusWorkspace workspace = + service.createWorkspace(regionResolver.resolveRegion(headers), alias, tags, kmsKeyArn); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("workspaceId", workspace.getWorkspaceId()); + response.put("arn", workspace.getArn()); + response.set("status", statusNode(workspace)); + response.set("tags", objectMapper.valueToTree(workspace.getTags())); + if (workspace.getKmsKeyArn() != null) { + response.put("kmsKeyArn", workspace.getKmsKeyArn()); + } + return Response.status(202).entity(response).build(); + } + + @GET + @Path("/workspaces") + public Response listWorkspaces(@Context HttpHeaders headers, + @QueryParam("alias") String alias, + @QueryParam("maxResults") String maxResultsParam, + @QueryParam("nextToken") String nextToken) { + PaginatedResult result = service.listWorkspaces( + regionResolver.resolveRegion(headers), alias, + Pagination.parseMaxResults(maxResultsParam, "ValidationException"), nextToken); + + Map response = new HashMap<>(); + response.put("workspaces", result.items().stream().map(this::toWorkspaceSummary).toList()); + if (result.nextToken() != null) { + response.put("nextToken", result.nextToken()); + } + return Response.ok(response).build(); + } + + @GET + @Path("/workspaces/{workspaceId}") + public Response describeWorkspace(@Context HttpHeaders headers, + @PathParam("workspaceId") String workspaceId) { + PrometheusWorkspace workspace = + service.describeWorkspace(regionResolver.resolveRegion(headers), workspaceId); + ObjectNode response = objectMapper.createObjectNode(); + response.set("workspace", toWorkspaceDescription(workspace)); + return Response.ok(response).build(); + } + + @DELETE + @Path("/workspaces/{workspaceId}") + public Response deleteWorkspace(@Context HttpHeaders headers, + @PathParam("workspaceId") String workspaceId) { + service.deleteWorkspace(regionResolver.resolveRegion(headers), workspaceId); + // The model documents "an HTTP 202 response with an empty HTTP body". + return Response.status(202).build(); + } + + @POST + @Path("/workspaces/{workspaceId}/alias") + public Response updateWorkspaceAlias(@Context HttpHeaders headers, + @PathParam("workspaceId") String workspaceId, + Map request) { + Map body = request != null ? request : Map.of(); + String alias = asString(body.get("alias"), "alias"); + service.updateWorkspaceAlias(regionResolver.resolveRegion(headers), workspaceId, alias); + return Response.status(204).build(); + } + + private ObjectNode toWorkspaceDescription(PrometheusWorkspace workspace) { + ObjectNode node = toWorkspaceSummary(workspace); + node.put("prometheusEndpoint", workspace.getPrometheusEndpoint()); + return node; + } + + // AWS's WorkspaceSummary shape (ListWorkspaces) carries every WorkspaceDescription member + // except prometheusEndpoint. + private ObjectNode toWorkspaceSummary(PrometheusWorkspace workspace) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("workspaceId", workspace.getWorkspaceId()); + if (workspace.getAlias() != null) { + node.put("alias", workspace.getAlias()); + } + node.put("arn", workspace.getArn()); + node.set("status", statusNode(workspace)); + // Smithy restJson1 timestamps with no timestampFormat trait are epoch-seconds; an ISO + // string here fails deserialization inside the AWS SDKs. + node.put("createdAt", workspace.getCreatedAt().toEpochMilli() / 1000.0); + node.set("tags", objectMapper.valueToTree(workspace.getTags())); + if (workspace.getKmsKeyArn() != null) { + node.put("kmsKeyArn", workspace.getKmsKeyArn()); + } + return node; + } + + private ObjectNode statusNode(PrometheusWorkspace workspace) { + ObjectNode status = objectMapper.createObjectNode(); + status.put("statusCode", workspace.getStatus()); + return status; + } + + private String asString(Object value, String fieldName) { + if (value == null) { + return null; + } + if (!(value instanceof String s)) { + throw new AwsException("ValidationException", fieldName + " must be a string.", 400); + } + return s; + } + + private Map asStringMap(Object value, String fieldName) { + if (value == null) { + return null; + } + if (!(value instanceof Map map) + || map.entrySet().stream().anyMatch(e -> !(e.getKey() instanceof String) || !(e.getValue() instanceof String))) { + throw new AwsException("ValidationException", fieldName + " must be a map of strings.", 400); + } + Map result = new HashMap<>(); + map.forEach((k, v) -> result.put((String) k, (String) v)); + return result; + } +} 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.java new file mode 100644 index 0000000000..21a29f01d3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/aps/ApsService.java @@ -0,0 +1,173 @@ +package io.github.hectorvent.floci.services.aps; + +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +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.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 com.fasterxml.jackson.core.type.TypeReference; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +@ApplicationScoped +public class ApsService implements TagHandler { + + private static final Logger LOG = Logger.getLogger(ApsService.class); + // 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 final StorageBackend storage; + private final RegionResolver regionResolver; + + @Inject + public ApsService(StorageFactory storageFactory, RegionResolver regionResolver) { + this.storage = storageFactory.create("aps", "aps-workspaces.json", + new TypeReference>() {}); + this.regionResolver = regionResolver; + } + + public PrometheusWorkspace createWorkspace(String region, String alias, Map tags, + String kmsKeyArn) { + String workspaceId = "ws-" + UUID.randomUUID(); + String arn = regionResolver.buildArn("aps", region, "workspace/" + workspaceId); + + PrometheusWorkspace workspace = new PrometheusWorkspace(); + workspace.setWorkspaceId(workspaceId); + workspace.setAlias(stripAlias(alias)); + workspace.setArn(arn); + // Real AMP answers the create 202 with status CREATING; the emulator provisions nothing, + // so the workspace is ACTIVE from birth and the terraform/pulumi provider's create waiter + // (Pending CREATING, Target ACTIVE) completes on its first DescribeWorkspace poll. + workspace.setStatus("ACTIVE"); + workspace.setPrometheusEndpoint( + "https://aps-workspaces." + region + ".amazonaws.com/workspaces/" + workspaceId + "/"); + workspace.setCreatedAt(Instant.now()); + workspace.setKmsKeyArn(kmsKeyArn); + if (tags != null) { + workspace.getTags().putAll(tags); + } + + storage.put(key(region, workspaceId), workspace); + LOG.infov("Created AMP workspace: {0} in {1}", workspaceId, region); + return workspace; + } + + public PrometheusWorkspace describeWorkspace(String region, String workspaceId) { + return storage.get(key(region, workspaceId)) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Workspace not found: " + workspaceId, 404)); + } + + // The alias parameter is a prefix filter, not an exact match: the terraform provider's + // aws_prometheus_workspaces data source exposes it as alias_prefix. + public PaginatedResult listWorkspaces(String region, String aliasPrefix, + Integer maxResults, String nextToken) { + String prefix = stripAlias(aliasPrefix); + String regionPrefix = keyPrefix(region); + List all = storage.scan(k -> k.startsWith(regionPrefix)).stream() + .filter(w -> prefix == null || prefix.isEmpty() + || (w.getAlias() != null && w.getAlias().startsWith(prefix))) + .toList(); + return Pagination.paginate(all, PrometheusWorkspace::getWorkspaceId, maxResults, nextToken, + DEFAULT_PAGE, MAX_PAGE, "ValidationException"); + } + + public void deleteWorkspace(String region, String workspaceId) { + describeWorkspace(region, workspaceId); + storage.delete(key(region, workspaceId)); + LOG.infov("Deleted AMP workspace: {0} in {1}", workspaceId, region); + } + + public void updateWorkspaceAlias(String region, String workspaceId, String alias) { + PrometheusWorkspace workspace = describeWorkspace(region, workspaceId); + workspace.setAlias(stripAlias(alias)); + storage.put(key(region, workspaceId), workspace); + } + + // ── TagHandler: the shared /tags/{resourceArn} dispatcher routes aps ARNs here ── + + @Override + public String serviceKey() { + return "aps"; + } + + // AMP defines TagResource/UntagResource with a 200 response, not the dispatcher's default 204. + @Override + public int tagResourceSuccessStatus() { + return 200; + } + + @Override + public int untagResourceSuccessStatus() { + return 200; + } + + @Override + public Map listTags(String region, String arn) { + return Map.copyOf(workspaceByArn(region, arn).getTags()); + } + + @Override + public void tagResource(String region, String arn, Map tags) { + // Per AMP's TagResource: keys must not begin with the reserved "aws:" prefix + // (case-insensitive, matching the sibling checks in FisService and BatchService). + for (String tagKey : tags.keySet()) { + if (tagKey.regionMatches(true, 0, "aws:", 0, 4)) { + throw new AwsException("ValidationException", + "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); + } + + @Override + public void untagResource(String region, String arn, List tagKeys) { + PrometheusWorkspace workspace = workspaceByArn(region, arn); + tagKeys.forEach(workspace.getTags()::remove); + storage.put(key(region, workspace.getWorkspaceId()), workspace); + } + + private PrometheusWorkspace workspaceByArn(String region, String arn) { + // arn:aws:aps:::workspace/ + String resource; + try { + resource = AwsArnUtils.parse(arn).resource(); + } catch (IllegalArgumentException e) { + throw new AwsException("ValidationException", "Invalid resource ARN: " + arn, 400); + } + String prefix = "workspace/"; + if (!resource.startsWith(prefix) || resource.length() == prefix.length()) { + throw new AwsException("ValidationException", + "Tags are only supported on AMP workspaces: " + arn, 400); + } + return describeWorkspace(region, resource.substring(prefix.length())); + } + + // AMP is regional ("You can have one or more workspaces in each Region in your account"), so + // the store is partitioned by request region, like CloudWatchLogsService's groupKey. + private static String key(String region, String workspaceId) { + return keyPrefix(region) + workspaceId; + } + + private static String keyPrefix(String region) { + return region + "::"; + } + + // 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/PrometheusWorkspace.java b/src/main/java/io/github/hectorvent/floci/services/aps/model/PrometheusWorkspace.java new file mode 100644 index 0000000000..4af3b6941c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/aps/model/PrometheusWorkspace.java @@ -0,0 +1,52 @@ +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 PrometheusWorkspace { + + private String workspaceId; + private String alias; + private String arn; + // WorkspaceStatusCode: the emulator only ever stores ACTIVE (creation is instantaneous). + private String status; + private String prometheusEndpoint; + private Instant createdAt; + private String kmsKeyArn; + private Map tags = new ConcurrentHashMap<>(); + + public PrometheusWorkspace() { + } + + public String getWorkspaceId() { return workspaceId; } + public void setWorkspaceId(String workspaceId) { this.workspaceId = workspaceId; } + + public String getAlias() { return alias; } + public void setAlias(String alias) { this.alias = alias; } + + 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 getPrometheusEndpoint() { return prometheusEndpoint; } + public void setPrometheusEndpoint(String prometheusEndpoint) { this.prometheusEndpoint = prometheusEndpoint; } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + + public String getKmsKeyArn() { return kmsKeyArn; } + public void setKmsKeyArn(String kmsKeyArn) { this.kmsKeyArn = kmsKeyArn; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { + this.tags = tags != null ? new ConcurrentHashMap<>(tags) : new ConcurrentHashMap<>(); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index d52d4b699b..a987947772 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -557,6 +557,8 @@ floci: enabled: true route53resolver: enabled: true + aps: + enabled: true lakeformation: enabled: true tagging: 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.java new file mode 100644 index 0000000000..c7ee7c7f2b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/aps/ApsControllerIntegrationTest.java @@ -0,0 +1,247 @@ +package io.github.hectorvent.floci.services.aps; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.emptyString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; + +@QuarkusTest +class ApsControllerIntegrationTest { + + // Region comes from the SigV4 credential scope; requests without the header use the default us-east-1. + private static String auth(String region) { + return "AWS4-HMAC-SHA256 Credential=AKID/20260827/" + region + + "/aps/aws4_request, SignedHeaders=host, Signature=abc"; + } + + private String createWorkspace(String alias) { + return given() + .contentType("application/json") + .body(""" + {"alias": "%s", "tags": {"team": "devops"}, "clientToken": "token-123"} + """.formatted(alias)) + .when() + .post("/workspaces") + .then() + .statusCode(202) + .body("workspaceId", startsWith("ws-")) + .body("arn", containsString(":workspace/ws-")) + .body("status.statusCode", equalTo("ACTIVE")) + .body("tags.team", equalTo("devops")) + .extract().path("workspaceId"); + } + + @Test + void workspaceLifecycleRoundTrip() { + String workspaceId = createWorkspace("lifecycle-test"); + + given() + .when() + .get("/workspaces/{workspaceId}", workspaceId) + .then() + .statusCode(200) + .body("workspace.workspaceId", equalTo(workspaceId)) + .body("workspace.alias", equalTo("lifecycle-test")) + .body("workspace.status.statusCode", equalTo("ACTIVE")) + .body("workspace.prometheusEndpoint", + equalTo("https://aps-workspaces.us-east-1.amazonaws.com/workspaces/" + workspaceId + "/")) + // Epoch-seconds number, not an ISO string: restJson1 timestamps with no + // timestampFormat trait fail SDK deserialization as strings. + .body("workspace.createdAt", notNullValue()) + .body("workspace.tags.team", equalTo("devops")); + + given() + .when() + .get("/workspaces") + .then() + .statusCode(200) + .body("workspaces.workspaceId", hasItem(workspaceId)) + // The WorkspaceSummary shape never carries prometheusEndpoint. + .body("workspaces.find { it.workspaceId == '" + workspaceId + "' }.prometheusEndpoint", + equalTo(null)); + + // The model documents "an HTTP 202 response with an empty HTTP body" for the delete. + given() + .when() + .delete("/workspaces/{workspaceId}", workspaceId) + .then() + .statusCode(202) + .body(is(emptyString())); + + // The terraform/pulumi provider's delete waiter matches the typed error via the + // X-Amzn-Errortype header; assert the wire contract, not just the status. + given() + .when() + .get("/workspaces/{workspaceId}", workspaceId) + .then() + .statusCode(404) + .header("X-Amzn-Errortype", equalTo("ResourceNotFoundException")); + } + + @Test + void listWorkspacesFiltersByAliasPrefix() { + String matching = createWorkspace("prefix-match-a"); + createWorkspace("other-alias"); + + given() + .when() + .get("/workspaces?alias=prefix-match") + .then() + .statusCode(200) + .body("workspaces.workspaceId", hasItem(matching)) + .body("workspaces.alias", not(hasItem("other-alias"))); + } + + @Test + void listWorkspacesRejectsZeroMaxResults() { + given() + .when() + .get("/workspaces?maxResults=0") + .then() + .statusCode(400) + .header("X-Amzn-Errortype", equalTo("ValidationException")); + } + + @Test + void updateWorkspaceAliasReturns204AndPersists() { + String workspaceId = createWorkspace("alias-before"); + + given() + .contentType("application/json") + .body("{\"alias\": \"alias-after\"}") + .when() + .post("/workspaces/{workspaceId}/alias", workspaceId) + .then() + .statusCode(204); + + given() + .when() + .get("/workspaces/{workspaceId}", workspaceId) + .then() + .statusCode(200) + .body("workspace.alias", equalTo("alias-after")); + } + + @Test + void workspacesAreIsolatedBetweenRegions() { + String workspaceId = createWorkspace("region-isolation-test"); + + // The same workspace id does not exist when the request is signed for another region. + given() + .header("Authorization", auth("eu-west-1")) + .when() + .get("/workspaces/{workspaceId}", workspaceId) + .then() + .statusCode(404) + .header("X-Amzn-Errortype", equalTo("ResourceNotFoundException")); + + given() + .header("Authorization", auth("eu-west-1")) + .when() + .get("/workspaces") + .then() + .statusCode(200) + .body("workspaces.workspaceId", not(hasItem(workspaceId))); + + given() + .header("Authorization", auth("eu-west-1")) + .when() + .delete("/workspaces/{workspaceId}", workspaceId) + .then() + .statusCode(404); + + // Still present in its own region after the cross-region delete attempt. + given() + .when() + .get("/workspaces/{workspaceId}", workspaceId) + .then() + .statusCode(200); + } + + @Test + void deleteWorkspaceUnknownIdReturns404() { + given() + .when() + .delete("/workspaces/{workspaceId}", "ws-missing") + .then() + .statusCode(404) + .header("X-Amzn-Errortype", equalTo("ResourceNotFoundException")); + } + + @Test + void tagsRoundTripThroughSharedTagsDispatcher() { + String workspaceId = createWorkspace("tags-test"); + String arn = given() + .when().get("/workspaces/{workspaceId}", workspaceId) + .then().statusCode(200) + .extract().path("workspace.arn"); + + given() + .when() + .get("/tags/{arn}", arn) + .then() + .statusCode(200) + .body("tags.team", equalTo("devops")); + + // AMP defines TagResource/UntagResource with 200 responses, not the dispatcher's + // default 204. + 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")); + + given() + .when() + .delete("/tags/{arn}?tagKeys=team", arn) + .then() + .statusCode(200); + + given() + .when() + .get("/tags/{arn}", arn) + .then() + .statusCode(200) + .body("tags.env", equalTo("test")) + .body("tags", not(org.hamcrest.Matchers.hasKey("team"))); + } + + @Test + void tagResourceRejectsReservedAwsKeyPrefix() { + String workspaceId = createWorkspace("aws-prefix-test"); + String arn = given() + .when().get("/workspaces/{workspaceId}", workspaceId) + .then().statusCode(200) + .extract().path("workspace.arn"); + + // The shared /tags route resolves the error-header protocol from the SigV4 credential + // scope, so this request carries one the way a real SDK call would. + given() + .header("Authorization", auth("us-east-1")) + .contentType("application/json") + .body("{\"tags\": {\"aws:cloudformation:stack\": \"x\"}}") + .when() + .post("/tags/{arn}", arn) + .then() + .statusCode(400) + .header("X-Amzn-Errortype", equalTo("ValidationException")); + } +} 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.java new file mode 100644 index 0000000000..efb16e53f7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/aps/ApsServiceTest.java @@ -0,0 +1,204 @@ +package io.github.hectorvent.floci.services.aps; + +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.StorageFactory; +import io.github.hectorvent.floci.services.aps.model.PrometheusWorkspace; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + +class ApsServiceTest { + + private static final String US_EAST_1 = "us-east-1"; + private static final String EU_WEST_1 = "eu-west-1"; + + private ApsService service; + + @BeforeEach + void setUp() { + StorageFactory storageFactory = Mockito.mock(StorageFactory.class); + when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any())) + .thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000")); + + service = new ApsService(storageFactory, new RegionResolver(US_EAST_1, "000000000000")); + } + + @Test + void createWorkspaceIsActiveWithArnAndEndpoint() { + PrometheusWorkspace workspace = + service.createWorkspace(US_EAST_1, "my-workspace", Map.of("team", "devops"), null); + + assertTrue(workspace.getWorkspaceId().startsWith("ws-")); + assertEquals("ACTIVE", workspace.getStatus()); + assertEquals("arn:aws:aps:us-east-1:000000000000:workspace/" + workspace.getWorkspaceId(), + workspace.getArn()); + assertEquals("https://aps-workspaces.us-east-1.amazonaws.com/workspaces/" + + workspace.getWorkspaceId() + "/", workspace.getPrometheusEndpoint()); + assertNotNull(workspace.getCreatedAt()); + assertEquals("devops", workspace.getTags().get("team")); + } + + @Test + void describeWorkspaceUnknownIdThrowsResourceNotFound() { + AwsException ex = assertThrows(AwsException.class, + () -> service.describeWorkspace(US_EAST_1, "ws-missing")); + assertEquals("ResourceNotFoundException", ex.getErrorCode()); + assertEquals(404, ex.getHttpStatus()); + } + + @Test + void describeWorkspaceAfterDeleteThrowsResourceNotFound() { + PrometheusWorkspace workspace = service.createWorkspace(US_EAST_1, "doomed", null, null); + service.deleteWorkspace(US_EAST_1, workspace.getWorkspaceId()); + + AwsException ex = assertThrows(AwsException.class, + () -> service.describeWorkspace(US_EAST_1, workspace.getWorkspaceId())); + assertEquals("ResourceNotFoundException", ex.getErrorCode()); + } + + @Test + void workspacesAreScopedToTheirRegion() { + PrometheusWorkspace workspace = service.createWorkspace(US_EAST_1, "regional", null, null); + + AwsException describe = assertThrows(AwsException.class, + () -> service.describeWorkspace(EU_WEST_1, workspace.getWorkspaceId())); + assertEquals("ResourceNotFoundException", describe.getErrorCode()); + + assertEquals(0, service.listWorkspaces(EU_WEST_1, null, null, null).items().size()); + assertEquals(1, service.listWorkspaces(US_EAST_1, null, null, null).items().size()); + + AwsException delete = assertThrows(AwsException.class, + () -> service.deleteWorkspace(EU_WEST_1, workspace.getWorkspaceId())); + assertEquals("ResourceNotFoundException", delete.getErrorCode()); + // The cross-region delete must not have touched the real workspace. + assertEquals(workspace.getWorkspaceId(), + service.describeWorkspace(US_EAST_1, workspace.getWorkspaceId()).getWorkspaceId()); + } + + @Test + void listWorkspacesFiltersByAliasPrefix() { + service.createWorkspace(US_EAST_1, "prod-metrics", null, null); + service.createWorkspace(US_EAST_1, "prod-traces", null, null); + service.createWorkspace(US_EAST_1, "staging-metrics", null, null); + + assertEquals(2, service.listWorkspaces(US_EAST_1, "prod-", null, null).items().size()); + assertEquals(3, service.listWorkspaces(US_EAST_1, null, null, null).items().size()); + assertEquals(0, service.listWorkspaces(US_EAST_1, "missing", null, null).items().size()); + } + + @Test + void aliasesAreStrippedOnCreateUpdateAndListFilter() { + PrometheusWorkspace workspace = service.createWorkspace(US_EAST_1, " prod ", null, null); + assertEquals("prod", workspace.getAlias()); + + // AWS strips the filter value too, so " prod " round-trips against a "prod" alias. + assertEquals(1, service.listWorkspaces(US_EAST_1, " prod ", null, null).items().size()); + + service.updateWorkspaceAlias(US_EAST_1, workspace.getWorkspaceId(), " renamed "); + assertEquals("renamed", + service.describeWorkspace(US_EAST_1, workspace.getWorkspaceId()).getAlias()); + } + + @Test + void listWorkspacesPaginates() { + service.createWorkspace(US_EAST_1, "a", null, null); + service.createWorkspace(US_EAST_1, "b", null, null); + service.createWorkspace(US_EAST_1, "c", null, null); + + PaginatedResult firstPage = + service.listWorkspaces(US_EAST_1, null, 2, null); + assertEquals(2, firstPage.items().size()); + assertNotNull(firstPage.nextToken()); + + PaginatedResult secondPage = + service.listWorkspaces(US_EAST_1, null, 2, firstPage.nextToken()); + assertEquals(1, secondPage.items().size()); + assertNull(secondPage.nextToken()); + } + + @Test + void listWorkspacesDefaultsToPagesOf100() { + for (int i = 0; i < 101; i++) { + service.createWorkspace(US_EAST_1, "bulk-" + i, null, null); + } + + PaginatedResult page = service.listWorkspaces(US_EAST_1, null, null, null); + assertEquals(100, page.items().size()); + assertNotNull(page.nextToken()); + } + + @Test + void listWorkspacesRejectsZeroMaxResultsWithValidationException() { + AwsException ex = assertThrows(AwsException.class, + () -> service.listWorkspaces(US_EAST_1, null, 0, null)); + assertEquals("ValidationException", ex.getErrorCode()); + } + + @Test + void updateWorkspaceAliasPersists() { + PrometheusWorkspace workspace = service.createWorkspace(US_EAST_1, "old-alias", null, null); + service.updateWorkspaceAlias(US_EAST_1, workspace.getWorkspaceId(), "new-alias"); + assertEquals("new-alias", + service.describeWorkspace(US_EAST_1, workspace.getWorkspaceId()).getAlias()); + } + + @Test + void tagHandlerRoundTripsTagsByArn() { + PrometheusWorkspace workspace = + service.createWorkspace(US_EAST_1, "tagged", Map.of("env", "test"), null); + String arn = workspace.getArn(); + + assertEquals("aps", service.serviceKey()); + 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)); + } + + @Test + void tagOperationsAreScopedToTheRequestRegion() { + PrometheusWorkspace workspace = service.createWorkspace(US_EAST_1, "tagged", null, null); + + // 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()); + assertTrue(service.listTags(US_EAST_1, workspace.getArn()).isEmpty()); + } + + @Test + void tagResourceRejectsReservedAwsKeyPrefix() { + PrometheusWorkspace workspace = service.createWorkspace(US_EAST_1, "tagged", null, null); + + AwsException ex = assertThrows(AwsException.class, + () -> service.tagResource(US_EAST_1, workspace.getArn(), Map.of("aws:cloudformation:stack", "x"))); + assertEquals("ValidationException", ex.getErrorCode()); + assertEquals(400, ex.getHttpStatus()); + } + + @Test + void tagHandlerUnknownWorkspaceArnThrowsResourceNotFound() { + AwsException ex = assertThrows(AwsException.class, () -> + service.listTags(US_EAST_1, "arn:aws:aps:us-east-1:000000000000:workspace/ws-missing")); + assertEquals("ResourceNotFoundException", ex.getErrorCode()); + } + + @Test + void tagHandlerMalformedArnThrowsValidationException() { + AwsException ex = assertThrows(AwsException.class, () -> + service.listTags(US_EAST_1, "arn:aws:aps:us-east-1:000000000000:workspace")); + assertEquals("ValidationException", ex.getErrorCode()); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 7e76d25660..431b0065af 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -351,6 +351,8 @@ floci: enabled: true route53resolver: enabled: true + aps: + enabled: true lakeformation: enabled: true tagging: diff --git a/tools/docs/service_matrix.yaml b/tools/docs/service_matrix.yaml index bfe232da8a..b9120b003e 100644 --- a/tools/docs/service_matrix.yaml +++ b/tools/docs/service_matrix.yaml @@ -17,6 +17,7 @@ aliases: apigateway: api-gateway # "API Gateway v1" row title apigatewayv2: api-gateway # v2 facet, documented at api-gateway.md#v2 + aps: managed-prometheus # AMP's SigV4 signing name is "aps" kafka: msk # MSK's SigV4 signing name is "kafka" mq: amazonmq # Amazon MQ's SigV4 signing name is "mq" signin: iam # AWS Sign-In facet, at iam.md#aws-sign-in-login-credentials