diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java new file mode 100644 index 0000000000..36b85efb5d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/AccountContextFilter.java @@ -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)); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AccountResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/AccountResolver.java new file mode 100644 index 0000000000..86fd47cad5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/AccountResolver.java @@ -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; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index 5ccc31c6c1..b6df884d7c 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -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; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java index a1d07e6d11..35933043fd 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java @@ -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 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(); } } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestContext.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestContext.java new file mode 100644 index 0000000000..3ec09e735b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestContext.java @@ -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; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java new file mode 100644 index 0000000000..35bbe31fec --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java @@ -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. + * + *

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. + * + *

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. + * + *

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 implements StorageBackend { + + private final StorageBackend delegate; + private final Instance requestContextInstance; + private final String defaultAccountId; + + public AccountAwareStorageBackend(StorageBackend delegate, + Instance 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 get(String key) { + String prefixedKey = prefixed(key); + Optional 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 scan(Predicate keyFilter) { + String prefix = prefix() + "/"; + return delegate.scan(k -> k.startsWith(prefix) && keyFilter.test(k.substring(prefix.length()))); + } + + @Override + public Set 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 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 scanAllAccountsAsMap() { + Map 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 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 scanForAccount(String accountId, Predicate keyFilter) { + String prefix = accountId + "/"; + return delegate.scan(k -> k.startsWith(prefix) && keyFilter.test(k.substring(prefix.length()))); + } + + public Set 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; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java b/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java index 10d6274c59..2cdeaf58dd 100644 --- a/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java +++ b/src/main/java/io/github/hectorvent/floci/core/storage/StorageFactory.java @@ -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> hybridBackends = new ArrayList<>(); private final List> walBackends = new ArrayList<>(); + @Inject + Instance 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 StorageBackend create(String serviceName, String fileName, - TypeReference> typeReference) { + public StorageBackend create(String serviceName, String fileName, + TypeReference> 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 backend = switch (mode) { + StorageBackend 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 backend = new AccountAwareStorageBackend<>( + inner, requestContextInstance, config.defaultAccountId()); allBackends.add(backend); return backend; } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java index 4f287c6358..16ce8b08d6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java @@ -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 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java index 0fc6f1df4d..b155756e69 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java @@ -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 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"); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index 4eeb7124cf..ff8ee0b64e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -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); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index 9dc4e23677..8d59363b8b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -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 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 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 resolvedParams = resolveDefaultParameters(template, params); // Resolve conditions first - Map conditions = resolveConditions(template, resolvedParams, stack, region); + Map conditions = resolveConditions(template, resolvedParams, stack, region, accountId); // Mappings Map 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 resolveConditions(JsonNode template, Map params, - Stack stack, String region) { + Stack stack, String region, String accountId) { Map 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 params, - Map conditions) { + Map 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 params) { + private String resolveConditionValue(JsonNode node, Map 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; diff --git a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java index c6ff6e0e92..b4e34937de 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java +++ b/src/main/java/io/github/hectorvent/floci/services/codebuild/CodeBuildRunner.java @@ -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 runningContainers = new ConcurrentHashMap<>(); private final ConcurrentHashMap 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 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 envList = buildEnvList(region, build, project, buildspec, logStream); diff --git a/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java b/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java index 79b1623bbb..6f9fc33b7b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java +++ b/src/main/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployService.java @@ -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 lambdaTargetMap = new ConcurrentHashMap<>(); lambdaTargetMap.put("deploymentId", deploymentId); lambdaTargetMap.put("targetId", targetId); @@ -591,7 +594,7 @@ public class CodeDeployService { Map 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 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") diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java index 0d4552c28f..f900335ad8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java @@ -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 allTables; + if (tableStore instanceof AccountAwareStorageBackend aware) { + allTables = aware.scanAllAccountsAsMap(); + } else { + allTables = new HashMap<>(); + tableStore.keys().forEach(k -> tableStore.get(k).ifPresent(v -> allTables.put(k, v))); + } + for (Map.Entry entry : allTables.entrySet()) { + String storageKey = entry.getKey(); + TableDefinition table = entry.getValue(); + if (!table.isTtlEnabled() || table.getTtlAttributeName() == null) { continue; } var items = itemsByTable.get(storageKey); diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java index 0aed6df138..9eaa765c52 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java @@ -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 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>() {}), factory.create("ecr", "image-metadata.json", new TypeReference>() {}), - registryManager, config); + registryManager, config, regionResolver); } EcrService(StorageBackend repoStore, StorageBackend 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) { diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java index e5b2ab7b31..411d709390 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java @@ -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 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>() {}); 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 allClusters() { + if (storage instanceof AccountAwareStorageBackend aware) { + return aware.scanAllAccounts(); + } + return storage.scan(k -> true); + } + + private void putCluster(Cluster cluster) { + if (cluster.getAccountId() != null && storage instanceof AccountAwareStorageBackend aware) { + aware.putForAccount(cluster.getAccountId(), cluster.getName(), cluster); + } else { + storage.put(cluster.getName(), cluster); + } + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java index 6d1a7598a8..7215bd94b6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java @@ -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; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java index 6f5b05d2fc..faced73199 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java @@ -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 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(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java index 8e35b5dfb5..5eab8c8755 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java @@ -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> 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java index 82b9692b21..48940fba1e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java @@ -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 allRules = ruleStore instanceof AccountAwareStorageBackend 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> entries) {} public PutEventsResult putEvents(List> entries, String region) { + return putEvents(entries, region, null); + } + + private PutEventsResult putEvents(List> entries, String region, String accountId) { int failed = 0; List> 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 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 matchedRules = ruleStore.scan(k -> - k.startsWith(rulePrefix) && isRuleEnabled(k)); + List 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 targets = targetStore.get(ruleKey).orElse(List.of()); + List 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 successEntry = new HashMap<>(); successEntry.put("EventId", eventId); @@ -913,16 +922,16 @@ public class EventBridgeService { } private void captureToArchives(Map 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 candidates = archiveStore.scan(k -> + List 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 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 t = targetStore.get(key).orElse(List.of()); + Rule r = accountGet(ruleStore, accountId, key).orElse(null); + List t = accountGet(targetStore, accountId, key).orElse(List.of()); return new RuleScheduler.ScheduleData(r, t); } ); } } + private java.util.Optional accountGet(StorageBackend store, String accountId, String key) { + if (accountId != null && store instanceof AccountAwareStorageBackend aware) { + return aware.getForAccount(accountId, key); + } + return store.get(key); + } + + private List accountScan(StorageBackend store, String accountId, + java.util.function.Predicate filter) { + if (accountId != null && store instanceof AccountAwareStorageBackend aware) { + return aware.scanForAccount(accountId, filter); + } + return store.scan(filter); + } + + private void accountPut(StorageBackend store, String accountId, String key, V value) { + if (accountId != null && store instanceof AccountAwareStorageBackend aware) { + aware.putForAccount(accountId, key, value); + } else { + store.put(key, value); + } + } + } diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/RuleScheduler.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/RuleScheduler.java index 89b29882f2..367f81fa45 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/RuleScheduler.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/RuleScheduler.java @@ -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 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()); diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Replay.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Replay.java index 66c939a8db..39b3c53e87 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Replay.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Replay.java @@ -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; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Rule.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Rule.java index cec437530a..0d91ca7132 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Rule.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/Rule.java @@ -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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java b/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java index cd72338452..32d2bae73f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java +++ b/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java @@ -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); diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/model/DeliveryStreamDescription.java b/src/main/java/io/github/hectorvent/floci/services/firehose/model/DeliveryStreamDescription.java index c7875a337d..8a4a2bce58 100644 --- a/src/main/java/io/github/hectorvent/floci/services/firehose/model/DeliveryStreamDescription.java +++ b/src/main/java/io/github/hectorvent/floci/services/firehose/model/DeliveryStreamDescription.java @@ -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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java index 309f083f07..0cee292dbb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java @@ -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 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 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 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 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 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(); diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesis/model/KinesisStream.java b/src/main/java/io/github/hectorvent/floci/services/kinesis/model/KinesisStream.java index f57a132ea4..e6c12cd533 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kinesis/model/KinesisStream.java +++ b/src/main/java/io/github/hectorvent/floci/services/kinesis/model/KinesisStream.java @@ -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 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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java index d7d276af20..2616f683a2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java @@ -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()); diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java index 4277fe890b..5757cabc12 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java @@ -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); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java index 29b37913a8..a0e3391e27 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java @@ -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()); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/EsmStore.java b/src/main/java/io/github/hectorvent/floci/services/lambda/EsmStore.java index f7dfd92b90..7dd6bfc1c2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/EsmStore.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/EsmStore.java @@ -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 aware) { + aware.putForAccount(accountId, esm.getUuid(), esm); + } else { + backend.put(esm.getUuid(), esm); + } + } + public Optional 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 listAll() { + if (backend instanceof AccountAwareStorageBackend aware) { + return aware.scanAllAccounts(); + } + return backend.scan(k -> true); + } + + public Optional getForAccount(String accountId, String uuid) { + if (backend instanceof AccountAwareStorageBackend aware) { + return aware.getForAccount(accountId, uuid); + } + return backend.get(uuid); + } + public List listByFunction(String functionKey) { return backend.scan(k -> { var esm = backend.get(k).orElse(null); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java index c8062bac04..b594661175 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java @@ -62,7 +62,7 @@ public class KinesisEventSourcePoller { } public void startPersistedPollers() { - List esms = esmStore.list(); + List 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStore.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStore.java index 1a5f2db281..c88af06b4f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStore.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStore.java @@ -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 all = backend instanceof AccountAwareStorageBackend 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 getForAccount(String accountId, String region, String functionName) { + if (backend instanceof AccountAwareStorageBackend aware) { + return aware.getForAccount(accountId, regionKey(region, functionName, "$LATEST")); + } + return backend.get(regionKey(region, functionName, "$LATEST")); + } + public Optional getByUrlId(String urlId) { return Optional.ofNullable(urlIdIndex.get(urlId)); } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java index 4cee9d4cef..297d25b92c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java @@ -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); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java index 48b1d9c2f5..3c1f424afe 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/SqsEventSourcePoller.java @@ -69,7 +69,7 @@ public class SqsEventSourcePoller { } public void startPersistedPollers() { - List esms = esmStore.list(); + List 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", diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java index 38fdb60c67..548aa40eee 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/EventSourceMapping.java @@ -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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java index 635a144625..0ca6751343 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaFunction.java @@ -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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java b/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java index 2e1be3b39c..0d1605a176 100644 --- a/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java +++ b/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java @@ -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 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>() {}); 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 allClusters() { + if (storage instanceof AccountAwareStorageBackend aware) { + return aware.scanAllAccounts(); + } + return storage.scan(k -> true); + } + + private void putCluster(MskCluster cluster) { + if (cluster.getAccountId() != null && storage instanceof AccountAwareStorageBackend aware) { + aware.putForAccount(cluster.getAccountId(), cluster.getClusterArn(), cluster); + } else { + storage.put(cluster.getClusterArn(), cluster); + } + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/msk/model/MskCluster.java b/src/main/java/io/github/hectorvent/floci/services/msk/model/MskCluster.java index 36835f694b..ed081def37 100644 --- a/src/main/java/io/github/hectorvent/floci/services/msk/model/MskCluster.java +++ b/src/main/java/io/github/hectorvent/floci/services/msk/model/MskCluster.java @@ -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; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java index 4df5894713..cc8ca85542 100644 --- a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java +++ b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java @@ -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 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>() {}); this.config = config; + this.regionResolver = regionResolver; this.domainManager = domainManager; } OpenSearchService(StorageBackend 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 allDomains() { + if (domainStore instanceof AccountAwareStorageBackend aware) { + return aware.scanAllAccounts(); + } + return domainStore.scan(k -> true); + } + + private void putDomain(Domain domain) { + if (domain.getAccountId() != null && domainStore instanceof AccountAwareStorageBackend aware) { + aware.putForAccount(domain.getAccountId(), domain.getDomainName(), domain); + } else { + domainStore.put(domain.getDomainName(), domain); + } + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/opensearch/model/Domain.java b/src/main/java/io/github/hectorvent/floci/services/opensearch/model/Domain.java index 64fafa51e7..6ed510ae97 100644 --- a/src/main/java/io/github/hectorvent/floci/services/opensearch/model/Domain.java +++ b/src/main/java/io/github/hectorvent/floci/services/opensearch/model/Domain.java @@ -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; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java index 3ef14f74f0..efdedfdf37 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java +++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java @@ -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 result = kinesisService.getRecords(iterator, batchSize, region); + Map 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; diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java index 970dfb4c02..366b66a602 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java +++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java @@ -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 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>() {}); - this.config = config; + this.regionResolver = regionResolver; this.poller = poller; } public void startPersistedPollers() { - List runningPipes = storage.scan(key -> true).stream() + List allPipes = storage instanceof AccountAwareStorageBackend aware + ? aware.scanAllAccounts() + : storage.scan(key -> true); + List 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/model/Pipe.java b/src/main/java/io/github/hectorvent/floci/services/pipes/model/Pipe.java index 4c852d8781..f27512e2b8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pipes/model/Pipe.java +++ b/src/main/java/io/github/hectorvent/floci/services/pipes/model/Pipe.java @@ -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; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index b3f5d6abaa..64eab0060b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -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"); diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java index 6d3b8dc33c..bb276a7101 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java @@ -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) { diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java index 55f964b53c..0176996e09 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java @@ -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 listAllSchedules() { + if (scheduleStore instanceof AccountAwareStorageBackend 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 aware) { + aware.deleteForAccount(accountId, key); + } else { + scheduleStore.delete(key); + } + LOG.infov("Deleted schedule: {0} in group {1}", name, effectiveGroup); + } + public List listSchedules(String groupName, String namePrefix, String state, String region) { String storagePrefix; if (groupName != null && !groupName.isBlank()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/model/Schedule.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/model/Schedule.java index 11e3a5119a..d56c44e109 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/model/Schedule.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/model/Schedule.java @@ -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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java index 59253903e8..1642e52aee 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java @@ -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)) { diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/model/Subscription.java b/src/main/java/io/github/hectorvent/floci/services/sns/model/Subscription.java index 154abfae46..3b110855e9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sns/model/Subscription.java +++ b/src/main/java/io/github/hectorvent/floci/services/sns/model/Subscription.java @@ -26,6 +26,8 @@ public class Subscription { @JsonProperty("Owner") private String owner; + private String accountId; + @JsonProperty("Attributes") private Map 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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java index 2f8d237fe2..0a843b825b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java @@ -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> 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 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> 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 entries, Instant now) { + ConcurrentHashMap 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 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 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 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 getQueueByUrl(String storageKey, String queueUrl) { + if (queueStore instanceof AccountAwareStorageBackend 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; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/model/Queue.java b/src/main/java/io/github/hectorvent/floci/services/sqs/model/Queue.java index 4466b29456..2be8822a06 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sqs/model/Queue.java +++ b/src/main/java/io/github/hectorvent/floci/services/sqs/model/Queue.java @@ -14,6 +14,7 @@ public class Queue { private String queueName; private String queueUrl; + private String accountId; private Map attributes; private Map 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 getAttributes() { return attributes; } public void setAttributes(Map attributes) { this.attributes = attributes; } diff --git a/src/main/java/io/github/hectorvent/floci/services/transfer/TransferService.java b/src/main/java/io/github/hectorvent/floci/services/transfer/TransferService.java index bf451a873d..ae948b0619 100644 --- a/src/main/java/io/github/hectorvent/floci/services/transfer/TransferService.java +++ b/src/main/java/io/github/hectorvent/floci/services/transfer/TransferService.java @@ -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 serverStore; private final StorageBackend userStore; private final StorageBackend> 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>() {}); this.userStore = factory.create("transfer", "transfer-users.json", new TypeReference>() {}); this.tagStore = factory.create("transfer", "transfer-tags.json", new TypeReference>>() {}); - this.accountId = config.defaultAccountId(); + this.regionResolver = regionResolver; } // ── Servers ─────────────────────────────────────────────────────────────── @@ -52,7 +53,7 @@ public class TransferService { String securityPolicyName, Map 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); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AccountIsolationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AccountIsolationIntegrationTest.java new file mode 100644 index 0000000000..763778f58c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/AccountIsolationIntegrationTest.java @@ -0,0 +1,183 @@ +package io.github.hectorvent.floci.core.common; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +/** + * Verifies that resources are isolated between accounts. + * Uses 12-digit numeric access key IDs so they are used directly as account IDs. + */ +@QuarkusTest +class AccountIsolationIntegrationTest { + + private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + // 12-digit numeric keys → used directly as account IDs + private static final String AUTH_ACCOUNT_1 = + "AWS4-HMAC-SHA256 Credential=000000000001/20260215/us-east-1/sqs/aws4_request, SignedHeaders=host, Signature=abc"; + private static final String AUTH_ACCOUNT_2 = + "AWS4-HMAC-SHA256 Credential=000000000002/20260215/us-east-1/sqs/aws4_request, SignedHeaders=host, Signature=abc"; + private static final String AUTH_ACCOUNT_1_SSM = + "AWS4-HMAC-SHA256 Credential=000000000001/20260215/us-east-1/ssm/aws4_request, SignedHeaders=host, Signature=abc"; + private static final String AUTH_ACCOUNT_2_SSM = + "AWS4-HMAC-SHA256 Credential=000000000002/20260215/us-east-1/ssm/aws4_request, SignedHeaders=host, Signature=abc"; + + @Test + void sqsQueuesAreIsolatedBetweenAccounts() { + // Account 1 creates a queue + given() + .header("Authorization", AUTH_ACCOUNT_1) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateQueue") + .formParam("QueueName", "account-isolation-queue") + .when().post("/") + .then() + .statusCode(200) + .body(containsString("000000000001")) + .body(containsString("account-isolation-queue")); + + // Account 2 lists queues — should NOT see account 1's queue + given() + .header("Authorization", AUTH_ACCOUNT_2) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListQueues") + .formParam("QueueNamePrefix", "account-isolation-queue") + .when().post("/") + .then() + .statusCode(200) + .body(not(containsString("account-isolation-queue"))); + + // Account 1 lists queues — should see its queue + given() + .header("Authorization", AUTH_ACCOUNT_1) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListQueues") + .formParam("QueueNamePrefix", "account-isolation-queue") + .when().post("/") + .then() + .statusCode(200) + .body(containsString("account-isolation-queue")); + } + + @Test + void sqsQueuesWithSameNameInDifferentAccountsAreIndependent() { + // Both accounts create a queue with the same name + given() + .header("Authorization", AUTH_ACCOUNT_1) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateQueue") + .formParam("QueueName", "shared-name-queue") + .when().post("/") + .then() + .statusCode(200) + .body(containsString("000000000001/shared-name-queue")); + + given() + .header("Authorization", AUTH_ACCOUNT_2) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateQueue") + .formParam("QueueName", "shared-name-queue") + .when().post("/") + .then() + .statusCode(200) + .body(containsString("000000000002/shared-name-queue")); + + // Account 1 sends a message to its queue + given() + .header("Authorization", AUTH_ACCOUNT_1) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "SendMessage") + .formParam("QueueUrl", "http://localhost:8081/000000000001/shared-name-queue") + .formParam("MessageBody", "message-for-account-1") + .when().post("/") + .then() + .statusCode(200); + + // Account 2 receives from its own queue — should get nothing (empty queue) + given() + .header("Authorization", AUTH_ACCOUNT_2) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ReceiveMessage") + .formParam("QueueUrl", "http://localhost:8081/000000000002/shared-name-queue") + .formParam("MaxNumberOfMessages", "1") + .formParam("WaitTimeSeconds", "0") + .when().post("/") + .then() + .statusCode(200) + .body(not(containsString("message-for-account-1"))); + } + + @Test + void ssmParametersAreIsolatedBetweenAccounts() { + // Account 1 puts a parameter + given() + .header("X-Amz-Target", "AmazonSSM.PutParameter") + .header("Authorization", AUTH_ACCOUNT_1_SSM) + .contentType(SSM_CONTENT_TYPE) + .body(""" + {"Name": "/account-isolation/key", "Value": "value-for-account-1", "Type": "String"} + """) + .when().post("/") + .then() + .statusCode(200); + + // Account 2 tries to get the same parameter — should not find it + given() + .header("X-Amz-Target", "AmazonSSM.GetParameter") + .header("Authorization", AUTH_ACCOUNT_2_SSM) + .contentType(SSM_CONTENT_TYPE) + .body(""" + {"Name": "/account-isolation/key"} + """) + .when().post("/") + .then() + .statusCode(400); + + // Account 1 can retrieve its parameter, ARN contains its account ID + given() + .header("X-Amz-Target", "AmazonSSM.GetParameter") + .header("Authorization", AUTH_ACCOUNT_1_SSM) + .contentType(SSM_CONTENT_TYPE) + .body(""" + {"Name": "/account-isolation/key"} + """) + .when().post("/") + .then() + .statusCode(200) + .body("Parameter.Value", equalTo("value-for-account-1")) + .body("Parameter.ARN", containsString("000000000001")); + } + + @Test + void sqsQueueArnContainsCorrectAccountId() { + given() + .header("Authorization", AUTH_ACCOUNT_1) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateQueue") + .formParam("QueueName", "arn-account-check-queue") + .when().post("/") + .then().statusCode(200); + + // GetQueueAttributes — QueueArn should embed account 1's ID + given() + .header("Authorization", AUTH_ACCOUNT_1) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "GetQueueAttributes") + .formParam("QueueUrl", "http://localhost:8081/000000000001/arn-account-check-queue") + .formParam("AttributeName.1", "QueueArn") + .when().post("/") + .then() + .statusCode(200) + .body(containsString("arn:aws:sqs:us-east-1:000000000001:arn-account-check-queue")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/StorageFactoryServiceCatalogIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/storage/StorageFactoryServiceCatalogIntegrationTest.java index 5d3fff8462..ee6d06406b 100644 --- a/src/test/java/io/github/hectorvent/floci/core/storage/StorageFactoryServiceCatalogIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/storage/StorageFactoryServiceCatalogIntegrationTest.java @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; @QuarkusTest @TestProfile(StorageFactoryServiceCatalogIntegrationTest.AcmPersistentStorageProfile.class) @@ -26,7 +27,7 @@ class StorageFactoryServiceCatalogIntegrationTest { new TypeReference>() {} ); - assertInstanceOf(PersistentStorage.class, backend); + assertInstanceOf(AccountAwareStorageBackend.class, backend); } public static final class AcmPersistentStorageProfile implements QuarkusTestProfile { diff --git a/src/test/java/io/github/hectorvent/floci/services/ecr/EcrServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ecr/EcrServiceTest.java index e3b4f816a8..580a32e0fc 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecr/EcrServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecr/EcrServiceTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ecr; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.ecr.model.AuthorizationData; import io.github.hectorvent.floci.services.ecr.model.ImageMetadata; @@ -45,13 +46,14 @@ class EcrServiceTest { // ensureStarted() is a no-op on the mock — no Docker calls in any test below. EmulatorConfig config = Mockito.mock(EmulatorConfig.class); - when(config.defaultAccountId()).thenReturn(ACCOUNT); + RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT); service = new EcrService( new InMemoryStorage<>(), new InMemoryStorage<>(), registryManager, - config); + config, + regionResolver); } // ------------------------------------------------------------ diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java index c1a8b64db8..e876805ed1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eks; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.eks.model.ClusterStatus; @@ -38,10 +39,10 @@ class EksServiceTest { when(eksConfig.mock()).thenReturn(true); when(eksConfig.apiServerBasePort()).thenReturn(6500); when(config.defaultRegion()).thenReturn("us-east-1"); - when(config.defaultAccountId()).thenReturn("000000000000"); clusterManager = Mockito.mock(EksClusterManager.class); - eksService = new EksService(storageFactory, config, clusterManager); + RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); + eksService = new EksService(storageFactory, config, regionResolver, clusterManager); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java index 698d312224..3a751bf6da 100644 --- a/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java @@ -198,9 +198,9 @@ class GlueServiceTest { } @Override - public StorageBackend create(String serviceName, - String fileName, - TypeReference> typeReference) { + public StorageBackend create(String serviceName, + String fileName, + TypeReference> typeReference) { return new InMemoryStorage<>(); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/msk/MskServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/msk/MskServiceTest.java index d547c68d26..4879a556cb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/msk/MskServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/msk/MskServiceTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.msk; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.msk.model.ClusterState; @@ -33,10 +34,12 @@ class MskServiceTest { when(config.services()).thenReturn(servicesConfig); when(servicesConfig.msk()).thenReturn(mskConfig); - when(mskConfig.mock()).thenReturn(true); // Mock mode for unit tests + when(mskConfig.mock()).thenReturn(true); + when(config.defaultRegion()).thenReturn("us-east-1"); redpandaManager = Mockito.mock(RedpandaManager.class); - mskService = new MskService(storageFactory, config, redpandaManager); + RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); + mskService = new MskService(storageFactory, config, regionResolver, redpandaManager); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesServiceTest.java index 6b2644ebc2..36cd367122 100644 --- a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesServiceTest.java @@ -1,7 +1,7 @@ package io.github.hectorvent.floci.services.pipes; -import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.pipes.model.DesiredState; @@ -28,11 +28,10 @@ class PipesServiceTest { when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any())) .thenReturn(new InMemoryStorage<>()); - EmulatorConfig config = Mockito.mock(EmulatorConfig.class); - when(config.defaultAccountId()).thenReturn("000000000000"); + RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000"); PipesPoller poller = Mockito.mock(PipesPoller.class); - pipesService = new PipesService(storageFactory, config, poller); + pipesService = new PipesService(storageFactory, regionResolver, poller); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java index e38df056bd..b57f72c0c6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcherTest.java @@ -91,11 +91,12 @@ class ScheduleDispatcherTest { void deletesAtScheduleWhenActionAfterCompletionIsDelete() { Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED"); s.setActionAfterCompletion("DELETE"); + s.setAccountId("000000000000"); when(schedulerService.listAllSchedules()).thenReturn(List.of(s)); dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z")); - verify(schedulerService, times(1)).deleteSchedule("at1", "default", "eu-central-1"); + verify(schedulerService, times(1)).deleteScheduleForAccount("000000000000", "at1", "default", "eu-central-1"); } @Test