pierrejeambrun commented on code in PR #45609:
URL: https://github.com/apache/airflow/pull/45609#discussion_r1928996837


##########
airflow/api_fastapi/logging/decorators.py:
##########
@@ -0,0 +1,156 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import itertools
+import json
+import logging
+from typing import Annotated
+
+import pendulum
+from fastapi import Depends, Request
+from pendulum.parsing.exceptions import ParserError
+
+from airflow.api_fastapi.common.db.common import SessionDep
+from airflow.api_fastapi.core_api.security import 
get_user_with_exception_handling
+from airflow.auth.managers.models.base_user import BaseUser
+from airflow.models import Log
+from airflow.utils.log import secrets_masker
+
+logger = logging.getLogger(__name__)
+
+
+def _mask_connection_fields(extra_fields):
+    """Mask connection fields."""
+    result = {}
+    for k, v in extra_fields.items():
+        if k == "extra" and v:
+            try:
+                extra = json.loads(v)
+                extra = {k: secrets_masker.redact(v, k) for k, v in 
extra.items()}
+                result[k] = dict(extra)
+            except json.JSONDecodeError:
+                result[k] = "Encountered non-JSON in `extra` field"
+        else:
+            result[k] = secrets_masker.redact(v, k)
+    return result
+
+
+def _mask_variable_fields(extra_fields):
+    """
+    Mask the 'val_content' field if 'key_content' is in the mask list.
+
+    The variable requests values and args comes in this form:
+    {'key': 'key_content', 'val': 'val_content', 'description': 
'description_content'}
+    """
+    result = {}
+    keyname = None
+    for k, v in extra_fields.items():
+        if k == "key":
+            keyname = v
+            result[k] = v
+        elif keyname and (k == "val" or k == "value"):
+            x = secrets_masker.redact(v, keyname)
+            result[k] = x
+            keyname = None
+        else:
+            result[k] = v
+    return result
+
+
+def action_logging(event: str | None = None):
+    async def log_action(
+        request: Request,
+        session: SessionDep,
+        user: Annotated[BaseUser, Depends(get_user_with_exception_handling)],
+    ):
+        """Log user actions."""
+        request_body = await request.json()
+        masked_body_json = {k: secrets_masker.redact(v, k) for k, v in 
request_body.items()}
+
+        event_name = event or request.url.path.strip("/").replace("/", ".")
+
+        if not user:
+            user_name = "anonymous"
+            user_display = ""
+        else:
+            user_name = user.get_name()
+            user_display = user.get_name()
+
+        hasJsonBody = "application/json" in 
request.headers.get("content-type", "") and request.json
+
+        fields_skip_logging = {
+            "csrf_token",
+            "_csrf_token",
+            "is_paused",
+            "dag_id",
+            "task_id",
+            "dag_run_id",
+            "run_id",
+            "logical_date",
+        }
+
+        extra_fields = {
+            k: secrets_masker.redact(v, k)
+            for k, v in itertools.chain(request.query_params.items(), 
request.path_params.items())
+            if k not in fields_skip_logging
+        }
+        if event_name and event_name.split(".")[-1] == "variables":
+            extra_fields = _mask_variable_fields(
+                {k: v for k, v in request_body.items()} if hasJsonBody else 
extra_fields

Review Comment:
   I think that covers listing variables for instance.
   `GET /api/v1/variables`
   But it will note activate masking variable fields for retrieving a single 
variable, for intance:
   `GET /api/v1/variables/{variable_name}`
   
   I think we need to cover both type of url. (detail ones and list ones).



##########
airflow/api_fastapi/core_api/routes/public/dag_run.py:
##########
@@ -331,9 +332,13 @@ def get_dag_runs(
             status.HTTP_409_CONFLICT,
         ]
     ),
+    dependencies=[Depends(action_logging())],
 )
 def trigger_dag_run(
-    dag_id, body: TriggerDAGRunPostBody, request: Request, session: SessionDep
+    dag_id,
+    body: TriggerDAGRunPostBody,
+    request: Request,
+    session: SessionDep,

Review Comment:
   We need to update the `trigger_dag_run_test` to assert that the action is 
correctly logged in the database. You can take a look at the legacy API, I 
remember this was also done for certain endpoints. As this is the first one 
where we log something we should test that it works properly.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to