Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(appsync): authorize data source service roles (#4555)

XuJian89344b76dcc9
diff --git a/docs/services/appsync.md b/docs/services/appsync.md
index 2a63be1bd8..71c79732e2 100644
--- a/docs/services/appsync.md
+++ b/docs/services/appsync.md
@@ -280,6 +280,23 @@ explicit unsupported operations rather than silently resolving to `null`.
### How a resolver gets called
+For a `NONE` data source, no IAM service role is needed. When
+`floci.services.iam.enforcement-enabled` is off (the default), existing DynamoDB, Lambda,
+and RDS resolvers are not blocked by local IAM role checks. When it is on, Floci checks the
+configured `serviceRoleArn` before invoking a backing resource. A valid same-account role ARN
+not present in Floci's IAM store remains permissive, as with STS AssumeRole. A known role must
+belong to the data source's account and partition, trust
+the partition's AppSync service principal (for example, `appsync.amazonaws.com` in commercial
+Regions), and have identity-policy permission for the requested operation and
+resource. An indexed DynamoDB Query or Scan checks the index ARN. RDS execution checks both
+`rds-data:ExecuteStatement` on the cluster and `secretsmanager:GetSecretValue` on the secret.
+Missing roles, missing trust, and insufficient permissions fail the field instead of calling
+the underlying service. IAM condition support here is limited to what Floci's trust and policy
+evaluators implement. `aws:SourceArn` and `aws:SourceAccount` trust conditions are checked for
+the calling API; identity-policy checks include `aws:RequestedRegion` for the resolver invocation.
+Unsupported trust conditions and unmapped DynamoDB operations fail closed. This is not a complete
+emulation of AWS STS AssumeRole credentials.
+
The GraphQL engine runs in the `floci-sidecar-graphql` container, so the sidecar walks the query and
Floci owns the resolvers. `POST /v1/execute` carries a `resolve` block naming every coordinate the
query touches that has a resolver, plus a callback URL and a token minted for that one operation.
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizer.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizer.java
new file mode 100644
index 0000000000..fde7264e55
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizer.java
@@ -0,0 +1,189 @@
+package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.model.CallerContext;
+import io.github.hectorvent.floci.services.iam.model.IamRole;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/** Checks the data source role before a resolver accesses a backing AWS resource. */
+@ApplicationScoped
+public class AppSyncDataSourceAuthorizer {
+
+ private final IamService iamService;
+ private final AssumeRolePolicyEvaluator trustEvaluator;
+ private final IamPolicyEvaluator policyEvaluator;
+ private final RegionResolver regionResolver;
+ private final ObjectMapper objectMapper;
+ private final EmulatorConfig config;
+
+ @Inject
+ public AppSyncDataSourceAuthorizer(IamService iamService,
+ AssumeRolePolicyEvaluator trustEvaluator,
+ IamPolicyEvaluator policyEvaluator,
+ RegionResolver regionResolver,
+ ObjectMapper objectMapper,
+ EmulatorConfig config) {
+ this.iamService = iamService;
+ this.trustEvaluator = trustEvaluator;
+ this.policyEvaluator = policyEvaluator;
+ this.regionResolver = regionResolver;
+ this.objectMapper = objectMapper;
+ this.config = config;
+ }
+
+ public void authorize(DataSource dataSource, Object request, String region) {
+ if (dataSource.getType() == DataSourceType.NONE
+ || !config.services().iam().enforcementEnabled()) {
+ return;
+ }
+ String roleArn = dataSource.getServiceRoleArn();
+ if (roleArn == null || roleArn.isBlank()) {
+ throw denied(dataSource, "no serviceRoleArn is configured");
+ }
+ AwsArnUtils.Arn roleId;
+ try {
+ roleId = AwsArnUtils.parse(roleArn);
+ } catch (IllegalArgumentException e) {
+ throw denied(dataSource, "serviceRoleArn is not an IAM role ARN");
+ }
+ if (!"iam".equals(roleId.service()) || !roleId.region().isEmpty()
+ || roleId.accountId().isBlank() || !roleId.resource().startsWith("role/")
+ || roleId.resource().endsWith("/")) {
+ throw denied(dataSource, "serviceRoleArn is not an IAM role ARN");
+ }
+ AwsArnUtils.Arn sourceId;
+ try {
+ sourceId = AwsArnUtils.parse(dataSource.getDataSourceArn());
+ } catch (IllegalArgumentException e) {
+ throw denied(dataSource, "data source ARN is invalid");
+ }
+ if (!"appsync".equals(sourceId.service()) || !sourceId.partition().equals(roleId.partition())
+ || !sourceId.accountId().equals(roleId.accountId())) {
+ throw denied(dataSource, "service role belongs to a different account or partition");
+ }
+ int suffix = sourceId.resource().indexOf("/datasources/");
+ if (!sourceId.resource().startsWith("apis/") || suffix < 0) {
+ throw denied(dataSource, "data source ARN is invalid");
+ }
+ String sourceArn = dataSource.getDataSourceArn().substring(0,
+ dataSource.getDataSourceArn().indexOf("/datasources/"));
+ String sourceAccount = sourceId.accountId();
+ String roleName = roleId.resource().substring(roleId.resource().lastIndexOf('/') + 1);
+ Optional<IamRole> role = iamService.findRole(roleId.accountId(), roleName);
+ if (role.isEmpty()) {
+ return;
+ }
+ if (!roleArn.equals(role.get().getArn())) {
+ throw denied(dataSource, "service role does not exist");
+ }
+ String servicePrincipal = "appsync." + AwsRegions.dnsSuffixFor(region);
+ if (!trustEvaluator.allowsService(role.get().getAssumeRolePolicyDocument(),
+ servicePrincipal, sourceArn, sourceAccount)) {
+ throw denied(dataSource, "service role does not trust " + servicePrincipal);
+ }
+
+ List<Permission> permissions = permissions(dataSource, request, region, roleId);
+ if (permissions.isEmpty()) {
+ // Let the invoker report a malformed/unsupported operation or missing configuration.
+ return;
+ }
+ CallerContext caller = iamService.resolvePrincipalContext(roleArn);
+ Map<String, List<String>> conditionContext = region == null
+ ? Map.of() : Map.of("aws:RequestedRegion", List.of(region));
+ for (Permission permission : permissions) {
+ if (policyEvaluator.simulatePrincipalPolicy(caller, permission.action(),
+ permission.resource(), conditionContext) != IamPolicyEvaluator.SimulationDecision.ALLOWED) {
+ throw denied(dataSource, "service role cannot perform " + permission.action()
+ + " on " + permission.resource());
+ }
+ }
+ }
+
+ private List<Permission> permissions(DataSource dataSource, Object request, String region,
+ AwsArnUtils.Arn roleId) {
+ return switch (dataSource.getType()) {
+ case AMAZON_DYNAMODB -> dynamoDbPermissions(dataSource, request, region, roleId);
+ case AWS_LAMBDA -> lambdaPermissions(dataSource);
+ case RELATIONAL_DATABASE -> relationalPermissions(dataSource, region);
+ default -> throw denied(dataSource, "data source type is not supported for role authorization");
+ };
+ }
+
+ private List<Permission> dynamoDbPermissions(DataSource dataSource, Object request, String region,
+ AwsArnUtils.Arn roleId) {
+ String table = text(dataSource.getDynamodbConfig(), "tableName");
+ JsonNode normalized = objectMapper.valueToTree(request == null ? Map.of() : request);
+ String operation = normalized.path("operation").asText(null);
+ if (table == null || operation == null) {
+ return List.of();
+ }
+ String action = switch (operation) {
+ case "GetItem", "PutItem", "UpdateItem", "DeleteItem", "Query", "Scan" ->
+ "dynamodb:" + operation;
+ default -> throw denied(dataSource, "DynamoDB operation is not supported for role authorization");
+ };
+ String resource = new AwsArnUtils.Arn(roleId.partition(), "dynamodb", region,
+ roleId.accountId(), "table/" + table).toString();
+ String index = normalized.path("index").asText(null);
+ if (index != null && !index.isBlank()
+ && ("dynamodb:Query".equals(action) || "dynamodb:Scan".equals(action))) {
+ resource += "/index/" + index;
+ }
+ return List.of(new Permission(action, resource));
+ }
+
+ private List<Permission> lambdaPermissions(DataSource dataSource) {
+ String functionArn = text(dataSource.getLambdaConfig(), "lambdaFunctionArn");
+ return functionArn == null ? List.of() : List.of(new Permission("lambda:InvokeFunction", functionArn));
+ }
+
+ private List<Permission> relationalPermissions(DataSource dataSource, String region) {
+ Map<String, Object> config = dataSource.getRelationalDatabaseConfig();
+ Object rawEndpoint = config == null ? null : config.get("rdsHttpEndpointConfig");
+ if (!(rawEndpoint instanceof Map<?, ?> endpoint)) {
+ return List.of();
+ }
+ String cluster = text(endpoint, "dbClusterIdentifier");
+ String secret = text(endpoint, "awsSecretStoreArn");
+ if (cluster == null || secret == null) {
+ return List.of();
+ }
+ String endpointRegion = text(endpoint, "awsRegion");
+ String clusterArn = cluster.startsWith("arn:") ? cluster
+ : AwsArnUtils.Arn.of("rds", endpointRegion == null ? region : endpointRegion,
+ regionResolver.getAccountId(), "cluster:" + cluster).toString();
+ List<Permission> permissions = new ArrayList<>();
+ permissions.add(new Permission("rds-data:ExecuteStatement", clusterArn));
+ permissions.add(new Permission("secretsmanager:GetSecretValue", secret));
+ return permissions;
+ }
+
+ private static String text(Map<?, ?> values, String key) {
+ Object value = values == null ? null : values.get(key);
+ return value == null || String.valueOf(value).isBlank() ? null : String.valueOf(value);
+ }
+
+ private static AwsException denied(DataSource dataSource, String reason) {
+ return new AwsException("AccessDeniedException",
+ "AppSync data source " + dataSource.getName() + ": " + reason, 403);
+ }
+
+ private record Permission(String action, String resource) {}
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokers.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokers.java
index e4c504a225..3fb0654f7e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokers.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokers.java
@@ -15,9 +15,18 @@ import java.util.Map;
public class AppSyncDataSourceInvokers {
private final Map<DataSourceType, AppSyncDataSourceInvoker> byType = new EnumMap<>(DataSourceType.class);
+ private final AppSyncDataSourceAuthorizer authorizer;
@Inject
- public AppSyncDataSourceInvokers(Instance<AppSyncDataSourceInvoker> invokers) {
+ public AppSyncDataSourceInvokers(Instance<AppSyncDataSourceInvoker> invokers,
+ AppSyncDataSourceAuthorizer authorizer) {
+ this((Iterable<AppSyncDataSourceInvoker>) invokers, authorizer);
+ }
+
+ /** Test constructor: an explicit set, bypassing CDI. */
+ public AppSyncDataSourceInvokers(Iterable<AppSyncDataSourceInvoker> invokers,
+ AppSyncDataSourceAuthorizer authorizer) {
+ this.authorizer = authorizer;
invokers.forEach(invoker -> {
AppSyncDataSourceInvoker existing = byType.put(invoker.type(), invoker);
if (existing != null) {
@@ -28,11 +37,6 @@ public class AppSyncDataSourceInvokers {
});
}
- /** Test constructor: an explicit set, bypassing CDI. */
- public AppSyncDataSourceInvokers(Iterable<AppSyncDataSourceInvoker> invokers) {
- invokers.forEach(invoker -> byType.put(invoker.type(), invoker));
- }
-
/**
* Runs the request against its data source.
*
@@ -41,11 +45,15 @@ public class AppSyncDataSourceInvokers {
* mode this whole layer exists to remove.
*/
public Object invoke(DataSource dataSource, Object request, String region) {
- return invokerFor(dataSource).invoke(dataSource, request, region);
+ AppSyncDataSourceInvoker invoker = invokerFor(dataSource);
+ authorizer.authorize(dataSource, request, region);
+ return invoker.invoke(dataSource, request, region);
}
public Object invokeVtl(DataSource dataSource, Object request, String region) {
- return invokerFor(dataSource).invokeVtl(dataSource, request, region);
+ AppSyncDataSourceInvoker invoker = invokerFor(dataSource);
+ authorizer.authorize(dataSource, request, region);
+ return invoker.invokeVtl(dataSource, request, region);
}
private AppSyncDataSourceInvoker invokerFor(DataSource dataSource) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java
index f59e522ee4..28a8e34a68 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java
@@ -7,6 +7,9 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -59,6 +62,9 @@ public class AssumeRolePolicyEvaluator {
LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
return false;
}
+ if (!hasValidEffects(statements)) {
+ return false;
+ }
boolean allow = false;
if (statements.isArray()) {
@@ -89,6 +95,9 @@ public class AssumeRolePolicyEvaluator {
LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
return false;
}
+ if (!hasValidEffects(statements)) {
+ return false;
+ }
boolean allow = false;
if (statements.isArray()) {
for (JsonNode statement : statements) {
@@ -104,8 +113,67 @@ public class AssumeRolePolicyEvaluator {
return allow;
}
+ /**
+ * Checks a service trust policy in the context of an AppSync API. AWS supports narrowing
+ * service trust with aws:SourceAccount and aws:SourceArn. Unknown condition keys or operators
+ * are rejected rather than silently turning a conditional Allow into an unconditional one.
+ */
+ public boolean allowsService(String trustPolicyDocument, String servicePrincipal,
+ String sourceArn, String sourceAccount) {
+ if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
+ return false;
+ }
+ JsonNode statements;
+ try {
+ statements = objectMapper.readTree(trustPolicyDocument).path("Statement");
+ } catch (Exception e) {
+ LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
+ return false;
+ }
+ if (!hasValidEffects(statements)) {
+ return false;
+ }
+ boolean allow = false;
+ if (statements.isArray()) {
+ for (JsonNode statement : statements) {
+ switch (evaluateServiceStatement(statement, servicePrincipal, sourceArn, sourceAccount)) {
+ case DENY -> { return false; }
+ case ALLOW -> allow = true;
+ case NO_MATCH -> { }
+ }
+ }
+ } else if (statements.isObject()) {
+ return evaluateServiceStatement(statements, servicePrincipal,
+ sourceArn, sourceAccount) == Match.ALLOW;
+ }
+ return allow;
+ }
+
private enum Match { ALLOW, DENY, NO_MATCH }
+ private boolean hasValidEffects(JsonNode statements) {
+ if (statements.isArray()) {
+ if (statements.isEmpty()) {
+ return false;
+ }
+ for (JsonNode statement : statements) {
+ if (!validEffect(statement)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ return validEffect(statements);
+ }
+
+ private boolean validEffect(JsonNode statement) {
+ if (!statement.isObject()) {
+ return false;
+ }
+ String effect = statement.path("Effect").asText("");
+ return "Allow".equals(effect) || "Deny".equals(effect);
+ }
+
private Match evaluateStatement(JsonNode stmt, String callerArn, String callerAccount) {
if (!actionApplies(stmt)) {
return Match.NO_MATCH;
@@ -113,14 +181,116 @@ public class AssumeRolePolicyEvaluator {
if (!matchesPrincipal(stmt.get("Principal"), callerArn, callerAccount)) {
return Match.NO_MATCH;
}
- return "Deny".equalsIgnoreCase(stmt.path("Effect").asText("Allow")) ? Match.DENY : Match.ALLOW;
+ return effectOf(stmt);
}
private Match evaluateServiceStatement(JsonNode stmt, String servicePrincipal) {
if (!actionApplies(stmt) || !matchesServicePrincipal(stmt.get("Principal"), servicePrincipal)) {
return Match.NO_MATCH;
}
- return "Deny".equalsIgnoreCase(stmt.path("Effect").asText("Allow")) ? Match.DENY : Match.ALLOW;
+ return effectOf(stmt);
+ }
+
+ private Match evaluateServiceStatement(JsonNode stmt, String servicePrincipal,
+ String sourceArn, String sourceAccount) {
+ if (!actionApplies(stmt) || !matchesServicePrincipal(stmt.get("Principal"), servicePrincipal)) {
+ return Match.NO_MATCH;
+ }
+ Match condition = serviceCondition(stmt.get("Condition"), sourceArn, sourceAccount);
+ if (condition != Match.ALLOW) {
+ return condition;
+ }
+ return effectOf(stmt);
+ }
+
+ private Match effectOf(JsonNode stmt) {
+ return switch (stmt.path("Effect").asText("")) {
+ case "Allow" -> Match.ALLOW;
+ case "Deny" -> Match.DENY;
+ default -> Match.NO_MATCH;
+ };
+ }
+
+ /** ALLOW means the condition matches, NO_MATCH means it does not, DENY means unsupported. */
+ private Match serviceCondition(JsonNode condition, String sourceArn, String sourceAccount) {
+ if (condition == null) {
+ return Match.ALLOW;
+ }
+ if (!condition.isObject() || condition.isEmpty()) {
+ return Match.DENY;
+ }
+ for (Iterator<Map.Entry<String, JsonNode>> operators = condition.fields();
+ operators.hasNext();) {
+ Map.Entry<String, JsonNode> operator = operators.next();
+ if (!"StringEquals".equals(operator.getKey()) && !"StringLike".equals(operator.getKey())
+ && !"ArnEquals".equals(operator.getKey()) && !"ArnLike".equals(operator.getKey())) {
+ return Match.DENY;
+ }
+ if (!operator.getValue().isObject() || operator.getValue().isEmpty()) {
+ return Match.DENY;
+ }
+ for (Iterator<Map.Entry<String, JsonNode>> keys = operator.getValue().fields();
+ keys.hasNext();) {
+ Map.Entry<String, JsonNode> key = keys.next();
+ String actual = switch (key.getKey().toLowerCase(Locale.ROOT)) {
+ case "aws:sourcearn" -> sourceArn;
+ case "aws:sourceaccount" -> sourceAccount;
+ default -> null;
+ };
+ if (!"aws:sourcearn".equalsIgnoreCase(key.getKey())
+ && !"aws:sourceaccount".equalsIgnoreCase(key.getKey())) {
+ return Match.DENY;
+ }
+ if (actual == null || !matchesServiceConditionValue(operator.getKey(), key.getValue(), actual)) {
+ return Match.NO_MATCH;
+ }
+ }
+ }
+ return Match.ALLOW;
+ }
+
+ private boolean matchesServiceConditionValue(String operator, JsonNode values, String actual) {
+ if (values.isArray()) {
+ for (JsonNode value : values) {
+ if (matchesServiceConditionValue(operator, value, actual)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ if (!values.isTextual()) {
+ return false;
+ }
+ if ("StringEquals".equals(operator)) {
+ return values.asText().equals(actual);
+ }
+ return globMatchesCaseSensitive(values.asText(), actual);
+ }
+
+ private boolean globMatchesCaseSensitive(String pattern, String value) {
+ int patternIndex = 0;
+ int valueIndex = 0;
+ int starIndex = -1;
+ int starValueIndex = -1;
+ while (valueIndex < value.length()) {
+ if (patternIndex < pattern.length()
+ && (pattern.charAt(patternIndex) == '?' || pattern.charAt(patternIndex) == value.charAt(valueIndex))) {
+ patternIndex++;
+ valueIndex++;
+ } else if (patternIndex < pattern.length() && pattern.charAt(patternIndex) == '*') {
+ starIndex = patternIndex++;
+ starValueIndex = valueIndex;
+ } else if (starIndex >= 0) {
+ patternIndex = starIndex + 1;
+ valueIndex = ++starValueIndex;
+ } else {
+ return false;
+ }
+ }
+ while (patternIndex < pattern.length() && pattern.charAt(patternIndex) == '*') {
+ patternIndex++;
+ }
+ return patternIndex == pattern.length();
}
private boolean matchesServicePrincipal(JsonNode principalNode, String servicePrincipal) {
@@ -132,11 +302,11 @@ public class AssumeRolePolicyEvaluator {
return false;
}
if (service.isTextual()) {
- return IamPolicyEvaluator.globMatches(service.asText(), servicePrincipal);
+ return service.asText().equals(servicePrincipal);
}
if (service.isArray()) {
for (JsonNode entry : service) {
- if (entry.isTextual() && IamPolicyEvaluator.globMatches(entry.asText(), servicePrincipal)) {
+ if (entry.isTextual() && entry.asText().equals(servicePrincipal)) {
return true;
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizerTest.java
new file mode 100644
index 0000000000..38328943f8
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizerTest.java
@@ -0,0 +1,326 @@
+package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.model.CallerContext;
+import io.github.hectorvent.floci.services.iam.model.IamRole;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+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.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 AppSyncDataSourceAuthorizerTest {
+
+ private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/appsync/Resolver";
+ private static final String DATA_SOURCE_ARN =
+ "arn:aws:appsync:us-east-1:000000000000:apis/example/datasources/Products";
+ private static final String TRUST = """
+ {"Statement":{"Effect":"Allow","Action":"sts:AssumeRole",
+ "Principal":{"Service":"appsync.amazonaws.com"}}}
+ """;
+
+ private final IamService iam = mock(IamService.class);
+ private final RegionResolver regionResolver = mock(RegionResolver.class);
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final EmulatorConfig config = mock(EmulatorConfig.class);
+ private final EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
+ private final EmulatorConfig.IamServiceConfig iamConfig = mock(EmulatorConfig.IamServiceConfig.class);
+ private final AppSyncDataSourceAuthorizer authorizer = new AppSyncDataSourceAuthorizer(
+ iam, new AssumeRolePolicyEvaluator(mapper), new IamPolicyEvaluator(mapper),
+ regionResolver, mapper, config);
+
+ @BeforeEach
+ void enableIamEnforcement() {
+ when(config.services()).thenReturn(services);
+ when(services.iam()).thenReturn(iamConfig);
+ when(iamConfig.enforcementEnabled()).thenReturn(true);
+ }
+
+ private record DynamoDbRequest(String operation, String index) {}
+
+ private DataSource dataSource(DataSourceType type) {
+ DataSource source = new DataSource();
+ source.setName("Products");
+ source.setType(type);
+ source.setDataSourceArn(DATA_SOURCE_ARN);
+ source.setServiceRoleArn(ROLE_ARN);
+ source.setDynamodbConfig(Map.of("tableName", "Products"));
+ source.setLambdaConfig(Map.of("lambdaFunctionArn",
+ "arn:aws:lambda:us-east-1:000000000000:function:products"));
+ source.setRelationalDatabaseConfig(Map.of("rdsHttpEndpointConfig", Map.of(
+ "dbClusterIdentifier", "products", "awsSecretStoreArn",
+ "arn:aws:secretsmanager:us-east-1:000000000000:secret:products")));
+ return source;
+ }
+
+ private void role(String trust, String policy) {
+ IamRole role = new IamRole("id", "Resolver", "/appsync/", ROLE_ARN, trust);
+ when(iam.findRole("000000000000", "Resolver")).thenReturn(Optional.of(role));
+ when(iam.resolvePrincipalContext(ROLE_ARN))
+ .thenReturn(CallerContext.of(List.of(policy)));
+ }
+
+ private static String allow(String action, String resource) {
+ return """
+ {"Statement":{"Effect":"Allow","Action":"%s","Resource":"%s"}}
+ """.formatted(action, resource);
+ }
+
+ private static AwsException denied(AppSyncDataSourceAuthorizer authorizer, DataSource source,
+ Object request) {
+ AwsException error = assertThrows(AwsException.class,
+ () -> authorizer.authorize(source, request, "us-east-1"));
+ assertEquals("AccessDeniedException", error.getErrorCode());
+ return error;
+ }
+
+ @Test
+ void noneNeedsNoRoleOrIamCall() {
+ DataSource source = dataSource(DataSourceType.NONE);
+ source.setServiceRoleArn(null);
+ authorizer.authorize(source, Map.of(), "us-east-1");
+ verifyNoInteractions(iam);
+ }
+
+ @Test
+ void disabledEnforcementPreservesUnmanagedDataSources() {
+ when(iamConfig.enforcementEnabled()).thenReturn(false);
+ for (DataSourceType type : List.of(DataSourceType.AMAZON_DYNAMODB,
+ DataSourceType.AWS_LAMBDA, DataSourceType.RELATIONAL_DATABASE)) {
+ DataSource source = dataSource(type);
+ source.setServiceRoleArn(null);
+ authorizer.authorize(source, Map.of(), "us-east-1");
+ }
+ verifyNoInteractions(iam);
+ }
+
+ @Test
+ void missingRoleAndCrossAccountRoleDenyBeforeDispatch() {
+ DataSource source = dataSource(DataSourceType.AMAZON_DYNAMODB);
+ source.setServiceRoleArn(null);
+ denied(authorizer, source, Map.of("operation", "GetItem"));
+ source.setServiceRoleArn("arn:aws:iam::111111111111:role/Resolver");
+ denied(authorizer, source, Map.of("operation", "GetItem"));
+ verifyNoInteractions(iam);
+ }
+
+ @Test
+ void untrustedRoleDenies() {
+ DataSource source = dataSource(DataSourceType.AWS_LAMBDA);
+ role("""
+ {"Statement":{"Effect":"Allow","Action":"sts:AssumeRole",
+ "Principal":{"Service":"lambda.amazonaws.com"}}}
+ """, allow("lambda:InvokeFunction", "*"));
+ denied(authorizer, source, Map.of("operation", "Invoke"));
+ }
+
+ @Test
+ void unknownRoleRemainsPermissiveWhenEnforcementIsEnabled() {
+ DataSource source = dataSource(DataSourceType.AWS_LAMBDA);
+ when(iam.findRole("000000000000", "Resolver")).thenReturn(Optional.empty());
+
+ authorizer.authorize(source, Map.of("operation", "Invoke"), "us-east-1");
+
+ verify(iam).findRole("000000000000", "Resolver");
+ verify(iam, never()).resolvePrincipalContext(ROLE_ARN);
+ }
+
+ @Test
+ void partialWildcardServicePrincipalCannotTrustAppSync() {
+ DataSource source = dataSource(DataSourceType.AWS_LAMBDA);
+ role("""
+ {"Statement":{"Effect":"Allow","Action":"sts:AssumeRole",
+ "Principal":{"Service":"appsync.*"}}}
+ """, allow("lambda:InvokeFunction", "*"));
+ denied(authorizer, source, Map.of("operation", "Invoke"));
+ }
+
+ @Test
+ void sourceConditionsRestrictWhichApiCanUseTheRole() {
+ DataSource source = dataSource(DataSourceType.AWS_LAMBDA);
+ String policy = allow("lambda:InvokeFunction", "*");
+ role("""
+ {"Statement":{"Effect":"Allow","Action":"sts:AssumeRole",
+ "Principal":{"Service":"appsync.amazonaws.com"},
+ "Condition":{"StringEquals":{"aws:SourceAccount":"000000000000"},
+ "ArnEquals":{"aws:SourceArn":"arn:aws:appsync:us-east-1:000000000000:apis/example"}}}}
+ """, policy);
+ authorizer.authorize(source, Map.of("operation", "Invoke"), "us-east-1");
+ source.setDataSourceArn(
+ "arn:aws:appsync:us-east-1:000000000000:apis/another/datasources/Products");
+ denied(authorizer, source, Map.of("operation", "Invoke"));
+ }
+
+ @Test
+ void unsupportedTrustConditionFailsClosed() {
+ DataSource source = dataSource(DataSourceType.AWS_LAMBDA);
+ role("""
+ {"Statement":{"Effect":"Allow","Action":"sts:AssumeRole",
+ "Principal":{"Service":"appsync.amazonaws.com"},
+ "Condition":{"StringEquals":{"aws:PrincipalTag/team":"admin"}}}}
+ """, allow("lambda:InvokeFunction", "*"));
+ denied(authorizer, source, Map.of("operation", "Invoke"));
+ }
+
+ @Test
+ void sourceArnConditionsAreCaseSensitive() {
+ DataSource source = dataSource(DataSourceType.AWS_LAMBDA);
+ role("""
+ {"Statement":{"Effect":"Allow","Action":"sts:AssumeRole",
+ "Principal":{"Service":"appsync.amazonaws.com"},
+ "Condition":{"ArnLike":{"aws:SourceArn":"arn:aws:appsync:us-east-1:000000000000:apis/EXAMPLE"}}}}
+ """, allow("lambda:InvokeFunction", "*"));
+ denied(authorizer, source, Map.of("operation", "Invoke"));
+ }
+
+ @Test
+ void missingTrustEffectDoesNotGrantAccess() {
+ DataSource source = dataSource(DataSourceType.AWS_LAMBDA);
+ role("""
+ {"Statement":{"Action":"sts:AssumeRole",
+ "Principal":{"Service":"appsync.amazonaws.com"}}}
+ """, allow("lambda:InvokeFunction", "*"));
+ denied(authorizer, source, Map.of("operation", "Invoke"));
+ }
+
+ @Test
+ void requestedRegionConditionUsesInvocationRegion() {
+ DataSource source = dataSource(DataSourceType.AWS_LAMBDA);
+ role(TRUST, """
+ {"Statement":{"Effect":"Allow","Action":"lambda:InvokeFunction",
+ "Resource":"*","Condition":{"StringEquals":{"aws:RequestedRegion":"us-east-1"}}}}
+ """);
+ authorizer.authorize(source, Map.of("operation", "Invoke"), "us-east-1");
+ assertThrows(AwsException.class,
+ () -> authorizer.authorize(source, Map.of("operation", "Invoke"), "eu-west-1"));
+ }
+
+ @Test
+ void unsupportedOperationCannotSkipPolicyEvaluation() {
+ DataSource source = dataSource(DataSourceType.AMAZON_DYNAMODB);
+ role(TRUST, allow("dynamodb:GetItem", "*"));
+ denied(authorizer, source, Map.of("operation", "BatchGetItem"));
+ }
+
+ @Test
+ void conditionalDenyOnlyAppliesToItsSourceAccount() {
+ DataSource source = dataSource(DataSourceType.AWS_LAMBDA);
+ role("""
+ {"Statement":[
+ {"Effect":"Allow","Action":"sts:AssumeRole",
+ "Principal":{"Service":"appsync.amazonaws.com"}},
+ {"Effect":"Deny","Action":"sts:AssumeRole",
+ "Principal":{"Service":"appsync.amazonaws.com"},
+ "Condition":{"StringEquals":{"aws:SourceAccount":"111111111111"}}}
+ ]}
+ """, allow("lambda:InvokeFunction", "*"));
+ authorizer.authorize(source, Map.of("operation", "Invoke"), "us-east-1");
+ }
+
+ @Test
+ void missingDataSourceArnCannotBypassSourceConditions() {
+ DataSource source = dataSource(DataSourceType.AWS_LAMBDA);
+ source.setDataSourceArn(null);
+ role(TRUST, allow("lambda:InvokeFunction", "*"));
+ denied(authorizer, source, Map.of("operation", "Invoke"));
+ }
+
+ @Test
+ void lambdaNeedsInvokeOnTheConfiguredFunction() {
+ DataSource source = dataSource(DataSourceType.AWS_LAMBDA);
+ role(TRUST, allow("lambda:InvokeFunction",
+ "arn:aws:lambda:us-east-1:000000000000:function:products"));
+ authorizer.authorize(source, Map.of("operation", "Invoke"), "us-east-1");
+ role(TRUST, allow("lambda:InvokeFunction",
+ "arn:aws:lambda:us-east-1:000000000000:function:other"));
+ denied(authorizer, source, Map.of("operation", "Invoke"));
+ }
+
+ @Test
+ void dynamoDbIndexQueryUsesIndexArnAndItsOwnAction() {
+ DataSource source = dataSource(DataSourceType.AMAZON_DYNAMODB);
+ role(TRUST, allow("dynamodb:Query",
+ "arn:aws:dynamodb:us-east-1:000000000000:table/Products/index/byCategory"));
+ authorizer.authorize(source, Map.of("operation", "Query", "index", "byCategory"), "us-east-1");
+ denied(authorizer, source, Map.of("operation", "Scan", "index", "byCategory"));
+ denied(authorizer, source, Map.of("operation", "Query", "index", "other"));
+ }
+
+ @Test
+ void jsonNodeDynamoDbRequestsCannotBypassOperationAndIndexPermissions() throws Exception {
+ DataSource source = dataSource(DataSourceType.AMAZON_DYNAMODB);
+ role(TRUST, allow("dynamodb:GetItem", "*"));
+ denied(authorizer, source, mapper.readTree("""
+ {"operation":"PutItem","key":{"id":{"S":"7"}}}
+ """));
+
+ role(TRUST, allow("dynamodb:Query",
+ "arn:aws:dynamodb:us-east-1:000000000000:table/Products"));
+ denied(authorizer, source, mapper.readTree("""
+ {"operation":"Query","index":"byCategory"}
+ """));
+ role(TRUST, allow("dynamodb:Query",
+ "arn:aws:dynamodb:us-east-1:000000000000:table/Products/index/byCategory"));
+ authorizer.authorize(source, mapper.readTree("""
+ {"operation":"Query","index":"byCategory"}
+ """), "us-east-1");
+ }
+
+ @Test
+ void serializableDynamoDbRequestsUseTheSameAuthorizationShapeAsTheInvoker() {
+ DataSource source = dataSource(DataSourceType.AMAZON_DYNAMODB);
+ role(TRUST, allow("dynamodb:GetItem", "*"));
+ denied(authorizer, source, new DynamoDbRequest("PutItem", null));
+ role(TRUST, allow("dynamodb:Query",
+ "arn:aws:dynamodb:us-east-1:000000000000:table/Products"));
+ denied(authorizer, source, new DynamoDbRequest("Query", "byCategory"));
+ }
+
+ @Test
+ void rdsRequiresBothClusterAndSecretPermissions() {
+ DataSource source = dataSource(DataSourceType.RELATIONAL_DATABASE);
+ when(regionResolver.getAccountId()).thenReturn("000000000000");
+ String cluster = "arn:aws:rds:us-east-1:000000000000:cluster:products";
+ String secret = "arn:aws:secretsmanager:us-east-1:000000000000:secret:products";
+ role(TRUST, allow("rds-data:ExecuteStatement", cluster));
+ denied(authorizer, source, "select 1");
+ role(TRUST, """
+ {"Statement":[
+ {"Effect":"Allow","Action":"rds-data:ExecuteStatement","Resource":"%s"},
+ {"Effect":"Allow","Action":"secretsmanager:GetSecretValue","Resource":"%s"}
+ ]}
+ """.formatted(cluster, secret));
+ authorizer.authorize(source, "select 1", "us-east-1");
+ }
+
+ @Test
+ void rdsAuthorizationChecksTheActualTargetAccount() {
+ DataSource source = dataSource(DataSourceType.RELATIONAL_DATABASE);
+ when(regionResolver.getAccountId()).thenReturn("111111111111");
+ role(TRUST, """
+ {"Statement":[
+ {"Effect":"Allow","Action":"rds-data:ExecuteStatement",
+ "Resource":"arn:aws:rds:us-east-1:000000000000:cluster:products"},
+ {"Effect":"Allow","Action":"secretsmanager:GetSecretValue","Resource":"*"}
+ ]}
+ """);
+ denied(authorizer, source, "select 1");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokersTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokersTest.java
new file mode 100644
index 0000000000..8efa538fc6
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokersTest.java
@@ -0,0 +1,159 @@
+package io.github.hectorvent.floci.services.appsync.graphql.datasource;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.appsync.model.DataSource;
+import io.github.hectorvent.floci.services.appsync.model.DataSourceType;
+import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.model.CallerContext;
+import io.github.hectorvent.floci.services.iam.model.IamRole;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+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.Mockito.doThrow;
+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 AppSyncDataSourceInvokersTest {
+
+ @Test
+ void deniedRoleCannotReachTheVtlBackingInvoker() {
+ AppSyncDataSourceAuthorizer authorizer = mock(AppSyncDataSourceAuthorizer.class);
+ AppSyncDataSourceInvoker invoker = mock(AppSyncDataSourceInvoker.class);
+ when(invoker.type()).thenReturn(DataSourceType.AWS_LAMBDA);
+ DataSource source = new DataSource();
+ source.setName("Products");
+ source.setType(DataSourceType.AWS_LAMBDA);
+ Map<String, Object> request = Map.of("version", "2018-05-29", "operation", "Invoke");
+ doThrow(new AwsException("AccessDeniedException", "Denied", 403))
+ .when(authorizer).authorize(source, request, "us-east-1");
+
+ AppSyncDataSourceInvokers dispatch = new AppSyncDataSourceInvokers(List.of(invoker), authorizer);
+ AwsException error = assertThrows(AwsException.class,
+ () -> dispatch.invokeVtl(source, request, "us-east-1"));
+
+ assertEquals("AccessDeniedException", error.getErrorCode());
+ verify(authorizer).authorize(source, request, "us-east-1");
+ verify(invoker, never()).invokeVtl(any(), any(), any());
+ }
+
+ @Test
+ void deniedRoleCannotReachTheBackingInvoker() {
+ AppSyncDataSourceAuthorizer authorizer = mock(AppSyncDataSourceAuthorizer.class);
+ DataSource source = new DataSource();
+ source.setName("Products");
+ source.setType(DataSourceType.AWS_LAMBDA);
+ Map<String, Object> request = Map.of("operation", "Invoke");
+ doThrow(new AwsException("AccessDeniedException", "Denied", 403))
+ .when(authorizer).authorize(source, request, "us-east-1");
+
+ AppSyncDataSourceInvoker invoker = new AppSyncDataSourceInvoker() {
+ @Override
+ public DataSourceType type() {
+ return DataSourceType.AWS_LAMBDA;
+ }
+
+ @Override
+ public Object invoke(DataSource dataSource, Object input, String region) {
+ throw new AssertionError("A denied role must not invoke the Lambda function");
+ }
+ };
+ AppSyncDataSourceInvokers dispatch = new AppSyncDataSourceInvokers(List.of(invoker), authorizer);
+ AwsException error = assertThrows(AwsException.class,
+ () -> dispatch.invoke(source, request, "us-east-1"));
+ assertEquals("AccessDeniedException", error.getErrorCode());
+ verify(authorizer).authorize(source, request, "us-east-1");
+ }
+
+ @Test
+ void realRolePolicyIsEnforcedBeforeLambdaDispatch() {
+ String roleArn = "arn:aws:iam::000000000000:role/appsync/Resolver";
+ String functionArn = "arn:aws:lambda:us-east-1:000000000000:function:products";
+ IamService iam = mock(IamService.class);
+ IamRole role = new IamRole("id", "Resolver", "/appsync/", roleArn, """
+ {"Statement":{"Effect":"Allow","Action":"sts:AssumeRole",
+ "Principal":{"Service":"appsync.amazonaws.com"}}}
+ """);
+ when(iam.findRole("000000000000", "Resolver")).thenReturn(Optional.of(role));
+ EmulatorConfig config = mock(EmulatorConfig.class);
+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
+ EmulatorConfig.IamServiceConfig iamConfig = mock(EmulatorConfig.IamServiceConfig.class);
+ when(config.services()).thenReturn(services);
+ when(services.iam()).thenReturn(iamConfig);
+ when(iamConfig.enforcementEnabled()).thenReturn(true);
+ ObjectMapper mapper = new ObjectMapper();
+ AppSyncDataSourceAuthorizer authorizer = new AppSyncDataSourceAuthorizer(iam,
+ new AssumeRolePolicyEvaluator(mapper), new IamPolicyEvaluator(mapper),
+ mock(RegionResolver.class), mapper, config);
+ AppSyncDataSourceInvoker invoker = mock(AppSyncDataSourceInvoker.class);
+ when(invoker.type()).thenReturn(DataSourceType.AWS_LAMBDA);
+ AppSyncDataSourceInvokers dispatch = new AppSyncDataSourceInvokers(List.of(invoker), authorizer);
+ DataSource source = new DataSource();
+ source.setName("Products");
+ source.setType(DataSourceType.AWS_LAMBDA);
+ source.setDataSourceArn(
+ "arn:aws:appsync:us-east-1:000000000000:apis/example/datasources/Products");
+ source.setServiceRoleArn(roleArn);
+ source.setLambdaConfig(Map.of("lambdaFunctionArn", functionArn));
+ Map<String, Object> request = Map.of("operation", "Invoke", "payload", Map.of());
+
+ when(iam.resolvePrincipalContext(roleArn)).thenReturn(CallerContext.of(List.of("""
+ {"Statement":{"Effect":"Allow","Action":"lambda:InvokeFunction",
+ "Resource":"arn:aws:lambda:us-east-1:000000000000:function:other"}}
+ """)));
+ AwsException error = assertThrows(AwsException.class,
+ () -> dispatch.invoke(source, request, "us-east-1"));
+ assertEquals("AccessDeniedException", error.getErrorCode());
+ verify(invoker, never()).invoke(any(), any(), any());
+
+ when(iam.resolvePrincipalContext(roleArn)).thenReturn(CallerContext.of(List.of("""
+ {"Statement":{"Effect":"Allow","Action":"lambda:InvokeFunction",
+ "Resource":"arn:aws:lambda:us-east-1:000000000000:function:products"}}
+ """)));
+ when(invoker.invoke(source, request, "us-east-1")).thenReturn(Map.of("accepted", true));
+ assertEquals(Map.of("accepted", true), dispatch.invoke(source, request, "us-east-1"));
+ verify(invoker).invoke(source, request, "us-east-1");
+ }
+
+ @Test
+ void disabledEnforcementAllowsJsAndVtlDispatchWithoutLocalRole() {
+ EmulatorConfig config = mock(EmulatorConfig.class);
+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
+ EmulatorConfig.IamServiceConfig iamConfig = mock(EmulatorConfig.IamServiceConfig.class);
+ when(config.services()).thenReturn(services);
+ when(services.iam()).thenReturn(iamConfig);
+ when(iamConfig.enforcementEnabled()).thenReturn(false);
+ IamService iam = mock(IamService.class);
+ ObjectMapper mapper = new ObjectMapper();
+ AppSyncDataSourceAuthorizer authorizer = new AppSyncDataSourceAuthorizer(iam,
+ new AssumeRolePolicyEvaluator(mapper), new IamPolicyEvaluator(mapper),
+ mock(RegionResolver.class), mapper, config);
+ AppSyncDataSourceInvoker invoker = mock(AppSyncDataSourceInvoker.class);
+ when(invoker.type()).thenReturn(DataSourceType.AWS_LAMBDA);
+ AppSyncDataSourceInvokers dispatch = new AppSyncDataSourceInvokers(List.of(invoker), authorizer);
+ DataSource source = new DataSource();
+ source.setName("Products");
+ source.setType(DataSourceType.AWS_LAMBDA);
+ Map<String, Object> request = Map.of("version", "2018-05-29", "operation", "Invoke");
+
+ dispatch.invoke(source, request, "us-east-1");
+ dispatch.invokeVtl(source, request, "us-east-1");
+
+ verify(invoker).invoke(source, request, "us-east-1");
+ verify(invoker).invokeVtl(source, request, "us-east-1");
+ verifyNoInteractions(iam);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java
index ac48f3de4a..263381632e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/resolver/AppSyncResolverExecutorTest.java
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncVtlEngine;
+import io.github.hectorvent.floci.services.appsync.graphql.datasource.AppSyncDataSourceAuthorizer;
import io.github.hectorvent.floci.services.appsync.graphql.datasource.AppSyncDataSourceInvoker;
import io.github.hectorvent.floci.services.appsync.graphql.datasource.AppSyncDataSourceInvokers;
import io.github.hectorvent.floci.services.appsync.graphql.datasource.LambdaDataSourceInvoker;
@@ -59,8 +60,8 @@ class AppSyncResolverExecutorTest {
private final RecordingInvoker lambdaInvoker = new RecordingInvoker(DataSourceType.AWS_LAMBDA);
private final ObjectMapper objectMapper = new ObjectMapper();
private final AppSyncResolverExecutor executor = new AppSyncResolverExecutor(appSync, jsRuntime,
- new AppSyncDataSourceInvokers(List.of(invoker, noneInvoker, dynamoDbInvoker, lambdaInvoker)),
- vtlEngine(), objectMapper);
+ new AppSyncDataSourceInvokers(List.of(invoker, noneInvoker, dynamoDbInvoker, lambdaInvoker),
+ mock(AppSyncDataSourceAuthorizer.class)), vtlEngine(), objectMapper);
private static AppSyncVtlEngine vtlEngine() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
@@ -639,7 +640,8 @@ class AppSyncResolverExecutorTest {
.thenReturn(new InvokeResult(200, null, "{\"id\":\"42\"}".getBytes(StandardCharsets.UTF_8),
null, "request-id"));
AppSyncResolverExecutor lambdaExecutor = new AppSyncResolverExecutor(appSync, jsRuntime,
- new AppSyncDataSourceInvokers(List.of(new LambdaDataSourceInvoker(lambdaService, objectMapper))),
+ new AppSyncDataSourceInvokers(List.of(new LambdaDataSourceInvoker(lambdaService, objectMapper)),
+ mock(AppSyncDataSourceAuthorizer.class)),
vtlEngine(), objectMapper);
Resolver resolver = resolver(ResolverKind.UNIT, "unit-code");
resolver.setDataSourceName("accountFunction");
@@ -669,7 +671,8 @@ class AppSyncResolverExecutorTest {
null, "request-id"));
AppSyncResolverExecutor lambdaExecutor = new AppSyncResolverExecutor(appSync, jsRuntime,
new AppSyncDataSourceInvokers(List.of(
- new LambdaDataSourceInvoker(lambdaService, objectMapper))),
+ new LambdaDataSourceInvoker(lambdaService, objectMapper)),
+ mock(AppSyncDataSourceAuthorizer.class)),
vtlEngine(), objectMapper);
Resolver resolver = resolver(ResolverKind.UNIT, null);
resolver.setDataSourceName("accountFunction");
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java
index b4676f4eee..5c12fbcb45 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java
@@ -218,6 +218,31 @@ class AssumeRolePolicyEvaluatorTest {
assertFalse(evaluator.allowsService(doc, "redshift.amazonaws.com"));
}
+ @Test
+ void malformedEffectInvalidatesTheWholeTrustDocument() {
+ String doc = """
+ {"Statement":[
+ {"Effect":"Allow","Principal":{"Service":"appsync.amazonaws.com"},"Action":"sts:AssumeRole"},
+ {"Principal":{"Service":"appsync.amazonaws.com"},"Action":"sts:AssumeRole"}]}
+ """;
+ assertFalse(evaluator.allowsService(doc, "appsync.amazonaws.com"));
+ assertFalse(evaluator.allowsService(doc, "appsync.amazonaws.com",
+ "arn:aws:appsync:us-east-1:000000000000:apis/example", "000000000000"));
+ }
+
+ @Test
+ void serviceSourceArnWildcardMatchesWithCaseSensitivity() {
+ String doc = """
+ {"Statement":{"Effect":"Allow","Principal":{"Service":"appsync.amazonaws.com"},
+ "Action":"sts:AssumeRole",
+ "Condition":{"ArnLike":{"aws:SourceArn":"arn:aws:appsync:us-east-1:000000000000:apis/Ex*"}}}}
+ """;
+ assertTrue(evaluator.allowsService(doc, "appsync.amazonaws.com",
+ "arn:aws:appsync:us-east-1:000000000000:apis/Example", "000000000000"));
+ assertFalse(evaluator.allowsService(doc, "appsync.amazonaws.com",
+ "arn:aws:appsync:us-east-1:000000000000:apis/example", "000000000000"));
+ }
+
@Test
void deniesBlankOrMalformedDocument() {
assertFalse(evaluator.allows(null, CALLER_ARN, CALLER_ACCOUNT));