diff --git a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java index a7cfca4fbc..fea8776b35 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java @@ -5599,12 +5599,20 @@ public class AslExecutor { // reference path written there is resolved the same way every other argument is, // and a path that matches nothing fails the state instead of formatting as the // path string itself. - JsonNode templateArg = resolveIntrinsicArg(parts.get(0), root, context); - String template = templateArg.isTextual() ? templateArg.asText() : templateArg.toString(); + String templateExpression = parts.get(0).trim(); + boolean literalTemplate = templateExpression.startsWith("'") && templateExpression.endsWith("'"); + JsonNode templateArg = resolveIntrinsicArg(templateExpression, root, context); + String template = literalTemplate + ? templateExpression.substring(1, templateExpression.length() - 1) + : templateArg.isTextual() ? templateArg.asText() : templateArg.toString(); StringBuilder sb = new StringBuilder(); int argIdx = 1; for (int i = 0; i < template.length(); i++) { - if (i + 1 < template.length() && template.charAt(i) == '{' && template.charAt(i + 1) == '}') { + if (literalTemplate && template.charAt(i) == '\\' && i + 1 < template.length() + && isIntrinsicEscapedCharacter(template.charAt(i + 1))) { + sb.append(template.charAt(++i)); + } else if (i + 1 < template.length() && template.charAt(i) == '{' + && template.charAt(i + 1) == '}') { if (argIdx >= parts.size()) { throw new FailStateException("States.Runtime", "States.Format: not enough arguments"); } @@ -6089,7 +6097,8 @@ public class AslExecutor { return applyIntrinsic(arg, root, context); } if (arg.startsWith("'") && arg.endsWith("'")) { - return objectMapper.getNodeFactory().textNode(arg.substring(1, arg.length() - 1)); + return objectMapper.getNodeFactory().textNode( + unescapeIntrinsicLiteral(arg.substring(1, arg.length() - 1))); } if (arg.startsWith("\"") && arg.endsWith("\"")) { return objectMapper.getNodeFactory().textNode(arg.substring(1, arg.length() - 1)); @@ -6112,6 +6121,24 @@ public class AslExecutor { } } + private static String unescapeIntrinsicLiteral(String literal) { + StringBuilder value = new StringBuilder(literal.length()); + for (int i = 0; i < literal.length(); i++) { + char c = literal.charAt(i); + if (c == '\\' && i + 1 < literal.length() + && isIntrinsicEscapedCharacter(literal.charAt(i + 1))) { + value.append(literal.charAt(++i)); + } else { + value.append(c); + } + } + return value.toString(); + } + + private static boolean isIntrinsicEscapedCharacter(char c) { + return c == '\'' || c == '{' || c == '}' || c == '\\'; + } + /** * Resolves a {@code $.} or {@code $$.} reference used as an intrinsic argument. A reference * that matches nothing fails the execution, as on real AWS, instead of formatting as null. @@ -6157,12 +6184,18 @@ public class AslExecutor { int start = 0; for (int i = 0; i < argsStr.length(); i++) { char c = argsStr.charAt(i); - if (c == '\'' && !inDoubleQuote) inSingleQuote = !inSingleQuote; - else if (c == '"' && !inSingleQuote) inDoubleQuote = !inDoubleQuote; - else if (!inSingleQuote && !inDoubleQuote) { - if (c == '(') depth++; - else if (c == ')') depth--; - else if (c == ',' && depth == 0) { + if (c == '\\' && (inSingleQuote || inDoubleQuote) && i + 1 < argsStr.length()) { + i++; + } else if (c == '\'' && !inDoubleQuote) { + inSingleQuote = !inSingleQuote; + } else if (c == '"' && !inSingleQuote) { + inDoubleQuote = !inDoubleQuote; + } else if (!inSingleQuote && !inDoubleQuote) { + if (c == '(') { + depth++; + } else if (c == ')') { + depth--; + } else if (c == ',' && depth == 0) { result.add(argsStr.substring(start, i).trim()); start = i + 1; } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorIntrinsicEscapesTest.java b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorIntrinsicEscapesTest.java new file mode 100644 index 0000000000..9ee9195e0d --- /dev/null +++ b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorIntrinsicEscapesTest.java @@ -0,0 +1,69 @@ +package io.floci.aws.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class AslExecutorIntrinsicEscapesTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private AslExecutor executor; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + executor = AslExecutorFixture.builder() + .objectMapper(mapper) + .customResourceLiveness(null) + .build(); + } + + @Test + void escapedApostropheDoesNotEndTheFormatLiteral() throws Exception { + JsonNode input = mapper.readTree("{\"firstName\":\"Ann\",\"lastName\":\"Lee\"}"); + + JsonNode result = executor.resolvePath( + "States.Format('Welcome to {} {}\\'s playlist.', $.firstName, $.lastName)", input); + + assertEquals("Welcome to Ann Lee's playlist.", result.asText()); + } + + @Test + void escapedBracesAreLiteralTextNotPlaceholders() throws Exception { + JsonNode input = mapper.readTree("{\"name\":\"Ann\"}"); + + assertEquals("{ Ann }", executor.resolvePath( + "States.Format('\\{ {} \\}', $.name)", input).asText()); + assertEquals("{} Ann", executor.resolvePath( + "States.Format('\\{\\} {}', $.name)", input).asText()); + } + + @Test + void escapedApostropheAndBackslashWorkInOtherIntrinsics() { + JsonNode result = executor.resolvePath("States.Array('it\\'s', 'C:\\\\', 'x')", + mapper.createObjectNode()); + + assertEquals(3, result.size()); + assertEquals("it's", result.get(0).asText()); + assertEquals("C:\\", result.get(1).asText()); + assertEquals("x", result.get(2).asText()); + } + + @Test + void pathValuesAreNotDecodedAsIntrinsicLiterals() throws Exception { + JsonNode input = mapper.readTree("{\"value\":\"\\\\{\\\\}\\\\'\"}"); + + assertEquals("\\{\\}\\'", executor.resolvePath("States.Array($.value)", input).get(0).asText()); + } + + @Test + void unreservedBackslashSequenceKeepsItsExistingMeaning() throws Exception { + JsonNode input = mapper.readTree("{\"name\":\"Ann\"}"); + + assertEquals("a\\q", executor.resolvePath("States.Array('a\\q')", input).get(0).asText()); + assertEquals("\\q Ann", executor.resolvePath("States.Format('\\q {}', $.name)", input).asText()); + } +} diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsIntrinsicEscapesIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsIntrinsicEscapesIntegrationTest.java new file mode 100644 index 0000000000..a19fbc8e35 --- /dev/null +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsIntrinsicEscapesIntegrationTest.java @@ -0,0 +1,75 @@ +package io.floci.aws.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.sfn.SfnClient; +import software.amazon.awssdk.services.sfn.model.DescribeExecutionResponse; + +import java.net.URI; +import java.time.Duration; +import java.util.UUID; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +class StepFunctionsIntrinsicEscapesIntegrationTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void sdkExecutionDecodesIntrinsicLiterals() throws Exception { + ObjectNode parameters = MAPPER.createObjectNode(); + parameters.put("greeting.$", "States.Format('Welcome to {} {}\\'s playlist.', $.firstName, $.lastName)"); + parameters.put("braces.$", "States.Format('\\{ {} \\}', $.firstName)"); + parameters.put("array.$", "States.Array('it\\'s', 'C:\\\\')"); + ObjectNode pass = MAPPER.createObjectNode().put("Type", "Pass").put("End", true); + pass.set("Parameters", parameters); + ObjectNode states = MAPPER.createObjectNode(); + states.set("Format", pass); + ObjectNode definition = MAPPER.createObjectNode().put("StartAt", "Format"); + definition.set("States", states); + + try (SfnClient client = SfnClient.builder() + .endpointOverride(URI.create("http://localhost:" + RestAssured.port)) + .httpClientBuilder(UrlConnectionHttpClient.builder()) + .region(Region.US_EAST_1) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) + .build()) { + String arn = client.createStateMachine(request -> request.name("intrinsic-escapes-" + UUID.randomUUID()) + .roleArn("arn:aws:iam::000000000000:role/test-role") + .definition(definition.toString())).stateMachineArn(); + try { + String execution = client.startExecution(request -> request.stateMachineArn(arn) + .input("{\"firstName\":\"Ann\",\"lastName\":\"Lee\"}")) + .executionArn(); + await().atMost(Duration.ofSeconds(10)).until(() -> !"RUNNING".equals(client.describeExecution( + request -> request.executionArn(execution)).statusAsString())); + DescribeExecutionResponse result = client.describeExecution(request -> request.executionArn(execution)); + assertEquals("SUCCEEDED", result.statusAsString(), result.toString()); + JsonNode output = MAPPER.readTree(result.output()); + assertEquals("Welcome to Ann Lee's playlist.", output.path("greeting").asText()); + assertEquals("{ Ann }", output.path("braces").asText()); + assertEquals("it's", output.path("array").get(0).asText()); + assertEquals("C:\\", output.path("array").get(1).asText()); + } finally { + client.deleteStateMachine(request -> request.stateMachineArn(arn)); + } + } + } +}