23tae commented on code in PR #67588:
URL: https://github.com/apache/airflow/pull/67588#discussion_r3310956834


##########
providers/imap/src/airflow/providers/imap/hooks/imap.py:
##########
@@ -311,9 +316,18 @@ def _correct_path(self, name: str, local_output_directory: 
str) -> str:
             else local_output_directory + os.sep + name
         )
 
-    def _create_file(self, name: str, payload: Any, local_output_directory: 
str) -> None:
+    def _create_file(
+        self, name: str, payload: Any, local_output_directory: str, 
overwrite_file: bool = True
+    ) -> None:
         file_path = self._correct_path(name, local_output_directory)
 
+        if not overwrite_file and os.path.exists(file_path):
+            base, ext = os.path.splitext(file_path)
+            counter = 1
+            while os.path.exists(f"{base}_{counter}{ext}"):
+                counter += 1
+            file_path = f"{base}_{counter}{ext}"

Review Comment:
   When `overwrite_file=False`, the current existence check and file creation 
(`"wb"`) are not atomic. In concurrent task runs, another process could create 
the same suffixed filename between `os.path.exists()` and `open()`, leading to 
an accidental overwrite. 
   
   Using exclusive creation mode (`"xb"`) and retrying on `FileExistsError` 
would make this atomic and safer.
   
   ```suggestion
               while True:
                   file_path = f"{base}_{counter}{ext}"
                   try:
                       with open(file_path, "xb") as file:
                           file.write(payload)
                       return
                   except FileExistsError:
                       counter += 1
   ```
   



-- 
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