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,40 @@
package io.github.hectorvent.floci.core.common;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.ext.Provider;
/**
* Populates {@link RequestContext} with the account ID and region derived from
* the incoming AWS Authorization header. Runs at AUTHENTICATION priority so that
* downstream filters (e.g. IAM enforcement) can rely on the context being set.
*/
@Provider
@ApplicationScoped
@Priority(Priorities.AUTHENTICATION - 100)
public class AccountContextFilter implements ContainerRequestFilter {
private final AccountResolver accountResolver;
private final RegionResolver regionResolver;
private final RequestContext requestContext;
@Inject
public AccountContextFilter(AccountResolver accountResolver,
RegionResolver regionResolver,
RequestContext requestContext) {
this.accountResolver = accountResolver;
this.regionResolver = regionResolver;
this.requestContext = requestContext;
}
@Override
public void filter(ContainerRequestContext ctx) {
String auth = ctx.getHeaderString("Authorization");
requestContext.setAccountId(accountResolver.resolve(auth));
requestContext.setRegion(regionResolver.resolveRegionFromAuth(auth));
}
}
@@ -0,0 +1,47 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.config.EmulatorConfig;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ApplicationScoped
public class AccountResolver {
private static final Pattern AKID_PATTERN = Pattern.compile("Credential=([^/]+)/");
private final String defaultAccountId;
@Inject
public AccountResolver(EmulatorConfig config) {
this.defaultAccountId = config.defaultAccountId();
}
/**
* Returns the account ID for the given Authorization header.
* When the access key ID is exactly 12 digits it is used directly as the account ID,
* matching LocalStack's multi-account convention. Any other key format falls back to
* the configured default account.
*/
public String resolve(String authorizationHeader) {
String akid = extractAccessKeyId(authorizationHeader);
if (akid != null && akid.matches("\\d{12}")) {
return akid;
}
return defaultAccountId;
}
/**
* Extracts the raw access key ID from an AWS SigV4 Authorization header,
* or returns null if the header is absent or does not contain a Credential field.
*/
public String extractAccessKeyId(String authorizationHeader) {
if (authorizationHeader == null) {
return null;
}
Matcher m = AKID_PATTERN.matcher(authorizationHeader);
return m.find() ? m.group(1) : null;
}
}
@@ -41,15 +41,12 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private static final Logger LOG = Logger.getLogger(IamEnforcementFilter.class);
/** Extracts the access key ID from an AWS SigV4 Authorization header. */
private static final Pattern AKID_PATTERN =
Pattern.compile("Credential=([^/]+)/");
/** Extracts the credential-scope service name (e.g. "s3", "lambda"). */
private static final Pattern SERVICE_PATTERN =
Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
private final EmulatorConfig config;
private final AccountResolver accountResolver;
private final IamService iamService;
private final IamPolicyEvaluator evaluator;
private final IamActionRegistry actionRegistry;
@@ -57,11 +54,13 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
@Inject
public IamEnforcementFilter(EmulatorConfig config,
AccountResolver accountResolver,
IamService iamService,
IamPolicyEvaluator evaluator,
IamActionRegistry actionRegistry,
ResourceArnBuilder arnBuilder) {
this.config = config;
this.accountResolver = accountResolver;
this.iamService = iamService;
this.evaluator = evaluator;
this.actionRegistry = actionRegistry;
@@ -79,7 +78,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return;
}
String akid = extractAccessKeyId(auth);
String akid = accountResolver.extractAccessKeyId(auth);
if (akid == null || "test".equals(akid)) {
return; // root bypass
}
@@ -100,7 +99,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
String region = config.defaultRegion();
String accountId = config.defaultAccountId();
String accountId = accountResolver.resolve(auth);
String resource = arnBuilder.build(credentialScope, ctx, region, accountId);
Decision decision = evaluator.evaluate(policies, action, resource);
@@ -110,11 +109,6 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
}
private String extractAccessKeyId(String auth) {
Matcher m = AKID_PATTERN.matcher(auth);
return m.find() ? m.group(1) : null;
}
private String extractCredentialScope(String auth) {
Matcher m = SERVICE_PATTERN.matcher(auth);
return m.find() ? m.group(1) : null;
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.config.EmulatorConfig;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.ContextNotActiveException;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.HttpHeaders;
@@ -18,6 +20,10 @@ public class RegionResolver {
private final String defaultRegion;
private final String defaultAccountId;
// Field-injected so the two-arg constructor used in tests remains valid.
@Inject
Instance<RequestContext> requestContextInstance;
@Inject
public RegionResolver(EmulatorConfig config) {
this(config.defaultRegion(), config.defaultAccountId());
@@ -32,26 +38,40 @@ public class RegionResolver {
if (headers == null) {
return defaultRegion;
}
String auth = headers.getHeaderString("Authorization");
if (auth == null || auth.isEmpty()) {
return resolveRegionFromAuth(headers.getHeaderString("Authorization"));
}
public String resolveRegionFromAuth(String authorizationHeader) {
if (authorizationHeader == null || authorizationHeader.isEmpty()) {
return defaultRegion;
}
Matcher matcher = CREDENTIAL_REGION_PATTERN.matcher(auth);
if (matcher.find()) {
return matcher.group(1);
}
return defaultRegion;
Matcher matcher = CREDENTIAL_REGION_PATTERN.matcher(authorizationHeader);
return matcher.find() ? matcher.group(1) : defaultRegion;
}
public String getDefaultRegion() {
return defaultRegion;
}
/**
* Returns the account ID for the current request when called from a request context,
* or the configured default account ID otherwise (async workers, startup, tests).
*/
public String getAccountId() {
if (requestContextInstance != null) {
try {
String accountId = requestContextInstance.get().getAccountId();
if (accountId != null) {
return accountId;
}
} catch (ContextNotActiveException ignored) {
// outside request scope — fall through to default
}
}
return defaultAccountId;
}
public String buildArn(String service, String region, String resource) {
return AwsArnUtils.Arn.of(service, region, defaultAccountId, resource).toString();
return AwsArnUtils.Arn.of(service, region, getAccountId(), resource).toString();
}
}
@@ -0,0 +1,31 @@
package io.github.hectorvent.floci.core.common;
import jakarta.enterprise.context.RequestScoped;
/**
* Holds per-request derived values — account ID and region — extracted from the
* incoming AWS credential and Authorization header. Populated by
* {@link AccountContextFilter} before any handler runs.
*/
@RequestScoped
public class RequestContext {
private String accountId;
private String region;
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
@@ -0,0 +1,168 @@
package io.github.hectorvent.floci.core.storage;
import io.github.hectorvent.floci.core.common.RequestContext;
import jakarta.enterprise.context.ContextNotActiveException;
import jakarta.enterprise.inject.Instance;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Decorator over {@link StorageBackend} that transparently prefixes every storage key
* with the current account ID, providing per-account resource isolation.
*
* <p>On the synchronous request path the account ID is read from {@link RequestContext},
* which is populated by {@code AccountContextFilter} before any handler runs.
* Outside a request (async workers, startup) the {@code defaultAccountId} is used.
*
* <p>Async workers that must access a specific account's data should use the explicit
* {@code *ForAccount} overloads, passing the account ID stored on the resource model.
*
* <p>Backward compatibility: on a {@link #get} miss for the prefixed key, the un-prefixed
* key is tried and the entry is migrated on read. This covers existing persistent/WAL data
* created before multi-account support was added.
*/
public class AccountAwareStorageBackend<V> implements StorageBackend<String, V> {
private final StorageBackend<String, V> delegate;
private final Instance<RequestContext> requestContextInstance;
private final String defaultAccountId;
public AccountAwareStorageBackend(StorageBackend<String, V> delegate,
Instance<RequestContext> requestContextInstance,
String defaultAccountId) {
this.delegate = delegate;
this.requestContextInstance = requestContextInstance;
this.defaultAccountId = defaultAccountId;
}
@Override
public void put(String key, V value) {
delegate.put(prefixed(key), value);
}
@Override
public Optional<V> get(String key) {
String prefixedKey = prefixed(key);
Optional<V> result = delegate.get(prefixedKey);
if (result.isPresent()) {
return result;
}
// Backward-compat: try un-prefixed key (pre-multi-account data) and migrate on read.
result = delegate.get(key);
if (result.isPresent()) {
delegate.put(prefixedKey, result.get());
delegate.delete(key);
}
return result;
}
@Override
public void delete(String key) {
delegate.delete(prefixed(key));
}
@Override
public List<V> scan(Predicate<String> keyFilter) {
String prefix = prefix() + "/";
return delegate.scan(k -> k.startsWith(prefix) && keyFilter.test(k.substring(prefix.length())));
}
@Override
public Set<String> keys() {
String prefix = prefix() + "/";
return delegate.keys().stream()
.filter(k -> k.startsWith(prefix))
.map(k -> k.substring(prefix.length()))
.collect(Collectors.toUnmodifiableSet());
}
@Override
public void flush() {
delegate.flush();
}
@Override
public void load() {
delegate.load();
}
@Override
public void clear() {
delegate.clear();
}
// --- Explicit-account methods for async workers ---
/** Scans all values across every account, without any account prefix filtering. */
public List<V> scanAllAccounts() {
return delegate.scan(k -> true);
}
/**
* Returns all entries across every account as a map of logical-key (account prefix stripped)
* to value. Entries without a slash-prefixed account segment are skipped.
*/
public Map<String, V> scanAllAccountsAsMap() {
Map<String, V> result = new LinkedHashMap<>();
for (String rawKey : delegate.keys()) {
int slash = rawKey.indexOf('/');
if (slash < 0) {
continue;
}
String logicalKey = rawKey.substring(slash + 1);
delegate.get(rawKey).ifPresent(v -> result.put(logicalKey, v));
}
return result;
}
public Optional<V> getForAccount(String accountId, String key) {
return delegate.get(accountId + "/" + key);
}
public void putForAccount(String accountId, String key, V value) {
delegate.put(accountId + "/" + key, value);
}
public void deleteForAccount(String accountId, String key) {
delegate.delete(accountId + "/" + key);
}
public List<V> scanForAccount(String accountId, Predicate<String> keyFilter) {
String prefix = accountId + "/";
return delegate.scan(k -> k.startsWith(prefix) && keyFilter.test(k.substring(prefix.length())));
}
public Set<String> keysForAccount(String accountId) {
String prefix = accountId + "/";
return delegate.keys().stream()
.filter(k -> k.startsWith(prefix))
.map(k -> k.substring(prefix.length()))
.collect(Collectors.toUnmodifiableSet());
}
// ---
private String prefix() {
if (requestContextInstance != null) {
try {
String accountId = requestContextInstance.get().getAccountId();
if (accountId != null) {
return accountId;
}
} catch (ContextNotActiveException ignored) {
// outside request scope — fall through to default
}
}
return defaultAccountId;
}
private String prefixed(String key) {
return prefix() + "/" + key;
}
}
@@ -1,9 +1,11 @@
package io.github.hectorvent.floci.core.storage;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -13,7 +15,9 @@ import java.util.List;
import java.util.Map;
/**
* Factory that creates StorageBackend instances based on configuration.
* Factory that creates {@link AccountAwareStorageBackend} instances based on configuration.
* Every backend is wrapped in an account-aware decorator so resources are automatically
* namespaced by the account ID of the calling credential.
* Tracks all created backends for lifecycle management.
*/
@ApplicationScoped
@@ -27,6 +31,9 @@ public class StorageFactory {
private final List<HybridStorage<?, ?>> hybridBackends = new ArrayList<>();
private final List<WalStorage<?, ?>> walBackends = new ArrayList<>();
@Inject
Instance<RequestContext> requestContextInstance;
@Inject
public StorageFactory(EmulatorConfig config, ServiceConfigAccess serviceConfigAccess) {
this.config = config;
@@ -34,14 +41,17 @@ public class StorageFactory {
}
/**
* Create a storage backend for the given service.
* Create an account-aware storage backend for the given service.
* All keys are automatically prefixed with the current account ID derived from
* the request credential. Async workers should use the {@code *ForAccount} overloads
* on {@link AccountAwareStorageBackend} with the account ID stored on the resource model.
*
* @param serviceName the service name (ssm, sqs, s3)
* @param serviceName the service name (ssm, sqs, s3, …)
* @param fileName the JSON file name for persistent storage
* @param typeReference Jackson type reference for deserialization
*/
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) {
String mode = resolveMode(serviceName);
long flushInterval = resolveFlushInterval(serviceName);
Path basePath = Path.of(config.storage().persistentPath());
@@ -49,7 +59,7 @@ public class StorageFactory {
LOG.infov("Creating {0} storage for service {1} (file: {2})", mode, serviceName, filePath);
StorageBackend<K, V> backend = switch (mode) {
StorageBackend<String, V> inner = switch (mode) {
case "memory" -> new InMemoryStorage<>();
case "persistent" -> new PersistentStorage<>(filePath, typeReference);
case "hybrid" -> {
@@ -68,9 +78,10 @@ public class StorageFactory {
default -> throw new IllegalArgumentException("Unknown storage mode: " + mode);
};
// load because loadAll() may run before the service is initialized
backend.load();
inner.load();
AccountAwareStorageBackend<V> backend = new AccountAwareStorageBackend<>(
inner, requestContextInstance, config.defaultAccountId());
allBackends.add(backend);
return backend;
}
@@ -618,7 +618,7 @@ public class ApiGatewayExecuteController {
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
resource.getPath(), requestId, "000000000000", null);
resource.getPath(), requestId, regionResolver.getAccountId(), null);
// Apply request parameter mapping (method.request.* → integration.request.*)
Map<String, String> integrationReqParams = integration.getRequestParameters();
@@ -789,7 +789,7 @@ public class ApiGatewayExecuteController {
if (responseTemplate != null && !responseTemplate.isEmpty()) {
VtlTemplateEngine.VtlContext responseMappingCtx = new VtlTemplateEngine.VtlContext(
responseBodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
resource.getPath(), requestId, "000000000000", null);
resource.getPath(), requestId, regionResolver.getAccountId(), null);
templateResult = vtlEngine.evaluate(responseTemplate, responseMappingCtx);
finalBody = templateResult.body();
} else {
@@ -924,7 +924,7 @@ public class ApiGatewayExecuteController {
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
resource.getPath(), requestId, "000000000000", null);
resource.getPath(), requestId, regionResolver.getAccountId(), null);
VtlTemplateEngine.EvaluateResult result = vtlEngine.evaluate(template, vtlCtx);
@@ -1136,7 +1136,7 @@ public class ApiGatewayExecuteController {
}
ObjectNode ctx = event.putObject("requestContext");
ctx.put("accountId", "000000000000");
ctx.put("accountId", regionResolver.getAccountId());
ctx.put("apiId", apiId);
ctx.put("domainName", apiId + ".execute-api.us-east-1.amazonaws.com");
ctx.put("domainPrefix", apiId);
@@ -2,8 +2,10 @@ package io.github.hectorvent.floci.services.autoscaling;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.autoscaling.model.*;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Instant;
import java.util.*;
@@ -13,7 +15,8 @@ import java.util.stream.Collectors;
@ApplicationScoped
public class AutoScalingService {
private static final String DEFAULT_ACCOUNT = "000000000000";
@Inject
RegionResolver regionResolver;
// region :: name → resource
private final Map<String, LaunchConfiguration> launchConfigs = new ConcurrentHashMap<>();
@@ -37,7 +40,7 @@ public class AutoScalingService {
LaunchConfiguration lc = new LaunchConfiguration();
lc.setLaunchConfigurationName(name);
lc.setLaunchConfigurationArn(
AwsArnUtils.Arn.of("autoscaling", region, DEFAULT_ACCOUNT,
AwsArnUtils.Arn.of("autoscaling", region, regionResolver.getAccountId(),
"launchConfiguration:" + name).toString());
lc.setImageId(imageId);
lc.setInstanceType(instanceType != null ? instanceType : "t3.micro");
@@ -95,7 +98,7 @@ public class AutoScalingService {
AutoScalingGroup asg = new AutoScalingGroup();
asg.setAutoScalingGroupName(name);
asg.setAutoScalingGroupArn(
AwsArnUtils.Arn.of("autoscaling", region, DEFAULT_ACCOUNT,
AwsArnUtils.Arn.of("autoscaling", region, regionResolver.getAccountId(),
"autoScalingGroup:" + name).toString());
asg.setLaunchConfigurationName(launchConfigName);
asg.setLaunchTemplateName(launchTemplateName);
@@ -324,7 +327,7 @@ public class AutoScalingService {
String key = policyKey(region, asgName, policyName);
ScalingPolicy policy = policies.computeIfAbsent(key, k -> new ScalingPolicy());
policy.setPolicyName(policyName);
policy.setPolicyArn(AwsArnUtils.Arn.of("autoscaling", region, DEFAULT_ACCOUNT,
policy.setPolicyArn(AwsArnUtils.Arn.of("autoscaling", region, regionResolver.getAccountId(),
"scalingPolicy:" + asgName + ":" + policyName).toString());
policy.setAutoScalingGroupName(asgName);
policy.setPolicyType(policyType != null ? policyType : "SimpleScaling");
@@ -149,7 +149,7 @@ public class CloudFormationResourceProvisioner {
case "AWS::CDK::Metadata" -> provisionCdkMetadata(resource);
case "AWS::S3::BucketPolicy" -> provisionS3BucketPolicy(resource, properties, engine);
case "AWS::SQS::QueuePolicy" -> provisionSqsQueuePolicy(resource, properties, engine);
case "AWS::ECR::Repository" -> provisionEcrRepository(resource, properties, engine, stackName);
case "AWS::ECR::Repository" -> provisionEcrRepository(resource, properties, engine, stackName, region);
case "AWS::Route53::HostedZone" -> provisionRoute53HostedZone(resource, properties, engine);
case "AWS::Route53::RecordSet" -> provisionRoute53RecordSet(resource, properties, engine);
case "AWS::Events::Rule" -> provisionEventBridgeRule(resource, properties, engine, region, stackName);
@@ -202,7 +202,7 @@ public class CloudFormationResourceProvisioner {
case "AWS::ApiGateway::RestApi" -> apiGatewayService.deleteRestApi(region, physicalId);
case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId);
case "AWS::ECR::Repository" ->
ecrService.deleteRepository(physicalId, null, true, "us-east-1");
ecrService.deleteRepository(physicalId, null, true, region);
case "AWS::Pipes::Pipe" -> pipesService.deletePipe(physicalId, region);
case "AWS::Lambda::EventSourceMapping" -> lambdaService.deleteEventSourceMapping(physicalId);
default -> LOG.debugv("Skipping delete of unsupported resource type: {0}", resourceType);
@@ -1299,7 +1299,7 @@ public class CloudFormationResourceProvisioner {
}
private void provisionEcrRepository(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String stackName) {
String stackName, String region) {
String repoName = resolveOptional(props, "RepositoryName", engine);
if (repoName == null || repoName.isBlank()) {
repoName = generatePhysicalName(stackName, r.getLogicalId(), 256, true);
@@ -1313,10 +1313,10 @@ public class CloudFormationResourceProvisioner {
Repository repo;
try {
repo = ecrService.createRepository(repoName, null, mutability, null, null, null, tags, "us-east-1");
repo = ecrService.createRepository(repoName, null, mutability, null, null, null, tags, region);
} catch (AwsException e) {
if ("RepositoryAlreadyExistsException".equals(e.getErrorCode())) {
repo = ecrService.describeRepositories(List.of(repoName), null, "us-east-1").get(0);
repo = ecrService.describeRepositories(List.of(repoName), null, region).get(0);
} else {
throw e;
}
@@ -1327,14 +1327,14 @@ public class CloudFormationResourceProvisioner {
JsonNode lp = engine.resolveNode(props.get("LifecyclePolicy"));
String policyText = lp.path("LifecyclePolicyText").asText(null);
if (policyText != null && !policyText.isEmpty()) {
ecrService.putLifecyclePolicy(repoName, null, policyText, "us-east-1");
ecrService.putLifecyclePolicy(repoName, null, policyText, region);
}
}
if (props != null && props.has("RepositoryPolicyText")) {
JsonNode pol = engine.resolveNode(props.get("RepositoryPolicyText"));
String policyText = pol.isTextual() ? pol.asText() : pol.toString();
if (policyText != null && !policyText.isEmpty()) {
ecrService.setRepositoryPolicy(repoName, null, policyText, "us-east-1");
ecrService.setRepositoryPolicy(repoName, null, policyText, region);
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
@@ -42,14 +43,17 @@ public class CloudFormationService {
private final S3Service s3Service;
private final ObjectMapper objectMapper;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
@Inject
public CloudFormationService(CloudFormationResourceProvisioner provisioner, S3Service s3Service,
ObjectMapper objectMapper, EmulatorConfig config) {
ObjectMapper objectMapper, EmulatorConfig config,
RegionResolver regionResolver) {
this.provisioner = provisioner;
this.s3Service = s3Service;
this.objectMapper = objectMapper;
this.config = config;
this.regionResolver = regionResolver;
}
// ── DescribeStacks ────────────────────────────────────────────────────────
@@ -84,7 +88,7 @@ public class CloudFormationService {
});
ChangeSet cs = new ChangeSet();
cs.setChangeSetId(AwsArnUtils.Arn.of("cloudformation", region, config.defaultAccountId(), "changeSet/" + changeSetName + "/" + UUID.randomUUID()).toString());
cs.setChangeSetId(AwsArnUtils.Arn.of("cloudformation", region, regionResolver.getAccountId(), "changeSet/" + changeSetName + "/" + UUID.randomUUID()).toString());
cs.setChangeSetName(changeSetName);
cs.setStackName(stackName);
cs.setStackId(stack.getStackId());
@@ -132,7 +136,8 @@ public class CloudFormationService {
String templateBody = cs.getTemplateBody();
Map<String, String> params = cs.getParameters() != null ? cs.getParameters() : Map.of();
return executor.submit(() -> executeTemplate(stack, templateBody, params, isCreate, region));
String accountId = regionResolver.getAccountId();
return executor.submit(() -> executeTemplate(stack, templateBody, params, isCreate, region, accountId));
}
// ── DeleteChangeSet ───────────────────────────────────────────────────────
@@ -252,7 +257,7 @@ public class CloudFormationService {
}
private void executeTemplate(Stack stack, String templateBody, Map<String, String> params,
boolean isCreate, String region) {
boolean isCreate, String region, String accountId) {
try {
JsonNode template = parseTemplate(templateBody);
stack.setTemplateBody(templateBody);
@@ -261,7 +266,7 @@ public class CloudFormationService {
Map<String, String> resolvedParams = resolveDefaultParameters(template, params);
// Resolve conditions first
Map<String, Boolean> conditions = resolveConditions(template, resolvedParams, stack, region);
Map<String, Boolean> conditions = resolveConditions(template, resolvedParams, stack, region, accountId);
// Mappings
Map<String, JsonNode> mappings = new HashMap<>();
@@ -289,7 +294,7 @@ public class CloudFormationService {
JsonNode props = resDef.path("Properties");
CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine(
config.defaultAccountId(), region, stack.getStackName(),
accountId, region, stack.getStackName(),
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper,
name -> exports.get(exportKey(region, name)));
@@ -303,7 +308,7 @@ public class CloudFormationService {
addEvent(stack, logicalId, null, type, "CREATE_IN_PROGRESS", null);
resource = provisioner.provision(logicalId, type, props.isMissingNode() ? null : props,
engine, region, config.defaultAccountId(), stack.getStackName(),
engine, region, accountId, stack.getStackName(),
resource.getPhysicalId(), resource.getAttributes());
stack.getResources().put(logicalId, resource);
@@ -316,7 +321,7 @@ public class CloudFormationService {
}
CloudFormationTemplateEngine finalEngine = new CloudFormationTemplateEngine(
config.defaultAccountId(), region, stack.getStackName(),
accountId, region, stack.getStackName(),
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper,
name -> exports.get(exportKey(region, name)));
@@ -405,7 +410,7 @@ public class CloudFormationService {
}
private Map<String, Boolean> resolveConditions(JsonNode template, Map<String, String> params,
Stack stack, String region) {
Stack stack, String region, String accountId) {
Map<String, Boolean> conditions = new HashMap<>();
JsonNode condNode = template.path("Conditions");
if (!condNode.isObject()) {
@@ -414,12 +419,12 @@ public class CloudFormationService {
// Two-pass: collect all names first, then evaluate (handles forward references)
condNode.fields().forEachRemaining(e -> conditions.put(e.getKey(), false));
condNode.fields().forEachRemaining(e ->
conditions.put(e.getKey(), evaluateCondition(e.getValue(), params, conditions)));
conditions.put(e.getKey(), evaluateCondition(e.getValue(), params, conditions, region, accountId)));
return conditions;
}
private boolean evaluateCondition(JsonNode expr, Map<String, String> params,
Map<String, Boolean> conditions) {
Map<String, Boolean> conditions, String region, String accountId) {
if (expr == null || expr.isNull()) {
return false;
}
@@ -433,20 +438,20 @@ public class CloudFormationService {
if (expr.has("Fn::Equals")) {
JsonNode args = expr.get("Fn::Equals");
if (args.isArray() && args.size() == 2) {
String left = resolveConditionValue(args.get(0), params);
String right = resolveConditionValue(args.get(1), params);
String left = resolveConditionValue(args.get(0), params, region, accountId);
String right = resolveConditionValue(args.get(1), params, region, accountId);
return left.equals(right);
}
}
if (expr.has("Fn::Not")) {
JsonNode args = expr.get("Fn::Not");
if (args.isArray() && !args.isEmpty()) {
return !evaluateCondition(args.get(0), params, conditions);
return !evaluateCondition(args.get(0), params, conditions, region, accountId);
}
}
if (expr.has("Fn::And")) {
for (JsonNode item : expr.get("Fn::And")) {
if (!evaluateCondition(item, params, conditions)) {
if (!evaluateCondition(item, params, conditions, region, accountId)) {
return false;
}
}
@@ -454,7 +459,7 @@ public class CloudFormationService {
}
if (expr.has("Fn::Or")) {
for (JsonNode item : expr.get("Fn::Or")) {
if (evaluateCondition(item, params, conditions)) {
if (evaluateCondition(item, params, conditions, region, accountId)) {
return true;
}
}
@@ -464,15 +469,16 @@ public class CloudFormationService {
return false;
}
private String resolveConditionValue(JsonNode node, Map<String, String> params) {
private String resolveConditionValue(JsonNode node, Map<String, String> params,
String region, String accountId) {
if (node.isTextual()) {
return node.textValue();
}
if (node.isObject() && node.has("Ref")) {
String name = node.get("Ref").asText();
return switch (name) {
case "AWS::AccountId" -> config.defaultAccountId();
case "AWS::Region" -> "us-east-1";
case "AWS::AccountId" -> accountId;
case "AWS::Region" -> region;
case "AWS::NoValue" -> "";
default -> params.getOrDefault(name, "");
};
@@ -561,7 +567,7 @@ public class CloudFormationService {
stack.setStackName(stackName);
stack.setRegion(region);
stack.setStatus("REVIEW_IN_PROGRESS");
String stackId = AwsArnUtils.Arn.of("cloudformation", region, config.defaultAccountId(), "stack/" + stackName + "/" + UUID.randomUUID()).toString();
String stackId = AwsArnUtils.Arn.of("cloudformation", region, regionResolver.getAccountId(), "stack/" + stackName + "/" + UUID.randomUUID()).toString();
stack.setStackId(stackId);
stack.setCreationTime(Instant.now());
return stack;
@@ -5,6 +5,7 @@ import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
@@ -66,6 +67,7 @@ public class CodeBuildRunner {
private final SecretsManagerService secretsManagerService;
private final EmulatorConfig config;
private final ContainerDetector containerDetector;
private final RegionResolver regionResolver;
private final ConcurrentHashMap<String, String> runningContainers = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, AtomicBoolean> stopFlags = new ConcurrentHashMap<>();
@@ -79,7 +81,8 @@ public class CodeBuildRunner {
SsmService ssmService,
SecretsManagerService secretsManagerService,
EmulatorConfig config,
ContainerDetector containerDetector) {
ContainerDetector containerDetector,
RegionResolver regionResolver) {
this.dockerClient = dockerClient;
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
@@ -89,6 +92,7 @@ public class CodeBuildRunner {
this.secretsManagerService = secretsManagerService;
this.config = config;
this.containerDetector = containerDetector;
this.regionResolver = regionResolver;
}
public void startBuild(String region, Build build, Project project, String buildspecOverride) {
@@ -181,7 +185,7 @@ public class CodeBuildRunner {
Map<String, Object> logsMap = new java.util.HashMap<>();
logsMap.put("groupName", logGroup);
logsMap.put("streamName", logStream);
logsMap.put("cloudWatchLogsArn", AwsArnUtils.Arn.of("logs", region, config.defaultAccountId(), "log-group:" + logGroup + ":log-stream:" + logStream).toString());
logsMap.put("cloudWatchLogsArn", AwsArnUtils.Arn.of("logs", region, regionResolver.getAccountId(), "log-group:" + logGroup + ":log-stream:" + logStream).toString());
build.setLogs(logsMap);
List<String> envList = buildEnvList(region, build, project, buildspec, logStream);
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.codedeploy.model.Application;
import io.github.hectorvent.floci.services.codedeploy.model.Deployment;
import io.github.hectorvent.floci.services.codedeploy.model.DeploymentConfig;
@@ -48,11 +49,12 @@ public class CodeDeployService {
private final Ec2Service ec2Service;
private final ObjectMapper mapper;
private final ObjectMapper yamlMapper;
private final RegionResolver regionResolver;
@Inject
public CodeDeployService(LambdaService lambdaService, EcsService ecsService,
ElbV2Service elbV2Service, SsmCommandService ssmCommandService,
Ec2Service ec2Service, ObjectMapper mapper) {
Ec2Service ec2Service, ObjectMapper mapper, RegionResolver regionResolver) {
this.lambdaService = lambdaService;
this.ecsService = ecsService;
this.elbV2Service = elbV2Service;
@@ -60,6 +62,7 @@ public class CodeDeployService {
this.ec2Service = ec2Service;
this.mapper = mapper;
this.yamlMapper = new ObjectMapper(new YAMLFactory());
this.regionResolver = regionResolver;
}
// key: region -> name -> application
@@ -478,7 +481,7 @@ public class CodeDeployService {
// Build initial target map
String targetId = appSpec.functionName + ":" + appSpec.aliasName;
String targetArn = AwsArnUtils.Arn.of("lambda", region, "000000000000", "function:" + appSpec.functionName + ":" + appSpec.aliasName).toString();
String targetArn = AwsArnUtils.Arn.of("lambda", region, regionResolver.getAccountId(), "function:" + appSpec.functionName + ":" + appSpec.aliasName).toString();
Map<String, Object> lambdaTargetMap = new ConcurrentHashMap<>();
lambdaTargetMap.put("deploymentId", deploymentId);
lambdaTargetMap.put("targetId", targetId);
@@ -591,7 +594,7 @@ public class CodeDeployService {
Map<String, OnPremisesInstance> store = onPremisesFor(region);
OnPremisesInstance inst = new OnPremisesInstance();
inst.setInstanceName(instanceName);
inst.setInstanceArn(AwsArnUtils.Arn.of("codedeploy", region, "000000000000",
inst.setInstanceArn(AwsArnUtils.Arn.of("codedeploy", region, regionResolver.getAccountId(),
"instance/" + instanceName).toString());
inst.setIamSessionArn(iamSessionArn);
inst.setIamUserArn(iamUserArn);
@@ -1142,7 +1145,7 @@ public class CodeDeployService {
}
String targetId = clusterName + ":" + serviceName;
String targetArn = AwsArnUtils.Arn.of("ecs", region, "000000000000", "service/" + clusterName + "/" + serviceName).toString();
String targetArn = AwsArnUtils.Arn.of("ecs", region, regionResolver.getAccountId(), "service/" + clusterName + "/" + serviceName).toString();
Map<String, Object> ecsTargetMap = new ConcurrentHashMap<>();
ecsTargetMap.put("deploymentId", deploymentId);
@@ -1643,11 +1646,11 @@ public class CodeDeployService {
}
public String applicationArn(String region, String name) {
return AwsArnUtils.Arn.of("codedeploy", region, "000000000000", "application:" + name).toString();
return AwsArnUtils.Arn.of("codedeploy", region, regionResolver.getAccountId(), "application:" + name).toString();
}
public String deploymentGroupArn(String region, String appName, String groupName) {
return AwsArnUtils.Arn.of("codedeploy", region, "000000000000", "deploymentgroup:" + appName + "/" + groupName).toString();
return AwsArnUtils.Arn.of("codedeploy", region, regionResolver.getAccountId(), "deploymentgroup:" + appName + "/" + groupName).toString();
}
@SuppressWarnings("unchecked")
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
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.dynamodb.model.AttributeDefinition;
@@ -994,9 +995,17 @@ public class DynamoDbService {
void deleteExpiredItems() {
int totalDeleted = 0;
for (String storageKey : tableStore.keys()) {
TableDefinition table = tableStore.get(storageKey).orElse(null);
if (table == null || !table.isTtlEnabled() || table.getTtlAttributeName() == null) {
Map<String, TableDefinition> allTables;
if (tableStore instanceof AccountAwareStorageBackend<TableDefinition> aware) {
allTables = aware.scanAllAccountsAsMap();
} else {
allTables = new HashMap<>();
tableStore.keys().forEach(k -> tableStore.get(k).ifPresent(v -> allTables.put(k, v)));
}
for (Map.Entry<String, TableDefinition> entry : allTables.entrySet()) {
String storageKey = entry.getKey();
TableDefinition table = entry.getValue();
if (!table.isTtlEnabled() || table.getTtlAttributeName() == null) {
continue;
}
var items = itemsByTable.get(storageKey);
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.ecr;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -39,26 +40,30 @@ public class EcrService {
private final StorageBackend<String, ImageMetadata> imageMetaStore;
private final EcrRegistryManager registryManager;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
@Inject
public EcrService(StorageFactory factory,
EcrRegistryManager registryManager,
EmulatorConfig config) {
EmulatorConfig config,
RegionResolver regionResolver) {
this(factory.create("ecr", "repositories.json",
new TypeReference<Map<String, Repository>>() {}),
factory.create("ecr", "image-metadata.json",
new TypeReference<Map<String, ImageMetadata>>() {}),
registryManager, config);
registryManager, config, regionResolver);
}
EcrService(StorageBackend<String, Repository> repoStore,
StorageBackend<String, ImageMetadata> imageMetaStore,
EcrRegistryManager registryManager,
EmulatorConfig config) {
EmulatorConfig config,
RegionResolver regionResolver) {
this.repoStore = repoStore;
this.imageMetaStore = imageMetaStore;
this.registryManager = registryManager;
this.config = config;
this.regionResolver = regionResolver;
this.registryManager.setReconcileHook(this::reconcileFromCatalog);
}
@@ -520,7 +525,7 @@ public class EcrService {
if (registryId != null && !registryId.isBlank()) {
return registryId;
}
return config.defaultAccountId();
return regionResolver.getAccountId();
}
private static void validateRepoName(String name) {
@@ -3,7 +3,9 @@ package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.TagHandler;
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.eks.model.CertificateAuthority;
@@ -35,14 +37,17 @@ public class EksService implements TagHandler {
private final StorageBackend<String, Cluster> storage;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final EksClusterManager clusterManager;
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
@Inject
public EksService(StorageFactory storageFactory, EmulatorConfig config, EksClusterManager clusterManager) {
public EksService(StorageFactory storageFactory, EmulatorConfig config,
RegionResolver regionResolver, EksClusterManager clusterManager) {
this.storage = storageFactory.create("eks", "eks-clusters.json",
new TypeReference<Map<String, Cluster>>() {});
this.config = config;
this.regionResolver = regionResolver;
this.clusterManager = clusterManager;
}
@@ -57,7 +62,7 @@ public class EksService implements TagHandler {
public void shutdown() {
poller.shutdownNow();
if (!config.services().eks().mock()) {
for (Cluster cluster : storage.scan(k -> true)) {
for (Cluster cluster : allClusters()) {
clusterManager.stopCluster(cluster);
}
}
@@ -74,12 +79,13 @@ public class EksService implements TagHandler {
}
String region = config.defaultRegion();
String accountId = config.defaultAccountId();
String accountId = regionResolver.getAccountId();
String arn = AwsArnUtils.Arn.of("eks", region, accountId, "cluster/" + name).toString();
Cluster cluster = new Cluster();
cluster.setName(name);
cluster.setArn(arn);
cluster.setAccountId(accountId);
cluster.setCreatedAt(Instant.now());
cluster.setVersion(request.getVersion() != null ? request.getVersion() : "1.29");
cluster.setRoleArn(request.getRoleArn());
@@ -225,13 +231,13 @@ public class EksService implements TagHandler {
private void startReadinessPoller() {
poller.scheduleAtFixedRate(() -> {
try {
for (Cluster cluster : storage.scan(k -> true)) {
for (Cluster cluster : allClusters()) {
if (cluster.getStatus() == ClusterStatus.CREATING) {
if (clusterManager.isReady(cluster)) {
LOG.infov("EKS cluster {0} is now ACTIVE", cluster.getName());
clusterManager.finalizeCluster(cluster);
cluster.setStatus(ClusterStatus.ACTIVE);
storage.put(cluster.getName(), cluster);
putCluster(cluster);
}
}
}
@@ -240,4 +246,19 @@ public class EksService implements TagHandler {
}
}, 2, 3, TimeUnit.SECONDS);
}
private List<Cluster> allClusters() {
if (storage instanceof AccountAwareStorageBackend<Cluster> aware) {
return aware.scanAllAccounts();
}
return storage.scan(k -> true);
}
private void putCluster(Cluster cluster) {
if (cluster.getAccountId() != null && storage instanceof AccountAwareStorageBackend<Cluster> aware) {
aware.putForAccount(cluster.getAccountId(), cluster.getName(), cluster);
} else {
storage.put(cluster.getName(), cluster);
}
}
}
@@ -53,6 +53,9 @@ public class Cluster {
@JsonIgnore
private String containerId;
@JsonIgnore
private String accountId;
public Cluster() {}
public String getName() { return name; }
@@ -93,4 +96,7 @@ public class Cluster {
public String getContainerId() { return containerId; }
public void setContainerId(String containerId) { this.containerId = containerId; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.elasticache;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
import io.github.hectorvent.floci.core.common.XmlBuilder;
@@ -32,11 +33,14 @@ public class ElastiCacheQueryHandler {
private final SigV4Validator sigV4Validator;
private final ElastiCacheService service;
private final RegionResolver regionResolver;
@Inject
public ElastiCacheQueryHandler(SigV4Validator sigV4Validator, ElastiCacheService service) {
public ElastiCacheQueryHandler(SigV4Validator sigV4Validator, ElastiCacheService service,
RegionResolver regionResolver) {
this.sigV4Validator = sigV4Validator;
this.service = service;
this.regionResolver = regionResolver;
}
public Response handle(String action, MultivaluedMap<String, String> params) {
@@ -289,7 +293,7 @@ public class ElastiCacheQueryHandler {
.elem("Engine", "redis")
.elem("MinimumEngineVersion", "6.0")
.start("UserGroupIds").end("UserGroupIds")
.elem("ARN", AwsArnUtils.Arn.of("elasticache", "us-east-1", "000000000000", "user:" + u.getUserId()).toString())
.elem("ARN", AwsArnUtils.Arn.of("elasticache", regionResolver.getDefaultRegion(), regionResolver.getAccountId(), "user:" + u.getUserId()).toString())
.build();
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.elbv2;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.elbv2.model.*;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -20,8 +21,10 @@ public class ElbV2Service {
@Inject
ElbV2HealthChecker healthChecker;
@Inject
RegionResolver regionResolver;
private static final String CANONICAL_HOSTED_ZONE_ID = "Z35SXDOTRQ7X7K";
private static final String DEFAULT_ACCOUNT = "000000000000";
// region → ARN → resource
private final Map<String, Map<String, LoadBalancer>> loadBalancers = new ConcurrentHashMap<>();
@@ -57,7 +60,7 @@ public class ElbV2Service {
String ipType = ipAddressType != null ? ipAddressType : "ipv4";
String typePrefix = lbTypePrefix(lbType);
String id = randomHex16();
String arn = AwsArnUtils.Arn.of("elasticloadbalancing", region, DEFAULT_ACCOUNT, "loadbalancer/" + typePrefix + "/" + name + "/" + id).toString();
String arn = AwsArnUtils.Arn.of("elasticloadbalancing", region, regionResolver.getAccountId(), "loadbalancer/" + typePrefix + "/" + name + "/" + id).toString();
String dnsName = name + "-" + id + ".elb.localhost";
LoadBalancer lb = new LoadBalancer();
@@ -177,7 +180,7 @@ public class ElbV2Service {
}
String id = randomHex16();
String arn = AwsArnUtils.Arn.of("elasticloadbalancing", region, DEFAULT_ACCOUNT, "targetgroup/" + name + "/" + id).toString();
String arn = AwsArnUtils.Arn.of("elasticloadbalancing", region, regionResolver.getAccountId(), "targetgroup/" + name + "/" + id).toString();
TargetGroup tg = new TargetGroup();
tg.setTargetGroupArn(arn);
@@ -301,7 +304,7 @@ public class ElbV2Service {
String typePrefix = lbTypePrefix(lbType);
String lbId = arnId(lbArn);
String listenerId = randomHex16();
String listenerArn = AwsArnUtils.Arn.of("elasticloadbalancing", region, DEFAULT_ACCOUNT, "listener/" + typePrefix + "/" + lb.getLoadBalancerName() + "/" + lbId + "/" + listenerId).toString();
String listenerArn = AwsArnUtils.Arn.of("elasticloadbalancing", region, regionResolver.getAccountId(), "listener/" + typePrefix + "/" + lb.getLoadBalancerName() + "/" + lbId + "/" + listenerId).toString();
Listener listener = new Listener();
listener.setListenerArn(listenerArn);
@@ -423,7 +426,7 @@ public class ElbV2Service {
String lbId = arnId(listener.getLoadBalancerArn());
String listenerId = arnId(listenerArn);
String ruleId = randomHex16();
String ruleArn = AwsArnUtils.Arn.of("elasticloadbalancing", region, DEFAULT_ACCOUNT, "listener-rule/" + typePrefix + "/" + lb.getLoadBalancerName() + "/" + lbId + "/" + listenerId + "/" + ruleId).toString();
String ruleArn = AwsArnUtils.Arn.of("elasticloadbalancing", region, regionResolver.getAccountId(), "listener-rule/" + typePrefix + "/" + lb.getLoadBalancerName() + "/" + lbId + "/" + listenerId + "/" + ruleId).toString();
Rule rule = new Rule();
rule.setRuleArn(ruleArn);
@@ -765,7 +768,7 @@ public class ElbV2Service {
String lbType = lb.getType() != null ? lb.getType() : "application";
String typePrefix = lbTypePrefix(lbType);
String ruleId = randomHex16();
String ruleArn = AwsArnUtils.Arn.of("elasticloadbalancing", region, DEFAULT_ACCOUNT, "listener-rule/" + typePrefix + "/" + lb.getLoadBalancerName() + "/" + lbId + "/" + listenerId + "/" + ruleId).toString();
String ruleArn = AwsArnUtils.Arn.of("elasticloadbalancing", region, regionResolver.getAccountId(), "listener-rule/" + typePrefix + "/" + lb.getLoadBalancerName() + "/" + lbId + "/" + listenerId + "/" + ruleId).toString();
Rule rule = new Rule();
rule.setRuleArn(ruleArn);
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
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.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.eventbridge.model.Archive;
@@ -100,9 +101,10 @@ public class EventBridgeService {
@PostConstruct
void init() {
if (ruleScheduler != null) {
ruleStore.keys().forEach(key -> {
ruleStore.get(key).ifPresent(this::startSchedulerIfNeeded);
});
List<Rule> allRules = ruleStore instanceof AccountAwareStorageBackend<Rule> aware
? aware.scanAllAccounts()
: ruleStore.scan(k -> true);
allRules.forEach(this::startSchedulerIfNeeded);
LOG.infov("EventBridge initialized, {0} scheduler(s) restored", ruleScheduler.getActiveSchedulerCount());
}
}
@@ -197,6 +199,7 @@ public class EventBridgeService {
String key = ruleKey(region, effectiveBus, name);
Rule rule = ruleStore.get(key).orElse(new Rule());
rule.setAccountId(regionResolver.getAccountId());
rule.setName(name);
rule.setArn(buildRuleArn(region, effectiveBus, name));
rule.setEventBusName(effectiveBus);
@@ -572,6 +575,10 @@ public class EventBridgeService {
public record PutEventsResult(int failedCount, List<Map<String, String>> entries) {}
public PutEventsResult putEvents(List<Map<String, Object>> entries, String region) {
return putEvents(entries, region, null);
}
private PutEventsResult putEvents(List<Map<String, Object>> entries, String region, String accountId) {
int failed = 0;
List<Map<String, String>> resultEntries = new ArrayList<>();
@@ -582,7 +589,7 @@ public class EventBridgeService {
if ("default".equals(effectiveBus)) {
getOrCreateDefaultBus(region);
} else if (busStore.get(busStoreKey).isEmpty()) {
} else if (accountGet(busStore, accountId, busStoreKey).isEmpty()) {
failed++;
Map<String, String> errorEntry = new HashMap<>();
errorEntry.put("ErrorCode", "InvalidArgument");
@@ -593,13 +600,15 @@ public class EventBridgeService {
String eventId = UUID.randomUUID().toString();
String rulePrefix = ruleKeyPrefix(region, effectiveBus);
List<Rule> matchedRules = ruleStore.scan(k ->
k.startsWith(rulePrefix) && isRuleEnabled(k));
List<Rule> candidateRules = accountScan(ruleStore, accountId, k -> k.startsWith(rulePrefix));
for (Rule rule : matchedRules) {
for (Rule rule : candidateRules) {
if (rule.getState() != RuleState.ENABLED) {
continue;
}
if (matchesPattern(entry, rule.getEventPattern())) {
String ruleKey = ruleKey(region, effectiveBus, rule.getName());
List<Target> targets = targetStore.get(ruleKey).orElse(List.of());
List<Target> targets = accountGet(targetStore, accountId, ruleKey).orElse(List.of());
String eventJson = buildEventEnvelope(entry, effectiveBus, eventId);
for (Target target : targets) {
invoker.invokeTarget(target, eventJson, region);
@@ -607,7 +616,7 @@ public class EventBridgeService {
}
}
captureToArchives(entry, busStoreKey, eventId, region);
captureToArchives(entry, busStoreKey, eventId, region, accountId);
Map<String, String> successEntry = new HashMap<>();
successEntry.put("EventId", eventId);
@@ -913,16 +922,16 @@ public class EventBridgeService {
}
private void captureToArchives(Map<String, Object> entry, String busStoreKey,
String eventId, String region) {
EventBus bus = busStore.get(busStoreKey).orElse(null);
String eventId, String region, String accountId) {
EventBus bus = accountGet(busStore, accountId, busStoreKey).orElse(null);
if (bus == null) {
return;
}
String busArn = bus.getArn();
String archivePrefix = "archive:" + region + ":";
List<Archive> candidates = archiveStore.scan(k ->
List<Archive> candidates = accountScan(archiveStore, accountId, k ->
k.startsWith(archivePrefix)
&& archiveStore.get(k).map(a ->
&& accountGet(archiveStore, accountId, k).map(a ->
a.getState() == ArchiveState.ENABLED
&& busArn.equals(a.getEventSourceArn())).orElse(false));
@@ -930,7 +939,7 @@ public class EventBridgeService {
if (matchesPattern(entry, archive.getEventPattern())) {
String evKey = archivedEventKey(region, archive.getArchiveName());
List<ArchivedEvent> stored = new ArrayList<>(
archivedEventStore.get(evKey).orElse(new ArrayList<>()));
accountGet(archivedEventStore, accountId, evKey).orElse(new ArrayList<>()));
ArchivedEvent ae = new ArchivedEvent(
eventId,
Instant.now(),
@@ -940,9 +949,9 @@ public class EventBridgeService {
busArn
);
stored.add(ae);
archivedEventStore.put(evKey, stored);
accountPut(archivedEventStore, accountId, evKey, stored);
archive.setEventCount(archive.getEventCount() + 1);
archiveStore.put(archiveKey(region, archive.getArchiveName()), archive);
accountPut(archiveStore, accountId, archiveKey(region, archive.getArchiveName()), archive);
}
}
}
@@ -971,6 +980,8 @@ public class EventBridgeService {
.get(archivedEventKey(region, archiveName))
.orElse(List.of());
String capturedAccountId = regionResolver.getAccountId();
Replay replay = new Replay();
replay.setReplayName(replayName);
replay.setReplayArn(regionResolver.buildArn("events", region, "replay/" + replayName));
@@ -981,14 +992,15 @@ public class EventBridgeService {
replay.setEventEndTime(eventEndTime);
replay.setState(ReplayState.STARTING);
replay.setReplayStartTime(Instant.now());
replay.setAccountId(capturedAccountId);
replayStore.put(key, replay);
replayDispatcher.dispatch(
replay,
events,
entries -> putEvents(entries, region),
(name, state) -> updateReplayState(name, state, region),
time -> updateReplayLastReplayed(replayName, time, region)
entries -> putEvents(entries, region, capturedAccountId),
(name, state) -> updateReplayStateForAccount(capturedAccountId, name, state, region),
time -> updateReplayLastReplayedForAccount(capturedAccountId, replayName, time, region)
);
LOG.infov("Started replay: {0} from archive {1}", replayName, archiveName);
@@ -1045,23 +1057,33 @@ public class EventBridgeService {
}
void updateReplayState(String replayName, ReplayState state, String region) {
updateReplayStateForAccount(null, replayName, state, region);
}
private void updateReplayStateForAccount(String accountId, String replayName,
ReplayState state, String region) {
String key = replayKey(region, replayName);
replayStore.get(key).ifPresent(r -> {
accountGet(replayStore, accountId, key).ifPresent(r -> {
r.setState(state);
if (state == ReplayState.COMPLETED || state == ReplayState.CANCELLED
|| state == ReplayState.FAILED) {
r.setReplayEndTime(Instant.now());
}
replayStore.put(key, r);
accountPut(replayStore, accountId, key, r);
LOG.debugv("Replay {0} transitioned to {1}", replayName, state);
});
}
void updateReplayLastReplayed(String replayName, Instant eventTime, String region) {
updateReplayLastReplayedForAccount(null, replayName, eventTime, region);
}
private void updateReplayLastReplayedForAccount(String accountId, String replayName,
Instant eventTime, String region) {
String key = replayKey(region, replayName);
replayStore.get(key).ifPresent(r -> {
accountGet(replayStore, accountId, key).ifPresent(r -> {
r.setEventLastReplayedTime(eventTime);
replayStore.put(key, r);
accountPut(replayStore, accountId, key, r);
});
}
@@ -1092,16 +1114,40 @@ public class EventBridgeService {
&& !rule.getScheduleExpression().isBlank()) {
String region = rule.getRegion() != null ? rule.getRegion() : "us-east-1";
String key = ruleKey(region, rule.getEventBusName(), rule.getName());
String accountId = rule.getAccountId();
ruleScheduler.startScheduler(
rule.getArn(),
rule.getScheduleExpression(),
() -> {
Rule r = ruleStore.get(key).orElse(null);
List<Target> t = targetStore.get(key).orElse(List.of());
Rule r = accountGet(ruleStore, accountId, key).orElse(null);
List<Target> t = accountGet(targetStore, accountId, key).orElse(List.of());
return new RuleScheduler.ScheduleData(r, t);
}
);
}
}
private <V> java.util.Optional<V> accountGet(StorageBackend<String, V> store, String accountId, String key) {
if (accountId != null && store instanceof AccountAwareStorageBackend<V> aware) {
return aware.getForAccount(accountId, key);
}
return store.get(key);
}
private <V> List<V> accountScan(StorageBackend<String, V> store, String accountId,
java.util.function.Predicate<String> filter) {
if (accountId != null && store instanceof AccountAwareStorageBackend<V> aware) {
return aware.scanForAccount(accountId, filter);
}
return store.scan(filter);
}
private <V> void accountPut(StorageBackend<String, V> store, String accountId, String key, V value) {
if (accountId != null && store instanceof AccountAwareStorageBackend<V> aware) {
aware.putForAccount(accountId, key, value);
} else {
store.put(key, value);
}
}
}
@@ -26,7 +26,7 @@ public class RuleScheduler {
private final Vertx vertx;
private final ObjectMapper objectMapper;
private final String accountId;
private final String defaultAccountId;
private final EventBridgeInvoker invoker;
private final ConcurrentHashMap<String, ScheduleContext> scheduleContexts = new ConcurrentHashMap<>();
@@ -37,7 +37,7 @@ public class RuleScheduler {
EventBridgeInvoker invoker) {
this.vertx = vertx;
this.objectMapper = objectMapper;
this.accountId = config.defaultAccountId();
this.defaultAccountId = config.defaultAccountId();
this.invoker = invoker;
}
@@ -150,7 +150,7 @@ public class RuleScheduler {
node.put("id", UUID.randomUUID().toString());
node.put("source", "aws.events");
node.put("detail-type", "Scheduled Event");
node.put("account", accountId);
node.put("account", rule.getAccountId() != null ? rule.getAccountId() : defaultAccountId);
node.put("time", now.toInstant().toString());
node.put("region", region);
node.putArray("resources").add(rule.getArn());
@@ -10,6 +10,7 @@ public class Replay {
private String replayName;
private String replayArn;
private String description;
private String accountId;
private String eventSourceArn;
private String destinationArn;
private Instant eventStartTime;
@@ -57,4 +58,7 @@ public class Replay {
public Instant getReplayEndTime() { return replayEndTime; }
public void setReplayEndTime(Instant replayEndTime) { this.replayEndTime = replayEndTime; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
}
@@ -12,6 +12,7 @@ public class Rule {
private String name;
private String arn;
private String accountId;
private String eventBusName;
private String eventPattern;
private String scheduleExpression;
@@ -29,6 +30,9 @@ public class Rule {
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getEventBusName() { return eventBusName; }
public void setEventBusName(String eventBusName) { this.eventBusName = eventBusName; }
@@ -43,6 +43,7 @@ public class FirehoseService {
public String createDeliveryStream(String name, S3Destination s3Config) {
String arn = AwsArnUtils.Arn.of("firehose", regionResolver.getDefaultRegion(), regionResolver.getAccountId(), "deliverystream/" + name).toString();
DeliveryStreamDescription description = new DeliveryStreamDescription(name, arn, s3Config);
description.setAccountId(regionResolver.getAccountId());
streamStore.put(name, description);
buffers.put(name, Collections.synchronizedList(new ArrayList<>()));
LOG.infov("Created Firehose delivery stream: {0}", name);
@@ -10,6 +10,7 @@ import java.util.List;
public class DeliveryStreamDescription {
@JsonProperty("DeliveryStreamName")
private String deliveryStreamName;
private String accountId;
@JsonProperty("DeliveryStreamARN")
private String deliveryStreamARN;
@JsonProperty("DeliveryStreamStatus")
@@ -31,6 +32,9 @@ public class DeliveryStreamDescription {
public String getDeliveryStreamName() { return deliveryStreamName; }
public void setDeliveryStreamName(String deliveryStreamName) { this.deliveryStreamName = deliveryStreamName; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getDeliveryStreamARN() { return deliveryStreamARN; }
public void setDeliveryStreamARN(String deliveryStreamARN) { this.deliveryStreamARN = deliveryStreamARN; }
public DeliveryStreamStatus getDeliveryStreamStatus() { return deliveryStreamStatus; }
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.kinesis;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
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.kinesis.model.KinesisConsumer;
@@ -68,6 +69,7 @@ public class KinesisService {
String arn = regionResolver.buildArn("kinesis", region, "stream/" + streamName);
KinesisStream stream = new KinesisStream(streamName, arn);
stream.setAccountId(regionResolver.getAccountId());
stream.setStreamMode(resolvedMode);
for (int i = 0; i < shardCount; i++) {
@@ -496,6 +498,76 @@ public class KinesisService {
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Stream " + streamName + " not found", 400));
}
private KinesisStream resolveStreamForAccount(String accountId, String streamName, String region) {
if (accountId != null && store instanceof AccountAwareStorageBackend<KinesisStream> aware) {
return aware.getForAccount(accountId, regionKey(region, streamName))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Stream " + streamName + " not found", 400));
}
return resolveStream(streamName, region);
}
public String getShardIteratorForAccount(String accountId, String streamName, String shardId,
String type, String sequenceNumber, String region) {
resolveStreamForAccount(accountId, streamName, region);
String raw = String.format("%s|%s|%s|%s|%d|",
streamName, shardId, type,
sequenceNumber != null ? sequenceNumber : "", 0);
return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
}
public Map<String, Object> getRecordsForAccount(String accountId, String shardIterator,
Integer limit, String region) {
byte[] decoded = Base64.getDecoder().decode(shardIterator);
String[] parts = new String(decoded, StandardCharsets.UTF_8).split(java.util.regex.Pattern.quote("|"), -1);
if (parts.length < 5) {
throw new AwsException("InvalidArgumentException", "Invalid shard iterator", 400);
}
String streamName = parts[0];
String shardId = parts[1];
String type = parts[2];
String startSeq = parts[3];
int lastIndex = Integer.parseInt(parts[4]);
KinesisStream stream = resolveStreamForAccount(accountId, streamName, region);
KinesisShard shard = stream.getShards().stream()
.filter(s -> s.getShardId().equals(shardId))
.findFirst()
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Shard not found", 400));
List<KinesisRecord> allRecords = shard.getRecords();
int startIndex = 0;
if ("TRIM_HORIZON".equals(type)) {
startIndex = lastIndex;
} else if ("LATEST".equals(type)) {
startIndex = allRecords.size();
} else if ("AFTER_SEQUENCE_NUMBER".equals(type)) {
for (int i = 0; i < allRecords.size(); i++) {
if (allRecords.get(i).getSequenceNumber().equals(startSeq)) {
startIndex = i + 1;
break;
}
}
}
int max = limit != null ? Math.min(limit, 1000) : 1000;
List<KinesisRecord> result = new ArrayList<>();
int nextIndex = startIndex;
for (int i = startIndex; i < allRecords.size() && result.size() < max; i++) {
result.add(allRecords.get(i));
nextIndex = i + 1;
}
String nextIterator = Base64.getEncoder().encodeToString(
String.format("%s|%s|%s|%s|%d|", streamName, shardId, "TRIM_HORIZON", "", nextIndex)
.getBytes(StandardCharsets.UTF_8));
Map<String, Object> response = new HashMap<>();
response.put("Records", result);
response.put("NextShardIterator", nextIterator);
response.put("MillisBehindLatest", computeMillisBehindLatest(allRecords, nextIndex));
return response;
}
private KinesisShard selectShard(KinesisStream stream, String partitionKey) {
// Simple hash-based shard selection among ALL shards, then resolve to open one
int index = Math.abs(partitionKey.hashCode()) % stream.getShards().size();
@@ -16,6 +16,7 @@ import java.util.Set;
public class KinesisStream {
private String streamName;
private String streamArn;
private String accountId;
private String streamStatus;
private List<KinesisShard> shards = new ArrayList<>();
private int retentionPeriodHours = 24;
@@ -41,6 +42,9 @@ public class KinesisStream {
public String getStreamArn() { return streamArn; }
public void setStreamArn(String streamArn) { this.streamArn = streamArn; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getStreamStatus() { return streamStatus; }
public void setStreamStatus(String streamStatus) { this.streamStatus = streamStatus; }
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.kms;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.services.kms.model.KmsAlias;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
@@ -22,11 +23,13 @@ public class KmsJsonHandler {
private final KmsService service;
private final ObjectMapper objectMapper;
private final RegionResolver regionResolver;
@Inject
public KmsJsonHandler(KmsService service, ObjectMapper objectMapper) {
public KmsJsonHandler(KmsService service, ObjectMapper objectMapper, RegionResolver regionResolver) {
this.service = service;
this.objectMapper = objectMapper;
this.regionResolver = regionResolver;
}
public Response handle(String action, JsonNode request, String region) {
@@ -340,7 +343,7 @@ public class KmsJsonHandler {
private ObjectNode keyToNode(KmsKey k) {
ObjectNode node = objectMapper.createObjectNode();
node.put("AWSAccountId", "000000000000");
node.put("AWSAccountId", regionResolver.getAccountId());
node.put("KeyId", k.getKeyId());
node.put("Arn", k.getArn());
node.put("CreationDate", k.getCreationDate());
@@ -65,10 +65,12 @@ public class KmsService {
this.regionResolver = regionResolver;
}
private static final String DEFAULT_KEY_POLICY =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Enable IAM User Permissions\"," +
"\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::000000000000:root\"}," +
"\"Action\":\"kms:*\",\"Resource\":\"*\"}]}";
private String buildDefaultKeyPolicy() {
String account = regionResolver.getAccountId();
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Enable IAM User Permissions\"," +
"\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::" + account + ":root\"}," +
"\"Action\":\"kms:*\",\"Resource\":\"*\"}]}";
}
public KmsKey createKey(String description, String region) {
return createKey(description, "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT", null, Map.of(), region);
@@ -95,7 +97,7 @@ public class KmsService {
key.setDescription(description);
key.setKeyUsage(effectiveUsage);
key.setCustomerMasterKeySpec(effectiveSpec);
key.setPolicy(policy != null ? policy : DEFAULT_KEY_POLICY);
key.setPolicy(policy != null ? policy : buildDefaultKeyPolicy());
key.getTags().putAll(ReservedTags.stripReservedTags(tags));
generateKeyMaterial(key);
@@ -59,7 +59,7 @@ public class DynamoDbStreamsEventSourcePoller {
}
public void startPersistedPollers() {
for (EventSourceMapping esm : esmStore.list()) {
for (EventSourceMapping esm : esmStore.listAll()) {
if (esm.isEnabled() && esm.getEventSourceArn().contains(":dynamodb:")) {
startPolling(esm);
}
@@ -79,8 +79,9 @@ public class DynamoDbStreamsEventSourcePoller {
return;
}
String uuid = esm.getUuid();
String accountId = esm.getAccountId();
long timerId = vertx.setPeriodic(pollIntervalMs, id ->
esmStore.get(uuid).ifPresent(latest -> {
esmStore.getForAccount(accountId, uuid).ifPresent(latest -> {
if (latest.isEnabled()) {
pollAndInvoke(latest);
}
@@ -103,7 +104,7 @@ public class DynamoDbStreamsEventSourcePoller {
}
pollExecutor.submit(() -> {
try {
LambdaFunction fn = functionStore.get(esm.getRegion(), esm.getFunctionName()).orElse(null);
LambdaFunction fn = functionStore.getForAccount(esm.getAccountId(), esm.getRegion(), esm.getFunctionName()).orElse(null);
if (fn == null) {
LOG.warnv("DynamoDB Streams ESM {0}: function {1} not found, skipping",
esm.getUuid(), esm.getFunctionName());
@@ -144,7 +145,7 @@ public class DynamoDbStreamsEventSourcePoller {
if (invokeResult.getFunctionError() == null) {
String newestSeq = records.get(records.size() - 1).getSequenceNumber();
esm.getShardSequenceNumbers().put(shardId, newestSeq);
esmStore.save(esm);
esmStore.saveForAccount(esm.getAccountId(), esm);
} else {
LOG.warnv("DynamoDB Streams ESM {0}: Lambda returned error [{1}], records will be retried",
esm.getUuid(), invokeResult.getFunctionError());
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.lambda;
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.lambda.model.EventSourceMapping;
@@ -33,6 +34,14 @@ public class EsmStore {
backend.put(esm.getUuid(), esm);
}
public void saveForAccount(String accountId, EventSourceMapping esm) {
if (backend instanceof AccountAwareStorageBackend<EventSourceMapping> aware) {
aware.putForAccount(accountId, esm.getUuid(), esm);
} else {
backend.put(esm.getUuid(), esm);
}
}
public Optional<EventSourceMapping> get(String uuid) {
return backend.get(uuid);
}
@@ -41,6 +50,21 @@ public class EsmStore {
return backend.scan(k -> true);
}
/** Returns all ESMs across all accounts — for use at startup outside request scope. */
public List<EventSourceMapping> listAll() {
if (backend instanceof AccountAwareStorageBackend<EventSourceMapping> aware) {
return aware.scanAllAccounts();
}
return backend.scan(k -> true);
}
public Optional<EventSourceMapping> getForAccount(String accountId, String uuid) {
if (backend instanceof AccountAwareStorageBackend<EventSourceMapping> aware) {
return aware.getForAccount(accountId, uuid);
}
return backend.get(uuid);
}
public List<EventSourceMapping> listByFunction(String functionKey) {
return backend.scan(k -> {
var esm = backend.get(k).orElse(null);
@@ -62,7 +62,7 @@ public class KinesisEventSourcePoller {
}
public void startPersistedPollers() {
List<EventSourceMapping> esms = esmStore.list();
List<EventSourceMapping> esms = esmStore.listAll();
for (EventSourceMapping esm : esms) {
if (esm.isEnabled() && esm.getEventSourceArn().contains(":kinesis:")) {
startPolling(esm);
@@ -80,8 +80,9 @@ public class KinesisEventSourcePoller {
public void startPolling(EventSourceMapping esm) {
if (timerIds.containsKey(esm.getUuid())) return;
String uuid = esm.getUuid();
String accountId = esm.getAccountId();
long timerId = vertx.setPeriodic(pollIntervalMs, id -> {
esmStore.get(uuid).ifPresent(latest -> {
esmStore.getForAccount(accountId, uuid).ifPresent(latest -> {
if (latest.isEnabled()) pollAndInvoke(latest);
});
});
@@ -98,7 +99,7 @@ public class KinesisEventSourcePoller {
if (activePolls.putIfAbsent(esm.getUuid(), Boolean.TRUE) != null) return;
pollExecutor.submit(() -> {
try {
LambdaFunction fn = functionStore.get(esm.getRegion(), esm.getFunctionName()).orElse(null);
LambdaFunction fn = functionStore.getForAccount(esm.getAccountId(), esm.getRegion(), esm.getFunctionName()).orElse(null);
if (fn == null) return;
String streamName = streamNameFromArn(esm.getEventSourceArn());
@@ -133,7 +134,7 @@ public class KinesisEventSourcePoller {
if (invokeResult.getFunctionError() == null) {
String newestSeq = records.get(records.size() - 1).getSequenceNumber();
esm.getShardSequenceNumbers().put(shard.getShardId(), newestSeq);
esmStore.save(esm);
esmStore.saveForAccount(esm.getAccountId(), esm);
}
}
}
@@ -162,7 +163,7 @@ public class KinesisEventSourcePoller {
record.put("eventVersion", "1.0");
record.put("eventID", shardId + ":" + rec.getSequenceNumber());
record.put("eventName", "aws:kinesis:record");
record.put("invokeIdentityArn", AwsArnUtils.Arn.of("iam", "", "000000000000", "role/lambda-role").toString());
record.put("invokeIdentityArn", AwsArnUtils.Arn.of("iam", "", esm.getAccountId(), "role/lambda-role").toString());
record.put("awsRegion", esm.getRegion());
record.put("eventSourceARN", esm.getEventSourceArn());
recordsArray.add(record);
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.lambda;
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.lambda.model.LambdaFunction;
@@ -34,7 +35,10 @@ public class LambdaFunctionStore {
}
private void loadIndex() {
backend.scan(key -> true).forEach(this::indexFunction);
List<LambdaFunction> all = backend instanceof AccountAwareStorageBackend<LambdaFunction> aware
? aware.scanAllAccounts()
: backend.scan(key -> true);
all.forEach(this::indexFunction);
}
private void indexFunction(LambdaFunction fn) {
@@ -80,6 +84,13 @@ public class LambdaFunctionStore {
return backend.get(regionKey(region, functionName, version));
}
public Optional<LambdaFunction> getForAccount(String accountId, String region, String functionName) {
if (backend instanceof AccountAwareStorageBackend<LambdaFunction> aware) {
return aware.getForAccount(accountId, regionKey(region, functionName, "$LATEST"));
}
return backend.get(regionKey(region, functionName, "$LATEST"));
}
public Optional<LambdaFunction> getByUrlId(String urlId) {
return Optional.ofNullable(urlIdIndex.get(urlId));
}
@@ -217,6 +217,7 @@ public class LambdaService {
}
LambdaFunction fn = new LambdaFunction();
fn.setAccountId(regionResolver.getAccountId());
fn.setFunctionName(functionName);
fn.setFunctionArn(regionResolver.buildArn("lambda", region, "function:" + functionName));
fn.setRuntime(runtime);
@@ -665,6 +666,7 @@ public class LambdaService {
EventSourceMapping esm = new EventSourceMapping();
esm.setUuid(UUID.randomUUID().toString());
esm.setAccountId(regionResolver.getAccountId());
esm.setFunctionArn(fn.getFunctionArn());
esm.setFunctionName(resolvedName);
esm.setEventSourceArn(eventSourceArn);
@@ -69,7 +69,7 @@ public class SqsEventSourcePoller {
}
public void startPersistedPollers() {
List<EventSourceMapping> esms = esmStore.list();
List<EventSourceMapping> esms = esmStore.listAll();
for (EventSourceMapping esm : esms) {
if (esm.isEnabled() && esm.getEventSourceArn().contains(":sqs:")) {
startPolling(esm);
@@ -91,10 +91,11 @@ public class SqsEventSourcePoller {
return; // already polling
}
String uuid = esm.getUuid();
String accountId = esm.getAccountId();
long timerId = vertx.setPeriodic(pollIntervalMs, id -> {
// Re-fetch from storage on each tick so updates (batchSize, enabled) are visible
// ConcurrentHashMap.get() establishes happens-before with the prior put()
esmStore.get(uuid).ifPresent(latest -> {
// Re-fetch from storage on each tick so updates (batchSize, enabled) are visible.
// Use account-scoped lookup since this runs outside request scope.
esmStore.getForAccount(accountId, uuid).ifPresent(latest -> {
if (latest.isEnabled()) {
pollAndInvoke(latest);
}
@@ -124,7 +125,8 @@ public class SqsEventSourcePoller {
try {
// Look up the function first so we can set an appropriate visibility
// timeout: fn.timeout + 30s keeps messages hidden while Lambda runs.
LambdaFunction fn = functionStore.get(esm.getRegion(), esm.getFunctionName())
// Use account-scoped lookup since this runs outside request scope.
LambdaFunction fn = functionStore.getForAccount(esm.getAccountId(), esm.getRegion(), esm.getFunctionName())
.orElse(null);
if (fn == null) {
LOG.warnv("ESM {0}: function {1} not found in region {2}, skipping",
@@ -15,6 +15,7 @@ public class EventSourceMapping {
private String uuid;
private String functionArn;
private String functionName;
private String accountId;
private String eventSourceArn;
private String queueUrl;
private String region;
@@ -38,6 +39,9 @@ public class EventSourceMapping {
public String getFunctionName() { return functionName; }
public void setFunctionName(String functionName) { this.functionName = functionName; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getEventSourceArn() { return eventSourceArn; }
public void setEventSourceArn(String eventSourceArn) { this.eventSourceArn = eventSourceArn; }
@@ -15,6 +15,7 @@ public class LambdaFunction {
private String functionName;
private String functionArn;
private String accountId;
private String runtime;
private String role;
private String handler;
@@ -62,6 +63,9 @@ public class LambdaFunction {
public String getFunctionName() { return functionName; }
public void setFunctionName(String functionName) { this.functionName = functionName; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getFunctionArn() { return functionArn; }
public void setFunctionArn(String functionArn) { this.functionArn = functionArn; }
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.msk;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
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.msk.model.ClusterState;
@@ -29,13 +31,16 @@ public class MskService {
private static final Logger LOG = Logger.getLogger(MskService.class);
private final StorageBackend<String, MskCluster> storage;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final RedpandaManager redpandaManager;
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
@Inject
public MskService(StorageFactory storageFactory, EmulatorConfig config, RedpandaManager redpandaManager) {
public MskService(StorageFactory storageFactory, EmulatorConfig config,
RegionResolver regionResolver, RedpandaManager redpandaManager) {
this.storage = storageFactory.create("msk", "msk-clusters.json", new TypeReference<Map<String, MskCluster>>() {});
this.config = config;
this.regionResolver = regionResolver;
this.redpandaManager = redpandaManager;
}
@@ -48,7 +53,7 @@ public class MskService {
public void shutdown() {
poller.shutdown();
if (!config.services().msk().mock()) {
for (MskCluster cluster : storage.scan(k -> true)) {
for (MskCluster cluster : allClusters()) {
redpandaManager.stopContainer(cluster);
}
}
@@ -59,9 +64,11 @@ public class MskService {
throw new AwsException("ConflictException", "Cluster already exists: " + clusterName, 409);
}
String clusterArn = AwsArnUtils.Arn.of("kafka", "us-east-1", "000000000000", "cluster/" + clusterName + "/" + java.util.UUID.randomUUID()).toString();
String accountId = regionResolver.getAccountId();
String clusterArn = AwsArnUtils.Arn.of("kafka", config.defaultRegion(), accountId, "cluster/" + clusterName + "/" + java.util.UUID.randomUUID()).toString();
MskCluster cluster = new MskCluster(clusterArn, clusterName);
cluster.setAccountId(accountId);
cluster.setVolumeId(String.format("%06x", new SecureRandom().nextInt(0xFFFFFF)));
if (config.services().msk().mock()) {
@@ -104,12 +111,12 @@ public class MskService {
private void startReadinessPoller() {
poller.scheduleAtFixedRate(() -> {
try {
for (MskCluster cluster : storage.scan(k -> true)) {
for (MskCluster cluster : allClusters()) {
if (cluster.getState() == ClusterState.CREATING && !config.services().msk().mock()) {
if (redpandaManager.isReady(cluster)) {
LOG.infov("MSK Cluster {0} is now ACTIVE", cluster.getClusterName());
cluster.setState(ClusterState.ACTIVE);
storage.put(cluster.getClusterArn(), cluster);
putCluster(cluster);
}
}
}
@@ -118,4 +125,19 @@ public class MskService {
}
}, 1, 2, TimeUnit.SECONDS);
}
private List<MskCluster> allClusters() {
if (storage instanceof AccountAwareStorageBackend<MskCluster> aware) {
return aware.scanAllAccounts();
}
return storage.scan(k -> true);
}
private void putCluster(MskCluster cluster) {
if (cluster.getAccountId() != null && storage instanceof AccountAwareStorageBackend<MskCluster> aware) {
aware.putForAccount(cluster.getAccountId(), cluster.getClusterArn(), cluster);
} else {
storage.put(cluster.getClusterArn(), cluster);
}
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.msk.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@@ -38,6 +39,9 @@ public class MskCluster {
// Docker container ID for mock=false
private String containerId;
@JsonIgnore
private String accountId;
// 6-char hex generated once at creation for stable, collision-free volume/container naming
private String volumeId;
@@ -83,6 +87,9 @@ public class MskCluster {
public String getContainerId() { return containerId; }
public void setContainerId(String containerId) { this.containerId = containerId; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getVolumeId() { return volumeId; }
public void setVolumeId(String volumeId) { this.volumeId = volumeId; }
}
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.opensearch;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
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.opensearch.model.ClusterConfig;
@@ -32,22 +34,25 @@ public class OpenSearchService {
private final StorageBackend<String, Domain> domainStore;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final OpenSearchDomainManager domainManager;
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
@Inject
public OpenSearchService(StorageFactory storageFactory, EmulatorConfig config,
OpenSearchDomainManager domainManager) {
RegionResolver regionResolver, OpenSearchDomainManager domainManager) {
this.domainStore = storageFactory.create("opensearch", "opensearch-domains.json",
new TypeReference<Map<String, Domain>>() {});
this.config = config;
this.regionResolver = regionResolver;
this.domainManager = domainManager;
}
OpenSearchService(StorageBackend<String, Domain> domainStore, EmulatorConfig config,
OpenSearchDomainManager domainManager) {
RegionResolver regionResolver, OpenSearchDomainManager domainManager) {
this.domainStore = domainStore;
this.config = config;
this.regionResolver = regionResolver;
this.domainManager = domainManager;
}
@@ -62,7 +67,7 @@ public class OpenSearchService {
public void shutdown() {
poller.shutdownNow();
if (!config.services().opensearch().mock()) {
for (Domain domain : domainStore.scan(k -> true)) {
for (Domain domain : allDomains()) {
domainManager.stopDomain(domain);
}
}
@@ -77,10 +82,11 @@ public class OpenSearchService {
"Domain with name " + domainName + " already exists.", 409);
}
String accountId = config.defaultAccountId();
String accountId = regionResolver.getAccountId();
Domain domain = new Domain();
domain.setDomainName(domainName);
domain.setDomainId(accountId + "/" + domainName);
domain.setAccountId(accountId);
domain.setArn(AwsArnUtils.Arn.of("es", region, accountId, "domain/" + domainName).toString());
domain.setEngineVersion(engineVersion != null ? engineVersion : DEFAULT_ENGINE_VERSION);
domain.setProcessing(false);
@@ -232,14 +238,29 @@ public class OpenSearchService {
private void startReadinessPoller() {
poller.scheduleWithFixedDelay(() -> {
for (Domain domain : domainStore.scan(k -> true)) {
for (Domain domain : allDomains()) {
if (domain.isProcessing() && domainManager.isReady(domain)) {
domain.setProcessing(false);
domainStore.put(domain.getDomainName(), domain);
putDomain(domain);
LOG.infov("OpenSearch domain {0} is ready at {1}",
domain.getDomainName(), domain.getEndpoint());
}
}
}, 3, 3, TimeUnit.SECONDS);
}
private List<Domain> allDomains() {
if (domainStore instanceof AccountAwareStorageBackend<Domain> aware) {
return aware.scanAllAccounts();
}
return domainStore.scan(k -> true);
}
private void putDomain(Domain domain) {
if (domain.getAccountId() != null && domainStore instanceof AccountAwareStorageBackend<Domain> aware) {
aware.putForAccount(domain.getAccountId(), domain.getDomainName(), domain);
} else {
domainStore.put(domain.getDomainName(), domain);
}
}
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.opensearch.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@@ -46,6 +47,9 @@ public class Domain {
@JsonProperty("ContainerId")
private String containerId;
@JsonIgnore
private String accountId;
@JsonProperty("VolumeId")
private String volumeId;
@@ -158,4 +162,12 @@ public class Domain {
public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
}
@@ -214,17 +214,20 @@ public class PipesPoller {
private void pollKinesis(Pipe pipe, String region) {
String pipeKey = pipeKey(pipe);
String streamName = extractResourceName(pipe.getSource());
String pipeAccountId = pipe.getAccountId();
int batchSize = getBatchSize(pipe, "KinesisStreamParameters");
String iterator = kinesisIterators.get(pipeKey);
if (iterator == null) {
iterator = initKinesisIterator(streamName, region);
iterator = initKinesisIterator(streamName, region, pipeAccountId);
if (iterator == null) {
return;
}
}
try {
@SuppressWarnings("unchecked")
Map<String, Object> result = kinesisService.getRecords(iterator, batchSize, region);
Map<String, Object> result = (pipeAccountId != null)
? kinesisService.getRecordsForAccount(pipeAccountId, iterator, batchSize, region)
: kinesisService.getRecords(iterator, batchSize, region);
String nextIterator = (String) result.get("NextShardIterator");
if (nextIterator != null) {
kinesisIterators.put(pipeKey, nextIterator);
@@ -254,10 +257,13 @@ public class PipesPoller {
}
}
private String initKinesisIterator(String streamName, String region) {
private String initKinesisIterator(String streamName, String region, String accountId) {
try {
return kinesisService.getShardIterator(
streamName, "shardId-000000000000", "TRIM_HORIZON", null, null, region);
return (accountId != null)
? kinesisService.getShardIteratorForAccount(
accountId, streamName, "shardId-000000000000", "TRIM_HORIZON", null, region)
: kinesisService.getShardIterator(
streamName, "shardId-000000000000", "TRIM_HORIZON", null, null, region);
} catch (Exception e) {
LOG.warnv("Failed to get Kinesis shard iterator for {0}: {1}", streamName, e.getMessage());
return null;
@@ -1,9 +1,10 @@
package io.github.hectorvent.floci.services.pipes;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.TagHandler;
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.pipes.model.DesiredState;
@@ -27,19 +28,22 @@ public class PipesService implements TagHandler {
private static final Logger LOG = Logger.getLogger(PipesService.class);
private final StorageBackend<String, Pipe> storage;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final PipesPoller poller;
@Inject
public PipesService(StorageFactory storageFactory, EmulatorConfig config, PipesPoller poller) {
public PipesService(StorageFactory storageFactory, RegionResolver regionResolver, PipesPoller poller) {
this.storage = storageFactory.create("pipes", "pipes.json",
new TypeReference<Map<String, Pipe>>() {});
this.config = config;
this.regionResolver = regionResolver;
this.poller = poller;
}
public void startPersistedPollers() {
List<Pipe> runningPipes = storage.scan(key -> true).stream()
List<Pipe> allPipes = storage instanceof AccountAwareStorageBackend<Pipe> aware
? aware.scanAllAccounts()
: storage.scan(key -> true);
List<Pipe> runningPipes = allPipes.stream()
.filter(pipe -> pipe.getCurrentState() == PipeState.RUNNING)
.toList();
for (Pipe pipe : runningPipes) {
@@ -74,8 +78,7 @@ public class PipesService implements TagHandler {
"Pipe " + name + " already exists.", 409);
}
String accountId = config.defaultAccountId();
String arn = AwsArnUtils.Arn.of("pipes", region, accountId, "pipe/" + name).toString();
String arn = regionResolver.buildArn("pipes", region, "pipe/" + name);
Instant now = Instant.now();
Pipe pipe = new Pipe();
@@ -95,6 +98,7 @@ public class PipesService implements TagHandler {
pipe.setTags(tags != null ? new HashMap<>(tags) : new HashMap<>());
pipe.setCreationTime(now);
pipe.setLastModifiedTime(now);
pipe.setAccountId(regionResolver.getAccountId());
storage.put(key, pipe);
LOG.infov("Created pipe: {0}", name);
@@ -65,6 +65,9 @@ public class Pipe {
@JsonProperty("StateReason")
private String stateReason;
@com.fasterxml.jackson.annotation.JsonIgnore
private String accountId;
public Pipe() {}
public String getName() { return name; }
@@ -114,4 +117,7 @@ public class Pipe {
public String getStateReason() { return stateReason; }
public void setStateReason(String stateReason) { this.stateReason = stateReason; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
}
@@ -38,7 +38,7 @@ import java.util.concurrent.ConcurrentHashMap;
@ApplicationScoped
public class S3Service {
private static final String DEFAULT_OWNER_ID = "000000000000";
private String ownerId() { return regionResolver != null ? regionResolver.getAccountId() : "000000000000"; }
private static final String DEFAULT_OWNER_DISPLAY_NAME = "floci";
private static final String ALL_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AllUsers";
private static final String AUTHENTICATED_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
@@ -1397,7 +1397,7 @@ public class S3Service {
public String getBucketAcl(String bucketName) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
return bucket.getAcl() != null ? bucket.getAcl() : defaultAclXml(DEFAULT_OWNER_ID, DEFAULT_OWNER_DISPLAY_NAME);
return bucket.getAcl() != null ? bucket.getAcl() : defaultAclXml(ownerId(), DEFAULT_OWNER_DISPLAY_NAME);
}
public void putBucketAcl(String bucketName, String acl) {
@@ -1409,7 +1409,7 @@ public class S3Service {
public String getObjectAcl(String bucketName, String key, String versionId) {
S3Object obj = getObject(bucketName, key, versionId);
return obj.getAcl() != null ? obj.getAcl() : defaultAclXml(DEFAULT_OWNER_ID, DEFAULT_OWNER_DISPLAY_NAME);
return obj.getAcl() != null ? obj.getAcl() : defaultAclXml(ownerId(), DEFAULT_OWNER_DISPLAY_NAME);
}
public void putObjectAcl(String bucketName, String key, String versionId, String acl) {
@@ -1517,16 +1517,16 @@ public class S3Service {
.build();
}
static String cannedObjectAclXml(String cannedAcl) {
String cannedObjectAclXml(String cannedAcl) {
if (cannedAcl == null || cannedAcl.isBlank()) {
return null;
}
return switch (cannedAcl) {
case "private", "bucket-owner-read", "bucket-owner-full-control" ->
defaultAclXml(DEFAULT_OWNER_ID, DEFAULT_OWNER_DISPLAY_NAME);
defaultAclXml(ownerId(), DEFAULT_OWNER_DISPLAY_NAME);
// Floci currently runs as a single synthetic account, so there is no distinct EC2 bundle-reader
// principal to represent in GetObjectAcl responses yet.
case "aws-exec-read" -> defaultAclXml(DEFAULT_OWNER_ID, DEFAULT_OWNER_DISPLAY_NAME);
case "aws-exec-read" -> defaultAclXml(ownerId(), DEFAULT_OWNER_DISPLAY_NAME);
case "public-read" -> objectAclXml(
ownerFullControlGrant(),
groupGrant(ALL_USERS_GROUP_URI, "READ"));
@@ -1560,8 +1560,8 @@ public class S3Service {
return normalized;
}
private static String ownerFullControlGrant() {
return canonicalUserGrant(DEFAULT_OWNER_ID, DEFAULT_OWNER_DISPLAY_NAME, "FULL_CONTROL");
private String ownerFullControlGrant() {
return canonicalUserGrant(ownerId(), DEFAULT_OWNER_DISPLAY_NAME, "FULL_CONTROL");
}
private static String canonicalUserGrant(String id, String displayName, String permission) {
@@ -1587,11 +1587,11 @@ public class S3Service {
.build();
}
private static String objectAclXml(String... grants) {
private String objectAclXml(String... grants) {
XmlBuilder xml = new XmlBuilder()
.start("AccessControlPolicy")
.start("Owner")
.elem("ID", DEFAULT_OWNER_ID)
.elem("ID", ownerId())
.elem("DisplayName", DEFAULT_OWNER_DISPLAY_NAME)
.end("Owner")
.start("AccessControlList");
@@ -133,7 +133,8 @@ public class ScheduleDispatcher {
if (kind == Kind.AT && isDeleteAfterCompletion(schedule)) {
try {
schedulerService.deleteSchedule(schedule.getName(), schedule.getGroupName(), regionOf(schedule));
schedulerService.deleteScheduleForAccount(
schedule.getAccountId(), schedule.getName(), schedule.getGroupName(), regionOf(schedule));
lastFireByArn.remove(schedule.getArn());
firedOnceByArn.remove(schedule.getArn());
} catch (Exception e) {
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.scheduler;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
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.scheduler.model.Schedule;
@@ -199,6 +200,7 @@ public class SchedulerService {
schedule.setKmsKeyArn(req.getKmsKeyArn());
schedule.setCreationDate(now);
schedule.setLastModificationDate(now);
schedule.setAccountId(regionResolver.getAccountId());
scheduleStore.put(key, schedule);
LOG.infov("Created schedule: {0} in group {1}, region {2}", req.getName(), effectiveGroup, region);
@@ -257,14 +259,28 @@ public class SchedulerService {
}
/**
* Return every persisted schedule across all regions and groups. Used by
* {@link ScheduleDispatcher} to evaluate due schedules; other callers should
* prefer {@link #listSchedules}.
* Return every persisted schedule across all regions, groups, and accounts.
* Used by {@link ScheduleDispatcher} to evaluate due schedules; other callers
* should prefer {@link #listSchedules}.
*/
public List<Schedule> listAllSchedules() {
if (scheduleStore instanceof AccountAwareStorageBackend<Schedule> aware) {
return aware.scanAllAccounts();
}
return scheduleStore.scan(k -> k.startsWith("schedule:"));
}
public void deleteScheduleForAccount(String accountId, String name, String groupName, String region) {
String effectiveGroup = resolveAndValidateGroup(groupName);
String key = scheduleKey(region, effectiveGroup, name);
if (scheduleStore instanceof AccountAwareStorageBackend<Schedule> aware) {
aware.deleteForAccount(accountId, key);
} else {
scheduleStore.delete(key);
}
LOG.infov("Deleted schedule: {0} in group {1}", name, effectiveGroup);
}
public List<Schedule> listSchedules(String groupName, String namePrefix, String state, String region) {
String storagePrefix;
if (groupName != null && !groupName.isBlank()) {
@@ -10,6 +10,7 @@ public class Schedule {
private String name;
private String arn;
private String groupName;
private String accountId;
private String state;
private String scheduleExpression;
private String scheduleExpressionTimezone;
@@ -28,6 +29,9 @@ public class Schedule {
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
@@ -198,6 +198,7 @@ public class SnsService {
String subscriptionArn = topicArn + ":" + UUID.randomUUID().toString();
Subscription subscription = new Subscription(subscriptionArn, topicArn, protocol, endpoint,
regionResolver.getAccountId());
subscription.setAccountId(regionResolver.getAccountId());
if (attributes != null) subscription.getAttributes().putAll(attributes);
if (PENDING_CONFIRMATION_PROTOCOLS.contains(protocol)) {
@@ -26,6 +26,8 @@ public class Subscription {
@JsonProperty("Owner")
private String owner;
private String accountId;
@JsonProperty("Attributes")
private Map<String, String> attributes = new HashMap<>();
@@ -51,6 +53,9 @@ public class Subscription {
public String getEndpoint() { return endpoint; }
public void setEndpoint(String endpoint) { this.endpoint = endpoint; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getOwner() { return owner; }
public void setOwner(String owner) { this.owner = owner; }
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
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.sns.SnsService;
@@ -106,9 +107,14 @@ public class SqsService {
if (messageStore == null) {
return;
}
for (String key : messageStore.keys()) {
messageStore.get(key).ifPresent(msgs ->
if (messageStore instanceof AccountAwareStorageBackend<List<Message>> aware) {
aware.scanAllAccountsAsMap().forEach((key, msgs) ->
messagesByQueue.put(key, new GuardedMessageQueue(msgs, messageStore, key)));
} else {
for (String key : messageStore.keys()) {
messageStore.get(key).ifPresent(msgs ->
messagesByQueue.put(key, new GuardedMessageQueue(msgs, messageStore, key)));
}
}
}
@@ -117,19 +123,25 @@ public class SqsService {
return;
}
Instant now = Instant.now();
for (String key : dedupStore.keys()) {
dedupStore.get(key).ifPresent(entries -> {
ConcurrentHashMap<String, Instant> active = new ConcurrentHashMap<>();
entries.forEach((dedupId, expiryMs) -> {
Instant expiry = Instant.ofEpochMilli(expiryMs);
if (now.isBefore(expiry)) {
active.put(dedupId, expiry);
}
});
if (!active.isEmpty()) {
deduplicationCache.put(key, active);
}
});
if (dedupStore instanceof AccountAwareStorageBackend<Map<String, Long>> aware) {
aware.scanAllAccountsAsMap().forEach((key, entries) -> loadDedupEntries(key, entries, now));
} else {
for (String key : dedupStore.keys()) {
dedupStore.get(key).ifPresent(entries -> loadDedupEntries(key, entries, now));
}
}
}
private void loadDedupEntries(String key, Map<String, Long> entries, Instant now) {
ConcurrentHashMap<String, Instant> active = new ConcurrentHashMap<>();
entries.forEach((dedupId, expiryMs) -> {
Instant expiry = Instant.ofEpochMilli(expiryMs);
if (now.isBefore(expiry)) {
active.put(dedupId, expiry);
}
});
if (!active.isEmpty()) {
deduplicationCache.put(key, active);
}
}
@@ -200,6 +212,7 @@ public class SqsService {
}
Queue queue = new Queue(queueName, queueUrl);
queue.setAccountId(regionResolver.getAccountId());
if (attributes != null) {
queue.getAttributes().putAll(attributes);
}
@@ -337,7 +350,7 @@ public class SqsService {
Map<String, MessageAttributeValue> messageAttributes,
String region) {
String storageKey = regionKey(region, queueUrl);
Queue queue = queueStore.get(storageKey)
Queue queue = getQueueByUrl(storageKey, queueUrl)
.orElseThrow(() -> new AwsException("AWS.SimpleQueueService.NonExistentQueue",
"The specified queue does not exist.", 400));
@@ -488,7 +501,7 @@ public class SqsService {
public List<Message> receiveMessage(String queueUrl, int maxMessages, int visibilityTimeout,
int waitTimeSeconds, String region) {
String storageKey = regionKey(region, queueUrl);
queueStore.get(storageKey)
getQueueByUrl(storageKey, queueUrl)
.orElseThrow(() -> new AwsException("AWS.SimpleQueueService.NonExistentQueue",
"The specified queue does not exist.", 400));
@@ -615,7 +628,10 @@ public class SqsService {
public void deleteMessage(String queueUrl, String receiptHandle, String region) {
String storageKey = regionKey(region, queueUrl);
ensureQueueExists(storageKey);
if (getQueueByUrl(storageKey, queueUrl).isEmpty()) {
throw new AwsException("AWS.SimpleQueueService.NonExistentQueue",
"The specified queue does not exist.", 400);
}
Optional<Message> removed = getOrCreateQueue(storageKey).removeByReceiptHandle(receiptHandle);
@@ -812,4 +828,30 @@ public class SqsService {
"The specified queue does not exist.", 400);
}
}
/**
* Looks up a queue by URL, deriving the account from the URL path rather than from request
* context. This allows background workers (e.g. pollers) to access queues for any account
* without a live CDI request scope.
*/
private Optional<Queue> getQueueByUrl(String storageKey, String queueUrl) {
if (queueStore instanceof AccountAwareStorageBackend<Queue> aware) {
String accountId = accountFromQueueUrl(queueUrl);
if (accountId != null) {
return aware.getForAccount(accountId, storageKey);
}
}
return queueStore.get(storageKey);
}
private static String accountFromQueueUrl(String queueUrl) {
String path = extractQueuePath(queueUrl); // "/000000000001/queueName"
if (path == null || path.isEmpty()) {
return null;
}
String trimmed = path.startsWith("/") ? path.substring(1) : path;
int slash = trimmed.indexOf('/');
String candidate = slash > 0 ? trimmed.substring(0, slash) : trimmed;
return candidate.matches("\\d{12}") ? candidate : null;
}
}
@@ -14,6 +14,7 @@ public class Queue {
private String queueName;
private String queueUrl;
private String accountId;
private Map<String, String> attributes;
private Map<String, String> tags;
private Instant createdTimestamp;
@@ -39,6 +40,9 @@ public class Queue {
public String getQueueUrl() { return queueUrl; }
public void setQueueUrl(String queueUrl) { this.queueUrl = queueUrl; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public Map<String, String> getAttributes() { return attributes; }
public void setAttributes(Map<String, String> attributes) { this.attributes = attributes; }
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.transfer;
import com.fasterxml.jackson.core.type.TypeReference;
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.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.transfer.model.HomeDirectoryMapping;
@@ -27,17 +28,17 @@ public class TransferService {
private final StorageBackend<String, Server> serverStore;
private final StorageBackend<String, User> userStore;
private final StorageBackend<String, Map<String, String>> tagStore;
private final String accountId;
private final RegionResolver regionResolver;
@Inject
public TransferService(StorageFactory factory, EmulatorConfig config) {
public TransferService(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver) {
this.serverStore = factory.create("transfer", "transfer-servers.json",
new TypeReference<Map<String, Server>>() {});
this.userStore = factory.create("transfer", "transfer-users.json",
new TypeReference<Map<String, User>>() {});
this.tagStore = factory.create("transfer", "transfer-tags.json",
new TypeReference<Map<String, Map<String, String>>>() {});
this.accountId = config.defaultAccountId();
this.regionResolver = regionResolver;
}
// ── Servers ───────────────────────────────────────────────────────────────
@@ -52,7 +53,7 @@ public class TransferService {
String securityPolicyName,
Map<String, String> tags) {
String serverId = generateServerId();
String arn = "arn:aws:transfer:" + region + ":" + accountId + ":server/" + serverId;
String arn = "arn:aws:transfer:" + region + ":" + regionResolver.getAccountId() + ":server/" + serverId;
Server server = new Server();
server.setServerId(serverId);
@@ -179,7 +180,7 @@ public class TransferService {
"User " + userName + " already exists on server " + serverId + ".", 400);
}
String arn = "arn:aws:transfer:" + region + ":" + accountId + ":user/" + serverId + "/" + userName;
String arn = "arn:aws:transfer:" + region + ":" + regionResolver.getAccountId() + ":user/" + serverId + "/" + userName;
User user = new User();
user.setUserName(userName);
user.setArn(arn);