From d4d197abb116487439c6132b438dd50bc437650b Mon Sep 17 00:00:00 2001 From: Reimar Bauer Date: Mon, 30 Nov 2026 19:13:47 +0100 Subject: [PATCH 1/5] Profile image: stored with / on Windows servers, Change Avatar without Gravatar (#3403) a server on Windows stored the profile image as profile\..., send_from_directory refused it with 404; new uploads are stored with /, rows with \ are served and deleted again; msui shows an uploaded image once the server has stored it, instead of fetching it back and falling back to gravatar.com ("Gravatar not found"), and no longer shows an image the server refuse. --- mslib/mscolab/file_manager.py | 18 ++++++++++-- mslib/msui/mscolab.py | 7 +++-- tests/_test_mscolab/test_server.py | 31 ++++++++++++++++++++ tests/_test_msui/test_mscolab.py | 45 ++++++++++++++++++++++++++++++ 4 files changed, 95 insertions(+), 6 deletions(-) diff --git a/mslib/mscolab/file_manager.py b/mslib/mscolab/file_manager.py index 5998543cd..10844fa23 100644 --- a/mslib/mscolab/file_manager.py +++ b/mslib/mscolab/file_manager.py @@ -53,6 +53,17 @@ UPDATABLE_OPERATION_ATTRIBUTES = ("path", "description", "category", "active", "last_used") +def profile_image_url_path(profile_image_path): + """ + The stored path of a profile image below UPLOAD_FOLDER with forward slashes + + Servers on Windows stored it with backslashes (e.g. profile\\1-....png) before 12.0.0; send_from_directory + refuses those there, so the profile image was never shown. The file name is a secure_filename, a backslash + can only be a separator. + """ + return profile_image_path.replace("\\", "/") + + class FileManager: """Class with handler functions for file related functionalities""" @@ -328,7 +339,7 @@ def delete_user_profile_image(self, image_to_be_deleted): upload_folder = upload_folder.replace('\\', '/') # Construct the full path to the image file - full_image_path = Path(upload_folder) / image_to_be_deleted + full_image_path = Path(upload_folder) / profile_image_url_path(image_to_be_deleted) # Check if the file exists and delete it if full_image_path.exists() and full_image_path.is_file(): @@ -383,7 +394,8 @@ def upload_file(self, file, subfolder=None, identifier=None, include_prefix=Fals # directory, which is configurable, and always uses forward slashes. static_file_path = str(PurePosixPath(ATTACHMENTS_URL_PREFIX, str(subfolder), file_name)) else: - static_file_path = str(Path(file_path).relative_to(Path(upload_folder))) + # stored in the database and served with send_from_directory, which refuses a backslash on Windows + static_file_path = Path(file_path).relative_to(Path(upload_folder)).as_posix() logging.debug(f'Relative Path: {static_file_path}') return static_file_path @@ -423,7 +435,7 @@ def get_user_profile_image(self, user_id, op_id, requesting_user_id): user = db.session.get(User, user_id) if user: if user.profile_image_path: - return True, user.profile_image_path + return True, profile_image_url_path(user.profile_image_path) return False, "Profile image not found" else: return False, "User not found" diff --git a/mslib/msui/mscolab.py b/mslib/msui/mscolab.py index 6613d23e0..5dc01ecd5 100644 --- a/mslib/msui/mscolab.py +++ b/mslib/msui/mscolab.py @@ -565,13 +565,12 @@ def upload_image(self, _=None): mime_type, _ = mimetypes.guess_type(file_name) file_format = mime_type.split('/')[1].upper() try: - # Resize the image and set profile image pixmap + # Resize the image image = Image.open(file_name) image = image.resize((64, 64), Image.LANCZOS) img_byte_arr = io.BytesIO() image.save(img_byte_arr, format=file_format) img_byte_arr.seek(0) - self.set_profile_pixmap(img_byte_arr.getvalue()) # Prepare the file data for upload try: @@ -583,8 +582,10 @@ def upload_image(self, _=None): # Check response status if response.status_code == 200: + # shown only once the server has it, and without fetching it back: when that failed, e.g. + # from a server on Windows before 12.0.0, msui fell back to the Gravatar + self.set_profile_pixmap(img_byte_arr.getvalue()) QMessageBox.information(self.prof_diag, "Success", "Image uploaded successfully") - self.fetch_profile_image(refresh=True) else: # the answer comes from the MSColab server QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html( diff --git a/tests/_test_mscolab/test_server.py b/tests/_test_mscolab/test_server.py index d8e62149d..a0f1414d3 100644 --- a/tests/_test_mscolab/test_server.py +++ b/tests/_test_mscolab/test_server.py @@ -638,6 +638,37 @@ def test_stored_profile_image_with_other_extension_served_as_download(self): assert response.headers["X-Content-Type-Options"] == "nosniff" assert response.headers["Content-Security-Policy"] == "sandbox" + def test_profile_image_stored_with_forward_slashes(self): + # a server on Windows stored profile\...; send_from_directory refuses a backslash there (#3403) + assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) + with self.app.test_client() as test_client: + token = self._get_token(test_client, self.userdata) + assert self._upload_profile_image(test_client, token, self.userdata[0]).status_code == 200 + profile_image_path = get_user(self.userdata[0]).profile_image_path + assert profile_image_path.startswith("profile/") + assert "\\" not in profile_image_path + + def test_profile_image_stored_with_backslashes_served_and_deleted(self): + # stored by a server on Windows before 12.0.0, the database may since have moved to another system + assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) + image = io.BytesIO() + Image.new('RGB', (4, 4), color='yellow').save(image, format='PNG') + profile_dir = Path(current_app.config['UPLOAD_FOLDER']) / "profile" + profile_dir.mkdir(parents=True, exist_ok=True) + image_file = profile_dir / "windows.png" + image_file.write_bytes(image.getvalue()) + user = get_user(self.userdata[0]) + user.profile_image_path = "profile\\windows.png" + db.session.commit() + with self.app.test_client() as test_client: + token = self._get_token(test_client, self.userdata) + response = test_client.get('/fetch_profile_image', data={"token": token, "user_id": str(user.id)}) + assert response.status_code == 200 + assert response.data == image.getvalue() + response = test_client.post('/delete_own_account', data={"token": token}) + assert response.status_code == 200 + assert not image_file.exists() + def test_unauthorized_profile_image_upload(self): other_user_data = 'other@ex.com', 'other', 'other', 'Other' assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) diff --git a/tests/_test_msui/test_mscolab.py b/tests/_test_msui/test_mscolab.py index fa4b44088..48d3a7eb6 100644 --- a/tests/_test_msui/test_mscolab.py +++ b/tests/_test_msui/test_mscolab.py @@ -1847,6 +1847,51 @@ def pixmap_updated(): assert initial_pixmap != fetched_pixmap assert uploaded_pixmap == fetched_pixmap + def _upload_image_from_profile(self, qtbot, tmp_path, image_format, suffix, fetch_fails=False): + self._connect_to_mscolab(qtbot) + modify_config_file({"MSS_auth": {self.url: self.userdata[0]}}) + self._login(qtbot, self.userdata[0], self.userdata[2]) + self.window.mscolab.profile_action.trigger() + image_path = tmp_path / f"avatar.{suffix}" + Image.new("RGB", (64, 64), color="cyan").save(image_path, format=image_format) + initial_pixmap = self.window.mscolab.profile_dialog.gravatarLabel.pixmap().toImage() + # e.g. a server on Windows before 12.0.0, which answers fetch_profile_image with 404 + fetch = mock.patch.object(self.window.mscolab.conn, "request_get", side_effect=mscolab.MSColabConnectionError) + with mock.patch("PyQt5.QtWidgets.QFileDialog.getOpenFileName", return_value=(str(image_path), "")), \ + mock.patch.object(QtWidgets.QMessageBox, "information") as information, \ + mock.patch.object(QtWidgets.QMessageBox, "critical") as critical, \ + mock.patch("mslib.msui.mscolab.show_popup") as popup, \ + mock.patch.object(mscolab.requests, "get") as gravatar_get, \ + (fetch if fetch_fails else mock.MagicMock()): + # gravatar.com answers 404 for an address without a Gravatar + gravatar_get.return_value.raise_for_status.side_effect = requests.exceptions.HTTPError("404 Not Found") + self.window.mscolab.upload_image() + return initial_pixmap, information, critical, popup, gravatar_get + + def test_uploaded_image_shown_without_gravatar(self, qtbot, tmp_path): + """ + A server on Windows before 12.0.0 doesn't return the uploaded image (#3403): fetching it back after the upload + fell back to the Gravatar and showed "Gravatar not found" instead of the uploaded image + """ + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( + qtbot, tmp_path, "PNG", "png", fetch_fails=True) + information.assert_called_once() + critical.assert_not_called() + popup.assert_not_called() + gravatar_get.assert_not_called() + shown = self.window.mscolab.profile_dialog.gravatarLabel.pixmap().toImage() + assert shown != initial_pixmap + assert shown.pixelColor(32, 32) == QtGui.QColor("cyan") + + def test_refused_image_not_shown(self, qtbot, tmp_path): + """An image the server refuses was shown in the profile all the same""" + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( + qtbot, tmp_path, "TIFF", "tiff") + information.assert_not_called() + critical.assert_called_once() + assert "Invalid file type" in critical.call_args.args[2] + assert self.window.mscolab.profile_dialog.gravatarLabel.pixmap().toImage() == initial_pixmap + def test_activate_operation_updates_active_users(self, qtbot): """ Test that selecting an operation updates the active users label correctly. From 839079ec35ca9d586201f87a636fa3e667e4df19 Mon Sep 17 00:00:00 2001 From: Reimar Bauer Date: Mon, 30 Nov 2026 20:18:23 +0100 Subject: [PATCH 2/5] Change Avatar: expired login, format from the image, uploads deleted only inside UPLOAD_FOLDER msui took a rejected token (HTTP 200 "False") for a successful upload; it asks for a new login now. The format is taken from the image, not from the MIME type of the file name (none without an extension, image/x-png from the Windows registry), formats the server refuses are refused before the upload, and the file dialog offers bmp (was *.bpm) and webp. The server deletes a profile image only inside UPLOAD_FOLDER; the stored path is built by stored_upload_path, tested with Windows paths --- mslib/mscolab/file_manager.py | 21 +++-- mslib/msui/mscolab.py | 85 ++++++++--------- tests/_test_mscolab/test_file_manager.py | 10 ++ tests/_test_mscolab/test_server.py | 30 ++++-- tests/_test_msui/test_mscolab.py | 111 ++++++++++++++++++++--- 5 files changed, 185 insertions(+), 72 deletions(-) diff --git a/mslib/mscolab/file_manager.py b/mslib/mscolab/file_manager.py index 10844fa23..fb76a542b 100644 --- a/mslib/mscolab/file_manager.py +++ b/mslib/mscolab/file_manager.py @@ -53,6 +53,14 @@ UPDATABLE_OPERATION_ATTRIBUTES = ("path", "description", "category", "active", "last_used") +def stored_upload_path(file_path, upload_folder): + """ + The path of an uploaded file relative to UPLOAD_FOLDER, as stored in the database: with forward slashes also on + Windows, where send_from_directory refuses a backslash + """ + return file_path.relative_to(upload_folder).as_posix() + + def profile_image_url_path(profile_image_path): """ The stored path of a profile image below UPLOAD_FOLDER with forward slashes @@ -334,12 +342,14 @@ def delete_user_profile_image(self, image_to_be_deleted): """ This function is called when deleting account or updating the profile picture """ - upload_folder = current_app.config['UPLOAD_FOLDER'] - if sys.platform.startswith('win'): - upload_folder = upload_folder.replace('\\', '/') + upload_folder = Path(current_app.config['UPLOAD_FOLDER']).resolve() # Construct the full path to the image file - full_image_path = Path(upload_folder) / profile_image_url_path(image_to_be_deleted) + full_image_path = (upload_folder / profile_image_url_path(image_to_be_deleted)).resolve() + if not full_image_path.is_relative_to(upload_folder): + # the path comes from the database; e.g. a stored ..\x must not delete a file elsewhere + logging.error(f"Not deleting the profile image {image_to_be_deleted}, it is outside of UPLOAD_FOLDER") + return # Check if the file exists and delete it if full_image_path.exists() and full_image_path.is_file(): @@ -394,8 +404,7 @@ def upload_file(self, file, subfolder=None, identifier=None, include_prefix=Fals # directory, which is configurable, and always uses forward slashes. static_file_path = str(PurePosixPath(ATTACHMENTS_URL_PREFIX, str(subfolder), file_name)) else: - # stored in the database and served with send_from_directory, which refuses a backslash on Windows - static_file_path = Path(file_path).relative_to(Path(upload_folder)).as_posix() + static_file_path = stored_upload_path(file_path, Path(upload_folder)) logging.debug(f'Relative Path: {static_file_path}') return static_file_path diff --git a/mslib/msui/mscolab.py b/mslib/msui/mscolab.py index 5dc01ecd5..28382054b 100644 --- a/mslib/msui/mscolab.py +++ b/mslib/msui/mscolab.py @@ -38,7 +38,6 @@ import types import requests import re -import mimetypes import urllib.parse from pathlib import Path @@ -53,7 +52,9 @@ from mslib.msui.mscolab_archive_browser import MSColab_OperationArchiveBrowser from mslib.msui.mscolab_connect_dialog import MSColab_ConnectDialog from mslib.mscolab.api import endpoints +from mslib.mscolab.api.attachments import IMAGE_EXTENSIONS, IMAGE_FORMATS from mslib.mscolab.api.schemas import ( + AUTH_FAILED_TEXT, MAX_VERSION_NAME_LENGTH, CreateOperationRequest, CreateOperationResponse, @@ -558,48 +559,48 @@ def on_context_menu(point): self.fetch_profile_image() def upload_image(self, _=None): - file_name, _ = QFileDialog.getOpenFileName(self.prof_diag, "Open Image", "", - "Image (*.png *.gif *.jpg *.jpeg *.bpm)") - if file_name: - # Determine the image format - mime_type, _ = mimetypes.guess_type(file_name) - file_format = mime_type.split('/')[1].upper() - try: - # Resize the image - image = Image.open(file_name) - image = image.resize((64, 64), Image.LANCZOS) + file_name, _ = QFileDialog.getOpenFileName( + self.prof_diag, "Open Image", "", f"Image ({' '.join(f'*.{ext}' for ext in IMAGE_EXTENSIONS)})") + if not file_name: + return + try: + with Image.open(file_name) as image: + # the format of the content, not a MIME type guessed from the file name: on Windows that comes from + # the registry, e.g. image/x-png, which Pillow can't save, and a name without an extension has none + file_format = image.format + if file_format not in IMAGE_FORMATS: + QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html( + f"A profile image has to be one of {', '.join(IMAGE_FORMATS)}, not {file_format}.")) + return img_byte_arr = io.BytesIO() - image.save(img_byte_arr, format=file_format) - img_byte_arr.seek(0) - - # Prepare the file data for upload - try: - img_byte_arr.seek(0) # Reset buffer position - # the image is stored for the user of the token - response = self.conn.request_post( - endpoints.UPLOAD_PROFILE_IMAGE, - files={'image': (os.path.basename(file_name), img_byte_arr, mime_type)}) - - # Check response status - if response.status_code == 200: - # shown only once the server has it, and without fetching it back: when that failed, e.g. - # from a server on Windows before 12.0.0, msui fell back to the Gravatar - self.set_profile_pixmap(img_byte_arr.getvalue()) - QMessageBox.information(self.prof_diag, "Success", "Image uploaded successfully") - else: - # the answer comes from the MSColab server - QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html( - f"Failed to upload image: {sc.response_message(response, response.text)}")) - - except requests.exceptions.RequestException as e: - QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html(f"Error occurred: {e}")) - - except UnidentifiedImageError as e: - QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html( - f'Cannot identify image file. Please check the file format. Error : {e}')) - except OSError as e: - QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html( - f'Cannot identify image file. Please check the file format. Error: {e}')) + image.resize((64, 64), Image.LANCZOS).save(img_byte_arr, format=file_format) + except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError, SyntaxError, EOFError) as e: + QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html( + f'Cannot identify image file. Please check the file format. Error: {e}')) + return + try: + # the image is stored for the user of the token + response = self.conn.request_post( + endpoints.UPLOAD_PROFILE_IMAGE, + files={'image': (os.path.basename(file_name), io.BytesIO(img_byte_arr.getvalue()), + Image.MIME.get(file_format, "application/octet-stream"))}) + except requests.exceptions.RequestException as e: + QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html(f"Error occurred: {e}")) + return + if response.content == AUTH_FAILED_TEXT.encode(): + # the server answers a rejected token with HTTP 200 and "False", nothing was stored + show_popup(self.prof_diag, "Error", "Session expired, new login required") + self.prof_diag.close() + self.logout() + elif response.status_code == 200: + # shown only once the server has it, and without fetching it back: when that failed, e.g. + # from a server on Windows before 12.0.0, msui fell back to the Gravatar + self.set_profile_pixmap(img_byte_arr.getvalue()) + QMessageBox.information(self.prof_diag, "Success", "Image uploaded successfully") + else: + # the answer comes from the MSColab server + QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html( + f"Failed to upload image: {sc.response_message(response, response.text)}")) def delete_own_account(self, _=None): reply = QMessageBox.question( diff --git a/tests/_test_mscolab/test_file_manager.py b/tests/_test_mscolab/test_file_manager.py index e666447b3..b666adaad 100644 --- a/tests/_test_mscolab/test_file_manager.py +++ b/tests/_test_mscolab/test_file_manager.py @@ -28,6 +28,7 @@ import pytest import os import mock +from pathlib import PurePosixPath, PureWindowsPath from werkzeug.datastructures import FileStorage @@ -38,10 +39,19 @@ from mslib.mscolab.seed import add_user, get_user, add_operation from mslib.mscolab.utils import ATTACHMENTS_URL_PREFIX, get_operation_dir from mslib.mscolab.seed import XML_CONTENT_INIT +from mslib.mscolab.file_manager import stored_upload_path from flask import current_app +def test_stored_upload_path_with_forward_slashes(): + """A server on Windows stored profile\\..., send_from_directory refused it there with 404 (#3403)""" + upload_folder = PureWindowsPath("C:/mss/colabdata/uploads") + assert stored_upload_path(upload_folder / "profile" / "1-x.png", upload_folder) == "profile/1-x.png" + upload_folder = PurePosixPath("/srv/mss/colabdata/uploads") + assert stored_upload_path(upload_folder / "profile" / "1-x.png", upload_folder) == "profile/1-x.png" + + class Test_FileManager: @pytest.fixture(autouse=True) def setup(self, mscolab_app, mscolab_managers): diff --git a/tests/_test_mscolab/test_server.py b/tests/_test_mscolab/test_server.py index a0f1414d3..52f4a96d4 100644 --- a/tests/_test_mscolab/test_server.py +++ b/tests/_test_mscolab/test_server.py @@ -638,16 +638,6 @@ def test_stored_profile_image_with_other_extension_served_as_download(self): assert response.headers["X-Content-Type-Options"] == "nosniff" assert response.headers["Content-Security-Policy"] == "sandbox" - def test_profile_image_stored_with_forward_slashes(self): - # a server on Windows stored profile\...; send_from_directory refuses a backslash there (#3403) - assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) - with self.app.test_client() as test_client: - token = self._get_token(test_client, self.userdata) - assert self._upload_profile_image(test_client, token, self.userdata[0]).status_code == 200 - profile_image_path = get_user(self.userdata[0]).profile_image_path - assert profile_image_path.startswith("profile/") - assert "\\" not in profile_image_path - def test_profile_image_stored_with_backslashes_served_and_deleted(self): # stored by a server on Windows before 12.0.0, the database may since have moved to another system assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) @@ -669,6 +659,26 @@ def test_profile_image_stored_with_backslashes_served_and_deleted(self): assert response.status_code == 200 assert not image_file.exists() + def test_profile_image_outside_upload_folder_not_deleted(self): + # the stored path is only joined onto UPLOAD_FOLDER; a backslash counts as separator since #3403 + assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) + upload_folder = Path(current_app.config['UPLOAD_FOLDER']) + # as on a server with profile images; the system resolves profile/.. only if it exists + (upload_folder / "profile").mkdir(parents=True, exist_ok=True) + outside = upload_folder.parent / "outside-of-uploads.png" + outside.write_bytes(b"not a profile image") + try: + user = get_user(self.userdata[0]) + user.profile_image_path = "profile\\..\\..\\outside-of-uploads.png" + db.session.commit() + with self.app.test_client() as test_client: + token = self._get_token(test_client, self.userdata) + response = test_client.post('/delete_own_account', data={"token": token}) + assert response.status_code == 200 + assert outside.exists() + finally: + outside.unlink(missing_ok=True) + def test_unauthorized_profile_image_upload(self): other_user_data = 'other@ex.com', 'other', 'other', 'Other' assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) diff --git a/tests/_test_msui/test_mscolab.py b/tests/_test_msui/test_mscolab.py index 48d3a7eb6..16ab8eba7 100644 --- a/tests/_test_msui/test_mscolab.py +++ b/tests/_test_msui/test_mscolab.py @@ -1847,50 +1847,133 @@ def pixmap_updated(): assert initial_pixmap != fetched_pixmap assert uploaded_pixmap == fetched_pixmap - def _upload_image_from_profile(self, qtbot, tmp_path, image_format, suffix, fetch_fails=False): + def _upload_image_from_profile(self, qtbot, tmp_path, image_format="PNG", file_name="avatar.png", + request_get=None, request_post=None, guess_type=None): self._connect_to_mscolab(qtbot) modify_config_file({"MSS_auth": {self.url: self.userdata[0]}}) self._login(qtbot, self.userdata[0], self.userdata[2]) self.window.mscolab.profile_action.trigger() - image_path = tmp_path / f"avatar.{suffix}" + image_path = tmp_path / file_name Image.new("RGB", (64, 64), color="cyan").save(image_path, format=image_format) initial_pixmap = self.window.mscolab.profile_dialog.gravatarLabel.pixmap().toImage() - # e.g. a server on Windows before 12.0.0, which answers fetch_profile_image with 404 - fetch = mock.patch.object(self.window.mscolab.conn, "request_get", side_effect=mscolab.MSColabConnectionError) + conn = self.window.mscolab.conn + patches = [mock.patch.object(conn, name, **kwargs) for name, kwargs in + (("request_get", request_get), ("request_post", request_post)) if kwargs is not None] + if guess_type is not None: + # e.g. a Windows registry that maps .png to image/x-png + patches.append(mock.patch("mimetypes.guess_type", return_value=guess_type)) with mock.patch("PyQt5.QtWidgets.QFileDialog.getOpenFileName", return_value=(str(image_path), "")), \ mock.patch.object(QtWidgets.QMessageBox, "information") as information, \ mock.patch.object(QtWidgets.QMessageBox, "critical") as critical, \ mock.patch("mslib.msui.mscolab.show_popup") as popup, \ - mock.patch.object(mscolab.requests, "get") as gravatar_get, \ - (fetch if fetch_fails else mock.MagicMock()): + mock.patch.object(mscolab.requests, "get") as gravatar_get: # gravatar.com answers 404 for an address without a Gravatar gravatar_get.return_value.raise_for_status.side_effect = requests.exceptions.HTTPError("404 Not Found") - self.window.mscolab.upload_image() + for patch in patches: + patch.start() + try: + self.window.mscolab.upload_image() + finally: + for patch in patches: + patch.stop() return initial_pixmap, information, critical, popup, gravatar_get + def _shown_profile_image(self): + return self.window.mscolab.profile_dialog.gravatarLabel.pixmap().toImage() + + def _shows_uploaded_image(self): + # cyan, up to the losses of e.g. WEBP + color = self._shown_profile_image().pixelColor(32, 32) + return color.red() <= 8 and color.green() >= 247 and color.blue() >= 247 + def test_uploaded_image_shown_without_gravatar(self, qtbot, tmp_path): """ A server on Windows before 12.0.0 doesn't return the uploaded image (#3403): fetching it back after the upload fell back to the Gravatar and showed "Gravatar not found" instead of the uploaded image """ + # such a server answers fetch_profile_image with 404 initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( - qtbot, tmp_path, "PNG", "png", fetch_fails=True) + qtbot, tmp_path, request_get={"side_effect": mscolab.MSColabConnectionError}) information.assert_called_once() critical.assert_not_called() popup.assert_not_called() gravatar_get.assert_not_called() - shown = self.window.mscolab.profile_dialog.gravatarLabel.pixmap().toImage() - assert shown != initial_pixmap - assert shown.pixelColor(32, 32) == QtGui.QColor("cyan") + assert self._shown_profile_image() != initial_pixmap + assert self._shows_uploaded_image() + + @pytest.mark.parametrize("image_format, file_name, guess_type", [ + # mimetypes gives no type for a name without an extension + ("PNG", "avatar", None), + # on Windows mimetypes reads the registry, Pillow can't save the format X-PNG + ("PNG", "avatar.png", ("image/x-png", None)), + ("BMP", "avatar.bmp", None), + ("WEBP", "avatar.webp", None), + ]) + def test_uploaded_image_format_from_its_content(self, qtbot, tmp_path, image_format, file_name, guess_type): + """The format was taken from the MIME type of the file name, which raised for these""" + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( + qtbot, tmp_path, image_format, file_name, guess_type=guess_type) + information.assert_called_once() + critical.assert_not_called() + assert self._shows_uploaded_image() + + def test_upload_offers_the_formats_of_the_server(self, qtbot, tmp_path): + """The file dialog offered *.bpm instead of *.bmp, and no *.webp""" + self._connect_to_mscolab(qtbot) + modify_config_file({"MSS_auth": {self.url: self.userdata[0]}}) + self._login(qtbot, self.userdata[0], self.userdata[2]) + self.window.mscolab.profile_action.trigger() + with mock.patch("PyQt5.QtWidgets.QFileDialog.getOpenFileName", return_value=("", "")) as dialog: + self.window.mscolab.upload_image() + offered = dialog.call_args.args[3] + for ext in ("png", "jpg", "jpeg", "gif", "bmp", "webp"): + assert f"*.{ext}" in offered + assert "*.bpm" not in offered + + def test_image_of_other_format_not_uploaded(self, qtbot, tmp_path): + """The server refuses e.g. TIFF; it is refused before the upload""" + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( + qtbot, tmp_path, "TIFF", "avatar.tiff", request_post={"side_effect": AssertionError("uploaded")}) + information.assert_not_called() + critical.assert_called_once() + assert "not TIFF" in critical.call_args.args[2] + assert self._shown_profile_image() == initial_pixmap def test_refused_image_not_shown(self, qtbot, tmp_path): - """An image the server refuses was shown in the profile all the same""" + """An image the server refused was shown in the profile all the same""" + refused = mock.Mock(status_code=400, content=b'{"message": "Invalid file type"}', + text='{"message": "Invalid file type"}') + refused.json.return_value = {"message": "Invalid file type"} initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( - qtbot, tmp_path, "TIFF", "tiff") + qtbot, tmp_path, request_post={"return_value": refused}) information.assert_not_called() critical.assert_called_once() assert "Invalid file type" in critical.call_args.args[2] - assert self.window.mscolab.profile_dialog.gravatarLabel.pixmap().toImage() == initial_pixmap + assert self._shown_profile_image() == initial_pixmap + + def test_upload_with_expired_session(self, qtbot, tmp_path): + """ + The server answers a rejected token with HTTP 200 and "False": msui showed the image and "Image uploaded + successfully", though nothing was stored + """ + self._connect_to_mscolab(qtbot) + modify_config_file({"MSS_auth": {self.url: self.userdata[0]}}) + self._login(qtbot, self.userdata[0], self.userdata[2]) + self.window.mscolab.profile_action.trigger() + # e.g. from another msui + self.window.mscolab.conn.request_post(endpoints.LOGOUT_EVERYWHERE) + image_path = tmp_path / "avatar.png" + Image.new("RGB", (64, 64), color="cyan").save(image_path) + with mock.patch("PyQt5.QtWidgets.QFileDialog.getOpenFileName", return_value=(str(image_path), "")), \ + mock.patch.object(QtWidgets.QMessageBox, "information") as information, \ + mock.patch("mslib.msui.mscolab.show_popup") as popup, \ + mock.patch.object(mscolab.requests, "get") as gravatar_get: + gravatar_get.return_value.raise_for_status.side_effect = requests.exceptions.HTTPError("404 Not Found") + self.window.mscolab.upload_image() + information.assert_not_called() + popup.assert_called_once() + assert "Session expired" in popup.call_args.args[2] + assert self.window.mscolab.conn is None def test_activate_operation_updates_active_users(self, qtbot): """ From a95ec10eabf08666a6512e0d850963a8cfd43fd2 Mon Sep 17 00:00:00 2001 From: Reimar Bauer Date: Tue, 1 Dec 2026 13:48:55 +0100 Subject: [PATCH 3/5] Profile images: phone photos (MPO), upright and square, symlinks below UPLOAD_FOLDER Pillow names the JPEGs of many phones MPO: the server accepts them as chat and profile images, msui uploads them as JPEG. msui opens only the formats the server accepts, applies the EXIF orientation and cuts the image to a square, and reports a failed conversion as such. Opening the profile asks for a new login when the session expired and shows the Gravatar when the server can't be reached; "Remove Gravatar" keeps an uploaded image. The server checks the stored path of a profile image by its parts instead of resolving it: an image that is a symlink is removed itself, not its target, and a symlinked directory below UPLOAD_FOLDER is allowed --- mslib/mscolab/api/attachments.py | 5 +- mslib/mscolab/file_manager.py | 16 ++--- mslib/msui/mscolab.py | 56 ++++++++++++----- tests/_test_mscolab/test_server.py | 61 +++++++++++++++++++ tests/_test_msui/test_mscolab.py | 96 +++++++++++++++++++++++++++++- 5 files changed, 205 insertions(+), 29 deletions(-) diff --git a/mslib/mscolab/api/attachments.py b/mslib/mscolab/api/attachments.py index c48321110..e9fb03345 100644 --- a/mslib/mscolab/api/attachments.py +++ b/mslib/mscolab/api/attachments.py @@ -24,8 +24,9 @@ limitations under the License. """ -# Formats of images, by the format PIL detects, with the extension they are stored with -IMAGE_FORMATS = {"PNG": "png", "JPEG": "jpg", "GIF": "gif", "BMP": "bmp", "WEBP": "webp"} +# Formats of images, by the format PIL detects, with the extension they are stored with. MPO is a JPEG with more +# pictures after the first one, e.g. the photos of many phones (portrait or depth photos); it is shown as JPEG. +IMAGE_FORMATS = {"PNG": "png", "JPEG": "jpg", "MPO": "jpg", "GIF": "gif", "BMP": "bmp", "WEBP": "webp"} IMAGE_EXTENSIONS = ("png", "jpg", "jpeg", "gif", "bmp", "webp") # Default of the server setting MSCOLAB_ATTACHMENT_EXTENSIONS. Left out on purpose: files a browser can run diff --git a/mslib/mscolab/file_manager.py b/mslib/mscolab/file_manager.py index fb76a542b..3a30c673d 100644 --- a/mslib/mscolab/file_manager.py +++ b/mslib/mscolab/file_manager.py @@ -34,7 +34,7 @@ import git import threading import mimetypes -from pathlib import Path, PurePosixPath +from pathlib import Path, PurePosixPath, PureWindowsPath from flask import current_app from werkzeug.utils import secure_filename from sqlalchemy import insert @@ -342,17 +342,17 @@ def delete_user_profile_image(self, image_to_be_deleted): """ This function is called when deleting account or updating the profile picture """ - upload_folder = Path(current_app.config['UPLOAD_FOLDER']).resolve() - - # Construct the full path to the image file - full_image_path = (upload_folder / profile_image_url_path(image_to_be_deleted)).resolve() - if not full_image_path.is_relative_to(upload_folder): - # the path comes from the database; e.g. a stored ..\x must not delete a file elsewhere + relative_path = profile_image_url_path(image_to_be_deleted) + # the path comes from the database: checked by its parts, not resolved, so a directory below UPLOAD_FOLDER may + # be a symlink (e.g. to another volume), and an image that is a symlink is removed itself, not its target + if (PurePosixPath(relative_path).is_absolute() or PureWindowsPath(relative_path).anchor + or ".." in PurePosixPath(relative_path).parts): logging.error(f"Not deleting the profile image {image_to_be_deleted}, it is outside of UPLOAD_FOLDER") return + full_image_path = Path(current_app.config['UPLOAD_FOLDER'], *PurePosixPath(relative_path).parts) # Check if the file exists and delete it - if full_image_path.exists() and full_image_path.is_file(): + if full_image_path.is_symlink() or full_image_path.is_file(): try: full_image_path.unlink() # Delete the file logging.debug(f"Successfully deleted image: {image_to_be_deleted}") diff --git a/mslib/msui/mscolab.py b/mslib/msui/mscolab.py index 28382054b..48e26fd90 100644 --- a/mslib/msui/mscolab.py +++ b/mslib/msui/mscolab.py @@ -41,7 +41,7 @@ import urllib.parse from pathlib import Path -from PIL import Image, UnidentifiedImageError +from PIL import Image, ImageOps, UnidentifiedImageError from mslib.msui import flighttrack as ft from mslib.msui import mscolab_chat as mc @@ -370,7 +370,8 @@ def after_login(self, emailid, url, response): self.ui.usernameLabel.setText(f"{self.user['username']}") self.ui.usernameLabel.show() self.ui.userOptionsTb.show() - self.fetch_profile_image() + if not self.fetch_profile_image(): + return False # enable add operation menu action self.ui.actionAddOperation.setEnabled(True) self.ui.actionCopyIntoNewMSColabOperation.setEnabled(True) @@ -410,13 +411,22 @@ def set_profile_pixmap(self, img_data): self.ui.userOptionsTb.setIcon(icon) def fetch_profile_image(self, refresh=False): + """Shows the profile image of the server, else the Gravatar; False if the session expired (logged out)""" req = FetchProfileImageRequest(user_id=str(self.user["id"])) try: response = self.conn.request_get(endpoints.FETCH_PROFILE_IMAGE, req.to_params()) - except MSColabConnectionError: + except MSColabSessionExpiredError as ex: + # a subclass of MSColabConnectionError, it fell back to the Gravatar + show_popup(self.ui, "Error", str(ex)) + # closes the profile dialog too + self.logout() + return False + except (MSColabConnectionError, requests.exceptions.RequestException): + # no profile image on the server, or the server can't be reached self.fetch_gravatar(refresh) else: self.set_profile_pixmap(response.content) + return True def fetch_gravatar(self, refresh): # Display default gravatar if custom profile image is not set @@ -563,20 +573,32 @@ def upload_image(self, _=None): self.prof_diag, "Open Image", "", f"Image ({' '.join(f'*.{ext}' for ext in IMAGE_EXTENSIONS)})") if not file_name: return + formats = ", ".join(ext.upper() for ext in dict.fromkeys(IMAGE_FORMATS.values())) try: - with Image.open(file_name) as image: - # the format of the content, not a MIME type guessed from the file name: on Windows that comes from - # the registry, e.g. image/x-png, which Pillow can't save, and a name without an extension has none - file_format = image.format - if file_format not in IMAGE_FORMATS: - QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html( - f"A profile image has to be one of {', '.join(IMAGE_FORMATS)}, not {file_format}.")) - return - img_byte_arr = io.BytesIO() - image.resize((64, 64), Image.LANCZOS).save(img_byte_arr, format=file_format) - except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError, SyntaxError, EOFError) as e: + # only the formats the server accepts, e.g. EPS would run Ghostscript. The format is the one of the content, + # not a MIME type guessed from the file name: on Windows that comes from the registry, e.g. image/x-png, + # which Pillow can't save, and a name without an extension has none. + # MPO has no opener of its own (KeyError), the JPEG plugin opens such files as MPO + with Image.open(file_name, formats=[name for name in IMAGE_FORMATS if name != "MPO"]) as image: + # the photo of a phone (MPO) as its first picture + file_format = "JPEG" if image.format == "MPO" else image.format + # upright as it was taken, and cut to a square instead of squeezed + avatar = ImageOps.fit(ImageOps.exif_transpose(image), (64, 64), Image.LANCZOS) + except UnidentifiedImageError: + QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html( + f"{os.path.basename(file_name)} is no image of a format the server accepts: {formats}.")) + return + except (Image.DecompressionBombError, OSError, ValueError, SyntaxError, EOFError) as e: + QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html( + f"Cannot read the image {os.path.basename(file_name)}: {e}")) + return + img_byte_arr = io.BytesIO() + try: + avatar.save(img_byte_arr, format=file_format) + except (OSError, ValueError, KeyError) as e: + # e.g. a Pillow without WEBP support QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html( - f'Cannot identify image file. Please check the file format. Error: {e}')) + f"Cannot convert the image to {file_format}: {e}")) return try: # the image is stored for the user of the token @@ -590,12 +612,14 @@ def upload_image(self, _=None): if response.content == AUTH_FAILED_TEXT.encode(): # the server answers a rejected token with HTTP 200 and "False", nothing was stored show_popup(self.prof_diag, "Error", "Session expired, new login required") - self.prof_diag.close() + # closes the profile dialog too self.logout() elif response.status_code == 200: # shown only once the server has it, and without fetching it back: when that failed, e.g. # from a server on Windows before 12.0.0, msui fell back to the Gravatar self.set_profile_pixmap(img_byte_arr.getvalue()) + # no longer a Gravatar: "Remove Gravatar" replaced the uploaded image with the default avatar + self.gravatar = None QMessageBox.information(self.prof_diag, "Success", "Image uploaded successfully") else: # the answer comes from the MSColab server diff --git a/tests/_test_mscolab/test_server.py b/tests/_test_mscolab/test_server.py index 52f4a96d4..d3c7261be 100644 --- a/tests/_test_mscolab/test_server.py +++ b/tests/_test_mscolab/test_server.py @@ -557,6 +557,28 @@ def test_image_attachment_must_be_image(self): message_type=str(int(MessageType.IMAGE))) assert response.get_json() == {"success": False, "message": "The image is no valid image."} + @staticmethod + def _phone_photo(): + # the JPEGs of many phones (portrait or depth photos) have more pictures, Pillow names them MPO + photo = io.BytesIO() + Image.new('RGB', (4, 4), color='yellow').save( + photo, format='MPO', save_all=True, append_images=[Image.new('RGB', (4, 4), color='blue')]) + assert Image.open(io.BytesIO(photo.getvalue())).format == "MPO" + return photo.getvalue() + + def test_phone_photo_accepted(self): + """Photos of phones were refused as "Images of format MPO can not be sent", also as profile image""" + assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) + with self.app.test_client() as test_client: + operation, token = self._create_operation(test_client, self.userdata) + response = self._attach(test_client, token, operation, "photo.jpg", self._phone_photo(), + message_type=str(int(MessageType.IMAGE))) + assert response.get_json()["success"] is True + response = test_client.post('/upload_profile_image', data={ + "token": token, "image": (io.BytesIO(self._phone_photo()), "photo.jpg", "image/jpeg")}) + assert response.status_code == 200 + assert get_user(self.userdata[0]).profile_image_path.endswith(".jpg") + def test_uploads_non_latin1_path(self): # the download name is encoded by werkzeug, a path that is no latin-1 does not break the answer assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) @@ -679,6 +701,45 @@ def test_profile_image_outside_upload_folder_not_deleted(self): finally: outside.unlink(missing_ok=True) + def _delete_account_with_profile_image(self, profile_image_path): + user = get_user(self.userdata[0]) + user.profile_image_path = profile_image_path + db.session.commit() + with self.app.test_client() as test_client: + token = self._get_token(test_client, self.userdata) + response = test_client.post('/delete_own_account', data={"token": token}) + assert response.status_code == 200 + + def test_profile_image_symlink_deleted_not_its_target(self): + # e.g. left by an administrator or a restore; resolving it deleted the attachment it points to + assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) + upload_folder = Path(current_app.config['UPLOAD_FOLDER']) + (upload_folder / "profile").mkdir(parents=True, exist_ok=True) + (upload_folder / "42").mkdir(parents=True, exist_ok=True) + report = upload_folder / "42" / "report.pdf" + report.write_bytes(b"attachment of operation 42") + link = upload_folder / "profile" / "1-a.png" + link.symlink_to(report) + self._delete_account_with_profile_image("profile/1-a.png") + assert not link.is_symlink() + assert report.read_bytes() == b"attachment of operation 42" + + def test_profile_image_below_symlinked_directory_deleted(self, tmp_path): + # e.g. UPLOAD_FOLDER/profile on another volume; resolved, it counted as outside of UPLOAD_FOLDER + assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) + upload_folder = Path(current_app.config['UPLOAD_FOLDER']) + upload_folder.mkdir(parents=True, exist_ok=True) + volume = tmp_path / "volume" / "profile" + volume.mkdir(parents=True) + image = volume / "1-x.png" + image.write_bytes(b"profile image") + (upload_folder / "profile").symlink_to(volume, target_is_directory=True) + try: + self._delete_account_with_profile_image("profile/1-x.png") + assert not image.exists() + finally: + (upload_folder / "profile").unlink() + def test_unauthorized_profile_image_upload(self): other_user_data = 'other@ex.com', 'other', 'other', 'Other' assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) diff --git a/tests/_test_msui/test_mscolab.py b/tests/_test_msui/test_mscolab.py index 16ab8eba7..974d7f1c8 100644 --- a/tests/_test_msui/test_mscolab.py +++ b/tests/_test_msui/test_mscolab.py @@ -1848,13 +1848,19 @@ def pixmap_updated(): assert uploaded_pixmap == fetched_pixmap def _upload_image_from_profile(self, qtbot, tmp_path, image_format="PNG", file_name="avatar.png", - request_get=None, request_post=None, guess_type=None): + request_get=None, request_post=None, guess_type=None, save=None, gravatar=None): self._connect_to_mscolab(qtbot) modify_config_file({"MSS_auth": {self.url: self.userdata[0]}}) self._login(qtbot, self.userdata[0], self.userdata[2]) self.window.mscolab.profile_action.trigger() image_path = tmp_path / file_name - Image.new("RGB", (64, 64), color="cyan").save(image_path, format=image_format) + if save is None: + Image.new("RGB", (64, 64), color="cyan").save(image_path, format=image_format) + else: + save(image_path) + if gravatar is not None: + # as after fetch_gravatar + self.window.mscolab.gravatar = gravatar initial_pixmap = self.window.mscolab.profile_dialog.gravatarLabel.pixmap().toImage() conn = self.window.mscolab.conn patches = [mock.patch.object(conn, name, **kwargs) for name, kwargs in @@ -1936,9 +1942,93 @@ def test_image_of_other_format_not_uploaded(self, qtbot, tmp_path): qtbot, tmp_path, "TIFF", "avatar.tiff", request_post={"side_effect": AssertionError("uploaded")}) information.assert_not_called() critical.assert_called_once() - assert "not TIFF" in critical.call_args.args[2] + assert "no image of a format the server accepts" in critical.call_args.args[2] assert self._shown_profile_image() == initial_pixmap + def test_phone_photo_uploaded_as_jpeg(self, qtbot, tmp_path): + """Pillow names the JPEGs of many phones (portrait or depth photos) MPO, they were refused""" + def save(path): + Image.new("RGB", (64, 64), color="cyan").save( + path, format="MPO", save_all=True, append_images=[Image.new("RGB", (64, 64), color="red")]) + assert Image.open(path).format == "MPO" + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( + qtbot, tmp_path, file_name="photo.jpg", save=save) + critical.assert_not_called() + information.assert_called_once() + assert self._shows_uploaded_image() + response = self.window.mscolab.conn.request_get( + endpoints.FETCH_PROFILE_IMAGE, {"user_id": str(self.window.mscolab.user["id"])}) + assert Image.open(io.BytesIO(response.content)).format == "JPEG" + + def test_photo_shown_upright_and_not_squeezed(self, qtbot, tmp_path): + """The EXIF orientation of a phone photo was ignored and the photo squeezed to a square""" + def save(path): + # stored lying, left red, right blue; Orientation 6: turned 90 degrees clockwise when shown + image = Image.new("RGB", (120, 60), color="red") + image.paste("blue", (60, 0, 120, 60)) + exif = Image.Exif() + exif[0x0112] = 6 + image.save(path, format="JPEG", exif=exif, quality=95) + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( + qtbot, tmp_path, file_name="photo.jpg", save=save) + information.assert_called_once() + shown = self._shown_profile_image() + # upright: red on top, blue below; the middle of it, not squeezed + top, bottom = shown.pixelColor(32, 8), shown.pixelColor(32, 56) + assert top.red() > 200 and top.blue() < 60 + assert bottom.blue() > 200 and bottom.red() < 60 + + def test_failed_conversion_has_its_own_message(self, qtbot, tmp_path): + """An error after opening the image, e.g. a Pillow without WEBP support, said it can't be identified""" + original_save = Image.Image.save + + def save(image, fp, *args, **kwargs): + # only the image converted for the upload + if isinstance(fp, io.BytesIO): + raise OSError("encoder not available") + return original_save(image, fp, *args, **kwargs) + with mock.patch.object(Image.Image, "save", autospec=True, side_effect=save): + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( + qtbot, tmp_path, request_post={"side_effect": AssertionError("uploaded")}) + critical.assert_called_once() + assert "Cannot convert the image to PNG: encoder not available" in critical.call_args.args[2] + information.assert_not_called() + + def test_remove_gravatar_keeps_uploaded_image(self, qtbot, tmp_path): + """After an upload, "Remove Gravatar" replaced the uploaded image with the default avatar""" + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( + qtbot, tmp_path, gravatar=str(tmp_path / "gravatar.png")) + information.assert_called_once() + self.window.mscolab.remove_gravatar() + assert self._shows_uploaded_image() + + def test_profile_with_expired_session(self, qtbot): + """With an expired session the profile showed the Gravatar instead of asking for a new login""" + self._connect_to_mscolab(qtbot) + modify_config_file({"MSS_auth": {self.url: self.userdata[0]}}) + self._login(qtbot, self.userdata[0], self.userdata[2]) + # e.g. from another msui + self.window.mscolab.conn.request_post(endpoints.LOGOUT_EVERYWHERE) + with mock.patch("mslib.msui.mscolab.show_popup") as popup, \ + mock.patch.object(self.window.mscolab, "fetch_gravatar") as fetch_gravatar: + self.window.mscolab.profile_action.trigger() + popup.assert_called_once() + assert "Session expired" in popup.call_args.args[2] + fetch_gravatar.assert_not_called() + assert self.window.mscolab.conn is None + + def test_profile_with_unreachable_server(self, qtbot): + """A server that can't be reached raised out of opening the profile""" + self._connect_to_mscolab(qtbot) + modify_config_file({"MSS_auth": {self.url: self.userdata[0]}}) + self._login(qtbot, self.userdata[0], self.userdata[2]) + with mock.patch.object(self.window.mscolab.conn, "request_get", + side_effect=requests.exceptions.ConnectionError("unreachable")), \ + mock.patch.object(self.window.mscolab, "fetch_gravatar") as fetch_gravatar: + self.window.mscolab.profile_action.trigger() + fetch_gravatar.assert_called_once_with(False) + assert self.window.mscolab.prof_diag is not None + def test_refused_image_not_shown(self, qtbot, tmp_path): """An image the server refused was shown in the profile all the same""" refused = mock.Mock(status_code=400, content=b'{"message": "Invalid file type"}', From f59cfde753b068288befb0f57bbaf08146e3eb52 Mon Sep 17 00:00:00 2001 From: Reimar Bauer Date: Tue, 1 Dec 2026 16:34:26 +0100 Subject: [PATCH 4/5] Profile images: no directory as image, upload named by its format, Fetch Gravatar (#3403) A stored profile image path must name a file below a directory of UPLOAD_FOLDER, and a link to a directory is never deleted, so the link of a symlinked profile directory stays. msui sends the image as profile., so servers before 12.0.0 store it with the right extension, lists upper-case file names in the dialog, removes a Gravatar cached for the session also after an upload, and "Fetch Gravatar" fetches the Gravatar also when the server has an uploaded image. The symlink tests are skipped on Windows, the out-of-folder test covers / and absolute paths --- mslib/mscolab/file_manager.py | 15 ++++++----- mslib/msui/mscolab.py | 37 ++++++++++++++++---------- tests/_test_mscolab/test_server.py | 35 ++++++++++++++++++++++--- tests/_test_msui/test_mscolab.py | 42 ++++++++++++++++++++++++++++++ 4 files changed, 106 insertions(+), 23 deletions(-) diff --git a/mslib/mscolab/file_manager.py b/mslib/mscolab/file_manager.py index 3a30c673d..0ac722dbc 100644 --- a/mslib/mscolab/file_manager.py +++ b/mslib/mscolab/file_manager.py @@ -343,16 +343,19 @@ def delete_user_profile_image(self, image_to_be_deleted): This function is called when deleting account or updating the profile picture """ relative_path = profile_image_url_path(image_to_be_deleted) + parts = PurePosixPath(relative_path).parts # the path comes from the database: checked by its parts, not resolved, so a directory below UPLOAD_FOLDER may - # be a symlink (e.g. to another volume), and an image that is a symlink is removed itself, not its target + # be a symlink (e.g. to another volume), and an image that is a symlink is removed itself, not its target. + # An image is a file in a directory below UPLOAD_FOLDER (e.g. profile/), never a directory of it: + # "profile" or "profile/." would remove the link of a symlinked profile directory if (PurePosixPath(relative_path).is_absolute() or PureWindowsPath(relative_path).anchor - or ".." in PurePosixPath(relative_path).parts): - logging.error(f"Not deleting the profile image {image_to_be_deleted}, it is outside of UPLOAD_FOLDER") + or ".." in parts or len(parts) < 2): + logging.error(f"Not deleting the profile image {image_to_be_deleted}, it is no file below UPLOAD_FOLDER") return - full_image_path = Path(current_app.config['UPLOAD_FOLDER'], *PurePosixPath(relative_path).parts) + full_image_path = Path(current_app.config['UPLOAD_FOLDER'], *parts) - # Check if the file exists and delete it - if full_image_path.is_symlink() or full_image_path.is_file(): + # Check if the file exists and delete it; a link to a directory is kept + if full_image_path.is_file() or (full_image_path.is_symlink() and not full_image_path.is_dir()): try: full_image_path.unlink() # Delete the file logging.debug(f"Successfully deleted image: {image_to_be_deleted}") diff --git a/mslib/msui/mscolab.py b/mslib/msui/mscolab.py index 48e26fd90..7bb2c5e51 100644 --- a/mslib/msui/mscolab.py +++ b/mslib/msui/mscolab.py @@ -309,7 +309,9 @@ def after_login(self, emailid, url, response): """Finish the login with the response of POST endpoints.TOKEN. Returns False and keeps the connect dialog open when the response - can't be read or the socket connection fails, True otherwise. + can't be read or the socket connection fails. Returns False as well when + the session expired while fetching the profile image: then msui has already + logged out and the connect dialog is closed. True otherwise. """ logging.debug("after login %s %s", emailid, url) # after_login is only ever called once the caller has already checked @@ -515,6 +517,16 @@ def set_gravatar(self, gravatar=None): if self.prof_diag is not None: self.profile_dialog.gravatarLabel.setPixmap(pixmap) + def remove_temporary_gravatar(self): + """Removes the shown Gravatar from the cache, unless the address is in gravatar_ids""" + config_path = Path(constants.MSUI_CONFIG_PATH) + gravatar_path = Path(constants.GRAVATAR_DIR_PATH) + # ToDo simplify + if (config_path / "gravatars").exists() and self.gravatar is not None: + if (self.email not in config_loader(dataset="gravatar_ids") and + (gravatar_path / Path(self.gravatar).name).exists()): + (gravatar_path / Path(self.gravatar).name).unlink() + def remove_gravatar(self): if self.gravatar is None: return @@ -560,7 +572,8 @@ def on_context_menu(point): # add context menu for right click on image self.gravatar_menu = QtWidgets.QMenu() - self.gravatar_menu.addAction('Fetch Gravatar', lambda: self.fetch_profile_image(refresh=True)) + # the Gravatar also when the server has an uploaded image + self.gravatar_menu.addAction('Fetch Gravatar', lambda: self.fetch_gravatar(refresh=True)) self.gravatar_menu.addAction('Remove Gravatar', lambda: self.remove_gravatar()) self.profile_dialog.gravatarLabel.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.profile_dialog.gravatarLabel.customContextMenuRequested.connect(on_context_menu) @@ -569,8 +582,9 @@ def on_context_menu(point): self.fetch_profile_image() def upload_image(self, _=None): - file_name, _ = QFileDialog.getOpenFileName( - self.prof_diag, "Open Image", "", f"Image ({' '.join(f'*.{ext}' for ext in IMAGE_EXTENSIONS)})") + # also in upper case, e.g. IMG_1234.JPG of a phone: the dialog of GTK matches the patterns case-sensitively + patterns = ' '.join(f'*.{ext}' for ext in (*IMAGE_EXTENSIONS, *(ext.upper() for ext in IMAGE_EXTENSIONS))) + file_name, _ = QFileDialog.getOpenFileName(self.prof_diag, "Open Image", "", f"Image ({patterns})") if not file_name: return formats = ", ".join(ext.upper() for ext in dict.fromkeys(IMAGE_FORMATS.values())) @@ -601,10 +615,11 @@ def upload_image(self, _=None): f"Cannot convert the image to {file_format}: {e}")) return try: - # the image is stored for the user of the token + # the image is stored for the user of the token. The name fits the content: servers before 12.0.0 store + # the image with the extension of that name, e.g. .unknown for a file name without one response = self.conn.request_post( endpoints.UPLOAD_PROFILE_IMAGE, - files={'image': (os.path.basename(file_name), io.BytesIO(img_byte_arr.getvalue()), + files={'image': (f"profile.{IMAGE_FORMATS[file_format]}", io.BytesIO(img_byte_arr.getvalue()), Image.MIME.get(file_format, "application/octet-stream"))}) except requests.exceptions.RequestException as e: QMessageBox.critical(self.prof_diag, "Error", plain_text_as_html(f"Error occurred: {e}")) @@ -619,6 +634,7 @@ def upload_image(self, _=None): # from a server on Windows before 12.0.0, msui fell back to the Gravatar self.set_profile_pixmap(img_byte_arr.getvalue()) # no longer a Gravatar: "Remove Gravatar" replaced the uploaded image with the default avatar + self.remove_temporary_gravatar() self.gravatar = None QMessageBox.information(self.prof_diag, "Success", "Image uploaded successfully") else: @@ -1867,14 +1883,7 @@ def logout(self): self.ui.workLocallyCheckbox.setChecked(False) self.ui.workLocallyCheckbox.blockSignals(False) - # remove temporary gravatar image - config_path = Path(constants.MSUI_CONFIG_PATH) - gravatar_path = Path(constants.GRAVATAR_DIR_PATH) - # ToDo simplify - if (config_path / "gravatars").exists() and self.gravatar is not None: - if (self.email not in config_loader(dataset="gravatar_ids") and - (gravatar_path / Path(self.gravatar).name).exists()): - (gravatar_path / Path(self.gravatar).name).unlink() + self.remove_temporary_gravatar() # clear gravatar image path self.gravatar = None # clear user email diff --git a/tests/_test_mscolab/test_server.py b/tests/_test_mscolab/test_server.py index d3c7261be..f61d99cd6 100644 --- a/tests/_test_mscolab/test_server.py +++ b/tests/_test_mscolab/test_server.py @@ -681,8 +681,14 @@ def test_profile_image_stored_with_backslashes_served_and_deleted(self): assert response.status_code == 200 assert not image_file.exists() - def test_profile_image_outside_upload_folder_not_deleted(self): - # the stored path is only joined onto UPLOAD_FOLDER; a backslash counts as separator since #3403 + @pytest.mark.parametrize("stored_path", [ + "profile/../../outside-of-uploads.png", + # a backslash counts as separator since #3403 + "profile\\..\\..\\outside-of-uploads.png", + "absolute", + ]) + def test_profile_image_outside_upload_folder_not_deleted(self, stored_path): + # the stored path is only joined onto UPLOAD_FOLDER assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) upload_folder = Path(current_app.config['UPLOAD_FOLDER']) # as on a server with profile images; the system resolves profile/.. only if it exists @@ -691,7 +697,7 @@ def test_profile_image_outside_upload_folder_not_deleted(self): outside.write_bytes(b"not a profile image") try: user = get_user(self.userdata[0]) - user.profile_image_path = "profile\\..\\..\\outside-of-uploads.png" + user.profile_image_path = str(outside) if stored_path == "absolute" else stored_path db.session.commit() with self.app.test_client() as test_client: token = self._get_token(test_client, self.userdata) @@ -710,6 +716,7 @@ def _delete_account_with_profile_image(self, profile_image_path): response = test_client.post('/delete_own_account', data={"token": token}) assert response.status_code == 200 + @pytest.mark.skipif(sys.platform.startswith("win"), reason="symbolic links need privileges on Windows") def test_profile_image_symlink_deleted_not_its_target(self): # e.g. left by an administrator or a restore; resolving it deleted the attachment it points to assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) @@ -724,6 +731,7 @@ def test_profile_image_symlink_deleted_not_its_target(self): assert not link.is_symlink() assert report.read_bytes() == b"attachment of operation 42" + @pytest.mark.skipif(sys.platform.startswith("win"), reason="symbolic links need privileges on Windows") def test_profile_image_below_symlinked_directory_deleted(self, tmp_path): # e.g. UPLOAD_FOLDER/profile on another volume; resolved, it counted as outside of UPLOAD_FOLDER assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) @@ -740,6 +748,27 @@ def test_profile_image_below_symlinked_directory_deleted(self, tmp_path): finally: (upload_folder / "profile").unlink() + @pytest.mark.skipif(sys.platform.startswith("win"), reason="symbolic links need privileges on Windows") + @pytest.mark.parametrize("stored_path", ["profile", "profile/.", "profile\\", "profile/sub"]) + def test_profile_image_path_of_a_directory_link_not_deleted(self, tmp_path, stored_path): + # e.g. after a manual change of the database; the link of the profile directory belongs to all users + assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) + upload_folder = Path(current_app.config['UPLOAD_FOLDER']) + upload_folder.mkdir(parents=True, exist_ok=True) + volume = tmp_path / "volume" / "profile" + (volume / "elsewhere").mkdir(parents=True) + image = volume / "2-y.png" + image.write_bytes(b"profile image of another user") + (upload_folder / "profile").symlink_to(volume, target_is_directory=True) + (volume / "sub").symlink_to(volume / "elsewhere", target_is_directory=True) + try: + self._delete_account_with_profile_image(stored_path) + assert (upload_folder / "profile").is_symlink() + assert (volume / "sub").is_symlink() + assert image.read_bytes() == b"profile image of another user" + finally: + (upload_folder / "profile").unlink() + def test_unauthorized_profile_image_upload(self): other_user_data = 'other@ex.com', 'other', 'other', 'Other' assert add_user(self.userdata[0], self.userdata[1], self.userdata[2], self.userdata[3]) diff --git a/tests/_test_msui/test_mscolab.py b/tests/_test_msui/test_mscolab.py index 974d7f1c8..d21a11226 100644 --- a/tests/_test_msui/test_mscolab.py +++ b/tests/_test_msui/test_mscolab.py @@ -1934,8 +1934,26 @@ def test_upload_offers_the_formats_of_the_server(self, qtbot, tmp_path): offered = dialog.call_args.args[3] for ext in ("png", "jpg", "jpeg", "gif", "bmp", "webp"): assert f"*.{ext}" in offered + # e.g. IMG_1234.JPG of a phone, the dialog of GTK matches case-sensitively + assert f"*.{ext.upper()}" in offered assert "*.bpm" not in offered + @pytest.mark.parametrize("image_format, file_name, sent_name, mime_type", [ + ("PNG", "avatar", "profile.png", "image/png"), + ("BMP", "avatar.png", "profile.bmp", "image/bmp"), + ]) + def test_uploaded_image_named_by_its_content(self, qtbot, tmp_path, image_format, file_name, sent_name, + mime_type): + """A server before 12.0.0 stores the image with the extension of the sent name, .unknown for avatar""" + connection_manager = mscolab.sc.ConnectionManager + with mock.patch.object(connection_manager, "request_post", autospec=True, + side_effect=connection_manager.request_post) as post: + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( + qtbot, tmp_path, image_format, file_name) + information.assert_called_once() + name, _, sent_mime_type = post.call_args.kwargs["files"]["image"] + assert (name, sent_mime_type) == (sent_name, mime_type) + def test_image_of_other_format_not_uploaded(self, qtbot, tmp_path): """The server refuses e.g. TIFF; it is refused before the upload""" initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( @@ -2002,6 +2020,30 @@ def test_remove_gravatar_keeps_uploaded_image(self, qtbot, tmp_path): self.window.mscolab.remove_gravatar() assert self._shows_uploaded_image() + def test_upload_removes_temporary_gravatar(self, qtbot, tmp_path): + """The cached Gravatar of an address not in gravatar_ids stayed on disk after an upload""" + from mslib.msui.utils import constants as msui_constants + cached = Path(msui_constants.GRAVATAR_DIR_PATH) / "0123456789abcdef.png" + cached.parent.mkdir(parents=True, exist_ok=True) + Image.new("RGB", (8, 8), color="green").save(cached) + try: + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( + qtbot, tmp_path, gravatar=str(cached)) + information.assert_called_once() + assert not cached.exists() + finally: + cached.unlink(missing_ok=True) + + def test_fetch_gravatar_with_uploaded_image(self, qtbot, tmp_path): + """"Fetch Gravatar" fetched the uploaded image of the server again, never the Gravatar""" + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile(qtbot, tmp_path) + information.assert_called_once() + action = next(action for action in self.window.mscolab.gravatar_menu.actions() + if action.text() == "Fetch Gravatar") + with mock.patch.object(self.window.mscolab, "fetch_gravatar") as fetch_gravatar: + action.trigger() + fetch_gravatar.assert_called_once_with(refresh=True) + def test_profile_with_expired_session(self, qtbot): """With an expired session the profile showed the Gravatar instead of asking for a new login""" self._connect_to_mscolab(qtbot) From 5d63102a64f374861d9c0fc9a28722e3c18b6e2f Mon Sep 17 00:00:00 2001 From: Reimar Bauer Date: Tue, 1 Dec 2026 19:19:55 +0100 Subject: [PATCH 5/5] Change Avatar: a locked Gravatar cache no longer breaks the upload, Remove Gravatar keeps the server image (#3403) The cached Gravatar is removed with its OSError caught: after the upload and on logout it is logged, "Remove Gravatar" reports it and keeps the Gravatar. Showing the profile image of the server clears the Gravatar, so "Remove Gravatar" after "Fetch Gravatar" and reopening the profile keeps the uploaded image --- mslib/msui/mscolab.py | 30 ++++++++---- tests/_test_msui/test_mscolab.py | 80 +++++++++++++++++++++++++++++++- 2 files changed, 100 insertions(+), 10 deletions(-) diff --git a/mslib/msui/mscolab.py b/mslib/msui/mscolab.py index 7bb2c5e51..b17f0bfd3 100644 --- a/mslib/msui/mscolab.py +++ b/mslib/msui/mscolab.py @@ -427,9 +427,16 @@ def fetch_profile_image(self, refresh=False): # no profile image on the server, or the server can't be reached self.fetch_gravatar(refresh) else: - self.set_profile_pixmap(response.content) + self.show_server_profile_image(response.content) return True + def show_server_profile_image(self, img_data): + """Shows the profile image of the server, which is no Gravatar""" + self.set_profile_pixmap(img_data) + # "Remove Gravatar" replaced it with the default avatar, e.g. after "Fetch Gravatar" before + self.remove_temporary_gravatar() + self.gravatar = None + def fetch_gravatar(self, refresh): # Display default gravatar if custom profile image is not set email_hash = hashlib.md5(bytes(self.email.encode('utf-8')).lower(), usedforsecurity=False).hexdigest() @@ -523,9 +530,12 @@ def remove_temporary_gravatar(self): gravatar_path = Path(constants.GRAVATAR_DIR_PATH) # ToDo simplify if (config_path / "gravatars").exists() and self.gravatar is not None: - if (self.email not in config_loader(dataset="gravatar_ids") and - (gravatar_path / Path(self.gravatar).name).exists()): - (gravatar_path / Path(self.gravatar).name).unlink() + if self.email not in config_loader(dataset="gravatar_ids"): + try: + (gravatar_path / Path(self.gravatar).name).unlink(missing_ok=True) + except OSError as ex: + # e.g. held open by another program on Windows; it is only a cache, the upload or logout goes on + logging.warning("can't remove the cached Gravatar %s: %s", self.gravatar, ex) def remove_gravatar(self): if self.gravatar is None: @@ -535,7 +545,12 @@ def remove_gravatar(self): # remove cached gravatar image if not found in config if gravatar_img_path.exists(): - gravatar_img_path.unlink() + try: + gravatar_img_path.unlink() + except OSError as ex: + # e.g. held open by another program on Windows; it stays shown, as it would be shown again + show_popup(self.prof_diag, "Error", f"Can't remove the cached Gravatar: {ex}") + return if self.email in config_loader(dataset="gravatar_ids"): show_popup( self.prof_diag, @@ -632,10 +647,7 @@ def upload_image(self, _=None): elif response.status_code == 200: # shown only once the server has it, and without fetching it back: when that failed, e.g. # from a server on Windows before 12.0.0, msui fell back to the Gravatar - self.set_profile_pixmap(img_byte_arr.getvalue()) - # no longer a Gravatar: "Remove Gravatar" replaced the uploaded image with the default avatar - self.remove_temporary_gravatar() - self.gravatar = None + self.show_server_profile_image(img_byte_arr.getvalue()) QMessageBox.information(self.prof_diag, "Success", "Image uploaded successfully") else: # the answer comes from the MSColab server diff --git a/tests/_test_msui/test_mscolab.py b/tests/_test_msui/test_mscolab.py index d21a11226..9e1130b96 100644 --- a/tests/_test_msui/test_mscolab.py +++ b/tests/_test_msui/test_mscolab.py @@ -2022,15 +2022,93 @@ def test_remove_gravatar_keeps_uploaded_image(self, qtbot, tmp_path): def test_upload_removes_temporary_gravatar(self, qtbot, tmp_path): """The cached Gravatar of an address not in gravatar_ids stayed on disk after an upload""" + cached = self._cached_gravatar() + try: + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( + qtbot, tmp_path, gravatar=str(cached)) + information.assert_called_once() + assert not cached.exists() + finally: + cached.unlink(missing_ok=True) + + def _cached_gravatar(self): from mslib.msui.utils import constants as msui_constants cached = Path(msui_constants.GRAVATAR_DIR_PATH) / "0123456789abcdef.png" cached.parent.mkdir(parents=True, exist_ok=True) Image.new("RGB", (8, 8), color="green").save(cached) + return cached + + @staticmethod + def _locked(path): + """Path.unlink raising for path, as for a file another program holds open on Windows""" + original_unlink = Path.unlink + + def unlink(self, *args, **kwargs): + if self == path: + raise PermissionError(13, "The process cannot access the file", str(path)) + return original_unlink(self, *args, **kwargs) + return mock.patch.object(Path, "unlink", autospec=True, side_effect=unlink) + + def test_upload_with_locked_cached_gravatar(self, qtbot, tmp_path): + """A cached Gravatar that couldn't be removed raised after the server had stored the image""" + cached = self._cached_gravatar() + try: + with self._locked(cached): + initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( + qtbot, tmp_path, gravatar=str(cached)) + information.assert_called_once() + critical.assert_not_called() + assert self.window.mscolab.gravatar is None + # the uploaded image counts as such + self.window.mscolab.remove_gravatar() + assert self._shows_uploaded_image() + finally: + cached.unlink(missing_ok=True) + + def test_remove_locked_gravatar(self, qtbot, tmp_path): + """A cached Gravatar that couldn't be removed raised out of Remove Gravatar""" + self._connect_to_mscolab(qtbot) + modify_config_file({"MSS_auth": {self.url: self.userdata[0]}}) + self._login(qtbot, self.userdata[0], self.userdata[2]) + self.window.mscolab.profile_action.trigger() + email_hash = hashlib.md5(self.userdata[0].encode("utf-8").lower(), usedforsecurity=False).hexdigest() + from mslib.msui.utils import constants as msui_constants + cached = Path(msui_constants.GRAVATAR_DIR_PATH) / f"{email_hash}.png" + cached.parent.mkdir(parents=True, exist_ok=True) + Image.new("RGB", (8, 8), color="green").save(cached) + try: + # as after fetch_gravatar + self.window.mscolab.set_gravatar(str(cached)) + with self._locked(cached), mock.patch("mslib.msui.mscolab.show_popup") as popup: + self.window.mscolab.remove_gravatar() + popup.assert_called_once() + assert "Can't remove the cached Gravatar" in popup.call_args.args[2] + assert cached.exists() + assert self.window.mscolab.gravatar == str(cached) + finally: + cached.unlink(missing_ok=True) + + def test_remove_gravatar_after_fetch_keeps_server_image(self, qtbot, tmp_path): + """ + "Fetch Gravatar", then the profile opened again (server image shown) and "Remove Gravatar" replaced the + uploaded image with the default avatar + """ + cached = self._cached_gravatar() try: initial_pixmap, information, critical, popup, gravatar_get = self._upload_image_from_profile( - qtbot, tmp_path, gravatar=str(cached)) + qtbot, tmp_path) information.assert_called_once() + # as after "Fetch Gravatar" + self.window.mscolab.set_gravatar(str(cached)) + assert not self._shows_uploaded_image() + # as on opening the profile again + assert self.window.mscolab.fetch_profile_image() + assert self._shows_uploaded_image() + assert self.window.mscolab.gravatar is None + # the address is not in gravatar_ids: only cached for the session assert not cached.exists() + self.window.mscolab.remove_gravatar() + assert self._shows_uploaded_image() finally: cached.unlink(missing_ok=True)