Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ram): add ListResourceSharePermissions (#5073)
Matheus Oliveira665603e8f47d
diff --git a/docs/services/index.md b/docs/services/index.mdindex 65b9c7e75c..50b095e2d9 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -113,7 +113,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [AWS Service Catalog](service-catalog.md) | `POST /` + `X-Amz-Target: AWS242ServiceCatalogService.*` | JSON 1.1 | 89 || [Service Quotas](servicequotas.md) | `POST /` + `X-Amz-Target: ServiceQuotasV20190624.*` | JSON 1.1 | 6 || [AWS Budgets](budgets.md) | `POST /` + `X-Amz-Target: AWSBudgetServiceGateway.*` | JSON 1.1 | 26 |-| [AWS RAM](ram.md) | `POST /{operationname}` (lowercase), `DELETE /deleteresourceshare` | REST JSON | 14 |+| [AWS RAM](ram.md) | `POST /{operationname}` (lowercase), `DELETE /deleteresourceshare` | REST JSON | 15 || [Control Catalog](controlcatalog.md) | `/get-control`, `/list-controls` | REST JSON | 2 || [AWS Marketplace](marketplace.md) | Marketplace Catalog API | REST JSON | 56 || [Control Tower](controltower.md) | `/list-landingzones`, `/get-landingzone`, `/create-landingzone`, `/*-baseline*` | REST JSON | 15 |diff --git a/docs/services/ram.md b/docs/services/ram.mdindex b5c10715af..21a6c33c6d 100644--- a/docs/services/ram.md+++ b/docs/services/ram.md@@ -24,6 +24,7 @@ below for what's simplified.| `AssociateResourceShare` | Adds resource ARNs and/or principals to an existing share (`POST /associateresourceshare`) || `DisassociateResourceShare` | Removes resource ARNs and/or principals from a share (`POST /disassociateresourceshare`) || `ListPrincipals` | Lists principals associated with visible shares (`POST /listprincipals`) |+| `ListResourceSharePermissions` | Lists the permissions associated with a share: one default AWS managed permission (`AWSRAMDefaultPermission<Type>`, `AWS_MANAGED`) per distinct resource type in the share; unknown share ARN is `UnknownResourceException` (`POST /listresourcesharepermissions`) || `TagResource` | Adds/overwrites tags on a resource share (`POST /tagresource`) || `UntagResource` | Removes tags by key from a resource share (`POST /untagresource`) || `GetResourceShareInvitations` | Lists invitations received by the caller, filterable by `resourceShareArns`/`resourceShareInvitationArns`. Empty for organization/OU-principal shares, which never get one (`POST /getresourceshareinvitations`) |@@ -100,7 +101,8 @@ aws --endpoint-url http://localhost:4566 ram accept-resource-share-invitation \- `TagResource`/`UntagResource` only support tagging by `resourceShareArn`; tagging anindividual shared resource via `resourceArn` is not modeled (RAM's `TagResource` acceptseither, but LZA only tags shares).-- Permission-related operations are not implemented: `CreatePermission`,- `AssociateResourceSharePermission`, `ListPermissions`, and the rest of the permission-version- family. Shares created here always use RAM's default managed permission implicitly: there- is no explicit permission model to associate or version.+- Only `ListResourceSharePermissions` of the permission family is implemented; `CreatePermission`,+ `AssociateResourceSharePermission`, `ListPermissions`, and the permission-version+ family are not, and `nextToken`/`maxResults` are accepted but ignored. Shares created here+ always use RAM's default managed permission implicitly: there is no explicit permission model+ to associate or version.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.javaindex e9cdc7ee73..3c92609715 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@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.organizations.OrganizationsService;import io.github.hectorvent.floci.services.ram.model.PrincipalAssociation;import io.github.hectorvent.floci.services.ram.model.ResourceShare;import io.github.hectorvent.floci.services.ram.model.ResourceShareInvitation;+import io.github.hectorvent.floci.services.ram.model.SharePermission;import io.github.hectorvent.floci.services.ram.model.SharedResource;import jakarta.inject.Inject;import jakarta.ws.rs.Consumes;@@ -220,6 +221,37 @@ public class RamController {return Response.ok(response).build();}+ @POST+ @Path("/listresourcesharepermissions")+ @Consumes(MediaType.WILDCARD)+ public Response listResourceSharePermissions(String body) {+ JsonNode request = readTree(body);+ List<SharePermission> permissions = service.listResourceSharePermissions(+ request.hasNonNull("resourceShareArn") ? request.path("resourceShareArn").asText() : null,+ regionResolver.getAccountId(), regionResolver.getRegion());++ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode array = objectMapper.createArrayNode();+ for (SharePermission permission : permissions) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("arn", permission.arn());+ node.put("version", "1");+ node.put("defaultVersion", true);+ node.put("name", permission.name());+ node.put("resourceType", permission.resourceType());+ node.put("status", "ATTACHABLE");+ node.put("creationTime", permission.creationTime().toEpochMilli() / 1000.0);+ node.put("lastUpdatedTime", permission.lastUpdatedTime().toEpochMilli() / 1000.0);+ node.put("isResourceTypeDefault", true);+ node.put("permissionType", "AWS_MANAGED");+ node.put("featureSet", "STANDARD");+ node.set("tags", objectMapper.createArrayNode());+ array.add(node);+ }+ response.set("permissions", array);+ return Response.ok(response).build();+ }+@POST@Path("/tagresource")@Consumes(MediaType.WILDCARD)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.javaindex c78a1d119c..43b1cb1c6e 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@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.ram.model.PrincipalAssociation;import io.github.hectorvent.floci.services.ram.model.ResourceShare;import io.github.hectorvent.floci.services.ram.model.ResourceShareInvitation;+import io.github.hectorvent.floci.services.ram.model.SharePermission;import io.github.hectorvent.floci.services.ram.model.SharedResource;import io.github.hectorvent.floci.services.organizations.OrganizationsService;import io.github.hectorvent.floci.services.organizations.model.Organization;@@ -53,6 +54,14 @@ public class RamService {/** The modeled ResourceShareStatus enum. */private static final List<String> SHARE_STATUSES =List.of("PENDING", "ACTIVE", "FAILED", "DELETING", "DELETED");+ /** The owner segment of an AWS managed permission ARN. */+ private static final String MANAGED_PERMISSION_OWNER = "aws";+ /**+ * Creation and update time reported for every AWS managed permission. It is fixed so the same+ * permission reports the same times in every share and does not move when a share changes.+ */+ private static final Instant MANAGED_PERMISSION_TIME = Instant.parse("2018-11-14T00:00:00Z");+ private static final String RESOURCE_SHARE_PREFIX = "resource-share/";/** An AWS account id, as opposed to an organization/OU principal ARN. */private static final Pattern ACCOUNT_ID_PRINCIPAL = Pattern.compile("\\d{12}");@@ -410,6 +419,55 @@ public class RamService {return result;}+ /**+ * Floci has no explicit permission model: every resource type in a share is governed by RAM's+ * default AWS managed permission for that type, so one summary is returned per distinct type.+ * Readable by the owner and by an account the share is visible to, like the other reads.+ */+ public List<SharePermission> listResourceSharePermissions(String resourceShareArn,+ String callerAccountId, String region) {+ if (resourceShareArn == null || resourceShareArn.isBlank()) {+ throw new AwsException("InvalidParameterException", "resourceShareArn is required.", 400);+ }+ if (!isResourceShareArn(resourceShareArn)) {+ throw new AwsException("MalformedArnException",+ "The specified Amazon Resource Name (ARN) has a format that isn't valid: "+ + resourceShareArn, 400);+ }+ ResourceShare share = sharesIn(region).stream()+ .filter(candidate -> candidate.getResourceShareArn().equals(resourceShareArn))+ .filter(candidate -> !"DELETED".equals(candidate.getStatus()))+ .filter(candidate -> candidate.getOwningAccountId().equals(callerAccountId)+ || isVisible(candidate, callerAccountId, "OTHER-ACCOUNTS"))+ .findFirst()+ .orElseThrow(() -> new AwsException("UnknownResourceException",+ "ResourceShare " + resourceShareArn + " does not exist.", 400));+ String partition = AwsArnUtils.parse(resourceShareArn).partition();+ Map<String, SharePermission> byType = new LinkedHashMap<>();+ for (String resourceArn : share.getResourceArns()) {+ String type = ramResourceType(resourceArn);+ if (type.isEmpty() || byType.containsKey(type)) {+ continue;+ }+ String name = "AWSRAMDefaultPermission" + type.substring(type.indexOf(':') + 1);+ byType.put(type, new SharePermission(+ AwsArnUtils.Arn.global(partition, "ram", MANAGED_PERMISSION_OWNER,+ "permission/" + name).toString(),+ name, type, MANAGED_PERMISSION_TIME, MANAGED_PERMISSION_TIME));+ }+ return List.copyOf(byType.values());+ }++ private static boolean isResourceShareArn(String arn) {+ if (!isValidArn(arn)) {+ return false;+ }+ AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);+ return "ram".equals(parsed.service())+ && parsed.resource().startsWith(RESOURCE_SHARE_PREFIX)+ && parsed.resource().length() > RESOURCE_SHARE_PREFIX.length();+ }+public void tagResource(String resourceShareArn, Map<String, String> newTags, String callerAccountId,String region) {ResourceShare share = requireOwnedShare(resourceShareArn, callerAccountId, region);@@ -620,8 +678,8 @@ public class RamService {}String service = parts[2];String resource = parts[5];- int slash = resource.indexOf('/');- String typeSegment = slash >= 0 ? resource.substring(0, slash) : resource;+ int separator = indexOfTypeSeparator(resource);+ String typeSegment = separator >= 0 ? resource.substring(0, separator) : resource;StringBuilder camel = new StringBuilder();for (String word : typeSegment.split("-")) {if (!word.isEmpty()) {@@ -630,4 +688,14 @@ public class RamService {}return service + ":" + camel;}++ /** ARN resources name their type before either a slash ({@code subnet/x}) or a colon ({@code cluster:x}). */+ private static int indexOfTypeSeparator(String resource) {+ int slash = resource.indexOf('/');+ int colon = resource.indexOf(':');+ if (slash < 0) {+ return colon;+ }+ return colon < 0 ? slash : Math.min(slash, colon);+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/model/SharePermission.java b/src/main/java/io/github/hectorvent/floci/services/ram/model/SharePermission.javanew file mode 100644index 0000000000..b036b5e7a9--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ram/model/SharePermission.java@@ -0,0 +1,14 @@+package io.github.hectorvent.floci.services.ram.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;++/**+ * One entry of a RAM ListResourceSharePermissions response: the AWS managed permission that+ * governs one resource type of a share.+ */+@RegisterForReflection+public record SharePermission(String arn, String name, String resourceType, Instant creationTime,+ Instant lastUpdatedTime) {+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ram/RamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ram/RamIntegrationTest.javaindex 8d21ac9448..9839af23bf 100644--- a/src/test/java/io/github/hectorvent/floci/services/ram/RamIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ram/RamIntegrationTest.java@@ -13,6 +13,7 @@ import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.containsString;import static org.hamcrest.Matchers.equalTo;import static org.hamcrest.Matchers.hasItem;+import static org.hamcrest.Matchers.hasItems;/*** Verifies the RAM restJson1 organization-sharing opt-in:@@ -383,6 +384,116 @@ class RamIntegrationTest {.body("resourceShares[0].name", equalTo("http-filtered-share"));}+ @Test+ void listResourceSharePermissionsReturnsDefaultManagedPermissionPerResourceType() {+ String shareArn =+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("""+ {+ "name": "perm-share",+ "resourceArns": [+ "arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0p1",+ "arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0p2",+ "arn:aws:ec2:us-east-1:000000000000:subnet/subnet-0p3"+ ]+ }+ """)+ .when()+ .post("/createresourceshare")+ .then()+ .statusCode(200)+ .extract().path("resourceShare.resourceShareArn");++ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"resourceShareArn\": \"" + shareArn + "\"}")+ .when()+ .post("/listresourcesharepermissions")+ .then()+ .statusCode(200)+ .body("permissions.size()", equalTo(2))+ .body("permissions.resourceType", hasItems("ec2:TransitGateway", "ec2:Subnet"))+ .body("permissions.find { it.resourceType == 'ec2:TransitGateway' }.arn",+ equalTo("arn:aws:ram::aws:permission/AWSRAMDefaultPermissionTransitGateway"))+ .body("permissions[0].permissionType", equalTo("AWS_MANAGED"))+ .body("permissions[0].status", equalTo("ATTACHABLE"))+ .body("permissions[0].defaultVersion", equalTo(true))+ .body("permissions[0].isResourceTypeDefault", equalTo(true));+ }++ @Test+ void listResourceSharePermissionsGroupsColonDelimitedResourcesByType() {+ String shareArn =+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("""+ {+ "name": "perm-share-clusters",+ "resourceArns": [+ "arn:aws:rds:us-east-1:000000000000:cluster:db1",+ "arn:aws:rds:us-east-1:000000000000:cluster:db2"+ ]+ }+ """)+ .when()+ .post("/createresourceshare")+ .then()+ .statusCode(200)+ .extract().path("resourceShare.resourceShareArn");++ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"resourceShareArn\": \"" + shareArn + "\"}")+ .when()+ .post("/listresourcesharepermissions")+ .then()+ .statusCode(200)+ .body("permissions.size()", equalTo(1))+ .body("permissions[0].resourceType", equalTo("rds:Cluster"))+ .body("permissions[0].name", equalTo("AWSRAMDefaultPermissionCluster"));+ }++ @Test+ void listResourceSharePermissionsRejectsAShareArnWithoutAnId() {+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"resourceShareArn\": \"arn:aws:ram:us-east-1:000000000000:resource-share/\"}")+ .when()+ .post("/listresourcesharepermissions")+ .then()+ .statusCode(400)+ .body("__type", equalTo("MalformedArnException"));+ }++ @Test+ void listResourceSharePermissionsRejectsUnknownAndMissingShare() {+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"resourceShareArn\": \"arn:aws:ram:us-east-1:000000000000:resource-share/none\"}")+ .when()+ .post("/listresourcesharepermissions")+ .then()+ .statusCode(400)+ .body("__type", equalTo("UnknownResourceException"));++ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{}")+ .when()+ .post("/listresourcesharepermissions")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"));+ }+@Testvoid deleteEchoesTheClientTokenAndSharesReportFeatureSet() {String shareArn =