feat(aps): add Amazon Managed Service for Prometheus workspaces (#2604)

* feat(aps): add Amazon Managed Service for Prometheus workspaces

Implements the AMP workspace lifecycle (CreateWorkspace,
DescribeWorkspace, ListWorkspaces, UpdateWorkspaceAlias,
DeleteWorkspace) plus tagging through the shared /tags/{resourceArn}
dispatcher via a TagHandler with service key aps. Previously the aps
service did not exist, so aws_prometheus_workspace could not be created
through Terraform or Pulumi at all.

Workspaces are ACTIVE from birth so the provider's create waiter
(CREATING to ACTIVE) completes on its first DescribeWorkspace poll, and
a deleted workspace answers DescribeWorkspace with the typed
ResourceNotFoundException its delete waiter matches. createdAt is
serialized as restJson1 epoch-seconds; the ListWorkspaces alias
parameter is a prefix filter, matching the provider's alias_prefix.

clientToken is accepted and ignored, kmsKeyArn is stored and echoed,
and no alertmanager/rulegroups/scraper/logging operations are included.

* refactor(aps): build ARNs via RegionResolver and parse tag ARNs with AwsArnUtils

Replaces the inlined AwsArnUtils.Arn.of + config.defaultRegion pair with
regionResolver.getRegion()/buildArn so a request signed for another
region gets an ARN and endpoint in that region, and drops the
EmulatorConfig dependency that existed only for that getter. The tag
dispatcher path now parses ARNs with AwsArnUtils.parse plus an explicit
workspace/ prefix check (the SchedulerTagHandler idiom), so a
non-workspace aps ARN fails with ValidationException instead of a
misleading workspace ResourceNotFoundException. Also makes the delete
and alias mutators void (their returns were unused) and removes a dead
DELETING status mutation.

* docs(aps): map the aps service key to managed-prometheus.md in the service matrix

The docs-check gate matches ResolvedServiceCatalog external keys against
docs/services/index.md rows by filename; aps is documented at
managed-prometheus.md, so it needs the same alias treatment as
kafka -> msk.

* fix(aps): partition workspaces by request region and align minor wire details

Review follow-ups from #2604:

- Key the workspace store by region (region::workspaceId, like
  CloudWatchLogsService's groupKey), and thread the SigV4-resolved request
  region through every lifecycle and TagHandler operation, so workspaces
  created in one region are invisible to describe/list/delete/tag calls
  served in another. Covered by unit and HTTP region-isolation tests.
- Default ListWorkspaces to pages of 100 (AWS's documented default) while
  keeping the 1000 ceiling, via Pagination's seven-argument overload.
- Strip leading/trailing blanks from aliases at create, alias update, and
  the list prefix filter, per the documented normalisation.
- Return DeleteWorkspace's 202 with an empty body instead of {}.
- Reject tag keys beginning with the reserved aws: prefix in TagResource
  with a ValidationException.

* refactor(aps): align the reserved tag-key check with sibling services

- Match the aws: prefix case-insensitively as a plain loop, the same idiom
  as FisService and BatchService, instead of a case-sensitive stream chain.
- Derive key() from keyPrefix() so the :: separator lives in one place, and
  hoist the region prefix out of the scan predicate.
- Replace the two near-identical SigV4 Authorization literals in the
  integration test with an auth(region) helper.
This commit is contained in:
Matan Baruch authored and GitHub committed 2026-08-28 10:05:42 -04:00
1 parent 29325006bb
commit 277809fb41
15 files changed
+1061

No files matched your search

@@ -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"));
}
}
@@ -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<PrometheusWorkspace> firstPage =
service.listWorkspaces(US_EAST_1, null, 2, null);
assertEquals(2, firstPage.items().size());
assertNotNull(firstPage.nextToken());
PaginatedResult<PrometheusWorkspace> 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<PrometheusWorkspace> 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());
}
}