Skip to content

Commit 8ee4476

Browse files
Release v2.2.0 (#797)
Signed-off-by: Andrew Coleman <andrew_coleman@uk.ibm.com>
1 parent f2dd8fc commit 8ee4476

8 files changed

Lines changed: 433 additions & 2 deletions

File tree

CHANGELOG.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
#### 2.2.0 Milestone Release
2+
3+
- New API to specify resource guardrails on expressions (PR #795)
4+
- Fix ISO8601 regex pattern (PR #793)
5+
- Prevent $lookup from accessing object prototype members (PR #794)
6+
- Enable OIDC publishing to NPM (PR #792)
7+
- Publish step to be triggered by new version tag (PR #796)
8+
19
#### 2.1.1 Maintenance Release
210

311
- Fix picture string parsing for $formatNumber (PR #788)

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "jsonata",
3-
"version": "2.1.1",
3+
"version": "2.2.0",
44
"description": "JSON query and transformation language",
55
"module": "jsonata.js",
66
"main": "jsonata.js",

website/sidebars.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,6 @@
44
"Language Guide": ["simple", "predicate", "expressions", "construction", "composition", "sorting-grouping", "processing", "programming", "regex", "date-time"],
55
"Operators": ["path-operators", "numeric-operators", "comparison-operators", "boolean-operators", "other-operators"],
66
"Function Library": ["string-functions", "numeric-functions", "aggregation-functions", "boolean-functions", "array-functions", "object-functions", "date-time-functions", "higher-order-functions"],
7-
"Extending JSONata": ["embedding-extending", "contributing"]
7+
"Extending JSONata": ["embedding-extending", "guardrails", "contributing"]
88
}
99
}
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
---
2+
id: version-2.2.0-embedding-extending
3+
title: Embedding and Extending JSONata
4+
sidebar_label: Embedding and Extending JSONata
5+
original_id: embedding-extending
6+
---
7+
8+
## API
9+
10+
### jsonata(str[, options])
11+
12+
Parse a string `str` as a JSONata expression and return a compiled JSONata expression object.
13+
14+
`options`, if present, is used to control certain aspects of the evaluator, and can be used to protect the server from expressions that take longer to execute than expected. See [Configuring Guardrails](guardrails) for more details.
15+
16+
```javascript
17+
var expression = jsonata("$sum(example.value)");
18+
```
19+
20+
If the expression is not valid JSONata, an `Error` is thrown containing information about the nature of the syntax error, for example:
21+
22+
```
23+
{
24+
code: "S0202",
25+
stack: "...",
26+
position: 16,
27+
token: "}",
28+
value: "]",
29+
message: "Syntax error: expected ']' got '}'"
30+
}
31+
```
32+
33+
`expression` has three methods:
34+
35+
### expression.evaluate(input[, bindings[, callback]])
36+
37+
Run the compiled JSONata expression against object `input` and return the result as a new object.
38+
39+
```javascript
40+
var result = await expression.evaluate({example: [{value: 4}, {value: 7}, {value: 13}]});
41+
```
42+
43+
`input` should be a JavaScript value such as would be returned from `JSON.parse()`. If `input` could not have been parsed from a JSON string (is circular, contains functions, ...), `evaluate`'s behaviour is not defined. `result` is a new JavaScript value suitable for `JSON.stringify()`ing.
44+
45+
`bindings`, if present, contain variable names and values (including functions) to be bound:
46+
47+
```javascript
48+
await jsonata("$a + $b()").evaluate({}, {a: 4, b: () => 78});
49+
// returns 82
50+
```
51+
52+
`expression.evaluate()` may throw a run-time `Error`:
53+
54+
```javascript
55+
var expression = jsonata("$notafunction()"); // OK, valid JSONata
56+
await expression.evaluate({}); // Throws
57+
```
58+
59+
The `Error` contains information about the nature of the run-time error, for example:
60+
61+
```
62+
{
63+
code: "T1006",
64+
stack: "...",
65+
position: 14,
66+
token: "notafunction",
67+
message: "Attempted to invoke a non-function"
68+
}
69+
```
70+
71+
If `callback(err, value)` is supplied, `expression.evaluate()` returns `undefined`, the expression is run asynchronously and the `Error` or result is passed to `callback`.
72+
73+
```javascript
74+
await jsonata("7 + 12").evaluate({}, {}, (error, result) => {
75+
if(error) {
76+
console.error(error);
77+
return;
78+
}
79+
console.log("Finished with", result);
80+
});
81+
console.log("Started");
82+
83+
// Prints "Started", then "Finished with 19"
84+
```
85+
86+
### expression.assign(name, value)
87+
88+
Permanently binds a value to a name in the expression, similar to how `bindings` worked above. Modifies `expression` in place and returns `undefined`. Useful in a JSONata expression factory.
89+
90+
```javascript
91+
var expression = jsonata("$a + $b()");
92+
expression.assign("a", 4);
93+
expression.assign("b", () => 1);
94+
95+
await expression.evaluate({}); // 5
96+
```
97+
98+
Note that the `bindings` argument in the `expression.evaluate()` call clobbers these values:
99+
100+
```javascript
101+
await expression.evaluate({}, {a: 109}); // 110
102+
```
103+
104+
### expression.registerFunction(name, implementation[, signature])
105+
106+
Permanently binds a function to a name in the expression.
107+
108+
```javascript
109+
var expression = jsonata("$greet()");
110+
expression.registerFunction("greet", () => "Hello world");
111+
112+
await expression.evaluate({}); // "Hello world"
113+
```
114+
115+
You can do this using `expression.assign` or `bindings` in `expression.evaluate`, but `expression.registerFunction` allows you to specify a function `signature`. This is a terse string which tells JSONata the expected input argument types and return value type of the function. JSONata raises a run-time error if the actual input argument types do not match (the return value type is not checked yet).
116+
117+
```javascript
118+
var expression = jsonata("$add(61, 10005)");
119+
expression.registerFunction("add", (a, b) => a + b, "<nn:n>");
120+
121+
await expression.evaluate({}); // 10066
122+
```
123+
124+
### Function signature syntax
125+
126+
A function signature is a string of the form `<params:return>`. `params` is a sequence of type symbols, each one representing an input argument's type. `return` is a single type symbol representing the return value type.
127+
128+
Type symbols work as follows:
129+
130+
Simple types:
131+
132+
- `b` - Boolean
133+
- `n` - number
134+
- `s` - string
135+
- `l` - `null`
136+
137+
Complex types:
138+
139+
- `a` - array
140+
- `o` - object
141+
- `f` - function
142+
143+
Union types:
144+
145+
- `(sao)` - string, array or object
146+
- `(o)` - same as `o`
147+
- `u` - equivalent to `(bnsl)` i.e. Boolean, number, string or `null`
148+
- `j` - any JSON type. Equivalent to `(bnsloa)` i.e. Boolean, number, string, `null`, object or array, but not function
149+
- `x` - any type. Equivalent to `(bnsloaf)`
150+
151+
Parametrised types:
152+
153+
- `a<s>` - array of strings
154+
- `a<x>` - array of values of any type
155+
156+
Some examples of signatures of built-in JSONata functions:
157+
158+
- `$count` has signature `<a:n>`; it accepts an array and returns a number.
159+
- `$append` has signature `<aa:a>`; it accepts two arrays and returns an array.
160+
- `$sum` has signature `<a<n>:n>`; it accepts an array of numbers and returns a number.
161+
- `$reduce` has signature `<fa<j>:j>`; it accepts a reducer function `f` and an `a<j>` (array of JSON objects) and returns a JSON object.
162+
163+
Each type symbol may also have *options* applied.
164+
165+
- `+` - one or more arguments of this type
166+
- E.g. `$zip` has signature `<a+>`; it accepts one array, or two arrays, or three arrays, or...
167+
- `?` - optional argument
168+
- E.g. `$join` has signature `<a<s>s?:s>`; it accepts an array of strings and an optional joiner string which defaults to the empty string. It returns a string.
169+
- `-` - if this argument is missing, use the context value ("focus").
170+
- E.g. `$length` has signature `<s-:n>`; it can be called as `$length(OrderID)` (one argument) but equivalently as `OrderID.$length()`.
171+
172+
### Writing higher-order function extensions
173+
174+
It is possible to write an extension function that takes one or more functions in its list of arguments and/or returns
175+
a function as its return value.
176+
177+
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
---
2+
id: version-2.2.0-guardrails
3+
title: Configuring Guardrails
4+
sidebar_label: Configuring Guardrails
5+
original_id: guardrails
6+
---
7+
8+
## Guardrails
9+
10+
This page contains information relating to the JavaScript [reference implementation](https://github.com/jsonata-js/jsonata) of JSONata, and not the JSONata expression language itself.
11+
12+
JSONata is a Turing-complete expression language, and as such, it is possible to write unbounded, or infinite loops. This can be a potential problem if an application using JSONata is exposing the ability for client users to input expressions that are evaluated on the server. A user could accidently or maliciously provide an expression that, if evaluated unchecked, could cause a denial of service situation.
13+
14+
This JSONata library provides a set of configurable 'guardrails' that limit the compute and memory resources that a single expression can consume. If this library is being used in a hosted environment to allow end users to provide their own expressions, then it would be prudent to set constraints. The following sections describe each of the guardrails and how to configure them. It does not provide recommended values or defaults.
15+
16+
### Stack overflow
17+
18+
In common with other functional languages, JSONata supports looping by writing [recursive functions](https://en.wikipedia.org/wiki/Functional_programming#Recursion). The JSONata evaluator processes an expression using a set of mutually recursive functions (eval-apply cycle). When a function is invoked (by itself or by another function), the call stack in the host JavaScript runtime will grow. If this stack grows too deep, evaluator could exhaust the memory of the host process causing it to crash.
19+
20+
The JSONata evaluator can be configured with a maximum stack[^stack] limit to prevent an expression from doing this by specifying the `stack` option. Error `D1011` will be thrown if the expression grows the stack beyond the specified limit.
21+
22+
```javascript
23+
const jsonata = require('jsonata');
24+
25+
const data = {JSON: data};
26+
const options = {
27+
stack: 500
28+
};
29+
30+
(async () => {
31+
const expression = jsonata('<JSONata expression>', options);
32+
const result = await expression.evaluate(data);
33+
})()
34+
```
35+
36+
37+
As an example, the [Ackermann function](https://en.wikipedia.org/wiki/Ackermann_function) could be implemented in JSONata using:
38+
39+
```
40+
(
41+
$ack := function($m, $n) {
42+
$m = 0 ? $n + 1 :
43+
$n = 0 ? $ack($m - 1, 1) :
44+
$ack($m - 1, $ack($m, $n - 1))
45+
};
46+
47+
$ack(3, 4)
48+
)
49+
```
50+
51+
Invoked as `$ack(3, 4)` would quickly evaluate to `125`. However, `$ack(4, 3)`, although theoretically computable, will readily hit the configured stack guardrail before causing any problems to the host server.
52+
53+
[^stack]: The term 'stack' is a slight misnomer here; it actually limits the number of times round the eval-apply cycle, which is related to the JavaScript stack depth.
54+
55+
### Excessive execution time
56+
57+
It's possible (and desirable) to write [tail recursive](programming#tail-call-optimization-tail-recursion) functions that don't grow the stack at all. For these types of functions, a [stack guardrail](#stack-overflow) would not be sufficient to protect against unbounded loops.
58+
59+
The JSONata evaluator can be configured with a maximum time limit to protect against runaway expressions by specifying the `timeout` option. Error `D1012` will be thrown if the expression runs for longer than the specified timeout (in milliseconds).
60+
61+
It's good practice to specify both `stack` and `timeout`.
62+
63+
```javascript
64+
const jsonata = require('jsonata');
65+
66+
const data = {JSON: data};
67+
const options = {
68+
stack: 500,
69+
timeout: 1000 // in milliseconds
70+
};
71+
72+
(async () => {
73+
const expression = jsonata('<JSONata expression>', options);
74+
const result = await expression.evaluate(data);
75+
})()
76+
```
77+
78+
As an example, an infinite loop could be written in JSONata:
79+
80+
```
81+
(
82+
$inf := function() {
83+
$inf()
84+
};
85+
86+
$inf()
87+
)
88+
```
89+
90+
This is tail recursive, and would run forever without the timeout guardrail.
91+
92+
### Excessive sequence length
93+
94+
It's possible to write expressions that result in excessively long result sequences. This could ultimately lead to memory exhaustion in the host server. The `sequence` option can be set to specify the maximum sequence length that can be created by an expression, including any intermediate sequences created by sub-expressions. Error `D2015` will be thrown if, during the evaluation of an expression, the evaluator attempts to generate a sequence exceeding this upper limit.
95+
96+
97+
```javascript
98+
const jsonata = require('jsonata');
99+
100+
const data = {JSON: data};
101+
const options = {
102+
sequence: 1e6 // maximum of one million items in a sequence
103+
};
104+
105+
(async () => {
106+
const expression = jsonata('<JSONata expression>', options);
107+
const result = await expression.evaluate(data);
108+
})()
109+
```
110+
111+
As an example, the following JSONata expression attempts to generate a sequence of 100 million numbers. The guardrail configured above would prevent this.
112+
113+
```
114+
[1..10000].([1..10000])
115+
```
116+
117+
### Rogue regular expressions
118+
119+
A number of functions use [regular expressions](regex) to process strings. Alongside the power and flexibility that regexes provide, there are situations whereby badly crafted or malicious expressions could cause the processing engine take an [excessive amount of time](https://en.wikipedia.org/wiki/ReDoS) (exponential to the input string length). Since the regex processing is not implemented in the core JSONata (eval-apply) evaluator, the `timeout` guardrail cannot protect against this.
120+
121+
It is possible to specify which regex processor is invoked by the JSONata evaluator. This is configured using the `RegexEngine` option. When this is not set, the evaluator will use the default JavaScript [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) class.
122+
123+
The [packaged version of JSONata](https://www.npmjs.com/package/jsonata) has no runtime dependencies on other packages, but it is possible to use the `RegexEngine` option to invoke a third-party ReDoS library whenever a regular expression is encountered in a JSONata expression.
124+
125+
The following code shows how this is done using the [redos-detector](https://github.com/tjenkinson/redos-detector) module:
126+
127+
```javascript
128+
const jsonata = require('jsonata');
129+
const redos = require('redos-detector');
130+
131+
// Simple wrapper that invokes redos-detector before delegating
132+
// to built-in RegExp class
133+
const SafeRegExp = function(regex) {
134+
if (!redos.isSafe(regex).safe) {
135+
throw {
136+
code: 'U1001',
137+
stack: (new Error()).stack,
138+
value: regex,
139+
message: 'Rejecting regex (potential ReDoS): ' + regex
140+
};
141+
}
142+
this.regex = regex;
143+
};
144+
145+
SafeRegExp.prototype.exec = function(str) {
146+
return this.regex.exec(str);
147+
}
148+
149+
const data = {JSON: data};
150+
const options = {
151+
RegexEngine: SafeRegExp
152+
};
153+
154+
(async () => {
155+
const expression = jsonata('<JSONata expression>', options);
156+
const result = await expression.evaluate(data);
157+
})()
158+
```
159+
160+
Other similar libraries are available. This is not an endorsement of any particular one. The developer should choose one according to their requirements.

0 commit comments

Comments
 (0)