fix(ram): enforce resource share principal visibility (#3266)

* fix(ram): enforce resource share principal visibility

* fix(ram): restrict resource share visibility

* fix(ram): handle reassociated invitations
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-08 23:44:01 -05:00
1 parent 290559cff0
commit 8e10fd1ea6
5 files changed
+355 -34

No files matched your search

@@ -76,7 +76,7 @@ public class RamController {
"Allows AWS Resource Access Manager to access AWS Organizations on your behalf.");
}
ObjectNode response = objectMapper.createObjectNode();
response.put("returnValue", service.enableSharingWithAwsOrganization());
response.put("returnValue", service.enableSharingWithAwsOrganization(regionResolver.getAccountId()));
return Response.ok(response).build();
}
@@ -10,6 +10,8 @@ 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 io.github.hectorvent.floci.services.organizations.OrganizationsService;
import io.github.hectorvent.floci.services.organizations.model.Organization;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -34,21 +36,14 @@ import java.util.regex.Pattern;
* 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", 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>Visibility is principal-aware: an owner sees its own shares, an account principal sees a
* share only while its invitation is pending or accepted, and organization/OU principals are
* visible only to members resolved through the existing Organizations service. This same rule
* is used by GetResourceShares, ListResources, and ListPrincipals so filtering one operation
* cannot leak metadata through another.
*
* <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.
* <p>Mutations remain owner-only, and a non-owner gets the same UnknownResourceException a
* never-created ARN gets.
*/
@ApplicationScoped
public class RamService {
@@ -61,13 +56,20 @@ public class RamService {
private static final Pattern ACCOUNT_ID_PRINCIPAL = Pattern.compile("\\d{12}");
private final StorageFactory storageFactory;
private final OrganizationsService organizationsService;
private StorageBackend<String, ResourceShare> shares;
private StorageBackend<String, Boolean> settings;
private StorageBackend<String, ResourceShareInvitation> invitations;
@Inject
public RamService(StorageFactory storageFactory) {
public RamService(StorageFactory storageFactory, OrganizationsService organizationsService) {
this.storageFactory = storageFactory;
this.organizationsService = organizationsService;
}
/** Constructor used by isolated service tests with an explicit Organizations test double. */
RamService(StorageFactory storageFactory) {
this(storageFactory, null);
}
@PostConstruct
@@ -85,10 +87,26 @@ public class RamService {
return true;
}
public boolean enableSharingWithAwsOrganization(String callerAccountId) {
if (settings instanceof AccountAwareStorageBackend<Boolean> accountAware) {
accountAware.putForAccount(callerAccountId, ORGANIZATION_SHARING_KEY, true);
} else {
settings.put(ORGANIZATION_SHARING_KEY, true);
}
return true;
}
public boolean isSharingWithOrganizationEnabled() {
return settings.get(ORGANIZATION_SHARING_KEY).orElse(false);
}
public boolean isSharingWithOrganizationEnabled(String accountId) {
if (settings instanceof AccountAwareStorageBackend<Boolean> accountAware) {
return accountAware.getForAccount(accountId, ORGANIZATION_SHARING_KEY).orElse(false);
}
return settings.get(ORGANIZATION_SHARING_KEY).orElse(false);
}
public ResourceShare createResourceShare(String name, List<String> principals,
List<String> resourceArns, boolean allowExternalPrincipals,
String region, String owningAccountId) {
@@ -239,7 +257,7 @@ public class RamService {
* was REJECTED gets invited again, same as real AWS re-sharing after a rejection.
*/
private void inviteAccountPrincipals(ResourceShare share, List<String> principals) {
if (isSharingWithOrganizationEnabled()) {
if (isSharingWithOrganizationEnabled(share.getOwningAccountId())) {
return;
}
// Serializes the live-invitation check against the insert: two concurrent
@@ -489,12 +507,87 @@ public class RamService {
if ("SELF".equals(resourceOwner)) {
return owned;
}
// OTHER-ACCOUNTS: every non-owned share is visible, regardless of principals.
// Launched-container credentials resolve to the emulator default account, so a
// principal-based check would hide account-principal shares from the very Lambda
// they were shared with (LZA's Custom::GetResourceShare filters client-side by
// owningAccountId + name anyway).
return !owned;
if (owned) {
return false;
}
return share.getPrincipals().stream()
.anyMatch(principal -> isVisibleToPrincipal(share, principal, callerAccountId));
}
private boolean isVisibleToPrincipal(ResourceShare share, String principal, String callerAccountId) {
if (ACCOUNT_ID_PRINCIPAL.matcher(principal).matches()) {
if (!principal.equals(callerAccountId)) {
return false;
}
// A rejected or removed invitation is no longer an authorization to discover the
// share. PENDING remains visible because RAM exposes the invitation's share metadata
// before the receiver accepts it.
boolean hasLiveInvitation = allInvitations().stream()
.anyMatch(candidate -> candidate.resourceShareArn().equals(share.getResourceShareArn())
&& candidate.receiverAccountId().equals(callerAccountId)
&& ("PENDING".equals(candidate.status())
|| "ACCEPTED".equals(candidate.status())));
if (hasLiveInvitation) {
return true;
}
// Organization sharing auto-accepts account principals without persisting an
// invitation. Restrict that path to the owner's organization, never any organization.
return isSharingWithOrganizationEnabled(share.getOwningAccountId())
&& isMemberOfSameOrganization(share.getOwningAccountId(), callerAccountId);
}
return isOrganizationPrincipalVisible(principal, callerAccountId);
}
private boolean isOrganizationPrincipalVisible(String principal, String callerAccountId) {
if (organizationsService == null) {
return false;
}
String[] arn = principal.split(":", 6);
if (arn.length != 6 || !"aws".equals(arn[1]) || !"organizations".equals(arn[2])) {
return false;
}
String[] resource = arn[5].split("/");
if (resource.length < 2) {
return false;
}
Organization organization = findOrganizationForCaller(callerAccountId);
if (organization == null) {
return false;
}
if (!organization.getId().equals(resource[1])) {
return false;
}
if ("organization".equals(resource[0])) {
return resource.length == 2;
}
if (!"ou".equals(resource[0]) || resource.length != 3) {
return false;
}
try {
String path = organizationsService.organizationPath(callerAccountId, callerAccountId);
return List.of(path.split("/")).contains(resource[2]);
} catch (AwsException e) {
return false;
}
}
private boolean isMemberOfSameOrganization(String ownerAccountId, String callerAccountId) {
Organization ownerOrganization = findOrganizationForCaller(ownerAccountId);
Organization callerOrganization = findOrganizationForCaller(callerAccountId);
return ownerOrganization != null && callerOrganization != null
&& ownerOrganization.getId().equals(callerOrganization.getId());
}
private Organization findOrganizationForCaller(String callerAccountId) {
if (organizationsService == null) {
return null;
}
try {
return organizationsService.describeOrganization(callerAccountId);
} catch (AwsException e) {
return null;
}
}
/** {@code arn:aws:ec2:...:transit-gateway/tgw-1} → {@code ec2:TransitGateway}. */
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ram;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -24,6 +25,18 @@ class RamIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ram/aws4_request";
private static String authFor(String accountId) {
return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260101/us-east-1/ram/aws4_request";
}
private static RequestSpecification organizations(String accountId, String action, String body) {
return given()
.header("Authorization", authFor(accountId))
.header("X-Amz-Target", "AWSOrganizationsV20161128." + action)
.contentType("application/x-amz-json-1.1")
.body(body);
}
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
@@ -165,6 +178,179 @@ class RamIntegrationTest {
.body("returnValue", equalTo(true));
}
@Test
void readOperationsOnlyExposeAResourceShareToItsOwnerOrInvitedAccount() {
String shareArn =
given()
.contentType("application/json")
.header("Authorization", authFor("111111111111"))
.body("""
{
"name": "account-visible-share",
"principals": ["222222222222"],
"resourceArns": ["arn:aws:ec2:us-east-1:111111111111:transit-gateway/tgw-visibility"]
}
""")
.when()
.post("/createresourceshare")
.then()
.statusCode(200)
.extract().path("resourceShare.resourceShareArn");
given()
.contentType("application/json")
.header("Authorization", authFor("111111111111"))
.body("{ \"resourceOwner\": \"SELF\", \"resourceShareArns\": [\"%s\"] }".formatted(shareArn))
.when()
.post("/getresourceshares")
.then()
.statusCode(200)
.body("resourceShares.size()", equalTo(1));
for (String path : new String[] {"/getresourceshares", "/listresources", "/listprincipals"}) {
given()
.contentType("application/json")
.header("Authorization", authFor("222222222222"))
.body("{ \"resourceOwner\": \"OTHER-ACCOUNTS\", \"resourceShareArns\": [\"%s\"] }".formatted(shareArn))
.when()
.post(path)
.then()
.statusCode(200)
.body(path.equals("/getresourceshares") ? "resourceShares.size()"
: path.equals("/listresources") ? "resources.size()" : "principals.size()", equalTo(1));
given()
.contentType("application/json")
.header("Authorization", authFor("333333333333"))
.body("{ \"resourceOwner\": \"OTHER-ACCOUNTS\", \"resourceShareArns\": [\"%s\"] }".formatted(shareArn))
.when()
.post(path)
.then()
.statusCode(200)
.body(path.equals("/getresourceshares") ? "resourceShares.size()"
: path.equals("/listresources") ? "resources.size()" : "principals.size()", equalTo(0));
}
}
@Test
void organizationAndOuSharesOnlyReachMembers() {
String owner = "444444444444";
String organizationId =
organizations(owner, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("Organization.Id");
String rootId =
organizations(owner, "ListRoots", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("Roots[0].Id");
String ouArn =
organizations(owner, "CreateOrganizationalUnit",
"{\"ParentId\":\"%s\",\"Name\":\"RamVisibility\"}".formatted(rootId))
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("OrganizationalUnit.Arn");
String member =
organizations(owner, "CreateAccount",
"{\"Email\":\"ram-visibility-%s@example.com\",\"AccountName\":\"RamMember\"}"
.formatted(organizationId))
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateAccountStatus.AccountId");
String memberRoot = rootId;
organizations(owner, "MoveAccount",
"{\"AccountId\":\"%s\",\"SourceParentId\":\"%s\",\"DestinationParentId\":\"%s\"}"
.formatted(member, memberRoot, ouArn.substring(ouArn.lastIndexOf('/') + 1)))
.when()
.post("/")
.then()
.statusCode(200);
organizations(member, "DescribeOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Organization.Id", equalTo(organizationId));
String organizationArn = "arn:aws:organizations::" + owner + ":organization/" + organizationId;
String shareArn =
given()
.contentType("application/json")
.header("Authorization", authFor(owner))
.body(("{\"name\":\"organization-visible-share\",\"principals\":[\"%s\"],"
+ "\"resourceArns\":[\"arn:aws:ec2:us-east-1:%s:transit-gateway/tgw-org\"]}")
.formatted(organizationArn, owner))
.when()
.post("/createresourceshare")
.then()
.statusCode(200)
.extract().path("resourceShare.resourceShareArn");
assertShareVisibility(shareArn, member, true);
assertShareVisibility(shareArn, "666666666666", false);
given()
.header("Authorization", authFor(owner))
.when()
.post("/enablesharingwithawsorganization")
.then()
.statusCode(200);
String accountShareArn =
given()
.contentType("application/json")
.header("Authorization", authFor(owner))
.body(("{\"name\":\"organization-account-visible-share\",\"principals\":[\"%s\"],"
+ "\"resourceArns\":[\"arn:aws:ec2:us-east-1:%s:transit-gateway/tgw-account\"]}")
.formatted(member, owner))
.when()
.post("/createresourceshare")
.then()
.statusCode(200)
.extract().path("resourceShare.resourceShareArn");
assertShareVisibility(accountShareArn, member, true);
assertShareVisibility(accountShareArn, "666666666666", false);
String ouShareArn =
given()
.contentType("application/json")
.header("Authorization", authFor(owner))
.body(("{\"name\":\"ou-visible-share\",\"principals\":[\"%s\"],"
+ "\"resourceArns\":[\"arn:aws:ec2:us-east-1:%s:transit-gateway/tgw-ou\"]}")
.formatted(ouArn, owner))
.when()
.post("/createresourceshare")
.then()
.statusCode(200)
.extract().path("resourceShare.resourceShareArn");
assertShareVisibility(ouShareArn, member, true);
assertShareVisibility(ouShareArn, "666666666666", false);
}
private static void assertShareVisibility(String shareArn, String caller, boolean visible) {
given()
.contentType("application/json")
.header("Authorization", authFor(caller))
.body("{\"resourceOwner\":\"OTHER-ACCOUNTS\",\"resourceShareArns\":[\"%s\"]}"
.formatted(shareArn))
.when()
.post("/getresourceshares")
.then()
.statusCode(200)
.body("resourceShares.size()", equalTo(visible ? 1 : 0));
}
@Test
void getResourceSharesHonoursTheNameFilterOverHttp() {
given()
@@ -6,6 +6,8 @@ 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.SharedResource;
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
import io.github.hectorvent.floci.services.organizations.model.Organization;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
@@ -14,6 +16,9 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** Verifies RAM organization settings and cross-account resource shares survive a restart. */
class RamServicePersistenceTest {
@@ -27,7 +32,7 @@ class RamServicePersistenceTest {
void resourceSharesAndOrganizationSettingSurviveRestart() {
SharedStorageFactory storage = new SharedStorageFactory();
RamService first = serviceWithStorage(storage);
first.enableSharingWithAwsOrganization();
first.enableSharingWithAwsOrganization(OWNER);
ResourceShare created = first.createResourceShare(
"us-east-1-tgw-share",
List.of("arn:aws:organizations::000000000000:ou/o-abc/ou-infra"),
@@ -35,7 +40,7 @@ class RamServicePersistenceTest {
RamService reloaded = serviceWithStorage(storage);
assertTrue(reloaded.isSharingWithOrganizationEnabled());
assertTrue(reloaded.isSharingWithOrganizationEnabled(OWNER));
List<ResourceShare> owned = reloaded.getResourceShares(OWNER, "SELF");
assertEquals(1, owned.size());
assertEquals(created.getResourceShareArn(), owned.getFirst().getResourceShareArn());
@@ -50,7 +55,13 @@ class RamServicePersistenceTest {
}
private static RamService serviceWithStorage(StorageFactory storage) {
RamService service = new RamService(storage);
OrganizationsService organizations = mock(OrganizationsService.class);
Organization organization = new Organization();
organization.setId("o-abc");
when(organizations.describeOrganization(anyString())).thenReturn(organization);
when(organizations.organizationPath(anyString(), anyString()))
.thenReturn("o-abc/r-root/ou-infra/222222222222/");
RamService service = new RamService(storage, organizations);
service.initializeStorage();
return service;
}
@@ -8,6 +8,8 @@ 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 io.github.hectorvent.floci.services.organizations.OrganizationsService;
import io.github.hectorvent.floci.services.organizations.model.Organization;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
@@ -23,6 +25,9 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Resource-share semantics behind LZA's TGW share flow: the owning account creates a share
@@ -42,7 +47,13 @@ class RamServiceTest {
@BeforeEach
void setUp() {
service = new RamService(new SharedStorageFactory());
OrganizationsService organizations = mock(OrganizationsService.class);
Organization organization = new Organization();
organization.setId("o-abc123");
when(organizations.describeOrganization(anyString())).thenReturn(organization);
when(organizations.organizationPath(anyString(), anyString()))
.thenReturn("o-abc123/r-root/ou-root-infra/222222222222/");
service = new RamService(new SharedStorageFactory(), organizations);
service.initializeStorage();
}
@@ -109,15 +120,27 @@ class RamServiceTest {
}
@Test
void accountPrincipalShareIsVisibleToAnyNonOwningCaller() {
// LZA's Custom::GetResourceShare Lambda runs on launched-container placeholder
// credentials, so its caller resolves to the emulator default account rather than
// the function's account. OTHER-ACCOUNTS must therefore return every non-owned
// share and leave the narrowing to the Lambda's own owningAccountId+name filter.
void unrelatedCallerCannotSeeAnAccountPrincipalShare() {
service.createResourceShare(
"ipam-pool-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
assertEquals(1, service.getResourceShares("000000000000", "OTHER-ACCOUNTS").size());
assertTrue(service.getResourceShares("000000000000", "OTHER-ACCOUNTS").isEmpty());
assertTrue(service.listResources("000000000000", "OTHER-ACCOUNTS", List.of()).isEmpty());
assertTrue(service.listPrincipals("000000000000", "OTHER-ACCOUNTS", List.of()).isEmpty());
}
@Test
void rejectedInvitationNoLongerGrantsShareVisibility() {
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())
.getFirst().resourceShareInvitationArn();
service.rejectResourceShareInvitation(invitationArn, ACCEPTER);
assertTrue(service.getResourceShares(ACCEPTER, "OTHER-ACCOUNTS").isEmpty());
assertTrue(service.listResources(ACCEPTER, "OTHER-ACCOUNTS", List.of()).isEmpty());
assertTrue(service.listPrincipals(ACCEPTER, "OTHER-ACCOUNTS", List.of()).isEmpty());
}
@Test
@@ -329,7 +352,7 @@ class RamServiceTest {
@Test
void accountPrincipalUnderEnabledOrganizationSharingCreatesNoInvitation() {
service.enableSharingWithAwsOrganization();
service.enableSharingWithAwsOrganization(OWNER);
service.createResourceShare(
"direct-share", List.of(ACCEPTER), List.of(TGW_ARN), false, "us-east-1", OWNER);
@@ -404,6 +427,14 @@ class RamServiceTest {
service.getResourceShareInvitations(ACCEPTER, List.of(), List.of());
assertEquals(2, invitations.size());
assertTrue(invitations.stream().anyMatch(i -> "PENDING".equals(i.status())));
// The live invitation must keep the share visible even when the rejected historical
// invitation is returned first by storage scans.
assertEquals(1, service.getResourceShares(ACCEPTER, "OTHER-ACCOUNTS").size());
assertEquals(1, service.listResources(ACCEPTER, "OTHER-ACCOUNTS",
List.of(share.getResourceShareArn())).size());
assertEquals(1, service.listPrincipals(ACCEPTER, "OTHER-ACCOUNTS",
List.of(share.getResourceShareArn())).size());
}
@Test