diff --git a/src/main/java/io/floci/aws/services/iam/RoleResourceAccessAuthorizer.java b/src/main/java/io/floci/aws/services/iam/RoleResourceAccessAuthorizer.java new file mode 100644 index 0000000000..68546cad78 --- /dev/null +++ b/src/main/java/io/floci/aws/services/iam/RoleResourceAccessAuthorizer.java @@ -0,0 +1,225 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.IamConditionContextResolver; +import io.floci.aws.services.iam.AccessDeniedMessages.PolicyType; +import io.floci.aws.services.iam.AssumeRolePolicyEvaluator.TrustDecision; +import io.floci.aws.services.iam.IamPolicyEvaluator.Decision; +import io.floci.aws.services.iam.IamPolicyEvaluator.ResourceAccountRelationship; +import io.floci.aws.services.iam.IamPolicyEvaluator.ResourcePolicyDecision; +import io.floci.aws.services.iam.IamPolicyEvaluator.SimulationDecision; +import io.floci.aws.services.iam.ResourcePolicyProvider.ResourcePolicy; +import io.floci.aws.services.iam.model.CallerContext; +import io.floci.aws.services.iam.model.IamRole; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Instance; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Decides whether a role may perform an action on a resource, the way a service that calls another as that role is + * judged: the role's identity policies, permissions boundary and its account's service control policies, together + * with the resource's own policy. Within one account, the role's policies or the resource's policy can allow the + * call; across accounts, both have to (IAM User Guide, cross-account policy evaluation logic). An explicit Deny in + * any of them refuses it. A refusal carries the access denied message AWS words for the policy that refused. + * + *

Whether IAM is enforced at all is the caller's decision; this class always evaluates. + */ +@ApplicationScoped +public class RoleResourceAccessAuthorizer { + + private static final Logger LOG = Logger.getLogger(RoleResourceAccessAuthorizer.class); + private static final String ANY_RESOURCE = "*"; + + private final IamService iamService; + private final IamPolicyEvaluator evaluator; + private final Instance resourcePolicies; + private final Instance scpProvider; + + @Inject + public RoleResourceAccessAuthorizer(IamService iamService, IamPolicyEvaluator evaluator, + Instance resourcePolicies, + Instance scpProvider) { + this.iamService = iamService; + this.evaluator = evaluator; + this.resourcePolicies = resourcePolicies; + this.scpProvider = scpProvider; + } + + /** + * Returns why {@code roleArn} may not perform {@code action} on {@code resourceArn}, as the service that owns + * the resource words its access denied message, or nothing when it may. + * + * @param resourceArn the resource, or {@code *} for an action with no resource-level permissions + * @param requestedRegion the Region the call is made in, for the {@code aws:RequestedRegion} condition key + * @param conditionKeys the condition keys the called service adds to the global ones + */ + public Optional refusal(String roleArn, String action, String resourceArn, String requestedRegion, + Map> conditionKeys) { + AwsArnUtils.Arn resource = ANY_RESOURCE.equals(resourceArn) ? null : AwsArnUtils.parse(resourceArn); + Optional invokingRole = role(roleArn); + if (invokingRole.isEmpty()) { + LOG.infov("Role {0} names no existing role, so it cannot invoke {1}", roleArn, resourceArn); + return Optional.of(denied(roleArn, action, resourceArn, PolicyType.IDENTITY_BASED_POLICY.noAllow(action))); + } + // The role is evaluated as itself, under the ARN IAM holds for it, whichever form names it. + String invokingRoleArn = invokingRole.get().getArn(); + CallerContext role = iamService.resolvePrincipalContext(invokingRoleArn); + AwsArnUtils.Arn roleId = AwsArnUtils.parse(invokingRoleArn); + List> scpLevels = scpLevels(roleId.accountId()); + + List policies = resource == null ? List.of() + : ResourcePolicyProviders.policiesFor(resourcePolicies, resource.service(), action, resourceArn); + String ownerAccount = policies.isEmpty() + ? (resource == null ? null : resource.accountId()) : policies.getFirst().ownerAccountId(); + List documents = policies.stream() + .map(ResourcePolicy::policyDocument) + .filter(document -> document != null && !document.isBlank()) + .toList(); + Map> serviceContext = new LinkedHashMap<>(conditionKeys); + serviceContext.put("aws:PrincipalArn", List.of(invokingRoleArn)); + Map> context = IamConditionContextResolver.withGlobalContext( + serviceContext, resourceArn, requestedRegion, roleId.accountId(), ownerAccount); + + RequestPrincipal session = RequestPrincipal.roleSession(sessionArn(invokingRoleArn), invokingRoleArn); + ResourcePolicyDecision resourcePolicy = evaluator.evaluateResourcePolicyFor( + documents.isEmpty() ? null : documents, session, action, resourceArn, context); + ResourceAccountRelationship relationship = relationship(roleId.accountId(), ownerAccount); + Decision decision = evaluator.evaluateResolvedResourcePolicy( + role.withScpLevels(scpLevels), resourcePolicy, relationship, action, resourceArn, context); + if (decision == Decision.ALLOW) { + return Optional.empty(); + } + return Optional.of(denied(invokingRoleArn, action, resourceArn, reason(role, scpLevels, action, resourceArn, + context, relationship, ResourceGrant.of(resourcePolicy)))); + } + + /** + * The role {@code roleArn} names, matched as STS {@code AssumeRole} matches a role ARN + * ({@link IamService#roleArnMatches}). A role ARN that names no role, or names one under + * another path, is not that role, and a grant written for the ARN must not admit it. + */ + public Optional role(String roleArn) { + if (!AwsArnUtils.isArn(roleArn)) { + return Optional.empty(); + } + AwsArnUtils.Arn arn = AwsArnUtils.parse(roleArn); + String roleName = arn.resource().substring(arn.resource().lastIndexOf('/') + 1); + return iamService.findRole(arn.accountId(), roleName) + .filter(role -> IamService.roleArnMatches(roleArn, role)); + } + + public List> scpLevels(String accountId) { + return scpProvider.isResolvable() ? scpProvider.get().effectiveScpLevels(accountId) : null; + } + + /** + * A resource whose account is unknown, an action on {@code *} or an S3 ARN of a bucket S3 does + * not hold, is judged within the caller's account: nothing says it belongs to another. + */ + public static ResourceAccountRelationship relationship(String callerAccount, String resourceAccount) { + return resourceAccount == null || resourceAccount.isBlank() || callerAccount.equals(resourceAccount) + ? ResourceAccountRelationship.SAME_ACCOUNT : ResourceAccountRelationship.CROSS_ACCOUNT; + } + + /** + * The context that ends the access denied message (IAM User Guide, "Access denied error message + * examples"): the first policy type that refuses the call, explicit denials before implicit ones, + * each in the order AWS evaluates the types: service control policies, the resource's policy, + * identity-based policies, then the permissions boundary. + */ + public String reason(CallerContext role, List> scpLevels, String action, String resource, + Map> context, ResourceAccountRelationship relationship, + ResourceGrant grant) { + List scps = scpLevels == null ? List.of() : scpLevels.stream() + .filter(level -> !level.isEmpty()) + .map(level -> simulate(level, action, resource, context)) + .toList(); + SimulationDecision identity = simulate(role.identityPolicies(), action, resource, context); + SimulationDecision boundary = role.boundaryPolicyDocument() == null + ? SimulationDecision.ALLOWED + : simulate(List.of(role.boundaryPolicyDocument()), action, resource, context); + boolean crossAccount = relationship == ResourceAccountRelationship.CROSS_ACCOUNT; + + if (scps.contains(SimulationDecision.EXPLICIT_DENY)) { + return PolicyType.SERVICE_CONTROL_POLICY.explicitDeny(); + } + if (grant.explicitDeny()) { + return grant.type().explicitDeny(); + } + if (identity == SimulationDecision.EXPLICIT_DENY) { + return PolicyType.IDENTITY_BASED_POLICY.explicitDeny(); + } + if (boundary == SimulationDecision.EXPLICIT_DENY) { + return PolicyType.PERMISSIONS_BOUNDARY.explicitDeny(); + } + if (scps.contains(SimulationDecision.IMPLICIT_DENY)) { + return PolicyType.SERVICE_CONTROL_POLICY.noAllow(action); + } + if ((grant.required() || crossAccount) && !grant.allows()) { + return grant.type().noAllow(action); + } + if (identity != SimulationDecision.ALLOWED && (crossAccount || !grant.sufficient())) { + return PolicyType.IDENTITY_BASED_POLICY.noAllow(action); + } + return PolicyType.PERMISSIONS_BOUNDARY.noAllow(action); + } + + private SimulationDecision simulate(List documents, String action, String resource, + Map> context) { + return evaluator.simulatePrincipalPolicy(CallerContext.of(documents), action, resource, context); + } + + public static String denied(String roleArn, String action, String resource, String reason) { + return AccessDeniedMessages.notAuthorized(sessionArn(roleArn), action, resource, reason); + } + + /** + * The role's session, which makes the call, as an access denied message writes it: + * {@code arn:aws:sts::account-id:assumed-role/role-name}. + */ + public static String sessionArn(String roleArn) { + try { + AwsArnUtils.Arn role = AwsArnUtils.parse(roleArn); + String roleName = role.resource().substring(role.resource().lastIndexOf('/') + 1); + return AwsArnUtils.Arn.global(role.partition(), "sts", role.accountId(), "assumed-role/" + roleName) + .toString(); + } catch (IllegalArgumentException ignored) { + // A role ARN that does not parse names no session, so the message names the ARN as given. + return roleArn; + } + } + + /** + * What the resource's own policy said about a call, and how the access denied message names it. + * + * @param allows whether it allows the call at all + * @param sufficient whether, within one account, that allow grants the call without the + * caller's identity-based policies + * @param required whether the call needs it to allow even within one account, as a role's + * trust policy does + * @param type the policy type, as the access denied message names it + */ + public record ResourceGrant(boolean explicitDeny, boolean allows, boolean sufficient, boolean required, + PolicyType type) { + + public static ResourceGrant of(ResourcePolicyDecision resourcePolicy) { + boolean sufficient = resourcePolicy == ResourcePolicyDecision.ALLOW + || resourcePolicy == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER; + return new ResourceGrant(resourcePolicy == ResourcePolicyDecision.EXPLICIT_DENY, + sufficient || resourcePolicy == ResourcePolicyDecision.ALLOW_ACCOUNT, sufficient, false, + PolicyType.RESOURCE_BASED_POLICY); + } + + public static ResourceGrant of(TrustDecision trust) { + return new ResourceGrant(trust == TrustDecision.EXPLICIT_DENY, + trust == TrustDecision.ALLOW || trust == TrustDecision.ALLOW_ACCOUNT, + trust == TrustDecision.ALLOW, true, PolicyType.ROLE_TRUST_POLICY); + } + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalFunctionValues.java b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalFunctionValues.java new file mode 100644 index 0000000000..4707c33f8f --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalFunctionValues.java @@ -0,0 +1,173 @@ +package io.floci.aws.services.redshift.spectrum; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.BooleanNode; +import com.fasterxml.jackson.databind.node.DecimalNode; +import com.fasterxml.jackson.databind.node.DoubleNode; +import com.fasterxml.jackson.databind.node.LongNode; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.TextNode; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.time.format.DateTimeParseException; +import java.time.temporal.ChronoField; +import java.util.Locale; +import java.util.Set; + +/** + * Converts the values of a Lambda UDF call between the text PostgreSQL holds them as and the JSON the Lambda + * function receives and returns. Numbers travel as JSON numbers, booleans as JSON booleans, and character, date + * and timestamp values as JSON strings; a SQL NULL is a JSON null. + */ +final class ExternalFunctionValues { + private static final String RESULT_ERROR = "22P02"; + private static final Set NON_FINITE = Set.of("NaN", "Infinity", "-Infinity"); + /** PostgreSQL's text form: seconds always, and a fraction of up to six digits only when there is one. */ + private static final DateTimeFormatter TIMESTAMP_TEXT = new DateTimeFormatterBuilder() + .appendPattern("yyyy-MM-dd HH:mm:ss").appendFraction(ChronoField.NANO_OF_SECOND, 0, 6, true) + .toFormatter(Locale.ROOT); + + private ExternalFunctionValues() { + } + + /** The JSON form of an argument, given as the text PostgreSQL printed for a value of the declared type. */ + static JsonNode toJson(String declaredType, String text) { + if (text == null) { + return NullNode.getInstance(); + } + String base = ExternalFunctionTypes.base(declaredType); + try { + return switch (base) { + case "smallint", "integer", "bigint" -> LongNode.valueOf(Long.parseLong(text.trim())); + case "numeric" -> numeric(text.trim()); + case "real", "double precision" -> floating(text.trim()); + case "boolean" -> BooleanNode.valueOf(booleanText(text)); + default -> TextNode.valueOf(text); + }; + } catch (IllegalArgumentException e) { + throw new SpectrumSqlException(RESULT_ERROR, "The argument \"" + text + "\" is not a valid " + base); + } + } + + private static JsonNode numeric(String text) { + // PostgreSQL numeric can hold NaN, which JSON cannot, so it travels as its text like a float's does + return "NaN".equalsIgnoreCase(text) ? TextNode.valueOf(text) : DecimalNode.valueOf(new BigDecimal(text)); + } + + /** + * The text of a result value, ready to be read back as the declared type, or null for a JSON null. A value of + * a JSON type the declared type does not take fails the call, as Redshift does for a mistyped result. + */ + static String fromJson(String declaredType, JsonNode value) { + if (value == null || value.isNull()) { + return null; + } + String base = ExternalFunctionTypes.base(declaredType); + return switch (base) { + case "smallint" -> whole(base, value, Short.MIN_VALUE, Short.MAX_VALUE); + case "integer" -> whole(base, value, Integer.MIN_VALUE, Integer.MAX_VALUE); + case "bigint" -> whole(base, value, Long.MIN_VALUE, Long.MAX_VALUE); + case "numeric" -> numericResult(base, value); + case "real", "double precision" -> floatResult(base, value); + case "boolean" -> Boolean.toString(bool(base, value)); + case "date" -> date(text(base, value)); + case "timestamp" -> timestamp(text(base, value)); + default -> text(base, value); + }; + } + + private static JsonNode floating(String text) { + double parsed = Double.parseDouble(text); + // JSON has no NaN or infinity, so those travel as the strings PostgreSQL prints them as + return Double.isFinite(parsed) ? DoubleNode.valueOf(parsed) : TextNode.valueOf(text); + } + + private static boolean booleanText(String text) { + return switch (text.trim().toLowerCase(Locale.ROOT)) { + case "t", "true" -> true; + case "f", "false" -> false; + default -> throw new IllegalArgumentException("Not a boolean: " + text); + }; + } + + private static String numericResult(String base, JsonNode value) { + // PostgreSQL numeric can hold NaN, which travels as text because JSON has no NaN + if (value.isTextual() && "NaN".equalsIgnoreCase(value.textValue())) { + return "NaN"; + } + return number(base, value).decimalValue().toPlainString(); + } + + private static String floatResult(String base, JsonNode value) { + // the non-finite values a float argument travels as come back the same way + if (value.isTextual() && NON_FINITE.contains(value.textValue())) { + return value.textValue(); + } + return Double.toString(number(base, value).doubleValue()); + } + + private static String whole(String base, JsonNode value, long min, long max) { + // an integer type takes a JSON number with no fraction (3 and 3.0, not 1.5 or "1") + if (!value.isNumber()) { + throw mistyped(base, value); + } + BigDecimal decimal = value.decimalValue(); + if (decimal.stripTrailingZeros().scale() > 0) { + throw mistyped(base, value); + } + BigInteger number = decimal.toBigInteger(); + if (number.compareTo(BigInteger.valueOf(min)) < 0 || number.compareTo(BigInteger.valueOf(max)) > 0) { + throw new SpectrumSqlException(RESULT_ERROR, "The Lambda result " + number + " is out of range for " + + base); + } + return number.toString(); + } + + private static JsonNode number(String base, JsonNode value) { + if (!value.isNumber()) { + throw mistyped(base, value); + } + return value; + } + + private static boolean bool(String base, JsonNode value) { + if (!value.isBoolean()) { + throw mistyped(base, value); + } + return value.booleanValue(); + } + + private static String text(String base, JsonNode value) { + if (!value.isTextual()) { + throw mistyped(base, value); + } + return value.textValue(); + } + + private static String date(String text) { + try { + return LocalDate.parse(text.trim()).toString(); + } catch (DateTimeParseException e) { + throw new SpectrumSqlException(RESULT_ERROR, "The Lambda result \"" + text + "\" is not a date"); + } + } + + private static String timestamp(String text) { + try { + // accepts the ISO form with a T and the PostgreSQL form with a space + return TIMESTAMP_TEXT.format(LocalDateTime.parse(text.trim().replace(' ', 'T'))); + } catch (DateTimeParseException e) { + throw new SpectrumSqlException(RESULT_ERROR, "The Lambda result \"" + text + "\" is not a timestamp"); + } + } + + private static SpectrumSqlException mistyped(String base, JsonNode value) { + return new SpectrumSqlException(RESULT_ERROR, "The Lambda result of JSON type " + value.getNodeType() + + " does not fit the return type " + base); + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/LambdaUdfInvoker.java b/src/main/java/io/floci/aws/services/redshift/spectrum/LambdaUdfInvoker.java new file mode 100644 index 0000000000..673cdb9891 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/LambdaUdfInvoker.java @@ -0,0 +1,335 @@ +package io.floci.aws.services.redshift.spectrum; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.cfg.JsonNodeFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +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.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.ServicePrincipals; +import io.floci.aws.services.iam.RoleResourceAccessAuthorizer; +import io.floci.aws.services.iam.ServiceRoleAuthorizer; +import io.floci.aws.services.lambda.LambdaService; +import io.floci.aws.services.lambda.model.InvocationType; +import io.floci.aws.services.lambda.model.InvokeResult; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.LongConsumer; +import java.util.regex.Pattern; + +/** + * Calls the Lambda function behind a scalar Lambda UDF with batches of argument rows, over the JSON interface + * Redshift documents: a request of {@code request_id}, {@code cluster}, {@code user}, {@code database}, + * {@code external_function}, {@code query_id}, {@code num_records} and {@code arguments}, and a response of + * {@code success}, {@code error_msg}, {@code num_records} and {@code results}. + * + *

Rows go in and results come back as the text PostgreSQL holds the values as, one result per row in the + * order of the rows, so the evaluator can read them straight from and into the backend. A batch holds at most the + * function's {@code MAX_BATCH_ROWS} rows and about its {@code MAX_BATCH_SIZE} bytes of arguments; a throttled + * call is retried for the function's {@code RETRY_TIMEOUT}. The function's role must be allowed to invoke the + * Lambda function when IAM enforcement is on. + */ +@ApplicationScoped +public class LambdaUdfInvoker { + + private static final Logger LOG = Logger.getLogger(LambdaUdfInvoker.class); + private static final String REDSHIFT_PRINCIPAL = ServicePrincipals.of("redshift"); + private static final String INVOKE_ACTION = "lambda:InvokeFunction"; + private static final String FUNCTION_ERROR = "XX000"; + private static final String NOT_AUTHORIZED = "42501"; + private static final long FIRST_RETRY_DELAY_MILLIS = 50; + private static final long MAX_RETRY_DELAY_MILLIS = 1_000; + // floats stay exact: a numeric result read as a double would lose digits, and stripping zeroes loses scale + private static final ObjectMapper JSON = JsonMapper.builder() + .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) + .disable(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES) + .build(); + private static final Pattern ACCOUNT_FUNCTION = Pattern.compile("\\d{12}:function:.+"); + + private final LambdaService lambda; + private final ServiceRoleAuthorizer authorizer; + private final RoleResourceAccessAuthorizer roleAccess; + private final EmulatorConfig config; + private final RegionResolver regionResolver; + private final Clock clock; + private final LongConsumer sleeper; + + @Inject + public LambdaUdfInvoker(LambdaService lambda, ServiceRoleAuthorizer authorizer, + RoleResourceAccessAuthorizer roleAccess, EmulatorConfig config, + RegionResolver regionResolver, Clock clock) { + this(lambda, authorizer, roleAccess, config, regionResolver, clock, LambdaUdfInvoker::sleep); + } + + LambdaUdfInvoker(LambdaService lambda, ServiceRoleAuthorizer authorizer, + RoleResourceAccessAuthorizer roleAccess, EmulatorConfig config, RegionResolver regionResolver, + Clock clock, LongConsumer sleeper) { + this.lambda = lambda; + this.authorizer = authorizer; + this.roleAccess = roleAccess; + this.config = config; + this.regionResolver = regionResolver; + this.clock = clock; + this.sleeper = sleeper; + } + + /** + * Calls the function for every row and returns one result per row, in order, each as the text of the value or + * null for SQL NULL. + * + * @param clusterRegion the Region of the cluster, which Redshift calls the function from; null where the cluster + * is not one Floci knows, which leaves the default Region + * @param user the database user whose query makes the call + * @param queryId the id of that query + * @param rows the argument rows as PostgreSQL prints them, each with one text (or null) per argument + */ + public List invoke(ExternalFunctionBinding function, SpectrumSession session, String clusterRegion, + String user, long queryId, List> rows) { + String region = clusterRegion != null ? clusterRegion : regionResolver.getDefaultRegion(); + String functionArn = functionArn(function, session.accountId(), region); + requireAuthorized(function, session.accountId(), functionArn); + String clusterArn = new AwsArnUtils.Arn(regionResolver.partitionForRegion(region), "redshift", region, + session.accountId(), "cluster:" + session.clusterIdentifier()).toString(); + List results = new ArrayList<>(rows.size()); + for (List batch : batches(function, rows)) { + ObjectNode request = request(function, session, clusterArn, user, queryId, batch); + results.addAll(call(function, functionArn, request, batch.size())); + } + return results; + } + + /** Splits the rows into the batches the function's limits allow; a row over the size limit goes alone. */ + private static List> batches(ExternalFunctionBinding function, List> rows) { + List> batches = new ArrayList<>(); + List batch = new ArrayList<>(); + // arguments serializes as "[" + records joined by "," + "]" + long bytes = 2; + for (List row : rows) { + ArrayNode record = record(function, row); + long size = record.toString().getBytes(StandardCharsets.UTF_8).length; + long added = batch.isEmpty() ? size : size + 1; + if (!batch.isEmpty() && (batch.size() >= function.maxBatchRows() + || bytes + added > function.maxBatchSizeBytes())) { + batches.add(batch); + batch = new ArrayList<>(); + bytes = 2; + added = size; + } + batch.add(record); + bytes += added; + } + if (!batch.isEmpty()) { + batches.add(batch); + } + return batches; + } + + private static ArrayNode record(ExternalFunctionBinding function, List row) { + if (row == null || row.size() != function.argumentTypes().size()) { + throw new SpectrumSqlException(FUNCTION_ERROR, "A call of " + function.functionName() + " has " + + (row == null ? 0 : row.size()) + " values for " + function.argumentTypes().size() + + " arguments"); + } + ArrayNode record = JsonNodeFactory.instance.arrayNode(); + for (int i = 0; i < function.argumentTypes().size(); i++) { + record.add(ExternalFunctionValues.toJson(function.argumentTypes().get(i), row.get(i))); + } + return record; + } + + private ObjectNode request(ExternalFunctionBinding function, SpectrumSession session, String clusterArn, + String user, long queryId, List batch) { + ObjectNode request = JsonNodeFactory.instance.objectNode(); + request.put("request_id", UUID.randomUUID().toString().toUpperCase(Locale.ROOT)); + request.put("cluster", clusterArn); + request.put("user", user); + request.put("database", session.databaseName()); + request.put("external_function", function.schemaName() + "." + function.functionName()); + request.put("query_id", queryId); + request.put("num_records", batch.size()); + ArrayNode arguments = request.putArray("arguments"); + for (ArrayNode record : batch) { + arguments.add(record); + } + return request; + } + + private List call(ExternalFunctionBinding function, String functionArn, ObjectNode request, + int expected) { + byte[] payload = request.toString().getBytes(StandardCharsets.UTF_8); + InvokeResult result = invokeWithRetry(function, functionArn, payload); + if (result.isTimedOut()) { + throw new SpectrumSqlException(FUNCTION_ERROR, "The Lambda function " + function.lambdaFunction() + + " timed out"); + } + if (result.getFunctionError() != null) { + throw new SpectrumSqlException(FUNCTION_ERROR, "The Lambda function " + function.lambdaFunction() + + " failed: " + functionErrorMessage(result)); + } + return results(function, parse(function, result.getPayload()), expected); + } + + /** A call the Lambda service throttles is repeated with a growing pause until the function's retry budget ends. */ + private InvokeResult invokeWithRetry(ExternalFunctionBinding function, String functionArn, byte[] payload) { + long start = clock.millis(); + long budget = Math.max(0, function.retryTimeoutMillis()); + long delay = FIRST_RETRY_DELAY_MILLIS; + while (true) { + try { + return lambda.invokeArn(functionArn, payload, InvocationType.RequestResponse); + } catch (AwsException e) { + if (!"TooManyRequestsException".equals(e.getErrorCode())) { + throw new SpectrumSqlException(FUNCTION_ERROR, "Cannot call the Lambda function " + + function.lambdaFunction() + ": " + e.getMessage()); + } + // compared as an elapsed time, so a huge RETRY_TIMEOUT cannot overflow a deadline + long remaining = budget - (clock.millis() - start); + if (remaining <= 0) { + throw new SpectrumSqlException(FUNCTION_ERROR, "The Lambda function " + + function.lambdaFunction() + " stayed throttled for " + function.retryTimeoutMillis() + + " ms: " + e.getMessage()); + } + long pause = Math.min(delay, remaining); + LOG.debugv("Lambda UDF {0} throttled, retrying in {1} ms", function.lambdaFunction(), pause); + sleeper.accept(pause); + delay = Math.min(delay * 2, MAX_RETRY_DELAY_MILLIS); + } catch (SpectrumSqlException e) { + throw e; + } catch (RuntimeException e) { + throw new SpectrumSqlException(FUNCTION_ERROR, "Cannot call the Lambda function " + + function.lambdaFunction() + ": " + e.getMessage()); + } + } + } + + private static JsonNode parse(ExternalFunctionBinding function, byte[] payload) { + try { + JsonNode response = JSON.readTree(payload == null ? new byte[0] : payload); + // Lambda handlers following the AWS Python docs often return json.dumps(body), which arrives as a JSON string + if (response != null && response.isTextual()) { + response = JSON.readTree(response.textValue()); + } + if (response == null || !response.isObject()) { + throw new SpectrumSqlException(FUNCTION_ERROR, "The Lambda function " + function.lambdaFunction() + + " did not return a JSON object"); + } + return response; + } catch (IOException e) { + throw new SpectrumSqlException(FUNCTION_ERROR, "The Lambda function " + function.lambdaFunction() + + " returned a response that is not JSON: " + e.getMessage()); + } + } + + private static List results(ExternalFunctionBinding function, JsonNode response, int expected) { + if (!response.path("success").isBoolean() || !response.path("success").booleanValue()) { + JsonNode message = response.get("error_msg"); + throw new SpectrumSqlException(FUNCTION_ERROR, "The Lambda function " + function.lambdaFunction() + + " reported a failure: " + (message != null && message.isTextual() ? message.textValue() + : "no error_msg")); + } + JsonNode results = response.get("results"); + if (results == null || !results.isArray()) { + throw new SpectrumSqlException(FUNCTION_ERROR, "The Lambda function " + function.lambdaFunction() + + " returned no results array"); + } + if (results.size() != expected || !response.path("num_records").isIntegralNumber() + || response.path("num_records").asLong(-1) != expected) { + throw new SpectrumSqlException(FUNCTION_ERROR, "The Lambda function " + function.lambdaFunction() + + " returned " + results.size() + " results (num_records " + response.path("num_records") + + ") for " + expected + " records"); + } + List texts = new ArrayList<>(expected); + for (JsonNode value : results) { + texts.add(ExternalFunctionValues.fromJson(function.returnType(), value)); + } + return texts; + } + + /** The message of a Lambda function error, which the runtime reports as a JSON object of errorMessage. */ + private static String functionErrorMessage(InvokeResult result) { + byte[] payload = result.getPayload(); + if (payload != null && payload.length > 0) { + try { + JsonNode body = JSON.readTree(payload); + JsonNode message = body == null ? null : body.get("errorMessage"); + if (message != null && message.isTextual()) { + return message.textValue(); + } + } catch (IOException expected) { + // the body of a function error is whatever the runtime wrote; the error type below still says why + } + } + return result.getFunctionError(); + } + + /** A bare function name is one of the cluster's account in the cluster's Region, as Lambda resolves it. */ + private String functionArn(ExternalFunctionBinding function, String accountId, String region) { + String reference = function.lambdaFunction(); + if (AwsArnUtils.looksLikeArn(reference)) { + AwsArnUtils.Arn arn; + try { + arn = AwsArnUtils.parse(reference); + } catch (IllegalArgumentException e) { + throw notAFunctionArn(reference); + } + if (!"lambda".equals(arn.service()) || !arn.resource().startsWith("function:")) { + throw notAFunctionArn(reference); + } + return reference; + } + // Lambda also takes :function:, which is a function of that account in this region + if (ACCOUNT_FUNCTION.matcher(reference).matches()) { + int separator = reference.indexOf(':'); + return new AwsArnUtils.Arn(regionResolver.partitionForRegion(region), "lambda", region, + reference.substring(0, separator), reference.substring(separator + 1)).toString(); + } + return new AwsArnUtils.Arn(regionResolver.partitionForRegion(region), "lambda", region, accountId, + "function:" + reference).toString(); + } + + private static SpectrumSqlException notAFunctionArn(String reference) { + return new SpectrumSqlException(FUNCTION_ERROR, "\"" + reference + "\" is not a Lambda function ARN"); + } + + private void requireAuthorized(ExternalFunctionBinding function, String accountId, String functionArn) { + Optional refusal = authorizer.refusal(function.iamRoleArn(), accountId, REDSHIFT_PRINCIPAL, null, + List.of()); + if (refusal.isPresent()) { + throw new SpectrumSqlException(NOT_AUTHORIZED, refusal.get()); + } + if (!config.services().iam().enforcementEnabled()) { + return; + } + refusal = roleAccess.refusal(function.iamRoleArn(), INVOKE_ACTION, functionArn, + AwsArnUtils.parse(functionArn).region(), Map.of()); + if (refusal.isPresent()) { + throw new SpectrumSqlException(NOT_AUTHORIZED, refusal.get()); + } + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new SpectrumSqlException(FUNCTION_ERROR, "Interrupted while waiting to call the Lambda function"); + } + } +} diff --git a/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java b/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java index 7a09814953..646e2595ea 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java @@ -3,7 +3,6 @@ package io.floci.aws.services.stepfunctions; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.IamConditionContextResolver; import io.floci.aws.core.common.ServicePrincipals; -import io.floci.aws.services.iam.AccessDeniedMessages; import io.floci.aws.services.iam.AccessDeniedMessages.PolicyType; import io.floci.aws.services.iam.AssumeRolePolicyEvaluator; import io.floci.aws.services.iam.AssumeRolePolicyEvaluator.TrustDecision; @@ -11,13 +10,12 @@ import io.floci.aws.services.iam.IamPolicyEvaluator; import io.floci.aws.services.iam.IamPolicyEvaluator.Decision; import io.floci.aws.services.iam.IamPolicyEvaluator.ResourceAccountRelationship; import io.floci.aws.services.iam.IamPolicyEvaluator.ResourcePolicyDecision; -import io.floci.aws.services.iam.IamPolicyEvaluator.SimulationDecision; import io.floci.aws.services.iam.IamService; import io.floci.aws.services.iam.IamService.CallerArns; -import io.floci.aws.services.iam.RequestPrincipal; import io.floci.aws.services.iam.ResourcePolicyProvider; -import io.floci.aws.services.iam.ResourcePolicyProvider.ResourcePolicy; import io.floci.aws.services.iam.ResourcePolicyProviders; +import io.floci.aws.services.iam.RoleResourceAccessAuthorizer; +import io.floci.aws.services.iam.RoleResourceAccessAuthorizer.ResourceGrant; import io.floci.aws.services.iam.ScpProvider; import io.floci.aws.services.iam.model.CallerContext; import io.floci.aws.services.iam.model.IamRole; @@ -27,7 +25,6 @@ import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.jboss.logging.Logger; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -57,7 +54,7 @@ public class LambdaTaskAuthorizer { private final IamPolicyEvaluator evaluator; private final AssumeRolePolicyEvaluator trustEvaluator; private final Instance resourcePolicies; - private final Instance scpProvider; + private final RoleResourceAccessAuthorizer access; @Inject public LambdaTaskAuthorizer(IamService iamService, IamPolicyEvaluator evaluator, @@ -68,7 +65,7 @@ public class LambdaTaskAuthorizer { this.evaluator = evaluator; this.trustEvaluator = trustEvaluator; this.resourcePolicies = resourcePolicies; - this.scpProvider = scpProvider; + this.access = new RoleResourceAccessAuthorizer(iamService, evaluator, resourcePolicies, scpProvider); } /** @@ -130,7 +127,7 @@ public class LambdaTaskAuthorizer { List permissions, boolean checkExecutionRole) { AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); if (checkExecutionRole) { - IamRole executionRole = role(machine.getRoleArn()).orElseThrow( + IamRole executionRole = access.role(machine.getRoleArn()).orElseThrow( () -> new AslExecutor.FailStateException("States.Permissions", "The execution role " + machine.getRoleArn() + " does not exist.")); if (!trustEvaluator.allowsService(executionRole.getAssumeRolePolicyDocument(), @@ -181,42 +178,7 @@ public class LambdaTaskAuthorizer { private Optional refusal(String roleArn, String action, String resourceArn, String requestedRegion, Map> conditionKeys) { - AwsArnUtils.Arn resource = ANY_RESOURCE.equals(resourceArn) ? null : AwsArnUtils.parse(resourceArn); - Optional invokingRole = role(roleArn); - if (invokingRole.isEmpty()) { - LOG.infov("Role {0} names no existing role, so it cannot invoke {1}", roleArn, resourceArn); - return Optional.of(denied(roleArn, action, resourceArn, PolicyType.IDENTITY_BASED_POLICY.noAllow(action))); - } - // The role is evaluated as itself, under the ARN IAM holds for it, whichever form names it. - String invokingRoleArn = invokingRole.get().getArn(); - CallerContext role = iamService.resolvePrincipalContext(invokingRoleArn); - AwsArnUtils.Arn roleId = AwsArnUtils.parse(invokingRoleArn); - List> scpLevels = scpLevels(roleId.accountId()); - - List policies = resource == null ? List.of() - : ResourcePolicyProviders.policiesFor(resourcePolicies, resource.service(), action, resourceArn); - String ownerAccount = policies.isEmpty() - ? (resource == null ? null : resource.accountId()) : policies.getFirst().ownerAccountId(); - List documents = policies.stream() - .map(ResourcePolicy::policyDocument) - .filter(document -> document != null && !document.isBlank()) - .toList(); - Map> serviceContext = new LinkedHashMap<>(conditionKeys); - serviceContext.put("aws:PrincipalArn", List.of(invokingRoleArn)); - Map> context = IamConditionContextResolver.withGlobalContext( - serviceContext, resourceArn, requestedRegion, roleId.accountId(), ownerAccount); - - RequestPrincipal session = RequestPrincipal.roleSession(sessionArn(invokingRoleArn), invokingRoleArn); - ResourcePolicyDecision functionPolicy = evaluator.evaluateResourcePolicyFor( - documents.isEmpty() ? null : documents, session, action, resourceArn, context); - ResourceAccountRelationship relationship = relationship(roleId.accountId(), ownerAccount); - Decision decision = evaluator.evaluateResolvedResourcePolicy( - role.withScpLevels(scpLevels), functionPolicy, relationship, action, resourceArn, context); - if (decision == Decision.ALLOW) { - return Optional.empty(); - } - return Optional.of(denied(invokingRoleArn, action, resourceArn, reason(role, scpLevels, action, resourceArn, - context, relationship, ResourceGrant.of(functionPolicy)))); + return access.refusal(roleArn, action, resourceArn, requestedRegion, conditionKeys); } /** @@ -229,25 +191,25 @@ public class LambdaTaskAuthorizer { * tutorial has the trust policy check. */ public Optional assumeRefusal(String executionRoleArn, String roleArn, String stateMachineArn) { - Optional executionRole = role(executionRoleArn); + Optional executionRole = access.role(executionRoleArn); if (executionRole.isEmpty()) { LOG.infov("Execution role {0} names no existing role, so it cannot assume {1}", executionRoleArn, roleArn); - return Optional.of(denied(executionRoleArn, ASSUME_ROLE, roleArn, + return Optional.of(RoleResourceAccessAuthorizer.denied(executionRoleArn, ASSUME_ROLE, roleArn, PolicyType.IDENTITY_BASED_POLICY.noAllow(ASSUME_ROLE))); } String callerRoleArn = executionRole.get().getArn(); - Optional target = role(roleArn); + Optional target = access.role(roleArn); if (target.isEmpty()) { // STS refuses a role that does not exist as it refuses one the caller may not assume, // and no policy of the role took part, so the message names none. LOG.infov("Role {0} named by a task''s Credentials does not exist", roleArn); - return Optional.of(denied(callerRoleArn, ASSUME_ROLE, roleArn, null)); + return Optional.of(RoleResourceAccessAuthorizer.denied(callerRoleArn, ASSUME_ROLE, roleArn, null)); } String targetRoleArn = target.get().getArn(); CallerContext caller = iamService.resolvePrincipalContext(callerRoleArn); AwsArnUtils.Arn callerId = AwsArnUtils.parse(callerRoleArn); String roleAccount = AwsArnUtils.parse(targetRoleArn).accountId(); - List> scpLevels = scpLevels(callerId.accountId()); + List> scpLevels = access.scpLevels(callerId.accountId()); Map> context = IamConditionContextResolver.withGlobalContext( Map.of("aws:PrincipalArn", List.of(callerRoleArn), "sts:ExternalId", List.of(stateMachineArn)), targetRoleArn, AwsArnUtils.parse(stateMachineArn).region(), callerId.accountId(), roleAccount); @@ -256,12 +218,12 @@ public class LambdaTaskAuthorizer { // is a session of it and carries AssumedRole as its aws:PrincipalType. That path mints no // session name, and a session's aws:userid is role-id:session-name, so it and aws:username // stay absent, which is what makes a condition on either of them not match. - CallerArns trustCaller = new CallerArns(sessionArn(callerRoleArn), callerRoleArn, + CallerArns trustCaller = new CallerArns(RoleResourceAccessAuthorizer.sessionArn(callerRoleArn), callerRoleArn, CallerArns.TYPE_ASSUMED_ROLE, null, null) .withOrganization(iamService.organizationContextOf(callerId.accountId()).orElse(null)); TrustDecision trust = trustEvaluator.decide(target.get().getAssumeRolePolicyDocument(), trustCaller, callerId.accountId(), context); - ResourceAccountRelationship relationship = relationship(callerId.accountId(), roleAccount); + ResourceAccountRelationship relationship = RoleResourceAccessAuthorizer.relationship(callerId.accountId(), roleAccount); // A grant to the execution role's account delegates to that account, so within it the // role's own policies have to allow the call too, as they do across accounts anyway. ResourcePolicyDecision trustGrant = switch (trust) { @@ -278,131 +240,7 @@ public class LambdaTaskAuthorizer { if (decision == Decision.ALLOW) { return Optional.empty(); } - return Optional.of(denied(callerRoleArn, ASSUME_ROLE, roleArn, - reason(caller, scpLevels, ASSUME_ROLE, targetRoleArn, context, relationship, grant))); - } - - /** - * The role {@code roleArn} names, matched as STS {@code AssumeRole} matches a role ARN - * ({@link IamService#roleArnMatches}). A role ARN that names no role, or names one under - * another path, is not that role, and a grant written for the ARN must not admit it. - */ - private Optional role(String roleArn) { - if (!AwsArnUtils.isArn(roleArn)) { - return Optional.empty(); - } - AwsArnUtils.Arn arn = AwsArnUtils.parse(roleArn); - String roleName = arn.resource().substring(arn.resource().lastIndexOf('/') + 1); - return iamService.findRole(arn.accountId(), roleName) - .filter(role -> IamService.roleArnMatches(roleArn, role)); - } - - private List> scpLevels(String accountId) { - return scpProvider.isResolvable() ? scpProvider.get().effectiveScpLevels(accountId) : null; - } - - /** - * A resource whose account is unknown, an action on {@code *} or an S3 ARN of a bucket S3 does - * not hold, is judged within the caller's account: nothing says it belongs to another. - */ - private static ResourceAccountRelationship relationship(String callerAccount, String resourceAccount) { - return resourceAccount == null || resourceAccount.isBlank() || callerAccount.equals(resourceAccount) - ? ResourceAccountRelationship.SAME_ACCOUNT : ResourceAccountRelationship.CROSS_ACCOUNT; - } - - /** - * The context that ends the access denied message (IAM User Guide, "Access denied error message - * examples"): the first policy type that refuses the call, explicit denials before implicit ones, - * each in the order AWS evaluates the types: service control policies, the resource's policy, - * identity-based policies, then the permissions boundary. - */ - private String reason(CallerContext role, List> scpLevels, String action, String resource, - Map> context, ResourceAccountRelationship relationship, - ResourceGrant grant) { - List scps = scpLevels == null ? List.of() : scpLevels.stream() - .filter(level -> !level.isEmpty()) - .map(level -> simulate(level, action, resource, context)) - .toList(); - SimulationDecision identity = simulate(role.identityPolicies(), action, resource, context); - SimulationDecision boundary = role.boundaryPolicyDocument() == null - ? SimulationDecision.ALLOWED - : simulate(List.of(role.boundaryPolicyDocument()), action, resource, context); - boolean crossAccount = relationship == ResourceAccountRelationship.CROSS_ACCOUNT; - - if (scps.contains(SimulationDecision.EXPLICIT_DENY)) { - return PolicyType.SERVICE_CONTROL_POLICY.explicitDeny(); - } - if (grant.explicitDeny()) { - return grant.type().explicitDeny(); - } - if (identity == SimulationDecision.EXPLICIT_DENY) { - return PolicyType.IDENTITY_BASED_POLICY.explicitDeny(); - } - if (boundary == SimulationDecision.EXPLICIT_DENY) { - return PolicyType.PERMISSIONS_BOUNDARY.explicitDeny(); - } - if (scps.contains(SimulationDecision.IMPLICIT_DENY)) { - return PolicyType.SERVICE_CONTROL_POLICY.noAllow(action); - } - if ((grant.required() || crossAccount) && !grant.allows()) { - return grant.type().noAllow(action); - } - if (identity != SimulationDecision.ALLOWED && (crossAccount || !grant.sufficient())) { - return PolicyType.IDENTITY_BASED_POLICY.noAllow(action); - } - return PolicyType.PERMISSIONS_BOUNDARY.noAllow(action); - } - - private SimulationDecision simulate(List documents, String action, String resource, - Map> context) { - return evaluator.simulatePrincipalPolicy(CallerContext.of(documents), action, resource, context); - } - - private static String denied(String roleArn, String action, String resource, String reason) { - return AccessDeniedMessages.notAuthorized(sessionArn(roleArn), action, resource, reason); - } - - /** - * The role's session, which makes the call, as the Step Functions Developer Guide writes it in - * an access denied message: {@code arn:aws:sts::account-id:assumed-role/StepFunctions-MyStateMachine-role}. - */ - private static String sessionArn(String roleArn) { - try { - AwsArnUtils.Arn role = AwsArnUtils.parse(roleArn); - String roleName = role.resource().substring(role.resource().lastIndexOf('/') + 1); - return AwsArnUtils.Arn.global(role.partition(), "sts", role.accountId(), "assumed-role/" + roleName) - .toString(); - } catch (IllegalArgumentException ignored) { - // A role ARN that does not parse names no session, so the message names the ARN as given. - return roleArn; - } - } - - /** - * What the resource's own policy said about a call, and how the access denied message names it. - * - * @param allows whether it allows the call at all - * @param sufficient whether, within one account, that allow grants the call without the - * caller's identity-based policies - * @param required whether the call needs it to allow even within one account, as a role's - * trust policy does - * @param type the policy type, as the access denied message names it - */ - private record ResourceGrant(boolean explicitDeny, boolean allows, boolean sufficient, boolean required, - PolicyType type) { - - static ResourceGrant of(ResourcePolicyDecision functionPolicy) { - boolean sufficient = functionPolicy == ResourcePolicyDecision.ALLOW - || functionPolicy == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER; - return new ResourceGrant(functionPolicy == ResourcePolicyDecision.EXPLICIT_DENY, - sufficient || functionPolicy == ResourcePolicyDecision.ALLOW_ACCOUNT, sufficient, false, - PolicyType.RESOURCE_BASED_POLICY); - } - - static ResourceGrant of(TrustDecision trust) { - return new ResourceGrant(trust == TrustDecision.EXPLICIT_DENY, - trust == TrustDecision.ALLOW || trust == TrustDecision.ALLOW_ACCOUNT, - trust == TrustDecision.ALLOW, true, PolicyType.ROLE_TRUST_POLICY); - } + return Optional.of(RoleResourceAccessAuthorizer.denied(callerRoleArn, ASSUME_ROLE, roleArn, + access.reason(caller, scpLevels, ASSUME_ROLE, targetRoleArn, context, relationship, grant))); } } diff --git a/src/test/java/io/floci/aws/services/iam/RoleResourceAccessAuthorizerTest.java b/src/test/java/io/floci/aws/services/iam/RoleResourceAccessAuthorizerTest.java new file mode 100644 index 0000000000..6d09d9bcb9 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/RoleResourceAccessAuthorizerTest.java @@ -0,0 +1,94 @@ +package io.floci.aws.services.iam; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.iam.ResourcePolicyProvider.ResourcePolicy; +import io.floci.aws.services.iam.model.CallerContext; +import io.floci.aws.services.iam.model.IamRole; +import jakarta.enterprise.inject.Instance; +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.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.startsWith; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class RoleResourceAccessAuthorizerTest { + + private static final String ACCOUNT = "111122223333"; + private static final String OTHER_ACCOUNT = "444455556666"; + private static final String ROLE = "arn:aws:iam::" + ACCOUNT + ":role/exec"; + private static final String ACTION = "lambda:InvokeFunction"; + private static final String OWN_FUNCTION = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":function:sum"; + private static final String OTHER_FUNCTION = "arn:aws:lambda:eu-west-1:" + OTHER_ACCOUNT + ":function:sum"; + private static final String INVOKE_ANYTHING = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"lambda:InvokeFunction","Resource":"*"}]}"""; + + private ResourcePolicyProvider functionPolicies; + private IamService iamService; + private RoleResourceAccessAuthorizer authorizer; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + iamService = mock(IamService.class); + functionPolicies = mock(ResourcePolicyProvider.class); + when(functionPolicies.getResourcePolicies(anyString(), anyString(), anyString())).thenReturn(List.of()); + Instance providers = mock(Instance.class); + when(providers.iterator()).thenAnswer(call -> List.of(functionPolicies).iterator()); + Instance scps = mock(Instance.class); + IamRole role = new IamRole(); + role.setArn(ROLE); + when(iamService.findRole(ACCOUNT, "exec")).thenReturn(Optional.of(role)); + when(iamService.resolvePrincipalContext(anyString())) + .thenReturn(CallerContext.of(List.of(INVOKE_ANYTHING))); + authorizer = new RoleResourceAccessAuthorizer(iamService, new IamPolicyEvaluator(new ObjectMapper()), + providers, scps); + } + + @Test + void aRoleItsOwnPoliciesAllowInvokesAFunctionOfItsAccountWithoutAResourcePolicy() { + assertThat(authorizer.refusal(ROLE, ACTION, OWN_FUNCTION, "us-east-1", Map.of()), equalTo(Optional.empty())); + } + + @Test + void aFunctionOfAnotherAccountNeedsItsResourcePolicyToGrantTheRole() { + when(functionPolicies.getResourcePolicies("lambda", ACTION, OTHER_FUNCTION)) + .thenReturn(List.of(new ResourcePolicy(null, OTHER_ACCOUNT))); + + Optional refusal = authorizer.refusal(ROLE, ACTION, OTHER_FUNCTION, "eu-west-1", Map.of()); + + assertThat(refusal.orElseThrow(), startsWith("User: arn:aws:sts::" + ACCOUNT + ":assumed-role/exec")); + assertThat(refusal.orElseThrow(), containsString("no resource-based policy allows the " + ACTION)); + } + + @Test + void anExplicitDenyInTheResourcePolicyRefusesARoleItsOwnPoliciesAllow() { + String deny = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":{"AWS":"%s"}, + "Action":"lambda:InvokeFunction","Resource":"%s"}]}""".formatted(ROLE, OWN_FUNCTION); + when(functionPolicies.getResourcePolicies("lambda", ACTION, OWN_FUNCTION)) + .thenReturn(List.of(new ResourcePolicy(deny, ACCOUNT))); + + Optional refusal = authorizer.refusal(ROLE, ACTION, OWN_FUNCTION, "us-east-1", Map.of()); + + assertThat(refusal.orElseThrow(), containsString("with an explicit deny in a resource-based policy")); + } + + @Test + void aRoleThatDoesNotExistIsRefused() { + String missing = "arn:aws:iam::" + ACCOUNT + ":role/gone"; + + Optional refusal = authorizer.refusal(missing, ACTION, OWN_FUNCTION, "us-east-1", Map.of()); + + assertThat(refusal.orElseThrow(), containsString("no identity-based policy allows the " + ACTION)); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/ExternalFunctionValuesTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/ExternalFunctionValuesTest.java new file mode 100644 index 0000000000..dea6933de8 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/ExternalFunctionValuesTest.java @@ -0,0 +1,129 @@ +package io.floci.aws.services.redshift.spectrum; + +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class ExternalFunctionValuesTest { + private static final JsonNodeFactory JSON = JsonNodeFactory.instance; + + @Test + void integerTypesTravelAsJsonNumbers() { + assertThat(ExternalFunctionValues.toJson("integer", "42").isIntegralNumber(), is(true)); + assertThat(ExternalFunctionValues.toJson("bigint", "-9223372036854775808").longValue(), + equalTo(Long.MIN_VALUE)); + } + + @Test + void numericKeepsItsScaleAndFloatsAreNumbers() { + assertThat(ExternalFunctionValues.toJson("numeric(10,2)", "1.50").decimalValue().toPlainString(), + equalTo("1.50")); + assertThat(ExternalFunctionValues.toJson("double precision", "2.5").doubleValue(), equalTo(2.5)); + } + + @Test + void anInfiniteFloatTravelsAsItsPostgresText() { + assertThat(ExternalFunctionValues.toJson("real", "Infinity").textValue(), equalTo("Infinity")); + } + + @Test + void booleanCharacterDateAndTimestampValuesMapToTheirJsonTypes() { + assertThat(ExternalFunctionValues.toJson("boolean", "t").booleanValue(), is(true)); + assertThat(ExternalFunctionValues.toJson("boolean", "false").booleanValue(), is(false)); + assertThat(ExternalFunctionValues.toJson("varchar(20)", "abc").textValue(), equalTo("abc")); + assertThat(ExternalFunctionValues.toJson("date", "2026-11-23").textValue(), equalTo("2026-11-23")); + assertThat(ExternalFunctionValues.toJson("timestamp", "2026-11-23 10:15:00").textValue(), + equalTo("2026-11-23 10:15:00")); + } + + @Test + void aSqlNullIsAJsonNullBothWays() { + assertThat(ExternalFunctionValues.toJson("integer", null).isNull(), is(true)); + assertThat(ExternalFunctionValues.fromJson("integer", JSON.nullNode()), is(nullValue())); + assertThat(ExternalFunctionValues.fromJson("integer", null), is(nullValue())); + } + + @Test + void resultsAreReadBackAsTheTextOfTheReturnType() { + assertThat(ExternalFunctionValues.fromJson("smallint", JSON.numberNode(7)), equalTo("7")); + assertThat(ExternalFunctionValues.fromJson("numeric(5,2)", JSON.numberNode(new BigDecimal("3.10"))), + equalTo("3.10")); + assertThat(ExternalFunctionValues.fromJson("boolean", JSON.booleanNode(true)), equalTo("true")); + assertThat(ExternalFunctionValues.fromJson("date", JSON.textNode("2026-11-23")), equalTo("2026-11-23")); + assertThat(ExternalFunctionValues.fromJson("timestamp", JSON.textNode("2026-11-23T10:15:00")), + equalTo("2026-11-23 10:15:00")); + assertThat(ExternalFunctionValues.fromJson("varchar", JSON.textNode("x")), equalTo("x")); + } + + @Test + void anIntegerResultMayCarryAZeroFraction() { + assertThat(ExternalFunctionValues.fromJson("integer", JSON.numberNode(new BigDecimal("3.0"))), equalTo("3")); + assertThat(ExternalFunctionValues.fromJson("bigint", JSON.numberNode(new BigDecimal("1E+3"))), + equalTo("1000")); + } + + @Test + void theNonFiniteValuesAFloatTravelsAsComeBack() { + assertThat(ExternalFunctionValues.fromJson("double precision", JSON.textNode("Infinity")), equalTo("Infinity")); + assertThat(ExternalFunctionValues.fromJson("real", JSON.textNode("NaN")), equalTo("NaN")); + assertThrows(SpectrumSqlException.class, + () -> ExternalFunctionValues.fromJson("real", JSON.textNode("a lot"))); + } + + @Test + void aNumericNanRoundTripsAsItsText() { + assertThat(ExternalFunctionValues.toJson("numeric", "NaN").textValue(), equalTo("NaN")); + assertThat(ExternalFunctionValues.fromJson("numeric", JSON.textNode("NaN")), equalTo("NaN")); + assertThat(ExternalFunctionValues.fromJson("numeric(10,2)", JSON.textNode("nan")), equalTo("NaN")); + assertThrows(SpectrumSqlException.class, + () -> ExternalFunctionValues.fromJson("numeric", JSON.textNode("Infinity"))); + assertThrows(SpectrumSqlException.class, + () -> ExternalFunctionValues.fromJson("numeric", JSON.textNode("not-a-number"))); + } + + @Test + void anArgumentThatIsNotAValueOfItsTypeIsAnSqlError() { + for (String[] bad : new String[][] {{"integer", "abc"}, {"numeric", "1.2.3"}, {"double precision", "x"}, + {"boolean", "yes"}}) { + SpectrumSqlException failed = assertThrows(SpectrumSqlException.class, + () -> ExternalFunctionValues.toJson(bad[0], bad[1])); + assertThat(failed.sqlState(), equalTo("22P02")); + } + } + + @Test + void aResultOfTheWrongJsonTypeFailsTheCall() { + SpectrumSqlException integerFromString = assertThrows(SpectrumSqlException.class, + () -> ExternalFunctionValues.fromJson("integer", JSON.textNode("1"))); + assertThat(integerFromString.sqlState(), equalTo("22P02")); + assertThrows(SpectrumSqlException.class, () -> ExternalFunctionValues.fromJson("integer", + JSON.numberNode(1.5))); + assertThrows(SpectrumSqlException.class, () -> ExternalFunctionValues.fromJson("boolean", + JSON.textNode("true"))); + assertThrows(SpectrumSqlException.class, () -> ExternalFunctionValues.fromJson("varchar", + JSON.numberNode(1))); + } + + @Test + void aResultOutsideTheRangeOfTheReturnTypeFailsTheCall() { + assertThrows(SpectrumSqlException.class, () -> ExternalFunctionValues.fromJson("smallint", + JSON.numberNode(40_000))); + assertThrows(SpectrumSqlException.class, () -> ExternalFunctionValues.fromJson("integer", + JSON.numberNode(3_000_000_000L))); + } + + @Test + void aMalformedDateOrTimestampFailsTheCall() { + assertThrows(SpectrumSqlException.class, () -> ExternalFunctionValues.fromJson("date", + JSON.textNode("yesterday"))); + assertThrows(SpectrumSqlException.class, () -> ExternalFunctionValues.fromJson("timestamp", + JSON.textNode("noon"))); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/LambdaUdfInvokerTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/LambdaUdfInvokerTest.java new file mode 100644 index 0000000000..415a5b219e --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/LambdaUdfInvokerTest.java @@ -0,0 +1,580 @@ +package io.floci.aws.services.redshift.spectrum; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.services.iam.RoleResourceAccessAuthorizer; +import io.floci.aws.services.iam.ServiceRoleAuthorizer; +import io.floci.aws.services.lambda.LambdaService; +import io.floci.aws.services.lambda.model.InvocationType; +import io.floci.aws.services.lambda.model.InvokeResult; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicLong; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class LambdaUdfInvokerTest { + private static final String ACCOUNT = "000000000000"; + private static final String ROLE = "arn:aws:iam::000000000000:role/udf"; + private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:sum"; + private static final SpectrumSession SESSION = new SpectrumSession(ACCOUNT, ACCOUNT + ":cluster-1", "dev", + List.of(), false); + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String REGION = "us-east-1"; + + private LambdaService lambda; + private ServiceRoleAuthorizer authorizer; + private RoleResourceAccessAuthorizer roleAccess; + private EmulatorConfig config; + private AtomicLong now; + private List sleeps; + private LambdaUdfInvoker invoker; + + @BeforeEach + void setUp() { + lambda = mock(LambdaService.class); + authorizer = mock(ServiceRoleAuthorizer.class); + when(authorizer.refusal(anyString(), anyString(), anyString(), any(), anyList())) + .thenReturn(Optional.empty()); + roleAccess = mock(RoleResourceAccessAuthorizer.class); + when(roleAccess.refusal(anyString(), anyString(), anyString(), any(), any())).thenReturn(Optional.empty()); + config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().iam().enforcementEnabled()).thenReturn(true); + RegionResolver regions = mock(RegionResolver.class); + when(regions.getDefaultRegion()).thenReturn("us-east-1"); + when(regions.partitionForRegion(anyString())).thenReturn("aws"); + now = new AtomicLong(1_000); + sleeps = new ArrayList<>(); + Clock clock = new Clock() { + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return Instant.ofEpochMilli(now.get()); + } + }; + invoker = new LambdaUdfInvoker(lambda, authorizer, roleAccess, + config, regions, clock, millis -> { + sleeps.add(millis); + now.addAndGet(millis); + }); + } + + private static ExternalFunctionBinding function(List args, String returns, int maxRows, long maxBytes, + long retryMillis) { + return new ExternalFunctionBinding(ACCOUNT, SESSION.clusterKey(), "dev", "public", "exfunc_sum", args, + returns, "STABLE", "sum", ROLE, retryMillis, maxRows, maxBytes); + } + + private static ExternalFunctionBinding twoInts() { + return function(List.of("integer", "integer"), "integer", Integer.MAX_VALUE, 5L * 1024 * 1024, 20_000); + } + + private static InvokeResult ok(String body) { + return new InvokeResult(200, null, body.getBytes(StandardCharsets.UTF_8), null, "req"); + } + + private static List> rows(String[]... rows) { + return Arrays.stream(rows).map(Arrays::asList).toList(); + } + + private JsonNode lastRequest() throws Exception { + ArgumentCaptor payload = ArgumentCaptor.forClass(byte[].class); + verify(lambda, atLeastOnce()).invokeArn(eq(FUNCTION_ARN), payload.capture(), + eq(InvocationType.RequestResponse)); + return JSON.readTree(payload.getValue()); + } + + @Test + void sendsTheDocumentedRequestAndReadsTheResultsInOrder() throws Exception { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn( + ok("{\"success\":true,\"num_records\":3,\"results\":[3,null,10]}")); + + List results = invoker.invoke(twoInts(), SESSION, REGION, "analyst", 5678234L, + rows(new String[] {"1", "2"}, new String[] {"3", null}, new String[] {"4", "6"})); + + assertThat(results, equalTo(Arrays.asList("3", null, "10"))); + JsonNode request = lastRequest(); + assertThat(request.get("cluster").textValue(), + equalTo("arn:aws:redshift:us-east-1:000000000000:cluster:cluster-1")); + assertThat(request.get("user").textValue(), equalTo("analyst")); + assertThat(request.get("database").textValue(), equalTo("dev")); + assertThat(request.get("external_function").textValue(), equalTo("public.exfunc_sum")); + assertThat(request.get("query_id").longValue(), equalTo(5678234L)); + assertThat(request.get("num_records").intValue(), equalTo(3)); + assertThat(request.get("request_id").textValue().length(), equalTo(36)); + assertThat(request.get("arguments").toString(), equalTo("[[1,2],[3,null],[4,6]]")); + } + + @Test + void callsABareFunctionNameAndNamesTheClusterInTheClustersOwnRegion() throws Exception { + String euFunctionArn = "arn:aws:lambda:eu-west-1:000000000000:function:sum"; + when(lambda.invokeArn(eq(euFunctionArn), any(), any())).thenReturn( + ok("{\"success\":true,\"num_records\":1,\"results\":[3]}")); + + invoker.invoke(twoInts(), SESSION, "eu-west-1", "u", 1, rows(new String[] {"1", "2"})); + + ArgumentCaptor payload = ArgumentCaptor.forClass(byte[].class); + verify(lambda).invokeArn(eq(euFunctionArn), payload.capture(), eq(InvocationType.RequestResponse)); + assertThat(JSON.readTree(payload.getValue()).get("cluster").textValue(), + equalTo("arn:aws:redshift:eu-west-1:000000000000:cluster:cluster-1")); + } + + @Test + void aFunctionOfOneArgumentGetsOneElementArrays() throws Exception { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn( + ok("{\"success\":true,\"num_records\":2,\"results\":[\"A\",null]}")); + + List results = invoker.invoke( + function(List.of("character varying"), "varchar", 100, 1024, 0), SESSION, REGION, "u", 1, + rows(new String[] {"a"}, new String[] {null})); + + assertThat(results, equalTo(Arrays.asList("A", null))); + assertThat(lastRequest().get("arguments").toString(), equalTo("[[\"a\"],[null]]")); + } + + @Test + void aJsonEncodedStringResponseIsAccepted() throws Exception { + String encoded = JSON.writeValueAsString("{\"success\":true,\"num_records\":2,\"results\":[3,10]}"); + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn(ok(encoded)); + + List results = invoker.invoke(twoInts(), SESSION, REGION, "u", 1, + rows(new String[] {"1", "2"}, new String[] {"4", "6"})); + + assertThat(results, equalTo(List.of("3", "10"))); + } + + @Test + void splitsRowsIntoBatchesOfAtMostMaxBatchRows() throws Exception { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn( + ok("{\"success\":true,\"num_records\":2,\"results\":[1,2]}"), + ok("{\"success\":true,\"num_records\":1,\"results\":[3]}")); + + List results = invoker.invoke( + function(List.of("integer"), "integer", 2, 5L * 1024 * 1024, 0), SESSION, REGION, "u", 1, + rows(new String[] {"1"}, new String[] {"2"}, new String[] {"3"})); + + assertThat(results, equalTo(List.of("1", "2", "3"))); + ArgumentCaptor payloads = ArgumentCaptor.forClass(byte[].class); + verify(lambda, times(2)).invokeArn(eq(FUNCTION_ARN), payloads.capture(), any()); + assertThat(JSON.readTree(payloads.getAllValues().get(0)).get("arguments").toString(), equalTo("[[1],[2]]")); + assertThat(JSON.readTree(payloads.getAllValues().get(1)).get("arguments").toString(), equalTo("[[3]]")); + } + + @Test + void splitsRowsIntoBatchesByTheirSizeAndSendsAnOversizedRowAlone() throws Exception { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenAnswer(call -> { + JsonNode request = JSON.readTree((byte[]) call.getArgument(1)); + int count = request.get("num_records").intValue(); + return ok("{\"success\":true,\"num_records\":" + count + ",\"results\":[" + + String.join(",", Collections.nCopies(count, "0")) + "]}"); + }); + + // the first row alone is over the size limit; the two small ones fit together in the next batch + invoker.invoke(function(List.of("varchar"), "integer", 100, 1024, 0), SESSION, REGION, "u", 1, + rows(new String[] {"x".repeat(2000)}, new String[] {"y"}, new String[] {"z"})); + + ArgumentCaptor payloads = ArgumentCaptor.forClass(byte[].class); + verify(lambda, times(2)).invokeArn(eq(FUNCTION_ARN), payloads.capture(), any()); + assertThat(JSON.readTree(payloads.getAllValues().get(0)).get("num_records").intValue(), equalTo(1)); + assertThat(JSON.readTree(payloads.getAllValues().get(1)).get("arguments").toString(), + equalTo("[[\"y\"],[\"z\"]]")); + } + + @Test + void batchesCountArgumentsArrayBracketsAndCommasAgainstMaxBatchSize() throws Exception { + long limit = 20; + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenAnswer(call -> { + JsonNode request = JSON.readTree((byte[]) call.getArgument(1)); + int count = request.get("num_records").intValue(); + return ok("{\"success\":true,\"num_records\":" + count + ",\"results\":[" + + String.join(",", Collections.nCopies(count, "0")) + "]}"); + }); + + // each row is "[1]" (3 bytes); 4 rows serialize to "[[1],[1],[1],[1]]" (17 bytes <= 20), 5 rows would be 21 + List> input = Collections.nCopies(10, List.of("1")); + invoker.invoke(function(List.of("integer"), "integer", 100, limit, 0), SESSION, REGION, "u", 1, input); + + ArgumentCaptor payloads = ArgumentCaptor.forClass(byte[].class); + verify(lambda, times(3)).invokeArn(eq(FUNCTION_ARN), payloads.capture(), any()); + for (byte[] payload : payloads.getAllValues()) { + String argumentsJson = JSON.readTree(payload).get("arguments").toString(); + assertThat((long) argumentsJson.getBytes(StandardCharsets.UTF_8).length, lessThanOrEqualTo(limit)); + } + } + + @Test + void anArnFunctionIsInvokedAsGiven() { + String arn = "arn:aws:lambda:us-east-1:000000000000:function:other:7"; + ExternalFunctionBinding function = new ExternalFunctionBinding(ACCOUNT, SESSION.clusterKey(), "dev", + "public", "f", List.of("integer"), "integer", "STABLE", arn, ROLE, 0, 10, 1024); + when(lambda.invokeArn(eq(arn), any(), any())).thenReturn( + ok("{\"success\":true,\"num_records\":1,\"results\":[5]}")); + + assertThat(invoker.invoke(function, SESSION, REGION, "u", 1, rows(new String[] {"1"})), equalTo(List.of("5"))); + } + + @Test + void noRowsMeansNoCall() { + assertThat(invoker.invoke(twoInts(), SESSION, REGION, "u", 1, List.of()), hasSize(0)); + + verify(lambda, never()).invokeArn(anyString(), any(), any()); + } + + @Test + void aRoleThatMayNotInvokeTheFunctionIsRefusedBeforeAnyCall() { + when(authorizer.refusal(eq(ROLE), eq(ACCOUNT), anyString(), isNull(), anyList())) + .thenReturn(Optional.of("The role does not allow lambda:InvokeFunction.")); + + SpectrumSqlException refused = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + + assertThat(refused.sqlState(), equalTo("42501")); + verify(lambda, never()).invokeArn(anyString(), any(), any()); + } + + @Test + void successFalseSurfacesTheErrorMessage() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn( + ok("{\"success\":false,\"error_msg\":\"my function is not working\"}")); + + SpectrumSqlException failed = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + + assertThat(failed.getMessage(), containsString("my function is not working")); + } + + @Test + void aFunctionErrorSurfacesTheRuntimeMessage() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn(new InvokeResult(200, "Unhandled", + "{\"errorMessage\":\"boom\",\"errorType\":\"Error\"}".getBytes(StandardCharsets.UTF_8), null, "r")); + + SpectrumSqlException failed = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + + assertThat(failed.getMessage(), containsString("boom")); + } + + @Test + void aTimedOutInvocationFailsTheCall() { + InvokeResult timedOut = ok(""); + timedOut.setTimedOut(true); + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn(timedOut); + + SpectrumSqlException failed = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + + assertThat(failed.getMessage(), containsString("timed out")); + } + + @Test + void aResponseWithTheWrongNumberOfResultsFailsTheCall() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn( + ok("{\"success\":true,\"num_records\":1,\"results\":[1]}")); + + SpectrumSqlException failed = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, + rows(new String[] {"1", "2"}, new String[] {"3", "4"}))); + + assertThat(failed.getMessage(), containsString("returned 1 results")); + } + + @Test + void aNumRecordsThatDisagreesWithTheRowsFailsEvenWhenTheResultsFit() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn( + ok("{\"success\":true,\"num_records\":5,\"results\":[1]}"), + ok("{\"success\":true,\"results\":[1]}"), + ok("{\"success\":true,\"num_records\":\"1\",\"results\":[1]}")); + + for (int attempt = 0; attempt < 3; attempt++) { + assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + } + } + + @Test + void successMustBeAJsonBoolean() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn( + ok("{\"success\":\"true\",\"num_records\":1,\"results\":[1]}"), + ok("{\"success\":1,\"num_records\":1,\"results\":[1]}")); + + for (int attempt = 0; attempt < 2; attempt++) { + assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + } + } + + @Test + void successFalseWithoutAnErrorMessageStillFails() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn(ok("{\"success\":false}")); + + SpectrumSqlException failed = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + + assertThat(failed.getMessage(), containsString("no error_msg")); + } + + @Test + void aResponseThatIsNotJsonOrHasNoResultsFailsTheCall() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn(ok("not json"), + ok("{\"success\":true,\"num_records\":1}")); + + SpectrumSqlException notJson = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + SpectrumSqlException noResults = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + + assertThat(notJson.getMessage(), containsString("not JSON")); + assertThat(noResults.getMessage(), containsString("no results array")); + } + + @Test + void aResponseThatIsNotAJsonObjectFailsTheCall() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn(ok("[]"), ok("")); + + for (int attempt = 0; attempt < 2; attempt++) { + assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + } + } + + @Test + void aFunctionErrorWithAnEmptyPayloadReportsTheErrorType() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())) + .thenReturn(new InvokeResult(200, "Unhandled", new byte[0], null, "r")); + + SpectrumSqlException failed = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + + assertThat(failed.getMessage(), containsString("Unhandled")); + } + + @Test + void aNumericResultKeepsEveryDigitThroughTheJsonParser() { + ExternalFunctionBinding function = function(List.of("integer"), "numeric(30,10)", 10, 1024, 0); + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn(ok( + "{\"success\":true,\"num_records\":2,\"results\":[12345678901234567890.1234567890,3.10]}")); + + List results = invoker.invoke(function, SESSION, REGION, "u", 1, + rows(new String[] {"1"}, new String[] {"2"})); + + assertThat(results, equalTo(List.of("12345678901234567890.1234567890", "3.10"))); + } + + @Test + void aRowWithTheWrongNumberOfValuesFailsBeforeAnyCall() { + assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1"}))); + assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2", "3"}))); + + verify(lambda, never()).invokeArn(anyString(), any(), any()); + } + + @Test + void anArgumentThatIsNotAValueOfItsTypeFailsBeforeAnyCall() { + SpectrumSqlException failed = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"abc", "2"}))); + + assertThat(failed.sqlState(), equalTo("22P02")); + verify(lambda, never()).invokeArn(anyString(), any(), any()); + } + + @Test + void aFunctionWithoutArgumentsGetsEmptyRecords() throws Exception { + ExternalFunctionBinding function = function(List.of(), "integer", 10, 1024, 0); + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn( + ok("{\"success\":true,\"num_records\":2,\"results\":[1,1]}")); + + invoker.invoke(function, SESSION, REGION, "u", 1, rows(new String[] {}, new String[] {})); + + assertThat(lastRequest().get("arguments").toString(), equalTo("[[],[]]")); + } + + @Test + void aFunctionGivenAsAccountFunctionNameIsInvokedInThatAccount() { + String arn = "arn:aws:lambda:us-east-1:111111111111:function:sum"; + ExternalFunctionBinding function = new ExternalFunctionBinding(ACCOUNT, SESSION.clusterKey(), "dev", + "public", "f", List.of("integer"), "integer", "STABLE", "111111111111:function:sum", ROLE, 0, 10, + 1024); + when(lambda.invokeArn(eq(arn), any(), any())).thenReturn( + ok("{\"success\":true,\"num_records\":1,\"results\":[5]}")); + + assertThat(invoker.invoke(function, SESSION, REGION, "u", 1, rows(new String[] {"1"})), equalTo(List.of("5"))); + verify(authorizer).refusal(eq(ROLE), eq(ACCOUNT), anyString(), isNull(), anyList()); + verify(roleAccess).refusal(eq(ROLE), eq("lambda:InvokeFunction"), eq(arn), eq("us-east-1"), any()); + } + + @Test + void aRoleTheFunctionsAccessPoliciesRefuseIsRefusedBeforeAnyCall() { + when(roleAccess.refusal(eq(ROLE), eq("lambda:InvokeFunction"), eq(FUNCTION_ARN), anyString(), any())) + .thenReturn(Optional.of("not authorized to perform: lambda:InvokeFunction")); + + SpectrumSqlException refused = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + + assertThat(refused.sqlState(), equalTo("42501")); + assertThat(refused.getMessage(), containsString("not authorized to perform: lambda:InvokeFunction")); + verify(lambda, never()).invokeArn(anyString(), any(), any()); + } + + @Test + void theFunctionsAccessPoliciesAreNotConsultedWhenEnforcementIsOff() { + when(config.services().iam().enforcementEnabled()).thenReturn(false); + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn( + ok("{\"success\":true,\"num_records\":1,\"results\":[5]}")); + + assertThat(invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"})), + equalTo(List.of("5"))); + verify(roleAccess, never()).refusal(anyString(), anyString(), anyString(), any(), any()); + } + + @Test + void aFunctionNameWithAQualifierIsAnArnOfThatVersion() { + String arn = "arn:aws:lambda:us-east-1:000000000000:function:sum:7"; + ExternalFunctionBinding function = new ExternalFunctionBinding(ACCOUNT, SESSION.clusterKey(), "dev", + "public", "f", List.of("integer"), "integer", "STABLE", "sum:7", ROLE, 0, 10, 1024); + when(lambda.invokeArn(eq(arn), any(), any())).thenReturn( + ok("{\"success\":true,\"num_records\":1,\"results\":[5]}")); + + assertThat(invoker.invoke(function, SESSION, REGION, "u", 1, rows(new String[] {"1"})), equalTo(List.of("5"))); + } + + @Test + void anArnThatIsNotALambdaFunctionFailsBeforeAnyCall() { + for (String reference : List.of("arn:foo", "arn:aws:sqs:us-east-1:000000000000:queue")) { + ExternalFunctionBinding function = new ExternalFunctionBinding(ACCOUNT, SESSION.clusterKey(), "dev", + "public", "f", List.of("integer"), "integer", "STABLE", reference, ROLE, 0, 10, 1024); + + assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(function, SESSION, REGION, "u", 1, rows(new String[] {"1"}))); + } + verify(lambda, never()).invokeArn(anyString(), any(), any()); + } + + @Test + void anUnexpectedFailureOfTheLambdaServiceIsAnSqlError() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenThrow(new IllegalStateException("executor down")); + + SpectrumSqlException failed = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + + assertThat(failed.getMessage(), containsString("executor down")); + } + + @Test + void aHugeRetryTimeoutDoesNotOverflowIntoNoRetry() { + AwsException throttled = new AwsException("TooManyRequestsException", "Rate Exceeded.", 429); + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenThrow(throttled).thenReturn( + ok("{\"success\":true,\"num_records\":1,\"results\":[3]}")); + + List results = invoker.invoke( + function(List.of("integer"), "integer", 10, 1024, Long.MAX_VALUE), SESSION, REGION, "u", 1, + rows(new String[] {"1"})); + + assertThat(results, equalTo(List.of("3"))); + } + + @Test + void aMistypedResultFailsTheCall() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenReturn( + ok("{\"success\":true,\"num_records\":1,\"results\":[\"three\"]}")); + + SpectrumSqlException failed = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + + assertThat(failed.sqlState(), equalTo("22P02")); + } + + @Test + void aThrottledCallIsRetriedWithGrowingPausesUntilItSucceeds() { + AwsException throttled = new AwsException("TooManyRequestsException", "Rate Exceeded.", 429); + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())).thenThrow(throttled, throttled).thenReturn( + ok("{\"success\":true,\"num_records\":1,\"results\":[3]}")); + + List results = invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"})); + + assertThat(results, equalTo(List.of("3"))); + assertThat(sleeps, equalTo(List.of(50L, 100L))); + } + + @Test + void aCallThatStaysThrottledFailsOnceTheRetryTimeoutIsSpent() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())) + .thenThrow(new AwsException("TooManyRequestsException", "Rate Exceeded.", 429)); + + SpectrumSqlException failed = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(function(List.of("integer"), "integer", 10, 1024, 300), SESSION, REGION, "u", 1, + rows(new String[] {"1"}))); + + assertThat(failed.getMessage(), containsString("throttled")); + // the last pause is cut to what is left of the 300 ms, and one more attempt follows it + assertThat(sleeps, equalTo(List.of(50L, 100L, 150L))); + verify(lambda, times(4)).invokeArn(anyString(), any(), any()); + } + + @Test + void aThrottledCallIsNotRetriedWithAZeroRetryTimeout() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())) + .thenThrow(new AwsException("TooManyRequestsException", "Rate Exceeded.", 429)); + + assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(function(List.of("integer"), "integer", 10, 1024, 0), SESSION, REGION, "u", 1, + rows(new String[] {"1"}))); + + assertThat(sleeps, hasSize(0)); + } + + @Test + void anotherLambdaErrorFailsTheCallWithoutRetry() { + when(lambda.invokeArn(eq(FUNCTION_ARN), any(), any())) + .thenThrow(new AwsException("ResourceNotFoundException", "Function not found", 404)); + + SpectrumSqlException failed = assertThrows(SpectrumSqlException.class, + () -> invoker.invoke(twoInts(), SESSION, REGION, "u", 1, rows(new String[] {"1", "2"}))); + + assertThat(failed.getMessage(), containsString("Function not found")); + assertThat(sleeps, hasSize(0)); + verify(lambda, times(1)).invokeArn(anyString(), any(), any()); + } +}