Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(ram): support resource-share invitation accept/reject (#3120)

Priamo Germosen81b8127de07b
diff --git a/docs/services/ram.md b/docs/services/ram.md
index 954b7ee499..093d8f7d10 100644
--- a/docs/services/ram.md
+++ b/docs/services/ram.md
@@ -7,8 +7,9 @@
Floci implements the AWS Resource Access Manager calls AWS Landing Zone Accelerator makes
while bootstrapping shared Transit Gateway attachments and other cross-account resources:
the organization-sharing opt-in, resource-share CRUD, association management, principal
-listing, and tagging. Sharing is modeled as a flat in-memory store, not full RAM semantics —
-see Current Scope below for what's simplified.
+listing, tagging, and invitation accept/reject (backing `aws_ram_resource_share_accepter`).
+Sharing is modeled as a flat in-memory store, not full RAM semantics: see Current Scope
+below for what's simplified.
## Supported Actions
@@ -25,7 +26,9 @@ see Current Scope below for what's simplified.
| `ListPrincipals` | Lists principals associated with visible shares (`POST /listprincipals`) |
| `TagResource` | Adds/overwrites tags on a resource share (`POST /tagresource`) |
| `UntagResource` | Removes tags by key from a resource share (`POST /untagresource`) |
-| `GetResourceShareInvitations` | Always returns an empty list — organization sharing auto-accepts, so invitations never exist here (`POST /getresourceshareinvitations`) |
+| `GetResourceShareInvitations` | Lists invitations received by the caller, filterable by `resourceShareArns`/`resourceShareInvitationArns`. Empty for organization/OU-principal shares, which never get one (`POST /getresourceshareinvitations`) |
+| `AcceptResourceShareInvitation` | Accepts a `PENDING` invitation; receiver-only (`POST /acceptresourceshareinvitation`) |
+| `RejectResourceShareInvitation` | Rejects a `PENDING` invitation; receiver-only (`POST /rejectresourceshareinvitation`) |
| `ListResources` | Lists shared resource ARNs, with the RAM resource type derived from the ARN, e.g. `ec2:TransitGateway` (`POST /listresources`) |
<!-- floci:actions:end -->
@@ -47,6 +50,11 @@ aws --endpoint-url http://localhost:4566 ram create-resource-share \
aws --endpoint-url http://localhost:4566 ram delete-resource-share \
--resource-share-arn arn:aws:ram:us-east-1:000000000000:resource-share/...
+
+# Direct account principals (not an OU/organization ARN) get a real invitation to accept:
+aws --endpoint-url http://localhost:4566 ram get-resource-share-invitations
+aws --endpoint-url http://localhost:4566 ram accept-resource-share-invitation \
+ --resource-share-invitation-arn arn:aws:ram:us-east-1:000000000000:resource-share-invitation/...
```
## Current Scope
@@ -55,7 +63,21 @@ aws --endpoint-url http://localhost:4566 ram delete-resource-share \
principal targeting, since launched-container credentials all resolve to the same default
account and a principal-based check would hide shares from consumers that should see them.
LZA's `Custom::GetResourceShare` Lambda filters client-side by `owningAccountId` + `name`
- anyway, so this doesn't affect that flow.
+ anyway, so this doesn't affect that flow. This holds regardless of invitation status too:
+ unlike real AWS, a `PENDING` invitation does not hide the share or its resources from the
+ invited account.
+- Invitations exist for bookkeeping (`aws_ram_resource_share_accepter` needs somewhere to
+ Accept/Reject), not as a visibility gate. One is created only for a bare AWS account-id
+ principal added while `EnableSharingWithAwsOrganization` has not been called: an
+ organization/OU principal never gets one, matching real AWS's own auto-accept behavior for
+ org-based sharing, and neither does an account principal once organization sharing is
+ enabled. `AcceptResourceShareInvitation`/`RejectResourceShareInvitation` are receiver-only
+ (`OperationNotPermittedException` otherwise) and terminal once accepted or rejected
+ (`ResourceShareInvitationAlready{Accepted,Rejected}Exception` on a repeat call); floci does
+ not model time-based `EXPIRED` transitions, or what happens to an invitation after its share
+ is deleted. `GetResourceShareInvitations` only returns invitations the caller received, not
+ ones it sent, matching the API reference ("invitations that you have received"). A
+ syntactically invalid ARN passed to any of the three fails with `MalformedArnException`.
- Mutations are owner-only: a caller that is not the share's owning account gets
`UnknownResourceException`, the same error an unknown ARN gets, since AWS resolves a share
ARN within the caller's own account. Visibility above is unaffected.
@@ -64,23 +86,21 @@ aws --endpoint-url http://localhost:4566 ram delete-resource-share \
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.
+ are accepted but ignored, every matching share is returned in one page.
- 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`.
+ `NoSuchBucket` XML body where the SDK expects JSON, not a modeled `UnknownOperationException`.
If a client reports an XML parse error against a RAM call, that is the cause, not credentials.
`GetResourceShareAssociations` is the one most likely to be hit: Terraform's
`aws_ram_resource_association` and `aws_ram_principal_association` read it on every refresh.
- `AssociateResourceShare`/`DisassociateResourceShare` responses synthesize one
`resourceShareAssociation` row per requested ARN/principal rather than tracking real
per-association status transitions (e.g. no `ASSOCIATING`/`DISASSOCIATING` intermediate
- state — everything completes synchronously).
+ state, everything completes synchronously).
- `TagResource`/`UntagResource` only support tagging by `resourceShareArn`; tagging an
individual shared resource via `resourceArn` is not modeled (RAM's `TagResource` accepts
either, 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
+ family. Shares created here always use RAM's default managed permission implicitly: there
is no explicit permission model to associate or version.
-- `AcceptResourceShareInvitation` / `RejectResourceShareInvitation` are not implemented —
- moot under organization sharing, which never produces invitations to begin with.
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 493a6b48f3..ee6dea50ea 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
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
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.SharedResource;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
@@ -35,7 +36,7 @@ import java.util.Map;
* <p>Serves the RAM calls AWS Landing Zone Accelerator makes: the organization-sharing opt-in
* plus the share reads of the Custom::GetResourceShare / Custom::GetResourceShareItem Lambdas.
* The literal paths take JAX-RS precedence over S3's {@code /{bucket}} template route, so no
- * extra routing wiring is needed — but any RAM path missing here falls through to S3 and
+ * extra routing wiring is needed, but any RAM path missing here falls through to S3 and
* produces an XML error a restJson1 client cannot parse.
*/
@Path("/")
@@ -227,14 +228,64 @@ public class RamController {
@Path("/getresourceshareinvitations")
@Consumes(MediaType.WILDCARD)
public Response getResourceShareInvitations(String body) {
- // The body is semantically ignored (invitations are always empty under
- // organization sharing) but malformed JSON is still a client error.
- readTree(body);
+ JsonNode request = readTree(body);
+ List<ResourceShareInvitation> invitations = service.getResourceShareInvitations(
+ regionResolver.getAccountId(),
+ stringList(request.path("resourceShareArns")),
+ stringList(request.path("resourceShareInvitationArns")));
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode array = objectMapper.createArrayNode();
+ invitations.forEach(invitation -> array.add(invitationNode(invitation)));
+ response.set("resourceShareInvitations", array);
+ return Response.ok(response).build();
+ }
+
+ @POST
+ @Path("/acceptresourceshareinvitation")
+ @Consumes(MediaType.WILDCARD)
+ public Response acceptResourceShareInvitation(String body) {
+ JsonNode request = readTree(body);
+ String clientToken = request.hasNonNull("clientToken") ? request.path("clientToken").asText() : null;
+ ResourceShareInvitation invitation = service.acceptResourceShareInvitation(
+ request.path("resourceShareInvitationArn").asText(), regionResolver.getAccountId());
+ return invitationResponse(invitation, clientToken);
+ }
+
+ @POST
+ @Path("/rejectresourceshareinvitation")
+ @Consumes(MediaType.WILDCARD)
+ public Response rejectResourceShareInvitation(String body) {
+ JsonNode request = readTree(body);
+ String clientToken = request.hasNonNull("clientToken") ? request.path("clientToken").asText() : null;
+ ResourceShareInvitation invitation = service.rejectResourceShareInvitation(
+ request.path("resourceShareInvitationArn").asText(), regionResolver.getAccountId());
+ return invitationResponse(invitation, clientToken);
+ }
+
+ private Response invitationResponse(ResourceShareInvitation invitation, String clientToken) {
ObjectNode response = objectMapper.createObjectNode();
- response.set("resourceShareInvitations", objectMapper.createArrayNode());
+ response.set("resourceShareInvitation", invitationNode(invitation));
+ // Echoes what the caller sent (or, per AWS, a generated one if it sent none); floci
+ // has no need to invent one when absent since nothing here retries on it.
+ if (clientToken != null) {
+ response.put("clientToken", clientToken);
+ }
return Response.ok(response).build();
}
+ private ObjectNode invitationNode(ResourceShareInvitation invitation) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("resourceShareInvitationArn", invitation.resourceShareInvitationArn());
+ node.put("resourceShareArn", invitation.resourceShareArn());
+ node.put("resourceShareName", invitation.resourceShareName());
+ node.put("senderAccountId", invitation.senderAccountId());
+ node.put("receiverAccountId", invitation.receiverAccountId());
+ node.put("invitationTimestamp", invitation.invitationTimestamp().toEpochMilli() / 1000.0);
+ node.put("status", invitation.status());
+ return node;
+ }
+
@POST
@Path("/listresources")
@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.java
index 965e8e79aa..f90da82c66 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
@@ -1,12 +1,14 @@
package io.github.hectorvent.floci.services.ram;
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.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
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.SharedResource;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
@@ -21,6 +23,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
+import java.util.regex.Pattern;
/**
* AWS Resource Access Manager (RAM) business logic.
@@ -28,15 +31,24 @@ import java.util.UUID;
* <p>Covers {@code EnableSharingWithAwsOrganization} plus the resource-share reads LZA's
* TGW share flow performs: the owning account registers a share (from the
* {@code AWS::RAM::ResourceShare} CFN provisioner), and accepting accounts page
- * GetResourceShareInvitations (always empty here — organization sharing auto-accepts, matching
- * real AWS), find the share via GetResourceShares(OTHER-ACCOUNTS), and read the shared ARNs via
- * ListResources.
+ * GetResourceShareInvitations, find the share via GetResourceShares(OTHER-ACCOUNTS), and read
+ * the shared ARNs via ListResources.
*
* <p>Principals are stored but not enforced for visibility: floci's org is the only org, and
* launched containers call in with placeholder credentials that resolve to the default account,
- * so OTHER-ACCOUNTS simply means "every share the caller does not own". Mutations are the
- * opposite: they are owner-only, and a non-owner gets the same UnknownResourceException a
- * never-created ARN gets.
+ * so OTHER-ACCOUNTS simply means "every share the caller does not own", and ListResources /
+ * GetResourceShares never wait on an invitation being accepted. Mutations are the opposite: they
+ * are owner-only, and a non-owner gets the same UnknownResourceException a never-created ARN
+ * gets.
+ *
+ * <p>Invitations exist purely as the accept/reject bookkeeping {@code aws_ram_resource_share_accepter}
+ * needs, not as a visibility gate: an organization/OU principal (real AWS's own auto-accept case)
+ * never gets one, and neither does an account principal while organization sharing is enabled
+ * (matching {@code EnableSharingWithAwsOrganization}'s effect on member accounts). A bare AWS
+ * account-id principal added while organization sharing is off gets a PENDING invitation the
+ * receiving account can accept or reject, but, unlike real AWS, the share and its resources are
+ * visible under OTHER-ACCOUNTS regardless of that invitation's status, for the same reason
+ * visibility isn't otherwise gated by principal.
*/
@ApplicationScoped
public class RamService {
@@ -45,10 +57,13 @@ public class RamService {
/** The modeled ResourceShareStatus enum. */
private static final List<String> SHARE_STATUSES =
List.of("PENDING", "ACTIVE", "FAILED", "DELETING", "DELETED");
+ /** An AWS account id, as opposed to an organization/OU principal ARN. */
+ private static final Pattern ACCOUNT_ID_PRINCIPAL = Pattern.compile("\\d{12}");
private final StorageFactory storageFactory;
private StorageBackend<String, ResourceShare> shares;
private StorageBackend<String, Boolean> settings;
+ private StorageBackend<String, ResourceShareInvitation> invitations;
@Inject
public RamService(StorageFactory storageFactory) {
@@ -61,6 +76,8 @@ public class RamService {
new TypeReference<Map<String, ResourceShare>>() {});
settings = storageFactory.create("ram", "ram-settings.json",
new TypeReference<Map<String, Boolean>>() {});
+ invitations = storageFactory.create("ram", "ram-resource-share-invitations.json",
+ new TypeReference<Map<String, ResourceShareInvitation>>() {});
}
public boolean enableSharingWithAwsOrganization() {
@@ -79,7 +96,9 @@ public class RamService {
+ ":resource-share/" + UUID.randomUUID();
ResourceShare share = new ResourceShare(
arn, name, owningAccountId, principals, resourceArns, allowExternalPrincipals);
- return putForOwner(share);
+ ResourceShare stored = putForOwner(share);
+ inviteAccountPrincipals(stored, principals);
+ return stored;
}
/** The unfiltered read: every share visible to the caller under {@code resourceOwner}. */
@@ -118,9 +137,155 @@ public class RamService {
return result;
}
- /** Organization sharing never creates invitations — resources become visible directly. */
- public List<Object> getResourceShareInvitations(String callerAccountId) {
- return List.of();
+ /**
+ * @param resourceShareArns restrict to invitations for these shares, or empty for any
+ * @param resourceShareInvitationArns restrict to these invitation ARNs, or empty for any
+ */
+ public List<ResourceShareInvitation> getResourceShareInvitations(String callerAccountId,
+ List<String> resourceShareArns,
+ List<String> resourceShareInvitationArns) {
+ requireValidArns(resourceShareArns);
+ requireValidArns(resourceShareInvitationArns);
+ List<ResourceShareInvitation> result = new ArrayList<>();
+ for (ResourceShareInvitation invitation : allInvitations()) {
+ // "Retrieves details about invitations that you have received": receiver only,
+ // not the sender (verified against the API reference; unlike GetResourceShares,
+ // there is no SELF/OTHER-ACCOUNTS style toggle here).
+ if (!callerAccountId.equals(invitation.receiverAccountId())) {
+ continue;
+ }
+ if (!resourceShareArns.isEmpty() && !resourceShareArns.contains(invitation.resourceShareArn())) {
+ continue;
+ }
+ if (!resourceShareInvitationArns.isEmpty()
+ && !resourceShareInvitationArns.contains(invitation.resourceShareInvitationArn())) {
+ continue;
+ }
+ result.add(invitation);
+ }
+ return result;
+ }
+
+ /** Both GetResourceShareInvitations and Accept/RejectResourceShareInvitation model this. */
+ private static void requireValidArns(List<String> arns) {
+ for (String arn : arns) {
+ if (!isValidArn(arn)) {
+ throw new AwsException("MalformedArnException",
+ "The specified Amazon Resource Name (ARN) has a format that isn't valid: " + arn, 400);
+ }
+ }
+ }
+
+ private static boolean isValidArn(String arn) {
+ try {
+ AwsArnUtils.parse(arn);
+ return true;
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ }
+
+ public ResourceShareInvitation acceptResourceShareInvitation(String resourceShareInvitationArn,
+ String callerAccountId) {
+ return resolveInvitation(resourceShareInvitationArn, callerAccountId, "ACCEPTED");
+ }
+
+ public ResourceShareInvitation rejectResourceShareInvitation(String resourceShareInvitationArn,
+ String callerAccountId) {
+ return resolveInvitation(resourceShareInvitationArn, callerAccountId, "REJECTED");
+ }
+
+ private ResourceShareInvitation resolveInvitation(String resourceShareInvitationArn,
+ String callerAccountId, String newStatus) {
+ if (!isValidArn(resourceShareInvitationArn)) {
+ throw new AwsException("MalformedArnException",
+ "The specified Amazon Resource Name (ARN) has a format that isn't valid: "
+ + resourceShareInvitationArn, 400);
+ }
+ // Serializes the status check against the write: two concurrent Accept calls on the
+ // same invitation must not both observe PENDING and both succeed.
+ synchronized (this) {
+ ResourceShareInvitation invitation = allInvitations().stream()
+ .filter(i -> i.resourceShareInvitationArn().equals(resourceShareInvitationArn))
+ .findFirst()
+ .orElseThrow(() -> new AwsException("ResourceShareInvitationArnNotFoundException",
+ "ResourceShareInvitation " + resourceShareInvitationArn + " does not exist.", 400));
+ // Only the invited account can act on its own invitation: the sender polls it via
+ // GetResourceShareInvitations but does not get to accept or reject on the receiver's
+ // behalf.
+ if (!callerAccountId.equals(invitation.receiverAccountId())) {
+ throw new AwsException("OperationNotPermittedException",
+ "You do not have permission to accept or reject this invitation.", 400);
+ }
+ if ("ACCEPTED".equals(invitation.status())) {
+ throw new AwsException("ResourceShareInvitationAlreadyAcceptedException",
+ "ResourceShareInvitation " + resourceShareInvitationArn + " has already been accepted.", 400);
+ }
+ if ("REJECTED".equals(invitation.status())) {
+ throw new AwsException("ResourceShareInvitationAlreadyRejectedException",
+ "ResourceShareInvitation " + resourceShareInvitationArn + " has already been rejected.", 400);
+ }
+ ResourceShareInvitation updated = invitation.withStatus(newStatus);
+ putInvitation(updated);
+ return updated;
+ }
+ }
+
+ /**
+ * An organization/OU principal (not a bare account id) never gets one: real AWS only
+ * invites account principals, and auto-accepts those too once organization sharing is
+ * enabled (matching {@link #enableSharingWithAwsOrganization()}). A principal already
+ * PENDING or ACCEPTED on this share is skipped so re-associating it is a no-op; one that
+ * was REJECTED gets invited again, same as real AWS re-sharing after a rejection.
+ */
+ private void inviteAccountPrincipals(ResourceShare share, List<String> principals) {
+ if (isSharingWithOrganizationEnabled()) {
+ return;
+ }
+ // Serializes the live-invitation check against the insert: two concurrent
+ // AssociateResourceShare calls for the same principal must not both observe "no
+ // live invitation" and both create one.
+ synchronized (this) {
+ for (String principal : principals) {
+ if (!ACCOUNT_ID_PRINCIPAL.matcher(principal).matches()) {
+ continue;
+ }
+ boolean live = allInvitations().stream()
+ .anyMatch(i -> i.resourceShareArn().equals(share.getResourceShareArn())
+ && i.receiverAccountId().equals(principal)
+ && !"REJECTED".equals(i.status()));
+ if (live) {
+ continue;
+ }
+ String region = extractRegion(share.getResourceShareArn());
+ String arn = "arn:aws:ram:" + region + ":" + share.getOwningAccountId()
+ + ":resource-share-invitation/" + UUID.randomUUID();
+ putInvitation(new ResourceShareInvitation(arn, share.getResourceShareArn(), share.getName(),
+ share.getOwningAccountId(), principal, Instant.now(), "PENDING"));
+ }
+ }
+ }
+
+ /** {@code arn:aws:ram:<region>:<account>:resource-share/<id>} → {@code <region>}. */
+ private static String extractRegion(String resourceShareArn) {
+ String[] parts = resourceShareArn.split(":", 6);
+ return parts.length < 4 ? "" : parts[3];
+ }
+
+ private void putInvitation(ResourceShareInvitation invitation) {
+ if (invitations instanceof AccountAwareStorageBackend<ResourceShareInvitation> accountAware) {
+ accountAware.putForAccount(invitation.receiverAccountId(),
+ invitation.resourceShareInvitationArn(), invitation);
+ return;
+ }
+ invitations.put(invitation.resourceShareInvitationArn(), invitation);
+ }
+
+ private List<ResourceShareInvitation> allInvitations() {
+ if (invitations instanceof AccountAwareStorageBackend<ResourceShareInvitation> accountAware) {
+ return accountAware.scanAllAccounts();
+ }
+ return invitations.scan(key -> true);
}
public List<SharedResource> listResources(String callerAccountId, String resourceOwner,
@@ -166,11 +331,21 @@ public class RamService {
public ResourceShare associateResourceShare(String resourceShareArn, List<String> resourceArns,
List<String> principals, String callerAccountId) {
- ResourceShare share = requireOwnedShare(resourceShareArn, callerAccountId);
- ResourceShare updated = share.withPrincipalsAndResources(
- mergeDistinct(share.getPrincipals(), principals),
- mergeDistinct(share.getResourceArns(), resourceArns));
- return putForOwner(updated);
+ // The read, the merged write, and the resulting invitation creation must all happen as
+ // one operation: two concurrent associates for different principals on the same share
+ // must not each read the pre-update share and overwrite each other's addition, which
+ // would also leave an invitation on record for a principal the stored share lost.
+ synchronized (this) {
+ ResourceShare share = requireOwnedShare(resourceShareArn, callerAccountId);
+ ResourceShare updated = share.withPrincipalsAndResources(
+ mergeDistinct(share.getPrincipals(), principals),
+ mergeDistinct(share.getResourceArns(), resourceArns));
+ ResourceShare stored = putForOwner(updated);
+ // Only newly-added principals: re-associating one already on the share (or one that
+ // already has a live invitation) must not spawn a second invitation.
+ inviteAccountPrincipals(stored, withoutAll(principals, share.getPrincipals()));
+ return stored;
+ }
}
public ResourceShare disassociateResourceShare(String resourceShareArn, List<String> resourceArns,
@@ -227,7 +402,7 @@ public class RamService {
/**
* Resolves a share the caller may mutate. A share owned by another account gets the same
* UnknownResourceException as one that was never created: AWS resolves a share ARN within
- * the caller's own account, so a non-owner must not learn that the ARN exists — let alone
+ * the caller's own account, so a non-owner must not learn that the ARN exists, let alone
* be able to rename, retag, or delete it.
*/
private ResourceShare requireOwnedShare(String resourceShareArn, String callerAccountId) {
@@ -284,7 +459,7 @@ public class RamService {
/**
* The model enumerates {@code resourceOwner} as {@code SELF} or {@code OTHER-ACCOUNTS} on every
* read operation that takes it. The visibility fork below is a two-way branch, so an unmodelled
- * value silently means OTHER-ACCOUNTS — a caller who sent {@code "self"} would be handed every
+ * value silently means OTHER-ACCOUNTS: a caller who sent {@code "self"} would be handed every
* share they do NOT own. AWS answers InvalidParameterException, which all three operations list.
*
* <p>It is also a required member, so a null one is rejected rather than defaulted: guessing
diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/model/ResourceShareInvitation.java b/src/main/java/io/github/hectorvent/floci/services/ram/model/ResourceShareInvitation.java
new file mode 100644
index 0000000000..1b6a0f1ad2
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ram/model/ResourceShareInvitation.java
@@ -0,0 +1,28 @@
+package io.github.hectorvent.floci.services.ram.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+/**
+ * One invitation sent to an AWS account principal directly associated with a resource share
+ * (not an organization/OU principal, which never needs one: see {@link
+ * io.github.hectorvent.floci.services.ram.RamService}). {@code status} is one of
+ * {@code PENDING}, {@code ACCEPTED}, {@code REJECTED}; floci does not model time-based
+ * {@code EXPIRED} transitions.
+ */
+@RegisterForReflection
+public record ResourceShareInvitation(
+ String resourceShareInvitationArn,
+ String resourceShareArn,
+ String resourceShareName,
+ String senderAccountId,
+ String receiverAccountId,
+ Instant invitationTimestamp,
+ String status) {
+
+ public ResourceShareInvitation withStatus(String newStatus) {
+ return new ResourceShareInvitation(resourceShareInvitationArn, resourceShareArn, resourceShareName,
+ senderAccountId, receiverAccountId, invitationTimestamp, newStatus);
+ }
+}
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.java
index ed85860805..32fc6217a1 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
@@ -49,9 +49,9 @@ class RamIntegrationTest {
@Test
void getResourceShareInvitations_returnsEmptyJson() {
- // LZA's Custom::GetResourceShare Lambda pages this first; under organization
- // sharing there are never invitations. The response must be JSON (restJson1) —
- // an XML fallthrough here is exactly the SyntaxError seen in run b81f0999.
+ // LZA's Custom::GetResourceShare Lambda pages this first, before any share has been
+ // created in this test's account. The response must be JSON (restJson1): an XML
+ // fallthrough here is exactly the SyntaxError seen in run b81f0999.
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
@@ -67,7 +67,7 @@ class RamIntegrationTest {
@Test
void ownerCanTagAndDeleteItsOwnShareOverHttp() {
// Mutations resolve the share within the caller's account, so the identity stamped at
- // create time has to be the identity resolved at tag/delete time — otherwise LZA's
+ // create time has to be the identity resolved at tag/delete time, otherwise LZA's
// AWS::RAM::ResourceShare teardown would fail against a share it had just created.
String shareArn =
given()
@@ -227,8 +227,8 @@ class RamIntegrationTest {
}
/**
- * A present-but-unmodelled resourceOwner — including a non-string that {@code asText}
- * coerces — has to reach the service check and come back as InvalidParameterException on the
+ * A present-but-unmodelled resourceOwner, including a non-string that {@code asText}
+ * coerces, has to reach the service check and come back as InvalidParameterException on the
* wire, which is the path LZA actually takes.
*/
@Test
@@ -263,7 +263,7 @@ class RamIntegrationTest {
/**
* resourceOwner is a required member on all three read operations. Substituting SELF for an
- * absent one answered a question the caller never asked — and answered it with the caller's
+ * absent one answered a question the caller never asked, and answered it with the caller's
* own shares, which is the more dangerous of the two branches to guess at.
*/
@Test
@@ -346,4 +346,67 @@ class RamIntegrationTest {
.body("resources[0].type", equalTo("ec2:TransitGateway"))
.body("resources[0].resourceShareArn", equalTo(shareArn));
}
+
+ @Test
+ void acceptResourceShareInvitationOverHttp() {
+ // A bare account-id principal (not an OU/organization ARN) gets a real PENDING
+ // invitation; targeting this test's own account keeps the whole flow within one
+ // Authorization header, same as the rest of this class.
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ {
+ "name": "http-invitation-share",
+ "principals": ["000000000000"],
+ "resourceArns": ["arn:aws:ec2:us-east-1:000000000000:transit-gateway/tgw-0inv"]
+ }
+ """)
+ .when()
+ .post("/createresourceshare")
+ .then()
+ .statusCode(200);
+
+ String invitationArn =
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("{}")
+ .when()
+ .post("/getresourceshareinvitations")
+ .then()
+ .statusCode(200)
+ .body("resourceShareInvitations.find { it.resourceShareName == 'http-invitation-share' }.status",
+ equalTo("PENDING"))
+ .extract()
+ .path("resourceShareInvitations.find { it.resourceShareName == 'http-invitation-share' }" +
+ ".resourceShareInvitationArn");
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceShareInvitationArn": "%s", "clientToken": "test-token" }
+ """.formatted(invitationArn))
+ .when()
+ .post("/acceptresourceshareinvitation")
+ .then()
+ .statusCode(200)
+ .contentType("application/json")
+ .body("resourceShareInvitation.status", equalTo("ACCEPTED"))
+ .body("resourceShareInvitation.resourceShareInvitationArn", equalTo(invitationArn))
+ .body("clientToken", equalTo("test-token"));
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ { "resourceShareInvitationArn": "%s" }
+ """.formatted(invitationArn))
+ .when()
+ .post("/acceptresourceshareinvitation")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ResourceShareInvitationAlreadyAcceptedException"));
+ }
}
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 51199f20c8..00c286fb4c 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
@@ -6,14 +6,21 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ram.model.ResourceShare;
+import io.github.hectorvent.floci.services.ram.model.ResourceShareInvitation;
import io.github.hectorvent.floci.services.ram.model.SharedResource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
+import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
@@ -118,7 +125,7 @@ class RamServiceTest {
service.createResourceShare(
"us-east-1-tgw-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
- assertTrue(service.getResourceShareInvitations(ACCEPTER).isEmpty());
+ assertTrue(service.getResourceShareInvitations(ACCEPTER, List.of(), List.of()).isEmpty());
}
@Test
@@ -186,7 +193,7 @@ class RamServiceTest {
/**
* The model enumerates resourceOwner as SELF or OTHER-ACCOUNTS on GetResourceShares,
* ListPrincipals and ListResources. Anything else used to fall through the "not SELF" branch
- * and silently return other accounts' shares — the opposite of what a caller who typo'd
+ * and silently return other accounts' shares, the opposite of what a caller who typo'd
* "self" expected.
*/
@Test
@@ -218,7 +225,7 @@ class RamServiceTest {
assertUnknownResource(() -> service.untagResource(arn, List.of("k"), OWNER));
assertUnknownResource(() -> service.deleteResourceShare(arn, OWNER));
- // Still readable with DELETED status — mutation rejection must not hide it from reads.
+ // Still readable with DELETED status: mutation rejection must not hide it from reads.
assertEquals("DELETED", service.getResourceShares(OWNER, "SELF").get(0).getStatus());
}
@@ -291,6 +298,241 @@ class RamServiceTest {
assertEquals(created.getCreationTime(), tagged.getCreationTime());
}
+ @Test
+ void accountPrincipalWithoutOrganizationSharingCreatesPendingInvitation() {
+ ResourceShare share = service.createResourceShare(
+ "direct-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ List<ResourceShareInvitation> invitations =
+ service.getResourceShareInvitations(ACCEPTER, List.of(), List.of());
+ assertEquals(1, invitations.size());
+ ResourceShareInvitation invitation = invitations.get(0);
+ assertEquals(share.getResourceShareArn(), invitation.resourceShareArn());
+ assertEquals(OWNER, invitation.senderAccountId());
+ assertEquals(ACCEPTER, invitation.receiverAccountId());
+ assertEquals("PENDING", invitation.status());
+
+ // Receiver-only, per the API reference ("invitations that you have received"): the
+ // sender does not see its own outstanding invitations through this call.
+ assertTrue(service.getResourceShareInvitations(OWNER, List.of(), List.of()).isEmpty());
+ // But the share itself is visible regardless: invitations are bookkeeping, not a gate.
+ assertEquals(1, service.getResourceShares(ACCEPTER, "OTHER-ACCOUNTS").size());
+ }
+
+ @Test
+ void organizationPrincipalNeverCreatesInvitationEvenWithoutOrganizationSharingEnabled() {
+ service.createResourceShare(
+ "ou-share", List.of(OU_ARN), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ assertTrue(service.getResourceShareInvitations(ACCEPTER, List.of(), List.of()).isEmpty());
+ }
+
+ @Test
+ void accountPrincipalUnderEnabledOrganizationSharingCreatesNoInvitation() {
+ service.enableSharingWithAwsOrganization();
+
+ service.createResourceShare(
+ "direct-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ assertTrue(service.getResourceShareInvitations(ACCEPTER, List.of(), List.of()).isEmpty());
+ }
+
+ @Test
+ void associatingNewAccountPrincipalCreatesInvitationButReassociatingExistingOneDoesNot() {
+ ResourceShare share = service.createResourceShare(
+ "direct-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ assertEquals(1, service.getResourceShareInvitations(ACCEPTER, List.of(), List.of()).size());
+
+ // Re-associating the same principal must not spawn a second invitation.
+ service.associateResourceShare(share.getResourceShareArn(), List.of(), List.of(ACCEPTER), OWNER);
+ assertEquals(1, service.getResourceShareInvitations(ACCEPTER, List.of(), List.of()).size());
+
+ // A genuinely new principal gets its own.
+ String other = "333333333333";
+ service.associateResourceShare(share.getResourceShareArn(), List.of(), List.of(other), OWNER);
+ assertEquals(1, service.getResourceShareInvitations(other, List.of(), List.of()).size());
+ assertEquals(1, service.getResourceShareInvitations(ACCEPTER, List.of(), List.of()).size());
+ }
+
+ @Test
+ void acceptResourceShareInvitationTransitionsToAcceptedAndIsThenTerminal() {
+ service.createResourceShare(
+ "direct-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ String invitationArn = service.getResourceShareInvitations(ACCEPTER, List.of(), List.of())
+ .get(0).resourceShareInvitationArn();
+
+ ResourceShareInvitation accepted = service.acceptResourceShareInvitation(invitationArn, ACCEPTER);
+ assertEquals("ACCEPTED", accepted.status());
+ assertEquals("ACCEPTED",
+ service.getResourceShareInvitations(ACCEPTER, List.of(), List.of()).get(0).status());
+
+ AwsException repeat = assertThrows(AwsException.class,
+ () -> service.acceptResourceShareInvitation(invitationArn, ACCEPTER));
+ assertEquals("ResourceShareInvitationAlreadyAcceptedException", repeat.getErrorCode());
+ }
+
+ @Test
+ void rejectResourceShareInvitationTransitionsToRejectedAndIsThenTerminal() {
+ service.createResourceShare(
+ "direct-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ String invitationArn = service.getResourceShareInvitations(ACCEPTER, List.of(), List.of())
+ .get(0).resourceShareInvitationArn();
+
+ ResourceShareInvitation rejected = service.rejectResourceShareInvitation(invitationArn, ACCEPTER);
+ assertEquals("REJECTED", rejected.status());
+
+ AwsException repeat = assertThrows(AwsException.class,
+ () -> service.rejectResourceShareInvitation(invitationArn, ACCEPTER));
+ assertEquals("ResourceShareInvitationAlreadyRejectedException", repeat.getErrorCode());
+ }
+
+ @Test
+ void reassociatingAfterRejectionSendsANewInvitation() {
+ ResourceShare share = service.createResourceShare(
+ "direct-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ String firstArn = service.getResourceShareInvitations(ACCEPTER, List.of(), List.of())
+ .get(0).resourceShareInvitationArn();
+ service.rejectResourceShareInvitation(firstArn, ACCEPTER);
+
+ // Disassociate and re-associate, same as a Terraform apply that removes then re-adds
+ // the principal: real AWS sends a fresh invitation rather than leaving the account
+ // permanently locked out by an old rejection.
+ service.disassociateResourceShare(share.getResourceShareArn(), List.of(), List.of(ACCEPTER), OWNER);
+ service.associateResourceShare(share.getResourceShareArn(), List.of(), List.of(ACCEPTER), OWNER);
+
+ List<ResourceShareInvitation> invitations =
+ service.getResourceShareInvitations(ACCEPTER, List.of(), List.of());
+ assertEquals(2, invitations.size());
+ assertTrue(invitations.stream().anyMatch(i -> "PENDING".equals(i.status())));
+ }
+
+ @Test
+ void onlyTheReceiverCanAcceptOrRejectAnInvitation() {
+ service.createResourceShare(
+ "direct-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ String invitationArn = service.getResourceShareInvitations(ACCEPTER, List.of(), List.of())
+ .get(0).resourceShareInvitationArn();
+
+ AwsException bySender = assertThrows(AwsException.class,
+ () -> service.acceptResourceShareInvitation(invitationArn, OWNER));
+ assertEquals("OperationNotPermittedException", bySender.getErrorCode());
+
+ AwsException byStranger = assertThrows(AwsException.class,
+ () -> service.rejectResourceShareInvitation(invitationArn, "444444444444"));
+ assertEquals("OperationNotPermittedException", byStranger.getErrorCode());
+ }
+
+ @Test
+ void unknownInvitationArnFailsWithNotFoundException() {
+ AwsException error = assertThrows(AwsException.class, () ->
+ service.acceptResourceShareInvitation(
+ "arn:aws:ram:us-east-1:222222222222:resource-share-invitation/does-not-exist", ACCEPTER));
+ assertEquals("ResourceShareInvitationArnNotFoundException", error.getErrorCode());
+ assertEquals(400, error.getHttpStatus());
+ }
+
+ @Test
+ void malformedInvitationArnFailsWithMalformedArnException() {
+ AwsException error = assertThrows(AwsException.class, () ->
+ service.acceptResourceShareInvitation("not-an-arn", ACCEPTER));
+ assertEquals("MalformedArnException", error.getErrorCode());
+ assertEquals(400, error.getHttpStatus());
+
+ AwsException filterError = assertThrows(AwsException.class, () ->
+ service.getResourceShareInvitations(ACCEPTER, List.of("not-an-arn"), List.of()));
+ assertEquals("MalformedArnException", filterError.getErrorCode());
+ }
+
+ @Test
+ void getResourceShareInvitationsFiltersByResourceShareArnAndInvitationArn() {
+ ResourceShare share = service.createResourceShare(
+ "direct-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ service.createResourceShare(
+ "other-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ String invitationArn = service.getResourceShareInvitations(ACCEPTER, List.of(), List.of()).stream()
+ .filter(i -> i.resourceShareArn().equals(share.getResourceShareArn()))
+ .findFirst().orElseThrow().resourceShareInvitationArn();
+
+ assertEquals(1, service.getResourceShareInvitations(
+ ACCEPTER, List.of(share.getResourceShareArn()), List.of()).size());
+ assertEquals(1, service.getResourceShareInvitations(
+ ACCEPTER, List.of(), List.of(invitationArn)).size());
+ assertTrue(service.getResourceShareInvitations(
+ ACCEPTER, List.of("arn:aws:ram:us-east-1:111111111111:resource-share/nope"), List.of()).isEmpty());
+ }
+
+ @Test
+ void concurrentAcceptCallsOnTheSameInvitationOnlySucceedOnce() throws Exception {
+ service.createResourceShare(
+ "direct-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
+ String invitationArn = service.getResourceShareInvitations(ACCEPTER, List.of(), List.of())
+ .get(0).resourceShareInvitationArn();
+
+ int threadCount = 8;
+ ExecutorService executor = Executors.newFixedThreadPool(threadCount);
+ try {
+ CountDownLatch ready = new CountDownLatch(threadCount);
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<Boolean>> results = new ArrayList<>();
+ for (int i = 0; i < threadCount; i++) {
+ results.add(executor.submit(() -> {
+ ready.countDown();
+ assertTrue(start.await(5, TimeUnit.SECONDS));
+ try {
+ service.acceptResourceShareInvitation(invitationArn, ACCEPTER);
+ return true;
+ } catch (AwsException e) {
+ assertEquals("ResourceShareInvitationAlreadyAcceptedException", e.getErrorCode());
+ return false;
+ }
+ }));
+ }
+ assertTrue(ready.await(5, TimeUnit.SECONDS), "every thread reached the start gate");
+ start.countDown();
+
+ int succeeded = 0;
+ for (Future<Boolean> result : results) {
+ if (result.get(5, TimeUnit.SECONDS)) {
+ succeeded++;
+ }
+ }
+ assertEquals(1, succeeded, "exactly one concurrent Accept call should win the race");
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+
+ @Test
+ void concurrentAssociateCallsForTheSamePrincipalCreateOnlyOneInvitation() throws Exception {
+ ResourceShare share = service.createResourceShare(
+ "direct-share", List.of(), List.of(TGW_ARN), false, "us-east-1", OWNER);
+
+ int threadCount = 8;
+ ExecutorService executor = Executors.newFixedThreadPool(threadCount);
+ try {
+ CountDownLatch ready = new CountDownLatch(threadCount);
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<Void>> results = new ArrayList<>();
+ for (int i = 0; i < threadCount; i++) {
+ results.add(executor.submit(() -> {
+ ready.countDown();
+ assertTrue(start.await(5, TimeUnit.SECONDS));
+ service.associateResourceShare(share.getResourceShareArn(), List.of(), List.of(ACCEPTER), OWNER);
+ return null;
+ }));
+ }
+ assertTrue(ready.await(5, TimeUnit.SECONDS), "every thread reached the start gate");
+ start.countDown();
+ for (Future<Void> result : results) {
+ result.get(5, TimeUnit.SECONDS);
+ }
+ } finally {
+ executor.shutdownNow();
+ }
+
+ assertEquals(1, service.getResourceShareInvitations(ACCEPTER, List.of(), List.of()).size());
+ }
+
private static void assertInvalidParameter(Executable read) {
AwsException error = assertThrows(AwsException.class, read);
assertEquals("InvalidParameterException", error.getErrorCode());
@@ -301,7 +543,7 @@ class RamServiceTest {
AwsException error = assertThrows(AwsException.class, mutation);
assertEquals("UnknownResourceException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
- // Same message an unknown ARN gets — a non-owner must not learn the share exists.
+ // Same message an unknown ARN gets: a non-owner must not learn the share exists.
assertTrue(error.getMessage().endsWith(" does not exist."));
}