diff --git a/docs/services/appsync.md b/docs/services/appsync.md index bea4cc6fea..ee67a55b85 100644 --- a/docs/services/appsync.md +++ b/docs/services/appsync.md @@ -400,7 +400,7 @@ after template. `$util.error` fails the field with its selected type and details `$util.appendError` reports an error beside the returned data. The existing VTL loop, output-size, timeout, and reflection-sandbox limits apply. The -`2017-02-28` template version and VTL-backed HTTP, EventBridge, OpenSearch, and Bedrock data sources +`2017-02-28` template version and VTL-backed EventBridge, OpenSearch, and Bedrock data sources are not included. | Setting | Env | Default | @@ -457,11 +457,70 @@ environment variables). `ctx.request.headers` is empty: the GraphQL context does | `AWS_LAMBDA` | `Invoke` and `BatchInvoke` for APPSYNC_JS, and `Invoke` for `2018-05-29` VTL UNIT resolvers and pipeline functions. Both runtimes send only the resolved `payload` to the function; `BatchInvoke` sends the payload list. A function error fails the field rather than resolving to the error object: `ctx.error.type` is `Lambda:` and the invoke's `FunctionError` (`Lambda:Unhandled` for a thrown error), and `ctx.error.message` is the function's `errorMessage`, or the raw error payload when it has none. | | `RELATIONAL_DATABASE` | Statements run over the RDS Data API against `rdsHttpEndpointConfig`. Accepts `{statements, variableMap}`, the `{statement, parameters}` the `/rds` helpers build, a list of either, or a bare SQL string. `variableTypeHintMap` is honoured, without it a bound date binds as text and PostgreSQL refuses the comparison (`operator does not exist: timestamp with time zone >= character varying`), so a resolver's date filters need it. The result is wrapped as `{sqlStatementResults: […]}`, which is what `toJsonObject()` reads. Supports APPSYNC_JS plus `2018-05-29` VTL UNIT resolvers and pipeline functions. | | `AMAZON_DYNAMODB` | `GetItem`, `PutItem`, `UpdateItem`, `DeleteItem`, `Query`, `Scan`, through the native DynamoDB path so expressions, conditions and indexes all apply. Items come back as **plain JSON**, not attribute values, as AppSync returns them. `nextToken` is an opaque encoding of `LastEvaluatedKey`. `BatchGetItem`, `TransactWriteItems` and `Sync` are not implemented and say so. Supports APPSYNC_JS plus `2018-05-29` VTL UNIT resolvers and pipeline functions. | -| `HTTP`, `AMAZON_EVENTBRIDGE`, `AMAZON_OPENSEARCH_SERVICE`, `AMAZON_BEDROCK_RUNTIME` | Not implemented; a resolver using one fails its field naming the type. | +| `HTTP` | HTTP requests from APPSYNC_JS and `2018-05-29` VTL UNIT resolvers and pipeline functions. Returns `{statusCode, headers, body}`, including non-success responses. See [HTTP requests](#http-requests) for endpoint and signing limits. | +| `AMAZON_EVENTBRIDGE`, `AMAZON_OPENSEARCH_SERVICE`, `AMAZON_BEDROCK_RUNTIME` | Not implemented; a resolver using one fails its field naming the type. | A field with no resolver falls back to reading its value off the parent object, which is how the fields of an object a resolver returned are populated. +### HTTP requests + +An HTTP data source uses `httpConfig.endpoint`. Its resolver returns `method`, `resourcePath`, +and optional `params.headers`, `params.query`, and `params.body`. Methods are `GET`, `POST`, +`PUT`, `PATCH`, and `DELETE`. Header and query values must be strings; query values are URL-encoded. +A string body is sent as text and an object body is JSON-encoded. The resource path is appended +to the configured endpoint's base path and cannot select another host. + +For example, a VTL request template can return: + +```json +{"version":"2018-05-29","method":"GET","resourcePath":"/items","params":{"query":{"limit":"10"}}} +``` + +The response handler receives `ctx.result.statusCode`, `ctx.result.headers`, and the text +`ctx.result.body`. A 4xx or 5xx response is still a result for the handler to inspect. Transport +failures use `HttpException`; invalid request mappings use `MappingTemplate`. Requests and responses +are limited to 5 MiB, and transport work has a 30-second deadline. Redirects and automatic retries +are disabled. Supported response charsets are respected; a missing, blank, or unrecognized charset +falls back to UTF-8. HTTPS keeps certificate and hostname verification enabled. +HTTP resolver callbacks use separate batches so independent query fields can run concurrently; +root mutation fields retain their selection order. + +Unsigned requests support public HTTP(S) endpoints and local development services on localhost +or private container networks. Floci rejects IPv4 and IPv6 link-local addresses +(`169.254.0.0/16` and `fe80::/10`) and the AWS IPv6 metadata address (`fd00:ec2::254`), +including IPv4-mapped equivalents and hostnames with any such DNS answer. It connects using +the validated DNS snapshot. This shared policy does not block Alibaba metadata at +`100.100.100.200`; that address remains reachable if the host can route to it. +Unsigned HTTP data sources do not require a service role. Transport capacity is bounded to +four active requests and sixteen queued requests. The caller deadline also covers DNS lookup, +but system DNS can ignore cancellation: a stuck lookup retains its worker until it returns. +If all four workers are stuck in DNS, other endpoints also lose transport capacity; excess +requests fail with `HttpException`. + +For the following local AWS operations, set `httpConfig.authorizationConfig.authorizationType` +to `AWS_IAM` and supply `awsIamConfig.signingRegion`, `awsIamConfig.signingServiceName`, and the +data source's `serviceRoleArn`: + +| Signing service | Supported requests | +|---|---| +| `scheduler` | `POST`, `GET`, and `DELETE` on `/schedules/` for CreateSchedule, GetSchedule, and DeleteSchedule. Query parameters are limited to `groupName` and `clientToken`. | +| `states` | `POST /` with `X-Amz-Target: AWSStepFunctions.SendTaskSuccess` or `AWSStepFunctions.SendTaskFailure`, using `application/json` or `application/x-amz-json-1.0`. | + +The endpoint must be the service's standard regional HTTPS hostname, for example +`https://scheduler.us-west-2.amazonaws.com`. The signing region must be a canonical published region +in the API's partition. The target region may differ from the API's region. The role ARN must belong +to the API's account and partition, and the target service must be enabled. Requests go to Floci's +own listener with temporary role credentials that are removed on completion or failure. With +`floci.services.iam.enforcement-enabled=true`, the role must exist and trust `appsync.amazonaws.com`, +including any source conditions, and the native service applies its IAM policies. With enforcement +off (the default), role existence, trust and permission checks are permissive, as for other local +data sources. Removing temporary credentials does not make permissive IAM mode enforce revocation +against a delayed or replayed request. Enable IAM enforcement when that check is required. +The native service's response is preserved in either mode. Step Functions tokens remain bound to +their owning account and region. Other signing services, operations, endpoint forms, and authorization +types are unsupported and fail before credentials or a request are sent. + ## Pagination All `List` operations support cursor-based pagination via query parameters: @@ -560,7 +619,7 @@ reaches `CREATE_COMPLETE` and nothing is created for it. Set These AWS AppSync capabilities are not yet implemented and are tracked in future phases: - **VTL resolver expansion**: the `2017-02-28` version and the remaining data sources -- **Data source adapters**: HTTP, EventBridge, OpenSearch, and Bedrock connectors +- **Data source adapters**: EventBridge, OpenSearch, and Bedrock connectors - **Guardrails** (Phase 10): query depth / complexity limits and related errors - **Realtime subscriptions** (Phase 11+): WebSocket real-time subscriptions - **Caching**: API-level and per-resolver caching diff --git a/src/main/java/io/floci/aws/core/common/ValidatingDnsResolver.java b/src/main/java/io/floci/aws/core/common/ValidatingDnsResolver.java new file mode 100644 index 0000000000..8d9de1adfb --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/ValidatingDnsResolver.java @@ -0,0 +1,46 @@ +package io.floci.aws.core.common; + +import org.apache.hc.client5.http.DnsResolver; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.function.UnaryOperator; + +/** Checks and returns one DNS snapshot so the connection uses the addresses its caller validated. */ +public final class ValidatingDnsResolver implements DnsResolver { + + @FunctionalInterface + public interface AddressCheck { + void validate(String host, InetAddress[] addresses) throws UnknownHostException; + } + + private final DnsResolver delegate; + private final AddressCheck check; + private final UnaryOperator canonicalHost; + + public ValidatingDnsResolver(DnsResolver delegate, AddressCheck check) { + this(delegate, check, UnaryOperator.identity()); + } + + public ValidatingDnsResolver(DnsResolver delegate, AddressCheck check, UnaryOperator canonicalHost) { + this.delegate = delegate; + this.check = check; + this.canonicalHost = canonicalHost; + } + + @Override + public InetAddress[] resolve(String host) throws UnknownHostException { + InetAddress[] addresses = delegate.resolve(host); + if (addresses == null || addresses.length == 0) { + throw new UnknownHostException("Host has no addresses: " + canonicalHost.apply(host)); + } + InetAddress[] snapshot = addresses.clone(); + check.validate(host, snapshot); + return snapshot; + } + + @Override + public String resolveCanonicalHostname(String host) { + return canonicalHost.apply(host); + } +} diff --git a/src/main/java/io/floci/aws/core/common/auth/LocalAwsSigningSession.java b/src/main/java/io/floci/aws/core/common/auth/LocalAwsSigningSession.java new file mode 100644 index 0000000000..9507fcfee8 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/auth/LocalAwsSigningSession.java @@ -0,0 +1,106 @@ +package io.floci.aws.core.common.auth; + +import io.floci.aws.core.common.Digests; +import io.floci.aws.services.iam.IamService; + +import java.net.URI; +import java.security.SecureRandom; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +/** Temporary signing credentials for an authorized request to Floci's runtime-owned listener. */ +public final class LocalAwsSigningSession implements AutoCloseable { + + private static final SecureRandom RANDOM = new SecureRandom(); + private static final DateTimeFormatter AMZ_DATE = + DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC); + private final IamService iam; + private final String accountId; + private final String accessKey = accessKey(); + private final String secret = randomToken(32); + private final String token = randomToken(48); + private final Instant expiration = Instant.now().plusSeconds(120); + + private LocalAwsSigningSession(IamService iam, String accountId) { + this.iam = iam; + this.accountId = accountId; + } + + public static LocalAwsSigningSession forAccount(IamService iam, String accountId, String roleArn) { + return open(iam, accountId, session -> iam.registerSessionForAccount(accountId, session.accessKey, + session.secret, session.token, roleArn, session.expiration, null)); + } + + /** The caller's request scope must be the role's account, as for IAM's assumed-role registration. */ + public static LocalAwsSigningSession assumedRole(IamService iam, String accountId, String roleArn, + String sessionName, String assumedRoleId) { + return open(iam, accountId, session -> iam.registerSession(session.accessKey, session.secret, session.token, + roleArn, session.expiration, null, accountId, sessionName, assumedRoleId)); + } + + private static LocalAwsSigningSession open(IamService iam, String accountId, Consumer register) { + LocalAwsSigningSession session = new LocalAwsSigningSession(iam, accountId); + try { + register.accept(session); + return session; + } catch (RuntimeException | Error failure) { + try { + session.close(); + } catch (RuntimeException | Error cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + /** Input header names are already lowercase and validated by the invoking service. */ + public Map> sign(String method, URI uri, byte[] payload, String region, String service, + Map> inputHeaders) throws Exception { + TreeMap> headers = new TreeMap<>(inputHeaders); + headers.remove("authorization"); + String stamp = AMZ_DATE.format(Instant.now()); + headers.put("host", List.of(uri.getRawAuthority())); + headers.put("x-amz-date", List.of(stamp)); + headers.put("x-amz-security-token", List.of(token)); + String signedHeaders = String.join(";", headers.keySet()); + CredentialScope scope = new CredentialScope(accessKey, stamp.substring(0, 8), region, service); + String canonical = method + "\n" + uri.getRawPath() + "\n" + + SigV4Canonicalization.canonicalQueryString(uri.getRawQuery(), false) + "\n" + + SigV4Canonicalization.canonicalHeaders(signedHeaders, name -> headers.get(name).stream() + .map(SigV4RequestValidator::normalizeHeaderValue).collect(Collectors.joining(","))) + "\n" + + signedHeaders + "\n" + Digests.sha256Hex(payload); + String toSign = "AWS4-HMAC-SHA256\n" + stamp + "\n" + scope.credentialScope() + "\n" + Digests.sha256Hex(canonical); + String signature = SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256( + SigV4RequestValidator.deriveSigningKey(secret, scope.date(), region, service), toSign)); + headers.put("authorization", List.of("AWS4-HMAC-SHA256 Credential=" + accessKey + "/" + scope.credentialScope() + + ", SignedHeaders=" + signedHeaders + ", Signature=" + signature)); + return headers; + } + + @Override + public void close() { + iam.unregisterSession(accountId, accessKey); + } + + private static String accessKey() { + String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + StringBuilder key = new StringBuilder("ASIA"); + for (int i = 0; i < 16; i++) { + key.append(alphabet.charAt(RANDOM.nextInt(alphabet.length()))); + } + return key.toString(); + } + + private static String randomToken(int length) { + byte[] bytes = new byte[length]; + RANDOM.nextBytes(bytes); + return Base64.getEncoder().encodeToString(bytes); + } +} 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 a065f93da7..7a166ddaae 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 @@ -22,7 +22,10 @@ import io.floci.aws.services.appsync.graphql.resolver.AppSyncResolverError; import io.floci.aws.services.appsync.graphql.resolver.AppSyncResolverExecutor; import io.floci.aws.services.appsync.graphql.resolver.ResolverCallbackSessions; import io.floci.aws.services.appsync.model.AuthenticationType; +import io.floci.aws.services.appsync.model.DataSourceType; import io.floci.aws.services.appsync.model.GraphqlApi; +import io.floci.aws.services.appsync.model.Resolver; +import io.floci.aws.services.appsync.model.ResolverKind; import jakarta.inject.Inject; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; @@ -202,8 +205,8 @@ public class AppSyncExecutionController { private Map executeQuery(String apiId, String preparedSdl, Map scalars, ParsedRequest parsed, List denyFields, PlanResult plan, AppSyncAuthContext authContext) { - List resolveFields = resolverBackedFields(apiId, plan, denyFields); - if (resolveFields.isEmpty()) { + CallbackPlan callbacks = resolverBackedFields(apiId, plan, denyFields); + if (callbacks.fields().isEmpty()) { return sidecarClient.execute(preparedSdl, scalars, parsed.query(), parsed.variables(), parsed.operationName(), denyFields); } @@ -211,7 +214,7 @@ public class AppSyncExecutionController { callbackSessions.open(apiId, authContext.identity(), authContext.authType(), authContext.accountId(), authContext.region())) { ResolveSpec resolve = new ResolveSpec(reachableEndpoint.baseUrl() + "/_floci/appsync/resolve", - session.token(), resolveFields, RESOLVE_MAX_BATCH); + session.token(), callbacks.fields(), callbacks.maxBatch()); Map result = sidecarClient.execute(preparedSdl, scalars, parsed.query(), parsed.variables(), parsed.operationName(), denyFields, resolve); return withAppendedErrors(result, session.appendedErrors()); @@ -222,37 +225,61 @@ public class AppSyncExecutionController { * The coordinates the sidecar should call back for: every planned field that has a resolver and * is not already denied, since {@code denyFields} wins and a denied field must never reach one. */ - private List resolverBackedFields(String apiId, PlanResult plan, List denyFields) { + private CallbackPlan resolverBackedFields(String apiId, PlanResult plan, List denyFields) { Set denied = new HashSet<>(); for (DenyField deny : denyFields) { denied.add(deny.typeName() + "." + deny.fieldName()); } Map wired = new LinkedHashMap<>(); + int maxBatch = RESOLVE_MAX_BATCH; for (PlannedField field : plan.fields()) { String key = field.typeName() + "." + field.fieldName(); if (denied.contains(key) || wired.containsKey(key)) { continue; } - if (hasResolver(apiId, field)) { + try { + Resolver resolver = resolverExecutor.findResolver(apiId, field.typeName(), field.fieldName()); + if (resolver == null) { + continue; + } wired.put(key, new ResolveField(field.typeName(), field.fieldName())); + if (usesHttpDataSource(apiId, resolver)) { + maxBatch = 1; + } + } catch (AwsException e) { + // Keep errors on the affected field, including metadata changed during execution. + wired.put(key, new ResolveField(field.typeName(), field.fieldName())); + maxBatch = 1; + LOG.debugv("Could not plan callback batching for {0}.{1}", field.typeName(), field.fieldName()); } } - return List.copyOf(wired.values()); + return new CallbackPlan(List.copyOf(wired.values()), maxBatch); } - private boolean hasResolver(String apiId, PlannedField field) { - try { - return resolverExecutor.findResolver(apiId, field.typeName(), field.fieldName()) != null; - } catch (AwsException e) { - // A control-plane failure here (a schema mid-recreation answers 409) must not take down - // the whole operation: wire the field anyway and let the callback report it on that - // field alone, which is where a resolver failure belongs. - LOG.debugv("Could not tell whether {0}.{1} has a resolver: {2}", - field.typeName(), field.fieldName(), e.getMessage()); - return true; + private boolean usesHttpDataSource(String apiId, Resolver resolver) { + if (resolver.getKind() != ResolverKind.PIPELINE) { + return isHttpDataSource(apiId, resolver.getDataSourceName()); } + Object functions = resolver.getPipelineConfig() == null ? null : resolver.getPipelineConfig().get("functions"); + if (functions instanceof List ids) { + for (Object id : ids) { + String dataSource = appSyncService.getFunction(apiId, String.valueOf(id)).getDataSourceName(); + if (isHttpDataSource(apiId, dataSource)) { + return true; + } + } + } + return false; } + private boolean isHttpDataSource(String apiId, String name) { + return name != null && !name.isBlank() && appSyncService.getDataSource(apiId, name).getType() == DataSourceType.HTTP; + } + + // HTTP invocations each need their own callback deadline. The sidecar dispatches chunks + // concurrently for queries and still executes root mutation fields in their original order. + private record CallbackPlan(List fields, int maxBatch) { } + /** * {@code util.appendError} reports errors and keeps the data, which the sidecar's * per-field callback response cannot say (it carries a value or an error, never both). They diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizer.java b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizer.java index c4362a151e..b0fe8a2f58 100644 --- a/src/main/java/io/floci/aws/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizer.java +++ b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizer.java @@ -50,7 +50,8 @@ public class AppSyncDataSourceAuthorizer { } public void authorize(DataSource dataSource, Object request, String region) { - if (dataSource.getType() == DataSourceType.NONE + // HTTP authorization depends on its optional signing configuration and is handled by its invoker. + if (dataSource.getType() == DataSourceType.NONE || dataSource.getType() == DataSourceType.HTTP || !config.services().iam().enforcementEnabled()) { return; } diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/datasource/AwsIamHttpDataSourceInvoker.java b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/AwsIamHttpDataSourceInvoker.java new file mode 100644 index 0000000000..102116dfec --- /dev/null +++ b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/AwsIamHttpDataSourceInvoker.java @@ -0,0 +1,94 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.ServicePrincipals; +import io.floci.aws.core.common.ServiceRegistry; +import io.floci.aws.core.common.auth.LocalAwsSigningSession; +import io.floci.aws.services.appsync.model.DataSource; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.iam.ServiceRoleAuthorizer; +import io.quarkus.vertx.http.HttpServer; +import jakarta.annotation.PreDestroy; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.apache.hc.client5.http.SystemDefaultDnsResolver; +import org.jboss.logging.Logger; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** Signs audited, same-account AWS operations for Floci's actual local listener, never for an external URL. */ +@ApplicationScoped +public class AwsIamHttpDataSourceInvoker { + + private static final Logger LOG = Logger.getLogger(AwsIamHttpDataSourceInvoker.class); + private final IamService iam; + private final ServiceRoleAuthorizer authorizer; + private final ServiceRegistry services; + private final RegionResolver regions; + private final HttpServer server; + // Its URL is exclusively the runtime-owned listener. + private final HttpDataSourceTransport local; + + @Inject + public AwsIamHttpDataSourceInvoker(IamService iam, ServiceRoleAuthorizer authorizer, + ServiceRegistry services, RegionResolver regions, + HttpServer server) { + this(iam, authorizer, services, regions, server, + new HttpDataSourceTransport(HttpDataSourceTransport.client(SystemDefaultDnsResolver.INSTANCE))); + } + + AwsIamHttpDataSourceInvoker(IamService iam, ServiceRoleAuthorizer authorizer, + ServiceRegistry services, RegionResolver regions, + HttpServer server, HttpDataSourceTransport local) { + this.iam = iam; + this.authorizer = authorizer; + this.services = services; + this.regions = regions; + this.server = server; + this.local = local; + } + + public Map invoke(DataSource source, HttpDataSourceRequest request, String apiRegion) { + HttpDataSourceAwsTarget target = HttpDataSourceAwsTarget.parse(source, request, apiRegion, regions); + String serviceId = "states".equals(target.service()) ? "stepfunctions" : "scheduler"; + if (!services.isServiceEnabled(serviceId)) { + throw new AwsException("ServiceNotAvailableException", "Service " + serviceId + " is not enabled", 400); + } + authorizer.refusal(target.roleArn(), target.accountId(), ServicePrincipals.of("appsync"), + target.sourceApiArn(), List.of()).ifPresent(reason -> { + throw new AwsException("AccessDeniedException", reason, 403); + }); + URI listener = server.getLocalBaseUri(); + if (listener == null) { + throw new AwsException("InternalFailureException", "The local AWS listener is not ready", 500); + } + String path = request.uri().getRawPath(); + String query = request.uri().getRawQuery(); + URI uri = listener.resolve(path + (query == null ? "" : "?" + query)); + try (LocalAwsSigningSession session = LocalAwsSigningSession.forAccount(iam, target.accountId(), target.roleArn())) { + Map> headers = new TreeMap<>(); + request.headers().forEach((name, value) -> headers.put(name, List.of(value))); + headers.putIfAbsent("content-type", List.of("states".equals(target.service()) + ? "application/x-amz-json-1.0" : "application/json")); + Map signed = new TreeMap<>(); + session.sign(request.method(), uri, request.body(), target.region(), target.service(), headers) + .forEach((name, values) -> signed.put(name, String.join(",", values))); + return local.send(new HttpDataSourceRequest(uri, request.method(), signed, request.body())); + } catch (AwsException e) { + throw e; + } catch (Exception e) { + LOG.debugv("Signed HTTP data source failed: service={0}, region={1}, cause={2}", + target.service(), target.region(), e.getClass().getSimpleName()); + throw new AwsException("HttpException", "The signed HTTP data source request could not complete", 500); + } + } + + @PreDestroy + void close() { + local.close(); + } +} diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceAwsTarget.java b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceAwsTarget.java new file mode 100644 index 0000000000..e0dc4cec9b --- /dev/null +++ b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceAwsTarget.java @@ -0,0 +1,122 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +import io.floci.aws.core.common.AwsArnShapes; +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.AwsEndpoints; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.AwsPartitions; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.services.appsync.model.DataSource; +import org.apache.hc.core5.http.ContentType; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** The audited AWS operations an HTTP data source may send to the emulator's own listener. */ +record HttpDataSourceAwsTarget(String accountId, String sourceApiArn, String roleArn, String service, String region) { + + static HttpDataSourceAwsTarget parse(DataSource source, HttpDataSourceRequest request, + String apiRegion, RegionResolver regions) { + Map config = source.getHttpConfig(); + String sourceArn = source.getDataSourceArn(); + String roleArn = source.getServiceRoleArn(); + if (config == null || !(config.get("authorizationConfig") instanceof Map auth) + || !"AWS_IAM".equals(auth.get("authorizationType")) + || !(auth.get("awsIamConfig") instanceof Map iam) + || !(iam.get("signingRegion") instanceof String region) + || !AwsPartitions.isPublishedRegion(region) + || !region.equals(region.trim().toLowerCase(Locale.ROOT)) + || !(iam.get("signingServiceName") instanceof String service) + || !Set.of("scheduler", "states").contains(service)) { + throw invalid("HTTP AWS_IAM requires a known signing region and a supported signing service"); + } + URI endpoint; + try { + endpoint = URI.create(String.valueOf(config.get("endpoint"))); + } catch (IllegalArgumentException e) { + throw invalid("Invalid HTTP AWS_IAM endpoint"); + } + String expectedHost = AwsEndpoints.host(service, region); + if (!"https".equalsIgnoreCase(endpoint.getScheme()) || !expectedHost.equalsIgnoreCase(endpoint.getHost()) + || endpoint.getPort() != -1 || endpoint.getRawUserInfo() != null || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null || !(endpoint.getRawPath().isEmpty() || "/".equals(endpoint.getRawPath())) + || !expectedHost.equalsIgnoreCase(request.uri().getHost()) + || !"https".equalsIgnoreCase(request.uri().getScheme()) || request.uri().getPort() != -1) { + throw invalid("HTTP AWS_IAM endpoint must be the signing service's standard regional HTTPS endpoint"); + } + if (!AwsArnUtils.isArnFor(sourceArn, "appsync") || !AwsArnUtils.isArnFor(roleArn, "iam")) { + throw denied("HTTP AWS_IAM requires a data source ARN and an IAM service role"); + } + AwsArnUtils.Arn owner = AwsArnUtils.parse(sourceArn); + AwsArnUtils.Arn role = AwsArnUtils.parse(roleArn); + if (!owner.accountId().equals(regions.getAccountId()) || !owner.region().equals(apiRegion) + || !RegionResolver.isKnownRegion(apiRegion) + || !owner.partition().equals(regions.partitionForRegion(apiRegion)) + || !owner.partition().equals(regions.partitionForRegion(region)) + || !owner.resource().matches("apis/[A-Za-z0-9_-]+/datasources/[A-Za-z0-9_-]+") + || !AwsArnShapes.isIamRole(role) || !role.region().isEmpty() || role.resource().endsWith("/") + || !role.partition().equals(owner.partition()) || !role.accountId().equals(owner.accountId())) { + throw denied("HTTP AWS_IAM service role and endpoint must share the data source's account and partition"); + } + validateOperation(request, service); + String apiResource = owner.resource().substring(0, owner.resource().indexOf("/datasources/")); + String apiArn = new AwsArnUtils.Arn(owner.partition(), "appsync", owner.region(), owner.accountId(), apiResource).toString(); + return new HttpDataSourceAwsTarget(owner.accountId(), apiArn, roleArn, service, region); + } + + private static void validateOperation(HttpDataSourceRequest request, String service) { + // These are the only caller headers the two audited protocols need. In particular, no + // authentication, routing, forwarding or internal-control headers can reach the listener. + Set headers = "states".equals(service) + ? Set.of("content-type", "accept", "x-amz-target") : Set.of("content-type", "accept"); + if (!headers.containsAll(request.headers().keySet())) { + throw invalid("Unsupported header for a signed HTTP data source request"); + } + if (request.headers().containsKey("content-type")) { + try { + ContentType type = ContentType.parse(request.headers().get("content-type")); + Set allowed = "states".equals(service) + ? Set.of("application/json", "application/x-amz-json-1.0") + : Set.of("application/json"); + if (!allowed.contains(type.getMimeType()) || !StandardCharsets.UTF_8.equals(type.getCharset(StandardCharsets.UTF_8))) { + throw invalid("Signed HTTP data sources require a UTF-8 JSON content type"); + } + } catch (IllegalArgumentException e) { + throw invalid("Invalid signed HTTP content type"); + } + } + String path = request.uri().getRawPath(); + String query = request.uri().getRawQuery(); + if ("scheduler".equals(service)) { + if (!Set.of("GET", "POST", "DELETE").contains(request.method()) + || !path.matches("/schedules/[A-Za-z0-9_.-]{1,64}") + || "/schedules/.".equals(path) || "/schedules/..".equals(path)) { + throw invalid("Signed Scheduler requests support CreateSchedule, GetSchedule and DeleteSchedule only"); + } + if (query != null && !query.isEmpty()) { + for (String pair : query.split("&")) { + String name = pair.split("=", 2)[0]; + if (!Set.of("groupName", "clientToken").contains(name)) { + throw invalid("Unsupported signed Scheduler query parameter"); + } + } + } + } else if (!"POST".equals(request.method()) || !"/".equals(path) || query != null + || request.headers().get("x-amz-target") == null + || !Set.of("AWSStepFunctions.SendTaskSuccess", "AWSStepFunctions.SendTaskFailure") + .contains(request.headers().get("x-amz-target"))) { + throw invalid("Signed Step Functions requests support SendTaskSuccess and SendTaskFailure only"); + } + } + + private static AwsException invalid(String message) { + return new AwsException("MappingTemplate", message, 400); + } + + private static AwsException denied(String message) { + return new AwsException("AccessDeniedException", message, 403); + } +} diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceInvoker.java b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceInvoker.java new file mode 100644 index 0000000000..e4acd6db5e --- /dev/null +++ b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceInvoker.java @@ -0,0 +1,37 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.appsync.model.DataSource; +import io.floci.aws.services.appsync.model.DataSourceType; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +/** Executes an HTTP resolver request and preserves its status, headers and body for the response handler. */ +@ApplicationScoped +public class HttpDataSourceInvoker implements AppSyncDataSourceInvoker { + + private final HttpDataSourceTransport transport; + private final ObjectMapper mapper; + private final AwsIamHttpDataSourceInvoker aws; + + @Inject + public HttpDataSourceInvoker(HttpDataSourceTransport transport, ObjectMapper mapper, AwsIamHttpDataSourceInvoker aws) { + this.transport = transport; + this.mapper = mapper; + this.aws = aws; + } + + @Override + public DataSourceType type() { + return DataSourceType.HTTP; + } + + @Override + public Object invoke(DataSource dataSource, Object request, String region) { + HttpDataSourceRequest outgoing = HttpDataSourceRequest.parse(dataSource, request, mapper); + if (dataSource.getHttpConfig().get("authorizationConfig") != null) { + return aws.invoke(dataSource, outgoing, region); + } + return transport.send(outgoing); + } +} diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceRequest.java b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceRequest.java new file mode 100644 index 0000000000..cdf856c005 --- /dev/null +++ b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceRequest.java @@ -0,0 +1,138 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.auth.SigV4Canonicalization; +import io.floci.aws.services.appsync.model.DataSource; +import org.apache.hc.core5.http.ContentType; + +import java.net.URI; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.stream.Collectors; + +/** The validated HTTP request produced by a resolver, before credentials or network access. */ +record HttpDataSourceRequest(URI uri, String method, Map headers, byte[] body) { + + private static final Set METHODS = Set.of("GET", "POST", "PUT", "PATCH", "DELETE"); + private static final Set RESERVED_HEADERS = Set.of("host", "connection", "user-agent", "expect", + "expectation", "transfer-encoding", "transfer_encoding", "content-length", "content_length", + "proxy-connection", "keep-alive", "te", "trailer", "upgrade"); + + HttpDataSourceRequest { + headers = Map.copyOf(headers); + body = body.clone(); + } + + @Override + public byte[] body() { + return body.clone(); + } + + static HttpDataSourceRequest parse(DataSource source, Object request, ObjectMapper mapper) { + if (!(request instanceof Map input)) { + throw invalid("HTTP request must be an object"); + } + Object endpoint = source.getHttpConfig() == null ? null : source.getHttpConfig().get("endpoint"); + URI base = uri(text(endpoint, "httpConfig.endpoint")); + if (!("https".equalsIgnoreCase(base.getScheme()) || "http".equalsIgnoreCase(base.getScheme())) + || base.getHost() == null || base.getRawUserInfo() != null || base.getRawQuery() != null + || base.getRawFragment() != null || base.getPort() < -1 || base.getPort() > 65535) { + throw invalid("HTTP endpoint must be an HTTP(S) URL without user info, query or fragment"); + } + String method = text(input.get("method"), "method"); + if (!METHODS.contains(method)) { + throw invalid("Unsupported HTTP method"); + } + if (input.containsKey("version") && !"2018-05-29".equals(input.get("version"))) { + throw invalid("Unsupported HTTP request version"); + } + String path = text(input.get("resourcePath"), "resourcePath"); + URI resource = uri(path); + if (!path.startsWith("/") || path.startsWith("//") || resource.isAbsolute() + || resource.getRawAuthority() != null || resource.getRawQuery() != null || resource.getRawFragment() != null) { + throw invalid("resourcePath must be a path on the configured HTTP endpoint"); + } + Map params = object(input.get("params"), "params"); + Map headers = stringMap(params.get("headers"), "headers"); + Map normalized = new TreeMap<>(); + for (Map.Entry header : headers.entrySet()) { + String name = header.getKey().toLowerCase(Locale.ROOT); + if (!name.matches("[!#$%&'*+.^_`|~0-9a-z-]+") || RESERVED_HEADERS.contains(name) + || header.getValue().chars().anyMatch(ch -> (ch < 32 && ch != '\t') || ch == 127 || ch > 255) + || normalized.putIfAbsent(name, header.getValue()) != null) { + throw invalid("Invalid or reserved HTTP header"); + } + } + Map query = stringMap(params.get("query"), "query"); + String encodedQuery = query.entrySet().stream() + .map(entry -> SigV4Canonicalization.uriEncode(entry.getKey()) + "=" + + SigV4Canonicalization.uriEncode(entry.getValue())) + .sorted().collect(Collectors.joining("&")); + String prefix = base.toString(); + if (prefix.endsWith("/")) { + prefix = prefix.substring(0, prefix.length() - 1); + } + URI target = uri(prefix + path + (encodedQuery.isEmpty() ? "" : "?" + encodedQuery)); + return new HttpDataSourceRequest(target, method, normalized, body(params.get("body"), normalized, mapper)); + } + + private static byte[] body(Object value, Map headers, ObjectMapper mapper) { + if (value == null) { + return new byte[0]; + } + try { + Charset charset = headers.containsKey("content-type") + ? ContentType.parse(headers.get("content-type")).getCharset(StandardCharsets.UTF_8) + : StandardCharsets.UTF_8; + String body = value instanceof String text ? text : mapper.writeValueAsString(value); + return body.getBytes(charset); + } catch (Exception e) { + throw invalid("Could not encode HTTP request body"); + } + } + + private static Map stringMap(Object value, String name) { + Map result = new TreeMap<>(); + for (Map.Entry entry : object(value, name).entrySet()) { + if (!(entry.getKey() instanceof String key) || !(entry.getValue() instanceof String text)) { + throw invalid(name + " must contain string keys and values"); + } + result.put(key, text); + } + return result; + } + + private static Map object(Object value, String name) { + if (value == null) { + return Map.of(); + } + if (value instanceof Map map) { + return map; + } + throw invalid(name + " must be an object"); + } + + private static String text(Object value, String name) { + if (value instanceof String text && !text.isBlank()) { + return text; + } + throw invalid(name + " must be a non-empty string"); + } + + private static URI uri(String value) { + try { + return URI.create(value); + } catch (IllegalArgumentException e) { + throw invalid("Invalid HTTP endpoint or resource path"); + } + } + + private static AwsException invalid(String message) { + return new AwsException("MappingTemplate", message, 400); + } +} diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceTransport.java b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceTransport.java new file mode 100644 index 0000000000..f798336a85 --- /dev/null +++ b/src/main/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceTransport.java @@ -0,0 +1,180 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.SsrfProtection; +import io.floci.aws.core.common.ValidatingDnsResolver; +import jakarta.annotation.PreDestroy; +import jakarta.enterprise.context.ApplicationScoped; +import org.apache.hc.client5.http.DnsResolver; +import org.apache.hc.client5.http.SystemDefaultDnsResolver; +import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; +import org.apache.hc.client5.http.config.ConnectionConfig; +import org.apache.hc.client5.http.config.RequestConfig; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.io.entity.ByteArrayEntity; +import org.apache.hc.core5.io.CloseMode; +import org.apache.hc.core5.util.Timeout; +import org.jboss.logging.Logger; + +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.io.InputStream; +import java.net.UnknownHostException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** Bounded HTTP transport for unsigned data-source endpoints, including local development services. */ +@ApplicationScoped +class HttpDataSourceTransport implements AutoCloseable { + + private static final Logger LOG = Logger.getLogger(HttpDataSourceTransport.class); + static final int MAX_BYTES = 5 * 1024 * 1024; + private final CloseableHttpClient client; + private final Duration timeout; + // System DNS may ignore interruption. Bound both waiting callers and outstanding lookups. + private final ThreadPoolExecutor workers = new ThreadPoolExecutor(4, 4, 0, TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(16), runnable -> { + Thread thread = new Thread(runnable, "appsync-http-request"); + thread.setDaemon(true); + return thread; + }); + + HttpDataSourceTransport() { + this(client(checkedResolver(SystemDefaultDnsResolver.INSTANCE))); + } + + HttpDataSourceTransport(CloseableHttpClient client) { + this(client, Duration.ofSeconds(30)); + } + + HttpDataSourceTransport(CloseableHttpClient client, Duration timeout) { + this.client = client; + this.timeout = timeout; + } + + static CloseableHttpClient client(DnsResolver resolver) { + return client(resolver, null); + } + + static CloseableHttpClient client(DnsResolver resolver, SSLContext sslContext) { + PoolingHttpClientConnectionManagerBuilder connections = PoolingHttpClientConnectionManagerBuilder.create() + .setDnsResolver(resolver) + .setDefaultConnectionConfig(ConnectionConfig.custom() + .setConnectTimeout(Timeout.ofSeconds(5)).setSocketTimeout(Timeout.ofSeconds(30)).build()) + .setMaxConnTotal(32).setMaxConnPerRoute(8); + if (sslContext != null) { + connections.setTlsSocketStrategy(ClientTlsStrategyBuilder.create().setSslContext(sslContext).buildClassic()); + } + return HttpClients.custom() + .setConnectionManager(connections.build()) + .setDefaultRequestConfig(RequestConfig.custom() + .setConnectionRequestTimeout(Timeout.ofSeconds(5)).setResponseTimeout(Timeout.ofSeconds(30)).build()) + .disableRedirectHandling().disableAutomaticRetries().disableCookieManagement() + .disableAuthCaching().disableContentCompression().build(); + } + + static DnsResolver checkedResolver(DnsResolver delegate) { + return new ValidatingDnsResolver(delegate, (host, addresses) -> { + try { + SsrfProtection.rejectMetadataAddresses(addresses, host); + } catch (IOException e) { + UnknownHostException failure = new UnknownHostException("HTTP data source endpoint resolves to a metadata address"); + failure.initCause(e); + throw failure; + } + }); + } + + Map send(HttpDataSourceRequest request) { + byte[] body = request.body(); + if (body.length > MAX_BYTES) { + throw new AwsException("HttpException", "HTTP data source request exceeds 5 MB", 400); + } + HttpUriRequestBase outgoing = new HttpUriRequestBase(request.method(), request.uri()); + request.headers().forEach(outgoing::addHeader); + if (body.length > 0 || "POST".equals(request.method()) || "PUT".equals(request.method()) || "PATCH".equals(request.method())) { + outgoing.setEntity(new ByteArrayEntity(body, null)); + } + Future> pending; + try { + pending = workers.submit(() -> execute(outgoing)); + } catch (RejectedExecutionException e) { + throw new AwsException("HttpException", "HTTP data source concurrency limit reached", 500); + } + boolean completed = false; + try { + Map result = pending.get(timeout.toMillis(), TimeUnit.MILLISECONDS); + completed = true; + return result; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AwsException("HttpException", "HTTP data source request was interrupted", 500); + } catch (TimeoutException e) { + LOG.debugv("HTTP data source deadline exceeded: method={0}, host={1}", request.method(), request.uri().getHost()); + throw new AwsException("HttpException", "HTTP data source request deadline exceeded", 500); + } catch (ExecutionException e) { + // Exception messages and URLs can contain credentials or query values. Log only the type. + LOG.debugv("HTTP data source failed: method={0}, host={1}, cause={2}", request.method(), + request.uri().getHost(), e.getCause().getClass().getSimpleName()); + throw new AwsException("HttpException", "HTTP data source request could not complete", 500); + } finally { + if (!completed) { + outgoing.cancel(); + pending.cancel(true); + } + } + } + + private Map execute(HttpUriRequestBase outgoing) throws IOException { + return client.execute(outgoing, response -> { + Map headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + for (Header header : response.getHeaders()) { + headers.merge(header.getName(), header.getValue(), (left, right) -> left + "," + right); + } + byte[] bytes; + if (response.getEntity() == null) { + bytes = new byte[0]; + } else { + try (InputStream stream = response.getEntity().getContent()) { + bytes = stream.readNBytes(MAX_BYTES + 1); + if (bytes.length > MAX_BYTES) { + outgoing.cancel(); + throw new IOException("HTTP data source response exceeds 5 MB"); + } + } + } + return Map.of("statusCode", response.getCode(), "headers", headers, "body", + new String(bytes, responseCharset(headers.get("content-type")))); + }); + } + + private static Charset responseCharset(String contentType) { + try { + return ContentType.getCharset(ContentType.parseLenient(contentType), StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + return StandardCharsets.UTF_8; + } + } + + @Override + @PreDestroy + public void close() { + workers.shutdownNow(); + client.close(CloseMode.IMMEDIATE); + } +} diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/resolver/AppSyncResolverExecutor.java b/src/main/java/io/floci/aws/services/appsync/graphql/resolver/AppSyncResolverExecutor.java index 2253179481..38f834e155 100644 --- a/src/main/java/io/floci/aws/services/appsync/graphql/resolver/AppSyncResolverExecutor.java +++ b/src/main/java/io/floci/aws/services/appsync/graphql/resolver/AppSyncResolverExecutor.java @@ -302,7 +302,7 @@ public class AppSyncResolverExecutor { DataSource dataSource = dataSource(dataSourceName); DataSourceType type = dataSource.getType(); return switch (type) { - case NONE, AMAZON_DYNAMODB, AWS_LAMBDA, RELATIONAL_DATABASE -> dataSource; + case NONE, AMAZON_DYNAMODB, AWS_LAMBDA, RELATIONAL_DATABASE, HTTP -> dataSource; default -> throw unsupportedVtlDataSource(type, dataSourceName, stageName); }; } @@ -366,6 +366,7 @@ public class AppSyncResolverExecutor { case AMAZON_DYNAMODB -> prepareVtlDynamoDbRequest(map); case AWS_LAMBDA -> prepareVtlLambdaRequest(map); case RELATIONAL_DATABASE -> prepareVtlRdsRequest(map); + case HTTP -> map; default -> throw unsupportedVtlDataSource(dataSource.getType(), dataSource.getName(), stage.function() ? "function" : "UNIT resolver"); }; diff --git a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontOriginHttpClient.java b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontOriginHttpClient.java index 00c3317a43..d8021467f4 100644 --- a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontOriginHttpClient.java +++ b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontOriginHttpClient.java @@ -1,6 +1,7 @@ package io.floci.aws.services.cloudfront; import io.floci.aws.core.common.SsrfProtection; +import io.floci.aws.core.common.ValidatingDnsResolver; import org.apache.hc.client5.http.ConnectTimeoutException; import org.apache.hc.client5.http.ConnectionKeepAliveStrategy; import org.apache.hc.client5.http.DnsResolver; @@ -123,9 +124,7 @@ final class CloudFrontOriginHttpClient implements AutoCloseable { Collection allowedPrivateOriginHosts, SSLContext sslContext, LongSupplier nanoClock) { - this(new ValidatingDnsResolver(delegate, allowedPrivateOriginHosts.stream() - .map(CloudFrontServingController::normalizeHost) - .collect(Collectors.toUnmodifiableSet())), sslContext, nanoClock); + this(validatingResolver(delegate, allowedPrivateOriginHosts), sslContext, nanoClock); } private CloudFrontOriginHttpClient( @@ -708,16 +707,11 @@ final class CloudFrontOriginHttpClient implements AutoCloseable { } } - private record ValidatingDnsResolver(DnsResolver delegate, Set allowedHosts) - implements DnsResolver { - - @Override - public InetAddress[] resolve(String host) throws UnknownHostException { - InetAddress[] addresses = delegate.resolve(host); + private static DnsResolver validatingResolver(DnsResolver delegate, Collection allowedPrivateOriginHosts) { + Set allowedHosts = allowedPrivateOriginHosts.stream().map(CloudFrontServingController::normalizeHost) + .collect(Collectors.toUnmodifiableSet()); + return new ValidatingDnsResolver(delegate, (host, addresses) -> { String normalizedHost = CloudFrontServingController.normalizeHost(host); - if (addresses == null || addresses.length == 0) { - throw new UnknownHostException("CloudFront origin host has no addresses: " + normalizedHost); - } if (!allowedHosts.contains(normalizedHost)) { for (InetAddress address : addresses) { if (SsrfProtection.isBlockedAddress(address)) { @@ -725,12 +719,6 @@ final class CloudFrontOriginHttpClient implements AutoCloseable { } } } - return addresses.clone(); - } - - @Override - public String resolveCanonicalHostname(String host) { - return CloudFrontServingController.normalizeHost(host); - } + }, CloudFrontServingController::normalizeHost); } } diff --git a/src/main/java/io/floci/aws/services/stepfunctions/ApiGatewayTaskInvoker.java b/src/main/java/io/floci/aws/services/stepfunctions/ApiGatewayTaskInvoker.java index 8ea2b78526..5531770a6c 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/ApiGatewayTaskInvoker.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/ApiGatewayTaskInvoker.java @@ -6,11 +6,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsEndpoints; -import io.floci.aws.core.common.Digests; import io.floci.aws.core.common.ServicePrincipals; -import io.floci.aws.core.common.auth.CredentialScope; +import io.floci.aws.core.common.auth.LocalAwsSigningSession; import io.floci.aws.core.common.auth.SigV4Canonicalization; -import io.floci.aws.core.common.auth.SigV4RequestValidator; import io.floci.aws.services.apigateway.ApiGatewayService; import io.floci.aws.services.apigateway.model.EndpointType; import io.floci.aws.services.apigateway.model.RestApi; @@ -30,13 +28,8 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; -import java.security.SecureRandom; import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; import java.util.ArrayList; -import java.util.Base64; import java.util.List; import java.util.Locale; import java.util.Map; @@ -48,13 +41,10 @@ import java.util.stream.Collectors; /** Regional, same-account REST API requests under the state machine's IAM execution role. */ @ApplicationScoped public class ApiGatewayTaskInvoker { - private static final SecureRandom RANDOM = new SecureRandom(); private static final Set RESERVED_HEADERS = Set.of( "authorization", "connection", "content-md5", "expect", "host", "max-forwards", "proxy-authenticate", "server", "te", "transfer-encoding", "trailer", "upgrade", "via", "www-authenticate"); - private static final DateTimeFormatter AMZ_DATE = - DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC); private final ApiGatewayService apiGateway; private final IamService iam; private final AssumeRolePolicyEvaluator trust; @@ -125,7 +115,7 @@ public class ApiGatewayTaskInvoker { AwsArnUtils.Arn roleId = AwsArnUtils.parse(roleArn); String roleName = roleId.resource().substring(roleId.resource().lastIndexOf('/') + 1); String principalId = iam.findRole(roleId.accountId(), roleName).map(IamRole::getRoleId).orElse(roleName); - TreeMap> headers = requestHeaders(input.path("Headers")); + Map> headers = requestHeaders(input.path("Headers")); headers.putIfAbsent("content-type", List.of("application/json")); JsonNode body = input.path("RequestBody"); if (!body.isObject() || containsNull(body)) { @@ -143,17 +133,13 @@ public class ApiGatewayTaskInvoker { String encodedPath = List.of(path.split("/", -1)).stream() .map(SigV4Canonicalization::uriEncode).collect(Collectors.joining("/")); URI uri = listener.resolve("/restapis/" + apiId + "/" + stage + "/_user_request_/" + encodedPath); - String accessKey = accessKey(); - String secret = randomSecret(30); - String token = randomSecret(48); String sessionName = "StepFunctions-" + UUID.randomUUID(); - iam.registerSession(accessKey, secret, token, roleArn, Instant.now().plusSeconds(120), - null, roleId.accountId(), sessionName, principalId + ":" + sessionName); - try { - sign(headers, uri, payload, owner.region(), accessKey, secret, token); + try (LocalAwsSigningSession session = LocalAwsSigningSession.assumedRole(iam, roleId.accountId(), roleArn, + sessionName, principalId + ":" + sessionName)) { + Map> signed = session.sign("POST", uri, payload, owner.region(), "execute-api", headers); HttpRequest.Builder request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(60)) .POST(HttpRequest.BodyPublishers.ofByteArray(payload)); - headers.forEach((name, value) -> { + signed.forEach((name, value) -> { if (!"host".equals(name)) { value.forEach(item -> request.header(name, item)); } @@ -177,8 +163,6 @@ public class ApiGatewayTaskInvoker { } catch (IOException error) { throw new AslExecutor.FailStateException("ApiGateway." + error.getClass().getSimpleName(), "API request could not complete"); - } finally { - iam.unregisterSession(roleId.accountId(), accessKey); } } @@ -256,41 +240,6 @@ public class ApiGatewayTaskInvoker { || lowerName.startsWith("x-amzn-") || lowerName.startsWith("x-forwarded-"); } - private static void sign(TreeMap> headers, URI uri, byte[] payload, String region, - String accessKey, String secret, String token) throws Exception { - String stamp = AMZ_DATE.format(Instant.now()); - headers.put("host", List.of(uri.getAuthority())); - headers.put("x-amz-date", List.of(stamp)); - headers.put("x-amz-security-token", List.of(token)); - String signed = String.join(";", headers.keySet()); - CredentialScope scope = new CredentialScope(accessKey, stamp.substring(0, 8), region, "execute-api"); - String canonical = "POST\n" + uri.getRawPath() + "\n\n" - + SigV4Canonicalization.canonicalHeaders(signed, name -> headers.get(name).stream() - .map(SigV4RequestValidator::normalizeHeaderValue).collect(Collectors.joining(","))) + "\n" + signed + "\n" - + Digests.sha256Hex(payload); - String toSign = "AWS4-HMAC-SHA256\n" + stamp + "\n" + scope.credentialScope() + "\n" - + Digests.sha256Hex(canonical); - String signature = SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256( - SigV4RequestValidator.deriveSigningKey(secret, scope.date(), region, "execute-api"), toSign)); - headers.put("authorization", List.of("AWS4-HMAC-SHA256 Credential=" + accessKey + "/" + scope.credentialScope() - + ", SignedHeaders=" + signed + ", Signature=" + signature)); - } - - private static String accessKey() { - String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - StringBuilder value = new StringBuilder("ASIA"); - for (int index = 0; index < 16; index++) { - value.append(alphabet.charAt(RANDOM.nextInt(alphabet.length()))); - } - return value.toString(); - } - - private static String randomSecret(int size) { - byte[] bytes = new byte[size]; - RANDOM.nextBytes(bytes); - return Base64.getEncoder().withoutPadding().encodeToString(bytes); - } - private static AslExecutor.FailStateException failure(int status, String cause) { return new AslExecutor.FailStateException("ApiGateway." + status, cause); } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 7ddd1dc228..daeabd0422 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -167,7 +167,7 @@ quarkus: - --initialize-at-run-time=io.floci.aws.services.redshift.proxy.RedshiftRoleAccess - --initialize-at-run-time=io.floci.aws.services.redshift.spectrum.SpectrumMaterializer - --initialize-at-run-time=io.floci.aws.services.ecs.exec.EcsExecSessionRegistry - - --initialize-at-run-time=io.floci.aws.services.stepfunctions.ApiGatewayTaskInvoker + - --initialize-at-run-time=io.floci.aws.core.common.auth.LocalAwsSigningSession # snappy-java (Firehose Snappy/HADOOP_SNAPPY delivery) extracts and loads a # bundled JNI library from the static initializers of these two classes. - --initialize-at-run-time=org.xerial.snappy.Snappy diff --git a/src/test/java/io/floci/aws/core/common/ValidatingDnsResolverTest.java b/src/test/java/io/floci/aws/core/common/ValidatingDnsResolverTest.java new file mode 100644 index 0000000000..eeeb08fcbe --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/ValidatingDnsResolverTest.java @@ -0,0 +1,59 @@ +package io.floci.aws.core.common; + +import org.apache.hc.client5.http.DnsResolver; +import org.junit.jupiter.api.Test; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ValidatingDnsResolverTest { + + private final DnsResolver delegate = mock(DnsResolver.class); + + @Test + void validatesAndReturnsTheSameSnapshotWithoutCanonicalDnsLookup() throws Exception { + InetAddress publicIp = InetAddress.getByAddress(new byte[]{8, 8, 8, 8}); + InetAddress[] answer = {publicIp}; + when(delegate.resolve("ORIGIN")).thenReturn(answer); + AtomicReference checked = new AtomicReference<>(); + ValidatingDnsResolver resolver = new ValidatingDnsResolver(delegate, (host, addresses) -> checked.set(addresses), + host -> host.toLowerCase(Locale.ROOT)); + InetAddress[] resolved = resolver.resolve("ORIGIN"); + answer[0] = InetAddress.getLoopbackAddress(); + assertSame(checked.get(), resolved); + assertEquals(publicIp, resolved[0]); + assertEquals("origin", resolver.resolveCanonicalHostname("ORIGIN")); + verify(delegate).resolve("ORIGIN"); + verify(delegate, never()).resolveCanonicalHostname("ORIGIN"); + } + + @Test + void absentDnsAnswersFailBeforeThePolicyRuns() throws Exception { + AtomicInteger checks = new AtomicInteger(); + ValidatingDnsResolver resolver = new ValidatingDnsResolver(delegate, (host, addresses) -> checks.incrementAndGet()); + for (InetAddress[] answer : new InetAddress[][]{null, new InetAddress[0]}) { + when(delegate.resolve("missing")).thenReturn(answer); + assertThrows(UnknownHostException.class, () -> resolver.resolve("missing")); + } + assertEquals(0, checks.get()); + } + + @Test + void callerSpecificRejectionIsPreserved() throws Exception { + when(delegate.resolve("blocked")).thenReturn(new InetAddress[]{InetAddress.getLoopbackAddress()}); + UnknownHostException blocked = new UnknownHostException("service-specific refusal"); + ValidatingDnsResolver resolver = new ValidatingDnsResolver(delegate, (host, addresses) -> { throw blocked; }); + assertSame(blocked, assertThrows(UnknownHostException.class, () -> resolver.resolve("blocked"))); + } +} diff --git a/src/test/java/io/floci/aws/core/common/auth/LocalAwsSigningSessionTest.java b/src/test/java/io/floci/aws/core/common/auth/LocalAwsSigningSessionTest.java new file mode 100644 index 0000000000..3fedf3f45f --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/auth/LocalAwsSigningSessionTest.java @@ -0,0 +1,88 @@ +package io.floci.aws.core.common.auth; + +import io.floci.aws.core.common.Digests; +import io.floci.aws.services.iam.IamService; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.net.URI; +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +class LocalAwsSigningSessionTest { + + private static final String ACCOUNT = "111111111111"; + private static final String ROLE = "arn:aws:iam::" + ACCOUNT + ":role/test"; + private final IamService iam = mock(IamService.class); + + @Test + void queryAndMultipleHeaderValuesUseTheNativeCanonicalForm() throws Exception { + ArgumentCaptor key = ArgumentCaptor.forClass(String.class); + ArgumentCaptor secret = ArgumentCaptor.forClass(String.class); + ArgumentCaptor token = ArgumentCaptor.forClass(String.class); + try (LocalAwsSigningSession session = LocalAwsSigningSession.forAccount(iam, ACCOUNT, ROLE)) { + verify(iam).registerSessionForAccount(eq(ACCOUNT), key.capture(), secret.capture(), token.capture(), + eq(ROLE), any(Instant.class), isNull()); + URI uri = URI.create("http://localhost:4566/schedules/space%20name?groupName=a%20b&clientToken=c%2Bd"); + byte[] payload = new byte[0]; + Map> headers = session.sign("GET", uri, payload, "us-west-2", "scheduler", + Map.of("x-values", List.of(" a ", " b c "))); + SigV4AuthorizationHeader auth = SigV4AuthorizationHeader.parse(headers.get("authorization").getFirst()); + CredentialScope scope = CredentialScope.parse(auth.credential()); + assertEquals(key.getValue(), scope.accessKeyId()); + assertEquals("us-west-2", scope.region()); + assertEquals("scheduler", scope.service()); + String stamp = headers.get("x-amz-date").getFirst(); + String canonicalHeaders = "host:localhost:4566\nx-amz-date:" + stamp + + "\nx-amz-security-token:" + token.getValue() + "\nx-values:a,b c\n"; + assertTrue(SigV4Canonicalization.signatureMatches("GET", "/schedules/space%20name", + "clientToken=c%2Bd&groupName=a%20b", canonicalHeaders, auth.signedHeaders(), + Digests.sha256Hex(payload), stamp, scope, secret.getValue(), auth.signature())); + } + verify(iam).unregisterSession(ACCOUNT, key.getValue()); + } + + @Test + void assumedRoleRegistrationKeepsItsIdentityAndLifetime() { + ArgumentCaptor key = ArgumentCaptor.forClass(String.class); + ArgumentCaptor expiration = ArgumentCaptor.forClass(Instant.class); + Instant before = Instant.now(); + try (LocalAwsSigningSession session = LocalAwsSigningSession.assumedRole(iam, ACCOUNT, ROLE, + "service-session", "AROAID:service-session")) { + verify(iam).registerSession(key.capture(), anyString(), anyString(), eq(ROLE), expiration.capture(), + isNull(), eq(ACCOUNT), eq("service-session"), eq("AROAID:service-session")); + assertTrue(key.getValue().matches("ASIA[A-Z0-9]{16}")); + assertTrue(!expiration.getValue().isBefore(before.plusSeconds(120)) + && !expiration.getValue().isAfter(Instant.now().plusSeconds(120))); + } + verify(iam).unregisterSession(ACCOUNT, key.getValue()); + } + + @Test + void registrationFailureRevokesTheKeyAndPreservesTheOriginalFailure() { + RuntimeException registration = new IllegalStateException("registration failed"); + RuntimeException cleanup = new IllegalStateException("cleanup failed"); + doThrow(registration).when(iam).registerSessionForAccount(eq(ACCOUNT), anyString(), anyString(), anyString(), + eq(ROLE), any(Instant.class), isNull()); + doThrow(cleanup).when(iam).unregisterSession(eq(ACCOUNT), anyString()); + assertSame(registration, assertThrows(IllegalStateException.class, + () -> LocalAwsSigningSession.forAccount(iam, ACCOUNT, ROLE))); + assertEquals(List.of(cleanup), List.of(registration.getSuppressed())); + ArgumentCaptor key = ArgumentCaptor.forClass(String.class); + verify(iam).registerSessionForAccount(eq(ACCOUNT), key.capture(), anyString(), anyString(), eq(ROLE), any(), isNull()); + verify(iam).unregisterSession(ACCOUNT, key.getValue()); + } +} diff --git a/src/test/java/io/floci/aws/services/appsync/AppSyncHttpDataSourceSidecarIntegrationTest.java b/src/test/java/io/floci/aws/services/appsync/AppSyncHttpDataSourceSidecarIntegrationTest.java new file mode 100644 index 0000000000..7125f48653 --- /dev/null +++ b/src/test/java/io/floci/aws/services/appsync/AppSyncHttpDataSourceSidecarIntegrationTest.java @@ -0,0 +1,187 @@ +package io.floci.aws.services.appsync; + +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.testing.AppSyncHttpTestPolicies; +import io.floci.aws.testing.AwsTestClients; +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 jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.appsync.AppSyncClient; +import software.amazon.awssdk.services.appsync.model.DataSource; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.CloudFormationException; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** SDK management, real GraphQL/Node sidecars, resolver callbacks and signed local AWS requests. */ +@QuarkusTest +@TestProfile(AppSyncHttpDataSourceSidecarIntegrationTest.EnforcedSidecars.class) +class AppSyncHttpDataSourceSidecarIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String TARGET_REGION = "us-west-2"; + + public static class EnforcedSidecars extends SidecarContainersProfile { + @Override + public Map getConfigOverrides() { + Map overrides = new HashMap<>(super.getConfigOverrides()); + overrides.put("floci.services.iam.enforcement-enabled", "true"); + overrides.put("floci.auth.validate-signatures", "true"); + return overrides; + } + } + + @Inject + IamService iam; + + private AppSyncClient client; + private String apiId; + private String apiKey; + private String roleName; + + @BeforeAll + static void requireSidecars() { + SidecarContainersProfile.requireDockerAndImage("floci.services.appsync.graphql-image"); + SidecarContainersProfile.requireDockerAndImage("floci.services.appsync.js-runtime.image"); + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void createApi() { + client = AwsTestClients.create(AppSyncClient.builder(), "test", Region.of(REGION)); + String suffix = UUID.randomUUID().toString(); + apiId = client.createGraphqlApi(r -> r.name("http-" + suffix).authenticationType("API_KEY")).graphqlApi().apiId(); + String apiArn = client.getGraphqlApi(r -> r.apiId(apiId)).graphqlApi().arn(); + apiKey = client.createApiKey(r -> r.apiId(apiId)).apiKey().id(); + client.startSchemaCreation(r -> r.apiId(apiId).definition(SdkBytes.fromUtf8String( + "type HttpResult { statusCode: Int! body: String! } type Query { lookup: HttpResult }"))); + await().atMost(Duration.ofSeconds(30)).until(() -> "SUCCESS".equals( + client.getSchemaCreationStatus(r -> r.apiId(apiId)).statusAsString())); + roleName = "http-resolver-" + suffix; + String roleArn = RequestScopes.callAs(ACCOUNT, REGION, () -> iam.createRole(roleName, "/", + AppSyncHttpTestPolicies.trust(apiArn, ACCOUNT), null, 3600, Map.of()).getArn()); + setPolicy("Allow"); + client.createDataSource(r -> r.apiId(apiId).name("Schedules").type("HTTP").serviceRoleArn(roleArn) + .httpConfig(h -> h.endpoint("https://scheduler." + TARGET_REGION + ".amazonaws.com") + .authorizationConfig(a -> a.authorizationType("AWS_IAM").awsIamConfig(i -> i + .signingRegion(TARGET_REGION).signingServiceName("scheduler"))))); + } + + @AfterEach + void cleanUp() { + try { + if (apiId != null) { + client.deleteGraphqlApi(r -> r.apiId(apiId)); + } + } finally { + try { + if (roleName != null) { + RequestScopes.runAs(ACCOUNT, REGION, () -> { + iam.deleteRolePolicy(roleName, "schedule"); + iam.deleteRole(roleName); + }); + } + } finally { + if (client != null) { + client.close(); + } + } + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void jsAndVtlResolversPreserveSignedServiceResponsesAndDenials(boolean vtl) { + if (vtl) { + client.createResolver(r -> r.apiId(apiId).typeName("Query").fieldName("lookup").kind("UNIT") + .dataSourceName("Schedules").requestMappingTemplate(""" + {"version":"2018-05-29","method":"GET","resourcePath":"/schedules/missing"} + """).responseMappingTemplate("$util.toJson($ctx.result)")); + } else { + client.createResolver(r -> r.apiId(apiId).typeName("Query").fieldName("lookup").kind("UNIT") + .dataSourceName("Schedules").runtime(t -> t.name("APPSYNC_JS").runtimeVersion("1.0.0")).code(""" + export function request(ctx) { + return { method: "GET", resourcePath: "/schedules/missing" }; + } + export function response(ctx) { return ctx.result; } + """)); + } + assertGraphqlResponse(404, "ResourceNotFoundException"); + setPolicy("Deny"); + assertGraphqlResponse(403, "AccessDeniedException"); + } + + @Test + void cloudFormationPreservesTheHttpEndpointAndSigningConfiguration() { + String stack = "http-source-" + UUID.randomUUID(); + String roleArn = client.getDataSource(r -> r.apiId(apiId).name("Schedules")).dataSource().serviceRoleArn(); + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.of(REGION))) { + cfn.createStack(r -> r.stackName(stack).templateBody(""" + {"Resources":{"Source":{"Type":"AWS::AppSync::DataSource","Properties":{ + "ApiId":"%s","Name":"CfnSchedules","Type":"HTTP","ServiceRoleArn":"%s", + "HttpConfig":{"Endpoint":"https://scheduler.%s.amazonaws.com", + "AuthorizationConfig":{"AuthorizationType":"AWS_IAM","AwsIamConfig":{ + "SigningRegion":"%s","SigningServiceName":"scheduler"}}}}}}} + """.formatted(apiId, roleArn, TARGET_REGION, TARGET_REGION))); + try { + await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> assertEquals("CREATE_COMPLETE", + cfn.describeStacks(r -> r.stackName(stack)).stacks().getFirst().stackStatusAsString())); + DataSource source = client.getDataSource(r -> r.apiId(apiId).name("CfnSchedules")).dataSource(); + assertEquals("HTTP", source.typeAsString()); + assertEquals(roleArn, source.serviceRoleArn()); + assertEquals("https://scheduler." + TARGET_REGION + ".amazonaws.com", source.httpConfig().endpoint()); + assertEquals("AWS_IAM", source.httpConfig().authorizationConfig().authorizationTypeAsString()); + assertEquals(TARGET_REGION, source.httpConfig().authorizationConfig().awsIamConfig().signingRegion()); + assertEquals("scheduler", source.httpConfig().authorizationConfig().awsIamConfig().signingServiceName()); + } finally { + cfn.deleteStack(r -> r.stackName(stack)); + await().atMost(Duration.ofSeconds(30)).until(() -> { + try { + cfn.describeStacks(r -> r.stackName(stack)); + return false; + } catch (CloudFormationException e) { + if ("ValidationError".equals(e.awsErrorDetails().errorCode())) { + return true; + } + throw e; + } + }); + } + } + } + + private void assertGraphqlResponse(int status, String code) { + given().header("x-api-key", apiKey).contentType("application/json") + .body(Map.of("query", "{ lookup { statusCode body } }")) + .when().post("/v1/apis/" + apiId + "/graphql") + .then().statusCode(200).body("errors", nullValue()) + .body("data.lookup.statusCode", equalTo(status)).body("data.lookup.body", containsString(code)); + } + + private void setPolicy(String effect) { + RequestScopes.runAs(ACCOUNT, REGION, () -> iam.putRolePolicy(roleName, "schedule", + AppSyncHttpTestPolicies.getSchedule(effect, TARGET_REGION, ACCOUNT))); + } +} diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/AppSyncExecutionControllerTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/AppSyncExecutionControllerTest.java index 01cb497532..31abe17803 100644 --- a/src/test/java/io/floci/aws/services/appsync/graphql/AppSyncExecutionControllerTest.java +++ b/src/test/java/io/floci/aws/services/appsync/graphql/AppSyncExecutionControllerTest.java @@ -16,8 +16,12 @@ import io.floci.aws.services.appsync.graphql.resolver.AppSyncResolverError; import io.floci.aws.services.appsync.graphql.resolver.AppSyncResolverExecutor; import io.floci.aws.services.appsync.graphql.resolver.ResolverCallbackSessions; import io.floci.aws.services.appsync.model.AuthenticationType; +import io.floci.aws.services.appsync.model.DataSource; +import io.floci.aws.services.appsync.model.DataSourceType; +import io.floci.aws.services.appsync.model.FunctionConfiguration; import io.floci.aws.services.appsync.model.GraphqlApi; import io.floci.aws.services.appsync.model.Resolver; +import io.floci.aws.services.appsync.model.ResolverKind; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.Response; @@ -240,6 +244,77 @@ class AppSyncExecutionControllerTest { spec.getValue().fields()); assertEquals("http://floci.local:4566/_floci/appsync/resolve", spec.getValue().url()); assertNotNull(spec.getValue().token()); + assertEquals(100, spec.getValue().maxBatch()); + } + + @Test + void httpUnitFieldsHaveIndependentCallbackDeadlines() { + planTwoFieldsOneWithAResolver(); + Resolver resolver = resolverExecutor.findResolver("api-1", "Query", "getMessages"); + // A missing kind follows the executor's UNIT behavior. + resolver.setDataSourceName("Http"); + DataSource source = new DataSource(); + source.setType(DataSourceType.HTTP); + when(appSyncService.getDataSource("api-1", "Http")).thenReturn(source); + assertEquals(1, executeAndCaptureCallbacks().maxBatch()); + } + + @Test + void pipelineHttpFunctionsHaveIndependentCallbackDeadlines() { + planTwoFieldsOneWithAResolver(); + Resolver resolver = resolverExecutor.findResolver("api-1", "Query", "getMessages"); + resolver.setKind(ResolverKind.PIPELINE); + resolver.setPipelineConfig(Map.of("functions", List.of("local", "http"))); + when(appSyncService.getFunction("api-1", "local")).thenReturn(new FunctionConfiguration()); + FunctionConfiguration function = new FunctionConfiguration(); + function.setDataSourceName("Http"); + when(appSyncService.getFunction("api-1", "http")).thenReturn(function); + DataSource source = new DataSource(); + source.setType(DataSourceType.HTTP); + when(appSyncService.getDataSource("api-1", "Http")).thenReturn(source); + assertEquals(1, executeAndCaptureCallbacks().maxBatch()); + } + + @Test + void nonHttpSourcesRetainNormalBatching() { + planTwoFieldsOneWithAResolver(); + Resolver resolver = resolverExecutor.findResolver("api-1", "Query", "getMessages"); + resolver.setDataSourceName("Table"); + DataSource source = new DataSource(); + source.setType(DataSourceType.AMAZON_DYNAMODB); + when(appSyncService.getDataSource("api-1", "Table")).thenReturn(source); + assertEquals(100, executeAndCaptureCallbacks().maxBatch()); + } + + @Test + void metadataFailureKeepsTheFieldWiredWithAnIndependentDeadline() { + planTwoFieldsOneWithAResolver(); + when(resolverExecutor.findResolver("api-1", "Query", "getMessages")) + .thenThrow(new AwsException("ConflictException", "schema changing", 409)); + GraphqlSidecarClient.ResolveSpec spec = executeAndCaptureCallbacks(); + assertEquals(1, spec.maxBatch()); + assertEquals(List.of(new GraphqlSidecarClient.ResolveField("Query", "getMessages")), spec.fields()); + } + + @Test + void dataSourceLookupFailureStillBelongsToTheCallbackField() { + planTwoFieldsOneWithAResolver(); + resolverExecutor.findResolver("api-1", "Query", "getMessages").setDataSourceName("Missing"); + when(appSyncService.getDataSource("api-1", "Missing")) + .thenThrow(new AwsException("NotFoundException", "missing", 404)); + GraphqlSidecarClient.ResolveSpec spec = executeAndCaptureCallbacks(); + assertEquals(1, spec.maxBatch()); + assertEquals(1, spec.fields().size()); + } + + private GraphqlSidecarClient.ResolveSpec executeAndCaptureCallbacks() { + when(fieldAuthorizationPlanner.planDenyFields(any(), any())).thenReturn(List.of()); + when(sidecarClient.execute(any(), any(), any(), any(), any(), any(), any())).thenReturn(Map.of("data", Map.of())); + controller.execute("api-1", jsonHeaders, "{\"query\":\"{ getMessages hello }\"}"); + ArgumentCaptor spec = + ArgumentCaptor.forClass(GraphqlSidecarClient.ResolveSpec.class); + verify(sidecarClient).execute(any(), any(), any(), any(), any(), any(), spec.capture()); + return spec.getValue(); } @Test @@ -256,6 +331,8 @@ class AppSyncExecutionControllerTest { verify(sidecarClient).execute(any(), any(), any(), any(), any(), any()); verify(sidecarClient, never()).execute(any(), any(), any(), any(), any(), any(), any()); + verify(resolverExecutor, never()).findResolver("api-1", "Query", "getMessages"); + verify(appSyncService, never()).getDataSource(any(), any()); } @Test diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/datasource/AwsIamHttpDataSourceIntegrationTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/AwsIamHttpDataSourceIntegrationTest.java new file mode 100644 index 0000000000..7abb7dcf82 --- /dev/null +++ b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/AwsIamHttpDataSourceIntegrationTest.java @@ -0,0 +1,260 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.services.appsync.model.DataSource; +import io.floci.aws.services.appsync.model.DataSourceType; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.scheduler.SchedulerService; +import io.floci.aws.services.stepfunctions.StepFunctionsService; +import io.floci.aws.testing.AppSyncHttpTestPolicies; +import io.floci.aws.testutil.AwsRequestSigner; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import io.quarkus.test.junit.mockito.InjectSpy; +import io.restassured.RestAssured; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +import java.net.URI; +import java.time.Instant; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.verify; + +@QuarkusTest +@TestProfile(AwsIamHttpDataSourceIntegrationTest.EnforcedSignatures.class) +class AwsIamHttpDataSourceIntegrationTest { + + private static final String ACCOUNT = "724600001234"; + private static final String API_REGION = "us-east-1"; + private static final String TARGET_REGION = "us-west-2"; + private static final String API_ARN = "arn:aws:appsync:" + API_REGION + ":" + ACCOUNT + ":apis/example"; + + public static class EnforcedSignatures implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.iam.enforcement-enabled", "true", "floci.auth.validate-signatures", "true"); + } + } + + @Inject + AppSyncDataSourceInvokers invokers; + @InjectSpy + IamService iam; + @Inject + SchedulerService scheduler; + @Inject + StepFunctionsService states; + + private String roleName; + private DataSource source; + + @BeforeEach + void createRole() { + roleName = "http-data-source-" + UUID.randomUUID(); + String roleArn = RequestScopes.callAs(ACCOUNT, API_REGION, () -> { + String arn = iam.createRole(roleName, "/appsync/", AppSyncHttpTestPolicies.trust(API_ARN, ACCOUNT), null, 3600, Map.of()).getArn(); + iam.putRolePolicy(roleName, "schedule", policy("Allow")); + return arn; + }); + source = new DataSource(); + source.setType(DataSourceType.HTTP); + source.setName("Scheduler"); + source.setDataSourceArn(API_ARN + "/datasources/Scheduler"); + source.setServiceRoleArn(roleArn); + source.setHttpConfig(Map.of("endpoint", "https://scheduler." + TARGET_REGION + ".amazonaws.com", + "authorizationConfig", Map.of("authorizationType", "AWS_IAM", "awsIamConfig", + Map.of("signingRegion", TARGET_REGION, "signingServiceName", "scheduler")))); + clearInvocations(iam); + } + + @AfterEach + void deleteRole() { + RequestScopes.runAs(ACCOUNT, API_REGION, () -> { + iam.deleteRolePolicy(roleName, "schedule"); + iam.deleteRole(roleName); + }); + } + + @Test + void signedSchedulerRequestReachesTheLocalServiceInTheConfiguredRegionAndAccount() { + Map result = invoke(); + assertEquals(404, result.get("statusCode")); + assertTrue(result.get("body").toString().contains("ResourceNotFoundException")); + assertSessionWasRemoved(); + } + + @Test + void targetServiceEnforcesTheRealRolePolicyAndStillCleansUpTheSession() { + RequestScopes.runAs(ACCOUNT, API_REGION, () -> iam.putRolePolicy(roleName, "schedule", policy("Deny"))); + Map result = invoke(); + assertEquals(403, result.get("statusCode")); + assertSessionWasRemoved(); + } + + @Test + void cleanedUpSessionCannotBeReplayedAgainstTheNativeListener() throws Exception { + assertEquals(404, invoke().get("statusCode")); + ArgumentCaptor key = ArgumentCaptor.forClass(String.class); + ArgumentCaptor secret = ArgumentCaptor.forClass(String.class); + ArgumentCaptor token = ArgumentCaptor.forClass(String.class); + verify(iam).registerSessionForAccount(eq(ACCOUNT), key.capture(), secret.capture(), token.capture(), + eq(source.getServiceRoleArn()), any(Instant.class), isNull()); + URI uri = URI.create("http://localhost:" + RestAssured.port + "/schedules/missing"); + Map headers = AwsRequestSigner.signedAs(key.getValue(), secret.getValue(), "scheduler") + .inRegion(TARGET_REGION).headersFor("GET", uri, + Map.of("x-amz-security-token", token.getValue()), new byte[0]); + given().headers(headers).header("x-amz-security-token", token.getValue()) + .when().get("/schedules/missing") + .then().statusCode(403).body(containsString("UnrecognizedClientException")); + } + + @Test + void signedSchedulerCreatesReadsAndDeletesOnlyInItsTargetAccountAndRegion() { + String name = "http-" + UUID.randomUUID(); + String executionRole = roleName + "-execution"; + String scheduleArn = "arn:aws:scheduler:" + TARGET_REGION + ":" + ACCOUNT + ":schedule/default/" + name; + String executionArn = RequestScopes.callAs(ACCOUNT, API_REGION, () -> iam.createRole(executionRole, "/", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", + "Principal":{"Service":"scheduler.amazonaws.com"}}]} + """, null, 3600, Map.of()).getArn()); + try { + RequestScopes.runAs(ACCOUNT, API_REGION, () -> iam.putRolePolicy(roleName, "schedule", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":["scheduler:CreateSchedule","scheduler:GetSchedule","scheduler:DeleteSchedule"], + "Resource":"%s"},{"Effect":"Allow","Action":"iam:PassRole","Resource":"%s"}]} + """.formatted(scheduleArn, executionArn))); + Map body = Map.of("ScheduleExpression", "at(2099-01-01T00:00:00)", "State", "DISABLED", + "FlexibleTimeWindow", Map.of("Mode", "OFF"), "Target", Map.of("RoleArn", executionArn, + "Arn", "arn:aws:lambda:" + TARGET_REGION + ":" + ACCOUNT + ":function:unused")); + assertEquals(200, invoke("POST", "/schedules/" + name, Map.of("body", body)).get("statusCode")); + Map read = invoke("GET", "/schedules/" + name, Map.of()); + assertEquals(200, read.get("statusCode")); + assertTrue(read.get("body").toString().contains(scheduleArn)); + assertTrue(RequestScopes.callAs(ACCOUNT, API_REGION, + () -> scheduler.listSchedules(null, name, null, API_REGION)).isEmpty()); + assertTrue(RequestScopes.callAs("724699999999", TARGET_REGION, + () -> scheduler.listSchedules(null, name, null, TARGET_REGION)).isEmpty()); + assertEquals(200, invoke("DELETE", "/schedules/" + name, Map.of()).get("statusCode")); + assertEquals(404, invoke("GET", "/schedules/" + name, Map.of()).get("statusCode")); + assertSessionWasRemoved(); + } finally { + scheduler.deleteScheduleForAccount(ACCOUNT, name, "default", TARGET_REGION); + RequestScopes.runAs(ACCOUNT, API_REGION, () -> iam.deleteRole(executionRole)); + } + } + + @Test + void aRoleWithoutCreateSchedulePermissionCannotStoreASchedule() { + String name = "denied-" + UUID.randomUUID(); + Map denied = invoke("POST", "/schedules/" + name, Map.of("body", Map.of())); + assertEquals(403, denied.get("statusCode")); + assertTrue(RequestScopes.callAs(ACCOUNT, TARGET_REGION, + () -> scheduler.listSchedules(null, name, null, TARGET_REGION)).isEmpty()); + assertSessionWasRemoved(); + } + + @ParameterizedTest + @ValueSource(strings = {"SendTaskSuccess", "SendTaskFailure"}) + void signedCallbacksRespectRoleDenialBeforeCompletingTheOwnedToken(String operation) { + String token = "http-" + UUID.randomUUID(); + String resource = "arn:aws:states:" + TARGET_REGION + ":" + ACCOUNT + ":stateMachine:callback"; + CompletableFuture future = states.registerPendingToken(token, ACCOUNT, resource); + configureStates(); + try { + callbackPolicy("Deny", operation, resource); + Map denied = callback(operation, token); + assertEquals(400, denied.get("statusCode")); + assertTrue(denied.get("body").toString().contains("AccessDeniedException")); + assertFalse(future.isDone()); + callbackPolicy("Allow", operation, resource); + assertEquals(200, callback(operation, token).get("statusCode")); + assertTrue(future.isDone()); + if ("SendTaskSuccess".equals(operation)) { + assertTrue(future.join().path("delivered").asBoolean()); + } else { + assertTrue(future.isCompletedExceptionally()); + } + assertSessionWasRemoved(); + } finally { + states.discardPendingToken(token); + } + } + + @Test + void aSignedCallbackCannotClaimATokenInAnotherRegion() { + String token = "http-" + UUID.randomUUID(); + String resource = "arn:aws:states:" + API_REGION + ":" + ACCOUNT + ":stateMachine:callback"; + CompletableFuture future = states.registerPendingToken(token, ACCOUNT, resource); + configureStates(); + try { + callbackPolicy("Allow", "SendTaskSuccess", "*"); + Map result = callback("SendTaskSuccess", token); + assertEquals(400, result.get("statusCode")); + assertTrue(result.get("body").toString().contains("InvalidToken")); + assertFalse(future.isDone()); + assertSessionWasRemoved(); + } finally { + states.discardPendingToken(token); + } + } + + private void configureStates() { + source.setHttpConfig(Map.of("endpoint", "https://states." + TARGET_REGION + ".amazonaws.com", + "authorizationConfig", Map.of("authorizationType", "AWS_IAM", "awsIamConfig", + Map.of("signingRegion", TARGET_REGION, "signingServiceName", "states")))); + } + + private void callbackPolicy(String effect, String operation, String resource) { + RequestScopes.runAs(ACCOUNT, API_REGION, () -> iam.putRolePolicy(roleName, "schedule", """ + {"Version":"2012-10-17","Statement":[{"Effect":"%s","Action":"states:%s","Resource":"%s"}]} + """.formatted(effect, operation, resource))); + } + + private Map callback(String operation, String token) { + return invoke("POST", "/", Map.of("headers", Map.of("X-Amz-Target", "AWSStepFunctions." + operation), + "body", Map.of("taskToken", token, "output", "{\"delivered\":true}", "error", "TaskFailed", "cause", "test"))); + } + + private Map invoke() { + return invoke("GET", "/schedules/missing", Map.of("headers", Map.of("Content-Type", "application/json"))); + } + + private Map invoke(String method, String path, Map params) { + return (Map) RequestScopes.callAs(ACCOUNT, API_REGION, () -> invokers.invoke(source, + Map.of("method", method, "resourcePath", path, "params", params), API_REGION)); + } + + private void assertSessionWasRemoved() { + ArgumentCaptor key = ArgumentCaptor.forClass(String.class); + verify(iam, atLeastOnce()).registerSessionForAccount(eq(ACCOUNT), key.capture(), anyString(), anyString(), + eq(source.getServiceRoleArn()), any(Instant.class), isNull()); + for (String issued : key.getAllValues()) { + assertFalse(iam.isKnownAccessKey(issued)); + } + } + + private static String policy(String effect) { + return AppSyncHttpTestPolicies.getSchedule(effect, TARGET_REGION, ACCOUNT); + } +} diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/datasource/AwsIamHttpDataSourceInvokerTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/AwsIamHttpDataSourceInvokerTest.java new file mode 100644 index 0000000000..afc6a19bb6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/AwsIamHttpDataSourceInvokerTest.java @@ -0,0 +1,109 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +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.ServiceRegistry; +import io.floci.aws.services.appsync.model.DataSource; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.iam.ServiceRoleAuthorizer; +import io.quarkus.vertx.http.HttpServer; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +import java.net.URI; +import java.time.Instant; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +class AwsIamHttpDataSourceInvokerTest { + + private static final String ACCOUNT = "724600001234"; + private static final String REGION = "us-east-1"; + private final IamService iam = mock(IamService.class); + private final ServiceRoleAuthorizer authorizer = mock(ServiceRoleAuthorizer.class); + private final ServiceRegistry services = mock(ServiceRegistry.class); + private final HttpServer server = mock(HttpServer.class); + private final HttpDataSourceTransport transport = mock(HttpDataSourceTransport.class); + private DataSource source; + private HttpDataSourceRequest request; + private AwsIamHttpDataSourceInvoker invoker; + + @BeforeEach + void setUp() { + when(services.isServiceEnabled("scheduler")).thenReturn(true); + when(server.getLocalBaseUri()).thenReturn(URI.create("http://localhost:4566")); + when(authorizer.refusal(any(), any(), any(), any(), any())).thenReturn(Optional.empty()); + source = new DataSource(); + source.setDataSourceArn("arn:aws:appsync:" + REGION + ":" + ACCOUNT + ":apis/example/datasources/Http"); + source.setServiceRoleArn("arn:aws:iam::" + ACCOUNT + ":role/appsync/Resolver"); + source.setHttpConfig(Map.of("endpoint", "https://scheduler.us-west-2.amazonaws.com", "authorizationConfig", + Map.of("authorizationType", "AWS_IAM", "awsIamConfig", + Map.of("signingRegion", "us-west-2", "signingServiceName", "scheduler")))); + request = HttpDataSourceRequest.parse(source, Map.of("method", "GET", "resourcePath", "/schedules/example"), + new ObjectMapper()); + invoker = new AwsIamHttpDataSourceInvoker(iam, authorizer, services, new RegionResolver(REGION, ACCOUNT), + server, transport); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void transportFailureOrTimeoutAlwaysRevokesTheIssuedSession(boolean timeout) { + RuntimeException failure = timeout ? new AwsException("HttpException", "HTTP deadline exceeded", 500) + : new IllegalStateException("connection failed"); + when(transport.send(any())).thenThrow(failure); + AwsException error = assertThrows(AwsException.class, () -> invoker.invoke(source, request, REGION)); + assertEquals("HttpException", error.getErrorCode()); + ArgumentCaptor key = ArgumentCaptor.forClass(String.class); + verify(iam).registerSessionForAccount(eq(ACCOUNT), key.capture(), anyString(), anyString(), + eq(source.getServiceRoleArn()), any(Instant.class), isNull()); + verify(iam).unregisterSession(ACCOUNT, key.getValue()); + } + + @Test + void signedRequestUsesTheNativeListenerAndRevokesItsCredentials() { + when(transport.send(any())).thenReturn(Map.of("statusCode", 200, "headers", Map.of(), "body", "ok")); + assertEquals(200, invoker.invoke(source, request, REGION).get("statusCode")); + ArgumentCaptor key = ArgumentCaptor.forClass(String.class); + verify(iam).registerSessionForAccount(eq(ACCOUNT), key.capture(), anyString(), anyString(), + eq(source.getServiceRoleArn()), any(Instant.class), isNull()); + verify(iam).unregisterSession(ACCOUNT, key.getValue()); + ArgumentCaptor outgoing = ArgumentCaptor.forClass(HttpDataSourceRequest.class); + verify(transport).send(outgoing.capture()); + assertEquals(URI.create("http://localhost:4566/schedules/example"), outgoing.getValue().uri()); + } + + @Test + void aDisabledServiceCannotReceiveASignedRequest() { + when(services.isServiceEnabled("scheduler")).thenReturn(false); + assertRefusedBeforeCredentials("ServiceNotAvailableException"); + } + + @Test + void aMissingOrUntrustedRoleCannotIssueCredentials() { + when(authorizer.refusal(any(), any(), any(), any(), any())).thenReturn(Optional.of("Role cannot be assumed")); + assertRefusedBeforeCredentials("AccessDeniedException"); + } + + private void assertRefusedBeforeCredentials(String code) { + assertEquals(code, assertThrows(AwsException.class, () -> invoker.invoke(source, request, REGION)).getErrorCode()); + verify(iam, never()).registerSessionForAccount(anyString(), anyString(), anyString(), anyString(), + anyString(), any(), any()); + verifyNoInteractions(transport); + } +} diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/datasource/AwsIamHttpDataSourcePermissiveIntegrationTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/AwsIamHttpDataSourcePermissiveIntegrationTest.java new file mode 100644 index 0000000000..3ec1ac5697 --- /dev/null +++ b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/AwsIamHttpDataSourcePermissiveIntegrationTest.java @@ -0,0 +1,68 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.services.appsync.model.DataSource; +import io.floci.aws.services.appsync.model.DataSourceType; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.testing.ValidateSignaturesProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.quarkus.test.junit.mockito.InjectSpy; +import jakarta.inject.Inject; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +import java.time.Instant; +import java.util.Map; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.verify; + +@QuarkusTest +@TestProfile(ValidateSignaturesProfile.class) +class AwsIamHttpDataSourcePermissiveIntegrationTest { + + private static final String ACCOUNT = "724600001234"; + private static final String API_REGION = "us-east-1"; + private static final String TARGET_REGION = "us-west-2"; + + @Inject + AppSyncDataSourceInvokers invokers; + @InjectSpy + IamService iam; + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void signedRequestsReachTheNativeListenerWithoutAnExistingRoleAndRevokeCredentials(boolean vtl) { + String roleName = "http-permissive-" + UUID.randomUUID(); + assertTrue(iam.findRole(ACCOUNT, roleName).isEmpty()); + DataSource source = new DataSource(); + source.setType(DataSourceType.HTTP); + source.setDataSourceArn("arn:aws:appsync:" + API_REGION + ":" + ACCOUNT + ":apis/example/datasources/Http"); + source.setServiceRoleArn("arn:aws:iam::" + ACCOUNT + ":role/" + roleName); + source.setHttpConfig(Map.of("endpoint", "https://scheduler." + TARGET_REGION + ".amazonaws.com", + "authorizationConfig", Map.of("authorizationType", "AWS_IAM", "awsIamConfig", + Map.of("signingRegion", TARGET_REGION, "signingServiceName", "scheduler")))); + Map request = Map.of("method", "GET", "resourcePath", "/schedules/" + roleName); + clearInvocations(iam); + + Map result = (Map) RequestScopes.callAs(ACCOUNT, API_REGION, + () -> vtl ? invokers.invokeVtl(source, request, API_REGION) : invokers.invoke(source, request, API_REGION)); + + assertEquals(404, result.get("statusCode")); + assertTrue(result.get("body").toString().contains("ResourceNotFoundException")); + ArgumentCaptor key = ArgumentCaptor.forClass(String.class); + verify(iam).registerSessionForAccount(eq(ACCOUNT), key.capture(), anyString(), anyString(), + eq(source.getServiceRoleArn()), any(Instant.class), isNull()); + assertFalse(iam.isKnownAccessKey(key.getValue())); + } +} diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceAwsTargetTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceAwsTargetTest.java new file mode 100644 index 0000000000..de3c9c899c --- /dev/null +++ b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceAwsTargetTest.java @@ -0,0 +1,136 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.services.appsync.model.DataSource; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class HttpDataSourceAwsTargetTest { + + private static final String ACCOUNT = "724600001234"; + private static final String API_REGION = "us-east-1"; + private static final String REGION = "us-west-2"; + private final ObjectMapper mapper = new ObjectMapper(); + private final RegionResolver regions = new RegionResolver(API_REGION, ACCOUNT); + + @Test + void schedulerCanUseADifferentRegionWithinTheSamePartition() { + HttpDataSourceAwsTarget target = parse(source("scheduler", endpoint("scheduler")), "GET", "/schedules/example", Map.of()); + assertEquals("scheduler", target.service()); + assertEquals(REGION, target.region()); + assertEquals(ACCOUNT, target.accountId()); + assertEquals("arn:aws:appsync:" + API_REGION + ":" + ACCOUNT + ":apis/example", target.sourceApiArn()); + } + + @ParameterizedTest + @ValueSource(strings = {"/_floci/state/reset", "/", "/schedules", "/schedules/.", "/schedules/..", + "/schedules/a/extra", "/schedules/a%2Fb", "/schedules/%2e%2e", "/schedules/a%3fb"}) + void schedulerCannotEscapeTheAuditedOperationPaths(String path) { + assertInvalid(source("scheduler", endpoint("scheduler")), "POST", path, Map.of()); + } + + @ParameterizedTest + @ValueSource(strings = {"http://scheduler.us-west-2.amazonaws.com", "https://scheduler.us-west-2.amazonaws.com:443", + "https://scheduler.us-west-2.amazonaws.com.evil.example", "https://scheduler.us-west-2.amazonaws.com/base", + "https://states.us-west-2.amazonaws.com"}) + void signingScopeCannotBeRedirectedToAnotherEndpoint(String endpoint) { + assertInvalid(source("scheduler", endpoint), "GET", "/schedules/example", Map.of()); + } + + @ParameterizedTest + @ValueSource(strings = {"authorization", "x-amz-date", "x-amz-security-token", "x-amzn-query-mode", + "x-forwarded-host", "x-floci-service"}) + void resolverHeadersCannotOverrideCredentialsOrListenerRouting(String header) { + assertInvalid(source("scheduler", endpoint("scheduler")), "GET", "/schedules/example", + Map.of("headers", Map.of(header, "untrusted"))); + } + + @ParameterizedTest + @ValueSource(strings = {"Action", "X-Amz-Credential", "X-Amz-Signature", "service"}) + void queryParametersCannotSelectAnotherProtocolOrIdentity(String name) { + assertInvalid(source("scheduler", endpoint("scheduler")), "GET", "/schedules/example", + Map.of("query", Map.of(name, "untrusted"))); + } + + @ParameterizedTest + @ValueSource(strings = {"s3", "ssm", "execute-api", "unknown"}) + void unauditedAwsServicesAreRefused(String service) { + assertInvalid(source(service, endpoint(service)), "POST", "/", Map.of()); + } + + @ParameterizedTest + @ValueSource(strings = {"aws-global", "us-fake-99", "US-WEST-2"}) + void nonRegionalSigningScopesAreRejected(String region) { + String endpoint = "https://scheduler." + region + ".amazonaws.com"; + DataSource source = source("scheduler", endpoint); + source.setHttpConfig(Map.of("endpoint", endpoint, "authorizationConfig", + Map.of("authorizationType", "AWS_IAM", "awsIamConfig", + Map.of("signingRegion", region, "signingServiceName", "scheduler")))); + assertInvalid(source, "GET", "/schedules/example", Map.of()); + } + + @ParameterizedTest + @ValueSource(strings = {"AWSStepFunctions.SendTaskSuccess", "AWSStepFunctions.SendTaskFailure"}) + void stateTaskCallbacksAreTheOnlySupportedJsonOperations(String operation) { + assertEquals("states", parse(source("states", endpoint("states")), "POST", "/", + Map.of("headers", Map.of("X-Amz-Target", operation))).service()); + } + + @ParameterizedTest + @ValueSource(strings = {"AWSStepFunctions.StartExecution", "AWSSimpleSystemsManagement.GetParameter", "unknown", ""}) + void jsonTargetsCannotSelectAnUnauditedOperation(String operation) { + assertInvalid(source("states", endpoint("states")), "POST", "/", + Map.of("headers", Map.of("X-Amz-Target", operation))); + } + + @Test + void anUnsupportedStepFunctionsWireProtocolIsRefusedBeforeSigning() { + assertInvalid(source("states", endpoint("states")), "POST", "/", Map.of("headers", + Map.of("X-Amz-Target", "AWSStepFunctions.SendTaskSuccess", "Content-Type", "application/x-amz-json-1.1"))); + } + + @Test + void missingStateTargetAndForeignRolesFailClosed() { + assertInvalid(source("states", endpoint("states")), "POST", "/", Map.of()); + for (String role : new String[]{"arn:aws:iam::999999999999:role/other", + "arn:aws-cn:iam::" + ACCOUNT + ":role/other"}) { + DataSource source = source("scheduler", endpoint("scheduler")); + source.setServiceRoleArn(role); + AwsException error = assertThrows(AwsException.class, () -> parse(source, "GET", "/schedules/example", Map.of())); + assertEquals("AccessDeniedException", error.getErrorCode()); + } + } + + private void assertInvalid(DataSource source, String method, String path, Map params) { + AwsException error = assertThrows(AwsException.class, () -> parse(source, method, path, params)); + assertEquals("MappingTemplate", error.getErrorCode()); + } + + private HttpDataSourceAwsTarget parse(DataSource source, String method, String path, Map params) { + HttpDataSourceRequest request = HttpDataSourceRequest.parse(source, + Map.of("method", method, "resourcePath", path, "params", params), mapper); + return HttpDataSourceAwsTarget.parse(source, request, API_REGION, regions); + } + + private static DataSource source(String service, String endpoint) { + DataSource source = new DataSource(); + source.setDataSourceArn("arn:aws:appsync:" + API_REGION + ":" + ACCOUNT + ":apis/example/datasources/Http"); + source.setServiceRoleArn("arn:aws:iam::" + ACCOUNT + ":role/Http"); + source.setHttpConfig(Map.of("endpoint", endpoint, "authorizationConfig", + Map.of("authorizationType", "AWS_IAM", "awsIamConfig", + Map.of("signingRegion", REGION, "signingServiceName", service)))); + return source; + } + + private static String endpoint(String service) { + return "https://" + service + "." + REGION + ".amazonaws.com"; + } +} diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceBatchSidecarIntegrationTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceBatchSidecarIntegrationTest.java new file mode 100644 index 0000000000..d5c7eb8ef4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceBatchSidecarIntegrationTest.java @@ -0,0 +1,120 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.floci.aws.testing.SidecarContainersProfile; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.appsync.AppSyncClient; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.when; + +@QuarkusTest +@TestProfile(SidecarContainersProfile.class) +class HttpDataSourceBatchSidecarIntegrationTest { + + @InjectMock + HttpDataSourceTransport transport; + + private final CountDownLatch started = new CountDownLatch(2); + private AppSyncClient client; + private String apiId; + private String apiKey; + + @BeforeAll + static void requireSidecar() { + SidecarContainersProfile.requireDockerAndImage("floci.services.appsync.graphql-image"); + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void createApi() { + reset(transport); + client = AwsTestClients.create(AppSyncClient.builder(), "test", Region.US_EAST_1); + apiId = client.createGraphqlApi(r -> r.name("http-batch-" + UUID.randomUUID()).authenticationType("API_KEY")) + .graphqlApi().apiId(); + apiKey = client.createApiKey(r -> r.apiId(apiId)).apiKey().id(); + client.startSchemaCreation(r -> r.apiId(apiId).definition(SdkBytes.fromUtf8String( + "type Query { first: String second: String } type Mutation { first: String second: String }"))); + await().atMost(Duration.ofSeconds(30)).until(() -> "SUCCESS".equals( + client.getSchemaCreationStatus(r -> r.apiId(apiId)).statusAsString())); + client.createDataSource(r -> r.apiId(apiId).name("Http").type("HTTP") + .httpConfig(h -> h.endpoint("https://public.example"))); + for (String type : List.of("Query", "Mutation")) { + for (String field : List.of("first", "second")) { + client.createResolver(r -> r.apiId(apiId).typeName(type).fieldName(field).dataSourceName("Http") + .kind("UNIT").requestMappingTemplate(""" + {"version":"2018-05-29","method":"GET","resourcePath":"/%s"} + """.formatted(field)).responseMappingTemplate("$util.toJson($ctx.result.body)")); + } + } + } + + @AfterEach + void cleanUp() { + started.countDown(); + started.countDown(); + try { + if (apiId != null) { + client.deleteGraphqlApi(r -> r.apiId(apiId)); + } + } finally { + if (client != null) { + client.close(); + } + } + } + + @Test + void independentHttpFieldsDoNotShareASequentialCallbackDeadline() { + when(transport.send(any())).thenAnswer(call -> { + started.countDown(); + if (!started.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Independent HTTP fields did not start concurrently"); + } + HttpDataSourceRequest request = call.getArgument(0); + return Map.of("statusCode", 200, "headers", Map.of(), "body", request.uri().getPath()); + }); + given().header("x-api-key", apiKey).contentType("application/json") + .body(Map.of("query", "{ first second }")) + .when().post("/v1/apis/" + apiId + "/graphql") + .then().statusCode(200).body("errors", nullValue()) + .body("data.first", equalTo("/first")).body("data.second", equalTo("/second")); + } + @Test + void rootMutationsStillRunInSelectionOrder() { + List calls = new CopyOnWriteArrayList<>(); + when(transport.send(any())).thenAnswer(call -> { + HttpDataSourceRequest request = call.getArgument(0); + calls.add(request.uri().getPath()); + return Map.of("statusCode", 200, "headers", Map.of(), "body", String.join(",", calls)); + }); + given().header("x-api-key", apiKey).contentType("application/json") + .body(Map.of("query", "mutation { first second }")) + .when().post("/v1/apis/" + apiId + "/graphql") + .then().statusCode(200).body("errors", nullValue()) + .body("data.first", equalTo("/first")).body("data.second", equalTo("/first,/second")); + } + +} diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceInvokerIntegrationTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceInvokerIntegrationTest.java new file mode 100644 index 0000000000..ab29c9391b --- /dev/null +++ b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceInvokerIntegrationTest.java @@ -0,0 +1,95 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.appsync.model.DataSource; +import io.floci.aws.services.appsync.model.DataSourceType; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@QuarkusTest +@TestProfile(HttpDataSourceInvokerIntegrationTest.Enforced.class) +class HttpDataSourceInvokerIntegrationTest { + + public static class Enforced implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.iam.enforcement-enabled", "true"); + } + } + + @Inject + AppSyncDataSourceInvokers invokers; + @InjectMock + HttpDataSourceTransport transport; + + private DataSource source; + + @BeforeEach + void setUp() { + reset(transport); + source = new DataSource(); + source.setName("PublicHttp"); + source.setType(DataSourceType.HTTP); + source.setDataSourceArn("arn:aws:appsync:us-east-1:000000000000:apis/example/datasources/PublicHttp"); + source.setHttpConfig(Map.of("endpoint", "https://public.example/base")); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void jsAndVtlExposeTheHttpResponseWithoutRequiringAnUnsignedSourceRole(boolean vtl) { + Map response = Map.of("statusCode", 409, "headers", Map.of("content-type", "text/plain"), + "body", "conflict"); + when(transport.send(any())).thenReturn(response); + Map request = Map.of("version", "2018-05-29", "method", "POST", "resourcePath", "/items", + "params", Map.of("query", Map.of("name", "a b"), "headers", Map.of("Content-Type", "text/plain"), + "body", "request")); + + Object result = vtl ? invokers.invokeVtl(source, request, "us-east-1") + : invokers.invoke(source, request, "us-east-1"); + + assertEquals(response, result); + ArgumentCaptor sent = ArgumentCaptor.forClass(HttpDataSourceRequest.class); + verify(transport).send(sent.capture()); + assertEquals(URI.create("https://public.example/base/items?name=a%20b"), sent.getValue().uri()); + assertEquals("POST", sent.getValue().method()); + assertEquals("request", new String(sent.getValue().body(), StandardCharsets.UTF_8)); + } + + @Test + void malformedRequestsFailBeforeNetworkAccess() { + AwsException error = assertThrows(AwsException.class, + () -> invokers.invoke(source, Map.of("method", "GET", "resourcePath", "//other.example/path"), "us-east-1")); + assertEquals("MappingTemplate", error.getErrorCode()); + verifyNoInteractions(transport); + } + + @Test + void unsupportedAuthorizationIsNeverSentUnsigned() { + source.setHttpConfig(Map.of("endpoint", "https://public.example", "authorizationConfig", + Map.of("authorizationType", "UNSUPPORTED"))); + AwsException error = assertThrows(AwsException.class, + () -> invokers.invoke(source, Map.of("method", "GET", "resourcePath", "/"), "us-east-1")); + assertEquals("MappingTemplate", error.getErrorCode()); + verifyNoInteractions(transport); + } +} diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceRequestTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceRequestTest.java new file mode 100644 index 0000000000..27e3a04f45 --- /dev/null +++ b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceRequestTest.java @@ -0,0 +1,103 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.appsync.model.DataSource; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class HttpDataSourceRequestTest { + + private final ObjectMapper mapper = new ObjectMapper(); + + @Test + void preservesEndpointBasePathAndEscapedResourcePath() { + HttpDataSourceRequest request = parse("https://api.example.com/base/", + Map.of("method", "GET", "resourcePath", "/items/a%2Fb")); + + assertEquals("https://api.example.com/base/items/a%2Fb", request.uri().toString()); + assertEquals("GET", request.method()); + assertArrayEquals(new byte[0], request.body()); + } + + @Test + void encodesQueryValuesOnceAndPreservesUtf8Body() { + HttpDataSourceRequest request = parse("https://api.example.com", Map.of( + "version", "2018-05-29", "method", "POST", "resourcePath", "/items", + "params", Map.of("query", Map.of("q", "a+b /ü&x=1"), + "headers", Map.of("Content-Type", "text/plain", "X-Request-Id", "abc"), + "body", "hello ü"))); + + assertEquals("https://api.example.com/items?q=a%2Bb%20%2F%C3%BC%26x%3D1", request.uri().toString()); + assertEquals(Map.of("content-type", "text/plain", "x-request-id", "abc"), request.headers()); + assertEquals("hello ü", new String(request.body(), StandardCharsets.UTF_8)); + } + + @Test + void serializesStructuredBodyAndHonorsDeclaredCharset() throws Exception { + HttpDataSourceRequest json = parse("https://api.example.com", Map.of( + "method", "PUT", "resourcePath", "/", "params", Map.of("body", Map.of("id", 7)))); + assertEquals(mapper.readTree("{\"id\":7}"), mapper.readTree(json.body())); + + HttpDataSourceRequest text = parse("https://api.example.com", Map.of( + "method", "PATCH", "resourcePath", "/", "params", Map.of("body", "café", + "headers", Map.of("Content-Type", "text/plain; charset=ISO-8859-1")))); + assertArrayEquals("café".getBytes(StandardCharsets.ISO_8859_1), text.body()); + } + + @Test + void refusesPathsThatReplaceOriginOrCarryQueryOrFragment() { + for (String path : List.of("https://other.example/a", "//other.example/a", "relative", "/a?x=1", "/a#f", "/a\\b")) { + assertInvalid("https://api.example.com", Map.of("method", "GET", "resourcePath", path)); + } + } + + @Test + void refusesAmbiguousEndpointAuthorityAndUnsupportedSchemes() { + for (String endpoint : List.of("file:///etc/passwd", "https://user:pass@api.example.com", "https://api.example.com?a=1", + "https://api.example.com#f", "http://", "https://api.example.com:99999")) { + assertInvalid(endpoint, Map.of("method", "GET", "resourcePath", "/")); + } + } + + @Test + void refusesReservedOrInjectedHeadersAndNonStringParams() { + for (String name : List.of("Host", "Connection", "Content-Length", "Transfer-Encoding", "Expect", "User-Agent", "Keep-Alive")) { + assertInvalid("https://api.example.com", Map.of("method", "GET", "resourcePath", "/", + "params", Map.of("headers", Map.of(name, "value")))); + } + assertInvalid("https://api.example.com", Map.of("method", "GET", "resourcePath", "/", + "params", Map.of("headers", Map.of("x-test", "good\r\nHost: evil")))); + assertInvalid("https://api.example.com", Map.of("method", "GET", "resourcePath", "/", + "params", Map.of("query", Map.of("id", 1)))); + assertInvalid("https://api.example.com", Map.of("method", "GET", "resourcePath", "/", "params", "bad")); + } + + @Test + void refusesMissingMethodPathUnsupportedMethodAndVersion() { + for (Map request : List.>of(Map.of("method", "GET"), Map.of("resourcePath", "/"), + Map.of("method", "TRACE", "resourcePath", "/"), + Map.of("method", "GET", "resourcePath", "/", "version", "2017-02-28"))) { + assertInvalid("https://api.example.com", request); + } + } + + private HttpDataSourceRequest parse(String endpoint, Map request) { + DataSource source = new DataSource(); + source.setName("Http"); + source.setHttpConfig(Map.of("endpoint", endpoint)); + return HttpDataSourceRequest.parse(source, request, mapper); + } + + private void assertInvalid(String endpoint, Map request) { + AwsException error = assertThrows(AwsException.class, () -> parse(endpoint, request)); + assertEquals("MappingTemplate", error.getErrorCode()); + } +} diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceTransportTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceTransportTest.java new file mode 100644 index 0000000000..19135cf70b --- /dev/null +++ b/src/test/java/io/floci/aws/services/appsync/graphql/datasource/HttpDataSourceTransportTest.java @@ -0,0 +1,309 @@ +package io.floci.aws.services.appsync.graphql.datasource; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpServer; +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsServer; +import io.floci.aws.config.FlociCertificateAuthority; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.Pem; +import io.floci.aws.services.acm.CertificateGenerator; +import io.floci.aws.services.acm.model.KeyAlgorithm; +import io.floci.aws.services.appsync.model.DataSource; +import io.floci.aws.testing.TlsTrust; +import org.apache.hc.client5.http.DnsResolver; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import javax.net.ssl.SSLContext; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class HttpDataSourceTransportTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private final AtomicInteger calls = new AtomicInteger(); + private HttpServer server; + private HttpDataSourceTransport transport; + private final CountDownLatch slowResponseReleased = new CountDownLatch(1); + + @BeforeEach + void startServer() throws Exception { + server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.createContext("/", exchange -> { + calls.incrementAndGet(); + byte[] body = exchange.getRequestBody().readAllBytes(); + byte[] response = mapper.writeValueAsBytes(Map.of( + "method", exchange.getRequestMethod(), "uri", exchange.getRequestURI().toString(), + "body", new String(body, StandardCharsets.UTF_8), + "authorization", String.valueOf(exchange.getRequestHeaders().getFirst("Authorization")), + "cookie", String.valueOf(exchange.getRequestHeaders().getFirst("Cookie")))); + exchange.getResponseHeaders().set("X-Result", "present"); + exchange.getResponseHeaders().set("Set-Cookie", "session=must-not-persist"); + exchange.sendResponseHeaders(200, response.length); + try (exchange) { + exchange.getResponseBody().write(response); + } + }); + server.createContext("/redirect", exchange -> { + exchange.getResponseHeaders().set("Location", "/"); + exchange.sendResponseHeaders(302, -1); + exchange.close(); + }); + server.createContext("/error", exchange -> { + byte[] body = "upstream failed".getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(503, body.length); + try (exchange) { + exchange.getResponseBody().write(body); + } + }); + server.createContext("/large", exchange -> { + byte[] body = new byte[HttpDataSourceTransport.MAX_BYTES + 1]; + exchange.sendResponseHeaders(200, body.length); + try (exchange) { + exchange.getResponseBody().write(body); + } + }); + server.createContext("/slow", exchange -> { + exchange.sendResponseHeaders(200, 0); + try (exchange) { + exchange.getResponseBody().write('a'); + exchange.getResponseBody().flush(); + try { + slowResponseReleased.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }); + server.start(); + // Only this transport fixture pins a synthetic public hostname to the test listener. + DnsResolver resolver = publicResolver(); + transport = new HttpDataSourceTransport(HttpDataSourceTransport.client(resolver)); + } + + private static DnsResolver publicResolver() throws UnknownHostException { + DnsResolver resolver = mock(DnsResolver.class, CALLS_REAL_METHODS); + when(resolver.resolve("public.example")).thenReturn(new InetAddress[]{InetAddress.getLoopbackAddress()}); + when(resolver.resolveCanonicalHostname("public.example")).thenReturn("public.example"); + return resolver; + } + + @AfterEach + void stopServer() { + slowResponseReleased.countDown(); + if (transport != null) { + transport.close(); + } + if (server != null) { + server.stop(0); + } + } + + @Test + void sendsResolverRequestAndReturnsHttpEnvelope() throws Exception { + Map result = transport.send(request("/echo", "POST", Map.of( + "headers", Map.of("Authorization", "Bearer external-only", "Content-Type", "text/plain"), + "query", Map.of("q", "a+b &"), "body", "hello ü"))); + + assertEquals(200, result.get("statusCode")); + assertTrue(((Map) result.get("headers")).keySet().stream() + .anyMatch(key -> key.toString().equalsIgnoreCase("X-Result"))); + JsonNode body = mapper.readTree((String) result.get("body")); + assertEquals("POST", body.path("method").asText()); + assertEquals("/echo?q=a%2Bb%20%26", body.path("uri").asText()); + assertEquals("hello ü", body.path("body").asText()); + assertEquals("Bearer external-only", body.path("authorization").asText()); + } + + @Test + void returnsRedirectWithoutFollowingIt() { + assertEquals(302, transport.send(request("/redirect", "GET", Map.of())).get("statusCode")); + assertEquals(0, calls.get()); + } + + @Test + void returnsNonSuccessStatusToResolverWithoutRetry() { + Map response = transport.send(request("/error", "GET", Map.of())); + assertEquals(503, response.get("statusCode")); + assertEquals("upstream failed", response.get("body")); + } + + @ParameterizedTest + @ValueSource(strings = {"", "text/plain; charset=does-not-exist", "text/plain; charset=bad@@@charset", "not a content type"}) + void malformedResponseContentTypeDoesNotDiscardStatusOrBody(String contentType) { + server.createContext("/charset", exchange -> { + byte[] body = "response retained".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", contentType); + exchange.sendResponseHeaders(503, body.length); + try (exchange) { + exchange.getResponseBody().write(body); + } + }); + Map response = transport.send(request("/charset", "GET", Map.of())); + assertEquals(503, response.get("statusCode")); + assertEquals("response retained", response.get("body")); + } + + @Test + void aSupportedResponseCharsetIsStillRespected() { + server.createContext("/latin", exchange -> { + byte[] body = "caf\u00e9".getBytes(StandardCharsets.ISO_8859_1); + exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=ISO-8859-1"); + exchange.sendResponseHeaders(200, body.length); + try (exchange) { + exchange.getResponseBody().write(body); + } + }); + assertEquals("caf\u00e9", transport.send(request("/latin", "GET", Map.of())).get("body")); + } + + @Test + void doesNotKeepCookiesAcrossResolverCalls() throws Exception { + transport.send(request("/one", "GET", Map.of())); + Map next = transport.send(request("/two", "GET", Map.of())); + assertEquals("null", mapper.readTree((String) next.get("body")).path("cookie").asText()); + } + + @Test + void refusesOversizedRequestBeforeSending() { + HttpDataSourceRequest request = new HttpDataSourceRequest( + URI.create(endpoint() + "/"), "POST", Map.of(), new byte[HttpDataSourceTransport.MAX_BYTES + 1]); + assertThrows(AwsException.class, () -> transport.send(request)); + assertEquals(0, calls.get()); + } + + @Test + void refusesOversizedResponse() { + assertThrows(AwsException.class, () -> transport.send(request("/large", "GET", Map.of()))); + } + + @Test + void totalDeadlineCancelsResponseBodyRead() throws Exception { + DnsResolver resolver = publicResolver(); + try (HttpDataSourceTransport shortDeadline = new HttpDataSourceTransport( + HttpDataSourceTransport.client(resolver), Duration.ofMillis(200))) { + long started = System.nanoTime(); + assertThrows(AwsException.class, () -> shortDeadline.send(request("/slow", "GET", Map.of()))); + assertTrue(Duration.ofNanos(System.nanoTime() - started).compareTo(Duration.ofSeconds(3)) < 0); + } + } + + @Test + void totalDeadlineAlsoBoundsDnsLookup() throws Exception { + CountDownLatch releaseDns = new CountDownLatch(1); + DnsResolver resolver = mock(DnsResolver.class, CALLS_REAL_METHODS); + when(resolver.resolve("public.example")).thenAnswer(call -> { + releaseDns.await(5, TimeUnit.SECONDS); + return new InetAddress[]{InetAddress.getLoopbackAddress()}; + }); + try (HttpDataSourceTransport shortDeadline = new HttpDataSourceTransport( + HttpDataSourceTransport.client(resolver), Duration.ofMillis(200))) { + long started = System.nanoTime(); + assertThrows(AwsException.class, () -> shortDeadline.send(request("/", "GET", Map.of()))); + assertTrue(Duration.ofNanos(System.nanoTime() - started).compareTo(Duration.ofSeconds(3)) < 0); + } finally { + releaseDns.countDown(); + } + } + + @Test + void defaultTransportCanReachALocalMock() { + try (HttpDataSourceTransport production = new HttpDataSourceTransport()) { + HttpDataSourceRequest request = new HttpDataSourceRequest( + URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/"), "GET", Map.of(), new byte[0]); + assertEquals(200, production.send(request).get("statusCode")); + assertEquals(1, calls.get()); + } + } + + @Test + void dnsValidationAllowsPrivateContainerAddresses() throws Exception { + DnsResolver delegate = mock(DnsResolver.class); + InetAddress[] addresses = {InetAddress.getByName("10.0.0.25"), InetAddress.getByName("172.18.0.2"), + InetAddress.getByName("192.168.1.2"), InetAddress.getByName("fd00::1"), + InetAddress.getByName("127.0.0.1"), InetAddress.getByName("::1")}; + when(delegate.resolve("compose-service")).thenReturn(addresses); + assertEquals(List.of(addresses), List.of(HttpDataSourceTransport.checkedResolver(delegate).resolve("compose-service"))); + } + + @ParameterizedTest + @ValueSource(strings = {"169.254.169.254", "169.254.0.1", "fe80::1", "fd00:ec2::254", "::ffff:169.254.169.254"}) + void dnsValidationRejectsMixedLocalAndMetadataAnswers(String address) throws Exception { + DnsResolver delegate = mock(DnsResolver.class); + when(delegate.resolve("mixed.example")).thenReturn(new InetAddress[]{InetAddress.getLoopbackAddress(), + InetAddress.getByName(address)}); + assertThrows(UnknownHostException.class, + () -> HttpDataSourceTransport.checkedResolver(delegate).resolve("mixed.example")); + } + + @Test + void httpsPreservesCertificateAndHostnameVerification(@TempDir Path tlsDirectory) throws Exception { + FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDirectory); + CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate( + "public.example", List.of("public.example"), KeyAlgorithm.RSA_2048, null); + SSLContext serverContext = ca.serverSslContext(Pem.parseCertificate(leaf.certificatePem()), + Pem.parsePrivateKey(leaf.privateKeyPem())); + HttpsServer https = HttpsServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + https.setHttpsConfigurator(new HttpsConfigurator(serverContext)); + AtomicInteger accepted = new AtomicInteger(); + https.createContext("/", exchange -> { + accepted.incrementAndGet(); + exchange.sendResponseHeaders(200, -1); + exchange.close(); + }); + https.start(); + DnsResolver resolver = mock(DnsResolver.class, CALLS_REAL_METHODS); + for (String host : List.of("public.example", "wrong.example")) { + when(resolver.resolve(host)).thenReturn(new InetAddress[]{InetAddress.getLoopbackAddress()}); + when(resolver.resolveCanonicalHostname(host)).thenReturn(host); + } + URI target = URI.create("https://public.example:" + https.getAddress().getPort() + "/"); + try (HttpDataSourceTransport ordinary = new HttpDataSourceTransport(HttpDataSourceTransport.client(resolver)); + HttpDataSourceTransport trusted = new HttpDataSourceTransport( + HttpDataSourceTransport.client(resolver, TlsTrust.trusting(ca.certificate())))) { + assertThrows(AwsException.class, () -> ordinary.send( + new HttpDataSourceRequest(target, "GET", Map.of(), new byte[0]))); + assertEquals(0, accepted.get()); + assertEquals(200, trusted.send(new HttpDataSourceRequest(target, "GET", Map.of(), new byte[0])).get("statusCode")); + URI wrong = URI.create("https://wrong.example:" + https.getAddress().getPort() + "/"); + assertThrows(AwsException.class, () -> trusted.send( + new HttpDataSourceRequest(wrong, "GET", Map.of(), new byte[0]))); + assertEquals(1, accepted.get()); + } finally { + https.stop(0); + } + } + + private HttpDataSourceRequest request(String path, String method, Map params) { + DataSource source = new DataSource(); + source.setHttpConfig(Map.of("endpoint", endpoint())); + return HttpDataSourceRequest.parse(source, Map.of("method", method, "resourcePath", path, "params", params), mapper); + } + + private String endpoint() { + return "http://public.example:" + server.getAddress().getPort(); + } +} diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java index 5ad971c96b..4aa0a43513 100644 --- a/src/test/java/io/floci/aws/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java +++ b/src/test/java/io/floci/aws/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java @@ -21,6 +21,8 @@ import io.floci.aws.services.lambda.LambdaService; import io.floci.aws.services.lambda.model.InvocationType; import io.floci.aws.services.lambda.model.InvokeResult; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import java.nio.charset.StandardCharsets; @@ -59,9 +61,10 @@ class AppSyncResolverExecutorTest { private final RecordingInvoker dynamoDbInvoker = new RecordingInvoker(DataSourceType.AMAZON_DYNAMODB); private final RecordingInvoker lambdaInvoker = new RecordingInvoker(DataSourceType.AWS_LAMBDA); + private final RecordingInvoker httpInvoker = new RecordingInvoker(DataSourceType.HTTP); private final ObjectMapper objectMapper = new ObjectMapper(); private final AppSyncResolverExecutor executor = new AppSyncResolverExecutor(appSync, jsRuntime, - new AppSyncDataSourceInvokers(List.of(invoker, noneInvoker, dynamoDbInvoker, lambdaInvoker), + new AppSyncDataSourceInvokers(List.of(invoker, noneInvoker, dynamoDbInvoker, lambdaInvoker, httpInvoker), mock(AppSyncDataSourceAuthorizer.class)), vtlEngine(), objectMapper); private static AppSyncVtlEngine vtlEngine() { @@ -807,6 +810,35 @@ class AppSyncResolverExecutorTest { assertEquals(Map.of(":active", true, ":id", "42"), request.get("variableMap")); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void vtlUnitAndPipelineFunctionsDispatchHttpRequestsAndPreserveErrorResponses(boolean pipeline) { + when(appSync.getDataSource(API_ID, "accountHttp")) + .thenReturn(dataSource("accountHttp", DataSourceType.HTTP)); + httpInvoker.answer = Map.of("statusCode", 404, "headers", Map.of(), "body", "missing"); + String requestTemplate = """ + {"version":"2018-05-29","method":"GET","resourcePath":"/schedules/$ctx.args.name"} + """; + Resolver resolver = resolver(pipeline ? ResolverKind.PIPELINE : ResolverKind.UNIT, + pipeline ? "pipeline-code" : null); + if (pipeline) { + when(appSync.getFunction(API_ID, "httpFn")).thenReturn(vtlFunction("httpFn", "accountHttp", + requestTemplate, "$util.toJson($ctx.result)")); + resolver.setPipelineConfig(Map.of("functions", List.of("httpFn"))); + jsRuntime.script("pipeline-code", "request", (h, ctx) -> ok(Map.of())); + jsRuntime.script("pipeline-code", "response", (h, ctx) -> ok(ctx.get("result"))); + } else { + resolver.setDataSourceName("accountHttp"); + resolver.setRequestMappingTemplate(requestTemplate); + resolver.setResponseMappingTemplate("$util.toJson($ctx.result)"); + } + ResolverOutcome result = executor.execute(resolver, invocation(Map.of("name", "example"))); + assertTrue(result.errors().isEmpty()); + assertEquals(httpInvoker.answer, result.data()); + assertEquals(List.of(Map.of("version", "2018-05-29", "method", "GET", "resourcePath", "/schedules/example")), + httpInvoker.requests); + } + @Test void vtlDataSourceErrorIsAvailableToTheResponseTemplate() { when(appSync.getDataSource(API_ID, "accountFunction")) @@ -958,10 +990,10 @@ class AppSyncResolverExecutorTest { @Test void vtlRequestReturnCannotBypassUnsupportedDataSourceValidation() { - when(appSync.getDataSource(API_ID, "accountHttp")) - .thenReturn(dataSource("accountHttp", DataSourceType.HTTP)); + when(appSync.getDataSource(API_ID, "accountEvents")) + .thenReturn(dataSource("accountEvents", DataSourceType.AMAZON_EVENTBRIDGE)); Resolver resolver = resolver(ResolverKind.UNIT, null); - resolver.setDataSourceName("accountHttp"); + resolver.setDataSourceName("accountEvents"); resolver.setRequestMappingTemplate("#return({\"short\":\"circuit\"})"); resolver.setResponseMappingTemplate("$util.toJson($ctx.result)"); diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java index 096cb1c278..0fd37181fc 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java @@ -1161,6 +1161,22 @@ class ElbV2ServiceTest { assertEquals(4, service.describeTargetGroups(REGION, null, List.of(tgArn), null).getFirst().getTargets().size()); } + @ParameterizedTest + @ValueSource(strings = {"100.64.0.1", "100.100.100.200", "100.127.255.254"}) + void registerTargetsAcceptsCarrierGradeIpAddresses(String address) { + TargetGroup group = service.createTargetGroup( + REGION, "carrier-grade-tg", "HTTP", "HTTP1", 9999, "vpc-a", "ip", + "HTTP", "traffic-port", true, "/v1/ready", 30, 5, 5, 2, "200", "ipv4", Map.of()); + TargetDescription target = new TargetDescription(); + target.setId(address); + + service.registerTargets(REGION, group.getTargetGroupArn(), List.of(target)); + + assertEquals(List.of(address), service.describeTargetGroups(REGION, null, + List.of(group.getTargetGroupArn()), null).getFirst().getTargets().stream() + .map(TargetDescription::getId).toList()); + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void registerTargetsUsesEffectivePortForIdentity(boolean initiallyExplicit) { diff --git a/src/test/java/io/floci/aws/testing/AppSyncHttpTestPolicies.java b/src/test/java/io/floci/aws/testing/AppSyncHttpTestPolicies.java new file mode 100644 index 0000000000..73e84cd634 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/AppSyncHttpTestPolicies.java @@ -0,0 +1,22 @@ +package io.floci.aws.testing; + +/** Policies shared by native and real-sidecar HTTP data-source tests. */ +public final class AppSyncHttpTestPolicies { + + private AppSyncHttpTestPolicies() { } + + public static String trust(String apiArn, String account) { + return """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", + "Principal":{"Service":"appsync.amazonaws.com"}, + "Condition":{"ArnEquals":{"aws:SourceArn":"%s"},"StringEquals":{"aws:SourceAccount":"%s"}}}]} + """.formatted(apiArn, account); + } + + public static String getSchedule(String effect, String region, String account) { + return """ + {"Version":"2012-10-17","Statement":[{"Effect":"%s","Action":"scheduler:GetSchedule", + "Resource":"arn:aws:scheduler:%s:%s:schedule/default/missing"}]} + """.formatted(effect, region, account); + } +}