mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(appsync): execute HTTP data sources and signed local AWS requests (#7609)
This commit is contained in:
1 parent
c97f913f5e
commit
d5b7a11f89
29 files changed
+2531
-102
No files matched your search
@@ -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<String> canonicalHost;
|
||||
|
||||
public ValidatingDnsResolver(DnsResolver delegate, AddressCheck check) {
|
||||
this(delegate, check, UnaryOperator.identity());
|
||||
}
|
||||
|
||||
public ValidatingDnsResolver(DnsResolver delegate, AddressCheck check, UnaryOperator<String> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<LocalAwsSigningSession> 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<String, List<String>> sign(String method, URI uri, byte[] payload, String region, String service,
|
||||
Map<String, List<String>> inputHeaders) throws Exception {
|
||||
TreeMap<String, List<String>> 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);
|
||||
}
|
||||
}
|
||||
+43
-16
@@ -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<String, Object> executeQuery(String apiId, String preparedSdl, Map<String, String> scalars,
|
||||
ParsedRequest parsed, List<DenyField> denyFields,
|
||||
PlanResult plan, AppSyncAuthContext authContext) {
|
||||
List<ResolveField> 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<String, Object> 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<ResolveField> resolverBackedFields(String apiId, PlanResult plan, List<DenyField> denyFields) {
|
||||
private CallbackPlan resolverBackedFields(String apiId, PlanResult plan, List<DenyField> denyFields) {
|
||||
Set<String> denied = new HashSet<>();
|
||||
for (DenyField deny : denyFields) {
|
||||
denied.add(deny.typeName() + "." + deny.fieldName());
|
||||
}
|
||||
Map<String, ResolveField> 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<ResolveField> fields, int maxBatch) { }
|
||||
|
||||
/**
|
||||
* {@code util.appendError} reports errors <em>and</em> keeps the data, which the sidecar's
|
||||
* per-field callback response cannot say (it carries a value or an error, never both). They
|
||||
|
||||
+2
-1
@@ -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;
|
||||
}
|
||||
|
||||
+94
@@ -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<String, Object> 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<String, List<String>> 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<String, String> 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();
|
||||
}
|
||||
}
|
||||
+122
@@ -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<String, Object> 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<String> 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<String> 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);
|
||||
}
|
||||
}
|
||||
+37
@@ -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);
|
||||
}
|
||||
}
|
||||
+138
@@ -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<String, String> headers, byte[] body) {
|
||||
|
||||
private static final Set<String> METHODS = Set.of("GET", "POST", "PUT", "PATCH", "DELETE");
|
||||
private static final Set<String> 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<String, String> headers = stringMap(params.get("headers"), "headers");
|
||||
Map<String, String> normalized = new TreeMap<>();
|
||||
for (Map.Entry<String, String> 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<String, String> 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<String, String> 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<String, String> stringMap(Object value, String name) {
|
||||
Map<String, String> 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);
|
||||
}
|
||||
}
|
||||
+180
@@ -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<String, Object> 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<Map<String, Object>> 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<String, Object> 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<String, Object> execute(HttpUriRequestBase outgoing) throws IOException {
|
||||
return client.execute(outgoing, response -> {
|
||||
Map<String, String> 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);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -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");
|
||||
};
|
||||
|
||||
@@ -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<String> 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<String> allowedHosts)
|
||||
implements DnsResolver {
|
||||
|
||||
@Override
|
||||
public InetAddress[] resolve(String host) throws UnknownHostException {
|
||||
InetAddress[] addresses = delegate.resolve(host);
|
||||
private static DnsResolver validatingResolver(DnsResolver delegate, Collection<String> allowedPrivateOriginHosts) {
|
||||
Set<String> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String, List<String>> headers = requestHeaders(input.path("Headers"));
|
||||
Map<String, List<String>> 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<String, List<String>> 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<String, List<String>> 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);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user