diff --git a/lean/components/cloud/push_manager.py b/lean/components/cloud/push_manager.py index 5c47c7d1..2dd5ae53 100644 --- a/lean/components/cloud/push_manager.py +++ b/lean/components/cloud/push_manager.py @@ -81,11 +81,47 @@ def push_projects(self, projects_to_push: List[Path], associated_libraries_to_pu organization_id = self._organization_manager.try_get_working_organization_id() + # a library pushed for the project that uses it gets no encryption key from the command, so its plain local files + # would replace its encrypted cloud files and remove its cloud encryption. A library encrypted with the key the + # command encrypts with is pushed with that key, and for any other nothing is pushed, because the projects that + # use the library can't always be pushed without it + command_key_hash = None + if encryption_action == ActionType.ENCRYPT and encryption_key is not None: + from lean.components.util.encryption_helper import get_project_key_hash + command_key_hash = get_project_key_hash(encryption_key) + libraries_cloud_keys = {library: self._get_cloud_only_encryption_key(library, organization_id) + for library in associated_libraries_to_push} + libraries_encrypted_only_in_cloud = "', '".join(library.relative_to(Path.cwd()).as_posix() + for library, key in libraries_cloud_keys.items() + if key is not None and key != command_key_hash) + if libraries_encrypted_only_in_cloud != "": + raise RuntimeError(f"Libraries encrypted in the cloud but not locally would lose their cloud encryption if " + f"pushed with the project: '{libraries_encrypted_only_in_cloud}'. Encrypt each of them " + f"locally with 'lean encrypt --key' to keep it encrypted, or push it on its own " + f"with --decrypt --key to decrypt it") + + # the cloud refuses to link an encrypted library to a project or library pushed without encryption, but only after + # it wrote their files, so nothing is pushed when one of them uses a library that this push sends encrypted + def is_pushed_encrypted(path: Path) -> bool: + if encryption_action is not None and encryption_key is not None and libraries_cloud_keys.get(path, '') is not None: + return encryption_action == ActionType.ENCRYPT + return self._project_config_manager.get_project_config(path).get("encrypted", False) + encrypted = {path for path in all_projects_to_push if associated_libraries_to_push and is_pushed_encrypted(path)} + unencrypted_users = "', '".join( + path.relative_to(Path.cwd()).as_posix() for path in all_projects_to_push + if path not in encrypted and any(LeanLibraryReference(**library).path.expanduser().resolve() in encrypted + for library in self._project_config_manager.get_project_config(path).get("libraries", []))) + if unencrypted_users != "": + raise RuntimeError(f"The cloud doesn't let projects and libraries pushed without encryption use the encrypted libraries " + f"pushed with them: '{unencrypted_users}'. Encrypt each of them locally with 'lean encrypt " + f" --key' to push it encrypted too, or decrypt the encrypted libraries they use") + for index, path in enumerate(all_projects_to_push, start=1): - # Check if it's an associated library to push, we don't encrypt those. - encryption_action_value = encryption_action if path not in associated_libraries_to_push else None - encryption_key_value = encryption_key if path not in associated_libraries_to_push else None + # Check if it's an associated library to push, we don't encrypt those unless they are encrypted in the cloud with the command's key. + with_command_key = path not in associated_libraries_to_push or libraries_cloud_keys[path] is not None + encryption_action_value = encryption_action if with_command_key else None + encryption_key_value = encryption_key if with_command_key else None relative_path = path.relative_to(Path.cwd()) try: self._logger.info(f"[{index}/{len(all_projects_to_push)}] Pushing '{relative_path}'") @@ -101,6 +137,22 @@ def push_projects(self, projects_to_push: List[Path], associated_libraries_to_pu return all_pushed + def _get_cloud_only_encryption_key(self, project: Path, organization_id: str) -> Optional[str]: + """Returns the hash of the cloud key of a project encrypted in the cloud but not locally, '' when the cloud + doesn't say which key, and None when the project isn't encrypted only in the cloud.""" + project_config = self._project_config_manager.get_project_config(project) + cloud_id = project_config.get("cloud-id") + if cloud_id is None or project_config.get("encrypted", False): + return None + try: + cloud_project = self._get_cloud_project(cloud_id, organization_id) + except RequestFailedError: + # the push of the project reports the cloud project it can't read + return None + if not cloud_project.encrypted: + return None + return cloud_project.encryptionKey.id if cloud_project.encryptionKey else '' + def _get_local_libraries_cloud_ids(self, project_dir: Path) -> List[int]: project_config = self._project_config_manager.get_project_config(project_dir) @@ -304,6 +356,12 @@ def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_act encryption_key_id = get_project_key_hash(encryption_key) update_args["encryption_key"] = encryption_key_id + # the cloud refuses to set a key on a project used as a library or shared with collaborators, even the key it + # already has, so a key that doesn't change is left out + cloud_encryption_key = cloud_project.encryptionKey.id if cloud_project.encryptionKey else '' + if cloud_encryption_key != '' and update_args["encryption_key"] == cloud_encryption_key: + del update_args["encryption_key"] + if not force: update_args["code_source_id"] = "cli" if update_args != {}: @@ -314,10 +372,14 @@ def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_act raise # projects/update checks a new encryption key before it writes any file, but the per-file path # sends the key last, so a refused key would leave the cloud files encrypted or decrypted anyway - cloud_encryption_key = cloud_project.encryptionKey.id if cloud_project.encryptionKey else '' - if update_args["encryption_key"] != cloud_encryption_key: + if update_args.get("encryption_key", cloud_encryption_key) != cloud_encryption_key: raise self._push_one_by_one(cloud_project, update_args) + finally: + # the update can change the cloud key even when it fails, so a later push to this cloud project, such as + # from another local copy of it, reads the key again + if "encryption_key" in update_args: + self._cloud_projects = [p for p in self._cloud_projects if p.projectId != cloud_project.projectId] if "encryption_key" in update_args: del update_args["encryption_key"] diff --git a/tests/commands/cloud/test_push.py b/tests/commands/cloud/test_push.py index c77927a0..84a0d092 100644 --- a/tests/commands/cloud/test_push.py +++ b/tests/commands/cloud/test_push.py @@ -378,7 +378,7 @@ def test_cloud_push_pushes_files_one_by_one_when_a_too_large_project_keeps_its_e for name, content in expected_encrypted_files.items()]) assert api_client.files.create.call_count == len(expected_encrypted_files) assert api_client.projects.update.call_count == 2 - assert api_client.projects.update.call_args.kwargs["encryption_key"] == key_hash + assert "encryption_key" not in api_client.projects.update.call_args.kwargs assert "files" not in api_client.projects.update.call_args.kwargs def test_cloud_push_aborts_sending_encrypted_files_when_local_file_encrypted_with_key_x_and_given_key_y() -> None: @@ -684,7 +684,7 @@ def test_cloud_push_keeps_cloud_project_encrypted_when_project_pulled_encrypted_ assert result.exit_code == 0 args, kwargs = api_client.projects.update.call_args - assert kwargs["encryption_key"] == get_project_key_hash(encryption_file_path) + assert "encryption_key" not in kwargs expected_encrypted_files = _get_expected_encrypted_files_content() assert {file["name"]: file["content"].strip() for file in kwargs["files"]} == \ {name: content.strip() for name, content in expected_encrypted_files.items()} diff --git a/tests/components/util/test_push_manager.py b/tests/components/util/test_push_manager.py index bdb5923c..bb04768e 100644 --- a/tests/components/util/test_push_manager.py +++ b/tests/components/util/test_push_manager.py @@ -24,6 +24,8 @@ from tests.test_helpers import create_fake_lean_cli_directory, create_api_project, create_lean_environments from tests.test_helpers import create_fake_lean_cli_project from lean.components import forbidden_characters +from lean.components.util.encryption_helper import get_encrypted_file_content_for_local_project, get_project_key_hash +from lean.models.encryption import ActionType def _create_organization_manager() -> mock.Mock: organization_manager = mock.Mock() @@ -713,6 +715,192 @@ def test_push_projects_returns_false_when_a_project_with_cloud_id_cannot_be_push assert not push_manager.push_projects([project_path]) +def _create_project_with_library_in_encrypted_cloud_project(library_path: Optional[Path] = None) -> (mock.Mock, Path, Path, Path): + create_fake_lean_cli_directory() + + project_path = Path.cwd() / "Python Project" + if library_path is None: + library_path = Path.cwd() / "Library/Python Library" + else: + container.project_manager.create_new_project(library_path, QCLanguage.Python) + container.library_manager.add_lean_library_reference_to_project(project_path, library_path) + + encryption_key_path = Path.cwd() / "encryption.txt" + encryption_key_path.write_text("KtSwJtq5a4uuQmxbPqcCP3d8yMRz5TZxDBAKy7kGwPcvcvsNBdCprGYwSBN8ntJa5JNNYHTB2GrBpAbkA38kCdnceegffZH7") + key_hash = get_project_key_hash(encryption_key_path) + + library_id = 31 + project_id = 32 + container.project_config_manager.get_project_config(library_path).set("cloud-id", library_id) + container.project_config_manager.get_project_config(project_path).set("cloud-id", project_id) + cloud_projects = [create_api_project(library_id, library_path.relative_to(Path.cwd()).as_posix(), encrypted=True, + encryptionKey={"name": "test", "id": key_hash}), + create_api_project(project_id, project_path.name, encrypted=True, + encryptionKey={"name": "test", "id": key_hash})] + + def update(proj_id, **kwargs): + # an update that sends a key sets it on a new copy of the cloud project, as a later projects/read returns it + if "encryption_key" in kwargs: + index = next(i for i, p in enumerate(cloud_projects) if p.projectId == proj_id) + key = kwargs["encryption_key"] + cloud_projects[index] = create_api_project(proj_id, cloud_projects[index].name, encrypted=key != "", + encryptionKey={"name": "test", "id": key} if key != "" else None) + + api_client = mock.Mock() + api_client.projects.get = mock.MagicMock(side_effect=lambda proj_id, *args: next(p for p in cloud_projects + if p.projectId == proj_id)) + api_client.projects.update = mock.MagicMock(side_effect=update) + api_client.encryption_keys.list = mock.MagicMock(return_value={"keys": [{"name": "test", "hash": key_hash}]}) + + return api_client, project_path, library_path, encryption_key_path + + +def _encrypt_project_locally(project_path: Path, encryption_key_path: Path) -> List[str]: + source_files = container.project_manager.get_source_files(project_path) + encrypted_contents = get_encrypted_file_content_for_local_project(project_path, source_files, encryption_key_path, + container.project_config_manager, "abc") + for source_file, encrypted_content in zip(source_files, encrypted_contents): + source_file.write_text(encrypted_content, encoding="utf-8") + project_config = container.project_config_manager.get_project_config(project_path) + project_config.set("encrypted", True) + project_config.set("encryption-key-path", str(encryption_key_path)) + return encrypted_contents + + +@pytest.mark.parametrize("encryption_action,other_key", [(None, False), + (ActionType.ENCRYPT, True), + (ActionType.DECRYPT, False)]) +def test_push_project_pushes_nothing_when_a_library_would_lose_its_cloud_encryption(encryption_action: Optional[ActionType], + other_key: bool) -> None: + api_client, project_path, library_path, encryption_key_path = _create_project_with_library_in_encrypted_cloud_project() + if other_key: + encryption_key_path = Path.cwd() / "other-encryption.txt" + encryption_key_path.write_text("aNotherKeyEmJ4KfR8vPzW2xYq7TbN3sLcUd6HgA9VrXk5mQwE1yZoBiCtFnDp") + + push_manager = _create_push_manager(api_client, container.project_manager) + with pytest.raises(RuntimeError, match="would lose their cloud encryption") as error: + push_manager.push_project(project_path, encryption_action, + encryption_key_path if encryption_action is not None else None) + + assert "'Library/Python Library'" in str(error.value) + api_client.projects.update.assert_not_called() + + +def test_push_project_creates_nothing_when_a_nested_library_would_lose_its_cloud_encryption() -> None: + api_client, project_path, library_path, _ = _create_project_with_library_in_encrypted_cloud_project() + new_library_path = Path.cwd() / "Library/New Library" + container.project_manager.create_new_project(new_library_path, QCLanguage.Python) + container.library_manager.remove_lean_library_reference_from_project(project_path, library_path) + container.library_manager.add_lean_library_reference_to_project(project_path, new_library_path) + container.library_manager.add_lean_library_reference_to_project(new_library_path, library_path) + + push_manager = _create_push_manager(api_client, container.project_manager) + with pytest.raises(RuntimeError, match="'Library/Python Library'"): + push_manager.push_project(project_path) + + api_client.projects.create.assert_not_called() + api_client.projects.update.assert_not_called() + assert container.project_config_manager.get_project_config(new_library_path).get("cloud-id") is None + + +@pytest.mark.skipif(platform.system() == "Windows", reason="Windows does not allow creating the unsupported path") +def test_push_project_does_not_rename_library_that_would_lose_its_cloud_encryption() -> None: + library_path = Path.cwd() / "Library/Trailing Lib." + api_client, project_path, _, _ = _create_project_with_library_in_encrypted_cloud_project(library_path) + + push_manager = _create_push_manager(api_client, container.project_manager) + with pytest.raises(RuntimeError, match="'Library/Trailing Lib.'"): + push_manager.push_project(project_path) + + assert library_path.exists() + project_libraries = container.project_config_manager.get_project_config(project_path).get("libraries") + assert project_libraries == [{"name": "Trailing Lib.", "path": "Library/Trailing Lib."}] + api_client.projects.update.assert_not_called() + + +def test_push_project_pushes_library_encrypted_locally_with_its_cloud_key() -> None: + api_client, project_path, library_path, encryption_key_path = _create_project_with_library_in_encrypted_cloud_project() + encrypted_contents = _encrypt_project_locally(library_path, encryption_key_path) + + push_manager = _create_push_manager(api_client, container.project_manager) + push_manager.push_project(project_path, ActionType.ENCRYPT, encryption_key_path) + + update_calls = api_client.projects.update.call_args_list + assert [args[0] for args, _ in update_calls] == [31, 32] + assert "encryption_key" not in update_calls[0].kwargs + assert {file["content"] for file in update_calls[0].kwargs["files"]} == set(encrypted_contents) + assert "encryption_key" not in update_calls[1].kwargs + assert update_calls[1].kwargs["libraries"] == [31] + push_manager._logger.warn.assert_not_called() + + +def test_push_project_pushes_library_encrypted_in_the_cloud_with_the_key_the_project_is_encrypted_with() -> None: + api_client, project_path, library_path, encryption_key_path = _create_project_with_library_in_encrypted_cloud_project() + source_files = container.project_manager.get_source_files(library_path) + encrypted_contents = get_encrypted_file_content_for_local_project(library_path, source_files, encryption_key_path, + container.project_config_manager, "abc") + + push_manager = _create_push_manager(api_client, container.project_manager) + push_manager.push_project(project_path, ActionType.ENCRYPT, encryption_key_path) + + update_calls = api_client.projects.update.call_args_list + assert [args[0] for args, _ in update_calls] == [31, 32] + assert "encryption_key" not in update_calls[0].kwargs + assert {file["content"] for file in update_calls[0].kwargs["files"]} == set(encrypted_contents) + assert "encryption_key" not in update_calls[1].kwargs + assert not container.project_config_manager.get_project_config(library_path).get("encrypted", False) + push_manager._logger.warn.assert_not_called() + + +@pytest.mark.parametrize("library_encrypted_locally", [False, True]) +def test_push_project_creates_nothing_when_an_unencrypted_library_uses_a_library_pushed_encrypted( + library_encrypted_locally: bool) -> None: + api_client, project_path, library_path, encryption_key_path = _create_project_with_library_in_encrypted_cloud_project() + if library_encrypted_locally: + _encrypt_project_locally(library_path, encryption_key_path) + new_library_path = Path.cwd() / "Library/New Library" + container.project_manager.create_new_project(new_library_path, QCLanguage.Python) + container.library_manager.remove_lean_library_reference_from_project(project_path, library_path) + container.library_manager.add_lean_library_reference_to_project(project_path, new_library_path) + container.library_manager.add_lean_library_reference_to_project(new_library_path, library_path) + + push_manager = _create_push_manager(api_client, container.project_manager) + with pytest.raises(RuntimeError, match="pushed without encryption") as error: + push_manager.push_project(project_path, ActionType.ENCRYPT, encryption_key_path) + + assert "'Library/New Library'" in str(error.value) + api_client.projects.create.assert_not_called() + api_client.projects.update.assert_not_called() + assert container.project_config_manager.get_project_config(new_library_path).get("cloud-id") is None + + +def test_push_projects_decrypts_encrypted_cloud_library_pushed_on_its_own() -> None: + api_client, _, library_path, _ = _create_project_with_library_in_encrypted_cloud_project() + + push_manager = _create_push_manager(api_client, container.project_manager) + + assert push_manager.push_projects([library_path]) + api_client.projects.update.assert_called_once() + assert api_client.projects.update.call_args.kwargs["encryption_key"] == "" + + +def test_push_projects_sends_key_again_after_another_copy_of_the_project_removed_it() -> None: + api_client, project_path, _, encryption_key_path = _create_project_with_library_in_encrypted_cloud_project() + copy_path = Path.cwd() / "Python Project Copy" + copy_path.mkdir() + for file in project_path.iterdir(): + (copy_path / file.name).write_bytes(file.read_bytes()) + _encrypt_project_locally(copy_path, encryption_key_path) + + push_manager = _create_push_manager(api_client, container.project_manager) + + assert push_manager.push_projects([project_path, copy_path]) + update_calls = api_client.projects.update.call_args_list + assert [args[0] for args, _ in update_calls] == [32, 32] + assert update_calls[0].kwargs["encryption_key"] == "" + assert update_calls[1].kwargs["encryption_key"] == get_project_key_hash(encryption_key_path) + + @pytest.mark.skipif(platform.system() == "Windows", reason="Windows does not allow creating the unsupported path") def test_push_project_updates_reference_to_library_renamed_by_the_push() -> None: create_fake_lean_cli_directory()