diff --git a/docs/services/appsync.md b/docs/services/appsync.md index 5d1db13d95..50326628bc 100644 --- a/docs/services/appsync.md +++ b/docs/services/appsync.md @@ -5,6 +5,14 @@ Floci implements the AWS AppSync Management API, providing local emulation of GraphQL API configuration, schema management, data source binding, resolver mapping, API key provisioning, custom domains, and channel namespaces. +## Regions + +GraphQL APIs and custom domain names are Regional, as on AWS: each is listed and reached only in the Region it was +created in, and so are an API's data sources, resolvers, functions, types, API keys, channel namespaces and merged-API +associations. Another Region's is answered for as one that doesn't exist. A domain name stays unique across the account's Regions: +creating one that another Region holds is refused. An API's endpoint, `/v1/apis/{apiId}/graphql`, names no +Region, so a query reaches the API whatever Region it is signed for, or none with an API key, and runs in the API's. + ## OIDC issuer network policy AppSync OIDC authentication uses the shared JWT issuer policy. By default, issuer discovery and @@ -265,7 +273,7 @@ Configured modes are the API default `authenticationType` plus `additionalAuthen | Mode | Emulator notes | |---|---| | API_KEY | Lookup by `ApiKey.id`, which is the key value (`da2-…`). Identity is absent (not `{}`). Default key expiry is 7 days when `expires` is omitted; stored `expires` is rounded down to the nearest hour. Create/UpdateApiKey require `expires` between 1 and 365 days from now (`ApiKeyValidityOutOfBoundsException`, 400). `deletes` is `expires` plus 60 days. | -| AWS_IAM | Verifies a real header-signed SigV4 request (`appsync` service, fixed `/v1/apis/{apiId}/graphql` canonical path, 5-minute clock skew): the `Credential=` access key must resolve to a secret via `IamService`, and the signature must match. The legacy `test`/`test` pair is still emulator ALLOW, but it must be signed with secret `test` like any other key, and it is not a bypass. A temporary (`ASIA...`) credential must also present the `X-Amz-Security-Token` header issued with it, and a long-term key must present none, as on AWS. The `test` key takes any token. An unknown key is 403 and an unsigned one 401, and neither becomes the account-root identity. The checks run in AppSync's order. The scope's region is not checked, because Floci takes the request's region from it. Known keys additionally evaluate `appsync:GraphQL`. | +| AWS_IAM | Verifies a real header-signed SigV4 request (`appsync` service, fixed `/v1/apis/{apiId}/graphql` canonical path, 5-minute clock skew): the `Credential=` access key must resolve to a secret via `IamService`, and the signature must match. The legacy `test`/`test` pair is still emulator ALLOW, but it must be signed with secret `test` like any other key, and it is not a bypass. A temporary (`ASIA...`) credential must also present the `X-Amz-Security-Token` header issued with it, and a long-term key must present none, as on AWS. The `test` key takes any token. An unknown key is 403 and an unsigned one 401, and neither becomes the account-root identity. The checks run in AppSync's order. The scope's region is not checked: the query runs in its API's Region, whatever Region it is signed for. Known keys additionally evaluate `appsync:GraphQL`. | | Cognito / OIDC | JWT signature is verified, not just decoded. Cognito checks the token against the issuing user pool's own RS256 signing key (`alg`, `kid`, issuer, audience/`clientId`, expiry); OIDC checks it against the configured issuer's published JWKS (via OIDC discovery), the same way the HTTP API JWT authorizer does. Both fail closed: an unreachable issuer, unsupported algorithm (including `none`), unmatched `kid`, or bad signature is 401. OIDC as the sole mode still skips the token's own `iss` claim check, but the signature is always verified against the configured issuer's keys. OIDC identity is `{sub, issuer, claims}` (no `sourceIp`). | | Lambda | AppSync `isAuthorized` contract via `LambdaService.invoke` (not an API Gateway policy document). | diff --git a/src/main/java/io/floci/aws/core/common/RegionResolver.java b/src/main/java/io/floci/aws/core/common/RegionResolver.java index 779e9207eb..ede807bfe7 100644 --- a/src/main/java/io/floci/aws/core/common/RegionResolver.java +++ b/src/main/java/io/floci/aws/core/common/RegionResolver.java @@ -301,6 +301,19 @@ public class RegionResolver { return defaultRegion; } + /** + * The Region {@code arn} names: the default Region for a record stored without an ARN, or with one that names + * none, as records stored before their service kept them per Region are. + */ + public String regionOf(String arn) { + return AwsArnUtils.regionOrDefault(arn, getDefaultRegion()); + } + + /** Whether a resource whose ARN is {@code arn} is of the request's Region, as {@link #regionOf} reads it. */ + public boolean inRequestRegion(String arn) { + return getRegion().equals(regionOf(arn)); + } + /** * 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). diff --git a/src/main/java/io/floci/aws/services/appsync/AppSyncController.java b/src/main/java/io/floci/aws/services/appsync/AppSyncController.java index b03fa5c46b..08dce239b3 100644 --- a/src/main/java/io/floci/aws/services/appsync/AppSyncController.java +++ b/src/main/java/io/floci/aws/services/appsync/AppSyncController.java @@ -7,8 +7,6 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.services.appsync.model.*; import jakarta.inject.Inject; import jakarta.ws.rs.*; -import jakarta.ws.rs.core.Context; -import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; @@ -42,8 +40,8 @@ public class AppSyncController { @POST @Path("/v1/apis") - public Response createGraphqlApi(@Context HttpHeaders headers, String body) throws IOException { - String region = regionResolver.resolveRegion(headers); + public Response createGraphqlApi(String body) throws IOException { + String region = regionResolver.getRegion(); @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); GraphqlApi api = service.createGraphqlApi(request, region); @@ -63,10 +61,9 @@ public class AppSyncController { @POST @Path("/v1/apis/{apiId}") - public Response updateGraphqlApi(@Context HttpHeaders headers, - @PathParam("apiId") String apiId, + public Response updateGraphqlApi(@PathParam("apiId") String apiId, String body) throws IOException { - String region = regionResolver.resolveRegion(headers); + String region = regionResolver.getRegion(); @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); GraphqlApi api = service.updateGraphqlApi(apiId, request, region); @@ -137,10 +134,9 @@ public class AppSyncController { @POST @Path("/v1/apis/{apiId}/datasources") - public Response createDataSource(@Context HttpHeaders headers, - @PathParam("apiId") String apiId, + public Response createDataSource(@PathParam("apiId") String apiId, String body) throws IOException { - String region = regionResolver.resolveRegion(headers); + String region = regionResolver.getRegion(); @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); DataSource ds = service.createDataSource(apiId, request, region); @@ -200,11 +196,10 @@ public class AppSyncController { @POST @Path("/v1/apis/{apiId}/types/{typeName}/resolvers") - public Response createResolver(@Context HttpHeaders headers, - @PathParam("apiId") String apiId, + public Response createResolver(@PathParam("apiId") String apiId, @PathParam("typeName") String typeName, String body) throws IOException { - String region = regionResolver.resolveRegion(headers); + String region = regionResolver.getRegion(); @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); request.put("typeName", typeName); @@ -288,9 +283,8 @@ public class AppSyncController { @POST @Path("/v1/apis/{apiId}/functions") - public Response createFunction(@Context HttpHeaders headers, - @PathParam("apiId") String apiId, String body) throws IOException { - String region = regionResolver.resolveRegion(headers); + public Response createFunction(@PathParam("apiId") String apiId, String body) throws IOException { + String region = regionResolver.getRegion(); @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); FunctionConfiguration fn = service.createFunction(apiId, request, region); @@ -637,10 +631,9 @@ public class AppSyncController { @POST @Path("/v1/sourceApis/{sourceApiIdentifier}/mergedApiAssociations") - public Response associateMergedGraphqlApi(@Context HttpHeaders headers, - @PathParam("sourceApiIdentifier") String sourceApiIdentifier, + public Response associateMergedGraphqlApi(@PathParam("sourceApiIdentifier") String sourceApiIdentifier, String body) throws IOException { - String region = regionResolver.resolveRegion(headers); + String region = regionResolver.getRegion(); @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); SourceApiAssociation assoc = service.createMergedApiAssociation(sourceApiIdentifier, request, region); @@ -651,10 +644,9 @@ public class AppSyncController { @POST @Path("/v1/mergedApis/{mergedApiIdentifier}/sourceApiAssociations") - public Response associateSourceGraphqlApi(@Context HttpHeaders headers, - @PathParam("mergedApiIdentifier") String mergedApiIdentifier, + public Response associateSourceGraphqlApi(@PathParam("mergedApiIdentifier") String mergedApiIdentifier, String body) throws IOException { - String region = regionResolver.resolveRegion(headers); + String region = regionResolver.getRegion(); @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); SourceApiAssociation assoc = service.createSourceApiAssociation(mergedApiIdentifier, request, region); diff --git a/src/main/java/io/floci/aws/services/appsync/AppSyncService.java b/src/main/java/io/floci/aws/services/appsync/AppSyncService.java index cfb0bc9966..73a0c6937f 100644 --- a/src/main/java/io/floci/aws/services/appsync/AppSyncService.java +++ b/src/main/java/io/floci/aws/services/appsync/AppSyncService.java @@ -80,14 +80,20 @@ public class AppSyncService { this.apiStore = storageFactory.create("appsync", "appsync-apis.json", new TypeReference<>() {}); this.schemaStore = schemaStore; this.schemaStatusStore = schemaStatusStore; - this.dataSourceStore = storageFactory.create("appsync", "appsync-datasources.json", new TypeReference<>() {}); - this.resolverStore = storageFactory.create("appsync", "appsync-resolvers.json", new TypeReference<>() {}); - this.functionStore = storageFactory.create("appsync", "appsync-functions.json", new TypeReference<>() {}); - this.apiKeyStore = storageFactory.create("appsync", "appsync-apikeys.json", new TypeReference<>() {}); - this.typeStore = storageFactory.create("appsync", "appsync-types.json", new TypeReference<>() {}); + this.dataSourceStore = apiResources(storageFactory.create("appsync", "appsync-datasources.json", + new TypeReference>() {})); + this.resolverStore = apiResources(storageFactory.create("appsync", "appsync-resolvers.json", + new TypeReference>() {})); + this.functionStore = apiResources(storageFactory.create("appsync", "appsync-functions.json", + new TypeReference>() {})); + this.apiKeyStore = apiResources(storageFactory.create("appsync", "appsync-apikeys.json", + new TypeReference>() {})); + this.typeStore = apiResources(storageFactory.create("appsync", "appsync-types.json", + new TypeReference>() {})); this.domainStore = storageFactory.create("appsync", "appsync-domainnames.json", new TypeReference<>() {}); this.associationStore = storageFactory.create("appsync", "appsync-associations.json", new TypeReference<>() {}); - this.channelNamespaceStore = storageFactory.create("appsync", "appsync-channelnamespaces.json", new TypeReference<>() {}); + this.channelNamespaceStore = apiResources(storageFactory.create("appsync", "appsync-channelnamespaces.json", + new TypeReference>() {})); this.mergedApiAssociationStore = storageFactory.create("appsync", "appsync-merged-api-associations.json", new TypeReference<>() {}); this.regionResolver = regionResolver; this.schemaRegistry = schemaRegistry; @@ -166,8 +172,10 @@ public class AppSyncService { return api; } + /** The request's Region's GraphQL API {@code apiId}: another Region's is not found, as one that doesn't exist. */ public GraphqlApi getGraphqlApi(String apiId) { return apiStore.get(apiId) + .filter(api -> regionResolver.inRequestRegion(api.getArn())) .map(this::refreshGraphqlApiUris) .orElseThrow(() -> new AwsException("NotFoundException", "GraphQL API not found: " + apiId, 404)); } @@ -175,7 +183,9 @@ public class AppSyncService { public Page listGraphqlApis(Integer maxResults, String nextToken) { List apis = new ArrayList<>(); for (GraphqlApi stored : apiStore.scan(k -> true)) { - apis.add(refreshGraphqlApiUris(stored)); + if (regionResolver.inRequestRegion(stored.getArn())) { + apis.add(refreshGraphqlApiUris(stored)); + } } return paginate(apis, nextToken, maxResults); } @@ -287,7 +297,10 @@ public class AppSyncService { * creation is in flight. */ void assertSchemaNotBusy(String apiId) { - schemaStatusStore.getForAccount(currentAccountId(), apiId).ifPresent(s -> throwIfProcessing(s.getStatus())); + // Another Region's API doesn't exist here: the operation's own lookup answers NotFoundException. + schemaStatusStore.getForAccount(currentAccountId(), apiId) + .filter(status -> status.getStatus() == SchemaCreationStatusType.PROCESSING && apiInRequestRegion(apiId)) + .ifPresent(status -> throwIfProcessing(status.getStatus())); } /** @@ -718,22 +731,29 @@ public class AppSyncService { // ──────────────────────────── Tags ──────────────────────────── public Map getTags(String resourceArn) { - String apiId = extractApiIdFromArn(resourceArn); - return getGraphqlApi(apiId).getTags(); + return taggedApi(resourceArn).getTags(); } public synchronized void tagResource(String resourceArn, Map tags) { - String apiId = extractApiIdFromArn(resourceArn); - GraphqlApi api = getGraphqlApi(apiId); + GraphqlApi api = taggedApi(resourceArn); api.getTags().putAll(tags); - apiStore.put(apiId, api); + apiStore.put(api.getApiId(), api); } public synchronized void untagResource(String resourceArn, List tagKeys) { + GraphqlApi api = taggedApi(resourceArn); + tagKeys.forEach(api.getTags()::remove); + apiStore.put(api.getApiId(), api); + } + + /** The API {@code resourceArn} names: the request's Region's API whose ARN it is, partition, Region and account. */ + private GraphqlApi taggedApi(String resourceArn) { String apiId = extractApiIdFromArn(resourceArn); GraphqlApi api = getGraphqlApi(apiId); - tagKeys.forEach(api.getTags()::remove); - apiStore.put(apiId, api); + if (!resourceArn.equals(api.getArn())) { + throw new AwsException("NotFoundException", "GraphQL API not found: " + apiId, 404); + } + return api; } // ──────────────────────────── Environment Variables ──────────────────────────── @@ -795,13 +815,16 @@ public class AppSyncService { dn.setHostedZoneId(edge.hostedZoneId()); } + /** The request's Region's domain name: another Region's is not found, as one that doesn't exist. */ public DomainName getDomainName(String domainName) { return domainStore.get(domainName) + .filter(dn -> regionResolver.inRequestRegion(dn.getDomainNameArn())) .orElseThrow(() -> new AwsException("NotFoundException", "Domain name not found: " + domainName, 404)); } public Page listDomainNames(Integer maxResults, String nextToken) { - return paginate(domainStore.scan(k -> true), nextToken, maxResults); + return paginate(domainStore.scan(k -> true).stream() + .filter(dn -> regionResolver.inRequestRegion(dn.getDomainNameArn())).toList(), nextToken, maxResults); } public synchronized DomainName updateDomainName(String domainName, Map request) { @@ -871,7 +894,7 @@ public class AppSyncService { ns.setName(name); ns.setApiId(apiId); ns.setDescription((String) request.get("description")); - ns.setChannelNamespaceArn(regionResolver.buildArn("appsync", apiRegion(api), + ns.setChannelNamespaceArn(regionResolver.buildArn("appsync", regionResolver.regionOf(api.getArn()), "apis/" + apiId + "/channelNamespaces/" + name)); ns.setCodeHandlers((String) request.get("codeHandlers")); ns.setCreated(System.currentTimeMillis()); @@ -964,8 +987,13 @@ public class AppSyncService { return assoc; } + /** + * The request's Region's association {@code associationId} of {@code mergedApiIdentifier}. It is the Region its own + * ARN names, not the APIs': an association outlives a source API deleted without it, and can still be removed. + */ public SourceApiAssociation getSourceApiAssociation(String mergedApiIdentifier, String associationId) { SourceApiAssociation assoc = mergedApiAssociationStore.get(associationId) + .filter(a -> regionResolver.inRequestRegion(a.getAssociationArn())) .orElseThrow(() -> new AwsException("NotFoundException", "Source API association not found: " + associationId, 404)); if (!mergedApiIdentifier.equals(assoc.getMergedApiId())) { @@ -1001,6 +1029,7 @@ public class AppSyncService { public Page listSourceApiAssociations(String apiId, Integer maxResults, String nextToken) { List summaries = mergedApiAssociationStore.scan(k -> true).stream() .filter(a -> apiId.equals(a.getMergedApiId()) || apiId.equals(a.getSourceApiId())) + .filter(a -> regionResolver.inRequestRegion(a.getAssociationArn())) .map(this::toSummary) .toList(); return paginate(summaries, nextToken, maxResults); @@ -1027,6 +1056,7 @@ public class AppSyncService { public synchronized SourceApiAssociation deleteMergedApiAssociation(String sourceApiIdentifier, String associationId) { assertSchemaNotBusy(sourceApiIdentifier); SourceApiAssociation assoc = mergedApiAssociationStore.get(associationId) + .filter(a -> regionResolver.inRequestRegion(a.getAssociationArn())) .orElseThrow(() -> new AwsException("NotFoundException", "Source API association not found: " + associationId, 404)); if (!sourceApiIdentifier.equals(assoc.getSourceApiId())) { @@ -1205,12 +1235,25 @@ public class AppSyncService { return apiId + "::" + typeName + "::" + fieldName; } - /** The region of an API's ARN, where its child resources live; the request region if it has none. */ - private String apiRegion(GraphqlApi api) { - if (api.getArn() != null && AwsArnUtils.isArn(api.getArn())) { - return AwsArnUtils.parse(api.getArn()).region(); - } - return regionResolver.getRegion(); + /** The request's Region's view of {@code store}, a store of the APIs' resources ({@link RegionalApiResources}). */ + private StorageBackend apiResources(StorageBackend store) { + return new RegionalApiResources<>(store, this::apiInRequestRegion); + } + + /** + * Whether {@code apiId} is a GraphQL API of the request's Region, or of no stored API: the resources of another + * Region's are hidden from the request ({@link RegionalApiResources}). + */ + private boolean apiInRequestRegion(String apiId) { + return apiStore.get(apiId).map(api -> regionResolver.inRequestRegion(api.getArn())).orElse(true); + } + + /** + * The Region of the GraphQL API {@code apiId}, whatever Region the request is in. The data plane reaches an API by + * its own endpoint, which names no Region, and runs in the API's. + */ + public Optional graphqlApiRegion(String apiId) { + return apiStore.get(apiId).map(api -> regionResolver.regionOf(api.getArn())); } private String buildApiArn(String apiId, String region) { diff --git a/src/main/java/io/floci/aws/services/appsync/RegionalApiResources.java b/src/main/java/io/floci/aws/services/appsync/RegionalApiResources.java new file mode 100644 index 0000000000..6ee16d6769 --- /dev/null +++ b/src/main/java/io/floci/aws/services/appsync/RegionalApiResources.java @@ -0,0 +1,93 @@ +package io.floci.aws.services.appsync; + +import io.floci.aws.core.storage.StorageBackend; + +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; + +/** + * The request's Region's view of a store of GraphQL APIs' resources (data sources, resolvers, functions, types, API + * keys, channel namespaces), each keyed {@code ::...}. A resource of an API of another Region is absent here, + * as a deleted API's is, so every operation answers for it as for one that doesn't exist. Writes go through: an + * operation finds its API, in the request's Region, before it stores one. + */ +final class RegionalApiResources implements StorageBackend { + + private static final String SEPARATOR = "::"; + + private final StorageBackend delegate; + private final Predicate apiInRequestRegion; + + /** {@code apiInRequestRegion} tells whether an API id is of the request's Region, or of no stored API. */ + RegionalApiResources(StorageBackend delegate, Predicate apiInRequestRegion) { + this.delegate = delegate; + this.apiInRequestRegion = apiInRequestRegion; + } + + @Override + public void put(String key, V value) { + delegate.put(key, value); + } + + @Override + public void putAll(Map entries) { + delegate.putAll(entries); + } + + @Override + public void putAllAtomically(Map entries) { + delegate.putAllAtomically(entries); + } + + @Override + public Optional get(String key) { + return visible(key) ? delegate.get(key) : Optional.empty(); + } + + @Override + public void delete(String key) { + if (visible(key)) { + delegate.delete(key); + } + } + + @Override + public void deleteAllAtomically(Set keys) { + delegate.deleteAllAtomically(keys.stream().filter(this::visible).collect(Collectors.toSet())); + } + + @Override + public List scan(Predicate keyFilter) { + return delegate.scan(key -> keyFilter.test(key) && visible(key)); + } + + @Override + public Set keys() { + return delegate.keys().stream().filter(this::visible).collect(Collectors.toSet()); + } + + /** Clears what this view holds, the request's Region's APIs' resources, as {@code RegionScopedStorage} does. */ + @Override + public void clear() { + keys().forEach(delegate::delete); + } + + @Override + public void flush() { + delegate.flush(); + } + + @Override + public void load() { + delegate.load(); + } + + private boolean visible(String key) { + int separator = key.indexOf(SEPARATOR); + return separator < 0 || apiInRequestRegion.test(key.substring(0, separator)); + } +} diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/AppSyncExecutionController.java b/src/main/java/io/floci/aws/services/appsync/graphql/AppSyncExecutionController.java index 7a166ddaae..50ebf07513 100644 --- a/src/main/java/io/floci/aws/services/appsync/graphql/AppSyncExecutionController.java +++ b/src/main/java/io/floci/aws/services/appsync/graphql/AppSyncExecutionController.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestContext; +import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.docker.ContainerReachableEndpoint; import io.floci.aws.services.appsync.AppSyncService; import io.floci.aws.services.appsync.GraphqlSidecarClient; @@ -105,11 +106,30 @@ public class AppSyncExecutionController { this.reachableEndpoint = reachableEndpoint; } + /** + * An API's endpoint names no Region, so a request reaches the API whatever Region it is signed for, or none with + * an API key, and runs in the API's Region, where its data sources, resolvers and functions are. A request for an + * API that doesn't exist is answered as before. + */ @POST @Path("/v1/apis/{apiId}/graphql") public Response execute(@PathParam("apiId") String apiId, @Context HttpHeaders headers, String body) { + Optional apiRegion; + try { + apiRegion = appSyncService.graphqlApiRegion(apiId); + } catch (RuntimeException e) { + // Stay on the data-plane errors envelope, as a failed lookup of the API itself does. + LOG.errorv(e, "Unexpected failure looking up API {0}", apiId); + return graphqlError(500, "InternalFailure", "InternalFailure"); + } + return apiRegion + .map(region -> RequestScopes.callAs(null, region, () -> executeInItsRegion(apiId, headers, body))) + .orElseGet(() -> executeInItsRegion(apiId, headers, body)); + } + + private Response executeInItsRegion(String apiId, HttpHeaders headers, String body) { try { if (!isAcceptedContentType(headers)) { return graphqlError(400, "MalformedHttpRequestException", diff --git a/src/main/java/io/floci/aws/services/cloudcontrol/CloudControlService.java b/src/main/java/io/floci/aws/services/cloudcontrol/CloudControlService.java index 440f19e03a..3d66a82a6b 100644 --- a/src/main/java/io/floci/aws/services/cloudcontrol/CloudControlService.java +++ b/src/main/java/io/floci/aws/services/cloudcontrol/CloudControlService.java @@ -316,7 +316,7 @@ public class CloudControlService { private void submitCreate(String region, String accountId, String typeName, String desiredStateJson, String token, ProgressEvent pending, JsonNode props, boolean replay) { persistRequest(new PersistedRequest(pending, region, desiredStateJson, System.currentTimeMillis())); - Runnable task = () -> RequestScopes.runAs(accountId, () -> { + Runnable task = () -> RequestScopes.runAs(accountId, region, () -> { try { StackResource resource = provisioner.provisionStandalone(typeName, props, region, accountId); if (resource == null || resource.getPhysicalId() == null) { @@ -510,7 +510,7 @@ public class CloudControlService { + "not hold for " + identifier + ".", null, accountId)); } - RequestScopes.runAs(accountId, + RequestScopes.runAs(accountId, region, () -> provisioner.deleteStandalone(typeName, identifier, region, attributes)); created.remove(key); removePersistedCreated(accountId, region, typeName, identifier); diff --git a/src/main/java/io/floci/aws/services/docdb/DocDbService.java b/src/main/java/io/floci/aws/services/docdb/DocDbService.java index b1f9488eeb..0547b4d39d 100644 --- a/src/main/java/io/floci/aws/services/docdb/DocDbService.java +++ b/src/main/java/io/floci/aws/services/docdb/DocDbService.java @@ -559,11 +559,6 @@ public class DocDbService { } } - /** The region a record was created in, taken from its ARN; older records carry the default. */ - private String regionOf(String arn) { - return AwsArnUtils.regionOrDefault(arn, regionResolver.getDefaultRegion()); - } - /** * Whether an ARN names a DocumentDB cluster or instance, matched against the stored ARN. * diff --git a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandler.java b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandler.java index 10ec0f5ef0..29afeb2d13 100644 --- a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandler.java +++ b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandler.java @@ -522,12 +522,12 @@ public class ElastiCacheQueryHandler { // Cache clusters are stored per account; like AWS, only the request's Region's are listed. List members = service.listMemberCacheClusters(filterId); List clusterList = new ArrayList<>(service.findCacheClusters(filterId).stream() - .filter(c -> service.inRequestRegion(c.getArn())).toList()); + .filter(c -> regionResolver.inRequestRegion(c.getArn())).toList()); // The Memcached lookup is the one that raises CacheClusterNotFound for an unknown id, // which is the right answer only once no other source has answered. if (!filtered || (members.isEmpty() && clusterList.isEmpty())) { memcachedService.listCacheClusters(filterId).stream() - .filter(c -> service.inRequestRegion(c.getArn())) + .filter(c -> regionResolver.inRequestRegion(c.getArn())) .forEach(clusterList::add); if (filtered && clusterList.isEmpty()) { throw new AwsException("CacheClusterNotFound", "Cache cluster " + filterId + " not found.", 404); diff --git a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java index c1e3d5120f..42a42d4a84 100644 --- a/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java +++ b/src/main/java/io/floci/aws/services/elasticache/ElastiCacheService.java @@ -919,21 +919,6 @@ public class ElastiCacheService implements ResourceProvider { } } - /** The region in a restored resource's ARN; one recorded without an ARN counts as the default region's. */ - private String regionOf(String arn) { - return AwsArnUtils.regionOrDefault(arn, regionResolver.getDefaultRegion()); - } - - /** - * Whether a resource belongs to the request's Region. Replication groups, cache clusters (including - * Memcached ones, which DescribeCacheClusters lists too), users and user groups are stored per account; - * like AWS, the Describe* listings only show the requesting Region's. - * The getters stay unscoped: credential lookups, restore and validation run outside a request. - */ - boolean inRequestRegion(String arn) { - return regionResolver.getRegion().equals(regionOf(arn)); - } - /** * Restarts the container and auth proxy behind a standalone Redis or Valkey cache cluster, * the same pair {@link #provisionCacheCluster} creates. The cache comes back empty, as it @@ -954,7 +939,8 @@ public class ElastiCacheService implements ResourceProvider { String clusterId = cluster.getCacheClusterId(); String image = config.services().elasticache().defaultImage(); try { - ElastiCacheContainerHandle handle = containerManager.tryStart(clusterId, image, regionOf(cluster.getArn())); + ElastiCacheContainerHandle handle = containerManager.tryStart(clusterId, image, + regionResolver.regionOf(cluster.getArn())); synchronized (lockFor("cc:" + clusterId)) { if (cacheClusterRestoreTargetLost(accountId, clusterId)) { abandonRestoredCacheClusterContainer(clusterId, handle); @@ -1083,7 +1069,8 @@ public class ElastiCacheService implements ResourceProvider { String groupId = group.getReplicationGroupId(); String image = config.services().elasticache().defaultImage(); try { - ElastiCacheContainerHandle handle = containerManager.tryStart(groupId, image, regionOf(group.getArn())); + ElastiCacheContainerHandle handle = containerManager.tryStart(groupId, image, + regionResolver.regionOf(group.getArn())); synchronized (lockFor("rg:" + groupId)) { if (restoreTargetLost(accountId, groupId)) { abandonRestoredContainer(groupId, handle); @@ -1221,7 +1208,8 @@ public class ElastiCacheService implements ResourceProvider { inFlightMemberId = node.getMemberClusterId(); ElastiCacheContainerHandle handle = containerManager.start( node.getMemberClusterId(), image, - clusterNodeFlags(endpointHost, announceIp, node.getProxyPort()), regionOf(group.getArn())); + clusterNodeFlags(endpointHost, announceIp, node.getProxyPort()), + regionResolver.regionOf(group.getArn())); inFlightMemberId = null; handles.add(handle); node.setContainerId(handle.getContainerId()); @@ -1333,12 +1321,12 @@ public class ElastiCacheService implements ResourceProvider { public Collection listReplicationGroups(String filterGroupId) { if (filterGroupId != null && !filterGroupId.isBlank()) { - return groups.get(filterGroupId).filter(g -> inRequestRegion(g.getArn())) + return groups.get(filterGroupId).filter(g -> regionResolver.inRequestRegion(g.getArn())) .map(List::of) .orElseThrow(() -> new AwsException("ReplicationGroupNotFoundFault", "Replication group " + filterGroupId + " not found.", 404)); } - return groups.scan(k -> true).stream().filter(g -> inRequestRegion(g.getArn())).toList(); + return groups.scan(k -> true).stream().filter(g -> regionResolver.inRequestRegion(g.getArn())).toList(); } public void deleteReplicationGroup(String groupId) { @@ -1454,7 +1442,7 @@ public class ElastiCacheService implements ResourceProvider { snapshot.setEngineVersion(group.getEngineVersion()); snapshot.setCacheNodeType(group.getCacheNodeType()); snapshot.setNumCacheClusters(group.getNumCacheClusters()); - snapshot.setArn(regionResolver.buildArn("elasticache", regionOf(group.getArn()), + snapshot.setArn(regionResolver.buildArn("elasticache", regionResolver.regionOf(group.getArn()), "snapshot:" + snapshotName)); snapshot.setCreatedAt(Instant.now()); snapshot.setSizeBytes(archive.length() * 3L / 4L); @@ -2129,7 +2117,7 @@ public class ElastiCacheService implements ResourceProvider { public List listMemberCacheClusters(String filterClusterId) { List members = new ArrayList<>(); for (ReplicationGroup group : groups.scan(k -> true)) { - if (!inRequestRegion(group.getArn())) { + if (!regionResolver.inRequestRegion(group.getArn())) { continue; } for (MemberCacheCluster member : memberCacheClusters(group)) { @@ -2731,13 +2719,18 @@ public class ElastiCacheService implements ResourceProvider { } /** - * {@code user} as the request's Region lists it, or empty when it is another Region's. AWS has the built-in + * Replication groups, cache clusters (including Memcached ones, which DescribeCacheClusters lists too), users and + * user groups are stored per account; like AWS, the Describe* listings only show the requesting Region's + * ({@link RegionResolver#inRequestRegion}). The getters stay unscoped: credential lookups, restore and validation + * run outside a request. + * + *

{@code user} as the request's Region lists it, or empty when it is another Region's. AWS has the built-in * default user in every Region; Floci seeds one per account, so it is listed in every Region, with that * Region's ARN. */ private Optional inRequestRegion(ElastiCacheUser user) { if (!DEFAULT_USER_ID.equals(user.getUserId())) { - return inRequestRegion(user.getArn()) ? Optional.of(user) : Optional.empty(); + return regionResolver.inRequestRegion(user.getArn()) ? Optional.of(user) : Optional.empty(); } String arn = regionResolver.buildArn("elasticache", regionResolver.getRegion(), "user:" + DEFAULT_USER_ID); if (arn.equals(user.getArn())) { @@ -2911,12 +2904,12 @@ public class ElastiCacheService implements ResourceProvider { public Collection listUserGroups(String filterUserGroupId) { if (filterUserGroupId != null && !filterUserGroupId.isBlank()) { ElastiCacheUserGroup userGroup = getUserGroup(filterUserGroupId); - if (!inRequestRegion(userGroup.getArn())) { + if (!regionResolver.inRequestRegion(userGroup.getArn())) { throw userGroupNotFound(filterUserGroupId); } return List.of(userGroup); } - return userGroups.scan(k -> true).stream().filter(g -> inRequestRegion(g.getArn())).toList(); + return userGroups.scan(k -> true).stream().filter(g -> regionResolver.inRequestRegion(g.getArn())).toList(); } public ElastiCacheUserGroup modifyUserGroup(String userGroupId, List userIdsToAdd, @@ -3026,7 +3019,7 @@ public class ElastiCacheService implements ResourceProvider { /** The request Region's user groups the user is a member of, as DescribeUserGroups lists them there. */ public List userGroupIdsContaining(String userId) { return userGroups.scan(k -> true).stream() - .filter(g -> inRequestRegion(g.getArn())) + .filter(g -> regionResolver.inRequestRegion(g.getArn())) .filter(g -> g.getUserIds().contains(userId)) .map(ElastiCacheUserGroup::getUserGroupId) .toList(); @@ -3712,7 +3705,8 @@ public class ElastiCacheService implements ResourceProvider { private void recordParameterGroupUse(Map> regionsUsing, String accountId, String name, String arn) { if (name != null) { - regionsUsing.computeIfAbsent(accountId + "/" + name, ignored -> new LinkedHashSet<>()).add(regionOf(arn)); + regionsUsing.computeIfAbsent(accountId + "/" + name, ignored -> new LinkedHashSet<>()) + .add(regionResolver.regionOf(arn)); } } @@ -3834,10 +3828,10 @@ public class ElastiCacheService implements ResourceProvider { return reservedParameterGroups.containsKey(parameterGroupReservationKey(name)) || groups.scan(key -> true).stream() .anyMatch(group -> name.equals(group.getCacheParameterGroupName()) - && inRequestRegion(group.getArn())) + && regionResolver.inRequestRegion(group.getArn())) || cacheClusters.scan(key -> true).stream() .anyMatch(cluster -> name.equals(cluster.getCacheParameterGroupName()) - && inRequestRegion(cluster.getArn())); + && regionResolver.inRequestRegion(cluster.getArn())); } @Override diff --git a/src/main/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryService.java b/src/main/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryService.java index e9d6f2a4ed..73d87ceef2 100644 --- a/src/main/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryService.java +++ b/src/main/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryService.java @@ -992,7 +992,7 @@ public class GlueSchemaRegistryService { private Schema schemaForVersion(SchemaVersion version) { String[] parts = parseSchemaArn(version.getSchemaArn()); - String key = schemaKey(regionOf(version.getSchemaArn()), parts[0], parts[1]); + String key = schemaKey(regionResolver.regionOf(version.getSchemaArn()), parts[0], parts[1]); return schemaStore.get(key) .orElseThrow(() -> new AwsException("EntityNotFoundException", "Schema not found for version: " + version.getSchemaVersionId(), 400)); @@ -1089,25 +1089,21 @@ public class GlueSchemaRegistryService { /** A stored schema's key, in the Region its ARN names. */ private String schemaKey(Schema schema) { - return schemaKey(regionOf(schema.getSchemaArn()), schema.getRegistryName(), schema.getSchemaName()); - } - - /** The Region an ARN this service minted names; one stored without an ARN counts as the default Region's. */ - private String regionOf(String arn) { - return AwsArnUtils.regionOrDefault(arn, regionResolver.getDefaultRegion()); + return schemaKey(regionResolver.regionOf(schema.getSchemaArn()), schema.getRegistryName(), + schema.getSchemaName()); } /** The version by that id, if its schema is of {@code region}: another Region's is not found. */ private SchemaVersion versionIn(String schemaVersionId, String region) { return versionStore.get(schemaVersionId) - .filter(version -> region.equals(regionOf(version.getSchemaArn()))) + .filter(version -> region.equals(regionResolver.regionOf(version.getSchemaArn()))) .orElseThrow(() -> new AwsException("EntityNotFoundException", "Schema version not found: " + schemaVersionId, 400)); } /** Refuses an ARN naming another Region: registries and schemas are Regional, so it names none here. */ private void requireArnInRegion(String arn, String region, Supplier notFound) { - if (arn != null && !arn.isBlank() && !region.equals(regionOf(arn))) { + if (arn != null && !arn.isBlank() && !region.equals(regionResolver.regionOf(arn))) { throw notFound.get(); } } @@ -1131,9 +1127,9 @@ public class GlueSchemaRegistryService { List> renamed = new ArrayList<>(); for (AccountEntry entry : schemaAccounts.scanAllAccountEntries(LEGACY_KEY)) { Schema schema = entry.value(); - String region = regionOf(schema.getSchemaArn()); + String region = regionResolver.regionOf(schema.getSchemaArn()); AccountEntry registry = registries.get(entry.accountId() + "/" + schema.getRegistryName()); - if (registry == null || region.equals(regionOf(registry.value().getRegistryArn()))) { + if (registry == null || region.equals(regionResolver.regionOf(registry.value().getRegistryArn()))) { continue; } String key = registryKey(region, schema.getRegistryName()); @@ -1147,7 +1143,8 @@ public class GlueSchemaRegistryService { } } registryAccounts.migrateLegacyEntriesInAllAccounts(LEGACY_KEY, - registry -> registryKey(regionOf(registry.getRegistryArn()), registry.getRegistryName())); + registry -> registryKey(regionResolver.regionOf(registry.getRegistryArn()), + registry.getRegistryName())); schemaAccounts.migrateLegacyEntriesInAllAccounts(LEGACY_KEY, this::schemaKey); // Written once moved, under the new key: a schema stored before accounts prefixed keys would otherwise // leave its unprefixed record beside a second legacy one. diff --git a/src/test/java/io/floci/aws/core/common/RegionResolverTest.java b/src/test/java/io/floci/aws/core/common/RegionResolverTest.java index 082e3a3f46..1bfaa08ff9 100644 --- a/src/test/java/io/floci/aws/core/common/RegionResolverTest.java +++ b/src/test/java/io/floci/aws/core/common/RegionResolverTest.java @@ -394,6 +394,22 @@ class RegionResolverTest { assertEquals("eu-west-1", resolver.resolveRegionFromAuth(header)); } + @Test + void aStoredResourcesRegionIsTheOneItsArnNamesOrTheDefault() { + assertEquals("eu-west-1", resolver.regionOf("arn:aws:appsync:eu-west-1:000000000000:apis/abc")); + // Records stored without an ARN, or with one that names no Region, count as the default Region's. + assertEquals("us-east-1", resolver.regionOf(null)); + assertEquals("us-east-1", resolver.regionOf("arn:aws:iam::000000000000:role/r")); + assertEquals("us-east-1", resolver.regionOf("not-an-arn")); + } + + @Test + void outsideARequestOnlyTheDefaultRegionsResourcesAreInTheRequestsRegion() { + assertTrue(resolver.inRequestRegion("arn:aws:appsync:us-east-1:000000000000:apis/abc")); + assertTrue(resolver.inRequestRegion(null)); + assertFalse(resolver.inRequestRegion("arn:aws:appsync:eu-west-1:000000000000:apis/abc")); + } + @Test void regionFromAuthWithAShortDateStaysDefault() { String header = "AWS4-HMAC-SHA256 Credential=AKID/2026021/eu-west-1/s3/aws4_request"; diff --git a/src/test/java/io/floci/aws/core/common/RequestRegionArnIntegrationTest.java b/src/test/java/io/floci/aws/core/common/RequestRegionArnIntegrationTest.java index a26463ea33..0b987d1c72 100644 --- a/src/test/java/io/floci/aws/core/common/RequestRegionArnIntegrationTest.java +++ b/src/test/java/io/floci/aws/core/common/RequestRegionArnIntegrationTest.java @@ -8,6 +8,7 @@ import java.util.Base64; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.startsWith; /** @@ -130,13 +131,22 @@ class RequestRegionArnIntegrationTest { .then() .statusCode(200) .extract().path("graphqlApi.apiId"); - // A namespace lives in its API's region, even when the request is signed for another one. + // A namespace lives in its API's Region, the only Region that reaches the API. given() .header("Authorization", auth(OTHER_REGION, "appsync")) .contentType("application/json") .body("{\"name\": \"region-arn-ns\"}") .when() .post("/v2/apis/" + apiId + "/channelNamespaces") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + given() + .header("Authorization", auth("appsync")) + .contentType("application/json") + .body("{\"name\": \"region-arn-ns\"}") + .when() + .post("/v2/apis/" + apiId + "/channelNamespaces") .then() .statusCode(200) .body("channelNamespace.channelNamespaceArn", startsWith("arn:aws:appsync:" + REGION + ":")); diff --git a/src/test/java/io/floci/aws/services/appsync/AppSyncExecutionIntegrationTest.java b/src/test/java/io/floci/aws/services/appsync/AppSyncExecutionIntegrationTest.java index 1b63500a3c..50168e78b3 100644 --- a/src/test/java/io/floci/aws/services/appsync/AppSyncExecutionIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/appsync/AppSyncExecutionIntegrationTest.java @@ -3,6 +3,7 @@ package io.floci.aws.services.appsync; import io.floci.aws.services.appsync.graphql.AppSyncErrorFormatter; import io.floci.aws.services.appsync.graphql.SchemaCreationWorker; import io.floci.aws.services.appsync.graphql.SchemaRegistry; +import io.floci.aws.testing.AppSyncRequests; import io.floci.aws.testing.RestAssuredJsonUtils; import io.floci.aws.testing.SidecarContainersProfile; import io.quarkus.test.junit.QuarkusTest; @@ -12,13 +13,11 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.time.Duration; import java.util.List; import java.util.Map; import java.util.UUID; import static io.restassured.RestAssured.given; -import static org.awaitility.Awaitility.await; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -47,7 +46,7 @@ class AppSyncExecutionIntegrationTest { apiId = createApi("exec-" + UUID.randomUUID().toString().substring(0, 8)); apiKey = createApiKey(apiId); startSchema(apiId, "type Query { hello: String }"); - awaitSchemaSuccess(apiId); + AppSyncRequests.awaitSchemaSuccess(apiId, AUTH); } @Test @@ -246,7 +245,7 @@ class AppSyncExecutionIntegrationTest { String multiApi = createApi("multi-" + UUID.randomUUID().toString().substring(0, 8)); String multiKey = createApiKey(multiApi); startSchema(multiApi, "type Query { hello(id: String): String }"); - awaitSchemaSuccess(multiApi); + AppSyncRequests.awaitSchemaSuccess(multiApi, AUTH); given() .header("x-api-key", multiKey) @@ -273,7 +272,7 @@ class AppSyncExecutionIntegrationTest { type Query { hello: String } type Subscription { onHello: String } """); - awaitSchemaSuccess(subApi); + AppSyncRequests.awaitSchemaSuccess(subApi, AUTH); given() .header("x-api-key", subKey) @@ -295,7 +294,7 @@ class AppSyncExecutionIntegrationTest { String scalarApi = createApi("scalar-lit-" + UUID.randomUUID().toString().substring(0, 8)); String scalarKey = createApiKey(scalarApi); startSchema(scalarApi, "type Query { echo(t: AWSDateTime): AWSDateTime }"); - awaitSchemaSuccess(scalarApi); + AppSyncRequests.awaitSchemaSuccess(scalarApi, AUTH); given() .header("x-api-key", scalarKey) @@ -326,7 +325,7 @@ class AppSyncExecutionIntegrationTest { String scalarApi = createApi("scalar-" + UUID.randomUUID().toString().substring(0, 8)); String scalarKey = createApiKey(scalarApi); startSchema(scalarApi, "type Query { echo(t: AWSDateTime): AWSDateTime }"); - awaitSchemaSuccess(scalarApi); + AppSyncRequests.awaitSchemaSuccess(scalarApi, AUTH); given() .header("x-api-key", scalarKey) @@ -367,7 +366,7 @@ class AppSyncExecutionIntegrationTest { String protectedApi = createApi("protected-" + UUID.randomUUID().toString().substring(0, 8)); String protectedKey = createApiKey(protectedApi); startSchema(protectedApi, "type Query { hello: String secret: String @aws_iam }"); - awaitSchemaSuccess(protectedApi); + AppSyncRequests.awaitSchemaSuccess(protectedApi, AUTH); given() .header("x-api-key", protectedKey) @@ -397,7 +396,7 @@ class AppSyncExecutionIntegrationTest { String hydrateApi = createApi("hydrate-" + UUID.randomUUID().toString().substring(0, 8)); String hydrateKey = createApiKey(hydrateApi); startSchema(hydrateApi, "type Query { hello: String }"); - awaitSchemaSuccess(hydrateApi); + AppSyncRequests.awaitSchemaSuccess(hydrateApi, AUTH); schemaRegistry.remove(hydrateApi); assertTrue(schemaRegistry.getSdl(hydrateApi).isEmpty()); @@ -470,19 +469,4 @@ class AppSyncExecutionIntegrationTest { .statusCode(200) .body("status", equalTo("PROCESSING")); } - - private static void awaitSchemaSuccess(String apiId) { - await().atMost(Duration.ofSeconds(10)) - .pollInterval(Duration.ofMillis(25)) - .until(() -> { - String status = given() - .header("Authorization", AUTH) - .when() - .get("/v1/apis/" + apiId + "/schemacreation") - .then() - .statusCode(200) - .extract().path("status"); - return "SUCCESS".equals(status); - }); - } } diff --git a/src/test/java/io/floci/aws/services/appsync/AppSyncJsResolverDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/appsync/AppSyncJsResolverDockerIntegrationTest.java index 54dcc79221..d852eca26a 100644 --- a/src/test/java/io/floci/aws/services/appsync/AppSyncJsResolverDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/appsync/AppSyncJsResolverDockerIntegrationTest.java @@ -1,6 +1,7 @@ package io.floci.aws.services.appsync; import com.fasterxml.jackson.core.io.JsonStringEncoder; +import io.floci.aws.testing.AppSyncRequests; import io.floci.aws.testing.RestAssuredJsonUtils; import io.floci.aws.testing.SidecarContainersProfile; import io.quarkus.test.junit.QuarkusTest; @@ -10,11 +11,9 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.time.Duration; import java.util.UUID; import static io.restassured.RestAssured.given; -import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -484,7 +483,7 @@ class AppSyncJsResolverDockerIntegrationTest { apiId = createApi("js-" + UUID.randomUUID().toString().substring(0, 8)); apiKey = createApiKey(apiId); startSchema(apiId, SCHEMA); - awaitSchemaSuccess(apiId); + AppSyncRequests.awaitSchemaSuccess(apiId, AUTH); createNoneDataSource(apiId, "local"); String functionId = createFunction(apiId, "Query_getMessages_0", "local", PIPELINE_FUNCTION); @@ -1007,13 +1006,6 @@ class AppSyncJsResolverDockerIntegrationTest { .statusCode(200); } - private static void awaitSchemaSuccess(String apiId) { - await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(25)).until(() -> - "SUCCESS".equals(given().header("Authorization", AUTH) - .when().get("/v1/apis/" + apiId + "/schemacreation") - .then().statusCode(200).extract().path("status"))); - } - private static void createNoneDataSource(String apiId, String name) { given() .header("Authorization", AUTH) diff --git a/src/test/java/io/floci/aws/services/appsync/AppSyncRegionDataPlaneIntegrationTest.java b/src/test/java/io/floci/aws/services/appsync/AppSyncRegionDataPlaneIntegrationTest.java new file mode 100644 index 0000000000..0e6a6308d0 --- /dev/null +++ b/src/test/java/io/floci/aws/services/appsync/AppSyncRegionDataPlaneIntegrationTest.java @@ -0,0 +1,66 @@ +package io.floci.aws.services.appsync; + +import io.floci.aws.testing.AppSyncRequests; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.floci.aws.testing.SidecarContainersProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; + +/** + * A GraphQL API's endpoint names no Region, so a query reaches an API of any Region: one authorized by an API key alone + * carries no Region, runs as the default Region's request, and is still answered by an API of another Region, in it. + * The answer comes from the API's resolver, which is found only in the API's Region, so a query left in the default + * Region would answer {@code null}. + */ +@QuarkusTest +@TestProfile(SidecarContainersProfile.class) +class AppSyncRegionDataPlaneIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "eu-west-1"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + SidecarContainersProfile.requireDockerAndImage("floci.services.appsync.graphql-image"); + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void anApiOfAnotherRegionThanTheDefaultAnswersAQueryThroughItsResolver() { + String apiId = in().body("{\"name\":\"west-orders\",\"authenticationType\":\"API_KEY\"}").post("/v1/apis") + .then().statusCode(200).extract().path("graphqlApi.apiId"); + cleanup.register(() -> in().delete("/v1/apis/" + apiId)); + String key = in().body("{}").post("/v1/apis/" + apiId + "/apikeys").then().statusCode(200) + .extract().path("apiKey.id"); + in().body("{\"definition\":\"type Query { hello: String }\"}").post("/v1/apis/" + apiId + "/schemacreation") + .then().statusCode(200); + AppSyncRequests.awaitSchemaSuccess(apiId, EnforcementFixtures.auth(ACCOUNT, REGION, "appsync")); + in().body("{\"name\":\"local\",\"type\":\"NONE\"}").post("/v1/apis/" + apiId + "/datasources") + .then().statusCode(200); + in().body("{\"fieldName\":\"hello\",\"dataSourceName\":\"local\",\"requestMappingTemplate\":" + + "\"{\\\"version\\\":\\\"2018-05-29\\\",\\\"payload\\\":\\\"west\\\"}\"," + + "\"responseMappingTemplate\":\"$util.toJson($ctx.result)\"}") + .post("/v1/apis/" + apiId + "/types/Query/resolvers").then().statusCode(200); + + given().header("x-api-key", key).contentType("application/json").body("{\"query\":\"{ hello }\"}") + .post("/v1/apis/" + apiId + "/graphql") + .then().statusCode(200).body("errors", nullValue()).body("data.hello", equalTo("west")); + } + + private static RequestSpecification in() { + return AppSyncRequests.signed(ACCOUNT, REGION); + } +} diff --git a/src/test/java/io/floci/aws/services/appsync/AppSyncRegionScopingIntegrationTest.java b/src/test/java/io/floci/aws/services/appsync/AppSyncRegionScopingIntegrationTest.java new file mode 100644 index 0000000000..2d4a254a5d --- /dev/null +++ b/src/test/java/io/floci/aws/services/appsync/AppSyncRegionScopingIntegrationTest.java @@ -0,0 +1,90 @@ +package io.floci.aws.services.appsync; + +import io.floci.aws.testing.AppSyncRequests; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; + +/** + * A GraphQL API and a custom domain name are Regional, as on AWS: each is listed and reached only in the Region it was + * created in, and so are an API's data sources and API keys. Another Region's is answered for as one that doesn't + * exist: {@code NotFoundException}, and an empty list of its resources. Each test works in an account of its own. + */ +@QuarkusTest +class AppSyncRegionScopingIntegrationTest { + + private static final AtomicLong ACCOUNTS = new AtomicLong(733100000000L); + private static final String HOME = "eu-west-1"; + private static final String OTHER = "eu-central-1"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private String account; + + @BeforeEach + void accountOfItsOwn() { + account = Long.toString(ACCOUNTS.incrementAndGet()); + } + + @Test + void anApiAndItsResourcesAreListedAndReachedOnlyInItsRegion() { + String apiId = in(HOME).body("{\"name\":\"orders\",\"authenticationType\":\"API_KEY\"}").post("/v1/apis") + .then().statusCode(200).body("graphqlApi.arn", startsWith("arn:aws:appsync:" + HOME + ":")) + .extract().path("graphqlApi.apiId"); + cleanup.register(() -> in(HOME).delete("/v1/apis/" + apiId)); + String apis = "/v1/apis/" + apiId; + in(HOME).body("{\"name\":\"none_ds\",\"type\":\"NONE\"}").post(apis + "/datasources").then().statusCode(200); + String keyId = in(HOME).body("{}").post(apis + "/apikeys").then().statusCode(200).extract().path("apiKey.id"); + + in(OTHER).get("/v1/apis").then().statusCode(200).body("graphqlApis.apiId", not(hasItem(apiId))); + notFound(in(OTHER).get(apis)); + in(OTHER).get(apis + "/datasources").then().statusCode(200).body("dataSources", empty()); + notFound(in(OTHER).get(apis + "/datasources/none_ds")); + notFound(in(OTHER).body("{\"name\":\"other_ds\",\"type\":\"NONE\"}").post(apis + "/datasources")); + in(OTHER).get(apis + "/apikeys").then().statusCode(200).body("apiKeys", empty()); + notFound(in(OTHER).delete(apis)); + + in(HOME).get("/v1/apis").then().statusCode(200).body("graphqlApis.apiId", hasItem(apiId)); + in(HOME).get(apis + "/datasources/none_ds").then().statusCode(200); + in(HOME).get(apis + "/apikeys").then().statusCode(200).body("apiKeys.id", hasItem(keyId)); + } + + @Test + void aDomainNameIsListedAndReachedOnlyInItsRegion() { + String name = "api-" + UUID.randomUUID().toString().substring(0, 8) + ".example.com"; + in(HOME).body("{\"domainName\":\"" + name + "\",\"certificateArn\":\"arn:aws:acm:us-east-1:" + account + + ":certificate/abc\"}").post("/v1/domainnames").then().statusCode(200) + .body("domainNameConfig.domainNameArn", startsWith("arn:aws:appsync:" + HOME + ":")); + cleanup.register(() -> in(HOME).delete("/v1/domainnames/" + name)); + + in(OTHER).get("/v1/domainnames").then().statusCode(200) + .body("domainNameConfigs.domainName", not(hasItem(name))); + notFound(in(OTHER).get("/v1/domainnames/" + name)); + notFound(in(OTHER).delete("/v1/domainnames/" + name)); + + in(HOME).get("/v1/domainnames").then().statusCode(200).body("domainNameConfigs.domainName", hasItem(name)); + in(HOME).get("/v1/domainnames/" + name).then().statusCode(200).body("domainNameConfig.domainName", equalTo(name)); + } + + private RequestSpecification in(String region) { + return AppSyncRequests.signed(account, region); + } + + private static void notFound(Response response) { + response.then().statusCode(404).body("__type", equalTo("NotFoundException")); + } +} diff --git a/src/test/java/io/floci/aws/services/appsync/AppSyncServiceFixture.java b/src/test/java/io/floci/aws/services/appsync/AppSyncServiceFixture.java index 5a861d63ed..cbaf701500 100644 --- a/src/test/java/io/floci/aws/services/appsync/AppSyncServiceFixture.java +++ b/src/test/java/io/floci/aws/services/appsync/AppSyncServiceFixture.java @@ -30,7 +30,12 @@ public final class AppSyncServiceFixture { } public static AppSyncService create(Clock clock) { - return create(clock, "http://localhost:4566", "us-east-1", null, + return create(clock, "us-east-1"); + } + + /** As above, answering for {@code region}, as a request there does: an API of another Region isn't found. */ + public static AppSyncService create(Clock clock, String region) { + return create(clock, "http://localhost:4566", region, null, AccountAwareStorageBackend.inMemory("000000000000"), null, mock(SchemaRegistry.class), new LambdaAuthorizerCache()); } diff --git a/src/test/java/io/floci/aws/services/appsync/AppSyncServiceTest.java b/src/test/java/io/floci/aws/services/appsync/AppSyncServiceTest.java index aceeaa29d6..b2a33d21ca 100644 --- a/src/test/java/io/floci/aws/services/appsync/AppSyncServiceTest.java +++ b/src/test/java/io/floci/aws/services/appsync/AppSyncServiceTest.java @@ -527,6 +527,9 @@ class AppSyncServiceTest { "cn-north-1, aws-cn", "us-isob-east-1, aws-iso-b"}) void tagResourceAcceptsAnApiArnFromAnyPartition(String region, String partition) { + // The service answers for the Region of the API, as a request tagging it there does. + this.region = region; + service = newService(Clock.fixed(NOW, ZoneOffset.UTC)); GraphqlApi api = service.createGraphqlApi( Map.of("name", "p-" + region, "authenticationType", "API_KEY"), region); String apiArn = "arn:" + partition + ":appsync:" + region + ":000000000000:apis/" + api.getApiId(); diff --git a/src/test/java/io/floci/aws/services/cloudcontrol/CloudControlIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudcontrol/CloudControlIntegrationTest.java index 08840f7dbb..124c0ecce0 100644 --- a/src/test/java/io/floci/aws/services/cloudcontrol/CloudControlIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudcontrol/CloudControlIntegrationTest.java @@ -3,6 +3,8 @@ package io.floci.aws.services.cloudcontrol; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.testing.AppSyncRequests; +import io.floci.aws.testing.EnforcementFixtures; import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; import io.restassured.parsing.Parser; @@ -276,6 +278,36 @@ class CloudControlIntegrationTest { assertThat(body, containsString(identifier)); } + /** + * A resource is created and deleted in the Region the request is signed for, where its service then finds it: an + * AppSync API outside the default Region gets the environment variables its create sets with a second call, and + * the delete removes it. + */ + @Test + void aResourceIsCreatedAndDeletedInTheRequestsRegion() throws InterruptedException { + String ct = "application/x-amz-json-1.0"; + String account = "333333333333"; + String region = "eu-west-1"; + String auth = EnforcementFixtures.auth(account, region, "cloudcontrol"); + String token = given().config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT))) + .contentType(ct).header("Authorization", auth) + .header("X-Amz-Target", "CloudApiService.CreateResource") + .body("{\"TypeName\":\"AWS::AppSync::GraphQLApi\",\"DesiredState\":\"{\\\"Name\\\":\\\"regional\\\"," + + "\\\"AuthenticationType\\\":\\\"API_KEY\\\"," + + "\\\"EnvironmentVariables\\\":{\\\"STAGE\\\":\\\"eu\\\"}}\"}") + .when().post("/").then().statusCode(200) + .extract().path("ProgressEvent.RequestToken"); + + String apiId = awaitIdentifier(token, ct, auth); + assertNotNull(apiId, "the create succeeds"); + + AppSyncRequests.signed(account, region).get("/v1/apis/" + apiId + "/environmentVariables") + .then().statusCode(200).body("environmentVariables.STAGE", equalTo("eu")); + + deleteThroughCloudControl(ct, auth, "AWS::AppSync::GraphQLApi", apiId, "SUCCESS"); + AppSyncRequests.signed(account, region).get("/v1/apis/" + apiId).then().statusCode(404); + } + @Test void deleteResourceReportsFailureWhenItWouldSilentlyNoOp() { String ct = "application/x-amz-json-1.0"; @@ -301,10 +333,14 @@ class CloudControlIntegrationTest { } private void deleteThroughCloudControl(String ct, String auth, String identifier, String status) { + deleteThroughCloudControl(ct, auth, "AWS::EC2::VPC", identifier, status); + } + + private void deleteThroughCloudControl(String ct, String auth, String typeName, String identifier, String status) { given().config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, TEXT))) .contentType(ct).header("Authorization", auth) .header("X-Amz-Target", "CloudApiService.DeleteResource") - .body("{\"TypeName\":\"AWS::EC2::VPC\",\"Identifier\":\"" + identifier + "\"}") + .body("{\"TypeName\":\"" + typeName + "\",\"Identifier\":\"" + identifier + "\"}") .when().post("/").then().statusCode(200) .body("ProgressEvent.OperationStatus", equalTo(status)); } diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/AppSyncCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/AppSyncCfnProvisionerTest.java index fe4a9708f9..3ed598dec2 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/AppSyncCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/AppSyncCfnProvisionerTest.java @@ -1240,7 +1240,8 @@ class AppSyncCfnProvisionerTest { void aRollbackThatTheServiceRefusesLeavesTheApiKeyAsTheUpdateLeftItAndKeepsTheSnapshot() throws Exception { Instant start = Instant.parse("2026-01-01T00:00:00Z"); AppSyncServiceFixture.MutableClock clock = new AppSyncServiceFixture.MutableClock(start); - AppSyncService real = AppSyncServiceFixture.create(clock); + // CloudFormation provisions in its stack's Region, eu-west-1 here, and the service answers for it. + AppSyncService real = AppSyncServiceFixture.create(clock, "eu-west-1"); AppSyncCfnProvisioner onRealService = new AppSyncCfnProvisioner(real); GraphqlApi created = real.createGraphqlApi(Map.of("name", "keys", "authenticationType", "API_KEY"), "eu-west-1"); long soonExpiry = start.getEpochSecond() + Duration.ofHours(25).getSeconds(); @@ -1267,7 +1268,8 @@ class AppSyncCfnProvisionerTest { @Test void aSnapshotThatIsNotJsonFailsTheRollbackNamingTheResourceAndChangesNothing() { - AppSyncService real = AppSyncServiceFixture.create(Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC)); + AppSyncService real = AppSyncServiceFixture.create( + Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC), "eu-west-1"); AppSyncCfnProvisioner onRealService = new AppSyncCfnProvisioner(real); GraphqlApi created = real.createGraphqlApi(Map.of("name", "corrupt", "authenticationType", "API_KEY"), "eu-west-1"); real.createDataSource(created.getApiId(), Map.of("name", "ds", "type", "NONE", "description", "kept"), "eu-west-1"); diff --git a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandlerTest.java b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandlerTest.java index f64cbea8dc..1cef60d4ba 100644 --- a/src/test/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/elasticache/ElastiCacheQueryHandlerTest.java @@ -44,10 +44,10 @@ class ElastiCacheQueryHandlerTest { void setUp() { SigV4Validator sigV4Validator = mock(SigV4Validator.class); service = mock(ElastiCacheService.class); - // Every record these tests describe belongs to the request's Region. - when(service.inRequestRegion(any())).thenReturn(true); memcachedService = mock(ElastiCacheMemcachedService.class); RegionResolver regionResolver = mock(RegionResolver.class); + // Every record these tests describe belongs to the request's Region. + when(regionResolver.inRequestRegion(any())).thenReturn(true); when(regionResolver.getRegion()).thenReturn("us-east-1"); when(regionResolver.getDefaultRegion()).thenReturn("us-east-1"); when(regionResolver.getAccountId()).thenReturn("000000000000"); diff --git a/src/test/java/io/floci/aws/testing/AppSyncRequests.java b/src/test/java/io/floci/aws/testing/AppSyncRequests.java new file mode 100644 index 0000000000..1ba1a095f9 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/AppSyncRequests.java @@ -0,0 +1,29 @@ +package io.floci.aws.testing; + +import io.restassured.specification.RequestSpecification; + +import java.time.Duration; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; + +/** AppSync control-plane requests signed for an account and a Region, over the test's RestAssured port. */ +public final class AppSyncRequests { + + private AppSyncRequests() {} + + /** A JSON request signed for {@code account} in {@code region}. */ + public static RequestSpecification signed(String account, String region) { + return given() + .header("Authorization", EnforcementFixtures.auth(account, region, "appsync")) + .contentType("application/json"); + } + + /** Waits until the schema creation of {@code apiId} has succeeded, its status read with {@code authorization}. */ + public static void awaitSchemaSuccess(String apiId, String authorization) { + await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(25)).until(() -> + "SUCCESS".equals(given().header("Authorization", authorization) + .when().get("/v1/apis/" + apiId + "/schemacreation") + .then().statusCode(200).extract().path("status"))); + } +}