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 5998543cd..0ac722dbc 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 @@ -53,6 +53,25 @@ 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 + + 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""" @@ -323,15 +342,20 @@ 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('\\', '/') - - # Construct the full path to the image file - full_image_path = Path(upload_folder) / image_to_be_deleted + 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. + # 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 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'], *parts) - # Check if the file exists and delete it - if full_image_path.exists() and 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}") @@ -383,7 +407,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: - static_file_path = str(Path(file_path).relative_to(Path(upload_folder))) + static_file_path = stored_upload_path(file_path, Path(upload_folder)) logging.debug(f'Relative Path: {static_file_path}') return static_file_path @@ -423,7 +447,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..b17f0bfd3 100644 --- a/mslib/msui/mscolab.py +++ b/mslib/msui/mscolab.py @@ -38,11 +38,10 @@ import types import requests import re -import mimetypes 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 @@ -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, @@ -308,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 @@ -369,7 +372,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) @@ -409,13 +413,29 @@ 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) + 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 @@ -504,6 +524,19 @@ 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"): + 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: return @@ -512,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, @@ -549,7 +587,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) @@ -558,47 +597,62 @@ 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 and set profile image pixmap - 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: - 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: - 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( - 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}')) + # 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())) + try: + # 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 convert the image to {file_format}: {e}")) + return + try: + # 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': (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}")) + 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") + # 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.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 + 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( @@ -1841,14 +1895,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_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 d8e62149d..f61d99cd6 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]) @@ -638,6 +660,115 @@ 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_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() + + @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 + (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 = 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) + 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 _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 + + @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]) + 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" + + @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]) + 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() + + @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 fa4b44088..9e1130b96 100644 --- a/tests/_test_msui/test_mscolab.py +++ b/tests/_test_msui/test_mscolab.py @@ -1847,6 +1847,344 @@ def pixmap_updated(): assert initial_pixmap != fetched_pixmap 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, 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 + 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 + (("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: + # 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") + 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, request_get={"side_effect": mscolab.MSColabConnectionError}) + information.assert_called_once() + critical.assert_not_called() + popup.assert_not_called() + gravatar_get.assert_not_called() + 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 + # 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( + qtbot, tmp_path, "TIFF", "avatar.tiff", request_post={"side_effect": AssertionError("uploaded")}) + information.assert_not_called() + critical.assert_called_once() + 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_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) + 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) + + 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) + 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"}', + 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, 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._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): """ Test that selecting an operation updates the active users label correctly.