From b0044970125b8acd15d58e88e723b232e1a5d228 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:31:09 +0000 Subject: [PATCH 1/6] bug: keep an encrypted library encrypted when it is pushed with the project that uses it `lean cloud push --project ` pushes the project's libraries too, without an encryption key. A library whose cloud project is encrypted and whose local files are plain, such as one pulled with --decrypt --key, was pushed with an empty key, which turned its cloud encryption off and stored its plain source. Such a library now isn't pushed: the push warns with how to push it on its own and goes on with the project, as for any library that can't be pushed. A push no longer sends an encryption key the cloud project already has. The cloud refuses to set a key on a project used as a library or shared with collaborators, even its current key, so an encrypted library could not be pushed while staying encrypted. Co-Authored-By: Claude Opus 5.5 --- lean/components/cloud/push_manager.py | 29 +++++++-- tests/commands/cloud/test_push.py | 4 +- tests/components/util/test_push_manager.py | 75 ++++++++++++++++++++++ 3 files changed, 99 insertions(+), 9 deletions(-) diff --git a/lean/components/cloud/push_manager.py b/lean/components/cloud/push_manager.py index 5c47c7d1..6338fb44 100644 --- a/lean/components/cloud/push_manager.py +++ b/lean/components/cloud/push_manager.py @@ -84,13 +84,15 @@ def push_projects(self, projects_to_push: List[Path], associated_libraries_to_pu 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 + is_associated_library = path in associated_libraries_to_push + encryption_action_value = encryption_action if not is_associated_library else None + encryption_key_value = encryption_key if not is_associated_library else None relative_path = path.relative_to(Path.cwd()) try: self._logger.info(f"[{index}/{len(all_projects_to_push)}] Pushing '{relative_path}'") self.pushed_project_paths[path] = self._push_project(path, organization_id, encryption_action_value, - encryption_key_value, force=force) + encryption_key_value, force=force, + keep_cloud_encryption=is_associated_library) except Exception as ex: from traceback import format_exc self._logger.debug(format_exc().strip()) @@ -127,7 +129,7 @@ def _get_local_libraries_cloud_ids(self, project_dir: Path) -> List[int]: return local_libraries_cloud_ids - def _push_project(self, project_path: Path, organization_id: str, encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool], suggested_rename_path: Path = None) -> Path: + def _push_project(self, project_path: Path, organization_id: str, encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool], suggested_rename_path: Path = None, keep_cloud_encryption: bool = False) -> Path: """Pushes a single local project to the cloud. Raises an error with a descriptive message if the project cannot be pushed. @@ -135,6 +137,7 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act :param project_path: the local project to push :param organization_id: the id of the organization to push the project to :param suggested_rename_path: the path to move the project to. + :param keep_cloud_encryption: whether to refuse a push that would remove the cloud project's encryption :return: the path of the pushed project, which differs from project_path when the push renamed it """ @@ -198,7 +201,8 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act if cloud_project.name != project_name: # cloud project name was changed. Repeat steps to validate the new name locally. self._logger.info(f"Received new name '{cloud_project.name}' for project '{project_name}' from QuantConnect.com") - return self._push_project(project_path, organization_id, encryption_action, encryption_key, force, Path.cwd() / cloud_project.name) + return self._push_project(project_path, organization_id, encryption_action, encryption_key, force, + Path.cwd() / cloud_project.name, keep_cloud_encryption) self._cloud_projects.append(cloud_project) organization_message_part = f" in organization '{organization_id}'" if organization_id is not None else "" @@ -210,6 +214,12 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act if local_encryption_state == True and encryption_key is None and local_encryption_key is not None: encryption_key = local_encryption_key encryption_action = ActionType.ENCRYPT if local_encryption_state else ActionType.DECRYPT + # a library pushed for the project that uses it gets no encryption key from the command, so its plain local + # files would replace the encrypted cloud files and turn the cloud library's encryption off + if keep_cloud_encryption and cloud_project.encrypted and encryption_action != ActionType.ENCRYPT: + raise RuntimeError("its cloud project is encrypted and its local files are not, so pushing it would remove " + "the cloud project's encryption. Push it on its own with --encrypt --key to keep the " + "cloud project encrypted, or --decrypt --key to decrypt it") # Finalize pushing by updating locally modified metadata, files and libraries self._push_metadata(project_path, cloud_project, encryption_action, encryption_key, force) return project_path @@ -304,6 +314,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,8 +330,7 @@ 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) 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..c47f6fb1 100644 --- a/tests/components/util/test_push_manager.py +++ b/tests/components/util/test_push_manager.py @@ -24,6 +24,7 @@ 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 def _create_organization_manager() -> mock.Mock: organization_manager = mock.Mock() @@ -713,6 +714,80 @@ 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() -> (mock.Mock, Path, Path, Path): + create_fake_lean_cli_directory() + + project_path = Path.cwd() / "Python Project" + library_path = Path.cwd() / "Library/Python Library" + 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/Python Library", encrypted=True, + encryptionKey={"name": "test", "id": key_hash}), + create_api_project(project_id, project_path.name)] + + 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.encryption_keys.list = mock.MagicMock(return_value={"keys": [{"name": "test", "hash": key_hash}]}) + + return api_client, project_path, library_path, encryption_key_path + + +def test_push_project_does_not_push_library_that_would_lose_its_cloud_encryption() -> None: + api_client, project_path, library_path, _ = _create_project_with_library_in_encrypted_cloud_project() + + push_manager = _create_push_manager(api_client, container.project_manager) + push_manager.push_project(project_path) + + update_calls = api_client.projects.update.call_args_list + assert [args[0] for args, _ in update_calls] == [32] + assert update_calls[0].kwargs["libraries"] == [31] + push_manager._logger.warn.assert_called_once() + warning = push_manager._logger.warn.call_args[0][0] + assert warning.startswith(f"Cannot push '{library_path.relative_to(Path.cwd())}'") + assert "would remove the cloud project's encryption" in warning + + +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() + + 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") + for source_file, encrypted_content in zip(source_files, encrypted_contents): + source_file.write_text(encrypted_content, encoding="utf-8") + library_config = container.project_config_manager.get_project_config(library_path) + library_config.set("encrypted", True) + library_config.set("encryption-key-path", str(encryption_key_path)) + + push_manager = _create_push_manager(api_client, container.project_manager) + push_manager.push_project(project_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) + push_manager._logger.warn.assert_not_called() + + +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"] == "" + + @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() From c73058838f0451986c550fd5105a8508f7e7f6dd Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:47:27 +0000 Subject: [PATCH 2/6] bug: don't push an unencrypted project that uses a library the push kept encrypted The cloud removes the project's key and writes its files before it refuses an encrypted library in an unencrypted project, so the push left the project half-written and failing to compile. Co-Authored-By: Claude Opus 5.5 --- lean/components/cloud/push_manager.py | 11 +++++++++++ tests/components/util/test_push_manager.py | 22 +++++++++++++++++++--- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/lean/components/cloud/push_manager.py b/lean/components/cloud/push_manager.py index 6338fb44..e996d079 100644 --- a/lean/components/cloud/push_manager.py +++ b/lean/components/cloud/push_manager.py @@ -53,6 +53,8 @@ def __init__(self, self._cloud_projects = [] # Where each pushed project is after its push, which renames directories whose name is not valid locally or in the cloud self.pushed_project_paths: Dict[Path, Path] = {} + # Cloud ids of the libraries left encrypted in the cloud because their local files are not + self._libraries_kept_encrypted = set() def push_project(self, project: Path, encryption_action: Optional[ActionType]=None, encryption_key: Optional[Path]=None, force: Optional[bool]=False) -> None: """Pushes the given project from the local drive to the cloud. @@ -217,6 +219,7 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act # a library pushed for the project that uses it gets no encryption key from the command, so its plain local # files would replace the encrypted cloud files and turn the cloud library's encryption off if keep_cloud_encryption and cloud_project.encrypted and encryption_action != ActionType.ENCRYPT: + self._libraries_kept_encrypted.add(cloud_project.projectId) raise RuntimeError("its cloud project is encrypted and its local files are not, so pushing it would remove " "the cloud project's encryption. Push it on its own with --encrypt --key to keep the " "cloud project encrypted, or --decrypt --key to decrypt it") @@ -320,6 +323,14 @@ def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_act if cloud_encryption_key != '' and update_args["encryption_key"] == cloud_encryption_key: del update_args["encryption_key"] + # the cloud writes the files and removes the key before it refuses an encrypted library in a project left + # unencrypted, so that push would leave the project half-written + if (update_args.get("encryption_key", cloud_encryption_key) == '' + and self._libraries_kept_encrypted.intersection(update_args["libraries"])): + raise RuntimeError("it uses a library whose cloud project stayed encrypted, and an unencrypted project can't " + "use an encrypted library. Push it with --encrypt --key to keep it encrypted, or push the " + "library on its own with --decrypt --key first") + if not force: update_args["code_source_id"] = "cli" if update_args != {}: diff --git a/tests/components/util/test_push_manager.py b/tests/components/util/test_push_manager.py index c47f6fb1..2e887dd9 100644 --- a/tests/components/util/test_push_manager.py +++ b/tests/components/util/test_push_manager.py @@ -25,6 +25,7 @@ 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() @@ -731,7 +732,8 @@ def _create_project_with_library_in_encrypted_cloud_project() -> (mock.Mock, Pat container.project_config_manager.get_project_config(project_path).set("cloud-id", project_id) cloud_projects = [create_api_project(library_id, "Library/Python Library", encrypted=True, encryptionKey={"name": "test", "id": key_hash}), - create_api_project(project_id, project_path.name)] + create_api_project(project_id, project_path.name, encrypted=True, + encryptionKey={"name": "test", "id": key_hash})] api_client = mock.Mock() api_client.projects.get = mock.MagicMock(side_effect=lambda proj_id, *args: next(p for p in cloud_projects @@ -742,10 +744,10 @@ def _create_project_with_library_in_encrypted_cloud_project() -> (mock.Mock, Pat def test_push_project_does_not_push_library_that_would_lose_its_cloud_encryption() -> None: - api_client, project_path, library_path, _ = _create_project_with_library_in_encrypted_cloud_project() + api_client, project_path, library_path, encryption_key_path = _create_project_with_library_in_encrypted_cloud_project() push_manager = _create_push_manager(api_client, container.project_manager) - push_manager.push_project(project_path) + 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] == [32] @@ -756,6 +758,20 @@ def test_push_project_does_not_push_library_that_would_lose_its_cloud_encryption assert "would remove the cloud project's encryption" in warning +def test_push_project_does_not_push_unencrypted_project_using_library_kept_encrypted() -> None: + api_client, project_path, library_path, _ = _create_project_with_library_in_encrypted_cloud_project() + + push_manager = _create_push_manager(api_client, container.project_manager) + push_manager.push_project(project_path) + + api_client.projects.update.assert_not_called() + warnings = [args[0] for args, _ in push_manager._logger.warn.call_args_list] + assert len(warnings) == 2 + assert warnings[0].startswith(f"Cannot push '{library_path.relative_to(Path.cwd())}'") + assert warnings[1].startswith(f"Cannot push '{project_path.relative_to(Path.cwd())}'") + assert "an unencrypted project can't use an encrypted library" in warnings[1] + + 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() From 941baf1e705e5e1e5bd71f83d9a10265902e178d Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:25:48 +0000 Subject: [PATCH 3/6] bug: refuse a push that would decrypt a library implicitly, instead of skipping the library Skipping a library whose cloud project is encrypted and whose local files are not, while pushing the rest, could leave projects the cloud can't use: an unencrypted or differently keyed project linked to the encrypted library, a new intermediate library created but never uploaded, or a renamed library's reference left stale. push_project now checks the libraries it would push before it renames, creates or writes anything, and fails with how to keep or remove the library's encryption. An update that sends an encryption key can change the cloud project's key even when it fails, so the cached cloud project is read again before a later push to it: a second local copy of the same cloud project pushed in the same command no longer leaves out a key the first copy removed. Co-Authored-By: Claude Opus 5.5 --- lean/components/cloud/push_manager.py | 59 ++++++----- tests/components/util/test_push_manager.py | 110 +++++++++++++++------ 2 files changed, 114 insertions(+), 55 deletions(-) diff --git a/lean/components/cloud/push_manager.py b/lean/components/cloud/push_manager.py index e996d079..905692cd 100644 --- a/lean/components/cloud/push_manager.py +++ b/lean/components/cloud/push_manager.py @@ -53,8 +53,6 @@ def __init__(self, self._cloud_projects = [] # Where each pushed project is after its push, which renames directories whose name is not valid locally or in the cloud self.pushed_project_paths: Dict[Path, Path] = {} - # Cloud ids of the libraries left encrypted in the cloud because their local files are not - self._libraries_kept_encrypted = set() def push_project(self, project: Path, encryption_action: Optional[ActionType]=None, encryption_key: Optional[Path]=None, force: Optional[bool]=False) -> None: """Pushes the given project from the local drive to the cloud. @@ -83,18 +81,28 @@ 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. Nothing is pushed then, because the + # projects that use the library can't always be pushed without it + libraries_encrypted_only_in_cloud = "', '".join(library.relative_to(Path.cwd()).as_posix() + for library in associated_libraries_to_push + if self._is_encrypted_only_in_cloud(library, organization_id)) + 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") + 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. - is_associated_library = path in associated_libraries_to_push - encryption_action_value = encryption_action if not is_associated_library else None - encryption_key_value = encryption_key if not is_associated_library else None + 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 relative_path = path.relative_to(Path.cwd()) try: self._logger.info(f"[{index}/{len(all_projects_to_push)}] Pushing '{relative_path}'") self.pushed_project_paths[path] = self._push_project(path, organization_id, encryption_action_value, - encryption_key_value, force=force, - keep_cloud_encryption=is_associated_library) + encryption_key_value, force=force) except Exception as ex: from traceback import format_exc self._logger.debug(format_exc().strip()) @@ -105,6 +113,17 @@ def push_projects(self, projects_to_push: List[Path], associated_libraries_to_pu return all_pushed + def _is_encrypted_only_in_cloud(self, project: Path, organization_id: str) -> bool: + 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 False + try: + return self._get_cloud_project(cloud_id, organization_id).encrypted + except RequestFailedError: + # the push of the project reports the cloud project it can't read + return False + def _get_local_libraries_cloud_ids(self, project_dir: Path) -> List[int]: project_config = self._project_config_manager.get_project_config(project_dir) @@ -131,7 +150,7 @@ def _get_local_libraries_cloud_ids(self, project_dir: Path) -> List[int]: return local_libraries_cloud_ids - def _push_project(self, project_path: Path, organization_id: str, encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool], suggested_rename_path: Path = None, keep_cloud_encryption: bool = False) -> Path: + def _push_project(self, project_path: Path, organization_id: str, encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool], suggested_rename_path: Path = None) -> Path: """Pushes a single local project to the cloud. Raises an error with a descriptive message if the project cannot be pushed. @@ -139,7 +158,6 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act :param project_path: the local project to push :param organization_id: the id of the organization to push the project to :param suggested_rename_path: the path to move the project to. - :param keep_cloud_encryption: whether to refuse a push that would remove the cloud project's encryption :return: the path of the pushed project, which differs from project_path when the push renamed it """ @@ -203,8 +221,7 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act if cloud_project.name != project_name: # cloud project name was changed. Repeat steps to validate the new name locally. self._logger.info(f"Received new name '{cloud_project.name}' for project '{project_name}' from QuantConnect.com") - return self._push_project(project_path, organization_id, encryption_action, encryption_key, force, - Path.cwd() / cloud_project.name, keep_cloud_encryption) + return self._push_project(project_path, organization_id, encryption_action, encryption_key, force, Path.cwd() / cloud_project.name) self._cloud_projects.append(cloud_project) organization_message_part = f" in organization '{organization_id}'" if organization_id is not None else "" @@ -216,13 +233,6 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act if local_encryption_state == True and encryption_key is None and local_encryption_key is not None: encryption_key = local_encryption_key encryption_action = ActionType.ENCRYPT if local_encryption_state else ActionType.DECRYPT - # a library pushed for the project that uses it gets no encryption key from the command, so its plain local - # files would replace the encrypted cloud files and turn the cloud library's encryption off - if keep_cloud_encryption and cloud_project.encrypted and encryption_action != ActionType.ENCRYPT: - self._libraries_kept_encrypted.add(cloud_project.projectId) - raise RuntimeError("its cloud project is encrypted and its local files are not, so pushing it would remove " - "the cloud project's encryption. Push it on its own with --encrypt --key to keep the " - "cloud project encrypted, or --decrypt --key to decrypt it") # Finalize pushing by updating locally modified metadata, files and libraries self._push_metadata(project_path, cloud_project, encryption_action, encryption_key, force) return project_path @@ -323,14 +333,6 @@ def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_act if cloud_encryption_key != '' and update_args["encryption_key"] == cloud_encryption_key: del update_args["encryption_key"] - # the cloud writes the files and removes the key before it refuses an encrypted library in a project left - # unencrypted, so that push would leave the project half-written - if (update_args.get("encryption_key", cloud_encryption_key) == '' - and self._libraries_kept_encrypted.intersection(update_args["libraries"])): - raise RuntimeError("it uses a library whose cloud project stayed encrypted, and an unencrypted project can't " - "use an encrypted library. Push it with --encrypt --key to keep it encrypted, or push the " - "library on its own with --decrypt --key first") - if not force: update_args["code_source_id"] = "cli" if update_args != {}: @@ -344,6 +346,11 @@ def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_act 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/components/util/test_push_manager.py b/tests/components/util/test_push_manager.py index 2e887dd9..6df17822 100644 --- a/tests/components/util/test_push_manager.py +++ b/tests/components/util/test_push_manager.py @@ -13,6 +13,7 @@ from datetime import datetime from pathlib import Path +from shutil import copytree from typing import List, Optional from unittest import mock import pytest @@ -715,11 +716,14 @@ 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() -> (mock.Mock, Path, Path, 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" - library_path = Path.cwd() / "Library/Python Library" + 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" @@ -730,67 +734,100 @@ def _create_project_with_library_in_encrypted_cloud_project() -> (mock.Mock, Pat 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/Python Library", encrypted=True, + 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 test_push_project_does_not_push_library_that_would_lose_its_cloud_encryption() -> None: +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("encrypt", [False, True]) +def test_push_project_pushes_nothing_when_a_library_would_lose_its_cloud_encryption(encrypt: bool) -> None: api_client, project_path, library_path, encryption_key_path = _create_project_with_library_in_encrypted_cloud_project() push_manager = _create_push_manager(api_client, container.project_manager) - push_manager.push_project(project_path, ActionType.ENCRYPT, encryption_key_path) + with pytest.raises(RuntimeError, match="would lose their cloud encryption") as error: + if encrypt: + push_manager.push_project(project_path, ActionType.ENCRYPT, encryption_key_path) + else: + push_manager.push_project(project_path) - update_calls = api_client.projects.update.call_args_list - assert [args[0] for args, _ in update_calls] == [32] - assert update_calls[0].kwargs["libraries"] == [31] - push_manager._logger.warn.assert_called_once() - warning = push_manager._logger.warn.call_args[0][0] - assert warning.startswith(f"Cannot push '{library_path.relative_to(Path.cwd())}'") - assert "would remove the cloud project's encryption" in warning + assert "'Library/Python Library'" in str(error.value) + api_client.projects.update.assert_not_called() -def test_push_project_does_not_push_unencrypted_project_using_library_kept_encrypted() -> None: +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) - push_manager.push_project(project_path) + 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() - warnings = [args[0] for args, _ in push_manager._logger.warn.call_args_list] - assert len(warnings) == 2 - assert warnings[0].startswith(f"Cannot push '{library_path.relative_to(Path.cwd())}'") - assert warnings[1].startswith(f"Cannot push '{project_path.relative_to(Path.cwd())}'") - assert "an unencrypted project can't use an encrypted library" in warnings[1] 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() - - 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") - for source_file, encrypted_content in zip(source_files, encrypted_contents): - source_file.write_text(encrypted_content, encoding="utf-8") - library_config = container.project_config_manager.get_project_config(library_path) - library_config.set("encrypted", True) - library_config.set("encryption-key-path", str(encryption_key_path)) + 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) + 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() @@ -804,6 +841,21 @@ def test_push_projects_decrypts_encrypted_cloud_library_pushed_on_its_own() -> N 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" + copytree(project_path, copy_path) + _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() From eccf6f495cec486f73e5932ccf7141781f08ad2d Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:34:03 +0000 Subject: [PATCH 4/6] Copy the project in the push manager test without shutil, which fails under pyfakefs on Python 3.14 Co-Authored-By: Claude Opus 5.5 --- tests/components/util/test_push_manager.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/components/util/test_push_manager.py b/tests/components/util/test_push_manager.py index 6df17822..d8c5f580 100644 --- a/tests/components/util/test_push_manager.py +++ b/tests/components/util/test_push_manager.py @@ -13,7 +13,6 @@ from datetime import datetime from pathlib import Path -from shutil import copytree from typing import List, Optional from unittest import mock import pytest @@ -844,7 +843,9 @@ def test_push_projects_decrypts_encrypted_cloud_library_pushed_on_its_own() -> N 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" - copytree(project_path, copy_path) + 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) From 35aa9bab7bd8615d77f4b74a5129046bc3615c86 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:52:50 +0000 Subject: [PATCH 5/6] Push a library encrypted in the cloud with the command's key along with the project instead of refusing A project push with --encrypt --key refused any library encrypted in the cloud but plain locally, even one encrypted with that very key, so a project and its library pulled with --decrypt --key couldn't be pushed back with --encrypt --key. Such a library is now pushed with the command's key, which leaves its cloud key as it is. The push still refuses a library encrypted with another key, and pushes with --decrypt --key or without options. Co-Authored-By: Claude Opus 5.5 --- lean/components/cloud/push_manager.py | 35 +++++++++++++++------- tests/components/util/test_push_manager.py | 34 +++++++++++++++++---- 2 files changed, 52 insertions(+), 17 deletions(-) diff --git a/lean/components/cloud/push_manager.py b/lean/components/cloud/push_manager.py index 905692cd..816ec65b 100644 --- a/lean/components/cloud/push_manager.py +++ b/lean/components/cloud/push_manager.py @@ -82,11 +82,18 @@ 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. Nothing is pushed then, because the - # projects that use the library can't always be pushed without it + # 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 in associated_libraries_to_push - if self._is_encrypted_only_in_cloud(library, organization_id)) + 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 " @@ -95,9 +102,10 @@ def push_projects(self, projects_to_push: List[Path], associated_libraries_to_pu 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}'") @@ -113,16 +121,21 @@ def push_projects(self, projects_to_push: List[Path], associated_libraries_to_pu return all_pushed - def _is_encrypted_only_in_cloud(self, project: Path, organization_id: str) -> bool: + 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 False + return None try: - return self._get_cloud_project(cloud_id, organization_id).encrypted + 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 False + 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) diff --git a/tests/components/util/test_push_manager.py b/tests/components/util/test_push_manager.py index d8c5f580..8faf0489 100644 --- a/tests/components/util/test_push_manager.py +++ b/tests/components/util/test_push_manager.py @@ -767,16 +767,20 @@ def _encrypt_project_locally(project_path: Path, encryption_key_path: Path) -> L return encrypted_contents -@pytest.mark.parametrize("encrypt", [False, True]) -def test_push_project_pushes_nothing_when_a_library_would_lose_its_cloud_encryption(encrypt: bool) -> None: +@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: - if encrypt: - push_manager.push_project(project_path, ActionType.ENCRYPT, encryption_key_path) - else: - push_manager.push_project(project_path) + 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() @@ -830,6 +834,24 @@ def test_push_project_pushes_library_encrypted_locally_with_its_cloud_key() -> N 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() + + 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() From 514b20efbfe2824eaee34cb709677749a7f14de9 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:07:22 +0000 Subject: [PATCH 6/6] Refuse a push that sends a library encrypted to a project or library pushed without encryption Co-Authored-By: Claude Opus 5.5 --- lean/components/cloud/push_manager.py | 16 ++++++++++++++++ tests/components/util/test_push_manager.py | 22 ++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/lean/components/cloud/push_manager.py b/lean/components/cloud/push_manager.py index 816ec65b..2dd5ae53 100644 --- a/lean/components/cloud/push_manager.py +++ b/lean/components/cloud/push_manager.py @@ -100,6 +100,22 @@ def push_projects(self, projects_to_push: List[Path], associated_libraries_to_pu 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 unless they are encrypted in the cloud with the command's key. diff --git a/tests/components/util/test_push_manager.py b/tests/components/util/test_push_manager.py index 8faf0489..bb04768e 100644 --- a/tests/components/util/test_push_manager.py +++ b/tests/components/util/test_push_manager.py @@ -852,6 +852,28 @@ def test_push_project_pushes_library_encrypted_in_the_cloud_with_the_key_the_pro 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()