feat(appsync): execute HTTP data sources and signed local AWS requests (#7609)

This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-11-14 12:07:22 -04:00
1 parent c97f913f5e
commit d5b7a11f89
29 files changed
+2531 -102

No files matched your search

@@ -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<InetAddress[]> 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")));
}
}
@@ -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<String> key = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> secret = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> 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<String, List<String>> 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<String> key = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Instant> 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<String> key = ArgumentCaptor.forClass(String.class);
verify(iam).registerSessionForAccount(eq(ACCOUNT), key.capture(), anyString(), anyString(), eq(ROLE), any(), isNull());
verify(iam).unregisterSession(ACCOUNT, key.getValue());
}
}
@@ -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<String, String> getConfigOverrides() {
Map<String, String> 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)));
}
}
@@ -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<GraphqlSidecarClient.ResolveSpec> 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
@@ -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<String, String> 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<String> key = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> secret = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> 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<String, String> 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<String, Object> 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<JsonNode> 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<JsonNode> 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<String, Object> 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<String> 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);
}
}
@@ -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<String> 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<String> 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<HttpDataSourceRequest> 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);
}
}
@@ -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<String, Object> 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<String> 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()));
}
}
@@ -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<String, Object> 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<String, Object> 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";
}
}
@@ -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<String> 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"));
}
}
@@ -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<String, String> 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<String, Object> response = Map.of("statusCode", 409, "headers", Map.of("content-type", "text/plain"),
"body", "conflict");
when(transport.send(any())).thenReturn(response);
Map<String, Object> 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<HttpDataSourceRequest> 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);
}
}
@@ -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<String, Object> request : List.<Map<String, Object>>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<String, Object> 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<String, Object> request) {
AwsException error = assertThrows(AwsException.class, () -> parse(endpoint, request));
assertEquals("MappingTemplate", error.getErrorCode());
}
}
@@ -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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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();
}
}
@@ -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)");
@@ -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) {
@@ -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);
}
}