Repository: apache/airflow

Issue:
Json Parse Error in Tree View
<!--

Welcome to Apache Airflow!  For a smooth issue process, try to answer the following questions.
Don't worry if they're not all applicable; just try to include what you can :-)

If you need to include code snippets or logs, please put them in fenced code
blocks.  If they're super-long, please use the details tag like
<details><summary>super-long log</summary> lots of stuff </details>

Please delete these comment blocks before submitting the issue.

-->

<!--

IMPORTANT!!!

PLEASE CHECK "SIMILAR TO X EXISTING ISSUES" OPTION IF VISIBLE
NEXT TO "SUBMIT NEW ISSUE" BUTTON!!!

PLEASE CHECK IF THIS ISSUE HAS BEEN REPORTED PREVIOUSLY USING SEARCH!!!

Please complete the next sections or the issue will be closed.
This questions are the first thing we need to know to understand the context.

-->

**Apache Airflow version**: 1.10.10

**What happened**:
When DAG is triggered with custom configuration that contains escape characters in a json variable value, tree view will fail to load due to json parse error at https://github.com/apache/airflow/blob/master/airflow/www/templates/airflow/tree.html#L139

**What you expected to happen**:
Tree view should load

<!-- What do you think went wrong? -->

**How to reproduce it**:
Create any simple dag and trigger with api call or on UI and provide following as configuration.
```
{
     "abc": "this is simple message\n"
}
```

The new logic in tree view will turn above json into string, then trying to parse it out.
<img width="392" alt="Screen Shot 2020-04-22 at 6 44 11 PM" src="https://user-images.githubusercontent.com/1458754/80041001-4b02f780-84c9-11ea-97ff-44e78a4b774e.png">


<!---

As minimally and precisely as possible. Keep in mind we do not have access to your cluster or dags.

If you are using kubernetes, please attempt to recreate the issue using minikube or kind.

## Install minikube/kind

- Minikube https://minikube.sigs.k8s.io/docs/start/
- Kind https://kind.sigs.k8s.io/docs/user/quick-start/

If this is a UI bug, please provide a screenshot of the bug or a link to a youtube video of the bug in action

You can include images using the .md sytle of
![alt text](http://url/to/img.png)

To record a screencast, mac users can use QuickTime and then create an unlisted youtube video with the resulting .mov file.

--->


**Anything else we need to know**:
Introduce in https://github.com/apache/airflow/pull/7492

<!--

How often does this problem occur? Once? Every time etc?

Any relevant logs to include? Put them here in side a detail tag:
<details><summary>x.log</summary> lots of stuff </details>

-->



Discussion:
Thanks for opening your first issue here! Be sure to follow the issue template!

cc @houqp 
Thanks @kaxil for the tag, I will look into this. It should escape all json strings.

Resolving patch:
diff --git a/airflow/www/views.py b/airflow/www/views.py
--- a/airflow/www/views.py
+++ b/airflow/www/views.py
@@ -1506,14 +1506,18 @@ def recurse_nodes(task, visited):
                                              'num_runs': num_runs})
         external_logs = conf.get('elasticsearch', 'frontend')
 
+        # avoid spaces to reduce payload size
+        data = htmlsafe_json_dumps(data, separators=(',', ':'))
+        # escape slashes to avoid JSON parse error in JS
+        data = data.replace('\\', '\\\\')
+
         return self.render_template(
             'airflow/tree.html',
             operators=sorted({op.task_type: op for op in dag.tasks}.values(), key=lambda x: x.task_type),
             root=root,
             form=form,
             dag=dag,
-            # avoid spaces to reduce payload size
-            data=htmlsafe_json_dumps(data, separators=(',', ':')),
+            data=data,
             blur=blur, num_runs=num_runs,
             show_external_logs=bool(external_logs))
 


Test patch:
diff --git a/tests/www/test_views.py b/tests/www/test_views.py
--- a/tests/www/test_views.py
+++ b/tests/www/test_views.py
@@ -545,6 +545,25 @@ def test_view_uses_existing_dagbag(self, endpoint, mock_get_dag):
         mock_get_dag.assert_called_once_with('example_bash_operator')
         self.check_content_in_response('example_bash_operator', resp)
 
+    @parameterized.expand([
+        ("hello\nworld", "hello\\\\nworld"),
+        ("hello'world", "hello\\\\u0027world"),
+        ("<script>", "\\\\u003cscript\\\\u003e"),
+    ])
+    def test_escape_in_tree_view(self, test_str, seralized_test_str):
+        dag = self.dagbag.dags['test_tree_view']
+        dag.create_dagrun(
+            run_id=self.run_id,
+            execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
+            start_date=timezone.utcnow(),
+            state=State.RUNNING,
+            conf={"abc": test_str},
+        )
+
+        url = 'tree?dag_id=test_tree_view'
+        resp = self.client.get(url, follow_redirects=True)
+        self.check_content_in_response(f'"conf":{{"abc":"{seralized_test_str}"}}', resp)
+
     def test_dag_details_trigger_origin_tree_view(self):
         dag = self.dagbag.dags['test_tree_view']
         dag.create_dagrun(