diff --git a/docs/services/ram.md b/docs/services/ram.md index 4fb48c70b5..7685fa2f86 100644 --- a/docs/services/ram.md +++ b/docs/services/ram.md @@ -87,8 +87,8 @@ aws --endpoint-url http://localhost:4566 ram accept-resource-share-invitation \ missing or unmodelled value is rejected with `InvalidParameterException` rather than defaulted to `SELF`. - `GetResourceShares` applies the `name`, `resourceShareArns` and `resourceShareStatus` filters; - `tagFilters`, `permissionArn`, `permissionVersion` and pagination (`nextToken`/`maxResults`) - are accepted but ignored, every matching share is returned in one page. + `maxResults`/`nextToken` page the matching shares. `tagFilters`, `permissionArn` and + `permissionVersion` are accepted but ignored. - Operations outside the table above are not routed. RAM's paths are matched literally, so an unimplemented operation falls through to S3's `/{bucket}` route and comes back as an S3 `NoSuchBucket` XML body where the SDK expects JSON, not a modeled `UnknownOperationException`. diff --git a/pom.xml b/pom.xml index 216d9d02fe..f557a997f2 100644 --- a/pom.xml +++ b/pom.xml @@ -531,6 +531,12 @@ ${aws.sdk.version} test + + software.amazon.awssdk + ram + ${aws.sdk.version} + test + software.amazon.awssdk redshiftdata diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java b/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java index 4b4404ef01..0dcce0d5d1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ram/RamController.java @@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; 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.ServicePrincipals; import io.github.hectorvent.floci.services.iam.IamService; @@ -113,19 +114,24 @@ public class RamController { JsonNode request = readTree(body); String resourceOwner = request.hasNonNull("resourceOwner") ? request.path("resourceOwner").asText() : null; - List shares = service.getResourceShares( + PaginatedResult page = service.getResourceSharesPage( regionResolver.getAccountId(), resourceOwner, request.hasNonNull("name") ? request.path("name").asText() : null, stringList(request.path("resourceShareArns")), request.hasNonNull("resourceShareStatus") ? request.path("resourceShareStatus").asText() : null, - regionResolver.getRegion()); + regionResolver.getRegion(), + Pagination.parseMaxResults(request, "maxResults", "InvalidParameterException"), + Pagination.parseNextToken(request, "nextToken", "InvalidNextTokenException")); ObjectNode response = objectMapper.createObjectNode(); ArrayNode array = objectMapper.createArrayNode(); - shares.forEach(share -> array.add(shareNode(share))); + page.items().forEach(share -> array.add(shareNode(share))); response.set("resourceShares", array); + if (page.nextToken() != null) { + response.put("nextToken", page.nextToken()); + } return Response.ok(response).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java b/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java index 3dbaf4cbbf..f262fcd873 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsPartitions; +import io.github.hectorvent.floci.core.common.Base64Url; import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; @@ -31,6 +32,8 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.function.Function; +import java.util.function.Supplier; import java.util.regex.Pattern; /** @@ -178,6 +181,19 @@ public class RamService { return result; } + public PaginatedResult getResourceSharesPage(String callerAccountId, String resourceOwner, + String name, List resourceShareArns, + String resourceShareStatus, String region, + Integer maxResults, String nextToken) { + return paginateRamResults( + () -> getResourceShares(callerAccountId, resourceOwner, name, + resourceShareArns, resourceShareStatus, region), + ResourceShare::getResourceShareArn, maxResults, nextToken, + () -> "ram-resource-shares|" + callerAccountId + "|" + region + "|" + resourceOwner + + "|" + (name == null ? "~" : Base64Url.encode(name)) + "|" + resourceShareStatus + "|" + + resourceShareArns.stream().distinct().sorted().map(Base64Url::encode).toList()); + } + /** * @param resourceShareArns restrict to invitations for these shares, or empty for any * @param resourceShareInvitationArns restrict to these invitation ARNs, or empty for any @@ -437,41 +453,49 @@ public class RamService { if (resourceArn != null && !isValidArn(resourceArn)) { throw new AwsException("MalformedArnException", "Invalid resourceArn: " + resourceArn, 400); } + return paginateRamResults(() -> { + List associations = new ArrayList<>(); + if (associationStatus == null || "ASSOCIATED".equals(associationStatus)) { + for (ResourceShare share : sharesIn(region)) { + if (!isConsumableShare(share, callerAccountId, "SELF", resourceShareArns)) { + continue; + } + if ("RESOURCE".equals(associationType)) { + for (String entity : new LinkedHashSet<>(share.getResourceArns())) { + if (resourceArn == null || resourceArn.equals(entity)) { + associations.add(association(share, entity, "RESOURCE")); + } + } + } else if ("PRINCIPAL".equals(associationType)) { + for (String entity : new LinkedHashSet<>(share.getPrincipals())) { + if (principal == null || principal.equals(entity)) { + associations.add(association(share, entity, "PRINCIPAL")); + } + } + } + } + } + return associations; + }, + association -> association.resourceShareArn() + "\u0000" + association.associatedEntity(), + maxResults, nextToken, + () -> "ram-associations|" + callerAccountId + "|" + region + "|" + associationType + + "|" + associationStatus + "|" + resourceShareArns.stream().sorted().toList() + + "|" + resourceArn + "|" + principal); + } + + private static PaginatedResult paginateRamResults(Supplier> items, + Function cursorOf, + Integer maxResults, String nextToken, + Supplier namespace) { if (maxResults != null && (maxResults < 1 || maxResults > 500)) { throw new AwsException("InvalidParameterException", "maxResults must be between 1 and 500.", 400); } if (nextToken != null && nextToken.isEmpty()) { throw new AwsException("InvalidNextTokenException", "Invalid nextToken.", 400); } - - List associations = new ArrayList<>(); - if (associationStatus == null || "ASSOCIATED".equals(associationStatus)) { - for (ResourceShare share : sharesIn(region)) { - if (!isConsumableShare(share, callerAccountId, "SELF", resourceShareArns)) { - continue; - } - if ("RESOURCE".equals(associationType)) { - for (String entity : new LinkedHashSet<>(share.getResourceArns())) { - if (resourceArn == null || resourceArn.equals(entity)) { - associations.add(association(share, entity, "RESOURCE")); - } - } - } else if ("PRINCIPAL".equals(associationType)) { - for (String entity : new LinkedHashSet<>(share.getPrincipals())) { - if (principal == null || principal.equals(entity)) { - associations.add(association(share, entity, "PRINCIPAL")); - } - } - } - } - } - - String namespace = "ram-associations|" + callerAccountId + "|" + region + "|" + associationType - + "|" + associationStatus + "|" + resourceShareArns.stream().sorted().toList() - + "|" + resourceArn + "|" + principal; - return Pagination.paginate(associations, - association -> association.resourceShareArn() + "\u0000" + association.associatedEntity(), - maxResults != null ? maxResults : 100, nextToken, namespace, + return Pagination.paginate(items.get(), cursorOf, + maxResults != null ? maxResults : 100, nextToken, namespace.get(), ignored -> new AwsException("InvalidNextTokenException", "Invalid nextToken.", 400)); } diff --git a/src/test/java/io/github/hectorvent/floci/services/ram/RamGetResourceSharesPaginationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ram/RamGetResourceSharesPaginationIntegrationTest.java new file mode 100644 index 0000000000..74a84ab5a1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ram/RamGetResourceSharesPaginationIntegrationTest.java @@ -0,0 +1,141 @@ +package io.github.hectorvent.floci.services.ram; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ram.RamClient; +import software.amazon.awssdk.services.ram.model.GetResourceSharesRequest; +import software.amazon.awssdk.services.ram.model.GetResourceSharesResponse; +import software.amazon.awssdk.services.ram.model.ResourceOwner; + +import java.util.List; +import java.util.Set; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +@QuarkusTest +class RamGetResourceSharesPaginationIntegrationTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=777777777779/20260101/us-east-1/ram/aws4_request"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void sdkPaginatorReturnsEachMatchingShareExactlyOnce() { + String suffix = UUID.randomUUID().toString(); + try (RamClient ram = AwsTestClients.create(RamClient.builder(), "777777777779", Region.US_EAST_1)) { + String firstArn = ram.createResourceShare(request -> request.name("pagination-sdk-first-" + suffix)) + .resourceShare().resourceShareArn(); + String secondArn = ram.createResourceShare(request -> request.name("pagination-sdk-second-" + suffix)) + .resourceShare().resourceShareArn(); + try { + GetResourceSharesRequest request = GetResourceSharesRequest.builder() + .resourceOwner(ResourceOwner.SELF).resourceShareArns(firstArn, secondArn) + .maxResults(1).build(); + List pages = ram.getResourceSharesPaginator(request).stream().toList(); + assertEquals(2, pages.size()); + assertEquals(1, pages.get(0).resourceShares().size()); + assertEquals(1, pages.get(1).resourceShares().size()); + List returnedArns = pages.stream().flatMap(page -> page.resourceShares().stream()) + .map(share -> share.resourceShareArn()).toList(); + assertEquals(2, returnedArns.size()); + assertEquals(Set.of(firstArn, secondArn), Set.copyOf(returnedArns)); + } finally { + ram.deleteResourceShare(request -> request.resourceShareArn(firstArn)); + ram.deleteResourceShare(request -> request.resourceShareArn(secondArn)); + } + } + } + + @Test + void getResourceSharesPaginatesFilteredSharesWithoutReusingOtherFilterTokens() { + String firstArn = createShare("pagination-first"); + String secondArn = createShare("pagination-second"); + String arns = "\"%s\",\"%s\"".formatted(firstArn, secondArn); + + Response first = getShares("{\"resourceOwner\":\"SELF\",\"resourceShareArns\":[" + + arns + "],\"maxResults\":1}"); + assertEquals(200, first.statusCode(), first.asString()); + List firstPage = first.jsonPath().getList("resourceShares.resourceShareArn"); + assertEquals(1, firstPage.size(), first.asString()); + String nextToken = first.jsonPath().getString("nextToken"); + assertNotNull(nextToken, first.asString()); + + Response second = getShares("{\"resourceOwner\":\"SELF\",\"resourceShareArns\":[\"" + + secondArn + "\",\"" + firstArn + "\"],\"maxResults\":1,\"nextToken\":\"" + + nextToken + "\"}"); + assertEquals(200, second.statusCode(), second.asString()); + List secondPage = second.jsonPath().getList("resourceShares.resourceShareArn"); + assertEquals(1, secondPage.size(), second.asString()); + assertNotEquals(firstPage.getFirst(), secondPage.getFirst()); + assertEquals(Set.of(firstArn, secondArn), Set.of(firstPage.getFirst(), secondPage.getFirst())); + assertNull(second.jsonPath().getString("nextToken"), second.asString()); + + Response changedFilter = getShares("{\"resourceOwner\":\"SELF\",\"resourceShareArns\":[\"" + + firstArn + "\"],\"maxResults\":1,\"nextToken\":\"" + nextToken + "\"}"); + assertEquals(400, changedFilter.statusCode(), changedFilter.asString()); + assertEquals("InvalidNextTokenException", changedFilter.jsonPath().getString("__type")); + + Response otherAccount = given() + .contentType("application/json") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=777777777778/20260101/us-east-1/ram/aws4_request") + .body("{\"resourceOwner\":\"SELF\",\"resourceShareArns\":[" + arns + + "],\"maxResults\":1,\"nextToken\":\"" + nextToken + "\"}") + .post("/getresourceshares"); + assertEquals(400, otherAccount.statusCode(), otherAccount.asString()); + assertEquals("InvalidNextTokenException", otherAccount.jsonPath().getString("__type")); + } + + @Test + void getResourceSharesRejectsInvalidPageSizeAndToken() { + for (String maxResults : List.of("0", "501", "1.5", "\"1\"")) { + Response response = getShares("{\"resourceOwner\":\"SELF\",\"maxResults\":" + + maxResults + "}"); + assertEquals(400, response.statusCode(), response.asString()); + assertEquals("InvalidParameterException", response.jsonPath().getString("__type")); + } + + Response invalidToken = getShares("{\"resourceOwner\":\"SELF\",\"nextToken\":\"bad-token\"}"); + assertEquals(400, invalidToken.statusCode(), invalidToken.asString()); + assertEquals("InvalidNextTokenException", invalidToken.jsonPath().getString("__type")); + + Response emptyToken = getShares("{\"resourceOwner\":\"SELF\",\"nextToken\":\"\"}"); + assertEquals(400, emptyToken.statusCode(), emptyToken.asString()); + assertEquals("InvalidNextTokenException", emptyToken.jsonPath().getString("__type")); + + Response numericToken = getShares("{\"resourceOwner\":\"SELF\",\"nextToken\":1}"); + assertEquals(400, numericToken.statusCode(), numericToken.asString()); + assertEquals("InvalidNextTokenException", numericToken.jsonPath().getString("__type")); + } + + private static String createShare(String name) { + Response response = given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body("{\"name\":\"" + name + "\"}") + .post("/createresourceshare"); + assertEquals(200, response.statusCode(), response.asString()); + return response.jsonPath().getString("resourceShare.resourceShareArn"); + } + + private static Response getShares(String body) { + return given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(body) + .post("/getresourceshares"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java index efc7cc15b3..b16ee3f88a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java @@ -150,6 +150,27 @@ class RamServiceTest { assertEquals("InvalidNextTokenException", malformed.getErrorCode()); } + @Test + void getResourceSharesPageDoesNotConfuseMissingNameWithLiteralNull() { + ResourceShare first = service.createResourceShare("first", List.of(), List.of(), + false, "us-east-1", OWNER); + ResourceShare second = service.createResourceShare("second", List.of(), List.of(), + false, "us-east-1", OWNER); + List arns = List.of(first.getResourceShareArn(), second.getResourceShareArn()); + PaginatedResult page = service.getResourceSharesPage( + OWNER, "SELF", null, arns, null, "us-east-1", 1, null); + assertNotNull(page.nextToken()); + + AwsException invalid = assertThrows(AwsException.class, () -> service.getResourceSharesPage( + OWNER, "SELF", "null", arns, null, "us-east-1", 1, page.nextToken())); + assertEquals("InvalidNextTokenException", invalid.getErrorCode()); + + AwsException wrongOperation = assertThrows(AwsException.class, () -> associations( + OWNER, "us-east-1", "RESOURCE", null, List.of(first.getResourceShareArn()), + null, null, 1, page.nextToken())); + assertEquals("InvalidNextTokenException", wrongOperation.getErrorCode()); + } + @Test void getResourceShareAssociationsRejectsInvalidInput() { assertInvalidParameter(() -> associations(OWNER, "us-east-1", null, null, @@ -162,6 +183,9 @@ class RamServiceTest { List.of(), null, null, 0, null)); assertInvalidParameter(() -> associations(OWNER, "us-east-1", "RESOURCE", null, List.of(), null, null, 501, null)); + AwsException emptyToken = assertThrows(AwsException.class, () -> associations( + OWNER, "us-east-1", "RESOURCE", null, List.of(), null, null, null, "")); + assertEquals("InvalidNextTokenException", emptyToken.getErrorCode()); AwsException malformedArn = assertThrows(AwsException.class, () -> associations( OWNER, "us-east-1", "RESOURCE", null, List.of("not-an-arn"), null, null, null, null));