feat(multitenancy): add per-account storage isolation across all services (#753)

Introduces multi-account isolation so that requests authenticated with
different AWS account IDs operate on completely separate resources,
with no cross-account data leakage.

- Add `RequestContext` (@RequestScoped CDI bean) to hold the current
  account ID for the duration of each HTTP request
- Add `AccountResolver` to extract a 12-digit numeric account ID from
  an AWS access key (AKID[4..15]), falling back to `defaultAccountId`
  for non-numeric or legacy keys
- Add `AccountContextFilter` (JAX-RS ContainerRequestFilter) to populate
  `RequestContext` on every incoming request
- Add `AccountAwareStorageBackend<V>` that transparently prefixes every
  storage key with the current account ID; provides explicit-account
  overloads (`getForAccount`, `putForAccount`, `scanAllAccounts`,
 `scanAllAccountsAsMap`, `keysForAccount`) for use by background
  workers that run outside request scope
- Update `StorageFactory` to always wrap created backends in
  `AccountAwareStorageBackend`, making isolation the default for all
  services with no per-service wiring required
- Update `RegionResolver.getAccountId()` to read from `RequestContext`,
  falling back to `defaultAccountId` outside request scope

Store `accountId` on model objects at creation time and use explicit-
account overloads in background pollers and schedulers to prevent
account overloads in background pollers and schedulers to prevent
cross-account data access:

- **SQS** — queue keys scoped per account; DLQ routing and ESM polling
  account-aware
- **SNS** — topic and subscription keys scoped per account
- **Lambda** — function store and ESM store account-aware; SQS, Kinesis,
  and DynamoDB Streams pollers use stored `accountId` for background reads
- **EventBridge** — rules, archives, and replays scoped per account;
  `RuleScheduler` uses rule's stored `accountId` for background dispatch
- **Kinesis** — stream keys and shard iterators scoped per account
- **Firehose** — delivery stream keys scoped per account
- **Pipes** — pipe keys scoped per account; poller uses stored `accountId`
- **Scheduler** — schedule and group keys scoped per account; dispatcher
  uses stored `accountId` for background execution
- **EKS** — cluster keys scoped per account; `accountId` stored on
 `Cluster` model (`@JsonIgnore`) for background use
- **MSK** — cluster keys scoped per account; readiness poller uses stored
  `accountId`; `accountId` stored on `MskCluster` model (`@JsonIgnore`)
- **ECR** — repository keys scoped per account via `effectiveAccount()`
  backed by `regionResolver`
- **OpenSearch** — domain keys scoped per account; readiness poller uses
  stored `accountId`; `accountId` stored on `Domain` model (`@JsonIgnore`)

Replace all occurrences of the hardcoded literal `"000000000000"` and
`config.defaultAccountId()` calls in ARN construction with
`regionResolver.getAccountId()` so that ARNs reflect the actual requesting
account:

- KMS — key ARNs and default key policy principal
- ELBv2 — load balancer, target group, listener, and rule ARNs
- AutoScaling — group, launch configuration, and policy ARNs
- API Gateway — VTL execution context `accountId`
- ElastiCache — user ARNs in DescribeUsers response
- CodeDeploy — application, deployment group, instance, and target ARNs
- CodeBuild — CloudWatch log group ARN
- Transfer — server and user ARNs
- S3 — ACL owner ID in GetBucketAcl / GetObjectAcl responses
- CloudFormation — stack ARN, changeset ARN, and `AWS::AccountId`
  pseudo-parameter; captures account at request time before handing
  off to executor thread
- DynamoDB TTL sweeper — use `scanAllAccountsAsMap()` so the background
  TTL sweep covers all accounts, not just the default

- Add `AccountIsolationIntegrationTest` verifying that SQS queues,
  DynamoDB tables, S3 buckets, Kinesis streams, EventBridge rules,
  Lambda functions, and Secrets Manager secrets created under one
  account are invisible when queried under a different account
- Update unit tests for EKS, MSK, ECR, Pipes, Scheduler, and Glue
  to pass `RegionResolver` through constructors (removes mock of
  `config.defaultAccountId()`)
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-05-09 08:02:24 -05:00
1 parent 7a036fdf59
commit 2bed9ec3ad
61 files changed
+1121 -215

No files matched your search

@@ -0,0 +1,183 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Verifies that resources are isolated between accounts.
* Uses 12-digit numeric access key IDs so they are used directly as account IDs.
*/
@QuarkusTest
class AccountIsolationIntegrationTest {
private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
// 12-digit numeric keys → used directly as account IDs
private static final String AUTH_ACCOUNT_1 =
"AWS4-HMAC-SHA256 Credential=000000000001/20260215/us-east-1/sqs/aws4_request, SignedHeaders=host, Signature=abc";
private static final String AUTH_ACCOUNT_2 =
"AWS4-HMAC-SHA256 Credential=000000000002/20260215/us-east-1/sqs/aws4_request, SignedHeaders=host, Signature=abc";
private static final String AUTH_ACCOUNT_1_SSM =
"AWS4-HMAC-SHA256 Credential=000000000001/20260215/us-east-1/ssm/aws4_request, SignedHeaders=host, Signature=abc";
private static final String AUTH_ACCOUNT_2_SSM =
"AWS4-HMAC-SHA256 Credential=000000000002/20260215/us-east-1/ssm/aws4_request, SignedHeaders=host, Signature=abc";
@Test
void sqsQueuesAreIsolatedBetweenAccounts() {
// Account 1 creates a queue
given()
.header("Authorization", AUTH_ACCOUNT_1)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", "account-isolation-queue")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("000000000001"))
.body(containsString("account-isolation-queue"));
// Account 2 lists queues — should NOT see account 1's queue
given()
.header("Authorization", AUTH_ACCOUNT_2)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListQueues")
.formParam("QueueNamePrefix", "account-isolation-queue")
.when().post("/")
.then()
.statusCode(200)
.body(not(containsString("account-isolation-queue")));
// Account 1 lists queues — should see its queue
given()
.header("Authorization", AUTH_ACCOUNT_1)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListQueues")
.formParam("QueueNamePrefix", "account-isolation-queue")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("account-isolation-queue"));
}
@Test
void sqsQueuesWithSameNameInDifferentAccountsAreIndependent() {
// Both accounts create a queue with the same name
given()
.header("Authorization", AUTH_ACCOUNT_1)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", "shared-name-queue")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("000000000001/shared-name-queue"));
given()
.header("Authorization", AUTH_ACCOUNT_2)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", "shared-name-queue")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("000000000002/shared-name-queue"));
// Account 1 sends a message to its queue
given()
.header("Authorization", AUTH_ACCOUNT_1)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage")
.formParam("QueueUrl", "http://localhost:8081/000000000001/shared-name-queue")
.formParam("MessageBody", "message-for-account-1")
.when().post("/")
.then()
.statusCode(200);
// Account 2 receives from its own queue — should get nothing (empty queue)
given()
.header("Authorization", AUTH_ACCOUNT_2)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ReceiveMessage")
.formParam("QueueUrl", "http://localhost:8081/000000000002/shared-name-queue")
.formParam("MaxNumberOfMessages", "1")
.formParam("WaitTimeSeconds", "0")
.when().post("/")
.then()
.statusCode(200)
.body(not(containsString("message-for-account-1")));
}
@Test
void ssmParametersAreIsolatedBetweenAccounts() {
// Account 1 puts a parameter
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.header("Authorization", AUTH_ACCOUNT_1_SSM)
.contentType(SSM_CONTENT_TYPE)
.body("""
{"Name": "/account-isolation/key", "Value": "value-for-account-1", "Type": "String"}
""")
.when().post("/")
.then()
.statusCode(200);
// Account 2 tries to get the same parameter — should not find it
given()
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.header("Authorization", AUTH_ACCOUNT_2_SSM)
.contentType(SSM_CONTENT_TYPE)
.body("""
{"Name": "/account-isolation/key"}
""")
.when().post("/")
.then()
.statusCode(400);
// Account 1 can retrieve its parameter, ARN contains its account ID
given()
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.header("Authorization", AUTH_ACCOUNT_1_SSM)
.contentType(SSM_CONTENT_TYPE)
.body("""
{"Name": "/account-isolation/key"}
""")
.when().post("/")
.then()
.statusCode(200)
.body("Parameter.Value", equalTo("value-for-account-1"))
.body("Parameter.ARN", containsString("000000000001"));
}
@Test
void sqsQueueArnContainsCorrectAccountId() {
given()
.header("Authorization", AUTH_ACCOUNT_1)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", "arn-account-check-queue")
.when().post("/")
.then().statusCode(200);
// GetQueueAttributes — QueueArn should embed account 1's ID
given()
.header("Authorization", AUTH_ACCOUNT_1)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueAttributes")
.formParam("QueueUrl", "http://localhost:8081/000000000001/arn-account-check-queue")
.formParam("AttributeName.1", "QueueArn")
.when().post("/")
.then()
.statusCode(200)
.body(containsString("arn:aws:sqs:us-east-1:000000000001:arn-account-check-queue"));
}
}
@@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(StorageFactoryServiceCatalogIntegrationTest.AcmPersistentStorageProfile.class)
@@ -26,7 +27,7 @@ class StorageFactoryServiceCatalogIntegrationTest {
new TypeReference<Map<String, String>>() {}
);
assertInstanceOf(PersistentStorage.class, backend);
assertInstanceOf(AccountAwareStorageBackend.class, backend);
}
public static final class AcmPersistentStorageProfile implements QuarkusTestProfile {
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ecr;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ecr.model.AuthorizationData;
import io.github.hectorvent.floci.services.ecr.model.ImageMetadata;
@@ -45,13 +46,14 @@ class EcrServiceTest {
// ensureStarted() is a no-op on the mock — no Docker calls in any test below.
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
service = new EcrService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
registryManager,
config);
config,
regionResolver);
}
// ------------------------------------------------------------
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.eks.model.ClusterStatus;
@@ -38,10 +39,10 @@ class EksServiceTest {
when(eksConfig.mock()).thenReturn(true);
when(eksConfig.apiServerBasePort()).thenReturn(6500);
when(config.defaultRegion()).thenReturn("us-east-1");
when(config.defaultAccountId()).thenReturn("000000000000");
clusterManager = Mockito.mock(EksClusterManager.class);
eksService = new EksService(storageFactory, config, clusterManager);
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
eksService = new EksService(storageFactory, config, regionResolver, clusterManager);
}
@Test
@@ -198,9 +198,9 @@ class GlueServiceTest {
}
@Override
public <K, V> StorageBackend<K, V> create(String serviceName,
String fileName,
TypeReference<Map<K, V>> typeReference) {
public <V> StorageBackend<String, V> create(String serviceName,
String fileName,
TypeReference<Map<String, V>> typeReference) {
return new InMemoryStorage<>();
}
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.msk;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.msk.model.ClusterState;
@@ -33,10 +34,12 @@ class MskServiceTest {
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.msk()).thenReturn(mskConfig);
when(mskConfig.mock()).thenReturn(true); // Mock mode for unit tests
when(mskConfig.mock()).thenReturn(true);
when(config.defaultRegion()).thenReturn("us-east-1");
redpandaManager = Mockito.mock(RedpandaManager.class);
mskService = new MskService(storageFactory, config, redpandaManager);
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
mskService = new MskService(storageFactory, config, regionResolver, redpandaManager);
}
@Test
@@ -1,7 +1,7 @@
package io.github.hectorvent.floci.services.pipes;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.pipes.model.DesiredState;
@@ -28,11 +28,10 @@ class PipesServiceTest {
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
.thenReturn(new InMemoryStorage<>());
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn("000000000000");
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
PipesPoller poller = Mockito.mock(PipesPoller.class);
pipesService = new PipesService(storageFactory, config, poller);
pipesService = new PipesService(storageFactory, regionResolver, poller);
}
@Test
@@ -91,11 +91,12 @@ class ScheduleDispatcherTest {
void deletesAtScheduleWhenActionAfterCompletionIsDelete() {
Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED");
s.setActionAfterCompletion("DELETE");
s.setAccountId("000000000000");
when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z"));
verify(schedulerService, times(1)).deleteSchedule("at1", "default", "eu-central-1");
verify(schedulerService, times(1)).deleteScheduleForAccount("000000000000", "at1", "default", "eu-central-1");
}
@Test