Skip to content

Commit 37f732e

Browse files
Add note on how to prevent ES|QL injection attacks
1 parent cd96ea7 commit 37f732e

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

docs/reference/esql-query-builder.md

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,26 @@ query = (
203203
)
204204
```
205205

206+
### Preventing injection attacks
207+
208+
ES|QL, like most query languages, is vulnerable to [code injection attacks](https://en.wikipedia.org/wiki/Code_injection) if untrusted data provided by users is added to a query. To eliminate this risk, ES|QL allows untrusted data to be given separately from the query as parameters.
209+
210+
Continuing with the example above, let's assume that the application needs a `find_employee_by_name()` function that searches for the name given as an argument. If this argument is received by the application from users, then it is considered untrusted and cannot be added to the query directly. Here is how to code the function in a secure manner:
211+
212+
```python
213+
def find_employee_by_name(name):
214+
query = (
215+
ESQL.from_("employees")
216+
.keep("first_name", "last_name", "height")
217+
.where(E("first_name") == E("?"))
218+
)
219+
return client.esql.query(query=str(query), params=[name])
220+
```
221+
222+
Here the part of the query in which the untrusted data needs to be inserted is replaced with a parameter, which in ES|QL is defined by the question mark. In Python the parameter is given as `E("?")` so that it is treated as an expression and not as a literal string.
223+
224+
The list of values given in the `params` argument to the query endpoint are assigned in order to the parameters defined in the query.
225+
206226
## Using ES|QL functions
207227

208228
The ES|QL language includes a rich set of functions that can be used in expressions and conditionals. These can be included in expressions given as strings, as shown in the example below:
@@ -235,6 +255,6 @@ query = (
235255
)
236256
```
237257

238-
Note that arguments passed to functions are assumed to be literals. When passing field names, it is necessary to wrap them with the `E()` helper function so that they are interpreted correctly.
258+
Note that arguments passed to functions are assumed to be literals. When passing field names, parameters or other ES|QL expressions, it is necessary to wrap them with the `E()` helper function so that they are interpreted correctly.
239259

240260
You can find the complete list of available functions in the Python client's [ES|QL API reference documentation](https://elasticsearch-py.readthedocs.io/en/stable/esql.html#module-elasticsearch.esql.functions).

0 commit comments

Comments
 (0)