Light, fluffy, and always free - The AWS Local Emulator alternative
feat(iot): evaluate the SQL subset of topic rules (#3021)
Mario Toffiad45c64545d44
diff --git a/docs/services/iot.md b/docs/services/iot.mdindex 74b4534033..fce6772ba8 100644--- a/docs/services/iot.md+++ b/docs/services/iot.md@@ -21,7 +21,7 @@ Current MVP 1 limitations:- The MQTT listener does not verify device certificates yet.- MQTT auth remains permissive; certificate and policy resources are modeled for provisioning compatibility, not enforced as broker authorization yet.-- Rules support basic topic filter extraction and action dispatch only; SQL projection, WHERE evaluation, and substitutions remain follow-up scope.+- Rules evaluate the SQL subset described under [Rule SQL](#rule-sql); substitution templates remain follow-up scope.## MVP 2 Coverage@@ -140,26 +140,92 @@ Phase 8 adds stored IoT topic rules and dispatches matching IoT publishes to rulSupported rule behavior:- `CreateTopicRule`, `GetTopicRule`, `ListTopicRules`, `EnableTopicRule`, `DisableTopicRule`, and `DeleteTopicRule` through AWS SDK-compatible IoT control-plane paths.-- SQL topic filter extraction for rules shaped like `SELECT * FROM 'topic/filter'`.+- Rule SQL parsing and evaluation for the subset described under [Rule SQL](#rule-sql): the `SELECT` projection,+ the `FROM` topic filter, and the `WHERE` predicate.- MQTT-style topic filter matching for exact topics, `+`, and terminal `#`.- IoT Data `Publish` and MQTT publishes use the same rule dispatch path.- Rule matching is region-scoped: an IoT Data `Publish` evaluates the rules of the region named by its SigV4 credential, and a rule's actions target the rule's own region.- Publishes that carry no region — MQTT, or an IoT Data `Publish` whose `Authorization` header is absent or not SigV4 — are evaluated against every region's rules.-- `republish` action republishes the original payload to another MQTT topic through `IotMqttBrokerService`.-- `sqs` action sends the original payload to an SQS queue through Floci's SQS service boundary.-- `sns` action publishes the original payload to an SNS topic through Floci's SNS service boundary.-- `s3` action writes the original payload to the configured bucket/key through Floci's S3 service boundary.-- `dynamoDBv2` action writes JSON object payload fields as DynamoDB attribute values through Floci's DynamoDB service boundary; nested objects and arrays become maps and lists.-- `kinesis` action puts the original payload into a Kinesis stream through Floci's Kinesis service boundary.+- Actions receive the projected document, which is the payload itself for a statement that selects only `*`.+- `republish` action republishes to another MQTT topic through `IotMqttBrokerService`.+- `sqs` action sends to an SQS queue through Floci's SQS service boundary.+- `sns` action publishes to an SNS topic through Floci's SNS service boundary.+- `s3` action writes to the configured bucket/key through Floci's S3 service boundary.+- `dynamoDBv2` action writes JSON object fields as DynamoDB attribute values through Floci's DynamoDB service boundary.+- `kinesis` action puts the document into a Kinesis stream through Floci's Kinesis service boundary.- `lambda` action invokes the configured function ARN through Floci's Lambda service boundary.-- `firehose` action puts the original payload into a Kinesis Data Firehose delivery stream through Floci's Firehose service boundary, with `separator` appended to each record; the separator must be `\n`, `\t`, `\r\n` or `,`, as the API model requires, or the rule is rejected with `InvalidRequestException`. With `batchMode`, a JSON array payload becomes one record per element.-- `cloudwatchLogs` action writes the original payload as a log event through Floci's CloudWatch Logs service boundary, into a log stream named after the rule that is created in `logGroupName` on first use. The log group must exist. With `batchMode`, a JSON array payload becomes one event per element, and each element supplies its own `timestamp` (epoch milliseconds) and `message`, as the AWS message format for batched device logs requires; an element without them is logged as its JSON text at publish time.+- `firehose` action puts the document into a Kinesis Data Firehose delivery stream through Floci's Firehose service boundary, with `separator` appended to each record; the separator must be `\n`, `\t`, `\r\n` or `,`, as the API model requires, or the rule is rejected with `InvalidRequestException`. With `batchMode`, a JSON array document becomes one record per element.+- `cloudwatchLogs` action writes the document as a log event through Floci's CloudWatch Logs service boundary, into a log stream named after the rule that is created in `logGroupName` on first use. The log group must exist. With `batchMode`, a JSON array document becomes one event per element, and each element supplies its own `timestamp` (epoch milliseconds) and `message`, as the AWS message format for batched device logs requires; an element without them is logged as its JSON text at publish time.- One failing action never fails the publish or the other actions of the rule. The failure is logged, and once every action ran the rule's `errorAction` receives the AWS failure document: `ruleName`, `topic`, `base64OriginalPayload` and `failures` with `failedAction`, `failedResource` and `errorMessage` per failed action.- `GetTopicRule` returns `awsIotSqlVersion` and `errorAction` as they were given to `CreateTopicRule` or `ReplaceTopicRule`.+### Rule SQL++A rule's statement is parsed once when it is created or replaced, and once on the first publish+for rules restored from storage. The grammar Floci understands is:++```+statement := SELECT item (',' item)* FROM '<topic filter>' [WHERE expr]+item := '*' | operand [AS identifier]+expr := term (OR term)*+term := factor (AND factor)*+factor := NOT factor | '(' expr ')' | operand [comparison operand]+comparison := '=' | '<>' | '!=' | '<' | '<=' | '>' | '>='+operand := path | literal | call+call := topic() | topic(<segment>) | startswith(operand, operand) | endswith(operand, operand)+path := identifier ('.' identifier)*+literal := 'string' | "string" | number | TRUE | FALSE | NULL+```++Semantics:++- Keywords and function names are case insensitive, field names are case sensitive.+- `topic()` is the full MQTT topic, `topic(n)` is its nth segment counting from 1.+- A select item without `AS` is written under the last segment of its path, or under the function+ name, so `topic()` becomes `topic`.+- When `*` is present, every payload field is copied first and the other select items are written+ over it. `SELECT *, topic() as topic` on a payload that already has a `topic` field therefore+ yields the MQTT topic, which is what AWS does.+- A select item whose value is undefined is left out of the document.+- A missing field, an out of range topic segment, and a function argument that cannot be converted+ are `Undefined`, as in AWS. It spreads: a comparison, `AND`, `OR` or `NOT` with an undefined+ operand is undefined, and a rule fires only when its `WHERE` is true. `endswith(clientToken, 'x')`+ therefore does not fire when the payload has no `clientToken`, and neither does+ `clientToken <> 'x'`.+- JSON `null` is a value, not `Undefined`: it equals only `NULL`, so `clientToken <> 'x'` is true+ when the field is null and undefined when it is missing.+- `=` and `<>` compare two numbers by value and anything else by type and value, so operands of+ different types are simply not equal: `level = '3'` is false and `level <> '3'` is true when+ `level` is the number 3. These follow the operator tables in the AWS IoT SQL reference.+- `<`, `<=`, `>` and `>=` convert both operands to a number. A string converts when it looks like+ one (`'10' > 9` is true); any other operand makes the comparison undefined.+- Payload numbers are read exactly, never through a double, so `9007199254740993.0`, `1e-400` and+ `0.30000000000000004` compare as written, at any size or precision, as AWS's Decimal does.+- `AND`, `OR` and `NOT` take booleans or the strings `'true'` and `'false'` in any case. Any other+ operand makes the result undefined.+- `startswith` and `endswith` convert numbers, booleans, arrays and objects to their string form+ first. A `null` or undefined argument makes the result undefined.+- String literals use single or double quotes, doubled to escape the quote itself.+- A statement that selects only `*` forwards the published bytes unchanged, so the payload does not+ have to be JSON when there is no `WHERE`. Any other statement needs a JSON object: a payload that+ is not one is logged at DEBUG and the rule does not fire.++Statements outside this grammar are not rejected. They are stored as sent and keep the behavior they+had before Floci evaluated rule SQL: the topic filter is read out of the statement and the rule fires+on every matching topic with the whole payload. Floci logs one WARN naming the rule and the token it+could not parse. Setting `floci.services.iot.rule-sql-strict` to `true`+(`FLOCI_SERVICES_IOT_RULE_SQL_STRICT`) makes `CreateTopicRule` and `ReplaceTopicRule` reject such a+statement with `SqlParseException` instead, the way AWS does. It is `false` by default.+Current limitations:-- SQL projection, WHERE clauses, functions, substitutions, and less common AWS IoT rule action types are follow-up scope.+- Not evaluated: `clientid()`, `timestamp()`, `accountid()`, `principal()`, `newuuid()`, `isNull()`,+ `isUndefined()`, `encode()`, `get_thing_shadow()`, arithmetic, array indexing, `IN`, `CASE`, and+ `${}` substitution templates in action fields. A rule using any of them takes the unparsed path+ described above.+- `awsIotSqlVersion` is stored and echoed back but not acted on. The versions differ in how+ `SELECT *` treats arrays, which Floci does not model.+- Less common AWS IoT rule action types are follow-up scope.Open follow-up scope for phase 7 unless explicitly deferred:diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 3f91080ed6..b79cedbd19 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -764,6 +764,14 @@ public interface EmulatorConfig {@WithDefault("true")boolean enabled();+ /**+ * Reject a topic rule whose SQL falls outside the subset Floci evaluates, as AWS does.+ * Off by default, so such a rule is stored and keeps firing on every matching topic+ * with the whole payload.+ */+ @WithDefault("false")+ boolean ruleSqlStrict();+MqttConfig mqtt();}diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.javaindex 915e39d0be..34144933bd 100644--- a/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotService.java@@ -25,6 +25,10 @@ import io.github.hectorvent.floci.services.iot.model.IotThingType;import io.github.hectorvent.floci.services.iot.model.IotTopicRule;import io.github.hectorvent.floci.services.acm.CertificateGenerator;import io.github.hectorvent.floci.services.iot.model.Thing;+import io.github.hectorvent.floci.services.iot.rules.RuleSql;+import io.github.hectorvent.floci.services.iot.rules.RuleSqlEvaluator;+import io.github.hectorvent.floci.services.iot.rules.RuleSqlParseException;+import io.github.hectorvent.floci.services.iot.rules.RuleSqlParser;import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;import io.github.hectorvent.floci.services.firehose.FirehoseService;import io.github.hectorvent.floci.services.firehose.model.Record;@@ -102,6 +106,7 @@ public class IotService {private final FirehoseService firehoseService;private final CloudWatchLogsService cloudWatchLogsService;private final FlociCertificateAuthority certificateAuthority;+ private final RuleSqlEvaluator ruleSqlEvaluator;@Injectpublic IotService(StorageFactory storageFactory,@@ -190,6 +195,7 @@ public class IotService {this.firehoseService = firehoseService;this.cloudWatchLogsService = cloudWatchLogsService;this.certificateAuthority = certificateAuthority;+ this.ruleSqlEvaluator = new RuleSqlEvaluator(objectMapper);}public String describeEndpoint(String endpointType) {@@ -990,6 +996,7 @@ public class IotService {validateAction(errorAction);rule.setErrorActionJson(errorAction.isObject() ? errorAction.toString() : null);rule.setCreatedAt(createdAt == null ? Instant.now() : createdAt);+ rule.setCompiledSql(compileSql(ruleName, rule.getSql(), config.services().iot().ruleSqlStrict()));topicRuleStore.put(topicRuleKey(region, ruleName), rule);return rule;}@@ -1006,6 +1013,26 @@ public class IotService {}}+ /**+ * Parses a rule's SQL. A statement outside the subset Floci evaluates is not rejected by+ * default: it is stored as it was sent and keeps the behaviour it had before this parser+ * existed, firing on every publish matching its topic filter with the whole payload.+ * Setting {@code floci.services.iot.rule-sql-strict} rejects it the way AWS does.+ */+ private RuleSql.Compilation compileSql(String ruleName, String sql, boolean strict) {+ try {+ return RuleSql.Compilation.of(RuleSqlParser.parse(sql));+ } catch (RuleSqlParseException e) {+ if (strict) {+ throw new AwsException("SqlParseException",+ "Invalid topic rule SQL for " + ruleName + ": " + e.getMessage(), 400);+ }+ LOG.warnv("Topic rule {0} is not evaluated: its SQL is outside the subset Floci understands ({1}). "+ + "It keeps firing on every matching topic with the whole payload.", ruleName, e.getMessage());+ return RuleSql.Compilation.PASSTHROUGH;+ }+ }+public IotTopicRule getTopicRule(String ruleName, String region) {return topicRuleStore.get(topicRuleKey(region, ruleName)).orElseThrow(() -> new AwsException("ResourceNotFoundException", "Topic rule not found: " + ruleName, 404));@@ -1036,12 +1063,43 @@ public class IotService {return;}for (IotTopicRule rule : rulesForPublish(region)) {- if (!rule.isRuleDisabled() && topicMatches(extractTopicPattern(rule.getSql()), topic)) {- executeTopicRule(rule, topic, eventPayload);+ if (!rule.isRuleDisabled()) {+ matchAndProject(rule, topic, eventPayload)+ .ifPresent(document -> executeTopicRule(rule, topic, eventPayload, document));}}}+ /**+ * Returns the document the rule's actions should receive, or empty when the rule does not+ * fire for this message. Rules whose SQL could not be parsed take the pre-parser path: the+ * topic filter is read straight out of the SQL and the payload is forwarded untouched.+ */+ private Optional<byte[]> matchAndProject(IotTopicRule rule, String topic, byte[] payload) {+ RuleSql query = ruleQuery(rule);+ if (query == null) {+ return topicMatches(extractTopicPattern(rule.getSql()), topic) ? Optional.of(payload) : Optional.empty();+ }+ if (!topicMatches(query.topicFilter(), topic)) {+ return Optional.empty();+ }+ return ruleSqlEvaluator.evaluate(rule.getRuleName(), query, topic, payload);+ }++ /**+ * The rule's parsed statement, or null when its SQL is outside the subset. A rule restored+ * from storage is parsed here on its first publish; one written through the API already+ * carries its parse.+ */+ private RuleSql ruleQuery(IotTopicRule rule) {+ RuleSql.Compilation compiled = rule.getCompiledSql();+ if (compiled == null) {+ compiled = compileSql(rule.getRuleName(), rule.getSql(), false);+ rule.setCompiledSql(compiled);+ }+ return compiled.query();+ }+private List<IotTopicRule> rulesForPublish(String region) {if (region != null) {return listTopicRules(region);@@ -1140,11 +1198,12 @@ public class IotService {}/**- * Runs the actions of a matching rule. One failing action never fails the publish or the actions- * after it, as on AWS: the failure is logged, and once every action ran the rule's error action,- * if it has one, receives the failure document listing every action that failed.+ * Runs the actions of a matching rule on the document its SQL produced. One failing action never+ * fails the publish or the actions after it, as on AWS: the failure is logged, and once every+ * action ran the rule's error action, if it has one, receives the failure document listing every+ * action that failed, with the original payload as published.*/- private void executeTopicRule(IotTopicRule rule, String topic, byte[] payload) {+ private void executeTopicRule(IotTopicRule rule, String topic, byte[] originalPayload, byte[] document) {String ruleRegion = AwsArnUtils.regionOrDefault(rule.getRuleArn(), config.defaultRegion());List<ObjectNode> failures = new ArrayList<>();for (JsonNode action : storedJson(rule.getRuleName(), rule.getActionsJson())) {@@ -1155,7 +1214,7 @@ public class IotService {}JsonNode config = action.get(type);try {- runAction(rule, type, config, payload, ruleRegion);+ runAction(rule, type, config, document, ruleRegion);} catch (RuntimeException e) {LOG.warnv(e, "Action {0} of topic rule {1} failed", type, rule.getRuleName());failures.add(failure(type, config, e));@@ -1171,7 +1230,7 @@ public class IotService {return;}try {- runAction(rule, type, errorAction.get(type), failureDocument(rule, topic, payload, failures), ruleRegion);+ runAction(rule, type, errorAction.get(type), failureDocument(rule, topic, originalPayload, failures), ruleRegion);} catch (RuntimeException e) {LOG.warnv(e, "Error action {0} of topic rule {1} failed", type, rule.getRuleName());}diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotTopicRule.java b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotTopicRule.javaindex 353b4a45d7..307fb59e37 100644--- a/src/main/java/io/github/hectorvent/floci/services/iot/model/IotTopicRule.java+++ b/src/main/java/io/github/hectorvent/floci/services/iot/model/IotTopicRule.java@@ -1,5 +1,7 @@package io.github.hectorvent.floci.services.iot.model;+import com.fasterxml.jackson.annotation.JsonIgnore;+import io.github.hectorvent.floci.services.iot.rules.RuleSql;import io.quarkus.runtime.annotations.RegisterForReflection;import java.time.Instant;@@ -11,6 +13,14 @@ public class IotTopicRule {private String ruleName;private String ruleArn;private String sql;++ /**+ * The parsed form of {@link #sql}, so a rule is parsed once instead of once per message.+ * The SQL string stays the source of truth, so this is never persisted and is rebuilt on+ * the first publish after a restart.+ */+ @JsonIgnore+ private transient volatile RuleSql.Compilation compiledSql;private String description;private boolean ruleDisabled;private String actionsJson = "[]";@@ -41,6 +51,15 @@ public class IotTopicRule {public void setSql(String sql) {this.sql = sql;+ this.compiledSql = null;+ }++ public RuleSql.Compilation getCompiledSql() {+ return compiledSql;+ }++ public void setCompiledSql(RuleSql.Compilation compiledSql) {+ this.compiledSql = compiledSql;}public String getDescription() {diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/rules/RuleSql.java b/src/main/java/io/github/hectorvent/floci/services/iot/rules/RuleSql.javanew file mode 100644index 0000000000..8d09b1b7a5--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/iot/rules/RuleSql.java@@ -0,0 +1,115 @@+package io.github.hectorvent.floci.services.iot.rules;++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.LongNode;+import com.fasterxml.jackson.databind.node.NullNode;+import com.fasterxml.jackson.databind.node.TextNode;++import java.math.BigDecimal;+import java.util.List;++/**+ * A parsed AWS IoT topic rule statement: the {@code SELECT} list, the {@code FROM} topic+ * filter, and the optional {@code WHERE} predicate. Produced by {@link RuleSqlParser} and+ * consumed by {@link RuleSqlEvaluator}.+ */+public record RuleSql(List<Projection> projections, String topicFilter, Expr where) {++ public RuleSql {+ projections = List.copyOf(projections);+ }++ /**+ * True when {@code *} is the only select item. Such a rule forwards the published bytes+ * unchanged instead of rebuilding a document, so the payload keeps its exact formatting+ * and, when there is no {@code WHERE}, does not have to be JSON at all.+ */+ public boolean isSelectAllOnly() {+ return projections.size() == 1 && projections.getFirst() instanceof SelectAll;+ }++ /**+ * The result of parsing a rule's SQL once. {@code query} is null when the statement is+ * outside the subset Floci evaluates. Such a rule keeps the behaviour it had before this+ * parser existed: it fires on every publish matching its topic filter and its actions+ * receive the whole payload.+ */+ public record Compilation(RuleSql query) {++ public static final Compilation PASSTHROUGH = new Compilation(null);++ public static Compilation of(RuleSql query) {+ return new Compilation(query);+ }+ }++ public sealed interface Projection permits SelectAll, Aliased {+ }++ /** The {@code *} select item: every field of the payload. */+ public record SelectAll() implements Projection {+ }++ /** A select item written under {@code alias} in the projected document. */+ public record Aliased(Expr expression, String alias) implements Projection {+ }++ public sealed interface Expr permits Path, Literal, Call, Comparison, Conjunction, Disjunction, Negation {+ }++ /** A dotted field path such as {@code state.reported.temperature}. */+ public record Path(List<String> segments) implements Expr {+ public Path {+ segments = List.copyOf(segments);+ }+ }++ public record Literal(JsonNode value) implements Expr {+ }++ /** A supported function call: {@code topic}, {@code startswith} or {@code endswith}. */+ public record Call(String function, List<Expr> arguments) implements Expr {+ public Call {+ arguments = List.copyOf(arguments);+ }+ }++ public record Comparison(Expr left, Operator operator, Expr right) implements Expr {+ }++ public record Conjunction(Expr left, Expr right) implements Expr {+ }++ public record Disjunction(Expr left, Expr right) implements Expr {+ }++ public record Negation(Expr operand) implements Expr {+ }++ public enum Operator {+ EQUAL, NOT_EQUAL, LESS, LESS_OR_EQUAL, GREATER, GREATER_OR_EQUAL+ }++ public static Literal text(String value) {+ return new Literal(TextNode.valueOf(value));+ }++ public static Literal number(long value) {+ return new Literal(LongNode.valueOf(value));+ }++ /** Kept as a {@code BigDecimal} so a literal a double cannot hold exactly still compares exactly. */+ public static Literal decimal(BigDecimal value) {+ return new Literal(DecimalNode.valueOf(value));+ }++ public static Literal bool(boolean value) {+ return new Literal(BooleanNode.valueOf(value));+ }++ public static Literal nullValue() {+ return new Literal(NullNode.getInstance());+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlEvaluator.javanew file mode 100644index 0000000000..4189295ad8--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlEvaluator.java@@ -0,0 +1,276 @@+package io.github.hectorvent.floci.services.iot.rules;++import com.fasterxml.jackson.databind.DeserializationFeature;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.ObjectReader;+import com.fasterxml.jackson.databind.node.BooleanNode;+import com.fasterxml.jackson.databind.node.JsonNodeFactory;+import com.fasterxml.jackson.databind.node.ObjectNode;+import com.fasterxml.jackson.databind.node.TextNode;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Aliased;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Call;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Comparison;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Conjunction;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Disjunction;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Expr;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Literal;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Negation;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Operator;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Path;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Projection;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.SelectAll;+import org.jboss.logging.Logger;++import java.io.IOException;+import java.math.BigDecimal;+import java.nio.charset.StandardCharsets;+import java.util.Optional;+import java.util.regex.Pattern;++/**+ * Evaluates a parsed topic rule statement against one published message, following the+ * operator and conversion tables of the AWS IoT SQL reference.+ *+ * <p>A value AWS reports as {@code Undefined} (a missing field, an out of range topic segment,+ * a function argument that cannot be converted) is a {@code null} {@link JsonNode}. It spreads:+ * a comparison, {@code AND}, {@code OR} or {@code NOT} with an undefined operand is undefined,+ * and a rule fires only when its {@code WHERE} is true. JSON {@code null} is not undefined: it+ * is a value that equals only itself.+ *+ * <p>Payload numbers are read as {@code BigDecimal}, never through a {@code double}, so they+ * compare exactly at any size or precision, as AWS's Decimal does.+ */+public final class RuleSqlEvaluator {++ private static final Logger LOG = Logger.getLogger(RuleSqlEvaluator.class);++ /** The string forms AWS converts to a number when an ordering operator meets a string. */+ private static final Pattern NUMERIC_STRING = Pattern.compile("-?\\d+(\\.\\d+)?([eE]-?\\d+)?");++ private final ObjectMapper objectMapper;+ private final ObjectReader payloadReader;++ public RuleSqlEvaluator(ObjectMapper objectMapper) {+ this.objectMapper = objectMapper;+ this.payloadReader = objectMapper.reader()+ .with(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)+ .with(JsonNodeFactory.withExactBigDecimals(true));+ }++ /**+ * Returns the document the rule's actions should receive, or empty when the rule does+ * not fire for this message.+ */+ public Optional<byte[]> evaluate(String ruleName, RuleSql query, String topic, byte[] payload) {+ byte[] message = payload == null ? new byte[0] : payload;+ if (query.isSelectAllOnly() && query.where() == null) {+ return Optional.of(message);+ }+ ObjectNode document = readObject(message);+ if (document == null) {+ LOG.debugv("Topic rule {0} skipped a payload that is not a JSON object on topic {1}", ruleName, topic);+ return Optional.empty();+ }+ if (query.where() != null && !Boolean.TRUE.equals(truth(value(query.where(), topic, document)))) {+ return Optional.empty();+ }+ return Optional.of(query.isSelectAllOnly() ? message : project(query, topic, document));+ }++ private ObjectNode readObject(byte[] payload) {+ if (payload.length == 0) {+ return null;+ }+ try {+ JsonNode document = payloadReader.readTree(payload);+ return document instanceof ObjectNode object ? object : null;+ } catch (IOException e) {+ LOG.debugv(e, "Topic rule payload is not JSON");+ return null;+ }+ }++ /**+ * Builds the projected document. Every payload field is copied first when {@code *} is+ * present, so a select item whose alias collides with a payload field overwrites it,+ * which is what AWS does for statements such as {@code SELECT *, topic() as topic}.+ */+ private byte[] project(RuleSql query, String topic, ObjectNode document) {+ ObjectNode projected = objectMapper.createObjectNode();+ if (query.projections().stream().anyMatch(SelectAll.class::isInstance)) {+ projected.setAll(document);+ }+ for (Projection projection : query.projections()) {+ if (projection instanceof Aliased aliased) {+ JsonNode value = value(aliased.expression(), topic, document);+ if (value != null) {+ projected.set(aliased.alias(), value);+ }+ }+ }+ return projected.toString().getBytes(StandardCharsets.UTF_8);+ }++ private JsonNode value(Expr expression, String topic, ObjectNode document) {+ return switch (expression) {+ case Literal literal -> literal.value();+ case Path path -> resolve(path, document);+ case Call call -> call(call, topic, document);+ case Comparison comparison -> compare(comparison, topic, document);+ case Conjunction conjunction -> booleanNode(and(+ truth(value(conjunction.left(), topic, document)),+ truth(value(conjunction.right(), topic, document))));+ case Disjunction disjunction -> booleanNode(or(+ truth(value(disjunction.left(), topic, document)),+ truth(value(disjunction.right(), topic, document))));+ case Negation negation -> {+ Boolean operand = truth(value(negation.operand(), topic, document));+ yield operand == null ? null : booleanNode(!operand);+ }+ };+ }++ private JsonNode resolve(Path path, ObjectNode document) {+ JsonNode current = document;+ for (String segment : path.segments()) {+ if (!(current instanceof ObjectNode object)) {+ return null;+ }+ current = object.get(segment);+ if (current == null) {+ return null;+ }+ }+ return current;+ }++ private JsonNode call(Call call, String topic, ObjectNode document) {+ if (call.function().equals("topic")) {+ if (call.arguments().isEmpty()) {+ return TextNode.valueOf(topic);+ }+ return call.arguments().getFirst() instanceof Literal position+ ? topicSegment(topic, position.value().asLong())+ : null;+ }+ String subject = text(value(call.arguments().get(0), topic, document));+ String argument = text(value(call.arguments().get(1), topic, document));+ if (subject == null || argument == null) {+ return null;+ }+ return booleanNode(call.function().equals("startswith")+ ? subject.startsWith(argument)+ : subject.endsWith(argument));+ }++ private JsonNode topicSegment(String topic, long position) {+ String[] segments = topic.split("/", -1);+ return position < 1 || position > segments.length ? null : TextNode.valueOf(segments[(int) position - 1]);+ }++ /**+ * AWS's standard conversion to String: numbers, booleans, arrays and objects convert,+ * {@code null} and Undefined do not.+ */+ private String text(JsonNode value) {+ if (value == null || value.isNull()) {+ return null;+ }+ if (value.isTextual()) {+ return value.textValue();+ }+ return value.isContainerNode() ? value.toString() : value.asText();+ }++ private JsonNode compare(Comparison comparison, String topic, ObjectNode document) {+ JsonNode left = value(comparison.left(), topic, document);+ JsonNode right = value(comparison.right(), topic, document);+ if (left == null || right == null) {+ return null;+ }+ Operator operator = comparison.operator();+ if (operator == Operator.EQUAL || operator == Operator.NOT_EQUAL) {+ return booleanNode(equal(left, right) == (operator == Operator.EQUAL));+ }+ BigDecimal leftNumber = decimal(left);+ BigDecimal rightNumber = decimal(right);+ return leftNumber == null || rightNumber == null+ ? null+ : booleanNode(matches(operator, leftNumber.compareTo(rightNumber)));+ }++ /**+ * AWS compares two numbers by value and everything else by type and value, so operands+ * of different types are simply not equal, and {@code null} equals only {@code null}.+ */+ private boolean equal(JsonNode left, JsonNode right) {+ if (left.isNumber() && right.isNumber()) {+ return left.decimalValue().compareTo(right.decimalValue()) == 0;+ }+ return left.getNodeType() == right.getNodeType() && left.equals(right);+ }++ /**+ * The ordering operators convert both operands to a number: numbers as they are, strings+ * when they look like a number, anything else is Undefined. A string whose exponent is+ * beyond what a BigDecimal can hold looks like a number but is not one either.+ */+ private BigDecimal decimal(JsonNode value) {+ if (value.isNumber()) {+ return value.decimalValue();+ }+ if (value.isTextual() && NUMERIC_STRING.matcher(value.textValue()).matches()) {+ try {+ return new BigDecimal(value.textValue());+ } catch (NumberFormatException e) {+ LOG.debugv("Numeric string {0} is out of range and evaluates as Undefined", value.textValue());+ return null;+ }+ }+ return null;+ }++ private boolean matches(Operator operator, int comparison) {+ return switch (operator) {+ case EQUAL -> comparison == 0;+ case NOT_EQUAL -> comparison != 0;+ case LESS -> comparison < 0;+ case LESS_OR_EQUAL -> comparison <= 0;+ case GREATER -> comparison > 0;+ case GREATER_OR_EQUAL -> comparison >= 0;+ };+ }++ /** AWS gives Undefined for {@code AND} and {@code OR} unless both operands convert to a boolean. */+ private Boolean and(Boolean left, Boolean right) {+ return left == null || right == null ? null : left && right;+ }++ private Boolean or(Boolean left, Boolean right) {+ return left == null || right == null ? null : left || right;+ }++ /** A boolean, or the strings {@code "true"} and {@code "false"} in any case; anything else is Undefined. */+ private Boolean truth(JsonNode value) {+ if (value == null) {+ return null;+ }+ if (value.isBoolean()) {+ return value.booleanValue();+ }+ if (value.isTextual()) {+ if (value.textValue().equalsIgnoreCase("true")) {+ return Boolean.TRUE;+ }+ if (value.textValue().equalsIgnoreCase("false")) {+ return Boolean.FALSE;+ }+ }+ return null;+ }++ private JsonNode booleanNode(Boolean value) {+ return value == null ? null : BooleanNode.valueOf(value);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlParseException.java b/src/main/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlParseException.javanew file mode 100644index 0000000000..e748e7ebcb--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlParseException.java@@ -0,0 +1,26 @@+package io.github.hectorvent.floci.services.iot.rules;++/**+ * Raised when a topic rule statement falls outside the SQL subset Floci evaluates. The+ * offending token and its zero-based offset in the statement are carried so callers can+ * name them in a warning or in an AWS {@code SqlParseException}.+ */+public class RuleSqlParseException extends RuntimeException {++ private final String token;+ private final int position;++ public RuleSqlParseException(String reason, String token, int position) {+ super(reason + ": '" + token + "' at position " + position);+ this.token = token;+ this.position = position;+ }++ public String token() {+ return token;+ }++ public int position() {+ return position;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlParser.java b/src/main/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlParser.javanew file mode 100644index 0000000000..0d58252357--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlParser.java@@ -0,0 +1,404 @@+package io.github.hectorvent.floci.services.iot.rules;++import io.github.hectorvent.floci.services.iot.rules.RuleSql.Aliased;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Call;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Comparison;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Conjunction;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Disjunction;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Expr;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Literal;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Negation;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Operator;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Path;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Projection;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.SelectAll;++import java.math.BigDecimal;+import java.util.ArrayList;+import java.util.List;+import java.util.Locale;+import java.util.Set;++/**+ * Recursive descent parser for the subset of the AWS IoT rules SQL dialect Floci evaluates:+ *+ * <pre>+ * statement := SELECT item (',' item)* FROM string [WHERE expr]+ * item := '*' | operand [AS identifier]+ * expr := term (OR term)*+ * term := factor (AND factor)*+ * factor := NOT factor | '(' expr ')' | operand [comparison operand]+ * comparison := '=' | '<>' | '!=' | '<' | '<=' | '>' | '>='+ * operand := path | literal | call+ * call := topic '(' [integer] ')' | (startswith | endswith) '(' operand ',' operand ')'+ * path := identifier ('.' identifier)*+ * literal := 'string' | "string" | number | TRUE | FALSE | NULL+ * </pre>+ *+ * Keywords and function names are case insensitive, field names are case sensitive, and anything+ * outside the grammar raises {@link RuleSqlParseException} naming the offending token.+ */+public final class RuleSqlParser {++ private static final Set<String> KEYWORDS =+ Set.of("SELECT", "FROM", "WHERE", "AS", "AND", "OR", "NOT", "TRUE", "FALSE", "NULL");++ /**+ * Bounds the work one statement can cost, counting real tokens only: {@link #tokenize} appends+ * an end marker. Real rules are a few dozen tokens, so this only stops a pathological statement+ * from driving the recursive descent, or the equally recursive evaluation of the tree it+ * produces, into a stack overflow.+ */+ private static final int MAX_TOKENS = 1000;++ private static final String TOPIC = "topic";+ private static final Set<String> STRING_PREDICATES = Set.of("startswith", "endswith");++ private final List<Token> tokens;+ private int index;++ private RuleSqlParser(List<Token> tokens) {+ this.tokens = tokens;+ }++ public static RuleSql parse(String sql) {+ if (sql == null || sql.isBlank()) {+ throw new RuleSqlParseException("Empty topic rule SQL statement", "", 0);+ }+ List<Token> tokens = tokenize(sql);+ if (tokens.size() - 1 > MAX_TOKENS) {+ Token beyondLimit = tokens.get(MAX_TOKENS);+ throw new RuleSqlParseException("Statement has more than " + MAX_TOKENS + " tokens",+ beyondLimit.text(), beyondLimit.position());+ }+ return new RuleSqlParser(tokens).statement();+ }++ private RuleSql statement() {+ expectKeyword("SELECT");+ List<Projection> projections = new ArrayList<>();+ projections.add(projection());+ while (matchSymbol(",")) {+ projections.add(projection());+ }+ expectKeyword("FROM");+ Token filter = peek();+ if (filter.kind() != Kind.STRING || filter.text().isBlank()) {+ throw fail("Expected a quoted topic filter after FROM", filter);+ }+ advance();+ Expr where = matchKeyword("WHERE") ? expression() : null;+ Token trailing = peek();+ if (trailing.kind() != Kind.END) {+ throw fail("Unsupported trailing input", trailing);+ }+ return new RuleSql(projections, filter.text(), where);+ }++ private Projection projection() {+ if (matchSymbol("*")) {+ return new SelectAll();+ }+ Token start = peek();+ Expr expression = operand();+ if (matchKeyword("AS")) {+ Token alias = peek();+ if (alias.kind() != Kind.IDENTIFIER) {+ throw fail("Expected an alias after AS", alias);+ }+ advance();+ return new Aliased(expression, alias.text());+ }+ return new Aliased(expression, defaultAlias(expression, start));+ }++ private String defaultAlias(Expr expression, Token start) {+ return switch (expression) {+ case Path path -> path.segments().getLast();+ case Call call -> call.function();+ default -> throw fail("Select item needs an AS alias", start);+ };+ }++ private Expr expression() {+ Expr left = term();+ while (matchKeyword("OR")) {+ left = new Disjunction(left, term());+ }+ return left;+ }++ private Expr term() {+ Expr left = factor();+ while (matchKeyword("AND")) {+ left = new Conjunction(left, factor());+ }+ return left;+ }++ private Expr factor() {+ if (matchKeyword("NOT")) {+ return new Negation(factor());+ }+ if (matchSymbol("(")) {+ Expr grouped = expression();+ expectSymbol(")");+ return grouped;+ }+ Expr left = operand();+ Operator operator = comparisonOperator();+ return operator == null ? left : new Comparison(left, operator, operand());+ }++ private Operator comparisonOperator() {+ Token token = peek();+ if (token.kind() != Kind.SYMBOL) {+ return null;+ }+ Operator operator = switch (token.text()) {+ case "=" -> Operator.EQUAL;+ case "<>", "!=" -> Operator.NOT_EQUAL;+ case "<" -> Operator.LESS;+ case "<=" -> Operator.LESS_OR_EQUAL;+ case ">" -> Operator.GREATER;+ case ">=" -> Operator.GREATER_OR_EQUAL;+ default -> null;+ };+ if (operator != null) {+ advance();+ }+ return operator;+ }++ private Expr operand() {+ Token token = peek();+ switch (token.kind()) {+ case STRING -> {+ advance();+ return RuleSql.text(token.text());+ }+ case NUMBER -> {+ advance();+ return numberLiteral(token);+ }+ case KEYWORD -> {+ String keyword = token.text().toUpperCase(Locale.ROOT);+ if (keyword.equals("TRUE") || keyword.equals("FALSE")) {+ advance();+ return RuleSql.bool(keyword.equals("TRUE"));+ }+ if (keyword.equals("NULL")) {+ advance();+ return RuleSql.nullValue();+ }+ throw fail("Unexpected keyword", token);+ }+ case IDENTIFIER -> {+ advance();+ return peekIsSymbol("(") ? call(token) : path(token);+ }+ default -> throw fail("Expected a field, literal or function", token);+ }+ }++ private Literal numberLiteral(Token token) {+ try {+ return token.text().indexOf('.') < 0+ ? RuleSql.number(Long.parseLong(token.text()))+ : RuleSql.decimal(new BigDecimal(token.text()));+ } catch (NumberFormatException e) {+ throw fail("Number is out of range", token);+ }+ }++ private Expr path(Token first) {+ List<String> segments = new ArrayList<>();+ segments.add(first.text());+ while (matchSymbol(".")) {+ Token segment = peek();+ if (segment.kind() != Kind.IDENTIFIER) {+ throw fail("Expected a field name after '.'", segment);+ }+ advance();+ segments.add(segment.text());+ }+ return new Path(segments);+ }++ private Expr call(Token name) {+ String function = name.text().toLowerCase(Locale.ROOT);+ if (!TOPIC.equals(function) && !STRING_PREDICATES.contains(function)) {+ throw fail("Unsupported function", name);+ }+ expectSymbol("(");+ List<Expr> arguments = new ArrayList<>();+ if (!peekIsSymbol(")")) {+ arguments.add(operand());+ while (matchSymbol(",")) {+ arguments.add(operand());+ }+ }+ expectSymbol(")");+ if (TOPIC.equals(function)) {+ validateTopicArguments(arguments, name);+ } else if (arguments.size() != 2) {+ throw fail("Function " + name.text() + " takes two arguments", name);+ }+ return new Call(function, arguments);+ }++ private void validateTopicArguments(List<Expr> arguments, Token name) {+ if (arguments.isEmpty()) {+ return;+ }+ if (arguments.size() != 1+ || !(arguments.getFirst() instanceof Literal literal)+ || !literal.value().isIntegralNumber()+ || literal.value().asLong() < 1) {+ throw fail("topic() takes no argument or a segment number starting at 1", name);+ }+ }++ private Token peek() {+ return tokens.get(index);+ }++ private void advance() {+ if (peek().kind() != Kind.END) {+ index++;+ }+ }++ private boolean peekIsSymbol(String symbol) {+ return peek().kind() == Kind.SYMBOL && peek().text().equals(symbol);+ }++ private boolean matchSymbol(String symbol) {+ if (!peekIsSymbol(symbol)) {+ return false;+ }+ advance();+ return true;+ }++ private void expectSymbol(String symbol) {+ if (!matchSymbol(symbol)) {+ throw fail("Expected '" + symbol + "'", peek());+ }+ }++ private boolean matchKeyword(String keyword) {+ if (peek().kind() != Kind.KEYWORD || !peek().text().equalsIgnoreCase(keyword)) {+ return false;+ }+ advance();+ return true;+ }++ private void expectKeyword(String keyword) {+ if (!matchKeyword(keyword)) {+ throw fail("Expected " + keyword, peek());+ }+ }++ private RuleSqlParseException fail(String reason, Token token) {+ return new RuleSqlParseException(reason, token.text(), token.position());+ }++ private static List<Token> tokenize(String sql) {+ List<Token> tokens = new ArrayList<>();+ int i = 0;+ while (i < sql.length()) {+ char c = sql.charAt(i);+ if (Character.isWhitespace(c)) {+ i++;+ } else if (c == '\'' || c == '"') {+ i = readString(sql, i, tokens);+ } else if (isNumberStart(sql, i)) {+ i = readNumber(sql, i, tokens);+ } else if (Character.isLetter(c) || c == '_') {+ i = readWord(sql, i, tokens);+ } else {+ i = readSymbol(sql, i, tokens);+ }+ }+ tokens.add(new Token(Kind.END, "", sql.length()));+ return tokens;+ }++ private static boolean isNumberStart(String sql, int i) {+ char c = sql.charAt(i);+ return Character.isDigit(c) || (c == '-' && i + 1 < sql.length() && Character.isDigit(sql.charAt(i + 1)));+ }++ /** A string in single or double quotes, as AWS's own examples use both; the quote is doubled to escape it. */+ private static int readString(String sql, int start, List<Token> tokens) {+ char quote = sql.charAt(start);+ StringBuilder value = new StringBuilder();+ int i = start + 1;+ while (i < sql.length()) {+ char c = sql.charAt(i);+ if (c != quote) {+ value.append(c);+ i++;+ } else if (i + 1 < sql.length() && sql.charAt(i + 1) == quote) {+ value.append(quote);+ i += 2;+ } else {+ tokens.add(new Token(Kind.STRING, value.toString(), start));+ return i + 1;+ }+ }+ throw new RuleSqlParseException("Unterminated string literal", String.valueOf(quote), start);+ }++ private static int readNumber(String sql, int start, List<Token> tokens) {+ int i = start + 1;+ boolean decimalPoint = false;+ while (i < sql.length()) {+ char c = sql.charAt(i);+ if (Character.isDigit(c)) {+ i++;+ } else if (c == '.' && !decimalPoint && i + 1 < sql.length() && Character.isDigit(sql.charAt(i + 1))) {+ decimalPoint = true;+ i++;+ } else {+ break;+ }+ }+ tokens.add(new Token(Kind.NUMBER, sql.substring(start, i), start));+ return i;+ }++ private static int readWord(String sql, int start, List<Token> tokens) {+ int i = start;+ while (i < sql.length() && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '_')) {+ i++;+ }+ String word = sql.substring(start, i);+ Kind kind = KEYWORDS.contains(word.toUpperCase(Locale.ROOT)) ? Kind.KEYWORD : Kind.IDENTIFIER;+ tokens.add(new Token(kind, word, start));+ return i;+ }++ private static int readSymbol(String sql, int start, List<Token> tokens) {+ String two = start + 1 < sql.length() ? sql.substring(start, start + 2) : "";+ if (two.equals("<>") || two.equals("<=") || two.equals(">=") || two.equals("!=")) {+ tokens.add(new Token(Kind.SYMBOL, two, start));+ return start + 2;+ }+ String one = sql.substring(start, start + 1);+ if (!",.()*=<>".contains(one)) {+ throw new RuleSqlParseException("Unsupported character", one, start);+ }+ tokens.add(new Token(Kind.SYMBOL, one, start));+ return start + 1;+ }++ private enum Kind {+ IDENTIFIER, KEYWORD, STRING, NUMBER, SYMBOL, END+ }++ private record Token(Kind kind, String text, int position) {+ }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex ce96b52888..d80ca3d539 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -585,6 +585,7 @@ floci:enabled: trueiot:enabled: true+ rule-sql-strict: falsemqtt:enabled: trueauto-start: falsediff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.javaindex 1b488500da..75d216fda8 100644--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotServiceTest.java@@ -43,6 +43,7 @@ import static org.mockito.ArgumentMatchers.anyInt;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;import static org.mockito.Mockito.times;@@ -74,8 +75,9 @@ class IotServiceTest {@BeforeEachvoid setUp() {- EmulatorConfig config = mock(EmulatorConfig.class);+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);when(config.defaultRegion()).thenReturn(REGION);+ when(config.services().iot().ruleSqlStrict()).thenReturn(false);service = new IotService(AccountAwareStorageBackend.inMemory(ACCOUNT),AccountAwareStorageBackend.inMemory(ACCOUNT),diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotTopicRuleSqlIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotTopicRuleSqlIntegrationTest.javanew file mode 100644index 0000000000..550f71bd95--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotTopicRuleSqlIntegrationTest.java@@ -0,0 +1,204 @@+package io.github.hectorvent.floci.services.iot;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.iot.model.IotTopicRule;+import io.github.hectorvent.floci.services.iot.rules.RuleSql;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;++import java.nio.charset.StandardCharsets;+import java.util.List;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertTrue;++@QuarkusTest+class IotTopicRuleSqlIntegrationTest {++ private static final String REGION = "us-east-1";++ @Inject+ IotService iotService;++ @Inject+ IotPublishEventRecorder eventRecorder;++ @Inject+ ObjectMapper objectMapper;++ @BeforeEach+ void clearEvents() {+ eventRecorder.clear();+ }++ @Test+ void aWhereClauseFiltersPublishesAndTheProjectionReachesTheAction() {+ createRule("sqlWhereRule", "SELECT *, topic() as topic FROM 'sqltest/where/+/update' "+ + "WHERE endswith(clientToken, ':inbound')", "sqltest/where-out");++ publish("sqltest/where/a/update", "{\"clientToken\":\"job:inbound\",\"topic\":\"stale\"}");+ publish("sqltest/where/b/update", "{\"clientToken\":\"job:outbound\"}");++ assertEquals(List.of("{\"clientToken\":\"job:inbound\",\"topic\":\"sqltest/where/a/update\"}"),+ republished("sqltest/where-out"));+ }++ @Test+ void aStatementOutsideTheSubsetKeepsFiringWithTheWholePayload() {+ createRule("sqlPassthroughRule", "SELECT clientid() as client FROM 'sqltest/passthrough/+'",+ "sqltest/passthrough-out");++ publish("sqltest/passthrough/a", "{\"any\":1}");++ assertEquals(List.of("{\"any\":1}"), republished("sqltest/passthrough-out"));+ }++ @Test+ void selectAllForwardsNonJsonBytesUnchanged() {+ createRule("sqlSelectAllRule", "SELECT * FROM 'sqltest/selectall/+'", "sqltest/selectall-out");++ publish("sqltest/selectall/a", "plain text");++ assertEquals(List.of("plain text"), republished("sqltest/selectall-out"));+ }++ @Test+ void aProjectingStatementSkipsANonJsonPayload() {+ createRule("sqlNonJsonRule", "SELECT *, topic() as topic FROM 'sqltest/nonjson/+'", "sqltest/nonjson-out");++ publish("sqltest/nonjson/a", "plain text");++ assertTrue(republished("sqltest/nonjson-out").isEmpty());+ }++ @Test+ void aStatementIsParsedOnceAndReusedAcrossPublishes() {+ createRule("sqlParseOnceRule", "SELECT *, topic() as topic FROM 'sqltest/parseonce/+'",+ "sqltest/parseonce-out");+ RuleSql parsed = compiledQuery("sqlParseOnceRule");+ assertNotNull(parsed);++ publish("sqltest/parseonce/a", "{\"v\":1}");+ publish("sqltest/parseonce/a", "{\"v\":2}");++ assertEquals(2, republished("sqltest/parseonce-out").size());+ assertSame(parsed, compiledQuery("sqlParseOnceRule"));+ }++ @Test+ void aRuleLoadedFromStorageIsParsedOnItsFirstPublish() {+ createRule("sqlLazyRule", "SELECT * FROM 'sqltest/lazy/+' WHERE endswith(clientToken, 'inbound')",+ "sqltest/lazy-out");+ IotTopicRule stored = iotService.getTopicRule("sqlLazyRule", REGION);+ stored.setCompiledSql(null);++ publish("sqltest/lazy/a", "{\"clientToken\":\"job:outbound\"}");++ assertTrue(republished("sqltest/lazy-out").isEmpty());+ assertNotNull(compiledQuery("sqlLazyRule"));+ }++ @Test+ void replacingARuleReplacesItsParsedStatement() {+ createRule("sqlReplaceRule", "SELECT * FROM 'sqltest/replace/+' WHERE endswith(clientToken, 'one')",+ "sqltest/replace-out");+ publish("sqltest/replace/a", "{\"clientToken\":\"one\"}");+ assertEquals(1, republished("sqltest/replace-out").size());++ iotService.replaceTopicRule("sqlReplaceRule",+ rulePayload("SELECT * FROM 'sqltest/replace/+' WHERE endswith(clientToken, 'two')",+ "sqltest/replace-out"), REGION);++ publish("sqltest/replace/a", "{\"clientToken\":\"one\"}");+ assertEquals(1, republished("sqltest/replace-out").size());++ publish("sqltest/replace/a", "{\"clientToken\":\"two\"}");+ assertEquals(2, republished("sqltest/replace-out").size());+ }++ @Test+ void disablingAndEnablingARuleKeepsItsParsedStatement() {+ createRule("sqlToggleRule", "SELECT *, topic() as topic FROM 'sqltest/toggle/+'", "sqltest/toggle-out");+ RuleSql parsed = compiledQuery("sqlToggleRule");++ iotService.setTopicRuleEnabled("sqlToggleRule", false, REGION);+ publish("sqltest/toggle/a", "{\"v\":1}");+ assertTrue(republished("sqltest/toggle-out").isEmpty());++ iotService.setTopicRuleEnabled("sqlToggleRule", true, REGION);+ publish("sqltest/toggle/a", "{\"v\":1}");++ assertEquals(1, republished("sqltest/toggle-out").size());+ assertSame(parsed, compiledQuery("sqlToggleRule"));+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "SELECT *, topic() as topic FROM '$aws/things/+/shadow/name/building/update/accepted' WHERE endswith(clientToken, 'inbound') | $aws/things/sensor-1/shadow/name/building/update/accepted | {\"clientToken\":\"job:inbound\"} | true",+ "SELECT *, topic() as topic FROM '$aws/things/+/shadow/name/building/update/accepted' WHERE endswith(clientToken, 'inbound') | $aws/things/sensor-1/shadow/name/building/update/accepted | {\"clientToken\":\"job:outbound\"} | false",+ "SELECT *, topic() as topic FROM '$aws/things/+/shadow/name/building/update/accepted' WHERE endswith(clientToken, 'inbound') | $aws/things/sensor-1/shadow/name/other/update/accepted | {\"clientToken\":\"job:inbound\"} | false",+ "SELECT *, topic(3) AS thingId FROM 'prod/fleet/+/ingest_v1' | prod/fleet/sensor-1/ingest_v1 | {\"v\":1} | true",+ "SELECT *, topic(3) AS thingId FROM 'prod/fleet/+/ingest_v1' | prod/fleet/sensor-1/metrics_v1 | {\"v\":1} | false",+ "SELECT * FROM '$aws/events/presence/connected/+' WHERE startswith(clientId, 'gw-') | $aws/events/presence/connected/gw-1 | {\"clientId\":\"gw-1\"} | true",+ "SELECT * FROM '$aws/events/presence/connected/+' WHERE startswith(clientId, 'gw-') | $aws/events/presence/connected/other | {\"clientId\":\"other\"} | false",+ "SELECT * FROM 'plant/+/events' WHERE endswith(clientToken, ':ingest:inbound') OR (endswith(clientToken, ':events:outbound') AND startswith(clientToken, 'gateway:')) | plant/a/events | {\"clientToken\":\"gateway:x:events:outbound\"} | true",+ "SELECT * FROM 'plant/+/events' WHERE endswith(clientToken, ':ingest:inbound') OR (endswith(clientToken, ':events:outbound') AND startswith(clientToken, 'gateway:')) | plant/a/events | {\"clientToken\":\"other:x:events:outbound\"} | false"+ })+ void evaluatesRuleStatementsAgainstTopicsAndPayloads(String sql, String topic, String payload, boolean fires) {+ String target = "sqltest/table-out";+ iotService.createTopicRule("sqlTableRule", rulePayload(sql, target), REGION);+ try {+ publish(topic, payload);++ assertEquals(fires, !republished(target).isEmpty());+ } finally {+ iotService.deleteTopicRule("sqlTableRule", REGION);+ }+ }++ private void createRule(String ruleName, String sql, String targetTopic) {+ iotService.createTopicRule(ruleName, rulePayload(sql, targetTopic), REGION);+ }++ private JsonNode rulePayload(String sql, String targetTopic) {+ try {+ return objectMapper.readTree("""+ {+ "sql": %s,+ "actions": [+ {+ "republish": {+ "roleArn": "arn:aws:iam::000000000000:role/iot-rule-role",+ "topic": "%s"+ }+ }+ ]+ }+ """.formatted(objectMapper.writeValueAsString(sql), targetTopic));+ } catch (Exception e) {+ throw new IllegalStateException("Could not build the topic rule payload", e);+ }+ }++ private void publish(String topic, String payload) {+ iotService.handlePublish(topic, payload.getBytes(StandardCharsets.UTF_8), true, REGION);+ }++ private List<String> republished(String targetTopic) {+ return eventRecorder.recentEvents().stream()+ .filter(event -> targetTopic.equals(event.topic()))+ .map(event -> new String(event.payload(), StandardCharsets.UTF_8))+ .toList();+ }++ private RuleSql compiledQuery(String ruleName) {+ return iotService.getTopicRule(ruleName, REGION).getCompiledSql().query();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotTopicRuleSqlStrictIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotTopicRuleSqlStrictIntegrationTest.javanew file mode 100644index 0000000000..0147b3a583--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotTopicRuleSqlStrictIntegrationTest.java@@ -0,0 +1,66 @@+package io.github.hectorvent.floci.services.iot;++import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import org.junit.jupiter.api.Test;++import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;++@QuarkusTest+@TestProfile(IotTopicRuleSqlStrictIntegrationTest.StrictRuleSqlProfile.class)+class IotTopicRuleSqlStrictIntegrationTest {++ @Test+ void strictModeRejectsAStatementOutsideTheSubset() {+ given()+ .contentType("application/json")+ .body(rule("SELECT clientid() as client FROM 'strict/rules/+'"))+ .when()+ .put("/rules/strictRejectedRule")+ .then()+ .statusCode(400)+ .body("__type", equalTo("SqlParseException"))+ .body("message", containsString("clientid"));+ }++ @Test+ void strictModeAcceptsAStatementInsideTheSubset() {+ given()+ .contentType("application/json")+ .body(rule("SELECT *, topic() as topic FROM 'strict/rules/+' WHERE endswith(clientToken, 'inbound')"))+ .when()+ .put("/rules/strictAcceptedRule")+ .then()+ .statusCode(200);+ }++ private String rule(String sql) {+ return """+ {+ "topicRulePayload": {+ "sql": "%s",+ "actions": [+ {+ "republish": {+ "roleArn": "arn:aws:iam::000000000000:role/iot-rule-role",+ "topic": "strict/rules-out"+ }+ }+ ]+ }+ }+ """.formatted(sql);+ }++ public static final class StrictRuleSqlProfile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of("floci.services.iot.rule-sql-strict", "true");+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/model/IotTopicRuleTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/model/IotTopicRuleTest.javanew file mode 100644index 0000000000..556a677b0c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iot/model/IotTopicRuleTest.java@@ -0,0 +1,40 @@+package io.github.hectorvent.floci.services.iot.model;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.iot.rules.RuleSql;+import io.github.hectorvent.floci.services.iot.rules.RuleSqlParser;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;++class IotTopicRuleTest {++ private final ObjectMapper objectMapper = new ObjectMapper();++ @Test+ void theParsedStatementIsNeverPersisted() throws Exception {+ IotTopicRule rule = new IotTopicRule();+ rule.setRuleName("persistenceRule");+ rule.setSql("SELECT * FROM 'a/b'");+ rule.setCompiledSql(RuleSql.Compilation.of(RuleSqlParser.parse(rule.getSql())));++ String json = objectMapper.writeValueAsString(rule);++ assertFalse(json.contains("compiledSql"), json);+ assertNull(objectMapper.readValue(json, IotTopicRule.class).getCompiledSql());+ }++ @Test+ void changingTheSqlDropsTheParsedStatement() {+ IotTopicRule rule = new IotTopicRule();+ rule.setSql("SELECT * FROM 'a/b'");+ rule.setCompiledSql(RuleSql.Compilation.of(RuleSqlParser.parse(rule.getSql())));+ assertNotNull(rule.getCompiledSql());++ rule.setSql("SELECT * FROM 'c/d'");++ assertNull(rule.getCompiledSql());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlCorpusTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlCorpusTest.javanew file mode 100644index 0000000000..45a85002ec--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlCorpusTest.java@@ -0,0 +1,115 @@+package io.github.hectorvent.floci.services.iot.rules;++import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import org.junit.jupiter.params.provider.ValueSource;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;++/**+ * Real statements, mostly lifted from the AWS IoT SQL reference, sorted into the two things the+ * parser may do with them. A statement inside the subset must parse. A statement outside it+ * must fail naming the first thing that could not be placed, never anything else, because+ * that failure is what sends the rule down the unparsed path and into the WARN log. The+ * tokenizer runs before the parser, so a character outside the grammar (an arithmetic sign,+ * an unquoted slash) is named ahead of any token the parser would have stumbled on.+ *+ * <p>When a construct is implemented, move its rows from the second test to the first.+ */+class RuleSqlCorpusTest {++ @ParameterizedTest+ @ValueSource(strings = {+ "SELECT * FROM 'topic/subtopic'",+ "SELECT color FROM 'topic/subtopic'",+ "SELECT color AS my_color FROM 'topic/subtopic'",+ "SELECT color as my_color, temperature as fahrenheit FROM 'topic/subtopic'",+ "SELECT *, 15 as speed FROM 'topic/subtopic'",+ "SELECT color.red as red_value FROM 'topic/subtopic'",+ "SELECT color AS rgb FROM 'topic/subtopic' WHERE temperature > 50",+ "SELECT color AS my_color FROM 'topic/subtopic' WHERE temperature > 50 AND color <> 'red'",+ "SELECT foo.bar AS baz FROM 'topic/subtopic'",+ "SELECT NULL AS n FROM 'topic/subtopic'",+ "SELECT topic(3) AS device_id FROM 'devices/+/data'",+ "SELECT *, topic() as topic FROM '$aws/things/+/shadow/name/building/update/accepted' WHERE endswith(clientToken, 'inbound')",+ "SELECT *, topic(3) AS thingId FROM 'prod/fleet/+/ingest_v1'",+ "SELECT * FROM '$aws/events/presence/connected/+' WHERE startswith(clientId, 'gw-')",+ "SELECT * FROM '$aws/events/presence/disconnected/+' WHERE startswith(clientId, 'gw-')",+ "SELECT state.reported.temperature AS temp FROM '$aws/things/+/shadow/update/accepted' WHERE state.reported.temperature >= 30",+ "SELECT * FROM 'a/b' WHERE NOT active = FALSE",+ "SELECT * FROM 'a/b' WHERE (size > 10 OR weight <= 2.5) AND color = 'red'",+ "SELECT * FROM 'a/b' WHERE flag = TRUE AND level != 0",+ "SELECT * FROM 'a/b' WHERE endswith(clientToken, ':ingest:inbound') OR (endswith(clientToken, ':events:outbound') AND startswith(clientToken, 'gateway:'))",+ "SELECT * FROM 'a/#'",+ "SELECT * FROM '+'",+ "SELECT * FROM '#'",+ "SELECT * FROM 'a/+/b/+'",+ "select * from 'a/b' where x = 'y'",+ "SELECT * FROM \"topic/subtopic\" WHERE startswith(\"ranger\", \"ran\")",+ "SELECT * FROM 'topic/subtopic' WHERE startswith(topic(), 'topic') AND endswith(topic(2), 'topic')",+ "SELECT * FROM 'a/b' WHERE temperature > -10 AND temperature < 100.5",+ "SELECT * FROM 'a/b' WHERE name = 'o''brien'",+ "SELECT *\n FROM 'topic/subtopic'\n WHERE temperature > 50\n AND color <> 'red'"+ })+ void aStatementInsideTheSubsetParses(String sql) {+ assertNotNull(RuleSqlParser.parse(sql));+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ // AWS syntax outside the subset today. Each row moves up when its construct lands.+ "SELECT (temperature - 32) * 5 / 9 AS celsius, upper(color) as my_color FROM 'topic/subtopic' | -",+ "SELECT temperature * 1.8 + 32 AS f FROM 'a/b' | +",+ "SELECT VALUE color FROM 'topic/subtopic' | color",+ "SELECT {'latitude': get(lat_long, 0)} as lat_long FROM 'topic/subtopic' | {",+ "SELECT [lat,long] as lat_long FROM 'topic/subtopic' | [",+ "SELECT * FROM 'a/b' WHERE 3 IN arr | IN",+ "SELECT * FROM 'a/b' WHERE exists (select * from arr as a where a = 3) | exists",+ "SELECT clientid() AS client FROM 'a/b' | clientid",+ "SELECT *, timestamp() AS ts FROM 'a/b' | timestamp",+ "SELECT *, accountid() AS account FROM 'a/b' | accountid",+ "SELECT newuuid() AS id FROM 'a/b' | newuuid",+ "SELECT principal() AS p FROM 'a/b' | principal",+ "SELECT * FROM 'a/b' WHERE traceid() <> '' | traceid",+ "SELECT * FROM 'a/b' WHERE isUndefined(x) | isUndefined",+ "SELECT * FROM 'a/b' WHERE isNull(x) | isNull",+ "SELECT get(get(get(mydata,\"item2\"),\"0\"),\"my-key\") FROM 'iot/rules' | get",+ "SELECT temp, md5(deviceid) AS hashed_id FROM 'topic/#' | md5",+ "SELECT encode(*, 'base64') AS data FROM 'a/b' | encode",+ "SELECT lower(color) AS c FROM 'a/b' | lower",+ "SELECT * FROM 'a/b' WHERE length(name) > 3 | length",+ "SELECT * FROM 'a/b' WHERE regexp_matches(x, '^a') | regexp_matches",+ "SELECT * FROM 'a/b' WHERE cast(x AS Int) = 1 | cast",+ "SELECT sql_version() AS v FROM 'a/b' | sql_version",+ "SELECT get_thing_shadow('t', 'arn') FROM 'a/b' | get_thing_shadow",+ "SELECT CASE temperature WHEN 0 THEN 'cold' ELSE 'warm' END AS label FROM 'a/b' | temperature",+ "SET t = temperature SELECT t FROM 'a/b' | SET",+ "SELECT foo.bar AS bar.baz FROM 'topic/subtopic' | .",+ "SELECT a.b[0] FROM 'a/b' | [",+ "SELECT * FROM topic/subtopic | /",+ "SELECT * FROM 'a/b' WHERE x = -y | -",+ // Not AWS syntax either. It must fail the same way rather than silently parse.+ "SELECT * FROM 'a/b' WHERE x LIKE 'a%' | LIKE",+ "SELECT * FROM 'a/b' WHERE x BETWEEN 1 AND 2 | BETWEEN",+ "SELECT * FROM 'a/b' WHERE x IS NULL | IS",+ "SELECT * FROM 'a/b' WHERE x IS NOT NULL | IS",+ "SELECT * FROM 'a/b' ORDER BY x | ORDER",+ "SELECT * FROM 'a/b' LIMIT 1 | LIMIT",+ "SELECT * FROM 'a/b' GROUP BY x | GROUP",+ "SELECT DISTINCT x FROM 'a/b' | x",+ "SELECT * FROM 'a/b' JOIN 'c/d' | JOIN",+ "SELECT * FROM 'a/b' WHERE x == 'y' | =",+ "SELECT * FROM 'a/b'; DROP TABLE x | ;",+ "SELECT * FROM 'a/b' -- comment | -",+ "SELECT * FROM 'a/b' WHERE x && y | &",+ "SELECT * FROM 'a/b' WHERE x = `y` | `",+ "INSERT INTO 'a/b' VALUES (1) | INSERT"+ })+ void aStatementOutsideTheSubsetFailsNamingTheFirstUnplaceableToken(String sql, String token) {+ RuleSqlParseException failure = assertThrows(RuleSqlParseException.class, () -> RuleSqlParser.parse(sql));++ assertEquals(token, failure.token(), failure.getMessage());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlEvaluatorTest.javanew file mode 100644index 0000000000..c2286b45e9--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlEvaluatorTest.java@@ -0,0 +1,296 @@+package io.github.hectorvent.floci.services.iot.rules;++import com.fasterxml.jackson.databind.ObjectMapper;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import org.junit.jupiter.params.provider.ValueSource;++import java.nio.charset.StandardCharsets;+import java.util.Optional;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++class RuleSqlEvaluatorTest {++ private static final String SHADOW_TOPIC = "$aws/things/sensor-1/shadow/name/building/update/accepted";++ private final RuleSqlEvaluator evaluator = new RuleSqlEvaluator(new ObjectMapper());++ @Test+ void selectAllWithoutWhereForwardsTheOriginalBytes() {+ byte[] payload = "not-json at all".getBytes(StandardCharsets.UTF_8);++ Optional<byte[]> result = evaluate("SELECT * FROM 'devices/+/telemetry'", "devices/a/telemetry", payload);++ assertTrue(result.isPresent());+ assertArrayEquals(payload, result.get());+ }++ @Test+ void selectAllWithAWhereForwardsTheOriginalBytesUnchanged() {+ byte[] payload = "{\n \"clientToken\" : \"job:inbound\"\n}".getBytes(StandardCharsets.UTF_8);++ Optional<byte[]> result = evaluate("SELECT * FROM 'a/b' WHERE endswith(clientToken, 'inbound')", "a/b", payload);++ assertTrue(result.isPresent());+ assertArrayEquals(payload, result.get());+ }++ @Test+ void aProjectionAliasOverridesAPayloadFieldOfTheSameName() {+ Optional<byte[]> result = evaluate("SELECT *, topic() as topic FROM '$aws/things/+/shadow/name/building/update/accepted'",+ SHADOW_TOPIC, "{\"topic\":\"stale\",\"clientToken\":\"ingest:inbound\"}");++ assertEquals("{\"topic\":\"" + SHADOW_TOPIC + "\",\"clientToken\":\"ingest:inbound\"}", text(result));+ }++ @Test+ void projectsTopicSegmentsStartingAtOne() {+ Optional<byte[]> result = evaluate("SELECT topic(1) AS env, topic(3) AS thingId FROM 'prod/fleet/+/ingest'",+ "prod/fleet/sensor-7/ingest", "{\"value\":1}");++ assertEquals("{\"env\":\"prod\",\"thingId\":\"sensor-7\"}", text(result));+ }++ @Test+ void omitsAProjectionWhoseValueIsUndefined() {+ Optional<byte[]> result = evaluate("SELECT topic(9) AS missingSegment, absent AS gone, value FROM 'a/b'",+ "a/b", "{\"value\":1}");++ assertEquals("{\"value\":1}", text(result));+ }++ @Test+ void projectsDottedPathsUnderTheirLastSegment() {+ Optional<byte[]> result = evaluate("SELECT state.reported.temperature FROM 'a/b'",+ "a/b", "{\"state\":{\"reported\":{\"temperature\":21.5}}}");++ assertEquals("{\"temperature\":21.5}", text(result));+ }++ @Test+ void treatsJsonNullAsAValueDistinctFromUndefined() {+ Optional<byte[]> projected = evaluate("SELECT clientToken FROM 'a/b'", "a/b", "{\"clientToken\":null}");+ assertEquals("{\"clientToken\":null}", text(projected));++ assertFalse(evaluate("SELECT * FROM 'a/b' WHERE clientToken = 'x'", "a/b", "{\"clientToken\":null}").isPresent());+ assertTrue(evaluate("SELECT * FROM 'a/b' WHERE clientToken <> 'x'", "a/b", "{\"clientToken\":null}").isPresent());+ assertTrue(evaluate("SELECT * FROM 'a/b' WHERE clientToken = NULL", "a/b", "{\"clientToken\":null}").isPresent());+ assertFalse(evaluate("SELECT * FROM 'a/b' WHERE clientToken <> 'x'", "a/b", "{}").isPresent());+ assertFalse(evaluate("SELECT * FROM 'a/b' WHERE clientToken = NULL", "a/b", "{}").isPresent());+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "{\"clientToken\":\"ingest:inbound\"} | true",+ "{\"clientToken\":\"cc-evt:outbound\"} | false",+ "{\"clientToken\":\"inbound-but-not-last\"}| false",+ "{\"other\":\"ingest:inbound\"} | false",+ "{\"clientToken\":42} | false",+ "{} | false"+ })+ void evaluatesEndswithWithUndefinedSemantics(String payload, boolean fires) {+ assertEquals(fires, evaluate("SELECT * FROM 'a/b' WHERE endswith(clientToken, 'inbound')", "a/b", payload)+ .isPresent());+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "{\"clientToken\":\"any:ingest:inbound\"} | true",+ "{\"clientToken\":\"gateway:x:events:outbound\"}| true",+ "{\"clientToken\":\"other:x:events:outbound\"} | false",+ "{\"clientToken\":\"gateway:x:events:inbound\"} | false",+ "{\"clientToken\":\"gateway:\"} | false"+ })+ void evaluatesAGroupedPredicateInsideADisjunction(String payload, boolean fires) {+ String sql = "SELECT *, topic() as topic FROM 'a/b' WHERE endswith(clientToken, ':ingest:inbound') "+ + "OR (endswith(clientToken, ':events:outbound') AND startswith(clientToken, 'gateway:'))";++ assertEquals(fires, evaluate(sql, "a/b", payload).isPresent());+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "level = 3 | true",+ "level = 4 | false",+ "level <> 4 | true",+ "level != 3 | false",+ "level > 2 | true",+ "level >= 3 | true",+ "level < 3 | false",+ "level <= 3 | true",+ "level = '3' | false",+ "level <> '3' | true",+ "NOT level = '3' | true",+ "name = 'ok' | true",+ "name > 'a' | false",+ "name = 3 | false",+ "name <> 3 | true",+ "enabled = TRUE | true",+ "enabled <> FALSE | true",+ "enabled = 'true' | false",+ "enabled <> 'true' | true",+ "level > '2' | true",+ "level >= '3.0' | true",+ "level < '1E1' | true",+ "level < 'abc' | false",+ "code > 9 | true",+ "code > '9' | true",+ "missing = 3 | false",+ "missing <> 3 | false",+ "NOT level = 4 | true",+ "NOT missing = 3 | false"+ })+ void evaluatesComparisonsWithUndefinedSemantics(String predicate, boolean fires) {+ String payload = "{\"level\":3,\"name\":\"ok\",\"enabled\":true,\"code\":\"10\"}";++ assertEquals(fires, evaluate("SELECT level FROM 'a/b' WHERE " + predicate, "a/b", payload).isPresent());+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "missing = 3 OR level = 3 | false",+ "level = 3 OR missing = 3 | false",+ "missing = 3 AND level = 3 | false",+ "NOT missing = 3 | false",+ "level = 3 AND level = 3 | true",+ "level = 4 OR level = 3 | true",+ "flag | true",+ "flag AND level = 3 | true",+ "NOT off | true",+ "off OR flag | true",+ "name AND flag | false",+ "NOT name | false",+ "level AND flag | false"+ })+ void propagatesUndefinedThroughAndOrNotAndCoercesBooleanStrings(String predicate, boolean fires) {+ String payload = "{\"level\":3,\"name\":\"ok\",\"flag\":\"TRUE\",\"off\":\"false\"}";++ assertEquals(fires, evaluate("SELECT level FROM 'a/b' WHERE " + predicate, "a/b", payload).isPresent());+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "endswith(code, '2') | true",+ "startswith(flag, 'tr') | true",+ "startswith(obj, '{') | true",+ "endswith(list, ']') | true",+ "endswith(name, 5) | true",+ "startswith(name, 5) | false",+ "endswith(nothing, 'x') | false",+ "endswith(name, nothing) | false",+ "endswith(missing, 'x') | false"+ })+ void convertsStringFunctionArgumentsToStringsExceptNullAndUndefined(String predicate, boolean fires) {+ String payload = "{\"code\":42,\"flag\":true,\"obj\":{\"a\":1},\"list\":[1],\"name\":\"a5\",\"nothing\":null}";++ assertEquals(fires, evaluate("SELECT * FROM 'a/b' WHERE " + predicate, "a/b", payload).isPresent());+ }++ @Test+ void comparesNumbersThatDoNotFitALong() {+ assertTrue(evaluate("SELECT * FROM 'a/b' WHERE level > 1", "a/b",+ "{\"level\":99999999999999999999999}").isPresent());+ assertTrue(evaluate("SELECT * FROM 'a/b' WHERE level = 3", "a/b", "{\"level\":3.0}").isPresent());+ }++ @ParameterizedTest+ @ValueSource(strings = {"1e-2147483648", "1e99999999999", "-1e-99999999999", "9e9999999999"})+ void treatsANumericStringWhoseExponentOverflowsAsUndefined(String value) {+ String payload = "{\"level\":\"" + value + "\"}";++ assertFalse(evaluate("SELECT * FROM 'a/b' WHERE level > 1", "a/b", payload).isPresent());+ assertFalse(evaluate("SELECT * FROM 'a/b' WHERE level < 1", "a/b", payload).isPresent());+ assertFalse(evaluate("SELECT * FROM 'a/b' WHERE level >= '1e5'", "a/b", payload).isPresent());+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "1e400 | level > 1 | true",+ "1e400 | level < 1 | false",+ "1e-400 | level = 0 | false",+ "1e-400 | level > 0 | true",+ "9007199254740993.0 | level = 9007199254740993.0 | true",+ "9007199254740993.0 | level = 9007199254740992.0 | false",+ "0.1 | level = 0.1 | true",+ "0.30000000000000004 | level <> 0.3 | true",+ "0.30000000000000004 | level = 0.30000000000000004 | true",+ "3.0 | level = 3 | true",+ "123456789012345678901234567890.123456789 | level > 123456789012345678901234567890.123456788 | true",+ "1E2 | level = 100 | true"+ })+ void readsPayloadNumbersExactlyWhateverTheirSizeOrPrecision(String number, String predicate, boolean fires) {+ assertEquals(fires, evaluate("SELECT * FROM 'a/b' WHERE " + predicate, "a/b",+ "{\"level\":" + number + "}").isPresent());+ }++ @Test+ void comparesAHugePayloadNumberAgainstItsPlainForm() {+ assertTrue(evaluate("SELECT * FROM 'a/b' WHERE level = 1" + "0".repeat(400) + ".0", "a/b",+ "{\"level\":1e400}").isPresent());+ assertFalse(evaluate("SELECT * FROM 'a/b' WHERE level = 1" + "0".repeat(399) + ".0", "a/b",+ "{\"level\":1e400}").isPresent());+ }++ @Test+ void projectsADecimalPayloadNumberAsWritten() {+ assertEquals("{\"level\":21.50}", text(evaluate("SELECT level FROM 'a/b'", "a/b", "{\"level\":21.50}")));+ assertEquals("{\"level\":9007199254740993.0}",+ text(evaluate("SELECT level FROM 'a/b'", "a/b", "{\"level\":9007199254740993.0}")));+ }++ @Test+ void comparesAWholeNumberAgainstADecimalLiteralExactly() {+ assertFalse(evaluate("SELECT * FROM 'a/b' WHERE level = 9007199254740992.0", "a/b",+ "{\"level\":9007199254740993}").isPresent());+ assertTrue(evaluate("SELECT * FROM 'a/b' WHERE level > 9007199254740992.0", "a/b",+ "{\"level\":9007199254740993}").isPresent());+ }++ @Test+ void keepsADecimalLiteralExactInsteadOfRoundingItToADouble() {+ assertFalse(evaluate("SELECT * FROM 'a/b' WHERE level = 9007199254740993.0", "a/b",+ "{\"level\":9007199254740992}").isPresent());+ assertTrue(evaluate("SELECT * FROM 'a/b' WHERE level = 9007199254740993.0", "a/b",+ "{\"level\":9007199254740993}").isPresent());+ }++ @Test+ void skipsANonJsonPayloadWhenTheStatementNeedsFields() {+ assertFalse(evaluate("SELECT *, topic() as topic FROM 'a/b'", "a/b", "plain text").isPresent());+ assertFalse(evaluate("SELECT * FROM 'a/b' WHERE endswith(clientToken, 'x')", "a/b", "plain text").isPresent());+ }++ @Test+ void skipsAJsonPayloadThatIsNotAnObject() {+ assertFalse(evaluate("SELECT *, topic() as topic FROM 'a/b'", "a/b", "[1,2,3]").isPresent());+ }++ @Test+ void treatsAnEmptyPayloadAsNonJson() {+ assertFalse(evaluate("SELECT *, topic() as topic FROM 'a/b'", "a/b", "").isPresent());+ }++ @Test+ void matchesStringFunctionsOnTopicSegments() {+ assertTrue(evaluate("SELECT * FROM '$aws/events/presence/connected/+' WHERE startswith(topic(5), 'gw-')",+ "$aws/events/presence/connected/gw-1", "{}").isPresent());+ }++ private Optional<byte[]> evaluate(String sql, String topic, String payload) {+ return evaluate(sql, topic, payload.getBytes(StandardCharsets.UTF_8));+ }++ private Optional<byte[]> evaluate(String sql, String topic, byte[] payload) {+ return evaluator.evaluate("test-rule", RuleSqlParser.parse(sql), topic, payload);+ }++ private String text(Optional<byte[]> result) {+ assertTrue(result.isPresent(), "Expected the rule to fire");+ return new String(result.get(), StandardCharsets.UTF_8);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlFuzzTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlFuzzTest.javanew file mode 100644index 0000000000..988e4ef678--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlFuzzTest.java@@ -0,0 +1,173 @@+package io.github.hectorvent.floci.services.iot.rules;++import com.fasterxml.jackson.databind.ObjectMapper;+import org.junit.jupiter.api.Test;++import java.nio.charset.StandardCharsets;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.List;+import java.util.Random;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Feeds the parser thousands of deterministic mutations of valid statements and requires that+ * the only exception it ever raises is {@link RuleSqlParseException}, and that whatever it does+ * accept can be evaluated against any payload without an exception at all. The statement text+ * and the payload both come from users, so this is the guarantee that matters most.+ */+class RuleSqlFuzzTest {++ private static final long SEED = 20260904L;+ private static final int MUTANTS_PER_STATEMENT = 400;++ private static final List<String> STATEMENTS = List.of(+ "SELECT * FROM 'devices/+/telemetry'",+ "SELECT color AS my_color, temperature as fahrenheit FROM 'topic/subtopic'",+ "SELECT *, 15 as speed FROM 'topic/subtopic'",+ "SELECT *, topic() as topic FROM '$aws/things/+/shadow/name/building/update/accepted' WHERE endswith(clientToken, 'inbound')",+ "SELECT *, topic(3) AS thingId FROM 'prod/fleet/+/ingest_v1'",+ "SELECT * FROM '$aws/events/presence/connected/+' WHERE startswith(clientId, 'gw-')",+ "SELECT * FROM 'plant/+/events' WHERE endswith(clientToken, ':ingest:inbound') OR (endswith(clientToken, ':events:outbound') AND startswith(clientToken, 'gateway:'))",+ "SELECT state.reported.temperature AS temp FROM '$aws/things/+/shadow/update/accepted' WHERE state.reported.temperature >= 30.5",+ "SELECT * FROM 'a/b' WHERE NOT active = FALSE AND (size > 10 OR weight <= -2.5) AND name <> NULL",+ "select level, name from \"a/b\" where level != 3 and name = \"o''brien\"",+ "SELECT NULL AS n, TRUE AS t, 'x' AS s, 1 AS i FROM 'topic/subtopic'",+ "SELECT * FROM 'a/#' WHERE startswith(topic(2), 'b') AND endswith(topic(), 'c')");++ private static final String ALPHABET = " \t\n'\"(),.*=<>!-+[]{}$/#_abcXYZ019äé😀\\;:%";++ private static final List<String> TOKENS = List.of(+ "SELECT", "FROM", "WHERE", "AS", "AND", "OR", "NOT", "TRUE", "FALSE", "NULL", "topic()", "topic(2)",+ "topic(0)", "startswith(", "endswith(", "clientid()", "'x'", "\"y\"", "''", "42", "-1.5", "1e400",+ "99999999999999999999", "*", ",", "(", ")", ".", "=", "<>", "!=", "<", "<=", ">", ">=", "a.b", "IN", "[", "]");++ private static final List<String> TOPICS = List.of("a/b/c", "$aws/things/x/shadow/update/accepted", "", "a");++ private static final List<byte[]> PAYLOADS = List.of(+ bytes("{}"),+ bytes("{\"a\":1,\"b\":\"x\",\"c\":true,\"level\":3,\"name\":\"o'brien\",\"clientToken\":\"job:inbound\",\"clientId\":\"gw-1\"}"),+ bytes("{\"state\":{\"reported\":{\"temperature\":31}},\"size\":11,\"weight\":-3,\"active\":false}"),+ bytes("{\"a\":{\"b\":[1,{\"c\":null}]},\"n\":null,\"level\":1e400,\"big\":99999999999999999999999}"),+ bytes("{\"level\":1e-400,\"size\":0.30000000000000004,\"weight\":9007199254740993.0,\"temperature\":-1E-2}"),+ bytes("{\"a\":[],\"b\":{},\"c\":\"\",\"level\":\"3\",\"active\":\"TRUE\"}"),+ bytes("{\"size\":\"1e-2147483648\",\"weight\":\"1e99999999999\",\"level\":\"9e9999999999\",\"temperature\":\"-1e-2147483649\"}"),+ bytes("[1,2,3]"),+ bytes("plain text"),+ bytes(""),+ new byte[] {(byte) 0xff, (byte) 0xfe, 0x00, 0x7b});++ private final RuleSqlEvaluator evaluator = new RuleSqlEvaluator(new ObjectMapper());++ @Test+ void theParserOnlyEverThrowsRuleSqlParseExceptionAndTheEvaluatorNeverThrows() {+ Random random = new Random(SEED);+ int parsed = 0;+ int rejected = 0;+ for (String statement : STATEMENTS) {+ for (int end = 0; end <= statement.length(); end++) {+ if (attempt(statement.substring(0, end))) {+ parsed++;+ } else {+ rejected++;+ }+ }+ for (int i = 0; i < MUTANTS_PER_STATEMENT; i++) {+ if (attempt(mutate(statement, random))) {+ parsed++;+ } else {+ rejected++;+ }+ }+ }+ assertTrue(parsed >= STATEMENTS.size(), "every seed statement and some mutants must parse, got " + parsed);+ assertTrue(rejected > parsed, "most mutants must be rejected, got " + rejected + " rejected vs " + parsed + " parsed");+ }++ @Test+ void everySeedStatementParsesAndEvaluatesAsItIs() {+ for (String statement : STATEMENTS) {+ assertTrue(attempt(statement), statement);+ }+ }++ /**+ * True when the statement parsed. A parse failure is the one exception the parser may raise;+ * anything else, and anything at all from the evaluator, fails the test naming the input.+ */+ private boolean attempt(String sql) {+ RuleSql query;+ try {+ query = RuleSqlParser.parse(sql);+ } catch (RuleSqlParseException expected) {+ return false;+ } catch (RuntimeException unexpected) {+ throw new AssertionError("Parser must only throw RuleSqlParseException but threw " + unexpected+ + " for: " + sql, unexpected);+ }+ for (String topic : TOPICS) {+ for (byte[] payload : PAYLOADS) {+ assertDoesNotThrow(() -> evaluator.evaluate("fuzz", query, topic, payload),+ () -> "Evaluator threw for statement [" + sql + "] on topic [" + topic + "] with payload "+ + new String(payload, StandardCharsets.UTF_8));+ }+ }+ return true;+ }++ private static String mutate(String statement, Random random) {+ String current = statement;+ int edits = 1 + random.nextInt(3);+ for (int i = 0; i < edits; i++) {+ current = switch (random.nextInt(5)) {+ case 0 -> deleteChar(current, random);+ case 1 -> insertAt(current, random, String.valueOf(ALPHABET.charAt(random.nextInt(ALPHABET.length()))));+ case 2 -> insertAt(current, random, " " + TOKENS.get(random.nextInt(TOKENS.size())) + " ");+ case 3 -> swapWords(current, random);+ default -> deleteSlice(current, random);+ };+ }+ return current;+ }++ private static String deleteChar(String text, Random random) {+ if (text.isEmpty()) {+ return text;+ }+ int at = random.nextInt(text.length());+ return text.substring(0, at) + text.substring(at + 1);+ }++ private static String insertAt(String text, Random random, String insertion) {+ int at = random.nextInt(text.length() + 1);+ return text.substring(0, at) + insertion + text.substring(at);+ }++ private static String deleteSlice(String text, Random random) {+ if (text.isEmpty()) {+ return text;+ }+ int from = random.nextInt(text.length());+ int to = Math.min(text.length(), from + 1 + random.nextInt(8));+ return text.substring(0, from) + text.substring(to);+ }++ private static String swapWords(String text, Random random) {+ List<String> words = new ArrayList<>(Arrays.asList(text.split(" ")));+ if (words.size() < 2) {+ return text;+ }+ int first = random.nextInt(words.size());+ int second = random.nextInt(words.size());+ String swapped = words.get(first);+ words.set(first, words.get(second));+ words.set(second, swapped);+ return String.join(" ", words);+ }++ private static byte[] bytes(String text) {+ return text.getBytes(StandardCharsets.UTF_8);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlParserRobustnessTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlParserRobustnessTest.javanew file mode 100644index 0000000000..1be913a585--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlParserRobustnessTest.java@@ -0,0 +1,205 @@+package io.github.hectorvent.floci.services.iot.rules;++import io.github.hectorvent.floci.services.iot.rules.RuleSql.Aliased;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Comparison;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Conjunction;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Disjunction;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Expr;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Negation;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Operator;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Path;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import org.junit.jupiter.params.provider.ValueSource;++import java.math.BigDecimal;+import java.util.List;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;++/**+ * The parts of parsing that are easy to get wrong and invisible in a happy path test: words+ * that begin with a keyword, statements without the usual spacing, how chains of AND and OR+ * nest, and the literal forms at the edge of the grammar.+ */+class RuleSqlParserRobustnessTest {++ private static final String CANONICAL =+ "SELECT *, topic(3) AS id FROM 'a/b' WHERE a = 'x' AND NOT (b <> 'y' OR c > 1)";++ @ParameterizedTest+ @ValueSource(strings = {+ "orange", "asset", "notify", "android", "frombar", "true_flag", "nullable", "selector",+ "whereabouts", "order", "ins", "existing", "valueOf", "case_id", "Andy", "Orb", "not_ready",+ "select_count", "from_device", "as_of", "fromDate", "topic_name", "startswith_x"+ })+ void aWordThatBeginsWithAKeywordIsAFieldName(String field) {+ RuleSql query = RuleSqlParser.parse("SELECT " + field + " FROM 'a/b' WHERE " + field + " = 'x'");++ assertEquals(List.of(new Aliased(new Path(List.of(field)), field)), query.projections());+ assertEquals(new Comparison(new Path(List.of(field)), Operator.EQUAL, RuleSql.text("x")), query.where());+ }++ @ParameterizedTest+ @ValueSource(strings = {"select", "Select", "sElEcT", "from", "As", "and", "Or", "NoT", "True", "false", "Null"})+ void aKeywordIsRecognisedInAnyCase(String keyword) {+ assertThrows(RuleSqlParseException.class,+ () -> RuleSqlParser.parse("SELECT " + keyword + " FROM 'a/b'"),+ keyword + " must be a keyword, not a field name");+ }++ @ParameterizedTest+ @ValueSource(strings = {+ "SELECT *,topic(3)AS id FROM 'a/b' WHERE a='x'AND NOT(b<>'y'OR c>1)",+ "SELECT\t*,\n\ttopic(3) AS id\nFROM 'a/b'\nWHERE a = 'x'\r\nAND NOT (b <> 'y' OR c > 1)",+ " SELECT *, topic(3) AS id FROM 'a/b' WHERE a = 'x' AND NOT (b <> 'y' OR c > 1) \n",+ "SELECT * , topic( 3 ) AS id FROM 'a/b' WHERE a = 'x' AND NOT ( b <> 'y' OR c > 1 )",+ "select *, TOPIC(3) as id from 'a/b' where a = 'x' and not (b <> 'y' or c > 1)"+ })+ void spacingAndCaseDoNotChangeTheParse(String variant) {+ assertEquals(RuleSqlParser.parse(CANONICAL), RuleSqlParser.parse(variant));+ }++ @Test+ void andAndOrChainsAreLeftAssociative() {+ Expr a = comparison("a");+ Expr b = comparison("b");+ Expr c = comparison("c");+ Expr d = comparison("d");++ assertEquals(new Conjunction(new Conjunction(a, b), c),+ RuleSqlParser.parse("SELECT * FROM 't' WHERE a = 'x' AND b = 'x' AND c = 'x'").where());+ assertEquals(new Disjunction(new Disjunction(a, b), c),+ RuleSqlParser.parse("SELECT * FROM 't' WHERE a = 'x' OR b = 'x' OR c = 'x'").where());+ assertEquals(new Disjunction(new Disjunction(a, new Conjunction(b, c)), d),+ RuleSqlParser.parse("SELECT * FROM 't' WHERE a = 'x' OR b = 'x' AND c = 'x' OR d = 'x'").where());+ assertEquals(new Disjunction(new Negation(a), b),+ RuleSqlParser.parse("SELECT * FROM 't' WHERE NOT a = 'x' OR b = 'x'").where());+ assertEquals(new Negation(new Negation(a)),+ RuleSqlParser.parse("SELECT * FROM 't' WHERE NOT NOT a = 'x'").where());+ assertEquals(new Negation(new Disjunction(a, b)),+ RuleSqlParser.parse("SELECT * FROM 't' WHERE NOT (a = 'x' OR b = 'x')").where());+ }++ @Test+ void keepsUnicodeInFiltersAndLiterals() {+ RuleSql query = RuleSqlParser.parse("SELECT * FROM 'devices/ä/+' WHERE name = '日本' OR emoji = '🚀'");++ assertEquals("devices/ä/+", query.topicFilter());+ Disjunction where = (Disjunction) query.where();+ assertEquals(RuleSql.text("日本"), ((Comparison) where.left()).right());+ assertEquals(RuleSql.text("🚀"), ((Comparison) where.right()).right());+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', quoteCharacter = '"', value = {+ "'' | text",+ "0 | long:0",+ "007 | long:7",+ "-0 | long:0",+ "42 | long:42",+ "-17 | long:-17",+ "1.50 | decimal:1.50",+ "-0.001 | decimal:-0.001",+ "9223372036854775807 | long:9223372036854775807"+ })+ void parsesEveryAcceptedLiteralForm(String literal, String expected) {+ Comparison where = (Comparison) RuleSqlParser.parse("SELECT * FROM 't' WHERE a = " + literal).where();++ RuleSql.Literal value = switch (expected.split(":")[0]) {+ case "long" -> RuleSql.number(Long.parseLong(expected.substring(5)));+ case "decimal" -> RuleSql.decimal(new BigDecimal(expected.substring(8)));+ default -> RuleSql.text("");+ };+ assertEquals(value, where.right());+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "1. | .",+ ".5 | .",+ "1e5 | e5",+ "+1 | +",+ "0x1F | x1F",+ "1_000 | _000",+ "1..2 | .",+ "--1 | -"+ })+ void rejectsLiteralFormsOutsideTheGrammarNamingTheToken(String literal, String token) {+ RuleSqlParseException failure = assertThrows(RuleSqlParseException.class,+ () -> RuleSqlParser.parse("SELECT * FROM 't' WHERE a = " + literal));++ assertEquals(token, failure.token());+ }++ @Test+ void acceptsIdentifiersWithDigitsAndUnderscoresAndLongNames() {+ String longName = "f".repeat(1000);+ RuleSql query = RuleSqlParser.parse("SELECT field1, _private, a1.b2._c3, " + longName + " FROM 't'");++ assertEquals(List.of(+ new Aliased(new Path(List.of("field1")), "field1"),+ new Aliased(new Path(List.of("_private")), "_private"),+ new Aliased(new Path(List.of("a1", "b2", "_c3")), "_c3"),+ new Aliased(new Path(List.of(longName)), longName)), query.projections());+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "SELECT 1field FROM 't' | 1",+ "SELECT a. FROM 't' | FROM",+ "SELECT .a FROM 't' | .",+ "SELECT a..b FROM 't' | .",+ "SELECT a.from FROM 't' | from",+ "SELECT a b FROM 't' | b",+ "SELECT a AS FROM 't' | FROM",+ "SELECT a AS 'x' FROM 't' | x",+ "SELECT a AS b.c FROM 't' | .",+ "SELECT * AS all FROM 't' | AS",+ "SELECT ** FROM 't' | *",+ "SELECT , a FROM 't' | ,",+ "SELECT a, FROM 't' | FROM",+ "SELECT a,, b FROM 't' | ,",+ "SELECT * FROM 't' 'u' | u",+ "SELECT * FROM 't' WHERE WHERE a | WHERE",+ "SELECT * FROM 't' WHERE () | )",+ "SELECT * FROM 't' WHERE (a = 'x')) | )",+ "SELECT * FROM 't' WHERE a = 'x' AND | ''",+ "SELECT * FROM 't' WHERE a = 'x' OR OR b = 'y' | OR",+ "SELECT * FROM 't' WHERE NOT | ''",+ "SELECT * FROM 't' WHERE a == 'x' | =",+ "SELECT * FROM 't' WHERE a => 1 | >",+ "SELECT * FROM 't' WHERE a =< 1 | <",+ "SELECT * FROM 't' WHERE a >< 1 | <",+ "SELECT * FROM 't' WHERE a = 'x' = 'y' | =",+ "SELECT * FROM 't' WHERE a && b | &",+ "SELECT * FROM 't' WHERE a ! = b | !",+ "SELECT * FROM 't' WHERE topic(1)(2) = 'x' | (",+ "SELECT * FROM 't' WHERE startswith(a, 'x',) | )",+ "SELECT * FROM 't' WHERE startswith(, 'x') | ,",+ "SELECT * FROM 't' WHERE startswith(a 'x') | x",+ "SELECT * FROM 't' WHERE endswith(a, 'x', 'y') | endswith",+ "SELECT * FROM 't' WHERE topic(a) = 'x' | topic",+ "SELECT * FROM 't' WHERE topic(1.5) = 'x' | topic",+ "SELECT * FROM 't' WHERE topic(-1) = 'x' | topic",+ "SELECT * FROM 't' WHERE topic(99999999999999999999) = 'x' | 99999999999999999999",+ "SELECT * FROM '' | ''",+ "SELECT * FROM ' ' | ' '",+ "SELECT * FROM t | t",+ "SELECT * FROM topic/subtopic | /",+ "SELECT * FROM 'a/b' -- comment | -",+ "SELECT * FROM 'a/b'; DROP x | ;",+ "SELECT * FROM 'a/b' /* c */ | /"+ })+ void rejectsMalformedShapesNamingTheFirstTokenItCannotPlace(String sql, String token) {+ RuleSqlParseException failure = assertThrows(RuleSqlParseException.class, () -> RuleSqlParser.parse(sql));++ assertEquals(token, failure.token(), failure.getMessage());+ }++ private static Expr comparison(String field) {+ return new Comparison(new Path(List.of(field)), Operator.EQUAL, RuleSql.text("x"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlParserTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlParserTest.javanew file mode 100644index 0000000000..027f69ee0a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iot/rules/RuleSqlParserTest.java@@ -0,0 +1,239 @@+package io.github.hectorvent.floci.services.iot.rules;++import io.github.hectorvent.floci.services.iot.rules.RuleSql.Aliased;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Call;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Comparison;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Conjunction;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Disjunction;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Negation;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Operator;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.Path;+import io.github.hectorvent.floci.services.iot.rules.RuleSql.SelectAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import org.junit.jupiter.params.provider.ValueSource;++import java.util.List;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertInstanceOf;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++class RuleSqlParserTest {++ @Test+ void parsesSelectAllWithTopicFilter() {+ RuleSql query = RuleSqlParser.parse("SELECT * FROM 'devices/+/telemetry'");++ assertEquals(List.of(new SelectAll()), query.projections());+ assertEquals("devices/+/telemetry", query.topicFilter());+ assertNull(query.where());+ assertTrue(query.isSelectAllOnly());+ }++ @Test+ void treatsKeywordsAsCaseInsensitiveAndIdentifiersAsCaseSensitive() {+ RuleSql query = RuleSqlParser.parse("select Payload as Alias from 'a/b' where Payload = 'x'");++ assertEquals(List.of(new Aliased(new Path(List.of("Payload")), "Alias")), query.projections());+ assertEquals(new Comparison(new Path(List.of("Payload")), Operator.EQUAL, RuleSql.text("x")), query.where());+ }++ @Test+ void defaultsTheAliasOfATopicFunctionToTopic() {+ RuleSql query = RuleSqlParser.parse("SELECT topic() FROM 'a/b'");++ assertEquals(List.of(new Aliased(new Call("topic", List.of()), "topic")), query.projections());+ }++ @Test+ void defaultsTheAliasOfAPathToItsLastSegment() {+ RuleSql query = RuleSqlParser.parse("SELECT state.reported.temperature FROM 'a/b'");++ assertEquals(List.of(new Aliased(new Path(List.of("state", "reported", "temperature")), "temperature")),+ query.projections());+ }++ @Test+ void parsesASegmentIndexOnTopic() {+ RuleSql query = RuleSqlParser.parse("SELECT *, topic(3) AS thingId FROM 'fleet/telemetry/+/status'");++ assertEquals(new SelectAll(), query.projections().get(0));+ assertEquals(new Aliased(new Call("topic", List.of(RuleSql.number(3))), "thingId"), query.projections().get(1));+ assertFalse(query.isSelectAllOnly());+ }++ @Test+ void parsesAGroupedPredicateInsideADisjunction() {+ RuleSql query = RuleSqlParser.parse("SELECT * FROM 'a/b' WHERE endswith(clientToken, ':ingest:inbound') "+ + "OR (endswith(clientToken, ':events:outbound') AND startswith(clientToken, 'gateway:'))");++ Disjunction where = assertInstanceOf(Disjunction.class, query.where());+ assertEquals(new Call("endswith", List.of(new Path(List.of("clientToken")), RuleSql.text(":ingest:inbound"))),+ where.left());+ assertInstanceOf(Conjunction.class, where.right());+ }++ @Test+ void bindsAndTighterThanOr() {+ RuleSql query = RuleSqlParser.parse("SELECT * FROM 'a/b' WHERE a = '1' OR b = '2' AND c = '3'");++ Disjunction where = assertInstanceOf(Disjunction.class, query.where());+ assertInstanceOf(Comparison.class, where.left());+ assertInstanceOf(Conjunction.class, where.right());+ }++ @Test+ void bindsNotTighterThanAnd() {+ RuleSql query = RuleSqlParser.parse("SELECT * FROM 'a/b' WHERE NOT a = '1' AND b = '2'");++ Conjunction where = assertInstanceOf(Conjunction.class, query.where());+ assertInstanceOf(Negation.class, where.left());+ assertInstanceOf(Comparison.class, where.right());+ }++ @ParameterizedTest+ @CsvSource({+ "'=', EQUAL",+ "'<>', NOT_EQUAL",+ "'!=', NOT_EQUAL",+ "'<', LESS",+ "'<=', LESS_OR_EQUAL",+ "'>', GREATER",+ "'>=', GREATER_OR_EQUAL"+ })+ void parsesEveryComparisonOperator(String symbol, Operator expected) {+ RuleSql query = RuleSqlParser.parse("SELECT * FROM 'a/b' WHERE level " + symbol + " 3");++ assertEquals(new Comparison(new Path(List.of("level")), expected, RuleSql.number(3)), query.where());+ }++ @Test+ void parsesNegativeNumberBooleanAndEscapedStringLiterals() {+ RuleSql query = RuleSqlParser.parse(+ "SELECT * FROM 'a/b' WHERE offset > -2 AND active = TRUE AND name = 'o''brien'");++ Conjunction outer = assertInstanceOf(Conjunction.class, query.where());+ Conjunction inner = assertInstanceOf(Conjunction.class, outer.left());+ assertEquals(new Comparison(new Path(List.of("offset")), Operator.GREATER, RuleSql.number(-2)), inner.left());+ assertEquals(new Comparison(new Path(List.of("active")), Operator.EQUAL, RuleSql.bool(true)), inner.right());+ assertEquals(new Comparison(new Path(List.of("name")), Operator.EQUAL, RuleSql.text("o'brien")), outer.right());+ }++ @Test+ void acceptsDoubleQuotedStringsAsAwsExamplesDo() {+ assertEquals(RuleSqlParser.parse("SELECT * FROM 'a/b' WHERE startswith(name, 'ra''n')"),+ RuleSqlParser.parse("SELECT * FROM \"a/b\" WHERE startswith(name, \"ra'n\")"));+ assertEquals(RuleSql.text("say \"hi\""),+ ((Comparison) RuleSqlParser.parse("SELECT * FROM 'a' WHERE x = \"say \"\"hi\"\"\"").where()).right());+ }++ @Test+ void keepsReservedTopicFiltersVerbatim() {+ RuleSql query = RuleSqlParser.parse("SELECT * FROM '$aws/events/presence/connected/+'");++ assertEquals("$aws/events/presence/connected/+", query.topicFilter());+ }++ @Test+ void reportsTheOffendingTokenAndPositionOfAnUnsupportedFunction() {+ RuleSqlParseException failure = assertThrows(RuleSqlParseException.class,+ () -> RuleSqlParser.parse("SELECT clientid() FROM 'a/b'"));++ assertEquals("clientid", failure.token());+ assertEquals(7, failure.position());+ assertTrue(failure.getMessage().contains("clientid"), failure.getMessage());+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "SELECT * FROM 'a/b' WHERE state IN ('on') | IN",+ "SELECT * FROM 'a/b' WHERE state IS NULL | IS",+ "SELECT CASE WHEN a THEN 1 END FROM 'a/b' | WHEN",+ "SELECT * FROM 'a/b' WHERE encode(a, 'base64') = 'x'| encode",+ "SELECT * FROM 'a/b' WHERE a[0] = 'x' | [",+ "SELECT * FROM 'a/b' ORDER BY a | ORDER"+ })+ void rejectsConstructsOutsideTheSubset(String sql, String expectedToken) {+ RuleSqlParseException failure = assertThrows(RuleSqlParseException.class, () -> RuleSqlParser.parse(sql));++ assertEquals(expectedToken, failure.token());+ }++ @ParameterizedTest+ @ValueSource(strings = {+ "SELECT * FROM",+ "SELECT * 'a/b'",+ "SELECT FROM 'a/b'",+ "SELECT * FROM 'a/b",+ "SELECT * FROM 'a/b' WHERE",+ "SELECT * FROM 'a/b' WHERE a =",+ "SELECT * FROM 'a/b' WHERE (a = 'b'",+ "SELECT topic(0) FROM 'a/b'",+ "SELECT topic('x') FROM 'a/b'",+ "SELECT topic(1, 2) FROM 'a/b'",+ "SELECT * FROM 'a/b' WHERE startswith(a) = TRUE",+ "SELECT *, FROM 'a/b'",+ "",+ " "+ })+ void rejectsMalformedStatements(String sql) {+ assertThrows(RuleSqlParseException.class, () -> RuleSqlParser.parse(sql));+ }++ @Test+ void rejectsANullStatement() {+ assertThrows(RuleSqlParseException.class, () -> RuleSqlParser.parse(null));+ }++ @Test+ void treatsFunctionNamesAsCaseInsensitive() {+ RuleSql query = RuleSqlParser.parse("SELECT TOPIC() FROM 'a/b' WHERE StartsWith = 'x' AND ENDSWITH(a, 'y')");++ assertEquals(List.of(new Aliased(new Call("topic", List.of()), "topic")), query.projections());+ Conjunction where = assertInstanceOf(Conjunction.class, query.where());+ assertEquals(new Call("endswith", List.of(new Path(List.of("a")), RuleSql.text("y"))), where.right());+ }++ @Test+ void rejectsANumberTooLargeToRepresent() {+ RuleSqlParseException failure = assertThrows(RuleSqlParseException.class,+ () -> RuleSqlParser.parse("SELECT * FROM 'a/b' WHERE level = 99999999999999999999999"));++ assertEquals("99999999999999999999999", failure.token());+ }++ @Test+ void acceptsAStatementExactlyOnTheTokenLimit() {+ String sql = "SELECT * FROM 'a/b' WHERE a = 'x'" + " AND a = 'x'".repeat(248);++ assertEquals(1000, tokenCount(sql));+ assertNotNull(RuleSqlParser.parse(sql).where());+ }++ @Test+ void rejectsAStatementPastTheTokenLimitNamingARealToken() {+ String sql = "SELECT * FROM 'a/b' WHERE a = 'x'" + " AND a = 'x'".repeat(249);++ RuleSqlParseException failure = assertThrows(RuleSqlParseException.class, () -> RuleSqlParser.parse(sql));++ assertFalse(failure.token().isEmpty(), "The reported token must be a real token, not the end of input");+ }++ /** Mirrors the parser's tokenizer closely enough to pin the boundary the limit is checked against. */+ private static int tokenCount(String sql) {+ return 5 + 3 + 4 * (sql.split(" AND ", -1).length - 1);+ }++ @Test+ void rejectsAStatementDeepEnoughToOverflowTheStack() {+ String sql = "SELECT * FROM 'a/b' WHERE " + "(".repeat(5000) + "a = 'b'" + ")".repeat(5000);++ assertThrows(RuleSqlParseException.class, () -> RuleSqlParser.parse(sql));+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 525b485d44..89bc79b569 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -348,6 +348,7 @@ floci:enabled: trueiot:enabled: true+ rule-sql-strict: falsemqtt:enabled: trueauto-start: false