Skip to content
72 changes: 67 additions & 5 deletions lean/components/cloud/push_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment thread
quantconnect-kronos-reviewer[bot] marked this conversation as resolved.
Resolved
if libraries_encrypted_only_in_cloud != "":
Comment thread
quantconnect-kronos-reviewer[bot] marked this conversation as resolved.
Resolved
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 <library> --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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When there are no associated libraries, encrypted is empty but this still parses every project’s references outside the per-project error handler. That turns one bad config into a failure for the whole workspace. Skip this scan when there are no encrypted targets to check, and test that a bulk push still uploads unrelated valid projects.

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"<project> --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}'")
Expand All @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A failed lookup does not establish that the library is unencrypted. Returning None lets the push proceed without having verified that it will preserve encryption. Stop before any changes if this lookup fails, and add a regression test asserting no writes when the encryption check cannot complete.

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)

Expand Down Expand Up @@ -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"]
Comment thread
quantconnect-kronos-reviewer[bot] marked this conversation as resolved.
Resolved
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved

if not force:
update_args["code_source_id"] = "cli"
if update_args != {}:
Expand All @@ -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"]
Expand Down
4 changes: 2 additions & 2 deletions tests/commands/cloud/test_push.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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()}
Expand Down
Loading
Loading